The Open Standard for Generative UI
feat: add A2UI support with OpenUI Lang components (#854)
Visharad Kashyapbdbb794ca889
diff --git a/.changeset/config.json b/.changeset/config.jsonindex 084dd3495..9eff22371 100644--- a/.changeset/config.json+++ b/.changeset/config.json@@ -11,7 +11,8 @@"@openuidev/react-lang","@openuidev/svelte-lang","@openuidev/vue-lang",- "@openuidev/angular-lang"+ "@openuidev/angular-lang",+ "@openuidev/a2ui"],["@openuidev/react-headless", "@openuidev/react-ui"]],diff --git a/README.md b/README.mdindex b5fe87faa..793b7993d 100644--- a/README.md+++ b/README.md@@ -104,6 +104,7 @@ Try it yourself in the [Playground](https://www.openui.com/playground): generate| [`@openuidev/svelte-lang`](./packages/svelte-lang) | Svelte integrations | Svelte 5 bindings for defining model-renderable components and rendering streamed OpenUI Lang || [`@openuidev/angular-lang`](./packages/angular-lang) | Angular integrations | Angular bindings for defining component libraries and rendering streamed OpenUI Lang || [`@openuidev/browser-bundle`](./packages/browser-bundle) | CDN, iframe, and no-build embeds | Prebuilt browser bundle that ships the renderer, UI library, React, and styles as script + stylesheet assets |+| [`@openuidev/a2ui`](./packages/a2ui) | A2UI with OpenUI Lang component payloads | Framework-agnostic A2UI v1.0 protocol client with an optional React renderer || [`@openuidev/server`](./packages/server) | Server side utilities | Server utilities for OpenUI and OpenUI Gateway || [`@openuidev/observability-cloud`](./packages/observability-cloud) | Hosted observability in the Thesys console | Cloud sink that batches OpenUI events and ships them to OpenUI Gateway || [`@openuidev/cli`](./packages/openui-cli) | Project scaffolding and prompt generation | CLI for creating new apps and generating system prompts or JSON schema from a library definition |@@ -125,6 +126,9 @@ npm install @openuidev/langchain @langchain/langgraphnpm install @openuidev/vue-langnpm install @openuidev/svelte-langnpm install @openuidev/angular-lang++# A2UI protocol with OpenUI Lang component payloads+npm install @openuidev/a2ui zod```## Why OpenUI Lang@@ -173,6 +177,7 @@ openui/│ ├── svelte-lang/ # Svelte runtime bindings for OpenUI Lang│ ├── angular-lang/ # Angular runtime bindings for OpenUI Lang│ ├── browser-bundle/ # Script-tag bundle for CDN / iframe / no-build embeds+│ ├── a2ui/ # A2UI protocol with OpenUI Lang component payloads│ ├── server/ # Server utilities for OpenUI & OpenUI Gateway│ ├── observability/ # Framework-free observability event bus│ ├── observability-cloud/ # Cloud sink shipping OpenUI events to Thesysdiff --git a/docs/content/docs/api-reference/a2ui.mdx b/docs/content/docs/api-reference/a2ui.mdxnew file mode 100644index 000000000..aa7e2396f--- /dev/null+++ b/docs/content/docs/api-reference/a2ui.mdx@@ -0,0 +1,562 @@+---+title: "@openuidev/a2ui"+description: A2UI v1.0 protocol support with OpenUI Lang component updates and an optional React renderer.+---++`@openuidev/a2ui` implements the [A2UI v1.0 candidate](https://github.com/a2ui-project/a2ui/blob/main/specification/v1_0/docs/a2ui_protocol.md) surface lifecycle while using OpenUI Lang for component payloads.++The package deliberately changes one part of the protocol: `createSurface.components` and `updateComponents.components` are arrays of OpenUI Lang statements instead of A2UI component JSON. All other lifecycle and message envelopes retain their A2UI v1.0 shapes, including surface creation and deletion, data-model updates, actions, function calls and responses, errors, capabilities, and renderer metadata.++```json+{+ "version": "v1.0",+ "updateComponents": {+ "surfaceId": "main",+ "components": [+ "root = Stack([title, save])",+ "title = TextContent(\"Account settings\")",+ "save = Button(\"Save\", onClick: @ToAssistant(\"Save these settings\"))"+ ]+ }+}+```++This gives you A2UI's stateful, bidirectional protocol and OpenUI Lang's compact, streaming-friendly component representation.++## Package structure++The package has two public entrypoints:++| Entrypoint | Environment | Responsibility |+| :---------------------- | :----------------- | :--------------------------------------------------------------------------------------------- |+| `@openuidev/a2ui` | Framework-agnostic | Protocol validation, surfaces, statement patches, data model, actions, functions, and metadata |+| `@openuidev/a2ui/react` | React (optional) | Subscribes to a surface and renders its OpenUI Lang source with `@openuidev/react-lang` |++The core client depends on `@openuidev/lang-core`; it does not depend on React. A Vue, Svelte, native, or server-side host can use the same client and provide its own rendering adapter.++## Installation++Install the framework-neutral client and its Zod peer:++```bash+npm install @openuidev/a2ui zod+```++For React rendering, also install the optional renderer peers:++```bash+npm install react @openuidev/react-lang+```++Install the package that provides your component library as well. For example, the built-in OpenUI library is exported by `@openuidev/react-ui`:++```bash+npm install @openuidev/react-ui+```++## Protocol flow++A typical surface moves through the following lifecycle:++1. The agent sends `createSurface` to allocate a surface and optionally seed its components and data model.+2. The agent sends one or more `updateComponents` messages. Each message patches OpenUI Lang statements by statement ID.+3. The agent can send `updateDataModel` at any time. Renderer state changes can flow back through action context or renderer metadata.+4. User interactions produce A2UI `action` messages from the renderer to the agent.+5. Either side can invoke catalog functions with `callRendererFunction` or `callAgentFunction` and settle them with the corresponding function-response envelope.+6. The agent sends `deleteSurface` when the UI is no longer needed.++The package owns protocol state, not transport. Your application is responsible for carrying messages over SSE, NDJSON, WebSocket, AG-UI, an agent SDK, or another channel, and for passing each decoded message to `client.process()`.++### Supported messages++| Direction | Message | Purpose |+| :--------------- | :------------------------- | :------------------------------------------------------------- |+| Agent → renderer | `createSurface` | Creates a surface, optionally with components and a data model |+| Agent → renderer | `updateComponents` | Adds, replaces, or removes OpenUI Lang statements |+| Agent → renderer | `updateDataModel` | Applies a JSON Pointer update to surface data |+| Agent → renderer | `deleteSurface` | Removes a surface and rejects its pending function calls |+| Agent → renderer | `callRendererFunction` | Invokes a registered renderer function |+| Agent → renderer | `agentFunctionResponse` | Settles a function call initiated by the renderer |+| Renderer → agent | `action` | Reports a user or component interaction |+| Renderer → agent | `callAgentFunction` | Invokes an agent function |+| Renderer → agent | `rendererFunctionResponse` | Returns the result of a requested renderer function |+| Renderer → agent | `error` | Reports validation, lifecycle, or function errors |++## Create a client++Create one client for the set of surfaces handled by a renderer:++```ts+import { createA2UIClient } from "@openuidev/a2ui";+import { openuiLibrary } from "@openuidev/react-ui";++const client = createA2UIClient({+ schema: openuiLibrary.toJSONSchema(),+ rootName: openuiLibrary.root,+ rendererCapabilities: {+ "v1.0": {+ supportedCatalogIds: ["com.example:openui"],+ },+ },+ onMessage(message, metadata) {+ transport.send({ message, metadata });+ },+});+```++### `A2UIClientOptions`++| Option | Type | Description |+| :--------------------- | :----------------------------------------- | :------------------------------------------------------------------------------------- |+| `schema` | `LibraryJSONSchema` | Required OpenUI component schema, normally from `library.toJSONSchema()` |+| `rootName` | `string` | Expected root component name from the library |+| `functions` | `Record<string, function \| registration>` | Renderer functions that incoming `callRendererFunction` messages may invoke |+| `rendererCapabilities` | `RendererCapabilities` | Catalog IDs and optional inline catalogs advertised in outgoing metadata |+| `onMessage` | `(message, metadata) => void` | Receives renderer-to-agent messages emitted by actions, functions, and protocol errors |+| `now` | `() => Date` | Optional clock override, useful for deterministic action timestamps in tests |+| `createId` | `() => string` | Optional ID generator for renderer-initiated agent function calls |++The schema and the rendered library must describe the same components. `catalogId` is a protocol identifier and capability check; the client does not download a catalog or choose a component library from that ID.++## Process agent messages++Pass decoded agent-to-renderer messages to `process()` in arrival order:++```ts+await client.process({+ version: "v1.0",+ createSurface: {+ surfaceId: "main",+ catalogId: "com.example:openui",+ sendDataModel: true,+ dataModel: {+ user: { name: "Alice" },+ },+ },+});++await client.process({+ version: "v1.0",+ updateComponents: {+ surfaceId: "main",+ components: ["root = Stack([greeting])", 'greeting = TextContent("Hello, " + $user.name)'],+ },+});+```++`process(input)` validates the envelope at runtime and returns:++```ts+interface ProcessResult {+ ok: boolean;+ outbound: RendererToAgentMessage[];+ issues?: Array<{ path: string; message: string }>;+}+```++`outbound` contains the messages emitted while processing that input. The same messages are also delivered to `onMessage` and `subscribeMessages()` listeners. A host can use either mechanism, but should avoid sending the same outbound message twice.++## Component updates++Each `components` entry is an OpenUI Lang statement or multiline statement block. Updates are merged by statement ID:++```json+{+ "version": "v1.0",+ "updateComponents": {+ "surfaceId": "main",+ "components": ["status = Badge(\"Saving\")"]+ }+}+```++- A new ID adds a statement.+- An existing ID replaces its previous statement without changing its position.+- `statementId = null` removes that statement.+- `root` remains the surface root.+- Statements may arrive before they are reachable from `root`; the client preserves them so a later patch can attach them.+- Entries are applied in array order, so a later entry for the same ID wins.++For example:++```ts+await client.process({+ version: "v1.0",+ updateComponents: {+ surfaceId: "main",+ components: [+ 'status = Badge("Saved")', // replace status+ "oldHelpText = null", // remove oldHelpText+ ],+ },+});+```++### Streaming component generation++An `updateComponents` message is a statement patch, not a raw text-delta event. When an LLM is generating OpenUI Lang, keep the current accumulated statement or statement block and send replacements under the same statement ID:++```ts+for await (const sourceSoFar of generateOpenUILang()) {+ await client.process({+ version: "v1.0",+ updateComponents: {+ surfaceId: "main",+ components: [sourceSoFar],+ },+ });+}+```++For true progressive rendering:++- Send `createSurface` as soon as the surface is known.+- Forward patches as model output arrives instead of buffering the complete generation.+- Send the accumulated source for an ID, not only the latest token delta. Statement replacement then produces a coherent surface snapshot.+- Stream raw OpenUI Lang without Markdown code fences. A fenced block cannot be interpreted until its closing fence arrives.+- Set the React adapter's `isStreaming` prop while the turn is active. The underlying OpenUI renderer can then render the usable prefix and tolerate incomplete trailing syntax.+- Mark streaming complete only after the final patch has been processed.++Transport boundaries and Lang statement boundaries do not need to match, but every `client.process()` call must receive a valid A2UI JSON envelope.++## Surface state++Read or subscribe to the framework-neutral surface store:++```ts+const unsubscribe = client.subscribe(() => {+ const surface = client.getSurface("main");+ console.log(surface?.source, surface?.dataModel, surface?.revision);+});++const allSurfaces = client.getSurfaces();++unsubscribe();+```++Each snapshot has the following shape:++```ts+interface SurfaceSnapshot {+ surfaceId: string;+ catalogId?: string;+ metadata?: A2UIMessageMetadata;+ sendDataModel: boolean;+ source: string;+ dataModel: JsonObject;+ parseResult: ParseResult | null;+ errors: OpenUIError[];+ revision: number;+}+```++`source` is the merged OpenUI Lang document. `parseResult` and `errors` come from `@openuidev/lang-core`. `revision` increases whenever any surface changes and is suitable for external-store subscriptions.++## Data-model updates++`updateDataModel` applies a JSON Pointer patch to a surface:++```ts+await client.process({+ version: "v1.0",+ updateDataModel: {+ surfaceId: "main",+ path: "/user/name",+ value: "Bob",+ },+});+```++The data model is always an object. The update behavior is:++| Input | Result |+| :----------------------------- | :----------------------------------------------------------------- |+| Missing `path`, `""`, or `"/"` | Replaces the root object |+| Nested object path | Creates missing object or array containers as needed |+| `null` at a property path | Deletes that property |+| `null` at an array index | Removes that item with `splice` semantics |+| `null` at the root | Resets the model to `{}` |+| Primitive or array at the root | Produces a validation error because the root must remain an object |++OpenUI Lang bindings use the same top-level keys. A data-model value such as `{ user: { name: "Bob" } }` is exposed to Lang as `$user`, so `$user.name` resolves to `"Bob"`.++The React adapter also synchronizes form state back into the surface data model. Use the framework-neutral method directly when building another adapter:++```ts+client.updateSurfaceFromOpenUIState("main", openUIState);+```++## Render a surface in React++Import the renderer from the optional React entrypoint:++```tsx+import { A2UIRenderer } from "@openuidev/a2ui/react";+import { openuiLibrary } from "@openuidev/react-ui";++export function Surface({ isStreaming }: { isStreaming: boolean }) {+ return (+ <A2UIRenderer+ client={client}+ surfaceId="main"+ library={openuiLibrary}+ isStreaming={isStreaming}+ onError={(errors) => console.error(errors)}+ />+ );+}+```++The component subscribes to the client with `useSyncExternalStore`, reads the requested surface, and passes its merged source and data model to the `@openuidev/react-lang` renderer. It returns `null` until that surface exists.++### `A2UIRendererProps`++| Prop | Type | Description |+| :-------------- | :------------------------------ | :---------------------------------------------------------------------------------------- |+| `client` | `A2UIClient` | Required protocol client |+| `surfaceId` | `string` | Surface to subscribe to and render |+| `library` | `Library` | React component library matching the schema given to the client |+| `isStreaming` | `boolean` | Whether the surrounding transport is still delivering the current agent turn |+| `mapAction` | `(event, surface) => options` | Maps an OpenUI action to A2UI name, source component, user message, context, and metadata |+| `onAction` | `(event, surface) => void` | Observes actions after built-in handling |+| `onOpenUrl` | `(url, event, surface) => void` | Handles `@OpenUrl`; defaults to a safe `window.open` in browsers |+| `onStateUpdate` | `(state, surface) => void` | Observes OpenUI state after it has been merged into the A2UI data model |+| `onParseResult` | `(result) => void` | Receives OpenUI Lang parse results |+| `onError` | `(errors) => void` | Receives OpenUI parser/runtime errors |+| `formStateKeys` | `readonly string[]` | Adds top-level data-model keys that should also hydrate form namespaces |+| `toolProvider` | `RendererProps["toolProvider"]` | Overrides the default A2UI routing for OpenUI Lang `Query()` and `Mutation()` calls |+| `queryLoader` | `ReactNode` | UI shown while a query is loading |++`@OpenUrl` is handled locally and is not emitted as an A2UI action. Other OpenUI actions are converted to A2UI actions automatically.++Without a `toolProvider`, the adapter routes OpenUI Lang `Query()` and `Mutation()` calls to the agent with `callAgentFunction`. Pass a `toolProvider` to execute those calls locally instead. The client's `functions` option handles the opposite direction: `callRendererFunction` messages sent by the agent.++## Actions++You can dispatch an action directly from any renderer adapter:++```ts+client.dispatchAction({+ surfaceId: "main",+ sourceComponentId: "saveButton",+ name: "save",+ context: { section: "profile" },+});+```++This emits an A2UI renderer-to-agent message through `onMessage`:++```json+{+ "version": "v1.0",+ "action": {+ "name": "save",+ "surfaceId": "main",+ "sourceComponentId": "saveButton",+ "timestamp": "2026-01-01T12:00:00.000Z",+ "context": { "section": "profile" }+ }+}+```++The React adapter calls `dispatchOpenUIAction()` for you. By default it uses the OpenUI action type as `name`, forwards the human-friendly message as `userMessage`, includes action params and form state in `context`, and uses `"root"` as the source component. Customize that mapping when your agent expects a more specific component ID or domain-specific action name:++```tsx+<A2UIRenderer+ client={client}+ surfaceId="main"+ library={openuiLibrary}+ mapAction={(event) => ({+ name: event.type === "continue_conversation" ? "submit" : event.type,+ sourceComponentId: "profileForm",+ context: { origin: "settings" },+ })}+/>+```++## Agent functions++Use `callAgentFunction()` when the renderer needs a correlated result from an agent-side function:++```ts+const response = client.callAgentFunction({+ surfaceId: "main",+ call: "saveProfile",+ args: { section: "profile" },+});+```++The client emits the current renderer-to-agent envelope:++```json+{+ "version": "v1.0",+ "callAgentFunction": {+ "surfaceId": "main",+ "functionCallId": "generated-call-id",+ "callFunction": {+ "call": "saveProfile",+ "args": { "section": "profile" }+ }+ }+}+```++Pass the matching agent response back to the client:++```ts+await client.process({+ version: "v1.0",+ agentFunctionResponse: {+ functionCallId: "generated-call-id",+ value: { saved: true },+ },+});++await response; // { saved: true }+```++An `agentFunctionResponse.error` rejects the promise with `A2UIFunctionError`. The React adapter uses this same path for OpenUI Lang `Query()` and `Mutation()` calls when no local `toolProvider` is supplied.++## Renderer functions++Register functions that the agent may ask the renderer to execute:++```ts+const client = createA2UIClient({+ schema: openuiLibrary.toJSONSchema(),+ functions: {+ getLocation: {+ catalogId: "com.example:functions",+ allowedCallers: "agentOnly",+ async handler() {+ return { latitude: 37.7749, longitude: -122.4194 };+ },+ },+ },+ onMessage(message, metadata) {+ transport.send({ message, metadata });+ },+});+```++Incoming call:++```json+{+ "version": "v1.0",+ "callRendererFunction": {+ "functionCallId": "call-1",+ "callFunction": {+ "call": "getLocation",+ "catalogId": "com.example:functions",+ "args": {}+ }+ }+}+```++The client always emits a correlated result:++```json+{+ "version": "v1.0",+ "rendererFunctionResponse": {+ "functionCallId": "call-1",+ "value": { "latitude": 37.7749, "longitude": -122.4194 }+ }+}+```++Registrations support `"rendererOnly"`, `"agentOnly"`, and `"rendererOrAgent"`. Object registrations default to `"rendererOnly"`, so set `allowedCallers` and `catalogId` explicitly for agent-callable functions. A direct function value is renderer-only shorthand and is never callable by an incoming agent message.++Unknown functions, disallowed calls, and handler failures produce protocol error messages correlated by `functionCallId`.++## Capabilities and renderer metadata++Configure capabilities when creating the client:++```ts+const client = createA2UIClient({+ schema,+ rendererCapabilities: {+ "v1.0": {+ supportedCatalogIds: ["com.example:openui"],+ inlineCatalogs: [],+ },+ },+});+```++If the renderer advertises at least one catalog ID, `createSurface` rejects an unsupported `catalogId`. The package does not automatically negotiate or install component libraries; your agent and renderer must be configured with the same OpenUI Lang component schema.++When a surface sets `sendDataModel: true`, `getRendererMetadata()` includes its current data model:++```ts+const metadata = client.getRendererMetadata();+// {+// a2uiRendererCapabilities: { ... },+// a2uiRendererDataModel: {+// version: "v1.0",+// surfaces: { main: { ... } }+// }+// }+```++The metadata is supplied as the second argument to `onMessage` and message subscribers. Your transport decides whether it is attached to a model request, agent context, or another protocol-specific location.++## Runtime validation and TypeScript types++Zod is the source of truth for runtime validation and inferred TypeScript types.++```ts+import {+ agentToRendererMessageSchema,+ rendererToAgentMessageSchema,+ validateAgentToRendererMessage,+ type AgentToRendererMessage,+ type RendererToAgentMessage,+} from "@openuidev/a2ui";++const result = agentToRendererMessageSchema.safeParse(input);+const validated = validateAgentToRendererMessage(input);+```++The package exports runtime Zod schemas for every message and shared protocol structure, including capabilities and renderer data-model metadata. The public TypeScript message types are inferred from those definitions, keeping runtime behavior and static types aligned without maintaining a second schema format.++## Client API++| Method | Description |+| :------------------------------------------------- | :---------------------------------------------------------------------- |+| `process(input)` | Validates and applies one agent-to-renderer message |+| `getSurface(surfaceId)` | Returns one surface snapshot, or `undefined` |+| `getSurfaces()` | Returns all current surface snapshots |+| `subscribe(listener)` | Subscribes to surface-store changes and returns an unsubscribe function |+| `subscribeMessages(listener)` | Subscribes to emitted renderer-to-agent messages and metadata |+| `dispatchAction(input)` | Emits an A2UI action |+| `dispatchOpenUIAction(surfaceId, event, options?)` | Converts an OpenUI action event into an A2UI action |+| `callAgentFunction(input)` | Emits `callAgentFunction` and returns its correlated response promise |+| `updateSurfaceFromOpenUIState(surfaceId, state)` | Merges OpenUI bindings and form state into a surface data model |+| `getRendererDataModel()` | Returns opted-in surface models in the A2UI renderer-data-model shape |+| `getRendererMetadata()` | Returns configured capabilities and opted-in data-model metadata |+| `dispose()` | Rejects pending function calls, clears surfaces, and removes listeners |++## Errors and cleanup++Malformed envelopes are rejected before they mutate state. When the invalid input identifies a surface or function call, the client also emits a correlated A2UI error message. OpenUI Lang validation errors are stored on the surface and emitted as `VALIDATION_FAILED` messages.++Call `dispose()` when the client is no longer needed:++```ts+client.dispose();+```++Deleting a surface or disposing the client rejects pending agent-function promises for that surface with `A2UIFunctionError`.++## Compatibility notes++- This package is currently experimental and implements the v1.0 message profile described above.+- It is not wire-compatible with a renderer that expects A2UI JSON component objects in `components`; both sides must agree that the array contains OpenUI Lang.+- The protocol client is framework-neutral. Only `@openuidev/a2ui/react` requires React and `@openuidev/react-lang`.+- The protocol does not define your transport. Preserve message order per surface and pass complete JSON envelopes to `process()`.+- The agent and renderer must use the same OpenUI component library/schema.diff --git a/docs/content/docs/api-reference/index.mdx b/docs/content/docs/api-reference/index.mdxindex 0ccbd36de..e31d75cd6 100644--- a/docs/content/docs/api-reference/index.mdx+++ b/docs/content/docs/api-reference/index.mdx@@ -33,6 +33,8 @@ The OpenUI SDK is split into packages that build on each other:- **`@openuidev/angular-lang`** — Angular bindings for defining component libraries with Zod schemas, generating prompts, and rendering streamed OpenUI Lang with reactive state and actions.+- **`@openuidev/a2ui`** — Framework-agnostic A2UI v1.0 protocol client that uses OpenUI Lang statements for component payloads. Add the optional React entrypoint to render surfaces with `@openuidev/react-lang`.+## Choosing a package| If you need... | Start here |@@ -51,6 +53,7 @@ The OpenUI SDK is split into packages that build on each other:| An in-app panel showing captured errors during development | [`@openuidev/devtools`](/docs/api-reference/devtools) || App scaffolding, prompt/schema generation, and deploy from the command line | [`@openuidev/cli`](/docs/api-reference/cli) || Angular integration | [`@openuidev/angular-lang`](/docs/api-reference/angular-lang) |+| A2UI lifecycle and messages with OpenUI Lang component payloads | [`@openuidev/a2ui`](/docs/api-reference/a2ui) |## Packages@@ -117,4 +120,8 @@ The OpenUI SDK is split into packages that build on each other:Angular component definitions, Renderer inputs and outputs, injection helpers, and formvalidation.</Card>+ <Card title="@openuidev/a2ui" href="/docs/api-reference/a2ui">+ A2UI v1.0 surface lifecycle, messages, actions, data model, functions, and schemas with OpenUI+ Lang component updates.+ </Card></Cards>diff --git a/docs/content/docs/api-reference/meta.json b/docs/content/docs/api-reference/meta.jsonindex 8ad4c9cf7..fa18a8b7a 100644--- a/docs/content/docs/api-reference/meta.json+++ b/docs/content/docs/api-reference/meta.json@@ -12,6 +12,7 @@"react-email","devtools","cli",- "angular-lang"+ "angular-lang",+ "a2ui"]}diff --git a/packages/a2ui/README.md b/packages/a2ui/README.mdnew file mode 100644index 000000000..97245597e--- /dev/null+++ b/packages/a2ui/README.md@@ -0,0 +1,97 @@+# `@openuidev/a2ui`++An experimental A2UI v1.0 profile that keeps the protocol lifecycle and envelopes intact while representing component lists as OpenUI Lang statements.++```json+{+ "version": "v1.0",+ "updateComponents": {+ "surfaceId": "main",+ "components": ["root = Stack([title])", "title = TextContent(\"Hello\")"]+ }+}+```++`updateDataModel`, `deleteSurface`, actions, `callRendererFunction`, `agentFunctionResponse`, `callAgentFunction`, `rendererFunctionResponse`, errors, capabilities, and renderer data-model metadata retain their A2UI v1.0 shapes. For v1.0 single-message creation, optional `createSurface.components` uses the same Lang statement array as `updateComponents.components`, so there is exactly one component representation on the wire.++Incoming protocol messages are validated with the exported Zod schemas in the package. The public TypeScript message types are inferred from the same definitions, so runtime validation and static types stay aligned.++## Installation++Install the framework-neutral protocol client with its runtime schema peer:++```bash+npm install @openuidev/a2ui zod+```++The React adapter is optional. Install its peers only when importing `@openuidev/a2ui/react`:++```bash+npm install react @openuidev/react-lang+```++## How updates work++Each array item is one complete OpenUI Lang statement (a multiline statement block is also accepted). Repeated messages are merged by statement ID and the resulting source is parsed by `@openuidev/lang-core`. A newer assignment replaces the previous statement, and `statementId = null` deletes it. The `root` statement remains the surface root.++## Usage++```tsx+import { createA2UIClient } from "@openuidev/a2ui";+import { A2UIRenderer } from "@openuidev/a2ui/react";+import { openuiLibrary } from "@openuidev/react-ui";++const client = createA2UIClient({+ schema: openuiLibrary.toJSONSchema(),+ rootName: openuiLibrary.root,+ rendererCapabilities: {+ "v1.0": { supportedCatalogIds: ["com.example:openui"] },+ },+ onMessage(message, metadata) {+ transport.send(message, metadata);+ },+});++await client.process({+ version: "v1.0",+ createSurface: {+ surfaceId: "main",+ catalogId: "com.example:openui",+ dataModel: { user: { name: "Alice" } },+ },+});++await client.process({+ version: "v1.0",+ updateComponents: {+ surfaceId: "main",+ components: ["root = Stack([greeting])", 'greeting = TextContent("Hello, " + $user.name)'],+ },+});++export function Surface() {+ return (+ <A2UIRenderer+ client={client}+ surfaceId="main"+ library={openuiLibrary}+ isStreaming={transport.isStreaming}+ mapAction={(event) => ({ name: event.type })}+ />+ );+}+```++The client is framework-neutral: it owns surface lifecycle, runtime envelope validation, Lang parsing and merging, data-model patches, actions, RPC, and protocol errors. `A2UIRenderer` is the React adapter; it subscribes to one surface and delegates the parsed OpenUI Lang UI to `@openuidev/react-lang`.++When `sendDataModel` is enabled, the second `onMessage` argument contains `a2uiRendererDataModel` metadata filtered to opted-in surfaces. Configured renderer capabilities are exposed in the same metadata object. The host transport decides where to attach this metadata.++Renderer functions can be registered as a direct function shorthand or as `{ handler, catalogId, allowedCallers }`. Explicit registrations default to `rendererOnly`; incoming `callRendererFunction` messages are accepted only when the catalog ID matches and `allowedCallers` is `agentOnly` or `rendererOrAgent`.++When no `toolProvider` is passed to `A2UIRenderer`, OpenUI Lang `Query()` and `Mutation()` calls automatically use A2UI `callAgentFunction` and settle from the matching `agentFunctionResponse`. Pass a `toolProvider` to handle those calls locally instead.++Use `mapAction` to provide `sourceComponentId` when the host renderer does not include one in its action event. Otherwise actions fall back to the surface `root` ID.++## Development++The `check:attw` script intentionally ignores the `no-resolution` rule. `./react` is exported through modern package `exports`; `attw` reports `no-resolution` only for legacy Node 10 resolution, which this package does not support.diff --git a/packages/a2ui/eslint.config.cjs b/packages/a2ui/eslint.config.cjsnew file mode 100644index 000000000..3276216a5--- /dev/null+++ b/packages/a2ui/eslint.config.cjs@@ -0,0 +1,3 @@+const base = require("../../eslint.config.cjs");++module.exports = [...base];diff --git a/packages/a2ui/package.json b/packages/a2ui/package.jsonnew file mode 100644index 000000000..c65a33a9c--- /dev/null+++ b/packages/a2ui/package.json@@ -0,0 +1,95 @@+{+ "name": "@openuidev/a2ui",+ "version": "0.3.0",+ "description": "A2UI v1.0 protocol support with OpenUI Lang component updates and React rendering",+ "license": "MIT",+ "type": "module",+ "main": "dist/index.cjs",+ "module": "dist/index.mjs",+ "types": "dist/index.d.cts",+ "sideEffects": false,+ "files": [+ "dist",+ "README.md"+ ],+ "exports": {+ ".": {+ "import": {+ "types": "./dist/index.d.mts",+ "default": "./dist/index.mjs"+ },+ "require": {+ "types": "./dist/index.d.cts",+ "default": "./dist/index.cjs"+ }+ },+ "./react": {+ "import": {+ "types": "./dist/react.d.mts",+ "default": "./dist/react.mjs"+ },+ "require": {+ "types": "./dist/react.d.cts",+ "default": "./dist/react.cjs"+ }+ }+ },+ "scripts": {+ "test": "vitest run",+ "build": "tsdown",+ "watch": "tsdown --watch",+ "typecheck": "tsc --noEmit",+ "lint:check": "eslint ./src",+ "lint:fix": "eslint ./src --fix",+ "format:fix": "prettier --write ./src README.md",+ "format:check": "prettier --check ./src README.md",+ "check:publint": "publint",+ "check:attw": "attw --pack . --ignore-rules=no-resolution",+ "prepare": "pnpm run build",+ "prepublishOnly": "pnpm run check:publint && pnpm run check:attw",+ "ci": "pnpm run lint:check && pnpm run format:check"+ },+ "keywords": [+ "a2ui",+ "openui",+ "openui-lang",+ "generative-ui",+ "renderer",+ "protocol"+ ],+ "homepage": "https://openui.com",+ "repository": {+ "type": "git",+ "url": "https://github.com/thesysdev/openui.git",+ "directory": "packages/a2ui"+ },+ "bugs": {+ "url": "https://github.com/thesysdev/openui/issues"+ },+ "author": "[email protected]",+ "dependencies": {+ "@openuidev/lang-core": "workspace:^"+ },+ "peerDependencies": {+ "@openuidev/react-lang": ">=0.3.0 <0.4.0",+ "react": "catalog:",+ "zod": "catalog:"+ },+ "peerDependenciesMeta": {+ "@openuidev/react-lang": {+ "optional": true+ },+ "react": {+ "optional": true+ }+ },+ "devDependencies": {+ "@openuidev/react-lang": "workspace:^",+ "@types/react": "catalog:",+ "@types/react-dom": "catalog:",+ "jsdom": "catalog:",+ "react": "catalog:",+ "react-dom": "catalog:",+ "vitest": "^4.0.18"+ }+}diff --git a/packages/a2ui/src/Renderer.tsx b/packages/a2ui/src/Renderer.tsxnew file mode 100644index 000000000..a3a3acfde--- /dev/null+++ b/packages/a2ui/src/Renderer.tsx@@ -0,0 +1,145 @@+import {+ BuiltinActionType,+ type ActionEvent,+ type OpenUIError,+ type ParseResult,+} from "@openuidev/lang-core";+import {+ Renderer as OpenUIRenderer,+ type Library,+ type RendererProps as OpenUIRendererProps,+} from "@openuidev/react-lang";+import { useCallback, useMemo, useSyncExternalStore } from "react";+import type { A2UIClient } from "./client";+import { dataModelToOpenUIState, toJsonObject } from "./json-pointer";+import type { MapOpenUIAction, OpenUIActionOptions, SurfaceSnapshot } from "./types";++export interface A2UIRendererProps {+ client: A2UIClient;+ surfaceId: string;+ library: Library;+ mapAction?: MapOpenUIAction;+ onAction?: (event: ActionEvent, surface: SurfaceSnapshot) => void;+ /** Handles OpenUI @OpenUrl locally. Defaults to window.open in browsers. */+ onOpenUrl?: (url: string, event: ActionEvent, surface: SurfaceSnapshot) => void;+ onStateUpdate?: (state: Record<string, unknown>, surface: SurfaceSnapshot) => void;+ onParseResult?: (result: ParseResult | null) => void;+ onError?: (errors: OpenUIError[]) => void;+ /** Whether the surrounding A2UI transport is still delivering this agent turn. */+ isStreaming?: boolean;+ /** Additional top-level data-model keys that should hydrate form namespaces. */+ formStateKeys?: readonly string[];+ toolProvider?: OpenUIRendererProps["toolProvider"];+ queryLoader?: OpenUIRendererProps["queryLoader"];+}++function collectFormStateKeys(result: ParseResult | null): string[] {+ const keys = new Set<string>();+ const seen = new WeakSet<object>();+ const visit = (value: unknown): void => {+ if (Array.isArray(value)) {+ for (const item of value) visit(item);+ return;+ }+ if (!value || typeof value !== "object" || seen.has(value)) return;+ seen.add(value);+ const object = value as Record<string, unknown>;+ if (object.type === "element" && object.typeName === "Form") {+ const props = object.props as Record<string, unknown> | undefined;+ if (typeof props?.name === "string") keys.add(props.name);+ }+ for (const child of Object.values(object)) visit(child);+ };+ visit(result?.root);+ return [...keys];+}++export function A2UIRenderer({+ client,+ surfaceId,+ library,+ mapAction,+ onAction,+ onOpenUrl,+ onStateUpdate,+ onParseResult,+ onError,+ isStreaming = false,+ formStateKeys,+ toolProvider,+ queryLoader,+}: A2UIRendererProps) {+ const subscribe = useCallback((notify: () => void) => client.subscribe(notify), [client]);+ const getSnapshot = useCallback(() => client.getSurface(surfaceId), [client, surfaceId]);+ const surface = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);+ const initialState = useMemo(() => {+ if (!surface) return undefined;+ const keys = new Set([...collectFormStateKeys(surface.parseResult), ...(formStateKeys ?? [])]);+ return dataModelToOpenUIState(surface.dataModel, keys);+ }, [formStateKeys, surface]);+ const agentToolProvider = useMemo<NonNullable<OpenUIRendererProps["toolProvider"]>>(+ () => ({+ async callTool({+ name,+ arguments: args,+ }: {+ name: string;+ arguments?: Record<string, unknown>;+ }) {+ const value = await client.callAgentFunction({+ surfaceId,+ call: name,+ args: toJsonObject(args),+ });+ return { content: [], structuredContent: value };+ },+ }),+ [client, surfaceId],+ );++ const handleAction = useCallback(+ (event: ActionEvent) => {+ const current = client.getSurface(surfaceId);+ if (!current) return;+ if (event.type === BuiltinActionType.OpenUrl) {+ const url = event.params?.url;+ if (typeof url === "string") {+ if (onOpenUrl) onOpenUrl(url, event, current);+ else if (typeof window !== "undefined") window.open(url, "_blank", "noopener,noreferrer");+ }+ onAction?.(event, current);+ return;+ }+ const options: OpenUIActionOptions = mapAction?.(event, current) ?? {};+ client.dispatchOpenUIAction(surfaceId, event, options);+ onAction?.(event, current);+ },+ [client, mapAction, onAction, onOpenUrl, surfaceId],+ );++ const handleStateUpdate = useCallback(+ (state: Record<string, unknown>) => {+ if (!client.updateSurfaceFromOpenUIState(surfaceId, state)) return;+ const current = client.getSurface(surfaceId);+ if (current) onStateUpdate?.(state, current);+ },+ [client, onStateUpdate, surfaceId],+ );++ if (!surface) return null;++ return (+ <OpenUIRenderer+ response={surface.source}+ library={library}+ initialState={initialState}+ isStreaming={isStreaming}+ onAction={handleAction}+ onStateUpdate={handleStateUpdate}+ onParseResult={onParseResult}+ onError={onError}+ toolProvider={toolProvider ?? agentToolProvider}+ queryLoader={queryLoader}+ />+ );+}diff --git a/packages/a2ui/src/__tests__/Renderer.test.tsx b/packages/a2ui/src/__tests__/Renderer.test.tsxnew file mode 100644index 000000000..327b4b651--- /dev/null+++ b/packages/a2ui/src/__tests__/Renderer.test.tsx@@ -0,0 +1,250 @@+import {+ createLibrary,+ defineComponent,+ FormNameContext,+ useIsStreaming,+ useStateField,+} from "@openuidev/react-lang";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it, vi } from "vitest";+import { z } from "zod/v4";+import { createA2UIClient } from "../client";+import { A2UIRenderer } from "../Renderer";+import type { RendererToAgentMessage } from "../types";++const TextContent = defineComponent({+ name: "TextContent",+ description: "Text",+ props: z.object({ text: z.string() }),+ component: ({ props, statementId }) => <span data-statement={statementId}>{props.text}</span>,+});++const Stack = defineComponent({+ name: "Stack",+ description: "Stack",+ props: z.object({ children: z.array(TextContent.ref) }),+ component: ({ props, renderNode }) => <div>{renderNode(props.children)}</div>,+});++const library = createLibrary({ components: [Stack, TextContent], root: "Stack" });++const Field = defineComponent({+ name: "Field",+ description: "Interactive test field",+ props: z.object({ name: z.string() }),+ component: ({ props }) => {+ const field = useStateField<string>(props.name);+ const isStreaming = useIsStreaming();+ return (+ <button+ data-streaming={String(isStreaming)}+ disabled={isStreaming}+ onClick={() => field.setValue("[email protected]")}+ >+ {field.value ?? ""}+ </button>+ );+ },+});++const Form = defineComponent({+ name: "Form",+ description: "Test form",+ props: z.object({ name: z.string(), fields: z.array(Field.ref) }),+ component: ({ props, renderNode }) => (+ <FormNameContext.Provider value={props.name}>+ {renderNode(props.fields)}+ </FormNameContext.Provider>+ ),+});++const formLibrary = createLibrary({ components: [Form, Field], root: "Form" });++describe("A2UIRenderer", () => {+ it("renders the active A2UI surface through the OpenUI Lang React renderer", async () => {+ const client = createA2UIClient({+ schema: library.toJSONSchema(),+ rootName: library.root,+ });+ await client.process({+ version: "v1.0",+ createSurface: { surfaceId: "main", catalogId: "com.example:test" },+ });+ await client.process({+ version: "v1.0",+ updateComponents: {+ surfaceId: "main",+ components: ["root = Stack([greeting])", 'greeting = TextContent("Hello A2UI")'],+ },+ });++ const html = renderToStaticMarkup(+ <A2UIRenderer client={client} surfaceId="main" library={library} />,+ );+ expect(html).toContain("Hello A2UI");+ expect(html).toContain('data-statement="greeting"');+ });++ it("renders nothing after the surface is deleted", async () => {+ const client = createA2UIClient({ schema: library.toJSONSchema() });+ await client.process({+ version: "v1.0",+ createSurface: { surfaceId: "main", catalogId: "com.example:test" },+ });+ await client.process({+ version: "v1.0",+ deleteSurface: { surfaceId: "main" },+ });++ expect(+ renderToStaticMarkup(<A2UIRenderer client={client} surfaceId="main" library={library} />),+ ).toBe("");+ });++ it("keeps live form input and the A2UI data model converged", async () => {+ const client = createA2UIClient({+ schema: formLibrary.toJSONSchema(),+ rootName: formLibrary.root,+ });+ await client.process({+ version: "v1.0",+ createSurface: {+ surfaceId: "main",+ dataModel: { contact: { email: "[email protected]" } },+ components: ['root = Form("contact", [email])', 'email = Field("email")'],+ },+ });++ const container = document.createElement("div");+ document.body.append(container);+ const root = createRoot(container);+ const onStateUpdate = vi.fn();+ const revisionBeforeInput = client.getSurface("main")!.revision;++ await act(async () => {+ root.render(+ <A2UIRenderer+ client={client}+ surfaceId="main"+ library={formLibrary}+ onStateUpdate={onStateUpdate}+ />,+ );+ });+ const button = container.querySelector("button")!;+ expect(button.textContent).toBe("[email protected]");++ await act(async () => {+ button.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ expect(button.textContent).toBe("[email protected]");+ expect(client.getSurface("main")?.dataModel).toEqual({+ contact: { email: "[email protected]" },+ });+ expect(client.getSurface("main")?.revision).toBe(revisionBeforeInput + 1);+ expect(onStateUpdate).toHaveBeenCalledTimes(1);++ await act(async () => {+ await Promise.resolve();+ });+ expect(client.getSurface("main")?.dataModel).toEqual({+ contact: { email: "[email protected]" },+ });++ await act(async () => {+ await client.process({+ version: "v1.0",+ updateDataModel: {+ surfaceId: "main",+ path: "/contact/email",+ value: "[email protected]",+ },+ });+ });+ expect(button.textContent).toBe("[email protected]");+ expect(client.getSurface("main")?.dataModel).toEqual({+ contact: { email: "[email protected]" },+ });++ await act(async () => root.unmount());+ container.remove();+ });++ it("forwards the A2UI transport streaming state", async () => {+ const client = createA2UIClient({+ schema: formLibrary.toJSONSchema(),+ rootName: formLibrary.root,+ });+ await client.process({+ version: "v1.0",+ createSurface: {+ surfaceId: "main",+ components: ['root = Form("contact", [email])', 'email = Field("email")'],+ },+ });+ const container = document.createElement("div");+ const root = createRoot(container);++ await act(async () => {+ root.render(+ <A2UIRenderer client={client} surfaceId="main" library={formLibrary} isStreaming />,+ );+ });+ expect(container.querySelector("button")?.disabled).toBe(true);+ expect(container.querySelector("button")?.dataset.streaming).toBe("true");++ await act(async () => root.unmount());+ });++ it("routes OpenUI Query calls through A2UI callAgentFunction by default", async () => {+ const messages: RendererToAgentMessage[] = [];+ const client = createA2UIClient({+ schema: library.toJSONSchema(),+ rootName: library.root,+ createId: () => "query-call-1",+ onMessage: (message) => messages.push(message),+ });+ await client.process({+ version: "v1.0",+ createSurface: {+ surfaceId: "main",+ components: [+ 'data = Query("lookup", {id: 42}, {text: "Loading"})',+ "root = Stack([greeting])",+ "greeting = TextContent(data.text)",+ ],+ },+ });+ const container = document.createElement("div");+ const root = createRoot(container);++ await act(async () => {+ root.render(<A2UIRenderer client={client} surfaceId="main" library={library} />);+ await new Promise((resolve) => setTimeout(resolve, 0));+ });+ expect(messages.at(-1)).toEqual({+ version: "v1.0",+ callAgentFunction: {+ surfaceId: "main",+ functionCallId: "query-call-1",+ callFunction: { call: "lookup", args: { id: 42 } },+ },+ });++ await act(async () => {+ await client.process({+ version: "v1.0",+ agentFunctionResponse: {+ functionCallId: "query-call-1",+ value: { text: "Loaded from agent" },+ },+ });+ await new Promise((resolve) => setTimeout(resolve, 0));+ });+ expect(container.textContent).toContain("Loaded from agent");++ await act(async () => root.unmount());+ });+});diff --git a/packages/a2ui/src/__tests__/client.test.ts b/packages/a2ui/src/__tests__/client.test.tsnew file mode 100644index 000000000..c8ba265cb--- /dev/null+++ b/packages/a2ui/src/__tests__/client.test.ts@@ -0,0 +1,543 @@+import type { LibraryJSONSchema } from "@openuidev/lang-core";+import { describe, expect, it, vi } from "vitest";+import { A2UIFunctionError, createA2UIClient } from "../client";+import {+ applyDataModelUpdate,+ dataModelToOpenUIState,+ mergeOpenUIStateIntoDataModel,+} from "../json-pointer";+import type { RendererToAgentMessage } from "../types";++const schema: LibraryJSONSchema = {+ $defs: {+ Stack: {+ properties: { children: {} },+ required: ["children"],+ },+ TextContent: {+ properties: { text: {}, variant: {} },+ required: ["text"],+ },+ },+};++function createSurface(client: ReturnType<typeof createA2UIClient>) {+ return client.process({+ version: "v1.0",+ createSurface: {+ surfaceId: "main",+ catalogId: "com.example:openui",+ dataModel: { user: { name: "Alice" } },+ },+ });+}++describe("A2UIClient", () => {+ it("runs the A2UI surface lifecycle with incremental OpenUI Lang updates", async () => {+ const client = createA2UIClient({ schema });++ expect((await createSurface(client)).ok).toBe(true);+ expect(+ (+ await client.process({+ version: "v1.0",+ updateComponents: {+ surfaceId: "main",+ components: ["root = Stack([title])", 'title = TextContent("Hello")'],+ },+ })+ ).ok,+ ).toBe(true);++ let surface = client.getSurface("main");+ expect(surface?.parseResult?.root?.typeName).toBe("Stack");+ expect(surface?.parseResult?.root?.props.children).toEqual([+ expect.objectContaining({+ typeName: "TextContent",+ statementId: "title",+ props: { text: "Hello", variant: undefined },+ }),+ ]);++ await client.process({+ version: "v1.0",+ updateComponents: {+ surfaceId: "main",+ components: ['title = TextContent("Updated")'],+ },+ });+ expect(client.getSurface("main")?.source).toContain('title = TextContent("Updated")');+ expect(client.getSurface("main")?.source).not.toContain('TextContent("Hello")');++ await client.process({+ version: "v1.0",+ updateDataModel: { surfaceId: "main", path: "/user/name", value: "Bob" },+ });+ surface = client.getSurface("main");+ expect(surface?.dataModel).toEqual({ user: { name: "Bob" } });++ expect(+ (+ await client.process({+ version: "v1.0",+ deleteSurface: { surfaceId: "main" },+ })+ ).ok,+ ).toBe(true);+ expect(client.getSurface("main")).toBeUndefined();+ });++ it("supports single-message creation with Lang components and no catalogId", async () => {+ const client = createA2UIClient({ schema });+ const result = await client.process({+ version: "v1.0",+ createSurface: {+ surfaceId: "main",+ components: ["root = Stack([title])", 'title = TextContent("Created inline")'],+ },+ });++ expect(result.ok).toBe(true);+ expect(client.getSurface("main")?.catalogId).toBeUndefined();+ expect(client.getSurface("main")?.parseResult?.root?.props.children).toEqual([+ expect.objectContaining({ props: { text: "Created inline", variant: undefined } }),+ ]);+ });++ it("preserves components that are referenced by a later incremental update", async () => {+ const client = createA2UIClient({ schema });+ await createSurface(client);+ await client.process({+ version: "v1.0",+ updateComponents: {+ surfaceId: "main",+ components: ["root = Stack([a])", 'a = TextContent("A")'],+ },+ });+ await client.process({+ version: "v1.0",+ updateComponents: { surfaceId: "main", components: ['b = TextContent("B")'] },+ });+ const result = await client.process({+ version: "v1.0",+ updateComponents: { surfaceId: "main", components: ["root = Stack([a, b])"] },+ });++ expect(result.ok).toBe(true);+ expect(client.getSurface("main")?.source).toContain('b = TextContent("B")');+ expect(client.getSurface("main")?.parseResult?.root?.props.children).toEqual([+ expect.objectContaining({ statementId: "a" }),+ expect.objectContaining({ statementId: "b" }),+ ]);+ });++ it("merges multiline blocks and deletes statements by ID", async () => {+ const client = createA2UIClient({ schema });+ await createSurface(client);++ await client.process({+ version: "v1.0",+ updateComponents: {+ surfaceId: "main",+ components: [+ `root = Stack([+ title+ ])+ title = TextContent("Before")`,+ ],+ },+ });+ const result = await client.process({+ version: "v1.0",+ updateComponents: {+ surfaceId: "main",+ components: ["title = null", "root = Stack([])"],+ },+ });++ expect(result.ok).toBe(true);+ expect(client.getSurface("main")?.source).toBe("root = Stack([])");+ });++ it("validates malformed transport input without throwing or corrupting state", async () => {+ const client = createA2UIClient({ schema });+ await createSurface(client);++ const missingComponents = await client.process({+ version: "v1.0",+ updateComponents: { surfaceId: "main" },+ });+ expect(missingComponents.ok).toBe(false);+ expect(missingComponents.issues?.[0]?.path).toBe("/updateComponents/components");+ expect(missingComponents.outbound[0]).toMatchObject({+ error: {+ code: "VALIDATION_FAILED",+ surfaceId: "main",+ path: "/updateComponents/components",+ },+ });++ const missingSurfaceId = await client.process({+ version: "v1.0",+ createSurface: { catalogId: "com.example:openui" },+ });+ expect(missingSurfaceId.ok).toBe(false);+ expect(missingSurfaceId.issues?.length).toBeGreaterThan(0);+ expect(client.getSurfaces()).toHaveLength(1);++ const wrongVersion = await client.process({ version: "v0.9", unknown: {} });+ expect(wrongVersion).toMatchObject({ ok: false, outbound: [], issues: expect.any(Array) });+ });++ it("emits the current A2UI action shape", async () => {+ const messages: RendererToAgentMessage[] = [];+ const client = createA2UIClient({+ schema,+ onMessage: (message) => messages.push(message),+ now: () => new Date("2026-07-24T10:00:00.000Z"),+ });+ await createSurface(client);++ client.dispatchAction({+ surfaceId: "main",+ sourceComponentId: "submitButton",+ name: "submit",+ userMessage: "Save profile",+ context: { intent: "save" },+ metadata: { extensions: { trace_id: "trace-1" } },+ });++ expect(messages.at(-1)).toEqual({+ version: "v1.0",+ action: {+ name: "submit",+ userMessage: "Save profile",+ surfaceId: "main",+ sourceComponentId: "submitButton",+ timestamp: "2026-07-24T10:00:00.000Z",+ context: { intent: "save" },+ metadata: { extensions: { trace_id: "trace-1" } },+ },+ });+ });++ it("calls agent functions and resolves agentFunctionResponse", async () => {+ const messages: RendererToAgentMessage[] = [];+ const client = createA2UIClient({+ schema,+ createId: () => "agent-call-1",+ onMessage: (message) => messages.push(message),+ });+ await createSurface(client);+ const response = client.callAgentFunction({+ surfaceId: "main",+ call: "lookup",+ args: { id: 42 },+ });++ expect(messages.at(-1)).toEqual({+ version: "v1.0",+ callAgentFunction: {+ surfaceId: "main",+ functionCallId: "agent-call-1",+ callFunction: { call: "lookup", args: { id: 42 } },+ },+ });++ await client.process({+ version: "v1.0",+ agentFunctionResponse: {+ functionCallId: "agent-call-1",+ value: { found: true },+ },+ });++ await expect(response).resolves.toEqual({ found: true });+ });++ it("rejects agent function errors", async () => {+ const client = createA2UIClient({ schema, createId: () => "agent-call-2" });+ await createSurface(client);+ const response = client.callAgentFunction({ surfaceId: "main", call: "save" });++ await client.process({+ version: "v1.0",+ agentFunctionResponse: {+ functionCallId: "agent-call-2",+ error: { code: "REJECTED", message: "Nope" },+ },+ });++ await expect(response).rejects.toEqual(+ expect.objectContaining<A2UIFunctionError>({ code: "REJECTED", message: "Nope" }),+ );+ });++ it("executes callRendererFunction and returns rendererFunctionResponse", async () => {+ const lookup = vi.fn(async ({ id }: { id?: unknown }) => ({ id: String(id), found: true }));+ const client = createA2UIClient({+ schema,+ functions: {+ lookup: {+ catalogId: "com.example:functions",+ allowedCallers: "agentOnly",+ handler: lookup as never,+ },+ },+ });++ const result = await client.process({+ version: "v1.0",+ callRendererFunction: {+ functionCallId: "function-1",+ callFunction: {+ call: "lookup",+ catalogId: "com.example:functions",+ args: { id: 42 },+ },+ },+ });++ expect(lookup).toHaveBeenCalledWith({ id: 42 });+ expect(result).toEqual({+ ok: true,+ outbound: [+ {+ version: "v1.0",+ rendererFunctionResponse: {+ functionCallId: "function-1",+ value: { id: "42", found: true },+ },+ },+ ],+ });+ });++ it("enforces allowedCallers and catalog identity for agent-initiated function calls", async () => {+ const client = createA2UIClient({+ schema,+ functions: {+ localOnly: {+ catalogId: "com.example:functions",+ allowedCallers: "rendererOnly",+ handler: () => ({ ok: true }),+ },+ },+ });++ const result = await client.process({+ version: "v1.0",+ callRendererFunction: {+ functionCallId: "function-local",+ callFunction: { call: "localOnly", catalogId: "com.example:functions" },+ },+ });++ expect(result.ok).toBe(false);+ expect(result.outbound[0]).toMatchObject({+ error: {+ code: "INVALID_FUNCTION_CALL",+ functionCallId: "function-local",+ },+ });+ });++ it("maps OpenUI action context, form state, and source statement to A2UI", async () => {+ const messages: RendererToAgentMessage[] = [];+ const client = createA2UIClient({ schema, onMessage: (message) => messages.push(message) });+ await createSurface(client);++ client.dispatchOpenUIAction(+ "main",+ {+ type: "submit",+ params: { mode: "fast" },+ humanFriendlyMessage: "Submit",+ formState: { contact: { email: { value: "[email protected]", componentType: "Input" } } },+ formName: "contact",+ },+ { sourceComponentId: "submitButton" },+ );++ expect(messages.at(-1)).toMatchObject({+ action: {+ name: "submit",+ sourceComponentId: "submitButton",+ context: {+ mode: "fast",+ formState: { contact: { email: "[email protected]" } },+ },+ },+ });+ });++ it("keeps renderer data-model metadata in sync with local OpenUI state", async () => {+ const client = createA2UIClient({ schema });+ await client.process({+ version: "v1.0",+ createSurface: {+ surfaceId: "main",+ catalogId: "com.example:openui",+ sendDataModel: true,+ dataModel: { user: { name: "Alice" } },+ },+ });++ expect(+ client.updateSurfaceFromOpenUIState("main", {+ $user: { name: "Carol" },+ contact: { email: { value: "[email protected]", componentType: "Input" } },+ }),+ ).toBe(true);+ expect(client.getRendererDataModel()).toEqual({+ version: "v1.0",+ surfaces: {+ main: {+ user: { name: "Carol" },+ contact: { email: "[email protected]" },+ },+ },+ });+ });++ it("filters renderer metadata to opted-in surfaces and includes capabilities", async () => {+ const metadata: unknown[] = [];+ const client = createA2UIClient({+ schema,+ rendererCapabilities: {+ "v1.0": { supportedCatalogIds: ["com.example:openui"] },+ },+ onMessage: (_message, nextMetadata) => metadata.push(nextMetadata),+ });+ await client.process({+ version: "v1.0",+ createSurface: {+ surfaceId: "shared",+ catalogId: "com.example:openui",+ sendDataModel: true,+ dataModel: { shared: true },+ },+ });+ await client.process({+ version: "v1.0",+ createSurface: {+ surfaceId: "private",+ catalogId: "com.example:openui",+ dataModel: { private: true },+ },+ });++ client.dispatchAction({+ surfaceId: "shared",+ sourceComponentId: "button",+ name: "submit",+ });++ expect(metadata.at(-1)).toEqual({+ a2uiRendererCapabilities: {+ "v1.0": { supportedCatalogIds: ["com.example:openui"] },+ },+ a2uiRendererDataModel: {+ version: "v1.0",+ surfaces: { shared: { shared: true } },+ },+ });+ });++ it("rejects a catalog outside configured renderer capabilities", async () => {+ const client = createA2UIClient({+ schema,+ rendererCapabilities: {+ "v1.0": { supportedCatalogIds: ["com.example:supported"] },+ },+ });++ const result = await client.process({+ version: "v1.0",+ createSurface: { surfaceId: "main", catalogId: "com.example:unsupported" },+ });++ expect(result.ok).toBe(false);+ expect(result.outbound[0]).toMatchObject({+ error: { code: "UNSUPPORTED_CATALOG", surfaceId: "main" },+ });+ });+});++describe("A2UI data model bridge", () => {+ it("supports RFC 6901 escaping, arrays, deletion, and root replacement", () => {+ let model = applyDataModelUpdate({}, "/a~1b/~0key", ["first", "second"]);+ expect(model).toEqual({ "a/b": { "~key": ["first", "second"] } });++ model = applyDataModelUpdate(model, "/a~1b/~0key/0", null);+ expect(model).toEqual({ "a/b": { "~key": ["second"] } });++ model = applyDataModelUpdate(model, "/", { replaced: true });+ expect(model).toEqual({ replaced: true });+ });++ it("converts A2UI data-model keys to Lang bindings and unwraps form state", () => {+ expect(dataModelToOpenUIState({ user: { name: "Alice" } })).toEqual({+ $user: { name: "Alice" },+ });+ expect(dataModelToOpenUIState({ user: { name: "Alice" } }, ["user"])).toEqual({+ $user: { name: "Alice" },+ user: { name: "Alice" },+ });+ expect(+ mergeOpenUIStateIntoDataModel(+ { untouched: true },+ { form: { field: { value: "hello", componentType: "Input" } } },+ ),+ ).toEqual({ untouched: true, form: { field: "hello" } });+ });++ it("selects whichever binding or form copy changed from the current model", () => {+ expect(+ mergeOpenUIStateIntoDataModel(+ { contact: { email: "[email protected]" } },+ {+ $contact: { email: "[email protected]" },+ contact: { email: { value: "[email protected]", componentType: "Input" } },+ },+ ),+ ).toEqual({ contact: { email: "[email protected]" } });++ expect(+ mergeOpenUIStateIntoDataModel({ filter: "all" }, { $filter: "active", filter: "all" }),+ ).toEqual({ filter: "all" });++ expect(mergeOpenUIStateIntoDataModel({ filter: "all" }, { $filter: "active" })).toEqual({+ filter: "active",+ });+ });++ it("does not let a stale binding mirror revert a user-edited form", async () => {+ const client = createA2UIClient({ schema });+ await client.process({+ version: "v1.0",+ createSurface: {+ surfaceId: "main",+ dataModel: { contact: { email: "[email protected]" } },+ },+ });+ const state = {+ $contact: { email: "[email protected]" },+ contact: {+ email: { value: "[email protected]", componentType: "Input" },+ },+ };++ expect(client.updateSurfaceFromOpenUIState("main", state)).toBe(true);+ const revision = client.getSurface("main")?.revision;+ expect(client.getSurface("main")?.dataModel).toEqual({+ contact: { email: "[email protected]" },+ });++ expect(client.updateSurfaceFromOpenUIState("main", state)).toBe(false);+ expect(client.getSurface("main")?.revision).toBe(revision);+ expect(client.getSurface("main")?.dataModel).toEqual({+ contact: { email: "[email protected]" },+ });+ });+});diff --git a/packages/a2ui/src/__tests__/protocol-schema.test.ts b/packages/a2ui/src/__tests__/protocol-schema.test.tsnew file mode 100644index 000000000..e5d827939--- /dev/null+++ b/packages/a2ui/src/__tests__/protocol-schema.test.ts@@ -0,0 +1,151 @@+import { describe, expect, it } from "vitest";+import {+ actionMessageSchema,+ agentCapabilitiesSchema,+ agentFunctionResponseMessageSchema,+ agentToRendererMessageSchema,+ callAgentFunctionMessageSchema,+ callRendererFunctionMessageSchema,+ genericErrorMessageSchema,+ rendererCapabilitiesSchema,+ rendererDataModelSchema,+ rendererToAgentMessageSchema,+ updateComponentsMessageSchema,+ validationFailedErrorMessageSchema,+} from "../protocol-schema";++describe("canonical A2UI protocol schemas", () => {+ it("validates OpenUI Lang component updates", () => {+ expect(+ updateComponentsMessageSchema.safeParse({+ version: "v1.0",+ updateComponents: {+ surfaceId: "main",+ components: ["root = Stack([title])", 'title = TextContent("Hello")'],+ },+ }).success,+ ).toBe(true);++ expect(+ updateComponentsMessageSchema.safeParse({+ version: "v1.0",+ updateComponents: { surfaceId: "main", components: [] },+ }).success,+ ).toBe(false);+ expect(+ updateComponentsMessageSchema.safeParse({+ version: "v1.0",+ updateComponents: { surfaceId: "main", components: [""] },+ }).success,+ ).toBe(false);+ });++ it("validates both protocol directions from the top-level schemas", () => {+ expect(+ agentToRendererMessageSchema.safeParse({+ version: "v1.0",+ callRendererFunction: {+ functionCallId: "call-1",+ callFunction: {+ call: "lookup",+ catalogId: "com.example:functions",+ args: { id: 42 },+ },+ },+ }).success,+ ).toBe(true);+ expect(+ callRendererFunctionMessageSchema.safeParse({+ version: "v1.0",+ callRendererFunction: {+ functionCallId: "call-1",+ callFunction: { call: "lookup" },+ },+ }).success,+ ).toBe(false);+ expect(+ agentFunctionResponseMessageSchema.safeParse({+ version: "v1.0",+ agentFunctionResponse: { functionCallId: "call-2", value: { ok: true } },+ }).success,+ ).toBe(true);+ expect(+ callAgentFunctionMessageSchema.safeParse({+ version: "v1.0",+ callAgentFunction: {+ surfaceId: "main",+ functionCallId: "call-2",+ callFunction: { call: "lookup", args: { id: 42 } },+ },+ }).success,+ ).toBe(true);++ const action = {+ version: "v1.0",+ action: {+ name: "submit",+ surfaceId: "main",+ sourceComponentId: "submit-button",+ timestamp: "2026-07-31T10:00:00.000Z",+ context: { intent: "save" },+ },+ };+ expect(actionMessageSchema.safeParse(action).success).toBe(true);+ expect(rendererToAgentMessageSchema.safeParse(action).success).toBe(true);+ expect(+ actionMessageSchema.safeParse({+ ...action,+ action: { ...action.action, timestamp: "2026-07-31T15:30:00+05:30" },+ }).success,+ ).toBe(true);+ expect(+ actionMessageSchema.safeParse({+ ...action,+ action: { ...action.action, timestamp: "not-a-timestamp" },+ }).success,+ ).toBe(false);+ });++ it("keeps validation failures distinct from generic protocol errors", () => {+ const validationFailure = {+ version: "v1.0",+ error: {+ code: "VALIDATION_FAILED",+ surfaceId: "main",+ path: "/updateComponents/components",+ message: "Required",+ },+ };+ expect(validationFailedErrorMessageSchema.safeParse(validationFailure).success).toBe(true);+ expect(+ validationFailedErrorMessageSchema.safeParse({+ ...validationFailure,+ error: { ...validationFailure.error, code: "UNALLOWED_CHILD" },+ }).success,+ ).toBe(true);+ expect(genericErrorMessageSchema.safeParse(validationFailure).success).toBe(false);+ expect(+ genericErrorMessageSchema.safeParse({+ version: "v1.0",+ error: { code: "FUNCTION_NOT_FOUND", functionCallId: "call-1", message: "Unknown" },+ }).success,+ ).toBe(true);+ });++ it("validates capabilities and renderer data-model metadata", () => {+ expect(+ rendererCapabilitiesSchema.safeParse({+ "v1.0": { supportedCatalogIds: ["com.example:openui"] },+ }).success,+ ).toBe(true);+ expect(+ agentCapabilitiesSchema.safeParse({ "v1.0": { acceptsInlineCatalogs: true } }).success,+ ).toBe(true);+ expect(+ rendererDataModelSchema.safeParse({+ version: "v1.0",+ surfaces: { main: { user: { name: "Alice" } } },+ }).success,+ ).toBe(true);+ });+});diff --git a/packages/a2ui/src/__tests__/statement-patch.test.ts b/packages/a2ui/src/__tests__/statement-patch.test.tsnew file mode 100644index 000000000..67cafbb3f--- /dev/null+++ b/packages/a2ui/src/__tests__/statement-patch.test.ts@@ -0,0 +1,92 @@+import { createParser, type LibraryJSONSchema } from "@openuidev/lang-core";+import { describe, expect, it } from "vitest";+import { mergeComponentStatements } from "../statement-patch";++const schema: LibraryJSONSchema = {+ $defs: {+ Stack: {+ properties: { children: {} },+ required: ["children"],+ },+ TextContent: {+ properties: { text: {} },+ required: ["text"],+ },+ },+};++const parser = createParser(schema);++describe("mergeComponentStatements", () => {+ it("compacts repeated statement IDs using last-write-wins semantics", () => {+ const source = mergeComponentStatements("", [+ "root = Stack([title])",+ 'title = TextContent("Before")',+ 'title = TextContent("After")',+ ]);++ expect(source).toBe('root = Stack([title])\ntitle = TextContent("After")');+ expect(parser.parse(source).meta.errors).toEqual([]);+ });++ it("preserves orphaned statements until a later patch references them", () => {+ const initial = mergeComponentStatements("", ["root = Stack([a])", 'a = TextContent("A")']);+ const withOrphan = mergeComponentStatements(initial, ['b = TextContent("B")']);++ expect(withOrphan).toContain('b = TextContent("B")');+ expect(parser.parse(withOrphan).meta.orphaned).toContain("b");++ const attached = mergeComponentStatements(withOrphan, ["root = Stack([a, b])"]);+ expect(parser.parse(attached).root?.props.children).toEqual([+ expect.objectContaining({ statementId: "a" }),+ expect.objectContaining({ statementId: "b" }),+ ]);+ });++ it("deletes statements only when a patch assigns null", () => {+ const existing = ["root = Stack([a, b])", 'a = TextContent("A")', 'b = TextContent("B")'].join(+ "\n",+ );+ const source = mergeComponentStatements(existing, ["b = null", "root = Stack([a])"]);++ expect(source).toBe('root = Stack([a])\na = TextContent("A")');+ expect(parser.parse(source).meta.errors).toEqual([]);+ });++ it("supports state IDs and top-level multiline ternaries accepted by lang-core", () => {+ const source = mergeComponentStatements("", [+ `$ready = true+ label = $ready+ ? "Ready"+ : "Waiting"+ root = TextContent(label)`,+ ]);+ const result = parser.parse(source);++ expect(source).toContain("$ready = true");+ expect(source).toContain('? "Ready"\n : "Waiting"');+ expect(result.meta.errors).toEqual([]);+ expect(result.root?.props.text).toMatchObject({+ k: "Ternary",+ cond: { k: "StateRef", n: "$ready" },+ then: { k: "Str", v: "Ready" },+ else: { k: "Str", v: "Waiting" },+ });+ });++ it("keeps quoted newlines intact and strips a per-item Markdown fence", () => {+ const source = mergeComponentStatements("", [+ `\`\`\`openui+ message = 'line one+ line two'+ root = TextContent(message)+ \`\`\``,+ ]);+ const result = parser.parse(source);++ expect(source).not.toContain("```");+ expect(result.meta.errors).toEqual([]);+ expect(result.root?.props.text).toContain("line one");+ expect(result.root?.props.text).toContain("line two");+ });+});diff --git a/packages/a2ui/src/client.ts b/packages/a2ui/src/client.tsnew file mode 100644index 000000000..c564e28b2--- /dev/null+++ b/packages/a2ui/src/client.ts@@ -0,0 +1,607 @@+import {+ createParser,+ type ActionEvent,+ type OpenUIError,+ type Parser,+ type ValidationError,+} from "@openuidev/lang-core";+import { applyDataModelUpdate, mergeOpenUIStateIntoDataModel, toJsonObject } from "./json-pointer";+import { validateAgentToRendererMessage } from "./runtime-schema";+import { mergeComponentStatements } from "./statement-patch";+import type {+ A2UIClientOptions,+ ActionMessage,+ AgentFunctionResponseMessage,+ AgentToRendererMessage,+ CallAgentFunctionInput,+ DispatchActionInput,+ GenericErrorMessage,+ JsonObject,+ JsonValue,+ OpenUIActionOptions,+ ProcessResult,+ ProtocolValidationIssue,+ RendererDataModel,+ RendererMetadata,+ RendererToAgentMessage,+ SurfaceSnapshot,+ ValidationFailedErrorMessage,+} from "./types";++type SurfaceListener = () => void;+type MessageListener = (message: RendererToAgentMessage, metadata: RendererMetadata) => void;++interface PendingAgentFunction {+ surfaceId: string;+ resolve: (value: JsonValue) => void;+ reject: (error: Error) => void;+}++export class A2UIFunctionError extends Error {+ readonly code: string;++ constructor(code: string, message: string) {+ super(message);+ this.name = "A2UIFunctionError";+ this.code = code;+ }+}++function defaultId(): string {+ return (+ globalThis.crypto?.randomUUID?.() ?? `a2ui-${Date.now()}-${Math.random().toString(16).slice(2)}`+ );+}++function parseError(error: ValidationError): OpenUIError {+ return {+ source: "parser",+ code: error.code,+ message: error.message,+ statementId: error.statementId,+ component: error.component,+ path: error.path,+ };+}++function isCreateSurface(+ message: AgentToRendererMessage,+): message is Extract<AgentToRendererMessage, { createSurface: unknown }> {+ return "createSurface" in message;+}++function isUpdateComponents(+ message: AgentToRendererMessage,+): message is Extract<AgentToRendererMessage, { updateComponents: unknown }> {+ return "updateComponents" in message;+}++function isUpdateDataModel(+ message: AgentToRendererMessage,+): message is Extract<AgentToRendererMessage, { updateDataModel: unknown }> {+ return "updateDataModel" in message;+}++function isDeleteSurface(+ message: AgentToRendererMessage,+): message is Extract<AgentToRendererMessage, { deleteSurface: unknown }> {+ return "deleteSurface" in message;+}++function isCallRendererFunction(+ message: AgentToRendererMessage,+): message is Extract<AgentToRendererMessage, { callRendererFunction: unknown }> {+ return "callRendererFunction" in message;+}++function record(value: unknown): Record<string, unknown> | undefined {+ return value != null && typeof value === "object" && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : undefined;+}++function validationTarget(input: unknown): {+ surfaceId?: string;+ functionCallId?: string;+} {+ const message = record(input);+ if (!message) return {};+ for (const key of ["createSurface", "updateComponents", "updateDataModel", "deleteSurface"]) {+ const payload = record(message[key]);+ if (typeof payload?.surfaceId === "string") {+ return { surfaceId: payload.surfaceId };+ }+ }+ for (const key of ["callRendererFunction", "agentFunctionResponse"]) {+ const payload = record(message[key]);+ if (typeof payload?.functionCallId === "string") {+ return { functionCallId: payload.functionCallId };+ }+ }+ return {};+}++export class A2UIClient {+ readonly #parser: Parser;+ readonly #functions: A2UIClientOptions["functions"];+ readonly #onMessage?: A2UIClientOptions["onMessage"];+ readonly #rendererCapabilities?: A2UIClientOptions["rendererCapabilities"];+ readonly #now: () => Date;+ readonly #createId: () => string;+ readonly #surfaces = new Map<string, SurfaceSnapshot>();+ readonly #surfaceListeners = new Set<SurfaceListener>();+ readonly #messageListeners = new Set<MessageListener>();+ readonly #pendingAgentFunctions = new Map<string, PendingAgentFunction>();+ #revision = 0;++ constructor(options: A2UIClientOptions) {+ this.#parser = createParser(options.schema, options.rootName);+ this.#functions = options.functions;+ this.#onMessage = options.onMessage;+ this.#rendererCapabilities = options.rendererCapabilities;+ this.#now = options.now ?? (() => new Date());+ this.#createId = options.createId ?? defaultId;+ }++ subscribe(listener: SurfaceListener): () => void {+ this.#surfaceListeners.add(listener);+ return () => this.#surfaceListeners.delete(listener);+ }++ subscribeMessages(listener: MessageListener): () => void {+ this.#messageListeners.add(listener);+ return () => this.#messageListeners.delete(listener);+ }++ getSurface(surfaceId: string): SurfaceSnapshot | undefined {+ return this.#surfaces.get(surfaceId);+ }++ getSurfaces(): SurfaceSnapshot[] {+ return [...this.#surfaces.values()];+ }++ getRendererDataModel(): RendererDataModel | undefined {+ const surfaces = Object.fromEntries(+ [...this.#surfaces]+ .filter(([, surface]) => surface.sendDataModel)+ .map(([surfaceId, surface]) => [surfaceId, structuredClone(surface.dataModel)]),+ );+ if (Object.keys(surfaces).length === 0) return undefined;+ return {+ version: "v1.0",+ surfaces,+ };+ }++ getRendererMetadata(): RendererMetadata {+ const dataModel = this.getRendererDataModel();+ return {+ ...(this.#rendererCapabilities+ ? { a2uiRendererCapabilities: structuredClone(this.#rendererCapabilities) }+ : {}),+ ...(dataModel ? { a2uiRendererDataModel: dataModel } : {}),+ };+ }++ async process(input: unknown): Promise<ProcessResult> {+ const outbound: RendererToAgentMessage[] = [];+ const capture = (next: RendererToAgentMessage) => outbound.push(next);+ this.#messageListeners.add(capture);+ try {+ const validated = validateAgentToRendererMessage(input);+ if (!validated.success) return this.#invalidMessage(input, validated.issues, outbound);+ const message = validated.message;++ if (isCreateSurface(message)) return this.#createSurface(message, outbound);+ if (isUpdateComponents(message)) return this.#updateComponents(message, outbound);+ if (isUpdateDataModel(message)) return this.#updateDataModel(message, outbound);+ if (isDeleteSurface(message)) return this.#deleteSurface(message, outbound);+ if (isCallRendererFunction(message)) {+ return await this.#callRendererFunction(message, outbound);+ }+ return this.#agentFunctionResponse(message, outbound);+ } finally {+ this.#messageListeners.delete(capture);+ }+ }++ updateSurfaceFromOpenUIState(surfaceId: string, state: Record<string, unknown>): boolean {+ const surface = this.#surfaces.get(surfaceId);+ if (!surface) return false;+ const dataModel = mergeOpenUIStateIntoDataModel(surface.dataModel, state);+ if (JSON.stringify(dataModel) === JSON.stringify(surface.dataModel)) return false;+ this.#replaceSurface({+ ...surface,+ dataModel,+ });+ return true;+ }++ dispatchOpenUIAction(+ surfaceId: string,+ event: ActionEvent,+ options: OpenUIActionOptions = {},+ ): void {+ const eventSourceComponentId = (event as ActionEvent & { sourceComponentId?: unknown })+ .sourceComponentId;+ const context: JsonObject = {+ ...toJsonObject(event.params),+ ...(event.formState ? { formState: toJsonObject(event.formState) } : {}),+ ...options.context,+ };+ this.dispatchAction({+ surfaceId,+ sourceComponentId:+ options.sourceComponentId ??+ (typeof eventSourceComponentId === "string" ? eventSourceComponentId : "root"),+ name: options.name ?? event.type,+ userMessage: (options.userMessage ?? event.humanFriendlyMessage) || undefined,+ context,+ metadata: options.metadata,+ });+ }++ dispatchAction(input: DispatchActionInput): void {+ if (!this.#surfaces.has(input.surfaceId)) {+ this.#emitGenericError(+ "SURFACE_NOT_FOUND",+ `Unknown surface: ${input.surfaceId}`,+ input.surfaceId,+ );+ return;+ }++ const message: ActionMessage = {+ version: "v1.0",+ action: {+ name: input.name,+ ...(input.userMessage ? { userMessage: input.userMessage } : {}),+ surfaceId: input.surfaceId,+ sourceComponentId: input.sourceComponentId,+ timestamp: this.#now().toISOString(),+ context: input.context ?? {},+ ...(input.metadata ? { metadata: input.metadata } : {}),+ },+ };+ this.#emit(message);+ }++ callAgentFunction(input: CallAgentFunctionInput): Promise<JsonValue> {+ if (!this.#surfaces.has(input.surfaceId)) {+ const message = `Unknown surface: ${input.surfaceId}`;+ this.#emitGenericError("SURFACE_NOT_FOUND", message, input.surfaceId);+ return Promise.reject(new A2UIFunctionError("SURFACE_NOT_FOUND", message));+ }++ const functionCallId = this.#createId();+ return new Promise<JsonValue>((resolve, reject) => {+ this.#pendingAgentFunctions.set(functionCallId, {+ surfaceId: input.surfaceId,+ resolve,+ reject,+ });+ this.#emit({+ version: "v1.0",+ callAgentFunction: {+ surfaceId: input.surfaceId,+ functionCallId,+ callFunction: {+ call: input.call,+ ...(input.catalogId ? { catalogId: input.catalogId } : {}),+ ...(input.args ? { args: input.args } : {}),+ },+ },+ });+ });+ }++ dispose(): void {+ for (const pending of this.#pendingAgentFunctions.values()) {+ pending.reject(new A2UIFunctionError("CLIENT_DISPOSED", "A2UI client was disposed"));+ }+ this.#pendingAgentFunctions.clear();+ this.#surfaces.clear();+ this.#surfaceListeners.clear();+ this.#messageListeners.clear();+ }++ #createSurface(+ message: Extract<AgentToRendererMessage, { createSurface: unknown }>,+ outbound: RendererToAgentMessage[],+ ): ProcessResult {+ const input = message.createSurface;+ if (this.#surfaces.has(input.surfaceId)) {+ this.#emitGenericError(+ "SURFACE_ALREADY_EXISTS",+ `Surface already exists: ${input.surfaceId}`,+ input.surfaceId,+ );+ return { ok: false, outbound };+ }+ const supportedCatalogIds = this.#rendererCapabilities?.["v1.0"].supportedCatalogIds ?? [];+ if (+ input.catalogId &&+ supportedCatalogIds.length > 0 &&+ !supportedCatalogIds.includes(input.catalogId)+ ) {+ this.#emitGenericError(+ "UNSUPPORTED_CATALOG",+ `Renderer does not support catalog: ${input.catalogId}`,+ input.surfaceId,+ );+ return { ok: false, outbound };+ }++ let source = "";+ let parseResult: SurfaceSnapshot["parseResult"] = null;+ let errors: OpenUIError[] = [];+ if (input.components) {+ try {+ ({ source, parseResult, errors } = this.#mergeComponents("", input.components));+ } catch (error) {+ this.#emitValidationError(+ input.surfaceId,+ "/createSurface/components",+ error instanceof Error ? error.message : String(error),+ );+ return { ok: false, outbound };+ }+ }+ this.#replaceSurface({+ surfaceId: input.surfaceId,+ catalogId: input.catalogId,+ metadata: input.metadata,+ sendDataModel: input.sendDataModel ?? false,+ source,+ dataModel: structuredClone(input.dataModel ?? {}),+ parseResult,+ errors,+ revision: 0,+ });+ for (const error of errors) {+ this.#emitValidationError(+ input.surfaceId,+ "/createSurface/components",+ error.statementId ? `${error.statementId}: ${error.message}` : error.message,+ );+ }+ return { ok: errors.length === 0, outbound };+ }++ #updateComponents(+ message: Extract<AgentToRendererMessage, { updateComponents: unknown }>,+ outbound: RendererToAgentMessage[],+ ): ProcessResult {+ const input = message.updateComponents;+ const surface = this.#requireSurface(input.surfaceId);+ if (!surface) return { ok: false, outbound };+ try {+ const { source, parseResult, errors } = this.#mergeComponents(+ surface.source,+ input.components,+ );+ this.#replaceSurface({ ...surface, source, parseResult, errors });+ for (const error of errors) {+ this.#emitValidationError(+ input.surfaceId,+ "/updateComponents/components",+ error.statementId ? `${error.statementId}: ${error.message}` : error.message,+ );+ }+ return { ok: errors.length === 0, outbound };+ } catch (error) {+ this.#emitValidationError(+ input.surfaceId,+ "/updateComponents/components",+ error instanceof Error ? error.message : String(error),+ );+ return { ok: false, outbound };+ }+ }++ #updateDataModel(+ message: Extract<AgentToRendererMessage, { updateDataModel: unknown }>,+ outbound: RendererToAgentMessage[],+ ): ProcessResult {+ const input = message.updateDataModel;+ const surface = this.#requireSurface(input.surfaceId);+ if (!surface) return { ok: false, outbound };+ try {+ const dataModel = applyDataModelUpdate(surface.dataModel, input.path, input.value);+ this.#replaceSurface({ ...surface, dataModel });+ return { ok: true, outbound };+ } catch (error) {+ this.#emitValidationError(+ input.surfaceId,+ "/updateDataModel/path",+ error instanceof Error ? error.message : String(error),+ );+ return { ok: false, outbound };+ }+ }++ #deleteSurface(+ message: Extract<AgentToRendererMessage, { deleteSurface: unknown }>,+ outbound: RendererToAgentMessage[],+ ): ProcessResult {+ const surfaceId = message.deleteSurface.surfaceId;+ if (!this.#requireSurface(surfaceId)) return { ok: false, outbound };+ this.#surfaces.delete(surfaceId);+ for (const [functionCallId, pending] of this.#pendingAgentFunctions) {+ if (pending.surfaceId === surfaceId) {+ pending.reject(+ new A2UIFunctionError("SURFACE_DELETED", `Surface was deleted: ${surfaceId}`),+ );+ this.#pendingAgentFunctions.delete(functionCallId);+ }+ }+ this.#notify();+ return { ok: true, outbound };+ }++ async #callRendererFunction(+ message: Extract<AgentToRendererMessage, { callRendererFunction: unknown }>,+ outbound: RendererToAgentMessage[],+ ): Promise<ProcessResult> {+ const { functionCallId, callFunction } = message.callRendererFunction;+ const { call, catalogId, args = {} } = callFunction;+ const registration = this.#functions?.[call];+ if (!registration) {+ this.#emitGenericError(+ "INVALID_FUNCTION_CALL",+ `Renderer function is not registered: ${call}`,+ undefined,+ functionCallId,+ );+ return { ok: false, outbound };+ }+ const fn = typeof registration === "function" ? registration : registration.handler;+ if (+ typeof registration === "function" ||+ (registration.allowedCallers ?? "rendererOnly") === "rendererOnly" ||+ registration.catalogId !== catalogId+ ) {+ this.#emitGenericError(+ "INVALID_FUNCTION_CALL",+ `Renderer function is not callable from catalog ${catalogId}: ${call}`,+ undefined,+ functionCallId,+ );+ return { ok: false, outbound };+ }+ try {+ const value = await fn(args);+ this.#emit({+ version: "v1.0",+ rendererFunctionResponse: { functionCallId, value },+ });+ return { ok: true, outbound };+ } catch (error) {+ this.#emit({+ version: "v1.0",+ rendererFunctionResponse: {+ functionCallId,+ error: {+ code: "EXECUTION_FAILED",+ message: error instanceof Error ? error.message : String(error),+ },+ },+ });+ return { ok: false, outbound };+ }+ }++ #agentFunctionResponse(+ message: AgentFunctionResponseMessage,+ outbound: RendererToAgentMessage[],+ ): ProcessResult {+ const response = message.agentFunctionResponse;+ const pending = this.#pendingAgentFunctions.get(response.functionCallId);+ if (!pending) {+ return {+ ok: false,+ outbound,+ issues: [+ {+ path: "/agentFunctionResponse/functionCallId",+ message: `Unknown functionCallId: ${response.functionCallId}`,+ },+ ],+ };+ }+ this.#pendingAgentFunctions.delete(response.functionCallId);+ if ("error" in response) {+ pending.reject(new A2UIFunctionError(response.error.code, response.error.message));+ return { ok: true, outbound };+ }+ pending.resolve(response.value);+ return { ok: true, outbound };+ }++ #replaceSurface(surface: Omit<SurfaceSnapshot, "revision"> & { revision?: number }): void {+ this.#revision += 1;+ this.#surfaces.set(surface.surfaceId, { ...surface, revision: this.#revision });+ this.#notify();+ }++ #mergeComponents(+ existing: string,+ components: string[],+ ): Pick<SurfaceSnapshot, "source" | "parseResult" | "errors"> {+ const source = mergeComponentStatements(existing, components);+ const parseResult = this.#parser.parse(source);+ return {+ source,+ parseResult,+ errors: parseResult.meta.errors.map(parseError),+ };+ }++ #invalidMessage(+ input: unknown,+ issues: ProtocolValidationIssue[],+ outbound: RendererToAgentMessage[],+ ): ProcessResult {+ const target = validationTarget(input);+ const issue = issues[0] ?? { path: "/", message: "Invalid A2UI message" };+ if (target.surfaceId !== undefined) {+ this.#emitValidationError(target.surfaceId, issue.path, issue.message);+ return { ok: false, outbound, issues };+ }+ if (target.functionCallId !== undefined) {+ this.#emitGenericError(+ "INVALID_MESSAGE",+ `${issue.path}: ${issue.message}`,+ undefined,+ target.functionCallId,+ );+ return { ok: false, outbound, issues };+ }+ return { ok: false, outbound, issues };+ }++ #requireSurface(surfaceId: string): SurfaceSnapshot | undefined {+ const surface = this.#surfaces.get(surfaceId);+ if (!surface) {+ this.#emitGenericError("SURFACE_NOT_FOUND", `Unknown surface: ${surfaceId}`, surfaceId);+ }+ return surface;+ }++ #emitValidationError(surfaceId: string, path: string, message: string): void {+ const error: ValidationFailedErrorMessage = {+ version: "v1.0",+ error: { code: "VALIDATION_FAILED", surfaceId, path, message },+ };+ this.#emit(error);+ }++ #emitGenericError(+ code: string,+ message: string,+ surfaceId?: string,+ functionCallId?: string,+ ): void {+ if (surfaceId === undefined && functionCallId === undefined) return;+ const error: GenericErrorMessage =+ surfaceId !== undefined+ ? { version: "v1.0", error: { code, message, surfaceId } }+ : { version: "v1.0", error: { code, message, functionCallId: functionCallId! } };+ this.#emit(error);+ }++ #emit(message: RendererToAgentMessage): void {+ const metadata = this.getRendererMetadata();+ this.#onMessage?.(message, metadata);+ for (const listener of this.#messageListeners) listener(message, metadata);+ }++ #notify(): void {+ for (const listener of this.#surfaceListeners) listener();+ }+}++export function createA2UIClient(options: A2UIClientOptions): A2UIClient {+ return new A2UIClient(options);+}diff --git a/packages/a2ui/src/index.ts b/packages/a2ui/src/index.tsnew file mode 100644index 000000000..1cdf13e71--- /dev/null+++ b/packages/a2ui/src/index.ts@@ -0,0 +1,66 @@+export { A2UIClient, A2UIFunctionError, createA2UIClient } from "./client";+export {+ applyDataModelUpdate,+ dataModelToOpenUIState,+ mergeOpenUIStateIntoDataModel,+} from "./json-pointer";+export {+ a2uiFunctionCallSchema,+ a2uiFunctionResponseSchema,+ actionMessageSchema,+ agentCapabilitiesSchema,+ agentFunctionResponseMessageSchema,+ agentToRendererMessageSchema,+ callAgentFunctionMessageSchema,+ callRendererFunctionMessageSchema,+ createSurfaceMessageSchema,+ deleteSurfaceMessageSchema,+ genericErrorMessageSchema,+ jsonObjectSchema,+ jsonValueSchema,+ messageMetadataSchema,+ rendererCapabilitiesSchema,+ rendererDataModelSchema,+ rendererFunctionResponseMessageSchema,+ rendererToAgentMessageSchema,+ updateComponentsMessageSchema,+ updateDataModelMessageSchema,+ validationFailedErrorMessageSchema,+} from "./protocol-schema";+export { validateAgentToRendererMessage } from "./runtime-schema";+export type {+ A2UIClientOptions,+ A2UIFunctionAllowedCaller,+ A2UIFunctionCall,+ A2UIFunctionResponse,+ A2UIMessageMetadata,+ A2UIRendererFunction,+ A2UIRendererFunctionRegistration,+ ActionMessage,+ AgentCapabilities,+ AgentFunctionResponseMessage,+ AgentToRendererMessage,+ CallAgentFunctionInput,+ CallAgentFunctionMessage,+ CallRendererFunctionMessage,+ CreateSurfaceMessage,+ DeleteSurfaceMessage,+ DispatchActionInput,+ GenericErrorMessage,+ JsonObject,+ JsonPrimitive,+ JsonValue,+ MapOpenUIAction,+ OpenUIActionOptions,+ ProcessResult,+ ProtocolValidationIssue,+ RendererCapabilities,+ RendererDataModel,+ RendererFunctionResponseMessage,+ RendererMetadata,+ RendererToAgentMessage,+ SurfaceSnapshot,+ UpdateComponentsMessage,+ UpdateDataModelMessage,+ ValidationFailedErrorMessage,+} from "./types";diff --git a/packages/a2ui/src/json-pointer.ts b/packages/a2ui/src/json-pointer.tsnew file mode 100644index 000000000..6a01d1ea2--- /dev/null+++ b/packages/a2ui/src/json-pointer.ts@@ -0,0 +1,149 @@+import type { JsonObject, JsonValue } from "./types";++function decodeToken(token: string): string {+ return token.replace(/~1/g, "/").replace(/~0/g, "~");+}++function tokensFor(path: string | undefined): string[] {+ if (path == null || path === "" || path === "/") return [];+ if (!path.startsWith("/")) throw new Error(`JSON Pointer must start with "/": ${path}`);+ return path.slice(1).split("/").map(decodeToken);+}++function isArrayIndex(value: string): boolean {+ return /^(0|[1-9]\d*)$/.test(value);+}++function containerFor(nextToken: string): JsonObject | JsonValue[] {+ return isArrayIndex(nextToken) ? [] : {};+}++export function applyDataModelUpdate(+ current: JsonObject,+ path: string | undefined,+ value: JsonValue,+): JsonObject {+ const tokens = tokensFor(path);+ if (tokens.length === 0) {+ if (value === null) return {};+ if (typeof value !== "object" || Array.isArray(value)) {+ throw new Error("The root A2UI data model must be an object");+ }+ return value;+ }++ const root = structuredClone(current);+ let cursor: JsonObject | JsonValue[] = root;++ for (let i = 0; i < tokens.length - 1; i++) {+ const token = tokens[i]!;+ const nextToken = tokens[i + 1]!;+ if (Array.isArray(cursor)) {+ if (!isArrayIndex(token)) throw new Error(`Invalid array index in JSON Pointer: ${token}`);+ const index = Number(token);+ const existing = cursor[index];+ if (existing == null || typeof existing !== "object") {+ cursor[index] = containerFor(nextToken);+ }+ const child = cursor[index];+ if (child == null || typeof child !== "object") {+ throw new Error(`Cannot traverse JSON Pointer segment: ${token}`);+ }+ cursor = child as JsonObject | JsonValue[];+ } else {+ const existing = cursor[token];+ if (existing == null || typeof existing !== "object") {+ cursor[token] = containerFor(nextToken);+ }+ const child = cursor[token];+ if (child == null || typeof child !== "object") {+ throw new Error(`Cannot traverse JSON Pointer segment: ${token}`);+ }+ cursor = child as JsonObject | JsonValue[];+ }+ }++ const leaf = tokens[tokens.length - 1]!;+ if (Array.isArray(cursor)) {+ if (!isArrayIndex(leaf)) throw new Error(`Invalid array index in JSON Pointer: ${leaf}`);+ const index = Number(leaf);+ if (value === null) cursor.splice(index, 1);+ else cursor[index] = value;+ } else if (value === null) {+ delete cursor[leaf];+ } else {+ cursor[leaf] = value;+ }++ return root;+}++function unwrapFormValue(value: unknown): JsonValue | undefined {+ if (value === undefined) return undefined;+ if (+ value === null ||+ typeof value === "string" ||+ typeof value === "number" ||+ typeof value === "boolean"+ ) {+ return value;+ }+ if (Array.isArray(value)) {+ return value.map(unwrapFormValue).filter((item): item is JsonValue => item !== undefined);+ }+ if (typeof value === "object") {+ const object = value as Record<string, unknown>;+ if ("value" in object && "componentType" in object) return unwrapFormValue(object.value);+ const result: JsonObject = {};+ for (const [key, child] of Object.entries(object)) {+ const unwrapped = unwrapFormValue(child);+ if (unwrapped !== undefined) result[key] = unwrapped;+ }+ return result;+ }+ return undefined;+}++export function dataModelToOpenUIState(+ dataModel: JsonObject,+ formStateKeys: Iterable<string> = [],+): Record<string, unknown> {+ const state: Record<string, unknown> = {};+ for (const [key, value] of Object.entries(dataModel)) {+ // $key is the canonical owner for Lang bindings such as $user.name.+ state[`$${key}`] = value;+ }+ // Form namespaces are opt-in so a stale form mirror cannot overwrite a+ // reactive $binding with the same top-level data-model key.+ for (const key of formStateKeys) {+ if (key in dataModel) state[key] = dataModel[key];+ }+ return state;+}++export function mergeOpenUIStateIntoDataModel(+ current: JsonObject,+ state: Record<string, unknown>,+): JsonObject {+ const next = structuredClone(current);+ const keys = new Set([+ ...Object.keys(current),+ ...Object.keys(state).map((key) => (key.startsWith("$") ? key.slice(1) : key)),+ ]);+ for (const key of keys) {+ const hasFormState = Object.prototype.hasOwnProperty.call(state, key);+ const hasBindingState = Object.prototype.hasOwnProperty.call(state, `$${key}`);+ const formValue = hasFormState ? unwrapFormValue(state[key]) : undefined;+ const bindingValue = hasBindingState ? unwrapFormValue(state[`$${key}`]) : undefined;++ // Once a real form namespace exists it owns that data-model key. Bindings+ // own every other key. This avoids change-detection races between mirrors.+ if (hasFormState && formValue !== undefined) next[key] = formValue;+ else if (hasBindingState && bindingValue !== undefined) next[key] = bindingValue;+ }+ return next;+}++export function toJsonObject(value: Record<string, unknown> | undefined): JsonObject {+ return (unwrapFormValue(value ?? {}) as JsonObject | undefined) ?? {};+}diff --git a/packages/a2ui/src/protocol-schema.ts b/packages/a2ui/src/protocol-schema.tsnew file mode 100644index 000000000..0fedc06de--- /dev/null+++ b/packages/a2ui/src/protocol-schema.ts@@ -0,0 +1,181 @@+import { z } from "zod/v4";++export const jsonValueSchema = z.json();+export const jsonObjectSchema = z.record(z.string(), jsonValueSchema);++const versionSchema = z.literal("v1.0");+const surfaceIdSchema = z.string();+const extensionKeySchema = z.string().regex(/^[\p{XID_Start}_][\p{XID_Continue}]*$/u);+const extensionsSchema = z.record(extensionKeySchema, jsonValueSchema);+export const messageMetadataSchema = z.strictObject({ extensions: extensionsSchema.optional() });+const langComponentsSchema = z+ .array(z.string().min(1))+ .min(1)+ .describe(+ "Complete OpenUI Lang statements or statement blocks, merged by statement ID in array order.",+ );++export const a2uiFunctionCallSchema = z.strictObject({+ call: z.string(),+ catalogId: z.string().optional(),+ args: jsonObjectSchema.optional(),+});++export const a2uiFunctionResponseSchema = z.union([+ z.strictObject({ functionCallId: z.string(), value: jsonValueSchema }),+ z.strictObject({+ functionCallId: z.string(),+ error: z.strictObject({ code: z.string(), message: z.string() }),+ }),+]);++export const createSurfaceMessageSchema = z.strictObject({+ version: versionSchema,+ createSurface: z.strictObject({+ surfaceId: surfaceIdSchema,+ catalogId: z.string().optional(),+ sendDataModel: z.boolean().optional().meta({ default: false }),+ components: langComponentsSchema+ .optional()+ .describe("Optional initial OpenUI Lang statements for single-message surface creation."),+ dataModel: jsonObjectSchema.optional(),+ metadata: messageMetadataSchema.optional(),+ }),+});++export const updateComponentsMessageSchema = z.strictObject({+ version: versionSchema,+ updateComponents: z.strictObject({+ surfaceId: surfaceIdSchema,+ components: langComponentsSchema,+ }),+});++export const updateDataModelMessageSchema = z.strictObject({+ version: versionSchema,+ updateDataModel: z.strictObject({+ surfaceId: surfaceIdSchema,+ path: z.string().optional(),+ value: jsonValueSchema,+ }),+});++export const deleteSurfaceMessageSchema = z.strictObject({+ version: versionSchema,+ deleteSurface: z.strictObject({ surfaceId: surfaceIdSchema }),+});++export const callRendererFunctionMessageSchema = z.strictObject({+ version: versionSchema,+ callRendererFunction: z.strictObject({+ functionCallId: z.string(),+ callFunction: a2uiFunctionCallSchema.extend({ catalogId: z.string() }),+ }),+});++export const agentFunctionResponseMessageSchema = z.strictObject({+ version: versionSchema,+ agentFunctionResponse: a2uiFunctionResponseSchema,+});++export const agentToRendererMessageSchema = z.union([+ createSurfaceMessageSchema,+ updateComponentsMessageSchema,+ updateDataModelMessageSchema,+ deleteSurfaceMessageSchema,+ callRendererFunctionMessageSchema,+ agentFunctionResponseMessageSchema,+]);++export const actionMessageSchema = z.strictObject({+ version: versionSchema,+ action: z.strictObject({+ name: z.string(),+ userMessage: z.string().optional(),+ surfaceId: surfaceIdSchema,+ sourceComponentId: z.string(),+ timestamp: z.iso.datetime({ offset: true }),+ context: jsonObjectSchema,+ metadata: messageMetadataSchema.optional(),+ }),+});++export const callAgentFunctionMessageSchema = z.strictObject({+ version: versionSchema,+ callAgentFunction: z.strictObject({+ surfaceId: surfaceIdSchema,+ functionCallId: z.string(),+ callFunction: a2uiFunctionCallSchema,+ }),+});++export const rendererFunctionResponseMessageSchema = z.strictObject({+ version: versionSchema,+ rendererFunctionResponse: a2uiFunctionResponseSchema,+});++const validationErrorCodeSchema = z.enum([+ "VALIDATION_FAILED",+ "UNALLOWED_PARENT",+ "UNALLOWED_CHILD",+]);++export const validationFailedErrorMessageSchema = z.strictObject({+ version: versionSchema,+ error: z.strictObject({+ code: validationErrorCodeSchema,+ surfaceId: surfaceIdSchema,+ path: z.string(),+ message: z.string(),+ }),+});++const genericErrorCodeSchema = z+ .string()+ .refine((code) => !validationErrorCodeSchema.options.includes(code as never));++export const genericErrorMessageSchema = z.union([+ z.strictObject({+ version: versionSchema,+ error: z.strictObject({+ code: genericErrorCodeSchema,+ message: z.string(),+ surfaceId: surfaceIdSchema,+ }),+ }),+ z.strictObject({+ version: versionSchema,+ error: z.strictObject({+ code: genericErrorCodeSchema,+ message: z.string(),+ functionCallId: z.string(),+ }),+ }),+]);++export const rendererToAgentMessageSchema = z.union([+ actionMessageSchema,+ callAgentFunctionMessageSchema,+ rendererFunctionResponseMessageSchema,+ validationFailedErrorMessageSchema,+ genericErrorMessageSchema,+]);++export const rendererCapabilitiesSchema = z.strictObject({+ "v1.0": z.strictObject({+ supportedCatalogIds: z.array(z.string()),+ inlineCatalogs: z.array(jsonObjectSchema).optional(),+ }),+});++export const agentCapabilitiesSchema = z.strictObject({+ "v1.0": z.strictObject({+ supportedCatalogIds: z.array(z.string()).optional(),+ acceptsInlineCatalogs: z.boolean().optional().meta({ default: false }),+ }),+});++export const rendererDataModelSchema = z.strictObject({+ version: versionSchema,+ surfaces: z.record(z.string(), jsonObjectSchema),+});diff --git a/packages/a2ui/src/react.ts b/packages/a2ui/src/react.tsnew file mode 100644index 000000000..5f4f4bffd--- /dev/null+++ b/packages/a2ui/src/react.ts@@ -0,0 +1,2 @@+export { A2UIRenderer } from "./Renderer";+export type { A2UIRendererProps } from "./Renderer";diff --git a/packages/a2ui/src/runtime-schema.ts b/packages/a2ui/src/runtime-schema.tsnew file mode 100644index 000000000..e99f61855--- /dev/null+++ b/packages/a2ui/src/runtime-schema.ts@@ -0,0 +1,62 @@+import {+ agentFunctionResponseMessageSchema,+ agentToRendererMessageSchema,+ callRendererFunctionMessageSchema,+ createSurfaceMessageSchema,+ deleteSurfaceMessageSchema,+ updateComponentsMessageSchema,+ updateDataModelMessageSchema,+} from "./protocol-schema";+import type { AgentToRendererMessage, ProtocolValidationIssue } from "./types";++function escapePointerToken(token: PropertyKey): string {+ return String(token).replace(/~/g, "~0").replace(/\//g, "~1");+}++function issuePath(path: PropertyKey[]): string {+ return path.length === 0 ? "/" : `/${path.map(escapePointerToken).join("/")}`;+}++export function validateAgentToRendererMessage(+ input: unknown,+):+ | { success: true; message: AgentToRendererMessage }+ | { success: false; issues: ProtocolValidationIssue[] } {+ const object =+ input != null && typeof input === "object" && !Array.isArray(input)+ ? (input as Record<string, unknown>)+ : undefined;+ const messageKeys = [+ "createSurface",+ "updateComponents",+ "updateDataModel",+ "deleteSurface",+ "callRendererFunction",+ "agentFunctionResponse",+ ] as const;+ const presentKeys = object+ ? messageKeys.filter((key) => Object.prototype.hasOwnProperty.call(object, key))+ : [];+ const selectedSchema =+ presentKeys.length === 1+ ? {+ createSurface: createSurfaceMessageSchema,+ updateComponents: updateComponentsMessageSchema,+ updateDataModel: updateDataModelMessageSchema,+ deleteSurface: deleteSurfaceMessageSchema,+ callRendererFunction: callRendererFunctionMessageSchema,+ agentFunctionResponse: agentFunctionResponseMessageSchema,+ }[presentKeys[0]!]+ : agentToRendererMessageSchema;+ const result = selectedSchema.safeParse(input);+ if (result.success) {+ return { success: true, message: result.data as AgentToRendererMessage };+ }+ return {+ success: false,+ issues: result.error.issues.map((issue) => ({+ path: issuePath(issue.path),+ message: issue.message,+ })),+ };+}diff --git a/packages/a2ui/src/statement-patch.ts b/packages/a2ui/src/statement-patch.tsnew file mode 100644index 000000000..286c4a8f2--- /dev/null+++ b/packages/a2ui/src/statement-patch.ts@@ -0,0 +1,96 @@+const STATEMENT_PATTERN = /^(\$?[A-Za-z_][A-Za-z0-9_]*)\s*=\s*([\s\S]*)$/u;++function stripFences(source: string): string {+ const trimmed = source.trim();+ if (!trimmed.startsWith("```")) return trimmed;++ const firstLineEnd = trimmed.indexOf("\n");+ const lastFence = trimmed.lastIndexOf("```");+ if (firstLineEnd === -1 || lastFence <= firstLineEnd) return trimmed;+ return trimmed.slice(firstLineEnd + 1, lastFence).trim();+}++function splitStatements(source: string): string[] {+ const statements: string[] = [];+ let depth = 0;+ let ternaryDepth = 0;+ let quote: false | '"' | "'" = false;+ let escaped = false;+ let start = 0;++ for (let index = 0; index < source.length; index += 1) {+ const character = source[index];+ if (escaped) {+ escaped = false;+ continue;+ }+ if (character === "\\" && quote) {+ escaped = true;+ continue;+ }+ if (quote) {+ if (character === quote) quote = false;+ continue;+ }+ if (character === '"' || character === "'") {+ quote = character;+ continue;+ }+ if (character === "(" || character === "[" || character === "{") depth += 1;+ else if (character === ")" || character === "]" || character === "}") {+ depth = Math.max(0, depth - 1);+ } else if (character === "?" && depth === 0) {+ ternaryDepth += 1;+ } else if (character === ":" && depth === 0 && ternaryDepth > 0) {+ ternaryDepth -= 1;+ } else if (character === "\n" && depth === 0 && ternaryDepth === 0) {+ // A top-level ternary may begin on the next line after its condition.+ let next = index + 1;+ while (next < source.length && /\s/u.test(source[next]!)) next += 1;+ if (source[next] === "?") continue;++ const statement = source.slice(start, index).trim();+ if (statement) statements.push(statement);+ start = index + 1;+ }+ }++ const finalStatement = source.slice(start).trim();+ if (finalStatement) statements.push(finalStatement);+ return statements;+}++function parseStatements(source: string): Array<{ id: string; expression: string; raw: string }> {+ return splitStatements(stripFences(source)).map((raw) => {+ const match = STATEMENT_PATTERN.exec(raw);+ if (!match) throw new Error(`Invalid OpenUI Lang statement: ${raw}`);+ return { id: match[1]!, expression: match[2]!.trim(), raw };+ });+}++/**+ * Applies statement-level A2UI component patches without removing temporarily+ * unreachable statements. A later update may attach those statements to root.+ */+export function mergeComponentStatements(existing: string, components: readonly string[]): string {+ const statements = new Map<string, string>();+ const order: string[] = [];++ const upsert = (source: string, allowDeletion: boolean): void => {+ for (const statement of parseStatements(source)) {+ if (allowDeletion && statement.expression === "null") {+ statements.delete(statement.id);+ const index = order.indexOf(statement.id);+ if (index !== -1) order.splice(index, 1);+ continue;+ }+ if (!statements.has(statement.id)) order.push(statement.id);+ statements.set(statement.id, statement.raw);+ }+ };++ if (existing.trim()) upsert(existing, false);+ for (const component of components) upsert(component, true);++ return order.map((id) => statements.get(id)!).join("\n");+}diff --git a/packages/a2ui/src/types.ts b/packages/a2ui/src/types.tsnew file mode 100644index 000000000..10d16b91f--- /dev/null+++ b/packages/a2ui/src/types.ts@@ -0,0 +1,131 @@+import type {+ ActionEvent,+ LibraryJSONSchema,+ OpenUIError,+ ParseResult,+} from "@openuidev/lang-core";+import type { z } from "zod/v4";+import type {+ a2uiFunctionCallSchema,+ a2uiFunctionResponseSchema,+ actionMessageSchema,+ agentCapabilitiesSchema,+ agentFunctionResponseMessageSchema,+ agentToRendererMessageSchema,+ callAgentFunctionMessageSchema,+ callRendererFunctionMessageSchema,+ createSurfaceMessageSchema,+ deleteSurfaceMessageSchema,+ genericErrorMessageSchema,+ jsonObjectSchema,+ jsonValueSchema,+ messageMetadataSchema,+ rendererCapabilitiesSchema,+ rendererDataModelSchema,+ rendererFunctionResponseMessageSchema,+ rendererToAgentMessageSchema,+ updateComponentsMessageSchema,+ updateDataModelMessageSchema,+ validationFailedErrorMessageSchema,+} from "./protocol-schema";++export type JsonValue = z.infer<typeof jsonValueSchema>;+export type JsonPrimitive = Extract<JsonValue, string | number | boolean | null>;+export type JsonObject = z.infer<typeof jsonObjectSchema>;+export type A2UIFunctionCall = z.infer<typeof a2uiFunctionCallSchema>;+export type A2UIFunctionResponse = z.infer<typeof a2uiFunctionResponseSchema>;+export type A2UIMessageMetadata = z.infer<typeof messageMetadataSchema>;+export type CreateSurfaceMessage = z.infer<typeof createSurfaceMessageSchema>;+export type UpdateComponentsMessage = z.infer<typeof updateComponentsMessageSchema>;+export type UpdateDataModelMessage = z.infer<typeof updateDataModelMessageSchema>;+export type DeleteSurfaceMessage = z.infer<typeof deleteSurfaceMessageSchema>;+export type CallRendererFunctionMessage = z.infer<typeof callRendererFunctionMessageSchema>;+export type AgentFunctionResponseMessage = z.infer<typeof agentFunctionResponseMessageSchema>;+export type AgentToRendererMessage = z.infer<typeof agentToRendererMessageSchema>;+export type ActionMessage = z.infer<typeof actionMessageSchema>;+export type CallAgentFunctionMessage = z.infer<typeof callAgentFunctionMessageSchema>;+export type RendererFunctionResponseMessage = z.infer<typeof rendererFunctionResponseMessageSchema>;+export type ValidationFailedErrorMessage = z.infer<typeof validationFailedErrorMessageSchema>;+export type GenericErrorMessage = z.infer<typeof genericErrorMessageSchema>;+export type RendererToAgentMessage = z.infer<typeof rendererToAgentMessageSchema>;+export type RendererCapabilities = z.infer<typeof rendererCapabilitiesSchema>;+export type AgentCapabilities = z.infer<typeof agentCapabilitiesSchema>;+export type RendererDataModel = z.infer<typeof rendererDataModelSchema>;++export interface SurfaceSnapshot {+ surfaceId: string;+ catalogId?: string;+ metadata?: A2UIMessageMetadata;+ sendDataModel: boolean;+ source: string;+ dataModel: JsonObject;+ parseResult: ParseResult | null;+ errors: OpenUIError[];+ revision: number;+}++export type A2UIRendererFunction = (args: JsonObject) => JsonValue | Promise<JsonValue>;++export type A2UIFunctionAllowedCaller = "rendererOnly" | "agentOnly" | "rendererOrAgent";++export interface A2UIRendererFunctionRegistration {+ handler: A2UIRendererFunction;+ /** Catalog that defines this function. Required when the agent may call it. */+ catalogId?: string;+ /** Matches A2UI catalog allowedCallers semantics. Defaults to rendererOnly. */+ allowedCallers?: A2UIFunctionAllowedCaller;+}++export interface A2UIClientOptions {+ schema: LibraryJSONSchema;+ rootName?: string;+ functions?: Record<string, A2UIRendererFunction | A2UIRendererFunctionRegistration>;+ rendererCapabilities?: RendererCapabilities;+ onMessage?: (message: RendererToAgentMessage, metadata: RendererMetadata) => void;+ now?: () => Date;+ createId?: () => string;+}++export interface ProtocolValidationIssue {+ path: string;+ message: string;+}++export interface ProcessResult {+ ok: boolean;+ outbound: RendererToAgentMessage[];+ /** Present when malformed input cannot be represented as an A2UI error envelope. */+ issues?: ProtocolValidationIssue[];+}++export interface DispatchActionInput {+ surfaceId: string;+ sourceComponentId: string;+ name: string;+ userMessage?: string;+ context?: JsonObject;+ metadata?: A2UIMessageMetadata;+}++export interface CallAgentFunctionInput {+ surfaceId: string;+ call: string;+ catalogId?: string;+ args?: JsonObject;+}++export interface OpenUIActionOptions {+ name?: string;+ /** A2UI component ID to report for the action. Defaults to root. */+ sourceComponentId?: string;+ userMessage?: string;+ context?: JsonObject;+ metadata?: A2UIMessageMetadata;+}++export type MapOpenUIAction = (event: ActionEvent, surface: SurfaceSnapshot) => OpenUIActionOptions;++export interface RendererMetadata {+ a2uiRendererCapabilities?: RendererCapabilities;+ a2uiRendererDataModel?: RendererDataModel;+}diff --git a/packages/a2ui/tsconfig.json b/packages/a2ui/tsconfig.jsonnew file mode 100644index 000000000..d2feca156--- /dev/null+++ b/packages/a2ui/tsconfig.json@@ -0,0 +1,17 @@+{+ "$schema": "https://json.schemastore.org/tsconfig",+ "extends": "../../tsconfig.json",+ "include": ["src/**/*"],+ "exclude": ["src/**/__tests__/**", "src/**/*.test.ts", "src/**/*.test.tsx"],+ "compilerOptions": {+ "moduleResolution": "bundler",+ "module": "ESNext",+ "outDir": "./dist",+ "rootDir": "./src",+ "noEmit": true,+ "noPropertyAccessFromIndexSignature": false,+ "noUncheckedIndexedAccess": false,+ "noImplicitReturns": false,+ "noImplicitOverride": false+ }+}diff --git a/packages/a2ui/tsconfig.test.json b/packages/a2ui/tsconfig.test.jsonnew file mode 100644index 000000000..60b3001d5--- /dev/null+++ b/packages/a2ui/tsconfig.test.json@@ -0,0 +1,9 @@+{+ "$schema": "https://json.schemastore.org/tsconfig",+ "extends": "./tsconfig.json",+ "compilerOptions": {+ "noEmit": true+ },+ "include": ["src/**/*"],+ "exclude": ["dist", "node_modules"]+}diff --git a/packages/a2ui/tsdown.config.ts b/packages/a2ui/tsdown.config.tsnew file mode 100644index 000000000..72ca11681--- /dev/null+++ b/packages/a2ui/tsdown.config.ts@@ -0,0 +1,14 @@+import { defineConfig } from "tsdown";++export default defineConfig({+ entry: ["src/index.ts", "src/react.ts"],+ format: ["esm", "cjs"],+ dts: true,+ sourcemap: true,+ target: "es2022",+ outDir: "dist",+ clean: true,+ deps: {+ neverBundle: [/^(?![./]|[A-Za-z]:[/\\])/],+ },+});diff --git a/packages/a2ui/vitest.config.ts b/packages/a2ui/vitest.config.tsnew file mode 100644index 000000000..9f6250a33--- /dev/null+++ b/packages/a2ui/vitest.config.ts@@ -0,0 +1,7 @@+import { defineConfig } from "vitest/config";++export default defineConfig({+ test: {+ environment: "jsdom",+ },+});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 8f787ae9b..eb59f0c8b 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -278,6 +278,37 @@ importers:specifier: ^4.1.18version: 4.3.3+ packages/a2ui:+ dependencies:+ '@openuidev/lang-core':+ specifier: workspace:^+ version: link:../lang-core+ zod:+ specifier: 'catalog:'+ version: 4.4.3+ devDependencies:+ '@openuidev/react-lang':+ specifier: workspace:^+ version: link:../react-lang+ '@types/react':+ specifier: 'catalog:'+ version: 19.2.17+ '@types/react-dom':+ specifier: 'catalog:'+ version: 19.2.3(@types/[email protected])+ jsdom:+ specifier: 'catalog:'+ version: 26.1.0+ react:+ specifier: 'catalog:'+ version: 19.2.4+ react-dom:+ specifier: 'catalog:'+ version: 19.2.4([email protected])+ vitest:+ specifier: ^4.0.18+ version: 4.1.10(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+packages/angular-lang:dependencies:'@openuidev/lang-core':