aither_agent/event.rs
1//! What a run emits: the events that observe it.
2//!
3//! Events observe; [`Hooks`](crate::Hooks) decide. Every enum, every variant
4//! and every struct here is `#[non_exhaustive]`, and none has a public
5//! constructor, because only aither emits them: a consumer matches with a
6//! wildcard arm and keeps working when a release adds an event.
7//!
8//! Every event reaches the consumer as a [`TimedEvent`], which names the agent
9//! that emitted it by its [`AgentPath`]: a subagent's events are forwarded
10//! on its parent's stream, tagged with the child's path.
11
12use core::time::Duration;
13use std::fmt;
14
15use aither_core::llm::tool::{ApprovalKind, Progress};
16use aither_core::llm::{ToolCallId, ToolResult, Usage};
17use jiff::Timestamp;
18
19use crate::context_window::ContextWindowPhase;
20use crate::error::AgentError;
21
22pub use aither_core::llm::AgentPath;
23
24macro_rules! text_id {
25 ($(#[$meta:meta])* $name:ident) => {
26 $(#[$meta])*
27 #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
28 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
29 #[cfg_attr(feature = "serde", serde(transparent))]
30 pub struct $name(String);
31
32 impl $name {
33 /// Names an id, for an agent that lives outside this crate and
34 /// mints its own.
35 #[must_use]
36 pub fn new(id: impl Into<String>) -> Self {
37 Self(id.into())
38 }
39
40 /// The identifier as text.
41 #[must_use]
42 pub fn as_str(&self) -> &str {
43 &self.0
44 }
45 }
46
47 impl fmt::Display for $name {
48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49 f.write_str(&self.0)
50 }
51 }
52 };
53}
54
55macro_rules! counter_id {
56 ($(#[$meta:meta])* $name:ident($inner:ty)) => {
57 $(#[$meta])*
58 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
59 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
60 #[cfg_attr(feature = "serde", serde(transparent))]
61 pub struct $name($inner);
62
63 impl $name {
64 /// Names an id, for an agent that lives outside this crate and
65 /// mints its own.
66 #[must_use]
67 pub const fn new(id: $inner) -> Self {
68 Self(id)
69 }
70
71 /// The identifier's number.
72 #[must_use]
73 pub const fn get(self) -> $inner {
74 self.0
75 }
76 }
77
78 impl fmt::Display for $name {
79 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80 self.0.fmt(f)
81 }
82 }
83 };
84}
85
86text_id! {
87 /// Identifies one run of an agent: from [`Agent::run`](crate::Agent::run)
88 /// or [`Agent::resume`](crate::Agent::resume) to its
89 /// [`RunEnded`](AgentEvent::RunEnded).
90 RunId
91}
92
93/// Identifies a [context source](crate::ContextSource) in
94/// [`ContextInjected`](AgentEvent::ContextInjected).
95#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
96#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
97#[cfg_attr(feature = "serde", serde(transparent))]
98pub struct SourceId(String);
99
100impl SourceId {
101 /// Names a source.
102 #[must_use]
103 pub fn new(id: impl Into<String>) -> Self {
104 Self(id.into())
105 }
106
107 /// The name as text.
108 #[must_use]
109 pub fn as_str(&self) -> &str {
110 &self.0
111 }
112}
113
114impl fmt::Display for SourceId {
115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116 f.write_str(&self.0)
117 }
118}
119
120counter_id! {
121 /// Identifies one request sent to the model, unique within an agent. A
122 /// request sent again after its response stream broke has a new id.
123 RequestId(u64)
124}
125
126counter_id! {
127 /// Identifies one block of a response within its request.
128 BlockId(u32)
129}
130
131counter_id! {
132 /// Identifies one pause, unique within an agent.
133 PauseId(u64)
134}
135
136/// What a streamed block of the model's response is.
137#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
138#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
139#[non_exhaustive]
140pub enum OutputKind {
141 /// Text for the reader.
142 Text,
143 /// The model's reasoning.
144 Reasoning,
145}
146
147/// Where a tool call runs.
148#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
149#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
150#[non_exhaustive]
151pub enum ToolOrigin {
152 /// A tool registered on the agent, run by the agent.
153 Local,
154 /// A tool the provider runs itself; nothing runs locally.
155 Hosted,
156}
157
158/// What the agent settled on for a tool call before running it.
159#[derive(Debug, Clone, PartialEq)]
160#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
161#[non_exhaustive]
162pub enum ToolVerdict {
163 /// The call runs as the model made it.
164 Allowed,
165 /// The call does not run; the model is told `reason`.
166 Denied {
167 /// Why the call was refused.
168 reason: String,
169 },
170 /// The call runs with arguments a hook replaced.
171 Rewritten,
172 /// The call waits on the approver; a [`Paused`](AgentEvent::Paused)
173 /// follows when the answer is not immediate, and the verdict is
174 /// [`Allowed`](Self::Allowed) or [`Denied`](Self::Denied) once it comes.
175 AwaitingApproval,
176}
177
178/// Why a run stopped short of an answer without failing.
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
181#[non_exhaustive]
182pub enum RunPause {
183 /// The context window is full and the run cannot continue.
184 ///
185 /// Emitted when usage reaches the
186 /// [pause point](crate::ContextPolicy::pause_point) and no compaction can
187 /// relieve it: there was nothing to compact, or the compaction landed and
188 /// the window is still full. Sending the request anyway would have the
189 /// provider reject it for length. A compaction that fails twice is a
190 /// failed run, not this pause.
191 ContextExhausted,
192}
193
194/// How a run ended.
195#[derive(Debug, Clone)]
196#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
197#[non_exhaustive]
198pub enum RunOutcome {
199 /// The model answered and nothing held the run.
200 Completed {
201 /// The model's final reply.
202 final_text: String,
203 },
204 /// The run stopped for a reason that needs the embedder.
205 Paused {
206 /// Why.
207 pause: RunPause,
208 },
209 /// [`Run::cancel`](crate::Run::cancel) was called, or the run was dropped.
210 Cancelled,
211 /// The run failed; [`Run::drive`](crate::Run::drive) returns the error.
212 Failed {
213 /// What went wrong.
214 error: AgentError,
215 },
216 /// The model kept calling tools past
217 /// [`max_iterations`](crate::AgentConfig::max_iterations).
218 IterationLimit,
219}
220
221/// How a request ended.
222#[derive(Debug, Clone)]
223#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
224#[non_exhaustive]
225pub enum RequestOutcome {
226 /// The response stream ended.
227 Completed,
228 /// The response stream broke after it opened, and the same request is
229 /// sent again after `delay` as a new request.
230 ///
231 /// Everything streamed since the request started — text, reasoning,
232 /// tool-call deltas and hosted tool calls — belonged to the broken
233 /// attempt: none of it enters the conversation and none of its tool calls
234 /// run. A client drops what it rendered of that attempt.
235 Retrying {
236 /// Why the stream broke.
237 error: AgentError,
238 /// Which retry this is, counting from 1.
239 retry: u32,
240 /// The most retries the model's
241 /// [`RetryPolicy`](aither_core::llm::RetryPolicy) allows.
242 max_retries: u32,
243 /// How long the agent waits before sending the request again.
244 delay: Duration,
245 },
246 /// The request failed and the run fails with the error.
247 Failed {
248 /// What went wrong.
249 error: AgentError,
250 },
251}
252
253/// Why a compaction started.
254#[derive(Debug, Clone, Copy, PartialEq, Eq)]
255#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
256#[non_exhaustive]
257pub enum CompactionTrigger {
258 /// [`Agent::compact`](crate::Agent::compact) was called.
259 Requested,
260 /// The window crossed the policy's
261 /// [start point](crate::ContextPolicy::start_point); the compaction is
262 /// forked alongside the run.
263 WindowFilling,
264 /// The window reached the pause point and the run made room.
265 PausePoint,
266 /// [`Agent::compact_when_idle`](crate::Agent::compact_when_idle) ran
267 /// shortly before the cache expired.
268 Idle,
269 /// A send found the cache cold and a compaction model set.
270 ColdCache,
271}
272
273/// How a compaction announced by [`AgentEvent::CompactionStarted`] ended.
274#[derive(Debug, Clone)]
275#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
276#[non_exhaustive]
277pub enum CompactionOutcome {
278 /// The handoff replaced the conversation below its fork point.
279 Applied(crate::CompactResult),
280 /// There was no conversation to compact; the window is as it was.
281 NothingToCompact,
282 /// The compaction failed; the window is as it was.
283 Failed(AgentError),
284 /// The handoff was dropped unapplied: the window it was forked from was
285 /// replaced first, by an explicit compaction,
286 /// [`clear_history`](crate::Agent::clear_history),
287 /// [`restore_checkpoint`](crate::Agent::restore_checkpoint), or by
288 /// dropping the run that carried it.
289 Discarded,
290}
291
292/// What an injection into the conversation was.
293#[derive(Debug, Clone, Copy, PartialEq, Eq)]
294#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
295#[non_exhaustive]
296pub enum InjectionKind {
297 /// A durable block appended to the conversation, which stays in the
298 /// cached prefix from the next request on.
299 Stable,
300 /// A block rendered into one request's volatile tail.
301 Tail,
302 /// The diff alert of a live source whose content changed.
303 LiveChange,
304}
305
306/// Why a checkpoint was emitted.
307#[derive(Debug, Clone, Copy, PartialEq, Eq)]
308#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
309#[non_exhaustive]
310pub enum CheckpointReason {
311 /// A turn that called tools ended.
312 TurnBoundary,
313 /// The run is stopping.
314 Stop,
315}
316
317/// Events emitted during agent execution.
318#[derive(Debug, Clone)]
319#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
320#[non_exhaustive]
321pub enum AgentEvent {
322 /// A run began.
323 #[non_exhaustive]
324 RunStarted {
325 /// The run.
326 run: RunId,
327 /// The agent that runs it.
328 agent: AgentPath,
329 },
330
331 /// A run ended; the last event of the run.
332 #[non_exhaustive]
333 RunEnded {
334 /// The run.
335 run: RunId,
336 /// How it ended.
337 outcome: RunOutcome,
338 },
339
340 /// A turn began: one request to the model and the tool calls it makes.
341 #[non_exhaustive]
342 TurnStarted {
343 /// The run.
344 run: RunId,
345 /// The turn, counting from 1.
346 turn: usize,
347 },
348
349 /// A turn ended.
350 #[non_exhaustive]
351 TurnEnded {
352 /// The run.
353 run: RunId,
354 /// The turn.
355 turn: usize,
356 /// How many tool calls the turn made.
357 tool_calls: usize,
358 },
359
360 /// A request to the model was sent.
361 #[non_exhaustive]
362 RequestStarted {
363 /// The request.
364 request: RequestId,
365 /// The hash chain of its prompt prefix and what rewrote that prefix
366 /// since the previous request, so a host can tell where a cache miss
367 /// began.
368 prefix: crate::context::PromptPrefix,
369 },
370
371 /// A request ended.
372 #[non_exhaustive]
373 RequestEnded {
374 /// The request.
375 request: RequestId,
376 /// The usage the provider reported for it, if it did.
377 usage: Option<Usage>,
378 /// How it ended.
379 outcome: RequestOutcome,
380 },
381
382 /// A chunk of a block of the response.
383 #[non_exhaustive]
384 BlockDelta {
385 /// The request.
386 request: RequestId,
387 /// The block within the request.
388 block: BlockId,
389 /// What the block is.
390 kind: OutputKind,
391 /// The chunk.
392 text: String,
393 },
394
395 /// A block of the response is complete.
396 #[non_exhaustive]
397 BlockEnded {
398 /// The request.
399 request: RequestId,
400 /// The block.
401 block: BlockId,
402 /// What the block is.
403 kind: OutputKind,
404 },
405
406 /// The model is streaming a tool call's name and arguments, before the
407 /// call is assembled.
408 #[non_exhaustive]
409 ToolCallDelta {
410 /// The call.
411 call: ToolCallId,
412 /// The tool; empty in the earliest deltas of some providers.
413 name: String,
414 /// The next fragment of the JSON arguments.
415 arguments_fragment: String,
416 },
417
418 /// A tool call was made.
419 #[non_exhaustive]
420 ToolCallStarted {
421 /// The call.
422 call: ToolCallId,
423 /// The tool.
424 name: String,
425 /// The arguments as the model made them; the detail of a hosted
426 /// call as a string.
427 arguments: serde_json::Value,
428 /// Where the call runs.
429 origin: ToolOrigin,
430 },
431
432 /// The agent settled whether the call runs, and how.
433 #[non_exhaustive]
434 ToolCallDecided {
435 /// The call.
436 call: ToolCallId,
437 /// What was decided.
438 decision: ToolVerdict,
439 },
440
441 /// A running tool reported progress.
442 #[non_exhaustive]
443 ToolProgress {
444 /// The call.
445 call: ToolCallId,
446 /// The tool's typed report.
447 progress: Progress,
448 },
449
450 /// A tool call ended.
451 #[non_exhaustive]
452 ToolCallEnded {
453 /// The call.
454 call: ToolCallId,
455 /// What the model reads of it.
456 result: ToolResult,
457 },
458
459 /// Work is waiting on something outside the agent: an approval, or a
460 /// question a tool put through the approver under a kind of its own.
461 #[non_exhaustive]
462 Paused {
463 /// The pause.
464 pause: PauseId,
465 /// The tool call that waits, if a tool call does.
466 call: Option<ToolCallId>,
467 /// What is waited for, as the embedder named it.
468 kind: ApprovalKind,
469 /// What the approval is about.
470 subject: String,
471 },
472
473 /// The pause ended.
474 #[non_exhaustive]
475 Resumed {
476 /// The pause.
477 pause: PauseId,
478 },
479
480 /// A compaction started: one forked alongside the run, or one run by
481 /// [`Agent::compact`](crate::Agent::compact),
482 /// [`Agent::compact_when_idle`](crate::Agent::compact_when_idle) or the
483 /// run itself at the pause point or on a cold cache.
484 ///
485 /// Exactly one [`CompactionEnded`](Self::CompactionEnded) follows, and no
486 /// other compaction starts before it. It is emitted on the stream of
487 /// whatever ends the compaction, which for one forked alongside a run may
488 /// be a later run or explicit compaction; one ended where no stream is
489 /// open finishes as [`CompactionOutcome::Discarded`] first thing on the
490 /// next stream the agent opens.
491 #[non_exhaustive]
492 CompactionStarted {
493 /// Why it started.
494 trigger: CompactionTrigger,
495 },
496
497 /// The compaction last [started](Self::CompactionStarted) ended.
498 #[non_exhaustive]
499 CompactionEnded {
500 /// How it ended.
501 outcome: CompactionOutcome,
502 },
503
504 /// A compaction failed with the window at the
505 /// [pause point](crate::ContextPolicy::pause_point), so the context was
506 /// cleaned and the compaction reruns on it now.
507 ///
508 /// The cleanup removes system alerts and reminders and moves long tool
509 /// outputs to files. When the rerun fails too the run fails; otherwise
510 /// the run continues on the compacted window.
511 #[non_exhaustive]
512 CompactionRecovery {
513 /// Why the compaction failed.
514 error: AgentError,
515 /// System alerts and reminders the cleanup removed.
516 alerts_removed: usize,
517 /// Long tool outputs the cleanup moved to files.
518 outputs_spilled: usize,
519 },
520
521 /// A context source or a hook put a block into the conversation.
522 #[non_exhaustive]
523 ContextInjected {
524 /// Who injected it.
525 source: SourceId,
526 /// What kind of injection it was.
527 kind: InjectionKind,
528 },
529
530 /// A subagent began. Its own events follow, tagged with its path.
531 #[non_exhaustive]
532 SubagentStarted {
533 /// The child's path.
534 child: AgentPath,
535 /// The child's name.
536 name: String,
537 /// What it was asked to do.
538 prompt: String,
539 },
540
541 /// A subagent ended.
542 #[non_exhaustive]
543 SubagentEnded {
544 /// The child's path.
545 child: AgentPath,
546 /// How its run ended.
547 outcome: RunOutcome,
548 },
549
550 /// A snapshot of the agent's state was taken after it changed.
551 #[non_exhaustive]
552 Checkpoint {
553 /// The run.
554 run: RunId,
555 /// Why the checkpoint was emitted.
556 reason: CheckpointReason,
557 /// The turn.
558 turn: usize,
559 /// The lifecycle phase of the assembled context window.
560 phase: ContextWindowPhase,
561 /// Number of recent conversation messages currently in memory.
562 message_count: usize,
563 },
564}
565
566/// An [`AgentEvent`] with the UTC time it was emitted and the agent that
567/// emitted it.
568///
569/// The time is taken at the emission point inside the run, not when the
570/// consumer reads the event.
571#[derive(Debug, Clone)]
572#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
573#[non_exhaustive]
574pub struct TimedEvent {
575 /// When the agent emitted the event.
576 pub at: Timestamp,
577 /// Which agent emitted it: the main agent, or a subagent whose events
578 /// are forwarded on its parent's stream.
579 pub agent: AgentPath,
580 /// The event itself.
581 pub event: AgentEvent,
582}
583
584impl TimedEvent {
585 /// An event emitted now by `agent`, for a [`ChildAgent`](crate::ChildAgent)
586 /// that lives outside this crate.
587 #[must_use]
588 pub fn now(agent: AgentPath, event: AgentEvent) -> Self {
589 Self {
590 at: Timestamp::now(),
591 agent,
592 event,
593 }
594 }
595}
596
597/// Constructors for the events an agent that lives outside this crate, such
598/// as an external session run as a [`ChildAgent`](crate::ChildAgent), can
599/// report.
600impl AgentEvent {
601 /// A run began.
602 #[must_use]
603 pub const fn run_started(run: RunId, agent: AgentPath) -> Self {
604 Self::RunStarted { run, agent }
605 }
606
607 /// A run ended.
608 #[must_use]
609 pub const fn run_ended(run: RunId, outcome: RunOutcome) -> Self {
610 Self::RunEnded { run, outcome }
611 }
612
613 /// A chunk of a block of a response.
614 #[must_use]
615 pub const fn block_delta(
616 request: RequestId,
617 block: BlockId,
618 kind: OutputKind,
619 text: String,
620 ) -> Self {
621 Self::BlockDelta {
622 request,
623 block,
624 kind,
625 text,
626 }
627 }
628
629 /// A block of a response is complete.
630 #[must_use]
631 pub const fn block_ended(request: RequestId, block: BlockId, kind: OutputKind) -> Self {
632 Self::BlockEnded {
633 request,
634 block,
635 kind,
636 }
637 }
638
639 /// A tool call was made.
640 #[must_use]
641 pub const fn tool_call_started(
642 call: ToolCallId,
643 name: String,
644 arguments: serde_json::Value,
645 origin: ToolOrigin,
646 ) -> Self {
647 Self::ToolCallStarted {
648 call,
649 name,
650 arguments,
651 origin,
652 }
653 }
654
655 /// The call's fate was settled.
656 #[must_use]
657 pub const fn tool_call_decided(call: ToolCallId, decision: ToolVerdict) -> Self {
658 Self::ToolCallDecided { call, decision }
659 }
660
661 /// A running tool reported progress.
662 #[must_use]
663 pub const fn tool_progress(call: ToolCallId, progress: Progress) -> Self {
664 Self::ToolProgress { call, progress }
665 }
666
667 /// A tool call ended.
668 #[must_use]
669 pub const fn tool_call_ended(call: ToolCallId, result: ToolResult) -> Self {
670 Self::ToolCallEnded { call, result }
671 }
672}
673
674impl AgentEvent {
675 /// The run this event belongs to, for the events that carry one.
676 #[must_use]
677 pub const fn run(&self) -> Option<&RunId> {
678 match self {
679 Self::RunStarted { run, .. }
680 | Self::RunEnded { run, .. }
681 | Self::TurnStarted { run, .. }
682 | Self::TurnEnded { run, .. }
683 | Self::Checkpoint { run, .. } => Some(run),
684 _ => None,
685 }
686 }
687}
688
689#[cfg(all(test, feature = "serde"))]
690mod serde_tests {
691 use aither_core::llm::tool::{ApprovalError, ApproverFailure};
692 use aither_core::llm::{Failure, Message};
693 use std::sync::Arc;
694
695 use super::*;
696 use crate::context::{PrefixChain, PrefixRewrites, PromptPrefix};
697
698 fn call() -> ToolCallId {
699 ToolCallId::new("call-1")
700 }
701
702 fn errors() -> Vec<AgentError> {
703 vec![
704 AgentError::Llm {
705 message: "overloaded".into(),
706 failure: Failure::transient().with_retry_after(Some(Duration::from_secs(5))),
707 },
708 AgentError::ToolExecution {
709 name: "terminal".into(),
710 error: "exit 1".into(),
711 },
712 AgentError::MaxIterations { limit: 8 },
713 AgentError::HookRejected {
714 hook: "before_tool".into(),
715 reason: "no".into(),
716 },
717 AgentError::ToolNotFound { name: "x".into() },
718 AgentError::Config("bad".into()),
719 AgentError::Approval(Arc::new(ApprovalError::NoApprover {
720 kind: ApprovalKind::new("run"),
721 })),
722 AgentError::Approval(Arc::new(ApprovalError::Failed {
723 kind: ApprovalKind::new("run"),
724 failure: ApproverFailure::new(std::io::Error::other("closed")),
725 })),
726 AgentError::Approval(Arc::new(ApprovalError::Cancelled)),
727 AgentError::Cancelled,
728 AgentError::Paused(RunPause::ContextExhausted),
729 ]
730 }
731
732 fn outcomes() -> Vec<RunOutcome> {
733 let mut all = vec![
734 RunOutcome::Completed {
735 final_text: "done".into(),
736 },
737 RunOutcome::Paused {
738 pause: RunPause::ContextExhausted,
739 },
740 RunOutcome::Cancelled,
741 RunOutcome::IterationLimit,
742 ];
743 all.extend(
744 errors()
745 .into_iter()
746 .map(|error| RunOutcome::Failed { error }),
747 );
748 all
749 }
750
751 #[allow(clippy::too_many_lines)]
752 fn events() -> Vec<AgentEvent> {
753 let run = || RunId::new("run-1");
754 let request = || RequestId::new(3);
755 let child = || AgentPath::main().child("reviewer");
756 let mut all = vec![
757 AgentEvent::RunStarted {
758 run: run(),
759 agent: child(),
760 },
761 AgentEvent::TurnStarted {
762 run: run(),
763 turn: 1,
764 },
765 AgentEvent::TurnEnded {
766 run: run(),
767 turn: 1,
768 tool_calls: 2,
769 },
770 AgentEvent::RequestStarted {
771 request: request(),
772 prefix: PromptPrefix {
773 chain: PrefixChain::of(&[], &[Message::user("hello")]),
774 rewrites: PrefixRewrites {
775 compacted: true,
776 reassembled: false,
777 },
778 first_request: true,
779 },
780 },
781 AgentEvent::RequestEnded {
782 request: request(),
783 usage: Some(Usage {
784 prompt_tokens: Some(10),
785 ..Usage::default()
786 }),
787 outcome: RequestOutcome::Completed,
788 },
789 AgentEvent::BlockDelta {
790 request: request(),
791 block: BlockId::new(0),
792 kind: OutputKind::Reasoning,
793 text: "hm".into(),
794 },
795 AgentEvent::BlockEnded {
796 request: request(),
797 block: BlockId::new(0),
798 kind: OutputKind::Text,
799 },
800 AgentEvent::ToolCallDelta {
801 call: call(),
802 name: "terminal".into(),
803 arguments_fragment: "{\"cmd".into(),
804 },
805 AgentEvent::ToolCallStarted {
806 call: call(),
807 name: "terminal".into(),
808 arguments: serde_json::json!({"cmd": "ls"}),
809 origin: ToolOrigin::Hosted,
810 },
811 AgentEvent::ToolProgress {
812 call: call(),
813 progress: Progress::new(1.0),
814 },
815 AgentEvent::ToolCallEnded {
816 call: call(),
817 result: ToolResult::text("ok"),
818 },
819 AgentEvent::Paused {
820 pause: PauseId::new(1),
821 call: Some(call()),
822 kind: ApprovalKind::new("run"),
823 subject: "rm -rf".into(),
824 },
825 AgentEvent::Resumed {
826 pause: PauseId::new(1),
827 },
828 AgentEvent::CompactionStarted {
829 trigger: CompactionTrigger::ColdCache,
830 },
831 AgentEvent::CompactionRecovery {
832 error: AgentError::Cancelled,
833 alerts_removed: 1,
834 outputs_spilled: 2,
835 },
836 AgentEvent::ContextInjected {
837 source: SourceId::new("memory"),
838 kind: InjectionKind::LiveChange,
839 },
840 AgentEvent::SubagentStarted {
841 child: child(),
842 name: "reviewer".into(),
843 prompt: "look".into(),
844 },
845 AgentEvent::Checkpoint {
846 run: run(),
847 reason: CheckpointReason::Stop,
848 turn: 2,
849 phase: ContextWindowPhase::Stable,
850 message_count: 4,
851 },
852 ];
853 for decision in [
854 ToolVerdict::Allowed,
855 ToolVerdict::Denied {
856 reason: "nope".into(),
857 },
858 ToolVerdict::Rewritten,
859 ToolVerdict::AwaitingApproval,
860 ] {
861 all.push(AgentEvent::ToolCallDecided {
862 call: call(),
863 decision,
864 });
865 }
866 for outcome in outcomes() {
867 all.push(AgentEvent::RunEnded {
868 run: run(),
869 outcome: outcome.clone(),
870 });
871 all.push(AgentEvent::SubagentEnded {
872 child: child(),
873 outcome,
874 });
875 }
876 for error in errors() {
877 all.push(AgentEvent::RequestEnded {
878 request: request(),
879 usage: None,
880 outcome: RequestOutcome::Failed {
881 error: error.clone(),
882 },
883 });
884 all.push(AgentEvent::CompactionEnded {
885 outcome: CompactionOutcome::Failed(error),
886 });
887 }
888 all.push(AgentEvent::RequestEnded {
889 request: request(),
890 usage: None,
891 outcome: RequestOutcome::Retrying {
892 error: AgentError::llm_local("x"),
893 retry: 1,
894 max_retries: 3,
895 delay: Duration::from_millis(1500),
896 },
897 });
898 all.push(AgentEvent::CompactionEnded {
899 outcome: CompactionOutcome::Applied(crate::CompactResult {
900 messages_compacted: 5,
901 messages_remaining: 2,
902 summary: "s".into(),
903 }),
904 });
905 all.push(AgentEvent::CompactionEnded {
906 outcome: CompactionOutcome::NothingToCompact,
907 });
908 all.push(AgentEvent::CompactionEnded {
909 outcome: CompactionOutcome::Discarded,
910 });
911 all
912 }
913
914 #[test]
915 fn every_event_survives_a_round_trip() {
916 let at = Timestamp::from_second(1_700_000_000).expect("a valid timestamp");
917 for event in events() {
918 let timed = TimedEvent {
919 at,
920 agent: AgentPath::main().child("reviewer"),
921 event,
922 };
923 let text = serde_json::to_string(&timed).expect("serializes");
924 let back: TimedEvent = serde_json::from_str(&text).expect("deserializes");
925 assert_eq!(back.at, timed.at, "{text}");
926 assert_eq!(back.agent, timed.agent, "{text}");
927 assert_eq!(
928 serde_json::to_string(&back).expect("serializes again"),
929 text,
930 "a decoded event encodes to the same text"
931 );
932 assert_eq!(format!("{:?}", back.event), format!("{:?}", timed.event));
933 }
934 }
935}