Skip to main content

strands/vended_plugins/skills/
agent_skills.rs

1//! The `AgentSkills` plugin.
2
3use std::cmp::Ordering;
4use std::fmt;
5use std::path::{Path, PathBuf};
6use std::sync::{Arc, Mutex, PoisonError, RwLock, Weak};
7
8use async_trait::async_trait;
9use futures::future::{BoxFuture, join_all};
10use indexmap::IndexMap;
11use schemars::JsonSchema;
12use serde::Deserialize;
13use tokio::sync::OnceCell;
14
15use super::skill::{Skill, SkillLoadOptions, UrlFetcher};
16use crate::agent::{LocalAgent, ToolAgent};
17use crate::error::{Error, Result};
18use crate::hooks::BeforeInvocationEvent;
19use crate::plugins::Plugin;
20use crate::sandbox::{FileInfo, Sandbox};
21use crate::state_store::StateStore;
22use crate::tools::{FunctionTool, ToolContext, ToolError, ToolSource};
23use crate::types::{JsonObject, JsonValue, SystemContentBlock, SystemPrompt};
24
25const AGENT_SKILLS_NAME: &str = "strands:agent-skills";
26const DEFAULT_STATE_KEY: &str = "agent_skills";
27const RESOURCE_DIRS: [&str; 3] = ["scripts", "references", "assets"];
28const DEFAULT_MAX_RESOURCE_FILES: usize = 20;
29const MAX_RESOURCE_DEPTH: usize = 3;
30const SKILL_MD_NAMES: [&str; 2] = ["SKILL.md", "skill.md"];
31const SKILLS_TOOL_DESCRIPTION: &str = "Activate a skill to load its full instructions. Use this tool to load the complete instructions for a skill listed in the available_skills section of your system prompt.";
32const NO_SKILLS_XML: &str = "<available_skills>\nNo skills are currently available.\n</available_skills>";
33
34type SkillMap = IndexMap<String, Skill>;
35
36/// One skill source (`SkillSource`): a [`Skill`], a filesystem path (a skill directory, its
37/// `SKILL.md`, or a parent directory of skill directories), or an `https://` URL of raw
38/// `SKILL.md` content.
39///
40/// Strings convert by prefix: `https://` is a URL, anything else a path.
41#[derive(Debug, Clone, PartialEq)]
42#[non_exhaustive]
43pub enum SkillSource {
44    /// A skill instance.
45    Skill(Box<Skill>),
46    /// A filesystem path, read through the agent's sandbox when the plugin initializes.
47    Path(String),
48    /// An `https://` URL of raw `SKILL.md` content.
49    Url(String),
50}
51
52impl From<Skill> for SkillSource {
53    fn from(skill: Skill) -> Self {
54        Self::Skill(Box::new(skill))
55    }
56}
57
58impl From<String> for SkillSource {
59    fn from(source: String) -> Self {
60        if source.starts_with("https://") {
61            Self::Url(source)
62        } else {
63            Self::Path(source)
64        }
65    }
66}
67
68impl From<&str> for SkillSource {
69    fn from(source: &str) -> Self {
70        Self::from(source.to_owned())
71    }
72}
73
74impl From<&String> for SkillSource {
75    fn from(source: &String) -> Self {
76        Self::from(source.clone())
77    }
78}
79
80/// Always a [`Path`](SkillSource::Path), whatever its text; a path that is not UTF-8 is converted
81/// lossily.
82impl From<&Path> for SkillSource {
83    fn from(path: &Path) -> Self {
84        Self::Path(path.to_string_lossy().into_owned())
85    }
86}
87
88/// Always a [`Path`](SkillSource::Path); see `From<&Path>`.
89impl From<PathBuf> for SkillSource {
90    fn from(path: PathBuf) -> Self {
91        Self::from(path.as_path())
92    }
93}
94
95/// Always a [`Path`](SkillSource::Path); see `From<&Path>`.
96impl From<&PathBuf> for SkillSource {
97    fn from(path: &PathBuf) -> Self {
98        Self::from(path.as_path())
99    }
100}
101
102/// Configuration for [`AgentSkills`] (`AgentSkillsConfig`).
103#[derive(Debug, Clone, Default, bon::Builder)]
104pub struct AgentSkillsConfig {
105    /// The skill sources.
106    #[builder(default, with = |skills: impl IntoIterator<Item = impl Into<SkillSource>>| {
107        skills.into_iter().map(Into::into).collect()
108    })]
109    pub skills: Vec<SkillSource>,
110    /// Maximum number of resource files listed in a skill response. Defaults to 20.
111    pub max_resource_files: Option<usize>,
112    /// Fail on skill validation issues instead of warning and loading anyway. Defaults to
113    /// `false`.
114    pub strict: Option<bool>,
115    /// The `app_state` key holding the plugin's per-agent state. Defaults to `agent_skills`.
116    #[builder(into)]
117    pub state_key: Option<String>,
118}
119
120/// Adds [AgentSkills.io](https://agentskills.io) skills to an agent (`AgentSkills`).
121///
122/// The plugin gives the agent a `skills` tool that loads a skill's full instructions on demand,
123/// lists the available skills (name, description, location) in the system prompt before each
124/// invocation, and records the activated skills in `app_state` under its state key.
125///
126/// Skill instances and URLs resolve once for the plugin; paths are read through the agent's
127/// sandbox when the plugin initializes on an agent, so one plugin shared by several agents loads
128/// each agent's skills from its own filesystem.
129///
130/// ```
131/// use strands::Agent;
132/// use strands::testing::MockModel;
133/// use strands::vended_plugins::skills::{AgentSkills, AgentSkillsConfig, Skill, SkillConfig};
134///
135/// let skill = Skill::new(SkillConfig {
136///     name: "my-skill".into(),
137///     description: "A custom skill".into(),
138///     instructions: Some("Do the thing".into()),
139///     ..Default::default()
140/// });
141/// let skills = AgentSkills::new(AgentSkillsConfig::builder().skills([skill]).build());
142/// let agent = Agent::builder()
143///     .model(MockModel::new())
144///     .plugins([skills])
145///     .printer(false)
146///     .build()?;
147/// # let _ = agent;
148/// # Ok::<(), strands::Error>(())
149/// ```
150#[derive(Clone)]
151pub struct AgentSkills {
152    inner: Arc<Inner>,
153}
154
155struct Inner {
156    strict: bool,
157    max_resource_files: usize,
158    state_key: String,
159    fetcher: UrlFetcher,
160    resolved: RwLock<Arc<Resolved>>,
161    agent_skills: Mutex<Vec<AgentEntry>>,
162}
163
164/// The skill set of the current sources: instances now, URLs once fetched, paths per agent.
165struct Resolved {
166    instances: SkillMap,
167    urls: Vec<String>,
168    paths: Vec<String>,
169    base: OnceCell<Arc<SkillMap>>,
170}
171
172/// One agent's loaded skills, keyed by its `app_state`.
173struct AgentEntry {
174    state: Weak<RwLock<JsonObject>>,
175    resolved: Weak<Resolved>,
176    skills: Arc<SkillMap>,
177}
178
179#[derive(Deserialize, JsonSchema)]
180#[serde(deny_unknown_fields)]
181struct SkillsInput {
182    /// Name of the skill to activate
183    #[schemars(length(min = 1))]
184    skill_name: String,
185}
186
187impl AgentSkills {
188    /// Creates the plugin (`new AgentSkills(config)`). URL sources are fetched when the plugin
189    /// first needs them; paths are read when it initializes on an agent.
190    #[must_use]
191    pub fn new(config: AgentSkillsConfig) -> Self {
192        Self::with_fetcher(config, UrlFetcher::default())
193    }
194
195    pub(crate) fn with_fetcher(config: AgentSkillsConfig, fetcher: UrlFetcher) -> Self {
196        let resolved = Arc::new(resolve_sources(config.skills));
197        Self {
198            inner: Arc::new(Inner {
199                strict: config.strict.unwrap_or(false),
200                max_resource_files: config.max_resource_files.unwrap_or(DEFAULT_MAX_RESOURCE_FILES),
201                state_key: config.state_key.unwrap_or_else(|| DEFAULT_STATE_KEY.to_owned()),
202                fetcher,
203                resolved: RwLock::new(resolved),
204                agent_skills: Mutex::new(Vec::new()),
205            }),
206        }
207    }
208
209    /// The available skills: with an agent, that agent's full set (the
210    /// plugin's skills plus those loaded from its paths); without one, the skill instances and
211    /// URL skills only.
212    pub async fn get_available_skills(&self, agent: Option<&LocalAgent>) -> Vec<Skill> {
213        let resolved = self.inner.current();
214        let base = self.inner.base(&resolved).await;
215        let skills = agent
216            .and_then(|agent| self.inner.agent_entry(agent.app_state(), &resolved))
217            .unwrap_or(base);
218        skills.values().cloned().collect()
219    }
220
221    /// Replaces every skill source. Agents load their skills again on
222    /// their next invocation or `skills` call; their activated-skill state is kept.
223    pub fn set_available_skills(&self, skills: impl IntoIterator<Item = impl Into<SkillSource>>) {
224        let resolved = Arc::new(resolve_sources(skills.into_iter().map(Into::into).collect()));
225        *self.inner.resolved.write().unwrap_or_else(PoisonError::into_inner) = resolved;
226        self.inner
227            .agent_skills
228            .lock()
229            .unwrap_or_else(PoisonError::into_inner)
230            .clear();
231    }
232
233    /// The skills `agent` activated, most recent last.
234    #[must_use]
235    pub fn get_activated_skills(&self, agent: &LocalAgent) -> Vec<String> {
236        self.inner.activated_skills(agent.app_state())
237    }
238
239    fn skills_tool(&self) -> FunctionTool {
240        let inner = self.inner.clone();
241        FunctionTool::builder("skills", SKILLS_TOOL_DESCRIPTION)
242            .input_schema_for::<SkillsInput>()
243            .callback(move |input, context| {
244                let inner = inner.clone();
245                async move {
246                    let input: SkillsInput = serde_json::from_value(input)?;
247                    inner.activate_skill(&input.skill_name, &context).await
248                }
249            })
250    }
251}
252
253impl fmt::Debug for AgentSkills {
254    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255        f.debug_struct("AgentSkills")
256            .field("strict", &self.inner.strict)
257            .field("max_resource_files", &self.inner.max_resource_files)
258            .field("state_key", &self.inner.state_key)
259            .finish_non_exhaustive()
260    }
261}
262
263#[async_trait]
264impl Plugin for AgentSkills {
265    fn name(&self) -> &str {
266        AGENT_SKILLS_NAME
267    }
268
269    async fn init_agent(&self, agent: &mut LocalAgent) -> Result<()> {
270        let resolved = self.inner.current();
271        self.inner.base(&resolved).await;
272        let skills = self.inner.load_skill_paths(agent, &resolved).await;
273        if skills.is_empty() {
274            tracing::warn!("no skills were loaded, the agent will have no skills available");
275        }
276        tracing::debug!("skill_count=<{}> | skills plugin initialized", skills.len());
277
278        let inner = self.inner.clone();
279        agent.add_async_hook::<BeforeInvocationEvent<'_>>(move |event| {
280            let inner = inner.clone();
281            Box::pin(async move { inner.before_invocation(event.agent_mut()).await })
282        });
283        Ok(())
284    }
285
286    fn get_tools(&self) -> Vec<ToolSource> {
287        vec![ToolSource::from(self.skills_tool())]
288    }
289}
290
291/// The sandbox the agent reads skill files through (`agent.sandbox`).
292fn agent_sandbox(agent: &LocalAgent) -> Arc<dyn Sandbox> {
293    Arc::clone(agent.sandbox())
294}
295
296/// The sandbox a tool call reads skill resources through (`context.agent.sandbox`).
297fn tool_agent_sandbox(agent: &ToolAgent) -> Arc<dyn Sandbox> {
298    Arc::clone(agent.sandbox())
299}
300
301fn insert_skill(skills: &mut SkillMap, skill: Skill) {
302    if skills.contains_key(skill.name()) {
303        tracing::warn!(
304            "name=<{}> | duplicate skill name, overwriting previous skill",
305            skill.name()
306        );
307    }
308    skills.insert(skill.name().to_owned(), skill);
309}
310
311/// Sorts the sources: instances into the map, URLs and paths for later.
312fn resolve_sources(sources: Vec<SkillSource>) -> Resolved {
313    let source_count = sources.len();
314    let mut resolved = Resolved {
315        instances: SkillMap::new(),
316        urls: Vec::new(),
317        paths: Vec::new(),
318        base: OnceCell::new(),
319    };
320    for source in sources {
321        match source {
322            SkillSource::Skill(skill) => insert_skill(&mut resolved.instances, *skill),
323            SkillSource::Url(url) => resolved.urls.push(url),
324            SkillSource::Path(path) => resolved.paths.push(path),
325        }
326    }
327    if resolved.urls.is_empty() {
328        tracing::debug!(
329            "source_count=<{source_count}>, resolved_count=<{}> | skills resolved",
330            resolved.instances.len()
331        );
332    }
333    resolved
334}
335
336/// Orders directory names: letters case-insensitively, then lowercase first.
337fn locale_compare(a: &str, b: &str) -> Ordering {
338    a.to_lowercase().cmp(&b.to_lowercase()).then_with(|| b.cmp(a))
339}
340
341/// The `SKILL.md` (preferred) or `skill.md` file among directory entries.
342fn find_skill_md_name(entries: &[FileInfo]) -> Option<&'static str> {
343    SKILL_MD_NAMES.into_iter().find(|name| {
344        entries
345            .iter()
346            .any(|entry| !entry.is_dir.unwrap_or(false) && entry.name == *name)
347    })
348}
349
350/// The type name of a JSON value that is not `null`: `string`, `number`, `boolean` or `object`.
351fn js_typeof(value: &JsonValue) -> &'static str {
352    match value {
353        JsonValue::String(_) => "string",
354        JsonValue::Number(_) => "number",
355        JsonValue::Bool(_) => "boolean",
356        JsonValue::Null | JsonValue::Array(_) | JsonValue::Object(_) => "object",
357    }
358}
359
360fn escape_xml(text: &str) -> String {
361    text.replace('&', "&amp;")
362        .replace('<', "&lt;")
363        .replace('>', "&gt;")
364        .replace('"', "&quot;")
365        .replace('\'', "&apos;")
366}
367
368impl Inner {
369    fn current(&self) -> Arc<Resolved> {
370        self.resolved.read().unwrap_or_else(PoisonError::into_inner).clone()
371    }
372
373    /// The instances plus the URL skills, fetched once per source set (`_ready`).
374    async fn base(&self, resolved: &Resolved) -> Arc<SkillMap> {
375        resolved
376            .base
377            .get_or_init(|| async {
378                let mut skills = resolved.instances.clone();
379                if resolved.urls.is_empty() {
380                    return Arc::new(skills);
381                }
382                let options = SkillLoadOptions { strict: self.strict };
383                let fetches = resolved
384                    .urls
385                    .iter()
386                    .map(|url| Skill::from_url_with(url, options, &self.fetcher));
387                for (url, result) in resolved.urls.iter().zip(join_all(fetches).await) {
388                    match result {
389                        Ok(skill) => insert_skill(&mut skills, skill),
390                        Err(error) => tracing::warn!("url=<{url}> | failed to load skill from URL: Error: {error}"),
391                    }
392                }
393                tracing::debug!(
394                    "source_count=<{}>, resolved_count=<{}> | skills resolved (including async)",
395                    resolved.instances.len() + resolved.urls.len() + resolved.paths.len(),
396                    skills.len()
397                );
398                Arc::new(skills)
399            })
400            .await
401            .clone()
402    }
403
404    fn agent_entry(&self, state: &StateStore, resolved: &Arc<Resolved>) -> Option<Arc<SkillMap>> {
405        let key = state.downgrade();
406        let resolved = Arc::downgrade(resolved);
407        self.agent_skills
408            .lock()
409            .unwrap_or_else(PoisonError::into_inner)
410            .iter()
411            .find(|entry| entry.state.ptr_eq(&key) && entry.resolved.ptr_eq(&resolved))
412            .map(|entry| entry.skills.clone())
413    }
414
415    fn store_agent_entry(&self, state: &StateStore, resolved: &Arc<Resolved>, skills: Arc<SkillMap>) {
416        let key = state.downgrade();
417        let mut entries = self.agent_skills.lock().unwrap_or_else(PoisonError::into_inner);
418        entries.retain(|entry| entry.state.strong_count() > 0 && !entry.state.ptr_eq(&key));
419        if !Arc::ptr_eq(resolved, &self.current()) {
420            return;
421        }
422        entries.push(AgentEntry {
423            state: key,
424            resolved: Arc::downgrade(resolved),
425            skills,
426        });
427    }
428
429    /// The agent's skills: the base set plus its paths read through its sandbox. Failures log a
430    /// warning and skip the source.
431    async fn load_skill_paths(&self, agent: &LocalAgent, resolved: &Arc<Resolved>) -> Arc<SkillMap> {
432        let mut skills = (*self.base(resolved).await).clone();
433        if !resolved.paths.is_empty() {
434            let sandbox = agent_sandbox(agent);
435            for path in &resolved.paths {
436                self.load_skill_path(sandbox.as_ref(), path, &mut skills).await;
437            }
438        }
439        let skills = Arc::new(skills);
440        self.store_agent_entry(agent.app_state(), resolved, skills.clone());
441        skills
442    }
443
444    async fn load_skill_path(&self, sandbox: &dyn Sandbox, skill_path: &str, skills: &mut SkillMap) {
445        let Ok(entries) = sandbox.list_files(skill_path).await else {
446            if skill_path.to_lowercase().ends_with("skill.md") {
447                let skill_dir = skill_path.rfind('/').map_or(".", |index| &skill_path[..index]);
448                self.load_skill(sandbox, skill_dir, skill_path, skills).await;
449            } else {
450                tracing::warn!("path=<{skill_path}> | skill source does not exist or is not a valid path");
451            }
452            return;
453        };
454        if let Some(md_name) = find_skill_md_name(&entries) {
455            self.load_skill(sandbox, skill_path, &format!("{skill_path}/{md_name}"), skills)
456                .await;
457            return;
458        }
459        let mut child_dirs = entries
460            .iter()
461            .filter(|entry| entry.is_dir.unwrap_or(false))
462            .map(|entry| entry.name.as_str())
463            .collect::<Vec<_>>();
464        child_dirs.sort_by(|a, b| locale_compare(a, b));
465        for child in child_dirs {
466            let child_dir = format!("{skill_path}/{child}");
467            let child_entries = match sandbox.list_files(&child_dir).await {
468                Ok(child_entries) => child_entries,
469                Err(error) => {
470                    tracing::warn!("path=<{child_dir}> | failed to load skill from sandbox: Error: {error}");
471                    continue;
472                }
473            };
474            if let Some(md_name) = find_skill_md_name(&child_entries) {
475                self.load_skill(sandbox, &child_dir, &format!("{child_dir}/{md_name}"), skills)
476                    .await;
477            }
478        }
479    }
480
481    async fn load_skill(&self, sandbox: &dyn Sandbox, skill_dir: &str, md_path: &str, skills: &mut SkillMap) {
482        let options = SkillLoadOptions { strict: self.strict };
483        let loaded = match sandbox.read_text(md_path).await {
484            Ok(content) => Skill::from_content_at(&content, options, Some(skill_dir.to_owned())),
485            Err(error) => Err(error),
486        };
487        match loaded {
488            Ok(skill) => insert_skill(skills, skill),
489            Err(error) => tracing::warn!("path=<{skill_dir}> | failed to load skill: Error: {error}"),
490        }
491    }
492
493    async fn before_invocation(&self, agent: &mut LocalAgent) -> Result<()> {
494        let resolved = self.current();
495        self.base(&resolved).await;
496        let skills = match self.agent_entry(agent.app_state(), &resolved) {
497            Some(skills) => skills,
498            None => self.load_skill_paths(agent, &resolved).await,
499        };
500        self.inject_skills_xml(agent, &skills)
501    }
502
503    fn state_field(&self, state: &StateStore, key: &str) -> Option<JsonValue> {
504        match state.get_value(&self.state_key) {
505            Some(JsonValue::Object(data)) => data.get(key).cloned(),
506            _ => None,
507        }
508    }
509
510    fn set_state_field(&self, state: &StateStore, key: &str, value: JsonValue) -> Result<()> {
511        let mut record = match state.get_value(&self.state_key) {
512            None | Some(JsonValue::Null) => JsonObject::new(),
513            Some(JsonValue::Object(data)) => data,
514            Some(other) => {
515                return Err(Error::other(format!(
516                    "expected object for state key '{}', got {}",
517                    self.state_key,
518                    js_typeof(&other)
519                )));
520            }
521        };
522        record.insert(key.to_owned(), value);
523        state.set(self.state_key.clone(), record)
524    }
525
526    fn activated_skills(&self, state: &StateStore) -> Vec<String> {
527        self.state_field(state, "activatedSkills")
528            .and_then(|value| serde_json::from_value(value).ok())
529            .unwrap_or_default()
530    }
531
532    /// Lists the skills in the system prompt, replacing the block injected last.
533    fn inject_skills_xml(&self, agent: &mut LocalAgent, skills: &SkillMap) -> Result<()> {
534        let skills_xml = generate_skills_xml(skills);
535        let last_injected = self
536            .state_field(agent.app_state(), "lastInjectedXml")
537            .and_then(|value| value.as_str().map(str::to_owned));
538        let (prompt, injected) = match agent.system_prompt() {
539            Some(SystemPrompt::Blocks(blocks)) => inject_into_blocks(blocks, last_injected.as_deref(), skills_xml),
540            Some(SystemPrompt::Text(text)) => inject_into_text(text, last_injected.as_deref(), &skills_xml),
541            None => inject_into_text("", last_injected.as_deref(), &skills_xml),
542        };
543        self.set_state_field(agent.app_state(), "lastInjectedXml", JsonValue::String(injected))?;
544        agent.set_system_prompt(Some(prompt));
545        Ok(())
546    }
547
548    async fn activate_skill(
549        &self,
550        skill_name: &str,
551        context: &ToolContext,
552    ) -> std::result::Result<JsonValue, ToolError> {
553        let resolved = self.current();
554        let base = self.base(&resolved).await;
555        let state = context.agent().app_state();
556        let skills = self.agent_entry(state, &resolved).unwrap_or(base);
557        let Some(skill) = skills.get(skill_name) else {
558            let available = skills.keys().map(String::as_str).collect::<Vec<_>>().join(", ");
559            return Ok(JsonValue::String(format!(
560                "Skill '{skill_name}' not found. Available skills: {available}"
561            )));
562        };
563        tracing::debug!("skill_name=<{skill_name}> | skill activated");
564        let mut activated = self.activated_skills(state);
565        activated.retain(|name| name != skill_name);
566        activated.push(skill_name.to_owned());
567        self.set_state_field(state, "activatedSkills", serde_json::to_value(activated)?)?;
568        let sandbox = tool_agent_sandbox(context.agent());
569        Ok(JsonValue::String(
570            self.format_skill_response(skill, sandbox.as_ref()).await,
571        ))
572    }
573
574    /// The `skills` tool's answer: instructions, metadata and resource files.
575    async fn format_skill_response(&self, skill: &Skill, sandbox: &dyn Sandbox) -> String {
576        if skill.instructions().is_empty() {
577            return format!("Skill '{}' activated (no instructions available).", skill.name());
578        }
579        let mut parts = vec![skill.instructions().to_owned()];
580        let mut metadata_lines = Vec::new();
581        if let Some(tools) = skill.allowed_tools().filter(|tools| !tools.is_empty()) {
582            metadata_lines.push(format!("Allowed tools: {}", tools.join(", ")));
583        }
584        if let Some(compatibility) = skill.compatibility() {
585            metadata_lines.push(format!("Compatibility: {compatibility}"));
586        }
587        if let Some(path) = skill.path() {
588            metadata_lines.push(format!("Location: {path}/SKILL.md"));
589        }
590        if !metadata_lines.is_empty() {
591            parts.push(format!("\n---\n{}", metadata_lines.join("\n")));
592        }
593        if let Some(path) = skill.path() {
594            let resources = self.list_skill_resources(sandbox, path).await;
595            if !resources.is_empty() {
596                let listing = resources
597                    .iter()
598                    .map(|resource| format!("  {resource}"))
599                    .collect::<Vec<_>>();
600                parts.push(format!("\nAvailable resources:\n{}", listing.join("\n")));
601            }
602        }
603        parts.join("\n")
604    }
605
606    /// Files under the skill's `scripts/`, `references/` and `assets/`, capped at
607    /// `max_resource_files`.
608    async fn list_skill_resources(&self, sandbox: &dyn Sandbox, skill_path: &str) -> Vec<String> {
609        let mut files = Vec::new();
610        for dir_name in RESOURCE_DIRS {
611            let Ok(mut entries) = list_files_recursive(sandbox, format!("{skill_path}/{dir_name}"), 0).await else {
612                continue;
613            };
614            crate::storage::sort_keys(&mut entries);
615            for entry in entries {
616                files.push(format!("{dir_name}/{entry}"));
617                if files.len() >= self.max_resource_files {
618                    files.push(format!("... (truncated at {} files)", self.max_resource_files));
619                    return files;
620                }
621            }
622        }
623        files
624    }
625}
626
627/// Lists a directory through the sandbox, recursing up to three levels, as paths relative to it.
628fn list_files_recursive(sandbox: &dyn Sandbox, dir: String, depth: usize) -> BoxFuture<'_, Result<Vec<String>>> {
629    Box::pin(async move {
630        if depth >= MAX_RESOURCE_DEPTH {
631            return Ok(Vec::new());
632        }
633        let mut result = Vec::new();
634        for entry in sandbox.list_files(&dir).await? {
635            if !entry.is_dir.unwrap_or(false) {
636                result.push(entry.name);
637                continue;
638            }
639            let nested = list_files_recursive(sandbox, format!("{dir}/{}", entry.name), depth + 1).await?;
640            result.extend(nested.into_iter().map(|path| format!("{}/{path}", entry.name)));
641        }
642        Ok(result)
643    })
644}
645
646/// The `<available_skills>` block of the system prompt.
647fn generate_skills_xml(skills: &SkillMap) -> String {
648    if skills.is_empty() {
649        return NO_SKILLS_XML.to_owned();
650    }
651    let mut lines = vec!["<available_skills>".to_owned()];
652    for skill in skills.values() {
653        lines.push("<skill>".to_owned());
654        lines.push(format!("<name>{}</name>", escape_xml(skill.name())));
655        lines.push(format!(
656            "<description>{}</description>",
657            escape_xml(skill.description())
658        ));
659        if let Some(path) = skill.path() {
660            lines.push(format!(
661                "<location>{}</location>",
662                escape_xml(&format!("{path}/SKILL.md"))
663            ));
664        }
665        lines.push("</skill>".to_owned());
666    }
667    lines.push("</available_skills>".to_owned());
668    lines.join("\n")
669}
670
671/// A string prompt with the previous injection removed and the new one appended; returns the
672/// prompt and the injected text.
673fn inject_into_text(prompt: &str, last_injected: Option<&str>, skills_xml: &str) -> (SystemPrompt, String) {
674    let mut current = prompt.to_owned();
675    if let Some(last) = last_injected {
676        if current.contains(last) {
677            current = current.replacen(last, "", 1);
678        } else {
679            tracing::warn!("unable to find previously injected skills XML in system prompt, re-appending");
680        }
681    }
682    if current.is_empty() {
683        return (SystemPrompt::Text(skills_xml.to_owned()), skills_xml.to_owned());
684    }
685    let injection = format!("\n\n{skills_xml}");
686    (SystemPrompt::Text(format!("{current}{injection}")), injection)
687}
688
689/// A block prompt with the previous skills block removed and a new text block appended.
690fn inject_into_blocks(
691    blocks: &[SystemContentBlock],
692    last_injected: Option<&str>,
693    skills_xml: String,
694) -> (SystemPrompt, String) {
695    let mut filtered = blocks.to_vec();
696    if let Some(last) = last_injected {
697        filtered.retain(|block| !matches!(block, SystemContentBlock::Text(text) if text.text == last));
698        if filtered.len() == blocks.len() {
699            tracing::warn!("unable to find previously injected skills XML in system prompt, re-appending");
700        }
701    }
702    filtered.push(SystemContentBlock::text(skills_xml.clone()));
703    (SystemPrompt::Blocks(filtered), skills_xml)
704}
705
706#[cfg(test)]
707mod tests;