ExAgent.Event (ExAgent v3.0.0)

View Source

Versioned, serializable event envelope — ExAgent's UI/runtime contract.

Stability — Stable.

ExAgent.Event is what LiveView, CLI frontends, channels, product logs and flow tests subscribe to. It is deliberately distinct from :telemetry, which stays the channel for technical observability (metrics, OTel, dashboards) and never carries content.

Events flow through ExAgent.PubSub. A subscriber receives messages shaped as {:exagent_event, %ExAgent.Event{}}. Build scoped topics with agent_topic(agent_id, namespace) and session_topic(session_id, namespace). The one-argument helpers produce "exagent:agent:<agent_id>" and "exagent:session:<session_id>" topics; a nil namespace preserves those topics.

Envelope (version 2)

  • version — envelope schema version, 2.
  • id — unique event id ("evt_...").
  • seq — monotonic within one emitter incarnation, not durable.
  • emitter_id — identifies that incarnation; changes after a runtime restart.
  • type — identifies the event. Built-in types are listed below.
  • source — :run, :server or :session.
  • occurred_at — DateTime.utc_now/0 at emission.
  • correlation — request_id, agent_id, session_id and
                 `participant_id` (any may be `nil`).
  • lineage — run_id, parent_run_id and root_run_id of the run
                 the event belongs to (`nil` outside a run).
  • namespace — trusted application consumer scope; nil without one.
                Logical conversation/participant IDs are local to it.
  • payload — JSON-encodable map; its shape per type is payload/2.
  • metadata — free-form, JSON-encodable map.

A consumer ignores the types it does not know: new types are additive in 3.x.

Built-in event types by source

:run — the elements of ExAgent.run_stream/3 (see payload/2) and the terminals that correspond to its {:result, _} or {:error, _}:

:run_started · :run_step_started · :text_delta · :commentary_delta · :thinking_delta
:tool_call_delta · :output_partial · :model_response · :tool_call_started
:tool_call_finished · :tool_data · :approval_requested
:run_step_finished · :run_finished · :run_paused · :run_failed
:guardrail_tripped · :context_compacted · :steering_applied · :run_handoff

With child_events: :all, the elements of a child started with ExAgent.run_child/4 arrive as Events of the same types whose run_id, parent_run_id and root_run_id are the child's. A Frame3 delegation also emits the child's start and observed stop when the root opts in. The Server adds candidate :child_run_stopped with its observed outcome and candidate :job_started for an acknowledged background submission.

:server

:server_request_queued · :server_request_cancelled · :server_stopped
:approval_decided · :deferred_result_supplied

Queued and cancelled turns, with or without an idempotency key, carry the reserved ID from the admission receipt in both run_id and root_run_id, even if they never start. Read the status from payload.status on :server_request_cancelled. It is :cancelled_before_start for a queued turn, :cancelled for a settled turn, or :uncertain when the C7 journal confirms a tool or callback still needs reconciliation. An active turn's payload.partial carries accounting and omits the status. For a confirmed C7 cancellation, its counts and coverage come from the turn's journal.

A confirmed C7 cancellation carries the journal revision, or the admission receipt revision for a queued turn. A queued cancellation without a live key is process-local. During shutdown the owner can drop a turn with payload.persistence.status: :unconfirmed if its cancellation lacks a Store receipt.

:session

:session_started · :session_paused · :session_resumed · :session_done · :session_closed
:participant_joined · :participant_left
:session_turn_changed · :shared_state_updated

:run_finished and :run_paused carry result_payload/1, which keeps new_messages but neither the whole history (messages) nor steps: read the conversation with ExAgent.Server.history/1. A tool output's :run_finished payload includes the selected branch in :output_name, which also survives strip_content/1. :run_failed and :server_request_cancelled carry error_payload/1. All terminals carry payload.persistence.

:session_done reports that the turn policy is exhausted. The Session process stays alive. Read payload.persistence for the checkpoint status at that revision.

On Session events, participant_id identifies the member who joined, left or updated shared state. On :session_turn_changed it identifies the member receiving the turn. These events also carry the same ID in the payload. Session lifecycle events leave the envelope field nil.

Content

Events are the application's UI channel, inside its trust boundary, so they carry content: prompts, deltas, model responses, tool arguments and results, and outputs. strip_content/1 sets every content field to nil before an event leaves for logs or external buses, empties the envelope metadata and replaces each error reason with its bounded diagnostic.

Tool observations carry :tool, a declared name or "unknown_tool", and :call_ref, an opaque reference to the invocation in its model request. A preview without a name has tool: nil. Raw model names and provider call IDs can occur inside content fields such as :response and :new_messages.

Cursor

cursor/1 is "emitter_id:seq" when an emitter is present. ExAgent.Server.events_since/2 replays the events after a cursor from the Server's bounded buffer, and after?/2 discards live events already seen. A cursor of another emitter (a restart) or one the buffer no longer covers is expired: read the persisted state again, which is never lost.

Summary

Functions

Whether event is not covered by cursor, so a consumer that has seen everything up to cursor has not seen it yet.

Recommended PubSub topic for an agent ("exagent:agent:<id>").

Agent topic scoped by a trusted application namespace; nil preserves the legacy topic.

The event's position, "emitter_id:seq".

Structural error projection, never a dump of live runtime structs.

Build a new event, filling id/occurred_at/version defaults.

The JSON payload of a run event from its stream data.

JSON projection of a result for a terminal event.

Recommended PubSub topic for a session ("exagent:session:<id>").

Session topic scoped by a trusted application namespace; nil preserves the legacy topic.

The event with every content field set to nil, for logs or buses outside the application's trust boundary.

Types

cursor()

@type cursor() :: String.t()

source()

@type source() :: :run | :server | :session

t()

@type t() :: %ExAgent.Event{
  agent_id: String.t() | nil,
  emitter_id: String.t() | nil,
  id: String.t(),
  metadata: map(),
  namespace: String.t() | nil,
  occurred_at: DateTime.t(),
  parent_run_id: String.t() | nil,
  participant_id: ExAgent.Session.TurnPolicy.id() | nil,
  payload: map(),
  request_id: String.t() | nil,
  root_run_id: String.t() | nil,
  run_id: String.t() | nil,
  seq: non_neg_integer(),
  session_id: String.t() | nil,
  source: source() | nil,
  type: atom(),
  version: pos_integer()
}

Functions

after?(event, cursor)

@spec after?(t(), cursor() | nil) :: boolean()

Whether event is not covered by cursor, so a consumer that has seen everything up to cursor has not seen it yet.

It is false only for an event of the cursor's emitter with a seq at or below the cursor's. An event of another emitter (a new incarnation after a restart) or a nil cursor gives true. A malformed cursor raises ArgumentError.

agent_topic(agent_id)

@spec agent_topic(String.t() | nil) :: String.t()

Recommended PubSub topic for an agent ("exagent:agent:<id>").

agent_topic(agent_id, namespace)

Agent topic scoped by a trusted application namespace; nil preserves the legacy topic.

cursor(event)

@spec cursor(t()) :: cursor() | nil

The event's position, "emitter_id:seq".

Pass it to ExAgent.Server.events_since/2 and after?/2. It identifies an emitter incarnation, not a durable log offset. An event created without an emitter has no replay position and returns nil.

error_payload(error)

Structural error projection, never a dump of live runtime structs.

reason is the UI projection: it keeps safe categories and application strings. strip_content/1 replaces it with the bounded diagnostic. This includes the error :type, the :provider and HTTP :status of a request error, or the :version of a required Store migration.

new(opts)

@spec new(keyword()) :: t()

Build a new event, filling id/occurred_at/version defaults.

:type and :seq are required (enforced); everything else is optional with sensible defaults. payload/metadata default to empty maps.

payload(type, data)

@spec payload(atom(), map()) :: map()

The JSON payload of a run event from its stream data.

data is the second element of an ExAgent.run_stream/3 element {type, data}; Server and Session use the same projection inside their %Event{}. One clause per type:

typepayloadcontent
:run_startedrun_id root_run_id parent_run_id attempt_id promptprompt
:run_step_startedstep—
:steering_appliedstep correction_id—
:run_handoffstep from to call_ref—
:guardrail_trippedstep name stage—
:context_compactedstep reason estimated_tokens_saved—
:text_delta, :commentary_delta, :thinking_deltastep texttext
:tool_call_deltastep index tool fragmentfragment
:output_partialstep outputoutput
:model_responsestep response (ExAgent.Message.to_json/1 of the effective response)response
:tool_call_startedstep tool call_ref args args_sourceargs
:tool_call_finishedstep tool call_ref status content content_withheld usage duration_ms duration_measuredcontent
:tool_datastep call_ref tool part_id name data transientdata
:approval_requestedcontinuation pending (item identifiers, optional candidate permission_rule and deferral_kind of :input, :external or :timer. Timers carry :wake_at in UTC milliseconds. Delegated Frame3 items carry the candidate delegation_path.)—
:approval_decidedaction approval_id call_ref tool continuation and candidate delegation_path for a delegated request—
:deferred_result_supplieddeferral_id call_ref tool status continuation and candidate delegation_path for a delegated call—
:run_step_finishedstep outcome—
:child_run_stopped (candidate)status (:succeeded, :failed, :cancelled or :paused)—
:job_started (candidate)job_id tool—

Nested Tool.CodeMode calls add the candidate payload keys program_call_ref, program_step (one-based) and effect (:read or :write) to tool start and finish events. These keys survive content stripping.

The stream's :run_started data has no prompt; the Server adds the prompt of the run it starts. For job activity this is a map with type "job_notice", job ID, terminal status and tool name. A value that cannot be projected to JSON becomes %{serialization_error: true}. Server :text_delta and :commentary_delta events carry payload.output_guarded? sampled at publication. A delta released by a stream guard also carries payload.stream_checked?: true. A browser-facing replay can show those reviewed drafts while final delivery is gated.

result_payload(result)

JSON projection of a result for a terminal event.

It keeps new_messages (the run's own messages) and drops the whole history and the live model: read the conversation with ExAgent.Server.history/1. Accepted structured output uses declared Jason encoders, including on nested values, with Ecto's embedded field projection as a fallback. The encoded value uses the run's payload byte limit. If projection fails, :output is %{serialization_error: true} and :output_text is nil. Each message, pending response or usage field that fails conversion is nil. Tool outputs carry the optional :output_name of the selected branch. The optional citations array follows ExAgent.Result.citations/1 for the accepted output. Its source data belongs inside the application's trust boundary. The original result remains available to the caller.

session_topic(session_id)

@spec session_topic(String.t() | nil) :: String.t()

Recommended PubSub topic for a session ("exagent:session:<id>").

session_topic(session_id, namespace)

Session topic scoped by a trusted application namespace; nil preserves the legacy topic.

strip_content(event, opts \\ [])

@spec strip_content(t(), [{:metadata_keys, [atom() | String.t()]}]) :: t()

The event with every content field set to nil, for logs or buses outside the application's trust boundary.

Content is the content column of payload/2, plus output, output_text, new_messages, pending_response and citations of terminal results (also the partial result of an error). Every error reason, including the nested outcome error and persistence.error, is replaced by its bounded diagnostic: the UI projection in reason can keep application strings. Each event type exports only its defined fields, for atom or string payload keys. Tool fields from older events lacking the projected :tool and :call_ref are omitted. A finished terminal keeps its validated output branch name. Terminal and partial usage keep only qualified counters and known numeric detail dimensions. An unknown type loses its whole payload. Participant IDs export as numbers or UTF-8 strings. Other values become nil. The timestamp exports in UTC. Envelope metadata defaults to an empty map for every type. Pass metadata_keys: [:region, "release"] to export those top-level keys. Atom and string keys match exactly, and each selected value is exported in full.