A2UI.Agent behaviour (A2UI v0.3.0)

Copy Markdown View Source

Behaviour and macro for building A2UI agents.

use A2UI.Agent eliminates GenServer boilerplate for agents that serve A2UI protocol messages to connected clients. Agents implement only the callbacks that matter: init/1, handle_connect/2, and handle_action/3.

Example

defmodule MyAgent do
  use A2UI.Agent

  def init(_opts), do: {:ok, %{}}

  @impl A2UI.Agent
  def handle_connect(conn, state) do
    A2UI.Agent.send_message(conn, %CreateSurface{surface_id: "main"})
    {:noreply, state}
  end

  @impl A2UI.Agent
  def handle_action(action, conn, state) do
    IO.inspect(action.name)
    {:noreply, state}
  end
end

Callbacks

Required:

  • init/1 — receives keyword opts, returns {:ok, state} or {:stop, reason}
  • handle_connect/2 — called when a client connects
  • handle_action/3 — called when a user triggers an action

Optional (default no-op):

  • handle_disconnect/2 — called when a client disconnects or its process dies
  • handle_info/2 — called for any non-A2UI messages

Summary

Functions

Sends a single A2UI protocol message to a connected client.

Sends a list of A2UI protocol messages to a connected client.

Types

conn()

@type conn() :: A2UI.Connection.t()

state()

@type state() :: term()

Callbacks

handle_action(t, conn, state)

@callback handle_action(A2UI.Protocol.Messages.Action.t(), conn(), state()) ::
  {:noreply, state()}

handle_connect(conn, state)

@callback handle_connect(conn(), state()) :: {:noreply, state()}

handle_disconnect(conn, state)

(optional)
@callback handle_disconnect(conn(), state()) :: {:noreply, state()}

handle_error(t, conn, state)

(optional)
@callback handle_error(A2UI.Protocol.Messages.Error.t(), conn(), state()) ::
  {:noreply, state()}

Functions

send_message(connection, message)

@spec send_message(conn, struct()) :: :ok | {:error, any()}
when conn: A2UI.Connection.t()

Sends a single A2UI protocol message to a connected client.

Dispatches through the connection's transport module.

send_messages(conn, messages)

@spec send_messages(conn, [struct()]) :: :ok when conn: A2UI.Connection.t()

Sends a list of A2UI protocol messages to a connected client.

Dispatches through the connection's transport module. This is a fire-and-forget operation — individual delivery failures are silently ignored. Use send_message/2 for per-message error handling.