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 rules: PluginComponentRef,
90    #[serde(default)]
91    pub mcp_servers: PluginComponentRef,
92    #[serde(default)]
93    pub content_sources: PluginComponentRef,
94    #[serde(default)]
95    pub artifacts: PluginComponentRef,
96    #[serde(default)]
97    pub hooks: PluginHooksRef,
98    #[serde(default)]
99    pub scripts: Vec<PluginScript>,
100}
101
102/// Selects which hooks a plugin materialises into its `hooks/hooks.json`.
103///
104/// Claude Code executes plugin hooks session-globally — a `PreToolUse` hook
105/// with a `*` matcher fires for every tool call regardless of which plugin
106/// contributed the tool. One plugin therefore carries the governance hooks for
107/// the whole instance; every other plugin emits an empty hooks file.
108///
109/// `comms` is an opt-in on that same owner: when set, the bridge also installs
110/// the `UserPromptSubmit`/`Stop` hooks that drain gateway announcements into
111/// the session. Off by default — a tenant that publishes no announcements has
112/// no reason to run a command on every prompt.
113#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
114#[serde(deny_unknown_fields)]
115pub struct PluginHooksRef {
116    #[serde(default)]
117    pub governance: bool,
118    #[serde(default)]
119    pub comms: bool,
120    #[serde(default, skip_serializing_if = "Vec::is_empty")]
121    pub include: Vec<String>,
122}
123
124impl PluginHooksRef {
125    #[must_use]
126    pub const fn is_empty(&self) -> bool {
127        !self.governance && self.include.is_empty()
128    }
129}
130
131#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
132pub struct PluginComponentRef {
133    #[serde(default)]
134    pub source: ComponentSource,
135    #[serde(default, skip_serializing_if = "Option::is_none")]
136    pub filter: Option<ComponentFilter>,
137    #[serde(default, skip_serializing_if = "Vec::is_empty")]
138    pub include: Vec<String>,
139    #[serde(default, skip_serializing_if = "Vec::is_empty")]
140    pub exclude: Vec<String>,
141}
142
143#[derive(Debug, Clone, Serialize, Deserialize)]
144pub struct PluginScript {
145    pub name: String,
146    pub source: String,
147}
148
149#[derive(Debug, Clone, Serialize, Deserialize)]
150pub struct PluginAuthor {
151    pub name: String,
152    pub email: String,
153}
154
155#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
156pub struct PluginSummary {
157    pub id: PluginId,
158    pub name: String,
159    pub display_name: String,
160    pub enabled: bool,
161    pub skill_count: usize,
162    pub agent_count: usize,
163}
164
165impl From<&PluginConfig> for PluginSummary {
166    fn from(config: &PluginConfig) -> Self {
167        Self {
168            id: config.id.clone(),
169            name: config.name.clone(),
170            display_name: config.name.clone(),
171            enabled: config.enabled,
172            skill_count: config.skills.include.len(),
173            agent_count: config.agents.include.len(),
174        }
175    }
176}
177
178impl PluginConfig {
179    pub fn validate(&self, key: &str) -> Result<(), ConfigValidationError> {
180        let id_str = self.id.as_str();
181        if id_str.len() < 3 || id_str.len() > 50 {
182            return Err(ConfigValidationError::invalid_field(format!(
183                "Plugin '{key}': id must be between 3 and 50 characters"
184            )));
185        }
186
187        if !id_str
188            .chars()
189            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
190        {
191            return Err(ConfigValidationError::invalid_field(format!(
192                "Plugin '{key}': id must be lowercase alphanumeric with hyphens only (kebab-case)"
193            )));
194        }
195
196        if self.version.is_empty() {
197            return Err(ConfigValidationError::required(format!(
198                "Plugin '{key}': version must not be empty"
199            )));
200        }
201
202        Self::validate_component_ref(&self.skills, key, "skills")?;
203        Self::validate_component_ref(&self.agents, key, "agents")?;
204        Self::validate_component_ref(&self.artifacts, key, "artifacts")?;
205        Self::validate_component_ref(&self.rules, key, "rules")?;
206
207        Ok(())
208    }
209
210    fn validate_component_ref(
211        component: &PluginComponentRef,
212        key: &str,
213        field: &str,
214    ) -> Result<(), ConfigValidationError> {
215        if component.source == ComponentSource::Instance && !component.include.is_empty() {
216            return Err(ConfigValidationError::invalid_field(format!(
217                "Plugin '{key}': {field}.source is 'instance' but {field}.include is set (ignored)"
218            )));
219        }
220
221        Ok(())
222    }
223}