strands_harness/plugins/
environment.rs1use std::sync::Arc;
15
16use async_trait::async_trait;
17use futures::future::BoxFuture;
18use strands::Plugin;
19use strands::agent::LocalAgent;
20use strands::injection::InjectionTrigger;
21use strands::sandbox::{ExecuteOptions, Sandbox};
22use strands::vended_plugins::context_injector::{ContextInjector, ContextInjectorConfig};
23use tokio::sync::OnceCell;
24
25use crate::sandbox::{SandboxShell, shell_of};
26
27const DEFAULT_NAME: &str = "strands:environment";
28
29const DISCOVERY_DEPTH: usize = 2;
31
32pub(crate) const AGENTS_MD_CAP: usize = 16_000;
35
36const SKIP_DIRS: [&str; 8] = [
38 "node_modules",
39 "dist",
40 "build",
41 "target",
42 "__pycache__",
43 "venv",
44 "site-packages",
45 "vendor",
46];
47
48const AGENTS_FILE: &str = "AGENTS.md";
49const README_FILE: &str = "README.md";
50
51const PWSH_PLATFORM_PROBE: &str = "if ($IsLinux -or $IsMacOS) { uname -s } else { 'Windows' }";
53
54#[derive(Debug, Clone, Default, PartialEq, Eq)]
56struct Gathered {
57 platform: Option<String>,
58 cwd: Option<String>,
59 shell: Option<SandboxShell>,
60 agents_md: Option<String>,
61 other_agents: Vec<String>,
62 readmes: Vec<String>,
63}
64
65#[derive(Debug, Clone, Default, bon::Builder)]
67#[builder(on(String, into))]
68pub struct EnvironmentContextConfig {
69 pub name: Option<String>,
71}
72
73#[derive(Debug, Clone)]
87pub struct EnvironmentContext {
88 name: String,
89}
90
91impl Default for EnvironmentContext {
92 fn default() -> Self {
93 Self::new(EnvironmentContextConfig::default())
94 }
95}
96
97impl EnvironmentContext {
98 #[must_use]
100 pub fn new(config: EnvironmentContextConfig) -> Self {
101 Self {
102 name: config.name.unwrap_or_else(|| DEFAULT_NAME.to_owned()),
103 }
104 }
105}
106
107#[async_trait]
108impl Plugin for EnvironmentContext {
109 fn name(&self) -> &str {
110 &self.name
111 }
112
113 async fn init_agent(&self, agent: &mut LocalAgent) -> strands::Result<()> {
114 let memo: Arc<OnceCell<Gathered>> = Arc::default();
115 let config = ContextInjectorConfig::new(move |context| {
116 let memo = memo.clone();
117 let sandbox = context.agent.sandbox().clone();
118 async move { Ok(Some(render_environment(&sandbox, &memo).await)) }
119 })
120 .with_name(format!("{}:injector", self.name))
121 .with_trigger(InjectionTrigger::UserTurn);
122 ContextInjector::new(config).init_agent(agent).await
123 }
124}
125
126async fn render_environment(sandbox: &Arc<dyn Sandbox>, memo: &OnceCell<Gathered>) -> String {
128 let gathered = memo.get_or_init(|| gather(sandbox)).await;
129 render(gathered, &today_iso())
130}
131
132fn today_iso() -> String {
134 jiff::Zoned::now().date().to_string()
135}
136
137fn render(gathered: &Gathered, date: &str) -> String {
138 let mut env = Vec::new();
139 if let Some(platform) = &gathered.platform {
140 env.push(format!("Platform: {platform}"));
141 }
142 if gathered.shell == Some(SandboxShell::PowerShell) {
143 env.push("Shell: PowerShell (the shell tool runs commands in it, not sh)".to_owned());
144 }
145 env.push(format!("Date: {date}"));
146 if let Some(cwd) = &gathered.cwd {
147 env.push(format!("Working directory: {cwd}"));
148 }
149 let mut sections = vec![format!("<environment>\n{}\n</environment>", env.join("\n"))];
150 if let Some(agents_md) = gathered.agents_md.as_deref().filter(|text| !text.is_empty()) {
151 sections.push(format!("<AGENTS.md>\n{agents_md}\n</AGENTS.md>"));
152 }
153 if !gathered.other_agents.is_empty() {
154 sections.push(format!(
155 "Other AGENTS.md files nearby (read as needed): {}",
156 gathered.other_agents.join(", ")
157 ));
158 }
159 if !gathered.readmes.is_empty() {
160 sections.push(format!(
161 "README files nearby (read as needed): {}",
162 gathered.readmes.join(", ")
163 ));
164 }
165 format!("<system-reminder>\n{}\n</system-reminder>", sections.join("\n\n"))
166}
167
168async fn gather(sandbox: &Arc<dyn Sandbox>) -> Gathered {
171 let shell = shell_of(sandbox).await.ok();
172 let platform_probe = if shell == Some(SandboxShell::PowerShell) {
173 PWSH_PLATFORM_PROBE
174 } else {
175 "uname -s"
176 };
177 let platform = probe(sandbox.as_ref(), platform_probe).await;
178 let cwd = probe(sandbox.as_ref(), "echo \"$PWD\"").await;
179 let agents_md = read_capped(sandbox.as_ref(), AGENTS_FILE).await;
180 let mut found = Found::default();
181 visit(sandbox.as_ref(), String::new(), 0, &mut found).await;
182 Gathered {
183 platform,
184 cwd,
185 shell,
186 agents_md,
187 other_agents: found.agents.into_iter().filter(|path| path != AGENTS_FILE).collect(),
188 readmes: found.readmes,
189 }
190}
191
192async fn probe(sandbox: &dyn Sandbox, command: &str) -> Option<String> {
193 let result = sandbox.execute(command, ExecuteOptions::default()).await.ok()?;
194 let out = result.stdout.trim();
195 if result.exit_code != 0 || out.is_empty() {
196 return None;
197 }
198 out.lines().next().map(|line| line.trim_end_matches('\r').to_owned())
199}
200
201async fn read_capped(sandbox: &dyn Sandbox, path: &str) -> Option<String> {
202 let text = sandbox.read_text(path).await.ok()?;
203 if text.chars().count() <= AGENTS_MD_CAP {
204 return Some(text);
205 }
206 let kept: String = text.chars().take(AGENTS_MD_CAP).collect();
207 Some(format!(
208 "{kept}\n\u{2026} (truncated \u{2014} read the full file if you need the rest)"
209 ))
210}
211
212#[derive(Default)]
213struct Found {
214 agents: Vec<String>,
215 readmes: Vec<String>,
216}
217
218fn visit<'a>(sandbox: &'a dyn Sandbox, rel: String, depth: usize, found: &'a mut Found) -> BoxFuture<'a, ()> {
219 Box::pin(async move {
220 let listed = if rel.is_empty() { "." } else { rel.as_str() };
221 let Ok(entries) = sandbox.list_files(listed).await else {
222 return;
223 };
224 for entry in entries {
225 let path = if rel.is_empty() {
226 entry.name.clone()
227 } else {
228 format!("{rel}/{}", entry.name)
229 };
230 if entry.is_dir == Some(true) {
231 let descend = depth < DISCOVERY_DEPTH
232 && !SKIP_DIRS.contains(&entry.name.as_str())
233 && !entry.name.starts_with('.');
234 if descend {
235 visit(sandbox, path, depth + 1, found).await;
236 }
237 continue;
238 }
239 match entry.name.as_str() {
240 AGENTS_FILE => found.agents.push(path),
241 README_FILE => found.readmes.push(path),
242 _ => {}
243 }
244 }
245 })
246}
247
248#[cfg(test)]
249mod tests;