Skip to main content

bevy_agent_core/
integration.rs

1//! Game integration builders, extractor resources and constructor validation.
2
3use crate::*;
4use bevy::ecs::schedule::Schedules;
5
6#[derive(
7    Resource, Clone, Debug, Default, Serialize, Deserialize, schemars::JsonSchema, PartialEq, Eq,
8)]
9#[serde(deny_unknown_fields)]
10pub struct EnvironmentMetadata {
11    pub name: String,
12    pub version: String,
13    pub description: Option<String>,
14}
15
16impl EnvironmentMetadata {
17    pub fn validate(&self) -> ControlResult<()> {
18        if self.name.trim().is_empty() || self.version.trim().is_empty() {
19            return Err(AgentControlError::InvalidIntegration(
20                "environment name and version must be explicitly configured".into(),
21            ));
22        }
23        Ok(())
24    }
25}
26
27type ObservationExtractorFn = dyn Fn(&mut World, ObservationMode) -> Observation + Send + Sync;
28type ChecksumExtractorFn = dyn Fn(&mut World) -> EnvironmentChecksum + Send + Sync;
29
30pub struct AgentObservationExtractor {
31    extract: Box<ObservationExtractorFn>,
32}
33
34impl AgentObservationExtractor {
35    pub fn new<F>(extract: F) -> Self
36    where
37        F: Fn(&mut World, ObservationMode) -> Observation + Send + Sync + 'static,
38    {
39        Self {
40            extract: Box::new(extract),
41        }
42    }
43
44    pub fn extract(&self, world: &mut World, mode: ObservationMode) -> Observation {
45        (self.extract)(world, mode)
46    }
47}
48
49impl Resource for AgentObservationExtractor {}
50
51pub struct AgentChecksumExtractor {
52    extract: Box<ChecksumExtractorFn>,
53}
54
55impl AgentChecksumExtractor {
56    pub fn new<F>(extract: F) -> Self
57    where
58        F: Fn(&mut World) -> EnvironmentChecksum + Send + Sync + 'static,
59    {
60        Self {
61            extract: Box::new(extract),
62        }
63    }
64
65    pub fn extract(&self, world: &mut World) -> EnvironmentChecksum {
66        (self.extract)(world)
67    }
68}
69
70impl Resource for AgentChecksumExtractor {}
71
72pub trait AgentControlAppExt {
73    fn insert_observation_extractor<F>(&mut self, extract: F) -> &mut Self
74    where
75        F: Fn(&mut World, ObservationMode) -> Observation + Send + Sync + 'static;
76
77    fn insert_checksum_extractor<F>(&mut self, extract: F) -> &mut Self
78    where
79        F: Fn(&mut World) -> EnvironmentChecksum + Send + Sync + 'static;
80
81    fn register_custom_action_schema(
82        &mut self,
83        name: impl Into<String>,
84        schema: serde_json::Value,
85    ) -> ControlResult<&mut Self>;
86
87    fn set_environment_metadata(
88        &mut self,
89        name: impl Into<String>,
90        version: impl Into<String>,
91        description: Option<String>,
92    ) -> &mut Self;
93
94    fn set_supported_actions(
95        &mut self,
96        actions: impl IntoIterator<Item = AgentActionKind>,
97    ) -> &mut Self;
98
99    fn set_supported_observation_modes(
100        &mut self,
101        modes: impl IntoIterator<Item = ObservationMode>,
102    ) -> &mut Self;
103
104    fn set_observation_schema(&mut self, schema: serde_json::Value) -> ControlResult<&mut Self>;
105}
106
107impl AgentControlAppExt for App {
108    fn insert_observation_extractor<F>(&mut self, extract: F) -> &mut Self
109    where
110        F: Fn(&mut World, ObservationMode) -> Observation + Send + Sync + 'static,
111    {
112        self.insert_resource(AgentObservationExtractor::new(extract))
113    }
114
115    fn insert_checksum_extractor<F>(&mut self, extract: F) -> &mut Self
116    where
117        F: Fn(&mut World) -> EnvironmentChecksum + Send + Sync + 'static,
118    {
119        self.insert_resource(AgentChecksumExtractor::new(extract))
120    }
121
122    fn register_custom_action_schema(
123        &mut self,
124        name: impl Into<String>,
125        schema: serde_json::Value,
126    ) -> ControlResult<&mut Self> {
127        if !self.world().contains_resource::<AgentActionCatalog>() {
128            self.init_resource::<AgentActionCatalog>();
129        }
130        self.world_mut()
131            .resource_mut::<AgentActionCatalog>()
132            .register_custom_action_schema(name, schema)?;
133        Ok(self)
134    }
135
136    fn set_environment_metadata(
137        &mut self,
138        name: impl Into<String>,
139        version: impl Into<String>,
140        description: Option<String>,
141    ) -> &mut Self {
142        self.insert_resource(EnvironmentMetadata {
143            name: name.into(),
144            version: version.into(),
145            description,
146        })
147    }
148
149    fn set_supported_actions(
150        &mut self,
151        actions: impl IntoIterator<Item = AgentActionKind>,
152    ) -> &mut Self {
153        if !self.world().contains_resource::<AgentActionCatalog>() {
154            self.init_resource::<AgentActionCatalog>();
155        }
156        self.world_mut()
157            .resource_mut::<AgentActionCatalog>()
158            .set_supported_actions(actions);
159        self
160    }
161
162    fn set_supported_observation_modes(
163        &mut self,
164        modes: impl IntoIterator<Item = ObservationMode>,
165    ) -> &mut Self {
166        self.init_resource::<AgentObservationCatalog>();
167        self.world_mut()
168            .resource_mut::<AgentObservationCatalog>()
169            .set_supported_modes(modes);
170        self
171    }
172
173    fn set_observation_schema(&mut self, schema: serde_json::Value) -> ControlResult<&mut Self> {
174        self.init_resource::<AgentObservationCatalog>();
175        self.world_mut()
176            .resource_mut::<AgentObservationCatalog>()
177            .set_schema(schema)?;
178        Ok(self)
179    }
180}
181fn require<'a, T: Resource>(world: &'a World, name: &'static str) -> ControlResult<&'a T> {
182    world
183        .get_resource::<T>()
184        .ok_or(AgentControlError::MissingResource(name))
185}
186
187pub(crate) fn validate_resources(world: &World) -> ControlResult<()> {
188    require::<SimClock>(world, "SimClock")?.validate()?;
189    require::<StableIdAllocator>(world, "StableIdAllocator")?;
190    require::<DeterministicRng>(world, "DeterministicRng")?;
191    require::<AgentControlState>(world, "AgentControlState")?;
192    require::<AgentActionQueue>(world, "AgentActionQueue")?;
193    require::<CurrentInputFrame>(world, "CurrentInputFrame")?;
194    require::<RewardState>(world, "RewardState")?;
195    require::<EpisodeState>(world, "EpisodeState")?;
196    require::<LastStepResponse>(world, "LastStepResponse")?;
197    require::<ExecutionContext>(world, "ExecutionContext")?;
198    require::<AgentTickFailure>(world, "AgentTickFailure")?;
199    require::<AgentObservationExtractor>(world, "AgentObservationExtractor")?;
200    require::<AgentChecksumExtractor>(world, "AgentChecksumExtractor")?;
201    require::<EnvironmentMetadata>(world, "EnvironmentMetadata")?.validate()?;
202    require::<AgentActionCatalog>(world, "AgentActionCatalog")?.validate()?;
203    let observations = require::<AgentObservationCatalog>(world, "AgentObservationCatalog")?;
204    observations.validate_mode(&require::<ObservationConfig>(world, "ObservationConfig")?.mode)?;
205    Ok(())
206}
207
208pub(crate) fn validate_runtime_config(world: &World) -> ControlResult<()> {
209    validate_resources(world)?;
210    let schedules = require::<Schedules>(world, "Schedules")?;
211    for (installed, name) in [
212        (schedules.contains(AgentReset), "AgentReset"),
213        (schedules.contains(AgentDecision), "AgentDecision"),
214        (schedules.contains(AgentPreTick), "AgentPreTick"),
215        (schedules.contains(AgentTick), "AgentTick"),
216        (schedules.contains(AgentPostTick), "AgentPostTick"),
217        (schedules.contains(AgentFinalize), "AgentFinalize"),
218    ] {
219        if !installed {
220            return Err(AgentControlError::MissingSchedule(name));
221        }
222    }
223    Ok(())
224}
225
226/// Checks resources, schedules, extractors, catalogs, metadata and imported
227/// future actions before constructing a controllable environment.
228pub fn validate_integration(world: &World) -> ControlResult<()> {
229    validate_runtime_config(world)?;
230    let catalog = world.resource::<AgentActionCatalog>();
231    let tick = world.resource::<SimClock>().tick;
232    for scheduled in world.resource::<AgentActionQueue>().iter() {
233        validate_future_action(catalog, tick, scheduled)?;
234    }
235    Ok(())
236}