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