# Integrate Moon A2UI with an agent or renderer

Moon A2UI owns protocol validation and state. Your application owns transport, authentication, business decisions and platform effects such as opening a URL. The browser example uses the official Lit renderer; a Native application can use the same MoonBit state and evaluation APIs with its own UI.

## Receive messages and return updates

Use `AgentMessage::parse` for the full agent-to-renderer stream and `RendererMessage::parse` for the reverse direction. These distinguish state updates, actions, RPC calls, responses and errors. `Message` is the state-update type used by the construction helpers.

```mbt
let incoming = @a2ui.AgentMessage::parse(text)
let outgoing = runtime.receive_agent(incoming)
for message in outgoing {
  send(message.to_json().stringify())
}
```

`receive_agent` applies updates and returns messages produced by function responses or resumed actions. Evaluations initiated directly through `resolve` can enqueue calls; send those with `drain_messages()`. A host acting as an agent can register handlers and pass an incoming `CallAgent` message to `handle_agent_call`.

Surface changes are validated before committing. Component updates replace their entire definition, including metadata. Progressive messages may reference components that have not arrived yet; call `validate_complete(surface_id)` when the stream has converged. Cycles and incompatible parent/child relationships are rejected during updates.

## Resolve values in the correct scope

A binding such as `@path: /name` reads the surface root. A relative path such as `@path: name` reads the current template scope. `template_contexts` creates contexts for array or object entries; `@index` evaluates the entry index with an optional offset.

```mbt
let context = @a2ui.EvaluationContext::root("form")
let value = runtime.evaluate({ "@path": "/name" }, context)
runtime.write_binding(context, { "@path": "/name" }, "Ada")
```

`component_properties` resolves a component's properties and applies schema-directed Boolean coercion. `watch_component` invokes its callback when those resolved values change and passes `None` when the surface is deleted. Keep the returned identifier and call `unwatch` when the view is disposed. Metadata-only changes do not trigger a property callback.

Keys beginning with `@@` represent literal keys beginning with `@`. An unrecognized single-`@` directive is rejected. Snapshots and returned metadata are owned values rather than writable references into the state store.

## Execute functions with explicit boundaries

Basic functions include required, regex, length, numeric, email, the five formatting functions, and/or/not and openUrl. Formatting uses `en-US`; dates follow the fixed A2UI reference's written-date and string-conversion rules. The safe regex implementation supports A2UI's prescribed syntax and four static safety checks, with a 256-code-point pattern limit and a 4,096-code-point value limit. Counted repetitions are bounded at 65,535, matching the fixed reference parser.

Register platform or application functions by catalog and name:

```mbt
runtime.register_function(catalog_id, "lookupAccount", (args, context) => {
  lookup_account(args, context)
})
```

Declarations control arguments, return types, allowed callers and user activation. `openUrl` requires a host handler and user activation. Checks and data bindings do not acquire activation merely because their enclosing code was called by a user event. The host should apply its actual platform permission policy inside the handler.

A renderer evaluation without a local implementation routes to the agent, including an undeclared function. An agent-originated renderer call must name a function in the renderer catalog. Catalog IDs identify registered definitions and are never fetched as URLs. A renderer-to-agent call can omit its catalog ID when the receiving runtime already knows the surface and its default catalog; otherwise, include the ID explicitly.

`resolve` returns `Ready`, `Pending` or `Failed`. Send queued `callAgentFunction` messages, then feed responses to `receive_agent`. IDs correlate replies; duplicate replies and responses to deleted surfaces are rejected. Reactive calls can reuse settled results. `activate` starts a fresh action, waits for dependent calls and resumes it when responses arrive, without repeating a completed call inside that action. `cancel_call` settles an outstanding call with a cancellation error. Direct callers can inspect `response` or consume it with `take_response`.

## Negotiate catalogs and keep metadata separate

Create `AgentCapabilities` with supported catalog IDs and an explicit inline-catalog opt-in. `CatalogRegistry::capabilities` describes renderer support; `negotiate` checks advertised definitions and rejects conflicting or unconsented inline catalogs before registration.

`SurfaceStore::metadata`, `set_metadata`, `set_extension` and `remove_extension` access surface or component extensions. `on_metadata_changed` provides owned before/after values; remove its listener when no longer needed. Unicode identifier rules apply to extension keys.

For surfaces created with `sendDataModel`, `renderer_data_model(surface_id)` returns the A2UI transport metadata payload. Other surfaces return `None`. Your transport decides how to attach this payload; it does not belong in action context.

## Handle invalid input

Decode untrusted JSON before mutating state. `ProtocolError` distinguishes invalid fields, unsupported state-message kinds, invalid state transitions and runtime function failures. Applications must separately authorize user actions and validate business inputs such as identifiers, prices and permissions.

Text decoding rejects duplicate keys and nesting beyond 64. Pointer traversal rejects invalid escapes and prototype-related keys; array growth stops at index 10,000. Expression evaluation and interpolation are bounded, and user-activation checks run before a host handler is invoked. Network request limits remain the transport's responsibility.
