use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use aidaemon_core::ChannelVisibility;
pub use aidaemon_core::UserRole;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum AttachmentProvenance {
#[default]
Inbound,
ToolObservation,
ToolArtifact,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct MessageAttachment {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resource_id: Option<String>,
pub local_path: String,
pub filename: String,
pub mime_type: String,
pub size_bytes: u64,
#[serde(default)]
pub provenance: AttachmentProvenance,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source_tool: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sha256: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub marked_up_from: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolRole {
Action,
Management,
Universal,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Offering {
Core,
Scoped,
#[default]
Deferred,
}
impl Offering {
pub fn always_sent(self) -> bool {
matches!(self, Self::Core | Self::Scoped)
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ToolDispatchFacts {
pub runs_as_judged: bool,
pub keeps_own_grants: bool,
pub shell_command_line: bool,
pub offering: Offering,
pub task_lead_delegation: bool,
pub same_tool_streak: SameToolStreak,
pub delivers_files: bool,
pub spawns_child_agents: bool,
pub requirement_checklist: bool,
pub opaque_execution: bool,
pub manages_own_timeout: bool,
pub records_launch_trust: bool,
pub goal_context: GoalContext,
pub network_reach: NetworkReach,
pub file_guard: FileGuard,
pub checkpoints_writes: bool,
pub needs_live_model: bool,
pub status_from_arguments: bool,
pub recap: RecapKind,
pub activity: ToolActivity,
pub status_label: Option<&'static str>,
pub project_dir_argument: ProjectDirArgument,
pub opens_project_instructions: bool,
pub result_fit: ResultFit,
pub channel_reach: ChannelReach,
pub evidence: EvidenceSource,
pub semantic_scope: Option<ToolSemanticScope>,
pub low_signal_result: bool,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum RecapKind {
#[default]
Other,
FileRead,
FileWrite,
Command,
FileSent,
Search,
ExternalRead,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ToolActivity {
#[default]
ByEffect,
Fixed(aidaemon_core::card::ActivityKind),
Memory,
}
impl ToolActivity {
pub fn kind(self, mutates: bool) -> aidaemon_core::card::ActivityKind {
use aidaemon_core::card::ActivityKind;
match self {
Self::Fixed(kind) => kind,
Self::Memory if mutates => ActivityKind::Remember,
Self::Memory => ActivityKind::Recall,
Self::ByEffect if mutates => ActivityKind::Change,
Self::ByEffect => ActivityKind::Check,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ProjectDirArgument {
#[default]
AnyPath,
SearchRoot,
WorkingDir,
ShellWorkingDir,
}
impl ProjectDirArgument {
pub const fn injected_key(self) -> Option<&'static str> {
match self {
Self::AnyPath => None,
Self::SearchRoot => Some("path"),
Self::WorkingDir | Self::ShellWorkingDir => Some("working_dir"),
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ResultFit {
pub preserve_inline: bool,
pub strip_control_markers: bool,
pub compact_json: bool,
pub cap_large_errors: bool,
pub pages_spilled_results: bool,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ChannelReach {
#[default]
Shared,
Public,
DirectOnly,
}
impl ChannelReach {
pub fn offered_in(self, visibility: ChannelVisibility) -> bool {
match self {
Self::Public => true,
Self::Shared => visibility != ChannelVisibility::PublicExternal,
Self::DirectOnly => matches!(
visibility,
ChannelVisibility::Private | ChannelVisibility::Internal
),
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum EvidenceSource {
#[default]
None,
GoalTrace,
Mandates,
GoalRecords,
ConversationHistory,
RemoteRead,
NodeReading,
NodeAction,
WebSearch,
FileRead,
FileSearch,
FileWrite,
Shell,
HostInfo,
Diagnostics,
}
impl EvidenceSource {
pub const MODELED: [Self; 14] = [
Self::GoalTrace,
Self::Mandates,
Self::GoalRecords,
Self::ConversationHistory,
Self::RemoteRead,
Self::NodeReading,
Self::NodeAction,
Self::WebSearch,
Self::FileRead,
Self::FileSearch,
Self::FileWrite,
Self::Shell,
Self::HostInfo,
Self::Diagnostics,
];
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum FileGuard {
#[default]
None,
Reads,
SensitiveReads,
Writes,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum NetworkReach {
#[default]
Any,
PublicAndLoopback,
PublicOnly,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum GoalContext {
#[default]
None,
Goal,
BackgroundDelivery,
MandateRun,
}
pub use aidaemon_core::SameToolStreak;
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub struct ToolCapabilities {
pub read_only: bool,
pub external_side_effect: bool,
pub needs_approval: bool,
pub idempotent: bool,
pub high_impact_write: bool,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
pub enum ToolCallEffect {
#[default]
Unknown,
Administrative,
Observation,
Mutation,
ObservationAndMutation,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(transparent)]
pub struct ToolMutationEffects(u32);
impl ToolMutationEffects {
pub const PROTOCOL_NAMES: [&str; 13] = [
"local_source_write",
"local_workspace_write",
"local_derived_write",
"repository_write",
"remote_mutation",
"remote_deploy",
"external_delivery",
"process_state",
"configuration",
"destructive",
"unspecified",
"scheduled_work",
"memory_write",
];
pub const NONE: Self = Self(0);
pub const LOCAL_SOURCE_WRITE: Self = Self(1 << 0);
pub const LOCAL_WORKSPACE_WRITE: Self = Self(1 << 1);
pub const LOCAL_DERIVED_WRITE: Self = Self(1 << 2);
pub const REPOSITORY_WRITE: Self = Self(1 << 3);
pub const REMOTE_MUTATION: Self = Self(1 << 4);
pub const REMOTE_DEPLOY: Self = Self(1 << 5);
pub const EXTERNAL_DELIVERY: Self = Self(1 << 6);
pub const PROCESS_STATE: Self = Self(1 << 7);
pub const CONFIGURATION: Self = Self(1 << 8);
pub const DESTRUCTIVE: Self = Self(1 << 9);
pub const UNSPECIFIED: Self = Self(1 << 10);
pub const SCHEDULED_WORK: Self = Self(1 << 11);
pub const MEMORY_WRITE: Self = Self(1 << 12);
pub const fn bits(self) -> u32 {
self.0
}
pub const fn from_bits(bits: u32) -> Self {
Self(bits)
}
pub fn protocol_names(self) -> Vec<&'static str> {
[
(Self::LOCAL_SOURCE_WRITE, "local_source_write"),
(Self::LOCAL_WORKSPACE_WRITE, "local_workspace_write"),
(Self::LOCAL_DERIVED_WRITE, "local_derived_write"),
(Self::REPOSITORY_WRITE, "repository_write"),
(Self::REMOTE_MUTATION, "remote_mutation"),
(Self::REMOTE_DEPLOY, "remote_deploy"),
(Self::EXTERNAL_DELIVERY, "external_delivery"),
(Self::PROCESS_STATE, "process_state"),
(Self::CONFIGURATION, "configuration"),
(Self::DESTRUCTIVE, "destructive"),
(Self::UNSPECIFIED, "unspecified"),
(Self::SCHEDULED_WORK, "scheduled_work"),
(Self::MEMORY_WRITE, "memory_write"),
]
.into_iter()
.filter_map(|(effect, name)| self.intersects(effect).then_some(name))
.collect()
}
pub fn telemetry_value(self) -> serde_json::Value {
let known_bits = Self::MEMORY_WRITE.bits()
| Self::SCHEDULED_WORK.bits()
| Self::UNSPECIFIED.bits()
| ((1 << 10) - 1);
serde_json::json!({
"bits": self.bits(),
"names": self.protocol_names(),
"unknown_bits": self.bits() & !known_bits,
})
}
pub const fn union(self, other: Self) -> Self {
Self(self.0 | other.0)
}
pub const fn intersect(self, other: Self) -> Self {
Self(self.0 & other.0)
}
pub fn from_protocol_name(name: &str) -> Option<Self> {
match name {
"local_source_write" => Some(Self::LOCAL_SOURCE_WRITE),
"local_workspace_write" => Some(Self::LOCAL_WORKSPACE_WRITE),
"local_derived_write" => Some(Self::LOCAL_DERIVED_WRITE),
"repository_write" => Some(Self::REPOSITORY_WRITE),
"remote_mutation" => Some(Self::REMOTE_MUTATION),
"remote_deploy" => Some(Self::REMOTE_DEPLOY),
"external_delivery" => Some(Self::EXTERNAL_DELIVERY),
"process_state" => Some(Self::PROCESS_STATE),
"configuration" => Some(Self::CONFIGURATION),
"destructive" => Some(Self::DESTRUCTIVE),
"unspecified" => Some(Self::UNSPECIFIED),
"scheduled_work" => Some(Self::SCHEDULED_WORK),
"memory_write" => Some(Self::MEMORY_WRITE),
_ => None,
}
}
pub const fn is_empty(&self) -> bool {
self.0 == 0
}
pub const fn contains(self, other: Self) -> bool {
(self.0 & other.0) == other.0
}
pub const fn intersects(self, other: Self) -> bool {
(self.0 & other.0) != 0
}
pub const fn has_specific_effects(self) -> bool {
(self.0 & !Self::UNSPECIFIED.0) != 0
}
pub const fn satisfies(self, required: Self) -> bool {
if required.is_empty() {
return true;
}
let generic_required = required.intersects(Self::UNSPECIFIED);
let generic_satisfied = !generic_required || !self.is_empty();
let specific_required = Self(required.0 & !Self::UNSPECIFIED.0);
let widened = if self.intersects(Self::LOCAL_SOURCE_WRITE)
|| self.intersects(Self::LOCAL_DERIVED_WRITE)
|| self.intersects(Self::LOCAL_WORKSPACE_WRITE)
{
Self(self.0 | Self::LOCAL_WORKSPACE_WRITE.0 | Self::LOCAL_DERIVED_WRITE.0)
} else {
self
};
let widened = if widened.intersects(Self::SCHEDULED_WORK) {
Self(widened.0 | Self::CONFIGURATION.0 | Self::PROCESS_STATE.0)
} else {
widened
};
let widened = if widened.intersects(Self::MEMORY_WRITE) {
Self(widened.0 | Self::LOCAL_DERIVED_WRITE.0)
} else {
widened
};
generic_satisfied && widened.contains(specific_required)
}
}
impl ToolCallEffect {
pub fn observes_state(self) -> bool {
matches!(self, Self::Observation | Self::ObservationAndMutation)
}
pub fn mutates_state(self) -> bool {
matches!(self, Self::Mutation | Self::ObservationAndMutation)
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
pub enum ToolVerificationMode {
#[default]
None,
ResultContent,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum ToolTargetHintKind {
Url,
Path,
ProjectScope,
ResourceId,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ToolTargetHint {
pub kind: ToolTargetHintKind,
pub value: String,
}
impl ToolTargetHint {
pub fn new(kind: ToolTargetHintKind, value: impl Into<String>) -> Option<Self> {
let value = value.into().trim().to_string();
if value.is_empty() {
None
} else {
Some(Self { kind, value })
}
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum ToolSemanticScope {
GoalState,
UserMemory,
ConversationHistory,
ExternalRemote,
LocalWorkspace,
HostLocal,
}
impl ToolSemanticScope {
pub const fn as_str(self) -> &'static str {
match self {
Self::GoalState => "goal_state",
Self::UserMemory => "user_memory",
Self::ConversationHistory => "conversation_history",
Self::ExternalRemote => "external_remote",
Self::LocalWorkspace => "local_workspace",
Self::HostLocal => "host_local",
}
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum EvidencePurpose {
CurrentState,
HistoricalRecord,
Content,
Outcome,
Attribution,
CausalExplanation,
}
impl EvidencePurpose {
pub const fn as_str(self) -> &'static str {
match self {
Self::CurrentState => "current_state",
Self::HistoricalRecord => "historical_record",
Self::Content => "content",
Self::Outcome => "outcome",
Self::Attribution => "attribution",
Self::CausalExplanation => "causal_explanation",
}
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum EvidenceAuthority {
Advisory,
Direct,
Canonical,
}
impl EvidenceAuthority {
const fn rank(self) -> u8 {
match self {
Self::Advisory => 0,
Self::Direct => 1,
Self::Canonical => 2,
}
}
pub const fn satisfies(self, required: Self) -> bool {
self.rank() >= required.rank()
}
pub const fn as_str(self) -> &'static str {
match self {
Self::Advisory => "advisory",
Self::Direct => "direct",
Self::Canonical => "canonical",
}
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum EvidenceTemporalScope {
Current,
Historical,
Both,
}
impl EvidenceTemporalScope {
pub const fn satisfies(self, required: Self) -> bool {
matches!(required, Self::Both) && matches!(self, Self::Both)
|| matches!(required, Self::Current) && matches!(self, Self::Current | Self::Both)
|| matches!(required, Self::Historical) && matches!(self, Self::Historical | Self::Both)
}
pub const fn as_str(self) -> &'static str {
match self {
Self::Current => "current",
Self::Historical => "historical",
Self::Both => "both",
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ToolEvidenceCapability {
pub scope: ToolSemanticScope,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub purposes: Vec<EvidencePurpose>,
pub authority: EvidenceAuthority,
pub temporal_scope: EvidenceTemporalScope,
}
impl ToolEvidenceCapability {
pub fn new(
scope: ToolSemanticScope,
purposes: &[EvidencePurpose],
authority: EvidenceAuthority,
temporal_scope: EvidenceTemporalScope,
) -> Self {
Self {
scope,
purposes: purposes.to_vec(),
authority,
temporal_scope,
}
}
}
#[allow(dead_code)]
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum ToolSemanticFacet {
GoalState,
Schedule,
RunState,
Recovery,
Control,
Measurement,
Authorization,
Ownership,
}
impl ToolSemanticFacet {
pub const PROTOCOL_NAMES: [&'static str; 8] = [
Self::GoalState.as_str(),
Self::Schedule.as_str(),
Self::RunState.as_str(),
Self::Recovery.as_str(),
Self::Control.as_str(),
Self::Measurement.as_str(),
Self::Authorization.as_str(),
Self::Ownership.as_str(),
];
pub const fn as_str(self) -> &'static str {
match self {
Self::GoalState => "goal_state",
Self::Schedule => "schedule",
Self::RunState => "run_state",
Self::Recovery => "recovery",
Self::Control => "control",
Self::Measurement => "measurement",
Self::Authorization => "authorization",
Self::Ownership => "ownership",
}
}
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum ToolCollectionCompleteness {
#[default]
Unknown,
Partial,
Complete,
}
impl ToolCollectionCompleteness {
pub const fn satisfies(self, required: Self) -> bool {
matches!(required, Self::Unknown)
|| matches!(required, Self::Partial) && matches!(self, Self::Partial | Self::Complete)
|| matches!(required, Self::Complete) && matches!(self, Self::Complete)
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ToolObservationEvidence {
pub subject: ToolTargetHint,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub facets: Vec<ToolSemanticFacet>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub source_collections: Vec<ToolTargetHint>,
}
impl ToolObservationEvidence {
pub fn new(subject: ToolTargetHint, facets: &[ToolSemanticFacet]) -> Self {
Self {
subject,
facets: facets.to_vec(),
source_collections: Vec::new(),
}
}
pub fn with_source_collection(mut self, collection: ToolTargetHint) -> Self {
if !self.source_collections.contains(&collection) {
self.source_collections.push(collection);
}
self
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ToolCollectionObservation {
pub collection: ToolTargetHint,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub facets: Vec<ToolSemanticFacet>,
#[serde(default)]
pub completeness: ToolCollectionCompleteness,
#[serde(default)]
pub returned_count: usize,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub total_count: Option<usize>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub members: Vec<ToolTargetHint>,
}
impl ToolCollectionObservation {
pub fn complete(
collection: ToolTargetHint,
facets: &[ToolSemanticFacet],
members: Vec<ToolTargetHint>,
) -> Self {
let returned_count = members.len();
Self {
collection,
facets: facets.to_vec(),
completeness: ToolCollectionCompleteness::Complete,
returned_count,
total_count: Some(returned_count),
members,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct StableObservationSubject {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resource_id: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub facets: Vec<ToolSemanticFacet>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub member_namespaces: Vec<String>,
pub summary: String,
}
impl StableObservationSubject {
pub fn collection(
resource_id: impl Into<String>,
facets: &[ToolSemanticFacet],
member_namespace: impl Into<String>,
summary: impl Into<String>,
) -> Self {
Self {
resource_id: Some(resource_id.into()),
facets: facets.to_vec(),
member_namespaces: vec![member_namespace.into()],
summary: summary.into(),
}
}
pub fn namespace(prefix: impl Into<String>, summary: impl Into<String>) -> Self {
Self {
resource_id: None,
facets: Vec::new(),
member_namespaces: vec![prefix.into()],
summary: summary.into(),
}
}
pub fn binds(&self, value: &str) -> bool {
self.resource_id.as_deref() == Some(value)
|| self
.member_namespaces
.iter()
.any(|prefix| value.len() > prefix.len() && value.starts_with(prefix.as_str()))
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "UPPERCASE")]
pub enum ToolCallOperation {
Get,
Head,
Options,
Post,
Put,
Patch,
Delete,
}
impl ToolCallOperation {
pub const fn from_http_method(method: &str) -> Option<Self> {
match method.as_bytes() {
b"GET" => Some(Self::Get),
b"HEAD" => Some(Self::Head),
b"OPTIONS" => Some(Self::Options),
b"POST" => Some(Self::Post),
b"PUT" => Some(Self::Put),
b"PATCH" => Some(Self::Patch),
b"DELETE" => Some(Self::Delete),
_ => None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct ToolCallSemantics {
#[serde(default)]
pub effect: ToolCallEffect,
#[serde(default)]
pub verification_mode: ToolVerificationMode,
#[serde(default, skip_serializing_if = "ToolMutationEffects::is_empty")]
pub mutation_effects: ToolMutationEffects,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub target_hints: Vec<ToolTargetHint>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<ToolCallOperation>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub evidence: Vec<ToolEvidenceCapability>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct ToolCallAccessManifest {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub execution_cwd: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub read_targets: Vec<ToolTargetHint>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub write_targets: Vec<ToolTargetHint>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub adapter_read_targets: Vec<ToolTargetHint>,
}
impl ToolCallSemantics {
pub fn with_untyped_change(&self) -> Self {
let mut changed = self.clone();
changed.mutation_effects = changed
.mutation_effects
.union(ToolMutationEffects::UNSPECIFIED);
changed.effect = if changed.observes_state() {
ToolCallEffect::ObservationAndMutation
} else {
ToolCallEffect::Mutation
};
changed
}
pub fn administrative() -> Self {
Self {
effect: ToolCallEffect::Administrative,
..Self::default()
}
}
pub fn observation() -> Self {
Self {
effect: ToolCallEffect::Observation,
..Self::default()
}
}
pub fn constrained_to_observation(mut self) -> Self {
self.effect = ToolCallEffect::Observation;
self.mutation_effects = ToolMutationEffects::NONE;
self
}
pub fn mutation() -> Self {
Self {
effect: ToolCallEffect::Mutation,
mutation_effects: ToolMutationEffects::UNSPECIFIED,
..Self::default()
}
}
pub fn observation_and_mutation() -> Self {
Self {
effect: ToolCallEffect::ObservationAndMutation,
mutation_effects: ToolMutationEffects::UNSPECIFIED,
..Self::default()
}
}
pub fn mutation_with(mutation_effects: ToolMutationEffects) -> Self {
Self {
effect: ToolCallEffect::Mutation,
mutation_effects: if mutation_effects.is_empty() {
ToolMutationEffects::UNSPECIFIED
} else {
mutation_effects
},
..Self::default()
}
}
pub fn observation_and_mutation_with(mutation_effects: ToolMutationEffects) -> Self {
Self {
effect: ToolCallEffect::ObservationAndMutation,
mutation_effects: if mutation_effects.is_empty() {
ToolMutationEffects::UNSPECIFIED
} else {
mutation_effects
},
..Self::default()
}
}
pub fn with_verification_mode(mut self, verification_mode: ToolVerificationMode) -> Self {
self.verification_mode = verification_mode;
self
}
pub fn with_target_hint(mut self, kind: ToolTargetHintKind, value: impl Into<String>) -> Self {
if let Some(target) = ToolTargetHint::new(kind, value) {
self.target_hints.push(target);
}
self
}
pub fn with_operation(mut self, operation: ToolCallOperation) -> Self {
self.operation = Some(operation);
self
}
pub fn with_evidence(mut self, evidence: Vec<ToolEvidenceCapability>) -> Self {
self.evidence = evidence;
self
}
pub fn observes_state(&self) -> bool {
self.effect.observes_state()
}
pub fn mutates_state(&self) -> bool {
self.effect.mutates_state() || !self.mutation_effects.is_empty()
}
pub fn can_verify_with_result_content(&self) -> bool {
self.verification_mode == ToolVerificationMode::ResultContent
}
pub fn is_empty(&self) -> bool {
self.effect == ToolCallEffect::Unknown
&& self.verification_mode == ToolVerificationMode::None
&& self.mutation_effects.is_empty()
&& self.target_hints.is_empty()
&& self.operation.is_none()
&& self.evidence.is_empty()
}
pub fn merge_missing_from(&mut self, fallback: Self) {
if self.effect == ToolCallEffect::Unknown {
self.effect = fallback.effect;
}
if self.verification_mode == ToolVerificationMode::None {
self.verification_mode = fallback.verification_mode;
}
if self.mutation_effects.is_empty()
&& (self.effect == ToolCallEffect::Unknown || self.effect.mutates_state())
{
self.mutation_effects = fallback.mutation_effects;
}
if self.target_hints.is_empty() {
self.target_hints = fallback.target_hints;
}
if self.operation.is_none() {
self.operation = fallback.operation;
}
if self.evidence.is_empty() {
self.evidence = fallback.evidence;
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ReadFileSelectionMetadata {
Full,
BoundedRange { start_line: usize, end_line: usize },
OpenEndedRange { start_line: usize },
Tail { requested_lines: usize },
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ReadFileResultMetadata {
pub display_path: String,
pub canonical_path: String,
pub selection: ReadFileSelectionMetadata,
pub returned_start_line: Option<usize>,
pub returned_end_line: Option<usize>,
pub total_lines: usize,
pub file_size: u64,
#[serde(skip_serializing_if = "Option::is_none")]
pub modified: Option<String>,
pub selected_lines: Vec<String>,
#[serde(default)]
pub truncated: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TruncationInfo {
pub shown_chars: usize,
pub total_chars: usize,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub remediation_hint: Option<String>,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum ToolResultCompleteness {
Complete,
Truncated,
#[default]
Unavailable,
}
impl ToolResultCompleteness {
pub const fn as_str(self) -> &'static str {
match self {
Self::Complete => "complete",
Self::Truncated => "truncated",
Self::Unavailable => "unavailable",
}
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum ToolResultContentSource {
ToolOutput,
DurableReplay,
SpillPreview,
PersistentSummary,
#[default]
Unavailable,
}
impl ToolResultContentSource {
pub const fn as_str(self) -> &'static str {
match self {
Self::ToolOutput => "tool_output",
Self::DurableReplay => "durable_replay",
Self::SpillPreview => "spill_preview",
Self::PersistentSummary => "persistent_summary",
Self::Unavailable => "unavailable",
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct ToolResultProvenance {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub result_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sha256: Option<String>,
#[serde(default)]
pub source: ToolResultContentSource,
#[serde(default)]
pub model_view_completeness: ToolResultCompleteness,
#[serde(default)]
pub durable_view_completeness: ToolResultCompleteness,
#[serde(default)]
pub authoritative_chars: usize,
#[serde(default)]
pub model_visible_chars: usize,
#[serde(default)]
pub durable_chars: usize,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub requested_range: Option<ReadFileSelectionMetadata>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub returned_start_line: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub returned_end_line: Option<usize>,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum AuthorizationPreflightStatus {
Ready,
Blocked,
Unverifiable,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct AuthorizationPreflightRecord {
pub schema_version: u16,
pub status: AuthorizationPreflightStatus,
pub intended_operation: String,
pub target_digest: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub auth_profile: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub account_id: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub authorized_scopes: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub credential_generation: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub refresh_result: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason_code: Option<String>,
pub checked_at: String,
}
impl AuthorizationPreflightRecord {
pub const SCHEMA_VERSION: u16 = 1;
pub const fn permits_io(&self) -> bool {
matches!(self.status, AuthorizationPreflightStatus::Ready)
}
}
impl ToolResultProvenance {
pub fn from_authoritative_result(
result: &str,
metadata: &ToolCallMetadata,
source: ToolResultContentSource,
) -> Self {
use sha2::{Digest, Sha256};
let sha256 = hex::encode(Sha256::digest(result.as_bytes()));
let chars = result.chars().count();
let tool_truncated = metadata.truncation.is_some()
|| metadata
.read_file
.as_ref()
.is_some_and(|read| read.truncated);
let completeness = if tool_truncated {
ToolResultCompleteness::Truncated
} else {
ToolResultCompleteness::Complete
};
let read = metadata.read_file.as_ref();
Self {
result_id: Some(format!("sha256:{sha256}")),
sha256: Some(sha256),
source,
model_view_completeness: completeness,
durable_view_completeness: completeness,
authoritative_chars: chars,
model_visible_chars: chars,
durable_chars: chars,
requested_range: read.map(|read| read.selection.clone()),
returned_start_line: read.and_then(|read| read.returned_start_line),
returned_end_line: read.and_then(|read| read.returned_end_line),
}
}
pub fn mark_model_view_truncated(&mut self, visible_result: &str) {
self.model_visible_chars = visible_result.chars().count();
self.model_view_completeness = ToolResultCompleteness::Truncated;
}
pub fn record_durable_view(&mut self, durable_result: &str, is_summary: bool) {
self.durable_chars = durable_result.chars().count();
if is_summary {
self.durable_view_completeness = ToolResultCompleteness::Truncated;
self.source = ToolResultContentSource::PersistentSummary;
} else {
self.durable_view_completeness = self.model_view_completeness;
}
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ToolOutcomeStatus {
Succeeded,
CompletedWithNegativeResult,
FailedRetryable,
FailedPermanent,
Blocked,
Backgrounded,
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ToolInvocationStage {
#[default]
Unknown,
RejectedBeforeDispatch,
RejectedBeforeIo,
Dispatched,
Replayed,
}
impl ToolInvocationStage {
pub const fn as_str(self) -> &'static str {
match self {
Self::Unknown => "unknown",
Self::RejectedBeforeDispatch => "rejected_before_dispatch",
Self::RejectedBeforeIo => "rejected_before_io",
Self::Dispatched => "dispatched",
Self::Replayed => "replayed",
}
}
pub const fn reached_dispatch(self) -> bool {
matches!(self, Self::Dispatched | Self::Replayed)
}
pub const fn performed_io(self) -> bool {
matches!(self, Self::Dispatched)
}
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ToolReceiptKind {
#[default]
Generic,
Process,
Http,
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ToolAccessEnforcement {
#[default]
Unknown,
NotApplicable,
AdapterEnforced,
ControllerEnforced,
KernelEnforced,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ToolAccessDenial {
pub reason_code: String,
pub enforcement: ToolAccessEnforcement,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exit_code: Option<i32>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub proposed_evidence: Vec<ToolEvidenceCapability>,
}
impl ToolOutcomeStatus {
pub const fn from_process_exit_code(code: i32) -> Self {
if code == 0 {
Self::Succeeded
} else if code > 0 {
Self::CompletedWithNegativeResult
} else {
Self::FailedPermanent
}
}
pub const fn as_str(self) -> &'static str {
match self {
Self::Succeeded => "succeeded",
Self::CompletedWithNegativeResult => "completed_with_negative_result",
Self::FailedRetryable => "failed_retryable",
Self::FailedPermanent => "failed_permanent",
Self::Blocked => "blocked",
Self::Backgrounded => "backgrounded",
}
}
pub fn satisfies_requested_condition(self) -> bool {
matches!(self, Self::Succeeded)
}
pub fn is_failure(self) -> bool {
matches!(
self,
Self::FailedRetryable | Self::FailedPermanent | Self::Blocked
)
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ToolResultPresentation {
NaturalSummary,
DiagnosticDetail,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct ToolCallMetadata {
#[serde(default)]
pub receipt_kind: ToolReceiptKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub access_manifest: Option<ToolCallAccessManifest>,
#[serde(default)]
pub access_enforcement: ToolAccessEnforcement,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub access_denial: Option<ToolAccessDenial>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub outcome_status: Option<ToolOutcomeStatus>,
#[serde(default)]
pub invocation_stage: ToolInvocationStage,
#[serde(default)]
pub contract_rejected: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub effective_tool_name: Option<String>,
#[serde(default)]
pub receipt_replayed: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub exit_code: Option<i32>,
#[serde(default)]
pub timed_out: bool,
#[serde(default)]
pub background_started: bool,
#[serde(default)]
pub detached: bool,
#[serde(default)]
pub completion_notifications_enabled: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub transport_error: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub http_status: Option<u16>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub truncation: Option<TruncationInfo>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub result_provenance: Option<ToolResultProvenance>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub authorization_preflight: Option<AuthorizationPreflightRecord>,
#[serde(default)]
pub background_handoff: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub background_settled: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub background_run_labels: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub checklist_items: Vec<usize>,
#[serde(default, skip_serializing_if = "is_zero")]
pub launched_runs: usize,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub changes_untyped: bool,
#[serde(default, skip_serializing_if = "ToolCallSemantics::is_empty")]
pub semantics: ToolCallSemantics,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub observations: Vec<ToolObservationEvidence>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub collection_observations: Vec<ToolCollectionObservation>,
#[serde(skip_serializing_if = "Option::is_none")]
pub read_file: Option<ReadFileResultMetadata>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub attachments: Vec<MessageAttachment>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub runtime_preparation_failure: Option<Box<RuntimePreparationFailure>>,
#[serde(default)]
pub untrusted_verbatim: bool,
#[serde(default)]
pub preserve_inline: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub persistent_output: Option<String>,
#[serde(default)]
pub suppress_activity_result: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub presentation: Option<ToolResultPresentation>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub internal_identifiers: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub output_trust: Option<aidaemon_core::SourceTrust>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ToolCallOutcome {
pub output: String,
#[serde(default)]
pub metadata: ToolCallMetadata,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub finish: Option<aidaemon_core::Finish>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct RuntimePreparationFailure {
pub field: String,
pub value: String,
pub error: String,
}
impl ToolCallOutcome {
pub fn from_output(output: String) -> Self {
Self {
output,
metadata: ToolCallMetadata::default(),
finish: None,
}
}
pub fn contract_rejection(output: impl Into<String>) -> Self {
Self {
output: output.into(),
metadata: ToolCallMetadata {
outcome_status: Some(ToolOutcomeStatus::Blocked),
invocation_stage: ToolInvocationStage::RejectedBeforeIo,
contract_rejected: true,
semantics: ToolCallSemantics::observation()
.with_verification_mode(ToolVerificationMode::ResultContent),
..ToolCallMetadata::default()
},
finish: None,
}
}
pub fn blocked(output: impl Into<String>) -> Self {
Self {
output: output.into(),
metadata: ToolCallMetadata {
outcome_status: Some(ToolOutcomeStatus::Blocked),
..ToolCallMetadata::default()
},
finish: None,
}
}
pub fn runtime_preparation_failure(
field: impl Into<String>,
value: impl Into<String>,
error: impl std::fmt::Display,
) -> Self {
let field = field.into();
let value = value.into();
let error = error.to_string();
Self {
output: format!(
"Error: the runtime could not prepare `{field}` entry `{value}` before running the command: {error}"
),
metadata: ToolCallMetadata {
outcome_status: Some(ToolOutcomeStatus::Blocked),
invocation_stage: ToolInvocationStage::RejectedBeforeIo,
semantics: ToolCallSemantics::observation()
.with_verification_mode(ToolVerificationMode::ResultContent),
runtime_preparation_failure: Some(Box::new(RuntimePreparationFailure {
field,
value,
error,
})),
..ToolCallMetadata::default()
},
finish: None,
}
}
pub fn completed_negative_result(output: impl Into<String>) -> Self {
Self {
output: output.into(),
metadata: ToolCallMetadata {
outcome_status: Some(ToolOutcomeStatus::CompletedWithNegativeResult),
..ToolCallMetadata::default()
},
finish: None,
}
}
pub fn with_finish(mut self, finish: aidaemon_core::Finish) -> Self {
self.finish = Some(finish);
self
}
pub fn handed_to_background(mut self) -> Self {
self.metadata.background_handoff = true;
self.finish = Some(aidaemon_core::Finish::new(
aidaemon_core::FinishOutcome::Partial,
None,
));
self
}
pub fn with_semantics(mut self, semantics: ToolCallSemantics) -> Self {
self.metadata.semantics = semantics;
self
}
pub fn with_observation_evidence(
mut self,
observations: Vec<ToolObservationEvidence>,
collection_observations: Vec<ToolCollectionObservation>,
) -> Self {
self.metadata.observations = observations;
self.metadata.collection_observations = collection_observations;
self
}
}
impl Default for ToolCapabilities {
fn default() -> Self {
Self {
read_only: false,
external_side_effect: false,
needs_approval: true,
idempotent: false,
high_impact_write: false,
}
}
}
fn string_to_target_hint(key: &str, value: &str) -> Option<ToolTargetHint> {
let trimmed = value.trim();
if trimmed.is_empty() {
return None;
}
let lower_key = key.to_ascii_lowercase();
if lower_key == "resource_id" {
return ToolTargetHint::new(ToolTargetHintKind::ResourceId, trimmed);
}
if matches!(
lower_key.as_str(),
"url" | "verify_url" | "callback_url" | "target_url" | "auth_url"
) || trimmed.starts_with("http://")
|| trimmed.starts_with("https://")
{
return ToolTargetHint::new(ToolTargetHintKind::Url, trimmed);
}
if matches!(
lower_key.as_str(),
"path"
| "file_path"
| "working_dir"
| "cwd"
| "directory"
| "dir"
| "repo_path"
| "repo_dir"
| "resource_path"
) {
return ToolTargetHint::new(ToolTargetHintKind::Path, trimmed);
}
if matches!(
lower_key.as_str(),
"project_path" | "project_dir" | "scope" | "project_scope"
) {
return ToolTargetHint::new(ToolTargetHintKind::ProjectScope, trimmed);
}
None
}
fn push_unique_target_hint(hints: &mut Vec<ToolTargetHint>, candidate: Option<ToolTargetHint>) {
let Some(candidate) = candidate else {
return;
};
if !hints.iter().any(|existing| existing == &candidate) {
hints.push(candidate);
}
}
fn collect_common_target_hints(arguments: &str) -> Vec<ToolTargetHint> {
let parsed = match serde_json::from_str::<Value>(arguments) {
Ok(Value::Object(map)) => map,
_ => return Vec::new(),
};
let mut hints = Vec::new();
for (key, value) in &parsed {
match value {
Value::String(s) => push_unique_target_hint(&mut hints, string_to_target_hint(key, s)),
Value::Array(items) if matches!(key.as_str(), "paths" | "urls") => {
for item in items.iter().filter_map(|item| item.as_str()) {
push_unique_target_hint(&mut hints, string_to_target_hint(key, item));
}
}
_ => {}
}
}
hints
}
fn default_access_manifest(
arguments: &str,
semantics: &ToolCallSemantics,
) -> ToolCallAccessManifest {
let parsed = serde_json::from_str::<Value>(arguments).ok();
let execution_cwd = parsed.as_ref().and_then(|value| {
value
.get("working_dir")
.or_else(|| value.get("cwd"))
.and_then(Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.map(str::to_string)
});
let targets = if semantics.target_hints.is_empty() {
collect_common_target_hints(arguments)
} else {
semantics.target_hints.clone()
};
let non_cwd_targets = targets
.into_iter()
.filter(|target| {
matches!(
target.kind,
ToolTargetHintKind::Path | ToolTargetHintKind::ProjectScope
)
})
.filter(|target| execution_cwd.as_deref() != Some(target.value.as_str()))
.collect::<Vec<_>>();
let mut read_targets = Vec::new();
if let Some(cwd) = execution_cwd.as_deref()
&& let Some(target) = ToolTargetHint::new(ToolTargetHintKind::ProjectScope, cwd)
{
read_targets.push(target);
}
if semantics.observes_state() {
read_targets.extend(non_cwd_targets.iter().cloned());
}
let write_targets = if semantics.mutates_state() {
non_cwd_targets
} else {
Vec::new()
};
ToolCallAccessManifest {
execution_cwd,
read_targets,
write_targets,
adapter_read_targets: Vec::new(),
}
}
pub fn semantics_for_exact_read_actions(
arguments: &str,
read_actions: &[&str],
mutation_effects: ToolMutationEffects,
) -> ToolCallSemantics {
let action = serde_json::from_str::<Value>(arguments)
.ok()
.and_then(|value| {
value
.get("action")
.and_then(Value::as_str)
.map(str::to_string)
});
let mut semantics = if action
.as_deref()
.is_some_and(|action| read_actions.contains(&action))
{
ToolCallSemantics::observation().with_verification_mode(ToolVerificationMode::ResultContent)
} else if mutation_effects.is_empty() {
ToolCallSemantics::mutation()
} else {
ToolCallSemantics::mutation_with(mutation_effects)
};
for target_hint in collect_common_target_hints(arguments) {
semantics = semantics.with_target_hint(target_hint.kind, target_hint.value);
}
semantics
}
fn default_semantics_from_identity(arguments: &str, caps: ToolCapabilities) -> ToolCallSemantics {
let mut semantics = if caps.read_only {
ToolCallSemantics::observation().with_verification_mode(ToolVerificationMode::ResultContent)
} else {
ToolCallSemantics::mutation()
};
for target_hint in collect_common_target_hints(arguments) {
semantics = semantics.with_target_hint(target_hint.kind, target_hint.value);
}
semantics
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ApprovalScope {
Call,
Request { method: String, url: String },
}
#[derive(Debug, Clone, Copy)]
pub struct ApprovalCall<'a> {
pub arguments: &'a Value,
pub as_sent: &'a Value,
pub refused: bool,
}
impl<'a> ApprovalCall<'a> {
pub fn as_sent(arguments: &'a Value) -> Self {
Self {
arguments,
as_sent: arguments,
refused: false,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum OwnerApprovalNeed {
Unjudged,
NotNeeded,
Ask(aidaemon_core::OwnerApprovalRequest),
}
#[derive(Clone, Default)]
pub struct ToolCallContext {
pub mandate_preapproved: bool,
pub mandate_execution: bool,
pub mutation_forbidden: bool,
pub kernel_approved: Option<ApprovalScope>,
pub trusted_session: bool,
pub user_role: Option<UserRole>,
pub untrusted_source: bool,
pub scope_escalation: Option<ScopeEscalation>,
pub session_id: String,
pub grant_session: String,
pub channel_visibility: Option<ChannelVisibility>,
pub channel_id: Option<String>,
pub task_id: Option<String>,
pub tool_call_id: Option<String>,
pub lone_root_call: bool,
pub turn_id: Option<String>,
pub goal_id: Option<String>,
pub goal_run_id: Option<String>,
pub task_attempt_id: Option<String>,
pub mandate_id: Option<String>,
pub mandate_version: Option<i64>,
pub project_scope: Option<String>,
pub project: Option<aidaemon_core::ProjectRef>,
pub workspace_collaboration_root: Option<String>,
pub trust_roots: Option<Vec<String>>,
pub trust_cwd: Option<String>,
pub model: Option<String>,
pub provider_kind: Option<String>,
pub model_chain: Option<Vec<String>>,
pub extensions: aidaemon_core::Extensions,
}
impl std::fmt::Debug for ToolCallContext {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ToolCallContext")
.field("mandate_preapproved", &self.mandate_preapproved)
.field("mandate_execution", &self.mandate_execution)
.field("mutation_forbidden", &self.mutation_forbidden)
.field("kernel_approved", &self.kernel_approved)
.field("trusted_session", &self.trusted_session)
.field("user_role", &self.user_role)
.field("untrusted_source", &self.untrusted_source)
.field("scope_escalation", &self.scope_escalation)
.field("session_id", &self.session_id)
.field("channel_visibility", &self.channel_visibility)
.field("channel_id", &self.channel_id)
.field("task_id", &self.task_id)
.field("tool_call_id", &self.tool_call_id)
.field("lone_root_call", &self.lone_root_call)
.field("turn_id", &self.turn_id)
.field("goal_id", &self.goal_id)
.field("goal_run_id", &self.goal_run_id)
.field("task_attempt_id", &self.task_attempt_id)
.field("mandate_id", &self.mandate_id)
.field("mandate_version", &self.mandate_version)
.field("project_scope", &self.project_scope)
.field(
"workspace_collaboration_root",
&self
.workspace_collaboration_root
.as_ref()
.map(|_| "[SCOPED WORKSPACE]"),
)
.field("trust_roots", &self.trust_roots)
.field("trust_cwd", &self.trust_cwd)
.field("model", &self.model)
.field("provider_kind", &self.provider_kind)
.field("model_chain", &self.model_chain)
.field("extensions", &self.extensions)
.finish()
}
}
impl ToolCallContext {
pub fn session(&self) -> Option<&str> {
Some(self.session_id.as_str()).filter(|id| !id.trim().is_empty())
}
pub fn grants_session(&self) -> &str {
if self.grant_session.trim().is_empty() {
&self.session_id
} else {
&self.grant_session
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ScopeEscalation {
#[serde(default)]
pub read_paths: Vec<String>,
#[serde(default)]
pub write_paths: Vec<String>,
}
impl ScopeEscalation {
pub fn is_empty(&self) -> bool {
self.read_paths.is_empty() && self.write_paths.is_empty()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DurableReplayDecision {
Replay,
Reexecute { reason: String },
Block { reason: String },
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolArgumentContractViolation {
pub reason: String,
pub recovery_hint: Option<String>,
}
impl ToolArgumentContractViolation {
pub fn new(reason: impl Into<String>) -> Self {
Self {
reason: reason.into(),
recovery_hint: None,
}
}
pub fn with_recovery_hint(mut self, hint: impl Into<String>) -> Self {
self.recovery_hint = Some(hint.into());
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PermissionMode {
#[default]
Default,
Cautious,
Yolo,
}
impl std::fmt::Display for PermissionMode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
PermissionMode::Default => write!(f, "default"),
PermissionMode::Cautious => write!(f, "cautious"),
PermissionMode::Yolo => write!(f, "yolo"),
}
}
}
#[derive(Debug, Clone, Copy, Default)]
pub enum ApprovalKind {
#[default]
Command,
CommandOnce,
GoalConfirmation,
AutopilotConfirmation,
Handoff,
}
#[derive(Debug, Clone)]
pub enum ApprovalResponse {
AllowOnce,
AllowSession,
AllowAlways,
Deny,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum RiskLevel {
Safe,
Medium,
High,
Critical,
}
impl std::fmt::Display for RiskLevel {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
RiskLevel::Safe => write!(f, "Safe"),
RiskLevel::Medium => write!(f, "Medium"),
RiskLevel::High => write!(f, "High"),
RiskLevel::Critical => write!(f, "Critical"),
}
}
}
impl RiskLevel {
pub const fn requires_owner_approval(self) -> bool {
matches!(self, Self::High | Self::Critical)
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum GoalConfirmationStyle {
#[default]
Standard,
Autopilot,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AgentRole {
Orchestrator,
TaskLead,
Executor,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FileWriteKind {
Edit { old_text: String, replace_all: bool },
Edits(Vec<TextEdit>),
Replace,
Append,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextEdit {
pub old_text: String,
pub replace_all: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileWrite {
pub path: String,
pub kind: FileWriteKind,
}
#[async_trait]
pub trait FileWriteGuard: Send {
async fn committed(self: Box<Self>);
}
#[async_trait]
pub trait FileFence: Send + Sync {
async fn observed(&self, path: &str, bytes: &[u8]);
async fn begin_write(&self, path: &str) -> Result<Box<dyn FileWriteGuard>, String>;
async fn claim_delivery(&self, _subject: &str) -> Result<(), DeliveredArtifact> {
Ok(())
}
async fn release_delivery(&self, _subject: &str) {}
async fn declare_deliverable(&self, deliverable: Deliverable) -> DeliveryPlan {
DeliveryPlan::Now(deliverable)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum DeliverableKind {
Screenshot { page: String },
File { name: String },
}
impl DeliverableKind {
pub fn subject(&self) -> String {
match self {
Self::Screenshot { page } => format!("screenshot:{page}"),
Self::File { name } => format!("file:{name}"),
}
}
pub fn words(&self) -> String {
match self {
Self::Screenshot { page } => format!("a screenshot of {page}"),
Self::File { name } => format!("the file {name}"),
}
}
}
pub type DeliverySend = Box<
dyn FnOnce() -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), String>> + Send>>
+ Send
+ Sync,
>;
pub struct Deliverable {
pub kind: DeliverableKind,
pub caption: String,
pub send: DeliverySend,
}
impl std::fmt::Debug for Deliverable {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Deliverable")
.field("kind", &self.kind)
.field("caption", &self.caption)
.finish_non_exhaustive()
}
}
#[derive(Debug)]
pub enum DeliveryPlan {
Now(Deliverable),
AtRunEnd { replaced: bool },
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeliveredArtifact {
pub by: String,
pub at: chrono::DateTime<chrono::Utc>,
}
impl DeliveredArtifact {
pub fn owner_time(&self) -> String {
self.at
.with_timezone(&chrono::Local)
.format("%-I:%M:%S %p")
.to_string()
}
}
#[derive(Clone)]
pub struct CallFileFence(pub std::sync::Arc<dyn FileFence>);
pub fn file_fence(facts: &ToolCallContext) -> Option<&std::sync::Arc<dyn FileFence>> {
facts
.extensions
.get::<CallFileFence>()
.map(|fence| &fence.0)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BackgroundJob {
pub key: String,
pub title: String,
pub started_at: chrono::DateTime<chrono::Utc>,
pub task_id: Option<String>,
}
#[async_trait]
pub trait ToolSemantics: Send + Sync {
fn canonicalize_arguments(
&self,
arguments: &str,
) -> Result<String, ToolArgumentContractViolation> {
Ok(arguments.to_string())
}
fn validate_arguments(&self, _arguments: &str) -> Result<(), ToolArgumentContractViolation> {
Ok(())
}
async fn on_task_end(&self, _task_id: &str, _session_id: &str) -> anyhow::Result<()> {
Ok(())
}
async fn session_context_note(&self, _session_id: &str) -> Option<String> {
None
}
async fn background_jobs(&self, _session_id: &str) -> Vec<BackgroundJob> {
Vec::new()
}
async fn stop_background_job(&self, _key: &str) -> bool {
false
}
async fn jobs_ended_by_task_end(&self, _task_id: &str) -> usize {
0
}
fn tool_role(&self) -> ToolRole {
ToolRole::Action
}
fn dispatch_facts(&self) -> ToolDispatchFacts {
ToolDispatchFacts::default()
}
fn capabilities(&self) -> ToolCapabilities {
ToolCapabilities::default()
}
fn owner_control_plane(&self) -> bool {
false
}
fn owner_control_plane_call(&self, _arguments: &str) -> bool {
false
}
async fn owner_approval_request(
&self,
_call: &ApprovalCall<'_>,
_facts: &ToolCallContext,
) -> OwnerApprovalNeed {
OwnerApprovalNeed::Unjudged
}
fn receipt_kind(&self, _arguments: &str) -> ToolReceiptKind {
ToolReceiptKind::Generic
}
fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
default_semantics_from_identity(arguments, self.capabilities())
}
fn call_access_manifest(&self, arguments: &str) -> ToolCallAccessManifest {
let semantics = self.call_semantics(arguments);
default_access_manifest(arguments, &semantics)
}
fn guarded_paths(&self, arguments: &str) -> (Vec<String>, Vec<String>) {
let manifest = self.call_access_manifest(arguments);
let values =
|targets: Vec<ToolTargetHint>| targets.into_iter().map(|target| target.value).collect();
(
values(manifest.read_targets),
values(manifest.write_targets),
)
}
fn adapter_owned_access_manifest(&self, _arguments: &str) -> ToolCallAccessManifest {
ToolCallAccessManifest::default()
}
async fn durable_replay_decision(&self, _arguments: &str) -> DurableReplayDecision {
DurableReplayDecision::Replay
}
fn stable_observation_subjects(&self) -> Vec<StableObservationSubject> {
Vec::new()
}
fn call_file_write(&self, _arguments: &str) -> Option<FileWrite> {
None
}
fn file_write_result(
&self,
_arguments: &str,
_current: Option<&[u8]>,
) -> Option<Result<Vec<u8>, String>> {
None
}
fn call_outbound(&self, _arguments: &str) -> aidaemon_core::Outbound {
aidaemon_core::Outbound::Nothing
}
fn call_effects(&self, _arguments: &str) -> aidaemon_core::CallEffects {
if self.capabilities().read_only {
aidaemon_core::CallEffects::none()
} else {
aidaemon_core::CallEffects::unknown()
}
}
fn named_files(&self, arguments: &str) -> Vec<String> {
declared_named_files(self, arguments)
}
fn call_annotations_in(
&self,
arguments: &str,
_roots: &TrustRoots<'_>,
) -> aidaemon_core::ToolAnnotations {
default_call_annotations(self.capabilities(), &self.call_semantics(arguments))
}
fn output_trust(
&self,
_arguments: &str,
_roots: &TrustRoots<'_>,
) -> aidaemon_core::SourceTrust {
if self.capabilities().external_side_effect {
aidaemon_core::SourceTrust::Untrusted
} else {
aidaemon_core::SourceTrust::Trusted
}
}
fn call_title(&self, _arguments: &str) -> Option<String> {
None
}
fn is_available(&self) -> bool {
true
}
fn offered_in_session(&self, _session_id: &str) -> bool {
true
}
}
pub const EGRESS_EFFECTS: ToolMutationEffects = ToolMutationEffects::EXTERNAL_DELIVERY
.union(ToolMutationEffects::REMOTE_MUTATION)
.union(ToolMutationEffects::REMOTE_DEPLOY)
.union(ToolMutationEffects::DESTRUCTIVE)
.union(ToolMutationEffects::CONFIGURATION);
pub fn default_call_annotations(
cap: ToolCapabilities,
semantics: &ToolCallSemantics,
) -> aidaemon_core::ToolAnnotations {
let read_only = cap.read_only
|| (matches!(
semantics.effect,
ToolCallEffect::Observation | ToolCallEffect::Administrative
) && !semantics.mutates_state());
let effects = semantics.mutation_effects;
let egress = !read_only
&& (effects.intersects(EGRESS_EFFECTS)
|| (cap.external_side_effect && !effects.has_specific_effects()));
aidaemon_core::ToolAnnotations {
read_only,
destructive: !read_only && effects.intersects(ToolMutationEffects::DESTRUCTIVE),
idempotent: read_only,
egress,
}
}
#[derive(Debug, Clone, Default)]
pub struct OwnedFolders(std::sync::Arc<std::sync::RwLock<Vec<String>>>);
impl OwnedFolders {
pub fn claim(&self, folders: &[String]) {
let mut owned = self.0.write().unwrap_or_else(|e| e.into_inner());
for folder in folders {
let folder = folder.trim();
if std::path::Path::new(folder).is_absolute() && !owned.iter().any(|f| f == folder) {
owned.push(folder.to_string());
}
}
}
pub fn release<P: AsRef<std::path::Path>>(&self, folders: &[P]) {
let mut owned = self.0.write().unwrap_or_else(|e| e.into_inner());
owned.retain(|kept| {
!folders
.iter()
.any(|folder| std::path::Path::new(kept) == folder.as_ref())
});
}
pub fn list(&self) -> Vec<String> {
self.0.read().unwrap_or_else(|e| e.into_inner()).clone()
}
pub fn absent_write_targets(effects: &aidaemon_core::CallEffects) -> Vec<std::path::PathBuf> {
effects
.keys
.iter()
.filter(|key| key.class == aidaemon_core::EffectClass::Write)
.map(|key| std::path::PathBuf::from(shellexpand::tilde(key.target.trim()).as_ref()))
.filter(|path| path.is_absolute() && std::fs::symlink_metadata(path).is_err())
.collect()
}
pub fn claim_created(&self, absent: &[std::path::PathBuf]) -> Vec<String> {
let created: Vec<String> = absent
.iter()
.filter(|path| {
std::fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_dir())
})
.map(|path| path.display().to_string())
.collect();
self.claim(&created);
created
}
}
#[cfg(test)]
mod owned_folder_tests {
use super::OwnedFolders;
#[test]
fn a_folder_a_call_created_becomes_owned() {
let base = tempfile::tempdir().unwrap();
let fresh = base.path().join("claude-drupal-11");
let file = base.path().join("notes.txt");
let before = base.path().join("existing-site");
std::fs::create_dir(&before).unwrap();
let key = |path: &std::path::Path| aidaemon_core::EffectKey {
class: aidaemon_core::EffectClass::Write,
target: path.display().to_string(),
};
let effects = aidaemon_core::CallEffects {
keys: vec![key(&fresh), key(&file), key(&before)],
complete: false,
understood: true,
};
let absent = OwnedFolders::absent_write_targets(&effects);
assert_eq!(absent, vec![fresh.clone(), file.clone()]);
std::fs::create_dir(&fresh).unwrap();
std::fs::write(&file, "x").unwrap();
let owned = OwnedFolders::default();
assert_eq!(
owned.claim_created(&absent),
vec![fresh.display().to_string()]
);
assert_eq!(owned.list(), vec![fresh.display().to_string()]);
}
}
pub fn within_owned(path: &str, folders: &[String]) -> bool {
let expanded = shellexpand::tilde(path.trim()).into_owned();
let path = std::path::Path::new(&expanded);
path.is_absolute()
&& folders.iter().any(|folder| {
aidaemon_policies::resolves_within(path, std::path::Path::new(folder.trim()))
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProducedFile {
Capture(DeliverableKind),
Created,
}
impl ProducedFile {
pub fn words(&self) -> String {
match self {
Self::Capture(kind) => format!("this request's own capture: {}", kind.words()),
Self::Created => "a file this request's own work created".to_string(),
}
}
}
#[derive(Debug, Clone, Default)]
pub struct ProducedFiles(
std::sync::Arc<std::sync::RwLock<std::collections::HashMap<String, ProducedFile>>>,
);
impl ProducedFiles {
pub fn note_capture(&self, path: &str, resource_id: Option<&str>, kind: &DeliverableKind) {
let mut produced = self.0.write().unwrap_or_else(|e| e.into_inner());
let capture = ProducedFile::Capture(kind.clone());
produced.insert(produced_key(path), capture.clone());
if let Some(id) = resource_id.map(str::trim).filter(|id| !id.is_empty()) {
produced.insert(id.to_string(), capture);
}
}
pub fn note_created(&self, path: &str, resource_id: Option<&str>) {
let mut produced = self.0.write().unwrap_or_else(|e| e.into_inner());
produced
.entry(produced_key(path))
.or_insert(ProducedFile::Created);
if let Some(id) = resource_id.map(str::trim).filter(|id| !id.is_empty()) {
produced
.entry(id.to_string())
.or_insert(ProducedFile::Created);
}
}
pub fn claim_created(&self, absent: &[std::path::PathBuf]) -> Vec<String> {
let created: Vec<String> = absent
.iter()
.filter(|path| std::fs::symlink_metadata(path).is_ok_and(|meta| meta.is_file()))
.map(|path| path.display().to_string())
.collect();
let mut produced = self.0.write().unwrap_or_else(|e| e.into_inner());
for path in &created {
produced
.entry(produced_key(path))
.or_insert(ProducedFile::Created);
}
created
}
pub fn get(&self, target: &str) -> Option<ProducedFile> {
self.0
.read()
.unwrap_or_else(|e| e.into_inner())
.get(&produced_key(target))
.cloned()
}
pub fn capture_kind(&self, path: &str) -> Option<DeliverableKind> {
match self.get(path)? {
ProducedFile::Capture(kind) => Some(kind),
ProducedFile::Created => None,
}
}
pub fn entries(&self) -> Vec<(String, ProducedFile)> {
self.0
.read()
.unwrap_or_else(|e| e.into_inner())
.iter()
.map(|(key, file)| (key.clone(), file.clone()))
.collect()
}
pub fn named_by(&self, named: &[String]) -> Vec<(String, ProducedFile)> {
named
.iter()
.filter_map(|name| Some((name.clone(), self.get(name)?)))
.collect()
}
}
pub fn declared_named_files<T: ToolSemantics + ?Sized>(tool: &T, arguments: &str) -> Vec<String> {
let mut named: Vec<String> = Vec::new();
let mut add = |value: &str| {
let value = value.trim();
if !value.is_empty() && !named.iter().any(|known| known == value) {
named.push(value.to_string());
}
};
for hint in tool.call_semantics(arguments).target_hints {
if matches!(
hint.kind,
ToolTargetHintKind::Path | ToolTargetHintKind::ResourceId
) {
add(&hint.value);
}
}
let manifest = tool.call_access_manifest(arguments);
for hint in manifest
.read_targets
.iter()
.chain(manifest.write_targets.iter())
{
if hint.kind == ToolTargetHintKind::Path {
add(&hint.value);
}
}
for key in tool.call_effects(arguments).keys {
if matches!(
key.class,
aidaemon_core::EffectClass::Write
| aidaemon_core::EffectClass::Delete
| aidaemon_core::EffectClass::Configuration
) {
add(&key.target);
}
}
named
}
fn produced_key(target: &str) -> String {
let expanded = shellexpand::tilde(target.trim()).into_owned();
dunce::canonicalize(&expanded)
.map(|path| path.to_string_lossy().into_owned())
.unwrap_or(expanded)
}
pub fn produced_files(facts: &ToolCallContext) -> Option<&ProducedFiles> {
facts.extensions.get::<ProducedFiles>()
}
#[cfg(test)]
mod produced_file_tests {
use super::{DeliverableKind, ProducedFile, ProducedFiles};
#[test]
fn a_file_a_tool_made_is_the_requests_own_by_path_and_id() {
let produced = ProducedFiles::default();
produced.note_created("/inbox/018d9d29_generated_image.png", Some("res_img"));
assert_eq!(
produced.get("/inbox/018d9d29_generated_image.png"),
Some(ProducedFile::Created)
);
assert_eq!(produced.get("res_img"), Some(ProducedFile::Created));
let page = DeliverableKind::Screenshot {
page: "demo.ddev.site".to_string(),
};
produced.note_capture("/inbox/shot.png", None, &page);
produced.note_created("/inbox/shot.png", None);
assert_eq!(produced.capture_kind("/inbox/shot.png"), Some(page));
}
#[test]
fn the_requests_own_files_come_from_evidence() {
let base = tempfile::tempdir().unwrap();
let shot = base.path().join("ea19c410_screenshot.png");
std::fs::write(&shot, b"png").unwrap();
let page = DeliverableKind::Screenshot {
page: "claude-drupal.ddev.site".to_string(),
};
let produced = ProducedFiles::default();
produced.note_capture(&shot.display().to_string(), Some("res_1"), &page);
let spelled = base
.path()
.join(".")
.join("ea19c410_screenshot.png")
.display()
.to_string();
assert_eq!(produced.capture_kind(&spelled), Some(page.clone()));
assert_eq!(
produced.get("res_1"),
Some(ProducedFile::Capture(page.clone()))
);
let fresh = base.path().join("report.md");
let older = base.path().join("notes.md");
std::fs::write(&older, "x").unwrap();
let absent = vec![fresh.clone(), shot.clone()];
std::fs::write(&fresh, "x").unwrap();
assert_eq!(produced.claim_created(&absent).len(), 2);
assert_eq!(
produced.get(&fresh.display().to_string()),
Some(ProducedFile::Created)
);
assert_eq!(
produced.capture_kind(&shot.display().to_string()),
Some(page)
);
assert_eq!(produced.get(&older.display().to_string()), None);
let named = produced.named_by(&[older.display().to_string(), fresh.display().to_string()]);
assert_eq!(named.len(), 1);
assert_eq!(named[0].1, ProducedFile::Created);
}
}
pub struct TrustRoots<'a> {
roots: &'a [String],
owned: &'a [String],
cwd: Option<&'a str>,
}
impl<'a> TrustRoots<'a> {
pub fn new(roots: &'a [String]) -> Self {
Self {
roots,
owned: &[],
cwd: None,
}
}
pub fn with_owned(mut self, owned: &'a [String]) -> Self {
self.owned = owned;
self
}
pub fn with_cwd(mut self, cwd: Option<&'a str>) -> Self {
self.cwd = cwd;
self
}
pub fn anchored_at<'b>(&'b self, cwd: Option<&'b str>) -> TrustRoots<'b> {
TrustRoots {
roots: self.roots,
owned: self.owned,
cwd,
}
}
pub fn holds_effect(&self, path: &str) -> bool {
if self.contains(path) {
return true;
}
let resolved = match self.cwd {
Some(cwd) if !is_absolute_or_home(path) => {
format!("{}/{}", cwd.trim_end_matches('/'), path.trim())
}
_ => path.to_string(),
};
within_owned(&resolved, self.owned)
}
pub fn owns(&self, path: &str) -> bool {
within_owned(path, self.owned)
}
pub fn cwd(&self) -> Option<&str> {
self.cwd
}
pub fn contains(&self, path: &str) -> bool {
let resolved = match self.cwd {
Some(cwd) if !is_absolute_or_home(path) => {
format!("{}/{}", cwd.trim_end_matches('/'), path.trim())
}
_ => path.to_string(),
};
let Some(path) = resolve_absolute(&resolved) else {
return false;
};
self.roots
.iter()
.any(|root| resolve_absolute(root).is_some_and(|root| path.starts_with(&root)))
}
}
pub fn file_output_trust(
arguments: &str,
keys: &[&str],
roots: &TrustRoots<'_>,
) -> aidaemon_core::SourceTrust {
let args = serde_json::from_str::<Value>(arguments).ok();
let path = args.as_ref().and_then(|args| {
keys.iter()
.find_map(|key| args.get(*key).and_then(Value::as_str))
});
match path {
Some(path) if roots.contains(path) => aidaemon_core::SourceTrust::Trusted,
_ => aidaemon_core::SourceTrust::Untrusted,
}
}
fn resolve_absolute(path: &str) -> Option<std::path::PathBuf> {
use std::path::{Component, PathBuf};
let expanded = shellexpand::tilde(path.trim()).into_owned();
let path = std::path::Path::new(&expanded);
if !path.is_absolute() {
return None;
}
let mut resolved = PathBuf::new();
let mut existing = true;
for component in path.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
if !resolved.pop() {
return None;
}
}
Component::Normal(part) => {
resolved.push(part);
if existing {
match dunce::canonicalize(&resolved) {
Ok(canonical) => resolved = canonical,
Err(_) => existing = false,
}
}
}
other => resolved.push(other.as_os_str()),
}
}
Some(resolved)
}
fn is_absolute_or_home(path: &str) -> bool {
let path = path.trim();
let path_ref = std::path::Path::new(path);
path.starts_with('~') || path_ref.is_absolute() || path_ref.has_root()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PreparedToolInvocation {
pub canonical_arguments: String,
pub semantics: ToolCallSemantics,
pub access_manifest: ToolCallAccessManifest,
pub receipt_kind: ToolReceiptKind,
}
pub fn prepare_invocation<T: ToolSemantics + ?Sized>(
tool: &T,
arguments: &str,
) -> Result<PreparedToolInvocation, ToolArgumentContractViolation> {
let canonical_arguments = tool.canonicalize_arguments(arguments)?;
tool.validate_arguments(&canonical_arguments)?;
Ok(PreparedToolInvocation {
semantics: tool.call_semantics(&canonical_arguments),
access_manifest: tool.call_access_manifest(&canonical_arguments),
receipt_kind: tool.receipt_kind(&canonical_arguments),
canonical_arguments,
})
}
#[cfg(test)]
mod file_trust_tests {
use super::{TrustRoots, file_output_trust};
use aidaemon_core::SourceTrust::{Trusted, Untrusted};
#[test]
fn files_inside_the_trusted_roots_are_trusted() {
let roots = vec!["/tmp/aidaemon-test/ws".to_string()];
let roots = TrustRoots::new(&roots);
let keys = ["path", "file_path"];
assert_eq!(
file_output_trust(r#"{"path":"/tmp/aidaemon-test/ws/a.txt"}"#, &keys, &roots),
Trusted
);
assert_eq!(
file_output_trust(
r#"{"file_path":"/tmp/aidaemon-test/ws/a.txt"}"#,
&keys,
&roots
),
Trusted
);
assert_eq!(
file_output_trust(r#"{"path":"/etc/hosts"}"#, &keys, &roots),
Untrusted
);
assert_eq!(file_output_trust(r#"{}"#, &keys, &roots), Untrusted);
assert_eq!(file_output_trust("not json", &keys, &roots), Untrusted);
}
}
fn is_zero(value: &usize) -> bool {
*value == 0
}
#[cfg(test)]
mod local_write_satisfaction_tests {
use super::ToolMutationEffects as E;
#[test]
fn local_write_labels_satisfy_each_other_except_source() {
assert!(E::LOCAL_WORKSPACE_WRITE.satisfies(E::LOCAL_DERIVED_WRITE));
assert!(E::LOCAL_DERIVED_WRITE.satisfies(E::LOCAL_WORKSPACE_WRITE));
assert!(E::LOCAL_SOURCE_WRITE.satisfies(E::LOCAL_DERIVED_WRITE));
assert!(E::LOCAL_SOURCE_WRITE.satisfies(E::LOCAL_WORKSPACE_WRITE));
assert!(!E::LOCAL_WORKSPACE_WRITE.satisfies(E::LOCAL_SOURCE_WRITE));
assert!(!E::LOCAL_DERIVED_WRITE.satisfies(E::LOCAL_SOURCE_WRITE));
assert!(!E::LOCAL_WORKSPACE_WRITE.satisfies(E::EXTERNAL_DELIVERY));
}
}