microclaw-engine 0.10.1

Channel-independent Agent Engine and default services for MicroClaw
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
use std::path::{Path, PathBuf};

use async_trait::async_trait;
use microclaw_core::llm_types::ToolDefinition;
use serde_json::json;

use crate::internal::tool_runtime::sandbox::SandboxMode;
use crate::internal::tool_runtime::types::WorkingDirIsolation;

pub struct ToolResult {
    pub content: String,
    pub is_error: bool,
    pub status_code: Option<i32>,
    pub bytes: usize,
    pub duration_ms: Option<u128>,
    pub error_type: Option<String>,
    pub metadata: Option<serde_json::Value>,
}

impl ToolResult {
    pub fn success(content: String) -> Self {
        let bytes = content.len();
        ToolResult {
            content,
            is_error: false,
            status_code: Some(0),
            bytes,
            duration_ms: None,
            error_type: None,
            metadata: None,
        }
    }

    pub fn error(content: String) -> Self {
        let bytes = content.len();
        ToolResult {
            content,
            is_error: true,
            status_code: Some(1),
            bytes,
            duration_ms: None,
            error_type: Some("tool_error".to_string()),
            metadata: None,
        }
    }

    pub fn with_status_code(mut self, status_code: i32) -> Self {
        self.status_code = Some(status_code);
        self
    }

    pub fn with_error_type(mut self, error_type: impl Into<String>) -> Self {
        self.error_type = Some(error_type.into());
        self
    }

    pub fn with_metadata(mut self, metadata: serde_json::Value) -> Self {
        self.metadata = Some(metadata);
        self
    }
}

/// Declaration order is the risk ordering (Low < Medium < High) — the derived
/// `Ord` is relied on by the tool-policy `max_risk` comparison.
#[derive(
    Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
)]
#[serde(rename_all = "lowercase")]
pub enum ToolRisk {
    Low,
    Medium,
    High,
}

impl ToolRisk {
    pub fn as_str(&self) -> &'static str {
        match self {
            ToolRisk::Low => "low",
            ToolRisk::Medium => "medium",
            ToolRisk::High => "high",
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ToolExecutionPolicy {
    HostOnly,
    SandboxOnly,
    Dual,
}

impl ToolExecutionPolicy {
    pub fn as_str(&self) -> &'static str {
        match self {
            ToolExecutionPolicy::HostOnly => "host-only",
            ToolExecutionPolicy::SandboxOnly => "sandbox-only",
            ToolExecutionPolicy::Dual => "dual",
        }
    }
}

pub fn tool_risk(name: &str) -> ToolRisk {
    match name {
        "bash" => ToolRisk::High,
        "write_file"
        | "edit_file"
        | "write_memory"
        | "a2a_send"
        | "send_message"
        | "sync_skills"
        | "schedule_task"
        | "pause_scheduled_task"
        | "resume_scheduled_task"
        | "cancel_scheduled_task"
        | "replay_scheduled_task_dlq"
        | "structured_memory_delete"
        | "structured_memory_update" => ToolRisk::Medium,
        // MCP tools are external code with unknown side effects; rating them
        // Low would let them sail under a `max_risk` policy that blocks
        // built-in write tools. Medium matches their SideEffect concurrency
        // default.
        name if name.starts_with("mcp_") => ToolRisk::Medium,
        _ => ToolRisk::Low,
    }
}

/// Classification for parallel tool execution within a single agent turn.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ToolConcurrencyClass {
    /// Safe to run concurrently with any other ReadOnly tool.
    ReadOnly,
    /// Has side effects — must run sequentially with respect to other SideEffect/Exclusive tools.
    SideEffect,
    /// Must run completely alone in its own execution wave (e.g., bash, activate_skill).
    Exclusive,
}

/// Returns the concurrency class for a built-in tool.
/// MCP tools (prefixed with `mcp_`) default to `SideEffect`.
/// Callers may override via `tool_concurrency_overrides` config.
pub fn tool_concurrency_class(name: &str) -> ToolConcurrencyClass {
    match name {
        // Read-only tools: safe to parallelize
        "read_file"
        | "glob"
        | "grep"
        | "web_fetch"
        | "web_search"
        | "deep_research"
        | "get_current_time"
        | "compare_time"
        | "calculate"
        | "read_memory"
        | "structured_memory_search"
        | "todo_read"
        | "export_chat"
        | "a2a_list_peers"
        | "list_scheduled_tasks"
        | "get_scheduled_task_history"
        | "list_scheduled_task_dlq"
        | "subagents_list"
        | "subagents_info"
        | "subagents_focused"
        | "subagents_log"
        | "browser"
        | "fetch_artifact" => ToolConcurrencyClass::ReadOnly,
        // Exclusive tools: must run alone
        "bash" | "activate_skill" | "sessions_spawn" => ToolConcurrencyClass::Exclusive,
        // MCP tools: default to SideEffect (unknown external effects)
        _ if name.starts_with("mcp_") => ToolConcurrencyClass::SideEffect,
        // All other tools with side effects
        "write_file"
        | "edit_file"
        | "write_memory"
        | "send_message"
        | "a2a_send"
        | "schedule_task"
        | "pause_scheduled_task"
        | "resume_scheduled_task"
        | "cancel_scheduled_task"
        | "replay_scheduled_task_dlq"
        | "structured_memory_update"
        | "structured_memory_delete"
        | "todo_write"
        | "sync_skills"
        | "subagents_send"
        | "subagents_focus"
        | "subagents_unfocus"
        | "subagents_kill"
        | "subagents_retry_announces"
        | "subagents_orchestrate" => ToolConcurrencyClass::SideEffect,
        // Unknown tools: conservative default
        _ => ToolConcurrencyClass::SideEffect,
    }
}

/// Parse a concurrency class from a config string.
pub fn parse_concurrency_class(s: &str) -> Option<ToolConcurrencyClass> {
    match s.to_ascii_lowercase().as_str() {
        "read_only" | "readonly" => Some(ToolConcurrencyClass::ReadOnly),
        "side_effect" | "sideeffect" => Some(ToolConcurrencyClass::SideEffect),
        "exclusive" => Some(ToolConcurrencyClass::Exclusive),
        _ => None,
    }
}

pub fn tool_execution_policy(name: &str) -> ToolExecutionPolicy {
    match name {
        "bash" => ToolExecutionPolicy::Dual,
        "write_file" | "edit_file" => ToolExecutionPolicy::HostOnly,
        _ => ToolExecutionPolicy::HostOnly,
    }
}

pub fn validate_execution_policy(
    name: &str,
    sandbox_mode: SandboxMode,
    sandbox_runtime_available: bool,
) -> Result<(), String> {
    let policy = tool_execution_policy(name);
    match policy {
        ToolExecutionPolicy::HostOnly => Ok(()),
        ToolExecutionPolicy::SandboxOnly => {
            if sandbox_mode == SandboxMode::All && sandbox_runtime_available {
                Ok(())
            } else {
                Err(format!(
                    "Tool '{name}' requires sandbox runtime (policy: {}). Enable sandbox and ensure docker runtime is available.",
                    policy.as_str()
                ))
            }
        }
        ToolExecutionPolicy::Dual => {
            if sandbox_mode == SandboxMode::All && !sandbox_runtime_available {
                // Allowed by current fallback behavior, but explicit for observability.
                tracing::warn!(
                    tool = name,
                    policy = policy.as_str(),
                    "sandbox configured but runtime unavailable; falling back to host execution"
                );
            }
            Ok(())
        }
    }
}

#[derive(Clone, Debug)]
pub struct ToolAuthContext {
    pub caller_channel: String,
    pub caller_chat_id: i64,
    /// Stable authorization principal (`main`, `scheduler`, or
    /// `subagent:<run-id>`). Tool grants can match this value or a trailing
    /// wildcard such as `subagent:*`.
    pub principal: String,
    pub control_chat_ids: Vec<i64>,
    pub env_files: Vec<String>,
}

impl ToolAuthContext {
    pub fn is_control_chat(&self) -> bool {
        self.control_chat_ids.contains(&self.caller_chat_id)
    }

    pub fn can_access_chat(&self, target_chat_id: i64) -> bool {
        self.is_control_chat() || self.caller_chat_id == target_chat_id
    }
}

const AUTH_CONTEXT_KEY: &str = "__microclaw_auth";

pub fn auth_context_from_input(input: &serde_json::Value) -> Option<ToolAuthContext> {
    let ctx = input.get(AUTH_CONTEXT_KEY)?;
    let caller_channel = ctx
        .get("caller_channel")
        .and_then(|v| v.as_str())
        .unwrap_or("telegram")
        .to_string();
    let caller_chat_id = ctx.get("caller_chat_id")?.as_i64()?;
    let control_chat_ids = ctx
        .get("control_chat_ids")
        .and_then(|v| v.as_array())
        .map(|arr| arr.iter().filter_map(|x| x.as_i64()).collect())
        .unwrap_or_default();
    let principal = ctx
        .get("principal")
        .and_then(|v| v.as_str())
        .unwrap_or("main")
        .to_string();
    let env_files = ctx
        .get("env_files")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|x| x.as_str().map(str::to_string))
                .collect()
        })
        .unwrap_or_default();
    Some(ToolAuthContext {
        caller_channel,
        caller_chat_id,
        principal,
        control_chat_ids,
        env_files,
    })
}

pub fn authorize_chat_access(input: &serde_json::Value, target_chat_id: i64) -> Result<(), String> {
    if let Some(auth) = auth_context_from_input(input) {
        if !auth.can_access_chat(target_chat_id) {
            return Err(format!(
                "Permission denied: chat {} cannot operate on chat {}",
                auth.caller_chat_id, target_chat_id
            ));
        }
    }
    Ok(())
}

pub fn inject_auth_context(input: serde_json::Value, auth: &ToolAuthContext) -> serde_json::Value {
    let mut obj = match input {
        serde_json::Value::Object(map) => map,
        _ => serde_json::Map::new(),
    };
    let mut auth_val = json!({
        "caller_channel": auth.caller_channel,
        "caller_chat_id": auth.caller_chat_id,
        "principal": auth.principal,
        "control_chat_ids": auth.control_chat_ids,
    });
    if !auth.env_files.is_empty() {
        auth_val["env_files"] = json!(auth.env_files);
    }
    obj.insert(AUTH_CONTEXT_KEY.to_string(), auth_val);
    serde_json::Value::Object(obj)
}

#[async_trait]
pub trait Tool: Send + Sync {
    fn name(&self) -> &str;
    fn definition(&self) -> ToolDefinition;
    async fn execute(&self, input: serde_json::Value) -> ToolResult;
}

pub fn resolve_tool_path(working_dir: &Path, path: &str) -> PathBuf {
    let candidate = PathBuf::from(path);
    if candidate.is_absolute() {
        candidate
    } else {
        working_dir.join(candidate)
    }
}

fn sanitize_channel_segment(channel: &str) -> String {
    let mut out = String::with_capacity(channel.len());
    for c in channel.chars() {
        if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
            out.push(c.to_ascii_lowercase());
        } else {
            out.push('_');
        }
    }
    if out.is_empty() {
        "unknown".to_string()
    } else {
        out
    }
}

pub fn chat_working_dir(base_working_dir: &Path, channel: &str, chat_id: i64) -> PathBuf {
    let chat_segment = if chat_id < 0 {
        format!("neg{}", chat_id.unsigned_abs())
    } else {
        chat_id.to_string()
    };
    base_working_dir
        .join("chat")
        .join(sanitize_channel_segment(channel))
        .join(chat_segment)
}

pub fn working_dir_for_context(
    base_working_dir: &Path,
    isolation: WorkingDirIsolation,
    channel: &str,
    chat_id: i64,
) -> PathBuf {
    match isolation {
        WorkingDirIsolation::Direct => base_working_dir.to_path_buf(),
        WorkingDirIsolation::Shared => base_working_dir.join("shared"),
        WorkingDirIsolation::Chat => chat_working_dir(base_working_dir, channel, chat_id),
    }
}

pub fn resolve_tool_working_dir(
    base_working_dir: &Path,
    isolation: WorkingDirIsolation,
    input: &serde_json::Value,
) -> PathBuf {
    let resolved = match isolation {
        WorkingDirIsolation::Direct => base_working_dir.to_path_buf(),
        WorkingDirIsolation::Shared => base_working_dir.join("shared"),
        WorkingDirIsolation::Chat => auth_context_from_input(input)
            .map(|auth| {
                chat_working_dir(base_working_dir, &auth.caller_channel, auth.caller_chat_id)
            })
            .unwrap_or_else(|| base_working_dir.join("shared")),
    };
    let _ = std::fs::create_dir_all(&resolved);
    resolved
}

fn requires_high_risk_approval(risk: ToolRisk, auth: &ToolAuthContext) -> bool {
    risk == ToolRisk::High
        && (auth.caller_channel == "web" || auth.caller_channel == "work" || auth.is_control_chat())
}

/// Input marker injected after explicit operator approval so a high-risk
/// tool (or an in-tool gate like bash dangerous patterns / sandboxed A2A
/// peers) executes on retry. Shared across crates so a rename can't silently
/// desync the producers and consumers.
pub const HIGH_RISK_APPROVED_KEY: &str = "__microclaw_high_risk_approved";

pub fn require_high_risk_approval(
    name: &str,
    auth: &ToolAuthContext,
    input: &serde_json::Value,
) -> Option<ToolResult> {
    require_high_risk_approval_with_risk(name, tool_risk(name), auth, input)
}

/// Like [`require_high_risk_approval`] but with the tool's effective risk
/// supplied by the caller — used when a registration-time override (e.g. an
/// MCP server trust tier) replaces the name-derived risk.
pub fn require_high_risk_approval_with_risk(
    name: &str,
    risk: ToolRisk,
    auth: &ToolAuthContext,
    input: &serde_json::Value,
) -> Option<ToolResult> {
    if !requires_high_risk_approval(risk, auth) {
        return None;
    }

    let approved = input
        .get(HIGH_RISK_APPROVED_KEY)
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    if approved {
        tracing::warn!(
            tool = name,
            channel = auth.caller_channel.as_str(),
            chat_id = auth.caller_chat_id,
            "Executing high-risk tool with explicit approval marker"
        );
        None
    } else {
        Some(
            ToolResult::error(format!(
                "Approval required for high-risk tool '{name}' (risk: {}). Add `{HIGH_RISK_APPROVED_KEY}: true` only after explicit operator approval.",
                risk.as_str(),
            ))
            .with_error_type("approval_required"),
        )
    }
}

pub fn schema_object(properties: serde_json::Value, required: &[&str]) -> serde_json::Value {
    json!({
        "type": "object",
        "properties": properties,
        "required": required,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_tool_execution_policy_levels() {
        assert_eq!(tool_execution_policy("bash"), ToolExecutionPolicy::Dual);
        assert_eq!(
            tool_execution_policy("write_file"),
            ToolExecutionPolicy::HostOnly
        );
        assert_eq!(
            tool_execution_policy("read_file"),
            ToolExecutionPolicy::HostOnly
        );
    }

    #[test]
    fn test_validate_execution_policy_dual_allows_fallback() {
        let ok = validate_execution_policy("bash", SandboxMode::All, false);
        assert!(ok.is_ok());
    }

    #[test]
    fn work_requires_high_risk_approval_but_cli_headless_remains_noninteractive() {
        let auth = |channel: &str| ToolAuthContext {
            caller_channel: channel.into(),
            caller_chat_id: 42,
            principal: "main".into(),
            control_chat_ids: Vec::new(),
            env_files: Vec::new(),
        };

        assert!(require_high_risk_approval("bash", &auth("work"), &json!({})).is_some());
        assert!(require_high_risk_approval("bash", &auth("headless"), &json!({})).is_none());
    }
}