1use crate::skill::{
45 SkillAction, SkillError, SkillErrorKind, SkillLocation, SkillOptions, SkillReport, SkillScope,
46 SkillSpec, run_skill_admin,
47};
48use crate::{
49 ArgSpec, CliEmitter, CliStop, Combination, CommandSpec, OutputSpec, ResolvedInvocation,
50 cli_invocation_invalid_event, json_error, json_result,
51};
52
53pub const SKILL_CLI_ACTIONS: [&str; 3] = ["skill_status", "skill_install", "skill_uninstall"];
56
57const SCOPES: [(&str, SkillScope); 2] = [
58 ("personal", SkillScope::Personal),
59 ("workspace", SkillScope::Workspace),
60];
61
62#[derive(Clone, Copy)]
63struct Verb {
64 command: &'static str,
65 action: SkillAction,
66 takes_force: bool,
67}
68
69const VERBS: [Verb; 3] = [
70 Verb {
71 command: "status",
72 action: SkillAction::Status,
73 takes_force: false,
74 },
75 Verb {
76 command: "install",
77 action: SkillAction::Install,
78 takes_force: true,
79 },
80 Verb {
81 command: "uninstall",
82 action: SkillAction::Uninstall,
83 takes_force: true,
84 },
85];
86
87#[must_use]
95pub fn skill_cli_commands(spec: &SkillSpec, output: &OutputSpec) -> Vec<CommandSpec> {
96 let mut commands = vec![CommandSpec::new(["skill"]).about(format!(
97 "Manage the {} skill. By default it uses the standard folders agents read skills from: the shared .agents/skills, .claude/skills, and, for personal scope, .gemini/config/skills. For an agent that reads only a folder of its own, pass that folder as --skills-dir",
98 spec.title
99 ))];
100 commands.extend(VERBS.iter().map(|verb| verb_command(spec, *verb, output)));
101 commands
102}
103
104fn verb_command(spec: &SkillSpec, verb: Verb, output: &OutputSpec) -> CommandSpec {
105 let (about, shape_verb) = match verb.action {
106 SkillAction::Status => (
107 format!(
108 "Report whether the {} skill is installed, valid, and current",
109 spec.title
110 ),
111 "Report on",
112 ),
113 SkillAction::Install => (format!("Install the {} skill", spec.title), "Install into"),
114 SkillAction::Uninstall => (
115 format!(
116 "Remove the {} skill that {} installed",
117 spec.title, spec.marker_slug
118 ),
119 "Remove from",
120 ),
121 };
122 let action = action_id(verb.action);
123 let mut command = CommandSpec::new(["skill", verb.command])
124 .about(about)
125 .arg(
126 ArgSpec::option_enum("--scope", SCOPES.iter().map(|(name, _)| *name))
127 .value_name("SCOPE")
128 .default("personal")
129 .about("Standard folders under the home directory (personal) or the current directory (workspace)"),
130 )
131 .arg(
132 ArgSpec::option("--skills-dir", "PATH")
133 .about("One skills directory to use instead of the standard folders"),
134 );
135 let mut standard_optional = vec!["scope"];
136 let mut directory_optional = Vec::new();
137 if verb.takes_force {
138 command = command.arg(ArgSpec::flag("--force").about(format!(
139 "Overwrite or remove a skill at the target path that {} did not install",
140 spec.marker_slug
141 )));
142 standard_optional.push("force");
143 directory_optional.push("force");
144 }
145 command
146 .combination(
147 Combination::new(format!("skill-{}-standard", verb.command))
148 .action(action)
149 .about(format!("{shape_verb} the standard skill folders"))
150 .optional(standard_optional)
151 .output(output.clone()),
152 )
153 .combination(
154 Combination::new(format!("skill-{}-directory", verb.command))
155 .action(action)
156 .about(format!("{shape_verb} one skills directory"))
157 .required(["skills_dir"])
158 .optional(directory_optional)
159 .output(output.clone()),
160 )
161}
162
163fn action_id(action: SkillAction) -> &'static str {
164 match action {
165 SkillAction::Status => SKILL_CLI_ACTIONS[0],
166 SkillAction::Install => SKILL_CLI_ACTIONS[1],
167 SkillAction::Uninstall => SKILL_CLI_ACTIONS[2],
168 }
169}
170
171#[derive(Clone, Debug)]
177pub struct SkillCliRequest {
178 action: SkillAction,
179 options: SkillOptions,
180}
181
182impl SkillCliRequest {
183 pub fn from_invocation(invocation: &ResolvedInvocation) -> Result<Self, CliStop> {
188 let action_id = invocation.action_id();
189 let verb = VERBS
190 .iter()
191 .find(|verb| self::action_id(verb.action) == action_id)
192 .ok_or_else(|| defect(&format!("action `{action_id}` is not a skill action")))?;
193 let action = verb.action;
194 let location = if invocation.declares("skills_dir") {
195 SkillLocation::Directory(invocation.text("skills_dir")?.to_string())
196 } else {
197 SkillLocation::Standard(
198 lookup(&SCOPES, invocation.text("scope")?, "--scope")
199 .map_err(|detail| defect(&detail))?,
200 )
201 };
202 let force = invocation.declares("force") && invocation.flag("force")?;
203 Ok(Self {
204 action,
205 options: SkillOptions { location, force },
206 })
207 }
208
209 #[must_use]
211 pub const fn action(&self) -> SkillAction {
212 self.action
213 }
214
215 #[must_use]
217 pub const fn options(&self) -> &SkillOptions {
218 &self.options
219 }
220
221 #[must_use]
227 pub fn execute(&self, spec: &SkillSpec) -> SkillCliOutcome {
228 SkillCliOutcome {
229 result: run_skill_admin(spec, self.action, &self.options),
230 }
231 }
232
233 pub fn run<W: std::io::Write>(&self, spec: &SkillSpec, emitter: &mut CliEmitter<W>) -> u8 {
238 self.execute(spec).emit(emitter)
239 }
240}
241
242#[derive(Debug)]
244pub struct SkillCliOutcome {
245 result: Result<SkillReport, SkillError>,
246}
247
248impl SkillCliOutcome {
249 #[must_use]
251 pub fn report(&self) -> Option<&SkillReport> {
252 self.result.as_ref().ok()
253 }
254
255 #[must_use]
257 pub fn error(&self) -> Option<&SkillError> {
258 self.result.as_ref().err()
259 }
260
261 pub fn emit<W: std::io::Write>(self, emitter: &mut CliEmitter<W>) -> u8 {
269 match self.result {
270 Ok(report) => match serde_json::to_value(&report) {
271 Ok(value) => emitter.finish(json_result(value).build(), 0),
272 Err(error) => emitter.finish(
273 build_error(json_error(
274 "skill_report_serialization_failed",
275 &format!("failed to serialize the skill report: {error}"),
276 )),
277 1,
278 ),
279 },
280 Err(error) => {
281 let status = match error.kind {
282 SkillErrorKind::Usage => 2,
283 _ => 1,
284 };
285 emitter.finish(skill_error_event(&error), status)
286 }
287 }
288 }
289}
290
291fn defect(detail: &str) -> CliStop {
292 CliStop::new(cli_invocation_invalid_event(detail), 1)
293}
294
295fn lookup<T: Copy>(table: &[(&str, T)], value: &str, flag: &str) -> Result<T, String> {
296 table
297 .iter()
298 .find(|(name, _)| *name == value)
299 .map(|(_, item)| *item)
300 .ok_or_else(|| format!("{flag} value `{value}` is not registered"))
301}
302
303fn skill_error_event(error: &SkillError) -> crate::Event {
304 let mut builder =
305 json_error(error.kind.code(), &error.message).hint_if_some(error.hint.as_deref());
306 if let Some(report) = error.partial_report.as_ref()
307 && let Ok(value) = serde_json::to_value(report)
308 {
309 builder = builder.field("partial_report", value);
310 }
311 build_error(builder)
312}
313
314fn build_error(builder: crate::ErrorBuilder) -> crate::Event {
315 builder
316 .build()
317 .unwrap_or_else(|_| cli_invocation_invalid_event("could not construct the skill error"))
318}
319
320#[cfg(test)]
321mod tests {
322 use super::*;
323 use crate::{CliOutcome, CliSpec, build_afdata_cli};
324
325 const SPEC: SkillSpec = SkillSpec {
326 name: "agent-first-widget",
327 source: "---\nname: agent-first-widget\ndescription: Widgets.\n---\n",
328 title: "Agent-First Widget",
329 marker_slug: "afwidget",
330 assets: &[],
331 };
332
333 fn cli() -> crate::BuiltCliSpec {
334 let output = OutputSpec::protocol_finite(["json"], ["split"], "json", "split");
335 let mut spec = CliSpec::new("afwidget", "1.0.0")
336 .lifecycle_output(output.clone())
337 .command(CommandSpec::root());
338 for command in skill_cli_commands(&SPEC, &output) {
339 spec = spec.command(command);
340 }
341 match build_afdata_cli(spec) {
342 Ok(cli) => cli,
343 Err(error) => panic!("skill commands must build: {error}"),
344 }
345 }
346
347 fn resolve(argv: &[&str]) -> Result<(SkillAction, SkillOptions), String> {
348 let mut full = vec!["afwidget"];
349 full.extend_from_slice(argv);
350 match cli().resolve_from(full) {
351 Ok(CliOutcome::Run(invocation)) => SkillCliRequest::from_invocation(&invocation)
352 .map(|request| (request.action, request.options))
353 .map_err(|stop| format!("{:?}", stop.event())),
354 Ok(_) => Err("not a run".to_string()),
355 Err(error) => Err(error.rule.code().to_string()),
356 }
357 }
358
359 #[test]
360 fn every_action_is_registered_once() {
361 let handlers = SKILL_CLI_ACTIONS.map(|action| {
362 (
363 action,
364 (|_: &ResolvedInvocation| Ok(())) as crate::CliHandler<()>,
365 )
366 });
367 assert!(cli().bind_actions(handlers).is_ok());
368 }
369
370 #[test]
371 fn defaults_reach_the_personal_standard_folders() {
372 match resolve(&["skill", "status"]) {
373 Ok((action, options)) => {
374 assert_eq!(action, SkillAction::Status);
375 assert_eq!(
376 options.location,
377 SkillLocation::Standard(SkillScope::Personal)
378 );
379 assert!(!options.force);
380 }
381 Err(error) => panic!("status must resolve: {error}"),
382 }
383 }
384
385 #[test]
386 fn every_registered_scope_translates() {
387 for (name, scope) in SCOPES {
388 match resolve(&["skill", "install", "--scope", name, "--force"]) {
389 Ok((action, options)) => {
390 assert_eq!(action, SkillAction::Install);
391 assert_eq!(options.location, SkillLocation::Standard(scope));
392 assert!(options.force);
393 }
394 Err(error) => panic!("--scope {name} must resolve: {error}"),
395 }
396 }
397 }
398
399 #[test]
400 fn serialized_names_are_the_cli_values() {
401 for (name, scope) in SCOPES {
402 let value = serde_json::to_value(scope).ok();
403 assert_eq!(value.as_ref().and_then(|value| value.as_str()), Some(name));
404 }
405 for verb in VERBS {
406 let value = serde_json::to_value(verb.action).ok();
407 assert_eq!(
408 value.as_ref().and_then(|value| value.as_str()),
409 Some(verb.command)
410 );
411 }
412 }
413
414 #[test]
415 fn skills_dir_is_its_own_shape_without_scope() {
416 for verb in VERBS {
417 let args = ["skill", verb.command, "--skills-dir", "/tmp/skills"];
418 let (action, options) = resolve(&args).expect("directory target resolves");
419 assert_eq!(action, verb.action);
420 assert_eq!(
421 options.location,
422 SkillLocation::Directory("/tmp/skills".to_string())
423 );
424 let mut with_scope = args.to_vec();
425 with_scope.extend(["--scope", "personal"]);
426 assert!(resolve(&with_scope).is_err());
427 }
428 assert!(resolve(&["skill", "install", "--agent", "codex"]).is_err());
429 }
430
431 fn request(argv: &[&str]) -> SkillCliRequest {
432 let mut full = vec!["afwidget"];
433 full.extend_from_slice(argv);
434 match cli().resolve_from(full) {
435 Ok(CliOutcome::Run(invocation)) => {
436 match SkillCliRequest::from_invocation(&invocation) {
437 Ok(request) => request,
438 Err(stop) => panic!("{argv:?} did not read: {:?}", stop.event()),
439 }
440 }
441 Ok(_) => panic!("{argv:?} is not a run"),
442 Err(error) => panic!("{argv:?} failed to resolve: {}", error.message),
443 }
444 }
445
446 #[test]
447 fn execute_reports_without_emitting() {
448 let dir = std::env::temp_dir().join(format!("afdata_skill_cli_{}", std::process::id()));
449 let dir_text = dir.to_string_lossy().to_string();
450 let install = request(&["skill", "install", "--skills-dir", &dir_text]);
451 assert_eq!(install.action(), SkillAction::Install);
452 assert_eq!(
453 install.options().location,
454 SkillLocation::Directory(dir_text.clone())
455 );
456 let installed = install.execute(&SPEC);
457 assert!(matches!(
458 installed.report(),
459 Some(SkillReport::Install { .. })
460 ));
461 assert!(installed.error().is_none());
462
463 let unmanaged = dir.join("agent-first-widget").join("SKILL.md");
464 assert!(
465 std::fs::write(
466 &unmanaged,
467 "---\nname: agent-first-widget\ndescription: Mine.\n---\n"
468 )
469 .is_ok()
470 );
471 let refused = install.execute(&SPEC);
472 assert!(refused.report().is_none());
473 assert_eq!(
474 refused.error().map(|error| error.kind),
475 Some(SkillErrorKind::Refused)
476 );
477 let _ = std::fs::remove_dir_all(&dir);
478 }
479
480 #[test]
481 fn status_rejects_force() {
482 assert!(resolve(&["skill", "status", "--force"]).is_err());
483 }
484}