1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! craftbag CLI: list, load, why, validate.
use std::io::{self, Write};
use std::path::PathBuf;
use std::process::ExitCode;
/// `print!` / `println!` panic on a closed pipe (`list | head`). Treat
/// `BrokenPipe` as a clean stop.
fn write_stdout(text: &str) -> Result<(), String> {
let mut out = io::stdout();
match out.write_all(text.as_bytes()).and_then(|_| out.flush()) {
Ok(()) => Ok(()),
Err(e) if e.kind() == io::ErrorKind::BrokenPipe => Ok(()),
Err(e) => Err(e.to_string()),
}
}
fn writeln_stdout(text: &str) -> Result<(), String> {
write_stdout(&format!("{text}\n"))
}
use clap::{Parser, Subcommand};
use craftbag::{
DiscoveryOptions, FormatOptions, ListFormat, LoadView, SkillSource, SkillSummary, discover,
find_skill_by_name, format_available_skills_xml, format_catalog, format_list_tsv,
format_load_view, format_skip_tsv, format_watch_dirs, format_why_text, parse_list_format,
progressive_budgets, unknown_or_skipped_skill_named, validate_path_with_options, watch_dirs,
why,
};
#[derive(Parser)]
#[command(
name = "craftbag",
version,
about = "Discover and load Agent Skills (SKILL.md) for CLI and MCP hosts"
)]
struct Cli {
#[command(subcommand)]
cmd: Cmd,
}
#[derive(clap::Args, Debug, Clone)]
struct DiscoveryArgs {
/// Extra package or collection root (not a project walk). Refuses a line separator or a token that collapses after whitespace (` /..`). A missing path is reported as unreadable. Example: --path ./my-skill
#[arg(long = "path", value_name = "PATH")]
paths: Vec<String>,
/// Opt-in vendor trees: bline, claude, cursor, grok. Example: --vendor claude
#[arg(long, value_delimiter = ',')]
vendor: Vec<String>,
/// User skills root (child dirs are packages). Refuses a line separator or a token that collapses after whitespace (` /..`). A missing path is reported as unreadable. Example: --user-dir ~/myskills
#[arg(long = "user-dir")]
user_dir: Option<PathBuf>,
/// Reject names outside `a-z0-9-`. Default still allows Unicode / NFKC.
#[arg(long = "ascii-names")]
ascii_names: bool,
/// Skip cwd-to-git .agents / vendor trees and $HOME/.agents / vendor trees. Default is on. Extra --path and --user-dir still load.
#[arg(long = "no-implicit-roots")]
no_implicit_roots: bool,
/// Skill names never loaded (silent; no skip row). Same NFKC identity as load / why. Example: --disabled secret
#[arg(long = "disabled", value_name = "NAME")]
disabled: Vec<String>,
/// Path prefix never loaded (silent; no skip row). Relative prefixes join cwd. Example: --ignore ./secret
#[arg(long = "ignore", value_name = "PATH")]
ignore: Vec<String>,
}
#[derive(Subcommand)]
enum Cmd {
/// Catalog discovered skills.
List {
/// Print `{ skills, skips }` (same shape as MCP skills_list).
#[arg(long)]
json: bool,
/// Official skills-ref `<available_skills>` XML inventory (includes disable_model_invocation for slash palettes).
#[arg(long, conflicts_with = "json")]
xml: bool,
/// Markdown catalog (name + description) for model prompts. Omits disable_model_invocation (official client-guide). JSON, XML, and TSV still list those rows.
#[arg(long, conflicts_with_all = ["json", "xml"])]
catalog: bool,
/// Print notify-watch roots (same walk as discover). Does not load SKILL.md.
#[arg(long = "watch-dirs", conflicts_with_all = ["json", "xml", "catalog"])]
watch_dirs: bool,
/// Same tokens as MCP skills_list format: json (`{ skills, skips }`), xml (`<available_skills>`), catalog, watch.
/// catalog omits disable_model_invocation (official client-guide); json, xml, and TSV still list those rows.
/// xml and catalog also emit `skip\tkind\tpath\tdetail` (CLI stderr; MCP text after the prompt fragment).
/// `watch-dirs` and `watch_dirs` are the `--watch-dirs` flag name.
#[arg(long = "format", value_name = "FORMAT", conflicts_with_all = ["json", "xml", "catalog", "watch_dirs"])]
format: Option<String>,
#[command(flatten)]
discovery: DiscoveryArgs,
/// Catalog ranking text (`--catalog` / `--format catalog`). JSON, XML, TSV, and watch ignore this. Example: --context rebase
#[arg(long)]
context: Option<String>,
/// Model context window size for catalog listing (default 8000). Used by `--catalog` / `--format catalog`.
#[arg(long, default_value_t = 8_000)]
context_tokens: usize,
},
/// Print one skill body plus package envelope (includes argument-hint, when-to-use, triggers, allowed-tools, license, compatibility, and metadata when set). --outline prints heading keys; --section KEY prints one heading. Does not dump scripts/ or references/ file bodies.
Load {
/// Frontmatter skill name (not a package path). Discover with list --path DIR.
name: String,
/// Success is `{ name, path, source, text }` (text is the envelope, including --outline / --section). On a miss, print `{ error_kind, error }` (same peel as `why --json` / `validate --json`), and `path` when a skip is known. A `name_collision` skip also peels `winner_path`. Exit 2 on a miss.
#[arg(long)]
json: bool,
/// Print SKILL.md heading keys and token costs instead of the body.
#[arg(long, conflicts_with = "section")]
outline: bool,
/// Print one SKILL.md heading section (key from --outline).
#[arg(long, value_name = "KEY", conflicts_with = "outline")]
section: Option<String>,
/// Copied into the envelope as User arguments. Matches argument-hint. Example: --args --fix
#[arg(long = "args", default_value = "", allow_hyphen_values = true)]
args: String,
#[command(flatten)]
discovery: DiscoveryArgs,
},
/// Explain loaded, skipped, and activation decisions.
Why {
/// Optional frontmatter skill name filter (not a package path).
name: Option<String>,
/// Print `{ loaded, skips, activation }` (same shape as MCP skills_why). On a name miss, print `{ error_kind, error }` (same peel as `validate --json`), and `path` when a skip is known. A `name_collision` skip also peels `winner_path`. Exit 2 on a name miss. Exit 1 on a tool error.
#[arg(long)]
json: bool,
/// Activation context text. Example: --context rebase
#[arg(long)]
context: Option<String>,
/// Model context window size (default 8000).
#[arg(long, default_value_t = 8_000)]
context_tokens: usize,
#[command(flatten)]
discovery: DiscoveryArgs,
},
/// Validate one SKILL.md file or package directory. `--json` success is ValidationReport (no error_kind).
Validate {
/// SKILL.md file, or a package directory that contains SKILL.md / skill.md. Refuses a line separator or a token that collapses after whitespace (` /..`). A missing path is reported as unreadable. Example: ./my-skill
path: PathBuf,
/// Reject unknown frontmatter keys (skills-ref default).
#[arg(long)]
strict: bool,
/// Success is ValidationReport (no error_kind). Same `{ error_kind, error }` peel as `why --json` on failure, plus `path`. A `name_collision` skip also peels `winner_path`.
#[arg(long)]
json: bool,
},
}
fn main() -> ExitCode {
match run(Cli::parse()) {
Ok(code) => code,
Err(e) => {
let _ = writeln!(io::stderr(), "{e}");
ExitCode::from(1)
}
}
}
fn run(cli: Cli) -> Result<ExitCode, String> {
match cli.cmd {
Cmd::List {
json,
xml,
catalog,
watch_dirs: watch,
format,
discovery,
context,
context_tokens,
} => {
let mode = list_output_mode(json, xml, catalog, watch, format)?;
let (cwd, opts) = discovery_opts(&discovery)?;
if matches!(mode, ListOutput::Watch) {
write_stdout(&format_watch_dirs(&watch_dirs(&cwd, &opts)))?;
return Ok(ExitCode::SUCCESS);
}
let report = discover(&cwd, &opts);
if matches!(mode, ListOutput::Catalog) {
write_stdout(&format_catalog(
&report.skills,
context.as_deref().unwrap_or(""),
progressive_budgets(context_tokens),
FormatOptions::default(),
))?;
} else if matches!(mode, ListOutput::Xml) {
write_stdout(&format_available_skills_xml(&report.skills))?;
} else if matches!(mode, ListOutput::Json) {
let v = serde_json::json!({
"skills": report.skills.iter().map(SkillSummary::from).collect::<Vec<_>>(),
"skips": report.skips,
});
writeln_stdout(&serde_json::to_string_pretty(&v).map_err(|e| e.to_string())?)?;
} else {
write_stdout(&format_list_tsv(&report.skills))?;
}
if !matches!(mode, ListOutput::Json) {
let _ = write!(io::stderr(), "{}", format_skip_tsv(&report.skips));
}
if report.skills.is_empty()
&& report.skips.is_empty()
&& !matches!(mode, ListOutput::Json | ListOutput::Xml)
{
write_empty_tree_note(&cwd, &opts);
}
Ok(ExitCode::SUCCESS)
}
Cmd::Load {
name,
json,
outline,
section,
args,
discovery,
} => {
let report = discover_cwd(&discovery)?;
match find_skill_by_name(&report.skills, &name) {
Some(skill) => {
let view = if outline {
LoadView::Outline
} else if let Some(key) = section.as_deref() {
LoadView::Section(key)
} else {
LoadView::Body
};
match format_load_view(skill, &args, FormatOptions::default(), view) {
Ok(text) => {
if json {
let v = serde_json::json!({
"name": skill.name,
"path": skill.source_path.as_ref().map(|p| p.display().to_string()),
"source": skill.source.as_str(),
"text": text,
});
writeln_stdout(
&serde_json::to_string_pretty(&v).map_err(|e| e.to_string())?,
)?;
} else {
write_stdout(&text)?;
}
Ok(ExitCode::SUCCESS)
}
Err(msg) => {
let _ = writeln!(io::stderr(), "{msg}");
if json {
let v = serde_json::json!({
"error_kind": "unknown_section",
"error": msg,
});
writeln_stdout(
&serde_json::to_string_pretty(&v).map_err(|e| e.to_string())?,
)?;
}
Ok(ExitCode::from(2))
}
}
}
None => {
let miss = unknown_or_skipped_skill_named(
&name,
&report.skips,
report.skills.iter().map(|s| s.name.as_str()),
);
let _ = writeln!(io::stderr(), "{miss}");
if json {
writeln_stdout(
&serde_json::to_string_pretty(&miss).map_err(|e| e.to_string())?,
)?;
}
Ok(ExitCode::from(2))
}
}
}
Cmd::Why {
name,
json,
context,
context_tokens,
discovery,
} => {
let (cwd, opts) = discovery_opts(&discovery)?;
let report = discover(&cwd, &opts);
let budgets = progressive_budgets(context_tokens);
let why = why(&report, name.as_deref(), context.as_deref(), Some(budgets));
if let Some(miss) = why.unknown_skill_miss() {
let _ = writeln!(io::stderr(), "{miss}");
if json {
writeln_stdout(
&serde_json::to_string_pretty(&miss).map_err(|e| e.to_string())?,
)?;
}
return Ok(ExitCode::from(2));
}
if json {
writeln_stdout(&serde_json::to_string_pretty(&why).map_err(|e| e.to_string())?)?;
} else {
write_stdout(&format_why_text(&why))?;
if report.skills.is_empty() && report.skips.is_empty() {
write_empty_tree_note(&cwd, &opts);
}
}
Ok(ExitCode::SUCCESS)
}
Cmd::Validate { path, strict, json } => {
let report = validate_path_with_options(&path, strict);
if report.ok {
if json {
writeln_stdout(
&serde_json::to_string_pretty(&report).map_err(|e| e.to_string())?,
)?;
} else {
writeln_stdout(&format!("ok\t{}", report.name.as_deref().unwrap_or("-")))?;
}
Ok(ExitCode::SUCCESS)
} else if let (true, Some(miss)) = (json, report.miss()) {
let _ = writeln!(io::stderr(), "{miss}");
writeln_stdout(&serde_json::to_string_pretty(&miss).map_err(|e| e.to_string())?)?;
Ok(ExitCode::from(1))
} else {
for e in &report.errors {
let _ = writeln!(io::stderr(), "{e}");
}
Ok(ExitCode::from(1))
}
}
}
}
enum ListOutput {
Tsv,
Json,
Xml,
Catalog,
Watch,
}
fn list_output_mode(
json: bool,
xml: bool,
catalog: bool,
watch: bool,
format: Option<String>,
) -> Result<ListOutput, String> {
if let Some(format) = format {
return Ok(match parse_list_format(&format)? {
ListFormat::Json => ListOutput::Json,
ListFormat::Xml => ListOutput::Xml,
ListFormat::Catalog => ListOutput::Catalog,
ListFormat::Watch => ListOutput::Watch,
});
}
if watch {
return Ok(ListOutput::Watch);
}
if catalog {
return Ok(ListOutput::Catalog);
}
if xml {
return Ok(ListOutput::Xml);
}
if json {
return Ok(ListOutput::Json);
}
Ok(ListOutput::Tsv)
}
fn discovery_opts(discovery: &DiscoveryArgs) -> Result<(PathBuf, DiscoveryOptions), String> {
let cwd = std::env::current_dir().map_err(|e| e.to_string())?;
let vendor_roots = SkillSource::parse_vendor_roots(&discovery.vendor)?;
let opts = DiscoveryOptions {
paths: discovery.paths.clone(),
ignore: discovery.ignore.clone(),
disabled: discovery.disabled.clone(),
vendor_roots,
user_skills_dir: discovery.user_dir.clone(),
ascii_names: discovery.ascii_names,
implicit_roots: !discovery.no_implicit_roots,
};
Ok((cwd, opts))
}
fn write_empty_tree_note(cwd: &std::path::Path, opts: &DiscoveryOptions) {
let dirs = watch_dirs(cwd, opts);
let _ = writeln!(io::stderr(), "no skills found. searched:");
if dirs.is_empty() {
let _ = writeln!(
io::stderr(),
" (no walk roots; pass --path DIR for a collection)"
);
} else {
for dir in dirs {
let _ = writeln!(
io::stderr(),
" {}",
craftbag::sanitize_error_token(&dir.display().to_string())
);
}
}
let _ = writeln!(
io::stderr(),
"hint: a skill is a directory containing SKILL.md; pass --path DIR for a collection root"
);
}
fn discover_cwd(discovery: &DiscoveryArgs) -> Result<craftbag::DiscoveryReport, String> {
let (cwd, opts) = discovery_opts(discovery)?;
Ok(discover(&cwd, &opts))
}