Skip to main content

adk_skill/
progressive.rs

1//! Google ADK-style progressive disclosure for skills.
2//!
3//! [`SkillToolset`] exposes a small, always-available tool surface:
4//!
5//! - **L1** [`list_skills`](ListSkillsTool): names and descriptions only.
6//! - **L2** [`load_skill`](LoadSkillTool): instructions and frontmatter for one skill.
7//! - **L3** [`load_skill_resource`](LoadSkillResourceTool): a single bundled resource.
8//!
9//! Loading a skill records its content ID and hash in agent-scoped session state.
10//! Business tools declared by `allowed-tools` become visible only after that
11//! activation is persisted and the runtime begins the next model turn. This is
12//! intentionally compatible with Google ADK's `SkillToolset`, while retaining
13//! ADK-Rust's strict [`ValidationMode`] and content-hash provenance guarantees.
14
15use crate::{SkillDocument, SkillIndex, SkillSummary, ToolRegistry, ValidationMode};
16use adk_core::{
17    AdkError, Content, LlmRequest, ReadonlyContext, Result, Tool, ToolContext, Toolset,
18};
19use async_trait::async_trait;
20use serde::{Deserialize, Serialize};
21use serde_json::{Value, json};
22use std::collections::HashSet;
23use std::fs;
24use std::path::{Component, Path, PathBuf};
25use std::sync::{Arc, LazyLock};
26
27#[cfg(feature = "vertex-skill-registry")]
28use crate::registry::{SkillContent, SkillRegistryClient, SkillSearchTool};
29#[cfg(feature = "vertex-skill-registry")]
30use std::collections::{BTreeMap, HashMap};
31#[cfg(feature = "vertex-skill-registry")]
32use tokio::sync::RwLock;
33
34const STATE_KEY_PREFIX: &str = "skill:active:";
35#[cfg(feature = "vertex-skill-registry")]
36const MAX_REMOTE_CACHE_INVOCATIONS: usize = 16;
37
38const LIST_SKILLS_TOOL_NAME: &str = "list_skills";
39const LOAD_SKILL_TOOL_NAME: &str = "load_skill";
40const LOAD_SKILL_RESOURCE_TOOL_NAME: &str = "load_skill_resource";
41const RUN_SKILL_SCRIPT_TOOL_NAME: &str = "run_skill_script";
42
43/// Builds the progressive-skill instructions injected into an LLM request.
44///
45/// This mirrors Google ADK Python's `_build_skill_system_instruction`: the
46/// text follows the tools actually exposed by the host, rather than assuming
47/// every skill capability is available.
48///
49/// `script_execution_enabled` must only be `true` when the host exposes a
50/// matching `run_skill_script` tool. ADK-Rust currently reads bundled scripts
51/// but does not execute them, so [`SkillToolset`] passes `false`.
52///
53/// # Example
54///
55/// ```rust
56/// use adk_skill::build_skill_system_instruction;
57///
58/// let instruction = build_skill_system_instruction(
59///     Some("workspace"),
60///     Some(&["list_skills", "load_skill"]),
61///     None,
62///     false,
63/// );
64/// assert!(instruction.contains("`workspace_load_skill`"));
65/// assert!(instruction.contains("`workspace_load_skill_resource`"));
66/// assert!(!instruction.contains("The `workspace_load_skill_resource` tool is for viewing"));
67/// ```
68pub fn build_skill_system_instruction(
69    prefix: Option<&str>,
70    allowed_tools: Option<&[&str]>,
71    skills_folder: Option<&Path>,
72    script_execution_enabled: bool,
73) -> String {
74    let prefix = prefix.map_or(String::new(), |prefix| format!("{prefix}_"));
75    let tool_is_available =
76        |tool_name| allowed_tools.is_none_or(|tools| tools.contains(&tool_name));
77    let can_load_skill = tool_is_available(LOAD_SKILL_TOOL_NAME);
78    let can_load_resource = tool_is_available(LOAD_SKILL_RESOURCE_TOOL_NAME);
79    let can_run_script = script_execution_enabled && tool_is_available(RUN_SKILL_SCRIPT_TOOL_NAME);
80    let scripts_bullet = if can_run_script {
81        "- **scripts/** (Optional): Executable scripts that can be run via bash.\n\n".to_string()
82    } else if can_load_resource {
83        format!(
84            "- **scripts/** (Optional): Scripts bundled with the skill. You cannot run them; use `{}{}` to read one and follow it yourself.\n\n",
85            prefix, LOAD_SKILL_RESOURCE_TOOL_NAME
86        )
87    } else {
88        "- **scripts/** (Optional): Scripts bundled with the skill.\n\n".to_string()
89    };
90    let mut steps = Vec::new();
91    if can_load_skill {
92        steps.push(format!(
93            "If a skill seems relevant to the current user query, you MUST use the `{}{}` tool with `skill_name=\"<SKILL_NAME>\"` to read its full instructions before proceeding.",
94            prefix, LOAD_SKILL_TOOL_NAME
95        ));
96        steps.push("Once you have read the instructions, follow them exactly as documented before replying to the user. For example, if the instruction lists multiple steps, make sure you complete all of them in order.".to_string());
97    }
98    if can_load_resource {
99        steps.push(format!(
100            "The `{}{}` tool is for viewing files within a skill's directory (e.g., `references/*`, `assets/*`, `scripts/*`). It is ONLY for skill-bundled files — do NOT use it to access documents or files provided by the user at runtime. Do NOT use other tools to access skill files.",
101            prefix, LOAD_SKILL_RESOURCE_TOOL_NAME
102        ));
103        if can_load_skill {
104            steps.push(format!(
105                "If `{}{}` reports that a skill must be loaded first, call `{}{}` for that skill, then retry the resource request once. For any other resource error, do not retry any path; report the error to the user and stop.",
106                prefix, LOAD_SKILL_RESOURCE_TOOL_NAME, prefix, LOAD_SKILL_TOOL_NAME
107            ));
108        } else {
109            steps.push(format!(
110                "If `{}{}` returns an error, do not retry any path. Report the error to the user and stop.",
111                prefix, LOAD_SKILL_RESOURCE_TOOL_NAME
112            ));
113        }
114    }
115    if can_run_script {
116        let view_before_running = if can_load_resource {
117            format!(
118                " Use `{}{}` to view script content first if needed.",
119                prefix, LOAD_SKILL_RESOURCE_TOOL_NAME
120            )
121        } else {
122            String::new()
123        };
124        steps.push(format!(
125            "Use `{}{}` to run scripts from a skill's `scripts/` directory.{view_before_running}",
126            prefix, RUN_SKILL_SCRIPT_TOOL_NAME
127        ));
128        steps.push(format!(
129            "If `{}{}` returns an error (for example `SCRIPT_NOT_FOUND`), do not retry the same script or guess a different script path. Report the error to the user and stop.",
130            prefix, RUN_SKILL_SCRIPT_TOOL_NAME
131        ));
132    }
133    if can_load_skill {
134        steps.push(format!(
135            "Loading a skill only retrieves its instructions; it does NOT complete your turn. After a `{}{}` call returns, continue in the SAME turn: call whatever tools the skill's steps require (search, data retrieval, render), then write your reply. Never end your turn with an empty response right after loading a skill.",
136            prefix, LOAD_SKILL_TOOL_NAME
137        ));
138    }
139    if can_run_script && let Some(folder) = skills_folder {
140        let folder = folder.to_string_lossy();
141        steps.push(format!(
142            "NOTE ON ENVIRONMENT EXECUTION: When using `{}{}` with the `command` parameter, all skill resources (including scripts and assets) are materialized in the execution environment under `{}/<skill_name>/`. Always specify file and script paths relative to or starting with `{}/<skill_name>/` (e.g., `{}/<skill_name>/scripts/<script_name>`).",
143            prefix, RUN_SKILL_SCRIPT_TOOL_NAME, folder, folder, folder
144        ));
145    }
146
147    let mut instruction = format!(
148        "You can use specialized 'skills' to help you with complex tasks. You MUST use the skill tools to interact with these skills.\n\nSkills are folders of instructions and resources that extend your capabilities for specialized tasks. Each skill folder contains:\n- **SKILL.md** (required): The main instruction file with skill metadata and detailed markdown instructions.\n- **references/** (Optional): Additional documentation or examples for skill usage.\n- **assets/** (Optional): Templates, scripts or other resources used by the skill.\n\n{scripts_bullet}This is very important:\n\n{}",
149        steps
150            .iter()
151            .enumerate()
152            .map(|(index, step)| format!("{}. {step}\n", index + 1))
153            .collect::<String>()
154    );
155    if let Some(allowed_tools) = allowed_tools {
156        let banned = [
157            RUN_SKILL_SCRIPT_TOOL_NAME,
158            LOAD_SKILL_RESOURCE_TOOL_NAME,
159            LOAD_SKILL_TOOL_NAME,
160            LIST_SKILLS_TOOL_NAME,
161        ]
162        .into_iter()
163        .filter(|tool_name| !allowed_tools.contains(tool_name))
164        .map(|tool_name| format!("`{prefix}{tool_name}`"))
165        .collect::<Vec<_>>();
166        if !banned.is_empty() {
167            instruction.push_str(&format!(
168                "\n\nNote: The following tools are NOT available: {}. Do NOT call them. After loading a skill (if available), apply its instructions in context and write your final reply as normal model text. Never wrap the user-facing answer inside a tool call.\n",
169                banned.join(", ")
170            ));
171        }
172    }
173    instruction
174}
175
176/// Default progressive-skill instruction for ADK-Rust's supported discovery
177/// and resource-reading tools.
178pub static DEFAULT_SKILL_SYSTEM_INSTRUCTION: LazyLock<String> =
179    LazyLock::new(|| build_skill_system_instruction(None, None, None, false));
180
181/// Rules for reading bundled skill resources.
182///
183/// [`ActivatedOnly`](Self::ActivatedOnly) is the default: a model must load a
184/// skill before inspecting its auxiliary files. [`GoogleCompatible`](Self::GoogleCompatible)
185/// is an explicit opt-in for hosts that need Google ADK Python interoperability.
186#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
187pub enum ResourceAccessPolicy {
188    /// Require an earlier successful `load_skill` call for this agent.
189    #[default]
190    ActivatedOnly,
191    /// Permit direct reads of a known skill, matching Google ADK Python.
192    GoogleCompatible,
193}
194
195/// Serialized activation provenance retained in agent-scoped session state.
196///
197/// The content hash pins an activation to the exact skill revision the model
198/// loaded. When a skill is edited or removed, [`SkillToolset`] discards the
199/// stale record rather than silently retaining its tools or resources.
200#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
201#[serde(rename_all = "camelCase")]
202pub struct ActivatedSkill {
203    /// Content-addressed document ID.
204    pub skill_id: String,
205    /// Canonical skill name.
206    pub name: String,
207    /// Content hash captured at activation time.
208    pub hash: String,
209    /// Source-specific address used to reload the skill.
210    ///
211    /// Local skills use their canonical name. Registry-backed skills retain
212    /// their fully-qualified resource name so a frontmatter name change does
213    /// not prevent a later model turn from validating the activation. Older
214    /// serialized activations omit this field and fall back to [`Self::name`].
215    #[serde(default, skip_serializing_if = "Option::is_none")]
216    pub source: Option<String>,
217}
218
219/// Configuration for [`SkillToolset`].
220///
221/// Defaults require resource activation while retaining bounded
222/// instruction/resource output and strict declared-tool validation. Set
223/// [`ResourceAccessPolicy::GoogleCompatible`] only when direct reads are
224/// required for interoperability.
225///
226/// # Example
227///
228/// ```rust
229/// use adk_skill::{ResourceAccessPolicy, SkillToolsetConfig};
230///
231/// let config = SkillToolsetConfig {
232///     resource_access: ResourceAccessPolicy::ActivatedOnly,
233///     max_instruction_chars: 4_000,
234///     ..SkillToolsetConfig::default()
235/// };
236/// assert_eq!(config.max_instruction_chars, 4_000);
237/// ```
238#[derive(Debug, Clone)]
239pub struct SkillToolsetConfig {
240    /// Whether resources require activation first.
241    pub resource_access: ResourceAccessPolicy,
242    /// Reject or tolerate skills whose declared business tools cannot be resolved.
243    pub validation_mode: ValidationMode,
244    /// Maximum number of active skills for one agent.
245    pub max_active_skills: usize,
246    /// Maximum number of characters returned by `load_skill`.
247    pub max_instruction_chars: usize,
248    /// Maximum number of characters returned by `load_skill_resource`.
249    pub max_resource_chars: usize,
250}
251
252impl Default for SkillToolsetConfig {
253    fn default() -> Self {
254        Self {
255            resource_access: ResourceAccessPolicy::ActivatedOnly,
256            validation_mode: ValidationMode::Strict,
257            max_active_skills: 8,
258            max_instruction_chars: 8_000,
259            max_resource_chars: 16_000,
260        }
261    }
262}
263
264/// A context-aware toolset implementing L1/L2/L3 progressive disclosure.
265///
266/// Register this type with an [`adk_core::Toolset`] consumer, such as an
267/// `LlmAgentBuilder::toolset` integration. It always contributes the three
268/// discovery/loading tools. After `load_skill` succeeds, a subsequent call to
269/// [`Toolset::tools`] additionally returns that skill's validated
270/// `allowed-tools` from the supplied [`ToolRegistry`].
271///
272/// This is opt-in; it does not alter the behavior of [`crate::SkillInjector`]
273/// or [`crate::ContextCoordinator`].
274///
275/// # Example
276///
277/// ```rust,ignore
278/// use adk_agent::LlmAgentBuilder;
279/// use adk_skill::{SkillToolset, SkillToolsetConfig, load_skill_index};
280/// use std::sync::Arc;
281///
282/// let index = Arc::new(load_skill_index(".")?);
283/// let skills = SkillToolset::new(index, Arc::new(tool_registry), SkillToolsetConfig::default());
284/// let agent = LlmAgentBuilder::new("assistant")
285///     .model(model)
286///     .toolset(Arc::new(skills))
287///     .build()?;
288/// # Ok::<(), Box<dyn std::error::Error>>(())
289/// ```
290#[derive(Clone)]
291pub struct SkillToolset {
292    index: Arc<SkillIndex>,
293    tool_registry: Arc<dyn ToolRegistry>,
294    config: SkillToolsetConfig,
295    #[cfg(feature = "vertex-skill-registry")]
296    registry_client: Option<Arc<SkillRegistryClient>>,
297    #[cfg(feature = "vertex-skill-registry")]
298    remote_cache: SharedRemoteSkillCache,
299}
300
301#[cfg(feature = "vertex-skill-registry")]
302#[derive(Clone)]
303struct RemoteSkill {
304    document: SkillDocument,
305    files: BTreeMap<String, Vec<u8>>,
306    locator: String,
307}
308
309#[cfg(feature = "vertex-skill-registry")]
310type RemoteSkillCache = HashMap<String, HashMap<String, Arc<RemoteSkill>>>;
311#[cfg(feature = "vertex-skill-registry")]
312type SharedRemoteSkillCache = Arc<RwLock<RemoteSkillCache>>;
313
314#[derive(Clone)]
315enum LoadedSkill {
316    Local(Arc<SkillDocument>),
317    #[cfg(feature = "vertex-skill-registry")]
318    Remote(Arc<RemoteSkill>),
319}
320
321impl LoadedSkill {
322    fn document(&self) -> &SkillDocument {
323        match self {
324            Self::Local(document) => document,
325            #[cfg(feature = "vertex-skill-registry")]
326            Self::Remote(skill) => &skill.document,
327        }
328    }
329
330    fn locator(&self) -> &str {
331        match self {
332            Self::Local(document) => &document.name,
333            #[cfg(feature = "vertex-skill-registry")]
334            Self::Remote(skill) => &skill.locator,
335        }
336    }
337
338    fn resource_content(&self, requested: &str) -> Result<String> {
339        match self {
340            Self::Local(skill) => {
341                let resource = SkillToolset::resource_path(skill, requested)?;
342                fs::read_to_string(&resource).map_err(|error| {
343                    AdkError::tool(format!("read skill resource '{requested}': {error}"))
344                })
345            }
346            #[cfg(feature = "vertex-skill-registry")]
347            Self::Remote(skill) => {
348                SkillToolset::validate_resource_path(requested)?;
349                let bytes = skill.files.get(requested).ok_or_else(|| {
350                    AdkError::tool(format!(
351                        "resource '{requested}' was not found in skill '{}'",
352                        skill.document.name
353                    ))
354                })?;
355                String::from_utf8(bytes.clone()).map_err(|_| {
356                    AdkError::tool(format!(
357                        "resource '{requested}' is binary and cannot be returned as text"
358                    ))
359                })
360            }
361        }
362    }
363}
364
365impl SkillToolset {
366    /// Creates a progressive skill toolset from an existing index.
367    ///
368    /// `tool_registry` is consulted at skill activation time and on each later
369    /// model turn. This permits a host to enforce availability, authorization,
370    /// or tenant-specific tool policies without placing provider logic in this
371    /// crate.
372    pub fn new(
373        index: Arc<SkillIndex>,
374        tool_registry: Arc<dyn ToolRegistry>,
375        config: SkillToolsetConfig,
376    ) -> Self {
377        Self {
378            index,
379            tool_registry,
380            config,
381            #[cfg(feature = "vertex-skill-registry")]
382            registry_client: None,
383            #[cfg(feature = "vertex-skill-registry")]
384            remote_cache: Arc::new(RwLock::new(HashMap::new())),
385        }
386    }
387
388    /// Enables lazy loading and semantic discovery from Vertex Skill Registry.
389    ///
390    /// Remote packages are fetched only when the model calls `load_skill` or
391    /// `load_skill_resource`. Each verified package is cached per invocation;
392    /// the cache is discarded with the toolset, not persisted into sessions.
393    /// It also adds the registry's `search_skills` tool to the L1 surface.
394    ///
395    /// # Example
396    ///
397    /// ```rust,ignore
398    /// use adk_skill::{SkillToolset, registry::SkillRegistryClient};
399    /// use std::sync::Arc;
400    ///
401    /// let toolset = SkillToolset::new(index, tool_registry, config)
402    ///     .with_registry_client(Arc::new(SkillRegistryClient::new_with_adc(registry_config)?));
403    /// # Ok::<(), Box<dyn std::error::Error>>(())
404    /// ```
405    #[cfg(feature = "vertex-skill-registry")]
406    #[must_use]
407    pub fn with_registry_client(mut self, client: Arc<SkillRegistryClient>) -> Self {
408        self.registry_client = Some(client);
409        self
410    }
411
412    /// Returns the state key used to persist activations for an agent.
413    ///
414    /// This is public for hosts that need to inspect, migrate, or clear an
415    /// activation explicitly. The agent name is part of the key so transferred
416    /// or nested agents do not inherit another agent's selected skills.
417    pub fn activation_state_key(agent_name: &str) -> String {
418        format!("{STATE_KEY_PREFIX}{agent_name}")
419    }
420
421    fn core_tools(&self) -> Vec<Arc<dyn Tool>> {
422        vec![
423            Arc::new(ListSkillsTool { toolset: self.clone() }),
424            Arc::new(LoadSkillTool { toolset: self.clone() }),
425            Arc::new(LoadSkillResourceTool { toolset: self.clone() }),
426        ]
427    }
428
429    fn summaries(&self) -> Vec<SkillSummary> {
430        self.index.summaries()
431    }
432
433    async fn load_skill(&self, ctx: &dyn ReadonlyContext, name: &str) -> Result<LoadedSkill> {
434        if let Some(skill) = self.index.find_by_name(name) {
435            return Ok(LoadedSkill::Local(Arc::new(skill.clone())));
436        }
437
438        #[cfg(feature = "vertex-skill-registry")]
439        if let Some(client) = &self.registry_client {
440            // The name comes from the model, and the registry request carries the agent's
441            // credentials, so only this project's skills may be named.
442            let own_skill = name
443                .strip_prefix(client.parent_resource_name())
444                .and_then(|rest| rest.strip_prefix("/skills/"))
445                .unwrap_or(name);
446            if crate::validate_skill_name(own_skill).is_err() {
447                return Err(AdkError::tool(format!(
448                    "skill '{}' was not found; registry skills are loaded by their name, such as \
449                     'expense-report', from the project this agent is configured for",
450                    name.escape_debug()
451                )));
452            }
453            return Ok(LoadedSkill::Remote(
454                self.fetch_remote_skill(client, ctx.invocation_id(), name).await?,
455            ));
456        }
457
458        #[cfg(not(feature = "vertex-skill-registry"))]
459        let _ = ctx;
460
461        Err(AdkError::tool(format!("skill '{name}' was not found")))
462    }
463
464    #[cfg(feature = "vertex-skill-registry")]
465    async fn fetch_remote_skill(
466        &self,
467        client: &SkillRegistryClient,
468        invocation_id: &str,
469        name: &str,
470    ) -> Result<Arc<RemoteSkill>> {
471        if let Some(skill) = self
472            .remote_cache
473            .read()
474            .await
475            .get(invocation_id)
476            .and_then(|skills| skills.get(name))
477            .cloned()
478        {
479            return Ok(skill);
480        }
481
482        let content = client.fetch_skill_content(name).await?;
483        let remote = Arc::new(Self::remote_skill_from_content(content)?);
484        let mut cache = self.remote_cache.write().await;
485        // Keep cache retention bounded even when a long-lived toolset serves
486        // many invocations. Each inner map may contain aliases for one package;
487        // eviction order is irrelevant because invocation caches are advisory.
488        if !cache.contains_key(invocation_id)
489            && cache.len() >= MAX_REMOTE_CACHE_INVOCATIONS
490            && let Some(evicted) = cache.keys().next().cloned()
491        {
492            cache.remove(&evicted);
493        }
494        let entries = cache.entry(invocation_id.to_string()).or_default();
495        entries.insert(name.to_string(), remote.clone());
496        entries.insert(remote.document.name.clone(), remote.clone());
497        Ok(remote)
498    }
499
500    #[cfg(feature = "vertex-skill-registry")]
501    fn remote_skill_from_content(content: SkillContent) -> Result<RemoteSkill> {
502        let document = crate::registry::load::document_from_content(&content)
503            .map_err(adk_core::AdkError::from)?;
504        let locator = content.skill.name;
505        Ok(RemoteSkill { document, files: content.files, locator })
506    }
507
508    fn activated_skills(&self, ctx: &dyn ReadonlyContext) -> Vec<ActivatedSkill> {
509        let key = Self::activation_state_key(ctx.agent_name());
510        ctx.state()
511            .and_then(|state| state.get(&key).and_then(|value| serde_json::from_value(value).ok()))
512            .unwrap_or_default()
513    }
514
515    async fn valid_activated_skills(&self, ctx: &dyn ReadonlyContext) -> Vec<LoadedSkill> {
516        let mut valid = Vec::new();
517        for activation in self.activated_skills(ctx) {
518            let source = activation.source.as_deref().unwrap_or(&activation.name);
519            let Ok(skill) = self.load_skill(ctx, source).await else {
520                continue;
521            };
522            let document = skill.document();
523            if document.id == activation.skill_id && document.hash == activation.hash {
524                valid.push(skill);
525            }
526        }
527        valid
528    }
529
530    async fn activate(&self, ctx: &dyn ToolContext, skill: &LoadedSkill) -> Result<()> {
531        let document = skill.document();
532        let mut active = self
533            .valid_activated_skills(ctx)
534            .await
535            .into_iter()
536            .map(|skill| ActivatedSkill {
537                skill_id: skill.document().id.clone(),
538                name: skill.document().name.clone(),
539                hash: skill.document().hash.clone(),
540                source: Some(skill.locator().to_string()),
541            })
542            .collect::<Vec<_>>();
543        if !active.iter().any(|item| item.skill_id == document.id) {
544            if active.len() >= self.config.max_active_skills {
545                return Err(AdkError::tool(format!(
546                    "cannot activate skill '{}': the {}-skill limit has been reached",
547                    document.name, self.config.max_active_skills
548                )));
549            }
550            active.push(ActivatedSkill {
551                skill_id: document.id.clone(),
552                name: document.name.clone(),
553                hash: document.hash.clone(),
554                source: Some(skill.locator().to_string()),
555            });
556        }
557
558        let mut actions = ctx.actions();
559        actions.state_delta.insert(
560            Self::activation_state_key(ctx.agent_name()),
561            serde_json::to_value(active)
562                .map_err(|error| AdkError::tool(format!("serialize skill activation: {error}")))?,
563        );
564        ctx.set_actions(actions);
565        Ok(())
566    }
567
568    fn validate_skill_tools(&self, skill: &SkillDocument) -> Result<()> {
569        if self.config.validation_mode != ValidationMode::Strict {
570            return Ok(());
571        }
572        let missing = skill
573            .allowed_tools
574            .iter()
575            .filter(|name| self.tool_registry.resolve(name).is_none())
576            .cloned()
577            .collect::<Vec<_>>();
578        if missing.is_empty() {
579            Ok(())
580        } else {
581            Err(AdkError::tool(format!(
582                "skill '{}' requires unavailable tools: {}",
583                skill.name,
584                missing.join(", ")
585            )))
586        }
587    }
588
589    fn resource_path(skill: &SkillDocument, requested: &str) -> Result<PathBuf> {
590        let relative = Self::validate_resource_path(requested)?;
591        let root = skill.path.parent().ok_or_else(|| {
592            AdkError::tool(format!("skill '{}' has no parent resource directory", skill.name))
593        })?;
594        let root = fs::canonicalize(root)
595            .map_err(|error| AdkError::tool(format!("resolve skill resource root: {error}")))?;
596        let candidate = fs::canonicalize(root.join(relative)).map_err(|error| {
597            AdkError::tool(format!("resource '{requested}' could not be resolved: {error}"))
598        })?;
599        if !candidate.starts_with(&root) {
600            return Err(AdkError::tool("resource path escapes the skill directory"));
601        }
602        Ok(candidate)
603    }
604
605    fn validate_resource_path(requested: &str) -> Result<&Path> {
606        let relative = Path::new(requested);
607        // Check lexical components before filesystem resolution. Canonicalization
608        // below then catches symlinks that would otherwise escape this package.
609        if !matches!(
610            relative.components().next(),
611            Some(Component::Normal(prefix))
612                if prefix == "references" || prefix == "assets" || prefix == "scripts"
613        ) || relative.is_absolute()
614            || relative.components().any(|component| matches!(component, Component::ParentDir))
615        {
616            return Err(AdkError::tool(
617                "resource path must be a relative path under references/, assets/, or scripts/",
618            ));
619        }
620        Ok(relative)
621    }
622
623    fn truncate(value: String, limit: usize) -> String {
624        if value.chars().count() <= limit {
625            return value;
626        }
627        let mut truncated = value.chars().take(limit).collect::<String>();
628        truncated.push_str("\n[... truncated]");
629        truncated
630    }
631
632    async fn resolve_business_tools(
633        &self,
634        ctx: &dyn ReadonlyContext,
635    ) -> Result<Vec<Arc<dyn Tool>>> {
636        let mut names = HashSet::new();
637        let mut tools = Vec::new();
638        let mut missing = Vec::new();
639
640        for active in self.valid_activated_skills(ctx).await {
641            for name in &active.document().allowed_tools {
642                if !names.insert(name.clone()) {
643                    continue;
644                }
645                match self.tool_registry.resolve(name) {
646                    Some(tool) => tools.push(tool),
647                    None => missing.push(name.clone()),
648                }
649            }
650        }
651
652        if !missing.is_empty() && self.config.validation_mode == ValidationMode::Strict {
653            return Err(AdkError::tool(format!(
654                "activated skills require unavailable tools: {}",
655                missing.join(", ")
656            )));
657        }
658        if !missing.is_empty() {
659            tracing::warn!(missing_tools = ?missing, "omitting unavailable skill tools");
660        }
661        Ok(tools)
662    }
663}
664
665#[async_trait]
666impl Toolset for SkillToolset {
667    fn name(&self) -> &str {
668        "skills"
669    }
670
671    async fn tools(&self, ctx: Arc<dyn ReadonlyContext>) -> Result<Vec<Arc<dyn Tool>>> {
672        let mut tools = self.core_tools();
673        #[cfg(feature = "vertex-skill-registry")]
674        if let Some(client) = &self.registry_client {
675            tools.push(Arc::new(SkillSearchTool::new(client.clone())));
676        }
677        tools.extend(self.resolve_business_tools(ctx.as_ref()).await?);
678        Ok(tools)
679    }
680
681    async fn process_llm_request(
682        &self,
683        _ctx: Arc<dyn ReadonlyContext>,
684        request: &mut LlmRequest,
685    ) -> Result<()> {
686        // LlmAgent instructions use user-role content for compatibility with
687        // providers that do not support a system role. Keep this protocol in
688        // the same request preamble, without persisting it to session history.
689        let available_tools =
690            [LIST_SKILLS_TOOL_NAME, LOAD_SKILL_TOOL_NAME, LOAD_SKILL_RESOURCE_TOOL_NAME];
691        request.contents.insert(
692            0,
693            Content::new("user").with_text(build_skill_system_instruction(
694                None,
695                Some(&available_tools),
696                None,
697                false,
698            )),
699        );
700        Ok(())
701    }
702}
703
704struct ListSkillsTool {
705    toolset: SkillToolset,
706}
707
708#[async_trait]
709impl Tool for ListSkillsTool {
710    fn name(&self) -> &str {
711        "list_skills"
712    }
713    fn description(&self) -> &str {
714        "Lists available skills with their names and descriptions."
715    }
716    fn is_read_only(&self) -> bool {
717        true
718    }
719    fn is_concurrency_safe(&self) -> bool {
720        true
721    }
722    fn parameters_schema(&self) -> Option<Value> {
723        Some(json!({"type": "object", "properties": {}}))
724    }
725    async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
726        serde_json::to_value(self.toolset.summaries())
727            .map_err(|error| AdkError::tool(format!("serialize skill catalog: {error}")))
728    }
729}
730
731struct LoadSkillTool {
732    toolset: SkillToolset,
733}
734
735#[async_trait]
736impl Tool for LoadSkillTool {
737    fn name(&self) -> &str {
738        "load_skill"
739    }
740    fn description(&self) -> &str {
741        "Loads the SKILL.md instructions for a given skill."
742    }
743    fn parameters_schema(&self) -> Option<Value> {
744        Some(
745            json!({"type":"object","properties":{"skill_name":{"type":"string"}},"required":["skill_name"]}),
746        )
747    }
748    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
749        let name = args
750            .get("skill_name")
751            .and_then(Value::as_str)
752            .ok_or_else(|| AdkError::tool("missing required string argument 'skill_name'"))?;
753        let skill = self.toolset.load_skill(ctx.as_ref(), name).await?;
754        let document = skill.document();
755        self.toolset.validate_skill_tools(document)?;
756        self.toolset.activate(ctx.as_ref(), &skill).await?;
757        Ok(json!({
758            "skillName": document.name,
759            "skillId": document.id,
760            "hash": document.hash,
761            "instructions": SkillToolset::truncate(document.body.clone(), self.toolset.config.max_instruction_chars),
762            "frontmatter": SkillSummary::from(document),
763        }))
764    }
765}
766
767struct LoadSkillResourceTool {
768    toolset: SkillToolset,
769}
770
771#[async_trait]
772impl Tool for LoadSkillResourceTool {
773    fn name(&self) -> &str {
774        "load_skill_resource"
775    }
776    fn description(&self) -> &str {
777        "Loads a resource file from references/, assets/, or scripts/ within a skill."
778    }
779    fn is_read_only(&self) -> bool {
780        true
781    }
782    fn parameters_schema(&self) -> Option<Value> {
783        Some(
784            json!({"type":"object","properties":{"skill_name":{"type":"string"},"file_path":{"type":"string"}},"required":["skill_name","file_path"]}),
785        )
786    }
787    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
788        let name = args
789            .get("skill_name")
790            .and_then(Value::as_str)
791            .ok_or_else(|| AdkError::tool("missing required string argument 'skill_name'"))?;
792        let path = args
793            .get("file_path")
794            .and_then(Value::as_str)
795            .ok_or_else(|| AdkError::tool("missing required string argument 'file_path'"))?;
796        let skill = self.toolset.load_skill(ctx.as_ref(), name).await?;
797        let document = skill.document();
798        if self.toolset.config.resource_access == ResourceAccessPolicy::ActivatedOnly
799            && !self
800                .toolset
801                .valid_activated_skills(ctx.as_ref())
802                .await
803                .iter()
804                .any(|item| item.document().id == document.id)
805        {
806            return Err(AdkError::tool(format!(
807                "skill '{name}' must be loaded before reading its resources; call load_skill first"
808            )));
809        }
810        let content = skill.resource_content(path)?;
811        Ok(json!({
812            "skillName": document.name,
813            "filePath": path,
814            "content": SkillToolset::truncate(content, self.toolset.config.max_resource_chars),
815        }))
816    }
817}
818
819#[cfg(test)]
820mod tests {
821    use super::*;
822    use adk_core::{Artifacts, CallbackContext, Content, EventActions, MemoryEntry, State};
823    use async_trait::async_trait;
824    use std::{collections::HashMap, sync::Mutex};
825
826    #[derive(Default)]
827    struct TestState {
828        values: HashMap<String, Value>,
829    }
830
831    impl State for TestState {
832        fn get(&self, key: &str) -> Option<Value> {
833            self.values.get(key).cloned()
834        }
835
836        fn set(&mut self, key: String, value: Value) {
837            self.values.insert(key, value);
838        }
839
840        fn all(&self) -> HashMap<String, Value> {
841            self.values.clone()
842        }
843    }
844
845    struct TestContext {
846        state: TestState,
847        actions: Mutex<EventActions>,
848        user_content: Content,
849    }
850
851    impl TestContext {
852        fn new() -> Self {
853            Self {
854                state: TestState::default(),
855                actions: Mutex::new(EventActions::default()),
856                user_content: Content::new("user").with_text("test"),
857            }
858        }
859
860        fn with_state(key: String, value: Value) -> Self {
861            let mut state = TestState::default();
862            state.set(key, value);
863            Self {
864                state,
865                actions: Mutex::new(EventActions::default()),
866                user_content: Content::new("user").with_text("test"),
867            }
868        }
869    }
870
871    #[async_trait]
872    impl ReadonlyContext for TestContext {
873        fn invocation_id(&self) -> &str {
874            "invocation"
875        }
876        fn agent_name(&self) -> &str {
877            "agent"
878        }
879        fn user_id(&self) -> &str {
880            "user"
881        }
882        fn app_name(&self) -> &str {
883            "app"
884        }
885        fn session_id(&self) -> &str {
886            "session"
887        }
888        fn branch(&self) -> &str {
889            ""
890        }
891        fn user_content(&self) -> &Content {
892            &self.user_content
893        }
894        fn state(&self) -> Option<&dyn State> {
895            Some(&self.state)
896        }
897    }
898
899    #[async_trait]
900    impl CallbackContext for TestContext {
901        fn artifacts(&self) -> Option<Arc<dyn Artifacts>> {
902            None
903        }
904    }
905
906    #[async_trait]
907    impl ToolContext for TestContext {
908        fn function_call_id(&self) -> &str {
909            "call"
910        }
911        fn actions(&self) -> EventActions {
912            self.actions.lock().expect("actions lock").clone()
913        }
914        fn set_actions(&self, actions: EventActions) {
915            *self.actions.lock().expect("actions lock") = actions;
916        }
917        async fn search_memory(&self, _query: &str) -> Result<Vec<MemoryEntry>> {
918            Ok(Vec::new())
919        }
920    }
921
922    struct DummyTool;
923
924    #[async_trait]
925    impl Tool for DummyTool {
926        fn name(&self) -> &str {
927            "weather_lookup"
928        }
929        fn description(&self) -> &str {
930            "Looks up weather."
931        }
932        async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
933            Ok(Value::Null)
934        }
935    }
936
937    struct TestRegistry;
938
939    impl ToolRegistry for TestRegistry {
940        fn resolve(&self, tool_name: &str) -> Option<Arc<dyn Tool>> {
941            (tool_name == "weather_lookup").then(|| Arc::new(DummyTool) as Arc<dyn Tool>)
942        }
943    }
944
945    fn setup() -> (tempfile::TempDir, SkillToolset) {
946        let temp = tempfile::tempdir().expect("tempdir");
947        let skill_dir = temp.path().join(".skills/weather");
948        fs::create_dir_all(skill_dir.join("references")).expect("skill directories");
949        fs::write(
950            skill_dir.join("SKILL.md"),
951            "---\nname: weather\ndescription: Answer weather questions\nallowed-tools: [weather_lookup]\n---\nLoad references/units.md before answering.\n",
952        )
953        .expect("skill file");
954        fs::write(skill_dir.join("references/units.md"), "Use Celsius.").expect("reference");
955        let index = Arc::new(crate::load_skill_index(temp.path()).expect("skill index"));
956        (temp, SkillToolset::new(index, Arc::new(TestRegistry), SkillToolsetConfig::default()))
957    }
958
959    fn tool_by_name(tools: &[Arc<dyn Tool>], name: &str) -> Arc<dyn Tool> {
960        tools.iter().find(|tool| tool.name() == name).expect("tool present").clone()
961    }
962
963    #[test]
964    fn skill_system_instruction_reflects_available_tools() {
965        let default_instruction = build_skill_system_instruction(None, None, None, false);
966        assert_eq!(&*DEFAULT_SKILL_SYSTEM_INSTRUCTION, &default_instruction);
967        assert!(default_instruction.contains("`load_skill`"));
968        assert!(default_instruction.contains("You cannot run them"));
969        assert!(default_instruction.contains("must be loaded first"));
970        assert!(default_instruction.contains("then retry the resource request once"));
971
972        let filtered = build_skill_system_instruction(
973            Some("workspace"),
974            Some(&[LIST_SKILLS_TOOL_NAME, LOAD_SKILL_TOOL_NAME]),
975            None,
976            false,
977        );
978        assert!(filtered.contains("`workspace_load_skill`"));
979        assert!(!filtered.contains("The `workspace_load_skill_resource` tool is for viewing"));
980        assert!(!filtered.contains("If `workspace_load_skill_resource` returns any error"));
981        assert!(filtered.contains("The following tools are NOT available"));
982    }
983
984    #[tokio::test]
985    async fn loading_a_skill_activates_its_declared_tool_and_resource_access() {
986        let (_temp, toolset) = setup();
987        let first_context = Arc::new(TestContext::new());
988        let initial_tools = toolset.tools(first_context.clone()).await.expect("initial tools");
989        assert_eq!(initial_tools.len(), 3);
990        assert!(!initial_tools.iter().any(|tool| tool.name() == "weather_lookup"));
991
992        let load = tool_by_name(&initial_tools, "load_skill");
993        let loaded = load
994            .execute(first_context.clone(), json!({"skill_name": "weather"}))
995            .await
996            .expect("load skill");
997        assert_eq!(loaded["skillName"], "weather");
998        assert!(loaded["instructions"].as_str().expect("instructions").contains("units.md"));
999
1000        let state_key = SkillToolset::activation_state_key("agent");
1001        let activation =
1002            first_context.actions().state_delta.remove(&state_key).expect("activation state");
1003        let second_context = Arc::new(TestContext::with_state(state_key, activation));
1004        let activated_tools = toolset.tools(second_context.clone()).await.expect("activated tools");
1005        assert!(activated_tools.iter().any(|tool| tool.name() == "weather_lookup"));
1006
1007        let resource = tool_by_name(&activated_tools, "load_skill_resource");
1008        let loaded_resource = resource
1009            .execute(
1010                second_context,
1011                json!({"skill_name": "weather", "file_path": "references/units.md"}),
1012            )
1013            .await
1014            .expect("load resource");
1015        assert_eq!(loaded_resource["content"], "Use Celsius.");
1016    }
1017
1018    #[tokio::test]
1019    async fn default_resources_require_activation() {
1020        let (_temp, toolset) = setup();
1021        let context = Arc::new(TestContext::new());
1022        let resource = tool_by_name(
1023            &toolset.tools(context.clone()).await.expect("tools"),
1024            "load_skill_resource",
1025        );
1026        let error = resource
1027            .execute(context, json!({"skill_name": "weather", "file_path": "references/units.md"}))
1028            .await
1029            .expect_err("resource access must require activation by default");
1030        assert!(error.to_string().contains("must be loaded"));
1031    }
1032
1033    #[tokio::test]
1034    async fn google_compatible_policy_allows_direct_resource_reads() {
1035        let (_temp, mut toolset) = setup();
1036        toolset.config.resource_access = ResourceAccessPolicy::GoogleCompatible;
1037        let context = Arc::new(TestContext::new());
1038        let resource = tool_by_name(
1039            &toolset.tools(context.clone()).await.expect("tools"),
1040            "load_skill_resource",
1041        );
1042        let loaded = resource
1043            .execute(context, json!({"skill_name": "weather", "file_path": "references/units.md"}))
1044            .await
1045            .expect("explicit Google-compatible resource read");
1046        assert_eq!(loaded["content"], "Use Celsius.");
1047    }
1048
1049    #[tokio::test]
1050    async fn resources_require_activation_and_reject_path_traversal() {
1051        let (_temp, mut toolset) = setup();
1052        toolset.config.resource_access = ResourceAccessPolicy::ActivatedOnly;
1053        let context = Arc::new(TestContext::new());
1054        let tools = toolset.tools(context.clone()).await.expect("tools");
1055        let resource = tool_by_name(&tools, "load_skill_resource");
1056        let error = resource
1057            .execute(
1058                context.clone(),
1059                json!({"skill_name": "weather", "file_path": "references/units.md"}),
1060            )
1061            .await
1062            .expect_err("activation denial must remain a tool error");
1063        assert!(error.to_string().contains("call load_skill first"));
1064
1065        let load = tool_by_name(&tools, "load_skill");
1066        load.execute(context.clone(), json!({"skill_name": "weather"})).await.expect("load skill");
1067        let state_key = SkillToolset::activation_state_key("agent");
1068        let activation =
1069            context.actions().state_delta.remove(&state_key).expect("activation state");
1070        let active_context = Arc::new(TestContext::with_state(state_key, activation));
1071        let error = resource
1072            .execute(
1073                active_context,
1074                json!({"skill_name": "weather", "file_path": "references/../SKILL.md"}),
1075            )
1076            .await
1077            .expect_err("traversal must fail");
1078        assert!(error.to_string().contains("resource path"));
1079    }
1080
1081    /// A registry endpoint on 127.0.0.1 that records every request path and answers 404.
1082    #[cfg(feature = "vertex-skill-registry")]
1083    async fn recording_registry() -> (Arc<SkillRegistryClient>, Arc<Mutex<Vec<String>>>) {
1084        use crate::registry::SkillRegistryConfig;
1085        let paths: Arc<Mutex<Vec<String>>> = Arc::default();
1086        let recorded = paths.clone();
1087        let app = axum::Router::new().fallback(move |uri: axum::http::Uri| {
1088            let recorded = recorded.clone();
1089            async move {
1090                recorded.lock().expect("paths lock").push(uri.path().to_string());
1091                axum::http::StatusCode::NOT_FOUND
1092            }
1093        });
1094        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.expect("bind");
1095        let endpoint = format!("http://{}", listener.local_addr().expect("address"));
1096        tokio::spawn(async move {
1097            let _ = axum::serve(listener, app).await;
1098        });
1099        let config = SkillRegistryConfig::new("own", "us-central1").with_endpoint(endpoint);
1100        let credentials =
1101            google_cloud_auth::credentials::api_key_credentials::Builder::new("k").build();
1102        let client = SkillRegistryClient::with_credentials(config, credentials).expect("client");
1103        (Arc::new(client), paths)
1104    }
1105
1106    #[cfg(feature = "vertex-skill-registry")]
1107    #[tokio::test]
1108    async fn model_supplied_names_reach_only_this_projects_registry_skills() {
1109        let (client, paths) = recording_registry().await;
1110        let toolset = SkillToolset::new(
1111            Arc::new(SkillIndex::new(Vec::new())),
1112            Arc::new(TestRegistry),
1113            SkillToolsetConfig::default(),
1114        )
1115        .with_registry_client(client);
1116        let context = Arc::new(TestContext::new());
1117        let load =
1118            tool_by_name(&toolset.tools(context.clone()).await.expect("tools"), "load_skill");
1119
1120        for hostile in [
1121            "projects/victim/locations/us-central1/skills/payroll",
1122            "../../victim/locations/us-central1/skills/payroll",
1123            "projects/own/locations/us-central1/skills/../../../victim/skills/payroll",
1124            "payroll?alt=media",
1125            "Payroll",
1126        ] {
1127            let error = load
1128                .execute(context.clone(), json!({ "skill_name": hostile }))
1129                .await
1130                .expect_err(hostile);
1131            assert!(error.message.contains("was not found"), "{hostile}: {}", error.message);
1132        }
1133        assert_eq!(*paths.lock().expect("paths lock"), Vec::<String>::new());
1134
1135        for own in ["expense-report", "projects/own/locations/us-central1/skills/expense-report"] {
1136            let _ = load.execute(context.clone(), json!({ "skill_name": own })).await;
1137        }
1138        assert_eq!(
1139            *paths.lock().expect("paths lock"),
1140            vec![
1141                "/v1beta1/projects/own/locations/us-central1/skills/expense-report".to_string();
1142                2
1143            ]
1144        );
1145    }
1146}