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