use std::sync::LazyLock;
use rho_providers::{model::ReasoningLevelSet, reasoning::ReasoningLevel};
use rho_sdk::{CapabilityKind, PolicyDecision};
use crate::permission::PermissionMode;
pub(crate) const DISALLOWED_NESTED_AGENT_TOOLS: [&str; 2] = ["Task", "Agent"];
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub(crate) enum ClaudeFenceError {
#[error(
"claude-cli agents cannot run in Auto or Allow edits unless the child stays \
on its declared tools: Claude auto-approves read-only Bash and allowedTools \
entries. Rho therefore refuses when inherit_claude_config is true, when a tool \
uses a specifier (for example Bash(git *)), or when any declared tool is not \
proven to stay inside that Rho approval class. Unknown Claude, plugin, and MCP \
names fail closed. Switch to Plan or Bypass, use only proven no-prompt tools, \
or disable inherited Claude config."
)]
Unbound,
#[error(
"claude-cli agents cannot run in Supervised permission mode: a delegated \
Claude run cannot ask you for approval. Switch to Auto, Allow edits, Plan, or \
Bypass, or change the agent. Auto and Allow edits only work when every tool is \
proven not to bypass that Rho approval class and inherit_claude_config is false."
)]
SupervisedUnsupported,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ClaudeMode {
Plan,
BypassPermissions,
Default,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SettingSources {
Inherited,
Project,
None,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ClaudeFence {
mode: ClaudeMode,
settings: SettingSources,
}
impl ClaudeFence {
pub(crate) fn new(
mode: PermissionMode,
tools: &[String],
inherit_claude_config: bool,
) -> Result<Self, ClaudeFenceError> {
let configured = if inherit_claude_config {
SettingSources::Inherited
} else {
SettingSources::Project
};
match mode {
PermissionMode::Plan => Ok(Self {
mode: ClaudeMode::Plan,
settings: configured,
}),
PermissionMode::Bypass => Ok(Self {
mode: ClaudeMode::BypassPermissions,
settings: configured,
}),
PermissionMode::Auto | PermissionMode::AllowEdits => {
if preserves_bound_set(mode, tools, inherit_claude_config) {
Ok(Self {
mode: ClaudeMode::Default,
settings: SettingSources::None,
})
} else {
Err(ClaudeFenceError::Unbound)
}
}
PermissionMode::Supervised => Err(ClaudeFenceError::SupervisedUnsupported),
}
}
pub(crate) fn headless() -> Self {
Self {
mode: ClaudeMode::Default,
settings: SettingSources::None,
}
}
pub(crate) fn session_mode(&self) -> &'static str {
match self.mode {
ClaudeMode::Plan => "plan",
ClaudeMode::BypassPermissions => "bypassPermissions",
ClaudeMode::Default => "default",
}
}
pub(crate) fn setting_sources(&self) -> &'static [&'static str] {
match self.settings {
SettingSources::Inherited => &["user", "project", "local"],
SettingSources::Project => &["project"],
SettingSources::None => &[],
}
}
}
fn preserves_bound_set(
mode: PermissionMode,
tools: &[String],
inherit_claude_config: bool,
) -> bool {
!inherit_claude_config
&& tools
.iter()
.all(|tool| tool_preserves_bound_set(mode, tool))
}
fn tool_preserves_bound_set(mode: PermissionMode, tool: &str) -> bool {
let base = tool_base_name(tool);
if is_nested_agent_tool(base) {
return true;
}
base == tool && bare_tool_preserves_approval_boundary(mode, base)
}
fn bare_tool_preserves_approval_boundary(mode: PermissionMode, base: &str) -> bool {
let Some(kind) = tool_capability_kind(base) else {
return false;
};
matches!(mode.decision_for(kind), PolicyDecision::Allow)
}
fn tool_capability_kind(base: &str) -> Option<CapabilityKind> {
Some(match base.to_ascii_lowercase().as_str() {
"read" | "glob" | "grep" | "lsp" => CapabilityKind::Read,
"webfetch" | "websearch" => CapabilityKind::Network,
"edit" | "write" | "notebookedit" => CapabilityKind::Write,
"bash" | "powershell" | "monitor" | "skill" => CapabilityKind::Process,
_ => return None,
})
}
pub(crate) fn tool_base_names(tools: &[String]) -> Vec<String> {
let mut names: Vec<String> = Vec::new();
for tool in tools {
let base = tool_base_name(tool);
if !is_nested_agent_tool(base) && !names.iter().any(|existing| existing == base) {
names.push(base.to_owned());
}
}
names
}
pub(crate) fn allowed_tool_entries(tools: &[String]) -> Vec<String> {
tools
.iter()
.filter(|tool| !is_nested_agent_tool(tool_base_name(tool)))
.cloned()
.collect()
}
fn is_nested_agent_tool(base: &str) -> bool {
DISALLOWED_NESTED_AGENT_TOOLS
.iter()
.any(|nested| base.eq_ignore_ascii_case(nested))
}
fn tool_base_name(tool: &str) -> &str {
tool.split_once('(').map_or(tool, |(base, _)| base)
}
pub(crate) fn claude_effort(level: ReasoningLevel) -> Option<&'static str> {
match level {
ReasoningLevel::Off | ReasoningLevel::Minimal => None,
ReasoningLevel::Low => Some("low"),
ReasoningLevel::Medium => Some("medium"),
ReasoningLevel::High => Some("high"),
ReasoningLevel::Xhigh => Some("xhigh"),
ReasoningLevel::Max => Some("max"),
}
}
pub(crate) fn require_claude_reasoning(
reasoning: Option<ReasoningLevel>,
) -> anyhow::Result<Option<ReasoningLevel>> {
match reasoning {
None => Ok(None),
Some(level) if claude_effort(level).is_some() => Ok(Some(level)),
Some(level) => anyhow::bail!(
"reasoning '{level}' is not a Claude Code effort level; \
expected one of: low, medium, high, xhigh, max (omit to inherit Claude's default)"
),
}
}
pub(crate) static CLAUDE_EFFORT_LEVELS: LazyLock<ReasoningLevelSet> = LazyLock::new(|| {
ReasoningLevelSet::new(
ReasoningLevel::ALL
.into_iter()
.filter(|level| claude_effort(*level).is_some())
.collect(),
)
});
#[cfg(test)]
#[path = "fence_tests.rs"]
mod tests;