a3s-code-core 3.3.0

A3S Code Core - Embeddable AI agent library with tool execution
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! Skill System
//!
//! Provides a lightweight skill system compatible with Claude Code skill format.
//! Skills are defined in Markdown files with YAML frontmatter.
//!
//! ## Skill Format
//!
//! ```markdown
//! ---
//! name: my-skill
//! description: What the skill does
//! allowed-tools: "read(*), grep(*)"
//! kind: instruction  # or "persona" or "tool"
//! ---
//! # Skill Instructions
//!
//! You are a specialized assistant that...
//! ```
//!
//! ## Skill Kinds
//!
//! - `instruction` (default): Injected into system prompt when matched
//! - `persona`: Session-level system prompt (bound at session creation)
//! - `tool`: Tool-like skill with specialized functionality (treated like instruction)

mod builtin;
mod registry;
pub mod validator;

pub use builtin::builtin_skills;
pub use registry::SkillRegistry;
pub use validator::{
    DefaultSkillValidator, SkillValidationError, SkillValidator, ValidationErrorKind,
};

use serde::{de, Deserialize, Deserializer, Serialize};
use std::collections::HashSet;
use std::path::Path;

/// Skill kind classification
///
/// Determines how the skill is used:
/// - `Instruction`: Prompt/instruction content injected into system prompt
/// - `Persona`: Session-level system prompt (bound at session creation, not injected globally)
/// - `Tool`: Tool-like skill that provides specialized functionality (treated as instruction)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum SkillKind {
    #[default]
    Instruction,
    Persona,
    Tool,
}

/// Tool permission pattern
///
/// Represents a tool permission in Claude Code format:
/// - `Bash(gh issue view:*)` -> tool: "Bash", pattern: "gh issue view:*"
/// - `read(*)` -> tool: "read", pattern: "*"
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ToolPermission {
    pub tool: String,
    pub pattern: String,
}

impl ToolPermission {
    /// Parse a tool permission from Claude Code format
    ///
    /// Examples:
    /// - "Bash(gh issue view:*)" -> ToolPermission { tool: "Bash", pattern: "gh issue view:*" }
    /// - "read(*)" -> ToolPermission { tool: "read", pattern: "*" }
    pub fn parse(s: &str) -> Option<Self> {
        let s = s.trim();

        // Find opening parenthesis
        let open = s.find('(')?;
        let close = s.rfind(')')?;

        if close <= open {
            return None;
        }

        let tool = s[..open].trim().to_string();
        let pattern = s[open + 1..close].trim().to_string();

        Some(ToolPermission { tool, pattern })
    }
}

/// Skill definition (Claude Code compatible)
///
/// Represents a skill loaded from a Markdown file with YAML frontmatter.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Skill {
    /// Skill name (from frontmatter or filename)
    #[serde(default)]
    pub name: String,

    /// Skill description
    #[serde(default)]
    pub description: String,

    /// Allowed tools (Claude Code format: "Bash(pattern:*), read(*)")
    #[serde(
        default,
        rename = "allowed-tools",
        deserialize_with = "deserialize_allowed_tools"
    )]
    pub allowed_tools: Option<String>,

    /// Whether to disable model invocation
    #[serde(default, rename = "disable-model-invocation")]
    pub disable_model_invocation: bool,

    /// Skill kind (instruction or persona)
    #[serde(default)]
    pub kind: SkillKind,

    /// Skill content (markdown instructions)
    #[serde(skip)]
    pub content: String,

    /// Optional tags for categorization
    #[serde(default)]
    pub tags: Vec<String>,

    /// Optional version
    #[serde(default)]
    pub version: Option<String>,
}

impl Skill {
    /// Parse a skill from markdown content
    ///
    /// Expected format:
    /// ```markdown
    /// ---
    /// name: skill-name
    /// description: What it does
    /// allowed-tools: "read(*), grep(*)"
    /// ---
    /// # Instructions
    /// ...
    /// ```
    pub fn parse(content: &str) -> Option<Self> {
        // Parse frontmatter (YAML between --- markers)
        let parts: Vec<&str> = content.splitn(3, "---").collect();

        if parts.len() < 3 {
            return None;
        }

        let frontmatter = parts[1].trim();
        let body = parts[2].trim();

        // Parse YAML frontmatter
        let mut skill: Skill = serde_yaml::from_str(frontmatter).ok()?;
        skill.content = body.to_string();

        Some(skill)
    }

    /// Load a skill from a file
    pub fn from_file(path: impl AsRef<Path>) -> anyhow::Result<Self> {
        let content = std::fs::read_to_string(path.as_ref())?;
        let mut skill =
            Self::parse(&content).ok_or_else(|| anyhow::anyhow!("Failed to parse skill file"))?;

        // Use filename as name if not specified
        if skill.name.is_empty() {
            if let Some(stem) = path.as_ref().file_stem() {
                skill.name = stem.to_string_lossy().to_string();
            }
        }

        Ok(skill)
    }

    /// Parse allowed tools into a set of tool permissions
    ///
    /// Claude Code format: "Bash(gh issue view:*), Bash(gh search:*)"
    /// Returns patterns like: ["Bash:gh issue view:*", "Bash:gh search:*"]
    pub fn parse_allowed_tools(&self) -> HashSet<ToolPermission> {
        let mut permissions = HashSet::new();

        let Some(allowed) = &self.allowed_tools else {
            return permissions;
        };

        // Parse Claude-style comma-separated permissions, plus legacy
        // whitespace-only tool lists such as "Read Write Edit Bash".
        // A single Bash(...) permission may itself contain spaces, so try the
        // canonical single-rule form before falling back to legacy splitting.
        let parts: Vec<&str> = if allowed.contains(',') {
            allowed.split(',').collect()
        } else if ToolPermission::parse(allowed).is_some() {
            vec![allowed.as_str()]
        } else {
            let parts: Vec<&str> = allowed.split_whitespace().collect();
            if parts.len() > 1 {
                tracing::warn!(
                    skill = %self.name,
                    allowed_tools = %allowed,
                    "Legacy whitespace-separated allowed-tools is deprecated; use comma-separated permissions such as Read(*), Write(*), Bash(*) or a YAML list"
                );
            }
            parts
        };
        for part in parts {
            let part = part.trim();
            if part.is_empty() {
                continue;
            }
            if let Some(perm) = ToolPermission::parse(part) {
                permissions.insert(perm);
            } else {
                permissions.insert(ToolPermission {
                    tool: part.to_string(),
                    pattern: "*".to_string(),
                });
            }
        }

        permissions
    }

    /// True when a skill still uses the legacy whitespace-only tool list.
    pub fn uses_legacy_allowed_tools_syntax(&self) -> bool {
        let Some(allowed) = &self.allowed_tools else {
            return false;
        };
        !allowed.contains(',')
            && ToolPermission::parse(allowed).is_none()
            && allowed.split_whitespace().count() > 1
    }

    /// Check if a tool is allowed by this skill
    pub fn is_tool_allowed(&self, tool_name: &str) -> bool {
        let permissions = self.parse_allowed_tools();

        if permissions.is_empty() {
            return false;
        }

        // Check if any permission matches
        permissions
            .iter()
            .any(|perm| perm.tool.eq_ignore_ascii_case(tool_name) && perm.pattern == "*")
    }

    /// Get the skill content formatted for injection into system prompt
    pub fn to_system_prompt(&self) -> String {
        format!(
            "# Skill: {}\n\n{}\n\n{}",
            self.name, self.description, self.content
        )
    }
}

fn deserialize_allowed_tools<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<serde_yaml::Value>::deserialize(deserializer)?;
    match value {
        None | Some(serde_yaml::Value::Null) => Ok(None),
        Some(serde_yaml::Value::String(s)) => Ok(Some(s)),
        Some(serde_yaml::Value::Sequence(items)) => {
            let mut tools = Vec::new();
            for item in items {
                match item {
                    serde_yaml::Value::String(s) => tools.push(s),
                    other => {
                        return Err(de::Error::custom(format!(
                            "allowed-tools list entries must be strings, got {other:?}"
                        )));
                    }
                }
            }
            Ok(Some(tools.join(", ")))
        }
        Some(other) => Err(de::Error::custom(format!(
            "allowed-tools must be a string or a list of strings, got {other:?}"
        ))),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_skill() {
        let content = r#"---
name: test-skill
description: A test skill
allowed-tools: "read(*), grep(*)"
kind: instruction
---
# Instructions

You are a test assistant.
"#;

        let skill = Skill::parse(content).unwrap();
        assert_eq!(skill.name, "test-skill");
        assert_eq!(skill.description, "A test skill");
        assert_eq!(skill.kind, SkillKind::Instruction);
        assert!(skill.content.contains("You are a test assistant"));
    }

    #[test]
    fn test_parse_tool_permission() {
        let perm = ToolPermission::parse("Bash(gh issue view:*)").unwrap();
        assert_eq!(perm.tool, "Bash");
        assert_eq!(perm.pattern, "gh issue view:*");

        let perm = ToolPermission::parse("read(*)").unwrap();
        assert_eq!(perm.tool, "read");
        assert_eq!(perm.pattern, "*");
    }

    #[test]
    fn test_parse_allowed_tools() {
        let skill = Skill {
            name: "test".to_string(),
            description: "test".to_string(),
            allowed_tools: Some("read(*), grep(*), Bash(gh:*)".to_string()),
            disable_model_invocation: false,
            kind: SkillKind::Instruction,
            content: String::new(),
            tags: Vec::new(),
            version: None,
        };

        let permissions = skill.parse_allowed_tools();
        assert_eq!(permissions.len(), 3);
    }

    #[test]
    fn test_parse_legacy_whitespace_allowed_tools() {
        let skill = Skill {
            name: "test".to_string(),
            description: "test".to_string(),
            allowed_tools: Some("Read Write Edit Bash".to_string()),
            disable_model_invocation: false,
            kind: SkillKind::Instruction,
            content: String::new(),
            tags: Vec::new(),
            version: None,
        };

        let permissions = skill.parse_allowed_tools();
        assert_eq!(permissions.len(), 4);
        assert!(skill.uses_legacy_allowed_tools_syntax());
        assert!(permissions
            .iter()
            .any(|perm| perm.tool == "Bash" && perm.pattern == "*"));
    }

    #[test]
    fn test_parse_single_allowed_tool_with_spaces() {
        let skill = Skill {
            name: "test".to_string(),
            description: "test".to_string(),
            allowed_tools: Some("Bash(uv run skills analyze-ci:*)".to_string()),
            disable_model_invocation: false,
            kind: SkillKind::Instruction,
            content: String::new(),
            tags: Vec::new(),
            version: None,
        };

        let permissions = skill.parse_allowed_tools();
        assert_eq!(permissions.len(), 1);
        assert!(permissions
            .iter()
            .any(|perm| { perm.tool == "Bash" && perm.pattern == "uv run skills analyze-ci:*" }));
        assert!(!skill.uses_legacy_allowed_tools_syntax());
    }

    #[test]
    fn test_parse_allowed_tools_yaml_list() {
        let content = r#"---
name: test-skill
description: A test skill
allowed-tools:
  - Read
  - Write
  - Bash(uv run skills analyze-ci:*)
---
# Instructions
"#;

        let skill = Skill::parse(content).unwrap();
        assert_eq!(
            skill.allowed_tools.as_deref(),
            Some("Read, Write, Bash(uv run skills analyze-ci:*)")
        );
        let permissions = skill.parse_allowed_tools();
        assert_eq!(permissions.len(), 3);
        assert!(permissions
            .iter()
            .any(|perm| perm.tool == "Read" && perm.pattern == "*"));
    }

    #[test]
    fn test_is_tool_allowed() {
        let skill = Skill {
            name: "test".to_string(),
            description: "test".to_string(),
            allowed_tools: Some("read(*), grep(*)".to_string()),
            disable_model_invocation: false,
            kind: SkillKind::Instruction,
            content: String::new(),
            tags: Vec::new(),
            version: None,
        };

        assert!(skill.is_tool_allowed("read"));
        assert!(skill.is_tool_allowed("grep"));
        assert!(!skill.is_tool_allowed("write"));
    }

    #[test]
    fn test_omitted_allowed_tools_does_not_allow_tools() {
        let skill = Skill {
            name: "test".to_string(),
            description: "test".to_string(),
            allowed_tools: None,
            disable_model_invocation: false,
            kind: SkillKind::Instruction,
            content: String::new(),
            tags: Vec::new(),
            version: None,
        };

        assert!(!skill.is_tool_allowed("read"));
    }
}