use serde::{Deserialize, Serialize};
pub const OWNER_DECLINED: &str = "[OWNER DECLINED]";
pub const OWNER_UNANSWERED: &str = "[NO ANSWER]";
pub const EGRESS_BLOCKED: &str = "[EGRESS BLOCKED]";
pub const AUTHORITY_BLOCKED: &str = "[AUTHORITY BLOCKED]";
pub const UNTRUSTED_BLOCKED: &str = "[UNTRUSTED BLOCKED]";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum EffectClass {
Egress,
Delete,
Write,
Configuration,
Credential,
Process,
Call,
}
impl std::fmt::Display for EffectClass {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Egress => "egress",
Self::Delete => "delete",
Self::Write => "write",
Self::Configuration => "configuration",
Self::Credential => "credential",
Self::Process => "process",
Self::Call => "call",
})
}
}
impl EffectClass {
fn is_path(self) -> bool {
matches!(self, Self::Delete | Self::Write | Self::Configuration)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct EffectKey {
pub class: EffectClass,
pub target: String,
}
impl EffectKey {
pub fn path(class: EffectClass, raw: &str) -> Option<EffectKey> {
let (root, rest, separators): (String, &str, &[char]) = match raw.as_bytes() {
[b'/', ..] => (String::new(), raw, &['/']),
[drive, b':', b'\\' | b'/', ..] if drive.is_ascii_alphabetic() => (
format!("{}:", (*drive as char).to_ascii_uppercase()),
&raw[2..],
&['/', '\\'],
),
_ => return None,
};
let mut parts: Vec<&str> = Vec::new();
for part in rest.split(separators) {
match part {
"" | "." => {}
".." => {
parts.pop()?;
}
part => parts.push(part),
}
}
Some(EffectKey {
class,
target: format!("{root}/{}", parts.join("/")),
})
}
pub fn egress(scheme: &str, host: &str, port: Option<u16>) -> EffectKey {
let port = port.unwrap_or_else(|| match scheme.to_ascii_lowercase().as_str() {
"http" => 80,
"https" => 443,
"ssh" => 22,
_ => 0,
});
EffectKey {
class: EffectClass::Egress,
target: format!("{}:{port}", host.to_ascii_lowercase().trim_end_matches('.')),
}
}
pub fn named(class: EffectClass, name: &str) -> EffectKey {
EffectKey {
class,
target: name.to_string(),
}
}
pub fn overlaps(&self, other: &EffectKey) -> bool {
if self.class != other.class {
return false;
}
if self.target == other.target {
return true;
}
self.class.is_path()
&& (path_covers(&self.target, &other.target)
|| path_covers(&other.target, &self.target))
}
}
fn path_covers(outer: &str, inner: &str) -> bool {
let outer = outer.trim_end_matches('/');
let inner = inner.trim_end_matches('/');
if outer == inner {
return true;
}
inner
.strip_prefix(outer)
.is_some_and(|rest| rest.starts_with('/'))
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CallEffects {
pub keys: Vec<EffectKey>,
pub complete: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub understood: bool,
}
impl CallEffects {
pub fn unknown() -> Self {
Self {
keys: Vec::new(),
complete: false,
understood: false,
}
}
pub fn none() -> Self {
Self {
keys: Vec::new(),
complete: true,
understood: true,
}
}
pub fn from_access(
access: &crate::AccessManifest,
annotations: crate::ToolAnnotations,
) -> Self {
let mut keys: Vec<EffectKey> = Vec::new();
let mut push = |key: EffectKey| {
if !keys.contains(&key) {
keys.push(key);
}
};
if !annotations.read_only {
for path in &access.writes {
if let Some(key) = EffectKey::path(EffectClass::Write, path) {
if annotations.destructive {
push(EffectKey {
class: EffectClass::Delete,
target: key.target.clone(),
});
}
push(key);
}
}
for command in &access.commands {
if let Some(program) = program_name(command) {
push(EffectKey::named(EffectClass::Process, program));
}
}
}
for host in &access.hosts {
if let Some(key) = host_effect(host) {
push(key);
}
}
Self {
keys,
complete: false,
understood: false,
}
}
pub fn touches_no_paths(&self) -> bool {
self.complete && !self.keys.iter().any(|key| key.class.is_path())
}
}
fn program_name(command: &str) -> Option<&str> {
let first = command.split_whitespace().next()?;
let program = first.rsplit('/').next().unwrap_or(first);
(!program.is_empty()).then_some(program)
}
fn host_effect(declared: &str) -> Option<EffectKey> {
let declared = declared.trim();
let (scheme, rest) = match declared.split_once("://") {
Some((scheme, rest)) => (scheme, rest),
None => ("https", declared),
};
let authority = rest.split(['/', '?', '#']).next().unwrap_or(rest);
let authority = authority.rsplit('@').next().unwrap_or(authority);
let (host, port) = if let Some(bracketed) = authority.strip_prefix('[') {
let (host, after) = bracketed.split_once(']')?;
(host, after.strip_prefix(':').and_then(|p| p.parse().ok()))
} else {
match authority.rsplit_once(':') {
Some((host, port)) if !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) => {
(host, port.parse().ok())
}
_ => (authority, None),
}
};
if host.is_empty() {
return None;
}
Some(EffectKey::egress(scheme, host, port))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ApprovalRisk {
Low,
Medium,
High,
Critical,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OwnerApprovalRequest {
pub effects: Vec<EffectKey>,
pub summary: String,
pub subject: String,
pub risk: ApprovalRisk,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub warnings: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub card: Option<Box<ApprovalCard>>,
}
impl OwnerApprovalRequest {
pub fn for_call(call: &crate::ToolCall, info: &crate::ToolInfo, why: &str) -> Self {
Self::for_tool(&call.name, &call.arguments, info, why)
}
pub fn for_tool(
tool: &str,
arguments: &serde_json::Value,
info: &crate::ToolInfo,
why: &str,
) -> Self {
let subject = if arguments.is_null() {
tool.to_string()
} else {
format!("{tool} {arguments}")
};
let why = why.trim();
Self {
card: Some(Box::new(call_card(tool, arguments, info))),
effects: info.effects.keys.clone(),
summary: if why.is_empty() {
format!("Run {subject}")
} else {
format!("Run {subject}: {why}")
},
subject,
risk: if info.annotations.destructive {
ApprovalRisk::Critical
} else {
ApprovalRisk::High
},
warnings: Vec::new(),
}
}
}
fn call_card(tool: &str, arguments: &serde_json::Value, info: &crate::ToolInfo) -> ApprovalCard {
let text = |key: &str| arguments.get(key).and_then(serde_json::Value::as_str);
let action = match text("command").or_else(|| text("script")) {
Some(line) => CardAction::Command {
line: line.to_string(),
title: text("description")
.map(|title| title.split_whitespace().collect::<Vec<_>>().join(" "))
.filter(|title| !title.is_empty()),
looks_inside: Vec::new(),
},
None => CardAction::Use {
what: format!("use {}", tool.replace('_', " ")),
detail: (!arguments.is_null()).then(|| arguments.to_string()),
},
};
ApprovalCard {
impact: info.annotations.destructive.then(|| HighImpact::Deletes {
targets: Vec::new(),
}),
..ApprovalCard::new(action)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ApprovalCard {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub asked_by: Option<String>,
pub action: CardAction,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<AskReason>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub impact: Option<HighImpact>,
}
impl ApprovalCard {
pub fn new(action: CardAction) -> Self {
Self {
asked_by: None,
action,
reason: None,
impact: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind")]
#[non_exhaustive]
pub enum CardAction {
Command {
line: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
title: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
looks_inside: Vec<String>,
},
OpenLocalSite {
site: String,
once_minutes: u64,
},
ClickOnSite {
site: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
target: Option<String>,
},
Use {
what: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
detail: Option<String>,
},
TakeOver {
surface_id: String,
what: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
site: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
keeps_sign_in: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
open_url: Option<String>,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind")]
#[non_exhaustive]
pub enum AskReason {
ReadOutsideContent {
#[serde(default, skip_serializing_if = "Option::is_none")]
check_says: Option<String>,
},
AfterADecline {
#[serde(default, skip_serializing_if = "Option::is_none")]
declined: Option<String>,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind")]
#[non_exhaustive]
pub enum HighImpact {
Deletes {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
targets: Vec<String>,
},
Sends,
Spends,
WritesOutsideWorkArea,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum InterruptKind {
#[default]
Untrusted,
OwnerApproval(OwnerApprovalRequest),
}
#[derive(Clone, Default)]
pub struct SharedDeclines(std::sync::Arc<std::sync::Mutex<Vec<EffectKey>>>);
impl SharedDeclines {
pub fn new() -> Self {
Self::default()
}
fn lock(&self) -> std::sync::MutexGuard<'_, Vec<EffectKey>> {
self.0.lock().unwrap_or_else(|e| e.into_inner())
}
pub fn record(&self, effects: &[EffectKey]) {
let mut shared = self.lock();
for effect in effects {
if !shared.contains(effect) {
shared.push(effect.clone());
}
}
}
pub fn snapshot(&self) -> Vec<EffectKey> {
self.lock().clone()
}
pub(crate) fn exchange(&self, local: &mut Vec<EffectKey>) -> bool {
let mut shared = self.lock();
for effect in local.iter() {
if !shared.contains(effect) {
shared.push(effect.clone());
}
}
let before = local.len();
for effect in shared.iter() {
if !local.contains(effect) {
local.push(effect.clone());
}
}
local.len() > before
}
pub fn same_set(&self, other: &SharedDeclines) -> bool {
std::sync::Arc::ptr_eq(&self.0, &other.0)
}
}
impl PartialEq for SharedDeclines {
fn eq(&self, other: &Self) -> bool {
self.same_set(other)
}
}
impl std::fmt::Debug for SharedDeclines {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("SharedDeclines")
.field(&self.snapshot())
.finish()
}
}