railwayapp 4.54.0

Interact with Railway via CLI
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
use super::*;
use crate::consts::get_user_agent;
use crate::util::progress::{create_spinner, fail_spinner, success_spinner};
use flate2::read::GzDecoder;
use std::collections::HashMap;
use std::io::{Cursor, Read};
use std::path::{Path, PathBuf};

const TARBALL_URL: &str =
    "https://github.com/railwayapp/railway-skills/archive/refs/heads/main.tar.gz";
const SKILLS_PATH_PREFIX: &str = "plugins/railway/skills/";

/// Install Railway agent skills for AI coding tools (Claude Code, Cursor, Codex, OpenCode, GitHub Copilot, Factory Droid, and all tools that support .agents/skills)
///
/// Always installs to ~/.agents/skills. Additionally installs to any detected tool directories (e.g. ~/.claude/skills, ~/.cursor/skills). Use --agent to target specific tools instead of auto-detection.
#[derive(Parser)]
pub struct Args {
    #[clap(subcommand)]
    command: Option<Commands>,

    /// Target specific agent(s) instead of all detected (e.g. --agent claude-code)
    #[clap(long, global = true)]
    agent: Vec<String>,
}

#[derive(Parser)]
enum Commands {
    /// Install Railway agent skills for AI coding tools (Claude Code, Cursor, Codex, OpenCode, GitHub Copilot, Factory Droid, and all tools that support .agents/skills)
    ///
    /// Always installs to ~/.agents/skills. Additionally installs to any detected tool directories (e.g. ~/.claude/skills, ~/.cursor/skills). Use --agent to target specific tools instead of auto-detection.
    #[clap(visible_alias = "update", visible_alias = "add")]
    Install,
    /// Remove Railway skills from all tools
    #[clap(visible_alias = "rm", visible_alias = "uninstall")]
    Remove,
}

#[derive(Clone)]
pub(super) struct CodingTool {
    pub slug: &'static str,
    pub name: &'static str,
    pub global_parent: PathBuf,
    skills_dir_name: &'static str,
}

struct InstallTarget {
    tool_name: String,
    skills_dir: PathBuf,
}

type SkillFiles = HashMap<String, Vec<(PathBuf, Vec<u8>)>>;

pub async fn command(args: Args) -> Result<()> {
    match args.command {
        None | Some(Commands::Install) => install_skills(&args.agent).await,
        Some(Commands::Remove) => remove_skills(&args.agent).await,
    }
}

pub(super) fn coding_tools(home: &Path) -> Vec<CodingTool> {
    vec![
        CodingTool {
            slug: "universal",
            name: "Universal (.agents)",
            global_parent: home.join(".agents"),
            skills_dir_name: "skills",
        },
        CodingTool {
            slug: "claude-code",
            name: "Claude Code",
            global_parent: home.join(".claude"),
            skills_dir_name: "skills",
        },
        CodingTool {
            slug: "codex",
            name: "OpenAI Codex",
            global_parent: home.join(".codex"),
            skills_dir_name: "skills",
        },
        CodingTool {
            slug: "opencode",
            name: "OpenCode",
            global_parent: home.join(".config").join("opencode"),
            skills_dir_name: "skills",
        },
        CodingTool {
            slug: "copilot",
            name: "GitHub Copilot",
            global_parent: home.join(".copilot"),
            skills_dir_name: "skills",
        },
        CodingTool {
            slug: "factory-droid",
            name: "Factory Droid",
            global_parent: home.join(".factory"),
            skills_dir_name: "skills",
        },
        CodingTool {
            slug: "cursor",
            name: "Cursor",
            global_parent: home.join(".cursor"),
            skills_dir_name: "skills",
        },
    ]
}

pub(super) fn resolve_tools(home: &Path, agent_filter: &[String]) -> Result<Vec<CodingTool>> {
    let all_tools = coding_tools(home);

    if agent_filter.is_empty() {
        // "agents" (universal) is always included; others require their config dir to exist.
        Ok(all_tools
            .into_iter()
            .filter(|tool| tool.slug == "universal" || tool.global_parent.is_dir())
            .collect())
    } else {
        let mut selected = Vec::new();
        for slug in agent_filter {
            match all_tools.iter().find(|t| t.slug == slug.as_str()) {
                Some(t) => selected.push(t.clone()),
                None => {
                    let valid = all_tools
                        .iter()
                        .map(|t| t.slug)
                        .collect::<Vec<_>>()
                        .join(", ");
                    bail!("Unknown agent: '{}'\n\nValid agents: {}", slug, valid);
                }
            }
        }
        Ok(selected)
    }
}

pub(super) fn skills_configured_for_slug(home: &Path, slug: &str) -> bool {
    coding_tools(home)
        .into_iter()
        .find(|tool| tool.slug == slug)
        .map(|tool| {
            tool.global_parent
                .join(tool.skills_dir_name)
                .join("use-railway")
        })
        .is_some_and(|path| path.is_dir())
}

fn build_targets(tools: &[CodingTool]) -> Vec<InstallTarget> {
    tools
        .iter()
        .map(|tool| InstallTarget {
            tool_name: tool.name.to_string(),
            skills_dir: tool.global_parent.join(tool.skills_dir_name),
        })
        .collect()
}

fn print_target_summary(action: &str, targets: &[InstallTarget]) {
    let target_names = targets
        .iter()
        .map(|target| target.tool_name.as_str())
        .collect::<Vec<_>>()
        .join(", ");

    println!("{} {}\n", action.bold(), target_names);
}

async fn download_tarball() -> Result<Vec<u8>> {
    let client = reqwest::Client::new();
    let response = client
        .get(TARBALL_URL)
        .header("User-Agent", get_user_agent())
        .send()
        .await
        .context("Failed to download Railway skills")?;

    if !response.status().is_success() {
        bail!(
            "Failed to download Railway skills: HTTP {}",
            response.status()
        );
    }

    Ok(response
        .bytes()
        .await
        .context("Failed to read response body")?
        .to_vec())
}

/// Extract all skills from the tarball, grouped by skill name.
/// Returns a map of skill_name -> Vec<(relative_path, file_contents)>.
fn extract_skill_files(tarball_bytes: &[u8]) -> Result<SkillFiles> {
    let decoder = GzDecoder::new(Cursor::new(tarball_bytes));
    let mut archive = tar::Archive::new(decoder);
    let mut skills: SkillFiles = HashMap::new();

    for entry in archive
        .entries()
        .context("Failed to read tarball entries")?
    {
        let mut entry = entry.context("Failed to read tarball entry")?;
        let path_str = entry
            .path()
            .context("Failed to read entry path")?
            .to_string_lossy()
            .into_owned();

        if let Some(pos) = path_str.find(SKILLS_PATH_PREFIX) {
            let after_prefix = &path_str[pos + SKILLS_PATH_PREFIX.len()..];

            // Split into skill_name/relative_path
            let Some(slash_pos) = after_prefix.find('/') else {
                continue;
            };
            let skill_name = &after_prefix[..slash_pos];
            let relative = &after_prefix[slash_pos + 1..];

            if skill_name.is_empty() || relative.is_empty() || entry.header().entry_type().is_dir()
            {
                continue;
            }

            let mut contents = Vec::new();
            entry
                .read_to_end(&mut contents)
                .context("Failed to read file from tarball")?;

            skills
                .entry(skill_name.to_string())
                .or_default()
                .push((PathBuf::from(relative), contents));
        }
    }

    if skills.is_empty() {
        bail!("No skills found in downloaded repository");
    }

    Ok(skills)
}

fn write_skills_to_target(target: &InstallTarget, skills: &SkillFiles) -> Result<()> {
    for (skill_name, files) in skills {
        let dest = target.skills_dir.join(skill_name);

        if let Err(e) = std::fs::remove_dir_all(&dest) {
            if e.kind() != std::io::ErrorKind::NotFound {
                return Err(e).with_context(|| {
                    format!("Failed to remove existing skill at {}", dest.display())
                });
            }
        }

        for (relative_path, contents) in files {
            let file_path = dest.join(relative_path);
            if let Some(parent) = file_path.parent() {
                std::fs::create_dir_all(parent)
                    .with_context(|| format!("Failed to create directory {}", parent.display()))?;
            }
            std::fs::write(&file_path, contents)
                .with_context(|| format!("Failed to write {}", file_path.display()))?;
        }
    }

    Ok(())
}

pub(super) async fn install_skills(agent_filter: &[String]) -> Result<()> {
    let home = dirs::home_dir().context("could not determine home directory")?;
    let tools = resolve_tools(&home, agent_filter)?;
    let targets = build_targets(&tools);

    println!("\n{}\n", "Railway Skills".bold());
    print_target_summary("Installing to:", &targets);

    let mut spinner = create_spinner("Downloading skills...".to_string());
    let tarball_bytes = match download_tarball().await {
        Ok(bytes) => {
            success_spinner(&mut spinner, "Downloaded skills".to_string());
            bytes
        }
        Err(e) => {
            fail_spinner(&mut spinner, "Failed to download skills".to_string());
            return Err(e);
        }
    };

    let skills = extract_skill_files(&tarball_bytes)?;
    let mut skill_names: Vec<&String> = skills.keys().collect();
    skill_names.sort();

    println!();

    for target in &targets {
        std::fs::create_dir_all(&target.skills_dir).with_context(|| {
            format!(
                "Failed to create skills directory {}",
                target.skills_dir.display()
            )
        })?;

        write_skills_to_target(target, &skills)?;

        for skill_name in &skill_names {
            let skill_path = target.skills_dir.join(skill_name);
            println!(
                "{} {}: installed {} \u{2192} {}",
                "\u{2713}".green(),
                target.tool_name.bold(),
                skill_name.green(),
                skill_path.display().to_string().cyan()
            );
        }
    }

    println!("\n{}", "Skills installed successfully!".green().bold());
    println!(
        "{} You may need to restart your tool(s) to load skills.\n",
        "!".yellow().bold()
    );

    Ok(())
}

// Remove fetches the skill list from the upstream repo rather than keeping a
// local manifest. The skills/ directory is shared with other providers, so we
// can't blindly delete everything — we need to know which subdirectories are
// ours. Using the repo as the source of truth avoids stale manifests when
// skills are renamed upstream.
async fn remove_skills(agent_filter: &[String]) -> Result<()> {
    let home = dirs::home_dir().context("could not determine home directory")?;
    let tools = resolve_tools(&home, agent_filter)?;
    let targets = build_targets(&tools);

    println!("\n{}\n", "Railway Skills".bold());
    print_target_summary("Removing from:", &targets);

    let mut spinner = create_spinner("Fetching skill list...".to_string());
    let tarball_bytes = match download_tarball().await {
        Ok(bytes) => {
            success_spinner(&mut spinner, "Fetched skill list".to_string());
            bytes
        }
        Err(e) => {
            fail_spinner(&mut spinner, "Failed to fetch skill list".to_string());
            return Err(e);
        }
    };

    let skills = extract_skill_files(&tarball_bytes)?;
    let mut skill_names: Vec<&String> = skills.keys().collect();
    skill_names.sort();

    println!();

    let mut removed_any = false;

    for target in &targets {
        for skill_name in &skill_names {
            let skill_dir = target.skills_dir.join(skill_name);
            match std::fs::remove_dir_all(&skill_dir) {
                Ok(()) => {
                    println!(
                        "{} {}: removed {}",
                        "\u{2713}".green(),
                        target.tool_name.bold(),
                        skill_name.red()
                    );
                    removed_any = true;
                }
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                    println!(
                        "{} {}: {} not installed, skipping",
                        "-".dimmed(),
                        target.tool_name,
                        skill_name
                    );
                }
                Err(e) => {
                    return Err(e).with_context(|| {
                        format!("Failed to remove skill at {}", skill_dir.display())
                    });
                }
            }
        }
    }

    if removed_any {
        println!("\n{}\n", "Skills removed successfully.".green().bold());
    } else {
        println!("\n{}\n", "No skills were installed.".dimmed());
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn detects_existing_use_railway_skill() {
        let home = tempfile::tempdir().unwrap();
        let path = home
            .path()
            .join(".agents")
            .join("skills")
            .join("use-railway");
        std::fs::create_dir_all(&path).unwrap();

        assert!(skills_configured_for_slug(home.path(), "universal"));
        assert!(!skills_configured_for_slug(home.path(), "cursor"));
    }

    #[test]
    fn detects_copilot_and_factory_droid_skills() {
        let home = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(
            home.path()
                .join(".copilot")
                .join("skills")
                .join("use-railway"),
        )
        .unwrap();
        std::fs::create_dir_all(
            home.path()
                .join(".factory")
                .join("skills")
                .join("use-railway"),
        )
        .unwrap();

        assert!(skills_configured_for_slug(home.path(), "copilot"));
        assert!(skills_configured_for_slug(home.path(), "factory-droid"));
    }
}