1mod approval_rules;
4mod effects;
5mod nested_budget;
6mod types;
7
8use crate::value::VmDictExt;
9use std::cell::RefCell;
10use std::collections::BTreeMap;
11use std::thread_local;
12
13use serde::{Deserialize, Serialize};
14
15use crate::runtime_limits::RuntimeLimits;
16use crate::tool_annotations::{SideEffectLevel, ToolAnnotations};
17use crate::value::{VmError, VmValue};
18use crate::workspace_path::{classify_workspace_path, WorkspacePathInfo};
19
20pub use crate::tool_annotations::{ToolArgSchema, ToolKind};
21pub use approval_rules::{
22 clear_all_approval_policy_repeat_counts, clear_approval_policy_repeat_counts,
23 next_approval_policy_repeat_count, ApprovalShape, PolicyAction, PolicyEvaluation,
24 PolicyMatchedRule, PolicyRule, PolicyRuleMatch,
25};
26pub use effects::{
27 compute_handoff_effects, effect_kind_label, effect_record_summary, effect_subset_violations,
28 effects_from_metadata, EffectKind, EffectRecord, EffectScope,
29};
30pub use nested_budget::{
31 annotate_nested_execution_options, enter_nested_execution_policy, NestedExecutionGuard,
32 NestedExecutionKind, NESTED_KIND_OPTION_KEY, NESTED_LABEL_OPTION_KEY,
33};
34pub use types::{
35 enforce_tool_arg_constraints, AutoCompactPolicy, BranchSemantics, CapabilityPolicy,
36 ContextPolicy, EqIgnored, EscalationPolicy, FeedbackBounds, FeedbackPolicy, JoinPolicy,
37 MapPolicy, ModelPolicy, NativeToolFallbackPolicy, ProcessSandboxPolicy, ProcessSandboxPreset,
38 ReducePolicy, RetryPolicy, SandboxProfile, StageContract, ToolArgConstraint, TurnPolicy,
39};
40
41thread_local! {
42 static EXECUTION_POLICY_STACK: RefCell<Vec<CapabilityPolicy>> = const { RefCell::new(Vec::new()) };
43 static EXECUTION_APPROVAL_POLICY_STACK: RefCell<Vec<ToolApprovalPolicy>> = const { RefCell::new(Vec::new()) };
44 static TRUSTED_BRIDGE_CALL_DEPTH: RefCell<usize> = const { RefCell::new(0) };
45}
46
47pub fn push_execution_policy(policy: CapabilityPolicy) {
48 EXECUTION_POLICY_STACK.with(|stack| stack.borrow_mut().push(policy));
49}
50
51pub fn pop_execution_policy() {
52 EXECUTION_POLICY_STACK.with(|stack| {
53 stack.borrow_mut().pop();
54 });
55}
56
57pub fn clear_execution_policy_stacks() {
58 EXECUTION_POLICY_STACK.with(|stack| stack.borrow_mut().clear());
59 EXECUTION_APPROVAL_POLICY_STACK.with(|stack| stack.borrow_mut().clear());
60 TRUSTED_BRIDGE_CALL_DEPTH.with(|depth| *depth.borrow_mut() = 0);
61}
62
63pub fn current_execution_policy() -> Option<CapabilityPolicy> {
64 EXECUTION_POLICY_STACK.with(|stack| stack.borrow().last().cloned())
65}
66
67pub fn execution_policy_active() -> bool {
72 EXECUTION_POLICY_STACK.with(|stack| !stack.borrow().is_empty())
73}
74
75pub fn push_approval_policy(policy: ToolApprovalPolicy) {
76 EXECUTION_APPROVAL_POLICY_STACK.with(|stack| stack.borrow_mut().push(policy));
77}
78
79pub fn pop_approval_policy() {
80 EXECUTION_APPROVAL_POLICY_STACK.with(|stack| {
81 stack.borrow_mut().pop();
82 });
83}
84
85pub fn current_approval_policy() -> Option<ToolApprovalPolicy> {
86 EXECUTION_APPROVAL_POLICY_STACK.with(|stack| stack.borrow().last().cloned())
87}
88
89pub(crate) fn swap_execution_policy_stack(next: Vec<CapabilityPolicy>) -> Vec<CapabilityPolicy> {
102 EXECUTION_POLICY_STACK.with(|stack| std::mem::replace(&mut *stack.borrow_mut(), next))
103}
104
105pub(crate) fn swap_approval_policy_stack(next: Vec<ToolApprovalPolicy>) -> Vec<ToolApprovalPolicy> {
106 EXECUTION_APPROVAL_POLICY_STACK.with(|stack| std::mem::replace(&mut *stack.borrow_mut(), next))
107}
108
109pub(crate) fn swap_trusted_bridge_depth(next: usize) -> usize {
110 TRUSTED_BRIDGE_CALL_DEPTH.with(|depth| std::mem::replace(&mut *depth.borrow_mut(), next))
111}
112
113pub fn current_tool_annotations(tool: &str) -> Option<ToolAnnotations> {
114 current_execution_policy().and_then(|policy| policy.tool_annotations.get(tool).cloned())
115}
116
117pub fn current_allowed_tool_names() -> Vec<String> {
125 let Some(policy) = current_execution_policy() else {
126 return Vec::new();
127 };
128 if !policy.tools.is_empty() {
129 return policy.tools;
130 }
131 policy.tool_annotations.keys().cloned().collect()
132}
133
134pub(super) fn tool_kind_participates_in_write_allowlist(tool_name: &str) -> bool {
135 current_tool_annotations(tool_name)
136 .map(|annotations| !annotations.kind.is_read_only())
137 .unwrap_or(true)
138}
139
140pub struct TrustedBridgeCallGuard;
141
142pub fn allow_trusted_bridge_calls() -> TrustedBridgeCallGuard {
143 TRUSTED_BRIDGE_CALL_DEPTH.with(|depth| {
144 *depth.borrow_mut() += 1;
145 });
146 TrustedBridgeCallGuard
147}
148
149impl Drop for TrustedBridgeCallGuard {
150 fn drop(&mut self) {
151 TRUSTED_BRIDGE_CALL_DEPTH.with(|depth| {
152 let mut depth = depth.borrow_mut();
153 *depth = depth.saturating_sub(1);
154 });
155 }
156}
157
158fn policy_allows_tool(policy: &CapabilityPolicy, tool: &str) -> bool {
159 policy.tools.is_empty() || policy.tools.iter().any(|allowed| allowed == tool)
160}
161
162fn policy_grants_capability(policy: &CapabilityPolicy, capability: &str, op: &str) -> bool {
163 policy
164 .capabilities
165 .get(capability)
166 .is_some_and(|ops| ops.is_empty() || ops.iter().any(|allowed| allowed == op))
167}
168
169fn policy_allows_capability(policy: &CapabilityPolicy, capability: &str, op: &str) -> bool {
170 if policy.capabilities.is_empty() {
171 return true;
173 }
174 if policy_grants_capability(policy, capability, op) {
175 return true;
176 }
177 if capability == "workspace" && op == "exists" {
189 return policy_grants_capability(policy, "workspace", "read_text")
190 || policy_grants_capability(policy, "workspace", "list");
191 }
192 false
193}
194
195fn policy_allows_side_effect(policy: &CapabilityPolicy, requested: &str) -> bool {
196 let requested_rank = SideEffectLevel::rank_str(requested);
202 policy
203 .side_effect_level
204 .as_ref()
205 .map(|allowed| SideEffectLevel::rank_str(allowed) >= requested_rank)
206 .unwrap_or(true)
207}
208
209pub(super) fn reject_policy(reason: String) -> Result<(), VmError> {
210 Err(VmError::CategorizedError {
211 message: reason,
212 category: crate::value::ErrorCategory::ToolRejected,
213 })
214}
215
216#[derive(Clone, Debug, PartialEq, Eq)]
223pub struct PolicyDenial {
224 pub gate: crate::agent_events::DenialGate,
225 pub capability: Option<String>,
226 pub reason: String,
227}
228
229impl From<PolicyDenial> for VmError {
230 fn from(denial: PolicyDenial) -> Self {
231 VmError::CategorizedError {
232 message: denial.reason,
233 category: crate::value::ErrorCategory::ToolRejected,
234 }
235 }
236}
237
238pub(super) fn reject_tool(
239 gate: crate::agent_events::DenialGate,
240 capability: Option<String>,
241 reason: String,
242) -> Result<(), PolicyDenial> {
243 Err(PolicyDenial {
244 gate,
245 capability,
246 reason,
247 })
248}
249
250pub fn current_tool_mutation_classification(tool_name: &str) -> String {
255 current_tool_annotations(tool_name)
256 .map(|annotations| annotations.kind.mutation_class().to_string())
257 .unwrap_or_else(|| "other".to_string())
258}
259
260pub fn current_tool_declared_paths(tool_name: &str, args: &serde_json::Value) -> Vec<String> {
264 current_tool_declared_path_entries(tool_name, args)
265 .into_iter()
266 .map(|entry| entry.display_path().to_string())
267 .collect()
268}
269
270pub fn current_tool_declared_path_entries(
275 tool_name: &str,
276 args: &serde_json::Value,
277) -> Vec<WorkspacePathInfo> {
278 let Some(map) = args.as_object() else {
279 return Vec::new();
280 };
281 let Some(annotations) = current_tool_annotations(tool_name) else {
282 return Vec::new();
283 };
284 let workspace_root = crate::stdlib::process::execution_root_path();
285 let mut entries = Vec::new();
286 for key in &annotations.arg_schema.path_params {
287 if let Some(value) = map.get(key) {
288 match value {
289 serde_json::Value::String(path) if !path.is_empty() => {
290 entries.push(classify_workspace_path(path, Some(&workspace_root)));
291 }
292 serde_json::Value::Array(items) => {
293 for item in items.iter().filter_map(|item| item.as_str()) {
294 if !item.is_empty() {
295 entries.push(classify_workspace_path(item, Some(&workspace_root)));
296 }
297 }
298 }
299 _ => {}
300 }
301 }
302 }
303 entries.sort_by(|a, b| a.display_path().cmp(b.display_path()));
304 entries.dedup_by(|left, right| left.policy_candidates() == right.policy_candidates());
305 entries
306}
307
308pub fn enforce_current_policy_for_builtin(name: &str, args: &[VmValue]) -> Result<(), VmError> {
309 let Some(policy) = current_execution_policy() else {
310 return Ok(());
311 };
312 match name {
313 "find_text"
314 if !policy_allows_capability(&policy, "workspace", "read_text")
315 || !policy_allows_capability(&policy, "workspace", "list") =>
316 {
317 return reject_policy(
318 "builtin 'find_text' exceeds workspace.read_text/workspace.list ceiling"
319 .to_string(),
320 );
321 }
322 "read_file"
323 | "read_file_result"
324 | "read_file_bytes"
325 | "package_snapshot_open"
326 | "render"
327 | "render_prompt"
328 | "render_with_provenance"
329 | "read_lines"
330 if !policy_allows_capability(&policy, "workspace", "read_text") =>
331 {
332 return reject_policy(format!(
333 "builtin '{name}' exceeds workspace.read_text ceiling"
334 ));
335 }
336 "list_dir" | "walk_dir" | "glob"
337 if !policy_allows_capability(&policy, "workspace", "list") =>
338 {
339 return reject_policy(format!("builtin '{name}' exceeds workspace.list ceiling"));
340 }
341 "file_exists" | "path_status" | "stat"
342 if !policy_allows_capability(&policy, "workspace", "exists") =>
343 {
344 return reject_policy(format!("builtin '{name}' exceeds workspace.exists ceiling"));
345 }
346 "write_file" | "write_file_bytes" | "append_file" | "append_file_locked" | "mkdir"
347 | "copy_file" | "move_file"
348 if !policy_allows_capability(&policy, "workspace", "write_text")
349 || !policy_allows_side_effect(&policy, "workspace_write") =>
350 {
351 return reject_policy(format!("builtin '{name}' exceeds workspace write ceiling"));
352 }
353 "delete_file"
354 if !policy_allows_capability(&policy, "workspace", "delete")
355 || !policy_allows_side_effect(&policy, "workspace_write") =>
356 {
357 return reject_policy(
358 "builtin 'delete_file' exceeds workspace.delete ceiling".to_string(),
359 );
360 }
361 "apply_edit"
362 if !policy_allows_capability(&policy, "workspace", "apply_edit")
363 || !policy_allows_side_effect(&policy, "workspace_write") =>
364 {
365 return reject_policy(
366 "builtin 'apply_edit' exceeds workspace.apply_edit ceiling".to_string(),
367 );
368 }
369 "exec"
370 | "exec_at"
371 | "shell"
372 | "shell_at"
373 | "git.repo.discover"
374 | "git.worktree.create"
375 | "git.worktree.remove"
376 | "git.fetch"
377 | "git.rebase"
378 | "git.status"
379 | "git.conflicts"
380 | "git.push"
381 | "git.diff"
382 | "git.merge_base"
383 | "git.tag_list"
384 | "git.describe"
385 | "git.ls_remote"
386 if !policy_allows_capability(&policy, "process", "exec")
387 || !policy_allows_side_effect(&policy, "process_exec") =>
388 {
389 return reject_policy(format!("builtin '{name}' exceeds process.exec ceiling"));
390 }
391 "__files_upload"
396 if !policy_allows_capability(&policy, "workspace", "read_text")
397 || !policy_allows_side_effect(&policy, "network") =>
398 {
399 return reject_policy(
400 "builtin '__files_upload' exceeds workspace.read_text/network ceiling".to_string(),
401 );
402 }
403 "http_get"
404 | "http_post"
405 | "http_put"
406 | "http_patch"
407 | "http_delete"
408 | "http_download"
409 | "http_request"
410 | "unix_socket_json_request"
411 | "__net_unix_socket_json_request"
412 | "http_session_request"
413 | "http_stream_open"
414 | "http_stream_read"
415 | "http_stream_close"
416 | "http_stream_info"
417 | "sse_connect"
418 | "sse_receive"
419 | "websocket_accept"
420 | "websocket_connect"
421 | "websocket_route"
422 | "websocket_send"
423 | "websocket_receive"
424 | "websocket_server"
425 if !policy_allows_side_effect(&policy, "network") =>
426 {
427 return reject_policy(format!("builtin '{name}' exceeds network ceiling"));
428 }
429 "llm_call" | "llm_call_safe" | "llm_completion" | "llm_stream" | "llm_stream_call"
430 | "llm_healthcheck" | "agent_loop"
431 if !policy_allows_capability(&policy, "llm", "call") =>
432 {
433 return reject_policy(format!("builtin '{name}' exceeds llm.call ceiling"));
434 }
435 "connector_call"
436 if !policy_allows_capability(&policy, "connector", "call")
437 || !policy_allows_side_effect(&policy, "network") =>
438 {
439 return reject_policy(
440 "builtin 'connector_call' exceeds connector.call/network ceiling".to_string(),
441 );
442 }
443 "secret_get" if !policy_allows_capability(&policy, "connector", "secret_get") => {
444 return reject_policy(
445 "builtin 'secret_get' exceeds connector.secret_get ceiling".to_string(),
446 );
447 }
448 "event_log_emit" if !policy_allows_capability(&policy, "connector", "event_log_emit") => {
449 return reject_policy(
450 "builtin 'event_log_emit' exceeds connector.event_log_emit ceiling".to_string(),
451 );
452 }
453 "metrics_inc" if !policy_allows_capability(&policy, "connector", "metrics_inc") => {
454 return reject_policy(
455 "builtin 'metrics_inc' exceeds connector.metrics_inc ceiling".to_string(),
456 );
457 }
458 "project_fingerprint"
459 | "project_context_profile_native"
460 | "project_scan_native"
461 | "project_scan_tree_native"
462 | "project_walk_tree_native"
463 | "project_catalog_native"
464 if !policy_allows_capability(&policy, "workspace", "list")
465 || !policy_allows_side_effect(&policy, "read_only") =>
466 {
467 return reject_policy(format!("builtin '{name}' exceeds workspace.list ceiling"));
468 }
469 "__agent_state_init"
470 | "__agent_state_resume"
471 | "__agent_state_write"
472 | "__agent_state_read"
473 | "__agent_state_list"
474 | "__agent_state_delete"
475 | "__agent_state_handoff"
476 if !policy_allows_capability(&policy, "agent_state", "access") =>
477 {
478 return reject_policy(format!(
479 "builtin '{name}' exceeds agent_state.access ceiling"
480 ));
481 }
482 "vision_ocr"
483 if !policy_allows_capability(&policy, "vision", "ocr")
484 || !policy_allows_side_effect(&policy, "process_exec") =>
485 {
486 return reject_policy(format!(
487 "builtin '{name}' exceeds vision.ocr/process ceiling"
488 ));
489 }
490 "mcp_connect"
491 | "mcp_ensure_active"
492 | "mcp_call"
493 | "mcp_list_tools"
494 | "mcp_list_resources"
495 | "mcp_list_resource_templates"
496 | "mcp_read_resource"
497 | "mcp_list_prompts"
498 | "mcp_get_prompt"
499 | "mcp_server_info"
500 | "mcp_disconnect"
501 if !policy_allows_capability(&policy, "process", "exec")
502 || !policy_allows_side_effect(&policy, "process_exec") =>
503 {
504 return reject_policy(format!("builtin '{name}' exceeds process.exec ceiling"));
505 }
506 "host_call" => {
507 let name = args.first().map(|v| v.display()).unwrap_or_default();
508 let Some((capability, op)) = name.split_once('.') else {
509 return reject_policy(format!(
510 "host_call '{name}' must use capability.operation naming"
511 ));
512 };
513 if !policy_allows_capability(&policy, capability, op) {
514 return reject_policy(format!(
515 "host_call {capability}.{op} exceeds capability ceiling"
516 ));
517 }
518 let requested_side_effect = match (capability, op) {
519 ("workspace", "write_text" | "apply_edit" | "delete") => "workspace_write",
520 ("process", "exec") => "process_exec",
521 _ => "read_only",
522 };
523 if !policy_allows_side_effect(&policy, requested_side_effect) {
524 return reject_policy(format!(
525 "host_call {capability}.{op} exceeds side-effect ceiling"
526 ));
527 }
528 }
529 "host_tool_list" | "host_tool_call"
530 if !policy_allows_capability(&policy, "host", "tool_call") =>
531 {
532 return reject_policy(format!("builtin '{name}' exceeds host.tool_call ceiling"));
533 }
534 _ => {}
535 }
536 Ok(())
537}
538
539pub fn enforce_current_policy_for_bridge_builtin(name: &str) -> Result<(), VmError> {
540 let trusted = TRUSTED_BRIDGE_CALL_DEPTH.with(|depth| *depth.borrow() > 0);
541 if trusted {
542 return Ok(());
543 }
544 if current_execution_policy().is_some() {
545 return reject_policy(format!(
546 "bridged builtin '{name}' exceeds execution policy; declare an explicit capability/tool surface instead"
547 ));
548 }
549 Ok(())
550}
551
552pub fn enforce_current_policy_for_tool(tool_name: &str) -> Result<(), PolicyDenial> {
553 use crate::agent_events::DenialGate;
554 let Some(policy) = current_execution_policy() else {
555 return Ok(());
556 };
557 if !policy_allows_tool(&policy, tool_name) {
558 return reject_tool(
559 DenialGate::ToolCeiling,
560 None,
561 format!("tool '{tool_name}' exceeds tool ceiling"),
562 );
563 }
564 if let Some(annotations) = policy.tool_annotations.get(tool_name) {
565 for (capability, ops) in &annotations.capabilities {
566 for op in ops {
567 if !policy_allows_capability(&policy, capability, op) {
568 return reject_tool(
569 DenialGate::CapabilityCeiling,
570 Some(format!("{capability}.{op}")),
571 format!("tool '{tool_name}' exceeds capability ceiling: {capability}.{op}"),
572 );
573 }
574 }
575 }
576 let requested_level = annotations.side_effect_level;
577 if requested_level != SideEffectLevel::None
578 && !policy_allows_side_effect(&policy, requested_level.as_str())
579 {
580 return reject_tool(
581 DenialGate::SideEffectCeiling,
582 None,
583 format!(
584 "tool '{tool_name}' exceeds side-effect ceiling: {}",
585 requested_level.as_str()
586 ),
587 );
588 }
589 }
590 Ok(())
591}
592
593pub fn redact_transcript_visibility(
605 transcript: &VmValue,
606 visibility: Option<&str>,
607) -> Option<VmValue> {
608 let Some(visibility) = visibility else {
609 return Some(transcript.clone());
610 };
611 if visibility != "public" && visibility != "public_only" {
612 return Some(transcript.clone());
613 }
614 let dict = transcript.as_dict()?;
615 let public_messages = match dict.get("messages") {
616 Some(VmValue::List(list)) => list
617 .iter()
618 .filter_map(redact_public_message)
619 .collect::<Vec<_>>(),
620 _ => Vec::new(),
621 };
622 let public_events = match dict.get("events") {
623 Some(VmValue::List(list)) => list
624 .iter()
625 .filter(|event| {
626 event
627 .as_dict()
628 .and_then(|d| d.get("visibility"))
629 .map(|v| v.display())
630 .map(|value| value == "public")
631 .unwrap_or(true)
632 })
633 .cloned()
634 .collect::<Vec<_>>(),
635 _ => Vec::new(),
636 };
637 let mut redacted = dict.clone();
638 redacted.insert(
639 crate::value::intern_key("messages"),
640 VmValue::List(std::sync::Arc::new(public_messages)),
641 );
642 redacted.insert(
643 crate::value::intern_key("events"),
644 VmValue::List(std::sync::Arc::new(public_events)),
645 );
646 Some(VmValue::dict(redacted))
647}
648
649fn redact_public_message(message: &VmValue) -> Option<VmValue> {
650 let Some(dict) = message.as_dict() else {
651 return Some(message.clone());
652 };
653 if dict.get("role").map(|value| value.display()).as_deref() == Some("tool_result") {
654 return None;
655 }
656 if dict
657 .get("visibility")
658 .map(|value| value.display())
659 .is_some_and(|visibility| visibility != "public")
660 {
661 return None;
662 }
663
664 let mut redacted = dict.clone();
665 let mut saw_structured_blocks = false;
666 let mut public_text = Vec::new();
667 for key in ["content", "blocks"] {
668 if let Some(VmValue::List(blocks)) = dict.get(key) {
669 saw_structured_blocks = true;
670 let public_blocks = blocks
671 .iter()
672 .filter_map(redact_public_block)
673 .collect::<Vec<_>>();
674 if key == "blocks" || public_text.is_empty() {
675 public_text = text_fragments_from_blocks(&public_blocks);
676 }
677 redacted.insert(
678 crate::value::intern_key(key),
679 VmValue::List(std::sync::Arc::new(public_blocks)),
680 );
681 }
682 }
683 if saw_structured_blocks {
684 if public_text.is_empty() {
685 redacted.remove("text");
686 } else {
687 redacted.put_str("text", public_text.join("\n"));
688 }
689 }
690 Some(VmValue::dict(redacted))
691}
692
693fn redact_public_block(block: &VmValue) -> Option<VmValue> {
694 let Some(dict) = block.as_dict() else {
695 return Some(block.clone());
696 };
697 if dict
698 .get("visibility")
699 .map(|value| value.display())
700 .is_some_and(|visibility| visibility != "public")
701 {
702 return None;
703 }
704 Some(block.clone())
705}
706
707fn text_fragments_from_blocks(blocks: &[VmValue]) -> Vec<String> {
708 blocks
709 .iter()
710 .filter_map(|block| block.as_dict())
711 .filter_map(|dict| dict.get("text"))
712 .filter_map(|text| match text {
713 VmValue::String(value) if !value.is_empty() => Some(value.to_string()),
714 _ => None,
715 })
716 .collect()
717}
718
719pub fn builtin_ceiling() -> CapabilityPolicy {
720 CapabilityPolicy {
721 tools: Vec::new(),
725 capabilities: BTreeMap::new(),
726 workspace_roots: Vec::new(),
727 read_only_roots: Vec::new(),
728 side_effect_level: Some(SideEffectLevel::MAX.as_str().to_string()),
738 recursion_limit: Some(RuntimeLimits::DEFAULT.max_nested_execution_depth),
739 tool_arg_constraints: Vec::new(),
740 tool_annotations: BTreeMap::new(),
741 sandbox_profile: SandboxProfile::Worktree,
742 process_sandbox: Default::default(),
743 }
744}
745
746#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
750#[serde(default)]
751pub struct ToolApprovalPolicy {
752 #[serde(default)]
755 pub rules: Vec<PolicyRule>,
756 #[serde(default)]
758 pub auto_approve: Vec<String>,
759 #[serde(default)]
761 pub auto_deny: Vec<String>,
762 #[serde(default)]
764 pub require_approval: Vec<String>,
765 #[serde(default)]
767 pub write_path_allowlist: Vec<String>,
768 #[serde(default)]
770 pub allow_sensitive_paths: bool,
771 #[serde(default)]
774 pub sensitive_path_patterns: Vec<String>,
775 #[serde(default)]
777 pub allow_external_paths: bool,
778 #[serde(default)]
780 pub external_roots: Vec<String>,
781 #[serde(default, alias = "repeated_call_limit")]
783 pub repeat_limit: Option<u64>,
784 #[serde(default, alias = "repeated_call_action")]
786 pub repeat_action: Option<PolicyAction>,
787}
788
789#[derive(Debug, Clone, PartialEq, Eq)]
791pub enum ToolApprovalDecision {
792 AutoApproved,
794 AutoDenied { reason: String },
796 RequiresHostApproval,
799}
800
801impl ToolApprovalPolicy {
802 pub fn evaluate_detailed(&self, tool_name: &str, args: &serde_json::Value) -> PolicyEvaluation {
803 approval_rules::evaluate_tool_approval_policy(self, tool_name, args, None)
804 }
805
806 pub fn evaluate_detailed_with_repeat(
807 &self,
808 tool_name: &str,
809 args: &serde_json::Value,
810 repeat_count: u64,
811 ) -> PolicyEvaluation {
812 approval_rules::evaluate_tool_approval_policy(self, tool_name, args, Some(repeat_count))
813 }
814
815 pub fn evaluate(&self, tool_name: &str, args: &serde_json::Value) -> ToolApprovalDecision {
818 let decision = self.evaluate_detailed(tool_name, args);
819 if decision.is_deny() {
820 return ToolApprovalDecision::AutoDenied {
821 reason: decision.reason,
822 };
823 }
824 if decision.is_ask() {
825 return ToolApprovalDecision::RequiresHostApproval;
826 }
827 ToolApprovalDecision::AutoApproved
828 }
829
830 pub fn intersect(&self, other: &ToolApprovalPolicy) -> ToolApprovalPolicy {
836 let auto_approve = if self.auto_approve.is_empty() {
837 other.auto_approve.clone()
838 } else if other.auto_approve.is_empty() {
839 self.auto_approve.clone()
840 } else {
841 self.auto_approve
842 .iter()
843 .filter(|p| other.auto_approve.contains(p))
844 .cloned()
845 .collect()
846 };
847 let mut auto_deny = self.auto_deny.clone();
848 auto_deny.extend(other.auto_deny.iter().cloned());
849 let mut require_approval = self.require_approval.clone();
850 require_approval.extend(other.require_approval.iter().cloned());
851 let write_path_allowlist = if self.write_path_allowlist.is_empty() {
852 other.write_path_allowlist.clone()
853 } else if other.write_path_allowlist.is_empty() {
854 self.write_path_allowlist.clone()
855 } else {
856 self.write_path_allowlist
857 .iter()
858 .filter(|p| other.write_path_allowlist.contains(p))
859 .cloned()
860 .collect()
861 };
862 let mut rules = self.rules.clone();
863 rules.extend(other.rules.iter().cloned());
864 let mut sensitive_path_patterns = self.sensitive_path_patterns.clone();
865 sensitive_path_patterns.extend(other.sensitive_path_patterns.iter().cloned());
866 sensitive_path_patterns.sort();
867 sensitive_path_patterns.dedup();
868 let external_roots = if self.external_roots.is_empty() {
869 other.external_roots.clone()
870 } else if other.external_roots.is_empty() {
871 self.external_roots.clone()
872 } else {
873 self.external_roots
874 .iter()
875 .filter(|root| other.external_roots.contains(root))
876 .cloned()
877 .collect()
878 };
879 ToolApprovalPolicy {
880 rules,
881 auto_approve,
882 auto_deny,
883 require_approval,
884 write_path_allowlist,
885 allow_sensitive_paths: self.allow_sensitive_paths && other.allow_sensitive_paths,
886 sensitive_path_patterns,
887 allow_external_paths: self.allow_external_paths && other.allow_external_paths,
888 external_roots,
889 repeat_limit: match (self.repeat_limit, other.repeat_limit) {
890 (Some(left), Some(right)) => Some(left.min(right)),
891 (Some(left), None) => Some(left),
892 (None, Some(right)) => Some(right),
893 (None, None) => None,
894 },
895 repeat_action: match (self.repeat_action, other.repeat_action) {
896 (Some(PolicyAction::Deny), _) | (_, Some(PolicyAction::Deny)) => {
897 Some(PolicyAction::Deny)
898 }
899 (Some(PolicyAction::Ask), _) | (_, Some(PolicyAction::Ask)) => {
900 Some(PolicyAction::Ask)
901 }
902 (Some(PolicyAction::Allow), Some(PolicyAction::Allow)) => Some(PolicyAction::Allow),
903 (Some(action), None) | (None, Some(action)) => Some(action),
904 (None, None) => None,
905 },
906 }
907 }
908}
909
910#[cfg(test)]
911mod approval_policy_tests {
912 use super::*;
913 use crate::orchestration::{pop_execution_policy, push_execution_policy, CapabilityPolicy};
914 use crate::tool_annotations::{ToolAnnotations, ToolArgSchema, ToolKind};
915
916 fn workspace_caps(ops: &[&str]) -> CapabilityPolicy {
917 CapabilityPolicy {
918 capabilities: std::collections::BTreeMap::from([(
919 "workspace".to_string(),
920 ops.iter().map(|s| s.to_string()).collect(),
921 )]),
922 ..Default::default()
923 }
924 }
925
926 #[test]
927 fn builtin_ceiling_permits_desktop_control_but_a_lower_ceiling_denies_it() {
928 let builtin = builtin_ceiling();
932 assert!(policy_allows_side_effect(
933 &builtin,
934 SideEffectLevel::DesktopControl.as_str()
935 ));
936
937 let network_ceiling = CapabilityPolicy {
941 side_effect_level: Some(SideEffectLevel::Network.as_str().to_string()),
942 ..Default::default()
943 };
944 assert!(!policy_allows_side_effect(
945 &network_ceiling,
946 SideEffectLevel::DesktopControl.as_str()
947 ));
948 assert!(policy_allows_side_effect(
950 &network_ceiling,
951 SideEffectLevel::ProcessExec.as_str()
952 ));
953 }
954
955 #[test]
956 fn read_text_subsumes_exists_probe() {
957 push_execution_policy(workspace_caps(&[
965 "read_text",
966 "list",
967 "write_text",
968 "apply_edit",
969 ]));
970 assert!(enforce_current_policy_for_builtin("file_exists", &[]).is_ok());
971 assert!(enforce_current_policy_for_builtin("path_status", &[]).is_ok());
972 assert!(enforce_current_policy_for_builtin("stat", &[]).is_ok());
973 pop_execution_policy();
974 }
975
976 #[test]
977 fn list_alone_subsumes_exists_probe() {
978 push_execution_policy(workspace_caps(&["list"]));
980 assert!(enforce_current_policy_for_builtin("file_exists", &[]).is_ok());
981 assert!(enforce_current_policy_for_builtin("path_status", &[]).is_ok());
982 pop_execution_policy();
983 }
984
985 #[test]
986 fn exists_probe_rejected_without_any_read_grant() {
987 push_execution_policy(workspace_caps(&["write_text", "apply_edit"]));
990 assert!(enforce_current_policy_for_builtin("file_exists", &[]).is_err());
991 assert!(enforce_current_policy_for_builtin("path_status", &[]).is_err());
992 pop_execution_policy();
993 }
994
995 #[test]
996 fn auto_deny_takes_precedence_over_auto_approve() {
997 let policy = ToolApprovalPolicy {
998 auto_approve: vec!["*".to_string()],
999 auto_deny: vec!["dangerous_*".to_string()],
1000 ..Default::default()
1001 };
1002 assert_eq!(
1003 policy.evaluate("dangerous_rm", &serde_json::json!({})),
1004 ToolApprovalDecision::AutoDenied {
1005 reason: "tool 'dangerous_rm' matches deny pattern 'dangerous_*'".to_string()
1006 }
1007 );
1008 }
1009
1010 #[test]
1011 fn auto_approve_matches_glob() {
1012 let policy = ToolApprovalPolicy {
1013 auto_approve: vec!["read*".to_string(), "search*".to_string()],
1014 ..Default::default()
1015 };
1016 assert_eq!(
1017 policy.evaluate("read_file", &serde_json::json!({})),
1018 ToolApprovalDecision::AutoApproved
1019 );
1020 assert_eq!(
1021 policy.evaluate("search", &serde_json::json!({})),
1022 ToolApprovalDecision::AutoApproved
1023 );
1024 }
1025
1026 #[test]
1027 fn require_approval_emits_decision() {
1028 let policy = ToolApprovalPolicy {
1029 require_approval: vec!["edit*".to_string()],
1030 ..Default::default()
1031 };
1032 let decision = policy.evaluate("edit_file", &serde_json::json!({"path": "foo.rs"}));
1033 assert!(matches!(
1034 decision,
1035 ToolApprovalDecision::RequiresHostApproval
1036 ));
1037 }
1038
1039 #[test]
1040 fn unmatched_tool_defaults_to_approved() {
1041 let policy = ToolApprovalPolicy {
1042 auto_approve: vec!["read*".to_string()],
1043 require_approval: vec!["edit*".to_string()],
1044 ..Default::default()
1045 };
1046 assert_eq!(
1047 policy.evaluate("unknown_tool", &serde_json::json!({})),
1048 ToolApprovalDecision::AutoApproved
1049 );
1050 }
1051
1052 #[test]
1053 fn intersect_merges_deny_lists() {
1054 let a = ToolApprovalPolicy {
1055 auto_deny: vec!["rm*".to_string()],
1056 ..Default::default()
1057 };
1058 let b = ToolApprovalPolicy {
1059 auto_deny: vec!["drop*".to_string()],
1060 ..Default::default()
1061 };
1062 let merged = a.intersect(&b);
1063 assert_eq!(merged.auto_deny.len(), 2);
1064 }
1065
1066 #[test]
1067 fn intersect_restricts_auto_approve_to_common_patterns() {
1068 let a = ToolApprovalPolicy {
1069 auto_approve: vec!["read*".to_string(), "search*".to_string()],
1070 ..Default::default()
1071 };
1072 let b = ToolApprovalPolicy {
1073 auto_approve: vec!["read*".to_string(), "write*".to_string()],
1074 ..Default::default()
1075 };
1076 let merged = a.intersect(&b);
1077 assert_eq!(merged.auto_approve, vec!["read*".to_string()]);
1078 }
1079
1080 #[test]
1081 fn intersect_defers_auto_approve_when_one_side_empty() {
1082 let a = ToolApprovalPolicy {
1083 auto_approve: vec!["read*".to_string()],
1084 ..Default::default()
1085 };
1086 let b = ToolApprovalPolicy::default();
1087 let merged = a.intersect(&b);
1088 assert_eq!(merged.auto_approve, vec!["read*".to_string()]);
1089 }
1090
1091 #[test]
1092 fn write_path_allowlist_matches_recovered_workspace_relative_path() {
1093 let temp = tempfile::tempdir().unwrap();
1094 std::fs::create_dir_all(temp.path().join("packages/demo")).unwrap();
1095 std::fs::write(temp.path().join("packages/demo/file.txt"), "ok").unwrap();
1096 crate::stdlib::process::set_thread_execution_context(Some(
1097 crate::orchestration::RunExecutionRecord {
1098 cwd: Some(temp.path().to_string_lossy().into_owned()),
1099 project_root: None,
1100 source_dir: Some(temp.path().to_string_lossy().into_owned()),
1101 env: BTreeMap::new(),
1102 adapter: None,
1103 repo_path: None,
1104 worktree_path: None,
1105 branch: None,
1106 base_ref: None,
1107 cleanup: None,
1108 },
1109 ));
1110
1111 let mut tool_annotations = BTreeMap::new();
1112 tool_annotations.insert(
1113 "write_file".to_string(),
1114 ToolAnnotations {
1115 kind: ToolKind::Edit,
1116 arg_schema: ToolArgSchema {
1117 path_params: vec!["path".to_string()],
1118 ..Default::default()
1119 },
1120 ..Default::default()
1121 },
1122 );
1123 push_execution_policy(CapabilityPolicy {
1124 tool_annotations,
1125 ..Default::default()
1126 });
1127
1128 let policy = ToolApprovalPolicy {
1129 write_path_allowlist: vec!["packages/demo/file.txt".to_string()],
1130 ..Default::default()
1131 };
1132 let decision = policy.evaluate(
1133 "write_file",
1134 &serde_json::json!({"path": "/packages/demo/file.txt"}),
1135 );
1136 assert_eq!(decision, ToolApprovalDecision::AutoApproved);
1137
1138 pop_execution_policy();
1139 crate::stdlib::process::set_thread_execution_context(None);
1140 }
1141
1142 #[test]
1143 fn write_path_allowlist_does_not_block_read_only_tools() {
1144 let temp = tempfile::tempdir().unwrap();
1145 std::fs::create_dir_all(temp.path().join("packages/demo")).unwrap();
1146 std::fs::write(temp.path().join("packages/demo/context.txt"), "ok").unwrap();
1147 crate::stdlib::process::set_thread_execution_context(Some(
1148 crate::orchestration::RunExecutionRecord {
1149 cwd: Some(temp.path().to_string_lossy().into_owned()),
1150 project_root: None,
1151 source_dir: Some(temp.path().to_string_lossy().into_owned()),
1152 env: BTreeMap::new(),
1153 adapter: None,
1154 repo_path: None,
1155 worktree_path: None,
1156 branch: None,
1157 base_ref: None,
1158 cleanup: None,
1159 },
1160 ));
1161
1162 let mut tool_annotations = BTreeMap::new();
1163 tool_annotations.insert(
1164 "read_file".to_string(),
1165 ToolAnnotations {
1166 kind: ToolKind::Read,
1167 arg_schema: ToolArgSchema {
1168 path_params: vec!["path".to_string()],
1169 ..Default::default()
1170 },
1171 ..Default::default()
1172 },
1173 );
1174 push_execution_policy(CapabilityPolicy {
1175 tool_annotations,
1176 ..Default::default()
1177 });
1178
1179 let policy = ToolApprovalPolicy {
1180 write_path_allowlist: vec!["packages/demo/file.txt".to_string()],
1181 ..Default::default()
1182 };
1183 let decision = policy.evaluate(
1184 "read_file",
1185 &serde_json::json!({"path": "/packages/demo/context.txt"}),
1186 );
1187 assert_eq!(decision, ToolApprovalDecision::AutoApproved);
1188
1189 pop_execution_policy();
1190 crate::stdlib::process::set_thread_execution_context(None);
1191 }
1192
1193 #[test]
1194 fn builtin_policy_covers_fs_read_and_list_helpers() {
1195 clear_execution_policy_stacks();
1196 push_execution_policy(CapabilityPolicy {
1197 capabilities: BTreeMap::from([("workspace".to_string(), vec!["exists".to_string()])]),
1198 side_effect_level: Some("read_only".to_string()),
1199 ..CapabilityPolicy::default()
1200 });
1201
1202 for name in [
1203 "read_lines",
1204 "find_text",
1205 "walk_dir",
1206 "glob",
1207 "project_context_profile_native",
1208 ] {
1209 assert!(
1210 enforce_current_policy_for_builtin(name, &[]).is_err(),
1211 "{name} should be rejected when the matching workspace capability is absent"
1212 );
1213 }
1214
1215 pop_execution_policy();
1216 }
1217
1218 #[test]
1219 fn move_file_requires_workspace_write_side_effect() {
1220 clear_execution_policy_stacks();
1221 push_execution_policy(CapabilityPolicy {
1222 capabilities: BTreeMap::from([(
1223 "workspace".to_string(),
1224 vec!["write_text".to_string()],
1225 )]),
1226 side_effect_level: Some("read_only".to_string()),
1227 ..CapabilityPolicy::default()
1228 });
1229
1230 let error = enforce_current_policy_for_builtin("move_file", &[]).unwrap_err();
1231 assert!(
1232 error.to_string().contains("workspace write ceiling"),
1233 "unexpected error: {error}"
1234 );
1235
1236 pop_execution_policy();
1237 }
1238
1239 #[test]
1240 fn unix_socket_json_request_requires_network_side_effect() {
1241 clear_execution_policy_stacks();
1242 push_execution_policy(CapabilityPolicy {
1243 side_effect_level: Some("read_only".to_string()),
1244 ..CapabilityPolicy::default()
1245 });
1246
1247 let error =
1248 enforce_current_policy_for_builtin("__net_unix_socket_json_request", &[]).unwrap_err();
1249 assert!(
1250 error.to_string().contains("network ceiling"),
1251 "unexpected error: {error}"
1252 );
1253
1254 pop_execution_policy();
1255 }
1256
1257 #[test]
1258 fn files_upload_requires_workspace_read_and_network_side_effect() {
1259 clear_execution_policy_stacks();
1260 push_execution_policy(CapabilityPolicy {
1261 capabilities: BTreeMap::from([(
1262 "workspace".to_string(),
1263 vec!["read_text".to_string()],
1264 )]),
1265 side_effect_level: Some("read_only".to_string()),
1266 ..CapabilityPolicy::default()
1267 });
1268
1269 let network_error = enforce_current_policy_for_builtin("__files_upload", &[]).unwrap_err();
1270 assert!(
1271 network_error.to_string().contains("network ceiling"),
1272 "unexpected error: {network_error}"
1273 );
1274 pop_execution_policy();
1275
1276 push_execution_policy(CapabilityPolicy {
1277 capabilities: BTreeMap::from([("workspace".to_string(), vec!["exists".to_string()])]),
1278 side_effect_level: Some("network".to_string()),
1279 ..CapabilityPolicy::default()
1280 });
1281 let read_error = enforce_current_policy_for_builtin("__files_upload", &[]).unwrap_err();
1282 assert!(
1283 read_error.to_string().contains("workspace.read_text"),
1284 "unexpected error: {read_error}"
1285 );
1286
1287 pop_execution_policy();
1288 }
1289}
1290
1291#[cfg(test)]
1292mod turn_policy_tests {
1293 use super::TurnPolicy;
1294
1295 #[test]
1296 fn default_allows_done_sentinel() {
1297 let policy = TurnPolicy::default();
1298 assert!(policy.allow_done_sentinel);
1299 assert!(!policy.require_action_or_yield);
1300 assert!(policy.max_prose_chars.is_none());
1301 }
1302
1303 #[test]
1304 fn deserializing_partial_dict_preserves_done_sentinel_pathway() {
1305 let policy: TurnPolicy =
1310 serde_json::from_value(serde_json::json!({ "require_action_or_yield": true }))
1311 .expect("deserialize");
1312 assert!(policy.require_action_or_yield);
1313 assert!(policy.allow_done_sentinel);
1314 }
1315
1316 #[test]
1317 fn deserializing_explicit_false_disables_done_sentinel() {
1318 let policy: TurnPolicy = serde_json::from_value(serde_json::json!({
1319 "require_action_or_yield": true,
1320 "allow_done_sentinel": false,
1321 }))
1322 .expect("deserialize");
1323 assert!(policy.require_action_or_yield);
1324 assert!(!policy.allow_done_sentinel);
1325 }
1326}
1327
1328#[cfg(test)]
1329mod visibility_redaction_tests {
1330 use super::*;
1331 use crate::value::VmValue;
1332
1333 fn mock_transcript() -> VmValue {
1334 let messages = vec![
1335 serde_json::json!({"role": "user", "content": "hi"}),
1336 serde_json::json!({"role": "assistant", "content": "hello"}),
1337 serde_json::json!({"role": "tool_result", "content": "internal tool output"}),
1338 ];
1339 crate::llm::helpers::transcript_to_vm_with_events(
1340 Some("test-id".to_string()),
1341 None,
1342 None,
1343 &messages,
1344 Vec::new(),
1345 Vec::new(),
1346 Some("active"),
1347 )
1348 }
1349
1350 fn message_count(transcript: &VmValue) -> usize {
1351 transcript
1352 .as_dict()
1353 .and_then(|d| d.get("messages"))
1354 .and_then(|v| match v {
1355 VmValue::List(list) => Some(list.len()),
1356 _ => None,
1357 })
1358 .unwrap_or(0)
1359 }
1360
1361 #[test]
1362 fn visibility_none_returns_unchanged() {
1363 let t = mock_transcript();
1364 let result = redact_transcript_visibility(&t, None).unwrap();
1365 assert_eq!(message_count(&result), 3);
1366 }
1367
1368 #[test]
1369 fn visibility_public_drops_tool_results() {
1370 let t = mock_transcript();
1371 let result = redact_transcript_visibility(&t, Some("public")).unwrap();
1372 assert_eq!(message_count(&result), 2);
1373 }
1374
1375 #[test]
1376 fn visibility_public_drops_private_content_blocks() {
1377 let t = crate::schema::json_to_vm_value(&serde_json::json!({
1378 "messages": [
1379 {
1380 "role": "assistant",
1381 "visibility": "public",
1382 "text": "visible answer\nsecret chain",
1383 "content": [
1384 {"type": "output_text", "text": "visible answer", "visibility": "public"},
1385 {"type": "reasoning", "text": "secret chain", "visibility": "private"}
1386 ],
1387 "blocks": [
1388 {"type": "output_text", "text": "visible block", "visibility": "public"},
1389 {"type": "tool_call", "text": "internal args", "visibility": "internal"}
1390 ]
1391 }
1392 ],
1393 "events": []
1394 }));
1395
1396 let result = redact_transcript_visibility(&t, Some("public")).unwrap();
1397 let rendered = result.display();
1398 assert!(rendered.contains("visible answer"));
1399 assert!(rendered.contains("visible block"));
1400 assert!(!rendered.contains("secret chain"));
1401 assert!(!rendered.contains("internal args"));
1402 }
1403
1404 #[test]
1405 fn visibility_unknown_string_is_pass_through() {
1406 let t = mock_transcript();
1407 let result = redact_transcript_visibility(&t, Some("internal")).unwrap();
1408 assert_eq!(message_count(&result), 3);
1409 }
1410}