agent-first-http 0.6.0

Give an AI agent any URL and get back a usable page — fetched directly, or rendered in a real browser when the page needs one — with a human able to take over the same browser for a login, captcha, or 2FA.
Documentation
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
//! `afhttp container` subcommand. Builds the host image and runs it under
//! Docker, Podman, or Apple Container — one command to stand up a long-lived
//! afhttp *host* locally, the orchestration counterpart to `afhttp host` (the
//! in-container browser process). It embeds the canonical `container/docker/
//! Dockerfile` and by default selects its `downloader` stage, which pulls the
//! matching prebuilt release (version hard-pinned to this binary) — so a
//! brew-only user needs no source tree. `--from-source` instead selects the
//! `builder` stage to compile from a checkout. See docs/deployment.md.

use std::path::{Path, PathBuf};
use std::process::Command;

use clap::{Args as ClapArgs, Subcommand, ValueEnum};
use serde::Serialize;

use crate::cli::output;
use crate::shared::error::{Error, ErrorCode};

/// Build context embedded in the binary and written to the cache dir at
/// `install` time. It is the SAME canonical Dockerfile used for from-source
/// builds — the embedded path just selects its `downloader` stage via
/// `--build-arg AFHTTP_BIN_FROM=downloader` (single source of truth, no fork).
const DOCKERFILE: &str = include_str!("../../../container/docker/Dockerfile");
const INSTALL_BACKENDS: &str = include_str!("../../../container/docker/install-backends.sh");
const ENTRYPOINT: &str = include_str!("../../../container/docker/entrypoint.sh");

/// This binary's version — the image downloads exactly this release.
const VERSION: &str = env!("CARGO_PKG_VERSION");
/// Source checkout used to compile this binary. Useful when `--from-source` is
/// requested from a different working directory, such as an agent scratch dir.
const MANIFEST_DIR: &str = env!("CARGO_MANIFEST_DIR");
/// Default container name and image repository.
const DEFAULT_NAME: &str = "afhttp-host";
const IMAGE_REPO: &str = "afhttp-host";

#[derive(ClapArgs, Debug)]
pub struct Args {
    #[command(subcommand)]
    pub sub: ContainerSub,
}

#[derive(Subcommand, Debug)]
pub enum ContainerSub {
    /// Build the host image if missing and run the container; print the client command.
    Install(InstallArgs),
    /// Stop and remove the container (--purge also removes the image and cache).
    Uninstall(UninstallArgs),
    /// Report whether the host is running, with its endpoint and client command.
    Status(StatusArgs),
    /// Stream the container logs (raw passthrough, not a JSON envelope).
    Logs(LogsArgs),
}

/// Flags shared by every subcommand.
#[derive(ClapArgs, Debug)]
pub struct CommonArgs {
    /// Container runtime: docker, podman, or apple (auto-detected if omitted).
    #[arg(long, value_enum)]
    pub runtime: Option<Runtime>,
    /// Container name.
    #[arg(long, default_value = DEFAULT_NAME)]
    pub name: String,
}

#[derive(ClapArgs, Debug)]
pub struct InstallArgs {
    #[command(flatten)]
    pub common: CommonArgs,
    /// Host CDP port, published on 127.0.0.1.
    #[arg(long, default_value_t = 9222)]
    pub port: u16,
    /// Profile name inside the container.
    #[arg(long, default_value = "work")]
    pub profile: String,
    /// Chromium /dev/shm size.
    #[arg(long = "shm-size", default_value = "1g")]
    pub shm_size: String,
    /// Optional backend to build in (repeatable): chrome-headless-shell,
    /// lightpanda, fingerprint-chromium, camoufox, kasmvnc.
    #[arg(long = "with", value_name = "BACKEND")]
    pub with: Vec<String>,
    /// Rebuild the image even if it already exists.
    #[arg(long)]
    pub rebuild: bool,
    /// Build the full image from a source checkout (container/docker/Dockerfile)
    /// instead of downloading the prebuilt release. Needs the source tree.
    #[arg(long = "from-source")]
    pub from_source: bool,
    /// Source checkout to build from with --from-source (default: current dir,
    /// then the checkout this afhttp binary was built from).
    #[arg(long, value_name = "DIR")]
    pub context: Option<String>,
    /// Extra args passed through to `afhttp host` inside the container.
    #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
    pub host_args: Vec<String>,
}

#[derive(ClapArgs, Debug)]
pub struct UninstallArgs {
    #[command(flatten)]
    pub common: CommonArgs,
    /// Also remove the built image and the cached build context.
    #[arg(long)]
    pub purge: bool,
}

#[derive(ClapArgs, Debug)]
pub struct StatusArgs {
    #[command(flatten)]
    pub common: CommonArgs,
    /// Published host port, used to format the endpoint and client command.
    #[arg(long, default_value_t = 9222)]
    pub port: u16,
}

#[derive(ClapArgs, Debug)]
pub struct LogsArgs {
    #[command(flatten)]
    pub common: CommonArgs,
    /// Follow the log output.
    #[arg(long, short = 'f')]
    pub follow: bool,
}

/// Container runtime selector. Parsed from `--runtime` (clap `ValueEnum`) and
/// from `AFHTTP_CONTAINER_RUNTIME` via [`runtime_from_str`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
pub enum Runtime {
    Docker,
    Podman,
    /// Apple's `container` CLI. Accepts `apple` or `container` on the
    /// command line; its binary is `container` (see [`Runtime::bin`]).
    #[value(alias = "container")]
    Apple,
}

impl Runtime {
    /// The runtime's CLI binary name.
    fn bin(self) -> &'static str {
        match self {
            Runtime::Docker => "docker",
            Runtime::Podman => "podman",
            Runtime::Apple => "container",
        }
    }

    /// Human label used in output and errors.
    fn label(self) -> &'static str {
        match self {
            Runtime::Docker => "docker",
            Runtime::Podman => "podman",
            Runtime::Apple => "apple",
        }
    }
}

pub async fn run(args: Args) -> Result<(), Error> {
    match args.sub {
        ContainerSub::Install(a) => install(a).await,
        ContainerSub::Uninstall(a) => uninstall(a),
        ContainerSub::Status(a) => status(a).await,
        ContainerSub::Logs(a) => logs(a),
    }
}

// ── install ────────────────────────────────────────────────────────────────

#[derive(Serialize)]
struct InstallResult {
    runtime: &'static str,
    image: String,
    container: String,
    endpoint: String,
    profile: String,
    token: String,
    client_command: String,
    backends: Vec<String>,
}

async fn install(args: InstallArgs) -> Result<(), Error> {
    let runtime = resolve_runtime(args.common.runtime)?;
    let backends = resolve_backends(&args.with)?;
    validate_install_args(&args, &backends)?;
    let image = image_tag();

    start_daemon(runtime);

    // --from-source always rebuilds (the canonical Dockerfile compiles afhttp);
    // the embedded path reuses a cached image unless --rebuild is set.
    if args.from_source {
        let ctx = resolve_source_context(args.context.as_deref())?;
        let build = build_args(
            &image,
            runtime,
            BuildSource::FromSource { ctx: &ctx },
            &backends,
        );
        exec_inherit(runtime.bin(), &build)?;
    } else if args.rebuild || !image_exists(runtime, &image) {
        let ctx = write_build_context()?;
        let target = target_triple(runtime, std::env::consts::ARCH);
        let build = build_args(
            &image,
            runtime,
            BuildSource::Embedded { ctx: &ctx, target },
            &backends,
        );
        exec_inherit(runtime.bin(), &build).map_err(|_| build_failed_error(target))?;
    }
    validate_container_image_host_args(runtime, &image, &args.host_args)?;

    // Recreate cleanly. The profile + token live in the named volume, so the
    // token is stable across recreation.
    let _ = capture(runtime.bin(), &["stop".into(), args.common.name.clone()]);
    let _ = capture(runtime.bin(), &["rm".into(), args.common.name.clone()]);

    let run = run_args(
        &args.common.name,
        &image,
        args.port,
        &args.profile,
        &args.shm_size,
        &args.host_args,
    );
    exec_inherit(runtime.bin(), &run)?;

    let token = read_token(runtime, &args.common.name).await?;
    let endpoint = endpoint_url(args.port);
    wait_for_container_health(runtime, &args.common.name, args.port, &token).await?;
    output::emit(
        "container_install",
        &InstallResult {
            runtime: runtime.label(),
            image,
            container: args.common.name.clone(),
            endpoint,
            profile: args.profile.clone(),
            client_command: client_command(args.port, &token),
            token,
            backends: backends.iter().map(|b| b.name.to_string()).collect(),
        },
    )
}

// ── uninstall ──────────────────────────────────────────────────────────────

#[derive(Serialize)]
struct UninstallResult {
    runtime: &'static str,
    container: String,
    removed: bool,
    image_removed: bool,
    purged: bool,
}

fn uninstall(args: UninstallArgs) -> Result<(), Error> {
    let runtime = resolve_runtime(args.common.runtime)?;
    let _ = capture(runtime.bin(), &["stop".into(), args.common.name.clone()]);
    let removed = capture(runtime.bin(), &["rm".into(), args.common.name.clone()])
        .map(|o| o.status.success())
        .unwrap_or(false);

    let mut image_removed = false;
    if args.purge {
        let image = image_tag();
        image_removed = capture(runtime.bin(), &["rmi".into(), image])
            .map(|o| o.status.success())
            .unwrap_or(false);
        if let Ok(ctx) = cache_context_dir() {
            let _ = std::fs::remove_dir_all(&ctx);
        }
    }

    output::emit(
        "container_uninstall",
        &UninstallResult {
            runtime: runtime.label(),
            container: args.common.name,
            removed,
            image_removed,
            purged: args.purge,
        },
    )
}

// ── status ─────────────────────────────────────────────────────────────────

#[derive(Serialize)]
struct StatusResult {
    runtime: &'static str,
    container: String,
    running: bool,
    endpoint: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    token: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    client_command: Option<String>,
}

async fn status(args: StatusArgs) -> Result<(), Error> {
    let runtime = resolve_runtime(args.common.runtime)?;
    let running = container_running(runtime, &args.common.name);
    let endpoint = endpoint_url(args.port);

    let token = if running {
        read_token(runtime, &args.common.name).await.ok()
    } else {
        None
    };
    let client_command = token.as_deref().map(|t| client_command(args.port, t));

    output::emit(
        "container_status",
        &StatusResult {
            runtime: runtime.label(),
            container: args.common.name,
            running,
            endpoint,
            token,
            client_command,
        },
    )
}

// ── logs ───────────────────────────────────────────────────────────────────

fn logs(args: LogsArgs) -> Result<(), Error> {
    let runtime = resolve_runtime(args.common.runtime)?;
    let mut argv: Vec<String> = vec!["logs".into()];
    if args.follow {
        argv.push("-f".into());
    }
    argv.push(args.common.name);
    exec_inherit(runtime.bin(), &argv)
}

// ── runtime resolution ───────────────────────────────────────────────────────

fn resolve_runtime(explicit: Option<Runtime>) -> Result<Runtime, Error> {
    if let Some(r) = explicit {
        return Ok(r);
    }
    if let Some(v) = std::env::var_os("AFHTTP_CONTAINER_RUNTIME") {
        return runtime_from_str(v.to_string_lossy().trim());
    }
    if on_path("docker") {
        Ok(Runtime::Docker)
    } else if on_path("podman") {
        Ok(Runtime::Podman)
    } else if on_path("container") {
        Ok(Runtime::Apple)
    } else {
        Err(Error::new(
            ErrorCode::InvalidArgument,
            "no container runtime found: install Docker, Podman, or Apple `container`, or pass --runtime",
        ))
    }
}

fn runtime_from_str(value: &str) -> Result<Runtime, Error> {
    match value {
        "docker" => Ok(Runtime::Docker),
        "podman" => Ok(Runtime::Podman),
        "apple" | "container" => Ok(Runtime::Apple),
        other => Err(Error::new(
            ErrorCode::InvalidArgument,
            format!("invalid container runtime '{other}': expected docker, podman, or apple"),
        )),
    }
}

fn on_path(bin: &str) -> bool {
    let Some(paths) = std::env::var_os("PATH") else {
        return false;
    };
    std::env::split_paths(&paths).any(|dir| dir.join(bin).is_file())
}

/// Apple's runtime needs its daemon started first; on Docker this is a no-op.
/// Best-effort — a real failure surfaces at the build step.
fn start_daemon(runtime: Runtime) {
    if runtime == Runtime::Apple {
        let _ = capture(runtime.bin(), &["system".into(), "start".into()]);
    }
}

// ── arg builders (pure, unit-tested) ─────────────────────────────────────────

fn image_tag() -> String {
    format!("{IMAGE_REPO}:{VERSION}")
}

fn volume_name(name: &str) -> String {
    format!("{name}-data")
}

fn endpoint_url(port: u16) -> String {
    format!("ws://127.0.0.1:{port}")
}

fn client_command(port: u16, token: &str) -> String {
    format!(
        "afhttp fetch https://example.com --endpoint-url ws://127.0.0.1:{port} --token-secret {token}"
    )
}

/// The Linux target triple for the image arch. Apple Container always runs
/// linux/arm64; Docker and Podman match the host arch.
fn target_triple(runtime: Runtime, host_arch: &str) -> &'static str {
    match runtime {
        Runtime::Apple => "aarch64-unknown-linux-gnu",
        Runtime::Docker | Runtime::Podman => match host_arch {
            "aarch64" | "arm64" => "aarch64-unknown-linux-gnu",
            _ => "x86_64-unknown-linux-gnu",
        },
    }
}

/// A resolved optional backend: the `--with` name plus its Dockerfile ARG.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Backend {
    name: &'static str,
    build_arg: &'static str,
}

const BACKENDS: [Backend; 5] = [
    Backend {
        name: "chrome-headless-shell",
        build_arg: "WITH_CHROME_HEADLESS_SHELL",
    },
    Backend {
        name: "lightpanda",
        build_arg: "WITH_LIGHTPANDA",
    },
    Backend {
        name: "fingerprint-chromium",
        build_arg: "WITH_FINGERPRINT_CHROMIUM",
    },
    Backend {
        name: "camoufox",
        build_arg: "WITH_CAMOUFOX",
    },
    Backend {
        name: "kasmvnc",
        build_arg: "WITH_KASMVNC",
    },
];

fn resolve_backends(names: &[String]) -> Result<Vec<Backend>, Error> {
    let mut out = Vec::with_capacity(names.len());
    for name in names {
        let backend = BACKENDS.iter().find(|b| b.name == name).ok_or_else(|| {
            Error::new(
                ErrorCode::InvalidArgument,
                format!(
                    "unknown backend '{name}': expected one of {}",
                    BACKENDS
                        .iter()
                        .map(|b| b.name)
                        .collect::<Vec<_>>()
                        .join(", ")
                ),
            )
        })?;
        if !out.contains(backend) {
            out.push(*backend);
        }
    }
    Ok(out)
}

fn validate_install_args(args: &InstallArgs, backends: &[Backend]) -> Result<(), Error> {
    let camoufox_built = backends.iter().any(|b| b.name == "camoufox");
    if args.profile != "-" && camoufox_built && host_args_select_camoufox(&args.host_args) {
        return Err(Error::new(
            ErrorCode::InvalidArgument,
            "camoufox does not yet support persistent profiles in afhttp; `container install` defaults to `--profile work`. Use `afhttp container install --profile - --with camoufox -- --browser camoufox`.",
        ));
    }
    Ok(())
}

fn host_args_select_camoufox(host_args: &[String]) -> bool {
    host_args
        .windows(2)
        .any(|pair| pair[0] == "--browser" && pair[1].as_str() == "camoufox")
        || host_args.iter().any(|arg| arg == "--browser=camoufox")
}

fn validate_container_image_host_args(
    runtime: Runtime,
    image: &str,
    host_args: &[String],
) -> Result<(), Error> {
    if !host_args_need_display_takeover_support(host_args) {
        return Ok(());
    }
    let Some(help) = container_image_host_help(runtime, image) else {
        return Ok(());
    };
    if help.contains("--display-provider") {
        return Ok(());
    }
    Err(Error::new(
        ErrorCode::InvalidArgument,
        format!(
            "container image `{image}` contains an older afhttp host binary that does not support `--takeover display --display-provider kasmvnc`; rebuild the image from this source checkout: `afhttp container install --from-source --with kasmvnc -- --takeover display --display-provider kasmvnc`"
        ),
    ))
}

fn host_args_need_display_takeover_support(host_args: &[String]) -> bool {
    host_args.iter().any(|arg| arg == "--display-provider")
        || host_args
            .iter()
            .any(|arg| arg.starts_with("--display-provider="))
        || host_args
            .windows(2)
            .any(|pair| pair[0] == "--takeover" && pair[1].as_str() == "display")
        || host_args.iter().any(|arg| arg == "--takeover=display")
}

fn container_image_host_help(runtime: Runtime, image: &str) -> Option<String> {
    let argv = image_host_help_args(image);
    let out = capture(runtime.bin(), &argv).ok()?;
    if !out.status.success() {
        return None;
    }
    let mut help = String::new();
    help.push_str(&String::from_utf8_lossy(&out.stdout));
    help.push_str(&String::from_utf8_lossy(&out.stderr));
    Some(help)
}

fn image_host_help_args(image: &str) -> Vec<String> {
    vec![
        "run".into(),
        "--rm".into(),
        "--entrypoint".into(),
        "/usr/local/bin/afhttp".into(),
        image.to_string(),
        "host".into(),
        "--help".into(),
    ]
}

/// Which `AFHTTP_BIN_FROM` stage of the canonical Dockerfile provides the binary.
/// `Embedded` selects the `downloader` stage (prebuilt release, the default
/// `container install` path); `FromSource` selects the `builder` stage (compile
/// from a checkout). Both build the same `container/docker/Dockerfile`.
enum BuildSource<'a> {
    Embedded { ctx: &'a Path, target: &'a str },
    FromSource { ctx: &'a Path },
}

fn build_args(
    image: &str,
    runtime: Runtime,
    source: BuildSource,
    backends: &[Backend],
) -> Vec<String> {
    let mut a: Vec<String> = vec!["build".into()];
    if runtime == Runtime::Apple {
        a.push("--platform".into());
        a.push("linux/arm64".into());
    }
    let ctx = match source {
        BuildSource::Embedded { ctx, target } => {
            a.push("--build-arg".into());
            a.push("AFHTTP_BIN_FROM=downloader".into());
            a.push("--build-arg".into());
            a.push(format!("AFHTTP_VERSION={VERSION}"));
            a.push("--build-arg".into());
            a.push(format!("AFHTTP_TARGET={target}"));
            ctx
        }
        BuildSource::FromSource { ctx } => {
            a.push("--build-arg".into());
            a.push("AFHTTP_BIN_FROM=builder".into());
            ctx
        }
    };
    for b in backends {
        a.push("--build-arg".into());
        a.push(format!("{}=1", b.build_arg));
    }
    a.push("-t".into());
    a.push(image.to_string());
    a.push("-f".into());
    a.push(
        ctx.join("container/docker/Dockerfile")
            .to_string_lossy()
            .into_owned(),
    );
    a.push(ctx.to_string_lossy().into_owned());
    a
}

/// Resolve and validate the source checkout for `--from-source`.
fn resolve_source_context(arg: Option<&str>) -> Result<PathBuf, Error> {
    if let Some(p) = arg {
        return validate_source_context(PathBuf::from(p), "--context");
    }
    let cwd = std::env::current_dir()
        .map_err(|e| Error::new(ErrorCode::IoError, format!("cannot read current dir: {e}")))?;
    if is_source_context(&cwd) {
        return Ok(cwd);
    }
    let manifest_dir = PathBuf::from(MANIFEST_DIR);
    if manifest_dir != cwd && is_source_context(&manifest_dir) {
        return Ok(manifest_dir);
    }
    Err(Error::new(
        ErrorCode::InvalidArgument,
        format!(
            "--from-source needs a source checkout: checked {} and {} \
             (run from the spore root or pass --context <dir>)",
            cwd.display(),
            manifest_dir.display()
        ),
    ))
}

fn validate_source_context(dir: PathBuf, source: &str) -> Result<PathBuf, Error> {
    let dockerfile = dir.join("container/docker/Dockerfile");
    if !dockerfile.is_file() {
        return Err(Error::new(
            ErrorCode::InvalidArgument,
            format!(
                "--from-source {source} needs a source checkout: {} not found \
                 (run from the spore root or pass --context <dir>)",
                dockerfile.display()
            ),
        ));
    }
    Ok(dir)
}

fn is_source_context(dir: &Path) -> bool {
    dir.join("container/docker/Dockerfile").is_file()
}

fn run_args(
    name: &str,
    image: &str,
    port: u16,
    profile: &str,
    shm_size: &str,
    host_args: &[String],
) -> Vec<String> {
    let mut a: Vec<String> = vec![
        "run".into(),
        "-d".into(),
        "--name".into(),
        name.to_string(),
        "-v".into(),
        format!("{}:/data", volume_name(name)),
        "-e".into(),
        format!("AFHTTP_PORT={port}"),
        "-e".into(),
        format!("AFHTTP_PROFILE={profile}"),
        "--shm-size".into(),
        shm_size.to_string(),
        "-p".into(),
        format!("127.0.0.1:{port}:{port}"),
        image.to_string(),
    ];
    a.extend(host_args.iter().cloned());
    a
}

// ── process plumbing ─────────────────────────────────────────────────────────

fn spawn_error(bin: &str, err: &std::io::Error) -> Error {
    if err.kind() == std::io::ErrorKind::NotFound {
        Error::new(
            ErrorCode::InvalidArgument,
            format!("container runtime `{bin}` not found on PATH"),
        )
    } else {
        Error::new(
            ErrorCode::IoError,
            format!("spawning `{bin}` failed: {err}"),
        )
    }
}

/// Run a runtime command, inheriting stdio so the user sees build/run progress.
fn exec_inherit(bin: &str, args: &[String]) -> Result<(), Error> {
    let status = Command::new(bin)
        .args(args)
        .status()
        .map_err(|e| spawn_error(bin, &e))?;
    if status.success() {
        Ok(())
    } else {
        Err(Error::new(
            ErrorCode::InternalError,
            format!("`{bin} {}` failed ({status})", args.join(" ")),
        ))
    }
}

/// Run a runtime command capturing stdout/stderr.
fn capture(bin: &str, args: &[String]) -> Result<std::process::Output, Error> {
    Command::new(bin)
        .args(args)
        .output()
        .map_err(|e| spawn_error(bin, &e))
}

fn image_exists(runtime: Runtime, image: &str) -> bool {
    capture(
        runtime.bin(),
        &["image".into(), "inspect".into(), image.to_string()],
    )
    .map(|o| o.status.success())
    .unwrap_or(false)
}

fn container_running(runtime: Runtime, name: &str) -> bool {
    // Plain `ps` (no --format) so the check works the same on Docker and Apple.
    capture(runtime.bin(), &["ps".into()])
        .map(|o| String::from_utf8_lossy(&o.stdout).contains(name))
        .unwrap_or(false)
}

/// Read the bearer token the entrypoint persisted to the data volume. The
/// entrypoint writes it on first start, so retry briefly after `run`.
async fn read_token(runtime: Runtime, name: &str) -> Result<String, Error> {
    let argv = vec![
        "exec".into(),
        name.to_string(),
        "cat".into(),
        "/data/afhttp/host-token".into(),
    ];
    for attempt in 0..20 {
        if let Ok(out) = capture(runtime.bin(), &argv) {
            if out.status.success() {
                let token = String::from_utf8_lossy(&out.stdout).trim().to_string();
                if !token.is_empty() {
                    return Ok(token);
                }
            }
        }
        if !container_running(runtime, name) {
            return Err(container_launch_failure_error(
                runtime,
                name,
                "container exited before the host token could be read",
            ));
        }
        if attempt < 19 {
            tokio::time::sleep(std::time::Duration::from_millis(500)).await;
        }
    }
    Err(container_launch_failure_error(
        runtime,
        name,
        "host token was not available before the startup deadline",
    ))
}

async fn wait_for_container_health(
    runtime: Runtime,
    name: &str,
    port: u16,
    token: &str,
) -> Result<(), Error> {
    let endpoint = endpoint_url(port);
    let client = crate::sdk::Client::connect(&endpoint)?.with_token(token.to_string());
    for attempt in 0..30 {
        if !container_running(runtime, name) {
            return Err(container_launch_failure_error(
                runtime,
                name,
                "container exited before /health became ready",
            ));
        }
        match client.health().await {
            Ok(health) if health.status == "ok" => return Ok(()),
            Ok(health) => {
                if let Some(backend_error) = health.backend_error {
                    return Err(Error::new(
                        backend_error.error_code,
                        format!(
                            "container host /health reported {}: {}",
                            health.status, backend_error.error
                        ),
                    ));
                }
            }
            Err(_) => {}
        }
        if attempt < 29 {
            tokio::time::sleep(std::time::Duration::from_millis(500)).await;
        }
    }
    Err(container_launch_failure_error(
        runtime,
        name,
        "container host did not pass /health before the startup deadline",
    ))
}

fn container_launch_failure_error(runtime: Runtime, name: &str, reason: &str) -> Error {
    let logs = container_logs_summary(runtime, name);
    let lower = logs.to_ascii_lowercase();
    let code = if lower.contains("backend_unsupported")
        || lower.contains("persistent profiles")
        || lower.contains("does not yet support")
    {
        ErrorCode::BackendUnsupported
    } else {
        ErrorCode::BrowserLaunchFailed
    };
    let mut detail = format!("container host launch failed: {reason}");
    if !logs.is_empty() {
        detail.push_str("; recent logs: ");
        detail.push_str(&logs);
    }
    Error::new(code, detail)
}

fn container_logs_summary(runtime: Runtime, name: &str) -> String {
    let Ok(out) = capture(runtime.bin(), &["logs".into(), name.to_string()]) else {
        return String::new();
    };
    let mut combined = String::new();
    combined.push_str(&String::from_utf8_lossy(&out.stdout));
    combined.push_str(&String::from_utf8_lossy(&out.stderr));
    let lines: Vec<&str> = combined.lines().rev().take(60).collect();
    let mut summary = lines.into_iter().rev().collect::<Vec<_>>().join(" | ");
    const MAX: usize = 4000;
    if summary.len() > MAX {
        let start = summary.len() - MAX;
        summary = format!("...{}", &summary[start..]);
    }
    summary
}

fn build_failed_error(target: &str) -> Error {
    Error::new(
        ErrorCode::InternalError,
        format!(
            "image build failed. If v{VERSION} has no published release asset for \
             {target}, build from a source checkout instead: \
             `afhttp container install --from-source` (or \
             docker compose -f container/docker/compose.yaml up --build)"
        ),
    )
}

// ── embedded build context ───────────────────────────────────────────────────

fn cache_context_dir() -> Result<PathBuf, Error> {
    let base = std::env::var_os("XDG_CACHE_HOME")
        .map(PathBuf::from)
        .filter(|p| p.is_absolute())
        .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache")))
        .ok_or_else(|| {
            Error::new(
                ErrorCode::IoError,
                "cannot resolve cache dir: set HOME or XDG_CACHE_HOME",
            )
        })?;
    Ok(base.join("afhttp").join("container").join(VERSION))
}

fn write_build_context() -> Result<PathBuf, Error> {
    let root = cache_context_dir()?;
    // Mirror the repo's container/docker/ layout so the Dockerfile's COPY paths
    // resolve the same way they do for a from-source build. The downloader stage
    // pulls the binary over the network, so no source tree is needed here.
    let dir = root.join("container").join("docker");
    std::fs::create_dir_all(&dir)?;
    std::fs::write(dir.join("Dockerfile"), DOCKERFILE)?;
    std::fs::write(dir.join("install-backends.sh"), INSTALL_BACKENDS)?;
    std::fs::write(dir.join("entrypoint.sh"), ENTRYPOINT)?;
    Ok(root)
}

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

    #[test]
    fn runtime_from_str_parses_and_rejects() {
        assert_eq!(runtime_from_str("docker").unwrap(), Runtime::Docker);
        assert_eq!(runtime_from_str("podman").unwrap(), Runtime::Podman);
        assert_eq!(runtime_from_str("apple").unwrap(), Runtime::Apple);
        assert_eq!(runtime_from_str("container").unwrap(), Runtime::Apple);
        assert_eq!(
            runtime_from_str("nerdctl").unwrap_err().error_code,
            ErrorCode::InvalidArgument
        );
    }

    #[test]
    fn explicit_runtime_wins_over_detection() {
        assert_eq!(
            resolve_runtime(Some(Runtime::Apple)).unwrap(),
            Runtime::Apple
        );
        assert_eq!(
            resolve_runtime(Some(Runtime::Docker)).unwrap(),
            Runtime::Docker
        );
    }

    #[test]
    fn target_triple_tracks_runtime_and_arch() {
        assert_eq!(
            target_triple(Runtime::Apple, "x86_64"),
            "aarch64-unknown-linux-gnu"
        );
        assert_eq!(
            target_triple(Runtime::Docker, "aarch64"),
            "aarch64-unknown-linux-gnu"
        );
        assert_eq!(
            target_triple(Runtime::Docker, "x86_64"),
            "x86_64-unknown-linux-gnu"
        );
        // Podman matches the host arch, same as Docker.
        assert_eq!(
            target_triple(Runtime::Podman, "aarch64"),
            "aarch64-unknown-linux-gnu"
        );
        assert_eq!(
            target_triple(Runtime::Podman, "x86_64"),
            "x86_64-unknown-linux-gnu"
        );
    }

    #[test]
    fn backend_names_map_to_build_args_and_reject_unknown() {
        let resolved = resolve_backends(&["camoufox".into(), "kasmvnc".into()]).unwrap();
        assert_eq!(resolved.len(), 2);
        assert_eq!(resolved[0].build_arg, "WITH_CAMOUFOX");
        assert_eq!(resolved[1].build_arg, "WITH_KASMVNC");

        // Duplicates collapse.
        let deduped = resolve_backends(&["camoufox".into(), "camoufox".into()]).unwrap();
        assert_eq!(deduped.len(), 1);

        assert_eq!(
            resolve_backends(&["nope".into()]).unwrap_err().error_code,
            ErrorCode::InvalidArgument
        );
    }

    #[test]
    fn install_precheck_rejects_camoufox_with_persistent_profile() {
        let args = InstallArgs {
            common: CommonArgs {
                runtime: Some(Runtime::Docker),
                name: "afhttp-host".into(),
            },
            port: 9222,
            profile: "work".into(),
            shm_size: "1g".into(),
            with: vec!["camoufox".into()],
            rebuild: false,
            from_source: false,
            context: None,
            host_args: vec!["--browser".into(), "camoufox".into()],
        };
        let backends = resolve_backends(&args.with).unwrap();
        let err = validate_install_args(&args, &backends).unwrap_err();
        assert_eq!(err.error_code, ErrorCode::InvalidArgument);
        assert!(err.detail.contains("--profile -"));
    }

    #[test]
    fn install_precheck_allows_camoufox_ephemeral_profile() {
        let args = InstallArgs {
            common: CommonArgs {
                runtime: Some(Runtime::Docker),
                name: "afhttp-host".into(),
            },
            port: 9222,
            profile: "-".into(),
            shm_size: "1g".into(),
            with: vec!["camoufox".into()],
            rebuild: false,
            from_source: false,
            context: None,
            host_args: vec!["--browser=camoufox".into()],
        };
        let backends = resolve_backends(&args.with).unwrap();
        validate_install_args(&args, &backends).unwrap();
    }

    #[test]
    fn display_host_args_trigger_image_support_probe() {
        assert!(host_args_need_display_takeover_support(&[
            "--takeover".into(),
            "display".into()
        ]));
        assert!(host_args_need_display_takeover_support(&[
            "--takeover=display".into()
        ]));
        assert!(host_args_need_display_takeover_support(&[
            "--display-provider".into(),
            "kasmvnc".into()
        ]));
        assert!(host_args_need_display_takeover_support(&[
            "--display-provider=kasmvnc".into()
        ]));
        assert!(!host_args_need_display_takeover_support(&[
            "--takeover".into(),
            "screencast".into()
        ]));
    }

    #[test]
    fn image_host_help_args_bypasses_entrypoint() {
        let args = image_host_help_args("afhttp-host:dev");
        assert_eq!(args[0], "run");
        assert!(args.contains(&"--rm".to_string()));
        assert!(args.contains(&"--entrypoint".to_string()));
        assert!(args.contains(&"/usr/local/bin/afhttp".to_string()));
        assert_eq!(args[args.len() - 3], "afhttp-host:dev");
        assert_eq!(args[args.len() - 2], "host");
        assert_eq!(args[args.len() - 1], "--help");
    }

    #[test]
    fn embedded_build_args_include_version_target_and_apple_platform() {
        let ctx = PathBuf::from("/cache/ctx");
        let backends = resolve_backends(&["lightpanda".into()]).unwrap();
        let docker = build_args(
            "afhttp-host:1.2.3",
            Runtime::Docker,
            BuildSource::Embedded {
                ctx: &ctx,
                target: "x86_64-unknown-linux-gnu",
            },
            &backends,
        );
        assert_eq!(docker[0], "build");
        assert!(!docker.contains(&"--platform".to_string()));
        assert!(docker.contains(&"AFHTTP_BIN_FROM=downloader".to_string()));
        assert!(docker.contains(&format!("AFHTTP_VERSION={VERSION}")));
        assert!(docker.contains(&"AFHTTP_TARGET=x86_64-unknown-linux-gnu".to_string()));
        assert!(docker.contains(&"WITH_LIGHTPANDA=1".to_string()));
        assert_eq!(
            docker[docker.len() - 2],
            "/cache/ctx/container/docker/Dockerfile"
        );
        assert_eq!(docker.last().unwrap(), "/cache/ctx");

        let apple = build_args(
            "afhttp-host:1.2.3",
            Runtime::Apple,
            BuildSource::Embedded {
                ctx: &ctx,
                target: "aarch64-unknown-linux-gnu",
            },
            &[],
        );
        let pos = apple.iter().position(|a| a == "--platform").unwrap();
        assert_eq!(apple[pos + 1], "linux/arm64");
    }

    #[test]
    fn from_source_build_args_use_canonical_dockerfile_no_release_args() {
        let repo = PathBuf::from("/repo");
        let backends = resolve_backends(&["camoufox".into()]).unwrap();
        let args = build_args(
            "afhttp-host:1.2.3",
            Runtime::Podman,
            BuildSource::FromSource { ctx: &repo },
            &backends,
        );
        // Selects the builder stage; no download build-args.
        assert!(args.contains(&"AFHTTP_BIN_FROM=builder".to_string()));
        assert!(!args.iter().any(|a| a.starts_with("AFHTTP_VERSION=")));
        assert!(!args.iter().any(|a| a.starts_with("AFHTTP_TARGET=")));
        assert!(args.contains(&"WITH_CAMOUFOX=1".to_string()));
        assert_eq!(args[args.len() - 2], "/repo/container/docker/Dockerfile");
        assert_eq!(args.last().unwrap(), "/repo");
        // Podman gets no --platform (host arch), same as Docker.
        assert!(!args.contains(&"--platform".to_string()));
    }

    #[test]
    fn run_args_publish_loopback_and_pass_host_args() {
        let a = run_args(
            "afhttp-host",
            "afhttp-host:1.2.3",
            9222,
            "work",
            "1g",
            &["--browser".into(), "camoufox".into()],
        );
        assert!(a.contains(&"afhttp-host-data:/data".to_string()));
        assert!(a.contains(&"AFHTTP_PORT=9222".to_string()));
        assert!(a.contains(&"AFHTTP_PROFILE=work".to_string()));
        assert!(a.contains(&"127.0.0.1:9222:9222".to_string()));
        // Image precedes the passthrough host args.
        let img = a.iter().position(|x| x == "afhttp-host:1.2.3").unwrap();
        let br = a.iter().position(|x| x == "--browser").unwrap();
        assert!(img < br);
    }

    #[test]
    fn client_command_uses_loopback_endpoint() {
        let cmd = client_command(9333, "deadbeef");
        assert!(cmd.contains("--endpoint-url ws://127.0.0.1:9333"));
        assert!(cmd.contains("--token-secret deadbeef"));
    }

    #[test]
    fn build_failure_error_points_at_compose_fallback() {
        let err = build_failed_error("aarch64-unknown-linux-gnu");
        assert_eq!(err.error_code, ErrorCode::InternalError);
        assert!(err.detail.contains("compose"));
        assert!(err.detail.contains("aarch64-unknown-linux-gnu"));
    }
}