Skip to main content

EventEmitter

Struct EventEmitter 

Source
pub struct EventEmitter<'a> {
    pub ctx: &'a RequestContext,
    pub queue: &'a (dyn EventQueueWriter + 'static),
}
Expand description

Ergonomic helper for emitting status and artifact events from an executor.

Caches task_id and context_id from the RequestContext so that every event emission is a one-liner instead of a struct literal.

§Example

The common agent answers in one call: complete_with_text emits the result artifact and then the terminal Completed status.

use a2a_protocol_server::executor_helpers::EventEmitter;

EventEmitter::new(ctx, queue).complete_with_text("hello").await?;

Each step on its own, for an agent that reports progress or streams its result in chunks (ArtifactChunk):

use a2a_protocol_server::executor_helpers::{ArtifactChunk, EventEmitter};
use a2a_protocol_types::message::Part;
use a2a_protocol_types::task::TaskState;

let emit = EventEmitter::new(ctx, queue);
emit.status(TaskState::Working).await?;
emit.artifact_chunk("result", vec![Part::text("hel")], ArtifactChunk::first()).await?;
emit.artifact_chunk("result", vec![Part::text("lo")], ArtifactChunk::last()).await?;
emit.status(TaskState::Completed).await?;

Fields§

§ctx: &'a RequestContext

The request context for this execution.

§queue: &'a (dyn EventQueueWriter + 'static)

The event queue writer for this execution.

Implementations§

Source§

impl EventEmitter<'_>

Source

pub async fn text_artifact( &self, id: &str, text: impl Into<String>, ) -> Result<(), A2aError>

Emits a complete artifact of one text part, text, under id.

The same event as artifact_chunk(id, vec![Part::text(text)], ArtifactChunk::whole()).

emit.text_artifact("summary", "Three tickets were closed today.").await?;
§Errors

Returns an error if the event queue write fails.

Source

pub async fn artifact_chunk( &self, id: &str, parts: Vec<Part>, chunk: ArtifactChunk, ) -> Result<(), A2aError>

Emits one chunk of the artifact id, placed by chunk.

The named form of artifact, whose two positional Option<bool>s read the same at every call site. artifact stays for the wire forms an ArtifactChunk does not produce: append sent as an explicit false, or lastChunk left out.

emit.artifact_chunk("story", vec![Part::text("Once upon")], ArtifactChunk::first()).await?;
emit.artifact_chunk("story", vec![Part::text(" a time")], ArtifactChunk::append()).await?;
emit.artifact_chunk("story", vec![Part::text(".")], ArtifactChunk::last()).await?;
§Errors

Returns an error if the event queue write fails.

Source

pub async fn complete_with(&self, parts: Vec<Part>) -> Result<(), A2aError>

Ends the task with parts as its result: emits them as one complete artifact, then the terminal Completed status, in that order (no event is accepted after a terminal status).

The artifact’s id is a fresh UUID, so it never replaces an artifact this run emitted earlier. A Working status first is optional; emit one with status when the work takes long enough for a caller to want to know it started.

§Errors

Returns an error if either event queue write fails; the status is not sent when the artifact was not.

Source

pub async fn complete_with_text( &self, text: impl Into<String>, ) -> Result<(), A2aError>

Ends the task with text as its result: complete_with with one text part. The whole of a one-shot agent:

use a2a_protocol_server::{EventEmitter, agent_executor};

struct HelloAgent;

agent_executor!(HelloAgent, |ctx, queue| async {
    let who = ctx.message.text().unwrap_or("world");
    EventEmitter::new(ctx, queue)
        .complete_with_text(format!("Hello, {who}!"))
        .await
});
§Errors

Returns an error if either event queue write fails.

Source§

impl<'a> EventEmitter<'a>

Source

pub fn new( ctx: &'a RequestContext, queue: &'a (dyn EventQueueWriter + 'static), ) -> EventEmitter<'a>

Creates a new EventEmitter from the given context and queue.

Source

pub async fn status(&self, state: TaskState) -> Result<(), A2aError>

Emits a status update event.

§Errors

Returns an error if the event queue write fails.

Source

pub async fn fail( &self, class: FailureClass, reason: impl Into<String>, ) -> Result<(), A2aError>

Emits the terminal Failed status, saying why in a form a caller can branch on.

An executor that returns Err instead gets a class inferred from the error code, which can only ever be InvalidRequest or Internal — no ErrorCode means “transient” or “refused on policy” — unless it recorded one on the error with set_error_class. An agent that knows it was rate limited upstream, or declined on a safety rule, is the only thing that can say so; this is one way, and the one that lets it keep writing its own status text.

// Retry me: the model was rate limited, not wrong.
emit.fail(FailureClass::Transient, "upstream model returned 429").await?;
§Errors

Returns an error if the event queue write fails.

Source

pub async fn request_approval( &self, request: ApprovalRequest, question: impl Into<String>, ) -> Result<ApprovalRequest, A2aError>

Parks the task at input-required asking a person to approve request, and returns the request as sent.

The request is recorded on the status message with the question as its text, and requested_by is set to this run’s caller, so an ApprovalGate can refuse that caller approving their own action. Return after calling it; the answer arrives as the next run of the task, at RequestContext::approval.

let action = serde_json::json!({ "tool": "refund", "order": 1182, "amount": "40.00" });
let digest = a2a_protocol_types::approval::action_digest(&action)?;
emit.request_approval(
    ApprovalRequest::new(uuid::Uuid::new_v4().to_string(), "Refund EUR 40 to order 1182", digest),
    "May I issue this refund?",
).await?;
§Errors

Returns an error if the event queue write fails.

Source

pub async fn artifact( &self, id: &str, parts: Vec<Part>, append: Option<bool>, last_chunk: Option<bool>, ) -> Result<(), A2aError>

Emits an artifact update event with append and lastChunk exactly as given (None leaves the field out).

The wire-faithful form. artifact_chunk names the four combinations a chunked artifact uses (ArtifactChunk) and text_artifact sends a complete one; this one remains for an explicit append: Some(false) or a missing lastChunk.

§Errors

Returns an error if the event queue write fails.

Source

pub async fn auth_required( &self, explanation: impl Into<String>, ) -> Result<(), A2aError>

Parks the task at auth-required, telling the client what it must authenticate for and how (spec §7.6.1: the agent “MUST” move the task to TASK_STATE_AUTH_REQUIRED and “SHOULD” include a status message explaining the required authentication).

The explanation is the status message’s text. Credentials are then obtained out of band, never through A2A (§7.6.1); return after calling this, and the task continues when the client sends its next message once it has them.

emit.auth_required("Sign in to the calendar service at https://cal.example/connect").await?;
§Errors

Returns an error if the event queue write fails.

Source

pub async fn relay_auth_required( &self, downstream: &TaskStatus, ) -> Result<(), A2aError>

Relays a downstream agent’s auth-required to this task’s own client (spec §7.6.2: an agent that delegated work “MAY” pass the request on as its own auth-required, since only its client can supply the credential).

The downstream status message’s parts become this task’s status message, under a new message id and this task’s ids; with no downstream message, a generic explanation is sent instead.

§Errors

Returns an error if the event queue write fails.

Source

pub fn is_cancelled(&self) -> bool

Returns true if the task has been cancelled.

Trait Implementations§

Source§

impl Debug for EventEmitter<'_>

Names the task and context, not the message: a Debug line in a log must not carry what the caller said (audit G-23).

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<'a> !RefUnwindSafe for EventEmitter<'a>

§

impl<'a> !UnwindSafe for EventEmitter<'a>

§

impl<'a> Forget for EventEmitter<'a>

§

impl<'a> Freeze for EventEmitter<'a>

§

impl<'a> Move for EventEmitter<'a>

§

impl<'a> Send for EventEmitter<'a>

§

impl<'a> Sync for EventEmitter<'a>

§

impl<'a> Unpin for EventEmitter<'a>

§

impl<'a> UnsafeUnpin for EventEmitter<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> FutureExt for T

§

fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
§

fn with_current_context(self) -> WithContext<Self> ⓘ

Attaches the current Context to this type, returning a WithContext wrapper. Read more
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> IntoRequest<T> for T

§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
§

impl<L> LayerExt<L> for L

§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in [Layered].
§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more