Skip to main content

adk_skill/
model.rs

1use adk_core::Tool;
2use serde::{Deserialize, Serialize};
3use std::path::PathBuf;
4use std::sync::Arc;
5
6/// Frontmatter metadata for a skill, following the `agentskills.io` specification.
7#[derive(Debug, Clone, Default, Serialize, Deserialize)]
8#[serde(default)]
9pub struct SkillFrontmatter {
10    /// A required short identifier (1-64 chars) containing only lowercase letters, numbers, and hyphens.
11    pub name: String,
12    /// A required concise description of what the skill does and when an agent should use it.
13    pub description: String,
14    /// An optional version identifier for the skill (e.g., "1.0.0").
15    pub version: Option<String>,
16    /// An optional license identifier or reference to a bundled license file.
17    pub license: Option<String>,
18    /// Optional environment requirements (e.g., "Requires system packages, network access").
19    pub compatibility: Option<String>,
20    /// A collection of categorizing labels for discovery and filtering.
21    #[serde(default)]
22    pub tags: Vec<String>,
23    /// Experimental: pre-approved tools the skill may use.
24    ///
25    /// Accepts a YAML list or, as the `agentskills.io` specification writes it, one
26    /// string of names separated by spaces or commas (`allowed-tools: Read Grep`).
27    #[serde(default, rename = "allowed-tools", deserialize_with = "names_or_list")]
28    pub allowed_tools: Vec<String>,
29    /// Optional list of paths to supporting resources (e.g., "references/data.json").
30    #[serde(default)]
31    pub references: Vec<String>,
32    /// If true, the skill is only included when explicitly invoked by name.
33    pub trigger: Option<bool>,
34    /// Optional hint text displayed for slash command guided input.
35    pub hint: Option<String>,
36    /// Arbitrary key-value mapping for custom extension metadata.
37    #[serde(default)]
38    pub metadata: std::collections::HashMap<String, serde_json::Value>,
39    /// File glob patterns that determine when this skill activates (e.g., `["*.rs", "Cargo.toml"]`).
40    #[serde(default)]
41    pub triggers: Vec<String>,
42}
43
44/// Reads a list of names written either as a sequence or as one delimited string.
45fn names_or_list<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
46where
47    D: serde::Deserializer<'de>,
48{
49    #[derive(Deserialize)]
50    #[serde(untagged)]
51    enum Names {
52        List(Vec<String>),
53        Text(String),
54    }
55    Ok(match Option::<Names>::deserialize(deserializer)? {
56        Some(Names::List(names)) => names,
57        Some(Names::Text(text)) => text
58            .split(|c: char| c.is_whitespace() || c == ',')
59            .filter(|name| !name.is_empty())
60            .map(str::to_string)
61            .collect(),
62        None => Vec::new(),
63    })
64}
65
66/// A parsed skill before it is assigned an ID and indexed.
67#[derive(Debug, Clone)]
68pub struct ParsedSkill {
69    /// The unique identifier from the frontmatter or filename.
70    pub name: String,
71    /// Description of the skill's purpose.
72    pub description: String,
73    /// Optional versioning string.
74    pub version: Option<String>,
75    /// Optional license information.
76    pub license: Option<String>,
77    /// Optional compatibility requirements.
78    pub compatibility: Option<String>,
79    /// Discovery tags.
80    pub tags: Vec<String>,
81    /// Pre-approved tool names.
82    pub allowed_tools: Vec<String>,
83    /// Supporting resource paths.
84    pub references: Vec<String>,
85    /// Whether the skill requires explicit invocation.
86    pub trigger: bool,
87    /// Guided input hint.
88    pub hint: Option<String>,
89    /// Extension metadata.
90    pub metadata: std::collections::HashMap<String, serde_json::Value>,
91    /// File glob patterns for activation triggers.
92    pub triggers: Vec<String>,
93    /// The raw Markdown body content (instructions).
94    pub body: String,
95}
96
97/// A fully indexed skill document with a content-based unique ID.
98#[derive(Debug, Clone, Serialize)]
99pub struct SkillDocument {
100    /// A unique ID derived from the name and content hash.
101    pub id: String,
102    /// The canonical name of the skill.
103    pub name: String,
104    /// Description used for agent discovery.
105    pub description: String,
106    /// Semantic version.
107    pub version: Option<String>,
108    /// License tag.
109    pub license: Option<String>,
110    /// Environment constraints.
111    pub compatibility: Option<String>,
112    /// List of discovery tags.
113    pub tags: Vec<String>,
114    /// Tools allowed for this skill.
115    pub allowed_tools: Vec<String>,
116    /// External resources required by the skill.
117    pub references: Vec<String>,
118    /// If true, requires explicit `@name` invocation.
119    pub trigger: bool,
120    /// Input guidance for users.
121    pub hint: Option<String>,
122    /// Custom extension metadata.
123    pub metadata: std::collections::HashMap<String, serde_json::Value>,
124    /// The instructional Markdown body.
125    pub body: String,
126    /// File system path where the skill was loaded from.
127    pub path: PathBuf,
128    /// SHA256 hash of the content.
129    pub hash: String,
130    /// Optional Unix timestamp of last file modification.
131    pub last_modified: Option<i64>,
132    /// File glob patterns for activation triggers.
133    pub triggers: Vec<String>,
134}
135
136impl SkillDocument {
137    /// Engineers a full system instruction from the skill body, with truncation
138    /// and optionally including tool capability hints.
139    pub fn engineer_instruction(&self, max_chars: usize, active_tools: &[Arc<dyn Tool>]) -> String {
140        let mut body = self.body.clone();
141        if body.chars().count() > max_chars {
142            body = body.chars().take(max_chars).collect();
143            body.push_str("\n[... truncated]");
144        }
145
146        let mut parts = Vec::new();
147        parts.push(format!("[skill:{}]", self.name));
148        parts.push(format!("# {}\n{}", self.name, self.description));
149
150        // Tool capability hint (so the LLM knows what it can do)
151        if !active_tools.is_empty() {
152            let names: Vec<_> = active_tools.iter().map(|t: &Arc<dyn Tool>| t.name()).collect();
153            parts.push(format!("You have access to the following tools: {}.", names.join(", ")));
154        }
155
156        parts.push(format!("## Instructions\n{}", body));
157        parts.push("[/skill]".to_string());
158
159        parts.join("\n\n")
160    }
161
162    /// Engineers a lightweight prompt block for Tier 1 injection.
163    pub fn engineer_prompt_block(&self, max_chars: usize) -> String {
164        let mut body = self.body.clone();
165        if body.chars().count() > max_chars {
166            body = body.chars().take(max_chars).collect();
167        }
168        format!("[skill:{}]\n{}\n[/skill]", self.name, body)
169    }
170}
171
172/// A lightweight summary of a skill, excluding the heavy body content.
173#[derive(Debug, Clone, Serialize)]
174pub struct SkillSummary {
175    /// Content-based unique ID.
176    pub id: String,
177    /// Skill name.
178    pub name: String,
179    /// Discovery description.
180    pub description: String,
181    /// Optional version.
182    pub version: Option<String>,
183    /// Optional license.
184    pub license: Option<String>,
185    /// Optional compatibility.
186    pub compatibility: Option<String>,
187    /// Discovery tags.
188    pub tags: Vec<String>,
189    /// Allowed tools.
190    pub allowed_tools: Vec<String>,
191    /// External references.
192    pub references: Vec<String>,
193    /// Trigger status.
194    pub trigger: bool,
195    /// Guided hint.
196    pub hint: Option<String>,
197    /// Extension metadata.
198    pub metadata: std::collections::HashMap<String, serde_json::Value>,
199    /// Associated file path.
200    pub path: PathBuf,
201    /// Content signature.
202    pub hash: String,
203    /// Last modified timestamp.
204    pub last_modified: Option<i64>,
205    /// File glob patterns for activation triggers.
206    pub triggers: Vec<String>,
207}
208
209impl From<&SkillDocument> for SkillSummary {
210    fn from(value: &SkillDocument) -> Self {
211        Self {
212            id: value.id.clone(),
213            name: value.name.clone(),
214            description: value.description.clone(),
215            version: value.version.clone(),
216            license: value.license.clone(),
217            compatibility: value.compatibility.clone(),
218            tags: value.tags.clone(),
219            allowed_tools: value.allowed_tools.clone(),
220            references: value.references.clone(),
221            trigger: value.trigger,
222            hint: value.hint.clone(),
223            metadata: value.metadata.clone(),
224            path: value.path.clone(),
225            hash: value.hash.clone(),
226            last_modified: value.last_modified,
227            triggers: value.triggers.clone(),
228        }
229    }
230}
231
232/// A collection of indexed skills, providing efficient access to metadata and summaries.
233#[derive(Debug, Clone, Default)]
234pub struct SkillIndex {
235    skills: Vec<SkillDocument>,
236}
237
238impl SkillIndex {
239    pub fn new(skills: Vec<SkillDocument>) -> Self {
240        Self { skills }
241    }
242
243    pub fn is_empty(&self) -> bool {
244        self.skills.is_empty()
245    }
246
247    pub fn len(&self) -> usize {
248        self.skills.len()
249    }
250
251    /// Returns the raw list of fully indexed skill documents.
252    pub fn skills(&self) -> &[SkillDocument] {
253        &self.skills
254    }
255
256    /// Returns a list of lightweight skill summaries, suitable for passing to agents or UI components.
257    pub fn summaries(&self) -> Vec<SkillSummary> {
258        self.skills.iter().map(SkillSummary::from).collect()
259    }
260
261    /// Find a skill by its canonical name.
262    pub fn find_by_name(&self, name: &str) -> Option<&SkillDocument> {
263        self.skills.iter().find(|s| s.name == name)
264    }
265
266    /// Find a skill by its unique ID (name + hash).
267    pub fn find_by_id(&self, id: &str) -> Option<&SkillDocument> {
268        self.skills.iter().find(|s| s.id == id)
269    }
270}
271
272/// Criteria used to filter and score skills during selection.
273#[derive(Debug, Clone)]
274pub struct SelectionPolicy {
275    /// Number of top-scoring matches to return.
276    pub top_k: usize,
277    /// Minimum score threshold for a skill to be included.
278    pub min_score: f32,
279    /// Optional list of tags that MUST be present on the skill.
280    pub include_tags: Vec<String>,
281    /// Optional list of tags that MUST NOT be present on the skill.
282    pub exclude_tags: Vec<String>,
283}
284
285impl Default for SelectionPolicy {
286    fn default() -> Self {
287        Self { top_k: 1, min_score: 1.0, include_tags: Vec::new(), exclude_tags: Vec::new() }
288    }
289}
290
291/// A ranked result representing a skill that matched a selection query.
292#[derive(Debug, Clone, Serialize)]
293pub struct SkillMatch {
294    /// Numerical relevance score calculated using weighted lexical overlap.
295    ///
296    /// The algorithm weights matches as follows:
297    /// - **Name Match**: +4.0
298    /// - **Description Match**: +2.5
299    /// - **Tag Match**: +2.0
300    /// - **Instruction Body Match**: +1.0
301    ///
302    /// The final score is normalized by `sqrt(unique_token_count)` of the body to
303    /// ensure long-form instructions do not unfairly drown out concise skills.
304    pub score: f32,
305    /// The lightweight summary of the matched skill.
306    pub skill: SkillSummary,
307}