Skip to main content

harn_vm/agent_events/
tool.rs

1use serde::{Deserialize, Serialize};
2
3/// Status of a tool call. Mirrors ACP's `toolCallStatus`.
4#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
5#[serde(rename_all = "snake_case")]
6pub enum ToolCallStatus {
7    /// Dispatched by the model but not yet started.
8    Pending,
9    /// Dispatch is actively running.
10    InProgress,
11    /// Finished successfully.
12    Completed,
13    /// Finished with an error.
14    Failed,
15}
16
17impl ToolCallStatus {
18    pub const ALL: [Self; 4] = [
19        Self::Pending,
20        Self::InProgress,
21        Self::Completed,
22        Self::Failed,
23    ];
24
25    pub fn as_str(self) -> &'static str {
26        match self {
27            Self::Pending => "pending",
28            Self::InProgress => "in_progress",
29            Self::Completed => "completed",
30            Self::Failed => "failed",
31        }
32    }
33}
34
35/// Wire-level classification of a `ToolCallUpdate` failure. Pairs with the
36/// human-readable `error` string so clients can render each failure type
37/// distinctly (e.g. surface a "permission denied" badge, or a different
38/// retry affordance for `network` vs `tool_error`). The enum is
39/// deliberately extensible — `unknown` is the default when the runtime
40/// could not classify a failure.
41#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
42#[serde(rename_all = "snake_case")]
43pub enum ToolCallErrorCategory {
44    /// Host-side validation rejected the args (missing required field,
45    /// invalid type, malformed JSON).
46    SchemaValidation,
47    /// The tool ran and returned an error result (e.g. `read_file` on a
48    /// missing path) — distinguished from a transport failure.
49    ToolError,
50    /// MCP transport / server-protocol error.
51    McpServerError,
52    /// Burin Swift host bridge returned an error during dispatch.
53    HostBridgeError,
54    /// `session/request_permission` denied by the client, or a policy
55    /// rule (static or dynamic) refused the call.
56    PermissionDenied,
57    /// The harn loop detector skipped this call because the same
58    /// (tool, args) pair repeated past the configured threshold.
59    RejectedLoop,
60    /// Streaming text candidate was detected (bare `name(` or
61    /// `<tool_call>` opener) but never resolved into a parseable call:
62    /// args parsed as malformed, the heredoc body broke, the tag closed
63    /// without a balanced expression, or the stream ended mid-call.
64    /// Used by the streaming candidate detector (harn#692) to retract a
65    /// `tool_call` candidate that turned out to be prose or syntactically
66    /// broken so clients can dismiss the in-flight chip.
67    ParseAborted,
68    /// The tool exceeded its time budget.
69    Timeout,
70    /// Transient network / rate-limited / 5xx provider failure.
71    Network,
72    /// The tool was cancelled (e.g. session aborted).
73    Cancelled,
74    /// Default when classification was not performed.
75    Unknown,
76}
77
78impl ToolCallErrorCategory {
79    pub const ALL: [Self; 11] = [
80        Self::SchemaValidation,
81        Self::ToolError,
82        Self::McpServerError,
83        Self::HostBridgeError,
84        Self::PermissionDenied,
85        Self::RejectedLoop,
86        Self::ParseAborted,
87        Self::Timeout,
88        Self::Network,
89        Self::Cancelled,
90        Self::Unknown,
91    ];
92
93    pub fn as_str(self) -> &'static str {
94        match self {
95            Self::SchemaValidation => "schema_validation",
96            Self::ToolError => "tool_error",
97            Self::McpServerError => "mcp_server_error",
98            Self::HostBridgeError => "host_bridge_error",
99            Self::PermissionDenied => "permission_denied",
100            Self::RejectedLoop => "rejected_loop",
101            Self::ParseAborted => "parse_aborted",
102            Self::Timeout => "timeout",
103            Self::Network => "network",
104            Self::Cancelled => "cancelled",
105            Self::Unknown => "unknown",
106        }
107    }
108
109    /// Map an internal `ErrorCategory` (used by the VM's `VmError`
110    /// classification) onto the wire enum. The internal taxonomy is
111    /// finer-grained — several transient categories collapse onto
112    /// `Network`, and the auth/quota family becomes `HostBridgeError`
113    /// because at the tool-dispatch boundary those errors come from
114    /// the bridge transport rather than the tool itself.
115    pub fn from_internal(category: &crate::value::ErrorCategory) -> Self {
116        use crate::value::ErrorCategory as Internal;
117        match category {
118            Internal::Timeout => Self::Timeout,
119            Internal::RateLimit
120            | Internal::Overloaded
121            | Internal::ServerError
122            | Internal::TransientNetwork => Self::Network,
123            Internal::SchemaValidation | Internal::SchemaStreamAborted => Self::SchemaValidation,
124            Internal::ToolError => Self::ToolError,
125            Internal::ToolRejected => Self::PermissionDenied,
126            Internal::Cancelled => Self::Cancelled,
127            Internal::Auth
128            | Internal::EgressBlocked
129            | Internal::ChannelClosed
130            | Internal::NotFound
131            | Internal::CircuitOpen
132            | Internal::BudgetExceeded
133            | Internal::Generic => Self::HostBridgeError,
134        }
135    }
136}
137
138/// Which gate refused a tool call. Pairs with [`ToolDenial`] so host
139/// harnesses can distinguish a hard capability/policy ceiling (terminal —
140/// retrying the identical call can never succeed) from a user/host
141/// approval rejection, without re-parsing the human-readable reason
142/// string (harn#2780).
143#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Default, Serialize, Deserialize)]
144#[serde(rename_all = "snake_case")]
145pub enum DenialGate {
146    /// The tool is not in the policy's allowed-tool list.
147    ToolCeiling,
148    /// The tool requires a capability/operation the policy does not grant
149    /// (e.g. `workspace.write_text`, `process.exec`).
150    CapabilityCeiling,
151    /// The tool's side-effect level exceeds the policy ceiling
152    /// (e.g. a `process_exec` tool under a `read_only` policy).
153    SideEffectCeiling,
154    /// A `tool_arg_constraint` allow-list rejected the resolved argument
155    /// value (e.g. a `command` that does not match `cargo *`).
156    ArgConstraint,
157    /// A dynamic permission rule (`when`/`unless` predicate) denied the
158    /// call.
159    DynamicPermission,
160    /// A static approval policy decided `deny`.
161    ApprovalPolicy,
162    /// Approval was required (`ask`) but could not be requested because no
163    /// host bridge was available or the request transport failed.
164    ApprovalUnavailable,
165    /// The host/user rejected an approval request (`session/request_permission`).
166    HostRejected,
167    /// A registered pre-tool hook returned `deny`.
168    HookDeny,
169    /// Gate could not be classified.
170    #[default]
171    Unknown,
172}
173
174impl DenialGate {
175    pub const ALL: [Self; 10] = [
176        Self::ToolCeiling,
177        Self::CapabilityCeiling,
178        Self::SideEffectCeiling,
179        Self::ArgConstraint,
180        Self::DynamicPermission,
181        Self::ApprovalPolicy,
182        Self::ApprovalUnavailable,
183        Self::HostRejected,
184        Self::HookDeny,
185        Self::Unknown,
186    ];
187
188    pub fn as_str(self) -> &'static str {
189        match self {
190            Self::ToolCeiling => "tool_ceiling",
191            Self::CapabilityCeiling => "capability_ceiling",
192            Self::SideEffectCeiling => "side_effect_ceiling",
193            Self::ArgConstraint => "arg_constraint",
194            Self::DynamicPermission => "dynamic_permission",
195            Self::ApprovalPolicy => "approval_policy",
196            Self::ApprovalUnavailable => "approval_unavailable",
197            Self::HostRejected => "host_rejected",
198            Self::HookDeny => "hook_deny",
199            Self::Unknown => "unknown",
200        }
201    }
202}
203
204/// Structured record of a tool call refused at the dispatch boundary —
205/// by a capability/policy ceiling, an argument allow-list, a permission
206/// rule, an approval decision, or a pre-tool hook. Carried on the denied
207/// `tool_result` and the `PermissionDeny` transcript event so host
208/// harnesses (and the loop's own stall detector) can fail or pivot early
209/// without re-parsing human-readable command output (harn#2780). The
210/// `denied_paths` field captures any workspace paths the refused call
211/// declared, so a path-scoped denial names the offending path.
212#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
213pub struct ToolDenial {
214    /// Which gate refused the call.
215    pub gate: DenialGate,
216    /// Capability/operation that was exceeded, e.g. `workspace.read_text`
217    /// or `process.exec`, when the gate identified one.
218    #[serde(skip_serializing_if = "Option::is_none", default)]
219    pub capability: Option<String>,
220    /// Workspace paths the denied call declared, when the tool annotates
221    /// path arguments. Empty for tools that declare no paths.
222    #[serde(skip_serializing_if = "Vec::is_empty", default)]
223    pub denied_paths: Vec<String>,
224    /// Whether re-issuing the identical call could ever succeed. Capability
225    /// and side-effect ceilings, argument allow-lists, and policy/approval
226    /// denials are terminal (`false`); a host harness should fail or pivot
227    /// rather than spend another model call retrying.
228    pub retryable: bool,
229    /// Human-readable explanation — the same text the model sees in the
230    /// tool result.
231    pub reason: String,
232}
233
234impl ToolDenial {
235    /// Build a terminal denial (`retryable: false`) with no declared paths
236    /// attached yet. Every gate Harn currently enforces is terminal —
237    /// re-issuing the identical call can never succeed — so the constructor
238    /// hard-codes `retryable: false`; the field exists so a future soft
239    /// denial can set it `true`. Callers at the dispatch boundary enrich
240    /// `denied_paths` from the tool's annotated path arguments.
241    pub fn terminal(
242        gate: DenialGate,
243        capability: Option<String>,
244        reason: impl Into<String>,
245    ) -> Self {
246        Self {
247            gate,
248            capability,
249            denied_paths: Vec::new(),
250            retryable: false,
251            reason: reason.into(),
252        }
253    }
254
255    pub fn to_json(&self) -> serde_json::Value {
256        serde_json::to_value(self).unwrap_or(serde_json::Value::Null)
257    }
258}
259
260/// Where a tool actually ran. Tags `ToolCallUpdate` so clients can render
261/// "via mcp:linear" / "via host bridge" badges, attribute latency by
262/// transport, and route errors to the right surface (harn#691).
263///
264/// On the wire this serializes adjacently-tagged so the `mcp_server`
265/// case carries the configured server name. The ACP adapter rewrites
266/// unit variants as bare strings (`"harn_builtin"`, `"host_bridge"`,
267/// `"provider_native"`) and the `McpServer` case as
268/// `{"kind": "mcp_server", "serverName": "..."}` to match the protocol's
269/// camelCase convention.
270#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
271#[serde(tag = "kind", rename_all = "snake_case")]
272pub enum ToolExecutor {
273    /// VM-stdlib (`read_file`, `write_file`, `exec`, `http_*`, `mcp_*`)
274    /// or any Harn-side handler closure registered in `tools_val`.
275    HarnBuiltin,
276    /// Capability provided by the host through `HostBridge.builtin_call`
277    /// (Swift-side IDE bridge, BurinApp, BurinCLI host shells).
278    HostBridge,
279    /// Tool dispatched against a configured MCP server. Detected by the
280    /// `_mcp_server` tag that `mcp_list_tools` injects on every tool
281    /// dict before the agent loop sees it.
282    McpServer { server_name: String },
283    /// Provider-side server-side tool execution — currently OpenAI
284    /// Responses-API server tools (e.g. native `tool_search`). The
285    /// runtime never dispatches these locally; the model returns the
286    /// already-executed result inline.
287    ProviderNative,
288}