1use crate::skill::{
45 SkillAction, SkillAgentSelection, SkillError, SkillErrorKind, SkillOptions, SkillReport,
46 SkillScope, 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 EVERY_AGENT: &str = "all";
59
60const AGENTS: [(&str, SkillAgentSelection); 4] = [
64 ("codex", SkillAgentSelection::Codex),
65 ("claude-code", SkillAgentSelection::ClaudeCode),
66 ("opencode", SkillAgentSelection::Opencode),
67 ("hermes", SkillAgentSelection::Hermes),
68];
69
70const SCOPES: [(&str, SkillScope); 2] = [
71 ("personal", SkillScope::Personal),
72 ("workspace", SkillScope::Workspace),
73];
74
75#[derive(Clone, Copy)]
76struct Verb {
77 command: &'static str,
78 action: SkillAction,
79 takes_force: bool,
80}
81
82const VERBS: [Verb; 3] = [
83 Verb {
84 command: "status",
85 action: SkillAction::Status,
86 takes_force: false,
87 },
88 Verb {
89 command: "install",
90 action: SkillAction::Install,
91 takes_force: true,
92 },
93 Verb {
94 command: "uninstall",
95 action: SkillAction::Uninstall,
96 takes_force: true,
97 },
98];
99
100#[must_use]
108pub fn skill_cli_commands(spec: &SkillSpec, output: &OutputSpec) -> Vec<CommandSpec> {
109 let mut commands = vec![CommandSpec::new(["skill"]).about(format!(
110 "Manage the {} skill for Codex, Claude Code, opencode, and Hermes",
111 spec.title
112 ))];
113 commands.extend(VERBS.iter().map(|verb| verb_command(spec, *verb, output)));
114 commands
115}
116
117fn verb_command(spec: &SkillSpec, verb: Verb, output: &OutputSpec) -> CommandSpec {
118 let (about, shape_verb) = match verb.action {
119 SkillAction::Status => (
120 format!(
121 "Report whether the {} skill is installed, valid, and current",
122 spec.title
123 ),
124 "Report on",
125 ),
126 SkillAction::Install => (format!("Install the {} skill", spec.title), "Install into"),
127 SkillAction::Uninstall => (
128 format!(
129 "Remove the {} skill that {} installed",
130 spec.title, spec.marker_slug
131 ),
132 "Remove from",
133 ),
134 };
135 let action = action_id(verb.action);
136 let mut command = CommandSpec::new(["skill", verb.command])
137 .about(about)
138 .arg(
139 ArgSpec::option_enum(
140 "--agent",
141 std::iter::once(EVERY_AGENT).chain(AGENTS.iter().map(|(name, _)| *name)),
142 )
143 .value_name("AGENT")
144 .default(EVERY_AGENT)
145 .about("Target agent"),
146 )
147 .arg(
148 ArgSpec::option_enum("--scope", SCOPES.iter().map(|(name, _)| *name))
149 .value_name("SCOPE")
150 .default("personal")
151 .about("Skill scope"),
152 )
153 .arg(
154 ArgSpec::option("--skills-dir", "PATH")
155 .about("Explicit skills directory; only valid with one named agent"),
156 );
157 let mut every_optional = vec!["scope"];
158 let mut named_optional = vec!["scope", "skills_dir"];
159 if verb.takes_force {
160 command = command.arg(ArgSpec::flag("--force").about(format!(
161 "Overwrite or remove a skill at the target path that {} did not install",
162 spec.marker_slug
163 )));
164 every_optional.push("force");
165 named_optional.push("force");
166 }
167 command
168 .combination(
169 Combination::new(format!("skill-{}-all", verb.command))
170 .action(action)
171 .about(format!("{shape_verb} every agent that supports the scope"))
172 .fixed("agent", EVERY_AGENT)
173 .optional(every_optional)
174 .output(output.clone()),
175 )
176 .combination(
177 Combination::new(format!("skill-{}-agent", verb.command))
178 .action(action)
179 .about(format!(
180 "{shape_verb} one named agent; only this shape accepts --skills-dir"
181 ))
182 .fixed_one_of("agent", AGENTS.iter().map(|(name, _)| *name))
183 .optional(named_optional)
184 .output(output.clone()),
185 )
186}
187
188fn action_id(action: SkillAction) -> &'static str {
189 match action {
190 SkillAction::Status => SKILL_CLI_ACTIONS[0],
191 SkillAction::Install => SKILL_CLI_ACTIONS[1],
192 SkillAction::Uninstall => SKILL_CLI_ACTIONS[2],
193 }
194}
195
196#[derive(Clone, Debug)]
202pub struct SkillCliRequest {
203 action: SkillAction,
204 options: SkillOptions,
205}
206
207impl SkillCliRequest {
208 pub fn from_invocation(invocation: &ResolvedInvocation) -> Result<Self, CliStop> {
213 let action_id = invocation.action_id();
214 let verb = VERBS
215 .iter()
216 .find(|verb| self::action_id(verb.action) == action_id)
217 .ok_or_else(|| defect(&format!("action `{action_id}` is not a skill action")))?;
218 let action = verb.action;
219 let agent_name = invocation.text("agent")?;
220 let agent = if agent_name == EVERY_AGENT {
221 SkillAgentSelection::All
222 } else {
223 lookup(&AGENTS, agent_name, "--agent").map_err(|detail| defect(&detail))?
224 };
225 let scope = lookup(&SCOPES, invocation.text("scope")?, "--scope")
226 .map_err(|detail| defect(&detail))?;
227 let skills_dir = if invocation.declares("skills_dir") {
231 invocation.optional_text("skills_dir")?.map(str::to_string)
232 } else {
233 None
234 };
235 let force = invocation.declares("force") && invocation.flag("force")?;
236 Ok(Self {
237 action,
238 options: SkillOptions {
239 agent,
240 scope,
241 skills_dir,
242 force,
243 },
244 })
245 }
246
247 #[must_use]
249 pub const fn action(&self) -> SkillAction {
250 self.action
251 }
252
253 #[must_use]
255 pub const fn options(&self) -> &SkillOptions {
256 &self.options
257 }
258
259 #[must_use]
265 pub fn execute(&self, spec: &SkillSpec) -> SkillCliOutcome {
266 SkillCliOutcome {
267 result: run_skill_admin(spec, self.action, &self.options),
268 }
269 }
270
271 pub fn run<W: std::io::Write>(&self, spec: &SkillSpec, emitter: &mut CliEmitter<W>) -> u8 {
276 self.execute(spec).emit(emitter)
277 }
278}
279
280#[derive(Debug)]
282pub struct SkillCliOutcome {
283 result: Result<SkillReport, SkillError>,
284}
285
286impl SkillCliOutcome {
287 #[must_use]
289 pub fn report(&self) -> Option<&SkillReport> {
290 self.result.as_ref().ok()
291 }
292
293 #[must_use]
295 pub fn error(&self) -> Option<&SkillError> {
296 self.result.as_ref().err()
297 }
298
299 pub fn emit<W: std::io::Write>(self, emitter: &mut CliEmitter<W>) -> u8 {
307 match self.result {
308 Ok(report) => match serde_json::to_value(&report) {
309 Ok(value) => emitter.finish(json_result(value).build(), 0),
310 Err(error) => emitter.finish(
311 build_error(json_error(
312 "skill_report_serialization_failed",
313 &format!("failed to serialize the skill report: {error}"),
314 )),
315 1,
316 ),
317 },
318 Err(error) => {
319 let status = match error.kind {
320 SkillErrorKind::Usage => 2,
321 _ => 1,
322 };
323 emitter.finish(skill_error_event(&error), status)
324 }
325 }
326 }
327}
328
329fn defect(detail: &str) -> CliStop {
330 CliStop::new(cli_invocation_invalid_event(detail), 1)
331}
332
333fn lookup<T: Copy>(table: &[(&str, T)], value: &str, flag: &str) -> Result<T, String> {
334 table
335 .iter()
336 .find(|(name, _)| *name == value)
337 .map(|(_, item)| *item)
338 .ok_or_else(|| format!("{flag} value `{value}` is not registered"))
339}
340
341fn skill_error_event(error: &SkillError) -> crate::Event {
342 let mut builder =
343 json_error(error.kind.code(), &error.message).hint_if_some(error.hint.as_deref());
344 if let Some(report) = error.partial_report.as_ref()
345 && let Ok(value) = serde_json::to_value(report)
346 {
347 builder = builder.field("partial_report", value);
348 }
349 build_error(builder)
350}
351
352fn build_error(builder: crate::ErrorBuilder) -> crate::Event {
353 builder
354 .build()
355 .unwrap_or_else(|_| cli_invocation_invalid_event("could not construct the skill error"))
356}
357
358#[cfg(test)]
359mod tests {
360 use super::*;
361 use crate::{CliOutcome, CliSpec, build_afdata_cli};
362
363 const SPEC: SkillSpec = SkillSpec {
364 name: "agent-first-widget",
365 source: "---\nname: agent-first-widget\ndescription: Widgets.\n---\n",
366 title: "Agent-First Widget",
367 marker_slug: "afwidget",
368 assets: &[],
369 };
370
371 fn cli() -> crate::BuiltCliSpec {
372 let output = OutputSpec::protocol_finite(["json"], ["split"], "json", "split");
373 let mut spec = CliSpec::new("afwidget", "1.0.0")
374 .lifecycle_output(output.clone())
375 .command(CommandSpec::root());
376 for command in skill_cli_commands(&SPEC, &output) {
377 spec = spec.command(command);
378 }
379 match build_afdata_cli(spec) {
380 Ok(cli) => cli,
381 Err(error) => panic!("skill commands must build: {error}"),
382 }
383 }
384
385 fn resolve(argv: &[&str]) -> Result<(SkillAction, SkillOptions), String> {
386 let mut full = vec!["afwidget"];
387 full.extend_from_slice(argv);
388 match cli().resolve_from(full) {
389 Ok(CliOutcome::Run(invocation)) => SkillCliRequest::from_invocation(&invocation)
390 .map(|request| (request.action, request.options))
391 .map_err(|stop| format!("{:?}", stop.event())),
392 Ok(_) => Err("not a run".to_string()),
393 Err(error) => Err(error.rule.code().to_string()),
394 }
395 }
396
397 #[test]
398 fn every_action_is_registered_once() {
399 let handlers = SKILL_CLI_ACTIONS.map(|action| {
400 (
401 action,
402 (|_: &ResolvedInvocation| Ok(())) as crate::CliHandler<()>,
403 )
404 });
405 assert!(cli().bind_actions(handlers).is_ok());
406 }
407
408 #[test]
409 fn defaults_reach_every_personal_agent() {
410 match resolve(&["skill", "status"]) {
411 Ok((action, options)) => {
412 assert_eq!(action, SkillAction::Status);
413 assert_eq!(options.agent, SkillAgentSelection::All);
414 assert_eq!(options.scope, SkillScope::Personal);
415 assert_eq!(options.skills_dir, None);
416 assert!(!options.force);
417 }
418 Err(error) => panic!("status must resolve: {error}"),
419 }
420 }
421
422 #[test]
423 fn every_registered_agent_translates() {
424 for (name, selection) in AGENTS {
425 match resolve(&["skill", "install", "--agent", name, "--force"]) {
426 Ok((action, options)) => {
427 assert_eq!(action, SkillAction::Install);
428 assert_eq!(options.agent, selection);
429 assert!(options.force);
430 }
431 Err(error) => panic!("--agent {name} must resolve: {error}"),
432 }
433 }
434 }
435
436 #[test]
437 fn serialized_names_are_the_cli_values() {
438 let every = serde_json::to_value(SkillAgentSelection::All).ok();
439 assert_eq!(
440 every.as_ref().and_then(|value| value.as_str()),
441 Some(EVERY_AGENT)
442 );
443 for (name, selection) in AGENTS {
444 let value = serde_json::to_value(selection).ok();
445 assert_eq!(value.as_ref().and_then(|value| value.as_str()), Some(name));
446 }
447 for (name, scope) in SCOPES {
448 let value = serde_json::to_value(scope).ok();
449 assert_eq!(value.as_ref().and_then(|value| value.as_str()), Some(name));
450 }
451 for verb in VERBS {
452 let value = serde_json::to_value(verb.action).ok();
453 assert_eq!(
454 value.as_ref().and_then(|value| value.as_str()),
455 Some(verb.command)
456 );
457 }
458 }
459
460 #[test]
461 fn skills_dir_needs_one_named_agent() {
462 assert!(resolve(&["skill", "install", "--skills-dir", "/tmp/skills"]).is_err());
463 match resolve(&[
464 "skill",
465 "uninstall",
466 "--agent",
467 "codex",
468 "--scope",
469 "workspace",
470 "--skills-dir",
471 "/tmp/skills",
472 ]) {
473 Ok((action, options)) => {
474 assert_eq!(action, SkillAction::Uninstall);
475 assert_eq!(options.scope, SkillScope::Workspace);
476 assert_eq!(options.skills_dir.as_deref(), Some("/tmp/skills"));
477 }
478 Err(error) => panic!("one named agent accepts --skills-dir: {error}"),
479 }
480 }
481
482 fn request(argv: &[&str]) -> SkillCliRequest {
483 let mut full = vec!["afwidget"];
484 full.extend_from_slice(argv);
485 match cli().resolve_from(full) {
486 Ok(CliOutcome::Run(invocation)) => {
487 match SkillCliRequest::from_invocation(&invocation) {
488 Ok(request) => request,
489 Err(stop) => panic!("{argv:?} did not read: {:?}", stop.event()),
490 }
491 }
492 Ok(_) => panic!("{argv:?} is not a run"),
493 Err(error) => panic!("{argv:?} failed to resolve: {}", error.message),
494 }
495 }
496
497 #[test]
498 fn execute_reports_without_emitting() {
499 let dir = std::env::temp_dir().join(format!("afdata_skill_cli_{}", std::process::id()));
500 let dir_text = dir.to_string_lossy().to_string();
501 let install = request(&[
502 "skill",
503 "install",
504 "--agent",
505 "codex",
506 "--skills-dir",
507 &dir_text,
508 ]);
509 assert_eq!(install.action(), SkillAction::Install);
510 assert_eq!(
511 install.options().skills_dir.as_deref(),
512 Some(dir_text.as_str())
513 );
514 let installed = install.execute(&SPEC);
515 assert!(matches!(
516 installed.report(),
517 Some(SkillReport::Install { .. })
518 ));
519 assert!(installed.error().is_none());
520
521 let unmanaged = dir.join("agent-first-widget").join("SKILL.md");
522 assert!(
523 std::fs::write(
524 &unmanaged,
525 "---\nname: agent-first-widget\ndescription: Mine.\n---\n"
526 )
527 .is_ok()
528 );
529 let refused = install.execute(&SPEC);
530 assert!(refused.report().is_none());
531 assert_eq!(
532 refused.error().map(|error| error.kind),
533 Some(SkillErrorKind::Refused)
534 );
535 let _ = std::fs::remove_dir_all(&dir);
536 }
537
538 #[test]
539 fn status_rejects_force() {
540 assert!(resolve(&["skill", "status", "--force"]).is_err());
541 }
542}