Skip to main content

trusty_code/agent_loop/
sink.rs

1//! Optional tool-event observation hook for `AgentLoop` (#2056).
2//!
3//! Why: #2055 built the session event taxonomy and `SessionRegistry::record_tool_*`
4//! emission plumbing, but `AgentLoop` had no seam to call it from — its tool
5//! dispatch (`dispatch_all`) was a closed loop over `ToolRegistry::dispatch_gated`
6//! with no observer. Rather than fork the loop for daemon-driven runs, this adds
7//! ONE optional hook: a handler invoked around every tool dispatch. `run_task`'s
8//! existing CLI path (which never sets a sink) is completely unaffected — the
9//! hook defaults to `None` and costs nothing when absent.
10//! What: [`ToolEventSink`] is the trait; `crate::task::SessionToolEventSink`
11//! (#2056) is the concrete implementation that forwards to
12//! `session::registry::SessionRegistry::record_tool_*`. Kept in `agent_loop`
13//! (not `session`) so this crate's lower-level engine module has no dependency
14//! on the higher-level session/daemon layer — `session` depends on
15//! `agent_loop`, never the reverse.
16//! Test: exercised via `agent_loop::tests` (a recording sink asserts hook call
17//! order) and `crate::task` tests (the real `SessionToolEventSink`).
18
19use async_trait::async_trait;
20
21use crate::tools::telemetry::ToolTelemetry;
22
23/// One turn's working-context budget measurement, handed to
24/// [`ToolEventSink::context_budget`].
25///
26/// Why: `cadence::CadenceOutcome` is the engine's internal result type and
27/// carries no notion of the model's context window — but the Infinite Sessions
28/// guarantee a consumer wants to render ("working context >= 60%") is a RATIO
29/// against that window. This bundles the outcome with the window and cap the
30/// caller resolved, so the sink receives everything a budget indicator needs
31/// and re-derives nothing.
32/// What: `overhead_tokens` is the measured model-facing transcript size;
33/// `overhead_cap_tokens` the hard cap; `context_window` the model's real
34/// window; `working_context_pct`/`overhead_pct` the two derived percentages
35/// (summing to 100); `within_budget`, `fired`, and `rounds` mirror
36/// `CadenceOutcome`.
37/// Test: `crate::task::sink::tests::forwards_context_budget`.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub struct ContextBudgetSnapshot {
40    pub context_window: usize,
41    pub overhead_tokens: usize,
42    pub overhead_cap_tokens: usize,
43    pub working_context_pct: u8,
44    pub overhead_pct: u8,
45    pub within_budget: bool,
46    /// Whether the scheduled cadence compaction ran this turn — i.e. history
47    /// was removed from the model-facing CONTEXT (never from the durable
48    /// record).
49    pub fired: bool,
50    pub rounds: usize,
51}
52
53/// Observes tool dispatch lifecycle events from an `AgentLoop` run.
54///
55/// Why: The only way to make an agent loop's tool activity observable to an
56/// external subscriber (a `session.attach`ed client) without forking the loop
57/// or the tool registry.
58/// What: Four hooks; `call_id` is the `ToolCall::id` the model assigned,
59/// correlating every hook for the same invocation. All are `&self` (not
60/// `&mut self`) so a sink can be shared as `Arc<dyn ToolEventSink>` across a
61/// PM loop and every delegated sub-agent loop.
62///
63/// (UI Phase 1) Every hook takes `agent` — the name of the agent whose loop
64/// is dispatching. It is a PARAMETER rather than sink state precisely BECAUSE
65/// one sink instance is shared by the PM's loop and every delegated
66/// sub-agent's loop (see `task::executor::run_and_record`, which clones one
67/// `Arc` into both): a sink that stored its own agent name could only ever
68/// report one of them. The calling `AgentLoop` is the only layer that knows
69/// which agent it is, so it passes its identity per call — see
70/// `AgentLoop::with_agent`.
71/// (DOC-39 AC-13.1/13.2) Every hook ALSO takes `agent_id` — the dispatching
72/// loop's STABLE per-spawn id (see `AgentLoop::with_agent_id`). `agent`
73/// alone cannot distinguish two concurrently-delegated sub-agents that
74/// share one name (e.g. two `python-engineer` delegations): both attribute
75/// as `"python-engineer"` on this stream, and prior to `agent_id` a client's
76/// only recourse was fragile `AgentSpawned`/`AgentDone` stream-ordering
77/// inference. `agent_id` is minted once per delegation
78/// (`runner::in_process::InProcessAgentRunner::run_pipeline`) and threaded
79/// through unchanged for that whole sub-agent run.
80/// Test: `crate::task::sink::tests::*`.
81#[async_trait]
82pub trait ToolEventSink: Send + Sync {
83    /// A tool invocation is about to run.
84    async fn tool_started(
85        &self,
86        agent: &str,
87        agent_id: &str,
88        call_id: &str,
89        tool: &str,
90        args_preview: &str,
91    );
92
93    /// A tool invocation completed (successfully or with a recoverable error —
94    /// `success` distinguishes the two). Use [`Self::tool_error`] instead for an
95    /// exceptional (non-recoverable) failure.
96    async fn tool_finished(
97        &self,
98        agent: &str,
99        agent_id: &str,
100        call_id: &str,
101        tool: &str,
102        success: bool,
103        result_preview: &str,
104    );
105
106    /// A tool invocation raised an exceptional (non-recoverable) error.
107    async fn tool_error(&self, agent: &str, agent_id: &str, call_id: &str, tool: &str, error: &str);
108
109    /// The working-context budget was measured at a turn boundary (epic
110    /// #2343).
111    ///
112    /// Why: `cadence::maybe_cadence_compress` recomputes this every turn and,
113    /// before this hook existed, DISCARDED it — its own doc said it existed
114    /// "for observability/tests" while observability consumed nothing. This is
115    /// the seam that lets the measurement reach a subscriber, reusing the sink
116    /// the loop already carries rather than threading an event bus (and a
117    /// session id the engine layer must not know about) into it.
118    /// What: called at most once per turn, only from a loop that has cadence
119    /// ENABLED — cadence is PM-only by construction
120    /// (`AgentLoopConfig.cadence` defaults `None`), so a delegated engineer
121    /// loop never calls this. Defaults to a no-op so every pre-existing sink
122    /// implementation compiles and behaves exactly as before.
123    async fn context_budget(&self, snapshot: &ContextBudgetSnapshot) {
124        let _ = snapshot;
125    }
126
127    /// A tool reported structured telemetry about what it actually did
128    /// (UI Phase 1) — a real search lane, or which recalled memories entered
129    /// context. Fires IN ADDITION to [`Self::tool_finished`], never instead
130    /// of it, so existing consumers of the generic tool events are unaffected.
131    ///
132    /// Why: a default no-op body keeps every pre-existing sink impl (and
133    /// every test double) compiling unchanged — only sinks that actually
134    /// serve the UI need to override it.
135    /// What: `telemetry` is the tool's own account, carried on its
136    /// `ToolResult`; see `crate::tools::telemetry`.
137    /// Test: `crate::task::sink::tests::forwards_search_and_recall_telemetry`.
138    async fn tool_telemetry(
139        &self,
140        _agent: &str,
141        _agent_id: &str,
142        _call_id: &str,
143        _tool: &str,
144        _telemetry: &ToolTelemetry,
145    ) {
146    }
147
148    /// An incremental piece of one assistant turn's text became available
149    /// (tcode streaming epic #3696 — Gap A Slice 1, completed by Gap B in
150    /// #4425).
151    ///
152    /// Why: before this hook, a text-bearing assistant turn was recorded to
153    /// the transcript (`transcript.push_response`) but never surfaced to a
154    /// `session.attach`ed client — only tool activity was observable via the
155    /// hooks above. This is the seam that makes the assistant's own words
156    /// streamable, reusing the same optional-sink pattern rather than
157    /// threading the event bus into the engine layer.
158    /// What: a default no-op body keeps every pre-existing sink impl (and
159    /// every test double) compiling unchanged — only sinks that actually
160    /// serve the UI need to override it. `turn_id` MUST be unique within the
161    /// session across ALL agents (see [`crate::events::Event::AgentMessageDelta`]'s
162    /// doc for why a per-agent-local counter is unsafe); callers mint a UUID
163    /// v4 per turn and reuse it for EVERY delta of that turn.
164    ///
165    /// # Delta protocol (#4425)
166    ///
167    /// `AgentLoop` calls this repeatedly per text-bearing turn: once per
168    /// content chunk with `done: false`, then exactly once with `done: true`
169    /// and an EMPTY `delta`. A subscriber therefore appends every delta it
170    /// receives and treats the `done: true` call purely as "this bubble is
171    /// complete" — it carries no text of its own, so appending it
172    /// unconditionally is correct. Chunk boundaries are the provider's, not
173    /// semantic: against a transport without native streaming (the Bedrock
174    /// path until #4426, and every scripted test double) the whole turn
175    /// arrives as ONE content delta followed by the terminal one, which is
176    /// indistinguishable to a correct consumer.
177    ///
178    /// A tool-only turn (the model emitted no text) calls this ZERO times —
179    /// there is no bubble to render — so a consumer must not assume every turn
180    /// produces a terminal delta.
181    /// Test: `crate::task::sink::tests::agent_message_reaches_stream_as_delta`;
182    /// the per-turn call sequence is pinned by
183    /// `crate::agent_loop::tests::sink_events::sink_receives_agent_message_delta_for_text_turn_only`
184    /// and `…::native_streaming_transport_emits_incremental_deltas`.
185    async fn agent_message(
186        &self,
187        _agent: &str,
188        _agent_id: &str,
189        _turn_id: &str,
190        _delta: &str,
191        _done: bool,
192    ) {
193    }
194
195    /// A delegated sub-agent's own loop is about to start (#7940).
196    ///
197    /// Why: the tool hooks above make a sub-agent's ACTIVITY observable but
198    /// say nothing about the delegation itself — a client could see an
199    /// engineer's `bash` calls arrive without ever learning that a
200    /// delegation began, who it went to, or what it was for. These three
201    /// lifecycle hooks are that missing bracket, reusing the sink the
202    /// delegated loop's construction site already holds rather than
203    /// threading the event bus (and a session id `agent_loop` must not know
204    /// about) into the runner.
205    /// What: called exactly once per `delegate_to_agent` dispatch from
206    /// `runner::in_process::InProcessAgentRunner::run_pipeline`, BEFORE the
207    /// sub-agent's loop runs, with the SAME `agent_id` that loop then stamps
208    /// on every tool/message hook of its run. Default no-op body, like the
209    /// hooks above, so every pre-existing sink impl compiles unchanged.
210    /// Test: `crate::task::sink::tests::forwards_agent_lifecycle`.
211    async fn agent_spawned(&self, _agent: &str, _agent_id: &str, _task_preview: &str) {}
212
213    /// A delegated sub-agent's loop returned normally (#7940) — see
214    /// [`Self::agent_spawned`]. `status` is a short label (`"success"`).
215    /// Exactly one of this and [`Self::agent_failed`] fires per spawn.
216    async fn agent_done(&self, _agent: &str, _agent_id: &str, _status: &str) {}
217
218    /// A delegated sub-agent's loop aborted (#7940) — see
219    /// [`Self::agent_spawned`]. `error` is the runner's error text.
220    async fn agent_failed(&self, _agent: &str, _agent_id: &str, _error: &str) {}
221}