Skip to main content

agentmux_srv/server/app_api/
skill.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! MuxAPI handlers for the v1 standalone Skill primitive.
5//! skill.list / skill.get / skill.upsert / skill.delete / skill.bind / skill.unbind
6//!
7//! Plus the Memory-level catalog (skill.catalog.*): global skills only,
8//! window-scoped — no `agent_id`, no `check_s1` (mirrors bundle.* auth
9//! shape, since Memory has no agent connection context to gate on).
10//!
11//! `db_skills` is authoritatively `identity_store` as of Phase 2 of
12//! SPEC_DURABLE_BINDINGS_2026_09_10.md (§5.1/§5.4) — `mstore` stays the
13//! ref-table owner (`db_agent_skills_ref`/`db_bundle_skills_ref` are not
14//! promoted until Phase 3/6). Pure single-table reads/writes (`skill_get`,
15//! `skill_upsert_unique_global`) call directly on `identity_store`; methods
16//! that combine a ref table with the catalog now take `identity_store` as an
17//! explicit `catalog` parameter while still being called ON `mstore` (the
18//! ref-owning receiver).
19
20use super::*;
21use crate::backend::storage::skill_source::SkillSource;
22#[path = "skill_app_rpc.rs"]
23mod app_rpc;
24#[path = "skill_catalog_rpc.rs"]
25mod catalog_rpc;
26use crate::backend::storage::skills::SkillCatalogItem;
27
28pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
29    register_skill_list(engine, state);
30    register_skill_get(engine, state);
31    register_skill_upsert(engine, state);
32    register_skill_delete(engine, state);
33    register_skill_bind(engine, state);
34    register_skill_unbind(engine, state);
35    register_skill_catalog_list(engine, state);
36    register_skill_catalog_upsert(engine, state);
37    register_skill_catalog_delete(engine, state);
38    register_skill_catalog_bind(engine, state);
39    register_skill_catalog_list_for_agent(engine, state);
40    register_skill_catalog_unbind(engine, state);
41    register_skill_catalog_set_reach(engine, state);
42    register_skill_catalog_bind_all(engine, state);
43    register_skill_catalog_import_preview(engine, state);
44    register_skill_catalog_import_commit(engine, state);
45    app_rpc::register(engine, state);
46    catalog_rpc::register(engine, state);
47    register_skill_catalog_set_opt_out(engine, state);
48    register_skill_catalog_bind_to_bundle(engine, state);
49    register_skill_catalog_unbind_from_bundle(engine, state);
50    register_skill_catalog_list_for_bundle(engine, state);
51    register_skill_catalog_upsert_for_bundle(engine, state);
52}
53
54fn register_skill_list(engine: &Arc<WshRpcEngine>, state: &AppState) {
55    let mstore = state.mstore.clone();
56    let identity_store = state.identity_store.clone();
57    engine.register_typed(
58        COMMAND_SKILL_LIST,
59        move |req: SkillAgentScopeData, ctx| {
60            let mstore = mstore.clone();
61            let identity_store = identity_store.clone();
62            async move {
63                check_s1(&mstore, &ctx, &req.agent_id)?;
64                let skills = mstore.skill_list(&identity_store, &req.agent_id)
65                    .map_err(|e| format!("skill.list: {e}"))?;
66                Ok(skills)
67            }
68        },
69    );
70}
71
72fn register_skill_get(engine: &Arc<WshRpcEngine>, state: &AppState) {
73    let mstore = state.mstore.clone();
74    let identity_store = state.identity_store.clone();
75    engine.register_typed(
76        COMMAND_SKILL_GET,
77        move |req: SkillAgentItemData, ctx| {
78            let mstore = mstore.clone();
79            let identity_store = identity_store.clone();
80            async move {
81                check_s1(&mstore, &ctx, &req.agent_id)?;
82                if !mstore.skill_is_accessible_to(&identity_store, &req.agent_id, &req.id)
83                    .map_err(|e| format!("skill.get: {e}"))?
84                {
85                    return Err("FORBIDDEN: skill not accessible to this agent".to_string());
86                }
87                let skill = identity_store.skill_get(&req.id)
88                    .map_err(|e| format!("skill.get: {e}"))?;
89                Ok(skill)
90            }
91        },
92    );
93}
94
95fn register_skill_upsert(engine: &Arc<WshRpcEngine>, state: &AppState) {
96    let mstore = state.mstore.clone();
97    let identity_store = state.identity_store.clone();
98    let broker = state.broker.clone();
99    engine.register_typed(
100        COMMAND_SKILL_UPSERT,
101        move |req: CommandSkillUpsertData, ctx| {
102            let mstore = mstore.clone();
103            let identity_store = identity_store.clone();
104            let broker = broker.clone();
105            async move {
106                check_s1(&mstore, &ctx, &req.agent_id)?;
107
108                let now = now_ms();
109                // created_at is preserved across updates so the response never
110                // reports a timestamp the DB won't persist (ON CONFLICT keeps
111                // the original). For a new row it defaults to `now`.
112                let (id, created_at) = if req.id.is_empty() {
113                    (uuid::Uuid::new_v4().to_string(), now)
114                } else {
115                    if !mstore.skill_is_bound_to(&req.agent_id, &req.id)
116                        .map_err(|e| format!("skill.upsert: {e}"))?
117                    {
118                        return Err("FORBIDDEN: skill not bound to this agent".to_string());
119                    }
120                    let existing = identity_store.skill_get(&req.id)
121                        .map_err(|e| format!("skill.upsert: {e}"))?;
122                    match existing {
123                        Some(s) if s.is_global => {
124                            return Err("FORBIDDEN: cannot mutate a global skill".to_string());
125                        }
126                        Some(s) => (req.id.clone(), s.created_at),
127                        None => (req.id.clone(), now),
128                    }
129                };
130
131                let skill = crate::backend::storage::Skill {
132                    id: id.clone(),
133                    name: req.name,
134                    trigger: req.trigger,
135                    skill_type: req.skill_type,
136                    description: req.description,
137                    content: req.content,
138                    is_global: false,
139                    created_at,
140                    updated_at: now,
141                };
142                // No longer a single transaction across the catalog insert and
143                // the ref-bind (Phase 2 of SPEC_DURABLE_BINDINGS_2026_09_10.md
144                // §5.4, accepted interim gap) — see
145                // `Store::managed_upsert_unique`'s doc comment.
146                mstore.skill_upsert_unique(&identity_store, &req.agent_id, &skill, req.id.is_empty())
147                    .map_err(|e| format!("skill.upsert: {e}"))?;
148                broker.publish_event::<crate::backend::mps_events::SkillsChanged>(&(), vec![], 0);
149                Ok(skill)
150            }
151        },
152    );
153}
154
155fn register_skill_delete(engine: &Arc<WshRpcEngine>, state: &AppState) {
156    let mstore = state.mstore.clone();
157    let identity_store = state.identity_store.clone();
158    let broker = state.broker.clone();
159    engine.register_typed(
160        COMMAND_SKILL_DELETE,
161        move |req: SkillAgentItemData, ctx| {
162            let mstore = mstore.clone();
163            let identity_store = identity_store.clone();
164            let broker = broker.clone();
165            async move {
166                check_s1(&mstore, &ctx, &req.agent_id)?;
167                if !mstore.skill_is_bound_to(&req.agent_id, &req.id)
168                    .map_err(|e| format!("skill.delete: {e}"))?
169                {
170                    return Err("FORBIDDEN: skill not bound to this agent".to_string());
171                }
172                if let Some(existing) = identity_store.skill_get(&req.id)
173                    .map_err(|e| format!("skill.delete: {e}"))?
174                {
175                    if existing.is_global {
176                        return Err("FORBIDDEN: cannot delete a global skill".to_string());
177                    }
178                }
179                let deleted = mstore.skill_delete(&identity_store, &req.id)
180                    .map_err(|e| format!("skill.delete: {e}"))?;
181                if deleted {
182                    broker.publish_event::<crate::backend::mps_events::SkillsChanged>(&(), vec![], 0);
183                }
184                Ok(SkillDeleteResult { deleted })
185            }
186        },
187    );
188}
189
190fn register_skill_bind(engine: &Arc<WshRpcEngine>, state: &AppState) {
191    let mstore = state.mstore.clone();
192    let identity_store = state.identity_store.clone();
193    let broker = state.broker.clone();
194    engine.register_typed(
195        COMMAND_SKILL_BIND,
196        move |req: SkillAgentBindingData, ctx| {
197            let mstore = mstore.clone();
198            let identity_store = identity_store.clone();
199            let broker = broker.clone();
200            async move {
201                check_s1(&mstore, &ctx, &req.agent_id)?;
202                // Only global skills (or ones already bound) may be bound, so an
203                // agent can't bootstrap read access to another agent's private skill.
204                match identity_store.skill_get(&req.skill_id)
205                    .map_err(|e| format!("skill.bind: {e}"))?
206                {
207                    None => return Err("skill.bind: skill not found".to_string()),
208                    Some(s) if !s.is_global => {
209                        if !mstore.skill_is_bound_to(&req.agent_id, &req.skill_id)
210                            .map_err(|e| format!("skill.bind: {e}"))?
211                        {
212                            return Err("FORBIDDEN: can only bind global skills".to_string());
213                        }
214                    }
215                    Some(_) => {}
216                }
217                mstore.skill_bind(&identity_store, &req.agent_id, &req.skill_id)
218                    .map_err(|e| format!("skill.bind: {e}"))?;
219                // An agent binding a skill to itself over its own authenticated
220                // connection should reach an already-open Stash Skills tab for
221                // that agent too — same reactivity as the catalog-tier bind.
222                // reagentx P2 on PR #2329.
223                broker.publish_event::<crate::backend::mps_events::SkillsChanged>(&(), vec![], 0);
224                Ok(SkillBindResult { bound: true })
225            }
226        },
227    );
228}
229
230fn register_skill_unbind(engine: &Arc<WshRpcEngine>, state: &AppState) {
231    let mstore = state.mstore.clone();
232    let broker = state.broker.clone();
233    engine.register_typed(
234        COMMAND_SKILL_UNBIND,
235        move |req: SkillAgentBindingData, ctx| {
236            let mstore = mstore.clone();
237            let broker = broker.clone();
238            async move {
239                check_s1(&mstore, &ctx, &req.agent_id)?;
240                let unbound = mstore.skill_unbind(&req.agent_id, &req.skill_id)
241                    .map_err(|e| format!("skill.unbind: {e}"))?;
242                if unbound {
243                    broker.publish_event::<crate::backend::mps_events::SkillsChanged>(&(), vec![], 0);
244                }
245                Ok(SkillUnbindResult { unbound })
246            }
247        },
248    );
249}
250
251fn register_skill_catalog_list(engine: &Arc<WshRpcEngine>, state: &AppState) {
252    let mstore = state.mstore.clone();
253    let identity_store = state.identity_store.clone();
254    engine.register_typed(
255        COMMAND_SKILL_CATALOG_LIST,
256        move |_req: SkillCatalogListData, _ctx| {
257            let mstore = mstore.clone();
258            let identity_store = identity_store.clone();
259            async move {
260                let skills = mstore.skill_list_global(&identity_store)
261                    .map_err(|e| format!("skill.catalog.list: {e}"))?;
262                Ok(skills)
263            }
264        },
265    );
266}
267
268fn register_skill_catalog_upsert(engine: &Arc<WshRpcEngine>, state: &AppState) {
269    let identity_store = state.identity_store.clone();
270    let broker = state.broker.clone();
271    engine.register_typed(
272        COMMAND_SKILL_CATALOG_UPSERT,
273        move |req: CommandSkillCatalogUpsertData, _ctx| {
274            let identity_store = identity_store.clone();
275            let broker = broker.clone();
276            async move {
277
278                let now = now_ms();
279                let (id, created_at) = if req.id.is_empty() {
280                    (uuid::Uuid::new_v4().to_string(), now)
281                } else {
282                    let existing = identity_store.skill_get(&req.id)
283                        .map_err(|e| format!("skill.catalog.upsert: {e}"))?;
284                    match existing {
285                        // No agent_id/check_s1 here to verify ownership of a private
286                        // skill, so the catalog surface may only create new global
287                        // rows or edit ones that are ALREADY global — never promote
288                        // a private skill into the catalog by supplying its id.
289                        Some(s) if !s.is_global => {
290                            return Err("FORBIDDEN: cannot promote a private skill via the catalog".to_string());
291                        }
292                        Some(s) => (req.id.clone(), s.created_at),
293                        None => (req.id.clone(), now),
294                    }
295                };
296
297                let skill = crate::backend::storage::Skill {
298                    id: id.clone(),
299                    name: req.name,
300                    trigger: req.trigger,
301                    skill_type: req.skill_type,
302                    description: req.description,
303                    content: req.content,
304                    is_global: true,
305                    created_at,
306                    updated_at: now,
307                };
308                // Global-scoped uniqueness (not skill_upsert_unique's
309                // per-agent check) — same defense-in-depth as the mcp.catalog
310                // fix, reagent P1 on #1948. Pure single-table op — called
311                // directly on identity_store.
312                let is_new = created_at == now;
313                identity_store.skill_upsert_unique_global(&skill)
314                    .map_err(|e| format!("skill.catalog.upsert: {e}"))?;
315                // A new catalog skill reaches the agents created after it, unless switched off
316                // (the operator's default: new agents get the global skills, with a per-skill opt-out).
317                if is_new {
318                    identity_store
319                        .skill_reach_default_for_new(&id, now)
320                        .map_err(|e| format!("skill.catalog.upsert: {e}"))?;
321                }
322                broker.publish_event::<crate::backend::mps_events::SkillsChanged>(&(), vec![], 0);
323                Ok(skill)
324            }
325        },
326    );
327}
328
329// Catalog-tier sibling of register_skill_bind (above) — same DB write and
330// "only global skills may be bound" safety check, but no check_s1: the
331// Memory's WebSocket never authenticates as an agent (see this file's
332// module doc comment), so a check_s1-gated bind can never be satisfied from
333// that caller. skill.bind itself is left untouched — it may still be the
334// intended surface for an agent binding a skill to itself over its own
335// authenticated connection, and loosening its gate would silently widen
336// what any authenticated agent connection can do (bind arbitrary skills to
337// *other* agent ids), which nobody asked for.
338// See docs/reports/REPORT_ARMORY_SKILLS_MARKDOWN_AND_BIND_BUG_2026_07_27.md §2.4.
339fn register_skill_catalog_bind(engine: &Arc<WshRpcEngine>, state: &AppState) {
340    let mstore = state.mstore.clone();
341    let identity_store = state.identity_store.clone();
342    let broker = state.broker.clone();
343    engine.register_typed(
344        COMMAND_SKILL_CATALOG_BIND,
345        move |req: SkillAgentBindingData, _ctx| {
346            let mstore = mstore.clone();
347            let identity_store = identity_store.clone();
348            let broker = broker.clone();
349            async move {
350                // Only global skills (or ones already bound) may be bound, so the
351                // catalog surface can't be used to bootstrap read access to
352                // another agent's private skill — same rule as skill.bind.
353                match identity_store.skill_get(&req.skill_id)
354                    .map_err(|e| format!("skill.catalog.bind: {e}"))?
355                {
356                    None => return Err("skill.catalog.bind: skill not found".to_string()),
357                    Some(s) if !s.is_global => {
358                        if !mstore.skill_is_bound_to(&req.agent_id, &req.skill_id)
359                            .map_err(|e| format!("skill.catalog.bind: {e}"))?
360                        {
361                            return Err("FORBIDDEN: can only bind global skills".to_string());
362                        }
363                    }
364                    Some(_) => {}
365                }
366                mstore.skill_bind(&identity_store, &req.agent_id, &req.skill_id)
367                    .map_err(|e| format!("skill.catalog.bind: {e}"))?;
368                // Lets any other open Stash/Memory view for this agent pick up
369                // the new binding without a manual refresh — skill.bind (the
370                // check_s1 agent-self-service path) intentionally left alone.
371                broker.publish_event::<crate::backend::mps_events::SkillsChanged>(&(), vec![], 0);
372                Ok(SkillBindResult { bound: true })
373            }
374        },
375    );
376}
377
378/// Catalog-tier sibling of `skill.list` (above) — GLOBAL SKILLS ONLY, each
379/// annotated with `bound_to_agent` for the caller-supplied `agent_id`, no
380/// `check_s1`. AgentStashModal's Skills tab (the per-agent Stash view) runs
381/// over the dashboard's connection, which is never agent-authenticated, so
382/// `skill.list`'s gate can never be satisfied from that caller — the exact
383/// same reasoning as `skill.catalog.bind` above. Deliberately does NOT
384/// reuse `skill.list`'s full computation (global + this agent's own
385/// private skills): with no `check_s1`, `agent_id` is unverified, and a
386/// private skill's `content`/`description`/`trigger` can carry sensitive
387/// agent-authored material — returning it for an arbitrary caller-chosen
388/// `agent_id` would be an IDOR into every agent's private skills. See
389/// `Store::skill_list_global_for_agent`'s doc comment and
390/// docs/reports/REPORT_ARMORY_ARCHITECTURE_AND_NAMING_REVIEW_2026_07_23.md §2.2.
391fn register_skill_catalog_list_for_agent(engine: &Arc<WshRpcEngine>, state: &AppState) {
392    let mstore = state.mstore.clone();
393    let identity_store = state.identity_store.clone();
394    engine.register_typed(
395        COMMAND_SKILL_CATALOG_LIST_FOR_AGENT,
396        move |req: SkillAgentScopeData, _ctx| {
397            let mstore = mstore.clone();
398            let identity_store = identity_store.clone();
399            async move {
400                let skills = mstore.skill_list_global_for_agent(&identity_store, &req.agent_id)
401                    .map_err(|e| format!("skill.catalog.list_for_agent: {e}"))?;
402                Ok(skills)
403            }
404        },
405    );
406}
407
408/// `skill.catalog.set_reach`: a global skill reaches every agent, the agents created from now on, or
409/// only the agents it is bound to.
410/// The switch lives in the identity store beside the catalog (`db_skill_reach`), so it survives an
411/// upgrade, like an MCP server's (`mcp.catalog.set_reach`).
412fn register_skill_catalog_set_reach(engine: &Arc<WshRpcEngine>, state: &AppState) {
413    let identity_store = state.identity_store.clone();
414    let broker = state.broker.clone();
415    engine.register_typed(
416        COMMAND_SKILL_CATALOG_SET_REACH,
417        move |req: CommandSkillCatalogSetReachData, _ctx| {
418            let identity_store = identity_store.clone();
419            let broker = broker.clone();
420            async move {
421                match identity_store.skill_get(&req.skill_id).map_err(|e| format!("skill.catalog.set_reach: {e}"))? {
422                    Some(s) if s.is_global => {}
423                    Some(_) => return Err("FORBIDDEN: a private skill has no catalog reach".to_string()),
424                    None => return Err(format!("skill.catalog.set_reach: no skill {}", req.skill_id)),
425                }
426                identity_store
427                    .skill_set_reach(&req.skill_id, req.all_agents, req.new_agents, now_ms())
428                    .map_err(|e| format!("skill.catalog.set_reach: {e}"))?;
429                broker.publish_event::<crate::backend::mps_events::SkillsChanged>(&(), vec![], 0);
430                Ok(SkillBindResult { bound: req.all_agents || req.new_agents })
431            }
432        },
433    );
434}
435
436/// `skill.catalog.bind_all`: a bind of one global skill to every agent that exists now. The agents
437/// are this channel's own definitions (not the seeded templates), the same ones the per-agent bind
438/// accepts.
439fn register_skill_catalog_bind_all(engine: &Arc<WshRpcEngine>, state: &AppState) {
440    let mstore = state.mstore.clone();
441    let identity_store = state.identity_store.clone();
442    let broker = state.broker.clone();
443    engine.register_typed(
444        COMMAND_SKILL_CATALOG_BIND_ALL,
445        move |req: CommandSkillCatalogBindAllData, _ctx| {
446            let mstore = mstore.clone();
447            let identity_store = identity_store.clone();
448            let broker = broker.clone();
449            async move {
450                match identity_store.skill_get(&req.skill_id).map_err(|e| format!("skill.catalog.bind_all: {e}"))? {
451                    Some(s) if s.is_global => {}
452                    Some(_) => return Err("FORBIDDEN: can only bind global skills".to_string()),
453                    None => return Err("skill.catalog.bind_all: skill not found".to_string()),
454                }
455                let mut bound: u64 = 0;
456                for agent in mstore.agent_def_list().map_err(|e| format!("skill.catalog.bind_all: {e}"))? {
457                    if agent.is_seeded == 1 {
458                        continue;
459                    }
460                    // A definition of another channel is not in this one's registry and refuses a bind: skipped.
461                    match mstore.skill_bind(&identity_store, &agent.id, &req.skill_id) {
462                        Ok(()) => bound += 1,
463                        Err(e) => tracing::debug!(agent_id = %agent.id, error = %e, "skill.catalog.bind_all: skipped an agent"),
464                    }
465                }
466                broker.publish_event::<crate::backend::mps_events::SkillsChanged>(&(), vec![], 0);
467                Ok(SkillBindAllResult { bound })
468            }
469        },
470    );
471}
472
473/// Catalog-tier sibling of `skill.unbind` (above) — same DB write, no
474/// `check_s1`. Restricted to global rows only, matching the guard
475/// `register_skill_catalog_bind`/`register_skill_catalog_delete` already
476/// apply in this file: any window connection can sever any agent's binding
477/// to a *global* skill (an intentional, pre-existing trust boundary — bind
478/// and delete already have the same or larger blast radius), but a private
479/// row's own binding must not be touchable via this no-`check_s1` surface,
480/// even though `skill_id` is never exposed by any no-`check_s1` command
481/// today — defense in depth over relying solely on UUID secrecy.
482/// reagentx P1 on PR #2329 (round 2).
483fn register_skill_catalog_unbind(engine: &Arc<WshRpcEngine>, state: &AppState) {
484    let mstore = state.mstore.clone();
485    let identity_store = state.identity_store.clone();
486    let broker = state.broker.clone();
487    engine.register_typed(
488        COMMAND_SKILL_CATALOG_UNBIND,
489        move |req: SkillAgentBindingData, _ctx| {
490            let mstore = mstore.clone();
491            let identity_store = identity_store.clone();
492            let broker = broker.clone();
493            async move {
494                match identity_store.skill_get(&req.skill_id)
495                    .map_err(|e| format!("skill.catalog.unbind: {e}"))?
496                {
497                    None => return Err("skill.catalog.unbind: skill not found".to_string()),
498                    Some(s) if !s.is_global => {
499                        return Err("FORBIDDEN: can only unbind global skills".to_string());
500                    }
501                    Some(_) => {}
502                }
503                let unbound = mstore.skill_unbind(&req.agent_id, &req.skill_id)
504                    .map_err(|e| format!("skill.catalog.unbind: {e}"))?;
505                if unbound {
506                    broker.publish_event::<crate::backend::mps_events::SkillsChanged>(&(), vec![], 0);
507                }
508                Ok(SkillUnbindResult { unbound })
509            }
510        },
511    );
512}
513
514// Bundle-scoped sibling of register_skill_catalog_bind (above) — same DB
515// write and "only global skills may be bound" safety check, keyed by
516// bundle_id via bundle_skill_bind instead of agent_id/skill_bind.
517// Composable model v2, docs/specs/SPEC_BUNDLE_AS_CONTAINER_V2_2026_08_17.md
518// (GH issue #2024 item 3).
519fn register_skill_catalog_bind_to_bundle(engine: &Arc<WshRpcEngine>, state: &AppState) {
520    let mstore = state.mstore.clone();
521    let id_store = state.id_store.clone();
522    let identity_store = state.identity_store.clone();
523    let broker = state.broker.clone();
524    engine.register_typed(
525        COMMAND_SKILL_CATALOG_BIND_TO_BUNDLE,
526        move |req: SkillBundleBindingData, _ctx| {
527            let mstore = mstore.clone();
528            let id_store = id_store.clone();
529            let identity_store = identity_store.clone();
530            let broker = broker.clone();
531            async move {
532                // Only global skills (or ones already bound) may be bound, so
533                // this surface can't be used to bootstrap read access to
534                // another entity's private skill — same rule as
535                // skill.catalog.bind.
536                match identity_store.skill_get(&req.skill_id)
537                    .map_err(|e| format!("skill.catalog.bind_to_bundle: {e}"))?
538                {
539                    None => return Err("skill.catalog.bind_to_bundle: skill not found".to_string()),
540                    Some(s) if !s.is_global => {
541                        if !mstore.bundle_skill_is_accessible_to(&identity_store, &req.bundle_id, &req.skill_id)
542                            .map_err(|e| format!("skill.catalog.bind_to_bundle: {e}"))?
543                        {
544                            return Err("FORBIDDEN: can only bind global skills to a bundle".to_string());
545                        }
546                    }
547                    Some(_) => {}
548                }
549                mstore.bundle_skill_bind(&identity_store, &id_store, &req.bundle_id, &req.skill_id)
550                    .map_err(|e| format!("skill.catalog.bind_to_bundle: {e}"))?;
551                broker.publish_event::<crate::backend::mps_events::SkillsChanged>(&(), vec![], 0);
552                Ok(SkillBindResult { bound: true })
553            }
554        },
555    );
556}
557
558/// Bundle-scoped sibling of `skill.list` — GLOBAL SKILLS ONLY plus this
559/// bundle's own referenced skills, each annotated with `bound_to_bundle`.
560/// No `check_s1` (a bundle has no agent identity to gate on). Deliberately
561/// restricted to global + bundle-bound rows only, same IDOR reasoning as
562/// `skill_list_global_for_agent`'s doc comment — see `bundle_skill_list`'s
563/// own implementation.
564fn register_skill_catalog_list_for_bundle(engine: &Arc<WshRpcEngine>, state: &AppState) {
565    let mstore = state.mstore.clone();
566    let identity_store = state.identity_store.clone();
567    engine.register_typed(
568        COMMAND_SKILL_CATALOG_LIST_FOR_BUNDLE,
569        move |req: SkillBundleScopeData, _ctx| {
570            let mstore = mstore.clone();
571            let identity_store = identity_store.clone();
572            async move {
573                let skills = mstore.bundle_skill_list(&identity_store, &req.bundle_id)
574                    .map_err(|e| format!("skill.catalog.list_for_bundle: {e}"))?;
575                Ok(skills)
576            }
577        },
578    );
579}
580
581/// Creates a NEW, PRIVATE skill scoped directly to a bundle (never global)
582/// — the bundle-level analog of `skill.upsert` (agent-scoped). See
583/// `mcp.rs`'s `register_mcp_catalog_upsert_for_bundle` for the full
584/// reasoning (reagentx P1 review on PR #2639).
585fn register_skill_catalog_upsert_for_bundle(engine: &Arc<WshRpcEngine>, state: &AppState) {
586    let mstore = state.mstore.clone();
587    let id_store = state.id_store.clone();
588    let identity_store = state.identity_store.clone();
589    let broker = state.broker.clone();
590    engine.register_typed(
591        COMMAND_SKILL_CATALOG_UPSERT_FOR_BUNDLE,
592        move |req: CommandSkillCatalogUpsertForBundleData, _ctx| {
593            let mstore = mstore.clone();
594            let id_store = id_store.clone();
595            let identity_store = identity_store.clone();
596            let broker = broker.clone();
597            async move {
598
599                let now = now_ms();
600                let (id, created_at) = if req.id.is_empty() {
601                    (uuid::Uuid::new_v4().to_string(), now)
602                } else {
603                    if !mstore.bundle_skill_is_bound_to(&req.bundle_id, &req.id)
604                        .map_err(|e| format!("skill.catalog.upsert_for_bundle: {e}"))?
605                    {
606                        return Err("FORBIDDEN: skill not bound to this bundle".to_string());
607                    }
608                    let existing = identity_store.skill_get(&req.id)
609                        .map_err(|e| format!("skill.catalog.upsert_for_bundle: {e}"))?;
610                    match existing {
611                        Some(s) if s.is_global => {
612                            return Err("FORBIDDEN: cannot mutate a global skill".to_string());
613                        }
614                        Some(s) => (req.id.clone(), s.created_at),
615                        None => (req.id.clone(), now),
616                    }
617                };
618
619                let skill = crate::backend::storage::Skill {
620                    id: id.clone(),
621                    name: req.name,
622                    trigger: req.trigger,
623                    skill_type: req.skill_type,
624                    description: req.description,
625                    content: req.content,
626                    is_global: false,
627                    created_at,
628                    updated_at: now,
629                };
630                mstore.bundle_skill_upsert_unique(&identity_store, &id_store, &req.bundle_id, &skill, req.id.is_empty())
631                    .map_err(|e| format!("skill.catalog.upsert_for_bundle: {e}"))?;
632                broker.publish_event::<crate::backend::mps_events::SkillsChanged>(&(), vec![], 0);
633                Ok(skill)
634            }
635        },
636    );
637}
638
639// Bundle-scoped sibling of register_skill_catalog_unbind (above). See
640// mcp.rs's register_mcp_catalog_unbind_from_bundle for why this does NOT
641// restrict to global-only, unlike its agent-level sibling.
642fn register_skill_catalog_unbind_from_bundle(engine: &Arc<WshRpcEngine>, state: &AppState) {
643    let mstore = state.mstore.clone();
644    let broker = state.broker.clone();
645    engine.register_typed(
646        COMMAND_SKILL_CATALOG_UNBIND_FROM_BUNDLE,
647        move |req: SkillBundleBindingData, _ctx| {
648            let mstore = mstore.clone();
649            let broker = broker.clone();
650            async move {
651                let unbound = mstore.bundle_skill_unbind(&req.bundle_id, &req.skill_id)
652                    .map_err(|e| format!("skill.catalog.unbind_from_bundle: {e}"))?;
653                if unbound {
654                    broker.publish_event::<crate::backend::mps_events::SkillsChanged>(&(), vec![], 0);
655                }
656                Ok(SkillUnbindResult { unbound })
657            }
658        },
659    );
660}
661
662fn register_skill_catalog_delete(engine: &Arc<WshRpcEngine>, state: &AppState) {
663    let mstore = state.mstore.clone();
664    let identity_store = state.identity_store.clone();
665    let broker = state.broker.clone();
666    engine.register_typed(
667        COMMAND_SKILL_CATALOG_DELETE,
668        move |req: SkillCatalogItemData, _ctx| {
669            let mstore = mstore.clone();
670            let identity_store = identity_store.clone();
671            let broker = broker.clone();
672            async move {
673                if let Some(existing) = identity_store.skill_get(&req.id)
674                    .map_err(|e| format!("skill.catalog.delete: {e}"))?
675                {
676                    if !existing.is_global {
677                        return Err("FORBIDDEN: cannot delete a private skill via the catalog".to_string());
678                    }
679                }
680                let deleted = mstore.skill_delete(&identity_store, &req.id)
681                    .map_err(|e| format!("skill.catalog.delete: {e}"))?;
682                if deleted {
683                    broker.publish_event::<crate::backend::mps_events::SkillsChanged>(&(), vec![], 0);
684                }
685                Ok(SkillDeleteResult { deleted })
686            }
687        },
688    );
689}
690
691
692/// What a source holds: a folder, a git repository (https) or one SKILL.md at an https URL.
693async fn read_skill_source(src: &SkillSource) -> Result<crate::backend::skill_import::Scan, String> {
694    use crate::backend::skill_import as imp;
695    match src.kind.as_str() {
696        "folder" => imp::scan_dir(&crate::backend::base::expand_home_dir_safe(src.location.trim())),
697        "file" => {
698            let path = crate::backend::base::expand_home_dir_safe(src.location.trim());
699            tokio::task::spawn_blocking(move || {
700                let scratch = tempfile::tempdir().map_err(|e| e.to_string())?;
701                crate::backend::skill_file::extract(&path, scratch.path())?;
702                imp::scan_dir(scratch.path())
703            })
704            .await
705            .map_err(|e| e.to_string())?
706        }
707        "git" => imp::fetch_git(&src.location, &src.git_ref).await,
708        "url" => imp::fetch_url(&src.location).await,
709        other => Err(format!("unknown source kind '{other}' (use folder, file, git or url)")),
710    }
711}
712
713// What the preview says about a computer-use skill's bundle: its files, its scripts and who signed it.
714// A bundle the signature check refuses is still shown, with the reason added to the warnings.
715fn preview_app(
716    catalog: &crate::backend::storage::store::Store,
717    b: &crate::backend::computer_use_skill::Bundle,
718    name: &str,
719    warnings: &mut Vec<String>,
720) -> crate::backend::storage::skill_app::SkillApp {
721    crate::backend::computer_use_skill::stash(b);
722    let signer = match crate::backend::computer_use_skill::check_signature(catalog, b) {
723        Ok(k) => k,
724        Err(e) => {
725            warnings.push(format!("{name}: {e}"));
726            None
727        }
728    };
729    let pins = catalog.skill_publisher_pins().unwrap_or_default();
730    crate::backend::storage::skill_app::SkillApp {
731        info: b.info.clone(),
732        scripts: crate::backend::computer_use_skill::script_infos(&b.manifest_json),
733        signature: crate::backend::widget::signature::describe(&format!("{}.{}", b.info.publisher, b.info.id), signer.as_deref(), &pins),
734        files: b
735            .files
736            .iter()
737            .map(|f| crate::backend::storage::skill_app::SkillFileInfo {
738                path: f.path.clone(),
739                sha256: String::new(),
740                bytes: f.image.as_ref().map_or(f.content.len(), Vec::len) as u64,
741                script: f.script,
742                approved: false,
743                image: f.image.is_some(),
744            })
745            .collect(),
746        verified: b.verified.clone(),
747        content_hash: b.content_hash.clone(),
748        from_catalog: false,
749    }
750}
751
752// Read a source and compare each skill in it with the catalog. Writes nothing: the person reads
753// the whole text (and the diff for a skill that already exists) before `import_commit`.
754fn register_skill_catalog_import_preview(engine: &Arc<WshRpcEngine>, state: &AppState) {
755    let mstore = state.mstore.clone();
756    let identity_store = state.identity_store.clone();
757    engine.register_typed(
758        COMMAND_SKILL_CATALOG_IMPORT_PREVIEW,
759        move |req: CommandSkillCatalogImportPreviewData, _ctx| {
760            let mstore = mstore.clone();
761            let identity_store = identity_store.clone();
762            async move {
763                const E: &str = "skill.catalog.import_preview";
764                // An update names a skill; its recorded source says where to read.
765                let (source, only_key) = match (&req.source, req.skill_id.is_empty()) {
766                    (_, false) => {
767                        let src = identity_store
768                            .skill_source_get(&req.skill_id)
769                            .map_err(|e| format!("{E}: {e}"))?
770                            .ok_or_else(|| format!("{E}: this skill was not imported from a source, so there is nothing to check"))?;
771                        let key = src.item_key.clone();
772                        (src, Some(key))
773                    }
774                    (Some(src), true) => (src.clone(), None),
775                    (None, true) => return Err(format!("{E}: give a source or a skill_id")),
776                };
777                let scan = read_skill_source(&source).await.map_err(|e| format!("{E}: {e}"))?;
778                let catalog = mstore.skill_list_global(&identity_store).map_err(|e| format!("{E}: {e}"))?;
779                let mut warnings = scan.warnings;
780                let mut items = Vec::new();
781                for c in scan.candidates {
782                    if only_key.as_deref().is_some_and(|k| k != c.key) {
783                        continue;
784                    }
785                    let existing = if !req.skill_id.is_empty() {
786                        catalog.iter().find(|i| i.skill.id == req.skill_id)
787                    } else {
788                        let from_here = |i: &&SkillCatalogItem| {
789                            i.source.as_ref().is_some_and(|s| s.kind == source.kind && s.location == source.location && s.item_key == c.key)
790                        };
791                        catalog.iter().find(from_here).or_else(|| catalog.iter().find(|i| i.skill.name == c.name))
792                    };
793                    // A computer-use skill is also changed when its files, manifest or version are, not only its text.
794                    let same_app = match (&c.app, existing.and_then(|e| e.app.as_ref())) {
795                        (None, None) => true,
796                        (Some(b), Some(old)) => b.content_hash == old.content_hash,
797                        _ => false,
798                    };
799                    let (status, e) = match existing {
800                        None => ("new", None),
801                        Some(e) if same_app && e.skill.description == c.description && e.skill.content == c.content && e.skill.name == c.name => ("same", Some(e)),
802                        Some(e) => ("changed", Some(e)),
803                    };
804                    let app_hash = c.app.as_ref().map(|b| b.content_hash.clone()).unwrap_or_default();
805                    let app = c.app.as_ref().map(|b| preview_app(&identity_store, b, &c.name, &mut warnings));
806                    items.push(SkillImportItem {
807                        key: c.key,
808                        name: c.name,
809                        description: c.description,
810                        content: c.content,
811                        status: status.to_string(),
812                        existing_id: e.map(|e| e.skill.id.clone()).unwrap_or_default(),
813                        existing_description: e.map(|e| e.skill.description.clone()).unwrap_or_default(),
814                        existing_content: e.map(|e| e.skill.content.clone()).unwrap_or_default(),
815                        app,
816                        app_hash,
817                    });
818                }
819                if items.is_empty() && warnings.is_empty() {
820                    warnings.push(if only_key.is_some() { "the skill is no longer in its source" } else { "no SKILL.md found in that source" }.to_string());
821                }
822                Ok(SkillImportPreview { source, items, warnings })
823            }
824        },
825    );
826}
827
828// Write the skills the person approved. A new one is global, unbound and outside "new agents get
829// it": an imported skill tells every agent it reaches what to do, so reaching them is a separate,
830// deliberate step. An existing one keeps its binds and reach.
831fn register_skill_catalog_import_commit(engine: &Arc<WshRpcEngine>, state: &AppState) {
832    let identity_store = state.identity_store.clone();
833    let broker = state.broker.clone();
834    engine.register_typed(
835        COMMAND_SKILL_CATALOG_IMPORT_COMMIT,
836        move |req: CommandSkillCatalogImportCommitData, _ctx| {
837            let identity_store = identity_store.clone();
838            let broker = broker.clone();
839            async move {
840                const E: &str = "skill.catalog.import_commit";
841                let now = now_ms();
842                // Check the whole batch before writing any of it, so a bad item cannot leave the
843                // ones before it written.
844                let mut seen = std::collections::HashSet::new();
845                let mut existing_rows = Vec::with_capacity(req.items.len());
846                let mut signers = Vec::with_capacity(req.items.len());
847                for item in &req.items {
848                    let name = item.name.trim();
849                    if name.is_empty() || name.chars().count() > 200 {
850                        return Err(format!("{E}: '{}' needs a name of 1 to 200 characters", item.key));
851                    }
852                    if item.description.chars().count() > 4000 || item.content.len() > 256 * 1024 {
853                        return Err(format!("{E}: '{name}' has a description over 4000 characters or text over 256 KB"));
854                    }
855                    if !seen.insert(name.to_string()) {
856                        return Err(format!("{E}: two of the skills are called '{name}'; import them one at a time"));
857                    }
858                    let mut signer = None;
859                    if !item.app_hash.is_empty() {
860                        // What the person saw must still be what is written: the text and name match the kept folder.
861                        match crate::backend::computer_use_skill::stashed(&item.app_hash) {
862                            Some(b) if b.name == name && b.content == item.content && b.description == item.description => {
863                                signer = crate::backend::computer_use_skill::check_signature(&identity_store, &b).map_err(|e| format!("{E}: '{name}': {e}"))?;
864                            }
865                            Some(_) => return Err(format!("{E}: '{name}' differs from the folder that was previewed; preview it again")),
866                            None => return Err(format!("{E}: the preview of '{name}' has expired; preview it again")),
867                        }
868                    }
869                    signers.push(signer);
870                    existing_rows.push(if item.existing_id.is_empty() {
871                        None
872                    } else {
873                        match identity_store.skill_get(&item.existing_id).map_err(|e| format!("{E}: {e}"))? {
874                            Some(s) if s.is_global => Some(s),
875                            _ => return Err(format!("{E}: the skill to update ('{name}') is not in the catalog")),
876                        }
877                    });
878                }
879                let mut saved = Vec::new();
880                let mut failure = None;
881                for ((item, existing), signer) in req.items.into_iter().zip(existing_rows).zip(signers) {
882                    let skill = crate::backend::storage::Skill {
883                        id: existing.as_ref().map_or_else(|| uuid::Uuid::new_v4().to_string(), |s| s.id.clone()),
884                        name: item.name.trim().to_string(),
885                        trigger: existing.as_ref().map_or_else(|| item.name.trim().to_string(), |s| s.trigger.clone()),
886                        skill_type: existing.as_ref().map_or_else(|| "agent-skill".to_string(), |s| s.skill_type.clone()),
887                        description: item.description,
888                        content: item.content,
889                        is_global: true,
890                        created_at: existing.as_ref().map_or(now, |s| s.created_at),
891                        updated_at: now,
892                    };
893                    let source = SkillSource { item_key: item.key, ..req.source.clone() };
894                    let bundle = crate::backend::computer_use_skill::stashed(&item.app_hash).filter(|_| !item.app_hash.is_empty());
895                    let written = identity_store
896                        .skill_upsert_unique_global(&skill)
897                        .and_then(|_| if existing.is_none() { identity_store.skill_set_reach(&skill.id, false, false, now) } else { Ok(()) })
898                        .and_then(|_| identity_store.skill_source_set(&skill.id, &source, now))
899                        .and_then(|_| match &bundle {
900                            Some(b) => crate::backend::computer_use_skill::install(&identity_store, &skill.id, b, signer.as_deref(), now),
901                            // A plain skill re-imported over an app skill carries no folder: drop the old one.
902                            None if existing.is_some() => identity_store.skill_app_forget(&skill.id),
903                            None => Ok(()),
904                        });
905                    match written {
906                        Ok(()) => saved.push(skill.id),
907                        Err(e) => {
908                            failure = Some(format!("{E}: '{}': {e}", skill.name));
909                            break;
910                        }
911                    }
912                }
913                // Tell the windows about what was written even when a later item failed.
914                if !saved.is_empty() {
915                    broker.publish_event::<crate::backend::mps_events::SkillsChanged>(&(), vec![], 0);
916                }
917                if let Some(f) = failure {
918                    return Err(if saved.is_empty() { f } else { format!("{f} ({} earlier skill(s) were saved)", saved.len()) });
919                }
920                Ok(SkillImportCommitResult { saved })
921            }
922        },
923    );
924}
925
926// One agent opts out of (or back into) what a catalog skill reaches it through. The reach switches
927// are the skill's; this is the agent's exception to them.
928fn register_skill_catalog_set_opt_out(engine: &Arc<WshRpcEngine>, state: &AppState) {
929    let mstore = state.mstore.clone();
930    let identity_store = state.identity_store.clone();
931    let broker = state.broker.clone();
932    engine.register_typed(
933        COMMAND_SKILL_CATALOG_SET_OPT_OUT,
934        move |req: CommandSkillCatalogSetOptOutData, _ctx| {
935            let mstore = mstore.clone();
936            let identity_store = identity_store.clone();
937            let broker = broker.clone();
938            async move {
939                const E: &str = "skill.catalog.set_opt_out";
940                match identity_store.skill_get(&req.skill_id).map_err(|e| format!("{E}: {e}"))? {
941                    Some(s) if s.is_global => {}
942                    _ => return Err(format!("{E}: skill not found in the catalog")),
943                }
944                if mstore.agent_def_get(&req.agent_id).map_err(|e| format!("{E}: {e}"))?.is_none() {
945                    return Err(format!("{E}: agent not found"));
946                }
947                identity_store.skill_optout_put(&req.skill_id, &req.agent_id, req.opted_out).map_err(|e| format!("{E}: {e}"))?;
948                broker.publish_event::<crate::backend::mps_events::SkillsChanged>(&(), vec![], 0);
949                Ok(())
950            }
951        },
952    );
953}
954
955#[cfg(test)]
956#[path = "skill_import_rpc_tests.rs"]
957mod import_rpc_tests;
958
959#[cfg(test)]
960#[path = "skill_optout_rpc_tests.rs"]
961mod optout_rpc_tests;