Skip to main content

microclaw_engine/tools/
mod.rs

1pub mod a2a;
2pub mod activate_skill;
3pub mod apply_patch;
4pub mod background_process;
5pub mod bash;
6pub mod browser;
7pub mod clarify;
8pub mod consult_specialist;
9pub mod deep_research;
10pub mod describe_image;
11pub mod edit_file;
12pub mod explore;
13pub mod export_chat;
14pub mod fetch_artifact;
15pub mod file_state;
16pub mod fuzzy_match;
17pub mod generate_image;
18pub mod generate_podcast;
19pub mod glob;
20pub mod grep;
21pub mod insights;
22pub mod knowledge_graph;
23pub mod learning_tracks;
24pub mod mcp;
25pub mod memory;
26pub mod osv_check;
27pub mod read_file;
28#[cfg(feature = "document-tools")]
29pub mod render_pdf;
30pub mod report_progress;
31pub mod schedule;
32pub mod send_message;
33pub mod session_search;
34pub mod skill_manage;
35pub mod specialists;
36pub mod structured_memory;
37pub mod subagents;
38pub mod sync_skills;
39pub mod text_to_speech;
40pub mod time_math;
41pub mod todo;
42pub mod transcribe_audio;
43pub mod web_fetch;
44pub mod web_search;
45pub mod workspace_walk;
46pub mod write_file;
47
48use std::sync::{Arc, OnceLock};
49use std::{path::PathBuf, time::Instant};
50
51/// Tools that are read-only / side-effect-free for the same arguments. Used
52/// by the per-turn guardrail controller (`tool_guardrails.rs`) to detect
53/// "no progress" loops where the model keeps re-running the same query and
54/// getting the same result. NOT a security boundary — that's `tool_risk` /
55/// `tool_execution_policy` in the runtime crate.
56pub const IDEMPOTENT_TOOLS: &[&str] = &[
57    "deep_research",
58    "describe_image",
59    "export_chat",
60    "fetch_artifact",
61    "glob",
62    "grep",
63    "insights",
64    "osv_check",
65    "read_file",
66    "session_search",
67    "time_math",
68    "transcribe_audio",
69    "web_fetch",
70    "web_search",
71];
72
73use crate::config::Config;
74use crate::internal::channels::channel_adapter::ChannelRegistry;
75use crate::internal::storage::db::Database;
76use crate::internal::tool_runtime::path_guard::{self, GovernanceGuard};
77use crate::internal::tool_runtime::runtime::inject_auth_context;
78pub use crate::internal::tool_runtime::runtime::{
79    auth_context_from_input, authorize_chat_access, resolve_tool_path, resolve_tool_working_dir,
80    schema_object, tool_execution_policy, tool_risk, validate_execution_policy, Tool,
81    ToolAuthContext, ToolResult, ToolRisk,
82};
83use crate::internal::tool_runtime::sandbox::{ExtraMount, SandboxMode, SandboxRouter};
84use crate::memory_backend::MemoryBackend;
85use microclaw_core::llm_types::ToolDefinition;
86
87pub struct ToolRegistry {
88    config: Config,
89    tools: Vec<Box<dyn Tool>>,
90    sandbox_mode: SandboxMode,
91    sandbox_runtime_available: bool,
92    cached_static_definitions: OnceLock<Vec<ToolDefinition>>,
93    /// For sealing tool-policy decisions into the audit chain. `None` only in
94    /// unit tests; both real constructors set it.
95    audit_db: Option<Arc<Database>>,
96    /// Registration-time risk overrides (e.g. MCP server trust tiers).
97    /// Consulted before the name-derived `tool_risk` at the policy and
98    /// approval choke points.
99    risk_overrides: std::collections::HashMap<String, ToolRisk>,
100}
101
102impl ToolRegistry {
103    fn should_inject_default_chat_id(tool_name: &str) -> bool {
104        matches!(
105            tool_name,
106            "write_memory"
107                | "read_memory"
108                | "todo_read"
109                | "todo_write"
110                | "send_message"
111                | "sessions_spawn"
112                | "subagents_list"
113                | "subagents_info"
114                | "subagents_kill"
115                | "subagents_focus"
116                | "subagents_unfocus"
117                | "subagents_focused"
118                | "subagents_send"
119                | "subagents_orchestrate"
120                | "session_search"
121                | "learning_tracks"
122        )
123    }
124
125    fn inject_default_chat_id_if_missing(
126        tool_name: &str,
127        input: serde_json::Value,
128        auth: &ToolAuthContext,
129    ) -> serde_json::Value {
130        if !Self::should_inject_default_chat_id(tool_name) {
131            return input;
132        }
133        let mut obj = match input {
134            serde_json::Value::Object(map) => map,
135            _ => serde_json::Map::new(),
136        };
137        let missing_chat_id = obj.get("chat_id").and_then(|v| v.as_i64()).is_none();
138        if missing_chat_id {
139            obj.insert(
140                "chat_id".to_string(),
141                serde_json::Value::Number(auth.caller_chat_id.into()),
142            );
143        }
144        serde_json::Value::Object(obj)
145    }
146
147    pub fn new(
148        config: &Config,
149        channel_registry: Arc<ChannelRegistry>,
150        db: Arc<Database>,
151        memory_backend: Arc<MemoryBackend>,
152    ) -> Self {
153        let audit_db = Some(db.clone());
154        let working_dir = PathBuf::from(&config.working_dir);
155        if let Err(e) = std::fs::create_dir_all(&working_dir) {
156            tracing::warn!(
157                "Failed to create working_dir '{}': {}",
158                working_dir.display(),
159                e
160            );
161        }
162        let skills_data_dir = config.skills_data_dir();
163        let sandbox_router = Arc::new(SandboxRouter::new(
164            config.sandbox.clone(),
165            &working_dir,
166            Self::build_extra_mounts(&working_dir, &skills_data_dir),
167        ));
168        tracing::info!(
169            mode = ?sandbox_router.mode(),
170            backend = sandbox_router.backend_name(),
171            "Sandbox initialized"
172        );
173        let processes = Arc::new(background_process::ProcessRegistry::default());
174        let file_state = Arc::new(file_state::FileStateTable::default());
175        let mut tools: Vec<Box<dyn Tool>> = vec![
176            Box::new(
177                bash::BashTool::new_with_isolation(
178                    &config.working_dir,
179                    config.working_dir_isolation,
180                )
181                .with_default_timeout_secs(config.tool_timeout_secs("bash", 120))
182                .with_sandbox_router(sandbox_router.clone())
183                .with_dangerous_patterns(&config.bash_dangerous_patterns)
184                .with_rtk(&config.rtk)
185                .with_process_registry(processes.clone()),
186            ),
187            Box::new(background_process::BashOutputTool(processes.clone())),
188            Box::new(background_process::BashKillTool(processes.clone())),
189            Box::new(background_process::BashInputTool(processes.clone())),
190            Box::new(
191                browser::BrowserTool::new(&config.data_dir)
192                    .with_default_timeout_secs(config.tool_timeout_secs("browser", 30)),
193            ),
194            Box::new(
195                read_file::ReadFileTool::new_with_isolation(
196                    &config.working_dir,
197                    config.working_dir_isolation,
198                )
199                .with_file_state(file_state.clone()),
200            ),
201            Box::new(
202                write_file::WriteFileTool::new_with_isolation(
203                    &config.working_dir,
204                    config.working_dir_isolation,
205                )
206                .with_diff_max_lines(config.diff_max_lines)
207                .with_governance_guard(Self::governance_guard(config))
208                .with_file_state(file_state.clone()),
209            ),
210            Box::new(
211                edit_file::EditFileTool::new_with_isolation(
212                    &config.working_dir,
213                    config.working_dir_isolation,
214                )
215                .with_diff_max_lines(config.diff_max_lines)
216                .with_governance_guard(Self::governance_guard(config))
217                .with_file_state(file_state.clone()),
218            ),
219            Box::new(
220                apply_patch::ApplyPatchTool::new_with_isolation(
221                    &config.working_dir,
222                    config.working_dir_isolation,
223                )
224                .with_diff_max_lines(config.diff_max_lines)
225                .with_governance_guard(Self::governance_guard(config))
226                .with_file_state(file_state.clone()),
227            ),
228            Box::new(glob::GlobTool::new_with_isolation(
229                &config.working_dir,
230                config.working_dir_isolation,
231            )),
232            Box::new(grep::GrepTool::new_with_isolation(
233                &config.working_dir,
234                config.working_dir_isolation,
235            )),
236            Box::new(memory::ReadMemoryTool::new(&config.data_dir, db.clone())),
237            Box::new(memory::WriteMemoryTool::new(
238                &config.data_dir,
239                db.clone(),
240                memory_backend.clone(),
241            )),
242            Box::new(web_fetch::WebFetchTool::new(
243                config.tool_timeout_secs("web_fetch", 15),
244                config.web_fetch_validation,
245                config.web_fetch_url_validation.clone(),
246            )),
247            Box::new(
248                web_search::WebSearchTool::new(config.tool_timeout_secs("web_search", 15))
249                    .with_provider(config.web_search.clone()),
250            ),
251            Box::new(deep_research::DeepResearchTool::new(
252                config.tool_timeout_secs("deep_research", 20),
253                config.web_search.clone(),
254                config.web_fetch_validation,
255                config.web_fetch_url_validation.clone(),
256            )),
257            Box::new(time_math::GetCurrentTimeTool::new(config.timezone.clone())),
258            Box::new(time_math::CompareTimeTool::new(config.timezone.clone())),
259            Box::new(time_math::CalculateTool::new()),
260            Box::new(send_message::SendMessageTool::new(
261                channel_registry.clone(),
262                db.clone(),
263                if config.bot_username.trim().is_empty() {
264                    "bot".to_string()
265                } else {
266                    config.bot_username.clone()
267                },
268                config.bot_username_overrides(),
269            )),
270            Box::new(a2a::A2AListPeersTool::new(config)),
271            Box::new(a2a::A2ASendTool::new(config)),
272            Box::new(schedule::ScheduleTaskTool::new(
273                channel_registry.clone(),
274                db.clone(),
275                config.timezone.clone(),
276            )),
277            Box::new(schedule::ListTasksTool::new(
278                channel_registry.clone(),
279                db.clone(),
280            )),
281            Box::new(schedule::PauseTaskTool::new(
282                channel_registry.clone(),
283                db.clone(),
284            )),
285            Box::new(schedule::ResumeTaskTool::new(
286                channel_registry.clone(),
287                db.clone(),
288            )),
289            Box::new(schedule::CancelTaskTool::new(
290                channel_registry.clone(),
291                db.clone(),
292            )),
293            Box::new(schedule::GetTaskHistoryTool::new(
294                channel_registry.clone(),
295                db.clone(),
296            )),
297            Box::new(schedule::ListTaskDlqTool::new(
298                channel_registry.clone(),
299                db.clone(),
300            )),
301            Box::new(schedule::ReplayTaskDlqTool::new(
302                channel_registry.clone(),
303                db.clone(),
304            )),
305            Box::new(learning_tracks::LearningTracksTool::new(
306                db.clone(),
307                config.timezone.clone(),
308            )),
309            Box::new(export_chat::ExportChatTool::new(
310                db.clone(),
311                &config.data_dir,
312            )),
313            Box::new(subagents::SessionsSpawnTool::new(
314                config,
315                db.clone(),
316                channel_registry.clone(),
317            )),
318            Box::new(subagents::SubagentsListTool::new(db.clone())),
319            Box::new(subagents::SubagentsInfoTool::new(db.clone())),
320            Box::new(subagents::SubagentsKillTool::new(config, db.clone())),
321            Box::new(subagents::SubagentsFocusTool::new(db.clone())),
322            Box::new(subagents::SubagentsUnfocusTool::new(db.clone())),
323            Box::new(subagents::SubagentsFocusedTool::new(db.clone())),
324            Box::new(subagents::SubagentsSendTool::new(
325                config,
326                db.clone(),
327                channel_registry.clone(),
328            )),
329            Box::new(subagents::SubagentsOrchestrateTool::new(
330                config,
331                db.clone(),
332                channel_registry.clone(),
333            )),
334            Box::new(subagents::SubagentsLogTool::new(db.clone())),
335            Box::new(subagents::SubagentsRetryAnnouncesTool::new(
336                config,
337                db.clone(),
338                channel_registry.clone(),
339            )),
340            Box::new(
341                activate_skill::ActivateSkillTool::new_with_runtime(
342                    &skills_data_dir,
343                    &config.data_dir,
344                )
345                .with_config_verification(config)
346                .with_db(db.clone()),
347            ),
348            Box::new(
349                skill_manage::SkillManageTool::new(
350                    &skills_data_dir,
351                    config.control_chat_ids.clone(),
352                )
353                .with_db(db.clone()),
354            ),
355            Box::new(sync_skills::SyncSkillsTool::new(&skills_data_dir)),
356            Box::new(todo::TodoReadTool::new(&config.data_dir)),
357            Box::new(todo::TodoWriteTool::new(&config.data_dir).with_db(db.clone())),
358            Box::new(structured_memory::StructuredMemorySearchTool::new(
359                db.clone(),
360                memory_backend.clone(),
361            )),
362            Box::new(structured_memory::StructuredMemoryDeleteTool::new(
363                db.clone(),
364                memory_backend.clone(),
365            )),
366            Box::new(structured_memory::StructuredMemoryUpdateTool::new(
367                db.clone(),
368                memory_backend.clone(),
369            )),
370            Box::new(knowledge_graph::KnowledgeGraphQueryTool::new(db.clone())),
371            Box::new(knowledge_graph::KnowledgeGraphAddTool::new(db.clone())),
372            Box::new(session_search::SessionSearchTool::new(db.clone())),
373            Box::new(
374                osv_check::OsvCheckTool::new(config.tool_timeout_secs("osv_check", 10))
375                    .with_cache(db.clone()),
376            ),
377            Box::new(clarify::ClarifyTool::new(
378                channel_registry.clone(),
379                db.clone(),
380                if config.bot_username.trim().is_empty() {
381                    "bot".to_string()
382                } else {
383                    config.bot_username.clone()
384                },
385                config.bot_username_overrides(),
386            )),
387            Box::new(generate_image::GenerateImageTool::new(
388                config,
389                channel_registry.clone(),
390                db.clone(),
391            )),
392            Box::new(describe_image::DescribeImageTool::new(config)),
393            Box::new(text_to_speech::TextToSpeechTool::new(
394                config,
395                channel_registry.clone(),
396                db.clone(),
397            )),
398            Box::new(generate_podcast::GeneratePodcastTool::new(
399                config,
400                channel_registry.clone(),
401                db.clone(),
402            )),
403            Box::new(transcribe_audio::TranscribeAudioTool::new(config)),
404            Box::new(insights::InsightsTool::new(db.clone())),
405            Box::new(fetch_artifact::FetchArtifactTool::new(db.clone())),
406        ];
407        if config.explore_tool {
408            tools.push(Box::new(explore::ExploreTool::new(config, db.clone())));
409        }
410
411        #[cfg(feature = "document-tools")]
412        tools.push(Box::new(render_pdf::RenderPdfTool::new(
413            config,
414            channel_registry.clone(),
415            db.clone(),
416        )));
417
418        // Add ClawHub tools if enabled
419        if config.clawhub.agent_tools_enabled {
420            tools.push(Box::new(crate::clawhub::tools::ClawHubSearchTool::new(
421                config,
422            )));
423            tools.push(Box::new(crate::clawhub::tools::ClawHubInstallTool::new(
424                config,
425            )));
426        }
427
428        ToolRegistry {
429            config: config.clone(),
430            tools,
431            sandbox_mode: sandbox_router.mode(),
432            sandbox_runtime_available: sandbox_router.runtime_available(),
433            cached_static_definitions: OnceLock::new(),
434            audit_db,
435            risk_overrides: std::collections::HashMap::new(),
436        }
437    }
438
439    /// Create a restricted tool registry for sub-agents.
440    /// When `allow_session_tools` is true, orchestration tools are exposed for depth-limited child spawning.
441    pub fn new_sub_agent(
442        config: &Config,
443        db: Arc<Database>,
444        channel_registry: Option<Arc<ChannelRegistry>>,
445        allow_session_tools: bool,
446    ) -> Self {
447        let audit_db = Some(db.clone());
448        let working_dir = PathBuf::from(&config.working_dir);
449        if let Err(e) = std::fs::create_dir_all(&working_dir) {
450            tracing::warn!(
451                "Failed to create working_dir '{}': {}",
452                working_dir.display(),
453                e
454            );
455        }
456        let skills_data_dir = config.skills_data_dir();
457        let sandbox_router = Arc::new(SandboxRouter::new(
458            config.sandbox.clone(),
459            &working_dir,
460            Self::build_extra_mounts(&working_dir, &skills_data_dir),
461        ));
462        let memory_backend = Arc::new(MemoryBackend::local_only(db.clone()));
463        let processes = Arc::new(background_process::ProcessRegistry::default());
464        let file_state = Arc::new(file_state::FileStateTable::default());
465        let mut tools: Vec<Box<dyn Tool>> = vec![
466            Box::new(
467                bash::BashTool::new_with_isolation(
468                    &config.working_dir,
469                    config.working_dir_isolation,
470                )
471                .with_default_timeout_secs(config.tool_timeout_secs("bash", 120))
472                .with_sandbox_router(sandbox_router.clone())
473                .with_dangerous_patterns(&config.bash_dangerous_patterns)
474                .with_rtk(&config.rtk)
475                .with_process_registry(processes.clone()),
476            ),
477            Box::new(background_process::BashOutputTool(processes.clone())),
478            Box::new(background_process::BashKillTool(processes.clone())),
479            Box::new(background_process::BashInputTool(processes.clone())),
480            Box::new(
481                browser::BrowserTool::new(&config.data_dir)
482                    .with_default_timeout_secs(config.tool_timeout_secs("browser", 30)),
483            ),
484            Box::new(
485                read_file::ReadFileTool::new_with_isolation(
486                    &config.working_dir,
487                    config.working_dir_isolation,
488                )
489                .with_file_state(file_state.clone()),
490            ),
491            Box::new(
492                write_file::WriteFileTool::new_with_isolation(
493                    &config.working_dir,
494                    config.working_dir_isolation,
495                )
496                .with_diff_max_lines(config.diff_max_lines)
497                .with_governance_guard(Self::governance_guard(config))
498                .with_file_state(file_state.clone()),
499            ),
500            Box::new(
501                edit_file::EditFileTool::new_with_isolation(
502                    &config.working_dir,
503                    config.working_dir_isolation,
504                )
505                .with_diff_max_lines(config.diff_max_lines)
506                .with_governance_guard(Self::governance_guard(config))
507                .with_file_state(file_state.clone()),
508            ),
509            Box::new(
510                apply_patch::ApplyPatchTool::new_with_isolation(
511                    &config.working_dir,
512                    config.working_dir_isolation,
513                )
514                .with_diff_max_lines(config.diff_max_lines)
515                .with_governance_guard(Self::governance_guard(config))
516                .with_file_state(file_state.clone()),
517            ),
518            Box::new(glob::GlobTool::new_with_isolation(
519                &config.working_dir,
520                config.working_dir_isolation,
521            )),
522            Box::new(grep::GrepTool::new_with_isolation(
523                &config.working_dir,
524                config.working_dir_isolation,
525            )),
526            Box::new(memory::ReadMemoryTool::new(&config.data_dir, db.clone())),
527            Box::new(web_fetch::WebFetchTool::new(
528                config.tool_timeout_secs("web_fetch", 15),
529                config.web_fetch_validation,
530                config.web_fetch_url_validation.clone(),
531            )),
532            Box::new(
533                web_search::WebSearchTool::new(config.tool_timeout_secs("web_search", 15))
534                    .with_provider(config.web_search.clone()),
535            ),
536            Box::new(deep_research::DeepResearchTool::new(
537                config.tool_timeout_secs("deep_research", 20),
538                config.web_search.clone(),
539                config.web_fetch_validation,
540                config.web_fetch_url_validation.clone(),
541            )),
542            Box::new(time_math::GetCurrentTimeTool::new(config.timezone.clone())),
543            Box::new(time_math::CompareTimeTool::new(config.timezone.clone())),
544            Box::new(time_math::CalculateTool::new()),
545            Box::new(
546                activate_skill::ActivateSkillTool::new_with_runtime(
547                    &skills_data_dir,
548                    &config.data_dir,
549                )
550                .with_config_verification(config)
551                .with_db(db.clone()),
552            ),
553            Box::new(structured_memory::StructuredMemorySearchTool::new(
554                db.clone(),
555                memory_backend,
556            )),
557            Box::new(session_search::SessionSearchTool::new(db.clone())),
558            Box::new(
559                osv_check::OsvCheckTool::new(config.tool_timeout_secs("osv_check", 10))
560                    .with_cache(db.clone()),
561            ),
562            Box::new(fetch_artifact::FetchArtifactTool::new(db.clone())),
563            Box::new(describe_image::DescribeImageTool::new(config)),
564            Box::new(consult_specialist::ConsultSpecialistTool::new(config)),
565        ];
566        // Visual creation + progress reporting: available to specialists whenever a
567        // channel registry is present, independent of session-spawn permissions.
568        if let Some(cr) = &channel_registry {
569            tools.push(Box::new(generate_image::GenerateImageTool::new(
570                config,
571                cr.clone(),
572                db.clone(),
573            )));
574            tools.push(Box::new(report_progress::ReportProgressTool::new(
575                config,
576                cr.clone(),
577                db.clone(),
578            )));
579        }
580        if allow_session_tools {
581            if let Some(channel_registry) = channel_registry {
582                tools.push(Box::new(subagents::SessionsSpawnTool::new(
583                    config,
584                    db.clone(),
585                    channel_registry.clone(),
586                )));
587                tools.push(Box::new(subagents::SubagentsListTool::new(db.clone())));
588                tools.push(Box::new(subagents::SubagentsInfoTool::new(db.clone())));
589                tools.push(Box::new(subagents::SubagentsKillTool::new(
590                    config,
591                    db.clone(),
592                )));
593                tools.push(Box::new(subagents::SubagentsOrchestrateTool::new(
594                    config,
595                    db.clone(),
596                    channel_registry.clone(),
597                )));
598                tools.push(Box::new(subagents::SubagentsLogTool::new(db.clone())));
599            }
600        }
601        ToolRegistry {
602            config: config.clone(),
603            tools,
604            sandbox_mode: sandbox_router.mode(),
605            sandbox_runtime_available: sandbox_router.runtime_available(),
606            cached_static_definitions: OnceLock::new(),
607            audit_db,
608            risk_overrides: std::collections::HashMap::new(),
609        }
610    }
611
612    /// Paths the generic file tools must not modify (issue #501): the agent's
613    /// own config, memory, soul and context files, plus the path allowlist.
614    fn governance_guard(config: &Config) -> GovernanceGuard {
615        if config.allow_governance_file_writes {
616            return GovernanceGuard::default();
617        }
618        let data_root = config.data_root_dir();
619        let souls_dir = PathBuf::from(config.souls_data_dir());
620        let mut guard = GovernanceGuard::default()
621            .protect_data_root(&data_root)
622            .protect_data_root(config.runtime_data_dir())
623            .exempt(&config.working_dir)
624            .exempt(config.skills_data_dir())
625            .protect_dir(&souls_dir)
626            .protect_dir(match &config.context_dir {
627                Some(dir) => PathBuf::from(shellexpand::tilde(dir).into_owned()),
628                None => data_root.join("context"),
629            });
630        if data_root.file_name().and_then(|n| n.to_str()) == Some("runtime") {
631            if let Some(parent) = data_root.parent() {
632                guard = guard.protect_data_root(parent);
633            }
634        }
635        if let Ok(Some(config_path)) = Config::resolve_config_path() {
636            guard = guard.protect_file(config_path);
637        }
638        if let Some(allowlist) = path_guard::path_allowlist_file() {
639            guard = guard.protect_file(allowlist);
640        }
641        // ./SOUL.md in the process directory is the last soul fallback.
642        guard = guard.protect_file("SOUL.md");
643        let mut soul_paths: Vec<String> = config.soul_path.iter().cloned().collect();
644        for (name, value) in &config.channels {
645            soul_paths.extend(config.soul_path_for_channel(name));
646            if let Some(accounts) = value.get("accounts").and_then(|v| v.as_mapping()) {
647                for account in accounts.keys().filter_map(|k| k.as_str()) {
648                    soul_paths.extend(config.soul_path_for_channel(&format!("{name}.{account}")));
649                }
650            }
651        }
652        for soul in soul_paths {
653            let configured = PathBuf::from(shellexpand::tilde(&soul).into_owned());
654            if configured.is_relative() {
655                guard = guard
656                    .protect_file(data_root.join(&configured))
657                    .protect_file(souls_dir.join(&configured));
658            }
659            guard = guard.protect_file(configured);
660        }
661        guard
662    }
663
664    fn build_extra_mounts(working_dir: &PathBuf, skills_data_dir: &str) -> Vec<ExtraMount> {
665        let skills_path = PathBuf::from(skills_data_dir);
666        let canonical_skills = std::fs::canonicalize(&skills_path).unwrap_or(skills_path.clone());
667        let canonical_working =
668            std::fs::canonicalize(working_dir).unwrap_or_else(|_| working_dir.clone());
669        let mut mounts = Vec::new();
670        if canonical_skills.exists() && canonical_skills != canonical_working {
671            mounts.push(ExtraMount {
672                host_path: canonical_skills,
673                read_only: true,
674            });
675        }
676        mounts
677    }
678
679    pub fn add_tool(&mut self, tool: Box<dyn Tool>) {
680        // Invalidate cache when a new tool is added
681        self.cached_static_definitions = OnceLock::new();
682        self.tools.push(tool);
683    }
684
685    /// Register a tool with an explicit effective risk that replaces the
686    /// name-derived `tool_risk` at the policy/approval choke points. Used
687    /// for MCP tools whose server carries a trust tier.
688    pub fn add_tool_with_risk(&mut self, tool: Box<dyn Tool>, risk: ToolRisk) {
689        self.risk_overrides.insert(tool.name().to_string(), risk);
690        self.add_tool(tool);
691    }
692
693    /// Register every MCP tool from `mcp_manager`, mapping each server's
694    /// trust tier onto the tool's effective risk. Shared by all boot paths
695    /// (runtime, ACP) so trust tiers are honored uniformly.
696    pub fn register_mcp_tools(&mut self, mcp_manager: &crate::mcp::McpManager) {
697        for (server, tool_info) in mcp_manager.all_tools() {
698            let risk = match server.trust() {
699                crate::mcp::McpTrust::Trusted => ToolRisk::Low,
700                crate::mcp::McpTrust::Limited => ToolRisk::Medium,
701                crate::mcp::McpTrust::Sandboxed => ToolRisk::High,
702            };
703            self.add_tool_with_risk(
704                Box::new(crate::tools::mcp::McpTool::new(server, tool_info)),
705                risk,
706            );
707        }
708    }
709
710    /// Effective risk of a tool: registration-time override first, then the
711    /// shared name-derived mapping.
712    pub fn effective_tool_risk(&self, name: &str) -> ToolRisk {
713        self.risk_overrides
714            .get(name)
715            .copied()
716            .unwrap_or_else(|| tool_risk(name))
717    }
718
719    pub fn definitions(&self) -> Vec<ToolDefinition> {
720        let static_defs = self
721            .cached_static_definitions
722            .get_or_init(|| self.tools.iter().map(|t| t.definition()).collect())
723            .clone();
724        let mut out = static_defs;
725        let mut existing: std::collections::HashSet<String> =
726            out.iter().map(|d| d.name.to_ascii_lowercase()).collect();
727        for plugin_def in crate::plugins::dynamic_plugin_tool_definitions(&self.config) {
728            let normalized = plugin_def.name.to_ascii_lowercase();
729            if existing.insert(normalized) {
730                out.push(plugin_def);
731            }
732        }
733        out
734    }
735
736    /// The catalog `auth` is actually allowed to use: [`Self::definitions`]
737    /// minus every tool whose call `execute_with_auth` would block under the
738    /// operator's `tool_policy` (global rules and capability grants). The
739    /// model is not offered what it cannot run, and a denied tool's existence
740    /// is not advertised. Warn-mode violations stay visible: the call runs
741    /// and is audited. This is advisory only; the choke point in
742    /// `execute_with_auth` still enforces the policy on every call.
743    pub fn definitions_for(&self, auth: &ToolAuthContext) -> Vec<ToolDefinition> {
744        self.definitions()
745            .into_iter()
746            .filter(|definition| {
747                !matches!(
748                    crate::tool_guardrails::evaluate_tool_policy_for_auth_with_risk(
749                        &self.config.tool_policy,
750                        &definition.name,
751                        auth,
752                        self.effective_tool_risk(&definition.name),
753                    ),
754                    crate::tool_guardrails::PolicyDecision::Block(_)
755                )
756            })
757            .collect()
758    }
759
760    pub async fn execute(&self, name: &str, input: serde_json::Value) -> ToolResult {
761        for tool in &self.tools {
762            if tool.name() == name {
763                let started = Instant::now();
764                let mut result = tool.execute(input).await;
765                result.duration_ms = Some(started.elapsed().as_millis());
766                result.bytes = result.content.len();
767                if result.is_error && result.error_type.is_none() {
768                    result.error_type = Some("tool_error".to_string());
769                }
770                if result.status_code.is_none() {
771                    result.status_code = Some(if result.is_error { 1 } else { 0 });
772                }
773                return result;
774            }
775        }
776        ToolResult::error(format!("Unknown tool: {name}")).with_error_type("unknown_tool")
777    }
778
779    pub async fn execute_with_auth(
780        &self,
781        name: &str,
782        input: serde_json::Value,
783        auth: &ToolAuthContext,
784    ) -> ToolResult {
785        if auth.principal.starts_with("subagent:")
786            && self
787                .config
788                .read_only_subagent_channels
789                .contains(&auth.caller_channel)
790            && !matches!(
791                name,
792                "web_search"
793                    | "web_fetch"
794                    | "deep_research"
795                    | "read_memory"
796                    | "structured_memory_search"
797                    | "session_search"
798                    | "read_file"
799                    | "grep"
800                    | "glob"
801                    | "time_math"
802                    | "get_current_time"
803                    | "compare_time"
804                    | "calculate"
805                    | "osv_check"
806                    | "fetch_artifact"
807                    | "describe_image"
808                    | "consult_specialist"
809                    | "report_progress"
810                    | "subagents_list"
811                    | "subagents_info"
812            )
813        {
814            return ToolResult::error(format!(
815                "Tool `{name}` is not available to sub-agents on this channel; workspace writes are owned by the main agent"
816            ))
817            .with_error_type("work_subagent_read_only");
818        }
819        if auth.principal == "learning_foundry"
820            && !matches!(
821                name,
822                "web_search"
823                    | "web_fetch"
824                    | "deep_research"
825                    | "read_memory"
826                    | "session_search"
827                    | "read_file"
828                    | "grep"
829                    | "glob"
830                    | "time_math"
831                    | "get_current_time"
832                    | "compare_time"
833                    | "calculate"
834            )
835        {
836            return ToolResult::error(format!(
837                "Tool `{name}` is not available to the read-only Learning Foundry principal"
838            ))
839            .with_error_type("learning_foundry_read_only");
840        }
841        // Operator-set tool policy. Enforced here — the single choke point —
842        // so main-loop calls, sub-agent loops, and any future caller are all
843        // covered; a denied tool cannot be reached by delegation. Decisions
844        // are sealed into the audit chain fire-and-forget (the DB write
845        // itself preserves chain order).
846        let effective_risk = self.effective_tool_risk(name);
847        match crate::tool_guardrails::evaluate_tool_policy_for_auth_with_risk(
848            &self.config.tool_policy,
849            name,
850            auth,
851            effective_risk,
852        ) {
853            crate::tool_guardrails::PolicyDecision::Allow => {}
854            decision => {
855                let (action, status, block_reason) = match decision {
856                    crate::tool_guardrails::PolicyDecision::Warn(reason) => {
857                        ("warn", "allowed", Err(reason))
858                    }
859                    crate::tool_guardrails::PolicyDecision::Block(reason) => {
860                        ("block", "blocked", Ok(reason))
861                    }
862                    crate::tool_guardrails::PolicyDecision::Allow => unreachable!(),
863                };
864                let reason = match &block_reason {
865                    Ok(r) | Err(r) => r.clone(),
866                };
867                tracing::warn!(
868                    tool = name,
869                    chat_id = auth.caller_chat_id,
870                    principal = %auth.principal,
871                    action,
872                    %reason,
873                    "Tool policy violation"
874                );
875                if let Some(db) = self.audit_db.clone() {
876                    let tool = name.to_string();
877                    let actor = format!("chat:{}:{}", auth.caller_chat_id, auth.principal);
878                    let detail = reason.clone();
879                    tokio::spawn(async move {
880                        let _ = crate::internal::storage::db::call_blocking(db, move |db| {
881                            db.log_audit_event(
882                                "tool_policy",
883                                &actor,
884                                action,
885                                Some(&tool),
886                                status,
887                                Some(&detail),
888                            )
889                        })
890                        .await;
891                    });
892                }
893                if block_reason.is_ok() {
894                    return ToolResult::error(format!(
895                        "Tool call blocked by policy: {reason}. Do not retry this tool; \
896                         use a permitted tool or explain the limitation to the user."
897                    ))
898                    .with_error_type("tool_policy_blocked");
899                }
900            }
901        }
902        for (url, decision) in crate::internal::tool_runtime::egress::evaluate_tool_input(
903            &self.config.egress_policy,
904            &input,
905        ) {
906            let (action, status, reason, blocked) = match decision {
907                crate::internal::tool_runtime::egress::EgressDecision::Allow => continue,
908                crate::internal::tool_runtime::egress::EgressDecision::Warn(reason) => {
909                    ("warn", "allowed", reason, false)
910                }
911                crate::internal::tool_runtime::egress::EgressDecision::Block(reason) => {
912                    ("block", "blocked", reason, true)
913                }
914            };
915            tracing::warn!(
916                tool = name,
917                chat_id = auth.caller_chat_id,
918                principal = %auth.principal,
919                %url,
920                action,
921                %reason,
922                "Egress policy violation"
923            );
924            if let Some(db) = self.audit_db.clone() {
925                let tool = name.to_string();
926                let actor = format!("chat:{}:{}", auth.caller_chat_id, auth.principal);
927                let detail = format!("{reason}; url={url}");
928                tokio::spawn(async move {
929                    let _ = crate::internal::storage::db::call_blocking(db, move |db| {
930                        db.log_audit_event(
931                            "egress_policy",
932                            &actor,
933                            action,
934                            Some(&tool),
935                            status,
936                            Some(&detail),
937                        )
938                    })
939                    .await;
940                });
941            }
942            if blocked {
943                return ToolResult::error(format!(
944                    "Tool call blocked by egress policy: {reason}. Do not retry this destination."
945                ))
946                .with_error_type("egress_policy_blocked");
947            }
948        }
949        if let Err(msg) =
950            validate_execution_policy(name, self.sandbox_mode, self.sandbox_runtime_available)
951        {
952            return ToolResult::error(msg).with_error_type("execution_policy_blocked");
953        }
954        let mut input = input;
955        if self.config.high_risk_tool_user_confirmation_required {
956            // Only tools that can actually pause for approval need the
957            // standing-grant lookup: High-risk tools (registry gate) plus the
958            // tools with their own in-tool gates (`a2a_send` sandboxed peer;
959            // `bash` is already High-risk). Everything else skips the DB read
960            // on the hot path.
961            let gateable = effective_risk == ToolRisk::High || name == "a2a_send";
962            if gateable {
963                // A standing per-chat allowance (operator replied "always
964                // allow" to a previous prompt) satisfies the gate. It never
965                // bypasses tool_policy or egress policy, which already ran
966                // above. When present, inject the approval marker so the
967                // in-tool gates (bash dangerous patterns, sandboxed a2a
968                // peers) honor it too instead of re-prompting every call.
969                let standing = if let Some(db) = self.audit_db.clone() {
970                    let key = format!("approved_tool:{}:{}", auth.caller_chat_id, name);
971                    crate::internal::storage::db::call_blocking(db, move |db| {
972                        db.get_runtime_meta(&key)
973                    })
974                    .await
975                    .ok()
976                    .flatten()
977                    .is_some()
978                } else {
979                    false
980                };
981                if standing {
982                    tracing::info!(
983                        tool = name,
984                        chat_id = auth.caller_chat_id,
985                        "High-risk tool allowed by standing per-chat approval"
986                    );
987                    if let serde_json::Value::Object(map) = &mut input {
988                        map.insert(
989                            "__microclaw_high_risk_approved".to_string(),
990                            serde_json::Value::Bool(true),
991                        );
992                    }
993                } else if let Some(blocked) =
994                    crate::internal::tool_runtime::runtime::require_high_risk_approval_with_policy(
995                        &crate::internal::tool_runtime::runtime::ApprovalPolicy::new(
996                            self.config.approval_channels.iter().cloned(),
997                        ),
998                        name,
999                        effective_risk,
1000                        auth,
1001                        &input,
1002                    )
1003                {
1004                    return blocked;
1005                }
1006            }
1007        }
1008
1009        tracing::debug!(
1010            tool = name,
1011            risk = effective_risk.as_str(),
1012            execution_policy = tool_execution_policy(name).as_str(),
1013            sandbox_mode = ?self.sandbox_mode,
1014            sandbox_runtime_available = self.sandbox_runtime_available,
1015            "tool execution policy evaluated"
1016        );
1017        let input = Self::inject_default_chat_id_if_missing(name, input, auth);
1018        let input = inject_auth_context(input, auth);
1019        let result = self.execute(name, input.clone()).await;
1020        if result.error_type.as_deref() == Some("unknown_tool") {
1021            if let Some(dynamic) =
1022                crate::plugins::execute_dynamic_plugin_tool(&self.config, name, input).await
1023            {
1024                return dynamic;
1025            }
1026        }
1027        result
1028    }
1029}
1030
1031#[cfg(test)]
1032mod tests {
1033    use super::*;
1034    use crate::config::WorkingDirIsolation;
1035    use async_trait::async_trait;
1036    use serde_json::json;
1037
1038    #[test]
1039    fn test_tool_result_success() {
1040        let r = ToolResult::success("ok".into());
1041        assert_eq!(r.content, "ok");
1042        assert!(!r.is_error);
1043    }
1044
1045    #[test]
1046    fn test_tool_result_error() {
1047        let r = ToolResult::error("fail".into());
1048        assert_eq!(r.content, "fail");
1049        assert!(r.is_error);
1050    }
1051
1052    #[test]
1053    fn test_schema_object() {
1054        let schema = schema_object(
1055            json!({
1056                "name": {"type": "string"},
1057                "age": {"type": "integer"}
1058            }),
1059            &["name"],
1060        );
1061        assert_eq!(schema["type"], "object");
1062        assert!(schema["properties"]["name"].is_object());
1063        assert!(schema["properties"]["age"].is_object());
1064        let required = schema["required"].as_array().unwrap();
1065        assert_eq!(required.len(), 1);
1066        assert_eq!(required[0], "name");
1067    }
1068
1069    #[test]
1070    fn test_schema_object_empty_required() {
1071        let schema = schema_object(json!({}), &[]);
1072        let required = schema["required"].as_array().unwrap();
1073        assert!(required.is_empty());
1074    }
1075
1076    #[test]
1077    fn test_auth_context_from_input() {
1078        let input = json!({
1079            "__microclaw_auth": {
1080                "caller_channel": "telegram",
1081                "caller_chat_id": 123,
1082                "control_chat_ids": [123, 999]
1083            }
1084        });
1085        let auth = auth_context_from_input(&input).unwrap();
1086        assert_eq!(auth.caller_channel, "telegram");
1087        assert_eq!(auth.caller_chat_id, 123);
1088        assert!(auth.is_control_chat());
1089        assert!(auth.can_access_chat(456));
1090    }
1091
1092    #[test]
1093    fn test_authorize_chat_access_denied() {
1094        let input = json!({
1095            "__microclaw_auth": {
1096                "caller_channel": "telegram",
1097                "caller_chat_id": 100,
1098                "control_chat_ids": []
1099            }
1100        });
1101        let err = authorize_chat_access(&input, 200).unwrap_err();
1102        assert!(err.contains("Permission denied"));
1103    }
1104
1105    #[test]
1106    fn test_resolve_tool_working_dir_shared() {
1107        let dir = resolve_tool_working_dir(
1108            std::path::Path::new("/tmp/work"),
1109            WorkingDirIsolation::Shared,
1110            &json!({
1111                "__microclaw_auth": {
1112                    "caller_channel": "telegram",
1113                    "caller_chat_id": 123,
1114                    "control_chat_ids": []
1115                }
1116            }),
1117        );
1118        assert_eq!(dir, std::path::PathBuf::from("/tmp/work/shared"));
1119    }
1120
1121    #[test]
1122    fn test_resolve_tool_working_dir_direct() {
1123        let dir = resolve_tool_working_dir(
1124            std::path::Path::new("/tmp/work"),
1125            WorkingDirIsolation::Direct,
1126            &json!({
1127                "__microclaw_auth": {
1128                    "caller_channel": "headless",
1129                    "caller_chat_id": 123,
1130                    "control_chat_ids": []
1131                }
1132            }),
1133        );
1134        assert_eq!(dir, std::path::PathBuf::from("/tmp/work"));
1135    }
1136
1137    #[test]
1138    fn test_resolve_tool_working_dir_chat() {
1139        let dir = resolve_tool_working_dir(
1140            std::path::Path::new("/tmp/work"),
1141            WorkingDirIsolation::Chat,
1142            &json!({
1143                "__microclaw_auth": {
1144                    "caller_channel": "discord",
1145                    "caller_chat_id": -100123,
1146                    "control_chat_ids": []
1147                }
1148            }),
1149        );
1150        assert_eq!(
1151            dir,
1152            std::path::PathBuf::from("/tmp/work/chat/discord/neg100123")
1153        );
1154    }
1155
1156    struct DummyTool {
1157        tool_name: String,
1158    }
1159
1160    #[async_trait]
1161    impl Tool for DummyTool {
1162        fn name(&self) -> &str {
1163            &self.tool_name
1164        }
1165
1166        fn definition(&self) -> ToolDefinition {
1167            ToolDefinition {
1168                name: self.tool_name.clone(),
1169                description: "dummy".into(),
1170                input_schema: schema_object(json!({}), &[]),
1171            }
1172        }
1173
1174        async fn execute(&self, _input: serde_json::Value) -> ToolResult {
1175            ToolResult::success("ok".into())
1176        }
1177    }
1178
1179    struct CaptureInputTool {
1180        tool_name: String,
1181    }
1182
1183    #[async_trait]
1184    impl Tool for CaptureInputTool {
1185        fn name(&self) -> &str {
1186            &self.tool_name
1187        }
1188
1189        fn definition(&self) -> ToolDefinition {
1190            ToolDefinition {
1191                name: self.tool_name.clone(),
1192                description: "capture".into(),
1193                input_schema: schema_object(json!({}), &[]),
1194            }
1195        }
1196
1197        async fn execute(&self, input: serde_json::Value) -> ToolResult {
1198            ToolResult::success(input.to_string())
1199        }
1200    }
1201
1202    #[test]
1203    fn test_tool_risk_levels() {
1204        assert_eq!(tool_risk("bash"), ToolRisk::High);
1205        assert_eq!(tool_risk("write_file"), ToolRisk::Medium);
1206        assert_eq!(tool_risk("pause_scheduled_task"), ToolRisk::Medium);
1207        assert_eq!(tool_risk("sync_skills"), ToolRisk::Medium);
1208        assert_eq!(tool_risk("read_file"), ToolRisk::Low);
1209    }
1210
1211    #[tokio::test]
1212    async fn test_tool_policy_blocks_at_choke_point() {
1213        // Policy enforcement lives in execute_with_auth so EVERY caller —
1214        // main loop, sub-agent loops — is covered. Denied tools return a
1215        // typed error before any execution-policy/approval logic runs.
1216        let mut config = crate::config::Config::test_defaults();
1217        config.tool_policy.mode = crate::tool_guardrails::ToolPolicyMode::Block;
1218        config.tool_policy.deny_tools = vec!["bash".to_string()];
1219        let registry = ToolRegistry {
1220            config,
1221            sandbox_mode: SandboxMode::Off,
1222            sandbox_runtime_available: false,
1223            cached_static_definitions: OnceLock::new(),
1224            audit_db: None,
1225            risk_overrides: std::collections::HashMap::new(),
1226            tools: vec![Box::new(DummyTool {
1227                tool_name: "bash".into(),
1228            })],
1229        };
1230        let auth = ToolAuthContext {
1231            caller_channel: "telegram".into(),
1232            caller_chat_id: 1,
1233            principal: "main".into(),
1234            control_chat_ids: vec![],
1235            env_files: vec![],
1236        };
1237        let result = registry.execute_with_auth("bash", json!({}), &auth).await;
1238        assert!(result.is_error);
1239        assert_eq!(result.error_type.as_deref(), Some("tool_policy_blocked"));
1240
1241        // Warn mode executes the tool (DummyTool returns success).
1242        let mut warn_config = crate::config::Config::test_defaults();
1243        warn_config.tool_policy.mode = crate::tool_guardrails::ToolPolicyMode::Warn;
1244        warn_config.tool_policy.deny_tools = vec!["bash".to_string()];
1245        warn_config.high_risk_tool_user_confirmation_required = false;
1246        let registry = ToolRegistry {
1247            config: warn_config,
1248            sandbox_mode: SandboxMode::Off,
1249            sandbox_runtime_available: false,
1250            cached_static_definitions: OnceLock::new(),
1251            audit_db: None,
1252            risk_overrides: std::collections::HashMap::new(),
1253            tools: vec![Box::new(DummyTool {
1254                tool_name: "bash".into(),
1255            })],
1256        };
1257        let result = registry.execute_with_auth("bash", json!({}), &auth).await;
1258        assert!(
1259            !result.is_error,
1260            "warn mode must still execute: {}",
1261            result.content
1262        );
1263    }
1264
1265    #[tokio::test]
1266    async fn learning_foundry_principal_is_read_only_at_choke_point() {
1267        let registry = ToolRegistry {
1268            config: crate::config::Config::test_defaults(),
1269            sandbox_mode: SandboxMode::Off,
1270            sandbox_runtime_available: false,
1271            cached_static_definitions: OnceLock::new(),
1272            audit_db: None,
1273            risk_overrides: std::collections::HashMap::new(),
1274            tools: vec![
1275                Box::new(DummyTool {
1276                    tool_name: "write_file".into(),
1277                }),
1278                Box::new(DummyTool {
1279                    tool_name: "web_search".into(),
1280                }),
1281            ],
1282        };
1283        let auth = ToolAuthContext {
1284            caller_channel: "learning_foundry".into(),
1285            caller_chat_id: -7,
1286            principal: "learning_foundry".into(),
1287            control_chat_ids: vec![],
1288            env_files: vec![],
1289        };
1290        let write = registry
1291            .execute_with_auth("write_file", json!({}), &auth)
1292            .await;
1293        assert!(write.is_error);
1294        assert_eq!(
1295            write.error_type.as_deref(),
1296            Some("learning_foundry_read_only")
1297        );
1298        let search = registry
1299            .execute_with_auth("web_search", json!({}), &auth)
1300            .await;
1301        assert!(!search.is_error);
1302    }
1303
1304    #[tokio::test]
1305    async fn work_subagent_is_read_only_but_main_agent_can_write() {
1306        let make_registry = || ToolRegistry {
1307            config: crate::config::Config::test_defaults(),
1308            sandbox_mode: SandboxMode::Off,
1309            sandbox_runtime_available: false,
1310            cached_static_definitions: OnceLock::new(),
1311            audit_db: None,
1312            risk_overrides: std::collections::HashMap::new(),
1313            tools: vec![
1314                Box::new(DummyTool {
1315                    tool_name: "write_file".into(),
1316                }),
1317                Box::new(DummyTool {
1318                    tool_name: "read_file".into(),
1319                }),
1320            ],
1321        };
1322        let mut auth = ToolAuthContext {
1323            caller_channel: "code".into(),
1324            caller_chat_id: 1,
1325            principal: "subagent:run-1".into(),
1326            control_chat_ids: vec![],
1327            env_files: vec![],
1328        };
1329
1330        let denied = make_registry()
1331            .execute_with_auth("write_file", json!({}), &auth)
1332            .await;
1333        assert!(denied.is_error);
1334        assert_eq!(
1335            denied.error_type.as_deref(),
1336            Some("work_subagent_read_only")
1337        );
1338        let read = make_registry()
1339            .execute_with_auth("read_file", json!({}), &auth)
1340            .await;
1341        assert!(!read.is_error);
1342
1343        auth.principal = "main".into();
1344        let write = make_registry()
1345            .execute_with_auth("write_file", json!({}), &auth)
1346            .await;
1347        assert!(!write.is_error);
1348    }
1349
1350    #[tokio::test]
1351    async fn test_high_risk_tool_requires_explicit_approval_on_web() {
1352        let registry = ToolRegistry {
1353            config: crate::config::Config::test_defaults(),
1354            sandbox_mode: SandboxMode::Off,
1355            sandbox_runtime_available: false,
1356            cached_static_definitions: OnceLock::new(),
1357            audit_db: None,
1358            risk_overrides: std::collections::HashMap::new(),
1359            tools: vec![Box::new(DummyTool {
1360                tool_name: "bash".into(),
1361            })],
1362        };
1363        let auth = ToolAuthContext {
1364            caller_channel: "web".into(),
1365            caller_chat_id: 1,
1366            principal: "main".into(),
1367            control_chat_ids: vec![],
1368            env_files: vec![],
1369        };
1370
1371        let first = registry.execute_with_auth("bash", json!({}), &auth).await;
1372        assert!(first.is_error);
1373        assert_eq!(first.error_type.as_deref(), Some("approval_required"));
1374
1375        let second = registry.execute_with_auth("bash", json!({}), &auth).await;
1376        assert!(second.is_error);
1377        assert_eq!(second.error_type.as_deref(), Some("approval_required"));
1378
1379        let approved = registry
1380            .execute_with_auth(
1381                "bash",
1382                json!({"__microclaw_high_risk_approved": true}),
1383                &auth,
1384            )
1385            .await;
1386        assert!(!approved.is_error);
1387        assert_eq!(approved.content, "ok");
1388    }
1389
1390    #[tokio::test]
1391    async fn test_high_risk_tool_requires_explicit_approval_on_control_chat() {
1392        let registry = ToolRegistry {
1393            config: crate::config::Config::test_defaults(),
1394            sandbox_mode: SandboxMode::Off,
1395            sandbox_runtime_available: false,
1396            cached_static_definitions: OnceLock::new(),
1397            audit_db: None,
1398            risk_overrides: std::collections::HashMap::new(),
1399            tools: vec![Box::new(DummyTool {
1400                tool_name: "bash".into(),
1401            })],
1402        };
1403        let auth = ToolAuthContext {
1404            caller_channel: "telegram".into(),
1405            caller_chat_id: 123,
1406            principal: "main".into(),
1407            control_chat_ids: vec![123],
1408            env_files: vec![],
1409        };
1410
1411        let first = registry.execute_with_auth("bash", json!({}), &auth).await;
1412        assert!(first.is_error);
1413        assert_eq!(first.error_type.as_deref(), Some("approval_required"));
1414
1415        let approved = registry
1416            .execute_with_auth(
1417                "bash",
1418                json!({"__microclaw_high_risk_approved": true}),
1419                &auth,
1420            )
1421            .await;
1422        assert!(!approved.is_error);
1423        assert_eq!(approved.content, "ok");
1424    }
1425
1426    #[tokio::test]
1427    async fn test_high_risk_tool_confirmation_flag_false_hard_disables_web_approval_gate() {
1428        let mut config = crate::config::Config::test_defaults();
1429        config.high_risk_tool_user_confirmation_required = false;
1430        let registry = ToolRegistry {
1431            config,
1432            sandbox_mode: SandboxMode::Off,
1433            sandbox_runtime_available: false,
1434            cached_static_definitions: OnceLock::new(),
1435            audit_db: None,
1436            risk_overrides: std::collections::HashMap::new(),
1437            tools: vec![Box::new(DummyTool {
1438                tool_name: "bash".into(),
1439            })],
1440        };
1441        let auth = ToolAuthContext {
1442            caller_channel: "web".into(),
1443            caller_chat_id: 1,
1444            principal: "main".into(),
1445            control_chat_ids: vec![],
1446            env_files: vec![],
1447        };
1448
1449        let result = registry.execute_with_auth("bash", json!({}), &auth).await;
1450        assert!(!result.is_error);
1451        assert_eq!(result.content, "ok");
1452    }
1453
1454    #[tokio::test]
1455    async fn test_high_risk_tool_confirmation_flag_false_hard_disables_control_chat_approval_gate()
1456    {
1457        let mut config = crate::config::Config::test_defaults();
1458        config.high_risk_tool_user_confirmation_required = false;
1459        let registry = ToolRegistry {
1460            config,
1461            sandbox_mode: SandboxMode::Off,
1462            sandbox_runtime_available: false,
1463            cached_static_definitions: OnceLock::new(),
1464            audit_db: None,
1465            risk_overrides: std::collections::HashMap::new(),
1466            tools: vec![Box::new(DummyTool {
1467                tool_name: "bash".into(),
1468            })],
1469        };
1470        let auth = ToolAuthContext {
1471            caller_channel: "telegram".into(),
1472            caller_chat_id: 123,
1473            principal: "main".into(),
1474            control_chat_ids: vec![123],
1475            env_files: vec![],
1476        };
1477
1478        let result = registry.execute_with_auth("bash", json!({}), &auth).await;
1479        assert!(!result.is_error);
1480        assert_eq!(result.content, "ok");
1481    }
1482
1483    #[tokio::test]
1484    async fn test_medium_risk_tool_no_second_approval() {
1485        let registry = ToolRegistry {
1486            config: crate::config::Config::test_defaults(),
1487            sandbox_mode: SandboxMode::Off,
1488            sandbox_runtime_available: false,
1489            cached_static_definitions: OnceLock::new(),
1490            audit_db: None,
1491            risk_overrides: std::collections::HashMap::new(),
1492            tools: vec![Box::new(DummyTool {
1493                tool_name: "write_file".into(),
1494            })],
1495        };
1496        let auth = ToolAuthContext {
1497            caller_channel: "web".into(),
1498            caller_chat_id: 1,
1499            principal: "main".into(),
1500            control_chat_ids: vec![],
1501            env_files: vec![],
1502        };
1503
1504        let result = registry
1505            .execute_with_auth("write_file", json!({}), &auth)
1506            .await;
1507        assert!(!result.is_error);
1508        assert_eq!(result.content, "ok");
1509    }
1510
1511    #[tokio::test]
1512    async fn test_dynamic_plugin_tool_executes_without_restart() {
1513        let root = std::env::temp_dir().join(format!("microclaw_plugin_{}", uuid::Uuid::new_v4()));
1514        let plugins_dir = root.join("plugins");
1515        std::fs::create_dir_all(&plugins_dir).unwrap();
1516        let manifest = plugins_dir.join("demo.yaml");
1517        std::fs::write(
1518            &manifest,
1519            r#"
1520name: demo
1521enabled: true
1522tools:
1523  - name: plugin_runtime_echo
1524    description: runtime echo
1525    input_schema:
1526      type: object
1527      properties: {}
1528      required: []
1529    run:
1530      command: "echo plugin-ok"
1531      timeout_secs: 5
1532"#,
1533        )
1534        .unwrap();
1535
1536        let mut config = crate::config::Config::test_defaults();
1537        config.working_dir = root.join("work").to_string_lossy().to_string();
1538        config.plugins.enabled = true;
1539        config.plugins.dir = Some(plugins_dir.to_string_lossy().to_string());
1540
1541        let registry = ToolRegistry {
1542            config,
1543            tools: vec![],
1544            sandbox_mode: SandboxMode::Off,
1545            sandbox_runtime_available: false,
1546            cached_static_definitions: OnceLock::new(),
1547            audit_db: None,
1548            risk_overrides: std::collections::HashMap::new(),
1549        };
1550        let auth = ToolAuthContext {
1551            caller_channel: "web".into(),
1552            caller_chat_id: 7,
1553            principal: "main".into(),
1554            control_chat_ids: vec![],
1555            env_files: vec![],
1556        };
1557
1558        let defs = registry.definitions();
1559        assert!(defs.iter().any(|d| d.name == "plugin_runtime_echo"));
1560
1561        let result = registry
1562            .execute_with_auth("plugin_runtime_echo", json!({}), &auth)
1563            .await;
1564        assert!(!result.is_error, "{}", result.content);
1565        assert!(result.content.contains("plugin-ok"));
1566
1567        let _ = std::fs::remove_dir_all(root);
1568    }
1569
1570    #[test]
1571    fn test_definitions_for_hides_policy_blocked_tools() {
1572        let mut config = crate::config::Config::test_defaults();
1573        config.tool_policy.mode = crate::tool_guardrails::ToolPolicyMode::Block;
1574        config.tool_policy.allow_tools = vec!["read_*".to_string()];
1575        let tools: Vec<Box<dyn Tool>> = ["read_file", "bash", "write_file"]
1576            .into_iter()
1577            .map(|name| {
1578                Box::new(CaptureInputTool {
1579                    tool_name: name.to_string(),
1580                }) as Box<dyn Tool>
1581            })
1582            .collect();
1583        let registry = ToolRegistry {
1584            config,
1585            sandbox_mode: SandboxMode::Off,
1586            sandbox_runtime_available: false,
1587            cached_static_definitions: OnceLock::new(),
1588            audit_db: None,
1589            risk_overrides: std::collections::HashMap::new(),
1590            tools,
1591        };
1592        let auth = ToolAuthContext {
1593            caller_channel: "telegram".into(),
1594            caller_chat_id: 1,
1595            principal: "main".into(),
1596            control_chat_ids: vec![],
1597            env_files: vec![],
1598        };
1599
1600        // The full catalog is untouched; the policy-aware view drops what
1601        // the choke point would block.
1602        assert_eq!(registry.definitions().len(), 3);
1603        let visible: Vec<String> = registry
1604            .definitions_for(&auth)
1605            .into_iter()
1606            .map(|d| d.name)
1607            .collect();
1608        assert_eq!(visible, vec!["read_file".to_string()]);
1609
1610        // Warn mode keeps every tool visible (the call runs, audited).
1611        let mut warn_registry = registry;
1612        warn_registry.config.tool_policy.mode = crate::tool_guardrails::ToolPolicyMode::Warn;
1613        assert_eq!(warn_registry.definitions_for(&auth).len(), 3);
1614    }
1615
1616    #[tokio::test]
1617    async fn test_allow_list_blocks_unlisted_tool_at_choke_point() {
1618        // The regression behind the 0.11.1 advisory: `allow_tools` alone used
1619        // to restrict nothing. Now an unlisted tool is blocked before it runs.
1620        let mut config = crate::config::Config::test_defaults();
1621        config.tool_policy.mode = crate::tool_guardrails::ToolPolicyMode::Block;
1622        config.tool_policy.allow_tools = vec!["read_file".to_string()];
1623        let registry = ToolRegistry {
1624            config,
1625            sandbox_mode: SandboxMode::Off,
1626            sandbox_runtime_available: false,
1627            cached_static_definitions: OnceLock::new(),
1628            audit_db: None,
1629            risk_overrides: std::collections::HashMap::new(),
1630            tools: vec![
1631                Box::new(CaptureInputTool {
1632                    tool_name: "write_file".into(),
1633                }),
1634                Box::new(CaptureInputTool {
1635                    tool_name: "read_file".into(),
1636                }),
1637            ],
1638        };
1639        let auth = ToolAuthContext {
1640            caller_channel: "telegram".into(),
1641            caller_chat_id: 1,
1642            principal: "main".into(),
1643            control_chat_ids: vec![],
1644            env_files: vec![],
1645        };
1646        let blocked = registry
1647            .execute_with_auth("write_file", json!({}), &auth)
1648            .await;
1649        assert!(blocked.is_error);
1650        assert_eq!(blocked.error_type.as_deref(), Some("tool_policy_blocked"));
1651        assert!(blocked.content.contains("not in tool_policy.allow_tools"));
1652
1653        let allowed = registry
1654            .execute_with_auth("read_file", json!({}), &auth)
1655            .await;
1656        assert!(!allowed.is_error, "{}", allowed.content);
1657    }
1658
1659    #[tokio::test]
1660    async fn test_injects_default_chat_id_for_memory_tools() {
1661        let registry = ToolRegistry {
1662            config: crate::config::Config::test_defaults(),
1663            sandbox_mode: SandboxMode::Off,
1664            sandbox_runtime_available: false,
1665            cached_static_definitions: OnceLock::new(),
1666            audit_db: None,
1667            risk_overrides: std::collections::HashMap::new(),
1668            tools: vec![Box::new(CaptureInputTool {
1669                tool_name: "write_memory".into(),
1670            })],
1671        };
1672        let auth = ToolAuthContext {
1673            caller_channel: "feishu".into(),
1674            caller_chat_id: 8009499081,
1675            principal: "main".into(),
1676            control_chat_ids: vec![],
1677            env_files: vec![],
1678        };
1679
1680        let result = registry
1681            .execute_with_auth(
1682                "write_memory",
1683                json!({"scope":"chat","content":"hello"}),
1684                &auth,
1685            )
1686            .await;
1687        assert!(!result.is_error);
1688        let payload: serde_json::Value = serde_json::from_str(&result.content).unwrap();
1689        assert_eq!(payload["chat_id"].as_i64(), Some(8009499081));
1690    }
1691
1692    #[tokio::test]
1693    async fn test_does_not_override_existing_chat_id() {
1694        let registry = ToolRegistry {
1695            config: crate::config::Config::test_defaults(),
1696            sandbox_mode: SandboxMode::Off,
1697            sandbox_runtime_available: false,
1698            cached_static_definitions: OnceLock::new(),
1699            audit_db: None,
1700            risk_overrides: std::collections::HashMap::new(),
1701            tools: vec![Box::new(CaptureInputTool {
1702                tool_name: "write_memory".into(),
1703            })],
1704        };
1705        let auth = ToolAuthContext {
1706            caller_channel: "feishu".into(),
1707            caller_chat_id: 8009499081,
1708            principal: "main".into(),
1709            control_chat_ids: vec![],
1710            env_files: vec![],
1711        };
1712
1713        let result = registry
1714            .execute_with_auth(
1715                "write_memory",
1716                json!({"scope":"chat","chat_id":42,"content":"hello"}),
1717                &auth,
1718            )
1719            .await;
1720        assert!(!result.is_error);
1721        let payload: serde_json::Value = serde_json::from_str(&result.content).unwrap();
1722        assert_eq!(payload["chat_id"].as_i64(), Some(42));
1723    }
1724
1725    #[tokio::test]
1726    async fn test_injects_default_chat_id_for_send_message_tool() {
1727        let registry = ToolRegistry {
1728            config: crate::config::Config::test_defaults(),
1729            sandbox_mode: SandboxMode::Off,
1730            sandbox_runtime_available: false,
1731            cached_static_definitions: OnceLock::new(),
1732            audit_db: None,
1733            risk_overrides: std::collections::HashMap::new(),
1734            tools: vec![Box::new(CaptureInputTool {
1735                tool_name: "send_message".into(),
1736            })],
1737        };
1738        let auth = ToolAuthContext {
1739            caller_channel: "web".into(),
1740            caller_chat_id: 9001,
1741            principal: "main".into(),
1742            control_chat_ids: vec![],
1743            env_files: vec![],
1744        };
1745
1746        let result = registry
1747            .execute_with_auth("send_message", json!({"text":"progress update"}), &auth)
1748            .await;
1749        assert!(!result.is_error);
1750        let payload: serde_json::Value = serde_json::from_str(&result.content).unwrap();
1751        assert_eq!(payload["chat_id"].as_i64(), Some(9001));
1752        assert_eq!(payload["text"].as_str(), Some("progress update"));
1753    }
1754}