use std::io::{BufRead, IsTerminal, Write};
use std::path::PathBuf;
use agent_loadout_core::adapters::adapter;
use agent_loadout_core::eject::{
self, EjectOptions, EjectReport, EjectTarget, EntryAction, SkillAction, StillReason,
TargetOutcome,
};
use agent_loadout_core::{CoreError, ErrorCode, brand};
use clap::Args;
use serde_json::{Value, json};
use super::{
Context, JSON_SCHEMA, error_json, path_json, print_json, read_only_json, read_only_note,
};
#[derive(Debug, Args)]
pub struct EjectArgs {
#[arg(long = "client", value_name = "CLIENT", conflicts_with = "resume")]
clients: Vec<String>,
#[arg(long, value_name = "PATH", conflicts_with = "resume")]
project: Option<PathBuf>,
#[arg(long, conflicts_with = "resume")]
keep_agent_skill: bool,
#[arg(long, conflicts_with = "resume")]
dry_run: bool,
#[arg(long)]
resume: bool,
}
pub fn run(ctx: &Context, args: &EjectArgs) -> Result<u8, CoreError> {
if args.resume {
return resume(ctx);
}
let project = match &args.project {
Some(path) => Some(super::project::project_root(ctx, path)?),
None => None,
};
let mut options = EjectOptions {
clients: (!args.clients.is_empty()).then(|| args.clients.clone()),
project,
keep_agent_skill: args.keep_agent_skill,
execute: false,
..EjectOptions::default()
};
let store = ctx.open_store()?;
let ax = ctx.apply_env();
if args.dry_run || !ctx.yes {
let plan = eject::eject(store.as_ref(), &ax, &options)?;
if args.dry_run {
if ctx.json {
print_json(&report_json(ctx, &plan));
} else {
print_plan(&plan);
println!(
"Dry run: nothing was written. Run `{} eject` to stop managing.",
brand::BIN_NAME
);
}
return Ok(0);
}
if ctx.json || !std::io::stdin().is_terminal() {
return Err(CoreError::new(
ErrorCode::ConfirmationRequired,
"stopping management rewrites client files; pass --yes to confirm (or --dry-run \
to see the plan)",
));
}
print_plan(&plan);
if !confirm()? {
println!("Nothing changed; Loadout still manages this machine.");
return Ok(0);
}
}
options.execute = true;
let report = eject::eject(store.as_ref(), &ax, &options)?;
if ctx.json {
print_json(&report_json(ctx, &report));
} else {
print_result(ctx, &report);
}
Ok(if report.failed() { 1 } else { 0 })
}
fn resume(ctx: &Context) -> Result<u8, CoreError> {
let count = eject::resume(ctx.fs(), &ctx.home)?.len();
if ctx.json {
print_json(&json!({ "schema": JSON_SCHEMA, "resumed": count }));
} else if count == 0 {
println!("Loadout already manages this machine.");
} else {
println!(
"Loadout manages this machine again. Run `{bin} apply --dry-run` to review: entries \
equal to the store are adopted, the rest need a decision (`{bin} adopt` or `{bin} \
import`).",
bin = brand::BIN_NAME
);
}
Ok(0)
}
pub fn note_if_ejected(ctx: &Context) -> Result<(), CoreError> {
let Some(ejected) = eject::status(ctx.fs(), &ctx.home)? else {
return Ok(());
};
let what = if ejected.all() {
"this machine".to_owned()
} else {
let mut parts: Vec<String> = Vec::new();
for run in &ejected.runs {
let clients = run.clients.as_ref().map_or_else(
|| "every client".to_owned(),
|ids| {
ids.iter()
.map(|id| client_name(id))
.collect::<Vec<_>>()
.join(", ")
},
);
parts.push(match &run.project_id {
Some(project) => format!("{clients} in project {project}"),
None => clients,
});
}
parts.join("; ")
};
eprintln!(
"note: Loadout is not managing {what} (stopped with `{bin} eject`); those files are left \
alone until `{bin} eject --resume`.",
bin = brand::BIN_NAME
);
if let Some(open) = ejected.unfinished() {
eprintln!(
"warning[unfinished_apply]: eject {id} stopped before it finished; run `{bin} \
rollback {id}`, then `{bin} eject` again.",
id = open.id,
bin = brand::BIN_NAME
);
}
Ok(())
}
fn confirm() -> Result<bool, CoreError> {
print!("Stop managing these files and skill folders? [y/N] ");
std::io::stdout().flush().ok();
let mut line = String::new();
std::io::stdin()
.lock()
.read_line(&mut line)
.map_err(|err| CoreError::new(ErrorCode::IoError, format!("cannot read stdin: {err}")))?;
Ok(matches!(line.trim(), "y" | "Y" | "yes" | "Yes"))
}
fn client_name(id: &str) -> &str {
adapter(id).map_or(id, |spec| spec.display_name)
}
fn print_plan(report: &EjectReport) {
if let Some(open) = &report.unfinished {
println!(
"warning[unfinished_apply]: eject {open} stopped before it finished; run `{bin} \
rollback {open}` first.",
bin = brand::BIN_NAME
);
}
if report.targets.is_empty() && report.skills.is_empty() {
println!("Loadout owns nothing here to hand back.");
}
for target in &report.targets {
print_target(target);
}
print_skills(report);
print_needs(report);
print_still_needed(report);
}
fn print_still_needed(report: &EjectReport) {
let still = report.still_needs_loadout();
if still.is_empty() {
return;
}
println!("Still need Loadout (uninstalling it or deleting its data folder breaks these):");
for item in &still {
let what = match item.reason {
StillReason::Manual => "still starts `loadout` (cannot be rewritten)",
StillReason::UsesDataFolder => "runs or reads something in the data folder",
StillReason::Blocked => "file left as it is, still starts `loadout`",
StillReason::Failed => "file not written, still starts `loadout`",
StillReason::SkillLink => "skill folder is still a link into the data folder",
};
let entry = item
.entry
.as_ref()
.map(|entry| format!("{entry} ({}) ", client_name(&item.client)))
.unwrap_or_default();
let detail = item
.detail
.as_ref()
.map(|detail| format!(": {detail}"))
.unwrap_or_default();
println!(" {entry}in {}: {what}{detail}", item.file.display());
}
}
fn print_target(target: &EjectTarget) {
let clients: Vec<&str> = target.clients.iter().map(|id| client_name(id)).collect();
println!(
"{:<9} {} ({}){}",
target.outcome.as_str(),
target.file.display(),
clients.join(", "),
read_only_note(target.read_only)
);
if let Some(err) = &target.error {
println!(" error[{}]: {}", err.code(), err.message());
}
for entry in &target.entries {
let what = match entry.action {
EntryAction::Keep => "kept as is".to_owned(),
EntryAction::Rewrite => "rewritten without Loadout".to_owned(),
EntryAction::Manual => format!(
"left as is, still starts `{}`: {}",
brand::BIN_NAME,
entry
.problem
.as_ref()
.map_or("", |problem| problem.message())
),
EntryAction::Gone => "no longer in the file".to_owned(),
};
println!(" {} {}: {what}", entry.action.as_str(), entry.name);
for need in &entry.needs_env {
println!(" needs env {}", need.name);
}
for manual in &entry.needs_manual_secret {
println!(
" needs a value pasted into {}.{} ({})",
manual.field, manual.key, manual.secret
);
}
if entry.uses_data_folder {
println!(" points into the data folder: keep it, or move what it runs");
}
}
}
fn print_skills(report: &EjectReport) {
for skill in &report.skills {
let what = match skill.action {
SkillAction::Copy => "link replaced by a copy",
SkillAction::Keep => "copy kept",
SkillAction::Remove => "removed (the Loadout agent skill)",
SkillAction::Changed => "edited since: left as is",
SkillAction::Gone => "no longer there",
};
println!(
"skill {} ({}): {what}{}",
skill.path.display(),
client_name(&skill.client),
read_only_note(skill.read_only)
);
if let Some(err) = skill.error.as_ref().filter(|_| skill.read_only.is_none()) {
println!(" error[{}]: {}", err.code(), err.message());
}
}
}
fn print_needs(report: &EjectReport) {
let env = report.env();
if !env.is_empty() {
println!("Set these environment variables where your clients start:");
for need in &env {
let secret = need
.secret
.as_ref()
.map(|alias| format!(" (secret {alias})"))
.unwrap_or_default();
println!(
" {}{secret}: read by {}",
need.name,
need.entries.join(", ")
);
}
}
let manual = report.manual();
if !manual.is_empty() {
println!("Paste these values yourself (the client cannot read them from the environment):");
for item in &manual {
let conflict = item
.secret
.conflicts_with
.as_ref()
.map(|name| format!("; {name} already stands for another secret"))
.unwrap_or_default();
println!(
" {} ({}): {}.{} in {} (secret {}{conflict})",
item.entry,
client_name(&item.client),
item.secret.field,
item.secret.key,
item.file.display(),
item.secret.secret
);
}
}
for conflict in report.conflicts() {
println!(
"warning: {} is needed for different secrets ({}) by {}; only the first keeps the \
variable, the others need their value pasted by hand.",
conflict.name,
conflict.secrets.join(", "),
conflict.entries.join(", ")
);
}
}
fn print_result(ctx: &Context, report: &EjectReport) {
for target in report.targets.iter().filter(|t| {
t.outcome != TargetOutcome::Unchanged
|| t.error.is_some()
|| t.entries
.iter()
.any(|e| e.action == EntryAction::Manual || e.uses_data_folder)
}) {
print_target(target);
}
print_skills(report);
print_needs(report);
print_still_needed(report);
let id = report.eject_id.as_deref().unwrap_or_default();
let written = report
.targets
.iter()
.filter(|t| t.outcome == TargetOutcome::Written)
.count();
println!(
"Eject {id}: {written} file(s) rewritten, {} skill entr{} handed back.",
report.skills.iter().filter(|s| s.done).count(),
if report.skills.iter().filter(|s| s.done).count() == 1 {
"y"
} else {
"ies"
}
);
if report
.targets
.iter()
.any(|t| t.outcome == TargetOutcome::Blocked)
{
println!(
"Blocked files were left as they are; make them writable (or bring their project \
folder back) and run `{} eject` again.",
brand::BIN_NAME
);
}
println!(
"Loadout no longer manages {}. Undo: `{bin} rollback {id}`. Start managing again: \
`{bin} eject --resume` or `{bin} import`.",
if report.all {
"this machine"
} else {
"the selected clients"
},
bin = brand::BIN_NAME
);
if report.still_needs_loadout().is_empty() {
println!(
"Your servers, skills and history are kept in {}. To remove Loadout completely, \
uninstall it and delete that folder.",
ctx.home.path.display()
);
} else {
println!(
"warning: keep Loadout installed and keep {} until the entries listed under \"Still \
need Loadout\" are handled; uninstalling or deleting the folder breaks them.",
ctx.home.path.display()
);
}
}
fn report_json(ctx: &Context, report: &EjectReport) -> Value {
json!({
"schema": JSON_SCHEMA,
"dry_run": !report.executed,
"eject_id": report.eject_id,
"all": report.all,
"failed": report.failed(),
"unfinished": report.unfinished,
"still_needs_loadout": report.still_needs_loadout().iter().map(|item| json!({
"client": item.client,
"entry": item.entry,
"file": path_json(&item.file),
"reason": item.reason.as_str(),
"detail": item.detail,
})).collect::<Vec<_>>(),
"conflicts": report.conflicts().iter().map(|conflict| json!({
"name": conflict.name,
"secrets": conflict.secrets,
"entries": conflict.entries,
})).collect::<Vec<_>>(),
"targets": report.targets.iter().map(target_json).collect::<Vec<_>>(),
"skills": report.skills.iter().map(|skill| json!({
"client": skill.client,
"scope": skill.scope,
"project_id": skill.project_id,
"skill": skill.skill_id,
"path": path_json(&skill.path),
"method": skill.method.as_str(),
"action": skill.action.as_str(),
"done": skill.done,
"read_only": read_only_json(skill.read_only),
"error": skill.error.as_ref().map(error_json),
})).collect::<Vec<_>>(),
"env": report.env().iter().map(|need| json!({
"name": need.name,
"secret": need.secret,
"entries": need.entries,
})).collect::<Vec<_>>(),
"manual": report.manual().iter().map(|item| json!({
"client": item.client,
"entry": item.entry,
"file": path_json(&item.file),
"field": item.secret.field,
"key": item.secret.key,
"secret": item.secret.secret,
"conflicts_with": item.secret.conflicts_with,
})).collect::<Vec<_>>(),
"data_folder": path_json(&ctx.home.path),
"resume_command": format!("{} eject --resume", brand::BIN_NAME),
})
}
fn target_json(target: &EjectTarget) -> Value {
json!({
"clients": target.clients,
"file": path_json(&target.file),
"project": target.project.as_deref().map(path_json),
"outcome": target.outcome.as_str(),
"written": target.outcome == TargetOutcome::Written,
"backup": target.backup.as_deref().map(path_json),
"read_only": read_only_json(target.read_only),
"error": target.error.as_ref().map(error_json),
"entries": target.entries.iter().map(|entry| json!({
"client": entry.client,
"scope": entry.scope,
"project_id": entry.project_id,
"name": entry.name,
"action": entry.action.as_str(),
"needs_env": entry.needs_env,
"needs_manual_secret": entry.needs_manual_secret,
"uses_data_folder": entry.uses_data_folder,
"problem": entry.problem.as_ref().map(error_json),
})).collect::<Vec<_>>(),
})
}