use std::io::{BufRead, IsTerminal, Write};
use std::path::{Path, PathBuf};
use anyhow::Context as _;
use clap::Args;
use serde_json::{Map, Value, json};
use crate::app::context::Ctx;
use crate::claude::seats::Seat;
use crate::core::harness::Harness;
use crate::ui::style::Tone;
#[derive(Args, Debug, Clone)]
pub struct SetupArgs {
#[arg(long, short)]
pub yes: bool,
#[arg(long)]
pub remove: bool,
#[arg(long)]
pub no_vault: bool,
#[arg(long)]
pub guard: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub enum StatusLine {
None,
Swarmy { wraps: Option<String> },
Other(String),
}
pub fn settings_file(seat: &Seat) -> PathBuf {
seat.dir.join("settings.json")
}
fn read_settings(path: &Path) -> anyhow::Result<Map<String, Value>> {
match std::fs::read_to_string(path) {
Ok(t) if t.trim().is_empty() => Ok(Map::new()),
Ok(t) => match serde_json::from_str::<Value>(&t) {
Ok(Value::Object(m)) => Ok(m),
Ok(_) | Err(_) => {
Err(crate::errors::SetupError::SettingsDamaged(path.to_path_buf()).into())
}
},
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Map::new()),
Err(e) => Err(e).with_context(|| format!("cannot read {}", path.display())),
}
}
pub fn status_line_of(settings: &Map<String, Value>) -> StatusLine {
let Some(cmd) = settings
.get("statusLine")
.and_then(|s| s.get("command"))
.and_then(Value::as_str)
else {
return StatusLine::None;
};
match cmd.find(" statusline") {
Some(_) if cmd.contains("swarmy") => StatusLine::Swarmy {
wraps: wrapped(cmd),
},
_ => StatusLine::Other(cmd.to_string()),
}
}
pub fn seat_status_line(seat: &Seat) -> StatusLine {
read_settings(&settings_file(seat))
.map(|s| status_line_of(&s))
.unwrap_or(StatusLine::None)
}
fn sh_quote(s: &str) -> String {
format!("'{}'", s.replace('\'', r"'\''"))
}
fn wrapped(cmd: &str) -> Option<String> {
let rest = cmd.split_once("--then ")?.1.trim();
let inner = rest.strip_prefix('\'')?.strip_suffix('\'')?;
Some(inner.replace(r"'\''", "'"))
}
fn exe_word(exe: &Path) -> String {
let exe = exe.to_string_lossy();
if exe.contains(' ') {
format!("\"{exe}\"")
} else {
exe.into_owned()
}
}
pub fn command_for(exe: &Path, previous: Option<&str>) -> String {
let exe = exe_word(exe);
match previous {
Some(p) => format!("{exe} statusline --then {}", sh_quote(p)),
None => format!("{exe} statusline"),
}
}
pub fn with_status_line(
mut settings: Map<String, Value>,
exe: &Path,
remove: bool,
refresh: u32,
) -> Option<Map<String, Value>> {
let current_refresh = settings
.get("statusLine")
.and_then(|s| s.get("refreshInterval"))
.and_then(Value::as_u64);
match (status_line_of(&settings), remove) {
(StatusLine::Swarmy { .. }, false) => {
if refresh == 0 || current_refresh.is_some() {
return None;
}
settings["statusLine"]["refreshInterval"] = json!(refresh);
Some(settings)
}
(StatusLine::None | StatusLine::Other(_), true) => None,
(StatusLine::None, false) => {
let mut sl = json!({"type": "command", "command": command_for(exe, None)});
if refresh > 0 {
sl["refreshInterval"] = json!(refresh);
}
settings.insert("statusLine".into(), sl);
Some(settings)
}
(StatusLine::Other(prev), false) => {
let mut sl = settings
.get("statusLine")
.cloned()
.unwrap_or_else(|| json!({}));
sl["command"] = Value::String(command_for(exe, Some(&prev)));
if refresh > 0 && sl.get("refreshInterval").is_none() {
sl["refreshInterval"] = json!(refresh);
}
settings.insert("statusLine".into(), sl);
Some(settings)
}
(StatusLine::Swarmy { wraps }, true) => {
match wraps {
Some(prev) => {
let mut sl = settings
.get("statusLine")
.cloned()
.unwrap_or_else(|| json!({}));
sl["command"] = Value::String(prev);
if let Some(o) = sl.as_object_mut() {
o.remove("refreshInterval");
}
settings.insert("statusLine".into(), sl);
}
None => {
settings.remove("statusLine");
}
}
Some(settings)
}
}
}
const GUARD_TIMEOUT_S: u64 = 5;
pub fn is_guard_command(cmd: &str) -> bool {
cmd.contains("swarmy") && cmd.trim_end().ends_with(" guard")
}
pub fn guard_command(exe: &Path) -> String {
format!("{} guard", exe_word(exe))
}
fn pre_tool_commands(settings: &Map<String, Value>) -> Vec<&str> {
settings
.get("hooks")
.and_then(|h| h.get("PreToolUse"))
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|group| group.get("hooks").and_then(Value::as_array))
.flatten()
.filter_map(|h| h.get("command").and_then(Value::as_str))
.collect()
}
pub fn has_guard(settings: &Map<String, Value>) -> bool {
pre_tool_commands(settings)
.into_iter()
.any(is_guard_command)
}
pub fn seat_has_guard(seat: &Seat) -> bool {
read_settings(&settings_file(seat)).is_ok_and(|s| has_guard(&s))
}
pub fn with_guard_hook(
mut settings: Map<String, Value>,
exe: &Path,
remove: bool,
) -> Result<Option<Map<String, Value>>, String> {
let shape = "its \"hooks\" is not the shape Claude Code reads; left as it is";
if remove {
if !has_guard(&settings) {
return Ok(None);
}
let Some(hooks) = settings.get_mut("hooks").and_then(Value::as_object_mut) else {
return Err(shape.into());
};
let Some(groups) = hooks.get_mut("PreToolUse").and_then(Value::as_array_mut) else {
return Err(shape.into());
};
for g in groups.iter_mut() {
if let Some(list) = g.get_mut("hooks").and_then(Value::as_array_mut) {
list.retain(|h| {
!h.get("command")
.and_then(Value::as_str)
.is_some_and(is_guard_command)
});
}
}
groups.retain(|g| {
g.get("hooks")
.and_then(Value::as_array)
.is_none_or(|l| !l.is_empty())
});
if groups.is_empty() {
hooks.remove("PreToolUse");
}
if hooks.is_empty() {
settings.remove("hooks");
}
return Ok(Some(settings));
}
if has_guard(&settings) {
return Ok(None);
}
let hooks = settings
.entry("hooks")
.or_insert_with(|| json!({}))
.as_object_mut()
.ok_or(shape)?;
let groups = hooks
.entry("PreToolUse")
.or_insert_with(|| json!([]))
.as_array_mut()
.ok_or(shape)?;
groups.push(json!({
"matcher": "*",
"hooks": [{"type": "command", "command": guard_command(exe), "timeout": GUARD_TIMEOUT_S}],
}));
Ok(Some(settings))
}
fn write_settings(path: &Path, settings: &Map<String, Value>) -> anyhow::Result<Option<PathBuf>> {
let backup = if path.exists() {
let stamp = chrono::Local::now().format("%Y%m%d-%H%M%S");
let mut b = path.with_extension(format!("json.swarmy-{stamp}.bak"));
let mut n = 1;
while b.exists() {
b = path.with_extension(format!("json.swarmy-{stamp}-{n}.bak"));
n += 1;
}
std::fs::copy(path, &b).with_context(|| format!("cannot back up {}", path.display()))?;
Some(b)
} else {
None
};
let mut text = serde_json::to_string_pretty(&Value::Object(settings.clone()))?;
text.push('\n');
crate::fsutil::atomic_write(path, text.as_bytes(), crate::fsutil::Mode::KeepExisting)
.with_context(|| format!("cannot write {}", path.display()))?;
Ok(backup)
}
fn ask(question: &str, yes: bool) -> bool {
if yes {
println!("{question} [Y/n] y");
return true;
}
print!("{question} [Y/n] ");
let _ = std::io::stdout().flush();
let mut line = String::new();
if std::io::stdin().lock().read_line(&mut line).is_err() {
return false;
}
!matches!(line.trim().to_lowercase().as_str(), "n" | "no")
}
pub fn run(ctx: &Ctx, a: &SetupArgs) -> anyhow::Result<()> {
let p = &ctx.painter;
if !a.yes && !std::io::stdin().is_terminal() {
anyhow::bail!("setup asks questions: run it in a terminal, or with --yes");
}
let home = &ctx.dirs.home;
let show = |path: &Path| match path.strip_prefix(home) {
Ok(rest) => format!("~/{}", rest.display()),
Err(_) => path.display().to_string(),
};
println!("{}", p.paint("swarmy setup", Tone::Header));
let claude_seats: Vec<&Seat> = ctx
.seats
.iter()
.filter(|s| s.harness.supports_statusline())
.collect();
if a.guard {
return guard_step(ctx, a, &claude_seats, &show);
}
'statusline: {
if claude_seats.is_empty() {
println!("No Claude Code config dir found: no status line to install.");
break 'statusline;
}
println!("\nClaude Code config dirs (seats) found:");
for s in &claude_seats {
let state = match seat_status_line(s) {
StatusLine::None => p.paint("no status line", Tone::Dim),
StatusLine::Swarmy { .. } => p.paint("swarmy status line ✓", Tone::Good),
StatusLine::Other(_) => p.paint("has its own status line", Tone::Dim),
};
println!(" {:<12} {:<34} {state}", s.label, show(&s.dir));
}
let exe = std::env::current_exe().context("cannot find the swarmy binary")?;
let exe = crate::fsutil::canonical(&exe).unwrap_or(exe);
let todo: Vec<&Seat> = claude_seats
.iter()
.copied()
.filter(|s| match read_settings(&settings_file(s)) {
Ok(settings) => with_status_line(
settings,
&exe,
a.remove,
ctx.config.statusline.refresh_seconds,
)
.is_some(),
Err(e) => {
println!(" {} {e:#}", p.paint("skipped:", Tone::Warn));
false
}
})
.collect();
println!();
if todo.is_empty() {
println!(
"{}",
if a.remove {
"No seat has the swarmy status line."
} else {
"Every seat already has the swarmy status line."
}
);
} else {
let q = if a.remove {
format!("Take the swarmy status line out of {} seat(s)?", todo.len())
} else {
println!(
"The swarmy status line shows week and 5-hour use under Claude Code's prompt, and"
);
println!(
"gives swarmy the exact limits after every response (no network, nothing else changes)."
);
println!("A status line you already have stays and is shown first.");
let fresh = todo
.iter()
.filter(|s| !matches!(seat_status_line(s), StatusLine::Swarmy { .. }))
.count();
if fresh == 0 {
format!(
"Update the swarmy status line in {} seat(s) (refresh every {} s)?",
todo.len(),
ctx.config.statusline.refresh_seconds
)
} else {
format!("Add it to {} seat(s)?", todo.len())
}
};
if ask(&q, a.yes) {
for s in todo {
let path = settings_file(s);
let settings = read_settings(&path)?;
if let Some(new) = with_status_line(
settings,
&exe,
a.remove,
ctx.config.statusline.refresh_seconds,
) {
let backup = write_settings(&path, &new)?;
println!(
" {} {}{}",
p.paint("✓", Tone::Good),
show(&path),
backup
.map(|b| format!(" (backup: {})", show(&b)))
.unwrap_or_default()
);
}
}
if !a.remove {
println!(" Claude Code shows it with the next response (or after a restart).");
}
}
}
}
if a.remove && !claude_seats.is_empty() {
guard_step(ctx, a, &claude_seats, &show)?;
}
if !a.remove
&& !a.no_vault
&& ctx.seats.iter().any(|s| s.harness == Harness::Claude)
&& let Some(e) = crate::vault::unavailable(Harness::Claude)
{
println!(
"{}",
ctx.painter.paint(&format!("Saved logins: {e}."), Tone::Dim)
);
}
if !a.remove && !a.no_vault {
let mut v = crate::vault::Vault::open(&ctx.dirs.vault_dir())?;
let vault_seats: Vec<Seat> = ctx
.seats
.iter()
.filter(|s| s.harness.supports_vault())
.cloned()
.collect();
let states = v.edit(|tx| tx.seat_states(&vault_seats))?;
let unsaved: Vec<&Seat> = ctx
.seats
.iter()
.filter(|s| {
s.harness.supports_vault()
&& states
.get(&s.id)
.is_some_and(|st| st.fingerprint.is_some() && st.saved_as.is_none())
})
.collect();
if !unsaved.is_empty() {
println!();
println!(
"Saving a seat's login lets you put another account into it when a limit runs out,"
);
println!(
"and switch back later (dashboard: panel 2, Enter; or `swarmy accounts switch`)."
);
for s in unsaved {
if ask(
&format!("Save the login of seat '{}' in the vault?", s.label),
a.yes,
) {
match v.edit(|tx| tx.capture(s, None))? {
Some(id) => println!(
" {} saved as '{}'",
p.paint("✓", Tone::Good),
v.logins()
.iter()
.find(|l| l.id == id)
.map(|l| l.label.as_str())
.unwrap_or("?")
),
None => println!(" no login in this seat"),
}
}
}
}
}
println!(
"\nDone. Run {} for the dashboard, {} for keys and a legend.",
p.paint("swarmy", Tone::Accent),
p.paint("?", Tone::Accent)
);
Ok(())
}
fn guard_step(
ctx: &Ctx,
a: &SetupArgs,
seats: &[&Seat],
show: &dyn Fn(&Path) -> String,
) -> anyhow::Result<()> {
let p = &ctx.painter;
if seats.is_empty() {
println!("No Claude Code config dir found: no seat to guard.");
return Ok(());
}
let exe = std::env::current_exe().context("cannot find the swarmy binary")?;
let exe = crate::fsutil::canonical(&exe).unwrap_or(exe);
let mut readable: Vec<(&Seat, Map<String, Value>)> = Vec::new();
for s in seats {
match read_settings(&settings_file(s)) {
Ok(st) => readable.push((s, st)),
Err(e) => println!(" {} {e:#}", p.paint("skipped:", Tone::Warn)),
}
}
if a.remove {
let todo: Vec<&Seat> = readable
.iter()
.filter(|(_, st)| has_guard(st))
.map(|(s, _)| *s)
.collect();
if todo.is_empty() {
println!("No seat has the guard hook.");
} else if ask(
&format!("Take the guard hook out of {} seat(s)?", todo.len()),
a.yes,
) {
for s in todo {
apply_guard(ctx, s, &exe, true, show)?;
}
}
return Ok(());
}
println!();
println!("The limit guard: before every tool call in a guarded seat, Claude Code asks swarmy");
println!(
"whether the account has reached the line set in config.toml [guard]. Agents are told"
);
println!(
"once to wrap up a few points before it, and stop at it. A seat without the guard keeps"
);
println!("working, so the rest of the limit stays yours there.");
println!();
for (s, st) in &readable {
let row = format!(" {:<12} {:<34}", s.label, show(&s.dir));
if has_guard(st) {
println!("{row} {}", p.paint("guarded ✓", Tone::Good));
} else if !matches!(status_line_of(st), StatusLine::Swarmy { .. }) {
println!(
"{row} {}",
p.paint(
"needs the swarmy status line first (swarmy setup)",
Tone::Dim
)
);
} else if ask(&format!("{row} guard it?"), a.yes) {
apply_guard(ctx, s, &exe, false, show)?;
}
}
if ctx.config.guard.is_set() {
println!(" New Claude Code sessions use it; restart the running ones.");
println!(" `swarmy doctor` shows the line of every account.");
} else {
println!(
"\nNo line is set yet: the guard lets everything through. Add one to {}:",
show(&ctx.dirs.config_file())
);
println!(" [guard]");
println!(" week = 85 # agents stop at 85% of the week, on every account");
println!(" # wrap_up = 5 # and are told to wrap up 5 points before");
println!(
" # [guard.account.personal] # one account's line: saved login label or email, or uuid"
);
println!(" # week = 80");
}
Ok(())
}
fn apply_guard(
ctx: &Ctx,
s: &Seat,
exe: &Path,
remove: bool,
show: &dyn Fn(&Path) -> String,
) -> anyhow::Result<()> {
let p = &ctx.painter;
let path = settings_file(s);
match with_guard_hook(read_settings(&path)?, exe, remove) {
Ok(Some(new)) => {
let backup = write_settings(&path, &new)?;
println!(
" {} {}{}",
p.paint("✓", Tone::Good),
show(&path),
backup.map_or(String::new(), |b| format!(" (backup: {})", show(&b)))
);
}
Ok(None) => {}
Err(why) => println!(
" {} {}: {why}",
p.paint("skipped:", Tone::Warn),
show(&path)
),
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn obj(v: Value) -> Map<String, Value> {
v.as_object().unwrap().clone()
}
#[test]
fn adds_wraps_and_removes_the_status_line() {
let exe = Path::new("/opt/bin/swarmy");
let s = with_status_line(obj(json!({"model": "opus"})), exe, false, 0).unwrap();
assert_eq!(s["statusLine"]["command"], "/opt/bin/swarmy statusline");
assert_eq!(s["model"], "opus");
assert_eq!(
with_status_line(s.clone(), exe, false, 0),
None,
"already there"
);
let timed = with_status_line(s.clone(), exe, false, 10).unwrap();
assert_eq!(timed["statusLine"]["refreshInterval"], 10);
let theirs = r#"bash -c 'echo it'"'"'s me'"#;
let s = obj(json!({"statusLine": {"type": "command", "command": theirs, "padding": 1}}));
let w = with_status_line(s, exe, false, 0).unwrap();
let cmd = w["statusLine"]["command"].as_str().unwrap();
assert!(
cmd.starts_with("/opt/bin/swarmy statusline --then '"),
"{cmd}"
);
assert_eq!(w["statusLine"]["padding"], 1);
assert_eq!(
status_line_of(&w),
StatusLine::Swarmy {
wraps: Some(theirs.to_string())
}
);
let back = with_status_line(w, exe, true, 0).unwrap();
assert_eq!(back["statusLine"]["command"], theirs);
let mine = with_status_line(obj(json!({})), exe, false, 10).unwrap();
assert!(
!with_status_line(mine, exe, true, 10)
.unwrap()
.contains_key("statusLine")
);
}
#[test]
fn adds_and_removes_the_guard_hook_beside_other_hooks() {
let exe = Path::new("/opt/bin/swarmy");
let s = with_guard_hook(obj(json!({"model": "opus"})), exe, false)
.unwrap()
.unwrap();
assert_eq!(s["model"], "opus");
let group = &s["hooks"]["PreToolUse"][0];
assert_eq!(group["matcher"], "*");
assert_eq!(group["hooks"][0]["type"], "command");
assert_eq!(group["hooks"][0]["command"], "/opt/bin/swarmy guard");
assert_eq!(group["hooks"][0]["timeout"], GUARD_TIMEOUT_S);
assert!(has_guard(&s));
assert_eq!(
with_guard_hook(s.clone(), exe, false),
Ok(None),
"already there"
);
let back = with_guard_hook(s, exe, true).unwrap().unwrap();
assert!(!back.contains_key("hooks"), "{back:?}");
assert_eq!(
with_guard_hook(back, exe, true),
Ok(None),
"nothing to take out"
);
let theirs = obj(json!({"hooks": {
"PreToolUse": [{"matcher": "Bash", "hooks": [{"type": "command", "command": "check.sh"}]}],
"Stop": [{"hooks": [{"type": "command", "command": "notify.sh"}]}]
}}));
let with = with_guard_hook(theirs.clone(), exe, false)
.unwrap()
.unwrap();
assert_eq!(with["hooks"]["PreToolUse"].as_array().unwrap().len(), 2);
assert_eq!(with["hooks"]["PreToolUse"][0]["matcher"], "Bash");
let without = with_guard_hook(with, exe, true).unwrap().unwrap();
assert_eq!(without, theirs, "exactly what was there before");
let shared = obj(json!({"hooks": {"PreToolUse": [{"matcher": "*", "hooks": [
{"type": "command", "command": "check.sh"},
{"type": "command", "command": "/usr/local/bin/swarmy guard"}
]}]}}));
let left = with_guard_hook(shared, exe, true).unwrap().unwrap();
assert_eq!(
left["hooks"]["PreToolUse"][0]["hooks"],
json!([{"type": "command", "command": "check.sh"}])
);
}
#[test]
fn a_hooks_of_another_shape_is_left_alone() {
let exe = Path::new("/opt/bin/swarmy");
for odd in [json!({"hooks": "x"}), json!({"hooks": {"PreToolUse": {}}})] {
assert!(with_guard_hook(obj(odd), exe, false).is_err());
}
}
#[test]
fn the_guard_command_is_told_from_others() {
assert!(is_guard_command("/opt/bin/swarmy guard"));
assert!(is_guard_command("\"/opt/my tools/swarmy\" guard"));
assert!(!is_guard_command("/opt/bin/swarmy statusline"));
assert!(!is_guard_command("/usr/bin/guard"));
assert_eq!(
guard_command(Path::new("/opt/my tools/swarmy")),
"\"/opt/my tools/swarmy\" guard"
);
}
}