infinity_agent_core/system/observer.rs
1//! The [`ThreadObserver`] trait: how embeddings observe thread execution.
2
3use async_trait::async_trait;
4use rap_protocol::ThreadId;
5use std::cell::RefCell;
6
7use super::events::{AgentEvent, ReplaySnapshot};
8
9/// Observes a thread's execution and commits any platform state derived from
10/// it.
11///
12/// The step pipeline calls these methods at exact points in its execution —
13/// there is no intermediate channel or forwarding task — which gives two
14/// guarantees:
15///
16/// - **Ordering**: [`on_event`](Self::on_event) is invoked synchronously at
17/// the moment the event is emitted, in the same executor poll that produced
18/// it. An embedding that broadcasts events to subscribers and answers
19/// attach requests from [`on_subscribe`](Self::on_subscribe) therefore gets
20/// exactly-once delivery for free: an event is either already reflected in
21/// the [`ReplaySnapshot`] a new subscriber receives, or it is broadcast to
22/// that subscriber afterwards — never both, never neither.
23/// - **Durability**: stateful events are emitted after the runtime has awaited
24/// their corresponding [`StateStore`](crate::traits::StateStore) transition.
25///
26/// Implementations that need mutable state should use interior mutability
27/// (`RefCell`); the methods take `&self` so the runtime can hold shared
28/// references across a step.
29#[async_trait(?Send)]
30pub trait ThreadObserver {
31 /// The attach-request type routed to running threads (see
32 /// [`RunningSystem::subscribe`](super::local::RunningSystem::subscribe)).
33 /// Embeddings that do not use the local driver can use `()`.
34 type SubscribeRequest: Send + 'static;
35
36 /// A display event was emitted. Called synchronously at the emission
37 /// point; keep this fast (fan-out, buffering).
38 fn on_event(&self, thread_id: &ThreadId<str>, event: &AgentEvent);
39
40 /// A subscriber attached to a running thread (local driver mode only;
41 /// step-mode embeddings never receive this call).
42 ///
43 /// This is the **live-attach hook**: when a client attaches to a thread
44 /// that is already running (via
45 /// [`RunningSystem::subscribe`](super::local::RunningSystem::subscribe)), the
46 /// driver produces a [`ReplaySnapshot`] — including in-memory state that
47 /// exists nowhere else, like the partially streamed turn and in-progress
48 /// reasoning — and hands it to the observer together with the
49 /// embedding-specific `request`. The implementation should render the
50 /// snapshot into its client-facing catch-up message and then register the
51 /// subscriber in the same list its [`on_event`](Self::on_event) fan-out
52 /// broadcasts to.
53 ///
54 /// The registration lives on the observer (rather than on
55 /// [`RunningSystem`](super::local::RunningSystem)) for two reasons: only the
56 /// embedding knows its client message type and subscriber registry, and
57 /// the snapshot + registration must happen **atomically relative to the
58 /// live event stream**. The driver invokes this method on the same task
59 /// that emits events, at a safe point between step polls, so every event
60 /// is either reflected in the snapshot or broadcast to the newly
61 /// registered subscriber afterwards — never both, never neither. Handing
62 /// the snapshot to another task to do the registration would reopen that
63 /// race.
64 fn on_subscribe(
65 &self,
66 _thread_id: &ThreadId<str>,
67 _request: Self::SubscribeRequest,
68 _snapshot: ReplaySnapshot,
69 ) {
70 }
71}
72
73/// An observer that buffers all events in memory, tagged with the thread that
74/// emitted them. Useful for step-mode embeddings (e.g. a Lambda handler) that
75/// inspect the events after the slice completes — a slice's batch may span
76/// multiple threads.
77#[derive(Default)]
78pub struct EventCollector {
79 events: RefCell<Vec<(ThreadId, AgentEvent)>>,
80}
81
82impl EventCollector {
83 pub fn new() -> Self {
84 Self::default()
85 }
86
87 /// Take the buffered `(thread_id, event)` pairs, leaving the collector
88 /// empty.
89 pub fn take(&self) -> Vec<(ThreadId, AgentEvent)> {
90 std::mem::take(&mut *self.events.borrow_mut())
91 }
92}
93
94#[async_trait(?Send)]
95impl ThreadObserver for EventCollector {
96 type SubscribeRequest = ();
97
98 fn on_event(&self, thread_id: &ThreadId<str>, event: &AgentEvent) {
99 self.events
100 .borrow_mut()
101 .push((thread_id.to_owned(), event.clone()));
102 }
103}