Skip to main content

agentmux_srv/server/agent_handlers/
skills.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4
5use std::sync::Arc;
6
7
8use crate::backend::rpc::engine::WshRpcEngine;
9use crate::backend::rpc_types::{
10    COMMAND_LIST_AGENT_SKILLS, COMMAND_CREATE_AGENT_SKILL, COMMAND_UPDATE_AGENT_SKILL,
11    COMMAND_DELETE_AGENT_SKILL,
12    CommandListAgentSkillsData, CommandCreateAgentSkillData, CommandUpdateAgentSkillData,
13    CommandDeleteAgentSkillData,
14};
15use crate::backend::storage::AgentSkill;
16
17use super::super::AppState;
18
19pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
20    let state_list = state.clone();
21    engine.register_typed(COMMAND_LIST_AGENT_SKILLS, move |cmd: CommandListAgentSkillsData, _ctx| {
22        let state = state_list.clone();
23        async move { list_agent_skills(&state, cmd) }
24    });
25
26    let state_create = state.clone();
27    engine.register_typed(COMMAND_CREATE_AGENT_SKILL, move |cmd: CommandCreateAgentSkillData, _ctx| {
28        let state = state_create.clone();
29        async move { create_agent_skill(&state, cmd) }
30    });
31
32    let state_update = state.clone();
33    engine.register_typed(COMMAND_UPDATE_AGENT_SKILL, move |cmd: CommandUpdateAgentSkillData, _ctx| {
34        let state = state_update.clone();
35        async move { update_agent_skill(&state, cmd) }
36    });
37
38    let state_delete = state.clone();
39    engine.register_typed(COMMAND_DELETE_AGENT_SKILL, move |cmd: CommandDeleteAgentSkillData, _ctx| {
40        let state = state_delete.clone();
41        async move { delete_agent_skill(&state, cmd) }
42    });
43}
44
45/// listagentskills → return this agent's EFFECTIVE skills (legacy
46/// db_agent_skills, or its own ref-bound db_skills + globals when any own
47/// refs exist — see Store::effective_skills). Window-scoped (no
48/// `check_s1`) because this is called from
49/// `agent-model.ts`'s pre-launch `launchAgentDefinition`, before any
50/// agent connection exists to authenticate as — that's also exactly why
51/// this must reuse the same merge algorithm as the Rust
52/// `write_agent_config_files` path rather than the frontend calling the
53/// agent-scoped `skill.list` RPC directly (it would fail check_s1 pre-
54/// launch). Previously returned only agent_skill_list (legacy-only),
55/// silently hiding every standalone/Memory → Skills skill from the actual
56/// launch flow (reagent P0 on PR #2322).
57pub(crate) fn list_agent_skills(state: &AppState, cmd: CommandListAgentSkillsData) -> Result<Vec<AgentSkill>, String> {
58    Ok(state.mstore.effective_skills(&state.identity_store, &cmd.agent_id))
59}
60
61/// createagentskill → insert new skill, broadcast agentskills:changed
62pub(crate) fn create_agent_skill(state: &AppState, cmd: CommandCreateAgentSkillData) -> Result<AgentSkill, String> {
63    let now = agentmux_common::time::now_ms();
64    let skill = AgentSkill {
65        id: uuid::Uuid::new_v4().to_string(),
66        agent_id: cmd.agent_id,
67        name: cmd.name,
68        trigger: cmd.trigger,
69        skill_type: cmd.skill_type,
70        description: cmd.description,
71        content: cmd.content,
72        created_at: now,
73    };
74    state.mstore.agent_skill_insert(&skill).map_err(|e| format!("createagentskill: {e}"))?;
75    state.broker.publish_event::<crate::backend::mps_events::AgentSkillsChanged>(&(), vec![], 0);
76    Ok(skill)
77}
78
79/// updateagentskill → update existing skill, broadcast agentskills:changed
80pub(crate) fn update_agent_skill(state: &AppState, cmd: CommandUpdateAgentSkillData) -> Result<AgentSkill, String> {
81    let existing = state
82        .mstore
83        .agent_skill_get(&cmd.id)
84        .map_err(|e| format!("updateagentskill: {e}"))?
85        .ok_or_else(|| format!("updateagentskill: skill {} not found", cmd.id))?;
86    let skill = AgentSkill {
87        id: cmd.id,
88        agent_id: existing.agent_id,
89        name: cmd.name,
90        trigger: cmd.trigger,
91        skill_type: cmd.skill_type,
92        description: cmd.description,
93        content: cmd.content,
94        created_at: existing.created_at,
95    };
96    let found = state.mstore.agent_skill_update(&skill).map_err(|e| format!("updateagentskill: {e}"))?;
97    if !found {
98        return Err(format!("updateagentskill: skill {} not found", skill.id));
99    }
100    state.broker.publish_event::<crate::backend::mps_events::AgentSkillsChanged>(&(), vec![], 0);
101    Ok(skill)
102}
103
104/// deleteagentskill → delete skill by id, broadcast agentskills:changed
105pub(crate) fn delete_agent_skill(state: &AppState, cmd: CommandDeleteAgentSkillData) -> Result<(), String> {
106    state.mstore.agent_skill_delete(&cmd.id).map_err(|e| format!("deleteagentskill: {e}"))?;
107    state.broker.publish_event::<crate::backend::mps_events::AgentSkillsChanged>(&(), vec![], 0);
108    Ok(())
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114    use crate::backend::rpc_types::{
115        CommandCreateAgentSkillData, CommandUpdateAgentSkillData,
116    };
117
118    /// All four skill commands record their request and response types.
119    #[tokio::test]
120    async fn register_typed_records_every_skill_command() {
121        let state = crate::server::tests::test_state();
122        let (engine, _rx) = WshRpcEngine::new();
123        register(&engine, &state);
124        let schema = engine.schema_json();
125        let rows = schema.as_array().unwrap();
126        let find = |cmd: &str| {
127            rows.iter()
128                .find(|r| r["command"] == cmd)
129                .unwrap_or_else(|| panic!("{cmd} missing from the schema"))
130        };
131
132        for (cmd, req, resp) in [
133            (COMMAND_CREATE_AGENT_SKILL, "CommandCreateAgentSkillData", "AgentSkill"),
134            (COMMAND_UPDATE_AGENT_SKILL, "CommandUpdateAgentSkillData", "AgentSkill"),
135            (COMMAND_DELETE_AGENT_SKILL, "CommandDeleteAgentSkillData", "()"),
136        ] {
137            let row = find(cmd);
138            assert_eq!(row["requestName"], req, "{cmd} request");
139            assert_eq!(row["responseName"], resp, "{cmd} response");
140        }
141
142        let list = find(COMMAND_LIST_AGENT_SKILLS);
143        assert_eq!(list["requestName"], "CommandListAgentSkillsData");
144        let list_resp = list["responseName"].as_str().unwrap();
145        assert!(
146            list_resp.starts_with("alloc::vec::Vec<") && list_resp.contains("AgentSkill"),
147            "listagentskills should answer Vec<AgentSkill>, got {list_resp:?}",
148        );
149    }
150
151    /// `skill_type` defaults differently on create and update, and the
152    /// hand-written TS typed both `skill_type?: string`, which hid it.
153    ///
154    /// `createagentskill` fills in "prompt"; `updateagentskill` fills in "".
155    /// Since update is a full replace -- it rebuilds the whole `AgentSkill`
156    /// from the request and keeps only `agent_id`/`created_at` -- a
157    /// create-then-update round trip that omits the field silently blanks a
158    /// value the create had set.
159    ///
160    /// This is documenting existing behaviour rather than changing it: the
161    /// fix is a product decision and `updateagentskill` has no caller today.
162    /// What this test does is make the asymmetry fail loudly if someone
163    /// "tidies" one of the two defaults without meaning to change the other.
164    #[test]
165    fn create_and_update_disagree_about_the_default_skill_type() {
166        let created: CommandCreateAgentSkillData = serde_json::from_value(serde_json::json!({
167            "agent_id": "a1",
168            "name": "review",
169        }))
170        .unwrap();
171        assert_eq!(created.skill_type, "prompt", "createagentskill defaults to prompt");
172
173        let updated: CommandUpdateAgentSkillData = serde_json::from_value(serde_json::json!({
174            "id": "s1",
175            "name": "review",
176        }))
177        .unwrap();
178        assert_eq!(
179            updated.skill_type, "",
180            "updateagentskill defaults to empty -- if this ever becomes \"prompt\", \
181             the two are consistent and the warning on CommandUpdateAgentSkillData \
182             should be removed with it",
183        );
184
185        // The other three content fields agree: both default to empty.
186        for (c, u) in [
187            (created.trigger.as_str(), updated.trigger.as_str()),
188            (created.description.as_str(), updated.description.as_str()),
189            (created.content.as_str(), updated.content.as_str()),
190        ] {
191            assert_eq!(c, "");
192            assert_eq!(u, "");
193        }
194    }
195
196    /// A skill belongs to an agent row, so the row has to exist.
197    fn state_with_agent(id: &str) -> AppState {
198        let state = crate::server::tests::test_state();
199        let mut def = crate::backend::storage::agents::test_agent_def(id, id, "claude", "agent", 1, "");
200        state.mstore.agent_def_insert(&mut def).unwrap();
201        state
202    }
203
204    fn create_req(agent_id: &str, name: &str) -> CommandCreateAgentSkillData {
205        serde_json::from_value(serde_json::json!({ "agent_id": agent_id, "name": name, "content": "do it" })).unwrap()
206    }
207
208    #[tokio::test]
209    async fn a_created_skill_is_stored_and_listed_for_its_agent() {
210        let state = state_with_agent("agent-s1");
211        let skill = create_agent_skill(&state, create_req("agent-s1", "review")).unwrap();
212        assert_eq!((skill.agent_id.as_str(), skill.name.as_str(), skill.skill_type.as_str()), ("agent-s1", "review", "prompt"));
213        assert!(!skill.id.is_empty());
214
215        let listed = list_agent_skills(&state, CommandListAgentSkillsData { agent_id: "agent-s1".into() }).unwrap();
216        assert!(listed.iter().any(|s| s.id == skill.id), "{listed:?}");
217        let other = list_agent_skills(&state, CommandListAgentSkillsData { agent_id: "agent-s2".into() }).unwrap();
218        assert!(!other.iter().any(|s| s.id == skill.id));
219    }
220
221    #[tokio::test]
222    async fn an_update_replaces_the_skill_and_keeps_its_agent_and_creation_time() {
223        let state = state_with_agent("agent-s1");
224        let created = create_agent_skill(&state, create_req("agent-s1", "review")).unwrap();
225        let req: CommandUpdateAgentSkillData =
226            serde_json::from_value(serde_json::json!({ "id": created.id, "name": "renamed", "content": "new" })).unwrap();
227        let updated = update_agent_skill(&state, req).unwrap();
228        assert_eq!((updated.name.as_str(), updated.content.as_str()), ("renamed", "new"));
229        assert_eq!((updated.agent_id.as_str(), updated.created_at), ("agent-s1", created.created_at));
230        assert_eq!(state.mstore.agent_skill_get(&created.id).unwrap().unwrap().name, "renamed");
231    }
232
233    #[tokio::test]
234    async fn updating_a_skill_that_is_not_there_names_the_command_and_the_id() {
235        let state = crate::server::tests::test_state();
236        let req: CommandUpdateAgentSkillData = serde_json::from_value(serde_json::json!({ "id": "nope", "name": "x" })).unwrap();
237        assert_eq!(update_agent_skill(&state, req).unwrap_err(), "updateagentskill: skill nope not found");
238    }
239
240    #[tokio::test]
241    async fn a_deleted_skill_is_gone() {
242        let state = state_with_agent("agent-s1");
243        let created = create_agent_skill(&state, create_req("agent-s1", "review")).unwrap();
244        delete_agent_skill(&state, CommandDeleteAgentSkillData { id: created.id.clone() }).unwrap();
245        assert!(state.mstore.agent_skill_get(&created.id).unwrap().is_none());
246    }
247}