feat(plugins): seam slash-commands contribuées par plugin via callback — #165 (QA verte)

Permet à un plugin de contribuer des commandes slash adossées à une callback,
transitant par le registry/contrat unifié (#162) :

- sdk/IdeaSDK: manifeste contributes.slashCommands (déclaratif) — pointer bumpé.
- domain: source Plugin étendue + effet PluginCallback (la commande ne
  s'exécute pas directement : elle renvoie une référence à la callback du plugin).
- application: registration des commandes plugin dans le registry + exécution
  renvoyant l'effet PluginCallback ; métadonnées UI suffisantes pour l'autocomplete.
- backend + app-tauri: DTO + commandes Tauri listant/invoquant les commandes plugin.
- frontend (contrat): types adapters/domain/ports/mock pour pluginCallback et
  l'invocation avec arguments.

L'exécution effective de la callback côté runtime UI est livrée par #166.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-08-06 15:46:52 +02:00
parent ff7696b724
commit fbaca9d5cc
17 changed files with 514 additions and 34 deletions

View File

@ -11,6 +11,7 @@ use tauri::ipc::Channel;
use tauri::{AppHandle, Emitter, Manager, State, WebviewUrl, WebviewWindowBuilder, WindowEvent};
use crate::dto::DismissEmbedderSuggestionRequestDto;
use application::plugin_slash_commands_from_runtime_catalog;
use application::{
AppError, AssignSkillToAgentInput, AttachLiveAgentInput, ChangeAgentProfileInput,
CloseProjectInput, CreateAgentInput, CreateLayoutInput, CreateMemoryInput, CreateSkillInput,
@ -110,17 +111,27 @@ pub fn health(
/// `list_slash_commands` — list/filter the unified slash-command registry.
#[tauri::command]
pub fn list_slash_commands(
pub async fn list_slash_commands(
request: Option<crate::dto::ListSlashCommandsRequestDto>,
state: State<'_, AppState>,
) -> SlashCommandListDto {
) -> Result<SlashCommandListDto, ErrorDto> {
let request = request.unwrap_or_default();
state
let catalog = state
.list_plugin_runtime_contributions
.execute()
.await
.map_err(ErrorDto::from)?;
let plugin_commands =
plugin_slash_commands_from_runtime_catalog(&catalog).map_err(ErrorDto::from)?;
Ok(state
.list_slash_commands
.execute(ListSlashCommandsInput {
prefix: request.prefix,
})
.into()
.execute_with_plugins(
ListSlashCommandsInput {
prefix: request.prefix,
},
plugin_commands,
)
.into())
}
/// `execute_slash_command` — execute a selected slash command.
@ -129,7 +140,7 @@ pub fn list_slash_commands(
/// Returns an [`ErrorDto`] (`INVALID` for unavailable commands/missing context,
/// `NOT_FOUND` for unknown commands or closed sessions).
#[tauri::command]
pub fn execute_slash_command(
pub async fn execute_slash_command(
request: ExecuteSlashCommandRequestDto,
state: State<'_, AppState>,
) -> Result<ExecuteSlashCommandResponseDto, ErrorDto> {
@ -138,12 +149,23 @@ pub fn execute_slash_command(
.as_deref()
.map(parse_session_id)
.transpose()?;
let catalog = state
.list_plugin_runtime_contributions
.execute()
.await
.map_err(ErrorDto::from)?;
let plugin_commands =
plugin_slash_commands_from_runtime_catalog(&catalog).map_err(ErrorDto::from)?;
let output = state
.execute_slash_command
.execute(ExecuteSlashCommandInput {
name: request.name,
session_id,
})
.execute_with_plugins(
ExecuteSlashCommandInput {
name: request.name,
session_id,
arguments: request.arguments,
},
plugin_commands,
)
.map_err(ErrorDto::from)?;
let effect = match output.effect {
@ -163,6 +185,17 @@ pub fn execute_slash_command(
SlashCommandEffect::ProfileSwitch { session_id } => SlashCommandEffectDto::ProfileSwitch {
session_id: session_id.to_string(),
},
SlashCommandEffect::PluginCallback {
plugin_id,
command_id,
session_id,
arguments,
} => SlashCommandEffectDto::PluginCallback {
plugin_id,
command_id,
session_id: session_id.map(|id| id.to_string()),
arguments,
},
};
Ok(ExecuteSlashCommandResponseDto {

View File

@ -14,7 +14,8 @@ use application::{
LoadLayoutOutput, OpenTerminalInput, SlashCommandEffect,
};
use domain::{
native_slash_commands, Direction, LayoutNode, LayoutTree, LeafCell, NodeId, PreferredView,
native_slash_commands, plugin_slash_command, Direction, LayoutNode, LayoutTree, LeafCell,
NodeId, PreferredView, SlashCommandAvailability,
};
use application::{AppError, HealthInput};
@ -60,9 +61,19 @@ fn health_request_deserialises_camel_case_and_defaults() {
#[test]
fn slash_command_list_dto_serialises_unified_metadata() {
let dto = SlashCommandListDto::from(ListSlashCommandsOutput {
commands: native_slash_commands(),
});
let mut commands = native_slash_commands();
commands.push(
plugin_slash_command(
"dev.acme.plugin",
"dev.acme.plugin.explain",
"/explain",
"Explain selection",
true,
SlashCommandAvailability::Available,
)
.unwrap(),
);
let dto = SlashCommandListDto::from(ListSlashCommandsOutput { commands });
let v = serde_json::to_value(&dto).unwrap();
assert_eq!(v["commands"][0]["name"], "/help");
@ -74,18 +85,32 @@ fn slash_command_list_dto_serialises_unified_metadata() {
);
assert_eq!(v["commands"][1]["name"], "/clean");
assert!(v["commands"][2]["requiresConfirmation"].as_bool().unwrap());
assert_eq!(v["commands"][2]["availability"]["status"], "unavailable");
assert_eq!(v["commands"][2]["availability"]["status"], "available");
assert_eq!(v["commands"][3]["name"], "/explain");
assert_eq!(
v["commands"][3]["source"],
json!({ "plugin": { "pluginId": "dev.acme.plugin" } })
);
assert_eq!(
v["commands"][3]["plugin"]["commandId"],
"dev.acme.plugin.explain"
);
assert!(v.get("requires_confirmation").is_none());
}
#[test]
fn slash_command_execute_request_deserialises_camelcase_session() {
let session_id = Uuid::from_u128(123).to_string();
let dto: ExecuteSlashCommandRequestDto =
serde_json::from_value(json!({ "name": "clean", "sessionId": session_id })).unwrap();
let dto: ExecuteSlashCommandRequestDto = serde_json::from_value(json!({
"name": "clean",
"sessionId": session_id,
"arguments": [{"selection": "abc"}]
}))
.unwrap();
assert_eq!(dto.name, "clean");
assert_eq!(dto.session_id.as_deref(), Some(session_id.as_str()));
assert_eq!(dto.arguments, vec![json!({ "selection": "abc" })]);
}
#[test]
@ -125,6 +150,28 @@ fn slash_command_help_effect_carries_command_metadata() {
assert_eq!(v["commands"][1]["name"], "/clean");
}
#[test]
fn slash_command_plugin_callback_effect_serialises_callback_identity() {
let dto = SlashCommandEffectDto::PluginCallback {
plugin_id: "dev.acme.plugin".to_owned(),
command_id: "dev.acme.plugin.explain".to_owned(),
session_id: Some(Uuid::from_u128(789).to_string()),
arguments: vec![json!({ "selection": "abc" })],
};
let v = serde_json::to_value(&dto).unwrap();
assert_eq!(
v,
json!({
"kind": "pluginCallback",
"pluginId": "dev.acme.plugin",
"commandId": "dev.acme.plugin.explain",
"sessionId": Uuid::from_u128(789).to_string(),
"arguments": [{ "selection": "abc" }]
})
);
}
#[test]
fn error_dto_carries_stable_code_and_message() {
let dto = ErrorDto::from(AppError::NotFound("project".into()));

View File

@ -24,6 +24,7 @@ fn plugin_admin_dto_serialises_exact_contract_shape() {
contribution_summary: PluginContributionSummaryDto {
top_level_menus: 1,
menu_items: 2,
slash_commands: 3,
layouts: 3,
mcp_servers: 4,
},
@ -35,6 +36,7 @@ fn plugin_admin_dto_serialises_exact_contract_shape() {
assert_eq!(value["lifecycleState"], "pending-disable");
assert_eq!(value["trustLevel"], "full");
assert_eq!(value["contributionSummary"]["topLevelMenus"], 1);
assert_eq!(value["contributionSummary"]["slashCommands"], 3);
}
#[test]

View File

@ -196,8 +196,9 @@ pub use skill::{
UpdateSkill, UpdateSkillInput, UpdateSkillOutput,
};
pub use slash_command::{
ExecuteSlashCommand, ExecuteSlashCommandInput, ExecuteSlashCommandOutput, ListSlashCommands,
ListSlashCommandsInput, ListSlashCommandsOutput, SlashCommandEffect, SlashCommandRegistry,
plugin_slash_commands_from_runtime_catalog, ExecuteSlashCommand, ExecuteSlashCommandInput,
ExecuteSlashCommandOutput, ListSlashCommands, ListSlashCommandsInput, ListSlashCommandsOutput,
SlashCommandEffect, SlashCommandRegistry,
};
pub use sprints::{
normalized_reorder, AssignTicketToSprint, AssignTicketToSprintInput,

View File

@ -31,6 +31,8 @@ pub struct PluginContributionSummary {
pub top_level_menus: usize,
/// Menu item count.
pub menu_items: usize,
/// Slash-command count.
pub slash_commands: usize,
/// Layout count.
pub layouts: usize,
/// MCP server count.
@ -42,6 +44,7 @@ impl From<&PluginContributionSet> for PluginContributionSummary {
Self {
top_level_menus: c.menus.len(),
menu_items: c.menu_items.len(),
slash_commands: c.slash_commands.len(),
layouts: c.layouts.len(),
mcp_servers: c.mcp_servers.len(),
}
@ -3088,6 +3091,8 @@ struct RawContributes {
#[serde(default)]
menu_items: Vec<RawMenuItem>,
#[serde(default)]
slash_commands: Vec<RawSlashCommand>,
#[serde(default)]
layouts: Vec<RawLayout>,
#[serde(default)]
mcp_servers: Vec<RawMcpServer>,
@ -3120,6 +3125,18 @@ struct RawMenuItem {
when: Option<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct RawSlashCommand {
name: String,
short_description: String,
command: String,
#[serde(default)]
requires_confirmation: bool,
#[serde(default)]
when: Option<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct RawLayout {
@ -3283,6 +3300,31 @@ fn validate_contributes(raw: RawContributes) -> Result<PluginContributionSet, Pl
})
})
.collect::<Result<Vec<_>, _>>()?;
let slash_commands = raw
.slash_commands
.into_iter()
.map(|s| {
insert(&s.name)?;
if !s.name.starts_with('/') {
return Err(PluginManifestError::Invalid(
"slashCommands[].name must start with '/'".to_owned(),
));
}
if s.short_description.trim().is_empty() {
return Err(PluginManifestError::Invalid(
"slashCommands[].shortDescription is required".to_owned(),
));
}
Ok(domain::PluginSlashCommandContribution {
name: s.name,
short_description: s.short_description,
command: domain::PluginCommandId::new(s.command)
.map_err(|e| PluginManifestError::Invalid(e.to_string()))?,
requires_confirmation: s.requires_confirmation,
when: s.when,
})
})
.collect::<Result<Vec<_>, _>>()?;
let layouts = raw
.layouts
.into_iter()
@ -3353,6 +3395,7 @@ fn validate_contributes(raw: RawContributes) -> Result<PluginContributionSet, Pl
Ok(PluginContributionSet {
menus,
menu_items,
slash_commands,
layouts,
mcp_servers,
})
@ -3423,6 +3466,7 @@ mod tests {
"contributes": {
"menus": [{"id":"dev.acme.menu","label":"Graph","topLevel":true}],
"menuItems": [{"id":"dev.acme.open","targetMenuId":"panels","label":"Open","command":"dev.acme.open"}],
"slashCommands": [{"name":"/graph","shortDescription":"Open graph tools","command":"dev.acme.open","requiresConfirmation":true}],
"layouts": [{"type":"dev.acme.layout","label":"Graph","component":"Graph"}],
"mcpServers": [{"id":"dev.acme.mcp","displayName":"Tools","command":"servers/tool","transport":"stdio","autoStart":true}]
}
@ -3745,6 +3789,9 @@ mod tests {
);
assert_eq!(m.contributes.layouts.len(), 1);
assert_eq!(m.contributes.mcp_servers.len(), 1);
assert_eq!(m.contributes.slash_commands.len(), 1);
assert_eq!(m.contributes.slash_commands[0].name, "/graph");
assert!(m.contributes.slash_commands[0].requires_confirmation);
}
#[test]
@ -3809,6 +3856,21 @@ mod tests {
.is_err());
}
#[test]
fn rejects_slash_command_without_leading_slash() {
let mut value: serde_json::Value = serde_json::from_slice(&valid_manifest()).unwrap();
value["contributes"]["slashCommands"][0]["name"] = serde_json::json!("graph");
assert!(validator()
.validate(
&serde_json::to_vec(&value).unwrap(),
&domain::PluginPackageRef {
plugin_id: None,
root: "x".into()
}
)
.is_err());
}
#[tokio::test]
async fn runtime_catalog_excludes_disabled_and_pending_uninstall_plugins() {
for state in [
@ -3849,6 +3911,7 @@ mod tests {
domain::PluginCapability::Tooling,
]
);
assert_eq!(catalog.plugins[0].contributes.slash_commands.len(), 1);
}
#[tokio::test]

View File

@ -4,11 +4,12 @@
//! commands without changing the frontend-facing list/filter contract.
use domain::{
filter_slash_commands, native_slash_commands, NativeSlashCommand, SessionId, SlashCommand,
SlashCommandAvailability,
filter_slash_commands, native_slash_commands, plugin_slash_command, NativeSlashCommand,
SessionId, SlashCommand, SlashCommandAvailability, SlashCommandSource,
};
use serde_json::Value;
use crate::AppError;
use crate::{AppError, PluginRuntimeCatalog};
/// Lists slash commands.
#[derive(Debug, Clone, Default)]
@ -31,6 +32,8 @@ pub struct ExecuteSlashCommandInput {
pub name: String,
/// Current structured chat session, required by conversation-local commands.
pub session_id: Option<SessionId>,
/// Opaque arguments forwarded to plugin callbacks.
pub arguments: Vec<Value>,
}
/// Execution output: application decides intent; adapters perform transport-only
@ -61,6 +64,17 @@ pub enum SlashCommandEffect {
/// Session whose agent/profile flow is targeted.
session_id: SessionId,
},
/// Dispatch to a plugin-owned callback. The plugin decides what the callback does.
PluginCallback {
/// Plugin id owning the callback.
plugin_id: String,
/// SDK command callback id.
command_id: String,
/// Current structured chat session, when available.
session_id: Option<SessionId>,
/// Opaque arguments supplied by the caller.
arguments: Vec<Value>,
},
}
/// In-memory slash-command registry.
@ -78,6 +92,12 @@ impl SlashCommandRegistry {
}
}
/// Creates a registry with already-projected plugin commands.
#[must_use]
pub fn with_plugin_commands(plugin_commands: Vec<SlashCommand>) -> Self {
Self { plugin_commands }
}
/// Returns all commands from all sources in deterministic order.
#[must_use]
pub fn all(&self) -> Vec<SlashCommand> {
@ -115,6 +135,18 @@ impl SlashCommandRegistry {
)));
}
if let Some(plugin) = command.plugin.clone() {
return Ok(ExecuteSlashCommandOutput {
command,
effect: SlashCommandEffect::PluginCallback {
plugin_id: plugin.plugin_id,
command_id: plugin.command_id,
session_id: input.session_id,
arguments: input.arguments,
},
});
}
let Some(native) = command.native else {
return Err(AppError::Invalid(format!(
"slash command {name} has no executable adapter"
@ -170,6 +202,16 @@ impl ListSlashCommands {
pub fn execute(&self, input: ListSlashCommandsInput) -> ListSlashCommandsOutput {
self.registry.list(input)
}
/// Executes the use case with runtime plugin commands merged into the registry.
#[must_use]
pub fn execute_with_plugins(
&self,
input: ListSlashCommandsInput,
plugin_commands: Vec<SlashCommand>,
) -> ListSlashCommandsOutput {
SlashCommandRegistry::with_plugin_commands(plugin_commands).list(input)
}
}
/// Use case wrapper for execution planning.
@ -192,6 +234,51 @@ impl ExecuteSlashCommand {
) -> Result<ExecuteSlashCommandOutput, AppError> {
self.registry.execute(input)
}
/// Executes the use case with runtime plugin commands merged into the registry.
pub fn execute_with_plugins(
&self,
input: ExecuteSlashCommandInput,
plugin_commands: Vec<SlashCommand>,
) -> Result<ExecuteSlashCommandOutput, AppError> {
SlashCommandRegistry::with_plugin_commands(plugin_commands).execute(input)
}
}
/// Projects active plugin runtime contributions into slash-command metadata.
///
/// The callback is not executed here. Execution returns [`SlashCommandEffect::PluginCallback`]
/// so the host SDK runtime can dispatch the plugin-owned handler.
pub fn plugin_slash_commands_from_runtime_catalog(
catalog: &PluginRuntimeCatalog,
) -> Result<Vec<SlashCommand>, AppError> {
let mut commands = Vec::new();
for plugin in &catalog.plugins {
for slash in &plugin.contributes.slash_commands {
let command = plugin_slash_command(
plugin.id.clone(),
slash.command.as_str().to_owned(),
slash.name.clone(),
slash.short_description.clone(),
slash.requires_confirmation,
if slash.when.as_deref().is_some_and(str::is_empty) {
SlashCommandAvailability::Unavailable {
reason: "Plugin slash command condition is empty".to_owned(),
}
} else {
SlashCommandAvailability::Available
},
)
.map_err(|e| AppError::Invalid(e.to_string()))?;
if !matches!(command.source, SlashCommandSource::Plugin { .. }) {
return Err(AppError::Invalid(
"plugin slash command must use plugin source".to_owned(),
));
}
commands.push(command);
}
}
Ok(commands)
}
#[cfg(test)]
@ -219,6 +306,7 @@ mod tests {
.execute(ExecuteSlashCommandInput {
name: "help".to_owned(),
session_id: None,
arguments: Vec::new(),
})
.unwrap();
assert_eq!(out.command.name, "/help");
@ -235,6 +323,7 @@ mod tests {
.execute(ExecuteSlashCommandInput {
name: "/clean".to_owned(),
session_id: Some(sid),
arguments: Vec::new(),
})
.unwrap();
assert_eq!(
@ -250,6 +339,7 @@ mod tests {
.execute(ExecuteSlashCommandInput {
name: "/profile".to_owned(),
session_id: Some(sid),
arguments: Vec::new(),
})
.unwrap();
assert_eq!(
@ -257,4 +347,85 @@ mod tests {
SlashCommandEffect::ProfileSwitch { session_id: sid }
);
}
#[test]
fn plugin_command_execution_returns_callback_effect() {
let command = plugin_slash_command(
"dev.acme.plugin",
"dev.acme.plugin.explain",
"/explain",
"Explain selection",
false,
SlashCommandAvailability::Available,
)
.unwrap();
let out = ExecuteSlashCommand::new(SlashCommandRegistry::new())
.execute_with_plugins(
ExecuteSlashCommandInput {
name: "/explain".to_owned(),
session_id: Some(session()),
arguments: vec![serde_json::json!({ "selection": "abc" })],
},
vec![command],
)
.unwrap();
let SlashCommandEffect::PluginCallback {
plugin_id,
command_id,
session_id,
arguments,
} = out.effect
else {
panic!("plugin callback effect expected");
};
assert_eq!(plugin_id, "dev.acme.plugin");
assert_eq!(command_id, "dev.acme.plugin.explain");
assert_eq!(session_id, Some(session()));
assert_eq!(arguments, vec![serde_json::json!({ "selection": "abc" })]);
}
#[test]
fn runtime_catalog_plugin_slash_commands_feed_unified_registry() {
let catalog = PluginRuntimeCatalog {
plugins: vec![crate::PluginRuntimePlugin {
id: "dev.acme.plugin".to_owned(),
display_name: "Acme".to_owned(),
publisher: None,
version: "1.0.0".to_owned(),
bundle_url: "idea-plugin://dev.acme.plugin/1.0.0/hash/dist/index.js".to_owned(),
icon_url: None,
content_hash: "abc".to_owned(),
capabilities: vec![domain::PluginCapability::Ui],
activation_scope: domain::PluginActivationScope::App,
contributes: domain::PluginContributionSet {
slash_commands: vec![domain::PluginSlashCommandContribution {
name: "/explain".to_owned(),
short_description: "Explain selection".to_owned(),
command: domain::PluginCommandId::new("dev.acme.plugin.explain").unwrap(),
requires_confirmation: true,
when: None,
}],
..domain::PluginContributionSet::default()
},
}],
};
let commands = plugin_slash_commands_from_runtime_catalog(&catalog).unwrap();
let listed = ListSlashCommands::new(SlashCommandRegistry::new()).execute_with_plugins(
ListSlashCommandsInput {
prefix: Some("exp".to_owned()),
},
commands,
);
assert_eq!(listed.commands.len(), 1);
assert_eq!(listed.commands[0].name, "/explain");
assert_eq!(
listed.commands[0].plugin.as_ref().unwrap().command_id,
"dev.acme.plugin.explain"
);
assert!(listed.commands[0].requires_confirmation);
}
}

View File

@ -38,6 +38,8 @@ pub struct PluginContributionSummaryDto {
pub top_level_menus: usize,
/// Menu items count.
pub menu_items: usize,
/// Slash commands count.
pub slash_commands: usize,
/// Layouts count.
pub layouts: usize,
/// MCP servers count.
@ -49,6 +51,7 @@ impl From<application::PluginContributionSummary> for PluginContributionSummaryD
Self {
top_level_menus: value.top_level_menus,
menu_items: value.menu_items,
slash_commands: value.slash_commands,
layouts: value.layouts,
mcp_servers: value.mcp_servers,
}
@ -803,6 +806,9 @@ pub struct ExecuteSlashCommandRequestDto {
/// conversation-local commands.
#[serde(default)]
pub session_id: Option<String>,
/// Opaque arguments forwarded to plugin callbacks.
#[serde(default)]
pub arguments: Vec<serde_json::Value>,
}
/// Slash-command execution response DTO.
@ -848,6 +854,21 @@ pub enum SlashCommandEffectDto {
#[serde(rename = "sessionId")]
session_id: String,
},
/// Dispatch to a plugin-owned SDK command callback.
PluginCallback {
/// Plugin id owning the callback.
#[serde(rename = "pluginId")]
plugin_id: String,
/// SDK command callback id registered by the plugin.
#[serde(rename = "commandId")]
command_id: String,
/// Current structured chat session, when available.
#[serde(default, rename = "sessionId", skip_serializing_if = "Option::is_none")]
session_id: Option<String>,
/// Opaque arguments supplied by the caller.
#[serde(default)]
arguments: Vec<serde_json::Value>,
},
}
impl From<SlashCommandEffect> for SlashCommandEffectDto {
@ -861,6 +882,17 @@ impl From<SlashCommandEffect> for SlashCommandEffectDto {
SlashCommandEffect::ProfileSwitch { session_id } => Self::ProfileSwitch {
session_id: session_id.to_string(),
},
SlashCommandEffect::PluginCallback {
plugin_id,
command_id,
session_id,
arguments,
} => Self::PluginCallback {
plugin_id,
command_id,
session_id: session_id.map(|id| id.to_string()),
arguments,
},
}
}
}

View File

@ -110,8 +110,8 @@ pub use chat_attachment::{
pub use skill::{Skill, SkillKind, SkillRef, SkillScope};
pub use slash_command::{
filter_slash_commands, native_slash_commands, NativeSlashCommand, SlashCommand,
SlashCommandAvailability, SlashCommandSource,
filter_slash_commands, native_slash_commands, plugin_slash_command, NativeSlashCommand,
PluginSlashCommandCallback, SlashCommand, SlashCommandAvailability, SlashCommandSource,
};
pub use template::{AgentTemplate, TemplateVersion};
@ -234,8 +234,9 @@ pub use plugin::{
PluginInstallSource, PluginLayoutContribution, PluginLayoutType, PluginLifecycleState,
PluginManifest, PluginMcpServerContribution, PluginMcpServerId, PluginMcpServerSpec,
PluginMcpStatus, PluginMcpStatusSet, PluginMenuItemContribution, PluginPackageRef,
PluginRegistry, PluginRegistryEntry, PluginTopLevelMenuContribution, PluginTrustLevel,
PluginVersion, RelativePath, RemovalOutcome, StagedPluginPackage,
PluginRegistry, PluginRegistryEntry, PluginSlashCommandContribution,
PluginTopLevelMenuContribution, PluginTrustLevel, PluginVersion, RelativePath, RemovalOutcome,
StagedPluginPackage,
};
pub use sandbox::{

View File

@ -411,6 +411,24 @@ pub struct PluginMenuItemContribution {
pub when: Option<String>,
}
/// Slash-command contribution backed by a plugin command callback.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginSlashCommandContribution {
/// Slash name, including the leading `/`.
pub name: String,
/// Short autocomplete/help description.
pub short_description: String,
/// Plugin command callback id registered through the SDK command registry.
pub command: PluginCommandId,
/// Whether the host should ask for confirmation before dispatching callback.
#[serde(default)]
pub requires_confirmation: bool,
/// Optional declarative condition reserved for host-side availability.
#[serde(default)]
pub when: Option<String>,
}
/// Layout contribution.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@ -472,6 +490,9 @@ pub struct PluginContributionSet {
/// Menu items.
#[serde(default)]
pub menu_items: Vec<PluginMenuItemContribution>,
/// Slash commands.
#[serde(default)]
pub slash_commands: Vec<PluginSlashCommandContribution>,
/// Layout contributions.
#[serde(default)]
pub layouts: Vec<PluginLayoutContribution>,

View File

@ -17,6 +17,7 @@ pub enum SlashCommandSource {
/// Contributed by a plugin.
Plugin {
/// Opaque plugin id.
#[serde(rename = "pluginId")]
plugin_id: String,
},
}
@ -54,6 +55,16 @@ pub enum NativeSlashCommand {
Profile,
}
/// Plugin callback identity for a contributed slash command.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginSlashCommandCallback {
/// Opaque plugin id.
pub plugin_id: String,
/// SDK command callback id registered by the plugin.
pub command_id: String,
}
/// UI-facing slash-command metadata.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@ -71,6 +82,9 @@ pub struct SlashCommand {
/// Built-in command discriminator when `source == native`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub native: Option<NativeSlashCommand>,
/// Plugin callback identity when `source == plugin`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub plugin: Option<PluginSlashCommandCallback>,
}
impl SlashCommand {
@ -86,6 +100,7 @@ impl SlashCommand {
availability: SlashCommandAvailability,
source: SlashCommandSource,
native: Option<NativeSlashCommand>,
plugin: Option<PluginSlashCommandCallback>,
) -> Result<Self, DomainError> {
let name = name.into();
let short_description = short_description.into();
@ -103,6 +118,7 @@ impl SlashCommand {
availability,
source,
native,
plugin,
})
}
}
@ -118,6 +134,7 @@ pub fn native_slash_commands() -> Vec<SlashCommand> {
SlashCommandAvailability::Available,
SlashCommandSource::Native,
Some(NativeSlashCommand::Help),
None,
)
.expect("valid native slash command"),
SlashCommand::new(
@ -127,6 +144,7 @@ pub fn native_slash_commands() -> Vec<SlashCommand> {
SlashCommandAvailability::Available,
SlashCommandSource::Native,
Some(NativeSlashCommand::Clean),
None,
)
.expect("valid native slash command"),
SlashCommand::new(
@ -136,11 +154,41 @@ pub fn native_slash_commands() -> Vec<SlashCommand> {
SlashCommandAvailability::Available,
SlashCommandSource::Native,
Some(NativeSlashCommand::Profile),
None,
)
.expect("valid native slash command"),
]
}
/// Builds validated metadata for a plugin-contributed slash command.
pub fn plugin_slash_command(
plugin_id: impl Into<String>,
command_id: impl Into<String>,
name: impl Into<String>,
short_description: impl Into<String>,
requires_confirmation: bool,
availability: SlashCommandAvailability,
) -> Result<SlashCommand, DomainError> {
let plugin_id = plugin_id.into();
let command_id = command_id.into();
crate::validation::non_empty(&plugin_id, "slash_command.plugin_id")?;
crate::validation::non_empty(&command_id, "slash_command.command_id")?;
SlashCommand::new(
name,
short_description,
requires_confirmation,
availability,
SlashCommandSource::Plugin {
plugin_id: plugin_id.clone(),
},
None,
Some(PluginSlashCommandCallback {
plugin_id,
command_id,
}),
)
}
/// Filters commands by a user-entered slash prefix.
///
/// Blank prefixes return every command. Prefixes without a leading `/` are
@ -180,6 +228,7 @@ mod tests {
assert!(commands[1].availability.is_available());
assert!(commands[2].availability.is_available());
assert!(commands[2].requires_confirmation);
assert!(commands.iter().all(|c| c.plugin.is_none()));
}
#[test]
@ -196,4 +245,24 @@ mod tests {
.collect::<Vec<_>>();
assert_eq!(names, vec!["/profile"]);
}
#[test]
fn plugin_command_carries_callback_identity() {
let command = plugin_slash_command(
"dev.acme.plugin",
"dev.acme.plugin.explain",
"/explain",
"Explain selection",
true,
SlashCommandAvailability::Available,
)
.unwrap();
assert_eq!(command.name, "/explain");
assert!(command.native.is_none());
assert_eq!(
command.plugin.unwrap().command_id,
"dev.acme.plugin.explain"
);
}
}

View File

@ -165,6 +165,7 @@ async fn installs_sdk_hello_plugin_and_loads_runtime_catalog() {
assert_eq!(result.plugin.display_name, "Hello Plugin");
assert_eq!(result.review.contribution_summary.top_level_menus, 1);
assert_eq!(result.review.contribution_summary.menu_items, 1);
assert_eq!(result.review.contribution_summary.slash_commands, 1);
assert_eq!(result.review.contribution_summary.layouts, 1);
assert!(app_data
.join("plugins/installed/com.example.hello-plugin/dist/index.js")
@ -187,6 +188,11 @@ async fn installs_sdk_hello_plugin_and_loads_runtime_catalog() {
plugin.contributes.menu_items[0].command.as_str(),
"hello-plugin"
);
assert_eq!(plugin.contributes.slash_commands[0].name, "/hello");
assert_eq!(
plugin.contributes.slash_commands[0].command.as_str(),
"hello-plugin"
);
assert_eq!(
plugin.contributes.layouts[0].layout_type.as_str(),
"hello-plugin.hello-world"

View File

@ -248,7 +248,7 @@ describe("TauriAgentGateway invoke payloads", () => {
});
expect(invoke).toHaveBeenCalledWith("execute_slash_command", {
request: { name: "/clean", sessionId: "chat-session-1" },
request: { name: "/clean", sessionId: "chat-session-1", arguments: [] },
});
expect(out.effect.kind).toBe("cleanConversation");
});

View File

@ -286,12 +286,13 @@ export class TauriAgentGateway implements AgentGateway {
async executeSlashCommand(
name: string,
options: { sessionId?: string | null } = {},
options: { sessionId?: string | null; arguments?: unknown[] } = {},
): Promise<ExecuteSlashCommandResult> {
return invoke<ExecuteSlashCommandResult>("execute_slash_command", {
request: {
name,
sessionId: options.sessionId ?? null,
arguments: options.arguments ?? [],
},
});
}

View File

@ -906,7 +906,7 @@ export class MockAgentGateway implements AgentGateway {
async executeSlashCommand(
name: string,
options: { sessionId?: string | null } = {},
options: { sessionId?: string | null; arguments?: unknown[] } = {},
): Promise<ExecuteSlashCommandResult> {
const normalized = name.trim().startsWith("/") ? name.trim() : `/${name.trim()}`;
const command = this.slashCommands.find((item) => item.name === normalized);
@ -951,6 +951,18 @@ export class MockAgentGateway implements AgentGateway {
},
};
}
if (command.plugin) {
return {
command: structuredClone(command),
effect: {
kind: "pluginCallback",
pluginId: command.plugin.pluginId,
commandId: command.plugin.commandId,
sessionId: options.sessionId ?? undefined,
arguments: structuredClone(options.arguments ?? []),
},
};
}
return {
command: structuredClone(command),
effect: {

View File

@ -1698,12 +1698,23 @@ export interface SlashCommand {
availability: SlashCommandAvailability;
source: SlashCommandSource;
native?: NativeSlashCommand;
plugin?: {
pluginId: string;
commandId: string;
};
}
export type SlashCommandEffect =
| { kind: "help"; commands: SlashCommand[] }
| { kind: "cleanConversation"; sessionId: string; clearedChunks: number }
| { kind: "profileSwitch"; sessionId: string };
| { kind: "profileSwitch"; sessionId: string }
| {
kind: "pluginCallback";
pluginId: string;
commandId: string;
sessionId?: string;
arguments: unknown[];
};
export interface ExecuteSlashCommandResult {
command: SlashCommand;
@ -1844,6 +1855,7 @@ export interface PluginUninstallResult {
export interface PluginContributionDto {
menus: PluginTopLevelMenuContribution[];
menuItems: PluginMenuItemContribution[];
slashCommands?: PluginSlashCommandContribution[];
layouts: PluginLayoutContribution[];
mcpServers: PluginMcpServerSummary[];
}
@ -2125,6 +2137,15 @@ export interface PluginMenuItemContribution {
when?: string;
}
/** Manifest declaration of a plugin-backed slash command. */
export interface PluginSlashCommandContribution {
name: string;
shortDescription: string;
command: string;
requiresConfirmation?: boolean;
when?: string;
}
/** A menu item resolved for rendering — enablement already evaluated (carnet §7.2). */
export interface ResolvedPluginMenuItem {
id: string;

View File

@ -315,7 +315,7 @@ export interface AgentGateway {
/** Executes a selected slash command and returns the planned UI effect. */
executeSlashCommand?(
name: string,
options?: { sessionId?: string | null },
options?: { sessionId?: string | null; arguments?: unknown[] },
): Promise<ExecuteSlashCommandResult>;
/** Interrupts only the current turn of a live structured session. */
cancelAgentChat?(sessionId: string): Promise<void>;