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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! Command-line interface.
pub mod accounts;
pub mod compact;
pub mod doctor;
pub mod limits;
pub mod models;
pub mod prices;
pub mod report;
pub mod setup;
use clap::{Args, CommandFactory, Parser, Subcommand, ValueEnum};
use crate::core::period::Period;
use crate::index::query::{Dim, Filter};
use crate::ui::style::{ColorChoice, Painter};
#[derive(Parser, Debug)]
#[command(
name = "swarmy",
version,
about = "Real-time analytics dashboard for coding agents (Claude Code, Antigravity, Codex): live swarm, history, API-equivalent spend, weekly limits, login vault",
long_about = None,
after_help = "Examples:
swarmy the live dashboard
swarmy limits limits per account and where they went
swarmy limits --seat current --format json this Claude Code's account, for agents
swarmy report -p 7d --by day --format csv spend per day as CSV
swarmy accounts switch work bob put saved login bob into seat work
swarmy setup --guard stop agents at a line in config.toml [guard]
report, models, prices and limits print --format table, json or csv.
Run `swarmy help <command>` for a command's options. Data never leaves this machine."
)]
pub struct Cli {
#[command(subcommand)]
pub command: Option<Command>,
/// When to use colours.
#[arg(long, value_enum, global = true, default_value_t = ColorChoice::Auto)]
pub color: ColorChoice,
/// Hide emails, names and full paths (for screenshots).
#[arg(long, global = true)]
pub mask: bool,
/// Skip the boot animation of the dashboard.
#[arg(long, global = true)]
pub no_boot: bool,
/// Low-power dashboard: fewer frames and refreshes (automatic on battery).
#[arg(long, global = true)]
pub eco: bool,
}
#[derive(Subcommand, Debug)]
pub enum Command {
/// API-equivalent spend grouped by project, account, model, agent, day…
Report(ReportArgs),
/// Usage statistics per model: cost, cache hits, thinking, effort mix, substitutions.
Models(PeriodFilterArgs),
/// Weekly / 5-hour limits per account: where they went and when they run out.
Limits {
/// Output: table for people, json for scripts and agents (adds seats, level, runs_out_at,
/// at_reset and the guard's line per window), csv with one row per account and window.
#[arg(long, value_enum, default_value_t = Format::Table)]
format: Format,
/// Projects to list per window (table and json).
#[arg(long, default_value_t = 8)]
top: usize,
/// Only the account this seat holds now: its label, its id, its dir, or `current` for the
/// seat of the Claude Code running this command (`CLAUDE_CONFIG_DIR`, else ~/.claude).
#[arg(long)]
seat: Option<String>,
/// Only this account: its uuid, its email or a saved login's label.
#[arg(long)]
account: Option<String>,
},
/// The login vault: save, switch and list OAuth logins across seats.
Accounts(accounts::AccountsArgs),
/// What was found on this machine and whether it is readable.
Doctor,
/// Roll per-request detail older than the raw window up into the archive and free the space.
Compact(compact::CompactArgs),
/// Optional: add the swarmy status line to Claude Code (exact limits), save logins; with
/// --guard, the limit guard that stops agents at a line you set.
Setup(setup::SetupArgs),
/// Jump to the Claude Code that has waited for you the longest (tmux, zellij, kitty, wezterm, iTerm2, Warp).
Jump {
/// Only list who waits, do not switch.
#[arg(long)]
list: bool,
},
/// Used by Claude Code's status line: records the limits it passes and prints a short line.
Statusline {
/// A status-line command to run first (the one you had before), with the same input.
#[arg(long)]
then: Option<String>,
},
/// Used by Claude Code's hook (`swarmy setup --guard`): tells agents to wrap up, then stops
/// them, when their account reaches the limit line set in config.toml (`[guard]`).
Guard,
/// The price in force for every model and its source.
Prices {
/// Output: table for people, json for scripts and agents, csv with one row per model.
#[arg(long, value_enum, default_value_t = Format::Table)]
format: Format,
},
/// Try the dashboard on a made-up world of agents (no real data is read).
Demo {
/// Record N frames headlessly into this file instead of opening the dashboard.
#[arg(long, hide = true)]
record: Option<std::path::PathBuf>,
#[arg(long, hide = true, default_value_t = 100)]
frames: usize,
#[arg(long, hide = true, default_value = "140x40")]
size: String,
/// Keys to press while recording: `frame:key,frame:key` (key `enter`, `esc` or a character).
#[arg(long, hide = true, default_value = "")]
keys: String,
/// The load of a busy 4K wall (three seats, ten days of history, about 18 agents at
/// work), for measuring the battery budget (`tools/perf.sh`).
#[arg(long, hide = true)]
wall: bool,
/// A Codex-only machine with an empty `~/.claude` (no login, no transcripts).
#[arg(long, hide = true)]
codex_only: bool,
},
/// Print shell completions.
Completions {
/// The shell to complete for.
#[arg(value_enum)]
shell: clap_complete::Shell,
},
/// Print the man page (roff).
Man,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum Format {
Table,
Json,
Csv,
}
#[derive(Args, Debug, Clone)]
pub struct FilterArgs {
/// Only this account: its uuid, its email or a saved login's label (resolved once; a name
/// that fits several accounts is an error that lists them).
#[arg(long)]
pub account: Option<String>,
/// Only this seat (its label, or its id from `swarmy doctor`).
#[arg(long)]
pub seat: Option<String>,
/// Only this harness (`claude`, `agy`, `codex`).
#[arg(long, value_enum)]
pub harness: Option<crate::core::harness::Harness>,
/// Only this project (name or path).
#[arg(long)]
pub project: Option<String>,
/// Only models whose id contains this.
#[arg(long)]
pub model: Option<String>,
/// Only work in linked git worktrees (`worktrees`) or outside them (`main`).
#[arg(long, value_enum)]
pub checkout: Option<CheckoutArg>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum CheckoutArg {
/// Linked git worktrees.
Worktrees,
/// Main checkouts (and dirs outside any repository).
Main,
}
impl FilterArgs {
/// The filter with what was typed resolved once, here at the edge: a seat label to its id,
/// an account uuid, email or login label to the account (review H7).
pub fn to_filter(
&self,
ctx: &crate::app::context::Ctx,
idx: &crate::index::Index,
) -> anyhow::Result<Filter> {
let seat = match &self.seat {
Some(s) => Some(ctx.resolve_seat(s)?.id.clone()),
None => None,
};
let account = match &self.account {
Some(a) => Some(ctx.resolve_account(idx, a)?),
None => None,
};
Ok(Filter {
account,
seat,
harness: self.harness,
project: self.project.clone(),
model: self.model.clone(),
in_worktree: self.checkout.map(|c| c == CheckoutArg::Worktrees),
})
}
}
#[derive(Args, Debug, Clone)]
pub struct PeriodFilterArgs {
/// today, yesterday, week (current limit window), month, all, 24h, 7d, YYYY-MM-DD, FROM..TO
#[arg(short, long, default_value = "week")]
pub period: Period,
#[command(flatten)]
pub filter: FilterArgs,
/// Output: table for people, json for scripts and agents, csv with one row per model.
#[arg(long, value_enum, default_value_t = Format::Table)]
pub format: Format,
}
#[derive(Args, Debug, Clone)]
pub struct ReportArgs {
/// Grouping.
#[arg(short, long, value_enum, default_value_t = Dim::Project)]
pub by: Dim,
/// today, yesterday, week (current limit window), month, all, 24h, 7d, YYYY-MM-DD, FROM..TO
#[arg(short, long, default_value = "week")]
pub period: Period,
#[command(flatten)]
pub filter: FilterArgs,
/// Rows to show (time groupings show all).
#[arg(long, default_value_t = 15)]
pub top: usize,
/// Output: table for people, json for scripts and agents (every row, with the period and
/// total), csv with one row per group.
#[arg(long, value_enum, default_value_t = Format::Table)]
pub format: Format,
}
pub fn run(cli: Cli) -> anyhow::Result<()> {
let painter = Painter::new(cli.color);
match cli.command {
Some(Command::Completions { shell }) => {
clap_complete::generate(shell, &mut Cli::command(), "swarmy", &mut std::io::stdout());
Ok(())
}
Some(Command::Jump { list }) => jump(list),
Some(Command::Statusline { then }) => {
// Runs after every model response: no index, no scanning, just record and print.
let dirs = crate::config::Dirs::resolve()?;
// A status line must never fail: a bad config.toml falls back to the defaults, and
// says so on the debug channel (`swarmy doctor` reports it too).
let config = crate::config::Config::load(&dirs).unwrap_or_else(|e| {
crate::diag::log("config", &format!("{e:#}"));
crate::config::Config::default()
});
crate::statusline::run(&dirs, &config, then.as_deref())
}
Some(Command::Guard) => {
guard();
Ok(())
}
Some(Command::Man) => {
clap_mangen::Man::new(Cli::command()).render(&mut std::io::stdout())?;
Ok(())
}
Some(Command::Demo {
record,
frames,
size,
keys,
wall,
codex_only,
}) => {
let dirs = crate::config::Dirs::resolve()?;
let load = if wall {
crate::demo::Load::Wall
} else if codex_only {
crate::demo::Load::CodexOnly
} else {
crate::demo::Load::Demo
};
let demo = crate::demo::start(&dirs.data.join("demo"), load)?;
let mut ctx = crate::app::context::Ctx::demo(painter, demo.seats.clone(), &demo.root)?;
ctx.mask = cli.mask;
// Saved logins, so the VAULT screen has something to show.
{
let mut v = crate::vault::Vault::open(&ctx.dirs.vault_dir())?;
for s in ctx.seats.iter().filter(|s| s.harness.supports_vault()) {
v.edit(|tx| tx.capture(s, Some(&format!("alex-{}", s.label))))?;
}
// A Codex-only machine has no other login: nothing keeps its empty seat shown.
if !codex_only {
let spare = crate::claude::credentials::Secret::new(serde_json::json!({
"accessToken": "demo-access-spare", "refreshToken": "demo-refresh-spare",
"refreshTokenExpiresAt": (chrono::Utc::now() + chrono::Duration::days(4)).timestamp_millis()
}));
let acct = crate::claude::config_json::Account {
account_uuid: "acc-demo-spare".into(),
email: Some("alex+spare@example.com".into()),
..Default::default()
};
v.edit(|tx| tx.put(&spare, Some(serde_json::json!({"accountUuid": "acc-demo-spare", "emailAddress": "alex+spare@example.com"})), Some(&acct), Some("alex-spare"), None))?;
// A second Google login for the agy seat.
let team = crate::claude::credentials::Secret::of(
crate::core::harness::Harness::Agy,
serde_json::json!({"token": {"access_token": "demo-agy-access-team", "refresh_token": "demo-agy-refresh-team",
"expiry": (chrono::Utc::now() + chrono::Duration::hours(1)).to_rfc3339()},
"auth_method": "consumer", "id_token_email": "alex.team@example.com"}),
);
let team_acct = crate::agy::account::account_of(team.expose());
v.edit(|tx| {
tx.put(&team, None, team_acct.as_ref(), Some("alex-g-team"), None)
})?;
}
// On the wall, one login serves two seats.
if wall && let Some(lab) = ctx.seats.iter().find(|s| s.label == "lab") {
v.edit(|tx| tx.switch(lab, "alex-work"))?;
}
}
// What the seats say now (the lab seat holds the work login), with account names
// from the saved logins just made: the index then sees the wall's seats as they are
// from its first pass, not a login change under the lab seat's sessions a while later.
ctx.reload_seat_info()?;
match record {
Some(out) => {
let (w, h) = size
.split_once('x')
.and_then(|(a, b)| Some((a.parse().ok()?, b.parse().ok()?)))
.unwrap_or((140, 40));
let keys: Vec<(usize, char)> = keys
.split(',')
.filter_map(|p| {
let (f, k) = p.split_once(':')?;
let c = match k {
"enter" => '\n',
"esc" => '\x1b',
k => k.chars().next()?,
};
Some((f.parse().ok()?, c))
})
.collect();
crate::tui::record(ctx, &out, w, h, frames, &keys)
}
None => crate::tui::run(ctx, cli.no_boot, cli.eco),
}
}
command => {
let ctx = crate::app::context::Ctx::load(painter, cli.mask)?;
match command {
Some(Command::Report(a)) => report::run(&ctx, &a),
Some(Command::Models(a)) => models::run(&ctx, &a),
Some(Command::Limits {
format,
top,
seat,
account,
}) => limits::run(
&ctx,
&limits::LimitsArgs {
format,
top,
seat: seat.as_deref(),
account: account.as_deref(),
},
),
Some(Command::Accounts(a)) => accounts::run(&ctx, &a),
Some(Command::Doctor) => doctor::run(&ctx),
Some(Command::Compact(a)) => compact::run(&ctx, &a),
Some(Command::Prices { format }) => prices::run(&ctx, format),
None => {
use std::io::IsTerminal;
if std::io::stdout().is_terminal() {
crate::tui::run(ctx, cli.no_boot, cli.eco)
} else {
limits::run(
&ctx,
&limits::LimitsArgs {
format: Format::Table,
top: 8,
seat: None,
account: None,
},
)
}
}
Some(Command::Setup(a)) => setup::run(&ctx, &a),
Some(
Command::Completions { .. }
| Command::Man
| Command::Demo { .. }
| Command::Statusline { .. }
| Command::Guard
| Command::Jump { .. },
) => {
unreachable!()
}
}
}
}
}
/// `swarmy guard`: runs before every tool call of a guarded seat, so it never fails: whatever
/// it cannot read lets the call go on (an exit code of 2 would refuse it). `SWARMY_GUARD=off`
/// in Claude Code's environment lets everything through.
fn guard() {
use std::io::Read;
let Ok(dirs) = crate::config::Dirs::resolve() else {
return;
};
let config = crate::config::Config::load(&dirs).unwrap_or_else(|e| {
crate::diag::log("config", &format!("{e:#}"));
crate::config::Config::default()
});
let mut text = String::new();
if let Err(e) = std::io::stdin().read_to_string(&mut text) {
crate::diag::log("guard", &format!("stdin: {e}"));
}
let bypass = std::env::var("SWARMY_GUARD").is_ok_and(|v| {
matches!(
v.trim().to_ascii_lowercase().as_str(),
"off" | "0" | "no" | "false"
)
});
let answer = crate::guard::run(&dirs, &config, &text, chrono::Utc::now(), bypass);
if let Some(json) = answer.json() {
println!("{json}");
}
}
/// `swarmy jump`: the oldest session that waits for the user, from the dashboard's summary when
/// it runs, else straight from the session registries.
fn jump(list: bool) -> anyhow::Result<()> {
let dirs = crate::config::Dirs::resolve()?;
let config = crate::config::Config::load(&dirs)?;
let now = chrono::Utc::now();
use crate::core::pane::Pane;
// (name, what, pane)
let waiting: Vec<(String, String, Option<Pane>)> = match crate::fleet::read_fresh(
&crate::fleet::path(&dirs.data),
config.statusline.fresh_seconds,
now,
) {
Some(f) => f
.needs_you
.into_iter()
.map(|n| (n.name, n.what, n.pane))
.collect(),
None => {
// Every seat the dashboard would find, short of running processes.
let env_dir = crate::statusline::current_config_dir(&dirs.home);
let mut found: Vec<(String, String, Option<crate::core::pane::Pane>)> =
crate::claude::seats::discover(&crate::claude::seats::Candidates {
home: &dirs.home,
env_dirs: vec![env_dir],
configured: config.seats_of(&dirs.home, crate::core::harness::Harness::Claude),
})
.iter()
.flat_map(|s| crate::claude::registry::waiting_sessions(&s.sessions_dir()))
.map(|w| (w.label(), w.what.clone(), w.pane.clone()))
.collect();
// Every Antigravity seat the dashboard would find, short of running processes.
let agy_seats =
crate::agy::discovery::discover(&crate::agy::discovery::AgyCandidates {
home: &dirs.home,
env_dirs: Vec::new(),
configured: config.seats_of(&dirs.home, crate::core::harness::Harness::Agy),
});
for seat in &agy_seats {
let agy_dir = &seat.dir;
let locked = crate::agy::live::locked_conversations_once(agy_dir);
if locked.is_empty() {
continue;
}
let mut cache = crate::agy::live::AgyLiveCache::default();
cache.resolve_procs(agy_dir, &locked);
let metas = crate::agy::summaries::read_all(agy_dir);
for cid in &locked {
if let Some(m) = metas.get(cid)
&& m.status == crate::agy::meta::RunStatus::WaitingForUser
{
let name = m
.title
.clone()
.unwrap_or_else(|| crate::core::ids::short(cid).to_string());
let pane = cache.proc_of(cid).and_then(|p| p.pane.clone());
found.push((name, "input needed".into(), pane));
}
}
}
found
}
};
if waiting.is_empty() {
println!("nothing waits for you");
return Ok(());
}
if list {
for (name, what, pane) in &waiting {
println!(
"▲ {name}: {what}{}",
pane.as_ref()
.map(|p| format!(" ({p})"))
.unwrap_or_default()
);
}
return Ok(());
}
let Some((name, what, Some(pane))) = waiting.iter().find(|w| w.2.is_some()).cloned() else {
anyhow::bail!(
"{} session(s) wait for you, none in a supported terminal (tmux, zellij, kitty, wezterm, iTerm2, Warp)",
waiting.len()
);
};
match crate::terminal::jump(&pane) {
crate::terminal::Jump::Done => {
println!("→ {name}: {what}");
Ok(())
}
crate::terminal::Jump::Unreachable(why) | crate::terminal::Jump::Failed(why) => {
anyhow::bail!(why)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Every option, argument and command a person (or an agent reading `swarmy help`) can see
/// says what it does.
#[test]
fn help_describes_everything_it_shows() {
fn walk(cmd: &clap::Command, path: &str, missing: &mut Vec<String>) {
for arg in cmd.get_arguments() {
let id = arg.get_id().as_str();
if arg.is_hide_set() || id == "help" || id == "version" {
continue;
}
if arg.get_help().is_none() && arg.get_long_help().is_none() {
missing.push(format!("{path} <{id}>"));
}
}
for sub in cmd.get_subcommands() {
if sub.is_hide_set() || sub.get_name() == "help" {
continue;
}
let at = format!("{path} {}", sub.get_name());
if sub.get_about().is_none() {
missing.push(format!("{at} (what it does)"));
}
walk(sub, &at, missing);
}
}
let mut cmd = Cli::command();
cmd.build();
let mut missing = Vec::new();
walk(&cmd, "swarmy", &mut missing);
assert!(missing.is_empty(), "no help text for: {missing:#?}");
}
#[test]
fn top_level_help_shows_machine_output_and_the_guard() {
let help = Cli::command().render_long_help().to_string();
for s in [
"--format json",
"--seat current",
"setup --guard",
"swarmy help <command>",
] {
assert!(help.contains(s), "{s} is not in:\n{help}");
}
}
}