Skip to main content

microclaw_engine/internal/tool_runtime/
runtime.rs

1use std::path::{Path, PathBuf};
2
3use async_trait::async_trait;
4use microclaw_core::llm_types::ToolDefinition;
5use serde_json::json;
6
7use crate::internal::tool_runtime::sandbox::SandboxMode;
8use crate::internal::tool_runtime::types::WorkingDirIsolation;
9
10pub struct ToolResult {
11    pub content: String,
12    pub is_error: bool,
13    pub status_code: Option<i32>,
14    pub bytes: usize,
15    pub duration_ms: Option<u128>,
16    pub error_type: Option<String>,
17    pub metadata: Option<serde_json::Value>,
18}
19
20impl ToolResult {
21    pub fn success(content: String) -> Self {
22        let bytes = content.len();
23        ToolResult {
24            content,
25            is_error: false,
26            status_code: Some(0),
27            bytes,
28            duration_ms: None,
29            error_type: None,
30            metadata: None,
31        }
32    }
33
34    pub fn error(content: String) -> Self {
35        let bytes = content.len();
36        ToolResult {
37            content,
38            is_error: true,
39            status_code: Some(1),
40            bytes,
41            duration_ms: None,
42            error_type: Some("tool_error".to_string()),
43            metadata: None,
44        }
45    }
46
47    pub fn with_status_code(mut self, status_code: i32) -> Self {
48        self.status_code = Some(status_code);
49        self
50    }
51
52    pub fn with_error_type(mut self, error_type: impl Into<String>) -> Self {
53        self.error_type = Some(error_type.into());
54        self
55    }
56
57    pub fn with_metadata(mut self, metadata: serde_json::Value) -> Self {
58        self.metadata = Some(metadata);
59        self
60    }
61}
62
63/// Declaration order is the risk ordering (Low < Medium < High) — the derived
64/// `Ord` is relied on by the tool-policy `max_risk` comparison.
65#[derive(
66    Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
67)]
68#[serde(rename_all = "lowercase")]
69pub enum ToolRisk {
70    Low,
71    Medium,
72    High,
73}
74
75impl ToolRisk {
76    pub fn as_str(&self) -> &'static str {
77        match self {
78            ToolRisk::Low => "low",
79            ToolRisk::Medium => "medium",
80            ToolRisk::High => "high",
81        }
82    }
83}
84
85#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86pub enum ToolExecutionPolicy {
87    HostOnly,
88    SandboxOnly,
89    Dual,
90}
91
92impl ToolExecutionPolicy {
93    pub fn as_str(&self) -> &'static str {
94        match self {
95            ToolExecutionPolicy::HostOnly => "host-only",
96            ToolExecutionPolicy::SandboxOnly => "sandbox-only",
97            ToolExecutionPolicy::Dual => "dual",
98        }
99    }
100}
101
102pub fn tool_risk(name: &str) -> ToolRisk {
103    match name {
104        "bash" => ToolRisk::High,
105        "write_file"
106        | "edit_file"
107        | "apply_patch"
108        | "bash_kill"
109        | "bash_input"
110        | "write_memory"
111        | "a2a_send"
112        | "send_message"
113        | "sync_skills"
114        | "schedule_task"
115        | "pause_scheduled_task"
116        | "resume_scheduled_task"
117        | "cancel_scheduled_task"
118        | "replay_scheduled_task_dlq"
119        | "structured_memory_delete"
120        | "structured_memory_update" => ToolRisk::Medium,
121        // MCP tools are external code with unknown side effects; rating them
122        // Low would let them sail under a `max_risk` policy that blocks
123        // built-in write tools. Medium matches their SideEffect concurrency
124        // default.
125        name if name.starts_with("mcp_") => ToolRisk::Medium,
126        _ => ToolRisk::Low,
127    }
128}
129
130/// Classification for parallel tool execution within a single agent turn.
131#[derive(Clone, Copy, Debug, PartialEq, Eq)]
132pub enum ToolConcurrencyClass {
133    /// Safe to run concurrently with any other ReadOnly tool.
134    ReadOnly,
135    /// Has side effects — must run sequentially with respect to other SideEffect/Exclusive tools.
136    SideEffect,
137    /// Must run completely alone in its own execution wave (e.g., bash, activate_skill).
138    Exclusive,
139}
140
141/// Tools offered to an Agent Profile with `ToolPolicy::WorkspaceWrite`: everything
142/// read-only plus the tools that change files or run commands in the workspace,
143/// planning helpers and operator-configured MCP tools. Tools that reach outside
144/// the workspace (channel delivery, scheduling, A2A, media generation, skill and
145/// memory management) are excluded.
146pub fn is_workspace_tool(name: &str) -> bool {
147    tool_concurrency_class(name) == ToolConcurrencyClass::ReadOnly
148        || name.starts_with("mcp_")
149        || name.starts_with("subagents_")
150        || matches!(
151            name,
152            "write_file"
153                | "edit_file"
154                | "apply_patch"
155                | "bash"
156                | "bash_kill"
157                | "bash_input"
158                | "todo_write"
159                | "clarify"
160                | "activate_skill"
161                | "report_progress"
162                | "sessions_spawn"
163                | "session_search"
164                | "osv_check"
165                | "describe_image"
166                | "consult_specialist"
167        )
168}
169
170/// Returns the concurrency class for a built-in tool.
171/// MCP tools (prefixed with `mcp_`) default to `SideEffect`.
172/// Callers may override via `tool_concurrency_overrides` config.
173pub fn tool_concurrency_class(name: &str) -> ToolConcurrencyClass {
174    match name {
175        // Read-only tools: safe to parallelize
176        "read_file"
177        | "glob"
178        | "grep"
179        | "web_fetch"
180        | "web_search"
181        | "deep_research"
182        | "get_current_time"
183        | "compare_time"
184        | "calculate"
185        | "read_memory"
186        | "structured_memory_search"
187        | "todo_read"
188        | "export_chat"
189        | "a2a_list_peers"
190        | "list_scheduled_tasks"
191        | "get_scheduled_task_history"
192        | "list_scheduled_task_dlq"
193        | "subagents_list"
194        | "subagents_info"
195        | "subagents_focused"
196        | "subagents_log"
197        | "browser"
198        | "bash_output"
199        | "fetch_artifact" => ToolConcurrencyClass::ReadOnly,
200        // Exclusive tools: must run alone
201        "bash" | "activate_skill" | "sessions_spawn" => ToolConcurrencyClass::Exclusive,
202        // MCP tools: default to SideEffect (unknown external effects)
203        _ if name.starts_with("mcp_") => ToolConcurrencyClass::SideEffect,
204        // All other tools with side effects
205        "write_file"
206        | "edit_file"
207        | "apply_patch"
208        | "bash_input"
209        | "write_memory"
210        | "send_message"
211        | "a2a_send"
212        | "schedule_task"
213        | "pause_scheduled_task"
214        | "resume_scheduled_task"
215        | "cancel_scheduled_task"
216        | "replay_scheduled_task_dlq"
217        | "structured_memory_update"
218        | "structured_memory_delete"
219        | "todo_write"
220        | "sync_skills"
221        | "subagents_send"
222        | "subagents_focus"
223        | "subagents_unfocus"
224        | "subagents_kill"
225        | "subagents_retry_announces"
226        | "subagents_orchestrate" => ToolConcurrencyClass::SideEffect,
227        // Unknown tools: conservative default
228        _ => ToolConcurrencyClass::SideEffect,
229    }
230}
231
232/// Parse a concurrency class from a config string.
233pub fn parse_concurrency_class(s: &str) -> Option<ToolConcurrencyClass> {
234    match s.to_ascii_lowercase().as_str() {
235        "read_only" | "readonly" => Some(ToolConcurrencyClass::ReadOnly),
236        "side_effect" | "sideeffect" => Some(ToolConcurrencyClass::SideEffect),
237        "exclusive" => Some(ToolConcurrencyClass::Exclusive),
238        _ => None,
239    }
240}
241
242pub fn tool_execution_policy(name: &str) -> ToolExecutionPolicy {
243    match name {
244        "bash" => ToolExecutionPolicy::Dual,
245        "write_file" | "edit_file" | "apply_patch" => ToolExecutionPolicy::HostOnly,
246        _ => ToolExecutionPolicy::HostOnly,
247    }
248}
249
250pub fn validate_execution_policy(
251    name: &str,
252    sandbox_mode: SandboxMode,
253    sandbox_runtime_available: bool,
254) -> Result<(), String> {
255    let policy = tool_execution_policy(name);
256    match policy {
257        ToolExecutionPolicy::HostOnly => Ok(()),
258        ToolExecutionPolicy::SandboxOnly => {
259            if sandbox_mode == SandboxMode::All && sandbox_runtime_available {
260                Ok(())
261            } else {
262                Err(format!(
263                    "Tool '{name}' requires sandbox runtime (policy: {}). Enable sandbox and ensure docker runtime is available.",
264                    policy.as_str()
265                ))
266            }
267        }
268        ToolExecutionPolicy::Dual => {
269            if sandbox_mode == SandboxMode::All && !sandbox_runtime_available {
270                // Allowed by current fallback behavior, but explicit for observability.
271                tracing::warn!(
272                    tool = name,
273                    policy = policy.as_str(),
274                    "sandbox configured but runtime unavailable; falling back to host execution"
275                );
276            }
277            Ok(())
278        }
279    }
280}
281
282#[derive(Clone, Debug)]
283pub struct ToolAuthContext {
284    pub caller_channel: String,
285    pub caller_chat_id: i64,
286    /// Stable authorization principal (`main`, `scheduler`, or
287    /// `subagent:<run-id>`). Tool grants can match this value or a trailing
288    /// wildcard such as `subagent:*`.
289    pub principal: String,
290    pub control_chat_ids: Vec<i64>,
291    pub env_files: Vec<String>,
292}
293
294impl ToolAuthContext {
295    pub fn is_control_chat(&self) -> bool {
296        self.control_chat_ids.contains(&self.caller_chat_id)
297    }
298
299    pub fn can_access_chat(&self, target_chat_id: i64) -> bool {
300        self.is_control_chat() || self.caller_chat_id == target_chat_id
301    }
302}
303
304const AUTH_CONTEXT_KEY: &str = "__microclaw_auth";
305
306pub fn auth_context_from_input(input: &serde_json::Value) -> Option<ToolAuthContext> {
307    let ctx = input.get(AUTH_CONTEXT_KEY)?;
308    let caller_channel = ctx
309        .get("caller_channel")
310        .and_then(|v| v.as_str())
311        .unwrap_or("telegram")
312        .to_string();
313    let caller_chat_id = ctx.get("caller_chat_id")?.as_i64()?;
314    let control_chat_ids = ctx
315        .get("control_chat_ids")
316        .and_then(|v| v.as_array())
317        .map(|arr| arr.iter().filter_map(|x| x.as_i64()).collect())
318        .unwrap_or_default();
319    let principal = ctx
320        .get("principal")
321        .and_then(|v| v.as_str())
322        .unwrap_or("main")
323        .to_string();
324    let env_files = ctx
325        .get("env_files")
326        .and_then(|v| v.as_array())
327        .map(|arr| {
328            arr.iter()
329                .filter_map(|x| x.as_str().map(str::to_string))
330                .collect()
331        })
332        .unwrap_or_default();
333    Some(ToolAuthContext {
334        caller_channel,
335        caller_chat_id,
336        principal,
337        control_chat_ids,
338        env_files,
339    })
340}
341
342pub fn authorize_chat_access(input: &serde_json::Value, target_chat_id: i64) -> Result<(), String> {
343    if let Some(auth) = auth_context_from_input(input) {
344        if !auth.can_access_chat(target_chat_id) {
345            return Err(format!(
346                "Permission denied: chat {} cannot operate on chat {}",
347                auth.caller_chat_id, target_chat_id
348            ));
349        }
350    }
351    Ok(())
352}
353
354pub fn inject_auth_context(input: serde_json::Value, auth: &ToolAuthContext) -> serde_json::Value {
355    let mut obj = match input {
356        serde_json::Value::Object(map) => map,
357        _ => serde_json::Map::new(),
358    };
359    let mut auth_val = json!({
360        "caller_channel": auth.caller_channel,
361        "caller_chat_id": auth.caller_chat_id,
362        "principal": auth.principal,
363        "control_chat_ids": auth.control_chat_ids,
364    });
365    if !auth.env_files.is_empty() {
366        auth_val["env_files"] = json!(auth.env_files);
367    }
368    obj.insert(AUTH_CONTEXT_KEY.to_string(), auth_val);
369    serde_json::Value::Object(obj)
370}
371
372#[async_trait]
373pub trait Tool: Send + Sync {
374    fn name(&self) -> &str;
375    fn definition(&self) -> ToolDefinition;
376    async fn execute(&self, input: serde_json::Value) -> ToolResult;
377}
378
379pub fn resolve_tool_path(working_dir: &Path, path: &str) -> PathBuf {
380    let candidate = PathBuf::from(path);
381    if candidate.is_absolute() {
382        candidate
383    } else {
384        working_dir.join(candidate)
385    }
386}
387
388fn sanitize_channel_segment(channel: &str) -> String {
389    let mut out = String::with_capacity(channel.len());
390    for c in channel.chars() {
391        if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
392            out.push(c.to_ascii_lowercase());
393        } else {
394            out.push('_');
395        }
396    }
397    if out.is_empty() {
398        "unknown".to_string()
399    } else {
400        out
401    }
402}
403
404pub fn chat_working_dir(base_working_dir: &Path, channel: &str, chat_id: i64) -> PathBuf {
405    let chat_segment = if chat_id < 0 {
406        format!("neg{}", chat_id.unsigned_abs())
407    } else {
408        chat_id.to_string()
409    };
410    base_working_dir
411        .join("chat")
412        .join(sanitize_channel_segment(channel))
413        .join(chat_segment)
414}
415
416pub fn working_dir_for_context(
417    base_working_dir: &Path,
418    isolation: WorkingDirIsolation,
419    channel: &str,
420    chat_id: i64,
421) -> PathBuf {
422    match isolation {
423        WorkingDirIsolation::Direct => base_working_dir.to_path_buf(),
424        WorkingDirIsolation::Shared => base_working_dir.join("shared"),
425        WorkingDirIsolation::Chat => chat_working_dir(base_working_dir, channel, chat_id),
426    }
427}
428
429pub fn resolve_tool_working_dir(
430    base_working_dir: &Path,
431    isolation: WorkingDirIsolation,
432    input: &serde_json::Value,
433) -> PathBuf {
434    let resolved = match isolation {
435        WorkingDirIsolation::Direct => base_working_dir.to_path_buf(),
436        WorkingDirIsolation::Shared => base_working_dir.join("shared"),
437        WorkingDirIsolation::Chat => auth_context_from_input(input)
438            .map(|auth| {
439                chat_working_dir(base_working_dir, &auth.caller_channel, auth.caller_chat_id)
440            })
441            .unwrap_or_else(|| base_working_dir.join("shared")),
442    };
443    let _ = std::fs::create_dir_all(&resolved);
444    resolved
445}
446
447/// Which callers must get a human's approval before a high-risk tool runs.
448/// Built from `approval_channels` in the configuration; control chats always
449/// need approval. This is the only place that decides it.
450#[derive(Debug, Clone, PartialEq, Eq)]
451pub struct ApprovalPolicy {
452    channels: Vec<String>,
453}
454
455impl Default for ApprovalPolicy {
456    fn default() -> Self {
457        Self::new(["web", "code"])
458    }
459}
460
461impl ApprovalPolicy {
462    pub fn new<I, S>(channels: I) -> Self
463    where
464        I: IntoIterator<Item = S>,
465        S: Into<String>,
466    {
467        Self {
468            channels: channels.into_iter().map(Into::into).collect(),
469        }
470    }
471
472    pub fn requires_approval(&self, risk: ToolRisk, auth: &ToolAuthContext) -> bool {
473        risk == ToolRisk::High
474            && (auth.is_control_chat() || self.channels.contains(&auth.caller_channel))
475    }
476}
477
478fn requires_high_risk_approval(risk: ToolRisk, auth: &ToolAuthContext) -> bool {
479    ApprovalPolicy::default().requires_approval(risk, auth)
480}
481
482/// Input marker injected after explicit operator approval so a high-risk
483/// tool (or an in-tool gate like bash dangerous patterns / sandboxed A2A
484/// peers) executes on retry. Shared across crates so a rename can't silently
485/// desync the producers and consumers.
486pub const HIGH_RISK_APPROVED_KEY: &str = "__microclaw_high_risk_approved";
487
488pub fn require_high_risk_approval(
489    name: &str,
490    auth: &ToolAuthContext,
491    input: &serde_json::Value,
492) -> Option<ToolResult> {
493    require_high_risk_approval_with_risk(name, tool_risk(name), auth, input)
494}
495
496/// Like [`require_high_risk_approval`] but with the tool's effective risk
497/// supplied by the caller — used when a registration-time override (e.g. an
498/// MCP server trust tier) replaces the name-derived risk.
499pub fn require_high_risk_approval_with_risk(
500    name: &str,
501    risk: ToolRisk,
502    auth: &ToolAuthContext,
503    input: &serde_json::Value,
504) -> Option<ToolResult> {
505    if !requires_high_risk_approval(risk, auth) {
506        return None;
507    }
508    approval_gate(name, risk, auth, input)
509}
510
511/// Like [`require_high_risk_approval_with_risk`] with an explicit policy.
512pub fn require_high_risk_approval_with_policy(
513    policy: &ApprovalPolicy,
514    name: &str,
515    risk: ToolRisk,
516    auth: &ToolAuthContext,
517    input: &serde_json::Value,
518) -> Option<ToolResult> {
519    if !policy.requires_approval(risk, auth) {
520        return None;
521    }
522    approval_gate(name, risk, auth, input)
523}
524
525fn approval_gate(
526    name: &str,
527    risk: ToolRisk,
528    auth: &ToolAuthContext,
529    input: &serde_json::Value,
530) -> Option<ToolResult> {
531    let approved = input
532        .get(HIGH_RISK_APPROVED_KEY)
533        .and_then(|v| v.as_bool())
534        .unwrap_or(false);
535    if approved {
536        tracing::warn!(
537            tool = name,
538            channel = auth.caller_channel.as_str(),
539            chat_id = auth.caller_chat_id,
540            "Executing high-risk tool with explicit approval marker"
541        );
542        None
543    } else {
544        Some(
545            ToolResult::error(format!(
546                "Approval required for high-risk tool '{name}' (risk: {}). Add `{HIGH_RISK_APPROVED_KEY}: true` only after explicit operator approval.",
547                risk.as_str(),
548            ))
549            .with_error_type("approval_required"),
550        )
551    }
552}
553
554pub fn schema_object(properties: serde_json::Value, required: &[&str]) -> serde_json::Value {
555    json!({
556        "type": "object",
557        "properties": properties,
558        "required": required,
559    })
560}
561
562#[cfg(test)]
563mod tests {
564    use super::*;
565
566    #[test]
567    fn workspace_tool_set_keeps_coding_tools_and_drops_outbound_ones() {
568        for name in [
569            "read_file",
570            "grep",
571            "glob",
572            "edit_file",
573            "apply_patch",
574            "write_file",
575            "bash",
576            "bash_output",
577            "bash_kill",
578            "todo_write",
579            "mcp_github_search",
580            "subagents_list",
581        ] {
582            assert!(is_workspace_tool(name), "{name} should be a workspace tool");
583        }
584        for name in [
585            "send_message",
586            "schedule_task",
587            "a2a_send",
588            "generate_image",
589            "write_memory",
590            "sync_skills",
591            "text_to_speech",
592        ] {
593            assert!(
594                !is_workspace_tool(name),
595                "{name} should not be a workspace tool"
596            );
597        }
598    }
599
600    #[test]
601    fn test_tool_execution_policy_levels() {
602        assert_eq!(tool_execution_policy("bash"), ToolExecutionPolicy::Dual);
603        assert_eq!(
604            tool_execution_policy("write_file"),
605            ToolExecutionPolicy::HostOnly
606        );
607        assert_eq!(
608            tool_execution_policy("read_file"),
609            ToolExecutionPolicy::HostOnly
610        );
611    }
612
613    #[test]
614    fn test_validate_execution_policy_dual_allows_fallback() {
615        let ok = validate_execution_policy("bash", SandboxMode::All, false);
616        assert!(ok.is_ok());
617    }
618
619    #[test]
620    fn approval_policy_follows_configured_channels() {
621        let auth = |channel: &str| ToolAuthContext {
622            caller_channel: channel.into(),
623            caller_chat_id: 42,
624            principal: "main".into(),
625            control_chat_ids: Vec::new(),
626            env_files: Vec::new(),
627        };
628        let policy = ApprovalPolicy::new(["discord"]);
629        assert!(policy.requires_approval(ToolRisk::High, &auth("discord")));
630        assert!(!policy.requires_approval(ToolRisk::High, &auth("code")));
631        assert!(!policy.requires_approval(ToolRisk::Medium, &auth("discord")));
632        let mut control = auth("telegram");
633        control.control_chat_ids = vec![control.caller_chat_id];
634        assert!(policy.requires_approval(ToolRisk::High, &control));
635        assert!(ApprovalPolicy::default().requires_approval(ToolRisk::High, &auth("web")));
636    }
637
638    #[test]
639    fn work_requires_high_risk_approval_but_cli_headless_remains_noninteractive() {
640        let auth = |channel: &str| ToolAuthContext {
641            caller_channel: channel.into(),
642            caller_chat_id: 42,
643            principal: "main".into(),
644            control_chat_ids: Vec::new(),
645            env_files: Vec::new(),
646        };
647
648        assert!(require_high_risk_approval("bash", &auth("code"), &json!({})).is_some());
649        assert!(require_high_risk_approval("bash", &auth("headless"), &json!({})).is_none());
650    }
651}