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