agent-loadout 1.0.0

Loadout CLI: manage MCP servers, skills and secret references for AI coding clients
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
//! `loadout eject [--client C]... [--project PATH] [--keep-agent-skill]
//! [--dry-run]` and `loadout eject --resume` (M57): stop managing this
//! machine. Every owned client entry is handed back in the client's own
//! form (no `loadout` command left in it, never a secret value), skill links
//! become copies, ownership is dropped and Loadout stays away until
//! `loadout eject --resume` or `loadout import`. Without `--yes` the plan is
//! shown and confirmed on a terminal; without a terminal (or with `--json`)
//! it fails with `confirmation_required` (exit 4). The store and history
//! are kept; `loadout rollback <eject-id>` undoes the run.

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 {
    /// Only this client (repeatable) [default: every client].
    #[arg(long = "client", value_name = "CLIENT", conflicts_with = "resume")]
    clients: Vec<String>,
    /// Only the project rooted at (or holding) this folder; user files are
    /// left managed.
    #[arg(long, value_name = "PATH", conflicts_with = "resume")]
    project: Option<PathBuf>,
    /// Keep the Loadout agent skill in client skill folders (as a copy).
    #[arg(long, conflicts_with = "resume")]
    keep_agent_skill: bool,
    /// Print the plan; change nothing.
    #[arg(long, conflicts_with = "resume")]
    dry_run: bool,
    /// Start managing again: the next apply adopts entries equal to the
    /// store and asks about the rest.
    #[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)
}

/// `note: ...` on stderr while this machine (or part of it) is ejected:
/// what apply and status leave alone.
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)
}

/// The plan for people: per file, what happens to each entry; the skills;
/// what the user has to set up.
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);
}

/// What still needs Loadout (or its data folder) after the eject.
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());
        }
    }
}

/// The variables to set and the values to paste.
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) {
    // Files written or with a problem, and files whose entries still need
    // Loadout (an entry that cannot be rewritten, the data folder).
    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<_>>(),
    })
}