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