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 RequestContextThe request context for this execution.
queue: &'a (dyn EventQueueWriter + 'static)The event queue writer for this execution.
Implementations§
Source§impl EventEmitter<'_>
impl EventEmitter<'_>
Sourcepub async fn text_artifact(
&self,
id: &str,
text: impl Into<String>,
) -> Result<(), A2aError>
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.
Sourcepub async fn artifact_chunk(
&self,
id: &str,
parts: Vec<Part>,
chunk: ArtifactChunk,
) -> Result<(), A2aError>
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.
Sourcepub async fn complete_with(&self, parts: Vec<Part>) -> Result<(), A2aError>
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.
Sourcepub async fn complete_with_text(
&self,
text: impl Into<String>,
) -> Result<(), A2aError>
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>
impl<'a> EventEmitter<'a>
Sourcepub fn new(
ctx: &'a RequestContext,
queue: &'a (dyn EventQueueWriter + 'static),
) -> EventEmitter<'a>
pub fn new( ctx: &'a RequestContext, queue: &'a (dyn EventQueueWriter + 'static), ) -> EventEmitter<'a>
Creates a new EventEmitter from the given context and queue.
Sourcepub async fn fail(
&self,
class: FailureClass,
reason: impl Into<String>,
) -> Result<(), A2aError>
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.
Sourcepub async fn request_approval(
&self,
request: ApprovalRequest,
question: impl Into<String>,
) -> Result<ApprovalRequest, A2aError>
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.
Sourcepub async fn artifact(
&self,
id: &str,
parts: Vec<Part>,
append: Option<bool>,
last_chunk: Option<bool>,
) -> Result<(), A2aError>
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.
Sourcepub async fn auth_required(
&self,
explanation: impl Into<String>,
) -> Result<(), A2aError>
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.
Sourcepub async fn relay_auth_required(
&self,
downstream: &TaskStatus,
) -> Result<(), A2aError>
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.
Sourcepub fn is_cancelled(&self) -> bool
pub fn is_cancelled(&self) -> bool
Returns true if the task has been cancelled.
Trait Implementations§
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§
§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
§impl<T> FutureExt for T
impl<T> FutureExt for T
§fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
§fn with_current_context(self) -> WithContext<Self> ⓘ
fn with_current_context(self) -> WithContext<Self> ⓘ
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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
impl<T> IntoRequest<T> for T
§fn into_request(self) -> Request<T>
fn into_request(self) -> Request<T>
T in a tonic::Request§impl<L> LayerExt<L> for L
impl<L> LayerExt<L> for L
§fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>where
L: Layer<S>,
fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>where
L: Layer<S>,
Layered].