Skip to main content

graphrt_ffi/
skills.rs

1//! Agent skills (feature `skills`): the `skills` field of `agent` nodes, served
2//! from a store in the app's own storage (config `skills_dir`). An app installs
3//! a skill from its `SKILL.md` text; no code of a skill ever runs.
4//!
5//! The methods exist in every build, so the bindings are the same for every
6//! feature set; without the feature, or without `skills_dir`, they fail with
7//! `GraphrtError.Unsupported`.
8
9use crate::{GraphrtError, Runtime};
10
11/// A tool granted to a skill.
12#[derive(Clone, Debug, PartialEq, Eq, uniffi::Record)]
13pub struct SkillGrant {
14    /// `provider/tool`, or `*` as the tool for every tool of the provider, exactly as the skill asks for it.
15    pub tool: String,
16    /// Calls run without asking; otherwise every call waits for approval.
17    pub allow: bool,
18}
19
20/// What to install.
21#[derive(Clone, Debug, PartialEq, Eq, uniffi::Record)]
22pub struct SkillInstall {
23    /// The whole `SKILL.md` (front matter and instructions).
24    pub skill_md: String,
25    /// Tools to grant; each must be one the skill asks for in `allowed-tools`.
26    #[uniffi(default)]
27    pub grants: Vec<SkillGrant>,
28    /// Replace an installed skill of the same name.
29    #[uniffi(default)]
30    pub replace: bool,
31    /// Install although the scan found something blocking.
32    #[uniffi(default)]
33    pub accept_findings: bool,
34}
35
36/// An installed skill.
37#[derive(Clone, Debug, PartialEq, Eq, uniffi::Record)]
38pub struct SkillInfo {
39    pub name: String,
40    pub description: String,
41    pub title: Option<String>,
42    pub enabled: bool,
43    /// Tools the skill asks for.
44    pub requested_tools: Vec<String>,
45    /// Tools granted to it.
46    pub grants: Vec<SkillGrant>,
47    /// What the scan found, one line each (`severity code: message`).
48    pub findings: Vec<String>,
49    pub version: Option<String>,
50}
51
52#[cfg(feature = "skills")]
53mod imp {
54    use std::sync::Arc;
55
56    use graphrt_skill::{Grant, GrantMode, InstallOptions, OriginKind, SkillEntry, SkillOrigin, SkillStore};
57
58    use super::{SkillGrant, SkillInfo, SkillInstall};
59    use crate::GraphrtError;
60
61    pub(crate) type Store = Arc<SkillStore>;
62
63    fn failed(e: graphrt_skill::Error) -> GraphrtError {
64        GraphrtError::input(e.to_string())
65    }
66
67    /// Open the store and register the service `agent` nodes read skills from.
68    pub(crate) fn install(dir: &str, services: &mut graphrt_core::Services) -> Store {
69        let store = Arc::new(SkillStore::open(dir));
70        services.insert(graphrt_skill::SkillSet::new(Arc::clone(&store)).into_service());
71        store
72    }
73
74    fn info(entry: SkillEntry) -> SkillInfo {
75        SkillInfo {
76            name: entry.name,
77            description: entry.description,
78            title: entry.title,
79            enabled: entry.enabled,
80            requested_tools: entry.requested_tools,
81            grants: entry
82                .grants
83                .into_iter()
84                .map(|g| SkillGrant { tool: g.tool, allow: g.mode == GrantMode::Allow })
85                .collect(),
86            findings: entry
87                .findings
88                .iter()
89                .map(|f| format!("{:?} {}: {}", f.severity, f.code, f.message).to_lowercase())
90                .collect(),
91            version: entry.version,
92        }
93    }
94
95    pub(crate) fn install_skill(store: &SkillStore, request: SkillInstall) -> Result<SkillInfo, GraphrtError> {
96        let package = graphrt_skill::package::package_from_skill_file(&request.skill_md).map_err(failed)?;
97        let grants = request
98            .grants
99            .into_iter()
100            .map(|g| if g.allow { Grant::allow(g.tool) } else { Grant::ask(g.tool) })
101            .collect();
102        let options = InstallOptions {
103            grants,
104            accept_findings: request.accept_findings,
105            replace: request.replace,
106            origin: SkillOrigin {
107                kind: OriginKind::Authored,
108                detail: Some("app".to_owned()),
109                ..SkillOrigin::default()
110            },
111        };
112        store.install_package(&package, options).map(info).map_err(failed)
113    }
114
115    pub(crate) fn list(store: &SkillStore) -> Result<Vec<SkillInfo>, GraphrtError> {
116        Ok(store.list().map_err(failed)?.into_iter().map(info).collect())
117    }
118
119    pub(crate) fn remove(store: &SkillStore, name: &str) -> Result<(), GraphrtError> {
120        store.remove(name).map_err(failed)
121    }
122
123    pub(crate) fn set_enabled(store: &SkillStore, name: &str, enabled: bool) -> Result<SkillInfo, GraphrtError> {
124        store.set_enabled(name, enabled).map(info).map_err(failed)
125    }
126}
127
128#[cfg(feature = "skills")]
129pub(crate) use imp::{Store, install};
130
131#[cfg(not(feature = "skills"))]
132pub(crate) type Store = ();
133
134impl Runtime {
135    #[cfg(feature = "skills")]
136    fn skill_store(&self) -> Result<&Store, GraphrtError> {
137        self.skills.as_ref().ok_or_else(|| GraphrtError::not_configured("skills", "skills_dir"))
138    }
139}
140
141#[uniffi::export]
142impl Runtime {
143    /// Install a skill from its `SKILL.md`. It is enabled once installed.
144    pub fn install_skill(&self, request: SkillInstall) -> Result<SkillInfo, GraphrtError> {
145        #[cfg(feature = "skills")]
146        {
147            imp::install_skill(self.skill_store()?, request)
148        }
149        #[cfg(not(feature = "skills"))]
150        {
151            let _ = request;
152            Err(GraphrtError::unsupported("skills", "skills"))
153        }
154    }
155
156    /// Every installed skill.
157    pub fn list_skills(&self) -> Result<Vec<SkillInfo>, GraphrtError> {
158        #[cfg(feature = "skills")]
159        {
160            imp::list(self.skill_store()?)
161        }
162        #[cfg(not(feature = "skills"))]
163        {
164            Err(GraphrtError::unsupported("skills", "skills"))
165        }
166    }
167
168    /// Turn a skill on or off for every agent.
169    pub fn set_skill_enabled(&self, name: String, enabled: bool) -> Result<SkillInfo, GraphrtError> {
170        #[cfg(feature = "skills")]
171        {
172            imp::set_enabled(self.skill_store()?, &name, enabled)
173        }
174        #[cfg(not(feature = "skills"))]
175        {
176            let _ = (name, enabled);
177            Err(GraphrtError::unsupported("skills", "skills"))
178        }
179    }
180
181    /// Remove an installed skill.
182    pub fn remove_skill(&self, name: String) -> Result<(), GraphrtError> {
183        #[cfg(feature = "skills")]
184        {
185            imp::remove(self.skill_store()?, &name)
186        }
187        #[cfg(not(feature = "skills"))]
188        {
189            let _ = name;
190            Err(GraphrtError::unsupported("skills", "skills"))
191        }
192    }
193}