Skip to main content

systemprompt_models/services/
plugin.rs

1//! Plugin configuration and component-reference model.
2//!
3//! [`PluginConfig`] is the manifest shape loaded from a plugin's config file;
4//! its skill/agent/MCP/content references are [`PluginComponentRef`]s resolved
5//! against the instance ([`ComponentSource`]). [`PluginSummary`] is the
6//! list-view projection; [`PluginConfig::validate`] enforces id and reference
7//! rules.
8//!
9//! Copyright (c) systemprompt.io — Business Source License 1.1.
10//! See <https://systemprompt.io> for licensing details.
11
12use std::fmt;
13
14use schemars::JsonSchema;
15use serde::{Deserialize, Serialize};
16use systemprompt_identifiers::PluginId;
17
18use crate::errors::ConfigValidationError;
19
20const fn default_true() -> bool {
21    true
22}
23
24#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
25#[serde(rename_all = "lowercase")]
26pub enum ComponentSource {
27    Instance,
28    #[default]
29    Explicit,
30}
31
32impl fmt::Display for ComponentSource {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        match self {
35            Self::Instance => write!(f, "instance"),
36            Self::Explicit => write!(f, "explicit"),
37        }
38    }
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
42#[serde(rename_all = "lowercase")]
43pub enum ComponentFilter {
44    Enabled,
45}
46
47impl fmt::Display for ComponentFilter {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        match self {
50            Self::Enabled => write!(f, "enabled"),
51        }
52    }
53}
54
55#[derive(Debug, Clone, Serialize, Deserialize)]
56pub struct PluginConfigFile {
57    pub plugin: PluginConfig,
58}
59
60#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
61pub struct PluginVariableDef {
62    pub name: String,
63    #[serde(default)]
64    pub description: String,
65    #[serde(default = "default_true")]
66    pub required: bool,
67    #[serde(default)]
68    pub secret: bool,
69    #[serde(skip_serializing_if = "Option::is_none")]
70    pub example: Option<String>,
71}
72
73#[derive(Debug, Clone, Serialize, Deserialize)]
74pub struct PluginConfig {
75    pub id: PluginId,
76    pub name: String,
77    pub description: String,
78    pub version: String,
79    #[serde(default = "default_true")]
80    pub enabled: bool,
81    pub author: PluginAuthor,
82    pub keywords: Vec<String>,
83    pub license: String,
84    pub category: String,
85
86    pub skills: PluginComponentRef,
87    pub agents: PluginComponentRef,
88    #[serde(default)]
89    pub mcp_servers: PluginComponentRef,
90    #[serde(default)]
91    pub content_sources: PluginComponentRef,
92    #[serde(default)]
93    pub artifacts: PluginComponentRef,
94    #[serde(default)]
95    pub hooks: PluginHooksRef,
96    #[serde(default)]
97    pub scripts: Vec<PluginScript>,
98}
99
100/// Selects which hooks a plugin materialises into its `hooks/hooks.json`.
101///
102/// Claude Code executes plugin hooks session-globally — a `PreToolUse` hook
103/// with a `*` matcher fires for every tool call regardless of which plugin
104/// contributed the tool. One plugin therefore carries the governance hooks for
105/// the whole instance; every other plugin emits an empty hooks file.
106#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
107#[serde(deny_unknown_fields)]
108pub struct PluginHooksRef {
109    #[serde(default)]
110    pub governance: bool,
111    #[serde(default, skip_serializing_if = "Vec::is_empty")]
112    pub include: Vec<String>,
113}
114
115impl PluginHooksRef {
116    #[must_use]
117    pub const fn is_empty(&self) -> bool {
118        !self.governance && self.include.is_empty()
119    }
120}
121
122#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
123pub struct PluginComponentRef {
124    #[serde(default)]
125    pub source: ComponentSource,
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub filter: Option<ComponentFilter>,
128    #[serde(default, skip_serializing_if = "Vec::is_empty")]
129    pub include: Vec<String>,
130    #[serde(default, skip_serializing_if = "Vec::is_empty")]
131    pub exclude: Vec<String>,
132}
133
134#[derive(Debug, Clone, Serialize, Deserialize)]
135pub struct PluginScript {
136    pub name: String,
137    pub source: String,
138}
139
140#[derive(Debug, Clone, Serialize, Deserialize)]
141pub struct PluginAuthor {
142    pub name: String,
143    pub email: String,
144}
145
146#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
147pub struct PluginSummary {
148    pub id: PluginId,
149    pub name: String,
150    pub display_name: String,
151    pub enabled: bool,
152    pub skill_count: usize,
153    pub agent_count: usize,
154}
155
156impl From<&PluginConfig> for PluginSummary {
157    fn from(config: &PluginConfig) -> Self {
158        Self {
159            id: config.id.clone(),
160            name: config.name.clone(),
161            display_name: config.name.clone(),
162            enabled: config.enabled,
163            skill_count: config.skills.include.len(),
164            agent_count: config.agents.include.len(),
165        }
166    }
167}
168
169impl PluginConfig {
170    pub fn validate(&self, key: &str) -> Result<(), ConfigValidationError> {
171        let id_str = self.id.as_str();
172        if id_str.len() < 3 || id_str.len() > 50 {
173            return Err(ConfigValidationError::invalid_field(format!(
174                "Plugin '{key}': id must be between 3 and 50 characters"
175            )));
176        }
177
178        if !id_str
179            .chars()
180            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
181        {
182            return Err(ConfigValidationError::invalid_field(format!(
183                "Plugin '{key}': id must be lowercase alphanumeric with hyphens only (kebab-case)"
184            )));
185        }
186
187        if self.version.is_empty() {
188            return Err(ConfigValidationError::required(format!(
189                "Plugin '{key}': version must not be empty"
190            )));
191        }
192
193        Self::validate_component_ref(&self.skills, key, "skills")?;
194        Self::validate_component_ref(&self.agents, key, "agents")?;
195        Self::validate_component_ref(&self.artifacts, key, "artifacts")?;
196
197        Ok(())
198    }
199
200    fn validate_component_ref(
201        component: &PluginComponentRef,
202        key: &str,
203        field: &str,
204    ) -> Result<(), ConfigValidationError> {
205        if component.source == ComponentSource::Instance && !component.include.is_empty() {
206            return Err(ConfigValidationError::invalid_field(format!(
207                "Plugin '{key}': {field}.source is 'instance' but {field}.include is set (ignored)"
208            )));
209        }
210
211        Ok(())
212    }
213}