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