# generative-a11y full documentation
# Getting started
Add paced screen-reader announcements to your existing AI interface.
Canonical: https://generativea11y.com/docs/getting-started
Markdown: https://generativea11y.com/markdown/docs/getting-started
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
Choose the [integration that matches your app](#choose-an-integration). The
React + AI SDK setup below is one starting point; other adapters connect the
same runtime to the lifecycle events your framework exposes.
## Start with your existing React + AI SDK app
```shell title="Terminal"
npm install @generative-a11y/react @generative-a11y/ai-sdk
```
```shell title="Terminal"
pnpm add @generative-a11y/react @generative-a11y/ai-sdk
```
```shell title="Terminal"
yarn add @generative-a11y/react @generative-a11y/ai-sdk
```
```shell title="Terminal"
bun add @generative-a11y/react @generative-a11y/ai-sdk
```
Use this with an existing React + AI SDK app. Check the
[supported versions and peers](/docs/integrations/ai-sdk#compatibility) before
installing.
Follow the [AI SDK integration guide](/docs/integrations/ai-sdk) to add the
provider and hooks to your chat.
This adds paced live-region updates for supported lifecycle events without
changing the visual UI or moving focus during ordinary streaming. Your host
still owns semantic structure, keyboard controls, and accessible content. Retry
detection is unavailable in the AI SDK adapter. Browser delivery does not prove
what a real screen reader speaks.
For React without AI SDK, install `@generative-a11y/react` and supply confirmed
lifecycle events from your app. See the [React API](/api/react). For other
frameworks, [choose an integration](#choose-an-integration).
## Advanced: custom browser integration
Use core and DOM directly when your app owns lifecycle reporting:
```shell title="Terminal"
npm install @generative-a11y/core @generative-a11y/dom
```
### Connect the runtime
Create one runtime and connect it to the browser. Send only the new text from
each streaming update. Report when the response finishes, fails, or stops.
Dispose both resources when the session ends.
```ts title="chat-accessibility.ts"
import { createRuntime } from "@generative-a11y/core";
import { bindRuntime } from "@generative-a11y/dom";
const runtime = createRuntime();
const delivery = bindRuntime(runtime);
// Send these events from your existing response lifecycle callbacks.
runtime.dispatch({ type: "response.started", responseId: "response-1" });
runtime.dispatch({
type: "response.text.delta",
responseId: "response-1",
delta: "A complete sentence.",
});
runtime.dispatch({ type: "response.completed", responseId: "response-1" });
// Call this when the chat is removed, not when a response finishes.
export function disposeChat() {
delivery.dispose();
runtime.dispose();
}
```
Keep the binding alive across responses. When the chat is removed, dispose
browser delivery before the runtime.
**Evidence and testing note**
generative-a11y can confirm when it adds an announcement to the page. Test
with real screen readers to confirm what people hear.
## Choose the package that matches your app
Use a framework adapter when your app already uses that framework. For a custom
app, send events directly to the core runtime.
| Application | Package | What it reports |
| --- | --- | --- |
| Framework-neutral | @generative-a11y/core + /dom | All standard library events |
| React | @generative-a11y/react | Provider, delivery, attention, preferences |
| AI SDK useChat | @generative-a11y/react + @generative-a11y/ai-sdk | Streaming, terminals, tools, approvals, citations |
| assistant-ui | @generative-a11y/assistant-ui | Messages, tools, approvals, sources |
| AG-UI / CopilotKit v2 | @generative-a11y/ag-ui | Protocol text, tools, interrupts |
| Development diagnostics | @generative-a11y/devtools | Redacted runtime and DOM delivery traces |
| Deterministic tests | @generative-a11y/core/testing | Event recording, replay, and semantic assertions |
For adapter setup, see [assistant-ui](/docs/integrations/assistant-ui),
[AG-UI](/docs/integrations/ag-ui), or
[CopilotKit](/docs/integrations/copilotkit).
---
# Choose an integration
Choose the adapter and delivery layer that connect your existing AI interface to generative-a11y.
Canonical: https://generativea11y.com/docs/integrations
Markdown: https://generativea11y.com/markdown/docs/integrations
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Start with the framework your app uses
Choose the guide that matches the public state or callbacks your app exposes.
Each guide starts with installation and a minimal integration for your existing
UI.
| Your app | Guide | Accessibility packages for that example |
| --------------------------- | ------------------------------------------------------------- | --------------------------------------- |
| Custom JavaScript | [Dispatch your app's events](/docs/integrations/custom) | `core` + `dom` |
| React with app-owned events | [Add a provider](/docs/getting-started) | `react` |
| AI SDK `useChat` | [Connect chat state and callbacks](/docs/integrations/ai-sdk) | `react` + `ai-sdk` |
| assistant-ui thread runtime | [Observe the public thread](/docs/integrations/assistant-ui) | `core` + `dom` + `assistant-ui` |
| AG-UI agent | [Subscribe to protocol callbacks](/docs/integrations/ag-ui) | `core` + `dom` + `ag-ui` |
| CopilotKit agent | [Connect the v2 agent hook](/docs/integrations/copilotkit) | `react` + `ag-ui` |
Package names above use the `@generative-a11y/` prefix. Your app supplies its
framework dependencies and backend. Check [compatibility](/docs/compatibility)
before installing an adapter into an existing dependency tree.
## Install only the layers you use
Core schedules events; DOM delivers them to browser live regions. React's
`A11yProvider` owns both. Adapters translate host state into events and borrow the
runtime you supply.
Install each package your own code imports. Core and DOM are transitive
dependencies of the React package, so a provider-based integration does not need
to declare them unless it imports them directly. Framework-neutral examples
import core and DOM themselves and therefore list both in their install command.
Keep one delivery layer per runtime. Adapters preserve the host application's
visible UI and do not supply message rendering, composer controls, or focus
navigation.
## Check which events the adapter can see
| Integration | Confirmed evidence | Limits to check |
| ------------------ | -------------------------------------------------------------- | ------------------------------------------------------- |
| Custom / React | Events your app dispatches | Your callbacks must confirm each event |
| AI SDK | Response text, terminal callbacks, tools, approvals, sources | Retry and regenerate detection unavailable |
| assistant-ui | Thread messages, known final states, tools, approvals, sources | Run hierarchy, retry, and connection events unavailable |
| AG-UI / CopilotKit | Runs, subagents, text, tools, interrupts | Steps and hierarchy partial; retries unavailable |
Adapters do not infer lifecycle from rendered text, elapsed time, or private
framework fields. Use [explicit core events](/docs/integrations/custom) when your
app has additional evidence, and keep IDs consistent with any adapter sharing
that runtime.
Each adapter reference describes its evidence levels, including [AG-UI fidelity](/api/ag-ui#fidelity). Browser
transcripts verify delivery writes; real assistive-technology testing is still
required to establish spoken behavior.
---
# Why generative AI needs an accessibility runtime
Learn why streaming responses, tool calls, approvals, retries, and failures need more than ordinary chat accessibility patterns.
Canonical: https://generativea11y.com/docs/why-generative-a11y
Markdown: https://generativea11y.com/markdown/docs/why-generative-a11y
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## AI interfaces change after the user acts
An accessibility runtime is the behavior layer between confirmed AI lifecycle
events and browser delivery. It decides which asynchronous changes deserve an
announcement, groups noisy updates into useful units, prioritizes states that
need attention, and cancels obsolete work without replacing the application’s
visible interface or taking focus from the user.
A conventional form usually has a short, predictable transition: submit,
validate, and show a result. An AI interface can stream a response for many
seconds, start tools, pause for approval, reconnect, retry, and finish long
after focus has moved elsewhere.
Semantic HTML, keyboard access, visible status, and sensible focus remain
required. They do not by themselves decide which asynchronous changes deserve an
announcement, how repeated changes should be grouped, or when lower-priority
updates should wait.
This complements, rather than replaces, the requirement in
[WCAG 2.2 status messages](https://www.w3.org/WAI/WCAG22/Understanding/status-messages.html)
that important changes be programmatically determinable without receiving focus.
The application still owns the semantic HTML and interaction design.
## Naive announcements create new barriers
Putting a changing transcript in an ARIA live region can announce partial
tokens, repeat the growing response, interrupt more important information, or
leave stale work queued after a retry. Moving focus for routine streaming and
status changes is more disruptive because it changes the user's reading
position.
* Partial words and token-sized updates are difficult to understand.
* Re-announcing the full accumulated response repeats content.
* Tool progress can overwhelm the response the user asked for.
* Approval and failure states can arrive behind low-priority updates.
* Retries can make announcements from an obsolete response misleading.
## Put policy between lifecycle state and browser delivery
generative-a11y accepts confirmed lifecycle events from the application or a
thin framework adapter. Core segments response text, prioritizes important
states, removes duplicates, coalesces updates, bounds queued work, and produces
announcement intents. The DOM package then performs browser delivery without
altering the visible interface.
This boundary keeps framework state, accessibility policy, and DOM behavior
independently testable. It also makes fidelity explicit: when an adapter cannot
observe a retry or connection event through a documented public API, it reports
that limitation instead of guessing.
**Evidence and testing note**
Deterministic runtime transcripts and DOM tests show what the library prepared
or added to the page. They do not prove what a particular screen reader spoke.
## Choose the smallest supported integration
Start with the framework-neutral core and DOM packages when your application
already owns lifecycle state. Use the React layer for provider and element
bindings. Add the AI SDK, assistant-ui, or AG-UI adapter only when the
application uses that framework's documented public lifecycle surface.
| Need | Read next |
| ---------------------------------------------- | ------------------------------------------------------------------------ |
| Install a custom integration | [Getting started](/docs/getting-started) |
| Understand streaming announcements | [Screen readers and streaming AI](/docs/screen-readers-and-streaming-ai) |
| Choose a framework adapter | [Choose an integration](/docs/integrations) |
| Test browser and assistive-technology behavior | [Testing](/docs/testing) |
## Sources and evidence
* [WAI-ARIA 1.2 live-region roles and properties](https://www.w3.org/TR/wai-aria/)
* [WCAG 2.2: Understanding Status Messages](https://www.w3.org/WAI/WCAG22/Understanding/status-messages.html)
* [generative-a11y testing boundaries](/docs/testing)
---
# Accessible streaming AI for screen readers
Make streaming AI responses understandable to screen-reader users by announcing meaningful text segments instead of tokens or repeated transcripts.
Canonical: https://generativea11y.com/docs/screen-readers-and-streaming-ai
Markdown: https://generativea11y.com/markdown/docs/screen-readers-and-streaming-ai
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## A visual stream and an audible stream need different pacing
Token-by-token streaming is difficult for screen readers because each visual
update can become a separate accessibility-tree change. Partial words, repeated
accumulated text, and a long queue of low-value changes make the audible stream
hard to follow. A better pattern keeps the visible transcript current while
announcing only confirmed, meaningful phrases and lifecycle boundaries.
The visible response should still update normally. The accessible announcement
stream is a separate representation of the same confirmed lifecycle, optimized
for useful listening rather than visual immediacy.
[WAI-ARIA defines live-region semantics](https://www.w3.org/TR/wai-aria/), but
those semantics are hints to user agents; they do not segment generative text or
model response, retry, and tool lifecycles. That policy belongs in application
logic or an accessibility runtime.
## Avoid announcing the growing transcript
This pattern makes the live region contain the entire accumulated response after
every token. Depending on the browser and assistive technology, users may hear
fragments, repeated content, or inconsistent results.
```tsx title="Avoid: live region around accumulated text"
function StreamingMessage({ text }: { text: string }) {
return
{text}
;
}
```
## Send append-only deltas and an explicit terminal event
Dispatch response.started once, send only newly arrived text in
response.text.delta, and finish with the terminal event the application actually
observed. Core buffers partial text and emits meaningful segments according to
the selected policy.
```typescript title="Dispatch confirmed response events"
runtime.dispatch({ type: "response.started", responseId: "r1" });
runtime.dispatch({
type: "response.text.delta",
responseId: "r1",
delta: "The migration completed successfully. ",
});
runtime.dispatch({ type: "response.completed", responseId: "r1" });
```
## Expected behavior and test boundaries
With the balanced policy, complete phrases can be announced without waiting for
every token or repeating earlier text. Higher-priority failures and approval
requests can take precedence over routine progress. Ordinary streaming never
moves focus.
Use deterministic tests to verify events, announcement intents, queue bounds,
and DOM delivery. Then test the integrated application with representative
browser and screen-reader combinations because spoken output is controlled
by software outside the library.
## Sources and evidence
* [WAI-ARIA 1.2 live-region roles and properties](https://www.w3.org/TR/wai-aria/)
* [WCAG 2.2: Understanding Status Messages](https://www.w3.org/WAI/WCAG22/Understanding/status-messages.html)
* [Manual assistive-technology test plan](/docs/testing)
---
# ARIA live regions for generative AI
Understand what ARIA live regions provide, why streaming tokens are a poor announcement unit, and how generative-a11y separates policy from delivery.
Canonical: https://generativea11y.com/docs/aria-live-and-generative-ai
Markdown: https://generativea11y.com/markdown/docs/aria-live-and-generative-ai
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Live regions expose changes without moving focus
An ARIA live region marks dynamic content so user agents can present changes to
assistive technology while keyboard focus stays where the user placed it. The
`polite` and `assertive` values communicate urgency, while `aria-atomic` and
`aria-relevant` describe which portion of a change is relevant. These semantics
support delivery; they do not decide whether every generated token is useful.
Use `polite` for routine updates and reserve `assertive` for information that
warrants interruption. Browser and assistive-technology behavior determines when
those updates are presented.
The normative behavior and supported values come from
[WAI-ARIA 1.2](https://www.w3.org/TR/wai-aria/). WCAG’s
[status-message guidance](https://www.w3.org/WAI/WCAG22/Understanding/status-messages.html)
also emphasizes informing users about important changes without unnecessarily
moving focus or interrupting their work.
A live region is a delivery mechanism, not an announcement policy. It does not
know whether a token is meaningful, whether a repeated update is obsolete, or
whether a tool failure should outrank routine progress.
## Do not use each token as a live-region update
Generative output changes far more frequently than ordinary status text. Sending
every token can create partial-word announcements and a backlog of
low-value mutations. Replacing the live region with the entire accumulated
response can instead repeat content or produce inconsistent results across
browser and screen-reader combinations.
* Keep the visible transcript semantic and readable independently of
announcements.
* Choose meaningful phrases or sentences as announcement units.
* Use assertive delivery sparingly for confirmed urgent states.
* Cancel queued work when a response fails, stops, retries, or the runtime is
disposed.
## generative-a11y separates scheduling from live-region delivery
The core package turns lifecycle events into polite or assertive announcement
intents after segmentation, prioritization, deduplication, and scheduling. The
DOM package owns stable polite and assertive regions, replaces their text for
live-region delivery, and can use the emerging ariaNotify API when the
browser exposes it in the configured mode.
The application still owns its visible messages, controls, headings, forms,
error relationships, keyboard interactions, and focus behavior. The library's
live regions are not a substitute for those fundamentals.
**Evidence and testing note**
Browser delivery confirms a DOM action, not audible output. Validate the
complete experience with real assistive technology.
## Use ordinary semantics for stable content
Do not announce information merely because it rendered. Stable assistant
messages should remain ordinary document content that users can navigate. Use
lifecycle announcements for changes that would otherwise be easy to miss: a
response becoming available, a tool changing state, approval becoming required,
a connection being lost, or work ending in failure.
## Sources and evidence
* [WAI-ARIA 1.2](https://www.w3.org/TR/wai-aria/)
* [WCAG 2.2: Understanding Status Messages](https://www.w3.org/WAI/WCAG22/Understanding/status-messages.html)
* [ARIA live-region implementation guidance](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Guides/Live_regions)
---
# Accessible AI agents and tool execution
Design screen-reader announcements for AI agent progress, tool calls, approvals, interruptions, failures, retries, and results.
Canonical: https://generativea11y.com/docs/accessible-ai-agents
Markdown: https://generativea11y.com/markdown/docs/accessible-ai-agents
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Agent interfaces have more states than a chat transcript
An agent can start a long-running tool, report progress, request a decision,
lose its connection, retry, and finish with a result. Visual indicators may make
these transitions obvious, while a screen-reader user remains on the
composer, transcript, or another part of the page.
Accessibility depends on communicating consequential state changes without
narrating every internal operation. Announcements should describe the
user-facing lifecycle, not expose raw tool payloads, backend errors, or
chain-of-thought-like implementation detail.
## Map confirmed agent state to normalized events
Choose events from confirmed application state. Tool argument streaming does not
establish that execution started; a disappearing approval control does not
establish that a decision was submitted. Keep stable IDs across each operation
and attach an instance ID when work can retry.
| Agent state | Normalized event | Announcement purpose |
| -------------------- | -------------------------- | ------------------------------------------------- |
| Tool begins | tool.started | Set context for a user-relevant operation |
| Meaningful milestone | tool.progress | Report progress without flooding |
| Approval needed | interaction.requested | Make a required decision discoverable |
| Tool fails | tool.failed | Communicate the safe user-facing failure label |
| Response retries | response.retrying | Cancel stale response work and identify the retry |
| Connection changes | connection.lost / restored | Report confirmed availability changes |
## Prioritize decisions and failures without stealing focus
An AI agent approval request should be announced as a confirmed request for
input, while the approval control remains part of the host application’s normal
keyboard and focus model. Routine progress can stay polite; required decisions
and safe failure labels can receive higher priority. The event stream must keep
each update attached to a stable response, tool, or approval identity so stale
work can be cancelled after retries and interruptions.
If an approval control needs focus, the host application makes that interaction
decision through its accessible dialog, disclosure, or inline workflow. See
[interactions and approvals](/docs/lifecycle/interactions) for the event
contract.
Bounded queues and terminal-event cleanup prevent outdated progress from
being delivered after a retry, failure, interruption, or disposal.
## Choose an adapter by observable lifecycle fidelity
The AI SDK, assistant-ui, and AG-UI adapters translate documented public
framework state into the normalized event model. Their pages list what they can
observe. When the host application knows about additional connection, retry, or
approval states, it can dispatch those core events directly instead of asking an
adapter to infer them from rendered UI.
## Sources and evidence
* [WCAG 2.2: Understanding Status Messages](https://www.w3.org/WAI/WCAG22/Understanding/status-messages.html)
* [WAI-ARIA 1.2](https://www.w3.org/TR/wai-aria/)
* [generative-a11y architecture and evidence boundaries](/docs/architecture)
---
# Accessibility model and architecture
Follow an AI lifecycle event through the framework-independent runtime, scheduling policy, and DOM delivery that produce paced screen-reader updates.
Canonical: https://generativea11y.com/docs/architecture
Markdown: https://generativea11y.com/markdown/docs/architecture
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## From an app event to a screen-reader update
AI framework → standard events → core runtime → browser delivery → screen
reader.
An adapter translates documented framework state into normalized events. Core
segments text, removes repeats, and schedules announcement intents. DOM delivers
those intents through browser APIs without changing your visible interface.
| Layer | Owns | Integration boundary |
| ---------------- | ----------------------------------------------- | ------------------------------------------------------- |
| Host application | Visible content, controls, lifecycle evidence | Reports confirmed state and keeps content readable |
| Adapter | Framework-to-event translation | Uses public state; declares missing evidence |
| Core runtime | Text segmentation, policy, queues, cancellation | Emits announcement intents without browser dependencies |
| DOM delivery | Live regions and browser notification calls | Reports browser delivery results |
| React bindings | Provider lifetime and host element refs | Connects existing elements to runtime and DOM behavior |
### The standard event vocabulary
Everything the runtime understands is expressed as a small set of typed,
serializable events. Adapters translate framework-specific state into
these events; the host app can also dispatch them directly. The categories
are:
* **Response events**: `response.started`, `response.text.delta`,
`response.completed`, `response.interrupted`, `response.failed`, and
`response.retrying`. These describe one assistant response from start to a
terminal state.
* **Tool events**: `tool.started`, `tool.progress`, `tool.completed`, and
`tool.failed`. These describe tool calls the assistant makes on the way to
an answer.
* **Run and step events**: `run.started`, `run.completed`, `run.failed`,
`run.interrupted`, `run.retrying`, and the matching `step.*` events. These
describe agent workflows with explicit ownership: a stable logical run
identity, plus an optional instance identity for each attempt, and the
same for steps.
* **Interaction and approval events**: `interaction.requested`,
`interaction.resolved`, `approval.requested`, and `approval.resolved`.
These describe moments where the app needs the user to decide something.
* **Connection events**: `connection.lost` and `connection.restored`.
* **Citations**: `citation.available`, for source references the app chooses
to surface.
* **Attention events**: `attention.changed` and `attention.override`, which
feed the attention model described below.
Every event carries a stable identity, such as a response id, tool id, or
run id, plus optional instance ids that distinguish retries and replays.
The runtime uses these identities to deduplicate and cancel correctly, so a
retried response does not produce duplicate announcements. Because the
events are serializable, they can be recorded, replayed, and asserted in
deterministic tests.
### Package map
The monorepo is organized so that each package owns one responsibility.
Dependencies point in one direction: adapters and bindings depend on core,
never the other way around.
| Package | Responsibility | Key sources |
| ------------------------------- | ------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `@generative-a11y/core` | Framework-independent runtime: events, policy, segmentation, scheduling | `runtime.ts`, `scheduler.ts`, `policy.ts`, `segmenter.ts`, `messages.ts`, `attention.ts`, `clock.ts`, `recorder.ts`, `testing.ts`, `types.ts` |
| `@generative-a11y/dom` | Browser delivery: live regions, focus utilities, preferences, attention binding | `index.ts` (`bindRuntime`), `focus.ts`, `composed-tree.ts`, `preferences.ts`, `attention-binding.ts` |
| `@generative-a11y/react` | React bindings: provider lifetime, hooks, attention control | `index.tsx` |
| `@generative-a11y/ai-sdk` | Adapter translating AI SDK `useChat` state into standard events | `react.tsx`, `index.ts` |
| `@generative-a11y/assistant-ui` | Adapter translating assistant-ui lifecycle into standard events | `index.ts` |
| `@generative-a11y/ag-ui` | Adapter translating the AG-UI protocol into standard events | `index.ts` |
| `@generative-a11y/devtools` | Development diagnostics: redacted runtime and DOM delivery traces | `overlay.ts`, `inspector.tsx`, `store.ts` |
Core has no browser dependencies at all: it never touches the DOM, timers
run through an injected clock, and it emits plain announcement intents. DOM
is independent of React and AI frameworks. Adapters are thin: they read
documented public framework state and emit events. When a framework does not
expose reliable evidence, the adapter declares reduced fidelity rather than
guessing, as documented in [limitations](/docs/limitations).
### The runtime pipeline
One dispatch travels through the runtime in stages:
1. **Dispatch.** The host or adapter calls `runtime.dispatch(event)` with a
standard event. The runtime updates its internal model of active
responses, tools, runs, and steps.
2. **Policy resolution.** The announcement policy decides what becomes an
announcement. Policies are presets you can override: `minimal`,
`balanced`, `verbose`, and `completion-only`. The text strategy selects
the granularity: `silent`, `sentence`, `paragraph`, or `completion`. For
example, the balanced preset announces text at sentence boundaries with
a minimum of 24 characters and a maximum delay of 2,500 ms, announces
tool starts after 1,500 ms, and announces completions, failures,
interruptions, and retries.
3. **Segmentation and dedupe.** Streaming text is normalized and segmented
into speakable units. Repeats within a dedupe window are removed, so a
re-sent chunk does not get announced twice.
4. **Scheduling.** Intents are queued and paced: a minimum gap separates
announcements, and the queue is bounded (200 intents) so a flood of
events cannot grow memory without limit. Time is injected through a
`SystemClock` abstraction, which is why tests can drive the scheduler
deterministically with a manual clock.
5. **Intent emission.** The runtime emits announcement intents with a
channel (`polite` or `assertive`) and a purpose (`response-text`,
`routine-status`, or `notice`). Errors and failures use the assertive
channel.
Timers and subscriptions are owned resources: every timer the runtime
creates is cancelled on terminal events and on `dispose()`. Queues and
tracked identities stay bounded. These are not optimizations; they are
correctness rules, because a leaked timer in an accessibility layer can
announce stale text long after the user moved on.
### Browser delivery
`bindRuntime(runtime)` from `@generative-a11y/dom` connects the runtime to
the page. It subscribes to announcement intents and writes them through
live regions and browser notification calls, without changing the visible
interface. Each delivery reports a result, so the host can observe what was
added to the page, while remembering the honesty rule: delivery confirmation
is not proof of speech.
Dispose in the right order: dispose browser delivery before the runtime, and
keep the binding alive across responses. Streaming and status changes never
move focus; focus utilities exist only for the cases where the host
explicitly manages focus, such as dialogs the host itself opens.
### Attention and preferences
The attention model keeps announcements appropriate to what the runtime can
conservatively observe. The observed modes are `foreground`, `background`,
`reading-history`, `away`, and `unknown`; the labels are deliberately
conservative and never claim to prove reading or intent. An explicit
override, `auto`, `normal`, or `quiet`, lets the host or the user take
precedence over observed evidence. The effective state is either `normal`
or `quiet`, and policies can quiet routine announcements when the user is
away or in the background.
Preferences follow the same principle: the host reports what the user chose,
and the runtime honors it. Preference handling stays in the DOM layer, where
browser storage and settings live, and is translated into core configuration
rather than read directly by the runtime.
### Diagnostics without surveillance
The runtime emits diagnostics alongside intents: what was prepared, when,
and under which policy. The devtools package renders these as redacted
traces, so developers can see the event-to-announcement pipeline
without leaking message content or user data into logs. The same
diagnostics power the recorder and replay fixtures used in tests.
Diagnostics describe the library's own behavior. They are evidence about
what the code did, not about what any person heard. Keep that boundary in
every dashboard, log line, and test report.
## Report only what the app knows
generative-a11y turns confirmed app events into screen-reader updates.
It records each update added to the page. Test with real screen readers to
confirm what they speak.
* Core does not use the DOM.
* Adapters do not run framework actions or control your interface.
* Streaming and status changes do not move focus.
* generative-a11y does not copy backend errors or tool results into
announcements.
The last point deserves emphasis: when a response fails or a tool errors,
the announcement is a curated status message from the announcement catalog,
not a paste of the backend error or tool result. Raw errors can contain
secrets, stack traces, or confusing internals; the catalog keeps
announcements safe, localizable, and honest about what is actually known.
### Messages and localization
Announcement wording lives in a message catalog, not inline in the
runtime. Each message has a key, parameters, and an optional locale, and
`formatAnnouncement` renders the final text. Keeping wording in one place
has three benefits: announcements stay consistent across events, they can
be translated without touching scheduling logic, and failure messages can
be curated rather than copied from backend errors.
The catalog never invents information. A tool failure announcement says a
tool failed; it does not include the tool's raw output. A retry
announcement says a retry is happening; it does not speculate about why.
This restraint is what makes the announcements safe to speak aloud in the
first place.
### Example: one streaming chat turn
Concretely, here is what happens when an assistant streams a two-sentence
reply in a React + AI SDK app:
1. The AI SDK adapter observes the framework's public streaming state and
dispatches `response.started` with a stable response id.
2. As text chunks arrive, the adapter dispatches `response.text.delta`
events carrying only the new text. The runtime buffers the text and,
under the balanced preset, waits for a sentence boundary with at least
24 characters before preparing an intent.
3. The scheduler emits a polite intent for the first sentence and queues
the second behind the minimum gap. If the same chunk arrives twice, the
dedupe window removes the repeat.
4. DOM delivery writes each intent into the live region and reports the
delivery result. Focus never moves.
5. When the framework reports the stream finished, the adapter dispatches
`response.completed`, and the policy prepares a completion announcement.
If the user interrupts instead, `response.interrupted` cancels the
pending queue first, so stale text is never announced after the fact.
At every stage the library can confirm what its own layer did: which
events arrived, which intents were prepared, and which updates reached the
page. What the screen reader spoke remains a question for manual testing.
---
# Attention-aware announcements
Opt into attention policy and add host-owned Auto, Normal, and Quiet controls to an existing React interface.
Canonical: https://generativea11y.com/docs/attention-aware-announcements
Markdown: https://generativea11y.com/markdown/docs/attention-aware-announcements
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Opt in at both layers
Core attention filtering is disabled by default. Set
`policy.attention.enabled: true` to enable it. Its default `quietWhen` is
`["background"]`; add `"reading-history"` or `"away"` only when appropriate for
your host interface.
The React provider's separate `attentionPolicy` prop opts into forwarding
browser observations to the runtime. It does not enable core filtering by
itself. A runtime supplied through `runtime` must already have its policy
configured; provider policy props do not reconfigure a borrowed runtime.
The provider renders no visible controls. Connect your existing interface, then
add an optional quiet toggle. With core attention disabled, the effective mode
remains normal.
## Enable attention policy
Follow the [React setup](/api/react), then import `A11yProvider` from
`@generative-a11y/react` and wrap your existing interface. Keep the default
system clock for production.
```tsx title="Provider configuration"
```
## Connect your existing elements
In your client module, import `useAttentionRefs` from `@generative-a11y/react`.
Call it inside a component under the provider to obtain callback refs for the
composer, conversation, and newest response. Attach those refs to your existing
elements to observe focus and visibility; keep your content and styling.
```tsx title="Conversation element bindings"
const { composerRef, conversationRef, newestResponseRef } = useAttentionRefs();
return (
<>
{response}
>
);
```
Here, `response` is your application's existing response content. These bindings
provide browser observations, not proof that someone is reading.
## Add controls where they fit
Import `useAttentionControl` from `@generative-a11y/react` in your client
module, then call it inside a component under the provider. Connect
`setOverride` to your own settings or controls. For example, a quiet toggle:
```tsx title="Quiet announcement toggle"
const { state, setOverride } = useAttentionControl();
return (
);
```
`setOverride("normal")` explicitly restores normal delivery regardless of
observations. `setOverride("auto")` follows attention policy again.
`state.observed` reports browser evidence; `state.effective` reports the
resulting normal or quiet mode.
## Understand what quiet suppresses
Quiet suppresses all response text, including full text announcements, and
routine response/tool/run/step starts and tool/step progress. It preserves
terminal, failure, interaction, connection, citation, and retry notices only
when the underlying policy already enables them. It does not turn on categories
disabled by the base policy.
There is no backlog on return. Text observed while quiet is discarded for
announcements while your host keeps rendering it normally. Sentence and
paragraph strategies discard the unit crossing the attention boundary and resume
at a fresh unit. A response that lost text during quiet mode is not replayed in
full by the completion strategy. This is more than a reduction in detail: users
can miss response content in announcements and must be able to read the host's
retained response.
Browser attention is a heuristic. The observer checks actual intersection of
your registered newest response, along with available focus and visibility
evidence. Intersection is not proof of a screen reader's virtual cursor location
or reading position. Missing evidence remains unknown. Ordinary streaming,
attention changes, and routine statuses never move focus.
## Ownership and delivery
The provider owns and disposes its internally created runtime, DOM delivery, and
stores when unmounted. An externally supplied runtime or store is borrowed: its
creator must dispose it after consumers detach.
Provider live regions are placed at body level, outside nested conversation
semantics. Keep your existing visible response and composer, and attach the
public ref bindings shown above. Do not add another live region around the
transcript: the provider handles delivery.
Without React, use `bindAttention({ runtime, attentionStore })` from
`@generative-a11y/dom`. It forwards the initial snapshot and subsequent changes.
Dispose the binding to unsubscribe and send an unknown observation; it owns
neither runtime nor store. Competing bindings to the same runtime are rejected.
See [DOM attention](/api/dom/attention), [core policy](/api/core/policy), and
[React hooks](/api/react/hooks).
Deterministic runtime tests and browser DOM checks establish filtering, cleanup,
and focus behavior in those environments. They do not prove actual
assistive-technology output. Manually test supported browser and screen-reader
combinations, including quiet/resume, background return, history navigation,
tool failure, approval, and explicit overrides.
---
# Streaming without repetition
Send only the new text from each streaming update so screen readers do not hear the whole response again and again.
Canonical: https://generativea11y.com/docs/lifecycle/streaming
Markdown: https://generativea11y.com/markdown/docs/lifecycle/streaming
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Send only the new text
Send response.started when a response begins. Each response.text.delta must
contain only the text that just arrived. Send response.completed to announce any
useful text still waiting. Send response.failed or response.interrupted to
discard that text.
```typescript title="Dispatch append-only response text"
runtime.dispatch({ type: "response.started", responseId: "r1" });
runtime.dispatch({
type: "response.text.delta",
responseId: "r1",
delta: "First complete sentence. ",
});
runtime.dispatch({
type: "response.text.delta",
responseId: "r1",
delta: "Second complete sentence.",
});
runtime.dispatch({ type: "response.completed", responseId: "r1" });
```
### Start the response
`response.started` opens the response under a `responseId` you choose, with an
optional `responseInstanceId` when you track attempts. The runtime creates its
tracking state here: the text buffer, the pending announcement queue, and the
locale. Dispatch the start before the first delta arrives, not after. A delta
for an unknown `responseId` is diagnosed as an unknown response and produces
no output, which is the correct behavior, but it means a missing start event
silently drops the beginning of your answer. If your framework's streaming
callbacks give you the first chunk and the start signal together, dispatch
both in the same tick, start first.
### Send new text only
Each `response.text.delta` must contain only the text that just arrived.
Never resend text from an earlier delta, and never send the full accumulated
response as a delta. The runtime treats every delta as new content; if you
send the accumulated string, the listener hears the first sentence again
with every chunk, then the first two sentences, then three, a triangular
repetition that makes long answers unlistenable. This is the single most
common streaming bug, and it is entirely in the host's hands to avoid. The
runtime cannot deduplicate for you because it cannot distinguish your
accumulated snapshot from genuinely repeated content.
### Let the runtime group text
Once honest deltas arrive, the runtime decides when the listener hears them.
The balanced policy groups text into sentences: it waits for a complete
sentence when possible, flushes buffered text after a maximum delay even
without a boundary, and skips announcements below a minimum character count.
In numbers, the balanced text policy is a sentence strategy, a 24-character
minimum, and a 2,500-millisecond maximum delay. That combination is the
reason the example above works: two sentence deltas become two announcements,
while a stream of word-level deltas would be reassembled into sentences
before anyone hears them.
The grouping has three moving parts worth understanding:
* **Segmentation.** The sentence strategy splits buffered text on
locale-aware sentence boundaries. Text after the last complete
boundary stays in the buffer as the remainder; it is not lost, just not
ready yet.
* **The minimum gate.** Buffered text shorter than `minimumCharacters` is not
announced on its own. This keeps fragments like "Sure," or "The answer is"
from becoming their own interruptions.
* **The maximum delay.** If text sits in the buffer longer than
`maximumDelayMs`, the runtime flushes what is there, boundary or not. A
listener waiting on a slow model still hears progress instead of silence.
### Finish the response
`response.completed` flushes any useful text still waiting, announces it when
it passes the minimum gate, and closes the response. Send it when the stream
ends normally, even if you think the buffer is empty; the completed event is
what releases the final boundary and marks the response terminal. The
terminal status is also what stops late deltas: any event arriving after
`response.completed`, `response.failed`, or `response.interrupted` is
diagnosed as a terminal response and produces no output.
## Tell append from replacement
Many frameworks expose accumulated text: each callback hands you the whole
response so far, not the new chunk. If your framework exposes accumulated
text, use its supported adapter to derive new text; the adapters do the
diffing for you. A custom integration must distinguish an append from a
replacement itself, and the distinction matters more than it sounds.
An append extends the previous text. A replacement rewrites it: the model
revised an earlier sentence, the framework re-rendered, or a tool result
was edited in place. Sending a replacement as a delta repeats the rewritten
region, and the runtime cannot tell the difference, it announces what you
send. The honest handling of a replacement depends on its size. For a small
correction inside an active response, send the corrected text as a delta and
accept that the listener hears the region twice; that is better than silence
about a changed answer. For a wholesale replacement, treat it as a retry:
send `response.retrying` with a new instance ID and start the text fresh, so
the old attempt's pending announcements are cancelled instead of interleaved.
See [stop and retry](/docs/lifecycle/stop-retry) for the attempt mechanics.
```ts title="Derive a delta from accumulated text"
let seen = "";
function onAccumulatedText(full: string, responseId: string) {
// Only the suffix is new. If the text was rewritten rather than
// extended, full will not start with seen, and the caller should
// treat it as a replacement, not an append.
if (!full.startsWith(seen)) {
runtime.dispatch({
type: "response.retrying",
responseId,
nextResponseInstanceId: `retry-${Date.now()}`,
attempt: 2,
});
seen = "";
}
const delta = full.slice(seen.length);
seen = full;
if (delta) {
runtime.dispatch({ type: "response.text.delta", responseId, delta });
}
}
```
This is a sketch, not a prescription: real diffing belongs in the adapter
for your framework. The point is the contract. Deltas are append-only by
definition, and anything that is not an append needs the retry path.
## Meaningful units, not tokens
Balanced mode waits for a complete sentence when possible. It can also prepare a
useful phrase after enough text arrives or a short delay. This avoids submitting
each token as its own announcement. See [core policy](/api/core/policy) to
change the text strategy or timing.
The available strategies:
| Strategy | Behavior |
| ------------ | ----------------------------------------------------------------------- |
| `sentence` | Groups into complete sentences; flushes on delay. The balanced default. |
| `paragraph` | Groups on blank-line boundaries instead of sentence boundaries. |
| `silent` | No text announcements; useful when the host reads content another way. |
| `completion` | Accumulates the full text and announces once when the response ends. |
Choose by how your content reads aloud. The sentence strategy suits chat
answers. The paragraph strategy suits structured content where a sentence
alone is a fragment, such as a list of steps. The completion strategy suits
short responses where intermediate announcements would be noise, at the cost
of the listener hearing nothing until the end. The silent strategy is for
hosts that surface text through their own accessible channel; it does not
mean the text is unimportant, only that this library is not its voice.
Change the strategy through `resolvePolicy`, not by post-processing
deltas yourself:
```ts title="Use the completion strategy"
import { createRuntime } from "@generative-a11y/core";
const runtime = createRuntime({
policy: {
text: { strategy: "completion", minimumCharacters: 0, maximumDelayMs: 0 },
},
});
```
`minimumCharacters` and `maximumDelayMs` tune the same grouping for the
sentence and paragraph strategies. Lower the minimum to hear shorter
fragments; raise the maximum delay to wait longer for a clean boundary. Every
tuning choice trades latency against coherence, and the balanced defaults
are the project's judgment about where that trade sits for most chat.
## Terminal events close the response
`response.completed`, `response.failed`, and `response.interrupted` each set
a terminal status on the response: completed, failed, or interrupted. The
status is terminal in the strong sense. The runtime retains just enough
state to diagnose what comes next, and every later event for that
`responseId` is diagnosed as a terminal response and produces no output.
This is what makes the stop and retry paths safe: a stopped answer cannot
be revived by a stray delta, and a failed answer cannot be completed by a
late success.
If you need to speak after a terminal event, you need a new response, not a
new event on the old one. Dispatch `response.started` with a fresh
`responseId` (or a retry with a new instance ID before the terminal event)
and the lifecycle begins again with a clean buffer and a clean slate.
## Keep one locale per response turn
Every event carries a `locale` field, and response announcements inherit it.
When the locale changes mid-response, for example a bilingual answer that
switches languages, the runtime flushes the buffered text in the old
language before switching, so announcements do not mix languages in one
breath. Pass the locale your host is actually rendering in on each event;
the message catalog is construction-time and locale-tagged, and the
prepared announcement carries the event's locale to the delivery layer. An
absent locale falls back to the runtime default, which is correct only when
your content is genuinely monolingual.
**Evidence and testing note**
Interactive examples show app text beside the screen-reader updates prepared
by a real runtime.
Prepared updates are still not heard speech. Confirm what people hear with
real screen readers, on the platforms your users use, before claiming an
experience is accessible.
## What these events prove
A `response.text.delta` proves your app reported new text and the runtime
accepted it into the buffer. A `response.completed` proves the runtime
flushed the remainder and closed the response. Neither proves what a screen
reader spoke, what the user heard, or that the grouping was pleasant to
listen to. Automated tests can assert on the prepared announcements; only
people with screen readers can tell you what the experience is like.
---
# Tool lifecycle
Tell users when an app action starts, makes progress, finishes, or fails without exposing private arguments or results.
Canonical: https://generativea11y.com/docs/lifecycle/tools
Markdown: https://generativea11y.com/markdown/docs/lifecycle/tools
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Report the start, progress, and result
Tool arguments can arrive before execution. Send `tool.started` only when the
operation begins, meaningful `tool.progress` milestones while it runs, and one
`tool.completed` or `tool.failed` event when it ends. Numeric `progress` is
optional; when present, use a value from 0 to 1.
Use the runtime already connected to your application:
```typescript title="Report a tool lifecycle"
runtime.dispatch({
type: "tool.started",
toolId: "report-1",
label: "Prepare report",
});
runtime.dispatch({
type: "tool.progress",
toolId: "report-1",
label: "Prepare report",
progress: 0.5,
message: "Halfway complete",
});
runtime.dispatch({
type: "tool.completed",
toolId: "report-1",
label: "Prepare report",
});
```
Field reference for all four events:
| Event | Field | Required | Meaning |
| ---------------- | ---------------- | -------- | ----------------------------------------------------- |
| `tool.started` | `toolId` | yes | Stable ID for the logical operation. |
| | `toolInstanceId` | no | Identifies one attempt when the tool runs repeatedly. |
| | `label` | yes | Short, translated, user-facing name of the operation. |
| `tool.progress` | `toolId` | yes | The same ID from the start. |
| | `toolInstanceId` | no | Must match the start's instance when one was given. |
| | `label` | yes | Short, translated, user-facing name. |
| | `progress` | no | Normalized progress from 0 to 1. |
| | `message` | no | Short, translated milestone copy. |
| `tool.completed` | `toolId` | yes | The same ID from the start. |
| | `toolInstanceId` | no | Must match the start's instance when one was given. |
| | `label` | yes | Short, translated, user-facing name. |
| | `summary` | no | Short result copy, announced when present. |
| `tool.failed` | `toolId` | yes | The same ID from the start. |
| | `toolInstanceId` | no | Must match the start's instance when one was given. |
| | `label` | yes | Short, translated, user-facing name. |
| | `error` | no | Diagnostic-only detail. Never announced. |
| | `announcement` | no | Short, translated, safe failure copy. Announced. |
Every field has a privacy contract. `label`, `message`, `summary`, and
`announcement` are user-facing copy and must already be translated and
safe to share. `error` is diagnostic-only and is never announced, which
is why backend detail belongs there. Raw tool results are not a field at
all; they stay private by construction.
### Keep one tool ID
Keep `toolId` stable for the operation across start, progress, completion, or
failure. The ID is the thread that ties the lifecycle together; the runtime
diagnoses progress for an unknown `toolId` as an unknown tool and produces
nothing. Labels may change between events if your copy does, but the ID must
not. For repeated executions of the same logical tool, add `toolInstanceId`
so late output from an earlier run is diagnosed as stale instead of being
attached to the new attempt. See [stable IDs](/docs/lifecycle/identity) for
the general rules.
```ts title="Separate repeated executions"
runtime.dispatch({
type: "tool.started",
toolId: "web-search",
toolInstanceId: "search-1",
label: "Search the web",
});
runtime.dispatch({
type: "tool.completed",
toolId: "web-search",
toolInstanceId: "search-1",
label: "Search the web",
summary: "Found 4 sources.",
});
```
### Provide localized copy
Labels and progress messages are user-facing copy; supply short,
translated text. The runtime never invents wording: start announcements are
rendered from a catalog message parameterized by your `label`, progress
announcements use your `message` when you provide one and a catalog fallback
otherwise, and completions announce your `summary` when present. The catalog
itself is construction-time and locale-tagged, and events carry a
`locale` field so prepared announcements inherit the right locale. If your
app supports multiple languages, translate the labels before dispatching;
the runtime cannot translate for you, and an English label in a Japanese UI
is a bug in your host, not in the library.
### Report progress milestones
Send `tool.progress` for meaningful milestones only, not for every tick of a
progress callback. When `progress` is present it must be a finite number from
0 to 1; values outside that range are diagnosed as invalid events. When
progress announcements are enabled, the runtime coalesces them into buckets
of `progressEveryPercent` (25 percent in the balanced policy), so a burst of
updates within one bucket produces a single announcement and the rest are
diagnosed as below the progress threshold.
The balanced policy keeps tool verbosity deliberately low:
| Setting | Balanced value | Effect |
| ---------------------- | -------------- | ------------------------------------------------- |
| `announceStart` | `true` | Start announcements exist... |
| `announceStartAfterMs` | `1,500` | ...but delayed 1.5 seconds, so quick tools stay |
| | | quiet and the listener hears only the completion. |
| `announceProgress` | `false` | Progress is silent by default. |
| `progressEveryPercent` | `25` | Bucket size when progress is enabled. |
| `announceCompletion` | `true` | Completions are announced. |
| `announceFailure` | `true` | Failures are announced on the polite channel. |
A tool that finishes before the 1.5-second start delay never announces a
start at all: the terminal event cancels the pending start announcement, and
the listener hears a single completion. That is the point. Most tool calls
in an agent loop are short, and announcing every start would be a drumbeat
of noise. If your tool is genuinely long-running and users need the
early signal, keep the default; the start announcement arrives 1.5 seconds
in, which is early enough to matter and late enough to skip the trivial.
### Summarize results briefly
`tool.completed` accepts a `summary`: one short sentence about the result,
announced when present. Use it for outcomes the user is waiting on: "Found 4
sources.", "Report saved to Downloads.", "No conflicts found." When
`summary` is absent, the runtime falls back to a catalog message built from
the label. Do not stuff raw tool output into `summary`; it is announced
verbatim, so it must be short, translated, and free of backend detail. If
the honest summary is "the tool returned 40 kilobytes of JSON," the summary
is not the place for it.
## Keep backend data out of announcements
Use error for debugging; generative-a11y never announces it. Set
announcement only when your app has a short, translated message that is safe
to share. Raw tool results also stay private.
The failure path deserves an example because it is the one place where
panic writes bad copy:
```ts title="Report a tool failure safely"
runtime.dispatch({
type: "tool.failed",
toolId: "report-1",
label: "Prepare report",
error: "template render: missing variable 'q3_revenue' (report.tpl:42)",
announcement: "The report could not be prepared. Check the template.",
});
```
The listener hears only the announcement, on the polite channel. The `error`
field, with its filename, line number, and variable name, goes to the
diagnostic trace and your logs. Note that tool failures announce on the
polite channel, not the assertive one: a failed tool is status information,
and the balanced policy reserves the assertive channel for response failures
and urgent interaction requests. If a tool failure genuinely demands
interruption, that is your host's decision to make through its own UI, not
something to smuggle into this event.
## What these events prove
A `tool.completed` event proves your host reported a completion and the
runtime prepared the corresponding announcement. It does not prove the tool
did the right thing, that the summary is accurate, or what a screen reader
spoke. Tool events describe your app's reporting of its own work. Test the
heard experience with real screen readers, and keep the diagnostic fields
honest so the trace is worth reading when something goes wrong.
---
# Represent hierarchical agent workflows
Model runs, nested and concurrent steps, retries, tools, and interactions without turning internal agent traffic into announcement noise.
Canonical: https://generativea11y.com/docs/lifecycle/workflows
Markdown: https://generativea11y.com/markdown/docs/lifecycle/workflows
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Preserve explicit hierarchy
`runId` and `stepId` identify logical work. `runInstanceId` and `stepInstanceId`
identify attempts. Parent run and step IDs preserve nesting only when the source
exposes it. Responses, tools, approvals, and interactions can carry the same
workflow context without becoming steps themselves.
For a run and parent step already reported to your runtime:
```ts title="Report an identified workflow step"
runtime.dispatch({
type: "step.started",
runId: "report",
runInstanceId: "run-1",
stepId: "sources",
stepInstanceId: "sources-2",
parentStepId: "research",
label: "Collect sources",
});
```
Concurrent siblings keep separate IDs. Completing or failing one does not
complete or cancel another. A successful parent completion is rejected while a
known child remains active.
## Keep routine workflow traffic quiet
The balanced policy announces terminal run summaries and identified steps only
after they become long-running. Nested steps and progress remain quiet by
default. Step failures use the configured error channel, while approval and
input requests retain their existing priority. When a completed response
boundary was already announced and a run has no identified step summary, its
generic completion is silent instead of repeating the same boundary.
Use [`policy.workflows`](/api/core/policy) to choose run boundary verbosity,
silent, long-running, or all step boundaries, the long-running threshold,
progress announcements, and whether nested steps may speak.
## Replace attempts without leaking stale work
`step.retrying` and `run.retrying` create explicit attempt boundaries. The
runtime cancels announcements owned by the replaced attempt and its descendants
while preserving siblings. Events carrying an older instance ID are diagnosed as
stale and do not produce output.
When a source exposes only a step name, omit `stepId`. The runtime emits an
ephemeral `partial-identity` diagnostic, but cannot create a step snapshot,
announcement, or run count from that evidence. It never treats display text,
array position, or timing as identity.
---
# Localized announcements
Connect your existing translations to runtime notices while keeping answer language, host UI, and lifecycle evidence independent.
Canonical: https://generativea11y.com/docs/localized-announcements
Markdown: https://generativea11y.com/markdown/docs/localized-announcements
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Use your existing translations
`generative-a11y` decides when an announcement is eligible and sends it to the
browser. Your application owns translated copy. A catalog contains strings or
synchronous functions that call your existing translation system; there is no
ICU parser, translation service, or additional i18n dependency.
```ts title="announcements.ts"
import { createRuntime } from "@generative-a11y/core";
import { en, type Messages } from "@generative-a11y/core/messages";
// English customization can reuse the English defaults.
const catalog = {
...en,
id: "my-app.en.v1",
messages: {
...en.messages,
"response.completed": "Your answer is ready.",
},
} satisfies Messages;
const runtime = createRuntime({ messages: catalog });
// Connect runtime to your existing DOM delivery or React provider.
// The owner calls runtime.dispose() at its terminal ownership boundary.
```
For another language, supply **all 25 keys**. Do not spread English defaults
into a catalog tagged French. A formatter receives only typed
labels/counts/outcomes; it can call your existing `t()` function and use your
application's pluralization. It never receives response content, backend errors,
or framework objects.
The complete
[French example catalog and adapter copy](https://github.com/bhaveshchow20/generative-a11y/blob/main/apps/docs/lib/french-announcements.ts)
shows every required key, including retries, workflows and plural counts. Copy
that file into your application as `announcements.ts`, then replace its
illustrative strings with your reviewed translations. `Intl.PluralRules` and
`Intl.NumberFormat` in that example are standard language APIs, not a
library-owned formatting engine.
## Language and ownership
`messages.locale` identifies runtime-generated sentences. Event `locale`
continues to identify host content: response text, explicit `announcement`,
`summary`, `message`, and request/resolution labels. An English answer can
coexist with French UI notices. Labels interpolated into a catalog sentence must
be supplied in that sentence's language; this API does not represent language
changes inside a single utterance.
Built-in English notices now explicitly carry `en`; previously a response locale
could incorrectly tag English boilerplate as another language. This is an
intentional metadata correction. Channels, timing, quiet mode and lifecycle
semantics do not change.
Catalog configuration is validated and copied at construction. All keys are
required, the ID and locale are limited to 128 UTF-16 code units, and
strings/results to 4,096. Use a non-sensitive versioned ID. Formatters must be
pure and synchronous. Invalid, empty, overlong or throwing results produce
`catalog-format-error` and a short English fallback tagged `en`, without
exposing arguments or exception text. A formatter cannot mute a notice or alter
urgency. Quiet/policy-suppressed messages never invoke it.
React's `A11yProvider` accepts `messages` through its existing options. For a
supplied `runtime`, configure the catalog on that runtime; the provider borrows
it and does not reconfigure it. Mount the provider with a stable catalog. Change
language at an intentional runtime/provider replacement boundary; do not replace
an active runtime on every render.
## Existing framework adapters
Pass `copy` to `createChatObserver`, `bindThread`, `bindAgent`, or
`useChatAccessibility`. This optional `AdapterCopy` contains `locale`,
`toolLabel`, `approvalRequested`, `approvalResolved`
(approved/rejected/cancelled), `inputRequested`, and `inputResolved`
(submitted/cancelled). Each adapter uses only the fields for events it already
recognizes.
```ts title="Localized AI SDK observer"
import { createChatObserver } from "@generative-a11y/ai-sdk";
import { createRuntime } from "@generative-a11y/core";
import { frenchCatalog, frenchAdapterCopy } from "./announcements";
const runtime = createRuntime({ messages: frenchCatalog });
const observer = createChatObserver({
runtime,
scopeId: "conversation-1",
copy: frenchAdapterCopy,
getToolLabel: () => "Recherche", // optional host label wins over toolLabel
});
// Feed documented public snapshots and terminal callbacks, as in the AI SDK guide.
// Cleanup: observer.dispose(), then runtime.dispose() when owned here.
```
The copy is validated, copied and frozen before subscribing.
`normalizeAdapterCopy(copy)` is exported from `@generative-a11y/core/messages`
for custom adapter authors; it returns that validated immutable copy and throws
`TypeError` for invalid configuration. It performs no translation.
Adapter copy applies its locale only to copy-bearing tool/interaction events,
never to generated response text. AI SDK `getToolLabel` must return text in the
configured copy language. The React hook captures copy with its observer; a new
runtime/scope or keyed component creates a new observer. Its current callback
may still supply a changing tool label. Defaults stay unchanged when copy is
omitted, including generic labels that avoid exposing backend tool names.
This customization adds no lifecycle inference and makes no new assistant-ui
approval-fidelity claim. Use the existing integration guides for provider order,
terminal callbacks and documented framework state:
* [AI SDK](/docs/integrations/ai-sdk)
* [assistant-ui](/docs/integrations/assistant-ui)
* [AG-UI](/docs/integrations/ag-ui)
## Test the integration
[Try localized announcements in the lifecycle lab](/examples/lifecycle-lab). The
visible answer remains English. Its response-text intents use `en`, while
completion uses the French catalog's `fr`. The example is illustrative copy, not
a reviewed translation pack or proof of screen-reader pronunciation.
With `ManualClock`, dispatch an English response start/delta/completion into a
runtime using your French catalog, then advance the clock. Assert English text
and French completion intents separately, including their locale fields. A zero
minimum gap still schedules delivery; dispatch alone does not drain timers.
Provider-owned live regions mount under `document.body`, outside the returned
render container.
Replay V1 remains unchanged. Reproduction requires the same catalog
implementation/version, adapter copy, policy, clock ordering and relevant Intl
environment. Fixtures contain normalized events and may contain host content;
they do not serialize callback code. Devtools shows only catalog ID/locale and
the format-error reason, never the catalog, arguments or exceptions.
Browser tests verify literal DOM insertion, language metadata before delivery,
focus and cleanup. They cannot establish speech, voice switching, pronunciation
or comprehension.
[WCAG language identification](https://www.w3.org/TR/WCAG22/#language-of-parts)
does not require translating every application or make a catalog proof of
conformance. Record real browser/AT observations separately.
## Public declarations: @generative-a11y/core/messages
Import from `@generative-a11y/core/messages`. Direct declarations from the source checkout; transitive upstream types and behavioral contracts require the linked guides and upstream documentation.
### AdapterCopy (type)
```typescript
interface AdapterCopy {
readonly locale: string;
readonly toolLabel: string;
readonly approvalRequested: string;
readonly approvalResolved: Readonly>;
readonly inputRequested: string;
readonly inputResolved: Readonly>;
}
```
### en (value)
```typescript
declare const en: Messages;
```
### MessageKey (type)
```typescript
type MessageKey = keyof MessageParams;
```
### MessageMap (type)
```typescript
type MessageMap = {
readonly [K in MessageKey]: string | ((parameters: Readonly) => string);
};
```
### MessageParams (type)
```typescript
/** Parameters contain only existing user-safe labels and bounded lifecycle facts. */
interface MessageParams {
"response.started": Record;
"response.completed": Record;
"response.interrupted": Record;
"response.failed": Record;
"response.retrying": {
attempt?: number;
};
"tool.started": {
label: string;
};
"tool.progress": {
label: string;
percent?: number;
};
"tool.completed": {
label: string;
};
"tool.failed": {
label: string;
};
"run.started": {
label?: string;
};
"run.completed": {
completedSteps: number;
failedSteps: number;
};
"run.interrupted": Record;
"run.failed": Record;
"run.retrying": {
attempt?: number;
};
"step.started": {
label: string;
};
"step.progress": {
label: string;
percent?: number;
};
"step.completed": {
label: string;
};
"step.interrupted": {
label: string;
};
"step.failed": {
label: string;
};
"step.retrying": {
label: string;
attempt?: number;
};
"interaction.resolved": {
kind: InteractionKind;
outcome: "approved" | "rejected" | "submitted" | "cancelled";
};
"approval.resolved": {
outcome: "approved" | "rejected" | "cancelled";
};
"connection.lost": Record;
"connection.restored": Record;
"citation.available": {
count: number;
};
}
```
### Messages (type)
```typescript
/** Construction-time, complete catalog. Callbacks must be pure and synchronous. */
interface Messages {
readonly id: string;
readonly locale: string;
readonly messages: MessageMap;
}
```
### normalizeAdapterCopy (value)
```typescript
/** Validate and snapshot shared adapter copy before creating a binding. */
declare function normalizeAdapterCopy(copy: AdapterCopy): AdapterCopy;
```
---
# Stop, abort, retry, and stale responses
Stop pending announcements when a response is cancelled, and ignore late updates from an older retry.
Canonical: https://generativea11y.com/docs/lifecycle/stop-retry
Markdown: https://generativea11y.com/markdown/docs/lifecycle/stop-retry
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Stopping a response clears pending text
Send response.interrupted when your app stops a response. Core discards waiting
text and prepares a short status update. Adapters do not treat a generic ready
state as proof that someone stopped a response. The host must also cancel its
network request or model generation; dispatching an accessibility event does not
abort that work or recall speech already handed to assistive technology.
Concretely, `response.interrupted` does three things inside the runtime:
1. Cancels the response's scheduled announcements and lifecycle scope, so no
queued sentence from the stopped answer can slip out later.
2. Clears the text buffer and anything waiting for the completed boundary.
3. Marks the response `interrupted` and, when the policy allows, prepares a
short polite status message from the message catalog, something equivalent
to "Response stopped." The balanced policy announces interruptions; the
`completion-only` preset stays silent.
What it does not do is just as important. The event cannot abort your fetch,
close your stream, or stop the model; you must do that in your own stop
handler, in the same tick, before or alongside the dispatch. It also cannot
recall speech already handed to assistive technology. If the screen reader has
already started speaking a sentence, that sentence finishes. The interruption
announcement describes what happened next: the response was stopped, and no
more of it is coming.
```ts title="Stop a response the user cancelled"
async function stopResponse(responseId: string) {
// 1. Stop the host work first: abort the fetch, close the reader.
controller.abort();
// 2. Then tell the runtime, so pending announcements are discarded.
runtime.dispatch({ type: "response.interrupted", responseId });
}
```
The order matters. If you dispatch first and abort second, a slow abort lets
late deltas arrive after the interruption, and those deltas extend a response
the user was told had stopped. Abort the host work, then report the stop.
## Failure discards text too
Not every ended response was stopped by the user. When a response ends in
error, a timed-out request, a failed model call, a stream that broke
mid-sentence, send `response.failed`:
```ts title="Report a failed response"
runtime.dispatch({
type: "response.failed",
responseId: "report",
error: "upstream 502 after 8.2s",
announcement: "The report could not be generated. Try again.",
});
```
The two message fields have opposite privacy rules:
| Field | Purpose |
| -------------- | ----------------------------------------------------- |
| `error` | Diagnostic-only backend detail. Never announced. |
| `announcement` | Short, translated, user-safe failure copy. Announced. |
When `announcement` is present, the runtime announces it. When it is absent,
the runtime falls back to a catalog message equivalent to "Response failed."
Failures announce on the error channel, which is assertive in the balanced
policy, because a failed response is information the user needs even if
something else is being read. The `completion-only` preset disables failure
announcements entirely; choose it only if your host surfaces errors through
its own accessible UI.
Keep `error` genuinely diagnostic: status codes, latencies, exception names.
It exists so your logs and the devtools trace can explain the failure without
leaking backend detail into the live region. Raw model errors often contain
prompt fragments or internal hostnames; they must never reach `announcement`.
Like interruption, failure clears the text buffer and anything staged for the
completed boundary, then marks the response failed. There is no host work left
to cancel, the work already failed, so dispatch `response.failed` as soon as
your error handler knows the response is over. Do not wait for a retry
decision: if you decide to retry afterward, send `response.retrying` as its
own event with a new instance ID. A failure followed by a retry is two facts,
and the listener deserves to hear both, the failure on the error channel and
the retry as a new attempt, rather than a silent pivot.
## Tell the runtime when a retry starts
`response.retrying` cancels the current attempt’s pending announcements. Keep
one `responseId` for the logical answer and give each attempt a new
`responseInstanceId`. Core ignores late updates from older attempts.
For an active `report` response on `attempt-1`:
```typescript title="Replace a response attempt"
runtime.dispatch({
type: "response.retrying",
responseId: "report",
responseInstanceId: "attempt-1",
nextResponseInstanceId: "attempt-2",
attempt: 2,
});
runtime.dispatch({
type: "response.text.delta",
responseId: "report",
responseInstanceId: "attempt-2",
delta: "The updated report is ready. ",
});
runtime.dispatch({
type: "response.completed",
responseId: "report",
responseInstanceId: "attempt-2",
});
```
### Identify the replaced attempt
The `response.retrying` event names the attempt being replaced through
`responseInstanceId`. This is the attempt whose pending announcements are
cancelled. If your host never assigned instance IDs and sent deltas with a
bare `responseId`, omit `responseInstanceId` here too; the retry then replaces
the un-instanced attempt. What you must not do is name the wrong
attempt: the cancellation is keyed on this field, and a mismatch leaves the
old attempt's queued sentences alive.
### Name the new attempt
`nextResponseInstanceId` becomes the identity of the replacement attempt.
`attempt` is the human-readable one-based attempt number and exists
for catalog copy, for example a retry announcement equivalent to "Retrying,
attempt 2." The balanced policy announces retries, so the listener hears that
a new attempt began instead of wondering why the text restarted. If you omit
`nextResponseInstanceId`, the runtime treats the retry as returning to an
un-instanced attempt, which is correct only when your attempts never had
instance IDs in the first place.
### Keep the response ID
The `responseId` is the logical answer and it does not change across retries.
The regenerated answer is still the answer to the same request, so it keeps
`responseId: "report"` while the instance moves from `"attempt-1"` to
`"attempt-2"`. Every later delta and terminal event carries `"attempt-2"`.
This is what lets the runtime attach the new text to the right answer, the
devtools trace show one answer with two attempts, and your tests assert on a
stable identifier that survives regeneration.
## Late updates from replaced attempts are ignored
A retry does not guarantee the old attempt is silent. A slow stream can
deliver one more delta for `attempt-1` after the retry already started. The
runtime compares the event's `responseInstanceId` against the current
instance, diagnoses the late event as a stale response, and produces no
output. The listener never hears interleaved fragments of an answer the app
already discarded. Even a delta that omits `responseInstanceId` is caught
once the retry named a current instance; the mismatch alone is enough.
This protection depends on you sending instance IDs consistently. If you
never use instance IDs at all, neither the runtime state nor the late event
carries one, and there is nothing to mismatch against. The same rule applies
to terminal events: a `response.completed` carrying the old instance ID
after a retry is diagnosed stale, not announced, so a completed boundary
from a discarded attempt can never masquerade as the new answer's
completion. An event for a response that is already terminal is diagnosed
as a terminal response and likewise produces nothing.
The general principle is worth stating plainly: the runtime trusts the IDs
you send. Unknown, terminal, or stale identities are diagnosed, never
announced. Supplying accurate instance IDs is what makes stop, retry, and
regeneration safe for the listener.
## What these events prove
A `response.interrupted` event proves your host dispatched a stop and the
runtime discarded its pending announcements. A `response.retrying` event
proves the runtime moved to a new attempt and will ignore late updates from
the old one. Neither proves what a screen reader spoke, and an interruption
announcement cannot unsay text the assistive technology already started
reading. Treat these events as lifecycle facts about your app's reporting,
and confirm the heard experience with real screen readers.
---
# Interactions and approvals
Announce approvals, confirmations, and requests for input when your app can confirm that they opened or closed.
Canonical: https://generativea11y.com/docs/lifecycle/interactions
Markdown: https://generativea11y.com/markdown/docs/lifecycle/interactions
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Prefer the general interaction model
Use `interaction.requested` and `interaction.resolved` for confirmations and
other requests for input. Use approval events when the framework provides a
specific approval state.
Dispatch through the runtime already connected to your application:
```ts title="Announce a confirmed approval decision"
runtime.dispatch({
type: "approval.requested",
approvalId: "publish-report",
label: "Approve publishing the report",
});
// Dispatch only after the application confirms the decision.
runtime.dispatch({
type: "approval.resolved",
approvalId: "publish-report",
outcome: "approved",
});
```
Keep the request ID through resolution. A rendered button, elapsed time, or
closed panel is insufficient evidence of approval. The host performs the
authorized action; these events only describe its lifecycle.
## Choose the event shape that matches the evidence
Two event pairs cover every request for human input. Pick by what your source
actually exposes:
| Pair | Use when |
| ------------------------------------------------ | -------------------------------------------------------- |
| `interaction.requested` / `interaction.resolved` | Your app asks for confirmation, input, or a decision. |
| `approval.requested` / `approval.resolved` | The framework exposes a specific approval state, such as |
| | tool-use approval in an agent framework adapter. |
The general pair is the default. If your app asks "Send this email?" or
"Which file did you mean?", that is an `interaction`, even if the UI calls it
an approval. Reserve the approval pair for integrations where the framework
itself tracks an approval lifecycle with an approval ID, because adapters map
those IDs directly to `approvalId`.
Field reference for the request side:
| Event | Field | Required | Meaning |
| ----------------------- | --------------- | -------- | ------------------------------------------ |
| `interaction.requested` | `interactionId` | yes | Stable ID for this request. |
| | `kind` | yes | `"approval"`, `"confirmation"`, `"input"`, |
| | | | or a custom string your host defines. |
| | `label` | yes | Short, translated, user-facing copy. |
| | `urgent` | no | `true` announces on the assertive channel. |
| `approval.requested` | `approvalId` | yes | Stable ID for this approval. |
| | `label` | yes | Short, translated, user-facing copy. |
| | `urgent` | no | `true` announces on the assertive channel. |
The `kind` field is an open union: `"approval" | "confirmation" | "input"`
plus any string your host defines. A custom kind such as `"disambiguation"`
or `"slot-fill"` is valid, but keep it a stable machine string. The kind is
used in the fallback catalog message when a resolution omits `label`, and it
appears in devtools traces, so a kind that changes wording per request makes
both unreadable. Kinds are not labels; the label carries the human copy.
```ts title="Request confirmation with a custom kind"
runtime.dispatch({
type: "interaction.requested",
interactionId: "pick-file",
kind: "disambiguation",
label: "Which file did you mean: report.md or report-final.md?",
});
```
## Mark urgent requests honestly
The request events announce `label` on the polite channel by default. Setting
`urgent: true` moves the announcement to the assertive channel, which can
interrupt speech already in progress. That interruption is a real cost to the
listener, so reserve `urgent` for requests where time genuinely matters and
the request blocks progress: an expiring payment confirmation, a
time-boxed deployment gate, a safety-critical override.
Do not mark a request urgent just because it is important. Importance without
a deadline still belongs on the polite channel; the user reaches it after the
current announcement finishes. If every request in your app is urgent, none of
them are, and you have trained the listener to ignore the assertive channel.
```ts title="Request an expiring confirmation"
runtime.dispatch({
type: "interaction.requested",
interactionId: "deploy-prod",
kind: "confirmation",
label: "Confirm the production deploy. This approval expires in 60 seconds.",
urgent: true,
});
```
## Resolve with an outcome, not just a label
A resolution must say what happened. The two pairs accept different outcomes
because they describe different evidence:
| Event | Outcome |
| ---------------------- | ------------------------------------------ |
| `interaction.resolved` | `"approved"`, `"rejected"`, `"submitted"`, |
| | `"cancelled"` |
| `approval.resolved` | `"approved"`, `"rejected"`, `"cancelled"` |
Use `"submitted"` for input the user filled in and sent, `"cancelled"` for a
dismissed or abandoned request, and `"approved"` / `"rejected"` for decisions.
Approval resolutions have no `"submitted"` because an approval is a decision,
not a form.
Field reference for the resolution side:
| Event | Field | Required | Meaning |
| ---------------------- | --------------- | -------- | ---------------------------------------------------- |
| `interaction.resolved` | `interactionId` | yes | The same ID from the request. |
| | `kind` | yes | The same kind from the request. |
| | `outcome` | yes | What the user did. |
| | `label` | no | Optional short result copy, e.g. "Report published." |
| `approval.resolved` | `approvalId` | yes | The same ID from the request. |
| | `outcome` | yes | What the decider did. |
| | `label` | no | Optional short result copy. |
When a resolution omits `label`, the runtime renders a catalog message from
`kind` and `outcome` instead, so the announcement still reads as a complete
sentence. Supply `label` when your app has result copy worth hearing, such as
what was actually published or where the submitted input went. Keep it short
and translated, the same standard as every other announcement.
```ts title="Resolve the disambiguation"
runtime.dispatch({
type: "interaction.resolved",
interactionId: "pick-file",
kind: "disambiguation",
outcome: "submitted",
label: "Using report-final.md.",
});
```
Dispatch the resolution only after the application confirms the decision, not
when the dialog closes. A dialog can close through dismissal, navigation, or
a crash, and none of those is evidence of what the user chose. The event
describes the lifecycle your host confirmed; the host is the only source that
can confirm it.
## Announcements do not move focus
generative-a11y can announce when your app needs input. Your app still opens
the dialog, manages its controls, and restores focus when it closes.
That division is deliberate. Moving focus is a destructive act for a screen
reader user: it yanks the reading cursor, destroys their place, and cannot be
undone by the announcement that caused it. So the library never moves focus,
and the host keeps every responsibility that focus implies:
* Opening the dialog or panel when the request goes out, in the same tick as
the `interaction.requested` or `approval.requested` dispatch where possible,
so the announcement and the available control arrive together.
* Trapping focus inside modal dialogs and returning it to the invoking
control when the dialog closes, following the usual dialog pattern.
* Handling Escape, dismissal, and the `"cancelled"` outcome honestly: a
dismissed request still gets its resolution event, because the lifecycle
did resolve, just not in the user's favor.
* Keeping the visible request text and the announcement `label` consistent so
a sighted user and a screen reader user hear about the same request.
The announcement is a polite (or assertive, when urgent) live-region
update. The dialog is the interaction. Do not rely on the announcement to
substitute for a reachable, keyboard-operable control.
## Scope IDs keep parallel surfaces apart
When two chat surfaces share one runtime, for example a main chat and a
sidebar assistant, framework IDs can collide. Framework adapters prevent that
by namespacing every stable ID with a `scopeId` supplied at adapter
construction. The AI SDK adapter builds scoped IDs such as
`` `${scopeId}:approval:${id}` `` for approvals, `` `${scopeId}:tool:${toolCallId}` ``
for tools, and `` `${scopeId}:message:${messageId}` `` for responses. Your
custom integration should do the same whenever one runtime serves more than
one surface: derive every dispatched ID from a per-surface prefix.
Adapters also defend the runtime from unbounded growth. An observer keeps a
set of tracked response, tool, approval, and source identities, capped by
`maxTrackedEntities`. Once that safety limit is reached, the adapter stops
accepting unknown IDs instead of tracking more. The runtime then diagnoses
events for unknown entities instead of announcing them, which is the same
treatment an unknown `interactionId` receives. If your adapter suddenly goes
quiet on a long-running surface, check whether it hit its tracked-entity
limit before assuming the runtime swallowed the events.
## What these events prove
An `interaction.requested` event proves that your app dispatched a request,
and the devtools trace can show that the announcement was prepared and which
channel carried it.
An `interaction.resolved` event proves that your host confirmed the outcome.
Neither proves what a screen reader spoke, what the user heard, or what the
user intended. Treat the events as lifecycle facts, test the experience with
real screen readers, and never claim that an automated transcript of
announcements is evidence of a human decision.
---
# Keep updates connected with stable IDs
Use stable IDs to keep every update connected to the correct run, step, response, tool, interaction, or approval.
Canonical: https://generativea11y.com/docs/lifecycle/identity
Markdown: https://generativea11y.com/markdown/docs/lifecycle/identity
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Use a stable ID for each piece of work
`runId` and `stepId` identify workflow entities, while their instance IDs
separate attempts. `responseId` identifies an answer, `toolId` identifies a tool
call, and `interactionId` or `approvalId` connects each request to its result.
For example, a regenerated answer keeps `responseId: "report"` while changing
`responseInstanceId` from `"attempt-1"` to `"attempt-2"`. Every later delta and
terminal event carries `"attempt-2"`. See
[stop and retry](/docs/lifecycle/stop-retry) for the transition event.
| Entity | Identity | Why it matters |
| ------------- | ----------------------- | ------------------------------------------------------------ |
| Run attempt | runId + runInstanceId | Separates workflow retries and delegated work |
| Step attempt | stepId + stepInstanceId | Preserves concurrent siblings and rejects stale retry output |
| Response | responseId | Keeps text and the final state together |
| Attempt | responseInstanceId | Ignores late text from an older retry |
| Tool | toolId + toolInstanceId | Separates repeated tool runs |
| Interaction | interactionId | Connects a request to its result |
| Adapter mount | scopeId | Prevents ID collisions across chats |
The pattern is the same everywhere: a stable ID names the logical thing, and
an instance ID names one attempt at it. The logical ID never changes for the
life of the work; the instance ID changes exactly when the work restarts.
When an event arrives, the runtime looks up the logical ID first. If it is
unknown, the event is diagnosed and ignored. If it is known but terminal,
the event is diagnosed and ignored. If the instance ID does not match the
current attempt, the event is diagnosed as stale and ignored. Only a live
logical ID with a current instance ID produces output. That ordering is the
whole safety model: identity decides whether an event may speak.
## Workflows carry context, not just identity
Responses, tools, approvals, and interactions are not steps, but they can
declare which workflow owns them. Every one of these events accepts the
workflow context fields: `runId`, `runInstanceId`, `stepId`, and
`stepInstanceId`. Supply them when the work genuinely belongs to a reported
run or step, for example a tool call the agent made inside step `"sources"`
of run `"report"`. The runtime uses the context for diagnostics and for the
devtools trace, so a tool failure can be read as "the search tool failed
inside the sources step" rather than as a free-floating failure.
The type system enforces the shape of that context: you can supply a `runId`
alone, or a `runId` with a `stepId`, but you cannot supply a `stepId`
without its owning `runId`, and you cannot supply instance IDs without
their logical IDs. Partial context, a bare step name with no `stepId`, for
instance, produces an ephemeral partial-identity diagnostic and no
snapshot, no announcement, and no run count. The runtime never treats
display text, array position, or timing as identity, so a name without an ID
is evidence of nothing.
```ts title="Attribute a tool call to its workflow step"
runtime.dispatch({
type: "tool.started",
toolId: "web-search-1",
label: "Search the web",
runId: "report",
runInstanceId: "run-1",
stepId: "sources",
stepInstanceId: "sources-2",
});
```
## Generate IDs the host can reproduce
Stable means stable across renders, retries, and replays, and reproducible
by the host without consulting the runtime. The best IDs are the ones your
framework already gives you: the message ID for a response, the tool-call
ID for a tool, the approval ID the framework tracks for an approval. Derive
your dispatched IDs from those, generate them once per logical entity, and
reuse them for every event in that entity's lifecycle.
A few rules keep generated IDs honest:
* Generate the ID when the logical work begins, not when the first event
fires. If the work exists before you report it, the ID should already
exist too.
* Never derive an ID from displayed text, a label, an array position, or a
render count. All four change: text gets translated, lists reorder,
renders repeat. An ID built from any of them will silently fork one
logical entity into several.
* Keep instance IDs ordered and human-readable where you can:
`"attempt-1"`, `"attempt-2"`. They appear in diagnostics and in the retry
announcement's attempt number, and a readable sequence is easier to debug
than a UUID.
* Do not reuse a logical ID for new work. When the user asks a follow-up
question, that is a new response with a new `responseId`, even if it looks
like a continuation. Reusing the old ID attaches the new answer to a
terminal response, and terminal responses do not speak.
## Scope IDs prevent cross-surface collisions
One runtime can serve more than one surface: a main chat and a sidebar
assistant, two tabs sharing a worker, a preview pane beside an editor. Each
surface gets its own `scopeId` at adapter construction, and the adapter
prefixes every stable framework ID with it. The AI SDK adapter builds
`` `${scopeId}:message:${messageId}` `` for responses,
`` `${scopeId}:tool:${toolCallId}` `` for tools, and
`` `${scopeId}:approval:${id}` `` for approvals. Two surfaces reporting
message `"abc"` become `chat-1:message:abc` and `chat-2:message:abc`: no
collision, no cross-talk, no sidebar announcement attributed to the main
chat.
If you write a custom integration over a shared runtime, do the same. The
`scopeId` is not a dispatched event field; it is a construction-time
namespace your adapter applies before dispatching. Pick it per surface,
keep it stable for the surface's lifetime, and never reuse one scope's IDs
in another.
## Capacity has a safety limit
Identity tracking is bounded on both sides of the dispatch. Adapters cap
their tracked response, tool, approval, and source identities with
`maxTrackedEntities`; once the limit is reached, the adapter stops accepting
unknown IDs rather than growing without bound. The runtime caps active
entities with `maxActiveEntities`, 1,000 in the balanced policy, and rejects
new work past the cap as an invalid event.
These limits are why a long-running surface can go quiet without any
error being announced. If your adapter stops reporting new tools on a chat
that has been open for hours, check whether it reached its tracked-entity
limit before assuming the runtime swallowed the events. The limit is a
safety property, not a bug: an unbounded identity map is a memory leak with
an announcement system attached.
## Unknown and stale IDs are diagnosed, not announced
Every identity check that fails produces a diagnostic instead of an
announcement. The diagnostic reasons name the failure precisely:
`unknown-response` and `unknown-tool` for IDs the runtime never saw,
`terminal-response` and `terminal-tool` for work that already ended,
`stale-response`, `stale-tool`, `stale-run`, and `stale-step` for events
carrying an older instance ID, and `partial-identity` for name-only
evidence without a stable ID. Subscribe with `onDiagnostic` on
`createRuntime` to watch these decisions during development.
Diagnostics are content-free by design: they carry the event type, the
IDs, the disposition, and the reason, never the announcement text. That is
what makes them safe to log, to render in the devtools inspector, and to
paste into a bug report. When a user says "I never heard the tool finish,"
the diagnostic trace answers whether the completion was announced,
suppressed by policy, or rejected for a stale instance ID, without exposing
what the tool said.
## Labels are copy, not identity
Do not use displayed text, labels, array positions, or render counts as IDs
because they can change. Framework adapters keep stable IDs from your framework
and stop accepting unknown IDs after reaching their safety limit.
This bears repeating because it is the most common identity bug in custom
integrations: the label is right there, it is unique right now, and using it
as the ID works in every demo. Then the app ships in twelve languages, the
label becomes a translation key's output, and one logical tool forks into
twelve identities, or two tools with the same display name merge into one.
Labels are copy. They are translated, punctuated, and rewritten by product.
IDs are identity. They are stable, opaque, and boring. Keep the two jobs
separate and the runtime can do its job.
## What stable IDs prove
Stable IDs prove routing: that an update reached the right response, the
right tool, the right attempt. They prove nothing about what a screen reader
spoke. An event with a perfect `responseId` and a current
`responseInstanceId` still only proves that the runtime prepared the
announcement. Treat identity as the addressing on the envelope, test the
heard experience with real screen readers, and let the diagnostics tell you
when the address was wrong.
---
# Vercel AI SDK accessibility
Add paced screen-reader updates to AI SDK through documented state, finish callbacks, and error callbacks.
Canonical: https://generativea11y.com/docs/integrations/ai-sdk
Markdown: https://generativea11y.com/markdown/docs/integrations/ai-sdk
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Install for your existing app
```shell title="Terminal"
npm install @generative-a11y/react @generative-a11y/ai-sdk
```
```shell title="Terminal"
pnpm add @generative-a11y/react @generative-a11y/ai-sdk
```
```shell title="Terminal"
yarn add @generative-a11y/react @generative-a11y/ai-sdk
```
```shell title="Terminal"
bun add @generative-a11y/react @generative-a11y/ai-sdk
```
Requires AI SDK 7 / `@ai-sdk/react` 4 and React 18.2+ or 19.
See [Compatibility](#compatibility) for the supported minor versions and peers.
## React integration
### Import the hooks
Add these imports to your chat module. In a React Server Components app, keep
it behind a `"use client"` boundary.
```tsx title="components/chat.tsx"
"use client";
import { DefaultChatTransport } from "ai";
import { useChat } from "@ai-sdk/react";
import { A11yProvider, useRuntime } from "@generative-a11y/react";
import {
useChatAccessibility,
useObserveChatAccessibility,
} from "@generative-a11y/ai-sdk/react";
```
### Connect your chat
Inside your existing `Chat()`, create accessibility before `useChat`, then
observe the returned state. Keep your transport and other chat options; the
example below uses `/api/chat`.
```tsx title="components/chat.tsx"
const runtime = useRuntime();
const accessibility = useChatAccessibility({
runtime,
scopeId: "support",
});
const chat = useChat({
id: "support",
transport: new DefaultChatTransport({ api: "/api/chat" }),
...accessibility.chatCallbacks,
});
useObserveChatAccessibility({ integration: accessibility, snapshot: chat });
```
### Add the provider
Wrap your chat once:
```tsx title="components/chat.tsx"
export function App() {
return (
);
}
```
Keep using `chat` in your existing UI. See the
[complete copyable component](/api/ai-sdk/use-chat-accessibility) for a minimal
message list and composer.
### Existing callbacks
Already use `onFinish` or `onError`? Pass your existing functions to
`useChatAccessibility` so they are composed rather than replaced. Keep the rest
of your options, including transport, in `existingOptions`, and spread the
composed callbacks last. Omit either callback if your app does not use it.
```tsx title="components/chat.tsx"
const accessibility = useChatAccessibility({
runtime,
scopeId: "support",
onFinish,
onError,
});
const chat = useChat({ ...existingOptions, ...accessibility.chatCallbacks });
```
### Ownership and behavior
**One provider per chat surface**
`A11yProvider` owns runtime and browser delivery. The adapter owns observer
cleanup. Both clean up on unmount; keep the provider mounted across responses
and `scopeId` stable for that session.
This adds paced live-region updates without changing your visible UI or moving
focus during ordinary streaming. Your app still owns semantic structure,
keyboard controls, and accessible content. DOM checks do not prove screen-reader
output.
## Advanced: preconstructed Chat
With `useChat({ chat: existingChat })`, other initialization options, including
callbacks, are ignored. Compose callbacks when constructing that chat using the
[observer API](/api/ai-sdk), and manage its subscription and cleanup at that
boundary.
## Compatibility
| Dependency | Supported range | Checked version |
| --------------------- | ------------------------------------------------- | --------------- |
| Node.js | 22+ | 22.16.0 |
| `ai` | `>=7.0.0 <7.1.0` | 7.0.77 |
| `@ai-sdk/react` | `>=4.0.0 <4.1.0` | 4.0.80 |
| `react` / `react-dom` | 18.2+ within major 18, or 19.x | 19.2.8 |
| `zod` (host SDK peer) | 3.25.76+ within major 3, or 4.1.8+ within major 4 | 4.4.3 |
Your existing AI SDK app supplies these dependencies and a working backend.
Core and DOM install transitively; declare them directly only if your own code
imports them. The React hooks live at `@generative-a11y/ai-sdk/react`; the root
observer entry remains usable without React.
## Lifecycle mapping
The adapter translates confirmed public SDK evidence:
| Evidence | Reports |
| ----------------------------------------- | ------------------------------------------------------ |
| Append-only assistant text | Response text updates |
| Tool parts, approval IDs, and source IDs | Tools, approvals, and citations |
| Composed `onFinish` / `onError` callbacks | Completion, cancellation, failure, and connection loss |
Retry and regenerate detection are unavailable. A successful finish after a
disconnection reports recovery. See the [observer reference](/api/ai-sdk) for
exact mappings and limits.
## Troubleshooting
* **Missing completion updates:** create accessibility before `useChat` and spread
its composed callbacks last.
* **Repeated output:** keep `scopeId` stable and attach only one observer per chat.
* **Existing messages are silent:** the first snapshot establishes a history
baseline. The adapter observes subsequent updates without replaying history.
---
# assistant-ui accessibility
Add paced screen-reader updates to an assistant-ui thread without replaying messages already present in its history.
Canonical: https://generativea11y.com/docs/integrations/assistant-ui
Markdown: https://generativea11y.com/markdown/docs/integrations/assistant-ui
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Install the assistant-ui adapter
```shell title="Terminal"
npm install @generative-a11y/core @generative-a11y/dom @generative-a11y/assistant-ui
```
```shell title="Terminal"
pnpm add @generative-a11y/core @generative-a11y/dom @generative-a11y/assistant-ui
```
```shell title="Terminal"
yarn add @generative-a11y/core @generative-a11y/dom @generative-a11y/assistant-ui
```
```shell title="Terminal"
bun add @generative-a11y/core @generative-a11y/dom @generative-a11y/assistant-ui
```
Use the thread your app already owns. See [Compatibility](#compatibility) for
supported host dependencies.
## Connect an existing thread runtime
### Create the binding
Add this function to your browser app. It creates a runtime and browser delivery,
then subscribes to your existing thread.
```ts title="accessibility/assistant-ui.ts"
import { createRuntime } from "@generative-a11y/core";
import { bindRuntime } from "@generative-a11y/dom";
import { bindThread, type ThreadRuntimeSource } from "@generative-a11y/assistant-ui";
export function connectAccessibility(thread: ThreadRuntimeSource) {
const runtime = createRuntime({});
const delivery = bindRuntime(runtime);
const binding = bindThread({
runtime,
scopeId: "support-thread",
thread,
});
return () => {
binding.dispose();
delivery.dispose();
runtime.dispose();
};
}
```
### Connect it to your app lifecycle
Call this once when your hydrated thread is ready. Here,
`thread` is your existing public assistant-ui thread runtime.
```ts title="App mount callback"
import { connectAccessibility } from "./accessibility/assistant-ui";
const disconnectAccessibility = connectAccessibility(thread);
```
Keep the binding alive across responses. Call the returned function when the
surface unmounts or before replacing the thread:
```ts title="App unmount callback"
disconnectAccessibility();
```
**Keep one owner for each resource**
The example owns its core runtime and DOM delivery. If your app already has
these, pass that runtime directly to `bindThread` and clean up only its returned
binding. In React, use the runtime from `A11yProvider` and return
`() => binding.dispose()` from your effect. Do not attach a second delivery
layer to that provider.
Keep `scopeId` stable and unique for each mounted thread. The adapter leaves your
visible UI and actions with the host application.
## Optional configuration
`maxTrackedEntities` defaults to `1000` and bounds adapter identity records.
`copy` supplies localized tool and interaction labels. See the
[`bindThread` reference](/api/assistant-ui/bind-thread) for
all options and the [localization guide](/docs/localized-announcements) for copy
configuration.
## Compatibility
| Dependency | Supported range | Checked version |
| -------------------- | ----------------- | --------------- |
| Node.js | 22+ | — |
| `@assistant-ui/core` | `>=0.3.13 <0.4.0` | 0.3.15 |
Your existing app supplies the host dependency. The adapter itself needs no
React rendering layer; this example uses core and DOM directly.
## Lifecycle mapping
| Public thread evidence | Reports |
| ---------------------------------------------- | ------------------------------------ |
| Append-only assistant text | Response text updates |
| Known complete or incomplete statuses | Completion, cancellation, or failure |
| Tool calls, results, approval IDs, and sources | Tool, approval, and citation updates |
`bindThread` reads only `getState` and `subscribe`. It records the initial
snapshot as history, so messages already present are not replayed. Connect after
history hydration to establish the intended baseline.
## Expected screen-reader behavior
Core paces announcement intents; DOM writes them to hidden live regions. Routine
streaming and status changes leave focus in place. Confirm spoken output with
your supported screen readers and browsers: a DOM transcript records browser
writes, not speech.
## What public state cannot prove
General retries, connection changes, runs, steps, and run hierarchy are
unavailable. Replay fidelity is partial. The adapter does not infer these events
from rendering or private framework state.
## Troubleshooting
* **History is announced:** bind after hydration and keep the thread identity and
`scopeId` stable.
* **Repeated updates:** check that only one binding observes the thread.
* **Missing updates:** verify the public thread state and supported dependency
range before changing announcement policy.
---
# AG-UI accessibility
Map documented AG-UI runs, subagents, partial steps, responses, tools, and interactions into paced accessible workflow updates.
Canonical: https://generativea11y.com/docs/integrations/ag-ui
Markdown: https://generativea11y.com/markdown/docs/integrations/ag-ui
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Install the AG-UI adapter
```shell title="Terminal"
npm install @generative-a11y/core @generative-a11y/dom @generative-a11y/ag-ui
```
```shell title="Terminal"
pnpm add @generative-a11y/core @generative-a11y/dom @generative-a11y/ag-ui
```
```shell title="Terminal"
yarn add @generative-a11y/core @generative-a11y/dom @generative-a11y/ag-ui
```
```shell title="Terminal"
bun add @generative-a11y/core @generative-a11y/dom @generative-a11y/ag-ui
```
Use the agent your app already owns. See [Compatibility](#compatibility) for
supported host dependencies.
## Subscribe to the public agent API
### Create the binding
Add this function to your browser app. It creates a runtime and browser delivery,
then subscribes to your existing agent.
```ts title="accessibility/ag-ui.ts"
import { createRuntime } from "@generative-a11y/core";
import { bindRuntime } from "@generative-a11y/dom";
import { bindAgent, type AgentSource } from "@generative-a11y/ag-ui";
export function connectAccessibility(agent: AgentSource) {
const runtime = createRuntime({});
const delivery = bindRuntime(runtime);
const binding = bindAgent({
runtime,
scopeId: "research-agent",
agent,
});
return () => {
binding.dispose();
delivery.dispose();
runtime.dispose();
};
}
```
### Connect it to your app lifecycle
Call this once when your agent is ready. Here,
`agent` is your existing public AG-UI agent.
```ts title="App mount callback"
import { connectAccessibility } from "./accessibility/ag-ui";
const disconnectAccessibility = connectAccessibility(agent);
```
Keep the binding alive across responses. Call the returned function when the
surface unmounts or before replacing the agent:
```ts title="App unmount callback"
disconnectAccessibility();
```
**Keep one owner for each resource**
The example owns its core runtime and DOM delivery. If your app already has
these, pass that runtime directly to `bindAgent` and clean up only its returned
binding. In React, use the runtime from `A11yProvider` and return
`() => binding.dispose()` from your effect. Do not attach a second delivery
layer to that provider.
Keep `scopeId` stable and unique for each mounted agent. The adapter leaves your
visible UI and actions with the host application.
## Optional configuration
`maxTrackedEntities` defaults to `1000` and bounds adapter identity records.
`copy` supplies localized tool and interaction labels. See the
[`bindAgent` reference](/api/ag-ui/bind-agent) for
all options and the [localization guide](/docs/localized-announcements) for copy
configuration.
## Compatibility
| Dependency | Supported range | Checked version |
| --------------- | ------------------ | --------------- |
| Node.js | 22+ | — |
| `@ag-ui/client` | `>=0.0.59 <0.0.60` | 0.0.59 |
Your existing app supplies the host dependency. The adapter itself needs no
React rendering layer; this example uses core and DOM directly.
## Lifecycle mapping
| Public subscriber evidence | Reports |
| ------------------------------- | ------------------------------------------------- |
| Run and subagent callbacks | Run lifecycle and documented parent relationships |
| Assistant text callbacks | Response text and completion |
| Tool start and result callbacks | Tool lifecycle |
| Interrupt IDs and resume input | Input requests and resolutions |
| Step callbacks | Partial-identity diagnostics only |
Text, tool, and interaction events retain run ownership when exposed. Step
callbacks provide `stepName` without stable step IDs. The adapter keeps the name
as a label and omits `stepId`; core does not create step snapshots,
announcements, or run summary counts from these diagnostics. Same-name
concurrent steps cannot be correlated exactly.
## Expected screen-reader behavior
Core paces response text and prioritizes input requests and failure states. DOM
updates live regions without moving focus during normal agent activity. A DOM
transcript records browser writes; test spoken behavior with real assistive
technology.
## What the protocol can report
Run identity is exact; step and hierarchy fidelity are partial. A top-level
`parentRunId` describes lineage and is not reinterpreted as delegation. Replay
and reconnection fidelity are partial because subscriptions have no mandatory
persistent cursor. Retry and connection event fidelity are unavailable. Custom
events and arbitrary state deltas require an explicit host mapping.
## Troubleshooting
* **Repeated updates:** attach only one subscriber per agent with a stable
`scopeId`.
* **Missing interactions:** check that callbacks contain stable interrupt IDs
and the binding was attached before the run began.
* **Updates stop in a long session:** review `maxTrackedEntities`. The adapter
suppresses further dispatch after capacity is reached; use a new binding at a
real session boundary instead of inferring missing events.
---
# CopilotKit v2
Connect your CopilotKit agent to paced screen-reader updates through the AG-UI adapter.
Canonical: https://generativea11y.com/docs/integrations/copilotkit
Markdown: https://generativea11y.com/markdown/docs/integrations/copilotkit
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Install the accessibility layers
```shell title="Terminal"
npm install @generative-a11y/react @generative-a11y/ag-ui
```
```shell title="Terminal"
pnpm add @generative-a11y/react @generative-a11y/ag-ui
```
```shell title="Terminal"
yarn add @generative-a11y/react @generative-a11y/ag-ui
```
```shell title="Terminal"
bun add @generative-a11y/react @generative-a11y/ag-ui
```
Start with an existing CopilotKit app and its configured provider. The
accessibility bridge uses the public `useAgent` hook from the v2 entry point;
see [Compatibility](#compatibility) for validation limits.
## Use the AG-UI adapter
### Create the bridge
Add this component beside your chat. It gets the accessibility runtime from
`A11yProvider`, waits for the agent, and removes its subscription on unmount.
```tsx title="components/copilotkit-accessibility.tsx"
"use client";
import { useEffect, useId } from "react";
import { useAgent } from "@copilotkit/react-core/v2";
import { bindAgent } from "@generative-a11y/ag-ui";
import { useRuntime } from "@generative-a11y/react";
export function CopilotKitAccessibility({ agentId }: { agentId: string }) {
const runtime = useRuntime();
const bindingScopeId = useId();
const { agent, isReady } = useAgent({ agentId });
useEffect(() => {
if (!isReady) return;
const binding = bindAgent({
agent,
runtime,
scopeId: `copilotkit:${bindingScopeId}`,
});
return () => binding.dispose();
}, [agent, isReady, runtime, bindingScopeId]);
return null;
}
```
### Wrap your existing chat
Render this wrapper inside your existing CopilotKit provider. Pass the configured
agent ID and your existing chat as `children`.
```tsx title="components/accessible-copilot-chat.tsx"
"use client";
import type { ReactNode } from "react";
import { A11yProvider } from "@generative-a11y/react";
import { CopilotKitAccessibility } from "./copilotkit-accessibility";
export function AccessibleCopilotChat({
agentId,
children,
}: {
agentId: string;
children: ReactNode;
}) {
return (
{children}
);
}
```
**One binding per agent**
Keep the wrapper mounted across responses. `A11yProvider` owns the runtime and
browser delivery; the bridge owns only its AG-UI subscription. If your chat
already has an accessibility provider, add just the bridge beneath it.
The bridge renders nothing and preserves your existing visible UI. Routine
streaming updates live regions without moving focus. Confirm speech with your
supported browsers and screen readers; DOM transcripts alone cannot prove it.
## Compatibility
| Dependency | Requirement |
| ----------------- | --------------------------------------------------- |
| Node.js | 22+ |
| React / React DOM | 18.2+ within major 18, or 19.x |
| `@ag-ui/client` | `>=0.0.59 <0.0.60`; adapter checked against 0.0.59 |
| CopilotKit | Public v2 `useAgent` exposing `agent` and `isReady` |
The repository checks the AG-UI adapter, but does not pin or typecheck a
CopilotKit package version. Validate the v2 hook and compatible AG-UI dependency
in your host app. See the [AG-UI lifecycle mapping](/docs/integrations/ag-ui#lifecycle-mapping)
for confirmed events and partial step, hierarchy, and replay support.
## Why there is no CopilotKit package
CopilotKit exposes the agent API the AG-UI adapter already observes. Client tools
that lack protocol IDs need an [explicit host mapping](/docs/integrations/custom);
the adapter cannot identify approvals or tool completion from names alone.
## Troubleshooting
* **No updates:** verify the component is inside both providers, the agent ID
matches your configuration, and `isReady` becomes true before the run starts.
* **Duplicate updates:** remove extra bridges or AG-UI bindings for the same agent.
* **Dependency mismatch:** check the resolved AG-UI client against the supported
range before assuming the CopilotKit integration is compatible.
---
# Custom applications
Connect a custom app by reporting its response, tool, and interaction events directly to generative-a11y.
Canonical: https://generativea11y.com/docs/integrations/custom
Markdown: https://generativea11y.com/markdown/docs/integrations/custom
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Install core and browser delivery
```shell title="Terminal"
npm install @generative-a11y/core @generative-a11y/dom
```
```shell title="Terminal"
pnpm add @generative-a11y/core @generative-a11y/dom
```
```shell title="Terminal"
yarn add @generative-a11y/core @generative-a11y/dom
```
```shell title="Terminal"
bun add @generative-a11y/core @generative-a11y/dom
```
Use this path when your app owns the callbacks that confirm response, tool, or
interaction events.
## Keep translation thin
### Connect browser delivery
Create one runtime for the mounted chat surface and keep it alive across
responses.
```ts title="accessibility.ts"
import { createRuntime } from "@generative-a11y/core";
import { bindRuntime } from "@generative-a11y/dom";
export function createAccessibility() {
const runtime = createRuntime({});
const delivery = bindRuntime(runtime);
return {
runtime,
dispose() {
delivery.dispose();
runtime.dispose();
},
};
}
```
### Report events at the source
Call the factory when your surface mounts, then dispatch from the transport or
application callbacks that confirm each event.
This sequence shows a successful response; replace the sample ID and text with
your app's values, and send only newly added text in each delta.
```ts title="Response lifecycle callbacks"
import { createAccessibility } from "./accessibility";
const accessibility = createAccessibility();
const { runtime } = accessibility;
runtime.dispatch({ type: "response.started", responseId: "response-1" });
runtime.dispatch({
type: "response.text.delta",
responseId: "response-1",
delta: "A complete sentence.",
});
runtime.dispatch({ type: "response.completed", responseId: "response-1" });
```
### Dispose by ownership
Stop your transport subscriptions, then call this when the chat surface unmounts.
Do not dispose after each response: delivery may still have paced output queued.
```ts title="App unmount callback"
accessibility.dispose();
```
## Report interruption and failure
Send exactly the terminal event confirmed by your app. For a cancelled response,
use this instead of `response.completed`:
```ts title="Cancellation callback"
runtime.dispatch({ type: "response.interrupted", responseId: "response-1" });
```
For a failed response:
```ts title="Error callback"
runtime.dispatch({ type: "response.failed", responseId: "response-1" });
```
## Preserve stable IDs
Use response and tool IDs from your app, with a namespace when multiple surfaces
share a runtime. Labels, array positions, and render counts are not stable IDs.
Provide translated user-facing labels when reporting tools or interactions.
See the [event reference](/api/core/events) for their required fields.
## Compatibility and delivery
The packages require Node.js 22+ and have no framework peers. Core works without
a browser; DOM delivery stays inactive when `document` is unavailable. In React,
use [`A11yProvider`](/api/react) to own runtime and browser delivery instead of
calling the factory above.
Your app keeps its visible UI, semantic structure, keyboard controls, and focus
management. Ordinary streaming does not move focus. Browser delivery tests do
not establish what a screen reader speaks.
## Leave out events the framework cannot report
Do not treat streamed arguments as a completed tool, a repeated render as a
retry, a ready state as an interruption, or a tool name as an approval. If the
framework does not report an event, the adapter leaves it out.
---
# Debug AI accessibility with the trace explorer
Inspect bounded, redacted runtime decisions and browser delivery evidence with the optional generative-a11y devtools package.
Canonical: https://generativea11y.com/docs/devtools
Markdown: https://generativea11y.com/markdown/docs/devtools
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Install development-only diagnostics
Install @generative-a11y/devtools in development environments. The package
observes public core diagnostics and does not patch dispatch, change
announcement policy, or depend on an AI framework.
```shell title="Terminal"
npm install --save-dev @generative-a11y/devtools
```
## Open the Accessibility Trace Explorer
Attach your existing `runtime` to a bounded store, then call `mountOverlay` in
the browser. The overlay starts collapsed and provides search, filters, causal
evidence, capture controls, and explicit trace copy.
```typescript title="devtools.ts"
import { createStore } from "@generative-a11y/devtools";
import { mountOverlay } from "@generative-a11y/devtools/overlay";
const store = createStore({ maxEntries: 250 });
const detach = store.attachRuntime({ id: "support", runtime });
const overlay = mountOverlay({ store });
// Call when removing the workbench. The runtime is borrowed.
export function disposeDevtools() {
overlay.dispose();
detach();
store.dispose();
}
```
`maxEntries` caps retained records; the store reports dropped older records. The
`"support"` runtime ID connects decisions and delivery results. The runtime is
borrowed, so its owner disposes it after devtools detaches.
Workflow records expose content-free run and step identity, parent
relationships, attempts, active or terminal state, and associated entity IDs
when the adapter supplies them. The inspector does not infer missing hierarchy.
Retry records connect the replaced and replacement attempt IDs, so causal chains
remain separate across retries and concurrent siblings.
## Captured evidence and redaction
The store retains event categories, outcomes, timing, stable IDs, queue and
entity snapshots, declared adapter evidence, and browser delivery metadata. It
excludes assistant text, labels, errors, tool data, stacks, DOM content,
deduplication keys, and timer handles.
Pass adapter metadata through source only when a documented integration can
support it. Devtools does not detect a framework or invent events that the
framework did not report.
## Correlate runtime decisions with DOM delivery
```ts title="Correlate browser delivery"
import { createRuntime } from "@generative-a11y/core";
import { bindRuntime } from "@generative-a11y/dom";
import { createStore } from "@generative-a11y/devtools";
export const runtime = createRuntime();
export const store = createStore();
const detach = store.attachRuntime({ id: "support", runtime });
const delivery = bindRuntime(runtime, {
onDelivery(result) {
store.recordDelivery({ runtimeId: "support", result });
},
});
// Dispatch your host events through runtime. Keep this binding for the session.
export function disposeChat() {
delivery.dispose();
detach();
store.dispose();
runtime.dispose();
}
```
Send DeliveryResult values from the active binding's onDelivery callback to
store.recordDelivery. Safe announcement and entity IDs connect the browser
action to the runtime decision that requested it.
**Evidence and testing note**
A trace can confirm a runtime decision and a browser API call or live-region
mutation. It cannot prove that assistive technology spoke the announcement.
## Overlay keyboard and focus behavior
Opening the workspace moves focus into it. Escape or the close control collapses
the workspace and restores the element focused before opening. Streaming records
do not move focus, the overlay does not trap focus, and it creates no live
region or global keyboard shortcut.
---
# Deterministic replay testing
Record normalized lifecycle events, replay them through a ManualClock, and assert announcement or diagnostic transcripts with optional Vitest matchers.
Canonical: https://generativea11y.com/docs/testing/replay
Markdown: https://generativea11y.com/markdown/docs/testing/replay
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Use the testing entry from core
Testing helpers ship with @generative-a11y/core. Import the testing entry
only in test code, and install Vitest only when the project uses the semantic
matchers.
```shell title="Terminal"
npm install @generative-a11y/core
npm install --save-dev vitest
```
## Record and replay normalized events
recordRuntime captures only events sent through the dispatch target it returns.
Fixtures use a versioned JSON envelope, relative timestamps, and array order for
events with the same time.
```typescript title="Record and replay a response"
import { ManualClock, createRuntime } from "@generative-a11y/core";
import { recordRuntime, replayEvents } from "@generative-a11y/core/testing";
const clock = new ManualClock(0);
const runtime = createRuntime({ clock });
const recording = recordRuntime({ runtime, clock });
recording.runtime.dispatch({
type: "response.started",
responseId: "report",
});
clock.advanceBy(100);
recording.runtime.dispatch({
type: "response.interrupted",
responseId: "report",
});
const fixture = recording.fixture();
const replayClock = new ManualClock(fixture.startAt);
const replayRuntime = createRuntime({ clock: replayClock });
replayEvents(replayRuntime, replayClock, fixture);
replayClock.runUntilIdle();
runtime.dispose();
replayRuntime.dispose();
```
`recording.runtime` is the dispatch target that captures events; calls sent
directly to the original runtime are not recorded. `runUntilIdle()` settles
delayed output; omit it when asserting an intermediate state. Keep fixture data
under your application’s test-data rules because normalized events can contain
host content.
Run and step events use the same fixture envelope. Preserve their IDs, parent
relationships, and instance IDs to test nested or concurrent work, retry
boundaries, late stale events, and parent completion races deterministically.
## Use semantic Vitest matchers
installVitestMatchers adds transcript, announcement, and diagnostic assertions.
Expected objects use semantic partial fields, which keeps tests focused on the
behavior under review.
```ts title="interruption.test.ts"
import { expect, test } from "vitest";
import { createRecorder } from "@generative-a11y/core";
import { installVitestMatchers } from "@generative-a11y/core/testing";
const accessibilityExpect = installVitestMatchers(expect);
test("announces a confirmed stop", () => {
const recorder = createRecorder();
recorder.runtime.dispatch({ type: "response.started", responseId: "r1" });
recorder.runtime.dispatch({ type: "response.interrupted", responseId: "r1" });
recorder.clock.runUntilIdle();
accessibilityExpect(recorder).toHaveAnnounced({
sourceType: "response.interrupted",
});
recorder.runtime.dispose();
});
```
Use `toHaveAnnouncementTranscript` for ordered output and `toHaveDiagnostic` for
a matching runtime decision. See the [testing reference](/api/core/testing) for
matcher fields and fixture limits.
## Keep the evidence boundary clear
Replay proves that normalized events produce repeatable runtime output under a
controlled clock. It does not prove browser delivery or screen-reader
speech. Keep browser fixtures and hands-on assistive-technology tests as
separate release evidence.
---
# Testing integrations
Test patterns for adapters, runtime behavior, browser delivery, and hands-on screen-reader checks.
Canonical: https://generativea11y.com/docs/testing
Markdown: https://generativea11y.com/markdown/docs/testing
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Test each layer separately
A runtime transcript shows what core prepared. A DOM test shows how the page
changed. Test with a real screen reader to confirm what it speaks.
| Layer | Check | Does not confirm |
| --------------------------- | --------------------------------------------------- | ------------------------------------------- |
| Adapter | Events and stable IDs | Announcements |
| Core | Prepared updates, timing, suppression, cancellation | Browser behavior |
| DOM | Browser results and page updates | Screen-reader speech |
| Browser | Keyboard, landmarks, focus, live regions | Every screen reader and browser combination |
| Hands-on screen-reader test | One user workflow | Behavior in every environment |
## Test every supported browser engine
In a checkout of this repository, browser fixtures run in Chromium, Firefox, and
WebKit. They check keyboard use, stable focus, page landmarks, live regions, and
browser delivery. Run these commands from the repository root:
```shell title="Terminal"
pnpm test:browser:install
pnpm test:browser
```
## Test a realistic app workflow
Fixtures cover streaming text, tool updates, stopping, retrying, and browser
announcements. Each assertion names the behavior it checks.
* Run the same scenarios in all three browser engines.
* Check that streaming and status updates do not move focus.
* Connect each app event to the runtime update and the resulting page change.
* Keep controls and visible status usable without the library.
## Record hands-on screen-reader tests
For each release, record the date, browser, operating system, screen reader and
version, workflow, expected result, actual result, and outcome. Repository
validation checks every required field.
**Evidence and testing note**
One test describes one setup and workflow. It does not guarantee the same result
with every screen reader and browser.
## Use ManualClock for time-dependent behavior
Advance the test clock instead of waiting for real timers. Check diagnostics
when the runtime intentionally skips an update.
```typescript title="streaming.test.ts"
import { expect, test } from "vitest";
import { createRecorder } from "@generative-a11y/core";
test("stopping discards buffered response text", () => {
const recorder = createRecorder({ preset: "balanced" });
recorder.runtime.dispatch({ type: "response.started", responseId: "r1" });
recorder.runtime.dispatch({
type: "response.text.delta",
responseId: "r1",
delta: "Unfinished",
});
recorder.runtime.dispatch({ type: "response.interrupted", responseId: "r1" });
recorder.clock.runUntilIdle();
expect(recorder.transcript().map(({ text }) => text)).toEqual([
"Response stopped.",
]);
recorder.runtime.dispose();
});
```
---
# Troubleshooting
Fix missing, repeated, late, delayed, or noisy announcements by checking each step from the framework event to the browser update.
Canonical: https://generativea11y.com/docs/troubleshooting
Markdown: https://generativea11y.com/markdown/docs/troubleshooting
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Nothing is announced
First check that the runtime receives a started event, new text only, and one
completed, failed, or interrupted event with the same response ID. Then check
runtime diagnostics and the browser result separately.
* Confirm the announcement listener or DOM binding is attached before dispatch.
* Complete a sentence or dispatch response.completed so buffered text can flush.
* Check for policy-silent, empty-text, unknown-response, or
runtime-disposed diagnostics.
* Check `DeliveryResult` for unavailable or disposed delivery.
* If attention filtering is enabled, inspect the effective quiet mode. Text
discarded while quiet has no announcement backlog when normal mode resumes.
* In tests, advance `ManualClock`; even a zero minimum gap schedules delivery.
* A successful page update does not confirm what a screen reader spoke. Test
that separately.
## Output repeats or arrives too often
response.text.delta must contain only the text that just arrived. If you send
the full response every time, earlier text may be announced again.
* Dispatch append-only deltas rather than accumulated message text.
* Keep responseId and responseInstanceId stable for one active attempt.
* Increase text.minimumCharacters or minimumGapMs when valid updates are too
granular.
* Inspect duplicate and coalesced diagnostics before changing policy.
## Old output appears after retry
A retry must replace the active response attempt. Core ignores late updates from
older attempts and reports stale-response diagnostics.
* Send response.retrying with the replaced and next response instance IDs.
* Attach the new responseInstanceId to each later text event and final event.
* Do not reuse a completed or interrupted response instance.
* If the framework does not provide retry IDs, report retry events directly from
your app instead of guessing.
## Tool progress is too noisy
Keep each tool ID stable and use short, translated labels. To reduce noise,
adjust the start delay and progress settings instead of filtering announcements
after they are created.
* Delay tool starts with tools.announceStartAfterMs so fast operations can
finish quietly.
* Raise tools.progressEveryPercent or disable progress announcements.
* Never copy raw arguments, results, or backend errors into user-facing
labels.
## Use diagnostics to find the first problem
Each diagnostic says what the runtime did and why. Start with the first
unexpected result instead of looking only at the final browser update.
| Reason | Meaning | First check |
| -------------------------------- | -------------------------------------------- | ---------------------------------------------------- |
| policy-silent | Active policy suppresses this event | Preset and explicit policy overrides |
| unknown-response or unknown-tool | No active matching identity exists | Started event order and IDs |
| stale-response or stale-tool | Event belongs to a replaced execution | Instance identity propagation |
| progress-threshold | Progress did not cross the configured bucket | progressEveryPercent |
| queue-capacity | Bounded scheduler rejected additional work | Producer rate and maxQueueSize |
| delivery-error | Every announcement listener failed | Listener exceptions and onDeliveryError |
| delivered | Listeners accepted the prepared announcement | Check the DOM result, then test with a screen reader |
## Inspect a redacted trace during development
Use [the devtools trace explorer](/docs/devtools) when a single diagnostic is
not enough to explain the event sequence. Its bounded store connects source
events, runtime decisions, snapshots, and optional DOM delivery results without
retaining response text, labels, tool data, or page content.
* Attach the store to an existing runtime and give that runtime a stable
development ID.
* Forward DeliveryResult values to recordDelivery when you need browser
correlation.
* Pause or clear capture without changing runtime scheduling or browser
delivery.
* Treat the trace as debugging evidence, not proof of screen-reader speech.
---
# Compatibility
Check supported framework ranges, server behavior, and the limits of automated browser coverage.
Canonical: https://generativea11y.com/docs/compatibility
Markdown: https://generativea11y.com/markdown/docs/compatibility
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Tested integration matrix
Use these ranges when choosing an adapter for an existing app. A checked version
is the repository's pinned dependency, not a claim that every version in its
range has been tested.
| Integration | Declared peer range | Checked version |
| ----------------- | ---------------------------------------------------- | --------------- |
| React / React DOM | `^18.2.0` or `^19.0.0` | 19.2.8 |
| AI SDK | `ai >=7.0.0 <7.1.0` / `@ai-sdk/react >=4.0.0 <4.1.0` | 7.0.77 / 4.0.80 |
| assistant-ui | `@assistant-ui/core >=0.3.13 <0.4.0` | 0.3.15 |
| AG-UI | `@ag-ui/client >=0.0.59 <0.0.60` | 0.0.59 |
All published packages require Node.js 22+. Host frameworks can have additional
peers; the [AI SDK guide](/docs/integrations/ai-sdk#compatibility) lists its Zod
requirements. Install instructions in each [integration guide](/docs/integrations)
assume an existing working host app.
[CopilotKit](/docs/integrations/copilotkit) reuses the AG-UI adapter through its
public v2 hook. This repository does not pin or typecheck a CopilotKit host
version; validate its hook and resolved AG-UI dependency in your app. Retest
these ranges when changing framework dependencies.
## Browser and server support
| Layer | Server behavior | Browser behavior |
| -------- | --------------------------------------------- | ---------------------------------------------- |
| Core | Runs without browser globals | Schedules normalized events |
| DOM | Stays inactive when `document` is unavailable | Delivers live-region updates |
| React | Renders stable hidden regions | Connects runtime delivery after hydration |
| Adapters | Imports do not require browser globals | Observe the host state or callbacks you supply |
Keep providers and browser effects within a client boundary in React Server
Components applications. Framework-neutral integrations should attach browser
delivery when their surface mounts and dispose it when that surface unmounts.
## Automated browser tests have limits
| Engine | Automated coverage | Required manual evidence |
| -------- | ---------------------------------------- | ------------------------------------------ |
| Chromium | Keyboard, focus, structure, DOM delivery | Named browser and screen-reader workflow |
| Firefox | Keyboard, focus, structure, DOM delivery | Named browser and screen-reader workflow |
| WebKit | Keyboard, focus, structure, DOM delivery | Safari and platform screen-reader workflow |
**Browser output is not speech evidence**
WebKit provides useful coverage, but it cannot replace Safari testing with a real
screen reader. Browser transcripts record DOM delivery and deterministic tests
record library behavior; neither proves what assistive technology speaks.
Record hands-on browser and screen-reader results separately.
## Development package compatibility
| Entry | Dependency requirement | Purpose |
| ----------------------------------- | ------------------------------------------------------------------- | --------------------------------------- |
| `@generative-a11y/devtools` | Core dependency; package declares React / React DOM `^19.0.0` peers | Headless bounded diagnostic store |
| `@generative-a11y/devtools/overlay` | React / React DOM `^19.0.0` | Browser trace explorer |
| `@generative-a11y/core/testing` | No test-runner peer; pass your Vitest `expect` for matchers | Record, replay, and semantic assertions |
The headless store uses public core contracts. React peers are declared at the
package level, even when importing only the headless entry. The overlay's React
requirement is narrower than the React accessibility provider's range. Testing
helpers accept Vitest structurally and do not add a test-runner dependency to
core.
---
# Stability and migrations
Understand generative-a11y package versions, framework compatibility ranges, deprecation policy, migration notes, and the guarantees available before 1.0.
Canonical: https://generativea11y.com/docs/stability
Markdown: https://generativea11y.com/markdown/docs/stability
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Public packages follow semantic versioning
Published package versions describe the public exports, event contracts, and
documented behavior of that package. Patch releases preserve compatible behavior
and minor releases add compatible capability. Before 1.0, a documented minor
release may include a breaking public API change; after 1.0, breaking public API
changes require a major release.
Internal implementation details, private framework state, and undocumented deep
imports are not compatibility surfaces.
## Adapter stability includes peer ranges
Framework adapters are supported only with the versions listed in their peer
dependency ranges. A new framework version can change the public events an
adapter receives even when generative-a11y has not changed.
* Review the [compatibility matrix](/docs/compatibility) before upgrading a
framework peer.
* Pin framework versions when your app depends on exact adapter behavior.
* Send core events directly when a framework does not report an event your app
needs.
## Package contracts are checked before publication
Release validation inspects package exports, declaration files,
provenance-ready metadata, packed contents, dependency boundaries, and
installability. Public entry points must resolve from the package users install.
* Every exported API has tests and documentation.
* Package manifests expose only supported public entry points.
* Packed artifacts are inspected instead of trusting the source tree.
* Framework adapters stay within their declared peer ranges.
## Each release check answers a different question
A release runs code checks, browser tests, package validation, and a validator
for hands-on screen-reader test records. Passing one check does not
replace the others.
| Check | What it covers | Limit |
| ------------------------- | ------------------------------------------- | ------------------------------- |
| Repository check | Types, builds, unit behavior, rendered docs | Code and runtime behavior |
| Browser matrix | Keyboard, focus, semantics, page updates | Browser behavior only |
| Package validation | Exports, tarballs, installability | Files received by package users |
| Screen-reader test record | A dated, hands-on workflow | One named setup |
## Migration checklist
Upgrade one package area at a time. Check runtime output first, then test in
browsers and with the screen readers you support.
* Read the package release notes and peer dependency changes.
* Update one generative-a11y package family to a consistent version set.
* Run type checking and adapter translation tests.
* Compare diagnostics for suppression, cancellation, and delivery changes.
* Exercise stop, retry, tool failure, and approval workflows in a browser.
* Repeat the application's documented assistive-technology smoke test.
## Deprecations remain documented
When an API is deprecated, its replacement and migration path remain documented
until removal. This pre-1.0 naming update makes direct breaking replacements
without a deprecation period. Release notes identify changed defaults, event
semantics, ownership rules, and peer dependency ranges.
## Public API naming update
This release replaces the earlier API names directly. There are no deprecated
aliases. Update imports, type annotations, and runtime configuration together.
The package provides context: `createRuntime` creates a core runtime,
`createAnnouncer` creates browser delivery, and `A11yProvider` owns the React
integration. Lifecycle event names and accessibility behavior are unchanged.
| Previous API | Current API |
| -------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
| `createGenerativeA11y` | `createRuntime` |
| `GenerativeA11yRuntime`, `GenerativeA11yOptions`, `GenerativeA11yEvent` | `Runtime`, `RuntimeOptions`, `RuntimeEvent` |
| `englishAnnouncementCatalog` from core | `en` from `@generative-a11y/core/messages` |
| `AnnouncementCatalog` | `Messages` from `core/messages` |
| `AnnouncementMessages`, `AnnouncementMessageParameters`, `AnnouncementMessageId` | `MessageMap`, `MessageParams`, `MessageKey` from `core/messages` |
| `AdapterAnnouncementCopy`, `normalizeAdapterAnnouncementCopy` | `AdapterCopy`, `normalizeAdapterCopy` from `core/messages` |
| `announcementCatalog` runtime/provider option | `messages` |
| `GenerativeA11yProvider` | `A11yProvider` |
| `useGenerativeA11y`, `useGenerativeA11yRuntime` | `useA11y`, `useRuntime` |
| `useGenerativeA11yAttention`, `useGenerativeA11yAttentionControl` | `useAttention`, `useAttentionControl` |
| `useGenerativeA11yPreferences`, `useGenerativeA11yBindings` | `usePreferences`, `useAttentionRefs` |
| `createDOMAnnouncer`, `connectRuntimeToDOM`, `bindAttentionToRuntime` | `createAnnouncer`, `bindRuntime`, `bindAttention` |
| `GenerativeA11yExpect`, `GenerativeA11yMatchers` | `A11yExpect`, `A11yMatchers` from `core/testing` |
| `createAnnouncementRecorder`, `createAnnouncementScheduler` | `createRecorder`, `createScheduler` |
| AI SDK `createObserver` | `createChatObserver` |
| assistant-ui `bindThreadRuntime` | `bindThread` |
| devtools `createDevtoolsStore`, `mountDevtoolsOverlay` | `createStore`, `mountOverlay` |
Associated types follow the same names: `A11yProviderProps`, `AnnouncerOptions`,
`Announcer`, `RuntimeBinding`, `SchedulerOptions`, `ChatObserverOptions`,
`BindThreadOptions`, `StoreOptions`, and `OverlayOptions`. The diagnostic
snapshot's `announcementCatalog` field is now `messages`; its content-free
`{ catalogId, locale }` value is unchanged.
English is the default. Import messages only when customizing the copy:
```ts title="Default runtime"
import { createRuntime } from "@generative-a11y/core";
const runtime = createRuntime();
```
```ts title="Custom English notices"
import { createRuntime } from "@generative-a11y/core";
import { en, type Messages } from "@generative-a11y/core/messages";
const messages = {
...en,
id: "my-app.en.v1",
messages: {
...en.messages,
"response.completed": "Your answer is ready.",
},
} satisfies Messages;
const runtime = createRuntime({ messages });
```
`Messages` is the complete configuration with an ID, locale and message map. A
different language supplies every message; use your existing translation system
inside the typed formatters. See
[localized announcements](/docs/localized-announcements).
### Additional type replacements
| Previous type | Current type |
| -------------------------------------- | ----------------------------------------------------------------- |
| `GenerativeA11yProviderProps` | `A11yProviderProps` |
| `GenerativeA11yContextValue` | `A11yContextValue` |
| `GenerativeA11yDOMOptions` | `DeliveryOptions` |
| `GenerativeA11yAttentionControlResult` | `AttentionControl` |
| `GenerativeA11yPreferencesResult` | `PreferencesResult` |
| `GenerativeA11yComposerProps` | `AttentionRefs["composerRef"]` (callback ref, not a props object) |
| `GenerativeA11yConversationProps` | `AttentionRefs["conversationRef"]` |
| `GenerativeA11yNewestResponseProps` | `AttentionRefs["newestResponseRef"]` |
| `GenerativeA11yBindings` | `AttentionRefs` |
| `DOMAnnouncer` | `Announcer` |
| `DOMAnnouncerOptions` | `AnnouncerOptions` |
| `DOMAnnouncementMode` | `DeliveryMode` |
| `DOMLiveRegions` | `LiveRegions` |
| `DOMDeliveryResult` | `DeliveryResult` |
| `DOMRuntimeBinding` | `RuntimeBinding` |
| `AttentionRuntimeBindingOptions` | `AttentionBindingOptions` |
| `AttentionRuntimeBinding` | `AttentionBinding` |
| `AnnouncementRecorder` | `Recorder` |
| `AnnouncementScheduler` | `Scheduler` |
| `AnnouncementSchedulerOptions` | `SchedulerOptions` |
| `CreateObserverOptions` | `ChatObserverOptions` |
| `BindThreadRuntimeOptions` | `BindThreadOptions` |
| `DevtoolsStoreOptions` | `StoreOptions` |
| `DevtoolsStore` | `Store` |
| `MountDevtoolsOverlayOptions` | `OverlayOptions` |
| `MountedDevtoolsOverlay` | `Overlay` |
### Integration clarity changes
* Provider `dom` is now `delivery`; its browser callback is `onDelivery`. Core
and preference-store `onDiagnostic` callbacks retain their separate meaning.
* `useBindings` becomes `useAttentionRefs`, returning `composerRef`,
`conversationRef`, and `newestResponseRef` directly. Use `ref={composerRef}`;
these refs observe attention and add no semantic props. The former props types
are removed; `AttentionRefs` describes the callbacks for host HTMLElements.
* Each adapter exports `adapterInfo` and `AdapterInfo` instead of
`CHAT_ADAPTER_METADATA`/`ChatAdapterMetadata`,
`THREAD_ADAPTER_METADATA`/`ThreadAdapterMetadata`, or
`AGENT_ADAPTER_METADATA`/`AgentAdapterMetadata`.
* Requested delivery mode `aria-notify` is removed because it behaved exactly
like `auto`. Use `auto` for notification with fallback, or `live-region` to
choose that path. The observed result method can still be `aria-notify`.
* Configuration errors name the invalid field or missing documented message key
without including supplied values.
See the [API reference](/api) for the updated imports, options, and usage
examples.
---
# Limitations and honest claims
Understand what the library can confirm, what it cannot see, and what still needs hands-on screen-reader testing.
Canonical: https://generativea11y.com/docs/limitations
Markdown: https://generativea11y.com/markdown/docs/limitations
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## What automated tests prove
Core tests check which updates the runtime prepares and when. Adapter tests
check how framework events are translated. DOM and browser tests check page
structure and updates. None can confirm what a specific screen reader spoke or
what a person heard.
**Evidence and testing note**
Test with real browsers and screen readers before release.
### What core tests check
Core tests run the framework-independent runtime in isolation and record
everything it prepares. A test dispatches standard lifecycle events, advances a
manually controlled clock, and reads back the resulting announcement intents.
This confirms the scheduling policy behaves deterministically: text is
segmented the same way, repeats are removed the same way, and intents are
emitted in the same order, every run.
The recorder and replay fixtures in `@generative-a11y/core/testing` make this
concrete. A recorded session captures each dispatched event with its timestamp,
and a replay fixture re-runs those events to assert the same intents come
out. Semantic assertions check meaning, not just strings: for example, that an
interruption cancels pending announcements, or that a failed tool call
produces a failure intent on the assertive channel. These tests prove the
runtime's decisions are correct and repeatable. They say nothing about what
any assistive technology did with the result.
### What DOM and browser tests check
DOM tests check that announcement intents are translated into the right page
updates: the correct live-region structure, the correct text content, and
the correct delivery calls to browser APIs. Browser tests run through
Playwright against real browser engines and confirm the page behaves as
expected when intents arrive, including focus behavior and preference handling.
This is where the honesty boundary matters most. A passing browser test proves
the announcement was added to the page and that the browser reported delivery.
It does not prove a screen reader spoke it, spoke it in full, spoke it at the
right time, or that a person understood it. Browser delivery is not
screen-reader output. Keep that distinction in every test name,
assertion message, and report you write.
### What no automated test can check
Some questions only a person with assistive technology can answer:
* What did the screen reader actually speak, and was anything dropped,
reordered, or interrupted?
* Did the pacing feel right, or did announcements arrive too fast to follow?
* Did the person understand the update in context, or was it noise?
* Did focus behave correctly while announcements were delivered?
* How did a specific browser and screen-reader combination behave,
including versions and settings you did not test against?
Automated tests are strong evidence about your code. Manual testing is the
only evidence about the user's experience. Both are required before release.
## The core honesty rule
Never claim that an automated transcript or page update proves what a screen
reader spoke. This is the single most important rule in this project, and it
applies to code comments, test names, documentation, changelogs, and
marketing copy.
It helps to state claims in terms of what each layer can actually confirm:
| What you can say | What you cannot say |
| ------------------------------------------------------- | ------------------------------------------ |
| The runtime prepared an announcement intent | The screen reader spoke the announcement |
| The intent was emitted at a specific policy-driven time | The user heard it at that moment |
| DOM delivery added the text to the page | The screen reader announced the added text |
| The browser reported a delivery result | The person understood what was announced |
| A replay fixture reproduces the same intents | Real usage will sound identical |
When you write a test, name the assertion after the layer you are testing.
"Emits a completion intent when the response completes" is honest.
"Announces the completion to the screen reader" is not.
## Unsupported by design
generative-a11y does not replace semantic HTML, keyboard support, focus
management, visible status messages, or dialogs. It cannot read private
framework state, run remote code, guarantee screen-reader speech, or guess
missing events from page text.
Put more plainly, this library is a pacing and delivery layer for confirmed
app events. It is not:
* A screen-reader simulator. Nothing in the library approximates what NVDA,
VoiceOver, JAWS, or TalkBack will speak.
* An accessibility audit. It does not scan your interface, score it, or find
violations.
* A WCAG conformance claim. Using this library does not make an interface
conformant, and no output of the library should be cited as conformance
evidence.
* A replacement for accessible design. If the underlying interface is not
keyboard-operable, focus-managed, and semantically structured, paced
announcements cannot fix it.
* A way to observe users. The attention model tracks coarse, explicitly
reported evidence such as foreground or background state; it never proves
attention, intent, or reading.
### Integration evidence limits
Adapters translate documented public framework state into normalized events.
When a framework does not expose reliable evidence for a lifecycle event, the
adapter declares reduced fidelity instead of inferring the event or depending
on a private API. These are the current known limits:
| Integration | Evidence limit |
| ----------------------------------------------- | ------------------------------------------------------------------------- |
| [assistant-ui](/docs/integrations/assistant-ui) | No general retry or connection event |
| [AI SDK](/docs/integrations/ai-sdk) | The host must report retries that public framework state cannot establish |
| [AG-UI](/docs/integrations/ag-ui) | No replay deduplication without a mandatory cursor |
| [CopilotKit](/docs/integrations/copilotkit) | Uses the supported AG-UI path; there is no duplicate adapter package |
These limits are documented per integration guide. If a framework later
exposes the missing evidence through a stable public API, the adapter can be
updated and the limit removed. Until then, the honest behavior is to say less,
not to guess more.
## Reporting what you observe
Manual findings are a first-class contribution. If you test with a real
screen reader and find behavior worth reporting, use the dedicated
[assistive-technology report](https://github.com/bhaveshchow20/generative-a11y/issues/new?template=assistive_technology_report.yml)
issue template. Positive results are welcome too: confirmed announcements
that sounded right in a specific browser and screen-reader combination
help everyone calibrate expectations.
When reporting, describe what you observed, not what you inferred. "NVDA
2026.x spoke the completion announcement after the response finished" is a
useful observation. "The library correctly announced the completion" assumes
the conclusion. Include the browser, screen reader, versions, and the
announcement policy in use so others can reproduce the conditions.
## Experimental and planned work
Some integrations or behaviors are explicitly experimental: they depend on
public framework state that is documented but unstable or incomplete. An
experimental label means the adapter may behave differently across framework
versions and that its evidence limits should be read carefully before
depending on it in production.
Planned work follows the same honesty rules as shipped work. A roadmap item
describes what will be attempted and what evidence it will rely on; it is
not a promise that the evidence will turn out to be available. If the
evidence does not materialize, the plan changes or the feature ships with
declared reduced fidelity. See [contributing](/docs/project/contributing)
for how to propose and document such work.
## What the policy cannot know
The announcement policy is a set of heuristics, not a model of the user.
Numbers like the 2,500 ms maximum text delay, the 2,000 ms dedupe window,
or the 100 ms minimum gap between announcements were chosen to keep speech
output paced and non-repetitive. They do not guarantee that any
particular person can follow the announcements, that the pacing suits
everyone, or that a faster or slower stream would not work better for a
given user. Treat policy defaults as a reasonable starting point that your
own manual testing should validate or adjust.
The same applies to text segmentation. Splitting streamed text into
sentences produces speakable units, but sentence boundaries in generated
text are not always clean: abbreviations, code, lists, and mixed languages
can all segment awkwardly. The segmenter is deterministic, which makes it
testable, but determinism is not correctness for every input. If your
content has unusual structure, test how it sounds before assuming the
policy handles it well.
The announcement catalog is localizable, and messages carry an optional
locale, but the library cannot know whether the locale it was given matches
the language the user actually hears, or whether the screen reader will
pronounce the text correctly. Report the locale you set; do not claim the
user heard the right language.
## Where the library stops and your app starts
generative-a11y handles paced announcements for confirmed lifecycle
events. Everything else in the accessible experience stays with the host
application, and no announcement layer can compensate for its absence:
* **Semantic HTML.** Live regions announce text, but the interface itself
must be structured: headings, landmarks, lists, and native controls.
* **Keyboard support.** Every action a mouse user can take must be
reachable and operable by keyboard, with a visible focus indicator.
* **Focus management.** Dialogs, navigation, and task completion must move
and restore focus deliberately. The library never moves focus during
streaming, which means the host owns every focus decision.
* **Visible status messages.** Some users do not use a screen reader.
Status that matters should be visible on the page, not only announced.
* **Error recovery.** When something fails, the user needs a way to
understand what happened and what to do next, in the interface itself.
If any of these are missing, adding this library will not make the
interface accessible. Fix the foundation first, then add paced
announcements on top of confirmed events.
---
# Project overview
See what each generative-a11y package does and how the project keeps integrations small and reliable.
Canonical: https://generativea11y.com/docs/project/overview
Markdown: https://generativea11y.com/markdown/docs/project/overview
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## A focused package family
Each package has one job: decide what to announce, update the browser, connect
React, or connect an AI framework. Install only what your app needs.
| Package | Purpose | Boundary |
| ------------ | ----------------------------------------------------- | ----------------------------------------- |
| core | Policy, scheduling, segmentation, and testing helpers | No DOM or framework dependency |
| dom | Browser delivery, focus, attention, preferences | No React or AI framework dependency |
| react | Provider and host-element bindings | Leaves the visual interface unchanged |
| ai-sdk | useChat lifecycle translation | Public state and callbacks only |
| assistant-ui | Thread runtime translation | getState and subscribe only |
| ag-ui | Protocol lifecycle translation | Documented subscriber callbacks only |
| devtools | Bounded redacted diagnostics and a trace explorer | No application content or runtime control |
## Test each part at the right level
Runtime, adapter, browser, and hands-on screen-reader tests answer
different questions. Keeping them separate prevents anyone from mistaking an
automated transcript for what a person heard.
Maintained by [Bhavesh Chowdhury](https://github.com/bhaveshchow20).
## Read documentation from tools
Use **Copy Markdown** below a guide or API page description to copy its content.
The **Open** dropdown links to Markdown, the GitHub source, and external AI
tools.
Start with [/llms.txt](/llms.txt) for guide and API Markdown links. Each export
includes its canonical HTML URL and source checkout context. For example,
[/markdown/docs/integrations/ai-sdk](/markdown/docs/integrations/ai-sdk) exports
the AI SDK recipe, and [/markdown/api/core](/markdown/api/core) includes
generated public declarations. Prefix any canonical `/docs/...` or `/api/...`
path with `/markdown`; the API landing page is `/markdown/api`. Unknown pages
return 404.
```shell title="Terminal"
curl -fsS https://generativea11y.com/llms.txt
curl -fsS https://generativea11y.com/markdown/docs/integrations/ai-sdk
npm view @generative-a11y/ai-sdk version peerDependencies --json
```
These docs track source, which can contain APIs awaiting publication even when
package manifest versions match npm. Check
[stability and migrations](/docs/stability) and the release tag for your
installed version. The
[typechecked consumer journeys](https://github.com/bhaveshchow20/generative-a11y/tree/main/examples/consumer-journeys)
provide fuller integration examples for the source checkout.
Prefer individual pages. For offline retrieval, use
[/llms-docs.txt](/llms-docs.txt) for guides, [/llms-api.txt](/llms-api.txt) for
references, or [/llms-full.txt](/llms-full.txt) for both. All share the same
compiled content; Markdown exports retain code and replace custom reference
components with text. HTML URLs continue to return HTML regardless of the
`Accept` header.
The existing [search endpoint](/api/search?query=useChatAccessibility) returns
Fumadocs search JSON with page and section URLs. Its response follows the
installed Fumadocs UI contract, with no package-version filter. Fetch the
matching page's Markdown URL for the full context; a search excerpt alone is not
an integration contract. These retrieval formats do not guarantee model
discovery or correct integration, and deterministic tests do not prove real
screen-reader behavior.
---
# Contributing
Contribute focused changes with tests, clear documentation, stable events, and clean package responsibilities.
Canonical: https://generativea11y.com/docs/project/contributing
Markdown: https://generativea11y.com/markdown/docs/project/contributing
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Development workflow
From a repository checkout, use the Node version in `.nvmrc` and install the
locked dependencies. Add tests and documentation for exported behavior, then run
repository and browser checks before requesting review.
```shell title="Terminal"
corepack enable
pnpm install --frozen-lockfile
pnpm check
pnpm test:browser:install
pnpm test:browser
```
### Walkthrough
#### Enable the package manager
The repository pins Node 24 in `.nvmrc` and pnpm 11.21.0 through
Corepack. Enable Corepack first so the pinned pnpm version is used; the
engines field also requires Node 22 or newer, but the `.nvmrc` version is
what CI and maintainers test against.
```shell title="Terminal"
nvm use
corepack enable
```
#### Install dependencies
Install the locked dependency tree exactly as committed. The frozen
lockfile flag fails instead of updating the lockfile, which keeps every
contributor and CI run on identical dependencies.
```shell title="Terminal"
pnpm install --frozen-lockfile
```
#### Run repository checks
`pnpm check` is the full gate. It runs, in order:
| Step | Command | What it covers |
| -------- | --------------------- | ------------------------------------------------------ |
| Format | `pnpm format:check` | Prettier formatting across the repo |
| Lint | `pnpm lint` | ESLint with zero warnings allowed, plus docs lint |
| Types | `pnpm typecheck` | Package typechecks, browser test types, consumer types |
| Coverage | `pnpm test:coverage` | Vitest with coverage, plus docs unit tests |
| Build | `pnpm build` | Builds every package |
| Package | `pnpm package:check` | Package metadata, publint, and the package smoke test |
| Examples | Example workflow test | Runs the hierarchical-workflow example test suite |
| Docs | Docs test | Runs the docs app test suite |
Fix failures in order: a formatting or type error will usually cascade, so
get the early steps green before investigating test failures. If you change
formatting, run `pnpm format` to write the fixes rather than editing by
hand.
#### Install browser engines
Browser tests run against real engines through Playwright. Install them
once per machine:
```shell title="Terminal"
pnpm test:browser:install
```
This installs Chromium, Firefox, and WebKit. It downloads several hundred
megabytes, so plan for that on a fresh machine.
#### Run browser checks
```shell title="Terminal"
pnpm test:browser
```
This builds the packages, runs the Playwright suite, and then runs the
docs app browser tests. Browser tests confirm DOM delivery behavior in
real engines, but remember the honesty rule from
[limitations](/docs/limitations): a passing browser test proves the
announcement reached the page, not what any screen reader spoke.
## Ways to contribute
Contributions are not limited to runtime code. Especially useful work
includes:
* Testing real interactions with screen readers and other assistive
technology, reported through the assistive-technology report issue
template.
* Reducing a framework lifecycle into a documented, reproducible event
trace that an adapter can translate.
* Improving examples, API documentation, or accessibility guidance.
* Reporting missing or ambiguous public lifecycle evidence in an AI
framework, so adapters can document reduced fidelity accurately.
* Implementing focused core behavior with deterministic tests, using the
injected clock and replay fixtures rather than real timers.
## Before opening a pull request
1. Open or find an issue for substantial changes so the problem and the
proposed API can be discussed first. Small fixes and documentation
improvements can go straight to a pull request.
2. Fork the repository and create a focused branch. One branch, one
concern: a focused branch is easier to review and easier to revert.
3. Install Node.js using `.nvmrc`, enable Corepack, then run
`pnpm install --frozen-lockfile`, as described in the walkthrough
above.
4. Make the change with tests and documentation where appropriate. Every
exported API requires both.
5. Run `pnpm changeset` for a user-visible package change, so the
release notes describe it accurately. See the changesets section below.
6. Run `pnpm check` before opening the pull request, and make sure the
full gate passes locally.
Adapters must rely on documented public framework state. If exact
lifecycle evidence is unavailable, document the reduced fidelity rather
than inferring the event or depending on a private API.
### Changesets
Add a changeset for user-visible published-package changes. The
changeset records which packages are affected, the semver bump type, and
a short description that becomes the release note. Internal refactors,
test-only changes, and documentation fixes that do not change
published behavior do not need one.
```shell title="Terminal"
pnpm changeset
```
Follow the prompts: select the affected `@generative-a11y/*` packages,
choose patch, minor, or major, and write the summary in plain language
describing what changed for the user.
## Accessibility expectations
Changes should describe the user need they address and how the behavior
was tested. When relevant, include keyboard-only and
assistive-technology testing details: which screen reader and browser
you used, their versions, and what you observed. Automated checks support
review but do not replace manual accessibility testing.
If your change affects announcement timing, wording, or policy defaults,
say so explicitly in the pull request and include the evidence you used
to choose the new behavior. Never claim that an automated transcript or
page update proves what a screen reader spoke; report what the code does
and what you observed manually, separately.
## Testing guidance
Every exported API requires tests, and core tests must be deterministic.
The rules that make this possible are architectural, so follow them when
you write tests:
* **Inject time, do not wait for it.** Core scheduling logic takes a clock
through the `SystemClock` abstraction. In tests, use `ManualClock` from
`@generative-a11y/core` to advance time explicitly. Core code must not
call global timers directly, and neither should your tests.
* **Record and replay.** Use the recorder in
`@generative-a11y/core/testing` to capture dispatched events with
timestamps, then replay the fixture and assert the same announcement
intents come out. Prefer semantic assertions over string matching: assert
that an interruption cancels pending intents, not the exact wording of
every intent.
* **Keep queues and timers owned.** Every timer your code creates must be
cancelled on terminal events and on `dispose()`. Write a test that
disposes the runtime and asserts nothing fires afterward.
* **Run the fast suite often.** `pnpm test` runs Vitest once;
`pnpm test:watch` keeps it running during development. `pnpm
test:coverage` is the gate version used by `pnpm check`.
* **Run browser tests for DOM changes.** Anything touching
`@generative-a11y/dom` should also pass `pnpm test:browser` after
`pnpm test:browser:install`. These run against real Chromium, Firefox,
and WebKit engines through Playwright.
Name test assertions after the layer under test. "Prepares a failure
intent on the assertive channel when the tool fails" describes runtime
behavior. "Announces the failure to the screen reader" claims something
no automated test can prove.
## Documentation changes
Docs live in `apps/docs/content/docs/` as MDX files. When you change
exported behavior, update the docs in the same pull request. Follow the
conventions the existing pages use:
* **Frontmatter and metadata stay in sync.** `title`, `description`,
`publicPath`, `section`, `keywords`, `related`, and `order` in the
frontmatter must match the `sourceMetadata` export exactly.
* **`searchableText` stays current.** The export must remain non-empty
and should reflect the page's headings and key sentences, so updates to
the body mean updates to the searchable text.
* **Keep anchors stable.** Existing anchor elements (`span` tags carrying an
`id` attribute) are link targets; do not rename or remove them. Add new
anchors when you add sections that deserve deep links.
* **Use only the components already in use.** Pages use a small set of MDX
components such as `Callout`; do not introduce new ones or add imports
the page does not already have.
* **Match the voice.** Docs are concise, honest, and evidence-focused.
State what each layer can confirm, cite the evidence limits, and never
let a test result read as a claim about what a person heard.
The docs app has its own test suite, run as part of `pnpm check`, which
validates metadata consistency and page structure. If you add a page,
give it a `publicPath`, `section`, and `order` that fit the existing
navigation.
## Security reports
Security reports follow [SECURITY.md](https://github.com/bhaveshchow20/generative-a11y/blob/main/SECURITY.md)
rather than public issues. Do not open a public issue for a suspected
vulnerability. Use GitHub's private vulnerability reporting, and include
the affected version or commit, reproduction steps, impact, and any known
mitigations. The project is pre-release, so security fixes are made on
the latest version only. Reports are acknowledged as soon as practical,
and disclosure is coordinated after a fix is available.
## Review expectations
Keep core independent of browsers, DOM independent of React and AI frameworks,
and adapters small. Never claim that an automated transcript or page update
proves what a screen reader spoke.
* Every exported API requires tests and documentation.
* Every owned timer and subscription must be disposed.
* All queues and tracked identities remain bounded.
* Security reports follow SECURITY.md rather than public issues.
Reviewers will check the architectural boundaries first: does core import
anything browser-specific? Does an adapter depend on a private
framework API instead of documented public state? Does scheduling logic
call a global timer instead of the injected clock? A change that breaks
these boundaries will be asked to restructure, even if its tests pass.
Expect feedback on API surface as well. Public events and policies are
serializable by design, so a new event field or policy option should stay
serializable where practical and be covered by deterministic tests. Keep
the change focused: one pull request, one concern, with tests and
documentation for the exported behavior it adds or changes.
## Pull requests
Keep pull requests focused and explain the reason for the change. Describe
the user need, link the issue for substantial changes, and summarize how
the behavior was tested, including any manual assistive-technology
testing. CI must pass, and maintainers may request API, test, or
documentation updates before merging.
By participating, you agree to follow the
[Code of Conduct](https://github.com/bhaveshchow20/generative-a11y/blob/main/CODE_OF_CONDUCT.md).
---
# API reference
Find public APIs for runtimes, browser delivery, React, adapters, and testing.
Canonical: https://generativea11y.com/api
Markdown: https://generativea11y.com/markdown/api
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Choose the packages and entries you need
Start with core. Add DOM or React for browser updates, then add a framework
adapter if your app uses that framework.
| Package or entry | Primary exports | Use for |
| --- | --- | --- |
| [@generative-a11y/core](/api/core) | createRuntime, events, policy, scheduler | Framework-independent policy |
| [@generative-a11y/dom](/api/dom) | announcer, runtime binding, focus, attention, preferences | Browser updates and helpers |
| [@generative-a11y/react](/api/react) | provider and hooks | React setup and element bindings |
| [@generative-a11y/ai-sdk](/api/ai-sdk) | observer, callbacks, React hooks | AI SDK useChat public state |
| [@generative-a11y/assistant-ui](/api/assistant-ui) | bindThread | assistant-ui ThreadRuntime |
| [@generative-a11y/ag-ui](/api/ag-ui) | bindAgent | AG-UI AgentSubscriber callbacks |
| [@generative-a11y/devtools](/api/devtools) | createStore, overlay | Bounded redacted development traces |
| [@generative-a11y/core/testing](/api/core/testing) | recordRuntime, replayEvents, matchers | Deterministic lifecycle tests |
## How to read this reference
Package pages list their exports; symbol pages show usage, options, defaults,
and cleanup. Generated declarations provide the complete public type contracts.
Follow the integration guides for installation and host framework setup.
* Method return values describe behavior the library can confirm.
* Cleanup notes list the timers, subscriptions, DOM nodes, or framework objects
released by dispose().
* Test notes separate runtime and browser results from hands-on
screen-reader tests.
## Install at a glance
Install core first, then add the packages your host needs. Framework adapters
depend on core; the DOM and React packages deliver announcements to the browser.
```shell title="Terminal"
npm install @generative-a11y/core
```
Add browser delivery:
```shell title="Terminal"
npm install @generative-a11y/core @generative-a11y/dom
```
Add React integration, which depends on core and DOM:
```shell title="Terminal"
npm install @generative-a11y/react
```
Add one or more framework adapters for the host you already use:
```shell title="Terminal"
npm install @generative-a11y/ai-sdk
npm install @generative-a11y/assistant-ui
npm install @generative-a11y/ag-ui
```
Add diagnostics only while developing:
```shell title="Terminal"
npm install --save-dev @generative-a11y/devtools
```
Peer requirements live on each package page: the React package supports React
18.2 and 19, the AI SDK adapter targets `ai@7.0.x` and `@ai-sdk/react@4.0.x`,
and the assistant-ui adapter observes `@assistant-ui/core@0.3.x`.
## What each package owns
Each package owns one layer and borrows the rest. Knowing the ownership
boundary tells you which package to reach for and which one to dispose.
**@generative-a11y/core** is the framework-independent accessibility
runtime. It turns streaming AI and agent lifecycle events into paced
screen-reader announcements. Your app dispatches `RuntimeEvent` objects;
core applies policy, schedules prepared output through a bounded queue with an
injected clock, and emits `AnnouncementIntent` objects when there is something
useful to announce. Core never touches the DOM and never claims assistive
technology spoke anything. Use it directly in any JavaScript runtime, including
tests without a document. Backend `error` fields are diagnostic-only; use
an event's `announcement` field for short, localized, user-safe spoken
error copy.
**@generative-a11y/dom** delivers core announcements to the browser. It
mounts or adopts live regions without changing the host application's visible
interface. `bindRuntime(runtime, options?)` creates an `Announcer`, subscribes
it to a runtime, and returns a `RuntimeBinding` that exposes the connected
announcer and an idempotent `dispose()` method. Disposing the binding
unsubscribes and disposes the announcer but never disposes the borrowed
runtime. It reports DOM delivery actions; it does not claim assistive
technology produced speech.
**@generative-a11y/react** adds React lifecycle integration on top of core
and DOM. Wrap the existing application in `A11yProvider` to supply runtime and
delivery ownership, then dispatch normalized public core events from the host's
existing lifecycle. The provider's only rendered infrastructure is one visually
hidden polite region and one visually hidden assertive region. It does not
replace or style the host application's chat, messages, composer, controls, or
preference UI.
**@generative-a11y/ai-sdk** is the Vercel AI SDK accessibility adapter.
It observes host-owned public state from `ai@7.0.x` and
`@ai-sdk/react@4.0.x` and dispatches to a borrowed core runtime. The root entry
is SSR-safe; the React integration lives at
`@generative-a11y/ai-sdk/react` with hooks such as `useChatAccessibility` and
`useObserveChatAccessibility`. It does not render UI, read the DOM, own a chat,
invoke `regenerate()`, or inspect private chat state.
**@generative-a11y/assistant-ui** observes only the documented public
`ThreadRuntime` `getState()` and `subscribe()` methods from
`@assistant-ui/core@0.3.x`. `bindThread()` silently baselines existing history
and translates later assistant text and documented terminal statuses, tool
result state, approvals, and sources into a borrowed generative-a11y
runtime. It does not render UI, access the DOM, or call host runtime actions.
Text is emitted only for append-only changes; a rewrite, an unknown
incomplete reason, or an observer that reaches its bounded identity capacity
fails closed. The documented thread snapshot does not expose stable run, step,
or hierarchy identity, so those lifecycle dimensions stay unavailable.
**@generative-a11y/ag-ui** observes an `AbstractAgent` only through its
documented `agent.subscribe(AgentSubscriber)` callbacks. `bindAgent()` translates
the agent's public subscription events, including run and subagent run
lifecycle, partial step lifecycle, assistant text messages, tool calls, and
interaction requests, into a borrowed core runtime. It does not subscribe to the
protocol observable, mutate agent state, render UI, or invoke agent actions.
Step events expose only `stepName`, so the adapter deliberately omits `stepId`:
names never become identity. Custom events and arbitrary state deltas are
ignored.
**@generative-a11y/devtools** is the development-only diagnostics
layer. The default headless store is framework-neutral, side-effect-free
on import, and retains a bounded redacted trace: categories, timing, outcomes,
stable runtime IDs, queue and entity snapshots, and browser delivery metadata.
It never retains assistant text, labels, error messages, tool data, stacks, or
DOM content. Attach a runtime with `store.attachRuntime()`, subscribe a render
function, and export a schema-versioned redacted trace for inspection. Keep
it out of production bundles.
## Subpath entries
Some behavior lives behind subpath exports rather than the package root:
* `@generative-a11y/core/testing` exposes the deterministic testing surface:
`ManualClock`, `createRecorder`, `recordRuntime`, `replayEvents`, and
matchers for lifecycle tests. These exports are not available from the core
root.
* `@generative-a11y/core/messages` exposes the localized copy surface: `en`,
`Messages`, `MessageMap`, `MessageParams`, `MessageKey`, `AdapterCopy`, and
`normalizeAdapterCopy`. Import this entry when you need custom copy or
adapter copy validation; these exports are not available from the core root.
* `@generative-a11y/ai-sdk/react` exposes the React hooks
(`useChatAccessibility`, `useObserveChatAccessibility`). The root entry is
SSR-safe and framework-neutral; the React integration is only
available from the subpath.
## Disposal ownership
Ownership is the rule that keeps cleanup predictable across packages:
* Creating something disposes it. `createRuntime()`, `createScheduler()`, and
`createStore()` each return an owned object with `dispose()`.
* Borrowing something never disposes it. Adapters and bindings
(`bindThread()`, `bindAgent()`, `bindRuntime()`) only unsubscribe and release
their own subscription and adapter records. Your thread, agent, and core
runtimes stay yours.
* Disposal is idempotent everywhere. Call `dispose()` once when the owning
scope ends, typically in a framework cleanup function or an explicit teardown
path.
---
# @generative-a11y/core
Turn application events into scheduled accessibility announcements.
Canonical: https://generativea11y.com/api/core
Markdown: https://generativea11y.com/markdown/api/core
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Install and import
Core does not depend on the DOM, React, or an AI framework. Your app sends it
RuntimeEvent objects, and it creates AnnouncementIntent objects when there is
something useful to announce.
```shell title="Terminal"
npm install @generative-a11y/core
```
Use core in any JavaScript runtime, including tests without a document. Browser
apps add [DOM](/api/dom) or [React](/api/react) for delivery.
```ts title="accessibility-runtime.ts"
import { createRuntime } from "@generative-a11y/core";
const runtime = createRuntime({
onAnnouncement: (intent) => console.log(intent.text),
});
// Call runtime.dispose() when its owner ends.
```
This listener records prepared output. Connect browser delivery before sending
lifecycle events in a web app.
## Public export map
Use the narrowest public export for the behavior you own.
| Category | Exports | Reference |
| --- | --- | --- |
| Runtime | createRuntime, Runtime | [/api/core/create-runtime](/api/core/create-runtime) |
| Events | RuntimeEvent and event family types | [/api/core/events](/api/core/events) |
| Workflows | WorkflowContext, run and step lifecycle types | [/api/core/workflows](/api/core/workflows) |
| Policy | presets, resolvePolicy, PolicyOverrides, WorkflowPolicy | [/api/core/policy](/api/core/policy) |
| Scheduler | createScheduler and scheduler types | [/api/core/scheduler](/api/core/scheduler) |
| Testing | ManualClock, createRecorder | [/api/core/testing](/api/core/testing) |
| Diagnostics | AnnouncementIntent, AnnouncementDiagnostic | [/api/core/diagnostics](/api/core/diagnostics) |
## Messages
English notices work without configuration. For custom copy, import `en` and
`Messages` from `@generative-a11y/core/messages` and pass `messages` to
`createRuntime`. This entry point also exports `MessageMap`, `MessageParams`,
`MessageKey`, `AdapterCopy`, and `normalizeAdapterCopy`. These exports are not
available from the core root.
See [localized announcements](/docs/localized-announcements) for examples and
[API naming changes](/docs/stability#public-api-naming-update) for the breaking
rename reference.
## Public declarations: @generative-a11y/core
Import from `@generative-a11y/core`. Direct declarations from the source checkout; transitive upstream types and behavioral contracts require the linked guides and upstream documentation.
### AdapterFidelity (type)
```typescript
interface AdapterFidelity {
/** Evidence quality for top-level and delegated run lifecycle. */
runs: "exact" | "partial" | "unavailable";
/** Evidence quality for step lifecycle and stable step identity. */
steps: "exact" | "partial" | "unavailable";
/** Evidence quality for parent-child relationships. */
hierarchy: "exact" | "partial" | "unavailable";
/** Evidence quality for tool lifecycle and workflow attribution. */
tools: "exact" | "partial" | "unavailable";
/** Evidence quality for human-interaction lifecycle and attribution. */
interactions: "exact" | "partial" | "unavailable";
/** Ability to suppress lifecycle duplicates when historical events replay. */
replay: "exact" | "partial" | "unavailable";
/** Evidence quality after a transport reconnects. */
reconnection: "exact" | "partial" | "unavailable";
/** Custom protocol events require a host-supplied explicit mapping. */
customEvents: "explicit-mapping" | "unsupported";
interruption: "exact" | "action-wrapper" | "unavailable";
retries: "exact" | "action-wrapper" | "unavailable";
connection: "exact" | "inferred" | "unavailable";
optionalEvents?: Array<"tool.progress" | "tool.failed" | "citation.available" | "interaction.requested">;
}
```
### AnnouncementCapacityPriority (type)
```typescript
type AnnouncementCapacityPriority = "status" | "content";
```
### AnnouncementChannel (type)
```typescript
type AnnouncementChannel = "polite" | "assertive";
```
### AnnouncementDiagnostic (type)
```typescript
interface AnnouncementDiagnostic {
at: number;
disposition: DiagnosticDisposition;
reason: DiagnosticReason;
/** Number of suppressed decisions or events represented by an aggregate. */
count?: number;
announcement?: AnnouncementIntent;
sourceType?: RuntimeEvent["type"];
sourceEventId?: string;
responseId?: string;
toolId?: string;
interactionId?: string;
/** Stable logical run identity associated with this decision. */
runId?: string;
/** Stable run attempt identity associated with this decision. */
runInstanceId?: string;
/** Stable logical step identity associated with this decision. */
stepId?: string;
/** Stable step attempt identity associated with this decision. */
stepInstanceId?: string;
scheduledAt?: number;
dueAt?: number;
delayMs?: number;
queueSequence?: number;
}
```
### AnnouncementIntent (type)
```typescript
interface AnnouncementIntent {
id: string;
at: number;
channel: AnnouncementChannel;
text: string;
sourceType: RuntimeEvent["type"];
sourceEventId?: string;
responseId?: string;
toolId?: string;
interactionId?: string;
/** Stable logical run identity associated with this intent. */
runId?: string;
/** Stable run attempt identity associated with this intent. */
runInstanceId?: string;
/** Stable logical step identity associated with this intent. */
stepId?: string;
/** Stable step attempt identity associated with this intent. */
stepInstanceId?: string;
locale?: string;
}
```
### AnnouncementListener (type)
```typescript
type AnnouncementListener = (announcement: AnnouncementIntent) => void;
```
### AnnouncementPolicy (type)
```typescript
interface AnnouncementPolicy {
/** Optional for compatibility with existing caller-authored policies. */
attention?: AttentionPolicy;
text: TextPolicy;
tools: ToolPolicy;
workflows: WorkflowPolicy;
announceResponseStarted: boolean;
announceResponseCompleted: boolean;
announceInterruption: boolean;
announceRetry: boolean;
announceInteractions: boolean;
announceConnections: boolean;
announceCitations: boolean;
errorChannel: AnnouncementChannel;
minimumGapMs: number;
dedupeWindowMs: number;
maxQueueSize: number;
maxActiveEntities: number;
}
```
### AnnouncementPurpose (type)
```typescript
/** Candidate purpose is independent of its source event and delivery channel. */
type AnnouncementPurpose = "response-text" | "routine-status" | "notice";
```
### AttentionMode (type)
```typescript
/** Conservative evidence labels, never proof of reading or user intent. */
type AttentionMode = "foreground" | "background" | "reading-history" | "away" | "unknown";
```
### AttentionOverride (type)
```typescript
/** Explicit host/user choice takes precedence over observed evidence. */
type AttentionOverride = "auto" | "normal" | "quiet";
```
### AttentionPolicy (type)
```typescript
interface AttentionPolicy {
enabled: boolean;
quietWhen: readonly Exclude[];
}
```
### AttentionState (type)
```typescript
interface AttentionState {
readonly observed: AttentionMode;
readonly override: AttentionOverride;
readonly effective: "normal" | "quiet";
}
```
### Clock (type)
```typescript
interface Clock {
now(): number;
setTimeout(callback: () => void, delayMs: number): ClockTimer;
clearTimeout(timer: ClockTimer): void;
}
```
### ClockTimer (type)
```typescript
type ClockTimer = unknown;
```
### createRecorder (value)
```typescript
declare function createRecorder(options?: Omit & {
startAt?: number;
}): Recorder;
```
### createRuntime (value)
```typescript
declare function createRuntime(options?: RuntimeOptions): Runtime;
```
### createScheduler (value)
```typescript
declare function createScheduler(options: SchedulerOptions): Scheduler;
```
### DiagnosticDisposition (type)
```typescript
type DiagnosticDisposition = "queued" | "merged" | "suppressed" | "cancelled" | "announced";
```
### DiagnosticListener (type)
```typescript
type DiagnosticListener = (diagnostic: AnnouncementDiagnostic) => void;
```
### DiagnosticPendingAnnouncement (type)
```typescript
/** A content-free queued announcement projection for diagnostic consumers. */
interface DiagnosticPendingAnnouncement {
id: string;
channel: AnnouncementChannel;
sourceType: RuntimeEvent["type"];
sourceEventId?: string;
responseId?: string;
toolId?: string;
interactionId?: string;
/** Stable logical run identity associated with this queued intent. */
runId?: string;
/** Stable run attempt identity associated with this queued intent. */
runInstanceId?: string;
/** Stable logical step identity associated with this queued intent. */
stepId?: string;
/** Stable step attempt identity associated with this queued intent. */
stepInstanceId?: string;
locale?: string;
scheduledAt: number;
dueAt: number;
delayMs: number;
sequence: number;
}
```
### DiagnosticReason (type)
```typescript
type DiagnosticReason = "catalog-format-error" | "scheduled" | "coalesced" | "duplicate" | "policy-silent" | "attention-quiet" | "attention-updated" | "unknown-response" | "terminal-response" | "stale-response" | "empty-text" | "scope-cancelled" | "runtime-disposed" | "queue-capacity" | "delivery-error" | "unknown-tool" | "terminal-tool" | "stale-tool" | "unknown-run" | "terminal-run" | "stale-run" | "unknown-step" | "terminal-step" | "stale-step" | "unknown-parent" | "open-children" | "partial-identity" | "invalid-event" | "progress-threshold" | "delivered";
```
### DiagnosticResponseSnapshot (type)
```typescript
interface DiagnosticResponseSnapshot {
responseId: string;
epoch: number;
instanceId?: string;
status: "active" | "completed" | "interrupted" | "failed";
locale?: string;
}
```
### DiagnosticRunSnapshot (type)
```typescript
/** Content-free immutable projection of one tracked run attempt. */
interface DiagnosticRunSnapshot {
/** Stable logical run identity. */
runId: string;
/** Stable attempt identity when supplied by the source. */
instanceId?: string;
/** Stable logical parent run identity. */
parentRunId?: string;
/** Parent attempt identity when supplied by the source. */
parentRunInstanceId?: string;
/** Tool that delegated to this run, when explicitly exposed. */
parentToolId?: string;
/** Response that owns this run, when explicitly exposed. */
parentResponseId?: string;
/** Current lifecycle state for this run attempt. */
status: "active" | "completed" | "interrupted" | "failed";
/** Number of identified steps completed in this attempt. */
completedSteps: number;
/** Number of identified steps failed in this attempt. */
failedSteps: number;
}
```
### DiagnosticStepSnapshot (type)
```typescript
/** Content-free immutable projection of one identified step attempt. */
interface DiagnosticStepSnapshot {
/** Stable logical owner run identity. */
runId: string;
/** Owner run attempt identity when supplied by the source. */
runInstanceId?: string;
/** Stable logical step identity. */
stepId: string;
/** Stable step attempt identity when supplied by the source. */
instanceId?: string;
/** Stable logical parent step identity. */
parentStepId?: string;
/** Parent step attempt identity when supplied by the source. */
parentStepInstanceId?: string;
/** Current lifecycle state for this step attempt. */
status: "active" | "completed" | "interrupted" | "failed";
/** Injected-clock timestamp when this attempt started. */
startedAt: number;
/** Last coalesced progress bucket, or -1 before progress. */
lastProgressBucket: number;
}
```
### DiagnosticToolSnapshot (type)
```typescript
interface DiagnosticToolSnapshot {
toolId: string;
instanceId?: string;
status: "active" | "completed" | "failed";
locale?: string;
lastProgressBucket: number;
}
```
### InteractionKind (type)
```typescript
type InteractionKind = "approval" | "confirmation" | "input" | (string & {});
```
### ManualClock (value)
```typescript
declare class ManualClock implements Clock {
#private;
constructor(startAt?: number);
now(): number;
setTimeout(callback: () => void, delayMs: number): number;
clearTimeout(timer: ClockTimer): void;
advanceBy(durationMs: number): void;
advanceTo(timestamp: number): void;
runNext(): boolean;
runUntilIdle(maxTasks?: number): void;
pendingCount(): number;
}
```
### normalizeAnnouncementText (value)
```typescript
declare function normalizeAnnouncementText(text: string): string;
```
### PolicyOverrides (type)
```typescript
type PolicyOverrides = Partial> & {
attention?: Partial>;
text?: Partial;
tools?: Partial;
workflows?: Partial;
};
```
### PresetName (type)
```typescript
type PresetName = "minimal" | "balanced" | "verbose" | "completion-only";
```
### presets (value)
```typescript
declare const presets: Readonly>;
```
### ReadonlyAnnouncementPolicy (type)
```typescript
type ReadonlyAnnouncementPolicy = Readonly & {
attention?: Readonly;
text: Readonly;
tools: Readonly;
workflows: Readonly;
}>;
```
### Recorder (type)
```typescript
interface Recorder {
runtime: ReturnType;
clock: ManualClock;
transcript(): AnnouncementIntent[];
diagnosticTranscript(): AnnouncementDiagnostic[];
clear(): void;
}
```
### resolvePolicy (value)
```typescript
declare function resolvePolicy(preset?: PresetName, overrides?: PolicyOverrides): ReadonlyAnnouncementPolicy;
```
### Runtime (type)
```typescript
interface Runtime {
dispatch(event: RuntimeEvent): boolean;
getPolicy(): ReadonlyAnnouncementPolicy;
pendingCount(): number;
subscribeAnnouncements(listener: AnnouncementListener): () => void;
subscribeDiagnostics(listener: DiagnosticListener): () => void;
subscribeDiagnosticEvents(listener: RuntimeDiagnosticListener): () => void;
getDiagnosticSnapshot(): RuntimeDiagnosticSnapshotV1;
dispose(): void;
}
```
### RuntimeDiagnosticEventV1 (type)
```typescript
type RuntimeDiagnosticEventV1 = {
schemaVersion: 1;
sequence: number;
at: number;
kind: "event-observed";
event: RuntimeEvent;
} | {
schemaVersion: 1;
sequence: number;
at: number;
kind: "decision";
decision: AnnouncementDiagnostic;
};
```
### RuntimeDiagnosticListener (type)
```typescript
type RuntimeDiagnosticListener = (event: RuntimeDiagnosticEventV1) => void;
```
### RuntimeDiagnosticSnapshotV1 (type)
```typescript
interface RuntimeDiagnosticSnapshotV1 {
readonly messages?: Readonly<{
catalogId: string;
locale: string;
}>;
schemaVersion: 1;
at: number;
policy: ReadonlyAnnouncementPolicy;
/** Cached immutable state, present only when attention policy is enabled. */
attention?: AttentionState;
pending: {
announcements: readonly DiagnosticPendingAnnouncement[];
flushes: readonly {
responseId: string;
epoch: number;
dueAt: number;
}[];
};
responses: readonly DiagnosticResponseSnapshot[];
tools: readonly DiagnosticToolSnapshot[];
/** Present when the runtime supports hierarchical workflow diagnostics. */
runs?: readonly DiagnosticRunSnapshot[];
/** Present when the runtime supports identified step diagnostics. */
steps?: readonly DiagnosticStepSnapshot[];
pendingCount: number;
}
```
### RuntimeEvent (type)
```typescript
type RuntimeEvent = (EventMetadata & {
type: "attention.changed";
mode: AttentionMode;
}) | (EventMetadata & {
type: "attention.override";
mode: AttentionOverride;
}) | (ContextualEventMetadata & {
type: "response.started";
responseId: string;
responseInstanceId?: string;
}) | (ContextualEventMetadata & {
type: "response.text.delta";
responseId: string;
responseInstanceId?: string;
delta: string;
}) | (ContextualEventMetadata & {
type: "response.completed";
responseId: string;
responseInstanceId?: string;
}) | (ContextualEventMetadata & {
type: "response.interrupted";
responseId: string;
responseInstanceId?: string;
}) | (ContextualEventMetadata & {
type: "response.failed";
responseId: string;
responseInstanceId?: string;
error?: string;
announcement?: string;
}) | (ContextualEventMetadata & {
type: "response.retrying";
responseId: string;
responseInstanceId?: string;
nextResponseInstanceId?: string;
attempt?: number;
}) | (ContextualEventMetadata & {
type: "tool.started";
toolId: string;
toolInstanceId?: string;
label: string;
}) | (ContextualEventMetadata & {
type: "tool.progress";
toolId: string;
toolInstanceId?: string;
label: string;
/** Normalized progress from 0 to 1. */
progress?: number;
message?: string;
}) | (ContextualEventMetadata & {
type: "tool.completed";
toolId: string;
toolInstanceId?: string;
label: string;
summary?: string;
}) | (ContextualEventMetadata & {
type: "tool.failed";
toolId: string;
toolInstanceId?: string;
label: string;
error?: string;
announcement?: string;
}) | (ContextualEventMetadata & {
type: "interaction.requested";
interactionId: string;
kind: InteractionKind;
label: string;
urgent?: boolean;
}) | (ContextualEventMetadata & {
type: "interaction.resolved";
interactionId: string;
kind: InteractionKind;
outcome: "approved" | "rejected" | "submitted" | "cancelled";
label?: string;
}) | (ContextualEventMetadata & {
type: "approval.requested";
approvalId: string;
label: string;
urgent?: boolean;
}) | (ContextualEventMetadata & {
type: "approval.resolved";
approvalId: string;
outcome: "approved" | "rejected" | "cancelled";
label?: string;
}) | (EventMetadata & {
type: "run.started";
/** Stable logical run identity. */
runId: string;
/** Stable identity for this run attempt. */
runInstanceId?: string;
/** Stable logical parent run, when explicitly exposed. */
parentRunId?: string;
/** Attempt identity of the explicit parent run. */
parentRunInstanceId?: string;
/** Tool that delegated to this run. */
parentToolId?: string;
/** Response that owns this run. */
parentResponseId?: string;
/** Localized display copy; never used as identity. */
label?: string;
}) | (EventMetadata & {
type: "run.completed" | "run.interrupted" | "run.failed";
/** Stable logical run identity. */
runId: string;
/** Stable identity for this run attempt. */
runInstanceId?: string;
/** Diagnostic-only backend detail; never announced automatically. */
error?: string;
/** Short localized user-safe terminal copy. */
announcement?: string;
}) | (EventMetadata & {
type: "run.retrying";
/** Stable logical run identity. */
runId: string;
/** Attempt being replaced. */
runInstanceId?: string;
/** Stable identity of the replacement attempt. */
nextRunInstanceId?: string;
/** Human-readable one-based attempt number. */
attempt?: number;
}) | (EventMetadata & {
type: "step.started";
/** Stable logical owner run identity. */
runId: string;
/** Stable owner run attempt identity. */
runInstanceId?: string;
/** Stable logical step identity; omit for name-only evidence. */
stepId?: string;
/** Stable identity for this step attempt. */
stepInstanceId?: string;
/** Stable logical parent step identity. */
parentStepId?: string;
/** Attempt identity of the explicit parent step. */
parentStepInstanceId?: string;
/** Localized display copy; never used as identity. */
label: string;
}) | (EventMetadata & {
type: "step.progress";
/** Stable logical owner run identity. */
runId: string;
/** Stable owner run attempt identity. */
runInstanceId?: string;
/** Stable logical step identity; omit for name-only evidence. */
stepId?: string;
/** Stable identity for this step attempt. */
stepInstanceId?: string;
/** Localized display copy; never used as identity. */
label: string;
/** Normalized progress from 0 to 1. */
progress?: number;
/** Optional localized user-safe progress copy. */
message?: string;
}) | (EventMetadata & {
type: "step.completed" | "step.interrupted" | "step.failed";
/** Stable logical owner run identity. */
runId: string;
/** Stable owner run attempt identity. */
runInstanceId?: string;
/** Stable logical step identity; omit for name-only evidence. */
stepId?: string;
/** Stable identity for this step attempt. */
stepInstanceId?: string;
/** Localized display copy; never used as identity. */
label: string;
/** Diagnostic-only backend detail; never announced automatically. */
error?: string;
/** Short localized user-safe terminal copy. */
announcement?: string;
}) | (EventMetadata & {
type: "step.retrying";
/** Stable logical owner run identity. */
runId: string;
/** Stable owner run attempt identity. */
runInstanceId?: string;
/** Stable logical step identity; omit for name-only evidence. */
stepId?: string;
/** Attempt being replaced. */
stepInstanceId?: string;
/** Stable identity of the replacement attempt. */
nextStepInstanceId?: string;
/** Human-readable one-based attempt number. */
attempt?: number;
/** Localized display copy; never used as identity. */
label: string;
}) | (EventMetadata & {
type: "connection.lost";
label?: string;
}) | (EventMetadata & {
type: "connection.restored";
label?: string;
}) | (EventMetadata & {
type: "citation.available";
count: number;
});
```
### RuntimeOptions (type)
```typescript
interface RuntimeOptions {
messages?: Messages;
preset?: PresetName;
policy?: PolicyOverrides;
clock?: Clock;
onAnnouncement?: (announcement: AnnouncementIntent) => void;
onDeliveryError?: (error: unknown, announcement: AnnouncementIntent) => void;
onDiagnostic?: (diagnostic: AnnouncementDiagnostic) => void;
}
```
### ScheduleAnnouncement (type)
```typescript
interface ScheduleAnnouncement {
/** Defaults to notice; independent of channel and source event. */
purpose?: AnnouncementPurpose;
channel: AnnouncementChannel;
text: string;
sourceType: RuntimeEvent["type"];
sourceEventId?: string;
responseId?: string;
toolId?: string;
interactionId?: string;
runId?: string;
runInstanceId?: string;
stepId?: string;
stepInstanceId?: string;
locale?: string;
delayMs?: number;
scope?: string;
coalesceKey?: string;
dedupeKey?: string;
capacityPriority?: AnnouncementCapacityPriority;
}
```
### Scheduler (type)
```typescript
interface Scheduler {
schedule(candidate: ScheduleAnnouncement): string | undefined;
cancelScope(scope: string): void;
/** Cancel only queued candidates of these purposes; already delivered output cannot be retracted. */
cancelPurposes(purposes: readonly AnnouncementPurpose[], reason?: DiagnosticReason): void;
dispose(): void;
pendingCount(): number;
getDiagnosticSnapshot(): readonly DiagnosticPendingAnnouncement[];
}
```
### SchedulerOptions (type)
```typescript
interface SchedulerOptions {
clock: Clock;
minimumGapMs: number;
dedupeWindowMs: number;
maxQueueSize: number;
onAnnouncement: (announcement: AnnouncementIntent) => void;
onDeliveryError?: (error: unknown, announcement: AnnouncementIntent) => void;
onDiagnostic?: (diagnostic: AnnouncementDiagnostic) => void;
}
```
### SegmentationResult (type)
```typescript
interface SegmentationResult {
complete: string[];
remainder: string;
}
```
### segmentText (value)
```typescript
declare function segmentText(text: string, strategy: Exclude, locale?: string): SegmentationResult;
```
### systemClock (value)
```typescript
declare const systemClock: Clock;
```
### TextPolicy (type)
```typescript
interface TextPolicy {
strategy: TextStrategy;
minimumCharacters: number;
maximumDelayMs: number;
}
```
### TextStrategy (type)
```typescript
type TextStrategy = "silent" | "sentence" | "paragraph" | "completion";
```
### ToolPolicy (type)
```typescript
interface ToolPolicy {
announceStart: boolean;
announceStartAfterMs: number;
announceProgress: boolean;
progressEveryPercent: number;
announceCompletion: boolean;
announceFailure: boolean;
}
```
### WorkflowContext (type)
```typescript
/** Explicit workflow ownership supplied by a source integration. */
type WorkflowContext = {
runId?: undefined;
runInstanceId?: never;
stepId?: never;
stepInstanceId?: never;
} | ({
/** Stable logical run identity. */
runId: string;
/** Stable identity for one attempt of the logical run. */
runInstanceId?: string;
} & ({
stepId?: undefined;
stepInstanceId?: never;
} | {
/** Stable logical step identity. */
stepId: string;
/** Stable identity for one attempt of the logical step. */
stepInstanceId?: string;
}));
```
### WorkflowPolicy (type)
```typescript
/** Announcement controls for hierarchical run and step lifecycle. */
interface WorkflowPolicy {
/** Run boundary verbosity. */
runs: "silent" | "terminal" | "all";
/** Identified step boundary verbosity. */
steps: "silent" | "long-running" | "all";
/** Delay and duration threshold for long-running step announcements. */
announceStepAfterMs: number;
/** Whether explicit step progress may be coalesced and announced. */
announceProgress: boolean;
/** Whether identified nested steps may produce announcements. */
announceNestedSteps: boolean;
}
```
---
# createRuntime
Create a runtime that turns application events into announcement intents.
Canonical: https://generativea11y.com/api/core/create-runtime
Markdown: https://generativea11y.com/markdown/api/core/create-runtime
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Signature and import
Create one runtime for your app or for each conversation that needs separate
settings. Connect delivery before sending events that can produce output.
```typescript title="accessibility-runtime.ts"
import { createRuntime } from "@generative-a11y/core";
const runtime = createRuntime({
onAnnouncement(intent) {
console.log(intent.text);
},
});
```
Browser apps usually connect output with [bindRuntime](/api/dom/bind-runtime).
Use `onAnnouncement` when your app owns another delivery mechanism.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| options | ` RuntimeOptions ` | no | ` {} ` | Construction options for policy, time, announcement delivery, delivery errors, and diagnostics. |
| return | ` Runtime ` | no | | Return. An owned runtime with synchronous dispatch, subscriptions, policy inspection, pending work inspection, and disposal. |
## RuntimeOptions
Options are read during construction. Nested policy overrides merge with the
selected preset.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| messages | ` Messages ` | no | ` English catalog ` | Localized notice catalog from core/messages, validated and captured at construction. Response text is unchanged. |
| preset | ` PresetName ` | no | ` "balanced" ` | Selects a complete baseline policy: minimal, balanced, verbose, or completion-only behavior. |
| policy | ` PolicyOverrides ` | no | ` {} ` | Overrides only intentional text, tool, status, pacing, channel, and capacity differences. |
| clock | ` Clock ` | no | ` systemClock ` | Injects time and timers. Use ManualClock for deterministic tests. |
| onAnnouncement | ` AnnouncementListener ` | no | ` undefined ` | Registers the first intent listener. Dispatch that produces output requires at least one listener. |
| onDeliveryError | ` (error, intent) => void ` | no | ` undefined ` | Observes listener failures while delivery continues to later listeners. |
| onDiagnostic | ` DiagnosticListener ` | no | ` undefined ` | Observes queued, merged, suppressed, cancelled, announced, and delivery-error decisions. |
## Runtime methods
Runtime methods are synchronous. Unsubscribe functions and dispose are
idempotent.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| dispatch(event) | ` boolean ` | no | | Method. Processes one serializable RuntimeEvent synchronously. Returns false after disposal or when a nested dispatch transaction reaches capacity. |
| getPolicy() | ` ReadonlyAnnouncementPolicy ` | no | | Method. Returns the resolved immutable policy used by this runtime. |
| pendingCount() | ` number ` | no | | Method. Counts scheduler candidates and owned response flush timers. Use it for tests and diagnostics, not application rendering. |
| subscribeAnnouncements(listener) | ` () => void ` | no | | Method. Registers an AnnouncementIntent listener and returns an idempotent unsubscribe function. |
| subscribeDiagnostics(listener) | ` () => void ` | no | | Method. Registers an AnnouncementDiagnostic listener and returns an idempotent unsubscribe function. |
| subscribeDiagnosticEvents(listener) | ` () => void ` | no | | Method. Observes a versioned ordered stream of source events and diagnostic decisions without changing scheduling. |
| getDiagnosticSnapshot() | ` RuntimeDiagnosticSnapshotV1 ` | no | | Method. Returns immutable content-free response, tool, run, step, queue, and flush timing state for diagnostic consumers. |
| dispose() | ` void ` | no | | Method. Cancels every owned timer, clears bounded state and queued work, then releases listeners. Repeated calls are safe. |
## Complete response lifecycle
Each delta contains only new text. A completed event announces useful text that
is still waiting, then closes the response.
```typescript title="Response lifecycle"
const accepted = runtime.dispatch({
type: "response.started",
responseId: "report-1",
});
runtime.dispatch({
type: "response.text.delta",
responseId: "report-1",
delta: "The migration completed successfully.",
});
runtime.dispatch({
type: "response.completed",
responseId: "report-1",
});
console.log({ accepted, pending: runtime.pendingCount() });
// Call when the owning surface is removed, after delivery is no longer needed.
function disposeRuntime() {
runtime.dispose();
}
```
Send `response.started` before deltas or terminal events for that response.
Completion cancels response timers; call `dispose()` when the runtime owner
ends.
**Evidence and testing note**
AnnouncementIntent describes an update prepared by core. Test with a real screen
reader to confirm what it speaks.
## Localized announcements
See [catalogs and adapter copy](/docs/localized-announcements) for the typed
`messages` and `copy` options, language ownership, validation, construction
lifetime, and replay requirements. Existing lifecycle evidence and timing remain
unchanged.
---
# RuntimeEvent
Report confirmed lifecycle changes with serializable runtime events.
Canonical: https://generativea11y.com/api/core/events
Markdown: https://generativea11y.com/markdown/api/core/events
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Dispatch an event
Use the same response ID for its start, appended text, and terminal event.
```ts title="Start a response"
import type { RuntimeEvent } from "@generative-a11y/core";
const event: RuntimeEvent = {
type: "response.started",
responseId: "report",
};
runtime.dispatch(event);
```
See
[the complete response lifecycle](/api/core/create-runtime#complete-lifecycle)
for text deltas and completion.
## Event families
Events describe actions and changes your app can confirm. They contain
serializable data, not rendered components or private framework state.
| Family | Events | Required identity |
| --- | --- | --- |
| Run | started, completed, interrupted, failed, retrying | runId |
| Step | started, progress, completed, interrupted, failed, retrying | runId; stepId when stable identity exists |
| Response | started, text.delta, completed, interrupted, failed, retrying | responseId |
| Tool | started, progress, completed, failed | toolId |
| Interaction | requested, resolved | interactionId |
| Approval | requested, resolved | approvalId |
| Connection | lost, restored | none |
| Citation | available | responseId |
## Response replacement example
Use responseInstanceId when one logical response can be replaced. Late events
from the old instance are suppressed as stale.
```typescript title="Replace a response attempt"
runtime.dispatch({
type: "response.retrying",
responseId: "report",
responseInstanceId: "attempt-1",
nextResponseInstanceId: "attempt-2",
attempt: 2,
});
```
Keep `responseId` stable across regeneration and use the replacement
`nextResponseInstanceId` on later deltas and terminal events. A later
`response.started` with the same `responseId` also replaces the active attempt
and makes events from older instance IDs stale.
## Common fields
ID fields connect related events. Labels and messages contain translated text
for users.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| type | ` string literal ` | yes | | Selects one member of the discriminated event union. |
| eventId | ` string ` | no | ` undefined ` | Connects an event to your app's logs without being used as the ID for a response, tool, interaction, run, or step. |
| locale | ` string ` | no | ` undefined ` | Carries the language for user-facing text into intents and DOM delivery. |
| label / message / announcement | ` string ` | no | ` undefined ` | Event-specific. Short, translated text supplied by your app. Do not pass raw arguments, results, or backend errors. |
## Localized announcements
See [catalogs and adapter copy](/docs/localized-announcements) for the typed
`messages` and `copy` options, language ownership, validation, construction
lifetime, and replay requirements. Existing lifecycle evidence and timing remain
unchanged.
---
# Workflow lifecycle
Track runs, steps, attempts, and the work they own.
Canonical: https://generativea11y.com/api/core/workflows
Markdown: https://generativea11y.com/markdown/api/core/workflows
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Start and complete a run
Give each run a logical ID and each attempt its own instance ID.
```ts title="Report a workflow run"
import { createRuntime } from "@generative-a11y/core";
const runtime = createRuntime();
runtime.dispatch({
type: "run.started",
runId: "report",
runInstanceId: "report-1",
});
// Complete after the run’s work and identified children have ended.
runtime.dispatch({
type: "run.completed",
runId: "report",
runInstanceId: "report-1",
});
// Call when the owning surface is removed, not after each run.
export function disposeWorkflowAccessibility() {
runtime.dispose();
}
```
Keep the runtime alive while the surface needs its queued announcements. Call
`disposeWorkflowAccessibility()` when that surface is removed.
## Workflow identity
`runId` and `stepId` identify logical work. `runInstanceId` and `stepInstanceId`
identify one attempt. A step always belongs to a run, and an attempt ID cannot
be supplied without its logical ID.
| Field | Meaning | Constraint |
| --- | --- | --- |
| runId | Logical run | Required for every run and step event |
| runInstanceId | Run attempt | Optional; requires runId |
| stepId | Logical step | Optional only when the source lacks stable step identity |
| stepInstanceId | Step attempt | Optional; requires stepId and runId |
## Run and step events
Run and identified step lifecycles start once and end once. A run cannot
complete while it has active identified child runs or steps. Terminal and retry
events cancel announcements owned by the ended or replaced attempt.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| run | ` run.started \| completed \| interrupted \| failed \| retrying ` | yes | | Tracks top-level or delegated work. Parent fields are accepted only when the source reports them explicitly. |
| step | ` step.started \| progress \| completed \| interrupted \| failed \| retrying ` | yes | | Tracks work within a run. Identified steps may be nested and concurrent. |
| nextRunInstanceId / nextStepInstanceId | ` string ` | no | ` undefined ` | Replacement attempt identity on retry. Late events from the replaced attempt are stale. |
| parentRunId / parentRunInstanceId | ` string ` | no | ` undefined ` | Explicit parent run and attempt identity. |
| parentStepId / parentStepInstanceId | ` string ` | no | ` undefined ` | Explicit parent step and attempt identity. |
| parentToolId / parentResponseId | ` string ` | no | ` undefined ` | Explicit tool delegation or response ownership. |
## WorkflowContext
Responses, tools, interactions, and approvals can carry workflow context. This
connects existing lifecycle events to the run or step that owns them without
turning those entities into steps.
```typescript title="Attach tool work to a workflow"
runtime.dispatch({
type: "tool.started",
toolId: "search",
toolInstanceId: "search-2",
runId: "report",
runInstanceId: "report-1",
stepId: "sources",
stepInstanceId: "sources-2",
label: "Search sources",
});
```
## Partial identity
When a framework exposes only a step name, omit `stepId`. Core emits a
`partial-identity` diagnostic but does not create a step snapshot, announcement,
or run summary count from that evidence. It never converts labels, array
positions, or timing into identity.
---
# Policy and presets
Choose announcement defaults and override timing, detail, and queue limits.
Canonical: https://generativea11y.com/api/core/policy
Markdown: https://generativea11y.com/markdown/api/core/policy
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## PresetName
Each preset defines a complete set of default values. `balanced` is the default.
```ts title="Choose a preset"
import { createRuntime } from "@generative-a11y/core";
const runtime = createRuntime({ preset: "minimal" });
```
The table compares their announcement behavior; use overrides below to change
individual settings.
| Preset | Streaming | Status updates | Workflow updates |
| --- | --- | --- | --- |
| minimal | Restrained | Final states | Terminal runs; steps silent |
| balanced | Sentence-paced | Useful status | Terminal runs; long-running steps |
| verbose | More frequent | Progress enabled | All run and step updates |
| completion-only | Final text only | Minimal | Workflow silent |
## PolicyOverrides
Nested overrides merge with the selected preset. Unspecified values remain
controlled by that preset.
```typescript title="accessibility-policy.ts"
import { createRuntime } from "@generative-a11y/core";
const runtime = createRuntime({
preset: "balanced",
policy: {
text: { minimumCharacters: 48, maximumDelayMs: 1_800 },
tools: { announceProgress: false },
workflows: { steps: "long-running", announceStepAfterMs: 3_000 },
minimumGapMs: 900,
maxQueueSize: 64,
},
});
```
This override reduces text fragmentation, silences tool progress, and caps
pending output at 64 items. `balanced` supplies every setting not shown.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| text.strategy | ` TextStrategy ` | no | ` preset value ` | Selects silent, sentence, paragraph, or completion segmentation. |
| text.minimumCharacters | ` number ` | no | ` preset value ` | Avoids tiny fragments except when a terminal or maximum-delay flush applies. |
| text.maximumDelayMs | ` number ` | no | ` preset value ` | Bounds how long useful buffered text waits for a natural boundary. |
| minimumGapMs | ` number ` | no | ` preset value ` | Paces adjacent intents to reduce interruption and overlap. |
| dedupeWindowMs | ` number ` | no | ` preset value ` | Suppresses equivalent recent output. |
| maxQueueSize | ` number ` | no | ` preset value ` | Bounds scheduler candidates and favors content over status during eviction. |
| maxActiveEntities | ` number ` | no | ` preset value ` | Bounds response, tool, run, and step identity state and fails closed after capacity. |
| workflows.runs | ` silent \| terminal \| all ` | no | ` preset value ` | Controls run boundary announcements. |
| workflows.steps | ` silent \| long-running \| all ` | no | ` preset value ` | Controls identified step boundary announcements. |
| workflows.announceStepAfterMs | ` number ` | no | ` preset value ` | Sets the start delay and completion duration threshold for long-running steps. |
| workflows.announceProgress | ` boolean ` | no | ` preset value ` | Allows explicit identified step progress announcements. |
| workflows.announceNestedSteps | ` boolean ` | no | ` preset value ` | Allows identified nested steps to announce. |
## Attention policy
`attention?: AttentionPolicy` is optional and disabled by default. Set
`{ enabled: true }` to quiet response text and routine starts/progress when
observed attention is background. `quietWhen` accepts `background`,
`reading-history`, and `away`; its default is `["background"]`.
`attention.changed` carries an `AttentionMode`; `attention.override` carries
`auto`, `normal`, or `quiet`. Explicit overrides take precedence over
observations. Optional `snapshot.attention` is a cached, frozen `AttentionState`
containing `observed`, `override`, and `effective`. Core exports
`AttentionMode`, `AttentionOverride`, `AttentionPolicy`, and `AttentionState`.
Quiet retains only base-policy-enabled terminal, failure, interaction,
connection, citation, and retry notices. Suppressed response text has no
backlog; crossing sentence/paragraph units are discarded, and completion
strategy cannot replay a response touched by quiet.
[Read the attention guide](/docs/attention-aware-announcements).
---
# createScheduler
Schedule prepared announcements with bounded queues and an injected clock.
Canonical: https://generativea11y.com/api/core/scheduler
Markdown: https://generativea11y.com/markdown/api/core/scheduler
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Signature and cleanup
Most apps should use createRuntime. Use the scheduler directly only if your app
already decides which events should produce announcements.
```typescript title="announcement-scheduler.ts"
import { createScheduler, systemClock } from "@generative-a11y/core";
const scheduler = createScheduler({
clock: systemClock,
minimumGapMs: 750,
dedupeWindowMs: 4_000,
maxQueueSize: 64,
onAnnouncement: (intent) => console.log(intent.text),
});
scheduler.schedule({
channel: "polite",
text: "The report is ready.",
sourceType: "response.completed",
scope: "response:report-1",
capacityPriority: "content",
});
```
Use `scope` to cancel related pending output when a response, tool, run, or step
ends. Under capacity pressure, response content can replace a status update.
Call `scheduler.dispose()` when its owner ends.
## SchedulerOptions
The scheduler requires explicit timing and capacity values; it does not apply a
runtime preset.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| clock | ` Clock ` | yes | | Time and timer implementation. Use systemClock in an app or ManualClock in a test. |
| minimumGapMs | ` number ` | yes | | Minimum spacing between deliveries, in milliseconds. Must be finite and non-negative. |
| dedupeWindowMs | ` number ` | yes | | Window for suppressing recently delivered equivalent output. Must be finite and non-negative. |
| maxQueueSize | ` number ` | yes | | Positive integer limiting pending announcements. |
| onAnnouncement | ` (intent: AnnouncementIntent) => void ` | yes | | Receives each prepared announcement when it is due. |
| onDeliveryError | ` (error, intent) => void ` | no | ` undefined ` | Observes failures thrown by the announcement listener. |
| onDiagnostic | ` (diagnostic: AnnouncementDiagnostic) => void ` | no | ` undefined ` | Observes scheduler decisions. |
| return | ` Scheduler ` | no | | Return. Owned scheduler with schedule, cancelScope, pendingCount, and dispose methods. |
## ScheduleAnnouncement
A candidate describes prepared user-facing output. It must not contain raw
backend data.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| purpose | ` response-text \| routine-status \| notice ` | no | ` "notice" ` | Independent of channel and source event. Used by cancelPurposes to retract only queued output of a given kind. |
| channel | ` polite \| assertive ` | yes | | Requested announcement urgency. |
| text | ` string ` | yes | | Translated text with whitespace normalized by the runtime. |
| sourceType | ` RuntimeEvent['type'] ` | yes | | Identifies the app event that produced this candidate. |
| sourceEventId | ` string ` | no | ` undefined ` | Optional source event correlation copied into intents. |
| responseId | ` string ` | no | ` undefined ` | Optional response identity used for dedupe grouping. |
| toolId | ` string ` | no | ` undefined ` | Optional tool identity used for dedupe grouping. |
| interactionId | ` string ` | no | ` undefined ` | Optional interaction identity used for dedupe grouping. |
| locale | ` string ` | no | ` undefined ` | Optional locale copied into the announcement intent. |
| delayMs | ` number ` | no | ` 0 ` | Additional eligibility delay measured by the injected clock. |
| scope | ` string ` | no | ` undefined ` | Key used to cancel pending work for one response, tool, interaction, run, or step. |
| runId / runInstanceId / stepId / stepInstanceId | ` string ` | no | ` undefined ` | Optional workflow correlation copied into intents and diagnostics. |
| coalesceKey | ` string ` | no | ` undefined ` | Replaces equivalent pending work with the newest candidate. |
| dedupeKey | ` string ` | no | ` source, entity, channel, and text ` | Suppresses equivalent recent delivery within the dedupe window. |
| capacityPriority | ` status \| content ` | no | ` "content" ` | Allows content to displace status work when bounded capacity is exhausted. |
## Scheduler methods
Dispose cancels the owned timer and pending queue.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| schedule(candidate) | ` string \| undefined ` | no | | Method. Returns the scheduled ID, including the replacement ID when coalescing pending work. Returns undefined when the candidate text is blank, the scheduler is disposed, or the candidate loses capacity eviction. Duplicate suppression happens at delivery and does not change the return value. |
| cancelScope(scope) | ` void ` | no | | Method. Cancels every pending candidate with the matching scope. |
| cancelPurposes(purposes, reason?) | ` void ` | no | | Method. Cancels only queued candidates whose purpose (defaulting to "notice") is in the given list. The optional reason defaults to "scope-cancelled". Already delivered output cannot be retracted. |
| pendingCount() | ` number ` | no | | Method. Returns the current bounded queue length. |
| getDiagnosticSnapshot() | ` readonly DiagnosticPendingAnnouncement[] ` | no | | Method. Returns the current content-free pending queue projection in due-time order. |
| dispose() | ` void ` | no | | Method. Cancels the timer and queue. Repeated calls are safe. |
## Delivery pacing
The scheduler keeps a single timer aimed at the next eligible candidate. An
announcement becomes eligible at its `dueAt` time, which is the scheduling
moment plus `delayMs` on the injected clock. Polite announcements additionally
wait for `minimumGapMs` to elapse since the last successful delivery, so a
burst of status updates cannot machine-gun a screen reader. Assertive
announcements bypass the minimum gap: when an eligible assertive and an
eligible polite candidate compete, the assertive one delivers first. The gap is
only updated by successful deliveries; a suppressed duplicate does not reset
pacing.
```typescript title="pacing.ts"
import { createScheduler, systemClock } from "@generative-a11y/core";
const scheduler = createScheduler({
clock: systemClock,
minimumGapMs: 1000,
dedupeWindowMs: 5_000,
maxQueueSize: 32,
onAnnouncement: (intent) => liveRegion.textContent = intent.text,
});
// Deliver soon, but no sooner than one second after the previous announcement.
const statusId = scheduler.schedule({
channel: "polite",
text: "Still working on your request.",
sourceType: "response.started",
responseId: "response:r1",
capacityPriority: "status",
});
// Urgent content jumps ahead of the polite queue.
scheduler.schedule({
channel: "assertive",
text: "Your approval is required.",
sourceType: "approval.requested",
interactionId: "interaction:a1",
capacityPriority: "content",
});
```
## Deduplication
Each delivered announcement registers a dedupe key for `dedupeWindowMs`. When
a queued candidate later becomes eligible with the same key, delivery is
suppressed and a `suppressed` / `duplicate` diagnostic is recorded. The key
combines the locale with either your explicit `dedupeKey` or a default built
from the source type, an entity identity
(`responseId ?? toolId ?? interactionId ?? scope ?? "global"`), the channel,
and the text. Passing an explicit `dedupeKey` lets you collapse equivalent
output that differs in incidental text, while the default keeps announcements
from two different responses separate even when the wording matches.
Coalescing is the queue-time counterpart. If a candidate carries a
`coalesceKey` that matches a pending item, the pending item is replaced in
place: it keeps its ID and queue position but adopts the newest candidate's
text and a fresh `dueAt`. A `merged` / `coalesced` diagnostic records the
replacement. Use coalescing for progress updates where only the latest value
matters.
## Capacity and eviction
The queue is bounded by `maxQueueSize`, a positive integer validated at
construction. When a new candidate arrives at a full queue, the scheduler
chooses a victim rather than growing: if any polite-channel candidate is
involved, only polite candidates are eligible for eviction, which shields
assertive output. Among the pool, the scheduler drops the lowest
`capacityPriority` (`status` before `content`) and then the oldest sequence.
If the new candidate itself is the victim, `schedule` returns `undefined` and
records a `cancelled` / `queue-capacity` diagnostic.
`cancelScope(scope)` removes every pending candidate tagged with that scope,
for example when a response, tool, run, or step ends and its follow-up
output is no longer relevant. `cancelPurposes(purposes, reason?)` removes only
queued candidates whose `purpose` (defaulting to `"notice"`) appears in the
list, with the reason defaulting to `"scope-cancelled"`. Both emit one
diagnostic per cancelled candidate. Already delivered output cannot be
retracted by either method.
## Diagnostics
Attach `onDiagnostic` to observe scheduler decisions without affecting them.
Every decision carries a disposition (`queued`, `announced`, `merged`,
`suppressed`, `cancelled`), a reason (such as `scheduled`, `coalesced`,
`duplicate`, `queue-capacity`, `scope-cancelled`, `delivery-error`, or
`runtime-disposed`), a timestamp from the injected clock, and, when relevant, a
content-free announcement projection plus the correlation IDs and timing
fields of the item involved.
`getDiagnosticSnapshot()` returns a frozen projection of the current pending
queue in due-time order. It is deliberately content-free: no text,
dedupe keys, or coalesce keys are exposed, so it is safe to log or render.
Diagnostic delivery is best-effort and budgeted. The scheduler drains
queued diagnostics with a budget of at least 16 entries (scaling with
`maxQueueSize`); if diagnostics are produced faster than they drain, the excess
is aggregated into a single `suppressed` / `queue-capacity` diagnostic with a
count. An `onDiagnostic` listener that throws cannot alter scheduling: the
error is swallowed.
## Error semantics
Construction validates its timing and capacity values up front:
`minimumGapMs` and `dedupeWindowMs` must be finite non-negative numbers,
and `maxQueueSize` must be a positive integer; violations throw a
`RangeError`. `schedule` throws a `RangeError` when `delayMs` is negative or
non-finite, and silently ignores candidates with blank text.
Delivery failures are contained. If `onAnnouncement` throws, the failed
announcement is suppressed with a `delivery-error` diagnostic and your
`onDeliveryError` observer is notified; an observer that throws is swallowed so
it cannot strand the remaining queue. A scheduler whose `onAnnouncement`
always throws keeps its queue moving: every queued item is attempted once, in
due order, regardless of earlier failures.
## Testing with a manual clock
Pair the scheduler with `ManualClock` from `@generative-a11y/core` to test
pacing deterministically. Advance the clock instead of waiting, and assert on
the announcements your `onAnnouncement` listener collects.
```typescript title="scheduler.test.ts"
import { createScheduler, ManualClock } from "@generative-a11y/core";
const clock = new ManualClock(0);
const announced: string[] = [];
const scheduler = createScheduler({
clock,
minimumGapMs: 1000,
dedupeWindowMs: 5_000,
maxQueueSize: 8,
onAnnouncement: (intent) => announced.push(intent.text),
});
scheduler.schedule({
channel: "polite",
text: "First update.",
sourceType: "response.started",
});
scheduler.schedule({
channel: "polite",
text: "Second update.",
sourceType: "response.text.delta",
});
// Nothing delivered yet: the timer waits on the manual clock.
clock.advanceBy(1);
console.log(announced); // ["First update."]
clock.advanceBy(1000);
console.log(announced); // ["First update.", "Second update."]
scheduler.dispose();
```
---
# Intents and diagnostics
Inspect prepared announcements and the runtime decisions that produced them.
Canonical: https://generativea11y.com/api/core/diagnostics
Markdown: https://generativea11y.com/markdown/api/core/diagnostics
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## AnnouncementIntent
An AnnouncementIntent describes an update prepared by core. It does not confirm
that the browser delivered it or that a screen reader spoke it.
```ts title="Inspect prepared announcements"
import { createRuntime } from "@generative-a11y/core";
const runtime = createRuntime({
onAnnouncement: (intent) => console.log(intent.sourceType, intent.channel),
onDiagnostic: (diagnostic) => console.log(diagnostic.reason),
});
// Call runtime.dispose() when inspection ends.
```
### Intent fields
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| id | ` string ` | yes | | Unique scheduled output identity. |
| at | ` number ` | yes | | Injected clock timestamp at delivery. |
| channel | ` polite \| assertive ` | yes | | Requested urgency for the delivery layer. |
| text | ` string ` | yes | | Translated text with normalized whitespace. |
| sourceType | ` event type ` | yes | | Identifies the app event that caused this intent. |
| responseId / toolId / interactionId / runId / runInstanceId / stepId / stepInstanceId | ` string ` | no | ` undefined ` | Optional source lifecycle correlation. |
## AnnouncementDiagnostic
Diagnostics record runtime decisions for tests and telemetry. Listener failures
do not change runtime behavior. Repeated queue-limit decisions can share one
diagnostic with a count.
| Disposition | Typical reasons | Meaning |
| --- | --- | --- |
| queued | scheduled | Candidate entered the scheduler |
| merged | coalesced | Pending equivalent work was replaced |
| suppressed | duplicate, policy-silent, stale-response, stale-run, stale-step, partial-identity | Policy or identity prevented output |
| cancelled | scope-cancelled, runtime-disposed | Pending work became invalid |
| announced | delivered, delivery-error | Listeners accepted output or every attempt failed |
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| disposition | ` DiagnosticDisposition ` | yes | | High-level outcome category. |
| reason | ` DiagnosticReason ` | yes | | Stable machine-readable explanation for the decision. |
| count | ` number ` | no | ` undefined ` | Number of equivalent decisions represented by an aggregated diagnostic. |
## Versioned runtime observability
subscribeDiagnosticEvents emits each normalized source event before the
decisions caused by that dispatch. getDiagnosticSnapshot returns current
lifecycle and queue timing without response text, labels, errors, scopes,
deduplication keys, or timer handles.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| RuntimeDiagnosticEventV1 | ` event-observed \| decision ` | no | | Event. Schema-versioned ordered diagnostic event with injected time and a monotonic sequence. |
| RuntimeDiagnosticSnapshotV1 | ` immutable object ` | no | | Snapshot. Content-free response, tool, run, identified step, pending announcement, and response flush state. |
| pending.announcements | ` readonly DiagnosticPendingAnnouncement[] ` | no | ` [] ` | Snapshot field. Stable correlation, channel, source, scheduling, due-time, delay, and queue sequence fields ordered by due time. |
| runs | ` readonly DiagnosticRunSnapshot[] ` | no | ` undefined ` | Content-free run attempts with explicit hierarchy, status, and identified step counts. Optional for schema-version compatibility. |
| steps | ` readonly DiagnosticStepSnapshot[] ` | no | ` undefined ` | Content-free identified step attempts with explicit hierarchy, status, start time, and progress bucket. Optional for schema-version compatibility. |
**Evidence and testing note**
Runtime diagnostics explain library behavior. They do not prove DOM delivery or
screen-reader speech.
---
# @generative-a11y/core/testing
Record events, replay fixtures, and assert deterministic runtime output.
Canonical: https://generativea11y.com/api/core/testing
Markdown: https://generativea11y.com/markdown/api/core/testing
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## ManualClock and createRecorder
ManualClock controls time without global timers. createRecorder bundles that
clock with a runtime plus announcement and diagnostic transcripts.
```typescript title="accessibility.test.ts"
import { createRecorder } from "@generative-a11y/core";
const recorder = createRecorder({
preset: "balanced",
startAt: 10_000,
});
recorder.runtime.dispatch({
type: "response.started",
responseId: "r1",
});
recorder.clock.runUntilIdle();
```
The recorder owns its runtime and clock. `runUntilIdle()` advances only that
clock; dispose `recorder.runtime` after the test.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| new ManualClock(startAt) | ` ManualClock ` | no | ` 0 ` | Constructor. Creates an injected clock at the supplied finite timestamp. |
| ManualClock.now() | ` number ` | no | | Method. Returns the current manual timestamp. |
| ManualClock.setTimeout(callback, delayMs) | ` ClockTimer ` | no | | Method. Schedules a callback in stable time and insertion order. |
| ManualClock.clearTimeout(timer) | ` void ` | no | | Method. Cancels a registered timer. |
| ManualClock.advanceBy(ms) | ` void ` | no | | Method. Advances time by a finite non-negative duration and runs due callbacks. |
| ManualClock.advanceTo(time) | ` void ` | no | | Method. Advances to an absolute time without allowing time to move backward. |
| ManualClock.runNext() | ` boolean ` | no | | Method. Runs the next pending callback and reports whether one existed. |
| ManualClock.runUntilIdle(maxTasks) | ` void ` | no | ` 10,000 ` | Method. Runs pending callbacks until idle and throws before exceeding the safety limit. |
| ManualClock.pendingCount() | ` number ` | no | | Method. Returns the number of callbacks still registered. |
| createRecorder(options?) | ` Recorder ` | no | ` {} ` | Function. Creates a runtime, ManualClock, independent mutable transcript copies, and clear method. |
## recordRuntime and replayEvents
Recording captures accepted events sent through the returned dispatch target.
Replay validates the full fixture before dispatching any event and advances the
supplied ManualClock in recorded order.
```typescript title="Replay a recorded lifecycle"
import { ManualClock, createRuntime } from "@generative-a11y/core";
import { recordRuntime, replayEvents } from "@generative-a11y/core/testing";
const clock = new ManualClock(0);
const runtime = createRuntime({ clock });
const recording = recordRuntime({ runtime, clock });
recording.runtime.dispatch({
type: "response.started",
responseId: "report",
});
const fixture = recording.fixture();
const replayClock = new ManualClock(fixture.startAt);
const replayRuntime = createRuntime({ clock: replayClock });
replayEvents(replayRuntime, replayClock, fixture);
runtime.dispose();
replayRuntime.dispose();
```
Only dispatches through `recording.runtime` enter the fixture. Times are
relative and non-negative; tied entries keep array order. `replayEvents`
advances the clock before each dispatch but does not run it until idle.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| recordRuntime({ runtime, clock }) | ` RuntimeRecording ` | no | | Function. Returns a dispatch target plus immutable events, fixture, and clear methods. |
| RuntimeRecording.events() | ` readonly RecordedEvent[] ` | no | ` [] ` | Method. Returns frozen copies of accepted normalized events with relative timestamps. |
| RuntimeRecording.fixture() | ` ReplayFixtureV1 ` | no | | Method. Builds a validated frozen fixture from the current recording. |
| RuntimeRecording.clear() | ` void ` | no | | Method. Removes recorded events without changing the target runtime or clock. |
| ReplayFixtureV1 | ` { format, version, startAt, events } ` | no | | Type. Defines the versioned JSON envelope and ordered recorded events used by replay. |
| createReplayFixture(events, options?) | ` ReplayFixtureV1 ` | no | ` startAt: 0 ` | Function. Validates and freezes a versioned local replay fixture. |
| replayEvents(runtime, clock, fixture) | ` void ` | no | | Function. Validates the fixture, advances ManualClock, and dispatches each copied event. |
| matchesPartial(actual, expected) | ` boolean ` | no | | Function. Compares expected top-level semantic fields with an announcement or diagnostic object. |
## Opt-in Vitest matchers
Import @generative-a11y/core/testing only in Vitest setup. The root package
entry has no Vitest runtime import.
```typescript title="Vitest matcher assertion"
import { expect } from "vitest";
import { installVitestMatchers } from "@generative-a11y/core/testing";
const accessibilityExpect = installVitestMatchers(expect);
recorder.runtime.dispatch({
type: "response.text.delta",
responseId: "r1",
delta: "Your answer is ready.",
});
recorder.runtime.dispatch({ type: "response.completed", responseId: "r1" });
recorder.clock.runUntilIdle();
accessibilityExpect(recorder).toHaveAnnounced({
sourceType: "response.completed",
});
```
Register matchers once in your Vitest setup. Partial expectations let each test
assert only the semantic fields it needs.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| toHaveAnnouncementTranscript(expected) | ` matcher ` | no | | Vitest. Checks ordered announcement output with partial semantic fields. |
| toHaveAnnounced(expected) | ` matcher ` | no | | Vitest. Checks that at least one announcement matches the expected fields. |
| toHaveDiagnostic(expected) | ` matcher ` | no | | Vitest. Checks that at least one runtime diagnostic matches the expected fields. |
## Validation and evidence limits
Replay rejects unsupported formats, versions, event types, backward times,
malformed workflow identity, and lifecycle events without required IDs before
dispatch. Run and step attempt boundaries remain in recorded fixtures. A passing
transcript confirms deterministic core output. It does not prove browser
delivery or screen-reader speech.
## Public declarations: @generative-a11y/core/testing
Import from `@generative-a11y/core/testing`. Direct declarations from the source checkout; transitive upstream types and behavioral contracts require the linked guides and upstream documentation.
### A11yExpect (type)
```typescript
interface A11yExpect {
(received: unknown): A11yMatchers;
}
```
### A11yMatchers (type)
```typescript
interface A11yMatchers {
toHaveAnnouncementTranscript(expected: readonly Partial[]): void;
toHaveAnnounced(expected: Partial): void;
toHaveDiagnostic(expected: Partial): void;
}
```
### AnnouncementExpectation (type)
```typescript
type AnnouncementExpectation = Partial;
```
### createReplayFixture (value)
```typescript
declare function createReplayFixture(events: readonly RecordedEvent[], options?: ReplayFixtureOptions): ReplayFixtureV1;
```
### DiagnosticExpectation (type)
```typescript
type DiagnosticExpectation = Partial;
```
### installVitestMatchers (value)
```typescript
declare function installVitestMatchers(expect: {
extend(matchers: Record): void;
}): A11yExpect;
```
### matchesPartial (value)
```typescript
declare function matchesPartial(actual: object, expected: object): boolean;
```
### RecordedEvent (type)
```typescript
interface RecordedEvent {
readonly at: number;
readonly event: RuntimeEvent;
}
```
### recordRuntime (value)
```typescript
declare function recordRuntime(options: RecordRuntimeOptions): RuntimeRecording;
```
### RecordRuntimeOptions (type)
```typescript
interface RecordRuntimeOptions {
readonly runtime: Pick;
readonly clock: Pick;
}
```
### replayEvents (value)
```typescript
declare function replayEvents(runtime: Pick, clock: ManualClock, fixture: ReplayFixtureV1): void;
```
### ReplayFixtureOptions (type)
```typescript
interface ReplayFixtureOptions {
readonly startAt?: number;
}
```
### ReplayFixtureV1 (type)
```typescript
interface ReplayFixtureV1 {
readonly format: "generative-a11y/replay";
readonly version: 1;
readonly startAt: number;
readonly events: readonly RecordedEvent[];
}
```
### RuntimeRecording (type)
```typescript
interface RuntimeRecording {
readonly runtime: Pick;
events(): readonly RecordedEvent[];
fixture(): ReplayFixtureV1;
clear(): void;
}
```
### toHaveAnnounced (value)
```typescript
declare function toHaveAnnounced(received: unknown, expected: Partial): MatcherResult;
```
### toHaveAnnouncementTranscript (value)
```typescript
declare function toHaveAnnouncementTranscript(received: unknown, expected: readonly Partial[]): MatcherResult;
```
### toHaveDiagnostic (value)
```typescript
declare function toHaveDiagnostic(received: unknown, expected: Partial): MatcherResult;
```
### TranscriptRecorder (type)
```typescript
interface TranscriptRecorder {
transcript(): readonly AnnouncementIntent[];
diagnosticTranscript(): readonly AnnouncementDiagnostic[];
}
```
Recorder transcript readers return mutable copies that cannot modify recorded
history. `clear()` removes recorded entries only; use a new recorder to reset
runtime state and clock time for a separate test.
---
# @generative-a11y/dom
Deliver announcements and connect focus, attention, and preference helpers.
Canonical: https://generativea11y.com/api/dom
Markdown: https://generativea11y.com/markdown/api/dom
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Install browser delivery
DOM uses core without depending on React or an AI framework.
```shell title="Terminal"
npm install @generative-a11y/core @generative-a11y/dom
```
Core prepares announcement intents; DOM delivers them with `ariaNotify` when
available and hidden live regions as a fallback. See
[bindRuntime](/api/dom/bind-runtime) for connection and cleanup.
## Public export map
Choose direct announcing or bind an existing runtime.
| Category | Exports | Reference |
| --- | --- | --- |
| Delivery | createAnnouncer | [/api/dom/create-announcer](/api/dom/create-announcer) |
| Runtime binding | bindRuntime | [/api/dom/bind-runtime](/api/dom/bind-runtime) |
| Focus | captureFocus, focusElement, restoreFocus | [/api/dom/focus](/api/dom/focus) |
| Attention | createAttentionStore | [/api/dom/attention](/api/dom/attention) |
| Preferences | createPreferenceStore and mapping helpers | [/api/dom/preferences](/api/dom/preferences) |
## Public declarations: @generative-a11y/dom
Import from `@generative-a11y/dom`. Direct declarations from the source checkout; transitive upstream types and behavioral contracts require the linked guides and upstream documentation.
### Announcer (type)
```typescript
interface Announcer {
announce(intent: AnnouncementIntent): DeliveryResult;
getRegions(): LiveRegions | undefined;
dispose(): void;
}
```
### AnnouncerOptions (type)
```typescript
interface AnnouncerOptions {
document?: Document;
mode?: DeliveryMode;
regions?: LiveRegions;
onDelivery?: (result: DeliveryResult) => void;
}
```
### AttentionBinding (type)
```typescript
interface AttentionBinding {
dispose(): void;
}
```
### AttentionBindingOptions (type)
```typescript
interface AttentionBindingOptions {
readonly runtime: Runtime;
readonly attentionStore: AttentionStore;
}
```
### AttentionIntersectionObserver (type)
```typescript
interface AttentionIntersectionObserver {
observe(target: Element): void;
unobserve(target: Element): void;
disconnect(): void;
}
```
### AttentionIntersectionObserverFactory (type)
```typescript
type AttentionIntersectionObserverFactory = (callback: IntersectionObserverCallback, options?: IntersectionObserverInit) => AttentionIntersectionObserver;
```
### AttentionSnapshot (type)
```typescript
interface AttentionSnapshot {
readonly visibility: "visible" | "hidden" | "unknown";
readonly windowFocus: "focused" | "blurred" | "unknown";
readonly focusArea: "composer" | "conversation" | "elsewhere" | "none" | "unknown";
readonly newestResponse: "visible" | "outside" | "unobserved" | "unknown";
readonly mode: "foreground" | "background" | "reading-history" | "away" | "unknown";
}
```
### AttentionStore (type)
```typescript
interface AttentionStore extends ExternalStore {
registerComposer(element: Element): () => void;
registerConversation(element: Element): () => void;
registerNewestResponse(element: Element): () => void;
dispose(): void;
}
```
### AttentionStoreOptions (type)
```typescript
interface AttentionStoreOptions {
document?: Document;
createIntersectionObserver?: AttentionIntersectionObserverFactory;
intersectionObserverInit?: IntersectionObserverInit;
}
```
### bindAttention (value)
```typescript
/** Borrow a store and runtime, forwarding observations without changing overrides. */
declare function bindAttention({ runtime, attentionStore, }: AttentionBindingOptions): AttentionBinding;
```
### bindRuntime (value)
```typescript
declare function bindRuntime(runtime: Runtime, options?: AnnouncerOptions): RuntimeBinding;
```
### captureFocus (value)
```typescript
declare function captureFocus(selectedDocument?: Document): FocusCapture;
```
### CorePreferenceConfiguration (type)
```typescript
interface CorePreferenceConfiguration {
readonly preset: PresetName;
readonly policy?: PolicyOverrides;
}
```
### createAnnouncer (value)
```typescript
declare function createAnnouncer(options?: AnnouncerOptions): Announcer;
```
### createAttentionStore (value)
```typescript
declare function createAttentionStore(options?: AttentionStoreOptions): AttentionStore;
```
### createPreferenceStore (value)
```typescript
declare function createPreferenceStore(options?: PreferenceStoreOptions): PreferenceStore;
```
### defaultPreferences (value)
```typescript
declare const defaultPreferences: PreferenceSchemaV1;
```
### DeliveryMode (type)
```typescript
type DeliveryMode = "auto" | "live-region";
```
### DeliveryResult (type)
```typescript
interface DeliveryResult {
status: "notified" | "mutated" | "unavailable" | "disposed";
method: "aria-notify" | "live-region" | "none";
channel: AnnouncementIntent["channel"];
announcementId: string;
sourceType: AnnouncementIntent["sourceType"];
at: number;
sourceEventId?: string;
responseId?: string;
toolId?: string;
interactionId?: string;
/** Stable logical run identity associated with the delivered intent. */
runId?: string;
/** Stable run attempt identity associated with the delivered intent. */
runInstanceId?: string;
/** Stable logical step identity associated with the delivered intent. */
stepId?: string;
/** Stable step attempt identity associated with the delivered intent. */
stepInstanceId?: string;
error?: {
name: string;
message: string;
};
}
```
### ExternalStore (type)
```typescript
interface ExternalStore {
subscribe(listener: () => void): () => void;
getSnapshot(): T;
getServerSnapshot(): T;
}
```
### FocusCapture (type)
```typescript
interface FocusCapture {
readonly document: Document | null;
readonly target: Element | null;
}
```
### focusElement (value)
```typescript
declare function focusElement(target: Element, options?: FocusElementOptions): FocusResult;
```
### FocusElementOptions (type)
```typescript
interface FocusElementOptions {
preventScroll?: boolean;
}
```
### FocusResult (type)
```typescript
type FocusResult = {
readonly status: "focused";
readonly target: Element;
} | {
readonly status: "skipped";
readonly reason: FocusSkippedReason;
readonly target: Element | null;
};
```
### FocusSkippedReason (type)
```typescript
type FocusSkippedReason = "unavailable" | "cross-document" | "disconnected" | "disabled" | "hidden" | "aria-hidden" | "inert" | "missing-focus" | "guard-mismatch" | "focus-error" | "focus-not-applied";
```
### LiveRegions (type)
```typescript
interface LiveRegions {
polite: HTMLElement;
assertive: HTMLElement;
}
```
### normalizePreferences (value)
```typescript
declare function normalizePreferences(value: PreferenceSchemaV1): PreferenceSchemaV1;
```
### PreferenceDiagnostic (type)
```typescript
interface PreferenceDiagnostic {
readonly source: PreferenceDiagnosticSource;
readonly code: PreferenceDiagnosticCode;
readonly error?: Readonly<{
name: string;
message: string;
}>;
}
```
### PreferenceDiagnosticCode (type)
```typescript
type PreferenceDiagnosticCode = "operation-failed" | "invalid-json" | "invalid-preference" | "unsupported-version";
```
### PreferenceDiagnosticSource (type)
```typescript
type PreferenceDiagnosticSource = "storage-read" | "storage-write" | "storage-event" | "event-subscribe" | "event-unsubscribe";
```
### PreferencePersistence (type)
```typescript
interface PreferencePersistence {
readonly key: string;
readonly storage?: PreferenceStorage;
readonly events?: PreferenceStorageEventSource;
}
```
### PreferenceSchemaV1 (type)
```typescript
type PreferenceSchemaV1 = Readonly<{
version: 1;
preset: "completion-only";
}> | Readonly<{
version: 1;
preset: "minimal" | "balanced" | "verbose";
streaming: StreamingVerbosity;
tools: ToolVerbosity;
}>;
```
### preferencesToCoreConfiguration (value)
```typescript
declare function preferencesToCoreConfiguration(value: PreferenceSchemaV1): CorePreferenceConfiguration;
```
### PreferenceStorage (type)
```typescript
interface PreferenceStorage {
getItem(key: string): string | null;
setItem(key: string, value: string): void;
}
```
### PreferenceStorageEvent (type)
```typescript
interface PreferenceStorageEvent {
readonly key: string | null;
readonly newValue: string | null;
readonly storageArea?: PreferenceStorage | null;
}
```
### PreferenceStorageEventSource (type)
```typescript
interface PreferenceStorageEventSource {
subscribe(listener: (event: PreferenceStorageEvent) => void): () => void;
}
```
### PreferenceStore (type)
```typescript
interface PreferenceStore extends ExternalStore {
setPreferences(value: PreferenceSchemaV1): void;
dispose(): void;
}
```
### PreferenceStoreOptions (type)
```typescript
interface PreferenceStoreOptions {
readonly defaultValue?: PreferenceSchemaV1;
readonly persistence?: PreferencePersistence;
readonly onDiagnostic?: (diagnostic: PreferenceDiagnostic) => void;
}
```
### restoreFocus (value)
```typescript
declare function restoreFocus(capture: FocusCapture, options?: RestoreFocusOptions): FocusResult;
```
### RestoreFocusOptions (type)
```typescript
interface RestoreFocusOptions extends FocusElementOptions {
onlyIfFocusWithin?: Element;
}
```
### RuntimeBinding (type)
```typescript
interface RuntimeBinding {
announcer: Announcer;
dispose(): void;
}
```
### samePreferences (value)
```typescript
declare function samePreferences(left: PreferenceSchemaV1, right: PreferenceSchemaV1): boolean;
```
### StreamingVerbosity (type)
```typescript
type StreamingVerbosity = "preset" | "off" | "completion" | "paragraph" | "sentence";
```
### ToolVerbosity (type)
```typescript
type ToolVerbosity = "preset" | "off" | "failures" | "status" | "progress";
```
---
# createAnnouncer
Deliver announcements through ariaNotify with a live-region fallback.
Canonical: https://generativea11y.com/api/dom/create-announcer
Markdown: https://generativea11y.com/markdown/api/dom/create-announcer
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Signature and import
auto mode attempts ariaNotify when available, then falls back to the selected
polite or assertive live region.
```typescript title="announcer.ts"
import { createAnnouncer } from "@generative-a11y/dom";
const announcer = createAnnouncer({
onDelivery(result) {
console.log(result.status, result.method);
},
});
const result = announcer.announce(intent);
// Call announcer.dispose() when the owning surface is removed.
```
`auto` also falls back if `ariaNotify` throws. `DeliveryResult` describes the
browser action; disposing the announcer removes only regions it created.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| options | ` AnnouncerOptions ` | no | ` {} ` | Selects document, delivery mode, supplied regions, and diagnostic observation. |
| return | ` Announcer ` | no | | Return. Owned announcer with announce, getRegions, and dispose methods. |
## AnnouncerOptions
Supplying regions transfers neither node ownership nor removal responsibility to
the library.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| document | ` Document ` | no | ` global document ` | Document used to create live regions. Without a document, the announcer remains inert and reports unavailable. |
| mode | ` auto \| live-region ` | no | ` "auto" ` | Selects progressive enhancement or a forced test path. |
| regions | ` LiveRegions ` | no | ` owned regions ` | Supplies stable polite and assertive elements. Both must belong to the same document. |
| onDelivery | ` (result) => void ` | no | ` undefined ` | Observes each delivery attempt. Callback failures cannot alter delivery. |
The document is resolved in a fixed order: the explicit `document` option
first, then the owner document of the supplied polite region, then the global
document. An invalid `mode` throws a `TypeError` immediately, before any region
is created or validated.
## Delivery pipeline
### Use progressive delivery
In `auto` mode, `announce` tries `ariaNotify` first. It reads `ariaNotify` off
the live region element for the intent's channel and calls it with the intent
text and a priority: `high` for assertive intents, `normal` for polite ones.
When the call returns without throwing, the result is `notified` via
`aria-notify`.
Two fallback paths lead to the live region. If the element has no `ariaNotify`
function, delivery skips straight to mutating the region. If `ariaNotify`
throws, the error is serialized into the result, a latch disables `ariaNotify`
for all later announcements, and delivery falls back to the region as well.
Because of the latch, one failing browser means subsequent announcements skip
the `ariaNotify` attempt entirely instead of throwing on every message.
`mode: "live-region"` skips the `ariaNotify` attempt altogether. Use it as a
forced test path when you want deterministic region-text assertions:
```typescript title="announcer.test.ts"
const announcer = createAnnouncer({ mode: "live-region" });
const result = announcer.announce(intent);
expect(result).toMatchObject({ status: "mutated", method: "live-region" });
expect(announcer.getRegions()?.[intent.channel].textContent).toBe(
intent.text,
);
```
### Observe the attempt
Every `announce` call reports through `onDelivery` synchronously, including
`unavailable` and `disposed` results. The callback is purely observational:
exceptions thrown inside it are swallowed and cannot alter delivery. Use it to
log the status and method per announcement, or to count how often the
`ariaNotify` path succeeds in the browsers your users run.
```typescript title="delivery-logging.ts"
const announcer = createAnnouncer({
onDelivery: (result) => {
if (result.status === "mutated" && result.error) {
console.warn("ariaNotify failed, fell back to live region:", result.error);
}
},
});
```
The `error` field is only set when `ariaNotify` threw, so this logs exactly
the fallback cases without noise from the normal live-region path.
### Release owned nodes
Call `dispose()` when the owning surface is removed. Disposal is idempotent.
It removes the polite and assertive regions only when the announcer created
them; regions you supplied stay in the document. After disposal, `announce`
returns a `disposed` result without touching the document.
## DeliveryResult
announce returns one result synchronously.
| Status | Method | Meaning |
| --- | --- | --- |
| notified | aria-notify | ariaNotify returned without throwing |
| mutated | live-region | Selected stable region text changed |
| unavailable | none | No usable document or region exists |
| disposed | none | announce was called after disposal |
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channel | ` polite \| assertive ` | yes | | Intent channel selected for this attempt. |
| announcementId | ` string ` | yes | | Stable ID copied from the AnnouncementIntent for diagnostic correlation. |
| sourceType | ` RuntimeEvent['type'] ` | yes | | Event type that produced the announcement intent. |
| at | ` number ` | yes | | Injected-clock timestamp copied from the announcement intent. |
| sourceEventId | ` string ` | no | ` undefined ` | Application event ID when the source event supplied one. |
| responseId / toolId / interactionId | ` string ` | no | ` undefined ` | Entity IDs copied from the announcement intent when present. |
| runId / runInstanceId | ` string ` | no | ` undefined ` | Run and attempt IDs copied from the intent when present. |
| stepId / stepInstanceId | ` string ` | no | ` undefined ` | Step and attempt IDs copied from the intent when present. |
| error | ` { name, message } ` | no | ` undefined ` | Serializable ariaNotify failure information when fallback was needed. |
The `error` field is only present when `ariaNotify` threw and delivery fell
back to the live region. `intent.locale`, when defined, sets the `lang`
attribute on the region before delivery; an undefined locale removes it.
## Supplied regions
When you pass `regions`, they are validated before anything else is created. A
violation throws a `TypeError`:
| Rule | Failure |
| --- | --- |
| Polite and assertive must be distinct elements | Passing the same element twice throws. |
| Both must be connected to the document | Detached elements throw. |
| Neither may contain the other | Nested regions throw. |
| Both must belong to the same document | Regions from different documents throw. |
| Both must belong to the provided document | A document option that disagrees with the regions throws. |
Supplied regions are normalized the same way owned regions are. The announcer
sets `aria-live` to the channel, `aria-atomic="true"`,
`aria-relevant="additions text"`, and applies visually-hidden styling so the
regions are exposed to assistive technology without affecting layout. It also
clears `role`, `aria-busy`, `hidden`, `aria-hidden`, and `inert` so a reused
container cannot accidentally silence itself.
```typescript title="supplied-regions.ts"
import { createAnnouncer } from "@generative-a11y/dom";
const announcer = createAnnouncer({
regions: {
polite: document.getElementById("sr-polite")!,
assertive: document.getElementById("sr-assertive")!,
},
});
```
## Owned regions
When you do not supply regions, the announcer creates its own pair. Each
region is a `div` appended to `document.body` (falling back to the document
element when there is no body), polite first and assertive second. Both are
normalized by the same configuration applied to supplied regions: the channel
as `aria-live`, `aria-atomic="true"`, `aria-relevant="additions text"`, and
visually-hidden styling that keeps the regions exposed to assistive
technology without affecting layout.
Owned regions are the only nodes `dispose()` removes. If your app also needs
visible status text, keep a separate element; the announcer regions are
exclusively a screen-reader channel and are hidden from sighted users by
design. Because the regions are appended at creation time, they sit after your
app's existing content in the DOM; their position does not affect announcement
behavior.
## Multiple announcers
Each `createAnnouncer` call is independent: it creates (or adopts) its own
region pair and its own `ariaNotify` latch. Two announcers on the same page do
not share state, and disposing one never touches the other's regions. Sharing
one region pair between two announcers via `options.regions` is allowed, but
each announcer normalizes the shared elements on creation, so prefer one
announcer per surface and dispose it with that surface.
## The inert announcer
When no document is available anywhere (no `document` option, no supplied
regions, no global document, as in server-side rendering), `createAnnouncer`
does not throw. It returns an inert announcer: `getRegions()` returns
`undefined` and every `announce` call reports `unavailable` with method `none`.
This makes SSR safe by default; create the announcer on the client or pass a
document explicitly.
## Common pitfalls
* **Expecting an error without a document.** The announcer stays inert and
reports `unavailable`. Check the result status in code that must run during
SSR.
* **Announcing after dispose.** `announce` returns a `disposed` result and
leaves the document alone. Do not retain the announcer past its owner.
* **Assuming `ariaNotify` runs everywhere.** It is progressive enhancement.
Browsers without it take the live-region path, and a throwing `ariaNotify`
disables itself after the first failure.
* **Reusing one element for both channels.** Passing the same element as
polite and assertive throws a `TypeError`.
* **Throwing inside `onDelivery`.** The error is swallowed. Keep the callback
side-effect free and handle logging failures outside it.
* **Reading regions before creation finishes.** `createAnnouncer` builds
regions synchronously, so `getRegions()` is populated immediately after the
call. There is no async setup step to wait for.
**Evidence and testing note**
A notified or mutated result confirms that the library updated the browser. Test
with a real screen reader to confirm what it speaks.
---
# bindRuntime
Connect a core runtime to browser announcement delivery.
Canonical: https://generativea11y.com/api/dom/bind-runtime
Markdown: https://generativea11y.com/markdown/api/dom/bind-runtime
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Signature and import
bindRuntime borrows your runtime. Disposing its binding removes only
subscription and announcer resources.
```typescript title="chat-accessibility.ts"
import { createRuntime } from "@generative-a11y/core";
import { bindRuntime } from "@generative-a11y/dom";
const runtime = createRuntime();
const delivery = bindRuntime(runtime, { mode: "auto" });
runtime.dispatch({ type: "response.started", responseId: "answer" });
// Call when the chat surface is removed.
export function disposeChat() {
delivery.dispose();
runtime.dispose();
}
```
Connect delivery before dispatching events. Dispose the delivery binding before
the runtime when removing the chat surface.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| runtime | ` Runtime ` | yes | | Supplies AnnouncementIntent objects while remaining under your app's control. |
| options | ` AnnouncerOptions ` | no | ` {} ` | Forwarded to the owned DOM announcer. An invalid mode throws a TypeError before the binding subscribes. |
| return | ` RuntimeBinding ` | no | | Return. Provides the announcer and an idempotent dispose function. |
## Disposal and ownership
The binding borrows the runtime; it never disposes it. Your app created the
runtime, so your app ends it. `dispose()` on the binding is idempotent: calling
it twice has no additional effect. Disposing from inside an `onDelivery`
callback is safe: the disposed flag stops any further forwarding, while the
in-flight announcement completes normally.
Disposal runs in a fixed order. The binding first unsubscribes its announcement
listener from the runtime, then disposes the owned announcer. The announcer
disposal runs inside a `finally` block, so the announcer is always released
even if unsubscribing throws. After disposal, the binding's internal guard also
stops forwarding intents, so a late dispatch can never reach a disposed
announcer.
Setup failure is cleaned up too. If `runtime.subscribeAnnouncements` throws
(for example, the runtime was already disposed), `bindRuntime` disposes the
announcer it just created and rethrows the original error. No live regions leak
from a failed bind.
The subscription callback also checks a disposed flag before forwarding. This
is a second layer of protection: even if an intent were somehow emitted after
`dispose()` ran, it would never reach the announcer. In practice the
unsubscribe removes the listener first, so the flag is a guard rather than the
primary mechanism.
## React usage
In React, create the runtime and the binding once inside an effect and dispose
both in the effect cleanup. A ref holds the binding for event handlers that
need the announcer outside the effect.
```tsx title="ChatSurface.tsx"
import { useEffect, useRef } from "react";
import { createRuntime } from "@generative-a11y/core";
import { bindRuntime, type RuntimeBinding } from "@generative-a11y/dom";
export function ChatSurface() {
const bindingRef = useRef(null);
useEffect(() => {
const runtime = createRuntime();
const delivery = bindRuntime(runtime, { mode: "auto" });
bindingRef.current = delivery;
return () => {
delivery.dispose();
runtime.dispose();
bindingRef.current = null;
};
}, []);
return ;
}
```
Creating the binding during render, or in an effect without cleanup, stacks a
new subscription and a new pair of live regions on every render. The effect
above runs once, and StrictMode's double-invocation is safe because the
cleanup disposes the first binding before the second effect run creates
another.
Ownership boundaries are strict:
* The runtime is never disposed by the binding. Dispose the binding first, then
the runtime.
* Live regions created by the announcer are removed when the binding is
disposed.
* Regions you supplied through `AnnouncerOptions` stay in the document. The
announcer never removes nodes it did not create.
## Walkthrough
### 1. Create the runtime
Create and configure the core runtime before connecting delivery. Policy,
messages, and any `onAnnouncement` listener belong to the core runtime; the
binding only adds browser delivery on top.
```ts title="runtime-setup.ts"
import { createRuntime } from "@generative-a11y/core";
const runtime = createRuntime({
onAnnouncement: (intent) => console.log(intent.text),
});
```
### 2. Connect browser delivery
Call `bindRuntime` once per chat surface. The options object is forwarded
unchanged to `createAnnouncer`, so `mode`, `document`, `regions`, and
`onDelivery` behave exactly as documented for the announcer.
```ts title="delivery-setup.ts"
import { bindRuntime } from "@generative-a11y/dom";
const delivery = bindRuntime(runtime, { mode: "auto" });
```
Two details matter here. First, an invalid `mode` throws a `TypeError`
immediately, before any subscription exists; there is no silent fallback to a
default mode. Second, `mode: "live-region"` forces the live-region path and is
the right choice for tests that assert on region text instead of relying on
`ariaNotify` availability.
Because options are forwarded unchanged, everything documented for
`createAnnouncer` applies: pass `document` to target a specific document (for
example an iframe's), `regions` to reuse existing live regions, and
`onDelivery` to observe each delivery. The binding adds no options of its own,
so there is nothing binding-specific to configure.
### 3. Dispatch events, then clean up in order
Dispatch `RuntimeEvent` objects as usual. Each announcement intent the runtime
produces flows to `announcer.announce` through the subscription, so
`onDelivery` observes every delivery the binding performs.
When the chat surface is removed, dispose the binding first and the runtime
second:
```ts title="teardown.ts"
export function disposeChat() {
delivery.dispose(); // unsubscribes, then disposes the owned announcer
runtime.dispose(); // ends scheduling; the runtime was never owned by the binding
}
```
Disposing the runtime first is not recommended. The binding would be left
holding a subscription on a dead runtime, and the owned announcer would stay in
the document until the binding is also disposed.
## Announcer access
The binding exposes the owned announcer, so you are not limited to
runtime-driven delivery. `delivery.announcer.announce(intent)` accepts a
manually built `AnnouncementIntent` for one-off messages, and
`delivery.announcer.getRegions()` returns the live regions for test assertions.
It returns undefined when the announcer is inert (no document available).
Disposing the binding disposes this announcer, so do not retain and use it
afterward: `announce` on a disposed announcer reports a `disposed` result
instead of touching the document.
A manual intent needs the required `AnnouncementIntent` fields: a stable `id`,
an `at` timestamp, a `channel`, the `text`, and the `sourceType` event name.
```typescript title="manual-announce.ts"
const result = delivery.announcer.announce({
id: "manual-1",
at: Date.now(),
channel: "polite",
text: "Your file finished uploading.",
sourceType: "response.completed",
});
```
## Testing delivery
Use `mode: "live-region"` so tests do not depend on `ariaNotify` availability.
Dispatch the events your feature produces, then assert on the region text for
the expected channel. Dispose the binding in test teardown so live regions
from one test cannot leak into the next.
```typescript title="delivery.test.ts"
import { createRuntime } from "@generative-a11y/core";
import { bindRuntime } from "@generative-a11y/dom";
test("streams status to the polite region", () => {
const runtime = createRuntime();
const deliveries: string[] = [];
const delivery = bindRuntime(runtime, {
mode: "live-region",
onDelivery: (result) => deliveries.push(`${result.status}:${result.method}`),
});
try {
runtime.dispatch({ type: "response.started", responseId: "answer" });
expect(deliveries).toContain("mutated:live-region");
expect(
delivery.announcer.getRegions()?.polite.textContent?.length,
).toBeGreaterThan(0);
} finally {
delivery.dispose();
runtime.dispose();
}
});
```
The exact text depends on your runtime messages and policy, so assert on the
channel selection and the delivery status rather than the full string. For
deterministic timing, pair the test with a `ManualClock` from
`@generative-a11y/core` instead of wall-clock dispatching.
## What the binding does not do
`bindRuntime` adds delivery and nothing else. It does not change runtime
policy, coalesce intents, or choose channels; the core runtime decides what is
announced and the binding only carries it to the browser. It forwards every
intent it receives without filtering or deduplicating: if the runtime emits
two intents, both are announced. It does not create a
document, so in server-side rendering the owned announcer is inert and reports
`unavailable` until a document exists. And it does not replay history: only
intents produced while the subscription is active are delivered.
## Common pitfalls
* **Dispatching before binding.** Intents produced before `bindRuntime` runs
have no delivery path. Connect delivery during setup, before the first
dispatch.
* **Binding on every render.** In React, create the binding once inside an
effect and dispose it in the effect cleanup. A binding per render stacks
duplicate subscriptions and duplicate live regions.
* **Forgetting disposal on route changes.** In a single-page app, a removed
chat surface without `delivery.dispose()` keeps its subscription alive, so a
later dispatch announces through a surface the user can no longer see.
* **Assuming the binding ends the runtime.** It does not. If the runtime is
never disposed, its scheduler and queue keep running after the binding is
gone.
* **Sharing one binding across surfaces.** A binding is tied to the announcer
it created. Two chat surfaces need two bindings, each disposed with its own
surface, so removing one surface does not silence the other.
* **Catching the mode TypeError too late.** Validate the mode in one place,
at startup. A typo like `"Live-Region"` throws on the first `bindRuntime`
call, which is easy to miss if binding happens lazily on user interaction.
## RuntimeBinding
dispose leaves app-supplied runtimes and live regions intact.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| announcer | ` Announcer ` | no | | Property. Owned announcer used for every runtime intent. |
| dispose() | ` void ` | no | | Method. Unsubscribes from the runtime and disposes the owned announcer. |
---
# Focus helpers
Helpers for capturing, moving, and restoring focus in dialogs and other app interactions.
Canonical: https://generativea11y.com/api/dom/focus
Markdown: https://generativea11y.com/markdown/api/dom/focus
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Capture and restore application focus
Call these helpers from dialogs and other interactions that your app controls.
Do not move focus for streaming text or routine status updates.
```typescript title="Restore focus after a dialog"
import { captureFocus, focusElement, restoreFocus } from "@generative-a11y/dom";
const capture = captureFocus(document);
const opened = focusElement(dialogHeading, { preventScroll: true });
// After the application-owned interaction closes:
const restored = restoreFocus(capture, {
onlyIfFocusWithin: dialog,
});
```
`captureFocus` records the active element without moving it. Choose a focusable
dialog target; `onlyIfFocusWithin` preserves the user’s new focus if they have
moved outside the dialog before it closes.
The helpers are shadow-DOM aware. Capture resolves the deep active element by
descending into shadow roots, and the eligibility checks walk the composed
tree, so `hidden`, `aria-hidden`, and `inert` on shadow hosts are honored.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| captureFocus(document) | ` FocusCapture ` | no | ` global document ` | Function. Captures the deep active element from the supplied document. |
| focusElement(element, options) | ` FocusResult ` | no | ` preventScroll: true ` | Function. Attempts focus and reports focused or a stable skipped reason. |
| options.preventScroll | ` boolean ` | no | ` true ` | Prevents scrolling when moving or restoring focus. |
| options.onlyIfFocusWithin | ` Element ` | no | ` undefined ` | Restoration guard. Skip restoration if current focus has left this element. |
| restoreFocus(capture, options) | ` FocusResult ` | no | | Function. Restores only when the captured target remains eligible and optional guards still match. |
| FocusCapture | ` { document, target } ` | no | | Frozen snapshot. `document` is the captured document (or null without one); `target` is the deep active element, or null when nothing restorable was focused. |
| FocusElementOptions | ` { preventScroll?: boolean } ` | no | | Options for focusElement. preventScroll defaults to true. |
| RestoreFocusOptions | ` { preventScroll?: boolean; onlyIfFocusWithin?: Element } ` | no | | Options for restoreFocus. Extends FocusElementOptions with the restoration guard. |
## The capture snapshot
`FocusCapture` is a frozen `{ document, target }` snapshot. It never changes
after creation, so a capture taken before a dialog opens stays valid while the
dialog is open, even as focus moves around.
The `target` is the deep active element at capture time: the helper descends
into shadow roots, so focus inside a web component is recorded as the inner
element, not the host. Three situations produce a null target, and all three
make `restoreFocus` report `skipped` with reason `unavailable`:
* No document exists (server-side rendering or a deleted global).
* `document.body` or the document element itself is focused. There is no
meaningful element to restore to.
* The document throws on property access. A hostile document is captured
without a restorable target instead of throwing.
The `document` field is null only when no document was available. Passing an
explicit document is the way to capture focus for an iframe or a secondary
document: `captureFocus(iframe.contentDocument)`. The default is the global
document when one exists.
## FocusResult
Results are explicit so applications can test focus workflows without guessing.
| Status | Meaning | Application response |
| --- | --- | --- |
| focused | Target became active | Continue the workflow |
| skipped | A documented eligibility check, browser failure, or restoration guard prevented focus | Preserve current focus and inspect reason |
### Skipped reasons
Every skip carries a stable `reason` string. Check `result.reason` in tests
instead of guessing why focus did not move.
| Reason | Meaning |
| --- | --- |
| unavailable | No usable document, element, or DOM access. Also used for hostile documents and property reads that throw. |
| cross-document | The captured target now belongs to a different document than the capture. |
| disconnected | Target is no longer connected to the document. |
| disabled | Target is disabled via the disabled attribute, the disabled property, or a `:disabled` selector match. |
| hidden | Target or a composed-tree ancestor has the hidden attribute. |
| aria-hidden | Target or a composed-tree ancestor has aria-hidden="true". |
| inert | Target or a composed-tree ancestor is inert. |
| missing-focus | Target has no callable focus() function. |
| guard-mismatch | The onlyIfFocusWithin guard failed: the guard is in another document, nothing is focused, or focus is outside the guard. |
| focus-error | focus() threw, or the active element could not be read afterward. The previous focus is restored on a best-effort basis. |
| focus-not-applied | focus() returned without throwing, but the element did not become the active element. |
## Walkthrough
### Capture current focus
Call `captureFocus` before the dialog opens, while the user's original focus
is still in place. The returned snapshot is frozen: `{ document, target }`.
`target` is the deep active element, so focus inside a web component's shadow
root is captured correctly. When `document.body` or the document element
itself is focused, or when no document exists, `target` is null and
`restoreFocus` later reports `skipped` with reason `unavailable`.
```ts title="capture-before-open.ts"
const capture = captureFocus(document);
openDialog(dialog);
```
Capture is defensive. A hostile document that throws on property access is
captured without a restorable target instead of throwing.
### Focus the dialog
Move focus to a target your app controls, such as the dialog heading with
`tabindex="-1"`. `focusElement` runs the eligibility checks first and only
then calls `focus({ preventScroll: true })` by default, so the page does not
jump on long documents.
```ts title="focus-dialog.ts"
const opened = focusElement(dialogHeading, { preventScroll: true });
if (opened.status === "skipped") {
console.warn("Dialog focus skipped:", opened.reason);
}
```
Always inspect the result. A `skipped` result tells you exactly why focus did
not move, which is the difference between a flaky dialog and a testable one.
### Restore when appropriate
After the interaction closes, restore the captured focus. The
`onlyIfFocusWithin` guard keeps the user's new focus when they have already
moved outside the dialog before it closed, which is the polite behavior for
modeless surfaces.
```ts title="restore-after-close.ts"
const restored = restoreFocus(capture, { onlyIfFocusWithin: dialog });
```
`restoreFocus` revalidates everything: the capture is read defensively, a
cross-document target is rejected, the guard is checked against the current
deep active element, and the final move goes through the same eligibility
checks as `focusElement`.
## Eligibility checks
`focusElement` checks eligibility before calling `focus()`, and checks again
afterward. The pre-checks run in this order: unavailable (no owner document,
not a real element, or DOM access throws), disconnected, disabled, hidden,
aria-hidden, inert, and missing-focus. Hidden, aria-hidden, and inert are
evaluated up the composed tree, so attributes on shadow hosts and slot
ancestors count.
If `focus()` throws, the helper attempts a best-effort rollback: it restores
the previously focused element with `preventScroll: true`, but only when the
previous element is still eligible and the failed target actually received
focus. The result is `skipped` with reason `focus-error`. When `focus()`
returns but the element never became active, the result is `skipped` with
reason `focus-not-applied`.
The composed-tree walk is what makes the checks shadow-DOM correct. Instead of
only looking at `parentElement`, the walk follows assigned slots and shadow
hosts, so `hidden` on a slot ancestor or `inert` on a custom element host is
detected. Cycles are guarded with a visited set: a cyclic tree reports
`unavailable` rather than hanging.
## Testing focus workflows
Because every outcome is a plain object, focus workflows are straightforward
to test in jsdom or a real browser. Assert on `status` for the happy path and
on `reason` for the guarded paths.
```typescript title="dialog-focus.test.ts"
import {
captureFocus,
focusElement,
restoreFocus,
} from "@generative-a11y/dom";
test("restores focus after the dialog closes", () => {
const trigger = document.getElementById("open-dialog")!;
trigger.focus();
const capture = captureFocus(document);
const dialog = document.getElementById("dialog")!;
const heading = dialog.querySelector("h2")!;
expect(focusElement(heading)).toMatchObject({ status: "focused" });
// The dialog closed with focus still inside it, so the guard passes and
// focus returns to the trigger.
const restored = restoreFocus(capture, { onlyIfFocusWithin: dialog });
expect(restored).toMatchObject({ status: "focused", target: trigger });
});
test("skips restoration when the trigger was removed", () => {
const trigger = document.getElementById("open-dialog")!;
trigger.focus();
const capture = captureFocus(document);
trigger.remove();
const restored = restoreFocus(capture);
expect(restored).toMatchObject({ status: "skipped", reason: "disconnected" });
});
```
Note the second test: removing the trigger makes restoration skip with reason
`disconnected` instead of throwing or moving focus somewhere unexpected. That
is the behavior to rely on, not to work around.
## Common pitfalls
* **Capturing after the dialog opens.** Capture first. A capture taken after
opening records an element inside the dialog, and restoring it after the
dialog is removed skips with reason `disconnected`.
* **Restoring into a removed trigger.** If the originally focused element was
removed from the DOM while the dialog was open, restoration skips as
`disconnected`. Leave focus where it is or choose a fallback target.
* **Moving focus for streaming updates.** These helpers are for
application-owned interactions like dialogs. Streaming text and routine
status updates should use announcements, not focus moves.
* **Ignoring the result.** `focusElement` and `restoreFocus` never throw for
eligibility problems; they report. Branch on `status` and log `reason`
instead of assuming focus moved.
---
# createAttentionStore
Observe browser focus and visibility for your existing interface.
Canonical: https://generativea11y.com/api/dom/attention
Markdown: https://generativea11y.com/markdown/api/dom/attention
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Create and register app elements
AttentionStore reads browser focus and visibility. It does not inspect a screen
reader's cursor or move focus.
```typescript title="attention.ts"
import { createAttentionStore } from "@generative-a11y/dom";
const attention = createAttentionStore({ document });
const unregisterComposer = attention.registerComposer(composer);
const unregisterConversation = attention.registerConversation(conversation);
const unregisterNewest = attention.registerNewestResponse(latestResponse);
const unsubscribe = attention.subscribe(() => {
console.log(attention.getSnapshot());
});
// Call when the owning surface is removed.
function disposeAttention() {
unsubscribe();
unregisterNewest();
unregisterConversation();
unregisterComposer();
attention.dispose();
}
```
Register the elements your app already owns. Each registration and subscription
returns a cleanup function; `dispose()` releases the store and its browser
listeners.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| options | ` AttentionStoreOptions ` | no | ` browser document ` | Injects the document, intersection observer factory, and observer configuration. |
| return | ` AttentionStore ` | no | | Return. External store with snapshots, registrations, subscriptions, and disposal. |
## AttentionSnapshot
A field stays unknown when the browser cannot provide enough information.
AttentionStore never guesses.
| Field | Values | Browser signal |
| --- | --- | --- |
| visibility | visible, hidden, unknown | Document visibility |
| windowFocus | focused, blurred, unknown | Window focus |
| focusArea | composer, conversation, elsewhere, none, unknown | Deep active element |
| newestResponse | visible, outside, unobserved, unknown | Intersection observer |
| mode | foreground, background, reading-history, away, unknown | Derived from the fields above |
## bindAttention
`bindAttention({ runtime, attentionStore })` explicitly forwards initial and
changed observations to the core runtime. Both inputs are borrowed. `dispose()`
unsubscribes and sends `attention.changed` with mode `unknown`, without
disposing either input. Competing bindings for one runtime throw. Core filtering
still requires `policy.attention.enabled`.
Actual newest-response intersection contributes browser evidence; this cannot
identify a screen reader virtual cursor.
[Read the attention guide](/docs/attention-aware-announcements).
---
# PreferenceStore
Store validated announcement preferences with optional persistence.
Canonical: https://generativea11y.com/api/dom/preferences
Markdown: https://generativea11y.com/markdown/api/dom/preferences
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## createPreferenceStore
createPreferenceStore validates loaded and assigned values before exposing a
stable snapshot.
```ts title="preferences.ts"
import { createPreferenceStore } from "@generative-a11y/dom";
const store = createPreferenceStore();
store.setPreferences({
version: 1,
preset: "balanced",
streaming: "sentence",
tools: "status",
});
// Read store.getSnapshot() or subscribe to changes.
// Call store.dispose() when its owner ends.
```
Persistence is disabled by default. Supply `persistence.key` to use browser
storage when it is available:
```ts title="Persist preferences"
const store = createPreferenceStore({
persistence: { key: "chat:a11y-preferences" },
});
```
Use `preferencesToCoreConfiguration` to map the snapshot to a core preset and
policy overrides. Unsubscribe listeners and dispose the store when its owner
ends.
## Options
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| defaultValue | ` PreferenceSchemaV1 ` | no | ` defaultPreferences ` | Validated snapshot used when persistence is missing or invalid. |
| persistence.key | ` string ` | yes | | Required when persistence is configured. Storage key for the serialized versioned schema. |
| persistence.storage | ` PreferenceStorage ` | no | ` localStorage when available ` | Injected getItem and setItem surface. |
| persistence.events | ` PreferenceStorageEventSource ` | no | ` browser events with browser storage ` | Synchronizes validated changes from other documents. |
| onDiagnostic | ` callback ` | no | ` undefined ` | Observes invalid, unavailable, read, write, and event-source outcomes. |
## Custom storage and runtime configuration
Supply `storage` and `events` together to persist and synchronize through a
custom storage layer. When you inject storage, the store uses only the event
source you provide.
```ts title="Create a runtime with stored preferences"
import { createRuntime } from "@generative-a11y/core";
import { preferencesToCoreConfiguration } from "@generative-a11y/dom";
const runtime = createRuntime(
preferencesToCoreConfiguration(store.getSnapshot()),
);
// Call runtime.dispose() when its owner ends.
```
Core reads this configuration at construction. Later preference changes update
the store without changing an active runtime. [A11yProvider](/api/react) also
uses preferences only when constructing its owned runtime, and only when no
explicit preset or policy is supplied. Apply saved changes when creating the
next runtime or remounting the provider at an intentional session boundary.
## PreferenceSchemaV1 and helpers
A version field makes persistence migrations explicit.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| defaultPreferences | ` PreferenceSchemaV1 ` | no | ` balanced ` | Constant. Frozen balanced user preference snapshot. |
| normalizePreferences(value) | ` PreferenceSchemaV1 ` | no | | Function. Validates and freezes a schema value. Invalid fields or unsupported versions throw TypeError. |
| samePreferences(left, right) | ` boolean ` | no | | Function. Compares the supported schema fields. |
| preferencesToCoreConfiguration(value) | ` CorePreferenceConfiguration ` | no | | Function. Maps user verbosity to a core preset and policy overrides. |
---
# @generative-a11y/react
Connect a runtime and browser delivery to your existing React interface.
Canonical: https://generativea11y.com/api/react
Markdown: https://generativea11y.com/markdown/api/react
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## A11yProvider
A11yProvider can own a runtime or borrow one from your app. It renders stable
hidden delivery regions and leaves visible UI unchanged.
```tsx title="components/app.tsx"
import { A11yProvider } from "@generative-a11y/react";
export function App() {
return (
);
}
```
Wrap the part of your app that sends events. The provider supplies browser
delivery by default; your existing components retain their markup, keyboard
behavior, and focus. See [React hooks](/api/react/hooks) to read the runtime.
## Provider options
The provider also accepts [RuntimeOptions](/api/core/create-runtime#options)
when it creates a runtime, including `preset`, `policy`, `messages`, and
`clock`.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| runtime | ` Runtime ` | no | ` owned runtime ` | Borrows an existing runtime when provided. A11yProvider never disposes app-supplied runtimes. |
| delivery | ` false \| DeliveryOptions ` | no | ` {} ` | Configures hidden DOM delivery or disables it. |
| attention | ` false \| AttentionStoreOptions ` | no | ` {} ` | Configures the provider's attention store or disables browser signal collection. |
| attentionPolicy | ` boolean ` | no | ` false ` | Forwards browser observations to core. Enable policy.attention.enabled separately to filter announcements. |
| attentionStore | ` AttentionStore ` | no | ` owned store ` | Borrows an application-supplied attention store. |
| preferences | ` PreferenceStoreOptions ` | no | ` {} ` | Configures an owned preference store. |
| preferenceStore | ` PreferenceStore ` | no | ` owned store ` | Borrows an application-supplied preference store. |
## Provider ownership
A11yProvider cleans up every runtime, browser connection, store, timer,
subscription, and live region it creates. Anything supplied by your app remains
under your control.
* Provider context is unavailable outside the provider.
* Server rendering uses stable hidden structure and reports attention as
unknown.
* Routine announcements never move focus.
* Initial preferences configure an owned runtime only when no explicit preset or
policy is supplied. Later preference changes update the store, not the active
runtime policy.
## Opt-in attention forwarding
`A11yProvider` accepts `attentionPolicy?: boolean` (default `false`). This
forwards browser observations to the runtime; independently enable
`policy.attention.enabled` for filtering. `useAttentionControl` exposes
observed, override, and effective state plus `setOverride`.
[See the complete attention guide](/docs/attention-aware-announcements).
## Localized announcements
See [catalogs and adapter copy](/docs/localized-announcements) for the typed
`messages` and `copy` options, language ownership, validation, construction
lifetime, and replay requirements. Existing lifecycle evidence and timing remain
unchanged.
## Public declarations: @generative-a11y/react
Import from `@generative-a11y/react`. Direct declarations from the source checkout; transitive upstream types and behavioral contracts require the linked guides and upstream documentation.
### A11yContextValue (type)
```typescript
interface A11yContextValue {
readonly runtime: Runtime;
readonly attentionStore: AttentionStore;
readonly preferenceStore: PreferenceStore;
}
```
### A11yProvider (value)
```typescript
declare function A11yProvider({ children, runtime: suppliedRuntime, delivery, attention, attentionStore: suppliedAttentionStore, attentionPolicy, preferences, preferenceStore: suppliedPreferenceStore, ...runtimeOptions }: A11yProviderProps): react.JSX.Element;
```
### A11yProviderProps (type)
```typescript
interface A11yProviderProps extends RuntimeOptions {
readonly children?: ReactNode;
readonly runtime?: Runtime;
readonly delivery?: false | DeliveryOptions;
readonly attention?: false | AttentionStoreOptions;
readonly attentionStore?: AttentionStore;
/** Opt into forwarding observations; configure runtime policy.attention separately. */
readonly attentionPolicy?: boolean;
readonly preferences?: PreferenceStoreOptions;
readonly preferenceStore?: PreferenceStore;
}
```
### AttentionControl (type)
```typescript
interface AttentionControl {
readonly state: AttentionState;
readonly setOverride: (mode: AttentionOverride) => void;
}
```
### AttentionRefs (type)
```typescript
/** Optional refs that register host elements for attention observations only. */
interface AttentionRefs {
readonly composerRef: RefCallback;
readonly conversationRef: RefCallback;
readonly newestResponseRef: RefCallback;
}
```
### DeliveryOptions (type)
```typescript
type DeliveryOptions = Omit;
```
### PreferencesResult (type)
```typescript
interface PreferencesResult {
readonly preferences: PreferenceSchemaV1;
readonly setPreferences: (preferences: PreferenceSchemaV1) => void;
readonly store: PreferenceStore;
}
```
### useA11y (value)
```typescript
declare function useA11y(): A11yContextValue;
```
### useAttention (value)
```typescript
declare function useAttention(): AttentionSnapshot;
```
### useAttentionControl (value)
```typescript
declare function useAttentionControl(): AttentionControl;
```
### useAttentionRefs (value)
```typescript
declare function useAttentionRefs(): AttentionRefs;
```
### usePreferences (value)
```typescript
declare function usePreferences(): PreferencesResult;
```
### useRuntime (value)
```typescript
declare function useRuntime(): Runtime;
```
---
# React hooks
React hooks for the runtime, attention, preferences, and refs for existing app elements.
Canonical: https://generativea11y.com/api/react/hooks
Markdown: https://generativea11y.com/markdown/api/react/hooks
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Bind an existing chat interface
AttentionRefs contain refs only. Add them to semantic elements already in your
app.
```tsx title="components/chat.tsx"
import {
useAttention,
useAttentionRefs,
usePreferences,
useRuntime,
} from "@generative-a11y/react";
function ExistingChat() {
const runtime = useRuntime();
const attention = useAttention();
const { setPreferences } = usePreferences();
const bindings = useAttentionRefs();
return (
Latest response
);
}
```
Mount these hooks under [A11yProvider](/api/react). Refs observe existing
elements without changing their markup or styles; preference updates are
validated before the store publishes them. Saving preferences does not change
the active runtime policy. Apply them when constructing the next runtime or
remounting its provider at an intentional session boundary.
## Hook results
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| useA11y() | ` A11yContextValue ` | no | | Hook. Returns runtime, attentionStore, and preferenceStore from the nearest provider. |
| useRuntime() | ` Runtime ` | no | | Hook. Returns the provider runtime. |
| useAttention() | ` AttentionSnapshot ` | no | ` unknown SSR snapshot ` | Hook. Uses useSyncExternalStore to report browser focus and visibility without guessing missing values. |
| usePreferences() | ` PreferencesResult ` | no | | Hook. Returns validated preferences, setPreferences, and the underlying store. |
| useAttentionRefs() | ` AttentionRefs ` | no | | Hook. Returns stable composer, conversation, and newest-response ref props. |
## AttentionRefs
Each property is a callback ref for an existing host element. These optional
refs observe attention only; they do not add semantics or enable announcement
delivery. Compose existing refs with your framework utility when necessary.
| Property | Target | Purpose |
| --- | --- | --- |
| composerRef | HTMLElement | Detects focus in the composer |
| conversationRef | HTMLElement | Detects focus in conversation history |
| newestResponseRef | HTMLElement | Checks whether the newest response is visible |
## useAttentionControl
Returns `{ state: { observed, override, effective }, setOverride }`. Call
`setOverride("quiet")`, `setOverride("normal")`, or `setOverride("auto")` from
controls owned by your host app. The provider adds no visible controls. With
attention filtering disabled, effective mode remains normal.
Set the provider's `attentionPolicy` prop to bridge browser observations and
independently configure core `policy.attention.enabled`.
[Copy a complete provider and ref-binding example](/docs/attention-aware-announcements).
---
# @generative-a11y/ai-sdk
Turn documented AI SDK useChat state and callbacks into generative-a11y events.
Canonical: https://generativea11y.com/api/ai-sdk
Markdown: https://generativea11y.com/markdown/api/ai-sdk
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Start here
For an existing compatible React + AI SDK app:
```shell title="Terminal"
npm install @generative-a11y/react @generative-a11y/ai-sdk
```
```shell title="Terminal"
pnpm add @generative-a11y/react @generative-a11y/ai-sdk
```
```shell title="Terminal"
yarn add @generative-a11y/react @generative-a11y/ai-sdk
```
```shell title="Terminal"
bun add @generative-a11y/react @generative-a11y/ai-sdk
```
See the [integration guide](/docs/integrations/ai-sdk) for peer versions,
provider placement, preserved host options, and the preconstructed `Chat` case.
The root observer alone does not provide browser delivery.
For React, start with
[useChatAccessibility](/api/ai-sdk/use-chat-accessibility). For a custom state
bridge, create an observer and install its composed callbacks when constructing
your chat:
```ts title="Observer setup"
import {
createChatObserver,
composeChatCallbacks,
} from "@generative-a11y/ai-sdk";
const observer = createChatObserver({ runtime, scopeId: "support" });
const chatCallbacks = composeChatCallbacks({ observer });
```
Pass public snapshots to `observer.observe(snapshot)` as they change. Dispose
the observer when its owner ends. The
[non-React reference](#non-react-observer-api) below includes callback contracts
and a complete deterministic example.
## Public APIs used
AI SDK adapters read documented messages, status, and error state. onFinish and
onError report final response state.
| Surface | Exports | Use |
| --- | --- | --- |
| Framework-neutral | createChatObserver, composeChatCallbacks | Custom subscription or state bridge |
| React | useChatAccessibility, useObserveChatAccessibility | AI SDK useChat components |
| Metadata | adapterInfo | Supported events and framework APIs |
## Runtime and app ownership
Your app owns the core runtime. Adapters report events without running chat
actions or reading rendered messages and private AI SDK fields.
* scopeId separates response and message IDs across chat instances.
* Tool arguments do not mean that execution started.
* Your onFinish and onError callbacks remain intact.
* Disposing the observer clears only records created by the adapter.
## Localized announcements
See [catalogs and adapter copy](/docs/localized-announcements) for the typed
`messages` and `copy` options, language ownership, validation, construction
lifetime, and replay requirements. Existing lifecycle evidence and timing remain
unchanged.
## Public declarations: @generative-a11y/ai-sdk
Import from `@generative-a11y/ai-sdk`. Direct declarations from the source checkout; transitive upstream types and behavioral contracts require the linked guides and upstream documentation.
### adapterInfo (value)
```typescript
declare const adapterInfo: AdapterInfo;
```
### AdapterInfo (type)
```typescript
interface AdapterInfo {
readonly name: "ai-sdk";
readonly fidelity: Readonly> & {
readonly optionalEvents: readonly NonNullable[number][];
};
readonly observedSnapshotFields: readonly [
"messages",
"status",
"error"
];
readonly terminalEvidence: readonly [
"onFinish",
"onError"
];
readonly saturation: "suppress-after-baseline-capacity";
}
```
### ChatFinishOutcome (type)
```typescript
interface ChatFinishOutcome {
readonly isAbort: boolean;
readonly isDisconnect: boolean;
readonly isError: boolean;
}
```
### ChatObserver (type)
```typescript
interface ChatObserver {
observe(snapshot: ChatSnapshot): void;
finish(message: UIMessage, outcome: ChatFinishOutcome): void;
failActiveResponse(): void;
dispose(): void;
}
```
### ChatObserverOptions (type)
```typescript
interface ChatObserverOptions {
/** Host-owned localized copy, captured and validated at construction. */
readonly copy?: AdapterCopy;
readonly runtime: Pick;
readonly scopeId: string;
/** Positive cap for each response, tool, approval, and source identity set. */
readonly maxTrackedEntities?: number;
/** Maps tool identity to localized host copy. The default is deliberately generic. */
readonly getToolLabel?: (context: ToolLabelContext) => string;
}
```
### ChatSnapshot (type)
```typescript
interface ChatSnapshot {
readonly messages: UI_MESSAGE[];
readonly status: "submitted" | "streaming" | "ready" | "error";
readonly error: Error | undefined;
}
```
### composeChatCallbacks (value)
```typescript
/** Composes host callbacks with the exact public AI SDK terminal evidence. */
declare function composeChatCallbacks(options: ComposeChatCallbacksOptions): {
onFinish: ChatOnFinishCallback;
onError: ChatOnErrorCallback;
};
```
### ComposeChatCallbacksOptions (type)
```typescript
interface ComposeChatCallbacksOptions {
readonly observer: ChatObserver;
readonly onFinish?: ChatOnFinishCallback;
readonly onError?: ChatOnErrorCallback;
}
```
### createChatObserver (value)
```typescript
/**
* Creates a bounded, borrowed-runtime observer. The first valid snapshot
* silently records history; it never interprets `ready` or `error` as a
* response terminal state.
*/
declare function createChatObserver(options: ChatObserverOptions): ChatObserver;
```
### ToolLabelContext (type)
```typescript
interface ToolLabelContext {
readonly toolCallId: string;
readonly toolName: string;
readonly title: string | undefined;
}
```
## Non-React observer API
For the observer example below, declare the packages it imports directly:
```shell title="Terminal"
npm install @generative-a11y/core @generative-a11y/ai-sdk "ai@~7.0.0"
```
The example records intents only. A live browser integration also needs a direct
`@generative-a11y/dom` dependency when importing `bindRuntime`, a delivery
binding, and cleanup of that binding before disposing the runtime.
`createChatObserver(options)` returns a `ChatObserver` and never owns the core
runtime. `ChatObserverOptions` requires a non-empty `scopeId` and a runtime with
`dispatch`. Optional `copy` comes from `core/messages`; `getToolLabel` receives
`ToolLabelContext` (`toolCallId`, `toolName`, and optional-value `title`). Its
safe label overrides the generic copy. `maxTrackedEntities` defaults to 1,000
and must be a positive safe integer.
| Method | Contract |
| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `observe(snapshot)` | Accepts `ChatSnapshot`: public `messages`, `status`, and `error`. The first valid snapshot establishes a silent baseline. Later append-only parts produce events; it does not subscribe to a framework for you. |
| `finish(message, outcome)` | Accepts an SDK assistant `UIMessage` and `ChatFinishOutcome` with `isAbort`, `isDisconnect`, and `isError`. Disconnect emits connection loss rather than completion; error precedes abort, and ordinary finish completes the active response. |
| `failActiveResponse()` | Reports failure for the last observed active response. No active response means no output; raw error text is never copied. |
| `dispose()` | Clears observer state and makes later observations/callbacks inert. It does not dispose the runtime. |
`composeChatCallbacks({ observer, onFinish?, onError? })` accepts
`ComposeChatCallbacksOptions` and returns the SDK-compatible callbacks. It calls
the observer first, then the host callback in a `finally` block so host handling
still runs if observer dispatch throws. Install these callbacks before creating
the SDK chat; observe its public snapshots separately.
After identity capacity is exhausted, **all later snapshot and terminal-callback
lifecycle events are suppressed**, including known identities. Create a fresh
observer at an intentional session boundary. A non-prefix text rewrite is also
suppressed for that part until its message ID changes. These conservative limits
prevent guessed lifecycle events.
The following complete deterministic example exercises the public observer
contract without a React component or backend. In a live application, use the
SDK's real snapshots and callbacks, a browser delivery binding, and cleanup when
the surface is removed. Do not recreate the adapter's private scoped IDs.
```ts title="chat-accessibility.ts"
import {
createRuntime,
ManualClock,
type AnnouncementIntent,
} from "@generative-a11y/core";
import {
createChatObserver,
composeChatCallbacks,
} from "@generative-a11y/ai-sdk";
import type { UIMessage } from "ai";
// A deterministic demonstration of the non-React API, using public SDK data.
export const announcements: AnnouncementIntent[] = [];
const clock = new ManualClock();
const runtime = createRuntime({
clock,
onAnnouncement: (intent) => announcements.push(intent),
});
const observer = createChatObserver({ runtime, scopeId: "support" });
const callbacks = composeChatCallbacks({ observer });
// Supply the initial public snapshot first; historical content is not replayed.
observer.observe({ messages: [], status: "ready", error: undefined });
const message: UIMessage = {
id: "assistant-1",
role: "assistant",
parts: [{ type: "text", text: "Your answer is ready." }],
};
observer.observe({
messages: [message],
status: "streaming",
error: undefined,
});
// In an application, pass callbacks to the SDK when constructing its chat.
callbacks.onFinish({
message,
messages: [message],
isAbort: false,
isDisconnect: false,
isError: false,
finishReason: "stop",
});
clock.runUntilIdle();
observer.dispose();
runtime.dispose();
```
---
# useChatAccessibility
Create the AI SDK observer and completion callbacks before calling useChat in the same React component.
Canonical: https://generativea11y.com/api/ai-sdk/use-chat-accessibility
Markdown: https://generativea11y.com/markdown/api/ai-sdk/use-chat-accessibility
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Start here
For an existing compatible React + AI SDK app:
```shell title="Terminal"
npm install @generative-a11y/react @generative-a11y/ai-sdk
```
```shell title="Terminal"
pnpm add @generative-a11y/react @generative-a11y/ai-sdk
```
```shell title="Terminal"
yarn add @generative-a11y/react @generative-a11y/ai-sdk
```
```shell title="Terminal"
bun add @generative-a11y/react @generative-a11y/ai-sdk
```
See the [integration guide](/docs/integrations/ai-sdk) for peer versions,
provider placement, preserved host options, and the preconstructed `Chat` case.
The root observer alone does not provide browser delivery.
## Complete useChat integration
Call useChatAccessibility first, pass chatCallbacks into useChat, then observe
the documented snapshot.
```tsx title="components/chat.tsx"
"use client";
import { DefaultChatTransport } from "ai";
import { useChat } from "@ai-sdk/react";
import { A11yProvider, useRuntime } from "@generative-a11y/react";
import {
useChatAccessibility,
useObserveChatAccessibility,
} from "@generative-a11y/ai-sdk/react";
import { useState } from "react";
function Chat() {
const runtime = useRuntime();
const accessibility = useChatAccessibility({
runtime,
scopeId: "support",
});
const chat = useChat({
id: "support",
transport: new DefaultChatTransport({ api: "/api/chat" }),
...accessibility.chatCallbacks,
});
useObserveChatAccessibility({ integration: accessibility, snapshot: chat });
const [input, setInput] = useState("");
// This is example host UI. Keep your existing message list and composer.
return (
);
}
export function App() {
return (
);
}
```
### Existing callbacks
Already use `onFinish` or `onError`? Pass your existing functions to
`useChatAccessibility` so they are composed rather than replaced. Keep the rest
of your options, including transport, in `existingOptions`, and spread the
composed callbacks last. Omit either callback if your app does not use it.
```tsx title="components/chat.tsx"
const accessibility = useChatAccessibility({
runtime,
scopeId: "support",
onFinish,
onError,
});
const chat = useChat({ ...existingOptions, ...accessibility.chatCallbacks });
```
## Options
Pass these options to `useChatAccessibility`. The provider supplies `runtime`;
keep `scopeId` stable for the mounted chat.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| copy | ` AdapterCopy ` | no | ` undefined ` | Optional complete localized copy from core/messages, validated and captured before subscription or observation. It does not translate response text. |
| runtime | ` Pick ` | yes | | Receives adapter events while remaining under your app's control. |
| scopeId | ` string ` | yes | | Stable non-empty namespace for messages, tools, approvals, and citations. |
| maxTrackedEntities | ` number ` | no | ` 1000 ` | Bounds adapter identity memory. After saturation, all later snapshot and terminal-callback lifecycle events are suppressed, including tracked identities. |
| getToolLabel | ` (context) => string ` | no | ` "A tool" ` | Maps public tool context to short localized copy without exposing arguments. |
| onFinish / onError | ` AI SDK callbacks ` | no | ` undefined ` | Your existing callbacks. chatCallbacks calls them after the adapter records the result. |
| return | ` ChatIntegration ` | no | | Return. Observer plus onFinish and onError callbacks for useChat. |
## useObserveChatAccessibility
useObserveChatAccessibility reads your ChatIntegration without disposing it.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| integration | ` ChatIntegration ` | yes | | Value returned by useChatAccessibility. |
| snapshot | ` UseChatSnapshot ` | yes | | Documented messages, status, and error fields from useChat. |
| return | ` void ` | no | | Return. Observation occurs in an effect after the snapshot commits. |
The example uses your existing AI SDK `/api/chat` endpoint. `A11yProvider`
owns the runtime and browser delivery; `useChatAccessibility` owns only its
observer. Both clean up on unmount. Keep your existing transport and UI.
Add host `onFinish`/`onError` callbacks to `useChatAccessibility` when needed;
it composes them with its own callbacks. Do not overwrite `chatCallbacks`
after spreading them into `useChat`.
## Public declarations: @generative-a11y/ai-sdk/react
Import from `@generative-a11y/ai-sdk/react`. Direct declarations from the source checkout; transitive upstream types and behavioral contracts require the linked guides and upstream documentation.
### ChatIntegration (type)
```typescript
interface ChatIntegration {
readonly observer: ChatObserver;
readonly chatCallbacks: {
readonly onFinish: ChatOnFinishCallback;
readonly onError: ChatOnErrorCallback;
};
}
```
### useChatAccessibility (value)
```typescript
/**
* Creates an observer and the callbacks that must be passed to `useChat()`.
* Invoke this hook before `useChat()` in the same component.
*/
declare function useChatAccessibility(options: UseChatAccessibilityOptions): ChatIntegration;
```
### UseChatAccessibilityOptions (type)
```typescript
interface UseChatAccessibilityOptions {
readonly runtime: Pick;
readonly scopeId: string;
/** Captured with the observer; replace its scope/runtime to change language. */
readonly copy?: AdapterCopy;
readonly maxTrackedEntities?: number;
readonly getToolLabel?: (context: ToolLabelContext) => string;
readonly onFinish?: ChatOnFinishCallback;
readonly onError?: ChatOnErrorCallback;
}
```
### UseChatSnapshot (type)
```typescript
/** The documented public state returned from `useChat()` that this hook reads. */
type UseChatSnapshot = Pick, "messages" | "status" | "error">;
```
### useObserveChatAccessibility (value)
```typescript
/**
* Observes a public `useChat()` snapshot after `useChat()` has been invoked.
* It borrows the integration and deliberately never disposes its observer.
*/
declare function useObserveChatAccessibility(options: UseObserveChatAccessibilityOptions): void;
```
### UseObserveChatAccessibilityOptions (type)
```typescript
interface UseObserveChatAccessibilityOptions {
readonly integration: ChatIntegration;
readonly snapshot: UseChatSnapshot;
}
```
---
# @generative-a11y/assistant-ui
Turn public assistant-ui ThreadRuntime state into response, tool, approval, and source events.
Canonical: https://generativea11y.com/api/assistant-ui
Markdown: https://generativea11y.com/markdown/api/assistant-ui
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Connect your runtime
Pass your existing `thread` and core `runtime`. The binding observes public
state and callbacks; your app owns execution and browser delivery.
```ts title="thread-accessibility.ts"
import { bindThread } from "@generative-a11y/assistant-ui";
const binding = bindThread({ runtime, scopeId: "support-thread", thread });
// Call binding.dispose() when the owning scope ends.
```
See [bindThread](/api/assistant-ui/bind-thread) for options and
[the integration guide](/docs/integrations/assistant-ui) for setup and
compatibility.
## Public exports
assistant-ui integration uses only getState and subscribe from your
ThreadRuntime.
| Export | Kind | Purpose |
| --- | --- | --- |
| bindThread | Function | Create one adapter subscription |
| adapterInfo | Frozen constant | List supported events and methods |
| BindThreadOptions | Interface | Options for the binding |
| ThreadBinding | Interface | Cleanup method for the binding |
## Events the adapter can report
Public thread state can report interruptions but not general retries or
connection changes. Tool failures and sources depend on content parts from
assistant-ui.
Missing events are never guessed from rendered text, timing, or private runtime
fields.
## Localized announcements
See [catalogs and adapter copy](/docs/localized-announcements) for the typed
`messages` and `copy` options, language ownership, validation, construction
lifetime, and replay requirements. Existing lifecycle evidence and timing remain
unchanged.
## Public declarations: @generative-a11y/assistant-ui
Import from `@generative-a11y/assistant-ui`. Direct declarations from the source checkout; transitive upstream types and behavioral contracts require the linked guides and upstream documentation.
### adapterInfo (value)
```typescript
declare const adapterInfo: AdapterInfo;
```
### AdapterInfo (type)
```typescript
interface AdapterInfo {
readonly name: "assistant-ui";
readonly fidelity: Readonly> & {
readonly optionalEvents: readonly NonNullable[number][];
};
readonly observedRuntimeMethods: readonly [
"getState",
"subscribe"
];
}
```
### bindThread (value)
```typescript
/**
* Subscribes to the documented public assistant-ui thread runtime. It only
* reads snapshots; disposing the returned binding never disposes either host runtime.
*/
declare function bindThread(options: BindThreadOptions): ThreadBinding;
```
### BindThreadOptions (type)
```typescript
interface BindThreadOptions {
/** Host-owned localized copy, captured and validated at construction. */
readonly copy?: AdapterCopy;
readonly runtime: Pick;
readonly scopeId: string;
readonly thread: ThreadRuntimeSource;
readonly maxTrackedEntities?: number;
}
```
### ThreadBinding (type)
```typescript
interface ThreadBinding {
dispose(): void;
}
```
### ThreadRuntimeSource (type)
```typescript
type ThreadRuntimeSource = Pick;
```
---
# bindThread
Connect public assistant-ui thread state to your application runtime.
Canonical: https://generativea11y.com/api/assistant-ui/bind-thread
Markdown: https://generativea11y.com/markdown/api/assistant-ui/bind-thread
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Signature and import
Create one binding per thread scope and dispose it when that subscription owner
unmounts.
```typescript title="thread-accessibility.ts"
import { bindThread } from "@generative-a11y/assistant-ui";
const binding = bindThread({
runtime,
scopeId: "support-thread",
thread,
});
// Call when the owning scope ends; removes only subscription and adapter state.
function disposeThreadBinding() {
binding.dispose();
}
```
Keep `scopeId` stable and unique across mounted conversations. The binding uses
only `getState` and `subscribe`; disposal releases the subscription and adapter
records while preserving your thread and core runtimes.
## Options
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| copy | ` AdapterCopy ` | no | ` undefined ` | Optional complete localized copy from core/messages, validated and captured before subscription or observation. It does not translate response text. |
| runtime | ` Pick ` | yes | | Receives adapter events while remaining under your app's control. |
| scopeId | ` string ` | yes | | Stable non-empty namespace for message, tool, approval, and citation identity. |
| thread | ` ThreadRuntimeSource ` | yes | | Borrowed getState and subscribe surface from assistant-ui. |
| maxTrackedEntities | ` number ` | no | ` 1000 ` | Bounds message, part, tool, and approval identity tracking. |
| return | ` ThreadBinding ` | no | | Return. An idempotent dispose method for the adapter subscription. |
After the tracking limit is exhausted, the binding suppresses subsequent
lifecycle events, including events for known identities. Create a fresh binding
at an intentional session boundary to resume observation.
## Events reported from thread state
Each public thread snapshot is compared with its previous value, and confirmed
changes become events.
| assistant-ui state | generative-a11y event | Source |
| --- | --- | --- |
| Assistant message starts running | response.started | Public message state |
| Text grows | response.text.delta | New text only |
| Message finishes, stops, or fails | completed, interrupted, failed | Public message status |
| Tool call and result parts | tool lifecycle | Public content parts |
| Approval state | approval requested or resolved | Public content parts |
| Source parts | citation.available | Optional content parts |
## Baselining existing history
`bindThread` calls its observer once during construction, before subscribing.
That first pass treats every message already in the thread as historical: it
records assistant messages, tools, approvals, and sources without dispatching
a single event. A user who opens a conversation with forty old messages hears
nothing. Only changes observed after binding become events.
Historical messages are not inert. If an old assistant message gains new text
later, the binding emits `response.started` followed by `response.text.delta`
for the new text, and a later terminal status still resolves the response.
Terminal outcomes (`response.completed`, `response.interrupted`,
`response.failed`) only dispatch for records that became active, so a
conversation opened on an already-finished exchange never announces stale
finishes.
The binding observes assistant messages only. A message must have a string
`id`, `role: "assistant"`, an array `content`, and a defined `status` to be
tracked. User and system messages are never inspected.
## Response identity
Every dispatched event is namespaced under your `scopeId`, which is trimmed at
construction and validated to be a non-empty string. Response identity is
derived, not borrowed: a response ID has the shape
`` `${scopeId}:message:${messageId}` ``, so two conversations mounted at the
same time produce disjoint event streams as long as their scope IDs differ.
Tool IDs take the shape `` `${scopeId}:tool:${toolCallId}` `` and approval IDs
`` `${scopeId}:approval:${approvalId}` ``.
Text deltas are emitted only for append-only growth. Each text part is
remembered per part index; when the observed text extends the previous value,
only the new slice is dispatched in `response.text.delta`. If the observed text
is rewritten instead of extended, the binding marks that part as poisoned and
stops reporting it. Poisoning never invents content: the user hears the text
that was already announced, not a reconstruction.
## Terminal statuses
Public assistant-ui statuses map to terminal events as follows:
* `status.type: "complete"` with reason `"stop"` or `"unknown"` becomes
`response.completed`.
* `status.type: "incomplete"` with reason `"cancelled"` becomes
`response.interrupted`.
* `status.type: "incomplete"` with reason `"error"` becomes
`response.failed`.
* Any other incomplete reason produces no terminal event.
An unknown reason fails closed: the binding never invents a stop, error, or
interruption it did not see. A terminal event dispatches at most once per
response record, and only after the record became active.
## Tool and approval translation
Tool-call parts (`type: "tool-call"` with a string `toolCallId`) produce
`tool.started` when first seen after the initial baseline, carrying a label
from your copy or the default `"A tool"`. When the part later gains a defined
`result`, the binding dispatches `tool.completed`, or `tool.failed` when
`isError` is `true`. A tool-call part with a result already present during the
initial baseline emits neither event, which keeps history replays quiet. The
same part first observed after the baseline emits `tool.started` followed by
its terminal event.
Approval parts work in two phases. An approval observed while its `approved`
field is still `undefined` dispatches `approval.requested`. When the same
approval later resolves to a boolean, the binding dispatches
`approval.resolved` with outcome `"approved"` or `"rejected"` and the matching
resolved label from your copy. An approval that was already decided in history
never announces a request.
Source parts (`type: "source"` with a string `id`) dispatch
`citation.available` with a `count` equal to the number of distinct sources
tracked so far. Each source ID is reported once.
Localized copy is captured and validated once at construction through
`normalizeAdapterCopy`. The copy's `locale` is stamped onto `tool.*` and
`approval.*` events only; response events carry no locale. It never translates
response text.
## Identity tracking and saturation
`maxTrackedEntities` (default `1000`) bounds five independent counters: message
records, tools, approvals, sources, and text parts per message record. The
default accommodates long conversations; raise it only for sessions you expect
to exceed a thousand distinct entities per counter.
When any counter is exhausted, the binding sets a saturated flag and suppresses
all subsequent dispatch, including events for identities it already knows. This
is a deliberate fail-closed choice: a saturated observer stops talking
rather than reporting an incomplete picture. Create a fresh binding at an
intentional session boundary (for example, when the user starts a new
conversation) to resume observation with a clean slate.
## Adapter fidelity
The package exports a frozen `adapterInfo` declaration describing what the
adapter can truthfully observe. Framework-independent consumers and the
devtools store use it to report public evidence without overclaiming.
| Lifecycle dimension | Fidelity |
| --- | --- |
| Runs | unavailable: the thread snapshot exposes no run identity |
| Steps | unavailable |
| Hierarchy | unavailable |
| Tools | exact |
| Interactions | unavailable |
| Replay | partial |
| Reconnection | unavailable |
| Custom events | unsupported |
| Interruption | exact |
| Retries | unavailable |
| Connection | unavailable |
| Optional events | tool.failed, citation.available |
| Observed runtime methods | getState, subscribe |
## Error semantics
Construction validates its options before touching the thread runtime:
* `scopeId` must be a string that is non-empty after trimming, otherwise a
`TypeError` is thrown.
* `maxTrackedEntities`, when provided, must be a positive safe integer,
otherwise a `TypeError` is thrown.
* An invalid `copy` is rejected by `normalizeAdapterCopy` at construction.
Host delivery is isolated: if your runtime's `dispatch` throws, the binding
swallows the exception and continues observing. A misbehaving host listener
cannot break the subscription. Disposal releases only the binding's own state:
the unsubscribe function, message records, tool records, approval records, and
source IDs. Your thread and core runtimes are preserved.
## Worked example
Two conversations mounted at once need two bindings with distinct, stable
scope IDs. Dispose each binding when its owning scope ends.
```typescript title="thread-accessibility.ts"
import { bindThread, type ThreadBinding } from "@generative-a11y/assistant-ui";
export function bindConversation(options: {
runtime: Parameters[0]["runtime"];
scopeId: string;
thread: Parameters[0]["thread"];
}): ThreadBinding {
const binding = bindThread({
runtime: options.runtime,
scopeId: options.scopeId,
thread: options.thread,
maxTrackedEntities: 2000,
});
return binding;
}
// In a React component:
// const bindingRef = useRef(null);
// useEffect(() => {
// bindingRef.current = bindConversation({ runtime, scopeId: "support-thread", thread });
// return () => bindingRef.current?.dispose();
// }, [runtime, thread]);
```
Keep the scope ID stable for the life of the conversation and unique across
mounted conversations. Re-using a scope ID for a new conversation can
replay identities the runtime has already attributed; when the user starts a
new session, bind with a new scope ID instead.
---
# @generative-a11y/ag-ui
Turn public AG-UI callbacks into runtime events.
Canonical: https://generativea11y.com/api/ag-ui
Markdown: https://generativea11y.com/markdown/api/ag-ui
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Connect your runtime
Pass your existing `agent` and core `runtime`. The binding observes public state
and callbacks; your app owns execution and browser delivery.
```ts title="agent-accessibility.ts"
import { bindAgent } from "@generative-a11y/ag-ui";
const binding = bindAgent({ runtime, scopeId: "research-agent", agent });
// Call binding.dispose() when the owning scope ends.
```
See [bindAgent](/api/ag-ui/bind-agent) for options and
[the integration guide](/docs/integrations/ag-ui) for setup and compatibility.
## Public exports
AG-UI integration subscribes through agent.subscribe(AgentSubscriber).
| Export | Kind | Purpose |
| --- | --- | --- |
| bindAgent | Function | Create one protocol subscription |
| adapterInfo | Frozen constant | List supported events and limits |
| BindAgentOptions | Interface | Options for the binding |
| AgentBinding | Interface | Cleanup method for the binding |
## Events the adapter can report
AG-UI 0.0.59 reports exact run and delegated subagent identity. Step events
expose labels but no stable IDs, making step and hierarchy support partial.
Replay and reconnection are partial because there is no mandatory persistent
cursor; retry support remains unavailable.
AG-UI integration never uses private observables or guesses events missing
from the protocol.
## Localized announcements
See [catalogs and adapter copy](/docs/localized-announcements) for the typed
`messages` and `copy` options, language ownership, validation, construction
lifetime, and replay requirements. Existing lifecycle evidence and timing remain
unchanged.
## Public declarations: @generative-a11y/ag-ui
Import from `@generative-a11y/ag-ui`. Direct declarations from the source checkout; transitive upstream types and behavioral contracts require the linked guides and upstream documentation.
### adapterInfo (value)
```typescript
declare const adapterInfo: AdapterInfo;
```
### AdapterInfo (type)
```typescript
interface AdapterInfo {
readonly name: "ag-ui";
readonly fidelity: Readonly> & {
readonly optionalEvents: readonly NonNullable[number][];
};
readonly observation: "agent.subscribe(AgentSubscriber)";
readonly saturation: "suppress-after-capacity";
}
```
### AgentBinding (type)
```typescript
interface AgentBinding {
dispose(): void;
}
```
### AgentSource (type)
```typescript
type AgentSource = Pick;
```
### bindAgent (value)
```typescript
/**
* Subscribes through AG-UI's documented AgentSubscriber callbacks. It does not
* subscribe to the replay-prone protocol observable or own agent/core lifetimes.
*/
declare function bindAgent(options: BindAgentOptions): AgentBinding;
```
### BindAgentOptions (type)
```typescript
interface BindAgentOptions {
/** Host-owned localized copy, captured and validated at construction. */
readonly copy?: AdapterCopy;
readonly runtime: Pick;
readonly scopeId: string;
readonly agent: AgentSource;
readonly maxTrackedEntities?: number;
}
```
---
# bindAgent
Connect an AG-UI agent to your application runtime.
Canonical: https://generativea11y.com/api/ag-ui/bind-agent
Markdown: https://generativea11y.com/markdown/api/ag-ui/bind-agent
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## Signature and import
Create the binding after the agent is ready, then dispose it when the owning
application scope ends.
```typescript title="agent-accessibility.ts"
import { bindAgent } from "@generative-a11y/ag-ui";
const binding = bindAgent({
runtime,
scopeId: "research-agent",
agent,
});
// Call when the owning scope ends; the agent and runtime remain yours.
function disposeAgentBinding() {
binding.dispose();
}
```
The binding subscribes without running the agent. Keep `scopeId` stable and
unique across mounted agents; disposing the binding leaves both the agent and
runtime under your app’s control.
## Options
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| copy | ` AdapterCopy ` | no | ` undefined ` | Optional complete localized copy from core/messages, validated and captured before subscription or observation. It does not translate response text. |
| runtime | ` Pick ` | yes | | Receives adapter events while remaining under your app's control. |
| scopeId | ` string ` | yes | | Stable non-empty namespace for AG-UI run, message, tool, and interrupt IDs. |
| agent | ` AgentSource ` | yes | | Borrowed object exposing documented subscribe behavior. |
| maxTrackedEntities | ` number ` | no | ` 1000 ` | Positive safe integer bounding tracked runs, responses, tools, and interactions. |
| return | ` AgentBinding ` | no | | Return. An idempotent dispose method for the protocol subscription. |
After the tracking limit is exhausted, the binding suppresses subsequent
lifecycle events, including events for known identities. Create a fresh binding
at an intentional session boundary to resume observation.
## How AgentSubscriber callbacks map to events
AG-UI integration reads public callbacks instead of rendered UI.
| AG-UI callback family | generative-a11y event | Notes |
| --- | --- | --- |
| Run start and finish | run lifecycle | Uses protocol run identity and preserves documented lineage |
| Subagent start and finish | delegated child run lifecycle | Preserves explicit parent run, tool, and message ownership |
| Step start and finish | partial step lifecycle | Keeps stepName as a label and omits stepId |
| Text message start, content, end | response lifecycle | Each update contains only new text |
| Tool call start, args, result, end | tool lifecycle | Arguments alone do not mean execution started |
| Run error or interruption | run and active descendant terminal events | Ends active response, tool, child run, and root run state |
| Interrupt and resume | interaction requested or resolved | Reports when the app needs user input |
| Run initialized | interaction resolution | Matches known active interrupt IDs |
**Declared fidelity**
AG-UI 0.0.59 provides stable run and subagent IDs. Step callbacks provide
`stepName` but no stable step ID, so step and hierarchy fidelity are partial.
Replay and reconnection are partial, retry support is unavailable, and custom
events require an explicit host mapping.
---
# @generative-a11y/devtools
Capture redacted runtime diagnostics and inspect them in a browser overlay.
Canonical: https://generativea11y.com/api/devtools
Markdown: https://generativea11y.com/markdown/api/devtools
Documentation channel: source checkout (may include unreleased APIs).
Repository: https://github.com/bhaveshchow20/generative-a11y
Build base revision: f7bcd7cee3f4381b23b5660942666a3dbe12f3e5 (modified checkout: false).
Source package manifest versions (not release parity): @generative-a11y/ag-ui@0.3.0, @generative-a11y/ai-sdk@0.2.0, @generative-a11y/assistant-ui@0.2.0, @generative-a11y/core@0.4.0, @generative-a11y/devtools@0.2.1, @generative-a11y/dom@0.3.0, @generative-a11y/react@0.2.0.
Compare your installed package version and its release tag before using these examples. Package manifest versions alone do not identify unreleased changes. See https://generativea11y.com/docs/stability.
## createStore
The headless store is framework-neutral and has no browser side effects on
import. It subscribes to public runtime diagnostics and owns only its bounded
captured history.
```typescript title="Capture runtime diagnostics"
import { createStore } from "@generative-a11y/devtools";
const store = createStore({ maxEntries: 250 });
const detach = store.attachRuntime({ id: "support", runtime });
const snapshot = store.getSnapshot();
const trace = store.exportTrace();
detach();
store.dispose();
```
`maxEntries` defaults to 250 and must be a positive safe integer. The store
borrows public runtime diagnostics; disposing it detaches runtimes without
disposing them. Snapshots and trace exports are immutable and content-free.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| createStore(options) | ` Store ` | no | ` maxEntries: 250 ` | Function. Creates an isolated store with bounded records and no attached runtimes. |
| attachRuntime({ id, runtime, source? }) | ` () => void ` | no | | Method. Attaches public core diagnostics under a stable ID and returns idempotent detach. |
| source | ` DevtoolsRuntimeSource ` | no | ` undefined ` | Optional attach option. Records the adapter name, documented public evidence, and declared fidelity supplied by the integration. |
| recordDelivery(input) | ` void ` | no | | Method. Adds validated content-free DOM delivery evidence correlated by safe IDs. |
| exportTrace() | ` DevtoolsTraceExportV1 ` | no | | Method. Refreshes runtime snapshots and exports the schema-versioned redacted trace. |
## Capture controls and ownership
pauseCapture and resumeCapture affect devtools capture only. They do not pause
runtime scheduling or browser delivery. clear removes records without detaching
runtimes; dispose detaches runtimes and removes subscribers.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| getSnapshot() | ` DevtoolsSnapshot ` | no | | Method. Returns a cached immutable view until captured state changes. |
| subscribe(listener) | ` () => void ` | no | | Method. Observes store changes with an idempotent unsubscribe function. |
| pauseCapture() / resumeCapture() | ` void ` | no | | Method. Controls diagnostic retention without changing the observed runtimes. |
| refreshSnapshots() | ` void ` | no | | Method. Requests fresh content-free snapshots from attached runtimes without changing their state. |
| clear() / dispose() | ` void ` | no | | Method. Clears captured state or releases all store-owned resources. |
## Snapshot and trace contracts
Devtools snapshots and V1 exports contain redacted records, runtime snapshots,
and declared adapter sources. The bounded record list reports how much older
data it dropped.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| droppedCount | ` number ` | no | ` 0 ` | Snapshot and export. Counts records removed from the ring buffer since the last clear. |
| runtimeSourceId | ` string ` | no | ` undefined ` | Optional record field. Connects a record to an immutable adapter evidence revision without copying that metadata into each record. |
| records | ` readonly DevtoolsRecord[] ` | no | ` [] ` | Snapshot and export. Contains redacted events, decisions, optional DOM delivery results, workflow identity, hierarchy, and attempt replacement fields in capture order. |
| runtimeSnapshots | ` Readonly> ` | no | ` {} ` | Snapshot and export. Stores the latest content-free core snapshot for each attached runtime. |
| runtimeSources | ` Readonly> ` | no | ` {} ` | Snapshot and export. Stores immutable adapter evidence revisions still referenced by retained records. |
## Workflow record correlation
Workflow records retain `runId`, `runInstanceId`, `stepId`, and
`stepInstanceId`. Parent fields preserve only hierarchy supplied by the source.
`nextRunInstanceId` and `nextStepInstanceId` connect a retry record to its
replacement attempt. The trace explorer uses these exact attempt keys so
concurrent or replaced attempts are not merged by label.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| runId / runInstanceId / nextRunInstanceId | ` string ` | no | ` undefined ` | Logical run, current attempt, and replacement attempt. |
| stepId / stepInstanceId / nextStepInstanceId | ` string ` | no | ` undefined ` | Logical step, current attempt, and replacement attempt. |
| parentRunId / parentRunInstanceId | ` string ` | no | ` undefined ` | Explicit parent run correlation. |
| parentStepId / parentStepInstanceId | ` string ` | no | ` undefined ` | Explicit parent step correlation. |
| parentToolId / parentResponseId | ` string ` | no | ` undefined ` | Explicit delegation and response ownership. |
### Adapter fidelity
`DevtoolsRuntimeSource` stores an integration's declared evidence and fidelity.
Workflow fields cover runs, steps, hierarchy, tools, interactions, replay,
reconnection, retries, interruption, connection, and custom events. Devtools
does not inspect framework internals or fill in evidence the adapter lacks.
## mountOverlay
Import the browser helper from @generative-a11y/devtools/overlay. It mounts
one Shadow DOM host after an explicit call, starts collapsed, and restores prior
focus when closed.
```typescript title="Mount the trace explorer"
import { mountOverlay } from "@generative-a11y/devtools/overlay";
const overlay = mountOverlay({ store });
// Call overlay.dispose() when removing the workbench.
```
The overlay reads your store without attaching runtimes itself. Importing the
module creates no browser UI or global shortcuts. `dispose()` removes the
workbench and its host.
| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| store | ` Store ` | yes | | Supplies the captured records and control methods displayed by the overlay. |
| document | ` Document ` | no | ` global document ` | Selects the document that receives the Shadow DOM host. |
| copyText | ` (value) => void \| Promise ` | no | ` Clipboard API ` | Overrides trace copying for hosts that provide their own clipboard bridge. |
| host | ` HTMLElement ` | no | | Return field. Exposes the mounted custom element for inspection or host-controlled placement. |
| dispose() | ` void ` | no | | Return method. Unmounts the workbench and removes its host. Repeated calls are safe. |
**Evidence and testing note**
Captured runtime and browser evidence does not prove that assistive technology
spoke an announcement.
## Localized announcements
See [catalogs and adapter copy](/docs/localized-announcements) for the typed
`messages` and `copy` options, language ownership, validation, construction
lifetime, and replay requirements. Existing lifecycle evidence and timing remain
unchanged.
## Public declarations: @generative-a11y/devtools
Import from `@generative-a11y/devtools`. Direct declarations from the source checkout; transitive upstream types and behavioral contracts require the linked guides and upstream documentation.
### AttachRuntimeOptions (type)
```typescript
interface AttachRuntimeOptions {
readonly id: string;
readonly runtime: Pick;
readonly source?: DevtoolsRuntimeSource;
}
```
### createStore (value)
```typescript
declare function createStore(options?: StoreOptions): Store;
```
### DeliveryRecordInput (type)
```typescript
interface DeliveryRecordInput {
readonly runtimeId: string;
readonly result: {
readonly status: "notified" | "mutated" | "unavailable" | "disposed";
readonly method: "aria-notify" | "live-region" | "none";
readonly channel: "polite" | "assertive";
readonly announcementId: string;
readonly sourceType: string;
readonly at: number;
readonly sourceEventId?: string;
readonly responseId?: string;
readonly toolId?: string;
readonly interactionId?: string;
/** Stable logical run identity copied from the delivered intent. */
readonly runId?: string;
/** Stable run attempt identity copied from the delivered intent. */
readonly runInstanceId?: string;
/** Stable logical step identity copied from the delivered intent. */
readonly stepId?: string;
/** Stable step attempt identity copied from the delivered intent. */
readonly stepInstanceId?: string;
readonly error?: {
readonly name: string;
readonly message?: string;
};
};
}
```
### DevtoolsRecord (type)
```typescript
interface DevtoolsRecord {
readonly attentionMode?: AttentionMode;
readonly attentionOverride?: AttentionOverride;
readonly runtimeId: string;
/** Opaque key for the immutable adapter evidence captured with this record. */
readonly runtimeSourceId?: string;
readonly sequence?: number;
readonly captureSequence: number;
readonly at: number;
readonly kind: DevtoolsRecordKind;
readonly sourceType?: string;
readonly sourceEventId?: string;
readonly disposition?: string;
readonly reason?: string;
readonly announcementId?: string;
readonly responseId?: string;
readonly responseInstanceId?: string;
readonly nextResponseInstanceId?: string;
readonly attempt?: number;
readonly toolId?: string;
readonly toolInstanceId?: string;
readonly interactionId?: string;
readonly approvalId?: string;
/** Stable logical run identity retained as content-free correlation data. */
readonly runId?: string;
/** Stable run attempt identity retained as correlation data. */
readonly runInstanceId?: string;
/** Replacement run attempt identity on retry evidence. */
readonly nextRunInstanceId?: string;
/** Explicit logical parent run identity. */
readonly parentRunId?: string;
/** Explicit parent run attempt identity. */
readonly parentRunInstanceId?: string;
/** Stable logical step identity retained as content-free correlation data. */
readonly stepId?: string;
/** Stable step attempt identity retained as correlation data. */
readonly stepInstanceId?: string;
/** Replacement step attempt identity on retry evidence. */
readonly nextStepInstanceId?: string;
/** Explicit logical parent step identity. */
readonly parentStepId?: string;
/** Explicit parent step attempt identity. */
readonly parentStepInstanceId?: string;
/** Explicit tool that delegated to a child run. */
readonly parentToolId?: string;
/** Explicit response that owns a child run. */
readonly parentResponseId?: string;
readonly progress?: number;
readonly outcome?: string;
readonly count?: number;
readonly scheduledAt?: number;
readonly dueAt?: number;
readonly delayMs?: number;
readonly queueSequence?: number;
readonly channel?: "polite" | "assertive";
readonly deliveryStatus?: "notified" | "mutated" | "unavailable" | "disposed";
readonly deliveryMethod?: "aria-notify" | "live-region" | "none";
readonly errorName?: string;
}
```
### DevtoolsRecordKind (type)
```typescript
type DevtoolsRecordKind = RuntimeDiagnosticEventV1["kind"] | "dom-delivery";
```
### DevtoolsRuntimeSource (type)
```typescript
/**
* Explicit, serializable evidence declared by an integration. Devtools never
* detects framework state or infers fidelity on its own.
*/
interface DevtoolsRuntimeSource {
readonly adapter: string;
readonly evidence: readonly string[];
readonly fidelity: Readonly & Partial> & {
readonly optionalEvents?: readonly NonNullable[number][];
}>;
}
```
### DevtoolsSnapshot (type)
```typescript
interface DevtoolsSnapshot {
readonly paused: boolean;
readonly droppedCount: number;
readonly records: readonly DevtoolsRecord[];
readonly runtimeIds: readonly string[];
readonly runtimeSnapshots: Readonly>;
readonly runtimeSources: Readonly>;
}
```
### DevtoolsTraceExportV1 (type)
```typescript
interface DevtoolsTraceExportV1 {
readonly schemaVersion: 1;
readonly kind: "generative-a11y/devtools-trace";
readonly paused: boolean;
readonly droppedCount: number;
readonly records: readonly DevtoolsRecord[];
readonly runtimeSnapshots: Readonly>;
readonly runtimeSources: Readonly>;
}
```
### Store (type)
```typescript
interface Store {
attachRuntime(options: AttachRuntimeOptions): () => void;
getSnapshot(): DevtoolsSnapshot;
subscribe(listener: () => void): () => void;
pauseCapture(): void;
resumeCapture(): void;
refreshSnapshots(): void;
recordDelivery(input: DeliveryRecordInput): void;
clear(): void;
exportTrace(): DevtoolsTraceExportV1;
dispose(): void;
}
```
### StoreOptions (type)
```typescript
interface StoreOptions {
readonly maxEntries?: number;
}
```
## Public declarations: @generative-a11y/devtools/overlay
Import from `@generative-a11y/devtools/overlay`. Direct declarations from the source checkout; transitive upstream types and behavioral contracts require the linked guides and upstream documentation.
### mountOverlay (value)
```typescript
declare function mountOverlay(options: OverlayOptions): Overlay;
```
### Overlay (type)
```typescript
interface Overlay {
readonly host: HTMLElement;
dispose(): void;
}
```
### OverlayOptions (type)
```typescript
interface OverlayOptions {
readonly store: Store;
readonly document?: Document;
readonly copyText?: (value: string) => void | Promise;
}
```