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