mod actions;
mod agent;
mod checks;
mod config;
mod daemon;
mod doctor;
mod forge;
mod git;
mod handoff;
mod herdr;
mod http;
mod job;
mod notify;
mod packs;
mod paths;
mod prompts;
mod repos;
mod schedule;
mod service;
mod setup;
mod skill;
mod state;
mod trust;
mod tui;
mod watch;
#[cfg(test)]
mod e2e_tests;
use anyhow::{Context, Result, bail};
use clap::{Parser, Subcommand};
use forge::{ForgeKind, RepoId};
use paths::Paths;
use state::{Db, Disposition, JobStatus};
#[derive(Parser)]
#[command(name = "nightporter", version, about = "Handles your PRs while you're away.")]
struct Cli {
#[command(subcommand)]
cmd: Option<Cmd>,
}
#[derive(Subcommand)]
enum Cmd {
Tui,
Daemon,
Setup,
Doctor,
Status,
Repos,
Subscribe { repo: String },
Unsubscribe { repo: String },
Approve {
id: i64,
#[arg(long)]
override_blocking: bool,
},
Reject { id: i64 },
Retry { id: i64 },
Handoff { id: i64 },
Show { id: i64 },
Inbox {
#[command(subcommand)]
cmd: InboxCmd,
},
Pause,
Resume,
Gc {
#[arg(long)]
all: bool,
},
Token {
#[command(subcommand)]
cmd: TokenCmd,
},
Service {
#[command(subcommand)]
cmd: ServiceCmd,
},
Market {
#[command(subcommand)]
cmd: MarketCmd,
},
Pack {
#[command(subcommand)]
cmd: PackCmd,
},
Events {
#[arg(long)]
json: bool,
},
Wait {
id: i64,
#[arg(long, default_value = "30m")]
timeout: String,
},
Skill {
#[command(subcommand)]
cmd: SkillCmd,
},
}
#[derive(Subcommand)]
enum SkillCmd {
Show,
Setup,
Remove,
}
#[derive(Subcommand)]
enum InboxCmd {
List,
AllowOnce { event: String },
Allow {
user: String,
#[arg(long, required_unless_present = "global", conflicts_with = "global")]
repo: Option<String>,
#[arg(long)]
global: bool,
},
Deny {
user: String,
#[arg(long, required_unless_present = "global", conflicts_with = "global")]
repo: Option<String>,
#[arg(long)]
global: bool,
},
Ignore { event: String },
}
#[derive(Subcommand)]
enum TokenCmd {
Set { forge: String, host: Option<String> },
}
#[derive(Subcommand)]
enum ServiceCmd {
Install,
Uninstall,
}
#[derive(Subcommand)]
enum MarketCmd {
Add { url: String },
List,
Update,
}
#[derive(Subcommand)]
enum PackCmd {
List,
Add {
name: String,
#[arg(long)]
yes: bool,
},
Update {
name: String,
#[arg(long)]
yes: bool,
},
Remove { name: String },
Env { name: String },
}
fn main() -> Result<()> {
#[cfg(unix)]
unsafe {
libc::signal(libc::SIGPIPE, libc::SIG_DFL);
}
let cli = Cli::parse();
let paths = Paths::detect()?;
let cmd = cli.cmd.unwrap_or(Cmd::Tui);
if std::env::var_os("NIGHTPORTER_JOB").is_some() && !read_only(&cmd) {
bail!("not available inside a Night Porter job; only read-only commands (status, show, inbox list, ...) are");
}
let cmd_name = match &cmd {
Cmd::Subscribe { .. } => "subscribe",
_ => "",
};
let rt = || tokio::runtime::Builder::new_multi_thread().enable_all().build();
match cmd {
Cmd::Tui => {
paths.ensure()?;
tui::run(&paths)
}
Cmd::Events { json } => watch::events(&paths, json),
Cmd::Wait { id, timeout } => {
let code = watch::wait(&paths, id, config::parse_duration(&timeout)?)?;
std::process::exit(code)
}
Cmd::Skill { cmd } => cmd_skill(&cmd),
Cmd::Daemon => {
init_tracing();
rt()?.block_on(daemon::run(paths))
}
Cmd::Setup => setup::run(&paths),
Cmd::Doctor => {
if !doctor::run(&paths) {
std::process::exit(1);
}
Ok(())
}
Cmd::Status => status(&paths),
Cmd::Repos => cmd_repos(&paths),
Cmd::Subscribe { repo } | Cmd::Unsubscribe { repo } => {
let on = matches!(cmd_name, "subscribe");
let r = resolve_repo(&paths, &repo)?;
actions::set_subscribed(&paths, &r, on)?;
println!("{} {}/{}", if on { "subscribed to" } else { "unsubscribed from" }, r.host, r.path);
Ok(())
}
Cmd::Approve { id, override_blocking } => {
println!("{}", actions::approve(&db(&paths)?, id, override_blocking)?);
Ok(())
}
Cmd::Reject { id } => {
actions::reject(&db(&paths)?, id)?;
println!("job {id} rejected: nothing will be pushed or posted");
Ok(())
}
Cmd::Retry { id } => {
println!("re-queued {} event(s)", actions::retry(&db(&paths)?, id)?);
Ok(())
}
Cmd::Handoff { id } => {
let db = db(&paths)?;
let j = db.job(id)?.with_context(|| format!("no job {id}"))?;
println!("{}", handoff::take_over(&paths, &db, &j)?);
Ok(())
}
Cmd::Show { id } => {
let db = db(&paths)?;
let j = db.job(id)?.with_context(|| format!("no job {id}"))?;
print!("{}", printable(&tui::job_text(&db, &j)));
Ok(())
}
Cmd::Inbox { cmd } => inbox(&paths, cmd),
Cmd::Pause => {
actions::set_paused(&db(&paths)?, true)?;
println!("paused: no new jobs will start (running jobs finish)");
Ok(())
}
Cmd::Resume => {
actions::set_paused(&db(&paths)?, false)?;
println!("resumed");
Ok(())
}
Cmd::Gc { all } => rt()?.block_on(async {
let cfg = config::Config::load(&paths)?;
let ctx = daemon::offline_ctx(&paths, cfg).await?;
job::gc(&ctx, all).await
}),
Cmd::Token { cmd: TokenCmd::Set { forge, host } } => cmd_token_set(&forge, host),
Cmd::Service { cmd } => cmd_service(&paths, &cmd),
Cmd::Market { cmd } => rt()?.block_on(market(&paths, cmd)),
Cmd::Pack { cmd } => rt()?.block_on(pack(&paths, cmd)),
}
}
fn cmd_skill(cmd: &SkillCmd) -> Result<()> {
match cmd {
SkillCmd::Show => print!("{}", skill::GUIDE),
SkillCmd::Setup => println!("{}", skill::setup()?),
SkillCmd::Remove => println!("{}", skill::remove()?),
}
Ok(())
}
fn init_tracing() {
tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::try_from_env("NIGHTPORTER_LOG").unwrap_or_else(|_| "nightporter=info".into()))
.init();
}
fn cmd_repos(paths: &Paths) -> Result<()> {
let cfg = config::Config::load(paths)?;
for (r, p) in repos::scan(&cfg.code_dir(), cfg.scan_depth, &cfg.accounts) {
let s = cfg.settings_for(paths, &r)?;
println!(
"{} {:<45} {:<8} {}",
if s.subscribed { "[on] " } else { "[off]" },
format!("{}/{}", r.host, r.path),
s.level.as_str(),
p.display()
);
}
Ok(())
}
fn cmd_token_set(forge: &str, host: Option<String>) -> Result<()> {
let f = ForgeKind::parse(forge).context("forge must be github or gitlab")?;
let host = host.unwrap_or_else(|| if f == ForgeKind::GitHub { "github.com".into() } else { "gitlab.com".into() });
eprint!("Paste the token for {host} and press Enter (input is hidden): ");
let t = read_secret()?;
if t.is_empty() {
bail!("empty token");
}
http::store_token(f, &host, &t)?;
eprintln!("\nstored in the OS keychain; set `token = \"keyring\"` on the account in config.toml");
Ok(())
}
fn cmd_service(paths: &Paths, cmd: &ServiceCmd) -> Result<()> {
println!(
"{}",
match cmd {
ServiceCmd::Install => service::install(&paths.log_file())?,
ServiceCmd::Uninstall => service::uninstall()?,
}
);
Ok(())
}
fn read_only(cmd: &Cmd) -> bool {
matches!(
cmd,
Cmd::Status
| Cmd::Show { .. }
| Cmd::Repos
| Cmd::Doctor
| Cmd::Events { .. }
| Cmd::Wait { .. }
| Cmd::Skill { cmd: SkillCmd::Show }
| Cmd::Inbox { cmd: InboxCmd::List }
| Cmd::Market { cmd: MarketCmd::List }
| Cmd::Pack { cmd: PackCmd::List }
)
}
#[must_use]
pub fn agent_for(paths: &Paths, repo: &RepoId) -> config::AgentKind {
config::Config::load(paths).and_then(|c| c.settings_for(paths, repo)).map_or(config::AgentKind::Claude, |s| s.agent)
}
fn db(paths: &Paths) -> Result<Db> {
Db::open(&paths.db())
}
fn resolve_repo(paths: &Paths, s: &str) -> Result<RepoId> {
let cfg = config::Config::load(paths)?;
let clones = repos::scan(&cfg.code_dir(), cfg.scan_depth, &cfg.accounts);
let hits: Vec<_> = clones.keys().filter(|r| r.path == s || format!("{}/{}", r.host, r.path) == s).collect();
match hits.as_slice() {
[one] => Ok((*one).clone()),
[] => bail!("{s} is not cloned under {}", cfg.code_dir().display()),
many => bail!("{s} is ambiguous: {}", many.iter().map(|r| format!("{}/{}", r.host, r.path)).collect::<Vec<_>>().join(", ")),
}
}
fn status(paths: &Paths) -> Result<()> {
let db = db(paths)?;
println!(
"Night Porter: daemon {}{}",
if paths.daemon_running() { "running" } else { "NOT RUNNING" },
if actions::paused(&db) { ", PAUSED" } else { "" }
);
let mut any = false;
for j in db.recent_jobs(200)?.into_iter().filter(|j| j.status.needs_user() || j.status.is_active() || j.status == JobStatus::Failed) {
any = true;
println!(
"job {:>4} {:<22} {}#{} {}",
j.id,
j.status.label(),
j.repo,
j.number,
printable(j.summary.lines().next().unwrap_or_default())
);
}
let inbox = db.events_with(Disposition::Inbox)?;
for (e, _) in &inbox {
any = true;
println!("inbox {} @{} on {}#{}: {}", e.id, e.author, e.repo, e.number, printable(e.body.lines().next().unwrap_or_default()));
}
if !any {
println!("Nothing needs you.");
}
Ok(())
}
fn printable(s: &str) -> String {
s.chars().filter(|c| !c.is_control() || *c == '\n' || *c == '\t').collect()
}
fn inbox(paths: &Paths, cmd: InboxCmd) -> Result<()> {
let db = db(paths)?;
let scope_repo = |r: &Option<String>| -> Result<Option<RepoId>> { r.as_deref().map(|r| resolve_repo(paths, r)).transpose() };
match cmd {
InboxCmd::List => {
for (e, _) in db.events_with(Disposition::Inbox)? {
println!(
"{} @{} ({:?}) on {}#{}\n {}",
e.id,
e.author,
e.role,
e.repo,
e.number,
printable(&e.body).replace('\n', "\n ")
);
}
}
InboxCmd::AllowOnce { event } => {
actions::allow_once(&db, &event)?;
println!("{event} allowed once");
}
InboxCmd::Ignore { event } => {
actions::ignore(&db, &event)?;
println!("{event} ignored");
}
InboxCmd::Allow { user, repo, .. } => {
let r = scope_repo(&repo)?;
let scope = r.as_ref().map_or(actions::Scope::Global, actions::Scope::Repo);
let n = actions::allow_always(paths, &db, &user, scope)?;
println!("@{user} trusted {}; {n} waiting event(s) released", r.map_or("on all repos".into(), |r| format!("on {r}")));
}
InboxCmd::Deny { user, repo, .. } => {
let r = scope_repo(&repo)?;
let scope = r.as_ref().map_or(actions::Scope::Global, actions::Scope::Repo);
let n = actions::deny(paths, &db, &user, scope)?;
println!("@{user} denied {}; {n} waiting event(s) dropped", r.map_or("on all repos".into(), |r| format!("on {r}")));
}
}
Ok(())
}
fn read_secret() -> Result<String> {
use std::io::BufRead;
let tty = std::io::IsTerminal::is_terminal(&std::io::stdin());
if tty {
let _ = std::process::Command::new("stty").arg("-echo").stdin(std::process::Stdio::inherit()).status();
}
let mut s = String::new();
let r = std::io::stdin().lock().read_line(&mut s);
if tty {
let _ = std::process::Command::new("stty").arg("echo").stdin(std::process::Stdio::inherit()).status();
}
r?;
Ok(s.trim().to_string())
}
fn confirm(q: &str) -> Result<bool> {
use std::io::{BufRead, Write};
print!("{q} (y/N): ");
std::io::stdout().flush()?;
let mut s = String::new();
std::io::stdin().lock().read_line(&mut s)?;
Ok(s.trim().eq_ignore_ascii_case("y"))
}
async fn market(paths: &Paths, cmd: MarketCmd) -> Result<()> {
let cfg = config::Config::load(paths)?;
match cmd {
MarketCmd::Add { url } => {
let m = packs::market_sync(paths, &url).await?;
config::edit_file(&paths.config_file(), |d| {
let arr = d["marketplaces"].or_insert(toml_edit::value(toml_edit::Array::new()));
if let Some(a) = arr.as_array_mut()
&& !a.iter().any(|v| v.as_str() == Some(&url))
{
a.push(url.as_str());
}
})?;
println!("added marketplace {} ({} packs)", m.name, m.packs.len());
}
MarketCmd::Update => {
for u in std::iter::once(packs::OFFICIAL_MARKET.to_string()).chain(cfg.marketplaces.clone()) {
match packs::market_sync(paths, &u).await {
Ok(m) => println!("{}: {} packs", m.name, m.packs.len()),
Err(e) => println!("{u}: {e:#}"),
}
}
}
MarketCmd::List => {
for u in std::iter::once(packs::OFFICIAL_MARKET.to_string()).chain(cfg.marketplaces.clone()) {
match packs::market(paths, &u) {
Ok(m) => {
println!("{} ({u})", m.name);
for p in m.packs {
println!(" {:<24} {}", p.name, p.description);
}
}
Err(_) => println!("{u}: not synced (run `nightporter market update`)"),
}
}
}
}
Ok(())
}
async fn pack(paths: &Paths, cmd: PackCmd) -> Result<()> {
let cfg = config::Config::load(paths)?;
std::fs::create_dir_all(paths.packs_dir())?;
match cmd {
PackCmd::List => {
for (name, l) in packs::lock(paths).packs {
let d = packs::manifest(&packs::pack_dir(paths, &name)).map(|m| m.description).unwrap_or_default();
println!("{name:<24} {} {} {d}", &l.rev[..l.rev.len().min(10)], l.url);
}
}
PackCmd::Add { name, yes } => {
let (url, rev) = if name.contains("://") || name.starts_with("git@") {
let (u, r) = name.rsplit_once('@').filter(|(u, _)| u.contains('/')).map_or((name.as_str(), "HEAD"), |(u, r)| (u, r));
(u.to_string(), r.to_string())
} else {
let e = packs::find(paths, &cfg.marketplaces, &name)
.with_context(|| format!("{name} not found in any marketplace (try `nightporter market update`)"))?;
(e.url, e.rev)
};
let (staging, m, sha) = packs::fetch(paths, &url, &rev).await?;
println!("{}", packs::describe(&m));
println!(
"Packs are prompts that steer an agent with access to your code. Review them before installing:\n {}",
staging.display()
);
if !yes && !confirm(&format!("Install {} at {}?", m.name, &sha[..10]))? {
let _ = std::fs::remove_dir_all(&staging);
return Ok(());
}
packs::commit(paths, &staging, &m, &url, &sha)?;
println!("installed. Enable it with `packs = [\"{}\"]` in [defaults] or a repo file.", m.name);
}
PackCmd::Update { name, yes } => {
let l = packs::lock(paths).packs.get(&name).cloned().with_context(|| format!("{name} is not installed"))?;
let rev = packs::find(paths, &cfg.marketplaces, &name).map_or_else(|| "HEAD".into(), |e| e.rev);
let (staging, m, sha) = packs::fetch(paths, &l.url, &rev).await?;
if sha == l.rev {
let _ = std::fs::remove_dir_all(&staging);
println!("{name} is up to date");
return Ok(());
}
println!("{}", packs::diff_dirs(&packs::pack_dir(paths, &name), &staging));
println!("{}", packs::describe(&m));
if !yes && !confirm(&format!("Update {name} {} → {}?", &l.rev[..l.rev.len().min(10)], &sha[..10]))? {
let _ = std::fs::remove_dir_all(&staging);
return Ok(());
}
packs::commit(paths, &staging, &m, &l.url, &sha)?;
println!("updated");
}
PackCmd::Remove { name } => {
packs::remove(paths, &name)?;
println!("removed {name}");
}
PackCmd::Env { name } => print!("{}", packs::env_preset(paths, &name)?),
}
Ok(())
}
#[cfg(test)]
mod tests {
#[test]
fn jobs_can_only_run_read_only_commands() {
use clap::Parser;
let ro = |args: &[&str]| super::read_only(&super::Cli::parse_from(args).cmd.unwrap());
assert!(ro(&["nightporter", "status"]) && ro(&["nightporter", "show", "3"]) && ro(&["nightporter", "inbox", "list"]));
assert!(!ro(&["nightporter", "approve", "3"]) && !ro(&["nightporter", "inbox", "allow", "x", "--global"]));
assert!(!ro(&["nightporter", "skill", "setup"]) && !ro(&["nightporter", "tui"]));
}
#[test]
fn printable_strips_terminal_escapes() {
assert_eq!(super::printable("ok\x1b[2K\x1b[1Ahidden\r\n\tnext\x07"), "ok[2K[1Ahidden\n\tnext");
}
}