Skip to main content

base/interface/
host_call.rs

1//! `HostCalls` — how the engine hands the host something only the host can
2//! do, and waits for its one answer: a tool the host declared, or a hook a
3//! host connection registered. Both share the wait, timeout, cancellation and
4//! disconnect handling; a call that names its [`HostId`] is answered by that
5//! connection alone.
6
7use std::path::PathBuf;
8use std::time::Duration;
9
10use async_trait::async_trait;
11use serde_json::Value;
12use tokio_util::sync::CancellationToken;
13
14use crate::interface::tool::{CallTraits, ProgressSender, ToolResult};
15
16/// The host connection that provides a tool or a hook, rather than the
17/// session's watchers at large.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
19pub struct HostId(pub u64);
20
21/// A tool the host declared for a session: the model is offered it as it is
22/// offered any other, and calling it goes to the host.
23#[derive(Debug, Clone, PartialEq)]
24#[non_exhaustive]
25pub struct HostToolDecl {
26    pub name: String,
27    pub description: String,
28    pub input_schema: Value,
29    pub traits: CallTraits,
30    pub timeout: Duration,
31    /// Offered by name only; the schema comes from `ToolSearch`.
32    pub deferred: bool,
33    /// The session's sub-agents are offered it too.
34    pub subagents: bool,
35    /// The connection that provides it; `None` for the session's own.
36    pub host: Option<HostId>,
37    /// The host lets its calls through without a rule; what refuses or asks
38    /// still does.
39    pub permitted: bool,
40}
41
42impl HostToolDecl {
43    pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(120);
44    pub const MIN_TIMEOUT: Duration = Duration::from_secs(1);
45    pub const MAX_TIMEOUT: Duration = Duration::from_secs(600);
46
47    pub fn new(
48        name: impl Into<String>,
49        description: impl Into<String>,
50        input_schema: Value,
51    ) -> Self {
52        Self {
53            name: name.into(),
54            description: description.into(),
55            input_schema,
56            traits: CallTraits::default(),
57            timeout: Self::DEFAULT_TIMEOUT,
58            deferred: false,
59            subagents: false,
60            host: None,
61            permitted: false,
62        }
63    }
64
65    pub fn traits(mut self, traits: CallTraits) -> Self {
66        self.traits = traits;
67        self
68    }
69
70    pub fn timeout(mut self, timeout: Duration) -> Self {
71        self.timeout = timeout;
72        self
73    }
74
75    pub fn deferred(mut self, yes: bool) -> Self {
76        self.deferred = yes;
77        self
78    }
79
80    pub fn subagents(mut self, yes: bool) -> Self {
81        self.subagents = yes;
82        self
83    }
84
85    pub fn host(mut self, host: HostId) -> Self {
86        self.host = Some(host);
87        self
88    }
89
90    pub fn permitted(mut self, yes: bool) -> Self {
91        self.permitted = yes;
92        self
93    }
94}
95
96#[derive(Debug, Clone, PartialEq)]
97#[non_exhaustive]
98pub enum HostCallKind {
99    /// Run the declared tool `name` on `input`, already checked against its
100    /// schema.
101    Tool { name: String, input: Value },
102    /// Answer the hook `event` on `input`, the payload a command hook reads.
103    Hook { event: String, input: Value },
104}
105
106/// One call put to the host.
107#[derive(Debug, Clone)]
108#[non_exhaustive]
109pub struct HostCall {
110    /// The engine's own id for the call, unique in the session the host
111    /// answers: a provider's `tool_use_id` is unique only within one reply,
112    /// and a parent and its sub-agent can reuse one.
113    pub call_id: String,
114    pub tool_use_id: String,
115    pub kind: HostCallKind,
116    pub timeout: Duration,
117    /// The background task of the session the host watches that the call
118    /// was made under, when a sub-agent made it.
119    pub task_id: Option<String>,
120    /// The sub-agent's own session, when a sub-agent made it.
121    pub agent_session_id: Option<String>,
122    /// The working directory of the session that made it, its own and not
123    /// the root's when a sub-agent made it.
124    pub cwd: PathBuf,
125    /// How many delegations deep the session that made it is; `0` for the
126    /// root.
127    pub depth: u32,
128    /// The one connection whose answer counts; `None`: any watcher's.
129    pub host: Option<HostId>,
130    /// Where the host's progress reports on a tool call go.
131    pub progress: Option<ProgressSender>,
132}
133
134impl HostCall {
135    pub fn tool(
136        call_id: impl Into<String>,
137        tool_use_id: impl Into<String>,
138        name: impl Into<String>,
139        input: Value,
140        timeout: Duration,
141    ) -> Self {
142        Self {
143            call_id: call_id.into(),
144            tool_use_id: tool_use_id.into(),
145            kind: HostCallKind::Tool {
146                name: name.into(),
147                input,
148            },
149            timeout,
150            task_id: None,
151            agent_session_id: None,
152            cwd: PathBuf::new(),
153            depth: 0,
154            host: None,
155            progress: None,
156        }
157    }
158
159    pub fn hook(
160        call_id: impl Into<String>,
161        tool_use_id: impl Into<String>,
162        event: impl Into<String>,
163        input: Value,
164        timeout: Duration,
165    ) -> Self {
166        Self {
167            kind: HostCallKind::Hook {
168                event: event.into(),
169                input,
170            },
171            ..Self::tool(call_id, tool_use_id, String::new(), Value::Null, timeout)
172        }
173    }
174
175    pub fn made_in(mut self, cwd: impl Into<PathBuf>, depth: u32) -> Self {
176        self.cwd = cwd.into();
177        self.depth = depth;
178        self
179    }
180
181    pub fn for_host(mut self, host: Option<HostId>) -> Self {
182        self.host = host;
183        self
184    }
185
186    pub fn with_progress(mut self, progress: ProgressSender) -> Self {
187        self.progress = Some(progress);
188        self
189    }
190
191    /// Made by a sub-agent: its session, if no deeper one is named already,
192    /// and the task it runs as, replacing a deeper one's — the host sees the
193    /// tasks of the session it watches.
194    pub fn from_delegate(mut self, task_id: Option<String>, agent_session_id: &str) -> Self {
195        if self.agent_session_id.is_none() {
196            self.agent_session_id = Some(agent_session_id.to_string());
197        }
198        if task_id.is_some() {
199            self.task_id = task_id;
200        }
201        self
202    }
203}
204
205/// What the host said.
206#[derive(Debug, Clone)]
207#[non_exhaustive]
208pub enum HostReply {
209    /// It ran the call; the result may itself say it failed (`is_error`).
210    Result(ToolResult),
211    /// It could not run the call.
212    Failed(String),
213    /// Its answer to a hook call: a hook response object.
214    Hook(Value),
215}
216
217/// How a call to the host ended.
218#[derive(Debug, Clone)]
219#[non_exhaustive]
220pub enum HostCallEnd {
221    Replied(HostReply),
222    TimedOut,
223    /// Nobody was there to answer when it was asked.
224    NoHost,
225    /// Everyone who could answer went away before anyone did.
226    HostGone,
227    Cancelled,
228}
229
230#[async_trait]
231pub trait HostCalls: Send + Sync {
232    /// Put `call` to the host and wait for how it ends: an answer, its
233    /// timeout, the host's absence, or `cancel`.
234    async fn call(&self, call: HostCall, cancel: &CancellationToken) -> HostCallEnd;
235}