Skip to main content

trusty_code/task/
sink.rs

1//! Concrete `ToolEventSink` forwarding tool-dispatch hooks to
2//! `SessionRegistry::record_tool_*` (#2056).
3//!
4//! Why: #2055 built the emission plumbing; #2056's `agent_loop` extension
5//! built the hook (`agent_loop::ToolEventSink`) that CAN call it. This is the
6//! small piece of glue that actually wires the two together for a specific
7//! session, kept in `task` (the daemon-execution layer) rather than
8//! `agent_loop` (the generic engine) or `session` (which must not depend
9//! upward on the engine) — see `agent_loop::sink`'s module docs for the
10//! layering rationale.
11//! What: [`SessionToolEventSink`] holds an `Arc<SessionRegistry>` and the
12//! target `session_id`; each hook forwards to the matching `record_tool_*`
13//! call, logging (not propagating — the sink trait's methods return `()`)
14//! any failure, which in practice only happens if the session vanished
15//! mid-run (e.g. a race with daemon shutdown).
16//! Test: `task::sink::tests::*`.
17
18use std::sync::Arc;
19
20use async_trait::async_trait;
21
22use crate::agent_loop::ToolEventSink;
23use crate::session::SessionRegistry;
24
25/// Forwards `AgentLoop` tool-dispatch hooks to a specific session's
26/// `SessionRegistry::record_tool_*` calls (#2056).
27///
28/// Why: the seam that makes a daemon-driven run's tool activity observable
29/// to a `session.attach`ed client, over both the PM's own loop and any
30/// delegated sub-agent loop that shares this same `Arc`.
31/// What: See module docs.
32/// Test: `task::sink::tests::forwards_started_finished_and_error`.
33pub struct SessionToolEventSink {
34    registry: Arc<SessionRegistry>,
35    session_id: String,
36}
37
38impl SessionToolEventSink {
39    /// Build a sink targeting `session_id` on `registry`.
40    pub fn new(registry: Arc<SessionRegistry>, session_id: impl Into<String>) -> Self {
41        Self {
42            registry,
43            session_id: session_id.into(),
44        }
45    }
46}
47
48#[async_trait]
49impl ToolEventSink for SessionToolEventSink {
50    async fn tool_started(&self, call_id: &str, tool: &str, args_preview: &str) {
51        if let Err(e) =
52            self.registry
53                .record_tool_started(&self.session_id, tool, call_id, args_preview)
54        {
55            tracing::warn!(session_id = %self.session_id, tool, call_id, "record_tool_started failed: {e}");
56        }
57    }
58
59    async fn tool_finished(&self, call_id: &str, tool: &str, success: bool, result_preview: &str) {
60        if let Err(e) = self.registry.record_tool_finished(
61            &self.session_id,
62            tool,
63            call_id,
64            success,
65            result_preview,
66        ) {
67            tracing::warn!(session_id = %self.session_id, tool, call_id, "record_tool_finished failed: {e}");
68        }
69    }
70
71    async fn tool_error(&self, call_id: &str, tool: &str, error: &str) {
72        if let Err(e) = self
73            .registry
74            .record_tool_error(&self.session_id, tool, call_id, error)
75        {
76            tracing::warn!(session_id = %self.session_id, tool, call_id, "record_tool_error failed: {e}");
77        }
78    }
79}
80
81#[cfg(test)]
82mod tests {
83    use super::*;
84    use tokio::sync::broadcast;
85
86    /// Read the process-global event bus until an envelope matching
87    /// `session_id` arrives (mirrors `session::registry::registry_tests`'
88    /// helper — the global bus is shared across the whole test binary).
89    async fn next_event_for(
90        rx: &mut broadcast::Receiver<crate::events::SessionEventEnvelope>,
91        session_id: &str,
92    ) -> crate::events::SessionEventEnvelope {
93        tokio::time::timeout(std::time::Duration::from_secs(2), async {
94            loop {
95                let envelope = rx.recv().await.expect("event bus closed unexpectedly");
96                if envelope.session_id == session_id {
97                    return envelope;
98                }
99            }
100        })
101        .await
102        .expect("timed out waiting for an event on this session")
103    }
104
105    /// Each hook must forward to the matching `record_tool_*` call and
106    /// publish the corresponding #2055 event kind.
107    #[tokio::test]
108    async fn forwards_started_finished_and_error() {
109        let registry = Arc::new(SessionRegistry::new());
110        let session = registry.create("t".to_string(), None, None);
111        let sink = SessionToolEventSink::new(Arc::clone(&registry), session.id.clone());
112        let mut events = crate::events::subscribe();
113
114        sink.tool_started("call-1", "bash", "echo hi").await;
115        let ev = next_event_for(&mut events, &session.id).await;
116        assert_eq!(ev.kind, "tool_started");
117
118        sink.tool_finished("call-1", "bash", true, "hi").await;
119        let ev = next_event_for(&mut events, &session.id).await;
120        assert_eq!(ev.kind, "tool_finished");
121
122        sink.tool_error("call-1", "bash", "boom").await;
123        let ev = next_event_for(&mut events, &session.id).await;
124        assert_eq!(ev.kind, "tool_error");
125    }
126
127    /// Hooks against an unknown session must not panic (they log and
128    /// swallow the `session_not_found` error — the sink trait is `()`-only).
129    #[tokio::test]
130    async fn unknown_session_does_not_panic() {
131        let registry = Arc::new(SessionRegistry::new());
132        let sink = SessionToolEventSink::new(registry, "does-not-exist".to_string());
133        sink.tool_started("c", "bash", "x").await;
134        sink.tool_finished("c", "bash", true, "x").await;
135        sink.tool_error("c", "bash", "x").await;
136    }
137}