rpi_agent/tool_program_observation.rs
1//! Optional host-owned observation of genuine native ToolProgram children.
2//!
3//! This is not a transcript or an event adapter. The observer owns its writer
4//! lifecycle: `close` must be idempotent and join/drain all accepted writes.
5//! Implementations must not panic. Requested arguments, partials, and finalized
6//! results are native values, not broker envelopes or guest-provided identities.
7use crate::AgentToolResult;
8use futures::future::BoxFuture;
9use serde_json::Value;
10use std::{future::Future, sync::Arc};
11use tokio_util::sync::CancellationToken;
12
13/// Native invocation identity. `request_id` remains the private `tp-*` call ID;
14/// an observation's public entry ID is separate and must not replace it.
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub struct ToolProgramChild {
17 pub root_id: String,
18 pub root_name: String,
19 pub parent_id: String,
20 pub request_id: String,
21 pub name: String,
22 pub ordinal: usize,
23}
24
25/// The creator owns all resources until `begin` returns `Ok`. On an error it
26/// must retire and join partially created writers itself; the driver cannot
27/// close a handle it never received. Construction must be panic-safe as well.
28/// After success, the driver owns calling `close`, including on cancellation.
29/// This seam does not itself install a durable store or advertise RPC support.
30pub trait ToolProgramObserver: Send + Sync {
31 fn begin<'a>(
32 &'a self,
33 child: ToolProgramChild,
34 arguments: &'a Value,
35 signal: CancellationToken,
36 ) -> BoxFuture<'a, Result<Arc<dyn ToolProgramObservation>, String>>;
37}
38
39pub trait ToolProgramObservation: Send + Sync {
40 fn id(&self) -> &str;
41 /// Nonblocking acceptance of the actual partial, without replay/truncation.
42 /// Queue/byte overflow must return an error, never silently drop a payload.
43 /// The driver retires admitted callbacks before `finish` or `close` starts.
44 fn update(&self, partial: Arc<AgentToolResult>) -> Result<(), String>;
45 /// The native harness calls this at its execution barrier, with prepared args.
46 fn prepared<'a>(&'a self, arguments: &'a Value) -> BoxFuture<'a, Result<(), String>>;
47 /// The known post-hook native result, even if transport encoding later fails.
48 fn finish<'a>(
49 &'a self,
50 result: &'a AgentToolResult,
51 is_error: bool,
52 cancelled: bool,
53 ) -> BoxFuture<'a, Result<(), String>>;
54 /// Explicitly retire the writer and drain/join its work before returning,
55 /// even when reporting an error. Catching a panic cannot guarantee cleanup;
56 /// implementations must keep worker ownership panic-safe through shutdown.
57 fn close<'a>(&'a self, reason: Option<&'a str>) -> BoxFuture<'a, Result<(), String>>;
58}
59
60tokio::task_local! { static CURRENT: Arc<dyn ToolProgramObservation>; }
61
62pub fn current_observation() -> Option<Arc<dyn ToolProgramObservation>> {
63 CURRENT.try_with(Clone::clone).ok()
64}
65
66/// Install only a native-owned observation around the child execution future.
67/// This does not grant guest authority to select an observer or entry identity.
68pub async fn scope<F: Future>(
69 observation: Arc<dyn ToolProgramObservation>,
70 future: F,
71) -> F::Output {
72 CURRENT.scope(observation, future).await
73}