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
21/// Observes tool dispatch lifecycle events from an `AgentLoop` run.
22///
23/// Why: The only way to make an agent loop's tool activity observable to an
24/// external subscriber (a `session.attach`ed client) without forking the loop
25/// or the tool registry.
26/// What: Three hooks, one per #2055 taxonomy kind; `call_id` is the
27/// `ToolCall::id` the model assigned, correlating start/finish/error for the
28/// same invocation. All are `&self` (not `&mut self`) so a sink can be shared
29/// as `Arc<dyn ToolEventSink>` across a PM loop and every delegated sub-agent
30/// loop.
31/// Test: `crate::task::sink::tests::*`.
32#[async_trait]
33pub trait ToolEventSink: Send + Sync {
34    /// A tool invocation is about to run.
35    async fn tool_started(&self, call_id: &str, tool: &str, args_preview: &str);
36
37    /// A tool invocation completed (successfully or with a recoverable error —
38    /// `success` distinguishes the two). Use [`Self::tool_error`] instead for an
39    /// exceptional (non-recoverable) failure.
40    async fn tool_finished(&self, call_id: &str, tool: &str, success: bool, result_preview: &str);
41
42    /// A tool invocation raised an exceptional (non-recoverable) error.
43    async fn tool_error(&self, call_id: &str, tool: &str, error: &str);
44}