1use async_trait::async_trait;
7use serde::{Deserialize, Serialize};
8use serde_json::Value;
9
10use aidaemon_core::ChannelVisibility;
11
12pub use aidaemon_core::UserRole;
14
15#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
17#[serde(rename_all = "snake_case")]
18pub enum AttachmentProvenance {
19 #[default]
21 Inbound,
22 ToolObservation,
24 ToolArtifact,
26}
27
28#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
30pub struct MessageAttachment {
31 #[serde(default, skip_serializing_if = "Option::is_none")]
34 pub resource_id: Option<String>,
35 pub local_path: String,
36 pub filename: String,
37 pub mime_type: String,
38 pub size_bytes: u64,
39 #[serde(default)]
40 pub provenance: AttachmentProvenance,
41 #[serde(default, skip_serializing_if = "Option::is_none")]
42 pub source_tool: Option<String>,
43 #[serde(default, skip_serializing_if = "Option::is_none")]
46 pub sha256: Option<String>,
47 #[serde(default, skip_serializing_if = "Option::is_none")]
50 pub marked_up_from: Option<String>,
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum ToolRole {
56 Action,
58 Management,
60 Universal,
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
66pub enum Offering {
67 Core,
71 Scoped,
74 #[default]
77 Deferred,
78}
79
80impl Offering {
81 pub fn always_sent(self) -> bool {
83 matches!(self, Self::Core | Self::Scoped)
84 }
85}
86
87#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
92pub struct ToolDispatchFacts {
93 pub runs_as_judged: bool,
97 pub keeps_own_grants: bool,
101 pub shell_command_line: bool,
105 pub offering: Offering,
109 pub task_lead_delegation: bool,
112 pub same_tool_streak: SameToolStreak,
115 pub delivers_files: bool,
118 pub spawns_child_agents: bool,
121 pub requirement_checklist: bool,
124 pub opaque_execution: bool,
128 pub manages_own_timeout: bool,
132 pub records_launch_trust: bool,
135 pub goal_context: GoalContext,
137 pub network_reach: NetworkReach,
139 pub file_guard: FileGuard,
141 pub checkpoints_writes: bool,
144 pub needs_live_model: bool,
147 pub status_from_arguments: bool,
150 pub recap: RecapKind,
152 pub activity: ToolActivity,
154 pub status_label: Option<&'static str>,
157 pub project_dir_argument: ProjectDirArgument,
160 pub opens_project_instructions: bool,
164 pub result_fit: ResultFit,
166 pub channel_reach: ChannelReach,
168 pub evidence: EvidenceSource,
170 pub semantic_scope: Option<ToolSemanticScope>,
173 pub low_signal_result: bool,
176}
177
178#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
181pub enum RecapKind {
182 #[default]
184 Other,
185 FileRead,
187 FileWrite,
189 Command,
191 FileSent,
193 Search,
195 ExternalRead,
197}
198
199#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
202pub enum ToolActivity {
203 #[default]
205 ByEffect,
206 Fixed(aidaemon_core::card::ActivityKind),
208 Memory,
211}
212
213impl ToolActivity {
214 pub fn kind(self, mutates: bool) -> aidaemon_core::card::ActivityKind {
217 use aidaemon_core::card::ActivityKind;
218 match self {
219 Self::Fixed(kind) => kind,
220 Self::Memory if mutates => ActivityKind::Remember,
221 Self::Memory => ActivityKind::Recall,
222 Self::ByEffect if mutates => ActivityKind::Change,
223 Self::ByEffect => ActivityKind::Check,
224 }
225 }
226}
227
228#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
231pub enum ProjectDirArgument {
232 #[default]
234 AnyPath,
235 SearchRoot,
237 WorkingDir,
240 ShellWorkingDir,
244}
245
246impl ProjectDirArgument {
247 pub const fn injected_key(self) -> Option<&'static str> {
249 match self {
250 Self::AnyPath => None,
251 Self::SearchRoot => Some("path"),
252 Self::WorkingDir | Self::ShellWorkingDir => Some("working_dir"),
253 }
254 }
255}
256
257#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
260pub struct ResultFit {
261 pub preserve_inline: bool,
264 pub strip_control_markers: bool,
267 pub compact_json: bool,
269 pub cap_large_errors: bool,
271 pub pages_spilled_results: bool,
274}
275
276#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
279pub enum ChannelReach {
280 #[default]
282 Shared,
283 Public,
285 DirectOnly,
288}
289
290impl ChannelReach {
291 pub fn offered_in(self, visibility: ChannelVisibility) -> bool {
294 match self {
295 Self::Public => true,
296 Self::Shared => visibility != ChannelVisibility::PublicExternal,
297 Self::DirectOnly => matches!(
298 visibility,
299 ChannelVisibility::Private | ChannelVisibility::Internal
300 ),
301 }
302 }
303}
304
305#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
309pub enum EvidenceSource {
310 #[default]
313 None,
314 GoalTrace,
316 Mandates,
318 GoalRecords,
320 ConversationHistory,
322 RemoteRead,
324 NodeReading,
326 NodeAction,
328 WebSearch,
330 FileRead,
332 FileSearch,
334 FileWrite,
338 Shell,
340 HostInfo,
342 Diagnostics,
344}
345
346impl EvidenceSource {
347 pub const MODELED: [Self; 14] = [
349 Self::GoalTrace,
350 Self::Mandates,
351 Self::GoalRecords,
352 Self::ConversationHistory,
353 Self::RemoteRead,
354 Self::NodeReading,
355 Self::NodeAction,
356 Self::WebSearch,
357 Self::FileRead,
358 Self::FileSearch,
359 Self::FileWrite,
360 Self::Shell,
361 Self::HostInfo,
362 Self::Diagnostics,
363 ];
364}
365
366#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
369pub enum FileGuard {
370 #[default]
371 None,
372 Reads,
374 SensitiveReads,
377 Writes,
379}
380
381#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
384pub enum NetworkReach {
385 #[default]
387 Any,
388 PublicAndLoopback,
390 PublicOnly,
392}
393
394#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
397pub enum GoalContext {
398 #[default]
400 None,
401 Goal,
403 BackgroundDelivery,
407 MandateRun,
410}
411
412pub use aidaemon_core::SameToolStreak;
416
417#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
419pub struct ToolCapabilities {
420 pub read_only: bool,
421 pub external_side_effect: bool,
422 pub needs_approval: bool,
423 pub idempotent: bool,
424 pub high_impact_write: bool,
425}
426
427#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
429pub enum ToolCallEffect {
430 #[default]
431 Unknown,
432 Administrative,
433 Observation,
434 Mutation,
435 ObservationAndMutation,
436}
437
438#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
446#[serde(transparent)]
447pub struct ToolMutationEffects(u32);
448
449impl ToolMutationEffects {
450 pub const PROTOCOL_NAMES: [&str; 13] = [
451 "local_source_write",
452 "local_workspace_write",
453 "local_derived_write",
454 "repository_write",
455 "remote_mutation",
456 "remote_deploy",
457 "external_delivery",
458 "process_state",
459 "configuration",
460 "destructive",
461 "unspecified",
462 "scheduled_work",
463 "memory_write",
464 ];
465 pub const NONE: Self = Self(0);
466 pub const LOCAL_SOURCE_WRITE: Self = Self(1 << 0);
468 pub const LOCAL_WORKSPACE_WRITE: Self = Self(1 << 1);
471 pub const LOCAL_DERIVED_WRITE: Self = Self(1 << 2);
473 pub const REPOSITORY_WRITE: Self = Self(1 << 3);
475 pub const REMOTE_MUTATION: Self = Self(1 << 4);
477 pub const REMOTE_DEPLOY: Self = Self(1 << 5);
479 pub const EXTERNAL_DELIVERY: Self = Self(1 << 6);
481 pub const PROCESS_STATE: Self = Self(1 << 7);
483 pub const CONFIGURATION: Self = Self(1 << 8);
485 pub const DESTRUCTIVE: Self = Self(1 << 9);
487 pub const UNSPECIFIED: Self = Self(1 << 10);
490 pub const SCHEDULED_WORK: Self = Self(1 << 11);
493 pub const MEMORY_WRITE: Self = Self(1 << 12);
496
497 pub const fn bits(self) -> u32 {
501 self.0
502 }
503
504 pub const fn from_bits(bits: u32) -> Self {
508 Self(bits)
509 }
510
511 pub fn protocol_names(self) -> Vec<&'static str> {
514 [
515 (Self::LOCAL_SOURCE_WRITE, "local_source_write"),
516 (Self::LOCAL_WORKSPACE_WRITE, "local_workspace_write"),
517 (Self::LOCAL_DERIVED_WRITE, "local_derived_write"),
518 (Self::REPOSITORY_WRITE, "repository_write"),
519 (Self::REMOTE_MUTATION, "remote_mutation"),
520 (Self::REMOTE_DEPLOY, "remote_deploy"),
521 (Self::EXTERNAL_DELIVERY, "external_delivery"),
522 (Self::PROCESS_STATE, "process_state"),
523 (Self::CONFIGURATION, "configuration"),
524 (Self::DESTRUCTIVE, "destructive"),
525 (Self::UNSPECIFIED, "unspecified"),
526 (Self::SCHEDULED_WORK, "scheduled_work"),
527 (Self::MEMORY_WRITE, "memory_write"),
528 ]
529 .into_iter()
530 .filter_map(|(effect, name)| self.intersects(effect).then_some(name))
531 .collect()
532 }
533
534 pub fn telemetry_value(self) -> serde_json::Value {
537 let known_bits = Self::MEMORY_WRITE.bits()
538 | Self::SCHEDULED_WORK.bits()
539 | Self::UNSPECIFIED.bits()
540 | ((1 << 10) - 1);
541 serde_json::json!({
542 "bits": self.bits(),
543 "names": self.protocol_names(),
544 "unknown_bits": self.bits() & !known_bits,
545 })
546 }
547
548 pub const fn union(self, other: Self) -> Self {
549 Self(self.0 | other.0)
550 }
551
552 pub const fn intersect(self, other: Self) -> Self {
556 Self(self.0 & other.0)
557 }
558
559 pub fn from_protocol_name(name: &str) -> Option<Self> {
562 match name {
563 "local_source_write" => Some(Self::LOCAL_SOURCE_WRITE),
564 "local_workspace_write" => Some(Self::LOCAL_WORKSPACE_WRITE),
565 "local_derived_write" => Some(Self::LOCAL_DERIVED_WRITE),
566 "repository_write" => Some(Self::REPOSITORY_WRITE),
567 "remote_mutation" => Some(Self::REMOTE_MUTATION),
568 "remote_deploy" => Some(Self::REMOTE_DEPLOY),
569 "external_delivery" => Some(Self::EXTERNAL_DELIVERY),
570 "process_state" => Some(Self::PROCESS_STATE),
571 "configuration" => Some(Self::CONFIGURATION),
572 "destructive" => Some(Self::DESTRUCTIVE),
573 "unspecified" => Some(Self::UNSPECIFIED),
574 "scheduled_work" => Some(Self::SCHEDULED_WORK),
575 "memory_write" => Some(Self::MEMORY_WRITE),
576 _ => None,
577 }
578 }
579
580 pub const fn is_empty(&self) -> bool {
581 self.0 == 0
582 }
583
584 pub const fn contains(self, other: Self) -> bool {
585 (self.0 & other.0) == other.0
586 }
587
588 pub const fn intersects(self, other: Self) -> bool {
589 (self.0 & other.0) != 0
590 }
591
592 pub const fn has_specific_effects(self) -> bool {
593 (self.0 & !Self::UNSPECIFIED.0) != 0
594 }
595
596 pub const fn satisfies(self, required: Self) -> bool {
604 if required.is_empty() {
605 return true;
606 }
607 let generic_required = required.intersects(Self::UNSPECIFIED);
608 let generic_satisfied = !generic_required || !self.is_empty();
609 let specific_required = Self(required.0 & !Self::UNSPECIFIED.0);
610 let widened = if self.intersects(Self::LOCAL_SOURCE_WRITE)
618 || self.intersects(Self::LOCAL_DERIVED_WRITE)
619 || self.intersects(Self::LOCAL_WORKSPACE_WRITE)
620 {
621 Self(self.0 | Self::LOCAL_WORKSPACE_WRITE.0 | Self::LOCAL_DERIVED_WRITE.0)
622 } else {
623 self
624 };
625 let widened = if widened.intersects(Self::SCHEDULED_WORK) {
629 Self(widened.0 | Self::CONFIGURATION.0 | Self::PROCESS_STATE.0)
630 } else {
631 widened
632 };
633 let widened = if widened.intersects(Self::MEMORY_WRITE) {
636 Self(widened.0 | Self::LOCAL_DERIVED_WRITE.0)
637 } else {
638 widened
639 };
640 generic_satisfied && widened.contains(specific_required)
641 }
642}
643
644impl ToolCallEffect {
645 pub fn observes_state(self) -> bool {
646 matches!(self, Self::Observation | Self::ObservationAndMutation)
647 }
648
649 pub fn mutates_state(self) -> bool {
650 matches!(self, Self::Mutation | Self::ObservationAndMutation)
651 }
652}
653
654#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
656pub enum ToolVerificationMode {
657 #[default]
658 None,
659 ResultContent,
660}
661
662#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
664pub enum ToolTargetHintKind {
665 Url,
666 Path,
667 ProjectScope,
668 ResourceId,
672}
673
674#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
675pub struct ToolTargetHint {
676 pub kind: ToolTargetHintKind,
677 pub value: String,
678}
679
680impl ToolTargetHint {
681 pub fn new(kind: ToolTargetHintKind, value: impl Into<String>) -> Option<Self> {
682 let value = value.into().trim().to_string();
683 if value.is_empty() {
684 None
685 } else {
686 Some(Self { kind, value })
687 }
688 }
689}
690
691#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
693#[serde(rename_all = "snake_case")]
694pub enum ToolSemanticScope {
695 GoalState,
696 UserMemory,
697 ConversationHistory,
698 ExternalRemote,
699 LocalWorkspace,
700 HostLocal,
701}
702
703impl ToolSemanticScope {
704 pub const fn as_str(self) -> &'static str {
705 match self {
706 Self::GoalState => "goal_state",
707 Self::UserMemory => "user_memory",
708 Self::ConversationHistory => "conversation_history",
709 Self::ExternalRemote => "external_remote",
710 Self::LocalWorkspace => "local_workspace",
711 Self::HostLocal => "host_local",
712 }
713 }
714}
715
716#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
719#[serde(rename_all = "snake_case")]
720pub enum EvidencePurpose {
721 CurrentState,
722 HistoricalRecord,
723 Content,
724 Outcome,
725 Attribution,
726 CausalExplanation,
727}
728
729impl EvidencePurpose {
730 pub const fn as_str(self) -> &'static str {
731 match self {
732 Self::CurrentState => "current_state",
733 Self::HistoricalRecord => "historical_record",
734 Self::Content => "content",
735 Self::Outcome => "outcome",
736 Self::Attribution => "attribution",
737 Self::CausalExplanation => "causal_explanation",
738 }
739 }
740}
741
742#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
744#[serde(rename_all = "snake_case")]
745pub enum EvidenceAuthority {
746 Advisory,
748 Direct,
750 Canonical,
752}
753
754impl EvidenceAuthority {
755 const fn rank(self) -> u8 {
756 match self {
757 Self::Advisory => 0,
758 Self::Direct => 1,
759 Self::Canonical => 2,
760 }
761 }
762
763 pub const fn satisfies(self, required: Self) -> bool {
764 self.rank() >= required.rank()
765 }
766
767 pub const fn as_str(self) -> &'static str {
768 match self {
769 Self::Advisory => "advisory",
770 Self::Direct => "direct",
771 Self::Canonical => "canonical",
772 }
773 }
774}
775
776#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
781#[serde(rename_all = "snake_case")]
782pub enum EvidenceTemporalScope {
783 Current,
784 Historical,
785 Both,
786}
787
788impl EvidenceTemporalScope {
789 pub const fn satisfies(self, required: Self) -> bool {
790 matches!(required, Self::Both) && matches!(self, Self::Both)
791 || matches!(required, Self::Current) && matches!(self, Self::Current | Self::Both)
792 || matches!(required, Self::Historical) && matches!(self, Self::Historical | Self::Both)
793 }
794
795 pub const fn as_str(self) -> &'static str {
796 match self {
797 Self::Current => "current",
798 Self::Historical => "historical",
799 Self::Both => "both",
800 }
801 }
802}
803
804#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
808pub struct ToolEvidenceCapability {
809 pub scope: ToolSemanticScope,
810 #[serde(default, skip_serializing_if = "Vec::is_empty")]
811 pub purposes: Vec<EvidencePurpose>,
812 pub authority: EvidenceAuthority,
813 pub temporal_scope: EvidenceTemporalScope,
814}
815
816impl ToolEvidenceCapability {
817 pub fn new(
818 scope: ToolSemanticScope,
819 purposes: &[EvidencePurpose],
820 authority: EvidenceAuthority,
821 temporal_scope: EvidenceTemporalScope,
822 ) -> Self {
823 Self {
824 scope,
825 purposes: purposes.to_vec(),
826 authority,
827 temporal_scope,
828 }
829 }
830}
831
832#[allow(dead_code)]
834#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
835#[serde(rename_all = "snake_case")]
836pub enum ToolSemanticFacet {
837 GoalState,
840 Schedule,
841 RunState,
842 Recovery,
843 Control,
844 Measurement,
845 Authorization,
846 Ownership,
847}
848
849impl ToolSemanticFacet {
850 pub const PROTOCOL_NAMES: [&'static str; 8] = [
851 Self::GoalState.as_str(),
852 Self::Schedule.as_str(),
853 Self::RunState.as_str(),
854 Self::Recovery.as_str(),
855 Self::Control.as_str(),
856 Self::Measurement.as_str(),
857 Self::Authorization.as_str(),
858 Self::Ownership.as_str(),
859 ];
860
861 pub const fn as_str(self) -> &'static str {
862 match self {
863 Self::GoalState => "goal_state",
864 Self::Schedule => "schedule",
865 Self::RunState => "run_state",
866 Self::Recovery => "recovery",
867 Self::Control => "control",
868 Self::Measurement => "measurement",
869 Self::Authorization => "authorization",
870 Self::Ownership => "ownership",
871 }
872 }
873}
874
875#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq, Hash)]
879#[serde(rename_all = "snake_case")]
880pub enum ToolCollectionCompleteness {
881 #[default]
882 Unknown,
883 Partial,
884 Complete,
885}
886
887impl ToolCollectionCompleteness {
888 pub const fn satisfies(self, required: Self) -> bool {
889 matches!(required, Self::Unknown)
890 || matches!(required, Self::Partial) && matches!(self, Self::Partial | Self::Complete)
891 || matches!(required, Self::Complete) && matches!(self, Self::Complete)
892 }
893}
894
895#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
899pub struct ToolObservationEvidence {
900 pub subject: ToolTargetHint,
901 #[serde(default, skip_serializing_if = "Vec::is_empty")]
902 pub facets: Vec<ToolSemanticFacet>,
903 #[serde(default, skip_serializing_if = "Vec::is_empty")]
906 pub source_collections: Vec<ToolTargetHint>,
907}
908
909impl ToolObservationEvidence {
910 pub fn new(subject: ToolTargetHint, facets: &[ToolSemanticFacet]) -> Self {
911 Self {
912 subject,
913 facets: facets.to_vec(),
914 source_collections: Vec::new(),
915 }
916 }
917
918 pub fn with_source_collection(mut self, collection: ToolTargetHint) -> Self {
919 if !self.source_collections.contains(&collection) {
920 self.source_collections.push(collection);
921 }
922 self
923 }
924}
925
926#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
931pub struct ToolCollectionObservation {
932 pub collection: ToolTargetHint,
933 #[serde(default, skip_serializing_if = "Vec::is_empty")]
934 pub facets: Vec<ToolSemanticFacet>,
935 #[serde(default)]
936 pub completeness: ToolCollectionCompleteness,
937 #[serde(default)]
938 pub returned_count: usize,
939 #[serde(default, skip_serializing_if = "Option::is_none")]
940 pub total_count: Option<usize>,
941 #[serde(default, skip_serializing_if = "Vec::is_empty")]
942 pub members: Vec<ToolTargetHint>,
943}
944
945impl ToolCollectionObservation {
946 pub fn complete(
947 collection: ToolTargetHint,
948 facets: &[ToolSemanticFacet],
949 members: Vec<ToolTargetHint>,
950 ) -> Self {
951 let returned_count = members.len();
952 Self {
953 collection,
954 facets: facets.to_vec(),
955 completeness: ToolCollectionCompleteness::Complete,
956 returned_count,
957 total_count: Some(returned_count),
958 members,
959 }
960 }
961}
962
963#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
969pub struct StableObservationSubject {
970 #[serde(default, skip_serializing_if = "Option::is_none")]
973 pub resource_id: Option<String>,
974 #[serde(default, skip_serializing_if = "Vec::is_empty")]
976 pub facets: Vec<ToolSemanticFacet>,
977 #[serde(default, skip_serializing_if = "Vec::is_empty")]
981 pub member_namespaces: Vec<String>,
982 pub summary: String,
984}
985
986impl StableObservationSubject {
987 pub fn collection(
988 resource_id: impl Into<String>,
989 facets: &[ToolSemanticFacet],
990 member_namespace: impl Into<String>,
991 summary: impl Into<String>,
992 ) -> Self {
993 Self {
994 resource_id: Some(resource_id.into()),
995 facets: facets.to_vec(),
996 member_namespaces: vec![member_namespace.into()],
997 summary: summary.into(),
998 }
999 }
1000
1001 pub fn namespace(prefix: impl Into<String>, summary: impl Into<String>) -> Self {
1002 Self {
1003 resource_id: None,
1004 facets: Vec::new(),
1005 member_namespaces: vec![prefix.into()],
1006 summary: summary.into(),
1007 }
1008 }
1009
1010 pub fn binds(&self, value: &str) -> bool {
1013 self.resource_id.as_deref() == Some(value)
1014 || self
1015 .member_namespaces
1016 .iter()
1017 .any(|prefix| value.len() > prefix.len() && value.starts_with(prefix.as_str()))
1018 }
1019}
1020
1021#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
1025#[serde(rename_all = "UPPERCASE")]
1026pub enum ToolCallOperation {
1027 Get,
1028 Head,
1029 Options,
1030 Post,
1031 Put,
1032 Patch,
1033 Delete,
1034}
1035
1036impl ToolCallOperation {
1037 pub const fn from_http_method(method: &str) -> Option<Self> {
1038 match method.as_bytes() {
1039 b"GET" => Some(Self::Get),
1040 b"HEAD" => Some(Self::Head),
1041 b"OPTIONS" => Some(Self::Options),
1042 b"POST" => Some(Self::Post),
1043 b"PUT" => Some(Self::Put),
1044 b"PATCH" => Some(Self::Patch),
1045 b"DELETE" => Some(Self::Delete),
1046 _ => None,
1047 }
1048 }
1049}
1050
1051#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1053pub struct ToolCallSemantics {
1054 #[serde(default)]
1055 pub effect: ToolCallEffect,
1056 #[serde(default)]
1057 pub verification_mode: ToolVerificationMode,
1058 #[serde(default, skip_serializing_if = "ToolMutationEffects::is_empty")]
1061 pub mutation_effects: ToolMutationEffects,
1062 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1063 pub target_hints: Vec<ToolTargetHint>,
1064 #[serde(default, skip_serializing_if = "Option::is_none")]
1068 pub operation: Option<ToolCallOperation>,
1069 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1073 pub evidence: Vec<ToolEvidenceCapability>,
1074}
1075
1076#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
1083pub struct ToolCallAccessManifest {
1084 #[serde(default, skip_serializing_if = "Option::is_none")]
1085 pub execution_cwd: Option<String>,
1086 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1087 pub read_targets: Vec<ToolTargetHint>,
1088 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1089 pub write_targets: Vec<ToolTargetHint>,
1090 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1096 pub adapter_read_targets: Vec<ToolTargetHint>,
1097}
1098
1099impl ToolCallSemantics {
1100 pub fn with_untyped_change(&self) -> Self {
1104 let mut changed = self.clone();
1105 changed.mutation_effects = changed
1106 .mutation_effects
1107 .union(ToolMutationEffects::UNSPECIFIED);
1108 changed.effect = if changed.observes_state() {
1109 ToolCallEffect::ObservationAndMutation
1110 } else {
1111 ToolCallEffect::Mutation
1112 };
1113 changed
1114 }
1115
1116 pub fn administrative() -> Self {
1117 Self {
1118 effect: ToolCallEffect::Administrative,
1119 ..Self::default()
1120 }
1121 }
1122
1123 pub fn observation() -> Self {
1124 Self {
1125 effect: ToolCallEffect::Observation,
1126 ..Self::default()
1127 }
1128 }
1129
1130 pub fn constrained_to_observation(mut self) -> Self {
1134 self.effect = ToolCallEffect::Observation;
1135 self.mutation_effects = ToolMutationEffects::NONE;
1136 self
1137 }
1138
1139 pub fn mutation() -> Self {
1140 Self {
1141 effect: ToolCallEffect::Mutation,
1142 mutation_effects: ToolMutationEffects::UNSPECIFIED,
1143 ..Self::default()
1144 }
1145 }
1146
1147 pub fn observation_and_mutation() -> Self {
1148 Self {
1149 effect: ToolCallEffect::ObservationAndMutation,
1150 mutation_effects: ToolMutationEffects::UNSPECIFIED,
1151 ..Self::default()
1152 }
1153 }
1154
1155 pub fn mutation_with(mutation_effects: ToolMutationEffects) -> Self {
1156 Self {
1157 effect: ToolCallEffect::Mutation,
1158 mutation_effects: if mutation_effects.is_empty() {
1159 ToolMutationEffects::UNSPECIFIED
1160 } else {
1161 mutation_effects
1162 },
1163 ..Self::default()
1164 }
1165 }
1166
1167 pub fn observation_and_mutation_with(mutation_effects: ToolMutationEffects) -> Self {
1168 Self {
1169 effect: ToolCallEffect::ObservationAndMutation,
1170 mutation_effects: if mutation_effects.is_empty() {
1171 ToolMutationEffects::UNSPECIFIED
1172 } else {
1173 mutation_effects
1174 },
1175 ..Self::default()
1176 }
1177 }
1178
1179 pub fn with_verification_mode(mut self, verification_mode: ToolVerificationMode) -> Self {
1180 self.verification_mode = verification_mode;
1181 self
1182 }
1183
1184 pub fn with_target_hint(mut self, kind: ToolTargetHintKind, value: impl Into<String>) -> Self {
1185 if let Some(target) = ToolTargetHint::new(kind, value) {
1186 self.target_hints.push(target);
1187 }
1188 self
1189 }
1190
1191 pub fn with_operation(mut self, operation: ToolCallOperation) -> Self {
1192 self.operation = Some(operation);
1193 self
1194 }
1195
1196 pub fn with_evidence(mut self, evidence: Vec<ToolEvidenceCapability>) -> Self {
1197 self.evidence = evidence;
1198 self
1199 }
1200
1201 pub fn observes_state(&self) -> bool {
1202 self.effect.observes_state()
1203 }
1204
1205 pub fn mutates_state(&self) -> bool {
1206 self.effect.mutates_state() || !self.mutation_effects.is_empty()
1207 }
1208
1209 pub fn can_verify_with_result_content(&self) -> bool {
1210 self.verification_mode == ToolVerificationMode::ResultContent
1211 }
1212
1213 pub fn is_empty(&self) -> bool {
1214 self.effect == ToolCallEffect::Unknown
1215 && self.verification_mode == ToolVerificationMode::None
1216 && self.mutation_effects.is_empty()
1217 && self.target_hints.is_empty()
1218 && self.operation.is_none()
1219 && self.evidence.is_empty()
1220 }
1221
1222 pub fn merge_missing_from(&mut self, fallback: Self) {
1223 if self.effect == ToolCallEffect::Unknown {
1224 self.effect = fallback.effect;
1225 }
1226 if self.verification_mode == ToolVerificationMode::None {
1227 self.verification_mode = fallback.verification_mode;
1228 }
1229 if self.mutation_effects.is_empty()
1233 && (self.effect == ToolCallEffect::Unknown || self.effect.mutates_state())
1234 {
1235 self.mutation_effects = fallback.mutation_effects;
1236 }
1237 if self.target_hints.is_empty() {
1238 self.target_hints = fallback.target_hints;
1239 }
1240 if self.operation.is_none() {
1241 self.operation = fallback.operation;
1242 }
1243 if self.evidence.is_empty() {
1244 self.evidence = fallback.evidence;
1245 }
1246 }
1247}
1248
1249#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1250#[serde(rename_all = "snake_case")]
1251pub enum ReadFileSelectionMetadata {
1252 Full,
1253 BoundedRange { start_line: usize, end_line: usize },
1254 OpenEndedRange { start_line: usize },
1255 Tail { requested_lines: usize },
1256}
1257
1258#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1259pub struct ReadFileResultMetadata {
1260 pub display_path: String,
1261 pub canonical_path: String,
1262 pub selection: ReadFileSelectionMetadata,
1263 pub returned_start_line: Option<usize>,
1264 pub returned_end_line: Option<usize>,
1265 pub total_lines: usize,
1266 pub file_size: u64,
1267 #[serde(skip_serializing_if = "Option::is_none")]
1268 pub modified: Option<String>,
1269 pub selected_lines: Vec<String>,
1270 #[serde(default)]
1274 pub truncated: bool,
1275}
1276
1277#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1283pub struct TruncationInfo {
1284 pub shown_chars: usize,
1285 pub total_chars: usize,
1286 #[serde(default, skip_serializing_if = "Option::is_none")]
1288 pub remediation_hint: Option<String>,
1289}
1290
1291#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
1293#[serde(rename_all = "snake_case")]
1294pub enum ToolResultCompleteness {
1295 Complete,
1296 Truncated,
1297 #[default]
1298 Unavailable,
1299}
1300
1301impl ToolResultCompleteness {
1302 pub const fn as_str(self) -> &'static str {
1303 match self {
1304 Self::Complete => "complete",
1305 Self::Truncated => "truncated",
1306 Self::Unavailable => "unavailable",
1307 }
1308 }
1309}
1310
1311#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
1313#[serde(rename_all = "snake_case")]
1314pub enum ToolResultContentSource {
1315 ToolOutput,
1316 DurableReplay,
1317 SpillPreview,
1318 PersistentSummary,
1319 #[default]
1320 Unavailable,
1321}
1322
1323impl ToolResultContentSource {
1324 pub const fn as_str(self) -> &'static str {
1325 match self {
1326 Self::ToolOutput => "tool_output",
1327 Self::DurableReplay => "durable_replay",
1328 Self::SpillPreview => "spill_preview",
1329 Self::PersistentSummary => "persistent_summary",
1330 Self::Unavailable => "unavailable",
1331 }
1332 }
1333}
1334
1335#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1339pub struct ToolResultProvenance {
1340 #[serde(default, skip_serializing_if = "Option::is_none")]
1341 pub result_id: Option<String>,
1342 #[serde(default, skip_serializing_if = "Option::is_none")]
1343 pub sha256: Option<String>,
1344 #[serde(default)]
1345 pub source: ToolResultContentSource,
1346 #[serde(default)]
1347 pub model_view_completeness: ToolResultCompleteness,
1348 #[serde(default)]
1349 pub durable_view_completeness: ToolResultCompleteness,
1350 #[serde(default)]
1351 pub authoritative_chars: usize,
1352 #[serde(default)]
1353 pub model_visible_chars: usize,
1354 #[serde(default)]
1355 pub durable_chars: usize,
1356 #[serde(default, skip_serializing_if = "Option::is_none")]
1357 pub requested_range: Option<ReadFileSelectionMetadata>,
1358 #[serde(default, skip_serializing_if = "Option::is_none")]
1359 pub returned_start_line: Option<usize>,
1360 #[serde(default, skip_serializing_if = "Option::is_none")]
1361 pub returned_end_line: Option<usize>,
1362}
1363
1364#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1369#[serde(rename_all = "snake_case")]
1370pub enum AuthorizationPreflightStatus {
1371 Ready,
1372 Blocked,
1373 Unverifiable,
1374}
1375
1376#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1377pub struct AuthorizationPreflightRecord {
1378 pub schema_version: u16,
1379 pub status: AuthorizationPreflightStatus,
1380 pub intended_operation: String,
1381 pub target_digest: String,
1382 #[serde(default, skip_serializing_if = "Option::is_none")]
1383 pub auth_profile: Option<String>,
1384 #[serde(default, skip_serializing_if = "Option::is_none")]
1385 pub account_id: Option<String>,
1386 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1389 pub authorized_scopes: Vec<String>,
1390 #[serde(default, skip_serializing_if = "Option::is_none")]
1391 pub credential_generation: Option<String>,
1392 #[serde(default, skip_serializing_if = "Option::is_none")]
1393 pub refresh_result: Option<String>,
1394 #[serde(default, skip_serializing_if = "Option::is_none")]
1395 pub reason_code: Option<String>,
1396 pub checked_at: String,
1397}
1398
1399impl AuthorizationPreflightRecord {
1400 pub const SCHEMA_VERSION: u16 = 1;
1401
1402 pub const fn permits_io(&self) -> bool {
1403 matches!(self.status, AuthorizationPreflightStatus::Ready)
1404 }
1405}
1406
1407impl ToolResultProvenance {
1408 pub fn from_authoritative_result(
1409 result: &str,
1410 metadata: &ToolCallMetadata,
1411 source: ToolResultContentSource,
1412 ) -> Self {
1413 use sha2::{Digest, Sha256};
1414
1415 let sha256 = hex::encode(Sha256::digest(result.as_bytes()));
1416 let chars = result.chars().count();
1417 let tool_truncated = metadata.truncation.is_some()
1418 || metadata
1419 .read_file
1420 .as_ref()
1421 .is_some_and(|read| read.truncated);
1422 let completeness = if tool_truncated {
1423 ToolResultCompleteness::Truncated
1424 } else {
1425 ToolResultCompleteness::Complete
1426 };
1427 let read = metadata.read_file.as_ref();
1428 Self {
1429 result_id: Some(format!("sha256:{sha256}")),
1430 sha256: Some(sha256),
1431 source,
1432 model_view_completeness: completeness,
1433 durable_view_completeness: completeness,
1434 authoritative_chars: chars,
1435 model_visible_chars: chars,
1436 durable_chars: chars,
1437 requested_range: read.map(|read| read.selection.clone()),
1438 returned_start_line: read.and_then(|read| read.returned_start_line),
1439 returned_end_line: read.and_then(|read| read.returned_end_line),
1440 }
1441 }
1442
1443 pub fn mark_model_view_truncated(&mut self, visible_result: &str) {
1444 self.model_visible_chars = visible_result.chars().count();
1445 self.model_view_completeness = ToolResultCompleteness::Truncated;
1446 }
1447
1448 pub fn record_durable_view(&mut self, durable_result: &str, is_summary: bool) {
1449 self.durable_chars = durable_result.chars().count();
1450 if is_summary {
1451 self.durable_view_completeness = ToolResultCompleteness::Truncated;
1452 self.source = ToolResultContentSource::PersistentSummary;
1453 } else {
1454 self.durable_view_completeness = self.model_view_completeness;
1455 }
1456 }
1457}
1458
1459#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1463#[serde(rename_all = "snake_case")]
1464pub enum ToolOutcomeStatus {
1465 Succeeded,
1466 CompletedWithNegativeResult,
1467 FailedRetryable,
1468 FailedPermanent,
1469 Blocked,
1470 Backgrounded,
1471}
1472
1473#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
1480#[serde(rename_all = "snake_case")]
1481pub enum ToolInvocationStage {
1482 #[default]
1484 Unknown,
1485 RejectedBeforeDispatch,
1487 RejectedBeforeIo,
1489 Dispatched,
1491 Replayed,
1493}
1494
1495impl ToolInvocationStage {
1496 pub const fn as_str(self) -> &'static str {
1497 match self {
1498 Self::Unknown => "unknown",
1499 Self::RejectedBeforeDispatch => "rejected_before_dispatch",
1500 Self::RejectedBeforeIo => "rejected_before_io",
1501 Self::Dispatched => "dispatched",
1502 Self::Replayed => "replayed",
1503 }
1504 }
1505
1506 pub const fn reached_dispatch(self) -> bool {
1507 matches!(self, Self::Dispatched | Self::Replayed)
1508 }
1509
1510 pub const fn performed_io(self) -> bool {
1513 matches!(self, Self::Dispatched)
1514 }
1515}
1516
1517#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
1524#[serde(rename_all = "snake_case")]
1525pub enum ToolReceiptKind {
1526 #[default]
1527 Generic,
1528 Process,
1529 Http,
1530}
1531
1532#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
1535#[serde(rename_all = "snake_case")]
1536pub enum ToolAccessEnforcement {
1537 #[default]
1539 Unknown,
1540 NotApplicable,
1542 AdapterEnforced,
1544 ControllerEnforced,
1547 KernelEnforced,
1549}
1550
1551#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1556pub struct ToolAccessDenial {
1557 pub reason_code: String,
1558 pub enforcement: ToolAccessEnforcement,
1559 #[serde(default, skip_serializing_if = "Option::is_none")]
1560 pub exit_code: Option<i32>,
1561 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1566 pub proposed_evidence: Vec<ToolEvidenceCapability>,
1567}
1568
1569impl ToolOutcomeStatus {
1570 pub const fn from_process_exit_code(code: i32) -> Self {
1576 if code == 0 {
1577 Self::Succeeded
1578 } else if code > 0 {
1579 Self::CompletedWithNegativeResult
1580 } else {
1581 Self::FailedPermanent
1582 }
1583 }
1584
1585 pub const fn as_str(self) -> &'static str {
1586 match self {
1587 Self::Succeeded => "succeeded",
1588 Self::CompletedWithNegativeResult => "completed_with_negative_result",
1589 Self::FailedRetryable => "failed_retryable",
1590 Self::FailedPermanent => "failed_permanent",
1591 Self::Blocked => "blocked",
1592 Self::Backgrounded => "backgrounded",
1593 }
1594 }
1595
1596 pub fn satisfies_requested_condition(self) -> bool {
1597 matches!(self, Self::Succeeded)
1598 }
1599
1600 pub fn is_failure(self) -> bool {
1601 matches!(
1602 self,
1603 Self::FailedRetryable | Self::FailedPermanent | Self::Blocked
1604 )
1605 }
1606}
1607
1608#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1614#[serde(rename_all = "snake_case")]
1615pub enum ToolResultPresentation {
1616 NaturalSummary,
1617 DiagnosticDetail,
1618}
1619
1620#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
1625pub struct ToolCallMetadata {
1626 #[serde(default)]
1630 pub receipt_kind: ToolReceiptKind,
1631 #[serde(default, skip_serializing_if = "Option::is_none")]
1634 pub access_manifest: Option<ToolCallAccessManifest>,
1635 #[serde(default)]
1638 pub access_enforcement: ToolAccessEnforcement,
1639 #[serde(default, skip_serializing_if = "Option::is_none")]
1642 pub access_denial: Option<ToolAccessDenial>,
1643 #[serde(default, skip_serializing_if = "Option::is_none")]
1647 pub outcome_status: Option<ToolOutcomeStatus>,
1648 #[serde(default)]
1651 pub invocation_stage: ToolInvocationStage,
1652 #[serde(default)]
1656 pub contract_rejected: bool,
1657 #[serde(default, skip_serializing_if = "Option::is_none")]
1660 pub effective_tool_name: Option<String>,
1661 #[serde(default)]
1664 pub receipt_replayed: bool,
1665 #[serde(skip_serializing_if = "Option::is_none")]
1667 pub exit_code: Option<i32>,
1668 #[serde(default)]
1670 pub timed_out: bool,
1671 #[serde(default)]
1673 pub background_started: bool,
1674 #[serde(default)]
1676 pub detached: bool,
1677 #[serde(default)]
1680 pub completion_notifications_enabled: bool,
1681 #[serde(skip_serializing_if = "Option::is_none")]
1683 pub transport_error: Option<String>,
1684 #[serde(default, skip_serializing_if = "Option::is_none")]
1687 pub http_status: Option<u16>,
1688 #[serde(default, skip_serializing_if = "Option::is_none")]
1691 pub truncation: Option<TruncationInfo>,
1692 #[serde(default, skip_serializing_if = "Option::is_none")]
1695 pub result_provenance: Option<ToolResultProvenance>,
1696 #[serde(default, skip_serializing_if = "Option::is_none")]
1699 pub authorization_preflight: Option<AuthorizationPreflightRecord>,
1700 #[serde(default)]
1706 pub background_handoff: bool,
1707 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1712 pub background_settled: bool,
1713 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1719 pub background_run_labels: Vec<String>,
1720 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1724 pub checklist_items: Vec<usize>,
1725 #[serde(default, skip_serializing_if = "is_zero")]
1731 pub launched_runs: usize,
1732 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1737 pub changes_untyped: bool,
1738 #[serde(default, skip_serializing_if = "ToolCallSemantics::is_empty")]
1740 pub semantics: ToolCallSemantics,
1741 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1745 pub observations: Vec<ToolObservationEvidence>,
1746 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1748 pub collection_observations: Vec<ToolCollectionObservation>,
1749 #[serde(skip_serializing_if = "Option::is_none")]
1751 pub read_file: Option<ReadFileResultMetadata>,
1752 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1754 pub attachments: Vec<MessageAttachment>,
1755 #[serde(default, skip_serializing_if = "Option::is_none")]
1759 pub runtime_preparation_failure: Option<Box<RuntimePreparationFailure>>,
1760 #[serde(default)]
1764 pub untrusted_verbatim: bool,
1765 #[serde(default)]
1768 pub preserve_inline: bool,
1769 #[serde(default, skip_serializing_if = "Option::is_none")]
1772 pub persistent_output: Option<String>,
1773 #[serde(default)]
1775 pub suppress_activity_result: bool,
1776 #[serde(default, skip_serializing_if = "Option::is_none")]
1781 pub presentation: Option<ToolResultPresentation>,
1782 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1786 pub internal_identifiers: Vec<String>,
1787 #[serde(default, skip_serializing_if = "Option::is_none")]
1791 pub output_trust: Option<aidaemon_core::SourceTrust>,
1792}
1793
1794#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1795pub struct ToolCallOutcome {
1796 pub output: String,
1797 #[serde(default)]
1798 pub metadata: ToolCallMetadata,
1799 #[serde(default, skip_serializing_if = "Option::is_none")]
1804 pub finish: Option<aidaemon_core::Finish>,
1805}
1806
1807#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1812pub struct RuntimePreparationFailure {
1813 pub field: String,
1815 pub value: String,
1817 pub error: String,
1819}
1820
1821impl ToolCallOutcome {
1822 pub fn from_output(output: String) -> Self {
1823 Self {
1824 output,
1825 metadata: ToolCallMetadata::default(),
1826 finish: None,
1827 }
1828 }
1829
1830 pub fn contract_rejection(output: impl Into<String>) -> Self {
1831 Self {
1832 output: output.into(),
1833 metadata: ToolCallMetadata {
1834 outcome_status: Some(ToolOutcomeStatus::Blocked),
1838 invocation_stage: ToolInvocationStage::RejectedBeforeIo,
1839 contract_rejected: true,
1840 semantics: ToolCallSemantics::observation()
1845 .with_verification_mode(ToolVerificationMode::ResultContent),
1846 ..ToolCallMetadata::default()
1847 },
1848 finish: None,
1849 }
1850 }
1851
1852 pub fn blocked(output: impl Into<String>) -> Self {
1853 Self {
1854 output: output.into(),
1855 metadata: ToolCallMetadata {
1856 outcome_status: Some(ToolOutcomeStatus::Blocked),
1857 ..ToolCallMetadata::default()
1858 },
1859 finish: None,
1860 }
1861 }
1862
1863 pub fn runtime_preparation_failure(
1867 field: impl Into<String>,
1868 value: impl Into<String>,
1869 error: impl std::fmt::Display,
1870 ) -> Self {
1871 let field = field.into();
1872 let value = value.into();
1873 let error = error.to_string();
1874 Self {
1875 output: format!(
1876 "Error: the runtime could not prepare `{field}` entry `{value}` before running the command: {error}"
1877 ),
1878 metadata: ToolCallMetadata {
1879 outcome_status: Some(ToolOutcomeStatus::Blocked),
1880 invocation_stage: ToolInvocationStage::RejectedBeforeIo,
1881 semantics: ToolCallSemantics::observation()
1882 .with_verification_mode(ToolVerificationMode::ResultContent),
1883 runtime_preparation_failure: Some(Box::new(RuntimePreparationFailure {
1884 field,
1885 value,
1886 error,
1887 })),
1888 ..ToolCallMetadata::default()
1889 },
1890 finish: None,
1891 }
1892 }
1893
1894 pub fn completed_negative_result(output: impl Into<String>) -> Self {
1895 Self {
1896 output: output.into(),
1897 metadata: ToolCallMetadata {
1898 outcome_status: Some(ToolOutcomeStatus::CompletedWithNegativeResult),
1899 ..ToolCallMetadata::default()
1900 },
1901 finish: None,
1902 }
1903 }
1904
1905 pub fn with_finish(mut self, finish: aidaemon_core::Finish) -> Self {
1907 self.finish = Some(finish);
1908 self
1909 }
1910
1911 pub fn handed_to_background(mut self) -> Self {
1916 self.metadata.background_handoff = true;
1917 self.finish = Some(aidaemon_core::Finish::new(
1918 aidaemon_core::FinishOutcome::Partial,
1919 None,
1920 ));
1921 self
1922 }
1923
1924 pub fn with_semantics(mut self, semantics: ToolCallSemantics) -> Self {
1925 self.metadata.semantics = semantics;
1926 self
1927 }
1928
1929 pub fn with_observation_evidence(
1930 mut self,
1931 observations: Vec<ToolObservationEvidence>,
1932 collection_observations: Vec<ToolCollectionObservation>,
1933 ) -> Self {
1934 self.metadata.observations = observations;
1935 self.metadata.collection_observations = collection_observations;
1936 self
1937 }
1938}
1939
1940impl Default for ToolCapabilities {
1941 fn default() -> Self {
1942 Self {
1943 read_only: false,
1944 external_side_effect: false,
1945 needs_approval: true,
1946 idempotent: false,
1947 high_impact_write: false,
1948 }
1949 }
1950}
1951
1952fn string_to_target_hint(key: &str, value: &str) -> Option<ToolTargetHint> {
1953 let trimmed = value.trim();
1954 if trimmed.is_empty() {
1955 return None;
1956 }
1957
1958 let lower_key = key.to_ascii_lowercase();
1959 if lower_key == "resource_id" {
1960 return ToolTargetHint::new(ToolTargetHintKind::ResourceId, trimmed);
1961 }
1962
1963 if matches!(
1964 lower_key.as_str(),
1965 "url" | "verify_url" | "callback_url" | "target_url" | "auth_url"
1966 ) || trimmed.starts_with("http://")
1967 || trimmed.starts_with("https://")
1968 {
1969 return ToolTargetHint::new(ToolTargetHintKind::Url, trimmed);
1970 }
1971
1972 if matches!(
1973 lower_key.as_str(),
1974 "path"
1975 | "file_path"
1976 | "working_dir"
1977 | "cwd"
1978 | "directory"
1979 | "dir"
1980 | "repo_path"
1981 | "repo_dir"
1982 | "resource_path"
1983 ) {
1984 return ToolTargetHint::new(ToolTargetHintKind::Path, trimmed);
1985 }
1986
1987 if matches!(
1988 lower_key.as_str(),
1989 "project_path" | "project_dir" | "scope" | "project_scope"
1990 ) {
1991 return ToolTargetHint::new(ToolTargetHintKind::ProjectScope, trimmed);
1992 }
1993
1994 None
1995}
1996
1997fn push_unique_target_hint(hints: &mut Vec<ToolTargetHint>, candidate: Option<ToolTargetHint>) {
1998 let Some(candidate) = candidate else {
1999 return;
2000 };
2001 if !hints.iter().any(|existing| existing == &candidate) {
2002 hints.push(candidate);
2003 }
2004}
2005
2006fn collect_common_target_hints(arguments: &str) -> Vec<ToolTargetHint> {
2007 let parsed = match serde_json::from_str::<Value>(arguments) {
2008 Ok(Value::Object(map)) => map,
2009 _ => return Vec::new(),
2010 };
2011
2012 let mut hints = Vec::new();
2013 for (key, value) in &parsed {
2014 match value {
2015 Value::String(s) => push_unique_target_hint(&mut hints, string_to_target_hint(key, s)),
2016 Value::Array(items) if matches!(key.as_str(), "paths" | "urls") => {
2017 for item in items.iter().filter_map(|item| item.as_str()) {
2018 push_unique_target_hint(&mut hints, string_to_target_hint(key, item));
2019 }
2020 }
2021 _ => {}
2022 }
2023 }
2024 hints
2025}
2026
2027fn default_access_manifest(
2028 arguments: &str,
2029 semantics: &ToolCallSemantics,
2030) -> ToolCallAccessManifest {
2031 let parsed = serde_json::from_str::<Value>(arguments).ok();
2032 let execution_cwd = parsed.as_ref().and_then(|value| {
2033 value
2034 .get("working_dir")
2035 .or_else(|| value.get("cwd"))
2036 .and_then(Value::as_str)
2037 .map(str::trim)
2038 .filter(|value| !value.is_empty())
2039 .map(str::to_string)
2040 });
2041 let targets = if semantics.target_hints.is_empty() {
2042 collect_common_target_hints(arguments)
2043 } else {
2044 semantics.target_hints.clone()
2045 };
2046 let non_cwd_targets = targets
2047 .into_iter()
2048 .filter(|target| {
2049 matches!(
2050 target.kind,
2051 ToolTargetHintKind::Path | ToolTargetHintKind::ProjectScope
2052 )
2053 })
2054 .filter(|target| execution_cwd.as_deref() != Some(target.value.as_str()))
2055 .collect::<Vec<_>>();
2056 let mut read_targets = Vec::new();
2057 if let Some(cwd) = execution_cwd.as_deref()
2058 && let Some(target) = ToolTargetHint::new(ToolTargetHintKind::ProjectScope, cwd)
2059 {
2060 read_targets.push(target);
2061 }
2062 if semantics.observes_state() {
2063 read_targets.extend(non_cwd_targets.iter().cloned());
2064 }
2065 let write_targets = if semantics.mutates_state() {
2066 non_cwd_targets
2067 } else {
2068 Vec::new()
2069 };
2070 ToolCallAccessManifest {
2071 execution_cwd,
2072 read_targets,
2073 write_targets,
2074 adapter_read_targets: Vec::new(),
2075 }
2076}
2077
2078pub fn semantics_for_exact_read_actions(
2085 arguments: &str,
2086 read_actions: &[&str],
2087 mutation_effects: ToolMutationEffects,
2088) -> ToolCallSemantics {
2089 let action = serde_json::from_str::<Value>(arguments)
2090 .ok()
2091 .and_then(|value| {
2092 value
2093 .get("action")
2094 .and_then(Value::as_str)
2095 .map(str::to_string)
2096 });
2097 let mut semantics = if action
2098 .as_deref()
2099 .is_some_and(|action| read_actions.contains(&action))
2100 {
2101 ToolCallSemantics::observation().with_verification_mode(ToolVerificationMode::ResultContent)
2102 } else if mutation_effects.is_empty() {
2103 ToolCallSemantics::mutation()
2104 } else {
2105 ToolCallSemantics::mutation_with(mutation_effects)
2106 };
2107 for target_hint in collect_common_target_hints(arguments) {
2108 semantics = semantics.with_target_hint(target_hint.kind, target_hint.value);
2109 }
2110 semantics
2111}
2112
2113fn default_semantics_from_identity(arguments: &str, caps: ToolCapabilities) -> ToolCallSemantics {
2114 let mut semantics = if caps.read_only {
2115 ToolCallSemantics::observation().with_verification_mode(ToolVerificationMode::ResultContent)
2116 } else {
2117 ToolCallSemantics::mutation()
2122 };
2123
2124 for target_hint in collect_common_target_hints(arguments) {
2125 semantics = semantics.with_target_hint(target_hint.kind, target_hint.value);
2126 }
2127 semantics
2128}
2129
2130#[derive(Debug, Clone, PartialEq, Eq)]
2133pub enum ApprovalScope {
2134 Call,
2136 Request { method: String, url: String },
2139}
2140
2141#[derive(Debug, Clone, Copy)]
2144pub struct ApprovalCall<'a> {
2145 pub arguments: &'a Value,
2149 pub as_sent: &'a Value,
2152 pub refused: bool,
2155}
2156
2157impl<'a> ApprovalCall<'a> {
2158 pub fn as_sent(arguments: &'a Value) -> Self {
2160 Self {
2161 arguments,
2162 as_sent: arguments,
2163 refused: false,
2164 }
2165 }
2166}
2167
2168#[derive(Debug, Clone, PartialEq)]
2170pub enum OwnerApprovalNeed {
2171 Unjudged,
2174 NotNeeded,
2176 Ask(aidaemon_core::OwnerApprovalRequest),
2178}
2179
2180#[derive(Clone, Default)]
2189pub struct ToolCallContext {
2190 pub mandate_preapproved: bool,
2194 pub mandate_execution: bool,
2199 pub mutation_forbidden: bool,
2202 pub kernel_approved: Option<ApprovalScope>,
2209 pub trusted_session: bool,
2213 pub user_role: Option<UserRole>,
2216 pub untrusted_source: bool,
2219 pub scope_escalation: Option<ScopeEscalation>,
2222 pub session_id: String,
2224 pub grant_session: String,
2229 pub channel_visibility: Option<ChannelVisibility>,
2232 pub channel_id: Option<String>,
2234 pub task_id: Option<String>,
2236 pub tool_call_id: Option<String>,
2238 pub lone_root_call: bool,
2241 pub turn_id: Option<String>,
2243 pub goal_id: Option<String>,
2247 pub goal_run_id: Option<String>,
2249 pub task_attempt_id: Option<String>,
2251 pub mandate_id: Option<String>,
2253 pub mandate_version: Option<i64>,
2255 pub project_scope: Option<String>,
2257 pub project: Option<aidaemon_core::ProjectRef>,
2262 pub workspace_collaboration_root: Option<String>,
2264 pub trust_roots: Option<Vec<String>>,
2267 pub trust_cwd: Option<String>,
2269 pub model: Option<String>,
2271 pub provider_kind: Option<String>,
2273 pub model_chain: Option<Vec<String>>,
2275 pub extensions: aidaemon_core::Extensions,
2279}
2280
2281impl std::fmt::Debug for ToolCallContext {
2282 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2283 f.debug_struct("ToolCallContext")
2284 .field("mandate_preapproved", &self.mandate_preapproved)
2285 .field("mandate_execution", &self.mandate_execution)
2286 .field("mutation_forbidden", &self.mutation_forbidden)
2287 .field("kernel_approved", &self.kernel_approved)
2288 .field("trusted_session", &self.trusted_session)
2289 .field("user_role", &self.user_role)
2290 .field("untrusted_source", &self.untrusted_source)
2291 .field("scope_escalation", &self.scope_escalation)
2292 .field("session_id", &self.session_id)
2293 .field("channel_visibility", &self.channel_visibility)
2294 .field("channel_id", &self.channel_id)
2295 .field("task_id", &self.task_id)
2296 .field("tool_call_id", &self.tool_call_id)
2297 .field("lone_root_call", &self.lone_root_call)
2298 .field("turn_id", &self.turn_id)
2299 .field("goal_id", &self.goal_id)
2300 .field("goal_run_id", &self.goal_run_id)
2301 .field("task_attempt_id", &self.task_attempt_id)
2302 .field("mandate_id", &self.mandate_id)
2303 .field("mandate_version", &self.mandate_version)
2304 .field("project_scope", &self.project_scope)
2305 .field(
2306 "workspace_collaboration_root",
2307 &self
2308 .workspace_collaboration_root
2309 .as_ref()
2310 .map(|_| "[SCOPED WORKSPACE]"),
2311 )
2312 .field("trust_roots", &self.trust_roots)
2313 .field("trust_cwd", &self.trust_cwd)
2314 .field("model", &self.model)
2315 .field("provider_kind", &self.provider_kind)
2316 .field("model_chain", &self.model_chain)
2317 .field("extensions", &self.extensions)
2318 .finish()
2319 }
2320}
2321
2322impl ToolCallContext {
2323 pub fn session(&self) -> Option<&str> {
2325 Some(self.session_id.as_str()).filter(|id| !id.trim().is_empty())
2326 }
2327
2328 pub fn grants_session(&self) -> &str {
2331 if self.grant_session.trim().is_empty() {
2332 &self.session_id
2333 } else {
2334 &self.grant_session
2335 }
2336 }
2337}
2338
2339#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
2345pub struct ScopeEscalation {
2346 #[serde(default)]
2347 pub read_paths: Vec<String>,
2348 #[serde(default)]
2349 pub write_paths: Vec<String>,
2350}
2351
2352impl ScopeEscalation {
2353 pub fn is_empty(&self) -> bool {
2354 self.read_paths.is_empty() && self.write_paths.is_empty()
2355 }
2356}
2357
2358#[derive(Debug, Clone, PartialEq, Eq)]
2366pub enum DurableReplayDecision {
2367 Replay,
2368 Reexecute { reason: String },
2369 Block { reason: String },
2370}
2371
2372#[derive(Debug, Clone, PartialEq, Eq)]
2374pub struct ToolArgumentContractViolation {
2375 pub reason: String,
2376 pub recovery_hint: Option<String>,
2377}
2378
2379impl ToolArgumentContractViolation {
2380 pub fn new(reason: impl Into<String>) -> Self {
2381 Self {
2382 reason: reason.into(),
2383 recovery_hint: None,
2384 }
2385 }
2386
2387 pub fn with_recovery_hint(mut self, hint: impl Into<String>) -> Self {
2388 self.recovery_hint = Some(hint.into());
2389 self
2390 }
2391}
2392
2393#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
2395#[serde(rename_all = "lowercase")]
2396pub enum PermissionMode {
2397 #[default]
2399 Default,
2400 Cautious,
2402 Yolo,
2404}
2405
2406impl std::fmt::Display for PermissionMode {
2407 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2408 match self {
2409 PermissionMode::Default => write!(f, "default"),
2410 PermissionMode::Cautious => write!(f, "cautious"),
2411 PermissionMode::Yolo => write!(f, "yolo"),
2412 }
2413 }
2414}
2415
2416#[derive(Debug, Clone, Copy, Default)]
2420pub enum ApprovalKind {
2421 #[default]
2423 Command,
2424 CommandOnce,
2427 GoalConfirmation,
2429 AutopilotConfirmation,
2433 Handoff,
2436}
2437
2438#[derive(Debug, Clone)]
2440pub enum ApprovalResponse {
2441 AllowOnce,
2443 AllowSession,
2445 AllowAlways,
2447 Deny,
2449}
2450
2451#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
2453pub enum RiskLevel {
2454 Safe,
2455 Medium,
2456 High,
2457 Critical,
2458}
2459
2460impl std::fmt::Display for RiskLevel {
2461 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2462 match self {
2463 RiskLevel::Safe => write!(f, "Safe"),
2464 RiskLevel::Medium => write!(f, "Medium"),
2465 RiskLevel::High => write!(f, "High"),
2466 RiskLevel::Critical => write!(f, "Critical"),
2467 }
2468 }
2469}
2470
2471impl RiskLevel {
2472 pub const fn requires_owner_approval(self) -> bool {
2477 matches!(self, Self::High | Self::Critical)
2478 }
2479}
2480
2481#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2483pub enum GoalConfirmationStyle {
2484 #[default]
2485 Standard,
2486 Autopilot,
2487}
2488
2489#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2491pub enum AgentRole {
2492 Orchestrator,
2494 TaskLead,
2496 Executor,
2498}
2499
2500#[derive(Debug, Clone, PartialEq, Eq)]
2502pub enum FileWriteKind {
2503 Edit { old_text: String, replace_all: bool },
2505 Edits(Vec<TextEdit>),
2508 Replace,
2510 Append,
2512}
2513
2514#[derive(Debug, Clone, PartialEq, Eq)]
2516pub struct TextEdit {
2517 pub old_text: String,
2518 pub replace_all: bool,
2519}
2520
2521#[derive(Debug, Clone, PartialEq, Eq)]
2523pub struct FileWrite {
2524 pub path: String,
2525 pub kind: FileWriteKind,
2526}
2527
2528#[async_trait]
2530pub trait FileWriteGuard: Send {
2531 async fn committed(self: Box<Self>);
2533}
2534
2535#[async_trait]
2538pub trait FileFence: Send + Sync {
2539 async fn observed(&self, path: &str, bytes: &[u8]);
2541
2542 async fn begin_write(&self, path: &str) -> Result<Box<dyn FileWriteGuard>, String>;
2546
2547 async fn claim_delivery(&self, _subject: &str) -> Result<(), DeliveredArtifact> {
2553 Ok(())
2554 }
2555
2556 async fn release_delivery(&self, _subject: &str) {}
2558
2559 async fn declare_deliverable(&self, deliverable: Deliverable) -> DeliveryPlan {
2566 DeliveryPlan::Now(deliverable)
2567 }
2568}
2569
2570#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2573pub enum DeliverableKind {
2574 Screenshot { page: String },
2576 File { name: String },
2578}
2579
2580impl DeliverableKind {
2581 pub fn subject(&self) -> String {
2583 match self {
2584 Self::Screenshot { page } => format!("screenshot:{page}"),
2585 Self::File { name } => format!("file:{name}"),
2586 }
2587 }
2588
2589 pub fn words(&self) -> String {
2591 match self {
2592 Self::Screenshot { page } => format!("a screenshot of {page}"),
2593 Self::File { name } => format!("the file {name}"),
2594 }
2595 }
2596}
2597
2598pub type DeliverySend = Box<
2601 dyn FnOnce() -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), String>> + Send>>
2602 + Send
2603 + Sync,
2604>;
2605
2606pub struct Deliverable {
2608 pub kind: DeliverableKind,
2609 pub caption: String,
2611 pub send: DeliverySend,
2612}
2613
2614impl std::fmt::Debug for Deliverable {
2615 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2616 f.debug_struct("Deliverable")
2617 .field("kind", &self.kind)
2618 .field("caption", &self.caption)
2619 .finish_non_exhaustive()
2620 }
2621}
2622
2623#[derive(Debug)]
2625pub enum DeliveryPlan {
2626 Now(Deliverable),
2628 AtRunEnd { replaced: bool },
2631}
2632
2633#[derive(Debug, Clone, PartialEq, Eq)]
2635pub struct DeliveredArtifact {
2636 pub by: String,
2639 pub at: chrono::DateTime<chrono::Utc>,
2640}
2641
2642impl DeliveredArtifact {
2643 pub fn owner_time(&self) -> String {
2645 self.at
2646 .with_timezone(&chrono::Local)
2647 .format("%-I:%M:%S %p")
2648 .to_string()
2649 }
2650}
2651
2652#[derive(Clone)]
2654pub struct CallFileFence(pub std::sync::Arc<dyn FileFence>);
2655
2656pub fn file_fence(facts: &ToolCallContext) -> Option<&std::sync::Arc<dyn FileFence>> {
2658 facts
2659 .extensions
2660 .get::<CallFileFence>()
2661 .map(|fence| &fence.0)
2662}
2663
2664#[derive(Debug, Clone, PartialEq, Eq)]
2666pub struct BackgroundJob {
2667 pub key: String,
2669 pub title: String,
2671 pub started_at: chrono::DateTime<chrono::Utc>,
2672 pub task_id: Option<String>,
2674 pub run: Option<String>,
2676}
2677
2678#[async_trait]
2683pub trait ToolSemantics: Send + Sync {
2684 fn canonicalize_arguments(
2690 &self,
2691 arguments: &str,
2692 ) -> Result<String, ToolArgumentContractViolation> {
2693 Ok(arguments.to_string())
2694 }
2695
2696 fn validate_arguments(&self, _arguments: &str) -> Result<(), ToolArgumentContractViolation> {
2700 Ok(())
2701 }
2702
2703 async fn on_task_end(&self, _task_id: &str, _session_id: &str) -> anyhow::Result<()> {
2707 Ok(())
2708 }
2709
2710 async fn session_context_note(&self, _session_id: &str) -> Option<String> {
2714 None
2715 }
2716
2717 async fn background_jobs(&self, _session_id: &str) -> Vec<BackgroundJob> {
2721 Vec::new()
2722 }
2723
2724 async fn stop_background_job(&self, _key: &str) -> bool {
2727 false
2728 }
2729
2730 async fn jobs_ended_by_task_end(&self, _task_id: &str) -> usize {
2734 0
2735 }
2736
2737 fn tool_role(&self) -> ToolRole {
2740 ToolRole::Action
2741 }
2742
2743 fn dispatch_facts(&self) -> ToolDispatchFacts {
2746 ToolDispatchFacts::default()
2747 }
2748
2749 fn capabilities(&self) -> ToolCapabilities {
2752 ToolCapabilities::default()
2753 }
2754
2755 fn owner_control_plane(&self) -> bool {
2760 false
2761 }
2762
2763 fn owner_control_plane_call(&self, _arguments: &str) -> bool {
2767 false
2768 }
2769
2770 async fn owner_approval_request(
2776 &self,
2777 _call: &ApprovalCall<'_>,
2778 _facts: &ToolCallContext,
2779 ) -> OwnerApprovalNeed {
2780 OwnerApprovalNeed::Unjudged
2781 }
2782
2783 fn receipt_kind(&self, _arguments: &str) -> ToolReceiptKind {
2788 ToolReceiptKind::Generic
2789 }
2790
2791 fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
2795 default_semantics_from_identity(arguments, self.capabilities())
2796 }
2797
2798 fn call_access_manifest(&self, arguments: &str) -> ToolCallAccessManifest {
2801 let semantics = self.call_semantics(arguments);
2802 default_access_manifest(arguments, &semantics)
2803 }
2804
2805 fn guarded_paths(&self, arguments: &str) -> (Vec<String>, Vec<String>) {
2809 let manifest = self.call_access_manifest(arguments);
2810 let values =
2811 |targets: Vec<ToolTargetHint>| targets.into_iter().map(|target| target.value).collect();
2812 (
2813 values(manifest.read_targets),
2814 values(manifest.write_targets),
2815 )
2816 }
2817
2818 fn adapter_owned_access_manifest(&self, _arguments: &str) -> ToolCallAccessManifest {
2823 ToolCallAccessManifest::default()
2824 }
2825
2826 async fn durable_replay_decision(&self, _arguments: &str) -> DurableReplayDecision {
2833 DurableReplayDecision::Replay
2834 }
2835
2836 fn stable_observation_subjects(&self) -> Vec<StableObservationSubject> {
2841 Vec::new()
2842 }
2843
2844 fn call_file_write(&self, _arguments: &str) -> Option<FileWrite> {
2847 None
2848 }
2849
2850 fn file_write_result(
2856 &self,
2857 _arguments: &str,
2858 _current: Option<&[u8]>,
2859 ) -> Option<Result<Vec<u8>, String>> {
2860 None
2861 }
2862
2863 fn call_outbound(&self, _arguments: &str) -> aidaemon_core::Outbound {
2865 aidaemon_core::Outbound::Nothing
2866 }
2867
2868 fn call_effects(&self, _arguments: &str) -> aidaemon_core::CallEffects {
2876 if self.capabilities().read_only {
2877 aidaemon_core::CallEffects::none()
2878 } else {
2879 aidaemon_core::CallEffects::unknown()
2880 }
2881 }
2882
2883 fn named_files(&self, arguments: &str) -> Vec<String> {
2890 declared_named_files(self, arguments)
2891 }
2892
2893 fn call_annotations_in(
2902 &self,
2903 arguments: &str,
2904 _roots: &TrustRoots<'_>,
2905 ) -> aidaemon_core::ToolAnnotations {
2906 default_call_annotations(self.capabilities(), &self.call_semantics(arguments))
2907 }
2908
2909 fn output_trust(
2914 &self,
2915 _arguments: &str,
2916 _roots: &TrustRoots<'_>,
2917 ) -> aidaemon_core::SourceTrust {
2918 if self.capabilities().external_side_effect {
2919 aidaemon_core::SourceTrust::Untrusted
2920 } else {
2921 aidaemon_core::SourceTrust::Trusted
2922 }
2923 }
2924
2925 fn call_title(&self, _arguments: &str) -> Option<String> {
2929 None
2930 }
2931
2932 fn is_available(&self) -> bool {
2937 true
2938 }
2939
2940 fn offered_in_session(&self, _session_id: &str) -> bool {
2947 true
2948 }
2949}
2950
2951pub const EGRESS_EFFECTS: ToolMutationEffects = ToolMutationEffects::EXTERNAL_DELIVERY
2954 .union(ToolMutationEffects::REMOTE_MUTATION)
2955 .union(ToolMutationEffects::REMOTE_DEPLOY)
2956 .union(ToolMutationEffects::DESTRUCTIVE)
2957 .union(ToolMutationEffects::CONFIGURATION);
2958
2959pub fn default_call_annotations(
2962 cap: ToolCapabilities,
2963 semantics: &ToolCallSemantics,
2964) -> aidaemon_core::ToolAnnotations {
2965 let read_only = cap.read_only
2966 || (matches!(
2967 semantics.effect,
2968 ToolCallEffect::Observation | ToolCallEffect::Administrative
2969 ) && !semantics.mutates_state());
2970 let effects = semantics.mutation_effects;
2971 let egress = !read_only
2972 && (effects.intersects(EGRESS_EFFECTS)
2973 || (cap.external_side_effect && !effects.has_specific_effects()));
2974 aidaemon_core::ToolAnnotations {
2975 read_only,
2976 destructive: !read_only && effects.intersects(ToolMutationEffects::DESTRUCTIVE),
2977 idempotent: read_only,
2978 egress,
2979 }
2980}
2981
2982#[derive(Debug, Clone, Default)]
2989pub struct OwnedFolders(std::sync::Arc<std::sync::RwLock<Vec<String>>>);
2990
2991impl OwnedFolders {
2992 pub fn claim(&self, folders: &[String]) {
2994 let mut owned = self.0.write().unwrap_or_else(|e| e.into_inner());
2995 for folder in folders {
2996 let folder = folder.trim();
2997 if std::path::Path::new(folder).is_absolute() && !owned.iter().any(|f| f == folder) {
2998 owned.push(folder.to_string());
2999 }
3000 }
3001 }
3002
3003 pub fn release<P: AsRef<std::path::Path>>(&self, folders: &[P]) {
3005 let mut owned = self.0.write().unwrap_or_else(|e| e.into_inner());
3006 owned.retain(|kept| {
3007 !folders
3008 .iter()
3009 .any(|folder| std::path::Path::new(kept) == folder.as_ref())
3010 });
3011 }
3012
3013 pub fn list(&self) -> Vec<String> {
3015 self.0.read().unwrap_or_else(|e| e.into_inner()).clone()
3016 }
3017
3018 pub fn absent_write_targets(effects: &aidaemon_core::CallEffects) -> Vec<std::path::PathBuf> {
3022 effects
3023 .keys
3024 .iter()
3025 .filter(|key| key.class == aidaemon_core::EffectClass::Write)
3026 .map(|key| std::path::PathBuf::from(shellexpand::tilde(key.target.trim()).as_ref()))
3027 .filter(|path| path.is_absolute() && std::fs::symlink_metadata(path).is_err())
3028 .collect()
3029 }
3030
3031 pub fn claim_created(&self, absent: &[std::path::PathBuf]) -> Vec<String> {
3040 let created: Vec<String> = absent
3041 .iter()
3042 .filter(|path| {
3043 std::fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_dir())
3044 })
3045 .map(|path| path.display().to_string())
3046 .collect();
3047 self.claim(&created);
3048 created
3049 }
3050}
3051
3052#[cfg(test)]
3053mod owned_folder_tests {
3054 use super::OwnedFolders;
3055
3056 #[test]
3059 fn a_folder_a_call_created_becomes_owned() {
3060 let base = tempfile::tempdir().unwrap();
3061 let fresh = base.path().join("claude-drupal-11");
3062 let file = base.path().join("notes.txt");
3063 let before = base.path().join("existing-site");
3064 std::fs::create_dir(&before).unwrap();
3065 let key = |path: &std::path::Path| aidaemon_core::EffectKey {
3066 class: aidaemon_core::EffectClass::Write,
3067 target: path.display().to_string(),
3068 };
3069 let effects = aidaemon_core::CallEffects {
3070 keys: vec![key(&fresh), key(&file), key(&before)],
3071 complete: false,
3072 understood: true,
3073 };
3074 let absent = OwnedFolders::absent_write_targets(&effects);
3075 assert_eq!(absent, vec![fresh.clone(), file.clone()]);
3076 std::fs::create_dir(&fresh).unwrap();
3077 std::fs::write(&file, "x").unwrap();
3078 let owned = OwnedFolders::default();
3079 assert_eq!(
3080 owned.claim_created(&absent),
3081 vec![fresh.display().to_string()]
3082 );
3083 assert_eq!(owned.list(), vec![fresh.display().to_string()]);
3084 }
3085}
3086
3087pub fn within_owned(path: &str, folders: &[String]) -> bool {
3090 let expanded = shellexpand::tilde(path.trim()).into_owned();
3091 let path = std::path::Path::new(&expanded);
3092 path.is_absolute()
3093 && folders.iter().any(|folder| {
3094 aidaemon_policies::resolves_within(path, std::path::Path::new(folder.trim()))
3095 })
3096}
3097
3098#[derive(Debug, Clone, PartialEq, Eq)]
3101pub enum ProducedFile {
3102 Capture(DeliverableKind),
3105 Created,
3107}
3108
3109impl ProducedFile {
3110 pub fn words(&self) -> String {
3112 match self {
3113 Self::Capture(kind) => format!("this request's own capture: {}", kind.words()),
3114 Self::Created => "a file this request's own work created".to_string(),
3115 }
3116 }
3117}
3118
3119#[derive(Debug, Clone, Default)]
3130pub struct ProducedFiles(
3131 std::sync::Arc<std::sync::RwLock<std::collections::HashMap<String, ProducedFile>>>,
3132);
3133
3134impl ProducedFiles {
3135 pub fn note_capture(&self, path: &str, resource_id: Option<&str>, kind: &DeliverableKind) {
3138 let mut produced = self.0.write().unwrap_or_else(|e| e.into_inner());
3139 let capture = ProducedFile::Capture(kind.clone());
3140 produced.insert(produced_key(path), capture.clone());
3141 if let Some(id) = resource_id.map(str::trim).filter(|id| !id.is_empty()) {
3142 produced.insert(id.to_string(), capture);
3143 }
3144 }
3145
3146 pub fn note_created(&self, path: &str, resource_id: Option<&str>) {
3150 let mut produced = self.0.write().unwrap_or_else(|e| e.into_inner());
3151 produced
3152 .entry(produced_key(path))
3153 .or_insert(ProducedFile::Created);
3154 if let Some(id) = resource_id.map(str::trim).filter(|id| !id.is_empty()) {
3155 produced
3156 .entry(id.to_string())
3157 .or_insert(ProducedFile::Created);
3158 }
3159 }
3160
3161 pub fn claim_created(&self, absent: &[std::path::PathBuf]) -> Vec<String> {
3167 let created: Vec<String> = absent
3168 .iter()
3169 .filter(|path| std::fs::symlink_metadata(path).is_ok_and(|meta| meta.is_file()))
3170 .map(|path| path.display().to_string())
3171 .collect();
3172 let mut produced = self.0.write().unwrap_or_else(|e| e.into_inner());
3173 for path in &created {
3174 produced
3175 .entry(produced_key(path))
3176 .or_insert(ProducedFile::Created);
3177 }
3178 created
3179 }
3180
3181 pub fn get(&self, target: &str) -> Option<ProducedFile> {
3184 self.0
3185 .read()
3186 .unwrap_or_else(|e| e.into_inner())
3187 .get(&produced_key(target))
3188 .cloned()
3189 }
3190
3191 pub fn capture_kind(&self, path: &str) -> Option<DeliverableKind> {
3194 match self.get(path)? {
3195 ProducedFile::Capture(kind) => Some(kind),
3196 ProducedFile::Created => None,
3197 }
3198 }
3199
3200 pub fn entries(&self) -> Vec<(String, ProducedFile)> {
3203 self.0
3204 .read()
3205 .unwrap_or_else(|e| e.into_inner())
3206 .iter()
3207 .map(|(key, file)| (key.clone(), file.clone()))
3208 .collect()
3209 }
3210
3211 pub fn named_by(&self, named: &[String]) -> Vec<(String, ProducedFile)> {
3215 named
3216 .iter()
3217 .filter_map(|name| Some((name.clone(), self.get(name)?)))
3218 .collect()
3219 }
3220}
3221
3222pub fn declared_named_files<T: ToolSemantics + ?Sized>(tool: &T, arguments: &str) -> Vec<String> {
3226 let mut named: Vec<String> = Vec::new();
3227 let mut add = |value: &str| {
3228 let value = value.trim();
3229 if !value.is_empty() && !named.iter().any(|known| known == value) {
3230 named.push(value.to_string());
3231 }
3232 };
3233 for hint in tool.call_semantics(arguments).target_hints {
3234 if matches!(
3235 hint.kind,
3236 ToolTargetHintKind::Path | ToolTargetHintKind::ResourceId
3237 ) {
3238 add(&hint.value);
3239 }
3240 }
3241 let manifest = tool.call_access_manifest(arguments);
3242 for hint in manifest
3243 .read_targets
3244 .iter()
3245 .chain(manifest.write_targets.iter())
3246 {
3247 if hint.kind == ToolTargetHintKind::Path {
3248 add(&hint.value);
3249 }
3250 }
3251 for key in tool.call_effects(arguments).keys {
3252 if matches!(
3253 key.class,
3254 aidaemon_core::EffectClass::Write
3255 | aidaemon_core::EffectClass::Delete
3256 | aidaemon_core::EffectClass::Configuration
3257 ) {
3258 add(&key.target);
3259 }
3260 }
3261 named
3262}
3263
3264fn produced_key(target: &str) -> String {
3267 let expanded = shellexpand::tilde(target.trim()).into_owned();
3268 dunce::canonicalize(&expanded)
3269 .map(|path| path.to_string_lossy().into_owned())
3270 .unwrap_or(expanded)
3271}
3272
3273pub fn produced_files(facts: &ToolCallContext) -> Option<&ProducedFiles> {
3276 facts.extensions.get::<ProducedFiles>()
3277}
3278
3279#[cfg(test)]
3280mod produced_file_tests {
3281 use super::{DeliverableKind, ProducedFile, ProducedFiles};
3282
3283 #[test]
3287 fn a_file_a_tool_made_is_the_requests_own_by_path_and_id() {
3288 let produced = ProducedFiles::default();
3289 produced.note_created("/inbox/018d9d29_generated_image.png", Some("res_img"));
3290 assert_eq!(
3291 produced.get("/inbox/018d9d29_generated_image.png"),
3292 Some(ProducedFile::Created)
3293 );
3294 assert_eq!(produced.get("res_img"), Some(ProducedFile::Created));
3295 let page = DeliverableKind::Screenshot {
3296 page: "demo.ddev.site".to_string(),
3297 };
3298 produced.note_capture("/inbox/shot.png", None, &page);
3299 produced.note_created("/inbox/shot.png", None);
3300 assert_eq!(produced.capture_kind("/inbox/shot.png"), Some(page));
3301 }
3302
3303 #[test]
3307 fn the_requests_own_files_come_from_evidence() {
3308 let base = tempfile::tempdir().unwrap();
3309 let shot = base.path().join("ea19c410_screenshot.png");
3310 std::fs::write(&shot, b"png").unwrap();
3311 let page = DeliverableKind::Screenshot {
3312 page: "claude-drupal.ddev.site".to_string(),
3313 };
3314 let produced = ProducedFiles::default();
3315 produced.note_capture(&shot.display().to_string(), Some("res_1"), &page);
3316 let spelled = base
3317 .path()
3318 .join(".")
3319 .join("ea19c410_screenshot.png")
3320 .display()
3321 .to_string();
3322 assert_eq!(produced.capture_kind(&spelled), Some(page.clone()));
3323 assert_eq!(
3324 produced.get("res_1"),
3325 Some(ProducedFile::Capture(page.clone()))
3326 );
3327
3328 let fresh = base.path().join("report.md");
3329 let older = base.path().join("notes.md");
3330 std::fs::write(&older, "x").unwrap();
3331 let absent = vec![fresh.clone(), shot.clone()];
3332 std::fs::write(&fresh, "x").unwrap();
3333 assert_eq!(produced.claim_created(&absent).len(), 2);
3334 assert_eq!(
3335 produced.get(&fresh.display().to_string()),
3336 Some(ProducedFile::Created)
3337 );
3338 assert_eq!(
3339 produced.capture_kind(&shot.display().to_string()),
3340 Some(page)
3341 );
3342 assert_eq!(produced.get(&older.display().to_string()), None);
3343
3344 let named = produced.named_by(&[older.display().to_string(), fresh.display().to_string()]);
3345 assert_eq!(named.len(), 1);
3346 assert_eq!(named[0].1, ProducedFile::Created);
3347 }
3348}
3349
3350pub struct TrustRoots<'a> {
3359 roots: &'a [String],
3360 owned: &'a [String],
3361 cwd: Option<&'a str>,
3362}
3363
3364impl<'a> TrustRoots<'a> {
3365 pub fn new(roots: &'a [String]) -> Self {
3366 Self {
3367 roots,
3368 owned: &[],
3369 cwd: None,
3370 }
3371 }
3372
3373 pub fn with_owned(mut self, owned: &'a [String]) -> Self {
3375 self.owned = owned;
3376 self
3377 }
3378
3379 pub fn with_cwd(mut self, cwd: Option<&'a str>) -> Self {
3381 self.cwd = cwd;
3382 self
3383 }
3384
3385 pub fn anchored_at<'b>(&'b self, cwd: Option<&'b str>) -> TrustRoots<'b> {
3388 TrustRoots {
3389 roots: self.roots,
3390 owned: self.owned,
3391 cwd,
3392 }
3393 }
3394
3395 pub fn holds_effect(&self, path: &str) -> bool {
3400 if self.contains(path) {
3401 return true;
3402 }
3403 let resolved = match self.cwd {
3404 Some(cwd) if !is_absolute_or_home(path) => {
3405 format!("{}/{}", cwd.trim_end_matches('/'), path.trim())
3406 }
3407 _ => path.to_string(),
3408 };
3409 within_owned(&resolved, self.owned)
3410 }
3411
3412 pub fn owns(&self, path: &str) -> bool {
3415 within_owned(path, self.owned)
3416 }
3417
3418 pub fn cwd(&self) -> Option<&str> {
3420 self.cwd
3421 }
3422
3423 pub fn contains(&self, path: &str) -> bool {
3424 let resolved = match self.cwd {
3425 Some(cwd) if !is_absolute_or_home(path) => {
3426 format!("{}/{}", cwd.trim_end_matches('/'), path.trim())
3427 }
3428 _ => path.to_string(),
3429 };
3430 let Some(path) = resolve_absolute(&resolved) else {
3431 return false;
3432 };
3433 self.roots
3434 .iter()
3435 .any(|root| resolve_absolute(root).is_some_and(|root| path.starts_with(&root)))
3436 }
3437}
3438
3439pub fn file_output_trust(
3443 arguments: &str,
3444 keys: &[&str],
3445 roots: &TrustRoots<'_>,
3446) -> aidaemon_core::SourceTrust {
3447 let args = serde_json::from_str::<Value>(arguments).ok();
3448 let path = args.as_ref().and_then(|args| {
3449 keys.iter()
3450 .find_map(|key| args.get(*key).and_then(Value::as_str))
3451 });
3452 match path {
3453 Some(path) if roots.contains(path) => aidaemon_core::SourceTrust::Trusted,
3454 _ => aidaemon_core::SourceTrust::Untrusted,
3455 }
3456}
3457
3458fn resolve_absolute(path: &str) -> Option<std::path::PathBuf> {
3463 use std::path::{Component, PathBuf};
3464 let expanded = shellexpand::tilde(path.trim()).into_owned();
3465 let path = std::path::Path::new(&expanded);
3466 if !path.is_absolute() {
3467 return None;
3468 }
3469 let mut resolved = PathBuf::new();
3470 let mut existing = true;
3471 for component in path.components() {
3472 match component {
3473 Component::CurDir => {}
3474 Component::ParentDir => {
3475 if !resolved.pop() {
3476 return None;
3477 }
3478 }
3479 Component::Normal(part) => {
3480 resolved.push(part);
3481 if existing {
3482 match dunce::canonicalize(&resolved) {
3483 Ok(canonical) => resolved = canonical,
3484 Err(_) => existing = false,
3485 }
3486 }
3487 }
3488 other => resolved.push(other.as_os_str()),
3489 }
3490 }
3491 Some(resolved)
3492}
3493
3494fn is_absolute_or_home(path: &str) -> bool {
3495 let path = path.trim();
3496 let path_ref = std::path::Path::new(path);
3499 path.starts_with('~') || path_ref.is_absolute() || path_ref.has_root()
3500}
3501
3502#[derive(Debug, Clone, PartialEq, Eq)]
3506pub struct PreparedToolInvocation {
3507 pub canonical_arguments: String,
3508 pub semantics: ToolCallSemantics,
3509 pub access_manifest: ToolCallAccessManifest,
3510 pub receipt_kind: ToolReceiptKind,
3511}
3512
3513pub fn prepare_invocation<T: ToolSemantics + ?Sized>(
3517 tool: &T,
3518 arguments: &str,
3519) -> Result<PreparedToolInvocation, ToolArgumentContractViolation> {
3520 let canonical_arguments = tool.canonicalize_arguments(arguments)?;
3521 tool.validate_arguments(&canonical_arguments)?;
3522 Ok(PreparedToolInvocation {
3523 semantics: tool.call_semantics(&canonical_arguments),
3524 access_manifest: tool.call_access_manifest(&canonical_arguments),
3525 receipt_kind: tool.receipt_kind(&canonical_arguments),
3526 canonical_arguments,
3527 })
3528}
3529
3530#[cfg(test)]
3531mod file_trust_tests {
3532 use super::{TrustRoots, file_output_trust};
3533 use aidaemon_core::SourceTrust::{Trusted, Untrusted};
3534
3535 #[test]
3536 fn files_inside_the_trusted_roots_are_trusted() {
3537 let roots = vec!["/tmp/aidaemon-test/ws".to_string()];
3538 let roots = TrustRoots::new(&roots);
3539 let keys = ["path", "file_path"];
3540 assert_eq!(
3541 file_output_trust(r#"{"path":"/tmp/aidaemon-test/ws/a.txt"}"#, &keys, &roots),
3542 Trusted
3543 );
3544 assert_eq!(
3545 file_output_trust(
3546 r#"{"file_path":"/tmp/aidaemon-test/ws/a.txt"}"#,
3547 &keys,
3548 &roots
3549 ),
3550 Trusted
3551 );
3552 assert_eq!(
3553 file_output_trust(r#"{"path":"/etc/hosts"}"#, &keys, &roots),
3554 Untrusted
3555 );
3556 assert_eq!(file_output_trust(r#"{}"#, &keys, &roots), Untrusted);
3557 assert_eq!(file_output_trust("not json", &keys, &roots), Untrusted);
3558 }
3559}
3560
3561fn is_zero(value: &usize) -> bool {
3562 *value == 0
3563}
3564
3565#[cfg(test)]
3566mod local_write_satisfaction_tests {
3567 use super::ToolMutationEffects as E;
3568
3569 #[test]
3572 fn local_write_labels_satisfy_each_other_except_source() {
3573 assert!(E::LOCAL_WORKSPACE_WRITE.satisfies(E::LOCAL_DERIVED_WRITE));
3574 assert!(E::LOCAL_DERIVED_WRITE.satisfies(E::LOCAL_WORKSPACE_WRITE));
3575 assert!(E::LOCAL_SOURCE_WRITE.satisfies(E::LOCAL_DERIVED_WRITE));
3576 assert!(E::LOCAL_SOURCE_WRITE.satisfies(E::LOCAL_WORKSPACE_WRITE));
3577 assert!(!E::LOCAL_WORKSPACE_WRITE.satisfies(E::LOCAL_SOURCE_WRITE));
3578 assert!(!E::LOCAL_DERIVED_WRITE.satisfies(E::LOCAL_SOURCE_WRITE));
3579 assert!(!E::LOCAL_WORKSPACE_WRITE.satisfies(E::EXTERNAL_DELIVERY));
3580 }
3581}