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" | "write_file_bytes" | "append_file" | "append_file_locked" | "mkdir"
396 | "copy_file" | "move_file"
397 if !policy_allows_capability(&policy, "workspace", "write_text")
398 || !policy_allows_side_effect(&policy, "workspace_write") =>
399 {
400 return reject_policy(format!("builtin '{name}' exceeds workspace write ceiling"));
401 }
402 "delete_file"
403 if !policy_allows_capability(&policy, "workspace", "delete")
404 || !policy_allows_side_effect(&policy, "workspace_write") =>
405 {
406 return reject_policy(
407 "builtin 'delete_file' exceeds workspace.delete ceiling".to_string(),
408 );
409 }
410 "apply_edit"
411 if !policy_allows_capability(&policy, "workspace", "apply_edit")
412 || !policy_allows_side_effect(&policy, "workspace_write") =>
413 {
414 return reject_policy(
415 "builtin 'apply_edit' exceeds workspace.apply_edit ceiling".to_string(),
416 );
417 }
418 "exec"
419 | "exec_at"
420 | "shell"
421 | "shell_at"
422 | "git.repo.discover"
423 | "git.worktree.create"
424 | "git.worktree.remove"
425 | "git.fetch"
426 | "git.rebase"
427 | "git.status"
428 | "git.conflicts"
429 | "git.push"
430 | "git.diff"
431 | "git.merge_base"
432 | "git.tag_list"
433 | "git.describe"
434 | "git.ls_remote"
435 if !policy_allows_capability(&policy, "process", "exec")
436 || !policy_allows_side_effect(&policy, "process_exec") =>
437 {
438 return reject_policy(format!("builtin '{name}' exceeds process.exec ceiling"));
439 }
440 "__files_upload" if !policy_allows_capability(&policy, "workspace", "read_text") => {
445 return reject_policy(
446 "builtin '__files_upload' exceeds workspace.read_text/network ceiling".to_string(),
447 );
448 }
449 "llm_call" | "llm_call_safe" | "llm_completion" | "llm_stream" | "llm_stream_call"
450 | "llm_healthcheck" | "agent_loop"
451 if !policy_allows_capability(&policy, "llm", "call") =>
452 {
453 return reject_policy(format!("builtin '{name}' exceeds llm.call ceiling"));
454 }
455 "connector_call"
456 if !policy_allows_capability(&policy, "connector", "call")
457 || !policy_allows_side_effect(&policy, "network") =>
458 {
459 return reject_policy(
460 "builtin 'connector_call' exceeds connector.call/network ceiling".to_string(),
461 );
462 }
463 "secret_get" if !policy_allows_capability(&policy, "connector", "secret_get") => {
464 return reject_policy(
465 "builtin 'secret_get' exceeds connector.secret_get ceiling".to_string(),
466 );
467 }
468 "event_log_emit" if !policy_allows_capability(&policy, "connector", "event_log_emit") => {
469 return reject_policy(
470 "builtin 'event_log_emit' exceeds connector.event_log_emit ceiling".to_string(),
471 );
472 }
473 "metrics_inc" if !policy_allows_capability(&policy, "connector", "metrics_inc") => {
474 return reject_policy(
475 "builtin 'metrics_inc' exceeds connector.metrics_inc ceiling".to_string(),
476 );
477 }
478 "project_fingerprint"
479 | "project_context_profile_native"
480 | "project_scan_native"
481 | "project_scan_tree_native"
482 | "project_walk_tree_native"
483 | "project_catalog_native"
484 if !policy_allows_capability(&policy, "workspace", "list")
485 || !policy_allows_side_effect(&policy, "read_only") =>
486 {
487 return reject_policy(format!("builtin '{name}' exceeds workspace.list ceiling"));
488 }
489 "__agent_state_init"
490 | "__agent_state_resume"
491 | "__agent_state_write"
492 | "__agent_state_read"
493 | "__agent_state_list"
494 | "__agent_state_delete"
495 | "__agent_state_handoff"
496 if !policy_allows_capability(&policy, "agent_state", "access") =>
497 {
498 return reject_policy(format!(
499 "builtin '{name}' exceeds agent_state.access ceiling"
500 ));
501 }
502 "vision_ocr"
503 if !policy_allows_capability(&policy, "vision", "ocr")
504 || !policy_allows_side_effect(&policy, "process_exec") =>
505 {
506 return reject_policy(format!(
507 "builtin '{name}' exceeds vision.ocr/process ceiling"
508 ));
509 }
510 "mcp_connect"
511 | "mcp_ensure_active"
512 | "mcp_call"
513 | "mcp_list_tools"
514 | "mcp_list_resources"
515 | "mcp_list_resource_templates"
516 | "mcp_read_resource"
517 | "mcp_list_prompts"
518 | "mcp_get_prompt"
519 | "mcp_server_info"
520 | "mcp_disconnect"
521 if !policy_allows_capability(&policy, "process", "exec")
522 || !policy_allows_side_effect(&policy, "process_exec") =>
523 {
524 return reject_policy(format!("builtin '{name}' exceeds process.exec ceiling"));
525 }
526 "host_call" => {
527 let name = args.first().map(|v| v.display()).unwrap_or_default();
528 let Some((capability, op)) = name.split_once('.') else {
529 return reject_policy(format!(
530 "host_call '{name}' must use capability.operation naming"
531 ));
532 };
533 if !policy_allows_capability(&policy, capability, op) {
534 return reject_policy(format!(
535 "host_call {capability}.{op} exceeds capability ceiling"
536 ));
537 }
538 let requested_side_effect = match (capability, op) {
539 ("workspace", "write_text" | "apply_edit" | "delete") => "workspace_write",
540 ("process", "exec") => "process_exec",
541 _ => "read_only",
542 };
543 if !policy_allows_side_effect(&policy, requested_side_effect) {
544 return reject_policy(format!(
545 "host_call {capability}.{op} exceeds side-effect ceiling"
546 ));
547 }
548 }
549 "host_tool_list" | "host_tool_call"
550 if !policy_allows_capability(&policy, "host", "tool_call") =>
551 {
552 return reject_policy(format!("builtin '{name}' exceeds host.tool_call ceiling"));
553 }
554 _ => {}
555 }
556 Ok(())
557}
558
559pub fn enforce_current_policy_for_bridge_builtin(name: &str) -> Result<(), VmError> {
560 let trusted = TRUSTED_BRIDGE_CALL_DEPTH.with(|depth| *depth.borrow() > 0);
561 if trusted {
562 return Ok(());
563 }
564 if current_execution_policy().is_some() {
565 return reject_policy(format!(
566 "bridged builtin '{name}' exceeds execution policy; declare an explicit capability/tool surface instead"
567 ));
568 }
569 Ok(())
570}
571
572pub fn enforce_current_policy_for_tool(tool_name: &str) -> Result<(), PolicyDenial> {
573 enforce_current_policy_for_tool_with_side_effect_grant(tool_name, None)
574}
575
576pub(crate) fn enforce_current_policy_for_tool_with_side_effect_grant(
581 tool_name: &str,
582 side_effect_grant: Option<&SideEffectCeilingGrant>,
583) -> Result<(), PolicyDenial> {
584 use crate::agent_events::DenialGate;
585 let Some(policy) = current_execution_policy() else {
586 return Ok(());
587 };
588 if !policy_allows_tool(&policy, tool_name) {
589 return reject_tool(
590 DenialGate::ToolCeiling,
591 None,
592 format!("tool '{tool_name}' exceeds tool ceiling"),
593 );
594 }
595 if let Some(annotations) = policy.tool_annotations.get(tool_name) {
596 for (capability, ops) in &annotations.capabilities {
597 for op in ops {
598 if !policy_allows_capability(&policy, capability, op) {
599 return reject_tool(
600 DenialGate::CapabilityCeiling,
601 Some(format!("{capability}.{op}")),
602 format!("tool '{tool_name}' exceeds capability ceiling: {capability}.{op}"),
603 );
604 }
605 }
606 }
607 let requested_level = annotations.side_effect_level;
608 if requested_level != SideEffectLevel::None
609 && !policy_allows_side_effect(&policy, requested_level.as_str())
610 {
611 let ceiling = policy
612 .side_effect_level
613 .as_deref()
614 .map(SideEffectLevel::parse)
615 .expect("a side-effect refusal requires an active policy ceiling");
616 let violation = SideEffectCeilingViolation {
617 ceiling,
618 required_level: requested_level,
619 };
620 if side_effect_grant.is_some_and(|grant| grant.matches(tool_name, violation)) {
621 return Ok(());
622 }
623 return Err(PolicyDenial {
624 gate: DenialGate::SideEffectCeiling,
625 capability: None,
626 reason: format!(
627 "tool '{tool_name}' requires side-effect level '{}' but the active ceiling is '{}'",
628 requested_level.as_str(),
629 ceiling.as_str(),
630 ),
631 side_effect_ceiling: Some(violation),
632 });
633 }
634 }
635 Ok(())
636}
637
638pub fn redact_transcript_visibility(
650 transcript: &VmValue,
651 visibility: Option<&str>,
652) -> Option<VmValue> {
653 let Some(visibility) = visibility else {
654 return Some(transcript.clone());
655 };
656 if visibility != "public" && visibility != "public_only" {
657 return Some(transcript.clone());
658 }
659 let dict = transcript.as_dict()?;
660 let public_messages = match dict.get("messages") {
661 Some(VmValue::List(list)) => list
662 .iter()
663 .filter_map(redact_public_message)
664 .collect::<Vec<_>>(),
665 _ => Vec::new(),
666 };
667 let public_events = match dict.get("events") {
668 Some(VmValue::List(list)) => list
669 .iter()
670 .filter(|event| {
671 event
672 .as_dict()
673 .and_then(|d| d.get("visibility"))
674 .map(|v| v.display())
675 .map(|value| value == "public")
676 .unwrap_or(true)
677 })
678 .cloned()
679 .collect::<Vec<_>>(),
680 _ => Vec::new(),
681 };
682 let mut redacted = dict.clone();
683 redacted.insert(
684 crate::value::intern_key("messages"),
685 VmValue::List(std::sync::Arc::new(public_messages)),
686 );
687 redacted.insert(
688 crate::value::intern_key("events"),
689 VmValue::List(std::sync::Arc::new(public_events)),
690 );
691 Some(VmValue::dict(redacted))
692}
693
694fn redact_public_message(message: &VmValue) -> Option<VmValue> {
695 let Some(dict) = message.as_dict() else {
696 return Some(message.clone());
697 };
698 if dict.get("role").map(|value| value.display()).as_deref() == Some("tool_result") {
699 return None;
700 }
701 if dict
702 .get("visibility")
703 .map(|value| value.display())
704 .is_some_and(|visibility| visibility != "public")
705 {
706 return None;
707 }
708
709 let mut redacted = dict.clone();
710 let mut saw_structured_blocks = false;
711 let mut public_text = Vec::new();
712 for key in ["content", "blocks"] {
713 if let Some(VmValue::List(blocks)) = dict.get(key) {
714 saw_structured_blocks = true;
715 let public_blocks = blocks
716 .iter()
717 .filter_map(redact_public_block)
718 .collect::<Vec<_>>();
719 if key == "blocks" || public_text.is_empty() {
720 public_text = text_fragments_from_blocks(&public_blocks);
721 }
722 redacted.insert(
723 crate::value::intern_key(key),
724 VmValue::List(std::sync::Arc::new(public_blocks)),
725 );
726 }
727 }
728 if saw_structured_blocks {
729 if public_text.is_empty() {
730 redacted.remove("text");
731 } else {
732 redacted.put_str("text", public_text.join("\n"));
733 }
734 }
735 Some(VmValue::dict(redacted))
736}
737
738fn redact_public_block(block: &VmValue) -> Option<VmValue> {
739 let Some(dict) = block.as_dict() else {
740 return Some(block.clone());
741 };
742 if dict
743 .get("visibility")
744 .map(|value| value.display())
745 .is_some_and(|visibility| visibility != "public")
746 {
747 return None;
748 }
749 Some(block.clone())
750}
751
752fn text_fragments_from_blocks(blocks: &[VmValue]) -> Vec<String> {
753 blocks
754 .iter()
755 .filter_map(|block| block.as_dict())
756 .filter_map(|dict| dict.get("text"))
757 .filter_map(|text| match text {
758 VmValue::String(value) if !value.is_empty() => Some(value.to_string()),
759 _ => None,
760 })
761 .collect()
762}
763
764pub fn builtin_ceiling() -> CapabilityPolicy {
765 CapabilityPolicy {
766 tools: Vec::new(),
770 capabilities: BTreeMap::new(),
771 workspace_roots: Vec::new(),
772 read_only_roots: Vec::new(),
773 side_effect_level: Some(SideEffectLevel::MAX.as_str().to_string()),
783 recursion_limit: Some(RuntimeLimits::DEFAULT.max_nested_execution_depth),
784 tool_arg_constraints: Vec::new(),
785 tool_annotations: BTreeMap::new(),
786 sandbox_profile: SandboxProfile::Worktree,
787 process_sandbox: Default::default(),
788 }
789}
790
791#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
795#[serde(default)]
796pub struct ToolApprovalPolicy {
797 #[serde(default)]
800 pub rules: Vec<PolicyRule>,
801 #[serde(default)]
803 pub auto_approve: Vec<String>,
804 #[serde(default)]
806 pub auto_deny: Vec<String>,
807 #[serde(default)]
809 pub require_approval: Vec<String>,
810 #[serde(default)]
812 pub write_path_allowlist: Vec<String>,
813 #[serde(default)]
815 pub allow_sensitive_paths: bool,
816 #[serde(default)]
819 pub sensitive_path_patterns: Vec<String>,
820 #[serde(default)]
822 pub allow_external_paths: bool,
823 #[serde(default)]
825 pub external_roots: Vec<String>,
826 #[serde(default, alias = "repeated_call_limit")]
828 pub repeat_limit: Option<u64>,
829 #[serde(default, alias = "repeated_call_action")]
831 pub repeat_action: Option<PolicyAction>,
832}
833
834#[derive(Debug, Clone, PartialEq, Eq)]
836pub enum ToolApprovalDecision {
837 AutoApproved,
839 AutoDenied { reason: String },
841 RequiresHostApproval,
844}
845
846impl ToolApprovalPolicy {
847 pub fn evaluate_detailed(&self, tool_name: &str, args: &serde_json::Value) -> PolicyEvaluation {
848 approval_rules::evaluate_tool_approval_policy(self, tool_name, args, None)
849 }
850
851 pub fn evaluate_detailed_with_repeat(
852 &self,
853 tool_name: &str,
854 args: &serde_json::Value,
855 repeat_count: u64,
856 ) -> PolicyEvaluation {
857 approval_rules::evaluate_tool_approval_policy(self, tool_name, args, Some(repeat_count))
858 }
859
860 pub fn evaluate(&self, tool_name: &str, args: &serde_json::Value) -> ToolApprovalDecision {
863 let decision = self.evaluate_detailed(tool_name, args);
864 if decision.is_deny() {
865 return ToolApprovalDecision::AutoDenied {
866 reason: decision.reason,
867 };
868 }
869 if decision.is_ask() {
870 return ToolApprovalDecision::RequiresHostApproval;
871 }
872 ToolApprovalDecision::AutoApproved
873 }
874
875 pub fn intersect(&self, other: &ToolApprovalPolicy) -> ToolApprovalPolicy {
881 let auto_approve = if self.auto_approve.is_empty() {
882 other.auto_approve.clone()
883 } else if other.auto_approve.is_empty() {
884 self.auto_approve.clone()
885 } else {
886 self.auto_approve
887 .iter()
888 .filter(|p| other.auto_approve.contains(p))
889 .cloned()
890 .collect()
891 };
892 let mut auto_deny = self.auto_deny.clone();
893 auto_deny.extend(other.auto_deny.iter().cloned());
894 let mut require_approval = self.require_approval.clone();
895 require_approval.extend(other.require_approval.iter().cloned());
896 let write_path_allowlist = if self.write_path_allowlist.is_empty() {
897 other.write_path_allowlist.clone()
898 } else if other.write_path_allowlist.is_empty() {
899 self.write_path_allowlist.clone()
900 } else {
901 self.write_path_allowlist
902 .iter()
903 .filter(|p| other.write_path_allowlist.contains(p))
904 .cloned()
905 .collect()
906 };
907 let mut rules = self.rules.clone();
908 rules.extend(other.rules.iter().cloned());
909 let mut sensitive_path_patterns = self.sensitive_path_patterns.clone();
910 sensitive_path_patterns.extend(other.sensitive_path_patterns.iter().cloned());
911 sensitive_path_patterns.sort();
912 sensitive_path_patterns.dedup();
913 let external_roots = if self.external_roots.is_empty() {
914 other.external_roots.clone()
915 } else if other.external_roots.is_empty() {
916 self.external_roots.clone()
917 } else {
918 self.external_roots
919 .iter()
920 .filter(|root| other.external_roots.contains(root))
921 .cloned()
922 .collect()
923 };
924 ToolApprovalPolicy {
925 rules,
926 auto_approve,
927 auto_deny,
928 require_approval,
929 write_path_allowlist,
930 allow_sensitive_paths: self.allow_sensitive_paths && other.allow_sensitive_paths,
931 sensitive_path_patterns,
932 allow_external_paths: self.allow_external_paths && other.allow_external_paths,
933 external_roots,
934 repeat_limit: match (self.repeat_limit, other.repeat_limit) {
935 (Some(left), Some(right)) => Some(left.min(right)),
936 (Some(left), None) => Some(left),
937 (None, Some(right)) => Some(right),
938 (None, None) => None,
939 },
940 repeat_action: match (self.repeat_action, other.repeat_action) {
941 (Some(PolicyAction::Deny), _) | (_, Some(PolicyAction::Deny)) => {
942 Some(PolicyAction::Deny)
943 }
944 (Some(PolicyAction::Ask), _) | (_, Some(PolicyAction::Ask)) => {
945 Some(PolicyAction::Ask)
946 }
947 (Some(PolicyAction::Allow), Some(PolicyAction::Allow)) => Some(PolicyAction::Allow),
948 (Some(action), None) | (None, Some(action)) => Some(action),
949 (None, None) => None,
950 },
951 }
952 }
953}
954
955#[cfg(test)]
956mod approval_policy_tests {
957 use super::*;
958 use crate::orchestration::{pop_execution_policy, push_execution_policy, CapabilityPolicy};
959 use crate::tool_annotations::{ToolAnnotations, ToolArgSchema, ToolKind};
960
961 fn workspace_caps(ops: &[&str]) -> CapabilityPolicy {
962 CapabilityPolicy {
963 capabilities: std::collections::BTreeMap::from([(
964 "workspace".to_string(),
965 ops.iter().map(|s| s.to_string()).collect(),
966 )]),
967 ..Default::default()
968 }
969 }
970
971 #[test]
972 fn builtin_ceiling_permits_desktop_control_but_a_lower_ceiling_denies_it() {
973 let builtin = builtin_ceiling();
977 assert!(policy_allows_side_effect(
978 &builtin,
979 SideEffectLevel::DesktopControl.as_str()
980 ));
981
982 let network_ceiling = CapabilityPolicy {
986 side_effect_level: Some(SideEffectLevel::Network.as_str().to_string()),
987 ..Default::default()
988 };
989 assert!(!policy_allows_side_effect(
990 &network_ceiling,
991 SideEffectLevel::DesktopControl.as_str()
992 ));
993 assert!(policy_allows_side_effect(
995 &network_ceiling,
996 SideEffectLevel::ProcessExec.as_str()
997 ));
998 }
999
1000 #[test]
1001 fn read_text_subsumes_exists_probe() {
1002 push_execution_policy(workspace_caps(&[
1010 "read_text",
1011 "list",
1012 "write_text",
1013 "apply_edit",
1014 ]));
1015 assert!(enforce_current_policy_for_builtin("file_exists", &[]).is_ok());
1016 assert!(enforce_current_policy_for_builtin("path_status", &[]).is_ok());
1017 assert!(enforce_current_policy_for_builtin("stat", &[]).is_ok());
1018 pop_execution_policy();
1019 }
1020
1021 #[test]
1022 fn list_alone_subsumes_exists_probe() {
1023 push_execution_policy(workspace_caps(&["list"]));
1025 assert!(enforce_current_policy_for_builtin("file_exists", &[]).is_ok());
1026 assert!(enforce_current_policy_for_builtin("path_status", &[]).is_ok());
1027 pop_execution_policy();
1028 }
1029
1030 #[test]
1031 fn exists_probe_rejected_without_any_read_grant() {
1032 push_execution_policy(workspace_caps(&["write_text", "apply_edit"]));
1035 assert!(enforce_current_policy_for_builtin("file_exists", &[]).is_err());
1036 assert!(enforce_current_policy_for_builtin("path_status", &[]).is_err());
1037 pop_execution_policy();
1038 }
1039
1040 #[test]
1041 fn auto_deny_takes_precedence_over_auto_approve() {
1042 let policy = ToolApprovalPolicy {
1043 auto_approve: vec!["*".to_string()],
1044 auto_deny: vec!["dangerous_*".to_string()],
1045 ..Default::default()
1046 };
1047 assert_eq!(
1048 policy.evaluate("dangerous_rm", &serde_json::json!({})),
1049 ToolApprovalDecision::AutoDenied {
1050 reason: "tool 'dangerous_rm' matches deny pattern 'dangerous_*'".to_string()
1051 }
1052 );
1053 }
1054
1055 #[test]
1056 fn auto_approve_matches_glob() {
1057 let policy = ToolApprovalPolicy {
1058 auto_approve: vec!["read*".to_string(), "search*".to_string()],
1059 ..Default::default()
1060 };
1061 assert_eq!(
1062 policy.evaluate("read_file", &serde_json::json!({})),
1063 ToolApprovalDecision::AutoApproved
1064 );
1065 assert_eq!(
1066 policy.evaluate("search", &serde_json::json!({})),
1067 ToolApprovalDecision::AutoApproved
1068 );
1069 }
1070
1071 #[test]
1072 fn require_approval_emits_decision() {
1073 let policy = ToolApprovalPolicy {
1074 require_approval: vec!["edit*".to_string()],
1075 ..Default::default()
1076 };
1077 let decision = policy.evaluate("edit_file", &serde_json::json!({"path": "foo.rs"}));
1078 assert!(matches!(
1079 decision,
1080 ToolApprovalDecision::RequiresHostApproval
1081 ));
1082 }
1083
1084 #[test]
1085 fn unmatched_tool_defaults_to_approved() {
1086 let policy = ToolApprovalPolicy {
1087 auto_approve: vec!["read*".to_string()],
1088 require_approval: vec!["edit*".to_string()],
1089 ..Default::default()
1090 };
1091 assert_eq!(
1092 policy.evaluate("unknown_tool", &serde_json::json!({})),
1093 ToolApprovalDecision::AutoApproved
1094 );
1095 }
1096
1097 #[test]
1098 fn intersect_merges_deny_lists() {
1099 let a = ToolApprovalPolicy {
1100 auto_deny: vec!["rm*".to_string()],
1101 ..Default::default()
1102 };
1103 let b = ToolApprovalPolicy {
1104 auto_deny: vec!["drop*".to_string()],
1105 ..Default::default()
1106 };
1107 let merged = a.intersect(&b);
1108 assert_eq!(merged.auto_deny.len(), 2);
1109 }
1110
1111 #[test]
1112 fn intersect_restricts_auto_approve_to_common_patterns() {
1113 let a = ToolApprovalPolicy {
1114 auto_approve: vec!["read*".to_string(), "search*".to_string()],
1115 ..Default::default()
1116 };
1117 let b = ToolApprovalPolicy {
1118 auto_approve: vec!["read*".to_string(), "write*".to_string()],
1119 ..Default::default()
1120 };
1121 let merged = a.intersect(&b);
1122 assert_eq!(merged.auto_approve, vec!["read*".to_string()]);
1123 }
1124
1125 #[test]
1126 fn intersect_defers_auto_approve_when_one_side_empty() {
1127 let a = ToolApprovalPolicy {
1128 auto_approve: vec!["read*".to_string()],
1129 ..Default::default()
1130 };
1131 let b = ToolApprovalPolicy::default();
1132 let merged = a.intersect(&b);
1133 assert_eq!(merged.auto_approve, vec!["read*".to_string()]);
1134 }
1135
1136 #[test]
1137 fn write_path_allowlist_matches_recovered_workspace_relative_path() {
1138 let temp = tempfile::tempdir().unwrap();
1139 std::fs::create_dir_all(temp.path().join("packages/demo")).unwrap();
1140 std::fs::write(temp.path().join("packages/demo/file.txt"), "ok").unwrap();
1141 crate::stdlib::process::set_thread_execution_context(Some(
1142 crate::orchestration::RunExecutionRecord {
1143 cwd: Some(temp.path().to_string_lossy().into_owned()),
1144 project_root: None,
1145 source_dir: Some(temp.path().to_string_lossy().into_owned()),
1146 env: BTreeMap::new(),
1147 adapter: None,
1148 repo_path: None,
1149 worktree_path: None,
1150 branch: None,
1151 base_ref: None,
1152 cleanup: None,
1153 grants: Vec::new(),
1154 },
1155 ));
1156
1157 let mut tool_annotations = BTreeMap::new();
1158 tool_annotations.insert(
1159 "write_file".to_string(),
1160 ToolAnnotations {
1161 kind: ToolKind::Edit,
1162 arg_schema: ToolArgSchema {
1163 path_params: vec!["path".to_string()],
1164 ..Default::default()
1165 },
1166 ..Default::default()
1167 },
1168 );
1169 push_execution_policy(CapabilityPolicy {
1170 tool_annotations,
1171 ..Default::default()
1172 });
1173
1174 let policy = ToolApprovalPolicy {
1175 write_path_allowlist: vec!["packages/demo/file.txt".to_string()],
1176 ..Default::default()
1177 };
1178 let decision = policy.evaluate(
1179 "write_file",
1180 &serde_json::json!({"path": "/packages/demo/file.txt"}),
1181 );
1182 assert_eq!(decision, ToolApprovalDecision::AutoApproved);
1183
1184 pop_execution_policy();
1185 crate::stdlib::process::set_thread_execution_context(None);
1186 }
1187
1188 #[test]
1189 fn write_path_allowlist_does_not_block_read_only_tools() {
1190 let temp = tempfile::tempdir().unwrap();
1191 std::fs::create_dir_all(temp.path().join("packages/demo")).unwrap();
1192 std::fs::write(temp.path().join("packages/demo/context.txt"), "ok").unwrap();
1193 crate::stdlib::process::set_thread_execution_context(Some(
1194 crate::orchestration::RunExecutionRecord {
1195 cwd: Some(temp.path().to_string_lossy().into_owned()),
1196 project_root: None,
1197 source_dir: Some(temp.path().to_string_lossy().into_owned()),
1198 env: BTreeMap::new(),
1199 adapter: None,
1200 repo_path: None,
1201 worktree_path: None,
1202 branch: None,
1203 base_ref: None,
1204 cleanup: None,
1205 grants: Vec::new(),
1206 },
1207 ));
1208
1209 let mut tool_annotations = BTreeMap::new();
1210 tool_annotations.insert(
1211 "read_file".to_string(),
1212 ToolAnnotations {
1213 kind: ToolKind::Read,
1214 arg_schema: ToolArgSchema {
1215 path_params: vec!["path".to_string()],
1216 ..Default::default()
1217 },
1218 ..Default::default()
1219 },
1220 );
1221 push_execution_policy(CapabilityPolicy {
1222 tool_annotations,
1223 ..Default::default()
1224 });
1225
1226 let policy = ToolApprovalPolicy {
1227 write_path_allowlist: vec!["packages/demo/file.txt".to_string()],
1228 ..Default::default()
1229 };
1230 let decision = policy.evaluate(
1231 "read_file",
1232 &serde_json::json!({"path": "/packages/demo/context.txt"}),
1233 );
1234 assert_eq!(decision, ToolApprovalDecision::AutoApproved);
1235
1236 pop_execution_policy();
1237 crate::stdlib::process::set_thread_execution_context(None);
1238 }
1239
1240 #[test]
1241 fn builtin_policy_covers_fs_read_and_list_helpers() {
1242 clear_execution_policy_stacks();
1243 push_execution_policy(CapabilityPolicy {
1244 capabilities: BTreeMap::from([("workspace".to_string(), vec!["exists".to_string()])]),
1245 side_effect_level: Some("read_only".to_string()),
1246 ..CapabilityPolicy::default()
1247 });
1248
1249 for name in [
1250 "read_lines",
1251 "find_text",
1252 "find_evidence",
1253 "walk_dir",
1254 "glob",
1255 "project_context_profile_native",
1256 ] {
1257 assert!(
1258 enforce_current_policy_for_builtin(name, &[]).is_err(),
1259 "{name} should be rejected when the matching workspace capability is absent"
1260 );
1261 }
1262
1263 pop_execution_policy();
1264 }
1265
1266 #[test]
1267 fn move_file_requires_workspace_write_side_effect() {
1268 clear_execution_policy_stacks();
1269 push_execution_policy(CapabilityPolicy {
1270 capabilities: BTreeMap::from([(
1271 "workspace".to_string(),
1272 vec!["write_text".to_string()],
1273 )]),
1274 side_effect_level: Some("read_only".to_string()),
1275 ..CapabilityPolicy::default()
1276 });
1277
1278 let error = enforce_current_policy_for_builtin("move_file", &[]).unwrap_err();
1279 assert!(
1280 error.to_string().contains("workspace write ceiling"),
1281 "unexpected error: {error}"
1282 );
1283
1284 pop_execution_policy();
1285 }
1286
1287 #[test]
1288 fn unix_socket_json_request_requires_network_side_effect() {
1289 clear_execution_policy_stacks();
1290 push_execution_policy(CapabilityPolicy {
1291 side_effect_level: Some("read_only".to_string()),
1292 ..CapabilityPolicy::default()
1293 });
1294
1295 let error =
1296 enforce_current_policy_for_builtin("__net_unix_socket_json_request", &[]).unwrap_err();
1297 assert!(
1298 error.to_string().contains("network.http ceiling"),
1299 "unexpected error: {error}"
1300 );
1301
1302 pop_execution_policy();
1303 }
1304
1305 #[test]
1306 fn files_upload_requires_workspace_read_and_network_side_effect() {
1307 clear_execution_policy_stacks();
1308 push_execution_policy(CapabilityPolicy {
1309 capabilities: BTreeMap::from([
1310 ("workspace".to_string(), vec!["read_text".to_string()]),
1311 ("network".to_string(), vec!["http".to_string()]),
1312 ]),
1313 side_effect_level: Some("read_only".to_string()),
1314 ..CapabilityPolicy::default()
1315 });
1316
1317 let network_error = enforce_current_policy_for_builtin("__files_upload", &[]).unwrap_err();
1318 assert!(
1319 network_error.to_string().contains("network.http ceiling"),
1320 "unexpected error: {network_error}"
1321 );
1322 pop_execution_policy();
1323
1324 push_execution_policy(CapabilityPolicy {
1325 capabilities: BTreeMap::from([
1326 ("workspace".to_string(), vec!["exists".to_string()]),
1327 ("network".to_string(), vec!["http".to_string()]),
1328 ]),
1329 side_effect_level: Some("network".to_string()),
1330 ..CapabilityPolicy::default()
1331 });
1332 let read_error = enforce_current_policy_for_builtin("__files_upload", &[]).unwrap_err();
1333 assert!(
1334 read_error.to_string().contains("workspace.read_text"),
1335 "unexpected error: {read_error}"
1336 );
1337
1338 pop_execution_policy();
1339 }
1340}
1341
1342#[cfg(test)]
1343mod turn_policy_tests {
1344 use super::TurnPolicy;
1345
1346 #[test]
1347 fn default_allows_done_sentinel() {
1348 let policy = TurnPolicy::default();
1349 assert!(policy.allow_done_sentinel);
1350 assert!(!policy.require_action_or_yield);
1351 assert!(policy.max_prose_chars.is_none());
1352 }
1353
1354 #[test]
1355 fn deserializing_partial_dict_preserves_done_sentinel_pathway() {
1356 let policy: TurnPolicy =
1361 serde_json::from_value(serde_json::json!({ "require_action_or_yield": true }))
1362 .expect("deserialize");
1363 assert!(policy.require_action_or_yield);
1364 assert!(policy.allow_done_sentinel);
1365 }
1366
1367 #[test]
1368 fn deserializing_explicit_false_disables_done_sentinel() {
1369 let policy: TurnPolicy = serde_json::from_value(serde_json::json!({
1370 "require_action_or_yield": true,
1371 "allow_done_sentinel": false,
1372 }))
1373 .expect("deserialize");
1374 assert!(policy.require_action_or_yield);
1375 assert!(!policy.allow_done_sentinel);
1376 }
1377}
1378
1379#[cfg(test)]
1380mod visibility_redaction_tests {
1381 use super::*;
1382 use crate::value::VmValue;
1383
1384 fn mock_transcript() -> VmValue {
1385 let messages = vec![
1386 serde_json::json!({"role": "user", "content": "hi"}),
1387 serde_json::json!({"role": "assistant", "content": "hello"}),
1388 serde_json::json!({"role": "tool_result", "content": "internal tool output"}),
1389 ];
1390 crate::llm::helpers::transcript_to_vm_with_events(
1391 Some("test-id".to_string()),
1392 None,
1393 None,
1394 &messages,
1395 Vec::new(),
1396 Vec::new(),
1397 Some("active"),
1398 )
1399 }
1400
1401 fn message_count(transcript: &VmValue) -> usize {
1402 transcript
1403 .as_dict()
1404 .and_then(|d| d.get("messages"))
1405 .and_then(|v| match v {
1406 VmValue::List(list) => Some(list.len()),
1407 _ => None,
1408 })
1409 .unwrap_or(0)
1410 }
1411
1412 #[test]
1413 fn visibility_none_returns_unchanged() {
1414 let t = mock_transcript();
1415 let result = redact_transcript_visibility(&t, None).unwrap();
1416 assert_eq!(message_count(&result), 3);
1417 }
1418
1419 #[test]
1420 fn visibility_public_drops_tool_results() {
1421 let t = mock_transcript();
1422 let result = redact_transcript_visibility(&t, Some("public")).unwrap();
1423 assert_eq!(message_count(&result), 2);
1424 }
1425
1426 #[test]
1427 fn visibility_public_drops_private_content_blocks() {
1428 let t = crate::schema::json_to_vm_value(&serde_json::json!({
1429 "messages": [
1430 {
1431 "role": "assistant",
1432 "visibility": "public",
1433 "text": "visible answer\nsecret chain",
1434 "content": [
1435 {"type": "output_text", "text": "visible answer", "visibility": "public"},
1436 {"type": "reasoning", "text": "secret chain", "visibility": "private"}
1437 ],
1438 "blocks": [
1439 {"type": "output_text", "text": "visible block", "visibility": "public"},
1440 {"type": "tool_call", "text": "internal args", "visibility": "internal"}
1441 ]
1442 }
1443 ],
1444 "events": []
1445 }));
1446
1447 let result = redact_transcript_visibility(&t, Some("public")).unwrap();
1448 let rendered = result.display();
1449 assert!(rendered.contains("visible answer"));
1450 assert!(rendered.contains("visible block"));
1451 assert!(!rendered.contains("secret chain"));
1452 assert!(!rendered.contains("internal args"));
1453 }
1454
1455 #[test]
1456 fn visibility_unknown_string_is_pass_through() {
1457 let t = mock_transcript();
1458 let result = redact_transcript_visibility(&t, Some("internal")).unwrap();
1459 assert_eq!(message_count(&result), 3);
1460 }
1461}