# 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