everruns-cli 0.51.0

Command-line interface for Everruns — run and manage agents from your terminal
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
//! `everruns docker`: run Everruns on this machine with Docker Compose.
//!
//! Decision: `up` describes an end state (a healthy instance and a CLI signed
//! in to it), not a first-time script. Every step checks before it acts, so
//! running it again is safe and fast, and it repairs what is missing instead of
//! starting over. Secrets are never regenerated and upgrades never happen as a
//! side effect: moving to a new image tag runs migrations, so it is asked for
//! explicitly with `upgrade`. `reset` is the one command that deletes data,
//! and it asks for the instance name first.

mod checks;
mod settings;
mod signin;

use std::io::IsTerminal;
use std::net::TcpListener;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

use anyhow::{Context, Result, bail};
use clap::{Args, Subcommand, ValueEnum};

use settings::{Instance, Settings};

const DEFAULT_PORT: u16 = 9300;
const HEALTH_TIMEOUT: Duration = Duration::from_secs(240);
const SERVER_IMAGE: &str = "ghcr.io/everruns/everruns-server";

#[derive(Subcommand)]
pub enum DockerCommand {
    /// Start Everruns on this machine, setting it up on first run. Safe to run again
    Up(UpArgs),

    /// Show whether the local instance runs, where, and which CLI profile points at it
    Status(InstanceArgs),

    /// Stop the containers. Data and settings are kept
    Stop(InstanceArgs),

    /// Show the containers' logs
    Logs {
        #[command(flatten)]
        instance: InstanceArgs,

        /// Only this service (server, worker-1, ui, caddy, postgres, ...)
        service: Option<String>,

        /// Print what is there and exit instead of following
        #[arg(long)]
        no_follow: bool,
    },

    /// Open the local UI in the browser
    Open(InstanceArgs),

    /// Check that Docker is ready, and run the system doctor on a running instance
    Doctor(InstanceArgs),

    /// Move the instance to this CLI's version (or --image-tag), backing up the database first
    Upgrade(UpgradeArgs),

    /// Delete the instance: containers, database and settings. Asks first
    Reset(ResetArgs),
}

#[derive(Args)]
pub struct UpgradeArgs {
    #[command(flatten)]
    pub instance: InstanceArgs,

    /// Image tag to move to, such as v0.49.0 or latest (default: this CLI's version)
    #[arg(long)]
    pub image_tag: Option<String>,

    /// Skip the database backup taken before the upgrade
    #[arg(long)]
    pub no_backup: bool,

    /// Do not ask, also when the move is to an older version
    #[arg(long, short = 'y')]
    pub yes: bool,
}

#[derive(Args)]
pub struct ResetArgs {
    #[command(flatten)]
    pub instance: InstanceArgs,

    /// Do not ask for the instance name (for scripts)
    #[arg(long, short = 'y')]
    pub yes: bool,
}

#[derive(Args)]
pub struct InstanceArgs {
    /// Instance name, for more than one local Everruns
    #[arg(long, default_value = "default")]
    pub name: String,
}

#[derive(Args)]
pub struct UpArgs {
    #[command(flatten)]
    pub instance: InstanceArgs,

    /// Who signs in
    #[arg(long, value_enum)]
    pub auth: Option<AuthChoice>,

    /// Admin email, used to sign in to the UI
    #[arg(long)]
    pub admin_email: Option<String>,

    /// LLM provider for the server's default key. The key comes from
    /// OPENAI_API_KEY, ANTHROPIC_API_KEY or GEMINI_API_KEY, or a prompt
    #[arg(long, value_enum)]
    pub provider: Option<LlmProvider>,

    /// Port for the UI and API on this machine (default 9300)
    #[arg(long)]
    pub port: Option<u16>,

    /// Image tag to run, such as v0.48.0 or latest (default: this CLI's version)
    #[arg(long)]
    pub image_tag: Option<String>,

    /// Accept the default for every question
    #[arg(long, short = 'y')]
    pub yes: bool,

    /// Do not open the browser
    #[arg(long)]
    pub no_open: bool,
}

#[derive(Clone, Copy, Debug, PartialEq, ValueEnum)]
pub enum AuthChoice {
    /// Just me, with a password (one admin account)
    Single,
    /// No sign-in: anyone who reaches the port is admin; listens on 127.0.0.1 only
    None,
    /// Accounts: people sign up and sign in
    Accounts,
}

impl AuthChoice {
    fn server_mode(self) -> &'static str {
        match self {
            Self::Single => "admin",
            Self::None => "none",
            Self::Accounts => "full",
        }
    }

    fn from_server_mode(mode: &str) -> Option<Self> {
        match mode {
            "admin" => Some(Self::Single),
            "none" => Some(Self::None),
            "full" => Some(Self::Accounts),
            _ => None,
        }
    }

    fn label(self) -> &'static str {
        match self {
            Self::Single => "Just me, with a password",
            Self::None => "No sign-in, for trying things out (only this machine can reach it)",
            Self::Accounts => "Accounts: people sign up and sign in",
        }
    }

    /// Whether the instance's default provider key may be shared with every
    /// user: only when no one can sign themselves up.
    fn shares_default_keys(self) -> bool {
        !matches!(self, Self::Accounts)
    }

    /// The server refuses no-sign-in outside the dev grade, which also turns
    /// on experimental features. That fits a throwaway local playground.
    fn deployment_grade(self) -> &'static str {
        match self {
            Self::None => "dev",
            Self::Single | Self::Accounts => "prod",
        }
    }

    /// Without sign-in, nothing outside this machine may reach the port.
    fn bind_address(self) -> &'static str {
        match self {
            Self::None => "127.0.0.1",
            Self::Single | Self::Accounts => "0.0.0.0",
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, ValueEnum)]
pub enum LlmProvider {
    Openai,
    Anthropic,
    Gemini,
    /// Add a provider later in the UI
    Skip,
}

impl LlmProvider {
    const ALL: [LlmProvider; 4] = [Self::Openai, Self::Anthropic, Self::Gemini, Self::Skip];

    fn key_env(self) -> Option<&'static str> {
        match self {
            Self::Openai => Some("OPENAI_API_KEY"),
            Self::Anthropic => Some("ANTHROPIC_API_KEY"),
            Self::Gemini => Some("GEMINI_API_KEY"),
            Self::Skip => None,
        }
    }

    /// The server variable that seeds the provider's default key.
    fn server_env(self) -> Option<&'static str> {
        match self {
            Self::Openai => Some("DEFAULT_OPENAI_API_KEY"),
            Self::Anthropic => Some("DEFAULT_ANTHROPIC_API_KEY"),
            Self::Gemini => Some("DEFAULT_GEMINI_API_KEY"),
            Self::Skip => None,
        }
    }

    fn name(self) -> &'static str {
        match self {
            Self::Openai => "openai",
            Self::Anthropic => "anthropic",
            Self::Gemini => "gemini",
            Self::Skip => "skip",
        }
    }

    fn label(self) -> &'static str {
        match self {
            Self::Openai => "OpenAI",
            Self::Anthropic => "Anthropic",
            Self::Gemini => "Gemini",
            Self::Skip => "Skip, I'll add one in the UI",
        }
    }

    fn env_key(self) -> Option<String> {
        self.key_env()
            .and_then(|k| std::env::var(k).ok())
            .filter(|v| !v.trim().is_empty())
    }
}

pub async fn run(command: DockerCommand) -> Result<()> {
    match command {
        DockerCommand::Up(args) => Box::pin(up(args)).await,
        DockerCommand::Status(args) => Box::pin(status(&args)).await,
        DockerCommand::Stop(args) => stop(&args),
        DockerCommand::Logs {
            instance,
            service,
            no_follow,
        } => logs(&instance, service.as_deref(), no_follow),
        DockerCommand::Open(args) => open(&args),
        DockerCommand::Doctor(args) => doctor(&args),
        DockerCommand::Upgrade(args) => Box::pin(upgrade(args)).await,
        DockerCommand::Reset(args) => reset(&args),
    }
}

/// How `up` may talk to the person running it.
#[derive(Clone, Copy)]
struct Asker {
    interactive: bool,
    yes: bool,
}

impl Asker {
    fn can_ask(self) -> bool {
        self.interactive && !self.yes
    }
}

async fn up(args: UpArgs) -> Result<()> {
    let docker = checks::program();
    require_docker(&docker, true)?;

    let inst = Instance::new(&args.instance.name)?;
    inst.ensure_dir()?;
    let _lock = inst.lock()?;

    let asker = Asker {
        interactive: std::io::stdin().is_terminal() && std::io::stderr().is_terminal(),
        yes: args.yes,
    };
    let mut s = Settings::load(&inst.env_path())?;
    let first_run = s.is_empty();

    // Who signs in.
    let auth = match args.auth {
        Some(auth) => auth,
        None => match s
            .value(settings::AUTH_MODE)
            .and_then(AuthChoice::from_server_mode)
        {
            Some(saved) => saved,
            None => ask_auth(asker)?,
        },
    };
    s.set(settings::AUTH_MODE, auth.server_mode());
    s.set(settings::BIND, auth.bind_address());
    s.set(settings::DEPLOYMENT_GRADE, auth.deployment_grade());

    // The admin account. Saved even without sign-in, so switching modes later
    // has an account ready.
    let email = match &args.admin_email {
        Some(email) => email.clone(),
        None => match s.value(settings::ADMIN_EMAIL) {
            Some(saved) => saved.to_string(),
            None if auth == AuthChoice::None => default_email(),
            None => ask_email(asker)?,
        },
    };
    s.set(settings::ADMIN_EMAIL, &email);
    s.set_missing(settings::ADMIN_PASSWORD, settings::password);
    s.fill_secrets();

    // LLM provider. The server only turns a default key into the default
    // organization's provider when nobody can sign themselves up; with
    // accounts, each organization adds its own key in the UI.
    s.set(
        settings::SEED_PROVIDER_KEYS,
        if auth.shares_default_keys() {
            "true"
        } else {
            "false"
        },
    );
    if !auth.shares_default_keys() {
        if args.provider.is_some_and(|p| p != LlmProvider::Skip) {
            bail!("with --auth accounts, add provider keys in the UI; drop --provider");
        }
    } else if let Some(provider) = args.provider {
        set_provider(&mut s, provider, asker)?;
    } else if s.value(settings::LLM_PROVIDER).is_none() {
        let provider = ask_provider(asker)?;
        set_provider(&mut s, provider, asker)?;
    }

    // Port: an explicit one wins; otherwise keep the saved one, or find a
    // free one on first run.
    let running = running_services(&docker, &inst);
    let caddy_running = running.iter().any(|s| s == "caddy");
    let port = match args.port {
        Some(port) => port,
        None => s
            .value(settings::PORT)
            .and_then(|p| p.parse().ok())
            .unwrap_or(DEFAULT_PORT),
    };
    let port = if caddy_running && s.value(settings::PORT) == Some(&port.to_string()) {
        port
    } else {
        choose_port(port, auth.bind_address(), args.port.is_some(), asker)?
    };
    s.set(settings::PORT, &port.to_string());

    // Image tag.
    let cli_tag = format!("v{}", env!("CARGO_PKG_VERSION"));
    let tag = match &args.image_tag {
        Some(tag) => tag.clone(),
        None => match s.value(settings::IMAGE_TAG) {
            Some(saved) => saved.to_string(),
            None => resolve_tag(&docker, &cli_tag),
        },
    };
    s.set(settings::IMAGE_TAG, &tag);

    s.save(&inst.env_path())?;
    inst.write_compose()?;

    if first_run {
        eprintln!(
            "Settings: {} (keep .env: it holds the encryption key)",
            inst.dir.display()
        );
    }

    // Start or update the containers. Compose leaves running containers whose
    // configuration did not change alone, so this is the idempotent step.
    let status = compose(&docker, &inst)
        .args(["up", "--detach", "--remove-orphans"])
        .status()
        .context("Failed to run docker compose")?;
    if !status.success() {
        bail!("`docker compose up` failed; see the output above");
    }

    let health = wait_healthy(&docker, &inst, port).await?;

    let api_url = format!("http://localhost:{port}/api");
    let creds = signin::Credentials {
        auth,
        email: &email,
        password: s.value(settings::ADMIN_PASSWORD).unwrap_or_default(),
    };
    let switch = if asker.yes {
        signin::SwitchPolicy::Always
    } else if asker.interactive {
        signin::SwitchPolicy::Ask
    } else {
        signin::SwitchPolicy::Never
    };
    let signed_in = Box::pin(signin::ensure_profile(
        &api_url,
        &inst.profile(),
        creds,
        switch,
    ))
    .await
    .context("The server is up, but signing the CLI in failed")?;

    let url = format!("http://localhost:{port}");
    eprintln!();
    eprintln!("Everruns {} is running at {url}", health.version);
    match auth {
        AuthChoice::None => eprintln!("  Sign-in: none (only this machine can reach it)"),
        AuthChoice::Single | AuthChoice::Accounts if first_run => eprintln!(
            "  Sign in: {email} / {}  (shown once; also in {})",
            s.value(settings::ADMIN_PASSWORD).unwrap_or_default(),
            inst.env_path().display()
        ),
        AuthChoice::Single | AuthChoice::Accounts => eprintln!(
            "  Sign in: {email} (password in {})",
            inst.env_path().display()
        ),
    }
    if signed_in.current {
        eprintln!(
            "  CLI: signed in as {} (profile '{}'), try `everruns agents list`",
            signed_in.email, signed_in.profile
        );
    } else {
        eprintln!(
            "  CLI: profile '{}'; use it with `everruns --profile {} agents list`",
            signed_in.profile, signed_in.profile
        );
    }
    if tag != cli_tag && tag != "latest" {
        eprintln!(
            "  This instance runs {tag}; this CLI is {cli_tag}. Move to it with \
             `everruns docker upgrade{}` (backs up the database, then runs migrations).",
            name_flag(&inst.name)
        );
    }

    if first_run && asker.interactive && !args.no_open && crate::browser::open(&url).is_err() {
        eprintln!("  Open {url} in your browser.");
    }
    Ok(())
}

fn require_docker(docker: &str, verbose: bool) -> Result<()> {
    let results = checks::run(docker);
    let failed = results.iter().any(checks::Check::failed);
    for check in &results {
        if verbose || failed || !matches!(check.outcome, checks::Outcome::Ok(_)) {
            check.print();
        }
    }
    if failed {
        bail!("Docker is not ready; fix the problem above and run this again");
    }
    Ok(())
}

/// `docker compose` for one instance. Variables `up` manages are removed from
/// the environment: Compose prefers the shell over `.env`, so a stray
/// `AUTH_MODE` in someone's shell would otherwise override the saved setup.
fn compose(docker: &str, inst: &Instance) -> Command {
    let mut cmd = Command::new(docker);
    cmd.arg("compose")
        .arg("--project-name")
        .arg(inst.project())
        .arg("--file")
        .arg(inst.compose_path())
        .arg("--env-file")
        .arg(inst.env_path());
    for key in settings::MANAGED_KEYS {
        cmd.env_remove(key);
    }
    cmd
}

fn running_services(docker: &str, inst: &Instance) -> Vec<String> {
    if !inst.compose_path().exists() {
        return Vec::new();
    }
    compose(docker, inst)
        .args(["ps", "--status", "running", "--services"])
        .stderr(Stdio::null())
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| {
            String::from_utf8_lossy(&o.stdout)
                .lines()
                .map(str::to_string)
                .collect()
        })
        .unwrap_or_default()
}

fn port_free(bind: &str, port: u16) -> bool {
    TcpListener::bind((bind, port)).is_ok()
}

fn choose_port(wanted: u16, bind: &str, explicit: bool, asker: Asker) -> Result<u16> {
    if port_free(bind, wanted) {
        return Ok(wanted);
    }
    if explicit {
        bail!("port {wanted} is in use; pick another with --port");
    }
    let next = (wanted.saturating_add(1)..=wanted.saturating_add(100))
        .find(|p| port_free(bind, *p))
        .with_context(|| {
            format!("port {wanted} is in use and no nearby port is free; use --port")
        })?;
    if asker.can_ask() {
        let ok = dialoguer::Confirm::new()
            .with_prompt(format!("Port {wanted} is in use. Use {next} instead?"))
            .default(true)
            .interact()
            .context("Failed to read the answer")?;
        if !ok {
            bail!("port {wanted} is in use; pick another with --port");
        }
    } else if !asker.yes {
        bail!("port {wanted} is in use; pick another with --port (or pass --yes to take {next})");
    } else {
        eprintln!("Port {wanted} is in use; using {next}.");
    }
    Ok(next)
}

/// This CLI's own release when its images exist, else `latest` (a CLI built
/// from an unreleased commit).
fn resolve_tag(docker: &str, cli_tag: &str) -> String {
    let exists = Command::new(docker)
        .args(["manifest", "inspect", &format!("{SERVER_IMAGE}:{cli_tag}")])
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .is_ok_and(|s| s.success());
    if exists {
        cli_tag.to_string()
    } else {
        eprintln!("No published images for {cli_tag} yet; using `latest`.");
        "latest".to_string()
    }
}

struct Health {
    version: String,
}

async fn wait_healthy(docker: &str, inst: &Instance, port: u16) -> Result<Health> {
    let http = reqwest::Client::builder()
        .timeout(Duration::from_secs(5))
        .build()?;
    let url = format!("http://127.0.0.1:{port}/health");
    let started = Instant::now();
    let mut told = false;
    loop {
        if let Ok(resp) = http.get(&url).send().await
            && resp.status().is_success()
        {
            let body: serde_json::Value = resp.json().await.unwrap_or_default();
            return Ok(Health {
                version: body["version"].as_str().unwrap_or("").to_string(),
            });
        }
        if started.elapsed() > HEALTH_TIMEOUT {
            eprintln!("The server did not become healthy. Its last log lines:");
            let _ = compose(docker, inst)
                .args(["logs", "--tail", "40", "server"])
                .status();
            bail!(
                "{url} did not answer within {}s; see `everruns docker logs server`",
                HEALTH_TIMEOUT.as_secs()
            );
        }
        if !told && started.elapsed() > Duration::from_secs(3) {
            eprintln!("Waiting for the server (the first start runs database migrations)...");
            told = true;
        }
        tokio::time::sleep(Duration::from_secs(2)).await;
    }
}

fn ask_auth(asker: Asker) -> Result<AuthChoice> {
    if !asker.can_ask() {
        return no_prompt(asker, "--auth", AuthChoice::Single);
    }
    let options = [AuthChoice::Single, AuthChoice::None, AuthChoice::Accounts];
    let labels: Vec<&str> = options.iter().map(|o| o.label()).collect();
    let pick = dialoguer::Select::new()
        .with_prompt("Who signs in?")
        .items(&labels)
        .default(0)
        .interact()
        .context("Failed to read the answer")?;
    Ok(options[pick])
}

fn default_email() -> String {
    Command::new("git")
        .args(["config", "--get", "user.email"])
        .stderr(Stdio::null())
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
        .filter(|e| e.contains('@'))
        .unwrap_or_else(|| "admin@example.com".to_string())
}

fn ask_email(asker: Asker) -> Result<String> {
    let default = default_email();
    if !asker.can_ask() {
        return no_prompt(asker, "--admin-email", default);
    }
    dialoguer::Input::new()
        .with_prompt("Admin email")
        .default(default)
        .validate_with(|e: &String| {
            if e.contains('@') {
                Ok(())
            } else {
                Err("enter an email address")
            }
        })
        .interact_text()
        .context("Failed to read the answer")
}

fn ask_provider(asker: Asker) -> Result<LlmProvider> {
    // A key already in the shell is the obvious default.
    let detected = LlmProvider::ALL.into_iter().find(|p| p.env_key().is_some());
    if !asker.can_ask() {
        return no_prompt(asker, "--provider", detected.unwrap_or(LlmProvider::Skip));
    }
    let labels: Vec<String> = LlmProvider::ALL
        .iter()
        .map(|p| match (p.key_env(), p.env_key()) {
            (Some(var), Some(_)) => format!("{} (use {var} from your shell)", p.label()),
            _ => p.label().to_string(),
        })
        .collect();
    let default = detected
        .and_then(|d| LlmProvider::ALL.iter().position(|p| *p == d))
        .unwrap_or(0);
    let pick = dialoguer::Select::new()
        .with_prompt("LLM provider")
        .items(&labels)
        .default(default)
        .interact()
        .context("Failed to read the answer")?;
    Ok(LlmProvider::ALL[pick])
}

fn set_provider(s: &mut Settings, provider: LlmProvider, asker: Asker) -> Result<()> {
    if let Some(var) = provider.server_env() {
        let key = match provider.env_key() {
            Some(key) => key,
            None if asker.can_ask() => dialoguer::Password::new()
                .with_prompt(format!("{} API key", provider.label()))
                .interact()
                .context("Failed to read the key")?,
            None => bail!(
                "--provider {} needs its key in {}",
                provider.name(),
                provider.key_env().unwrap_or_default()
            ),
        };
        s.set(var, key.trim());
    }
    s.set(settings::LLM_PROVIDER, provider.name());
    Ok(())
}

/// No one to ask: `--yes` takes the default, otherwise name the flag.
fn no_prompt<T>(asker: Asker, flag: &str, default: T) -> Result<T> {
    if asker.yes {
        Ok(default)
    } else {
        bail!("no terminal to ask on; pass {flag} (or --yes to accept the defaults)")
    }
}

/// An instance that has been set up, or a friendly "nothing here yet".
fn existing(args: &InstanceArgs) -> Result<Option<(Instance, Settings)>> {
    let inst = Instance::new(&args.name)?;
    if !inst.exists() {
        return Ok(None);
    }
    let s = Settings::load(&inst.env_path())?;
    Ok(Some((inst, s)))
}

/// ` --name <n>` for messages that suggest a command, empty for the default.
fn name_flag(name: &str) -> String {
    if name == "default" {
        String::new()
    } else {
        format!(" --name {name}")
    }
}

fn not_set_up(args: &InstanceArgs) {
    eprintln!(
        "No local instance yet. Run `everruns docker up{}`.",
        name_flag(&args.name)
    );
}

fn port_of(s: &Settings) -> u16 {
    s.value(settings::PORT)
        .and_then(|p| p.parse().ok())
        .unwrap_or(DEFAULT_PORT)
}

async fn status(args: &InstanceArgs) -> Result<()> {
    let Some((inst, s)) = existing(args)? else {
        not_set_up(args);
        return Ok(());
    };
    let docker = checks::program();
    let port = port_of(&s);
    let auth = s
        .value(settings::AUTH_MODE)
        .and_then(AuthChoice::from_server_mode)
        .map_or("unknown", AuthChoice::label);

    let http = reqwest::Client::builder()
        .timeout(Duration::from_secs(3))
        .build()?;
    let health = match http
        .get(format!("http://127.0.0.1:{port}/health"))
        .send()
        .await
    {
        Ok(resp) if resp.status().is_success() => "healthy".to_string(),
        Ok(resp) => format!("unhealthy ({})", resp.status()),
        Err(_) => "not reachable".to_string(),
    };

    let store = crate::auth::CredentialStore::load().unwrap_or_default();
    let profile = inst.profile();
    let profile_line = match store.profiles.get(&profile) {
        Some(_) if store.current_profile == profile => format!("{profile} (current)"),
        Some(_) => profile.clone(),
        None => "none yet (run `everruns docker up`)".to_string(),
    };

    println!("Instance: {}", inst.name);
    println!("URL:      http://localhost:{port}");
    println!("Health:   {health}");
    println!(
        "Version:  {}",
        s.value(settings::IMAGE_TAG).unwrap_or("unknown")
    );
    println!("Sign-in:  {auth}");
    println!("Profile:  {profile_line}");
    println!("Settings: {}", inst.dir.display());
    println!();
    let _ = compose(&docker, &inst)
        .args(["ps", "--all", "--format", "table {{.Service}}\t{{.Status}}"])
        .status();
    Ok(())
}

fn stop(args: &InstanceArgs) -> Result<()> {
    let Some((inst, _)) = existing(args)? else {
        not_set_up(args);
        return Ok(());
    };
    let docker = checks::program();
    require_docker(&docker, false)?;
    let _lock = inst.lock()?;
    let status = compose(&docker, &inst).arg("stop").status()?;
    if !status.success() {
        bail!("`docker compose stop` failed");
    }
    eprintln!("Stopped. Data is kept; `everruns docker up` starts it again.");
    Ok(())
}

fn logs(args: &InstanceArgs, service: Option<&str>, no_follow: bool) -> Result<()> {
    let Some((inst, _)) = existing(args)? else {
        not_set_up(args);
        return Ok(());
    };
    let mut cmd = compose(&checks::program(), &inst);
    cmd.args(["logs", "--tail", "200"]);
    if !no_follow {
        cmd.arg("--follow");
    }
    if let Some(service) = service {
        cmd.arg(service);
    }
    let status = cmd.status()?;
    if !status.success() {
        bail!("`docker compose logs` failed");
    }
    Ok(())
}

fn open(args: &InstanceArgs) -> Result<()> {
    let Some((_, s)) = existing(args)? else {
        not_set_up(args);
        return Ok(());
    };
    let url = format!("http://localhost:{}", port_of(&s));
    if crate::browser::open(&url).is_err() {
        println!("{url}");
    }
    Ok(())
}

fn doctor(args: &InstanceArgs) -> Result<()> {
    let docker = checks::program();
    let results = checks::run(&docker);
    for check in &results {
        check.print();
    }
    if results.iter().any(checks::Check::failed) {
        bail!("Docker is not ready for a local instance");
    }
    if let Some((inst, s)) = existing(args)? {
        let port = port_of(&s);
        let bind = s.value(settings::BIND).unwrap_or("0.0.0.0");
        let running = running_services(&docker, &inst);
        if running.iter().any(|s| s == "caddy") {
            eprintln!("✓ Port: {port} is this instance's");
        } else if port_free(bind, port) {
            eprintln!("✓ Port: {port} is free");
        } else {
            eprintln!(
                "✗ Port: {port} is used by something else\n  Pick another with `everruns docker up --port <port>`"
            );
            bail!("port {port} is taken");
        }
        if running.iter().any(|s| s == "server") {
            system_doctor(&docker, &inst)?;
        }
    } else if port_free("0.0.0.0", DEFAULT_PORT) {
        eprintln!("✓ Port: {DEFAULT_PORT} is free");
    } else {
        eprintln!("! Port: {DEFAULT_PORT} is in use; `everruns docker up` will offer another");
    }
    Ok(())
}

/// With the instance running, Docker being ready says little about Everruns
/// itself, so run the system doctor inside the server container. It needs no
/// sign-in there and sees the same settings the server does.
fn system_doctor(docker: &str, inst: &Instance) -> Result<()> {
    eprintln!();
    let output = compose(docker, inst)
        .args(["exec", "-T", "server", "/app/everruns-server", "--doctor"])
        .stderr(Stdio::piped())
        .output()
        .context("Failed to run docker compose")?;
    let stderr = String::from_utf8_lossy(&output.stderr);
    // Images from before the doctor reject the flag.
    if stderr.contains("unexpected argument") {
        eprintln!(
            "! System doctor: this server version has none; `everruns docker upgrade` adds it"
        );
        return Ok(());
    }
    print!("{}", String::from_utf8_lossy(&output.stdout));
    match output.status.code() {
        Some(0) => Ok(()),
        Some(1) => bail!("the system doctor found problems; see the fixes above"),
        _ => {
            eprint!("{stderr}");
            bail!("the system doctor could not run in the server container")
        }
    }
}

/// Decision: an upgrade is the one moment a database migration runs, and
/// migrations only go forward, so the database is dumped first. A dump is
/// small next to the cost of a migration that goes wrong on someone's only
/// copy. An older tag is allowed (after a question) for undoing a bad move,
/// but only together with restoring the backup taken before it.
async fn upgrade(args: UpgradeArgs) -> Result<()> {
    let Some((inst, mut s)) = existing(&args.instance)? else {
        not_set_up(&args.instance);
        return Ok(());
    };
    let docker = checks::program();
    require_docker(&docker, false)?;
    let _lock = inst.lock()?;

    let cli_tag = format!("v{}", env!("CARGO_PKG_VERSION"));
    let target = match &args.image_tag {
        Some(tag) => tag.clone(),
        None => resolve_tag(&docker, &cli_tag),
    };
    let current = s.value(settings::IMAGE_TAG).unwrap_or("latest").to_string();
    // `latest` moves under the same name, so it always pulls.
    if target == current && target != "latest" {
        eprintln!("Already on {current}.");
        return Ok(());
    }
    if is_downgrade(&current, &target) {
        let asker = Asker {
            interactive: std::io::stdin().is_terminal() && std::io::stderr().is_terminal(),
            yes: args.yes,
        };
        let reason = format!(
            "{target} is older than {current}. The database was migrated for {current}, \
             so {target} may fail unless you restore a backup taken before."
        );
        if !confirm(asker, &reason, "--yes")? {
            bail!("not moved; still on {current}");
        }
    }

    if !args.no_backup {
        let file = backup(&docker, &inst, &current)?;
        eprintln!("Backed up the database to {}", file.display());
    }

    s.set(settings::IMAGE_TAG, &target);
    s.save(&inst.env_path())?;
    // A newer CLI may carry a newer compose file too.
    inst.write_compose()?;

    let pulled = compose(&docker, &inst)
        .arg("pull")
        .status()
        .context("Failed to run docker compose")?;
    if !pulled.success() {
        // Leave the instance on the tag it can run.
        s.set(settings::IMAGE_TAG, &current);
        s.save(&inst.env_path())?;
        bail!("pulling the {target} images failed; still on {current}");
    }
    let status = compose(&docker, &inst)
        .args(["up", "--detach", "--remove-orphans"])
        .status()
        .context("Failed to run docker compose")?;
    if !status.success() {
        bail!("`docker compose up` failed; see the output above");
    }
    let health = wait_healthy(&docker, &inst, port_of(&s)).await?;
    eprintln!("Everruns is now on {}.", display_version(&health, &target));
    Ok(())
}

fn display_version(health: &Health, tag: &str) -> String {
    if health.version.is_empty() {
        tag.to_string()
    } else {
        format!("{} ({tag})", health.version)
    }
}

/// `vX.Y.Z` as numbers; anything else (such as `latest`) is not comparable.
fn release(tag: &str) -> Option<(u64, u64, u64)> {
    let mut parts = tag.strip_prefix('v').unwrap_or(tag).splitn(3, '.');
    let major = parts.next()?.parse().ok()?;
    let minor = parts.next()?.parse().ok()?;
    let patch = parts.next()?.parse().ok()?;
    Some((major, minor, patch))
}

fn is_downgrade(current: &str, target: &str) -> bool {
    matches!((release(current), release(target)), (Some(c), Some(t)) if t < c)
}

/// Dump the database into the instance's `backups/` folder. Starts PostgreSQL
/// alone if the instance is stopped, so a backup never depends on the server.
fn backup(docker: &str, inst: &Instance, tag: &str) -> Result<std::path::PathBuf> {
    let started = compose(docker, inst)
        .args(["up", "--detach", "--wait", "postgres"])
        .stdout(Stdio::null())
        .status()
        .context("Failed to run docker compose")?;
    if !started.success() {
        bail!("could not start PostgreSQL for the backup; pass --no-backup to skip it");
    }
    let dir = inst.dir.join("backups");
    std::fs::create_dir_all(&dir).with_context(|| format!("Failed to create {}", dir.display()))?;
    let stamp = chrono::Utc::now().format("%Y%m%dT%H%M%SZ");
    let path = dir.join(format!("everruns-{tag}-{stamp}.dump"));
    let file = std::fs::File::create(&path)
        .with_context(|| format!("Failed to create {}", path.display()))?;
    // Private before anything is written: the dump holds every record.
    settings::set_private(&path)?;
    let dumped = compose(docker, inst)
        .args([
            "exec",
            "-T",
            "postgres",
            "pg_dump",
            "--username",
            "everruns",
            "--format",
            "custom",
            "everruns",
        ])
        .stdout(file)
        .status()
        .context("Failed to run pg_dump")?;
    if !dumped.success() {
        let _ = std::fs::remove_file(&path);
        bail!("the database backup failed; pass --no-backup to upgrade without one");
    }
    Ok(path)
}

/// Delete everything the instance has: containers, the database volume, the
/// settings folder (with the encryption key and backups) and its CLI profile.
fn reset(args: &ResetArgs) -> Result<()> {
    let inst = Instance::new(&args.instance.name)?;
    let docker = checks::program();
    // Without a settings folder there can still be containers and a volume
    // from a folder deleted by hand, so check Docker for the project too.
    let has_project = project_exists(&docker, &inst);
    if !inst.dir.exists() && !has_project {
        eprintln!("Nothing to reset: no local instance '{}'.", inst.name);
        return Ok(());
    }
    require_docker(&docker, false)?;

    let asker = Asker {
        interactive: std::io::stdin().is_terminal() && std::io::stderr().is_terminal(),
        yes: args.yes,
    };
    if !asker.yes {
        if !asker.interactive {
            bail!(
                "no terminal to ask on; pass --yes to delete instance '{}'",
                inst.name
            );
        }
        eprintln!(
            "This deletes the local instance '{}': its containers, database and settings \
             in {}, including the backups.",
            inst.name,
            inst.dir.display()
        );
        let typed: String = dialoguer::Input::new()
            .with_prompt(format!("Type '{}' to delete it", inst.name))
            .allow_empty(true)
            .interact_text()
            .context("Failed to read the answer")?;
        if typed.trim() != inst.name {
            bail!("not deleted");
        }
    }

    {
        let _lock = if inst.dir.exists() {
            Some(inst.lock()?)
        } else {
            None
        };
        if inst.dir.exists() {
            // `down` needs the compose file; an old or missing one is replaced.
            inst.write_compose()?;
            if !inst.env_path().exists() {
                std::fs::write(inst.env_path(), "")?;
            }
            let down = compose(&docker, &inst)
                .args(["down", "--volumes", "--remove-orphans"])
                .status()
                .context("Failed to run docker compose")?;
            if !down.success() {
                bail!("`docker compose down` failed; nothing else was deleted");
            }
        } else {
            remove_project(&docker, &inst)?;
        }
    }
    if inst.dir.exists() {
        std::fs::remove_dir_all(&inst.dir)
            .with_context(|| format!("Failed to delete {}", inst.dir.display()))?;
    }
    let removed_profile = forget_profile(&inst.profile())?;

    eprintln!("Deleted the local instance '{}'.", inst.name);
    if removed_profile {
        eprintln!("Removed the CLI profile '{}'.", inst.profile());
    }
    Ok(())
}

/// Whether Docker has containers or volumes of the instance's project.
fn project_exists(docker: &str, inst: &Instance) -> bool {
    let label = format!("label=com.docker.compose.project={}", inst.project());
    [
        vec!["ps", "--all", "--quiet", "--filter", &label],
        vec!["volume", "ls", "--quiet", "--filter", &label],
    ]
    .iter()
    .any(|args| {
        Command::new(docker)
            .args(args)
            .stderr(Stdio::null())
            .output()
            .is_ok_and(|o| o.status.success() && !o.stdout.trim_ascii().is_empty())
    })
}

/// Remove a project's containers and volumes when its compose file is gone.
fn remove_project(docker: &str, inst: &Instance) -> Result<()> {
    let label = format!("label=com.docker.compose.project={}", inst.project());
    for (list, remove) in [
        (vec!["ps", "--all", "--quiet"], vec!["rm", "--force"]),
        (
            vec!["volume", "ls", "--quiet"],
            vec!["volume", "rm", "--force"],
        ),
        (vec!["network", "ls", "--quiet"], vec!["network", "rm"]),
    ] {
        let out = Command::new(docker)
            .args(&list)
            .args(["--filter", &label])
            .output()
            .context("Failed to run docker")?;
        let ids: Vec<String> = String::from_utf8_lossy(&out.stdout)
            .split_whitespace()
            .map(str::to_string)
            .collect();
        if ids.is_empty() {
            continue;
        }
        let status = Command::new(docker)
            .args(&remove)
            .args(&ids)
            .stdout(Stdio::null())
            .status()
            .context("Failed to run docker")?;
        if !status.success() {
            bail!("`docker {}` failed", remove.join(" "));
        }
    }
    Ok(())
}

/// Drop the instance's CLI profile, so nothing points at a server that is gone.
fn forget_profile(profile: &str) -> Result<bool> {
    let mut store = crate::auth::CredentialStore::load().unwrap_or_default();
    if !store.remove_profile(profile) {
        return Ok(false);
    }
    if store.current_profile == profile {
        store.current_profile = String::new();
    }
    store.save()?;
    Ok(true)
}

/// Ask whether to go ahead despite `reason`; without a terminal only `flag`
/// says yes.
fn confirm(asker: Asker, reason: &str, flag: &str) -> Result<bool> {
    if asker.yes {
        return Ok(true);
    }
    if !asker.interactive {
        bail!("{reason} No terminal to ask on; pass {flag} to go ahead");
    }
    dialoguer::Confirm::new()
        .with_prompt(format!("{reason} Continue?"))
        .default(false)
        .interact()
        .context("Failed to read the answer")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn auth_modes_round_trip_through_the_server_names() {
        for choice in [AuthChoice::Single, AuthChoice::None, AuthChoice::Accounts] {
            assert_eq!(
                AuthChoice::from_server_mode(choice.server_mode()),
                Some(choice)
            );
        }
        assert_eq!(AuthChoice::from_server_mode("external"), None);
    }

    #[test]
    fn only_no_sign_in_is_kept_off_the_network() {
        assert_eq!(AuthChoice::None.bind_address(), "127.0.0.1");
        assert_eq!(AuthChoice::Single.bind_address(), "0.0.0.0");
    }

    #[test]
    fn without_a_terminal_the_flag_is_named() {
        let quiet = Asker {
            interactive: false,
            yes: false,
        };
        let err = no_prompt(quiet, "--auth", 1).unwrap_err().to_string();
        assert!(err.contains("--auth") && err.contains("--yes"), "{err}");
        let yes = Asker {
            interactive: false,
            yes: true,
        };
        assert_eq!(no_prompt(yes, "--auth", 1).unwrap(), 1);
    }

    #[test]
    fn provider_flag_without_a_key_fails_without_a_terminal() {
        let quiet = Asker {
            interactive: false,
            yes: true,
        };
        let mut s = Settings::default();
        // Skip needs no key and records the answer.
        set_provider(&mut s, LlmProvider::Skip, quiet).unwrap();
        assert_eq!(s.value(settings::LLM_PROVIDER), Some("skip"));
    }

    #[test]
    fn only_an_older_release_is_a_downgrade() {
        assert!(is_downgrade("v0.49.0", "v0.48.3"));
        assert!(is_downgrade("v1.0.0", "v0.99.99"));
        assert!(!is_downgrade("v0.48.0", "v0.49.0"));
        assert!(!is_downgrade("v0.48.0", "v0.48.0"));
        // `latest` and other names cannot be compared, so they never ask.
        assert!(!is_downgrade("latest", "v0.48.0"));
        assert!(!is_downgrade("v0.48.0", "latest"));
        assert_eq!(release("v0.48.10"), Some((0, 48, 10)));
        assert_eq!(release("main"), None);
    }

    #[test]
    fn suggested_commands_name_only_other_instances() {
        assert_eq!(name_flag("default"), "");
        assert_eq!(name_flag("demo"), " --name demo");
    }

    #[test]
    fn confirm_without_a_terminal_needs_the_flag() {
        let quiet = Asker {
            interactive: false,
            yes: false,
        };
        let err = confirm(quiet, "It is older.", "--yes")
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("It is older.") && err.contains("--yes"),
            "{err}"
        );
        let yes = Asker {
            interactive: false,
            yes: true,
        };
        assert!(confirm(yes, "It is older.", "--yes").unwrap());
    }

    #[test]
    fn a_taken_explicit_port_is_an_error() {
        let held = TcpListener::bind(("127.0.0.1", 0)).unwrap();
        let port = held.local_addr().unwrap().port();
        let asker = Asker {
            interactive: false,
            yes: true,
        };
        assert!(choose_port(port, "127.0.0.1", true, asker).is_err());
        let other = choose_port(port, "127.0.0.1", false, asker).unwrap();
        assert_ne!(other, port);
        let quiet = Asker {
            interactive: false,
            yes: false,
        };
        assert!(choose_port(port, "127.0.0.1", false, quiet).is_err());
    }
}