Skip to main content

strands_harness/plugins/
environment.rs

1//! `EnvironmentContext`: surface the working environment and project docs to the model.
2//!
3//! Before each user turn an internal [`ContextInjector`] writes a small block: the platform, the
4//! sandbox shell when it is PowerShell, the current date (injected rather than put in the system
5//! prompt, so the cached prompt prefix stays warm), the working directory, the contents of the
6//! project's `AGENTS.md`, and links to other `AGENTS.md` / `README.md` files a couple of levels
7//! down (links, not contents, so the block stays small).
8//!
9//! Everything is read through the agent's sandbox, so it works against a local, Docker or SSH
10//! sandbox. Discovery (the directory walk, platform and working directory) runs once per agent;
11//! only the date is recomputed each turn. `AGENTS.md` contents are injected verbatim: repo docs
12//! are trusted, the same files the agent's `read` tool already surfaces.
13
14use 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
29/// How many directory levels below the working directory discovery scans.
30const DISCOVERY_DEPTH: usize = 2;
31
32/// `AGENTS.md` is injected in full up to this many characters; a longer file is truncated with a
33/// marker (`AGENTS_MD_CAP`).
34pub(crate) const AGENTS_MD_CAP: usize = 16_000;
35
36/// Dependency, build and VCS trees discovery skips; hidden directories are skipped too.
37const 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
51/// `$IsLinux`/`$IsMacOS` are unset on Windows PowerShell 5.1.
52const PWSH_PLATFORM_PROBE: &str = "if ($IsLinux -or $IsMacOS) { uname -s } else { 'Windows' }";
53
54/// What discovery found, once per agent.
55#[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/// Configuration for the [`EnvironmentContext`] plugin (`EnvironmentContextConfig`).
66#[derive(Debug, Clone, Default, bon::Builder)]
67#[builder(on(String, into))]
68pub struct EnvironmentContextConfig {
69    /// Plugin name, for logging and duplicate detection. Defaults to `strands:environment`.
70    pub name: Option<String>,
71}
72
73/// Injects working-environment and project-doc context before each user turn
74/// (`EnvironmentContext`).
75///
76/// Reads through the agent's sandbox, so it honours whatever sandbox the agent runs against.
77/// Sharing one instance across agents is safe: the memoized discovery is scoped per
78/// [`init_agent`](Plugin::init_agent) call.
79///
80/// ```
81/// use strands::Plugin;
82/// use strands_harness::EnvironmentContext;
83///
84/// assert_eq!(EnvironmentContext::default().name(), "strands:environment");
85/// ```
86#[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    /// The plugin with `config`.
99    #[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
126/// The injected block, gathering (and memoizing) the static parts on the first call.
127async 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
132/// The local calendar date, not UTC: an evening turn at a negative offset is still today.
133fn 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
168/// Platform and working directory come from the sandbox (`uname`, `$PWD`), not the host
169/// process, so they describe where the agent actually runs.
170async 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;