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        // Embedder gate (permission rules, user hooks). Runs after the
956        // operator policies above, so it can only tighten them.
957        let gate = self.config.tool_gate.get().cloned();
958        let gate_input = crate::tool_gate::public_input(&input);
959        if let Some(gate) = &gate {
960            let approved = input
961                .get(crate::internal::tool_runtime::runtime::HIGH_RISK_APPROVED_KEY)
962                .and_then(|v| v.as_bool())
963                .unwrap_or(false);
964            let call = crate::tool_gate::ToolGateCall {
965                tool: name,
966                input: &gate_input,
967                caller_channel: &auth.caller_channel,
968                principal: &auth.principal,
969                chat_id: auth.caller_chat_id,
970                approved,
971            };
972            let outcome = gate.before(&call).await;
973            if let Some(updated) = outcome.updated_input {
974                input = crate::tool_gate::merge_internal_keys(&input, updated);
975            }
976            match outcome.decision {
977                crate::tool_gate::ToolGateDecision::Allow => {}
978                crate::tool_gate::ToolGateDecision::Approve { rule } => {
979                    tracing::info!(
980                        tool = name,
981                        ?rule,
982                        "Tool call approved by the embedder gate"
983                    );
984                    if let serde_json::Value::Object(map) = &mut input {
985                        map.insert(
986                            crate::internal::tool_runtime::runtime::HIGH_RISK_APPROVED_KEY
987                                .to_string(),
988                            serde_json::Value::Bool(true),
989                        );
990                    }
991                }
992                crate::tool_gate::ToolGateDecision::Ask { reason } => {
993                    if !approved && self.config.high_risk_tool_user_confirmation_required {
994                        let why = reason.map(|r| format!(" ({r})")).unwrap_or_default();
995                        return ToolResult::error(format!(
996                            "Approval required for '{name}' by a permission rule{why}."
997                        ))
998                        .with_error_type("approval_required");
999                    }
1000                }
1001                crate::tool_gate::ToolGateDecision::Deny { reason } => {
1002                    tracing::info!(tool = name, %reason, "Tool call denied by the embedder gate");
1003                    return ToolResult::error(format!(
1004                        "Tool call blocked: {reason}. Do not retry it unchanged; \
1005                         use another approach or explain the limitation to the user."
1006                    ))
1007                    .with_error_type("tool_gate_denied");
1008                }
1009            }
1010        }
1011        if self.config.high_risk_tool_user_confirmation_required {
1012            // Only tools that can actually pause for approval need the
1013            // standing-grant lookup: High-risk tools (registry gate) plus the
1014            // tools with their own in-tool gates (`a2a_send` sandboxed peer;
1015            // `bash` is already High-risk). Everything else skips the DB read
1016            // on the hot path.
1017            let gateable = effective_risk == ToolRisk::High || name == "a2a_send";
1018            if gateable {
1019                // A standing per-chat allowance (operator replied "always
1020                // allow" to a previous prompt) satisfies the gate. It never
1021                // bypasses tool_policy or egress policy, which already ran
1022                // above. When present, inject the approval marker so the
1023                // in-tool gates (bash dangerous patterns, sandboxed a2a
1024                // peers) honor it too instead of re-prompting every call.
1025                let standing = if let Some(db) = self.audit_db.clone() {
1026                    let key = format!("approved_tool:{}:{}", auth.caller_chat_id, name);
1027                    crate::internal::storage::db::call_blocking(db, move |db| {
1028                        db.get_runtime_meta(&key)
1029                    })
1030                    .await
1031                    .ok()
1032                    .flatten()
1033                    .is_some()
1034                } else {
1035                    false
1036                };
1037                if standing {
1038                    tracing::info!(
1039                        tool = name,
1040                        chat_id = auth.caller_chat_id,
1041                        "High-risk tool allowed by standing per-chat approval"
1042                    );
1043                    if let serde_json::Value::Object(map) = &mut input {
1044                        map.insert(
1045                            "__microclaw_high_risk_approved".to_string(),
1046                            serde_json::Value::Bool(true),
1047                        );
1048                    }
1049                } else if let Some(blocked) =
1050                    crate::internal::tool_runtime::runtime::require_high_risk_approval_with_policy(
1051                        &crate::internal::tool_runtime::runtime::ApprovalPolicy::new(
1052                            self.config.approval_channels.iter().cloned(),
1053                        ),
1054                        name,
1055                        effective_risk,
1056                        auth,
1057                        &input,
1058                    )
1059                {
1060                    return blocked;
1061                }
1062            }
1063        }
1064
1065        tracing::debug!(
1066            tool = name,
1067            risk = effective_risk.as_str(),
1068            execution_policy = tool_execution_policy(name).as_str(),
1069            sandbox_mode = ?self.sandbox_mode,
1070            sandbox_runtime_available = self.sandbox_runtime_available,
1071            "tool execution policy evaluated"
1072        );
1073        let input = Self::inject_default_chat_id_if_missing(name, input, auth);
1074        let input = inject_auth_context(input, auth);
1075        let mut result = self.execute(name, input.clone()).await;
1076        if result.error_type.as_deref() == Some("unknown_tool") {
1077            if let Some(dynamic) =
1078                crate::plugins::execute_dynamic_plugin_tool(&self.config, name, input).await
1079            {
1080                result = dynamic;
1081            }
1082        }
1083        if let Some(gate) = &gate {
1084            let call = crate::tool_gate::ToolGateCall {
1085                tool: name,
1086                input: &gate_input,
1087                caller_channel: &auth.caller_channel,
1088                principal: &auth.principal,
1089                chat_id: auth.caller_chat_id,
1090                approved: true,
1091            };
1092            let seen = crate::tool_gate::ToolGateResult {
1093                content: &result.content,
1094                is_error: result.is_error,
1095                error_type: result.error_type.as_deref(),
1096            };
1097            if let Some(extra) = gate.after(&call, &seen).await {
1098                if !extra.trim().is_empty() {
1099                    result.content = format!("{}\n\n{}", result.content.trim_end(), extra.trim());
1100                }
1101            }
1102        }
1103        result
1104    }
1105}
1106
1107#[cfg(test)]
1108mod tests {
1109    use super::*;
1110    use crate::config::WorkingDirIsolation;
1111    use async_trait::async_trait;
1112    use serde_json::json;
1113
1114    #[test]
1115    fn test_tool_result_success() {
1116        let r = ToolResult::success("ok".into());
1117        assert_eq!(r.content, "ok");
1118        assert!(!r.is_error);
1119    }
1120
1121    #[test]
1122    fn test_tool_result_error() {
1123        let r = ToolResult::error("fail".into());
1124        assert_eq!(r.content, "fail");
1125        assert!(r.is_error);
1126    }
1127
1128    #[test]
1129    fn test_schema_object() {
1130        let schema = schema_object(
1131            json!({
1132                "name": {"type": "string"},
1133                "age": {"type": "integer"}
1134            }),
1135            &["name"],
1136        );
1137        assert_eq!(schema["type"], "object");
1138        assert!(schema["properties"]["name"].is_object());
1139        assert!(schema["properties"]["age"].is_object());
1140        let required = schema["required"].as_array().unwrap();
1141        assert_eq!(required.len(), 1);
1142        assert_eq!(required[0], "name");
1143    }
1144
1145    #[test]
1146    fn test_schema_object_empty_required() {
1147        let schema = schema_object(json!({}), &[]);
1148        let required = schema["required"].as_array().unwrap();
1149        assert!(required.is_empty());
1150    }
1151
1152    #[test]
1153    fn test_auth_context_from_input() {
1154        let input = json!({
1155            "__microclaw_auth": {
1156                "caller_channel": "telegram",
1157                "caller_chat_id": 123,
1158                "control_chat_ids": [123, 999]
1159            }
1160        });
1161        let auth = auth_context_from_input(&input).unwrap();
1162        assert_eq!(auth.caller_channel, "telegram");
1163        assert_eq!(auth.caller_chat_id, 123);
1164        assert!(auth.is_control_chat());
1165        assert!(auth.can_access_chat(456));
1166    }
1167
1168    #[test]
1169    fn test_authorize_chat_access_denied() {
1170        let input = json!({
1171            "__microclaw_auth": {
1172                "caller_channel": "telegram",
1173                "caller_chat_id": 100,
1174                "control_chat_ids": []
1175            }
1176        });
1177        let err = authorize_chat_access(&input, 200).unwrap_err();
1178        assert!(err.contains("Permission denied"));
1179    }
1180
1181    #[test]
1182    fn test_resolve_tool_working_dir_shared() {
1183        let dir = resolve_tool_working_dir(
1184            std::path::Path::new("/tmp/work"),
1185            WorkingDirIsolation::Shared,
1186            &json!({
1187                "__microclaw_auth": {
1188                    "caller_channel": "telegram",
1189                    "caller_chat_id": 123,
1190                    "control_chat_ids": []
1191                }
1192            }),
1193        );
1194        assert_eq!(dir, std::path::PathBuf::from("/tmp/work/shared"));
1195    }
1196
1197    #[test]
1198    fn test_resolve_tool_working_dir_direct() {
1199        let dir = resolve_tool_working_dir(
1200            std::path::Path::new("/tmp/work"),
1201            WorkingDirIsolation::Direct,
1202            &json!({
1203                "__microclaw_auth": {
1204                    "caller_channel": "headless",
1205                    "caller_chat_id": 123,
1206                    "control_chat_ids": []
1207                }
1208            }),
1209        );
1210        assert_eq!(dir, std::path::PathBuf::from("/tmp/work"));
1211    }
1212
1213    #[test]
1214    fn test_resolve_tool_working_dir_chat() {
1215        let dir = resolve_tool_working_dir(
1216            std::path::Path::new("/tmp/work"),
1217            WorkingDirIsolation::Chat,
1218            &json!({
1219                "__microclaw_auth": {
1220                    "caller_channel": "discord",
1221                    "caller_chat_id": -100123,
1222                    "control_chat_ids": []
1223                }
1224            }),
1225        );
1226        assert_eq!(
1227            dir,
1228            std::path::PathBuf::from("/tmp/work/chat/discord/neg100123")
1229        );
1230    }
1231
1232    struct DummyTool {
1233        tool_name: String,
1234    }
1235
1236    #[async_trait]
1237    impl Tool for DummyTool {
1238        fn name(&self) -> &str {
1239            &self.tool_name
1240        }
1241
1242        fn definition(&self) -> ToolDefinition {
1243            ToolDefinition {
1244                name: self.tool_name.clone(),
1245                description: "dummy".into(),
1246                input_schema: schema_object(json!({}), &[]),
1247            }
1248        }
1249
1250        async fn execute(&self, _input: serde_json::Value) -> ToolResult {
1251            ToolResult::success("ok".into())
1252        }
1253    }
1254
1255    struct CaptureInputTool {
1256        tool_name: String,
1257    }
1258
1259    #[async_trait]
1260    impl Tool for CaptureInputTool {
1261        fn name(&self) -> &str {
1262            &self.tool_name
1263        }
1264
1265        fn definition(&self) -> ToolDefinition {
1266            ToolDefinition {
1267                name: self.tool_name.clone(),
1268                description: "capture".into(),
1269                input_schema: schema_object(json!({}), &[]),
1270            }
1271        }
1272
1273        async fn execute(&self, input: serde_json::Value) -> ToolResult {
1274            ToolResult::success(input.to_string())
1275        }
1276    }
1277
1278    #[test]
1279    fn test_tool_risk_levels() {
1280        assert_eq!(tool_risk("bash"), ToolRisk::High);
1281        assert_eq!(tool_risk("write_file"), ToolRisk::Medium);
1282        assert_eq!(tool_risk("pause_scheduled_task"), ToolRisk::Medium);
1283        assert_eq!(tool_risk("sync_skills"), ToolRisk::Medium);
1284        assert_eq!(tool_risk("read_file"), ToolRisk::Low);
1285    }
1286
1287    #[tokio::test]
1288    async fn test_tool_policy_blocks_at_choke_point() {
1289        // Policy enforcement lives in execute_with_auth so EVERY caller —
1290        // main loop, sub-agent loops — is covered. Denied tools return a
1291        // typed error before any execution-policy/approval logic runs.
1292        let mut config = crate::config::Config::test_defaults();
1293        config.tool_policy.mode = crate::tool_guardrails::ToolPolicyMode::Block;
1294        config.tool_policy.deny_tools = vec!["bash".to_string()];
1295        let registry = ToolRegistry {
1296            config,
1297            sandbox_mode: SandboxMode::Off,
1298            sandbox_runtime_available: false,
1299            cached_static_definitions: OnceLock::new(),
1300            audit_db: None,
1301            risk_overrides: std::collections::HashMap::new(),
1302            tools: vec![Box::new(DummyTool {
1303                tool_name: "bash".into(),
1304            })],
1305        };
1306        let auth = ToolAuthContext {
1307            caller_channel: "telegram".into(),
1308            caller_chat_id: 1,
1309            principal: "main".into(),
1310            control_chat_ids: vec![],
1311            env_files: vec![],
1312        };
1313        let result = registry.execute_with_auth("bash", json!({}), &auth).await;
1314        assert!(result.is_error);
1315        assert_eq!(result.error_type.as_deref(), Some("tool_policy_blocked"));
1316
1317        // Warn mode executes the tool (DummyTool returns success).
1318        let mut warn_config = crate::config::Config::test_defaults();
1319        warn_config.tool_policy.mode = crate::tool_guardrails::ToolPolicyMode::Warn;
1320        warn_config.tool_policy.deny_tools = vec!["bash".to_string()];
1321        warn_config.high_risk_tool_user_confirmation_required = false;
1322        let registry = ToolRegistry {
1323            config: warn_config,
1324            sandbox_mode: SandboxMode::Off,
1325            sandbox_runtime_available: false,
1326            cached_static_definitions: OnceLock::new(),
1327            audit_db: None,
1328            risk_overrides: std::collections::HashMap::new(),
1329            tools: vec![Box::new(DummyTool {
1330                tool_name: "bash".into(),
1331            })],
1332        };
1333        let result = registry.execute_with_auth("bash", json!({}), &auth).await;
1334        assert!(
1335            !result.is_error,
1336            "warn mode must still execute: {}",
1337            result.content
1338        );
1339    }
1340
1341    #[tokio::test]
1342    async fn learning_foundry_principal_is_read_only_at_choke_point() {
1343        let registry = ToolRegistry {
1344            config: crate::config::Config::test_defaults(),
1345            sandbox_mode: SandboxMode::Off,
1346            sandbox_runtime_available: false,
1347            cached_static_definitions: OnceLock::new(),
1348            audit_db: None,
1349            risk_overrides: std::collections::HashMap::new(),
1350            tools: vec![
1351                Box::new(DummyTool {
1352                    tool_name: "write_file".into(),
1353                }),
1354                Box::new(DummyTool {
1355                    tool_name: "web_search".into(),
1356                }),
1357            ],
1358        };
1359        let auth = ToolAuthContext {
1360            caller_channel: "learning_foundry".into(),
1361            caller_chat_id: -7,
1362            principal: "learning_foundry".into(),
1363            control_chat_ids: vec![],
1364            env_files: vec![],
1365        };
1366        let write = registry
1367            .execute_with_auth("write_file", json!({}), &auth)
1368            .await;
1369        assert!(write.is_error);
1370        assert_eq!(
1371            write.error_type.as_deref(),
1372            Some("learning_foundry_read_only")
1373        );
1374        let search = registry
1375            .execute_with_auth("web_search", json!({}), &auth)
1376            .await;
1377        assert!(!search.is_error);
1378    }
1379
1380    #[tokio::test]
1381    async fn work_subagent_is_read_only_but_main_agent_can_write() {
1382        let make_registry = || ToolRegistry {
1383            config: crate::config::Config::test_defaults(),
1384            sandbox_mode: SandboxMode::Off,
1385            sandbox_runtime_available: false,
1386            cached_static_definitions: OnceLock::new(),
1387            audit_db: None,
1388            risk_overrides: std::collections::HashMap::new(),
1389            tools: vec![
1390                Box::new(DummyTool {
1391                    tool_name: "write_file".into(),
1392                }),
1393                Box::new(DummyTool {
1394                    tool_name: "read_file".into(),
1395                }),
1396            ],
1397        };
1398        let mut auth = ToolAuthContext {
1399            caller_channel: "code".into(),
1400            caller_chat_id: 1,
1401            principal: "subagent:run-1".into(),
1402            control_chat_ids: vec![],
1403            env_files: vec![],
1404        };
1405
1406        let denied = make_registry()
1407            .execute_with_auth("write_file", json!({}), &auth)
1408            .await;
1409        assert!(denied.is_error);
1410        assert_eq!(
1411            denied.error_type.as_deref(),
1412            Some("work_subagent_read_only")
1413        );
1414        let read = make_registry()
1415            .execute_with_auth("read_file", json!({}), &auth)
1416            .await;
1417        assert!(!read.is_error);
1418
1419        auth.principal = "main".into();
1420        let write = make_registry()
1421            .execute_with_auth("write_file", json!({}), &auth)
1422            .await;
1423        assert!(!write.is_error);
1424    }
1425
1426    #[tokio::test]
1427    async fn test_high_risk_tool_requires_explicit_approval_on_web() {
1428        let registry = ToolRegistry {
1429            config: crate::config::Config::test_defaults(),
1430            sandbox_mode: SandboxMode::Off,
1431            sandbox_runtime_available: false,
1432            cached_static_definitions: OnceLock::new(),
1433            audit_db: None,
1434            risk_overrides: std::collections::HashMap::new(),
1435            tools: vec![Box::new(DummyTool {
1436                tool_name: "bash".into(),
1437            })],
1438        };
1439        let auth = ToolAuthContext {
1440            caller_channel: "web".into(),
1441            caller_chat_id: 1,
1442            principal: "main".into(),
1443            control_chat_ids: vec![],
1444            env_files: vec![],
1445        };
1446
1447        let first = registry.execute_with_auth("bash", json!({}), &auth).await;
1448        assert!(first.is_error);
1449        assert_eq!(first.error_type.as_deref(), Some("approval_required"));
1450
1451        let second = registry.execute_with_auth("bash", json!({}), &auth).await;
1452        assert!(second.is_error);
1453        assert_eq!(second.error_type.as_deref(), Some("approval_required"));
1454
1455        let approved = registry
1456            .execute_with_auth(
1457                "bash",
1458                json!({"__microclaw_high_risk_approved": true}),
1459                &auth,
1460            )
1461            .await;
1462        assert!(!approved.is_error);
1463        assert_eq!(approved.content, "ok");
1464    }
1465
1466    #[tokio::test]
1467    async fn test_high_risk_tool_requires_explicit_approval_on_control_chat() {
1468        let registry = ToolRegistry {
1469            config: crate::config::Config::test_defaults(),
1470            sandbox_mode: SandboxMode::Off,
1471            sandbox_runtime_available: false,
1472            cached_static_definitions: OnceLock::new(),
1473            audit_db: None,
1474            risk_overrides: std::collections::HashMap::new(),
1475            tools: vec![Box::new(DummyTool {
1476                tool_name: "bash".into(),
1477            })],
1478        };
1479        let auth = ToolAuthContext {
1480            caller_channel: "telegram".into(),
1481            caller_chat_id: 123,
1482            principal: "main".into(),
1483            control_chat_ids: vec![123],
1484            env_files: vec![],
1485        };
1486
1487        let first = registry.execute_with_auth("bash", json!({}), &auth).await;
1488        assert!(first.is_error);
1489        assert_eq!(first.error_type.as_deref(), Some("approval_required"));
1490
1491        let approved = registry
1492            .execute_with_auth(
1493                "bash",
1494                json!({"__microclaw_high_risk_approved": true}),
1495                &auth,
1496            )
1497            .await;
1498        assert!(!approved.is_error);
1499        assert_eq!(approved.content, "ok");
1500    }
1501
1502    #[tokio::test]
1503    async fn test_high_risk_tool_confirmation_flag_false_hard_disables_web_approval_gate() {
1504        let mut config = crate::config::Config::test_defaults();
1505        config.high_risk_tool_user_confirmation_required = false;
1506        let registry = ToolRegistry {
1507            config,
1508            sandbox_mode: SandboxMode::Off,
1509            sandbox_runtime_available: false,
1510            cached_static_definitions: OnceLock::new(),
1511            audit_db: None,
1512            risk_overrides: std::collections::HashMap::new(),
1513            tools: vec![Box::new(DummyTool {
1514                tool_name: "bash".into(),
1515            })],
1516        };
1517        let auth = ToolAuthContext {
1518            caller_channel: "web".into(),
1519            caller_chat_id: 1,
1520            principal: "main".into(),
1521            control_chat_ids: vec![],
1522            env_files: vec![],
1523        };
1524
1525        let result = registry.execute_with_auth("bash", json!({}), &auth).await;
1526        assert!(!result.is_error);
1527        assert_eq!(result.content, "ok");
1528    }
1529
1530    #[tokio::test]
1531    async fn test_high_risk_tool_confirmation_flag_false_hard_disables_control_chat_approval_gate()
1532    {
1533        let mut config = crate::config::Config::test_defaults();
1534        config.high_risk_tool_user_confirmation_required = false;
1535        let registry = ToolRegistry {
1536            config,
1537            sandbox_mode: SandboxMode::Off,
1538            sandbox_runtime_available: false,
1539            cached_static_definitions: OnceLock::new(),
1540            audit_db: None,
1541            risk_overrides: std::collections::HashMap::new(),
1542            tools: vec![Box::new(DummyTool {
1543                tool_name: "bash".into(),
1544            })],
1545        };
1546        let auth = ToolAuthContext {
1547            caller_channel: "telegram".into(),
1548            caller_chat_id: 123,
1549            principal: "main".into(),
1550            control_chat_ids: vec![123],
1551            env_files: vec![],
1552        };
1553
1554        let result = registry.execute_with_auth("bash", json!({}), &auth).await;
1555        assert!(!result.is_error);
1556        assert_eq!(result.content, "ok");
1557    }
1558
1559    #[tokio::test]
1560    async fn test_medium_risk_tool_no_second_approval() {
1561        let registry = ToolRegistry {
1562            config: crate::config::Config::test_defaults(),
1563            sandbox_mode: SandboxMode::Off,
1564            sandbox_runtime_available: false,
1565            cached_static_definitions: OnceLock::new(),
1566            audit_db: None,
1567            risk_overrides: std::collections::HashMap::new(),
1568            tools: vec![Box::new(DummyTool {
1569                tool_name: "write_file".into(),
1570            })],
1571        };
1572        let auth = ToolAuthContext {
1573            caller_channel: "web".into(),
1574            caller_chat_id: 1,
1575            principal: "main".into(),
1576            control_chat_ids: vec![],
1577            env_files: vec![],
1578        };
1579
1580        let result = registry
1581            .execute_with_auth("write_file", json!({}), &auth)
1582            .await;
1583        assert!(!result.is_error);
1584        assert_eq!(result.content, "ok");
1585    }
1586
1587    #[tokio::test]
1588    async fn test_dynamic_plugin_tool_executes_without_restart() {
1589        let root = std::env::temp_dir().join(format!("microclaw_plugin_{}", uuid::Uuid::new_v4()));
1590        let plugins_dir = root.join("plugins");
1591        std::fs::create_dir_all(&plugins_dir).unwrap();
1592        let manifest = plugins_dir.join("demo.yaml");
1593        std::fs::write(
1594            &manifest,
1595            r#"
1596name: demo
1597enabled: true
1598tools:
1599  - name: plugin_runtime_echo
1600    description: runtime echo
1601    input_schema:
1602      type: object
1603      properties: {}
1604      required: []
1605    run:
1606      command: "echo plugin-ok"
1607      timeout_secs: 5
1608"#,
1609        )
1610        .unwrap();
1611
1612        let mut config = crate::config::Config::test_defaults();
1613        config.working_dir = root.join("work").to_string_lossy().to_string();
1614        config.plugins.enabled = true;
1615        config.plugins.dir = Some(plugins_dir.to_string_lossy().to_string());
1616
1617        let registry = ToolRegistry {
1618            config,
1619            tools: vec![],
1620            sandbox_mode: SandboxMode::Off,
1621            sandbox_runtime_available: false,
1622            cached_static_definitions: OnceLock::new(),
1623            audit_db: None,
1624            risk_overrides: std::collections::HashMap::new(),
1625        };
1626        let auth = ToolAuthContext {
1627            caller_channel: "web".into(),
1628            caller_chat_id: 7,
1629            principal: "main".into(),
1630            control_chat_ids: vec![],
1631            env_files: vec![],
1632        };
1633
1634        let defs = registry.definitions();
1635        assert!(defs.iter().any(|d| d.name == "plugin_runtime_echo"));
1636
1637        let result = registry
1638            .execute_with_auth("plugin_runtime_echo", json!({}), &auth)
1639            .await;
1640        assert!(!result.is_error, "{}", result.content);
1641        assert!(result.content.contains("plugin-ok"));
1642
1643        let _ = std::fs::remove_dir_all(root);
1644    }
1645
1646    #[test]
1647    fn test_definitions_for_hides_policy_blocked_tools() {
1648        let mut config = crate::config::Config::test_defaults();
1649        config.tool_policy.mode = crate::tool_guardrails::ToolPolicyMode::Block;
1650        config.tool_policy.allow_tools = vec!["read_*".to_string()];
1651        let tools: Vec<Box<dyn Tool>> = ["read_file", "bash", "write_file"]
1652            .into_iter()
1653            .map(|name| {
1654                Box::new(CaptureInputTool {
1655                    tool_name: name.to_string(),
1656                }) as Box<dyn Tool>
1657            })
1658            .collect();
1659        let registry = ToolRegistry {
1660            config,
1661            sandbox_mode: SandboxMode::Off,
1662            sandbox_runtime_available: false,
1663            cached_static_definitions: OnceLock::new(),
1664            audit_db: None,
1665            risk_overrides: std::collections::HashMap::new(),
1666            tools,
1667        };
1668        let auth = ToolAuthContext {
1669            caller_channel: "telegram".into(),
1670            caller_chat_id: 1,
1671            principal: "main".into(),
1672            control_chat_ids: vec![],
1673            env_files: vec![],
1674        };
1675
1676        // The full catalog is untouched; the policy-aware view drops what
1677        // the choke point would block.
1678        assert_eq!(registry.definitions().len(), 3);
1679        let visible: Vec<String> = registry
1680            .definitions_for(&auth)
1681            .into_iter()
1682            .map(|d| d.name)
1683            .collect();
1684        assert_eq!(visible, vec!["read_file".to_string()]);
1685
1686        // Warn mode keeps every tool visible (the call runs, audited).
1687        let mut warn_registry = registry;
1688        warn_registry.config.tool_policy.mode = crate::tool_guardrails::ToolPolicyMode::Warn;
1689        assert_eq!(warn_registry.definitions_for(&auth).len(), 3);
1690    }
1691
1692    #[tokio::test]
1693    async fn test_allow_list_blocks_unlisted_tool_at_choke_point() {
1694        // The regression behind the 0.11.1 advisory: `allow_tools` alone used
1695        // to restrict nothing. Now an unlisted tool is blocked before it runs.
1696        let mut config = crate::config::Config::test_defaults();
1697        config.tool_policy.mode = crate::tool_guardrails::ToolPolicyMode::Block;
1698        config.tool_policy.allow_tools = vec!["read_file".to_string()];
1699        let registry = ToolRegistry {
1700            config,
1701            sandbox_mode: SandboxMode::Off,
1702            sandbox_runtime_available: false,
1703            cached_static_definitions: OnceLock::new(),
1704            audit_db: None,
1705            risk_overrides: std::collections::HashMap::new(),
1706            tools: vec![
1707                Box::new(CaptureInputTool {
1708                    tool_name: "write_file".into(),
1709                }),
1710                Box::new(CaptureInputTool {
1711                    tool_name: "read_file".into(),
1712                }),
1713            ],
1714        };
1715        let auth = ToolAuthContext {
1716            caller_channel: "telegram".into(),
1717            caller_chat_id: 1,
1718            principal: "main".into(),
1719            control_chat_ids: vec![],
1720            env_files: vec![],
1721        };
1722        let blocked = registry
1723            .execute_with_auth("write_file", json!({}), &auth)
1724            .await;
1725        assert!(blocked.is_error);
1726        assert_eq!(blocked.error_type.as_deref(), Some("tool_policy_blocked"));
1727        assert!(blocked.content.contains("not in tool_policy.allow_tools"));
1728
1729        let allowed = registry
1730            .execute_with_auth("read_file", json!({}), &auth)
1731            .await;
1732        assert!(!allowed.is_error, "{}", allowed.content);
1733    }
1734
1735    #[tokio::test]
1736    async fn test_injects_default_chat_id_for_memory_tools() {
1737        let registry = ToolRegistry {
1738            config: crate::config::Config::test_defaults(),
1739            sandbox_mode: SandboxMode::Off,
1740            sandbox_runtime_available: false,
1741            cached_static_definitions: OnceLock::new(),
1742            audit_db: None,
1743            risk_overrides: std::collections::HashMap::new(),
1744            tools: vec![Box::new(CaptureInputTool {
1745                tool_name: "write_memory".into(),
1746            })],
1747        };
1748        let auth = ToolAuthContext {
1749            caller_channel: "feishu".into(),
1750            caller_chat_id: 8009499081,
1751            principal: "main".into(),
1752            control_chat_ids: vec![],
1753            env_files: vec![],
1754        };
1755
1756        let result = registry
1757            .execute_with_auth(
1758                "write_memory",
1759                json!({"scope":"chat","content":"hello"}),
1760                &auth,
1761            )
1762            .await;
1763        assert!(!result.is_error);
1764        let payload: serde_json::Value = serde_json::from_str(&result.content).unwrap();
1765        assert_eq!(payload["chat_id"].as_i64(), Some(8009499081));
1766    }
1767
1768    #[tokio::test]
1769    async fn test_does_not_override_existing_chat_id() {
1770        let registry = ToolRegistry {
1771            config: crate::config::Config::test_defaults(),
1772            sandbox_mode: SandboxMode::Off,
1773            sandbox_runtime_available: false,
1774            cached_static_definitions: OnceLock::new(),
1775            audit_db: None,
1776            risk_overrides: std::collections::HashMap::new(),
1777            tools: vec![Box::new(CaptureInputTool {
1778                tool_name: "write_memory".into(),
1779            })],
1780        };
1781        let auth = ToolAuthContext {
1782            caller_channel: "feishu".into(),
1783            caller_chat_id: 8009499081,
1784            principal: "main".into(),
1785            control_chat_ids: vec![],
1786            env_files: vec![],
1787        };
1788
1789        let result = registry
1790            .execute_with_auth(
1791                "write_memory",
1792                json!({"scope":"chat","chat_id":42,"content":"hello"}),
1793                &auth,
1794            )
1795            .await;
1796        assert!(!result.is_error);
1797        let payload: serde_json::Value = serde_json::from_str(&result.content).unwrap();
1798        assert_eq!(payload["chat_id"].as_i64(), Some(42));
1799    }
1800
1801    #[tokio::test]
1802    async fn test_injects_default_chat_id_for_send_message_tool() {
1803        let registry = ToolRegistry {
1804            config: crate::config::Config::test_defaults(),
1805            sandbox_mode: SandboxMode::Off,
1806            sandbox_runtime_available: false,
1807            cached_static_definitions: OnceLock::new(),
1808            audit_db: None,
1809            risk_overrides: std::collections::HashMap::new(),
1810            tools: vec![Box::new(CaptureInputTool {
1811                tool_name: "send_message".into(),
1812            })],
1813        };
1814        let auth = ToolAuthContext {
1815            caller_channel: "web".into(),
1816            caller_chat_id: 9001,
1817            principal: "main".into(),
1818            control_chat_ids: vec![],
1819            env_files: vec![],
1820        };
1821
1822        let result = registry
1823            .execute_with_auth("send_message", json!({"text":"progress update"}), &auth)
1824            .await;
1825        assert!(!result.is_error);
1826        let payload: serde_json::Value = serde_json::from_str(&result.content).unwrap();
1827        assert_eq!(payload["chat_id"].as_i64(), Some(9001));
1828        assert_eq!(payload["text"].as_str(), Some("progress update"));
1829    }
1830
1831    struct FakeGate {
1832        outcome: crate::tool_gate::ToolGateOutcome,
1833        after: Option<String>,
1834        seen: std::sync::Mutex<Vec<(String, bool, serde_json::Value)>>,
1835    }
1836
1837    impl FakeGate {
1838        fn new(outcome: crate::tool_gate::ToolGateOutcome) -> Arc<Self> {
1839            Arc::new(Self {
1840                outcome,
1841                after: None,
1842                seen: std::sync::Mutex::new(Vec::new()),
1843            })
1844        }
1845    }
1846
1847    #[async_trait]
1848    impl crate::tool_gate::ToolGate for FakeGate {
1849        async fn before(
1850            &self,
1851            call: &crate::tool_gate::ToolGateCall<'_>,
1852        ) -> crate::tool_gate::ToolGateOutcome {
1853            self.seen.lock().unwrap().push((
1854                call.tool.to_string(),
1855                call.approved,
1856                call.input.clone(),
1857            ));
1858            self.outcome.clone()
1859        }
1860
1861        async fn after(
1862            &self,
1863            _call: &crate::tool_gate::ToolGateCall<'_>,
1864            _result: &crate::tool_gate::ToolGateResult<'_>,
1865        ) -> Option<String> {
1866            self.after.clone()
1867        }
1868    }
1869
1870    fn gated_registry(gate: Arc<FakeGate>, tool: Box<dyn Tool>) -> ToolRegistry {
1871        let mut config = crate::config::Config::test_defaults();
1872        config.tool_gate = crate::tool_gate::ToolGateHandle::new(gate);
1873        ToolRegistry {
1874            config,
1875            sandbox_mode: SandboxMode::Off,
1876            sandbox_runtime_available: false,
1877            cached_static_definitions: OnceLock::new(),
1878            audit_db: None,
1879            risk_overrides: std::collections::HashMap::new(),
1880            tools: vec![tool],
1881        }
1882    }
1883
1884    fn gate_auth() -> ToolAuthContext {
1885        ToolAuthContext {
1886            caller_channel: "code".into(),
1887            caller_chat_id: 7,
1888            principal: "main".into(),
1889            control_chat_ids: vec![],
1890            env_files: vec![],
1891        }
1892    }
1893
1894    #[tokio::test]
1895    async fn test_tool_gate_deny_blocks_the_call() {
1896        let gate = FakeGate::new(crate::tool_gate::ToolGateOutcome::with(
1897            crate::tool_gate::ToolGateDecision::Deny {
1898                reason: "denied by permission rule `read(**/.env)`".into(),
1899            },
1900        ));
1901        let registry = gated_registry(
1902            gate.clone(),
1903            Box::new(DummyTool {
1904                tool_name: "read_file".into(),
1905            }),
1906        );
1907        let result = registry
1908            .execute_with_auth("read_file", json!({"path": ".env"}), &gate_auth())
1909            .await;
1910        assert!(result.is_error);
1911        assert_eq!(result.error_type.as_deref(), Some("tool_gate_denied"));
1912        assert!(result.content.contains("read(**/.env)"));
1913        // The gate sees the public input only.
1914        let seen = gate.seen.lock().unwrap();
1915        assert_eq!(seen[0].0, "read_file");
1916        assert_eq!(seen[0].2, json!({"path": ".env"}));
1917    }
1918
1919    #[tokio::test]
1920    async fn test_tool_gate_ask_requires_approval_marker() {
1921        let gate = FakeGate::new(crate::tool_gate::ToolGateOutcome::with(
1922            crate::tool_gate::ToolGateDecision::Ask {
1923                reason: Some("rule".into()),
1924            },
1925        ));
1926        // A low-risk tool that would normally run without approval.
1927        let registry = gated_registry(
1928            gate.clone(),
1929            Box::new(DummyTool {
1930                tool_name: "read_file".into(),
1931            }),
1932        );
1933        let first = registry
1934            .execute_with_auth("read_file", json!({"path": "a"}), &gate_auth())
1935            .await;
1936        assert!(first.is_error);
1937        assert_eq!(first.error_type.as_deref(), Some("approval_required"));
1938        assert!(first.content.contains("(rule)"));
1939
1940        let approved = registry
1941            .execute_with_auth(
1942                "read_file",
1943                json!({"path": "a", "__microclaw_high_risk_approved": true}),
1944                &gate_auth(),
1945            )
1946            .await;
1947        assert!(!approved.is_error, "{}", approved.content);
1948        assert_eq!(approved.content, "ok");
1949        let seen = gate.seen.lock().unwrap();
1950        assert_eq!(
1951            seen.iter().map(|s| s.1).collect::<Vec<_>>(),
1952            vec![false, true]
1953        );
1954        assert_eq!(seen[1].2, json!({"path": "a"}));
1955    }
1956
1957    #[tokio::test]
1958    async fn test_tool_gate_updated_input_is_applied() {
1959        let gate = FakeGate::new(crate::tool_gate::ToolGateOutcome {
1960            decision: crate::tool_gate::ToolGateDecision::Allow,
1961            updated_input: Some(json!({"text": "rewritten"})),
1962        });
1963        let registry = gated_registry(
1964            gate,
1965            Box::new(CaptureInputTool {
1966                tool_name: "echo_tool".into(),
1967            }),
1968        );
1969        let result = registry
1970            .execute_with_auth("echo_tool", json!({"text": "original"}), &gate_auth())
1971            .await;
1972        assert!(!result.is_error, "{}", result.content);
1973        let payload: serde_json::Value = serde_json::from_str(&result.content).unwrap();
1974        assert_eq!(payload["text"], "rewritten");
1975        // Internal keys survive the rewrite.
1976        assert_eq!(payload["__microclaw_auth"]["caller_chat_id"], 7);
1977    }
1978
1979    #[tokio::test]
1980    async fn test_tool_gate_after_text_is_appended() {
1981        let gate = Arc::new(FakeGate {
1982            outcome: crate::tool_gate::ToolGateOutcome::allow(),
1983            after: Some("  hook says: run the tests  ".into()),
1984            seen: std::sync::Mutex::new(Vec::new()),
1985        });
1986        let registry = gated_registry(
1987            gate,
1988            Box::new(DummyTool {
1989                tool_name: "read_file".into(),
1990            }),
1991        );
1992        let result = registry
1993            .execute_with_auth("read_file", json!({"path": "a"}), &gate_auth())
1994            .await;
1995        assert!(!result.is_error);
1996        assert_eq!(result.content, "ok\n\nhook says: run the tests");
1997    }
1998}