use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use serde_json::Value;
use uuid::Uuid;
use crate::agents::config::AgentConfig;
use crate::tools::{
CLEAR_GOAL_TOOL_NAME, DELEGATE_TO_AGENT_TOOL_NAME, FINISH_TASK_TOOL_NAME,
RECALL_SESSION_TOOL_NAME, SET_GOAL_TOOL_NAME, TODO_WRITE_TOOL_NAME, USE_SKILL_TOOL_NAME,
};
use super::config::RuleDecision;
use super::matcher::subjects_for_in_root;
use super::protocol::PermissionDecision;
use super::redact::redact_subject;
use super::session::SessionPermissions;
pub const PERMISSION_MODE_ENV: &str = "TCODE_PERMISSION_MODE";
pub const DEFAULT_ASK_TIMEOUT_SECS: u64 = 300;
pub const ALLOW_ASKS_SOURCE: &str = "allow_asks";
pub const REMEMBERED_SOURCE: &str = "remembered";
pub const HARNESS_REGISTERED_TOOLS: &[&str] = &[
DELEGATE_TO_AGENT_TOOL_NAME,
FINISH_TASK_TOOL_NAME,
SET_GOAL_TOOL_NAME,
CLEAR_GOAL_TOOL_NAME,
RECALL_SESSION_TOOL_NAME,
USE_SKILL_TOOL_NAME,
TODO_WRITE_TOOL_NAME,
];
fn is_harness_registered(tool: &str) -> bool {
HARNESS_REGISTERED_TOOLS.contains(&tool)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PermissionMode {
#[default]
Default,
AllowAsks,
}
impl PermissionMode {
pub fn parse_lenient(s: &str) -> Option<Self> {
match s.trim().to_ascii_lowercase().replace('_', "-").as_str() {
"default" => Some(Self::Default),
"allow-asks" | "allowasks" => Some(Self::AllowAsks),
_ => None,
}
}
pub fn resolve(cli: Option<&str>) -> Self {
Self::resolve_from(cli, std::env::var(PERMISSION_MODE_ENV).ok().as_deref())
}
pub fn resolve_from(cli: Option<&str>, env: Option<&str>) -> Self {
[cli, env]
.into_iter()
.flatten()
.find_map(Self::parse_lenient)
.unwrap_or_default()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Decision {
Allow,
Deny { rule: String },
Ask { rule: String },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DenySource {
Policy,
Headless,
Timeout,
Client,
}
impl DenySource {
pub fn as_str(self) -> &'static str {
match self {
Self::Policy => "policy",
Self::Headless => "headless",
Self::Timeout => "timeout",
Self::Client => "client",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
Allow,
Denied { rule: String, source: DenySource },
}
impl Outcome {
pub fn message(&self) -> Option<String> {
match self {
Outcome::Allow => None,
Outcome::Denied { rule, source } => Some(match source {
DenySource::Policy => format!("denied by policy ({rule})"),
DenySource::Headless => format!("denied by policy ({rule}): headless run"),
DenySource::Timeout => format!("denied by policy ({rule}): no decision"),
DenySource::Client => format!("denied by policy ({rule}): denied by client"),
}),
}
}
}
pub trait PermissionEvents: Send + Sync {
#[allow(clippy::too_many_arguments)]
fn permission_requested(
&self,
session_id: &str,
request_id: &str,
agent: &str,
agent_id: &str,
tool: &str,
subject: &str,
rule: &str,
);
fn permission_resolved(
&self,
session_id: &str,
request_id: &str,
agent: &str,
agent_id: &str,
decision: &str,
source: &str,
);
fn prompter_attached(&self, session_id: &str) -> bool;
}
#[derive(Clone)]
pub struct PermissionContext {
pub mode: PermissionMode,
pub timeout: Duration,
pub session_id: String,
pub ask: Option<Arc<SessionPermissions>>,
pub events: Option<Arc<dyn PermissionEvents>>,
pub root: Option<PathBuf>,
}
impl PermissionContext {
pub fn headless(mode: PermissionMode) -> Self {
Self {
mode,
timeout: Duration::from_secs(DEFAULT_ASK_TIMEOUT_SECS),
session_id: String::new(),
ask: None,
events: None,
root: None,
}
}
pub fn with_root(mut self, root: impl Into<PathBuf>) -> Self {
self.root = Some(root.into());
self
}
pub fn gate_for(&self, agent: Arc<AgentConfig>, agent_id: impl Into<String>) -> PermissionGate {
PermissionGate {
agent,
agent_id: agent_id.into(),
ctx: self.clone(),
}
}
}
pub struct PermissionGate {
agent: Arc<AgentConfig>,
agent_id: String,
ctx: PermissionContext,
}
impl PermissionGate {
pub fn evaluate(agent: &AgentConfig, tool: &str, args: &Value) -> Decision {
Self::evaluate_in_root(agent, tool, args, None)
}
pub fn evaluate_in_root(
agent: &AgentConfig,
tool: &str,
args: &Value,
root: Option<&Path>,
) -> Decision {
if let Some(allowed) = agent.tools.as_ref().and_then(|t| t.allowed.as_ref())
&& !allowed.iter().any(|a| a == tool)
&& !is_harness_registered(tool)
{
return Decision::Deny {
rule: "tcode_tools allowlist".to_string(),
};
}
let Some(map) = agent.permissions.as_ref() else {
return Decision::Allow;
};
match map.evaluate_call(tool, &subjects_for_in_root(tool, args, root)) {
None => Decision::Allow,
Some(m) => match m.decision {
RuleDecision::Allow => Decision::Allow,
RuleDecision::Deny => Decision::Deny { rule: m.rule },
RuleDecision::Ask => Decision::Ask { rule: m.rule },
},
}
}
pub async fn resolve(&self, tool: &str, args: &Value) -> Outcome {
let root = self.ctx.root.as_deref();
let rule = match Self::evaluate_in_root(&self.agent, tool, args, root) {
Decision::Allow => return Outcome::Allow,
Decision::Deny { rule } => {
return Outcome::Denied {
rule,
source: DenySource::Policy,
};
}
Decision::Ask { rule } => rule,
};
let subjects = subjects_for_in_root(tool, args, root);
if let Some(state) = &self.ctx.ask
&& state.is_remembered(tool, &subjects)
{
self.record_auto_allow(
tool,
&subjects,
&rule,
"allow_for_session",
REMEMBERED_SOURCE,
"permission: ask satisfied by a remembered session grant",
);
return Outcome::Allow;
}
if self.ctx.mode == PermissionMode::AllowAsks {
self.record_auto_allow(
tool,
&subjects,
&rule,
"allow_once",
ALLOW_ASKS_SOURCE,
"permission: ask auto-approved by allow-asks mode",
);
return Outcome::Allow;
}
let Some(state) = self.ctx.ask.clone().filter(|_| self.prompter_attached()) else {
return Outcome::Denied {
rule,
source: DenySource::Headless,
};
};
self.ask(&state, tool, &subjects, rule).await
}
fn prompter_attached(&self) -> bool {
self.ctx
.events
.as_ref()
.is_some_and(|events| events.prompter_attached(&self.ctx.session_id))
}
fn record_auto_allow(
&self,
tool: &str,
subjects: &[String],
rule: &str,
decision: &str,
source: &str,
reason: &'static str,
) {
let request_id = Uuid::new_v4().to_string();
let agent_name = self.agent.agent.name.as_str();
tracing::info!(
session_id = %self.ctx.session_id,
agent = %agent_name,
agent_id = %self.agent_id,
tool = %tool,
subject = %redact_subject(&subjects.join("\n")),
rule = %rule,
request_id = %request_id,
decision = %decision,
source = %source,
"{reason}"
);
if let Some(events) = &self.ctx.events {
events.permission_resolved(
&self.ctx.session_id,
&request_id,
agent_name,
&self.agent_id,
decision,
source,
);
}
}
async fn ask(
&self,
state: &Arc<SessionPermissions>,
tool: &str,
subjects: &[String],
rule: String,
) -> Outcome {
let request_id = Uuid::new_v4().to_string();
let rx = state.register(&request_id);
let agent_name = self.agent.agent.name.as_str();
if let Some(events) = &self.ctx.events {
events.permission_requested(
&self.ctx.session_id,
&request_id,
agent_name,
&self.agent_id,
tool,
&redact_subject(&subjects.join("\n")),
&rule,
);
}
let denied = |source| Outcome::Denied {
rule: rule.clone(),
source,
};
let (outcome, decision, source) = match tokio::time::timeout(self.ctx.timeout, rx).await {
Ok(Ok(PermissionDecision::AllowOnce)) => (Outcome::Allow, "allow_once", "client"),
Ok(Ok(PermissionDecision::AllowForSession { pattern })) => {
state.remember(tool, subjects, pattern.as_deref());
(Outcome::Allow, "allow_for_session", "client")
}
Ok(Ok(PermissionDecision::Deny)) => (denied(DenySource::Client), "deny", "client"),
Ok(Err(_)) | Err(_) => {
state.forget(&request_id);
(denied(DenySource::Timeout), "deny", "timeout")
}
};
if let Some(events) = &self.ctx.events {
events.permission_resolved(
&self.ctx.session_id,
&request_id,
agent_name,
&self.agent_id,
decision,
source,
);
}
outcome
}
}