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