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