a3s-code-core 4.2.8

A3S Code Core - Embeddable AI agent library with tool execution
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
//! Tool-use safety gate.
//!
//! This module concentrates the pre-execution decision chain for tool calls:
//! skill restrictions, hook blocks, permission policy, and HITL requirements.

use crate::agent::AgentConfig;
use crate::hitl::TimeoutAction;
use crate::permissions::PermissionDecision;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ToolGateApproval {
    PermissionAllow,
    ConfirmationNotRequired,
}

impl ToolGateApproval {
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            ToolGateApproval::PermissionAllow => "permission_allow",
            ToolGateApproval::ConfirmationNotRequired => "confirmation_not_required",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ToolGateDenial {
    SkillRestriction,
    HookBlock,
    PermissionDeny,
    MissingConfirmationManager,
}

impl ToolGateDenial {
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            ToolGateDenial::SkillRestriction => "skill_restriction",
            ToolGateDenial::HookBlock => "hook_block",
            ToolGateDenial::PermissionDeny => "permission_deny",
            ToolGateDenial::MissingConfirmationManager => "missing_confirmation_manager",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ToolGateDecision {
    Execute {
        reason: ToolGateApproval,
    },
    Confirm {
        timeout_ms: u64,
        timeout_action: TimeoutAction,
    },
    Deny {
        output: String,
        event_reason: String,
        reason: ToolGateDenial,
    },
}

pub(crate) struct ToolGateInput<'a> {
    pub(crate) tool_name: &'a str,
    pub(crate) args: &'a serde_json::Value,
    pub(crate) pre_tool_block: Option<String>,
}

pub(crate) struct ToolSafetyGate<'a> {
    config: &'a AgentConfig,
}

impl<'a> ToolSafetyGate<'a> {
    pub(crate) fn new(config: &'a AgentConfig) -> Self {
        Self { config }
    }

    pub(crate) async fn decide(&self, input: ToolGateInput<'_>) -> ToolGateDecision {
        if let Some(decision) = self.check_skill_restrictions(input.tool_name) {
            return decision;
        }

        if let Some(reason) = input.pre_tool_block {
            return ToolGateDecision::Deny {
                output: format!("Tool '{}' blocked by hook: {}", input.tool_name, reason),
                event_reason: reason,
                reason: ToolGateDenial::HookBlock,
            };
        }

        match self.permission_decision(input.tool_name, input.args) {
            PermissionDecision::Deny => ToolGateDecision::Deny {
                output: format!(
                    "Permission denied: Tool '{}' is blocked by permission policy.",
                    input.tool_name
                ),
                event_reason: "Blocked by deny rule in permission policy".to_string(),
                reason: ToolGateDenial::PermissionDeny,
            },
            PermissionDecision::Allow => ToolGateDecision::Execute {
                reason: ToolGateApproval::PermissionAllow,
            },
            PermissionDecision::Ask => self.confirmation_decision(input.tool_name).await,
        }
    }

    pub(crate) fn check_skill_restrictions(&self, tool_name: &str) -> Option<ToolGateDecision> {
        if !self.config.enforce_active_skill_tool_restrictions {
            return None;
        }

        let registry = self.config.skill_registry.as_ref()?;
        let restricting_skills = registry.global_tool_restricting_skills();
        if restricting_skills.is_empty() {
            return None;
        }

        let allowed = restricting_skills
            .iter()
            .any(|skill| skill.is_tool_allowed(tool_name));
        if allowed {
            return None;
        }

        let msg = format!("Tool '{}' is not allowed by any active skill.", tool_name);
        Some(ToolGateDecision::Deny {
            output: msg.clone(),
            event_reason: msg,
            reason: ToolGateDenial::SkillRestriction,
        })
    }

    pub(crate) fn permission_decision(
        &self,
        tool_name: &str,
        args: &serde_json::Value,
    ) -> PermissionDecision {
        self.config
            .permission_checker
            .as_ref()
            .map(|checker| checker.check(tool_name, args))
            .unwrap_or(PermissionDecision::Ask)
    }

    async fn confirmation_decision(&self, tool_name: &str) -> ToolGateDecision {
        let Some(cm) = &self.config.confirmation_manager else {
            let msg = format!(
                "Tool '{}' requires confirmation but no HITL confirmation manager is configured. \
                 Configure a confirmation policy to enable tool execution.",
                tool_name
            );
            return ToolGateDecision::Deny {
                output: msg.clone(),
                event_reason: msg,
                reason: ToolGateDenial::MissingConfirmationManager,
            };
        };

        if !cm.requires_confirmation(tool_name).await {
            return ToolGateDecision::Execute {
                reason: ToolGateApproval::ConfirmationNotRequired,
            };
        }

        let policy = cm.policy().await;
        ToolGateDecision::Confirm {
            timeout_ms: policy.default_timeout_ms,
            timeout_action: policy.timeout_action,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::hitl::{ConfirmationManager, ConfirmationPolicy};
    use crate::permissions::{PermissionChecker, PermissionDecision};
    use crate::queue::SessionLane;
    use crate::skills::{Skill, SkillKind, SkillRegistry};
    use serde_json::json;
    use std::sync::Arc;
    use tokio::sync::broadcast;

    struct StaticPermission(PermissionDecision);

    impl PermissionChecker for StaticPermission {
        fn check(&self, _tool_name: &str, _args: &serde_json::Value) -> PermissionDecision {
            self.0
        }
    }

    fn restricted_registry() -> Arc<SkillRegistry> {
        let registry = SkillRegistry::new();
        registry.register_unchecked(Arc::new(Skill {
            name: "read-only".to_string(),
            description: String::new(),
            allowed_tools: Some("read(*), grep(*)".to_string()),
            disable_model_invocation: false,
            kind: SkillKind::Instruction,
            content: String::new(),
            tags: Vec::new(),
            version: None,
        }));
        Arc::new(registry)
    }

    #[tokio::test]
    async fn active_skill_restriction_is_ignored_by_default_before_permission_allow() {
        let config = AgentConfig {
            skill_registry: Some(restricted_registry()),
            permission_checker: Some(Arc::new(StaticPermission(PermissionDecision::Allow))),
            ..Default::default()
        };
        let gate = ToolSafetyGate::new(&config);

        let decision = gate
            .decide(ToolGateInput {
                tool_name: "write",
                args: &json!({"file_path": "x"}),
                pre_tool_block: None,
            })
            .await;

        assert!(matches!(
            decision,
            ToolGateDecision::Execute {
                reason: ToolGateApproval::PermissionAllow,
            }
        ));
    }

    #[tokio::test]
    async fn active_skill_restriction_denies_when_legacy_mode_is_enabled() {
        let config = AgentConfig {
            skill_registry: Some(restricted_registry()),
            enforce_active_skill_tool_restrictions: true,
            permission_checker: Some(Arc::new(StaticPermission(PermissionDecision::Allow))),
            ..Default::default()
        };
        let gate = ToolSafetyGate::new(&config);

        let decision = gate
            .decide(ToolGateInput {
                tool_name: "write",
                args: &json!({"file_path": "x"}),
                pre_tool_block: None,
            })
            .await;

        assert!(matches!(
            decision,
            ToolGateDecision::Deny {
                reason: ToolGateDenial::SkillRestriction,
                ..
            }
        ));
    }

    #[tokio::test]
    async fn ignored_active_skill_restriction_still_allows_permission_deny() {
        let config = AgentConfig {
            skill_registry: Some(restricted_registry()),
            permission_checker: Some(Arc::new(StaticPermission(PermissionDecision::Deny))),
            ..Default::default()
        };
        let gate = ToolSafetyGate::new(&config);

        let decision = gate
            .decide(ToolGateInput {
                tool_name: "write",
                args: &json!({"file_path": "x"}),
                pre_tool_block: None,
            })
            .await;

        assert!(matches!(
            decision,
            ToolGateDecision::Deny {
                reason: ToolGateDenial::PermissionDeny,
                ..
            }
        ));
    }

    #[tokio::test]
    async fn builtin_skill_permissions_do_not_restrict_default_session_tools() {
        let config = AgentConfig {
            skill_registry: Some(Arc::new(SkillRegistry::with_builtins())),
            permission_checker: Some(Arc::new(StaticPermission(PermissionDecision::Allow))),
            ..Default::default()
        };
        let gate = ToolSafetyGate::new(&config);

        let decision = gate
            .decide(ToolGateInput {
                tool_name: "write",
                args: &json!({"file_path": "x"}),
                pre_tool_block: None,
            })
            .await;

        assert!(matches!(
            decision,
            ToolGateDecision::Execute {
                reason: ToolGateApproval::PermissionAllow,
            }
        ));
    }

    #[tokio::test]
    async fn hook_block_denies_before_permission_allow() {
        let config = AgentConfig {
            skill_registry: None,
            permission_checker: Some(Arc::new(StaticPermission(PermissionDecision::Allow))),
            ..Default::default()
        };
        let gate = ToolSafetyGate::new(&config);

        let decision = gate
            .decide(ToolGateInput {
                tool_name: "bash",
                args: &json!({"command": "echo ok"}),
                pre_tool_block: Some("blocked by policy".to_string()),
            })
            .await;

        assert!(matches!(
            decision,
            ToolGateDecision::Deny {
                reason: ToolGateDenial::HookBlock,
                ..
            }
        ));
    }

    #[tokio::test]
    async fn ask_without_confirmation_manager_is_safe_deny() {
        let config = AgentConfig {
            skill_registry: None,
            permission_checker: None,
            confirmation_manager: None,
            ..Default::default()
        };
        let gate = ToolSafetyGate::new(&config);

        let decision = gate
            .decide(ToolGateInput {
                tool_name: "bash",
                args: &json!({"command": "echo ok"}),
                pre_tool_block: None,
            })
            .await;

        assert!(matches!(
            decision,
            ToolGateDecision::Deny {
                reason: ToolGateDenial::MissingConfirmationManager,
                ..
            }
        ));
    }

    #[tokio::test]
    async fn ask_with_confirmation_manager_requests_confirmation() {
        let (event_tx, _) = broadcast::channel(8);
        let manager = Arc::new(ConfirmationManager::new(
            ConfirmationPolicy::enabled().with_timeout(1234, crate::hitl::TimeoutAction::Reject),
            event_tx,
        ));
        let config = AgentConfig {
            skill_registry: None,
            confirmation_manager: Some(manager),
            ..Default::default()
        };
        let gate = ToolSafetyGate::new(&config);

        let decision = gate
            .decide(ToolGateInput {
                tool_name: "bash",
                args: &json!({"command": "echo ok"}),
                pre_tool_block: None,
            })
            .await;

        assert_eq!(
            decision,
            ToolGateDecision::Confirm {
                timeout_ms: 1234,
                timeout_action: crate::hitl::TimeoutAction::Reject,
            }
        );
    }

    #[tokio::test]
    async fn yolo_lane_executes_without_confirmation() {
        let (event_tx, _) = broadcast::channel(8);
        let manager = Arc::new(ConfirmationManager::new(
            ConfirmationPolicy::enabled().with_yolo_lanes([SessionLane::Query]),
            event_tx,
        ));
        let config = AgentConfig {
            skill_registry: None,
            confirmation_manager: Some(manager),
            ..Default::default()
        };
        let gate = ToolSafetyGate::new(&config);

        let decision = gate
            .decide(ToolGateInput {
                tool_name: "read",
                args: &json!({"file_path": "README.md"}),
                pre_tool_block: None,
            })
            .await;

        assert_eq!(
            decision,
            ToolGateDecision::Execute {
                reason: ToolGateApproval::ConfirmationNotRequired,
            }
        );
    }
}