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#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
834#[serde(rename_all = "snake_case")]
835pub enum ToolSemanticFacet {
836 GoalState,
839 Schedule,
840 RunState,
841 Recovery,
842 Control,
843 Measurement,
844 Authorization,
845 Ownership,
846}
847
848impl ToolSemanticFacet {
849 pub const PROTOCOL_NAMES: [&'static str; 8] = [
850 Self::GoalState.as_str(),
851 Self::Schedule.as_str(),
852 Self::RunState.as_str(),
853 Self::Recovery.as_str(),
854 Self::Control.as_str(),
855 Self::Measurement.as_str(),
856 Self::Authorization.as_str(),
857 Self::Ownership.as_str(),
858 ];
859
860 pub const fn as_str(self) -> &'static str {
861 match self {
862 Self::GoalState => "goal_state",
863 Self::Schedule => "schedule",
864 Self::RunState => "run_state",
865 Self::Recovery => "recovery",
866 Self::Control => "control",
867 Self::Measurement => "measurement",
868 Self::Authorization => "authorization",
869 Self::Ownership => "ownership",
870 }
871 }
872}
873
874#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq, Hash)]
878#[serde(rename_all = "snake_case")]
879pub enum ToolCollectionCompleteness {
880 #[default]
881 Unknown,
882 Partial,
883 Complete,
884}
885
886impl ToolCollectionCompleteness {
887 pub const fn satisfies(self, required: Self) -> bool {
888 matches!(required, Self::Unknown)
889 || matches!(required, Self::Partial) && matches!(self, Self::Partial | Self::Complete)
890 || matches!(required, Self::Complete) && matches!(self, Self::Complete)
891 }
892}
893
894#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
898pub struct ToolObservationEvidence {
899 pub subject: ToolTargetHint,
900 #[serde(default, skip_serializing_if = "Vec::is_empty")]
901 pub facets: Vec<ToolSemanticFacet>,
902 #[serde(default, skip_serializing_if = "Vec::is_empty")]
905 pub source_collections: Vec<ToolTargetHint>,
906}
907
908impl ToolObservationEvidence {
909 pub fn new(subject: ToolTargetHint, facets: &[ToolSemanticFacet]) -> Self {
910 Self {
911 subject,
912 facets: facets.to_vec(),
913 source_collections: Vec::new(),
914 }
915 }
916
917 pub fn with_source_collection(mut self, collection: ToolTargetHint) -> Self {
918 if !self.source_collections.contains(&collection) {
919 self.source_collections.push(collection);
920 }
921 self
922 }
923}
924
925#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
930pub struct ToolCollectionObservation {
931 pub collection: ToolTargetHint,
932 #[serde(default, skip_serializing_if = "Vec::is_empty")]
933 pub facets: Vec<ToolSemanticFacet>,
934 #[serde(default)]
935 pub completeness: ToolCollectionCompleteness,
936 #[serde(default)]
937 pub returned_count: usize,
938 #[serde(default, skip_serializing_if = "Option::is_none")]
939 pub total_count: Option<usize>,
940 #[serde(default, skip_serializing_if = "Vec::is_empty")]
941 pub members: Vec<ToolTargetHint>,
942}
943
944impl ToolCollectionObservation {
945 pub fn complete(
946 collection: ToolTargetHint,
947 facets: &[ToolSemanticFacet],
948 members: Vec<ToolTargetHint>,
949 ) -> Self {
950 let returned_count = members.len();
951 Self {
952 collection,
953 facets: facets.to_vec(),
954 completeness: ToolCollectionCompleteness::Complete,
955 returned_count,
956 total_count: Some(returned_count),
957 members,
958 }
959 }
960}
961
962#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
968pub struct StableObservationSubject {
969 #[serde(default, skip_serializing_if = "Option::is_none")]
972 pub resource_id: Option<String>,
973 #[serde(default, skip_serializing_if = "Vec::is_empty")]
975 pub facets: Vec<ToolSemanticFacet>,
976 #[serde(default, skip_serializing_if = "Vec::is_empty")]
980 pub member_namespaces: Vec<String>,
981 pub summary: String,
983}
984
985impl StableObservationSubject {
986 pub fn collection(
987 resource_id: impl Into<String>,
988 facets: &[ToolSemanticFacet],
989 member_namespace: impl Into<String>,
990 summary: impl Into<String>,
991 ) -> Self {
992 Self {
993 resource_id: Some(resource_id.into()),
994 facets: facets.to_vec(),
995 member_namespaces: vec![member_namespace.into()],
996 summary: summary.into(),
997 }
998 }
999
1000 pub fn namespace(prefix: impl Into<String>, summary: impl Into<String>) -> Self {
1001 Self {
1002 resource_id: None,
1003 facets: Vec::new(),
1004 member_namespaces: vec![prefix.into()],
1005 summary: summary.into(),
1006 }
1007 }
1008
1009 pub fn binds(&self, value: &str) -> bool {
1012 self.resource_id.as_deref() == Some(value)
1013 || self
1014 .member_namespaces
1015 .iter()
1016 .any(|prefix| value.len() > prefix.len() && value.starts_with(prefix.as_str()))
1017 }
1018}
1019
1020#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
1024#[serde(rename_all = "UPPERCASE")]
1025pub enum ToolCallOperation {
1026 Get,
1027 Head,
1028 Options,
1029 Post,
1030 Put,
1031 Patch,
1032 Delete,
1033}
1034
1035impl ToolCallOperation {
1036 pub const fn from_http_method(method: &str) -> Option<Self> {
1037 match method.as_bytes() {
1038 b"GET" => Some(Self::Get),
1039 b"HEAD" => Some(Self::Head),
1040 b"OPTIONS" => Some(Self::Options),
1041 b"POST" => Some(Self::Post),
1042 b"PUT" => Some(Self::Put),
1043 b"PATCH" => Some(Self::Patch),
1044 b"DELETE" => Some(Self::Delete),
1045 _ => None,
1046 }
1047 }
1048}
1049
1050#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1052pub struct ToolCallSemantics {
1053 #[serde(default)]
1054 pub effect: ToolCallEffect,
1055 #[serde(default)]
1056 pub verification_mode: ToolVerificationMode,
1057 #[serde(default, skip_serializing_if = "ToolMutationEffects::is_empty")]
1060 pub mutation_effects: ToolMutationEffects,
1061 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1062 pub target_hints: Vec<ToolTargetHint>,
1063 #[serde(default, skip_serializing_if = "Option::is_none")]
1067 pub operation: Option<ToolCallOperation>,
1068 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1072 pub evidence: Vec<ToolEvidenceCapability>,
1073}
1074
1075#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
1082pub struct ToolCallAccessManifest {
1083 #[serde(default, skip_serializing_if = "Option::is_none")]
1084 pub execution_cwd: Option<String>,
1085 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1086 pub read_targets: Vec<ToolTargetHint>,
1087 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1088 pub write_targets: Vec<ToolTargetHint>,
1089 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1095 pub adapter_read_targets: Vec<ToolTargetHint>,
1096}
1097
1098impl ToolCallSemantics {
1099 pub fn with_untyped_change(&self) -> Self {
1103 let mut changed = self.clone();
1104 changed.mutation_effects = changed
1105 .mutation_effects
1106 .union(ToolMutationEffects::UNSPECIFIED);
1107 changed.effect = if changed.observes_state() {
1108 ToolCallEffect::ObservationAndMutation
1109 } else {
1110 ToolCallEffect::Mutation
1111 };
1112 changed
1113 }
1114
1115 pub fn administrative() -> Self {
1116 Self {
1117 effect: ToolCallEffect::Administrative,
1118 ..Self::default()
1119 }
1120 }
1121
1122 pub fn observation() -> Self {
1123 Self {
1124 effect: ToolCallEffect::Observation,
1125 ..Self::default()
1126 }
1127 }
1128
1129 pub fn mutation() -> Self {
1130 Self {
1131 effect: ToolCallEffect::Mutation,
1132 mutation_effects: ToolMutationEffects::UNSPECIFIED,
1133 ..Self::default()
1134 }
1135 }
1136
1137 pub fn observation_and_mutation() -> Self {
1138 Self {
1139 effect: ToolCallEffect::ObservationAndMutation,
1140 mutation_effects: ToolMutationEffects::UNSPECIFIED,
1141 ..Self::default()
1142 }
1143 }
1144
1145 pub fn mutation_with(mutation_effects: ToolMutationEffects) -> Self {
1146 Self {
1147 effect: ToolCallEffect::Mutation,
1148 mutation_effects: if mutation_effects.is_empty() {
1149 ToolMutationEffects::UNSPECIFIED
1150 } else {
1151 mutation_effects
1152 },
1153 ..Self::default()
1154 }
1155 }
1156
1157 pub fn observation_and_mutation_with(mutation_effects: ToolMutationEffects) -> Self {
1158 Self {
1159 effect: ToolCallEffect::ObservationAndMutation,
1160 mutation_effects: if mutation_effects.is_empty() {
1161 ToolMutationEffects::UNSPECIFIED
1162 } else {
1163 mutation_effects
1164 },
1165 ..Self::default()
1166 }
1167 }
1168
1169 pub fn with_verification_mode(mut self, verification_mode: ToolVerificationMode) -> Self {
1170 self.verification_mode = verification_mode;
1171 self
1172 }
1173
1174 pub fn with_target_hint(mut self, kind: ToolTargetHintKind, value: impl Into<String>) -> Self {
1175 if let Some(target) = ToolTargetHint::new(kind, value) {
1176 self.target_hints.push(target);
1177 }
1178 self
1179 }
1180
1181 pub fn with_operation(mut self, operation: ToolCallOperation) -> Self {
1182 self.operation = Some(operation);
1183 self
1184 }
1185
1186 pub fn with_evidence(mut self, evidence: Vec<ToolEvidenceCapability>) -> Self {
1187 self.evidence = evidence;
1188 self
1189 }
1190
1191 pub fn observes_state(&self) -> bool {
1192 self.effect.observes_state()
1193 }
1194
1195 pub fn mutates_state(&self) -> bool {
1196 self.effect.mutates_state() || !self.mutation_effects.is_empty()
1197 }
1198
1199 pub fn can_verify_with_result_content(&self) -> bool {
1200 self.verification_mode == ToolVerificationMode::ResultContent
1201 }
1202
1203 pub fn is_empty(&self) -> bool {
1204 self.effect == ToolCallEffect::Unknown
1205 && self.verification_mode == ToolVerificationMode::None
1206 && self.mutation_effects.is_empty()
1207 && self.target_hints.is_empty()
1208 && self.operation.is_none()
1209 && self.evidence.is_empty()
1210 }
1211
1212 pub fn merge_missing_from(&mut self, fallback: Self) {
1213 if self.effect == ToolCallEffect::Unknown {
1214 self.effect = fallback.effect;
1215 }
1216 if self.verification_mode == ToolVerificationMode::None {
1217 self.verification_mode = fallback.verification_mode;
1218 }
1219 if self.mutation_effects.is_empty()
1223 && (self.effect == ToolCallEffect::Unknown || self.effect.mutates_state())
1224 {
1225 self.mutation_effects = fallback.mutation_effects;
1226 }
1227 if self.target_hints.is_empty() {
1228 self.target_hints = fallback.target_hints;
1229 }
1230 if self.operation.is_none() {
1231 self.operation = fallback.operation;
1232 }
1233 if self.evidence.is_empty() {
1234 self.evidence = fallback.evidence;
1235 }
1236 }
1237}
1238
1239#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1240#[serde(rename_all = "snake_case")]
1241pub enum ReadFileSelectionMetadata {
1242 Full,
1243 BoundedRange { start_line: usize, end_line: usize },
1244 OpenEndedRange { start_line: usize },
1245 Tail { requested_lines: usize },
1246}
1247
1248#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1249pub struct ReadFileResultMetadata {
1250 pub display_path: String,
1251 pub canonical_path: String,
1252 pub selection: ReadFileSelectionMetadata,
1253 pub returned_start_line: Option<usize>,
1254 pub returned_end_line: Option<usize>,
1255 pub total_lines: usize,
1256 pub file_size: u64,
1257 #[serde(skip_serializing_if = "Option::is_none")]
1258 pub modified: Option<String>,
1259 pub selected_lines: Vec<String>,
1260 #[serde(default)]
1264 pub truncated: bool,
1265}
1266
1267#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1273pub struct TruncationInfo {
1274 pub shown_chars: usize,
1275 pub total_chars: usize,
1276 #[serde(default, skip_serializing_if = "Option::is_none")]
1278 pub remediation_hint: Option<String>,
1279}
1280
1281#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
1283#[serde(rename_all = "snake_case")]
1284pub enum ToolResultCompleteness {
1285 Complete,
1286 Truncated,
1287 #[default]
1288 Unavailable,
1289}
1290
1291impl ToolResultCompleteness {
1292 pub const fn as_str(self) -> &'static str {
1293 match self {
1294 Self::Complete => "complete",
1295 Self::Truncated => "truncated",
1296 Self::Unavailable => "unavailable",
1297 }
1298 }
1299}
1300
1301#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
1303#[serde(rename_all = "snake_case")]
1304pub enum ToolResultContentSource {
1305 ToolOutput,
1306 DurableReplay,
1307 SpillPreview,
1308 PersistentSummary,
1309 #[default]
1310 Unavailable,
1311}
1312
1313impl ToolResultContentSource {
1314 pub const fn as_str(self) -> &'static str {
1315 match self {
1316 Self::ToolOutput => "tool_output",
1317 Self::DurableReplay => "durable_replay",
1318 Self::SpillPreview => "spill_preview",
1319 Self::PersistentSummary => "persistent_summary",
1320 Self::Unavailable => "unavailable",
1321 }
1322 }
1323}
1324
1325#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1329pub struct ToolResultProvenance {
1330 #[serde(default, skip_serializing_if = "Option::is_none")]
1331 pub result_id: Option<String>,
1332 #[serde(default, skip_serializing_if = "Option::is_none")]
1333 pub sha256: Option<String>,
1334 #[serde(default)]
1335 pub source: ToolResultContentSource,
1336 #[serde(default)]
1337 pub model_view_completeness: ToolResultCompleteness,
1338 #[serde(default)]
1339 pub durable_view_completeness: ToolResultCompleteness,
1340 #[serde(default)]
1341 pub authoritative_chars: usize,
1342 #[serde(default)]
1343 pub model_visible_chars: usize,
1344 #[serde(default)]
1345 pub durable_chars: usize,
1346 #[serde(default, skip_serializing_if = "Option::is_none")]
1347 pub requested_range: Option<ReadFileSelectionMetadata>,
1348 #[serde(default, skip_serializing_if = "Option::is_none")]
1349 pub returned_start_line: Option<usize>,
1350 #[serde(default, skip_serializing_if = "Option::is_none")]
1351 pub returned_end_line: Option<usize>,
1352}
1353
1354#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1359#[serde(rename_all = "snake_case")]
1360pub enum AuthorizationPreflightStatus {
1361 Ready,
1362 Blocked,
1363 Unverifiable,
1364}
1365
1366#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1367pub struct AuthorizationPreflightRecord {
1368 pub schema_version: u16,
1369 pub status: AuthorizationPreflightStatus,
1370 pub intended_operation: String,
1371 pub target_digest: String,
1372 #[serde(default, skip_serializing_if = "Option::is_none")]
1373 pub auth_profile: Option<String>,
1374 #[serde(default, skip_serializing_if = "Option::is_none")]
1375 pub account_id: Option<String>,
1376 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1379 pub authorized_scopes: Vec<String>,
1380 #[serde(default, skip_serializing_if = "Option::is_none")]
1381 pub credential_generation: Option<String>,
1382 #[serde(default, skip_serializing_if = "Option::is_none")]
1383 pub refresh_result: Option<String>,
1384 #[serde(default, skip_serializing_if = "Option::is_none")]
1385 pub reason_code: Option<String>,
1386 pub checked_at: String,
1387}
1388
1389impl AuthorizationPreflightRecord {
1390 pub const SCHEMA_VERSION: u16 = 1;
1391
1392 pub const fn permits_io(&self) -> bool {
1393 matches!(self.status, AuthorizationPreflightStatus::Ready)
1394 }
1395}
1396
1397impl ToolResultProvenance {
1398 pub fn from_authoritative_result(
1399 result: &str,
1400 metadata: &ToolCallMetadata,
1401 source: ToolResultContentSource,
1402 ) -> Self {
1403 use sha2::{Digest, Sha256};
1404
1405 let sha256 = hex::encode(Sha256::digest(result.as_bytes()));
1406 let chars = result.chars().count();
1407 let tool_truncated = metadata.truncation.is_some()
1408 || metadata
1409 .read_file
1410 .as_ref()
1411 .is_some_and(|read| read.truncated);
1412 let completeness = if tool_truncated {
1413 ToolResultCompleteness::Truncated
1414 } else {
1415 ToolResultCompleteness::Complete
1416 };
1417 let read = metadata.read_file.as_ref();
1418 Self {
1419 result_id: Some(format!("sha256:{sha256}")),
1420 sha256: Some(sha256),
1421 source,
1422 model_view_completeness: completeness,
1423 durable_view_completeness: completeness,
1424 authoritative_chars: chars,
1425 model_visible_chars: chars,
1426 durable_chars: chars,
1427 requested_range: read.map(|read| read.selection.clone()),
1428 returned_start_line: read.and_then(|read| read.returned_start_line),
1429 returned_end_line: read.and_then(|read| read.returned_end_line),
1430 }
1431 }
1432
1433 pub fn mark_model_view_truncated(&mut self, visible_result: &str) {
1434 self.model_visible_chars = visible_result.chars().count();
1435 self.model_view_completeness = ToolResultCompleteness::Truncated;
1436 }
1437
1438 pub fn record_durable_view(&mut self, durable_result: &str, is_summary: bool) {
1439 self.durable_chars = durable_result.chars().count();
1440 if is_summary {
1441 self.durable_view_completeness = ToolResultCompleteness::Truncated;
1442 self.source = ToolResultContentSource::PersistentSummary;
1443 } else {
1444 self.durable_view_completeness = self.model_view_completeness;
1445 }
1446 }
1447}
1448
1449#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1453#[serde(rename_all = "snake_case")]
1454pub enum ToolOutcomeStatus {
1455 Succeeded,
1456 CompletedWithNegativeResult,
1457 FailedRetryable,
1458 FailedPermanent,
1459 Blocked,
1460 Backgrounded,
1461}
1462
1463#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
1470#[serde(rename_all = "snake_case")]
1471pub enum ToolInvocationStage {
1472 #[default]
1474 Unknown,
1475 RejectedBeforeDispatch,
1477 RejectedBeforeIo,
1479 Dispatched,
1481 Replayed,
1483}
1484
1485impl ToolInvocationStage {
1486 pub const fn as_str(self) -> &'static str {
1487 match self {
1488 Self::Unknown => "unknown",
1489 Self::RejectedBeforeDispatch => "rejected_before_dispatch",
1490 Self::RejectedBeforeIo => "rejected_before_io",
1491 Self::Dispatched => "dispatched",
1492 Self::Replayed => "replayed",
1493 }
1494 }
1495
1496 pub const fn reached_dispatch(self) -> bool {
1497 matches!(self, Self::Dispatched | Self::Replayed)
1498 }
1499
1500 pub const fn performed_io(self) -> bool {
1503 matches!(self, Self::Dispatched)
1504 }
1505}
1506
1507#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
1514#[serde(rename_all = "snake_case")]
1515pub enum ToolReceiptKind {
1516 #[default]
1517 Generic,
1518 Process,
1519 Http,
1520}
1521
1522#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
1525#[serde(rename_all = "snake_case")]
1526pub enum ToolAccessEnforcement {
1527 #[default]
1529 Unknown,
1530 NotApplicable,
1532 AdapterEnforced,
1534 ControllerEnforced,
1537 KernelEnforced,
1539}
1540
1541#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1546pub struct ToolAccessDenial {
1547 pub reason_code: String,
1548 pub enforcement: ToolAccessEnforcement,
1549 #[serde(default, skip_serializing_if = "Option::is_none")]
1550 pub exit_code: Option<i32>,
1551 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1556 pub proposed_evidence: Vec<ToolEvidenceCapability>,
1557}
1558
1559impl ToolOutcomeStatus {
1560 pub const fn from_process_exit_code(code: i32) -> Self {
1566 if code == 0 {
1567 Self::Succeeded
1568 } else if code > 0 {
1569 Self::CompletedWithNegativeResult
1570 } else {
1571 Self::FailedPermanent
1572 }
1573 }
1574
1575 pub const fn as_str(self) -> &'static str {
1576 match self {
1577 Self::Succeeded => "succeeded",
1578 Self::CompletedWithNegativeResult => "completed_with_negative_result",
1579 Self::FailedRetryable => "failed_retryable",
1580 Self::FailedPermanent => "failed_permanent",
1581 Self::Blocked => "blocked",
1582 Self::Backgrounded => "backgrounded",
1583 }
1584 }
1585
1586 pub fn satisfies_requested_condition(self) -> bool {
1587 matches!(self, Self::Succeeded)
1588 }
1589
1590 pub fn is_failure(self) -> bool {
1591 matches!(
1592 self,
1593 Self::FailedRetryable | Self::FailedPermanent | Self::Blocked
1594 )
1595 }
1596}
1597
1598#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1604#[serde(rename_all = "snake_case")]
1605pub enum ToolResultPresentation {
1606 NaturalSummary,
1607 DiagnosticDetail,
1608}
1609
1610#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
1615pub struct ToolCallMetadata {
1616 #[serde(default)]
1620 pub receipt_kind: ToolReceiptKind,
1621 #[serde(default, skip_serializing_if = "Option::is_none")]
1624 pub access_manifest: Option<ToolCallAccessManifest>,
1625 #[serde(default)]
1628 pub access_enforcement: ToolAccessEnforcement,
1629 #[serde(default, skip_serializing_if = "Option::is_none")]
1632 pub access_denial: Option<ToolAccessDenial>,
1633 #[serde(default, skip_serializing_if = "Option::is_none")]
1637 pub outcome_status: Option<ToolOutcomeStatus>,
1638 #[serde(default)]
1641 pub invocation_stage: ToolInvocationStage,
1642 #[serde(default)]
1646 pub contract_rejected: bool,
1647 #[serde(default, skip_serializing_if = "Option::is_none")]
1650 pub effective_tool_name: Option<String>,
1651 #[serde(default)]
1654 pub receipt_replayed: bool,
1655 #[serde(skip_serializing_if = "Option::is_none")]
1657 pub exit_code: Option<i32>,
1658 #[serde(default)]
1660 pub timed_out: bool,
1661 #[serde(default)]
1663 pub background_started: bool,
1664 #[serde(default)]
1666 pub detached: bool,
1667 #[serde(default)]
1670 pub completion_notifications_enabled: bool,
1671 #[serde(skip_serializing_if = "Option::is_none")]
1673 pub transport_error: Option<String>,
1674 #[serde(default, skip_serializing_if = "Option::is_none")]
1677 pub http_status: Option<u16>,
1678 #[serde(default, skip_serializing_if = "Option::is_none")]
1682 pub created_resource_id: Option<String>,
1683 #[serde(default, skip_serializing_if = "Option::is_none")]
1686 pub truncation: Option<TruncationInfo>,
1687 #[serde(default, skip_serializing_if = "Option::is_none")]
1690 pub result_provenance: Option<ToolResultProvenance>,
1691 #[serde(default, skip_serializing_if = "Option::is_none")]
1694 pub authorization_preflight: Option<AuthorizationPreflightRecord>,
1695 #[serde(default)]
1701 pub background_handoff: bool,
1702 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1707 pub background_settled: bool,
1708 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1714 pub background_run_labels: Vec<String>,
1715 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1719 pub checklist_items: Vec<usize>,
1720 #[serde(default, skip_serializing_if = "is_zero")]
1726 pub launched_runs: usize,
1727 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1732 pub changes_untyped: bool,
1733 #[serde(default, skip_serializing_if = "ToolCallSemantics::is_empty")]
1735 pub semantics: ToolCallSemantics,
1736 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1740 pub observations: Vec<ToolObservationEvidence>,
1741 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1743 pub collection_observations: Vec<ToolCollectionObservation>,
1744 #[serde(skip_serializing_if = "Option::is_none")]
1746 pub read_file: Option<ReadFileResultMetadata>,
1747 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1749 pub attachments: Vec<MessageAttachment>,
1750 #[serde(default, skip_serializing_if = "Option::is_none")]
1754 pub runtime_preparation_failure: Option<Box<RuntimePreparationFailure>>,
1755 #[serde(default)]
1759 pub untrusted_verbatim: bool,
1760 #[serde(default)]
1763 pub preserve_inline: bool,
1764 #[serde(default, skip_serializing_if = "Option::is_none")]
1767 pub persistent_output: Option<String>,
1768 #[serde(default)]
1770 pub suppress_activity_result: bool,
1771 #[serde(default, skip_serializing_if = "Option::is_none")]
1776 pub presentation: Option<ToolResultPresentation>,
1777 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1781 pub internal_identifiers: Vec<String>,
1782 #[serde(default, skip_serializing_if = "Option::is_none")]
1786 pub output_trust: Option<aidaemon_core::SourceTrust>,
1787}
1788
1789#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1790pub struct ToolCallOutcome {
1791 pub output: String,
1792 #[serde(default)]
1793 pub metadata: ToolCallMetadata,
1794 #[serde(default, skip_serializing_if = "Option::is_none")]
1799 pub finish: Option<aidaemon_core::Finish>,
1800}
1801
1802#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1807pub struct RuntimePreparationFailure {
1808 pub field: String,
1810 pub value: String,
1812 pub error: String,
1814}
1815
1816impl ToolCallOutcome {
1817 pub fn from_output(output: String) -> Self {
1818 Self {
1819 output,
1820 metadata: ToolCallMetadata::default(),
1821 finish: None,
1822 }
1823 }
1824
1825 pub fn contract_rejection(output: impl Into<String>) -> Self {
1826 Self {
1827 output: output.into(),
1828 metadata: ToolCallMetadata {
1829 outcome_status: Some(ToolOutcomeStatus::Blocked),
1833 invocation_stage: ToolInvocationStage::RejectedBeforeIo,
1834 contract_rejected: true,
1835 semantics: ToolCallSemantics::observation()
1840 .with_verification_mode(ToolVerificationMode::ResultContent),
1841 ..ToolCallMetadata::default()
1842 },
1843 finish: None,
1844 }
1845 }
1846
1847 pub fn blocked(output: impl Into<String>) -> Self {
1848 Self {
1849 output: output.into(),
1850 metadata: ToolCallMetadata {
1851 outcome_status: Some(ToolOutcomeStatus::Blocked),
1852 ..ToolCallMetadata::default()
1853 },
1854 finish: None,
1855 }
1856 }
1857
1858 pub fn runtime_preparation_failure(
1862 field: impl Into<String>,
1863 value: impl Into<String>,
1864 error: impl std::fmt::Display,
1865 ) -> Self {
1866 let field = field.into();
1867 let value = value.into();
1868 let error = error.to_string();
1869 Self {
1870 output: format!(
1871 "Error: the runtime could not prepare `{field}` entry `{value}` before running the command: {error}"
1872 ),
1873 metadata: ToolCallMetadata {
1874 outcome_status: Some(ToolOutcomeStatus::Blocked),
1875 invocation_stage: ToolInvocationStage::RejectedBeforeIo,
1876 semantics: ToolCallSemantics::observation()
1877 .with_verification_mode(ToolVerificationMode::ResultContent),
1878 runtime_preparation_failure: Some(Box::new(RuntimePreparationFailure {
1879 field,
1880 value,
1881 error,
1882 })),
1883 ..ToolCallMetadata::default()
1884 },
1885 finish: None,
1886 }
1887 }
1888
1889 pub fn completed_negative_result(output: impl Into<String>) -> Self {
1890 Self {
1891 output: output.into(),
1892 metadata: ToolCallMetadata {
1893 outcome_status: Some(ToolOutcomeStatus::CompletedWithNegativeResult),
1894 ..ToolCallMetadata::default()
1895 },
1896 finish: None,
1897 }
1898 }
1899
1900 pub fn with_finish(mut self, finish: aidaemon_core::Finish) -> Self {
1902 self.finish = Some(finish);
1903 self
1904 }
1905
1906 pub fn handed_to_background(mut self) -> Self {
1911 self.metadata.background_handoff = true;
1912 self.finish = Some(aidaemon_core::Finish::new(
1913 aidaemon_core::FinishOutcome::Partial,
1914 None,
1915 ));
1916 self
1917 }
1918
1919 pub fn with_semantics(mut self, semantics: ToolCallSemantics) -> Self {
1920 self.metadata.semantics = semantics;
1921 self
1922 }
1923
1924 pub fn with_observation_evidence(
1925 mut self,
1926 observations: Vec<ToolObservationEvidence>,
1927 collection_observations: Vec<ToolCollectionObservation>,
1928 ) -> Self {
1929 self.metadata.observations = observations;
1930 self.metadata.collection_observations = collection_observations;
1931 self
1932 }
1933}
1934
1935impl ToolCapabilities {
1936 pub const READ_ONLY: Self = Self {
1938 read_only: true,
1939 external_side_effect: false,
1940 needs_approval: false,
1941 idempotent: true,
1942 high_impact_write: false,
1943 };
1944 pub const EXTERNAL_HIGH_IMPACT: Self = Self {
1946 read_only: false,
1947 external_side_effect: true,
1948 needs_approval: true,
1949 idempotent: false,
1950 high_impact_write: true,
1951 };
1952 pub const LOCAL_WRITE: Self = Self {
1954 read_only: false,
1955 external_side_effect: false,
1956 needs_approval: false,
1957 idempotent: false,
1958 high_impact_write: false,
1959 };
1960 pub const EXTERNAL_WRITE: Self = Self {
1962 read_only: false,
1963 external_side_effect: true,
1964 needs_approval: false,
1965 idempotent: false,
1966 high_impact_write: false,
1967 };
1968 pub const IDEMPOTENT_LOCAL_WRITE: Self = Self {
1970 read_only: false,
1971 external_side_effect: false,
1972 needs_approval: false,
1973 idempotent: true,
1974 high_impact_write: false,
1975 };
1976 pub const READ_ONLY_EXTERNAL: Self = Self {
1978 read_only: true,
1979 external_side_effect: true,
1980 needs_approval: false,
1981 idempotent: true,
1982 high_impact_write: false,
1983 };
1984 pub const APPROVED_HIGH_IMPACT_LOCAL: Self = Self {
1986 read_only: false,
1987 external_side_effect: false,
1988 needs_approval: true,
1989 idempotent: false,
1990 high_impact_write: true,
1991 };
1992 pub const IDEMPOTENT_EXTERNAL_WRITE: Self = Self {
1994 read_only: false,
1995 external_side_effect: true,
1996 needs_approval: false,
1997 idempotent: true,
1998 high_impact_write: false,
1999 };
2000}
2001
2002impl Default for ToolCapabilities {
2003 fn default() -> Self {
2004 Self {
2005 read_only: false,
2006 external_side_effect: false,
2007 needs_approval: true,
2008 idempotent: false,
2009 high_impact_write: false,
2010 }
2011 }
2012}
2013
2014fn string_to_target_hint(key: &str, value: &str) -> Option<ToolTargetHint> {
2015 let trimmed = value.trim();
2016 if trimmed.is_empty() {
2017 return None;
2018 }
2019
2020 let lower_key = key.to_ascii_lowercase();
2021 if lower_key == "resource_id" {
2022 return ToolTargetHint::new(ToolTargetHintKind::ResourceId, trimmed);
2023 }
2024
2025 if matches!(
2026 lower_key.as_str(),
2027 "url" | "verify_url" | "callback_url" | "target_url" | "auth_url"
2028 ) || trimmed.starts_with("http://")
2029 || trimmed.starts_with("https://")
2030 {
2031 return ToolTargetHint::new(ToolTargetHintKind::Url, trimmed);
2032 }
2033
2034 if matches!(
2035 lower_key.as_str(),
2036 "path"
2037 | "file_path"
2038 | "working_dir"
2039 | "cwd"
2040 | "directory"
2041 | "dir"
2042 | "repo_path"
2043 | "repo_dir"
2044 | "resource_path"
2045 ) {
2046 return ToolTargetHint::new(ToolTargetHintKind::Path, trimmed);
2047 }
2048
2049 if matches!(
2050 lower_key.as_str(),
2051 "project_path" | "project_dir" | "scope" | "project_scope"
2052 ) {
2053 return ToolTargetHint::new(ToolTargetHintKind::ProjectScope, trimmed);
2054 }
2055
2056 None
2057}
2058
2059fn push_unique_target_hint(hints: &mut Vec<ToolTargetHint>, candidate: Option<ToolTargetHint>) {
2060 let Some(candidate) = candidate else {
2061 return;
2062 };
2063 if !hints.iter().any(|existing| existing == &candidate) {
2064 hints.push(candidate);
2065 }
2066}
2067
2068fn collect_common_target_hints(arguments: &str) -> Vec<ToolTargetHint> {
2069 let parsed = match serde_json::from_str::<Value>(arguments) {
2070 Ok(Value::Object(map)) => map,
2071 _ => return Vec::new(),
2072 };
2073
2074 let mut hints = Vec::new();
2075 for (key, value) in &parsed {
2076 match value {
2077 Value::String(s) => push_unique_target_hint(&mut hints, string_to_target_hint(key, s)),
2078 Value::Array(items) if matches!(key.as_str(), "paths" | "urls") => {
2079 for item in items.iter().filter_map(|item| item.as_str()) {
2080 push_unique_target_hint(&mut hints, string_to_target_hint(key, item));
2081 }
2082 }
2083 _ => {}
2084 }
2085 }
2086 hints
2087}
2088
2089fn default_access_manifest(
2090 arguments: &str,
2091 semantics: &ToolCallSemantics,
2092) -> ToolCallAccessManifest {
2093 let parsed = serde_json::from_str::<Value>(arguments).ok();
2094 let execution_cwd = parsed.as_ref().and_then(|value| {
2095 value
2096 .get("working_dir")
2097 .or_else(|| value.get("cwd"))
2098 .and_then(Value::as_str)
2099 .map(str::trim)
2100 .filter(|value| !value.is_empty())
2101 .map(str::to_string)
2102 });
2103 let targets = if semantics.target_hints.is_empty() {
2104 collect_common_target_hints(arguments)
2105 } else {
2106 semantics.target_hints.clone()
2107 };
2108 let non_cwd_targets = targets
2109 .into_iter()
2110 .filter(|target| {
2111 matches!(
2112 target.kind,
2113 ToolTargetHintKind::Path | ToolTargetHintKind::ProjectScope
2114 )
2115 })
2116 .filter(|target| execution_cwd.as_deref() != Some(target.value.as_str()))
2117 .collect::<Vec<_>>();
2118 let mut read_targets = Vec::new();
2119 if let Some(cwd) = execution_cwd.as_deref()
2120 && let Some(target) = ToolTargetHint::new(ToolTargetHintKind::ProjectScope, cwd)
2121 {
2122 read_targets.push(target);
2123 }
2124 if semantics.observes_state() {
2125 read_targets.extend(non_cwd_targets.iter().cloned());
2126 }
2127 let write_targets = if semantics.mutates_state() {
2128 non_cwd_targets
2129 } else {
2130 Vec::new()
2131 };
2132 ToolCallAccessManifest {
2133 execution_cwd,
2134 read_targets,
2135 write_targets,
2136 adapter_read_targets: Vec::new(),
2137 }
2138}
2139
2140pub fn semantics_for_exact_read_actions(
2147 arguments: &str,
2148 read_actions: &[&str],
2149 mutation_effects: ToolMutationEffects,
2150) -> ToolCallSemantics {
2151 let action = serde_json::from_str::<Value>(arguments)
2152 .ok()
2153 .and_then(|value| {
2154 value
2155 .get("action")
2156 .and_then(Value::as_str)
2157 .map(str::to_string)
2158 });
2159 let mut semantics = if action
2160 .as_deref()
2161 .is_some_and(|action| read_actions.contains(&action))
2162 {
2163 ToolCallSemantics::observation().with_verification_mode(ToolVerificationMode::ResultContent)
2164 } else if mutation_effects.is_empty() {
2165 ToolCallSemantics::mutation()
2166 } else {
2167 ToolCallSemantics::mutation_with(mutation_effects)
2168 };
2169 for target_hint in collect_common_target_hints(arguments) {
2170 semantics = semantics.with_target_hint(target_hint.kind, target_hint.value);
2171 }
2172 semantics
2173}
2174
2175fn default_semantics_from_identity(arguments: &str, caps: ToolCapabilities) -> ToolCallSemantics {
2176 let mut semantics = if caps.read_only {
2177 ToolCallSemantics::observation().with_verification_mode(ToolVerificationMode::ResultContent)
2178 } else {
2179 ToolCallSemantics::mutation()
2184 };
2185
2186 for target_hint in collect_common_target_hints(arguments) {
2187 semantics = semantics.with_target_hint(target_hint.kind, target_hint.value);
2188 }
2189 semantics
2190}
2191
2192#[derive(Debug, Clone, PartialEq, Eq)]
2195pub enum ApprovalScope {
2196 Call,
2198 Request { method: String, url: String },
2201}
2202
2203pub fn require_call_approval(scope: Option<&ApprovalScope>, what: &str) -> anyhow::Result<()> {
2207 if scope != Some(&ApprovalScope::Call) {
2208 anyhow::bail!(
2209 "{what} requires approval through the agent kernel; it was called outside an \
2210 approved agent call"
2211 );
2212 }
2213 Ok(())
2214}
2215
2216#[derive(Debug, Clone, Copy)]
2219pub struct ApprovalCall<'a> {
2220 pub arguments: &'a Value,
2224 pub as_sent: &'a Value,
2227 pub refused: bool,
2230}
2231
2232impl<'a> ApprovalCall<'a> {
2233 pub fn as_sent(arguments: &'a Value) -> Self {
2235 Self {
2236 arguments,
2237 as_sent: arguments,
2238 refused: false,
2239 }
2240 }
2241}
2242
2243#[derive(Debug, Clone, PartialEq)]
2245pub enum OwnerApprovalNeed {
2246 Unjudged,
2249 NotNeeded,
2251 Ask(aidaemon_core::OwnerApprovalRequest),
2253}
2254
2255#[derive(Clone, Default)]
2264pub struct ToolCallContext {
2265 pub mandate_preapproved: bool,
2269 pub mandate_execution: bool,
2274 pub mutation_forbidden: bool,
2277 pub kernel_approved: Option<ApprovalScope>,
2284 pub trusted_session: bool,
2288 pub user_role: Option<UserRole>,
2291 pub untrusted_source: bool,
2294 pub scope_escalation: Option<ScopeEscalation>,
2297 pub session_id: String,
2299 pub grant_session: String,
2304 pub channel_visibility: Option<ChannelVisibility>,
2307 pub channel_id: Option<String>,
2309 pub task_id: Option<String>,
2311 pub user_message: Option<String>,
2314 pub tool_call_id: Option<String>,
2316 pub lone_root_call: bool,
2319 pub turn_id: Option<String>,
2321 pub goal_id: Option<String>,
2325 pub goal_run_id: Option<String>,
2327 pub task_attempt_id: Option<String>,
2329 pub mandate_id: Option<String>,
2331 pub mandate_version: Option<i64>,
2333 pub project_scope: Option<String>,
2335 pub project: Option<aidaemon_core::ProjectRef>,
2340 pub workspace_collaboration_root: Option<String>,
2342 pub trust_roots: Option<Vec<String>>,
2345 pub trust_cwd: Option<String>,
2347 pub model: Option<String>,
2349 pub provider_kind: Option<String>,
2351 pub model_chain: Option<Vec<String>>,
2353 pub extensions: aidaemon_core::Extensions,
2357}
2358
2359impl std::fmt::Debug for ToolCallContext {
2360 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2361 f.debug_struct("ToolCallContext")
2362 .field("mandate_preapproved", &self.mandate_preapproved)
2363 .field("mandate_execution", &self.mandate_execution)
2364 .field("mutation_forbidden", &self.mutation_forbidden)
2365 .field("kernel_approved", &self.kernel_approved)
2366 .field("trusted_session", &self.trusted_session)
2367 .field("user_role", &self.user_role)
2368 .field("untrusted_source", &self.untrusted_source)
2369 .field("scope_escalation", &self.scope_escalation)
2370 .field("session_id", &self.session_id)
2371 .field("channel_visibility", &self.channel_visibility)
2372 .field("channel_id", &self.channel_id)
2373 .field("task_id", &self.task_id)
2374 .field(
2375 "user_message",
2376 &self.user_message.as_ref().map(|_| "[USER MESSAGE]"),
2377 )
2378 .field("tool_call_id", &self.tool_call_id)
2379 .field("lone_root_call", &self.lone_root_call)
2380 .field("turn_id", &self.turn_id)
2381 .field("goal_id", &self.goal_id)
2382 .field("goal_run_id", &self.goal_run_id)
2383 .field("task_attempt_id", &self.task_attempt_id)
2384 .field("mandate_id", &self.mandate_id)
2385 .field("mandate_version", &self.mandate_version)
2386 .field("project_scope", &self.project_scope)
2387 .field(
2388 "workspace_collaboration_root",
2389 &self
2390 .workspace_collaboration_root
2391 .as_ref()
2392 .map(|_| "[SCOPED WORKSPACE]"),
2393 )
2394 .field("trust_roots", &self.trust_roots)
2395 .field("trust_cwd", &self.trust_cwd)
2396 .field("model", &self.model)
2397 .field("provider_kind", &self.provider_kind)
2398 .field("model_chain", &self.model_chain)
2399 .field("extensions", &self.extensions)
2400 .finish()
2401 }
2402}
2403
2404impl ToolCallContext {
2405 pub fn session(&self) -> Option<&str> {
2407 Some(self.session_id.as_str()).filter(|id| !id.trim().is_empty())
2408 }
2409
2410 pub fn grants_session(&self) -> &str {
2413 if self.grant_session.trim().is_empty() {
2414 &self.session_id
2415 } else {
2416 &self.grant_session
2417 }
2418 }
2419}
2420
2421#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
2427pub struct ScopeEscalation {
2428 #[serde(default)]
2429 pub read_paths: Vec<String>,
2430 #[serde(default)]
2431 pub write_paths: Vec<String>,
2432}
2433
2434impl ScopeEscalation {
2435 pub fn is_empty(&self) -> bool {
2436 self.read_paths.is_empty() && self.write_paths.is_empty()
2437 }
2438}
2439
2440#[derive(Debug, Clone, PartialEq, Eq)]
2448pub enum DurableReplayDecision {
2449 Replay,
2450 Reexecute { reason: String },
2451 Block { reason: String },
2452}
2453
2454#[derive(Debug, Clone, PartialEq, Eq)]
2456pub struct ToolArgumentContractViolation {
2457 pub reason: String,
2458 pub recovery_hint: Option<String>,
2459}
2460
2461impl ToolArgumentContractViolation {
2462 pub fn new(reason: impl Into<String>) -> Self {
2463 Self {
2464 reason: reason.into(),
2465 recovery_hint: None,
2466 }
2467 }
2468
2469 pub fn with_recovery_hint(mut self, hint: impl Into<String>) -> Self {
2470 self.recovery_hint = Some(hint.into());
2471 self
2472 }
2473}
2474
2475#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
2477#[serde(rename_all = "lowercase")]
2478pub enum PermissionMode {
2479 #[default]
2481 Default,
2482 Cautious,
2484 Yolo,
2486}
2487
2488impl std::fmt::Display for PermissionMode {
2489 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2490 match self {
2491 PermissionMode::Default => write!(f, "default"),
2492 PermissionMode::Cautious => write!(f, "cautious"),
2493 PermissionMode::Yolo => write!(f, "yolo"),
2494 }
2495 }
2496}
2497
2498#[derive(Debug, Clone, Copy, Default)]
2502pub enum ApprovalKind {
2503 #[default]
2505 Command,
2506 CommandOnce,
2509 GoalConfirmation,
2511 AutopilotConfirmation,
2515 Handoff,
2518}
2519
2520#[derive(Debug, Clone)]
2522pub enum ApprovalResponse {
2523 AllowOnce,
2525 AllowSession,
2527 AllowAlways,
2529 Deny,
2531}
2532
2533#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
2535pub enum RiskLevel {
2536 Safe,
2537 Medium,
2538 High,
2539 Critical,
2540}
2541
2542impl std::fmt::Display for RiskLevel {
2543 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2544 match self {
2545 RiskLevel::Safe => write!(f, "Safe"),
2546 RiskLevel::Medium => write!(f, "Medium"),
2547 RiskLevel::High => write!(f, "High"),
2548 RiskLevel::Critical => write!(f, "Critical"),
2549 }
2550 }
2551}
2552
2553impl RiskLevel {
2554 pub const fn requires_owner_approval(self) -> bool {
2559 matches!(self, Self::High | Self::Critical)
2560 }
2561}
2562
2563#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2565pub enum GoalConfirmationStyle {
2566 #[default]
2567 Standard,
2568 Autopilot,
2569}
2570
2571#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2573pub enum AgentRole {
2574 Orchestrator,
2576 TaskLead,
2578 Executor,
2580}
2581
2582#[derive(Debug, Clone, PartialEq, Eq)]
2584pub enum FileWriteKind {
2585 Edit { old_text: String, replace_all: bool },
2587 Edits(Vec<TextEdit>),
2590 Replace,
2592 Append,
2594}
2595
2596#[derive(Debug, Clone, PartialEq, Eq)]
2598pub struct TextEdit {
2599 pub old_text: String,
2600 pub replace_all: bool,
2601}
2602
2603#[derive(Debug, Clone, PartialEq, Eq)]
2605pub struct FileWrite {
2606 pub path: String,
2607 pub kind: FileWriteKind,
2608}
2609
2610#[async_trait]
2612pub trait FileWriteGuard: Send {
2613 async fn committed(self: Box<Self>);
2615}
2616
2617#[async_trait]
2620pub trait FileFence: Send + Sync {
2621 async fn observed(&self, path: &str, bytes: &[u8]);
2623
2624 async fn begin_write(&self, path: &str) -> Result<Box<dyn FileWriteGuard>, String>;
2628
2629 async fn claim_delivery(&self, _subject: &str) -> Result<(), DeliveredArtifact> {
2635 Ok(())
2636 }
2637
2638 async fn release_delivery(&self, _subject: &str) {}
2640
2641 async fn declare_deliverable(&self, deliverable: Deliverable) -> DeliveryPlan {
2648 DeliveryPlan::Now(deliverable)
2649 }
2650}
2651
2652#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2655pub enum DeliverableKind {
2656 Screenshot { page: String },
2658 File { name: String },
2660}
2661
2662impl DeliverableKind {
2663 pub fn subject(&self) -> String {
2665 match self {
2666 Self::Screenshot { page } => format!("screenshot:{page}"),
2667 Self::File { name } => format!("file:{name}"),
2668 }
2669 }
2670
2671 pub fn words(&self) -> String {
2673 match self {
2674 Self::Screenshot { page } => format!("a screenshot of {page}"),
2675 Self::File { name } => format!("the file {name}"),
2676 }
2677 }
2678}
2679
2680pub type DeliverySend = Box<
2683 dyn FnOnce() -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), String>> + Send>>
2684 + Send
2685 + Sync,
2686>;
2687
2688pub struct Deliverable {
2690 pub kind: DeliverableKind,
2691 pub caption: String,
2693 pub send: DeliverySend,
2694}
2695
2696impl std::fmt::Debug for Deliverable {
2697 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2698 f.debug_struct("Deliverable")
2699 .field("kind", &self.kind)
2700 .field("caption", &self.caption)
2701 .finish_non_exhaustive()
2702 }
2703}
2704
2705#[derive(Debug)]
2707pub enum DeliveryPlan {
2708 Now(Deliverable),
2710 AtRunEnd { replaced: bool },
2713}
2714
2715#[derive(Debug, Clone, PartialEq, Eq)]
2717pub struct DeliveredArtifact {
2718 pub by: String,
2721 pub at: chrono::DateTime<chrono::Utc>,
2722}
2723
2724impl DeliveredArtifact {
2725 pub fn owner_time(&self) -> String {
2727 self.at
2728 .with_timezone(&chrono::Local)
2729 .format("%-I:%M:%S %p")
2730 .to_string()
2731 }
2732}
2733
2734#[derive(Clone)]
2736pub struct CallFileFence(pub std::sync::Arc<dyn FileFence>);
2737
2738pub fn file_fence(facts: &ToolCallContext) -> Option<&std::sync::Arc<dyn FileFence>> {
2740 facts
2741 .extensions
2742 .get::<CallFileFence>()
2743 .map(|fence| &fence.0)
2744}
2745
2746#[derive(Debug, Clone, PartialEq, Eq)]
2748pub struct BackgroundJob {
2749 pub key: String,
2751 pub title: String,
2753 pub started_at: chrono::DateTime<chrono::Utc>,
2754 pub task_id: Option<String>,
2756 pub run: Option<String>,
2758}
2759
2760#[async_trait]
2765pub trait ToolSemantics: Send + Sync {
2766 fn canonicalize_arguments(
2772 &self,
2773 arguments: &str,
2774 ) -> Result<String, ToolArgumentContractViolation> {
2775 Ok(arguments.to_string())
2776 }
2777
2778 fn validate_arguments(&self, _arguments: &str) -> Result<(), ToolArgumentContractViolation> {
2782 Ok(())
2783 }
2784
2785 async fn on_task_end(&self, _task_id: &str, _session_id: &str) -> anyhow::Result<()> {
2789 Ok(())
2790 }
2791
2792 async fn session_context_note(&self, _session_id: &str) -> Option<String> {
2796 None
2797 }
2798
2799 async fn background_jobs(&self, _session_id: &str) -> Vec<BackgroundJob> {
2803 Vec::new()
2804 }
2805
2806 async fn stop_background_job(&self, _key: &str) -> bool {
2809 false
2810 }
2811
2812 async fn jobs_ended_by_task_end(&self, _task_id: &str) -> usize {
2816 0
2817 }
2818
2819 fn tool_role(&self) -> ToolRole {
2822 ToolRole::Action
2823 }
2824
2825 fn dispatch_facts(&self) -> ToolDispatchFacts {
2828 ToolDispatchFacts::default()
2829 }
2830
2831 fn capabilities(&self) -> ToolCapabilities {
2834 ToolCapabilities::default()
2835 }
2836
2837 fn owner_control_plane(&self) -> bool {
2842 false
2843 }
2844
2845 fn owner_control_plane_call(&self, _arguments: &str) -> bool {
2849 false
2850 }
2851
2852 async fn owner_approval_request(
2858 &self,
2859 _call: &ApprovalCall<'_>,
2860 _facts: &ToolCallContext,
2861 ) -> OwnerApprovalNeed {
2862 OwnerApprovalNeed::Unjudged
2863 }
2864
2865 fn receipt_kind(&self, _arguments: &str) -> ToolReceiptKind {
2870 ToolReceiptKind::Generic
2871 }
2872
2873 fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
2877 default_semantics_from_identity(arguments, self.capabilities())
2878 }
2879
2880 fn call_access_manifest(&self, arguments: &str) -> ToolCallAccessManifest {
2883 let semantics = self.call_semantics(arguments);
2884 default_access_manifest(arguments, &semantics)
2885 }
2886
2887 fn guarded_paths(&self, arguments: &str) -> (Vec<String>, Vec<String>) {
2891 let manifest = self.call_access_manifest(arguments);
2892 let values =
2893 |targets: Vec<ToolTargetHint>| targets.into_iter().map(|target| target.value).collect();
2894 (
2895 values(manifest.read_targets),
2896 values(manifest.write_targets),
2897 )
2898 }
2899
2900 fn adapter_owned_access_manifest(&self, _arguments: &str) -> ToolCallAccessManifest {
2905 ToolCallAccessManifest::default()
2906 }
2907
2908 async fn durable_replay_decision(&self, _arguments: &str) -> DurableReplayDecision {
2915 DurableReplayDecision::Replay
2916 }
2917
2918 fn stable_observation_subjects(&self) -> Vec<StableObservationSubject> {
2923 Vec::new()
2924 }
2925
2926 fn call_file_write(&self, _arguments: &str) -> Option<FileWrite> {
2929 None
2930 }
2931
2932 fn file_write_result(
2938 &self,
2939 _arguments: &str,
2940 _current: Option<&[u8]>,
2941 ) -> Option<Result<Vec<u8>, String>> {
2942 None
2943 }
2944
2945 fn call_outbound(&self, _arguments: &str) -> aidaemon_core::Outbound {
2947 aidaemon_core::Outbound::Nothing
2948 }
2949
2950 fn call_effects(&self, _arguments: &str) -> aidaemon_core::CallEffects {
2958 if self.capabilities().read_only {
2959 aidaemon_core::CallEffects::none()
2960 } else {
2961 aidaemon_core::CallEffects::unknown()
2962 }
2963 }
2964
2965 fn named_files(&self, arguments: &str) -> Vec<String> {
2972 declared_named_files(self, arguments)
2973 }
2974
2975 fn call_annotations_in(
2984 &self,
2985 arguments: &str,
2986 _roots: &TrustRoots<'_>,
2987 ) -> aidaemon_core::ToolAnnotations {
2988 default_call_annotations(self.capabilities(), &self.call_semantics(arguments))
2989 }
2990
2991 fn output_trust(
2996 &self,
2997 _arguments: &str,
2998 _roots: &TrustRoots<'_>,
2999 ) -> aidaemon_core::SourceTrust {
3000 if self.capabilities().external_side_effect {
3001 aidaemon_core::SourceTrust::Untrusted
3002 } else {
3003 aidaemon_core::SourceTrust::Trusted
3004 }
3005 }
3006
3007 fn call_title(&self, _arguments: &str) -> Option<String> {
3011 None
3012 }
3013
3014 fn is_available(&self) -> bool {
3019 true
3020 }
3021
3022 fn offered_in_session(&self, _session_id: &str) -> bool {
3029 true
3030 }
3031}
3032
3033pub const EGRESS_EFFECTS: ToolMutationEffects = ToolMutationEffects::EXTERNAL_DELIVERY
3036 .union(ToolMutationEffects::REMOTE_MUTATION)
3037 .union(ToolMutationEffects::REMOTE_DEPLOY)
3038 .union(ToolMutationEffects::DESTRUCTIVE)
3039 .union(ToolMutationEffects::CONFIGURATION);
3040
3041pub fn default_call_annotations(
3044 cap: ToolCapabilities,
3045 semantics: &ToolCallSemantics,
3046) -> aidaemon_core::ToolAnnotations {
3047 let read_only = cap.read_only
3048 || (matches!(
3049 semantics.effect,
3050 ToolCallEffect::Observation | ToolCallEffect::Administrative
3051 ) && !semantics.mutates_state());
3052 let effects = semantics.mutation_effects;
3053 let egress = !read_only
3054 && (effects.intersects(EGRESS_EFFECTS)
3055 || (cap.external_side_effect && !effects.has_specific_effects()));
3056 aidaemon_core::ToolAnnotations {
3057 read_only,
3058 destructive: !read_only && effects.intersects(ToolMutationEffects::DESTRUCTIVE),
3059 idempotent: read_only,
3060 egress,
3061 }
3062}
3063
3064#[derive(Debug, Clone, Default)]
3071pub struct OwnedFolders(std::sync::Arc<std::sync::RwLock<Vec<String>>>);
3072
3073impl OwnedFolders {
3074 pub fn claim(&self, folders: &[String]) {
3076 let mut owned = self.0.write().unwrap_or_else(|e| e.into_inner());
3077 for folder in folders {
3078 let folder = folder.trim();
3079 if std::path::Path::new(folder).is_absolute() && !owned.iter().any(|f| f == folder) {
3080 owned.push(folder.to_string());
3081 }
3082 }
3083 }
3084
3085 pub fn release<P: AsRef<std::path::Path>>(&self, folders: &[P]) {
3087 let mut owned = self.0.write().unwrap_or_else(|e| e.into_inner());
3088 owned.retain(|kept| {
3089 !folders
3090 .iter()
3091 .any(|folder| std::path::Path::new(kept) == folder.as_ref())
3092 });
3093 }
3094
3095 pub fn list(&self) -> Vec<String> {
3097 self.0.read().unwrap_or_else(|e| e.into_inner()).clone()
3098 }
3099
3100 pub fn absent_write_targets(effects: &aidaemon_core::CallEffects) -> Vec<std::path::PathBuf> {
3104 effects
3105 .keys
3106 .iter()
3107 .filter(|key| key.class == aidaemon_core::EffectClass::Write)
3108 .map(|key| std::path::PathBuf::from(shellexpand::tilde(key.target.trim()).as_ref()))
3109 .filter(|path| path.is_absolute() && std::fs::symlink_metadata(path).is_err())
3110 .collect()
3111 }
3112
3113 pub fn claim_created(&self, absent: &[std::path::PathBuf]) -> Vec<String> {
3122 let created: Vec<String> = absent
3123 .iter()
3124 .filter(|path| {
3125 std::fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_dir())
3126 })
3127 .map(|path| path.display().to_string())
3128 .collect();
3129 self.claim(&created);
3130 created
3131 }
3132}
3133
3134#[cfg(test)]
3135mod owned_folder_tests {
3136 use super::OwnedFolders;
3137
3138 #[test]
3141 fn a_folder_a_call_created_becomes_owned() {
3142 let base = tempfile::tempdir().unwrap();
3143 let fresh = base.path().join("claude-drupal-11");
3144 let file = base.path().join("notes.txt");
3145 let before = base.path().join("existing-site");
3146 std::fs::create_dir(&before).unwrap();
3147 let key = |path: &std::path::Path| aidaemon_core::EffectKey {
3148 class: aidaemon_core::EffectClass::Write,
3149 target: path.display().to_string(),
3150 };
3151 let effects = aidaemon_core::CallEffects {
3152 keys: vec![key(&fresh), key(&file), key(&before)],
3153 complete: false,
3154 understood: true,
3155 };
3156 let absent = OwnedFolders::absent_write_targets(&effects);
3157 assert_eq!(absent, vec![fresh.clone(), file.clone()]);
3158 std::fs::create_dir(&fresh).unwrap();
3159 std::fs::write(&file, "x").unwrap();
3160 let owned = OwnedFolders::default();
3161 assert_eq!(
3162 owned.claim_created(&absent),
3163 vec![fresh.display().to_string()]
3164 );
3165 assert_eq!(owned.list(), vec![fresh.display().to_string()]);
3166 }
3167}
3168
3169pub fn within_owned(path: &str, folders: &[String]) -> bool {
3172 let expanded = shellexpand::tilde(path.trim()).into_owned();
3173 let path = std::path::Path::new(&expanded);
3174 path.is_absolute()
3175 && folders.iter().any(|folder| {
3176 aidaemon_policies::resolves_within(path, std::path::Path::new(folder.trim()))
3177 })
3178}
3179
3180#[derive(Debug, Clone, PartialEq, Eq)]
3183pub enum ProducedFile {
3184 Capture(DeliverableKind),
3187 Created,
3189}
3190
3191impl ProducedFile {
3192 pub fn words(&self) -> String {
3194 match self {
3195 Self::Capture(kind) => format!("this request's own capture: {}", kind.words()),
3196 Self::Created => "a file this request's own work created".to_string(),
3197 }
3198 }
3199}
3200
3201#[derive(Debug, Clone, Default)]
3212pub struct ProducedFiles(
3213 std::sync::Arc<std::sync::RwLock<std::collections::HashMap<String, ProducedFile>>>,
3214);
3215
3216impl ProducedFiles {
3217 pub fn note_capture(&self, path: &str, resource_id: Option<&str>, kind: &DeliverableKind) {
3220 let mut produced = self.0.write().unwrap_or_else(|e| e.into_inner());
3221 let capture = ProducedFile::Capture(kind.clone());
3222 produced.insert(produced_key(path), capture.clone());
3223 if let Some(id) = resource_id.map(str::trim).filter(|id| !id.is_empty()) {
3224 produced.insert(id.to_string(), capture);
3225 }
3226 }
3227
3228 pub fn note_created(&self, path: &str, resource_id: Option<&str>) {
3232 let mut produced = self.0.write().unwrap_or_else(|e| e.into_inner());
3233 produced
3234 .entry(produced_key(path))
3235 .or_insert(ProducedFile::Created);
3236 if let Some(id) = resource_id.map(str::trim).filter(|id| !id.is_empty()) {
3237 produced
3238 .entry(id.to_string())
3239 .or_insert(ProducedFile::Created);
3240 }
3241 }
3242
3243 pub fn claim_created(&self, absent: &[std::path::PathBuf]) -> Vec<String> {
3249 let created: Vec<String> = absent
3250 .iter()
3251 .filter(|path| std::fs::symlink_metadata(path).is_ok_and(|meta| meta.is_file()))
3252 .map(|path| path.display().to_string())
3253 .collect();
3254 let mut produced = self.0.write().unwrap_or_else(|e| e.into_inner());
3255 for path in &created {
3256 produced
3257 .entry(produced_key(path))
3258 .or_insert(ProducedFile::Created);
3259 }
3260 created
3261 }
3262
3263 pub fn get(&self, target: &str) -> Option<ProducedFile> {
3266 self.0
3267 .read()
3268 .unwrap_or_else(|e| e.into_inner())
3269 .get(&produced_key(target))
3270 .cloned()
3271 }
3272
3273 pub fn capture_kind(&self, path: &str) -> Option<DeliverableKind> {
3276 match self.get(path)? {
3277 ProducedFile::Capture(kind) => Some(kind),
3278 ProducedFile::Created => None,
3279 }
3280 }
3281
3282 pub fn entries(&self) -> Vec<(String, ProducedFile)> {
3285 self.0
3286 .read()
3287 .unwrap_or_else(|e| e.into_inner())
3288 .iter()
3289 .map(|(key, file)| (key.clone(), file.clone()))
3290 .collect()
3291 }
3292
3293 pub fn named_by(&self, named: &[String]) -> Vec<(String, ProducedFile)> {
3297 named
3298 .iter()
3299 .filter_map(|name| Some((name.clone(), self.get(name)?)))
3300 .collect()
3301 }
3302}
3303
3304pub fn declared_named_files<T: ToolSemantics + ?Sized>(tool: &T, arguments: &str) -> Vec<String> {
3308 let mut named: Vec<String> = Vec::new();
3309 let mut add = |value: &str| {
3310 let value = value.trim();
3311 if !value.is_empty() && !named.iter().any(|known| known == value) {
3312 named.push(value.to_string());
3313 }
3314 };
3315 for hint in tool.call_semantics(arguments).target_hints {
3316 if matches!(
3317 hint.kind,
3318 ToolTargetHintKind::Path | ToolTargetHintKind::ResourceId
3319 ) {
3320 add(&hint.value);
3321 }
3322 }
3323 let manifest = tool.call_access_manifest(arguments);
3324 for hint in manifest
3325 .read_targets
3326 .iter()
3327 .chain(manifest.write_targets.iter())
3328 {
3329 if hint.kind == ToolTargetHintKind::Path {
3330 add(&hint.value);
3331 }
3332 }
3333 for key in tool.call_effects(arguments).keys {
3334 if matches!(
3335 key.class,
3336 aidaemon_core::EffectClass::Write
3337 | aidaemon_core::EffectClass::Delete
3338 | aidaemon_core::EffectClass::Configuration
3339 ) {
3340 add(&key.target);
3341 }
3342 }
3343 named
3344}
3345
3346fn produced_key(target: &str) -> String {
3349 let expanded = shellexpand::tilde(target.trim()).into_owned();
3350 dunce::canonicalize(&expanded)
3351 .map(|path| path.to_string_lossy().into_owned())
3352 .unwrap_or(expanded)
3353}
3354
3355pub fn produced_files(facts: &ToolCallContext) -> Option<&ProducedFiles> {
3358 facts.extensions.get::<ProducedFiles>()
3359}
3360
3361#[cfg(test)]
3362mod produced_file_tests {
3363 use super::{DeliverableKind, ProducedFile, ProducedFiles};
3364
3365 #[test]
3369 fn a_file_a_tool_made_is_the_requests_own_by_path_and_id() {
3370 let produced = ProducedFiles::default();
3371 produced.note_created("/inbox/018d9d29_generated_image.png", Some("res_img"));
3372 assert_eq!(
3373 produced.get("/inbox/018d9d29_generated_image.png"),
3374 Some(ProducedFile::Created)
3375 );
3376 assert_eq!(produced.get("res_img"), Some(ProducedFile::Created));
3377 let page = DeliverableKind::Screenshot {
3378 page: "demo.ddev.site".to_string(),
3379 };
3380 produced.note_capture("/inbox/shot.png", None, &page);
3381 produced.note_created("/inbox/shot.png", None);
3382 assert_eq!(produced.capture_kind("/inbox/shot.png"), Some(page));
3383 }
3384
3385 #[test]
3389 fn the_requests_own_files_come_from_evidence() {
3390 let base = tempfile::tempdir().unwrap();
3391 let shot = base.path().join("ea19c410_screenshot.png");
3392 std::fs::write(&shot, b"png").unwrap();
3393 let page = DeliverableKind::Screenshot {
3394 page: "claude-drupal.ddev.site".to_string(),
3395 };
3396 let produced = ProducedFiles::default();
3397 produced.note_capture(&shot.display().to_string(), Some("res_1"), &page);
3398 let spelled = base
3399 .path()
3400 .join(".")
3401 .join("ea19c410_screenshot.png")
3402 .display()
3403 .to_string();
3404 assert_eq!(produced.capture_kind(&spelled), Some(page.clone()));
3405 assert_eq!(
3406 produced.get("res_1"),
3407 Some(ProducedFile::Capture(page.clone()))
3408 );
3409
3410 let fresh = base.path().join("report.md");
3411 let older = base.path().join("notes.md");
3412 std::fs::write(&older, "x").unwrap();
3413 let absent = vec![fresh.clone(), shot.clone()];
3414 std::fs::write(&fresh, "x").unwrap();
3415 assert_eq!(produced.claim_created(&absent).len(), 2);
3416 assert_eq!(
3417 produced.get(&fresh.display().to_string()),
3418 Some(ProducedFile::Created)
3419 );
3420 assert_eq!(
3421 produced.capture_kind(&shot.display().to_string()),
3422 Some(page)
3423 );
3424 assert_eq!(produced.get(&older.display().to_string()), None);
3425
3426 let named = produced.named_by(&[older.display().to_string(), fresh.display().to_string()]);
3427 assert_eq!(named.len(), 1);
3428 assert_eq!(named[0].1, ProducedFile::Created);
3429 }
3430}
3431
3432pub struct TrustRoots<'a> {
3441 roots: &'a [String],
3442 owned: &'a [String],
3443 cwd: Option<&'a str>,
3444}
3445
3446impl<'a> TrustRoots<'a> {
3447 pub fn new(roots: &'a [String]) -> Self {
3448 Self {
3449 roots,
3450 owned: &[],
3451 cwd: None,
3452 }
3453 }
3454
3455 pub fn with_owned(mut self, owned: &'a [String]) -> Self {
3457 self.owned = owned;
3458 self
3459 }
3460
3461 pub fn with_cwd(mut self, cwd: Option<&'a str>) -> Self {
3463 self.cwd = cwd;
3464 self
3465 }
3466
3467 pub fn anchored_at<'b>(&'b self, cwd: Option<&'b str>) -> TrustRoots<'b> {
3470 TrustRoots {
3471 roots: self.roots,
3472 owned: self.owned,
3473 cwd,
3474 }
3475 }
3476
3477 pub fn holds_effect(&self, path: &str) -> bool {
3482 if self.contains(path) {
3483 return true;
3484 }
3485 let resolved = match self.cwd {
3486 Some(cwd) if !is_absolute_or_home(path) => {
3487 format!("{}/{}", cwd.trim_end_matches('/'), path.trim())
3488 }
3489 _ => path.to_string(),
3490 };
3491 within_owned(&resolved, self.owned)
3492 }
3493
3494 pub fn owns(&self, path: &str) -> bool {
3497 within_owned(path, self.owned)
3498 }
3499
3500 pub fn cwd(&self) -> Option<&str> {
3502 self.cwd
3503 }
3504
3505 pub fn contains(&self, path: &str) -> bool {
3506 let resolved = match self.cwd {
3507 Some(cwd) if !is_absolute_or_home(path) => {
3508 format!("{}/{}", cwd.trim_end_matches('/'), path.trim())
3509 }
3510 _ => path.to_string(),
3511 };
3512 let Some(path) = resolve_absolute(&resolved) else {
3513 return false;
3514 };
3515 self.roots
3516 .iter()
3517 .any(|root| resolve_absolute(root).is_some_and(|root| path.starts_with(&root)))
3518 }
3519}
3520
3521pub fn file_output_trust(
3525 arguments: &str,
3526 keys: &[&str],
3527 roots: &TrustRoots<'_>,
3528) -> aidaemon_core::SourceTrust {
3529 let args = serde_json::from_str::<Value>(arguments).ok();
3530 let path = args.as_ref().and_then(|args| {
3531 keys.iter()
3532 .find_map(|key| args.get(*key).and_then(Value::as_str))
3533 });
3534 match path {
3535 Some(path) if roots.contains(path) => aidaemon_core::SourceTrust::Trusted,
3536 _ => aidaemon_core::SourceTrust::Untrusted,
3537 }
3538}
3539
3540fn resolve_absolute(path: &str) -> Option<std::path::PathBuf> {
3545 use std::path::{Component, PathBuf};
3546 let expanded = shellexpand::tilde(path.trim()).into_owned();
3547 let path = std::path::Path::new(&expanded);
3548 if !path.is_absolute() {
3549 return None;
3550 }
3551 let mut resolved = PathBuf::new();
3552 let mut existing = true;
3553 for component in path.components() {
3554 match component {
3555 Component::CurDir => {}
3556 Component::ParentDir => {
3557 if !resolved.pop() {
3558 return None;
3559 }
3560 }
3561 Component::Normal(part) => {
3562 resolved.push(part);
3563 if existing {
3564 match dunce::canonicalize(&resolved) {
3565 Ok(canonical) => resolved = canonical,
3566 Err(_) => existing = false,
3567 }
3568 }
3569 }
3570 other => resolved.push(other.as_os_str()),
3571 }
3572 }
3573 Some(resolved)
3574}
3575
3576fn is_absolute_or_home(path: &str) -> bool {
3577 let path = path.trim();
3578 let path_ref = std::path::Path::new(path);
3581 path.starts_with('~') || path_ref.is_absolute() || path_ref.has_root()
3582}
3583
3584#[derive(Debug, Clone, PartialEq, Eq)]
3588pub struct PreparedToolInvocation {
3589 pub canonical_arguments: String,
3590 pub semantics: ToolCallSemantics,
3591 pub access_manifest: ToolCallAccessManifest,
3592 pub receipt_kind: ToolReceiptKind,
3593}
3594
3595pub fn prepare_invocation<T: ToolSemantics + ?Sized>(
3599 tool: &T,
3600 arguments: &str,
3601) -> Result<PreparedToolInvocation, ToolArgumentContractViolation> {
3602 let canonical_arguments = tool.canonicalize_arguments(arguments)?;
3603 tool.validate_arguments(&canonical_arguments)?;
3604 Ok(PreparedToolInvocation {
3605 semantics: tool.call_semantics(&canonical_arguments),
3606 access_manifest: tool.call_access_manifest(&canonical_arguments),
3607 receipt_kind: tool.receipt_kind(&canonical_arguments),
3608 canonical_arguments,
3609 })
3610}
3611
3612#[cfg(test)]
3613mod file_trust_tests {
3614 use super::{TrustRoots, file_output_trust};
3615 use aidaemon_core::SourceTrust::{Trusted, Untrusted};
3616
3617 #[test]
3618 fn files_inside_the_trusted_roots_are_trusted() {
3619 let roots = vec!["/tmp/aidaemon-test/ws".to_string()];
3620 let roots = TrustRoots::new(&roots);
3621 let keys = ["path", "file_path"];
3622 assert_eq!(
3623 file_output_trust(r#"{"path":"/tmp/aidaemon-test/ws/a.txt"}"#, &keys, &roots),
3624 Trusted
3625 );
3626 assert_eq!(
3627 file_output_trust(
3628 r#"{"file_path":"/tmp/aidaemon-test/ws/a.txt"}"#,
3629 &keys,
3630 &roots
3631 ),
3632 Trusted
3633 );
3634 assert_eq!(
3635 file_output_trust(r#"{"path":"/etc/hosts"}"#, &keys, &roots),
3636 Untrusted
3637 );
3638 assert_eq!(file_output_trust(r#"{}"#, &keys, &roots), Untrusted);
3639 assert_eq!(file_output_trust("not json", &keys, &roots), Untrusted);
3640 }
3641}
3642
3643fn is_zero(value: &usize) -> bool {
3644 *value == 0
3645}
3646
3647#[cfg(test)]
3648mod local_write_satisfaction_tests {
3649 use super::ToolMutationEffects as E;
3650
3651 #[test]
3654 fn local_write_labels_satisfy_each_other_except_source() {
3655 assert!(E::LOCAL_WORKSPACE_WRITE.satisfies(E::LOCAL_DERIVED_WRITE));
3656 assert!(E::LOCAL_DERIVED_WRITE.satisfies(E::LOCAL_WORKSPACE_WRITE));
3657 assert!(E::LOCAL_SOURCE_WRITE.satisfies(E::LOCAL_DERIVED_WRITE));
3658 assert!(E::LOCAL_SOURCE_WRITE.satisfies(E::LOCAL_WORKSPACE_WRITE));
3659 assert!(!E::LOCAL_WORKSPACE_WRITE.satisfies(E::LOCAL_SOURCE_WRITE));
3660 assert!(!E::LOCAL_DERIVED_WRITE.satisfies(E::LOCAL_SOURCE_WRITE));
3661 assert!(!E::LOCAL_WORKSPACE_WRITE.satisfies(E::EXTERNAL_DELIVERY));
3662 }
3663}