diff --git a/.claude/skills/issues/SKILL.md b/.claude/skills/issues/SKILL.md index b6bc2e22..f8acd323 100644 --- a/.claude/skills/issues/SKILL.md +++ b/.claude/skills/issues/SKILL.md @@ -123,8 +123,9 @@ links in someone else's text. ## Other repositories -hyperstructure has three repositories: fctl (this one), fctl-site (fctl.sh) -and design (`@hyperstructure/design`). An fctl session's GitHub token covers +hyperstructure has four repositories: fctl (this one), fctl-site (fctl.sh), +design (`@hyperstructure/design`) and sandbox (the default sandbox image, +public). An fctl session's GitHub token covers only its own repository. When a change needs work in another one, name it in your pull request or issue ("fctl-site needs the new docs page in `PAGES`") and tell the person. Only open the change there yourself when you diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md index ec039d5e..a28eebd7 100644 --- a/.claude/skills/release/SKILL.md +++ b/.claude/skills/release/SKILL.md @@ -1,6 +1,6 @@ --- name: release -description: Release a new version of fctl through the Release workflow, which publishes the archives to GitHub and fctl.sh/releases, updates the CHANGELOG and redeploys app.fctl.sh. Only for people and agents with release access (write access to Actions on hyperstructure/fctl). Use when asked to release, publish or ship fctl, to preview what the next release contains, or to fix a failed release. +description: Release a new version of fctl through the Release workflow, which publishes the archives to GitHub and fctl.sh/releases, updates the CHANGELOG and redeploys app.fctl.sh; hyperstructure/sandbox then publishes the release's sandbox image to GHCR. Only for people and agents with release access (write access to Actions on hyperstructure/fctl). Use when asked to release, publish or ship fctl, to preview what the next release contains, or to fix a failed release. --- # Releasing fctl @@ -59,6 +59,14 @@ It runs in three steps: the installer as a check, and starts CI on `main`, which redeploys app.fctl.sh. +Within the hour, the Image workflow of +[hyperstructure/sandbox](https://github.com/hyperstructure/sandbox) finds +the release on fctl.sh and publishes its sandbox image, +`ghcr.io/hyperstructure/sandbox:X.Y.Z`, for arm64 and amd64, moving `X.Y` +and `latest`. Hosts of the new version pull it; until it is there, their +sessions start from `latest`. To publish it at once: +`gh workflow run image.yml -R hyperstructure/sandbox`. + Follow it with `gh run watch` or in the Actions tab; it takes about 10 minutes. @@ -68,6 +76,10 @@ minutes. `fctl self update --check` sees it. - The GitHub release and `CHANGELOG.md` on `main` have the notes. - `https://app.fctl.sh/api/v1/health` reports the version once CI is done. +- Within the hour, `docker buildx imagetools inspect + ghcr.io/hyperstructure/sandbox:X.Y.Z` lists linux/amd64 and linux/arm64 + (`gh run list -R hyperstructure/sandbox --workflow image.yml` shows the + runs). - Hosts update with `fctl self update` (it restarts the host service; running sessions keep going). @@ -82,6 +94,12 @@ minutes. tag from the start with `gh workflow run release.yml --ref main -f tag=vX.Y.Z`. If the code is broken, fix it and release a patch. +- **The image** (hyperstructure/sandbox's Image workflow failed, or the + release has no image after an hour): its `publish` skill says what to do. + Start it for the release with + `gh workflow run image.yml -R hyperstructure/sandbox -f version=X.Y.Z`. + The image is built from that repository's `main`, so fixing it takes a + pull request there, not an fctl release. - Never move or delete a published tag or its files on fctl.sh: installed CLIs and hosts download releases by version. @@ -90,3 +108,5 @@ minutes. - **hyperstructure/design** releases are tags as well; see its AGENTS.md and release skill. - **hyperstructure/fctl-site** deploys from `main` and has no releases. +- **hyperstructure/sandbox** publishes the sandbox image from `main`, for + every fctl release; see its AGENTS.md and publish skill. diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 157778ac..08f5d808 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -7,10 +7,12 @@ # then cross-compile the release binaries, all at once (`cargo xtask dist # build`), and "Publish" makes the archives from them, makes the GitHub # release with the notes, publishes to https://fctl.sh/releases and starts CI -# on main, which redeploys app.fctl.sh. `tag` rebuilds an existing release tag -# from main; `dry_run` only shows what would ship. Tags pushed by hand do not -# publish anything: starting this workflow takes write access to Actions, -# which agents running in fctl sessions do not have. +# on main, which redeploys app.fctl.sh. Within the hour, hyperstructure/sandbox +# publishes the release's sandbox image, ghcr.io/hyperstructure/sandbox:. +# `tag` rebuilds an existing release tag from main; `dry_run` only shows what +# would ship. Tags pushed by hand do not publish anything: starting this +# workflow takes write access to Actions, which agents running in fctl +# sessions do not have. name: Release on: diff --git a/AGENTS.md b/AGENTS.md index 2a1a0c23..852420bd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -90,9 +90,17 @@ fake-claude's behaviors are listed in [docs/development.md](docs/development.md) policy (`legal/privacy.md`) says what app.fctl.sh stores, who receives it and how long it is kept: a change here that alters any of that needs a matching change there. - -Both are private for now: `npm ci` reaches the design package over git, so -it needs GitHub access (CI uses a read-only deploy key). +- [hyperstructure/sandbox](https://github.com/hyperstructure/sandbox): the + default sandbox image, `ghcr.io/hyperstructure/sandbox`, published for + every release. Hosts pull it, and `fctl host image build` builds its + `main`. The host relies on its layout (the `agent` user, the PATH, + `/opt/fctl/bin`) and on `Dockerfile` and `provision.sh` at its root: + change those there, together with `docs/sandbox-images.md` here. Its Rust + is the one in `rust-toolchain.toml`; bump the two together. + +design and fctl-site are private for now: `npm ci` reaches the design +package over git, so it needs GitHub access (CI uses a read-only deploy +key). sandbox is public. ## Commits, pull requests and releases @@ -137,8 +145,8 @@ it needs GitHub access (CI uses a read-only deploy key). #13, and add labels. Add to other people's issues (a comment or a new section) instead of rewriting them. - An fctl session's token covers only this repository: name what - hyperstructure/fctl-site or hyperstructure/design need, and tell the - person. + hyperstructure/fctl-site, hyperstructure/design or hyperstructure/sandbox + need, and tell the person. - The procedures: [.claude/skills/issues/SKILL.md](.claude/skills/issues/SKILL.md). ## After opening a pull request diff --git a/Cargo.lock b/Cargo.lock index 669243dc..6dc3cb22 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -610,12 +610,14 @@ dependencies = [ "fctl-client", "fctl-domain", "fctl-proto", + "flate2", "futures", "hex", "regex", "serde", "serde_json", "sha2", + "tar", "tempfile", "tokio", "tokio-tungstenite", diff --git a/Cargo.toml b/Cargo.toml index 1e73a0dc..c0389851 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -43,6 +43,7 @@ anyhow = "1.0.104" base64 = "0.23.1" bytes = "1.12.1" clap = { version = "4.6.7", features = ["derive", "env", "wrap_help"] } +flate2 = "1.1.10" futures = "0.3.34" getrandom = "0.4.3" hex = "0.4.3" @@ -60,6 +61,7 @@ serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.154" serde_with = { version = "3", default-features = false, features = ["macros"] } sha2 = "0.11.1" +tar = "0.4.46" thiserror = "2.0.21" tokio = { version = "1.53.3", features = ["full"] } toml = "1.1.8" diff --git a/README.md b/README.md index c3a0de60..8f49e7c8 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ sessions with your team. ```sh curl -fsSL https://fctl.sh/install | sh fctl login app.fctl.sh -fctl host install --build-image # this machine now runs agents +fctl host install # this machine now runs agents fctl run -p my-app "Add a dark mode toggle" ``` diff --git a/ROADMAP.md b/ROADMAP.md index ed0edfc2..0496b4cd3 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -48,7 +48,7 @@ this file is the overview. Order within a section is priority. container driver (DNS, clock, disk, caches) from what they show (#1) - [x] CI on GitHub Actions: checks on pull requests, deploys from `main`, releases from tags -- [ ] Prebuilt sandbox images (GHCR) so `fctl host image build` is a pull (#2) +- [x] Prebuilt sandbox images (GHCR) so `fctl host image build` is a pull (#2) - [ ] Shared caches per project (npm, cargo, uv) mounted into sandboxes (#3) - [x] Notifications when a session waits for you or fails: web push, with followers, per-person settings and digests (#4) diff --git a/crates/fctl-agent/src/supervisor.rs b/crates/fctl-agent/src/supervisor.rs index d38c83a0..66db3ea5 100644 --- a/crates/fctl-agent/src/supervisor.rs +++ b/crates/fctl-agent/src/supervisor.rs @@ -657,7 +657,7 @@ impl Supervisor { self.log( LogSource::Agent, LogLevel::Info, - "This sandbox has no fctl that can rename the session, so it keeps the title it started with. Rebuilding the default image (fctl host image build) installs one.", + "This sandbox has no fctl that can rename the session, so it keeps the title it started with. The default image, ghcr.io/hyperstructure/sandbox, has one; an image of your own needs fctl on the PATH.", ); } let setting_sources = match claude::project_settings_are_unsafe(&paths.workdir) { diff --git a/crates/fctl-host/Cargo.toml b/crates/fctl-host/Cargo.toml index cd52b3c0..58aacacb 100644 --- a/crates/fctl-host/Cargo.toml +++ b/crates/fctl-host/Cargo.toml @@ -13,11 +13,13 @@ base64.workspace = true fctl-client.workspace = true fctl-domain.workspace = true fctl-proto.workspace = true +flate2.workspace = true futures.workspace = true regex.workspace = true serde.workspace = true serde_json.workspace = true sha2.workspace = true +tar.workspace = true hex.workspace = true tokio.workspace = true tokio-tungstenite.workspace = true diff --git a/crates/fctl-host/src/config.rs b/crates/fctl-host/src/config.rs index d808b1e8..55c63ad4 100644 --- a/crates/fctl-host/src/config.rs +++ b/crates/fctl-host/src/config.rs @@ -5,7 +5,7 @@ //! name = "studio-mac" //! driver = "auto" # apple | docker | lima | process | auto //! capacity = 4 -//! image = "fctl-agent:latest" +//! image = "ghcr.io/acme/agent:1" # unset: the published image of this version //! cpus = 4 # per sandbox, when its project sets none //! memory_mb = 8192 # per sandbox, when its project sets none //! max_cpus = 8 # per sandbox (default: what the machine has) @@ -19,6 +19,26 @@ use fctl_proto::runner::{SandboxLimits, SandboxSize}; use serde::{Deserialize, Serialize}; use std::path::{Path, PathBuf}; +/// Where the default sandbox image is published, by the Image workflow of +/// https://github.com/hyperstructure/sandbox: a tag for every release. +pub const IMAGE_REPOSITORY: &str = "ghcr.io/hyperstructure/sandbox"; + +/// The default image before it was published, which hosts installed until +/// then have in host.toml. +const OLD_DEFAULT_IMAGE: &str = "fctl-agent:latest"; + +/// The published sandbox image of this version of fctl. +pub fn default_image() -> String { + format!("{IMAGE_REPOSITORY}:{}", crate::agentbin::VERSION) +} + +/// Whether an image setting, the host's or a project's, means the host's +/// default: empty, or the name the default had before it was published. +pub fn means_default_image(image: &str) -> bool { + let image = image.trim(); + image.is_empty() || image == OLD_DEFAULT_IMAGE +} + #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(default)] pub struct HostConfig { @@ -29,8 +49,9 @@ pub struct HostConfig { pub driver: String, /// Maximum concurrent sessions. pub capacity: u32, - /// Sandbox image for sessions whose project sets none. - pub image: String, + /// Sandbox image for sessions whose project sets none. Unset: the + /// published image of this host's version ([`default_image`]). + pub image: Option, /// CPUs and memory (MiB) for sandboxes whose project sets none. pub cpus: u32, pub memory_mb: u32, @@ -62,7 +83,7 @@ impl Default for HostConfig { name: hostname(), driver: "auto".into(), capacity: 4, - image: "fctl-agent:latest".into(), + image: None, cpus: 4, memory_mb: 8192, max_cpus: None, @@ -142,7 +163,13 @@ impl HostConfig { path.display() ) })?; - toml::from_str(&text).with_context(|| format!("parsing {}", path.display())) + Self::from_toml(&text).with_context(|| format!("parsing {}", path.display())) + } + + fn from_toml(text: &str) -> Result { + let mut cfg: Self = toml::from_str(text)?; + cfg.image = cfg.image.filter(|i| !means_default_image(i)); + Ok(cfg) } pub fn save(&self) -> Result<()> { @@ -182,6 +209,21 @@ impl HostConfig { self.data_dir.clone().unwrap_or_else(default_data_dir) } + /// The sandbox image for sessions whose project sets none. + pub fn image(&self) -> String { + self.image.clone().unwrap_or_else(default_image) + } + + /// What sandboxes use when [`image`](Self::image) can't be pulled: on + /// the default image, the latest published one. A release's own image is + /// published a few minutes after the release, and development builds may + /// have a version with none. + pub fn fallback_image(&self) -> Option { + self.image + .is_none() + .then(|| format!("{IMAGE_REPOSITORY}:latest")) + } + /// What this host gives each sandbox: the configured defaults and /// maximums, within `runtime`, what the sandboxes run on has (0: unknown). pub fn sandbox_limits(&self, runtime: SandboxSize) -> SandboxLimits { @@ -225,6 +267,31 @@ mod tests { SandboxSize { cpus, memory_mb } } + #[test] + fn hosts_on_the_default_image_follow_their_version() -> Result<()> { + let published = format!( + "ghcr.io/hyperstructure/sandbox:{}", + crate::agentbin::VERSION + ); + // Unset, empty, or the default's name from before it was published. + for text in ["", "image = \"\"", "image = \"fctl-agent:latest\""] { + let cfg = HostConfig::from_toml(text)?; + assert_eq!(cfg.image, None, "{text}"); + assert_eq!(cfg.image(), published); + assert_eq!( + cfg.fallback_image().as_deref(), + Some("ghcr.io/hyperstructure/sandbox:latest") + ); + } + let cfg = HostConfig::from_toml("image = \"ghcr.io/acme/agent:1\"")?; + assert_eq!(cfg.image(), "ghcr.io/acme/agent:1"); + assert_eq!(cfg.fallback_image(), None); + // host.toml leaves the default out, so the next version brings its own. + let saved = toml::to_string_pretty(&HostConfig::default())?; + assert!(!saved.lines().any(|l| l.starts_with("image")), "{saved}"); + Ok(()) + } + #[test] fn sandboxes_get_at_most_what_the_runtime_has() { let docker_vm = size(10, 15_990); diff --git a/crates/fctl-host/src/daemon.rs b/crates/fctl-host/src/daemon.rs index 3f9ca996..61f8fd94 100644 --- a/crates/fctl-host/src/daemon.rs +++ b/crates/fctl-host/src/daemon.rs @@ -113,6 +113,26 @@ impl Daemon { }) } + /// Pulls the host's sandbox image in the background when it isn't here + /// yet, so that the first session after an upgrade doesn't wait for it. + fn prefetch_image(&self) { + if !self.ctx.driver.uses_images() { + return; + } + let ctx = self.ctx.clone(); + tokio::spawn(async move { + let image = ctx.cfg.image(); + if ctx.driver.has_image(&image).await { + return; + } + tracing::info!("pulling {image}"); + match ctx.driver.pull(&image, false).await { + Ok(()) => tracing::info!("pulled {image}"), + Err(e) => tracing::warn!("pulling {image}: {e:#} (sessions try again)"), + } + }); + } + /// Re-attaches to sandboxes that survived a restart. False when the /// runtime doesn't answer: the hello must not tell the control plane /// that sessions are gone (it would stop them) when they may still run. @@ -284,7 +304,7 @@ impl Daemon { capacity: self.ctx.cfg.capacity, labels: self.ctx.cfg.labels.clone(), sessions: self.reports(), - image: Some(self.ctx.cfg.image.clone()), + image: Some(self.ctx.cfg.image()), sandbox: Some(self.ctx.sandbox_limits()), } } @@ -321,6 +341,8 @@ impl Daemon { } wait = (wait * 2).min(Duration::from_secs(60)); } + // Once the runtime answers. + self.prefetch_image(); self.start_sweep(); refresh_facts_every(self.ctx.clone(), FACTS_EVERY); let url = format!( diff --git a/crates/fctl-host/src/driver/container.rs b/crates/fctl-host/src/driver/container.rs index be9b2057..74149831 100644 --- a/crates/fctl-host/src/driver/container.rs +++ b/crates/fctl-host/src/driver/container.rs @@ -28,6 +28,13 @@ pub struct ContainerDriver { bin: String, } +/// Why a sandbox wasn't created. +enum Create { + /// Its image isn't on this host and pulling it failed. + NoImage(anyhow::Error), + Failed(anyhow::Error), +} + impl ContainerDriver { pub fn apple() -> Self { Self { @@ -195,6 +202,33 @@ impl ContainerDriver { "Creating sandbox {} from {}", spec.name, spec.image )); + let pull_error = match self.create(spec, &spec.image, log).await { + Ok(()) => return Ok(sb), + Err(Create::Failed(e)) => return Err(e), + Err(Create::NoImage(e)) => e, + }; + let missing = format!("{} is not on this host and can't be pulled", spec.image); + if let Some(fallback) = &spec.fallback_image { + log(format!("{missing}; starting from {fallback} instead")); + match self.create(spec, fallback, log).await { + Ok(()) => return Ok(sb), + Err(Create::Failed(e)) => return Err(e), + Err(Create::NoImage(_)) => {} + } + return Err(pull_error.context(format!( + "{missing} (`fctl host image build` builds it here)" + ))); + } + Err(pull_error.context(missing)) + } + + /// Starts the sandbox from `image`, pulling the image when it isn't here. + async fn create( + &self, + spec: &SandboxSpec, + image: &str, + log: &(dyn Fn(String) + Send + Sync), + ) -> Result<(), Create> { let cpus = spec.cpus.max(1).to_string(); let memory = match self.flavor { Flavor::Apple => format!("{}M", spec.memory_mb.max(512)), @@ -215,28 +249,53 @@ impl ContainerDriver { "--init", "--entrypoint", "tail", - &spec.image, + image, "-f", "/dev/null", ]; - if let Err(e) = self.run(&args).await { - // A missing image: pull it and try once more. - log(format!("Pulling {}", spec.image)); - let pull = match self.flavor { - Flavor::Apple => self.run(&["image", "pull", &spec.image]).await, - Flavor::Docker => self.run(&["pull", &spec.image]).await, - }; - if pull.is_err() { - return Err(e).with_context(|| { - format!( - "starting {} (is the image {} built? run `fctl host image build`)", - spec.name, spec.image - ) - }); - } - self.run(&args).await?; + let failed = + |e: anyhow::Error| Create::Failed(e.context(format!("starting {}", spec.name))); + let Err(e) = self.run(&args).await else { + return Ok(()); + }; + // A runtime that doesn't answer isn't missing the image. + if e.is::() || self.has_image(image).await { + return Err(failed(e)); + } + log(format!("Pulling {image}")); + self.pull(image, false).await.map_err(Create::NoImage)?; + self.run(&args).await.map(drop).map_err(failed) + } + + pub async fn has_image(&self, image: &str) -> bool { + let inspect: &[&str] = match self.flavor { + Flavor::Apple => &["image", "inspect", image], + Flavor::Docker => &["image", "inspect", "--format", "{{.Id}}", image], + }; + self.run(inspect).await.is_ok() + } + + /// Pulls `image` for the platform sandboxes run on: without one, Apple's + /// `container` pulls every platform an image has. + pub async fn pull(&self, image: &str, progress: bool) -> Result<()> { + let platform = format!("linux/{}", linux_arch(std::env::consts::ARCH)); + let args: &[&str] = match self.flavor { + Flavor::Apple => &["image", "pull", "--platform", &platform, image], + Flavor::Docker => &["pull", image], + }; + if !progress { + return self.run(args).await.map(drop); + } + let status = tokio::process::Command::new(&self.bin) + .args(args) + .stdin(Stdio::null()) + .status() + .await + .map_err(|e| super::spawn_error(&self.bin, e))?; + if !status.success() { + anyhow::bail!("{} {} failed ({status})", self.bin, args.join(" ")); } - Ok(sb) + Ok(()) } pub async fn install_agent(&self, sb: &Sandbox, binary: &Path) -> Result<()> { @@ -361,6 +420,15 @@ impl ContainerDriver { } } +/// An architecture as images name it: `arm64` for Rust's `aarch64`. +fn linux_arch(arch: &str) -> &str { + match arch { + "aarch64" => "arm64", + "x86_64" => "amd64", + other => other, + } +} + /// `docker info --format '{{.NCPU}} {{.MemTotal}}'`: CPUs, and memory in bytes. fn docker_resources(out: &str) -> Option { let mut words = out.split_whitespace(); @@ -404,6 +472,200 @@ mod tests { } } + /// A stand-in for the `docker` or `container` CLI with no sandboxes yet: + /// `have` are the images on the host, `registry` those it can pull. It + /// writes each call to `calls`, and with `fail_run` every `run` fails. + struct FakeCli { + dir: tempfile::TempDir, + } + + impl FakeCli { + fn new(have: &[&str], registry: &[&str]) -> Result { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir()?; + let root = dir.path(); + for (sub, images) in [("have", have), ("registry", registry)] { + std::fs::create_dir(root.join(sub))?; + for image in images { + std::fs::write(root.join(sub).join(image.replace(['/', ':'], "_")), "")?; + } + } + let script = format!( + r#"#!/bin/sh +d='{}' +echo "$*" >> "$d/calls" +key() {{ printf '%s' "$1" | tr '/:' '__'; }} +for last in "$@"; do :; done +pull() {{ + [ -e "$d/registry/$(key "$last")" ] || {{ echo "$last: manifest unknown" >&2; exit 1; }} + touch "$d/have/$(key "$last")" +}} +case "$1 $2" in + "image inspect") [ -e "$d/have/$(key "$last")" ] ;; + "image pull" | "pull "*) pull ;; + "inspect "*) exit 1 ;; + "run "*) + [ ! -e "$d/fail_run" ] || {{ echo "no room for it" >&2; exit 1; }} + while [ $# -gt 0 ] && [ "$1" != tail ]; do shift; done + [ -e "$d/have/$(key "$2")" ] || {{ echo "Unable to find image '$2' locally" >&2; exit 125; }} ;; + *) echo "unexpected: $*" >&2; exit 2 ;; +esac +"#, + root.display() + ); + let bin = root.join("cli"); + std::fs::write(&bin, script)?; + std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755))?; + Ok(Self { dir }) + } + + fn driver(&self, flavor: Flavor) -> ContainerDriver { + ContainerDriver { + flavor, + bin: self.dir.path().join("cli").display().to_string(), + } + } + + fn calls(&self) -> Vec { + std::fs::read_to_string(self.dir.path().join("calls")) + .unwrap_or_default() + .lines() + .map(str::to_owned) + .collect() + } + + /// Creates the sandbox: the image it started from, and the log. + async fn ensure( + &self, + flavor: Flavor, + spec: &SandboxSpec, + ) -> Result<(String, Vec)> { + let lines = Mutex::new(Vec::new()); + let log = |line: String| { + lines + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push(line) + }; + self.driver(flavor).ensure(spec, &log).await?; + let run = self + .calls() + .into_iter() + .rev() + .find(|c| c.starts_with("run ")); + let image = run + .as_deref() + .and_then(|c| c.split(" tail ").nth(1)?.split(' ').next()) + .unwrap_or_default() + .to_owned(); + Ok(( + image, + lines.into_inner().unwrap_or_else(PoisonError::into_inner), + )) + } + } + + use std::sync::{Mutex, PoisonError}; + + const VERSION_IMAGE: &str = "ghcr.io/hyperstructure/sandbox:0.3.0"; + const LATEST_IMAGE: &str = "ghcr.io/hyperstructure/sandbox:latest"; + + fn spec(image: &str, fallback: Option<&str>) -> SandboxSpec { + SandboxSpec { + name: "fctl-ses-1".into(), + image: image.into(), + fallback_image: fallback.map(str::to_owned), + cpus: 2, + memory_mb: 2048, + } + } + + fn error_of(result: Result) -> String { + match result { + Ok(v) => format!("no error: {v:?}"), + Err(e) => format!("{e:#}"), + } + } + + #[tokio::test] + async fn sandboxes_pull_their_image_when_it_is_not_here() -> Result<()> { + let default = spec(VERSION_IMAGE, Some(LATEST_IMAGE)); + let cli = FakeCli::new(&[VERSION_IMAGE], &[])?; + let (image, log) = cli.ensure(Flavor::Docker, &default).await?; + assert_eq!(image, VERSION_IMAGE); + assert_eq!( + log, + [format!("Creating sandbox fctl-ses-1 from {VERSION_IMAGE}")] + ); + + let cli = FakeCli::new(&[], &[VERSION_IMAGE, LATEST_IMAGE])?; + let (image, log) = cli.ensure(Flavor::Docker, &default).await?; + assert_eq!(image, VERSION_IMAGE); + assert_eq!(log[1], format!("Pulling {VERSION_IMAGE}")); + assert!(cli.calls().contains(&format!("pull {VERSION_IMAGE}"))); + + // Apple's CLI pulls every platform of an image unless told one. + let cli = FakeCli::new(&[], &[VERSION_IMAGE])?; + let (image, _) = cli + .ensure(Flavor::Apple, &spec(VERSION_IMAGE, None)) + .await?; + assert_eq!(image, VERSION_IMAGE); + let platform = format!("linux/{}", linux_arch(std::env::consts::ARCH)); + let pull = format!("image pull --platform {platform} {VERSION_IMAGE}"); + assert!(cli.calls().contains(&pull), "{:?}", cli.calls()); + Ok(()) + } + + #[tokio::test] + async fn the_default_image_falls_back_to_the_latest_published_one() -> Result<()> { + // A release's image is published a few minutes after the release. + let default = spec(VERSION_IMAGE, Some(LATEST_IMAGE)); + let cli = FakeCli::new(&[], &[LATEST_IMAGE])?; + let (image, log) = cli.ensure(Flavor::Docker, &default).await?; + assert_eq!(image, LATEST_IMAGE); + let note = format!( + "{VERSION_IMAGE} is not on this host and can't be pulled; starting from {LATEST_IMAGE} instead" + ); + assert!(log.contains(¬e), "{log:?}"); + + let cli = FakeCli::new(&[], &[])?; + let error = error_of(cli.ensure(Flavor::Docker, &default).await); + let missing = format!("{VERSION_IMAGE} is not on this host and can't be pulled"); + assert!( + error.starts_with(&format!( + "{missing} (`fctl host image build` builds it here): " + )), + "{error}" + ); + assert!( + error.ends_with(&format!("{VERSION_IMAGE}: manifest unknown")), + "{error}" + ); + + // A project's own image has nothing to fall back to. + let project = spec("ghcr.io/acme/agent:1", None); + let error = error_of(cli.ensure(Flavor::Docker, &project).await); + let missing = "ghcr.io/acme/agent:1 is not on this host and can't be pulled: "; + assert!(error.starts_with(missing), "{error}"); + Ok(()) + } + + #[tokio::test] + async fn other_failures_are_not_about_the_image() -> Result<()> { + let cli = FakeCli::new(&[VERSION_IMAGE], &[LATEST_IMAGE])?; + std::fs::write(cli.dir.path().join("fail_run"), "")?; + let default = spec(VERSION_IMAGE, Some(LATEST_IMAGE)); + let error = error_of(cli.ensure(Flavor::Docker, &default).await); + assert!(error.starts_with("starting fctl-ses-1: "), "{error}"); + assert!(error.contains("no room for it"), "{error}"); + assert!( + !cli.calls().iter().any(|c| c.contains("pull")), + "{:?}", + cli.calls() + ); + Ok(()) + } + #[tokio::test] async fn says_whether_the_runtime_is_missing_or_stopped() { // `true` and `false` stand in for a CLI whose every command succeeds or fails. diff --git a/crates/fctl-host/src/driver/mod.rs b/crates/fctl-host/src/driver/mod.rs index 807c621d..a251a7bb 100644 --- a/crates/fctl-host/src/driver/mod.rs +++ b/crates/fctl-host/src/driver/mod.rs @@ -33,6 +33,8 @@ pub const SLOW_COMMAND_TIMEOUT: Duration = Duration::from_secs(30 * 60); pub struct SandboxSpec { pub name: String, pub image: String, + /// The image to use when `image` is not here and can't be pulled. + pub fallback_image: Option, pub cpus: u32, pub memory_mb: u32, } @@ -151,6 +153,28 @@ impl Driver { !matches!(self, Self::Process(_)) } + /// Whether sandboxes are made from images (Lima clones its base VM, and + /// the process driver has none). + pub fn uses_images(&self) -> bool { + matches!(self, Self::Container(_)) + } + + /// Whether `image` is on this host. + pub async fn has_image(&self, image: &str) -> bool { + match self { + Self::Container(d) => d.has_image(image).await, + _ => false, + } + } + + /// Pulls `image` from its registry; `progress` shows the CLI's own output. + pub async fn pull(&self, image: &str, progress: bool) -> Result<()> { + match self { + Self::Container(d) => d.pull(image, progress).await, + _ => anyhow::bail!("the {} driver does not use images", self.name()), + } + } + pub async fn probe(&self) -> DriverInfo { match self { Self::Process(d) => d.probe().await, diff --git a/crates/fctl-host/src/image.rs b/crates/fctl-host/src/image.rs index 3630cdda..50698f94 100644 --- a/crates/fctl-host/src/image.rs +++ b/crates/fctl-host/src/image.rs @@ -1,36 +1,67 @@ -//! Building the default sandbox image (or the Lima base VM) on this host. +//! Building the default sandbox image (or the Lima base VM) on this host, +//! from its sources in hyperstructure/sandbox. use crate::driver::{Driver, lima::BASE_VM, spawn_error}; -use anyhow::{Result, bail}; +use anyhow::{Context, Result, bail}; +use std::path::{Path, PathBuf}; use std::process::Stdio; -pub const DOCKERFILE: &str = include_str!("../../../images/agent/Dockerfile"); -pub const PROVISION: &str = include_str!("../../../images/agent/provision.sh"); +/// The default image's sources: an archive of the branch it is published +/// from. Its Dockerfile builds with the archive's root as the context, and +/// its provision.sh also prepares the Lima VM. +pub const SOURCE: &str = "https://github.com/hyperstructure/sandbox/archive/refs/heads/main.tar.gz"; -/// Builds `tag` with the driver's tooling, streaming output to the terminal. -/// The image gets this host's version of fctl, from `download_base`. -pub async fn build(driver: &Driver, tag: &str, download_base: &str) -> Result<()> { - if driver.name() != "process" { - let info = driver.probe().await; - // Lima only needs limactl here: its base VM is what this builds. - if !info.available && !(driver.name() == "lima" && info.version.is_some()) { - bail!( - "The {} driver is not ready: {}", - info.name, - info.detail.unwrap_or_default() - ); - } +/// Builds `tag` with the driver's tooling, streaming output to the terminal, +/// from `source`, a checkout of hyperstructure/sandbox, or else from +/// [`SOURCE`]. The image gets this host's version of fctl, from +/// `download_base`. +pub async fn build( + driver: &Driver, + tag: &str, + download_base: &str, + source: Option<&Path>, +) -> Result<()> { + if driver.name() == "process" { + println!( + "The process driver runs agents directly on this machine; there is no image to build." + ); + println!( + "Install Claude Code here instead: curl -fsSL https://claude.ai/install.sh | bash" + ); + return Ok(()); } - let dir = std::env::temp_dir().join(format!("fctl-image-{}", std::process::id())); - std::fs::create_dir_all(&dir)?; - std::fs::write(dir.join("Dockerfile"), DOCKERFILE)?; - std::fs::write(dir.join("provision.sh"), PROVISION)?; + let info = driver.probe().await; + // Lima only needs limactl here: its base VM is what this builds. + if !info.available && !(driver.name() == "lima" && info.version.is_some()) { + bail!( + "The {} driver is not ready: {}", + info.name, + info.detail.unwrap_or_default() + ); + } + let tmp = std::env::temp_dir().join(format!("fctl-image-{}", std::process::id())); + let result = async { + let dir = match source { + Some(dir) => { + std::fs::canonicalize(dir).with_context(|| format!("finding {}", dir.display()))? + } + None => download(&tmp).await?, + }; + build_from(driver, tag, download_base, &dir).await + } + .await; + let _ = std::fs::remove_dir_all(&tmp); + result +} + +async fn build_from(driver: &Driver, tag: &str, download_base: &str, dir: &Path) -> Result<()> { + check_source(dir)?; let ctx = dir.display().to_string(); // provision.sh installs the latest release when this version is not // published (a development build). let version = format!("FCTL_VERSION={}", crate::agentbin::VERSION); let download = format!("FCTL_DOWNLOAD={download_base}"); - let result = match driver.name() { + match driver.name() { "apple" => { run_inherit( "container", @@ -65,22 +96,53 @@ pub async fn build(driver: &Driver, tag: &str, download_base: &str) -> Result<() ) .await } - "lima" => build_lima_base(&dir, &[&version, &download]).await, - _ => { - println!( - "The process driver runs agents directly on this machine; there is no image to build." - ); - println!( - "Install Claude Code here instead: curl -fsSL https://claude.ai/install.sh | bash" + "lima" => build_lima_base(dir, &[&version, &download]).await, + other => bail!("the {other} driver has no image to build"), + } +} + +/// Downloads [`SOURCE`] into `dir`; returns the directory with its files. +async fn download(dir: &Path) -> Result { + println!("Downloading the image's sources from {SOURCE}"); + let http = fctl_client::HttpClient::new(std::time::Duration::from_secs(120)); + let archive = http + .download(SOURCE) + .await + .with_context(|| format!("downloading {SOURCE}"))?; + unpack(&archive, dir) +} + +/// Unpacks a `.tar.gz` of a repository into `dir`, and returns the one +/// directory GitHub's archives hold (`sandbox-main`). +fn unpack(archive: &[u8], dir: &Path) -> Result { + std::fs::create_dir_all(dir)?; + tar::Archive::new(flate2::read::GzDecoder::new(archive)) + .unpack(dir) + .context("unpacking the image's sources")?; + let mut dirs = std::fs::read_dir(dir)? + .filter_map(|e| e.ok()) + .map(|e| e.path()) + .filter(|p| p.is_dir()); + match (dirs.next(), dirs.next()) { + (Some(top), None) => Ok(top), + _ => bail!("the archive of the image's sources should hold one directory"), + } +} + +/// What a build needs from a checkout of hyperstructure/sandbox. +fn check_source(dir: &Path) -> Result<()> { + for file in ["Dockerfile", "provision.sh"] { + if !dir.join(file).is_file() { + bail!( + "{} has no {file}: build from a checkout of https://github.com/hyperstructure/sandbox", + dir.display() ); - Ok(()) } - }; - let _ = std::fs::remove_dir_all(&dir); - result + } + Ok(()) } -async fn build_lima_base(dir: &std::path::Path, env: &[&str]) -> Result<()> { +async fn build_lima_base(dir: &Path, env: &[&str]) -> Result<()> { run_inherit( "limactl", &[ @@ -135,7 +197,7 @@ async fn run_inherit(program: &str, args: &[&str]) -> Result<()> { #[cfg(test)] mod tests { - use super::{PROVISION, shell_quote}; + use super::{check_source, shell_quote, unpack}; #[test] fn quotes_values_for_sh() { @@ -146,36 +208,59 @@ mod tests { assert_eq!(shell_quote("it's"), "'it'\\''s'"); } - /// Sessions working on fctl find its toolchain already installed, rather - /// than having rustup download a second one. - #[test] - fn installs_the_rust_this_repository_builds_with() -> anyhow::Result<()> { - #[derive(serde::Deserialize)] - struct File { - toolchain: Toolchain, - } - #[derive(serde::Deserialize)] - struct Toolchain { - channel: String, - #[serde(default)] - components: Vec, - #[serde(default)] - targets: Vec, - } - let File { toolchain } = toml::from_str(include_str!("../../../rust-toolchain.toml"))?; - let mut wanted = vec![format!("RUST_VERSION:-{}}}", toolchain.channel)]; - if !toolchain.components.is_empty() { - wanted.push(format!("--component {}", toolchain.components.join(","))); - } - if !toolchain.targets.is_empty() { - wanted.push(format!("--target {}", toolchain.targets.join(","))); - } - for w in wanted { - assert!( - PROVISION.contains(&w), - "images/agent/provision.sh should have `{w}`, as rust-toolchain.toml says" - ); + /// An archive like GitHub's: a pax header with the commit, then one + /// directory named after the repository and the branch. + fn github_archive(files: &[(&str, &str)]) -> anyhow::Result> { + let gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast()); + let mut tar = tar::Builder::new(gz); + let comment = b"52 comment=688d0ddc129fb274e9d97e73de7fa70803f7a0f7\n"; + let mut pax = tar::Header::new_ustar(); + pax.set_entry_type(tar::EntryType::XGlobalHeader); + pax.set_size(comment.len() as u64); + tar.append_data(&mut pax, "pax_global_header", &comment[..])?; + let mut dir = tar::Header::new_ustar(); + dir.set_entry_type(tar::EntryType::Directory); + dir.set_mode(0o755); + dir.set_size(0); + tar.append_data(&mut dir, "sandbox-main/", std::io::empty())?; + for (name, text) in files { + let mut file = tar::Header::new_ustar(); + file.set_mode(0o644); + file.set_size(text.len() as u64); + tar.append_data(&mut file, format!("sandbox-main/{name}"), text.as_bytes())?; } + Ok(tar.into_inner()?.finish()?) + } + + #[test] + fn unpacks_the_sources_from_githubs_archive() -> anyhow::Result<()> { + let tmp = tempfile::tempdir()?; + let archive = github_archive(&[ + ("Dockerfile", "FROM debian:bookworm-slim\n"), + ("provision.sh", "#!/usr/bin/env bash\n"), + ("README.md", "# Sandbox\n"), + ])?; + let dir = unpack(&archive, tmp.path())?; + assert_eq!(dir, tmp.path().join("sandbox-main")); + assert_eq!( + std::fs::read_to_string(dir.join("Dockerfile"))?, + "FROM debian:bookworm-slim\n" + ); + check_source(&dir)?; + Ok(()) + } + + #[test] + fn needs_a_dockerfile_and_provision_sh() -> anyhow::Result<()> { + let tmp = tempfile::tempdir()?; + let archive = github_archive(&[("Dockerfile", "FROM debian:bookworm-slim\n")])?; + let dir = unpack(&archive, tmp.path())?; + let err = check_source(&dir).err().map(|e| e.to_string()); + assert!( + err.as_deref() + .is_some_and(|e| e.contains("has no provision.sh")), + "{err:?}" + ); Ok(()) } } diff --git a/crates/fctl-host/src/login.rs b/crates/fctl-host/src/login.rs index 3c15807f..7b0a6376 100644 --- a/crates/fctl-host/src/login.rs +++ b/crates/fctl-host/src/login.rs @@ -63,7 +63,8 @@ async fn login( } let spec = SandboxSpec { name: name.to_owned(), - image: ctx.cfg.image.clone(), + image: ctx.cfg.image(), + fallback_image: ctx.cfg.fallback_image(), cpus: 1, memory_mb: 1024, }; diff --git a/crates/fctl-host/src/session.rs b/crates/fctl-host/src/session.rs index 20329f35..abf1a2c5 100644 --- a/crates/fctl-host/src/session.rs +++ b/crates/fctl-host/src/session.rs @@ -1,7 +1,7 @@ //! One task per session: sandbox, fctl-agent, and the bridge between the //! agent and the session's uplink. -use crate::config::HostConfig; +use crate::config::{HostConfig, means_default_image}; use crate::driver::{AgentIo, Driver, Sandbox, SandboxSpec, sandbox_name}; use crate::files; use crate::liveness::{Check, Health, Retry}; @@ -353,16 +353,15 @@ fn host_log(uplink: &Uplink, level: LogLevel, text: String) { } async fn prepare(ctx: &HostCtx, spec: &SessionSpec, uplink: &Uplink) -> Result { - let image = spec - .project - .settings - .image - .clone() - .unwrap_or_else(|| ctx.cfg.image.clone()); + let (image, fallback_image) = match spec.project.settings.image.as_deref() { + Some(image) if !means_default_image(image) => (image.to_owned(), None), + _ => (ctx.cfg.image(), ctx.cfg.fallback_image()), + }; let size = ctx.sandbox_size(spec); let sspec = SandboxSpec { name: sandbox_name(spec.session_id.as_str()), image, + fallback_image, cpus: size.cpus, memory_mb: size.memory_mb, }; diff --git a/crates/fctl/Cargo.toml b/crates/fctl/Cargo.toml index be4b2751..5886cab6 100644 --- a/crates/fctl/Cargo.toml +++ b/crates/fctl/Cargo.toml @@ -20,13 +20,13 @@ fctl-client.workspace = true fctl-domain.workspace = true fctl-host.workspace = true fctl-proto.workspace = true -flate2 = "1.1.10" +flate2.workspace = true futures.workspace = true hex.workspace = true serde.workspace = true serde_json.workspace = true sha2.workspace = true -tar = "0.4.46" +tar.workspace = true tokio.workspace = true toml.workspace = true tracing.workspace = true diff --git a/crates/fctl/src/cmd/host.rs b/crates/fctl/src/cmd/host.rs index f28d98c5..7f12c08d 100644 --- a/crates/fctl/src/cmd/host.rs +++ b/crates/fctl/src/cmd/host.rs @@ -5,6 +5,7 @@ use crate::style; use anyhow::{Context, Result, bail}; use clap::Subcommand; use fctl_domain::size; +use fctl_host::config::means_default_image; use fctl_host::driver::Driver; use fctl_host::{HostConfig, service}; @@ -33,7 +34,8 @@ pub enum HostCmd { /// The most memory one sandbox may have, like 16g (new hosts: all of the machine's or the Docker VM's). #[arg(long, value_parser = memory_arg)] max_memory: Option, - /// Sandbox image. + /// Sandbox image for sessions whose project sets none (default: the + /// published image of this version; "" goes back to it). #[arg(long)] image: Option, /// Use an existing runner token instead of registering a new runner. @@ -42,7 +44,8 @@ pub enum HostCmd { /// Write the configuration but do not install a service. #[arg(long)] no_service: bool, - /// Also build the sandbox image now. + /// Also build the sandbox image here (the Lima base VM, or for a host + /// that can't pull the published image). #[arg(long)] build_image: bool, }, @@ -57,7 +60,7 @@ pub enum HostCmd { #[arg(short = 'n', long, default_value_t = 100)] lines: usize, }, - /// Build the default sandbox image with this host's driver. + /// Pull the sandbox image, or build it with this host's driver. #[command(subcommand)] Image(ImageCmd), /// Restart the service (sessions keep running). @@ -68,14 +71,20 @@ pub enum HostCmd { #[derive(Subcommand)] pub enum ImageCmd { - /// Build `fctl-agent:latest` (or the Lima base VM). + /// Pull the host's sandbox image now (again: for a newer build of it). + Pull, + /// Build the default image here instead of pulling it (or the Lima base VM). Build { /// apple, docker or lima (default: the host's driver). #[arg(long)] driver: Option, - /// Image tag (default: the host's image, fctl-agent:latest). + /// Image tag (default: the host's image, so that sessions use the build). #[arg(long)] tag: Option, + /// A checkout of hyperstructure/sandbox to build from (default: its + /// main branch, downloaded from GitHub). + #[arg(long, value_name = "DIR")] + source: Option, }, } @@ -112,7 +121,7 @@ pub async fn run(server: Option<&str>, cmd: HostCmd, json: bool) -> Result<()> { cfg.max_cpus = max_cpus.or(cfg.max_cpus); cfg.max_memory_mb = max_memory.or(cfg.max_memory_mb); if let Some(i) = image { - cfg.image = i; + cfg.image = (!means_default_image(&i)).then_some(i); } // Registering a runner leaves something behind, so it waits until // everything that can fail on this machine has passed. @@ -145,7 +154,7 @@ pub async fn run(server: Option<&str>, cmd: HostCmd, json: bool) -> Result<()> { }; let d = Driver::select(&driver, &cfg.data_dir(), cfg.agent_bin.clone()).await?; if build_image { - fctl_host::image::build(&d, &cfg.image, &cfg.download_base).await?; + fctl_host::image::build(&d, &cfg.image(), &cfg.download_base, None).await?; } let info = d.probe().await; if !info.available { @@ -189,14 +198,19 @@ pub async fn run(server: Option<&str>, cmd: HostCmd, json: bool) -> Result<()> { style::accent("✓"), HostConfig::path().display() ); - if !build_image && d.needs_linux_agent() { + if !build_image && d.uses_images() { println!( "{}", style::dim(&format!( - "Build the sandbox image once with `fctl host image build` (tag {}).", - cfg.image + "Sessions start from {}; the host pulls it when it starts.", + cfg.image() )) ); + } else if !build_image && d.needs_linux_agent() { + println!( + "{}", + style::dim("Prepare the base VM once with `fctl host image build`.") + ); } if !no_service { let exe = std::env::current_exe()?; @@ -224,7 +238,7 @@ pub async fn run(server: Option<&str>, cmd: HostCmd, json: bool) -> Result<()> { }; if json { return style::print_json( - &serde_json::json!({ "config": cfg, "sandbox": sandbox, "service_installed": installed, "service_running": running }), + &serde_json::json!({ "config": cfg, "image": cfg.image(), "sandbox": sandbox, "service_installed": installed, "service_running": running }), ); } println!("{} {}", style::bold(&cfg.name), style::dim(&cfg.server)); @@ -233,7 +247,7 @@ pub async fn run(server: Option<&str>, cmd: HostCmd, json: bool) -> Result<()> { if let Some(l) = &sandbox { println!("sandbox: {}", size::limits(l)); } - println!("image: {}", cfg.image); + println!("image: {}", cfg.image()); println!( "service: {}", match (installed, running) { @@ -255,12 +269,38 @@ pub async fn run(server: Option<&str>, cmd: HostCmd, json: bool) -> Result<()> { } Ok(()) } - HostCmd::Image(ImageCmd::Build { driver, tag }) => { + HostCmd::Image(ImageCmd::Pull) => { + let cfg = HostConfig::load().unwrap_or_default(); + let d = Driver::select(&cfg.driver, &cfg.data_dir(), cfg.agent_bin.clone()).await?; + if !d.uses_images() { + bail!( + "The {} driver doesn't use images{}", + d.name(), + if d.needs_linux_agent() { + ": its sessions clone the base VM that `fctl host image build` prepares" + } else { + "" + } + ); + } + let image = cfg.image(); + d.pull(&image, !json).await?; + if json { + return style::print_json(&serde_json::json!({ "image": image })); + } + println!("{} Pulled {image}", style::accent("✓")); + Ok(()) + } + HostCmd::Image(ImageCmd::Build { + driver, + tag, + source, + }) => { let cfg = HostConfig::load().unwrap_or_default(); let name = driver.unwrap_or(cfg.driver.clone()); let d = Driver::select(&name, &cfg.data_dir(), cfg.agent_bin.clone()).await?; - fctl_host::image::build(&d, tag.as_deref().unwrap_or(&cfg.image), &cfg.download_base) - .await + let tag = tag.unwrap_or_else(|| cfg.image()); + fctl_host::image::build(&d, &tag, &cfg.download_base, source.as_deref()).await } HostCmd::Restart => { service::restart()?; @@ -327,6 +367,23 @@ async fn doctor() -> Result<()> { println!("{} {}", style::dim("·"), style::dim(&line)); } } + if let Ok(d) = Driver::select(&cfg.driver, &cfg.data_dir(), None).await + && d.uses_images() + && d.probe().await.available + { + let image = cfg.image(); + if d.has_image(&image).await { + check(true, &format!("sandbox image {image}"), ""); + } else { + println!( + "{} {}", + style::dim("·"), + style::dim(&format!( + "sandbox image {image}: not here yet (the host pulls it when it starts; `fctl host image pull` pulls it now)" + )) + ); + } + } let (installed, running) = service::status(); check( installed && running, diff --git a/docs/README.md b/docs/README.md index 1af38efe..48c7a79d 100644 --- a/docs/README.md +++ b/docs/README.md @@ -23,6 +23,7 @@ Three pieces make up a factory: | Start using fctl on an instance someone set up | [Getting started](getting-started.md) | | Drive everything from a terminal or a script | [The CLI](cli.md) | | Run your own instance on your Cloudflare account | [Self-hosting](self-hosting.md) | +| Know what sessions run in, or build an image for them | [Sandbox images](sandbox-images.md) | | Understand how the pieces talk to each other | [Architecture](architecture.md) | | Know what fctl does with your credentials | [Security](security.md) | | Work on fctl itself | [Development](development.md) | diff --git a/docs/adr/0012-the-sandbox-image-lives-in-its-own-public-repository.md b/docs/adr/0012-the-sandbox-image-lives-in-its-own-public-repository.md new file mode 100644 index 00000000..9db30778 --- /dev/null +++ b/docs/adr/0012-the-sandbox-image-lives-in-its-own-public-repository.md @@ -0,0 +1,59 @@ +# 0012: The sandbox image lives in its own public repository + +2026-10-18 · accepted + +## Context + +The default sandbox image started in this repository, in `images/agent`, +and [#39](https://github.com/hyperstructure/fctl/pull/39) first published +it to GHCR from here, building each release's image from the release's tag. +That fits it badly: + +- Hosts pull the image without signing in, so it is public, and the people + who run agents in it or build images from it should be able to read what + goes into it. This repository is private for now. +- Its cadence isn't fctl's. It is rebuilt when Claude Code or Debian move + on and when a tool is added or upgraded; none of that needs an fctl + release, yet a broken image built from a tag needed one to be fixed. + +## Decision + +- [hyperstructure/sandbox](https://github.com/hyperstructure/sandbox), a + public repository, holds the image: `Dockerfile` and `provision.sh` at + its root, `check.sh`, and the Image workflow that publishes + `ghcr.io/hyperstructure/sandbox` for arm64 and amd64 from its `main`. + This amends [0005](0005-three-repositories.md): images leave this + repository. +- The tags stay as #39 made them: one for each fctl release, which that + release's hosts pull, plus `X.Y` and `latest`. Each is the sandbox's + `main` with that release of fctl and the newest Claude Code. +- The repositories connect through fctl.sh, not tokens: the Image workflow + looks for new releases on fctl.sh every hour, as it reads Claude Code's + latest version from downloads.claude.ai. fctl's Release workflow starts + nothing there. +- `fctl host image build` downloads an archive of the sandbox's `main` + instead of carrying the files in the binary, and gives Lima's base VM its + `provision.sh`. `--source DIR` builds from a checkout. +- The layout (the `agent` user, the PATH, `/opt/fctl/bin`) and the files + `fctl host image build` reads are an interface between the two + repositories. `check.sh` checks every build for the layout, and + `docs/sandbox-images.md` here describes it. + +## Consequences + +- Changes to the image ship when they merge in hyperstructure/sandbox, + without an fctl release, and anyone can read how it's made. +- A release's image follows the release within the hour rather than within + minutes. Hosts start sessions from `latest` meanwhile, as they did for + those minutes. +- An image is no longer built from its release's tag: the newest release's + is rebuilt from the sandbox's `main`, and older ones only when someone + asks. Changing the layout means changing and releasing fctl first. +- No test checks any longer that the image's Rust matches + `rust-toolchain.toml`; both repositories' instructions say to bump them + together. +- `fctl host image build` needs to reach GitHub, as it already needed the + package mirrors and installers its build downloads from. +- GitHub turns off scheduled workflows in public repositories after 60 + days without activity, warning by email first. Until someone turns the + Image workflow back on, new releases get no image of their own. diff --git a/docs/adr/README.md b/docs/adr/README.md index 9ec10f41..0856aef9 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -16,3 +16,4 @@ supersede an earlier one. Copy the newest record to start a new one. | [0008](0008-attachments-in-a-durable-object-per-project.md) | Attachments live in a Durable Object per project | | [0009](0009-projects-span-an-accounts-repositories.md) | Projects span the repositories of one GitHub account | | [0010](0010-notifications-are-web-push-from-a-durable-object-per-person.md) | Notifications are Web Push, sent from a Durable Object per person | +| [0012](0012-the-sandbox-image-lives-in-its-own-public-repository.md) | The sandbox image lives in its own public repository | diff --git a/docs/architecture.md b/docs/architecture.md index 7ed57e80..c98ffe5d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -43,15 +43,17 @@ before changing anything that crosses a component boundary. | `crates/fake-claude` | A scripted stand-in for `claude` that speaks stream-json. Used by tests and `cargo xtask dev`. | dev, CI | | `xtask` | Development automation (`cargo xtask dev`, `check`, `gen`, `deploy`, `dist`, `publish`). | dev, CI | | `web/` | The web app (React, Vite, TypeScript, WebGL), installable on phones and computers. Served by fctl-control. | browser | -| `images/agent` | The default sandbox image (Debian, git, gh, Python, Rust, Node.js, Bun, claude, fctl). | sandboxes | -Two more repositories complete the picture: +Three more repositories complete the picture: [hyperstructure/design](https://github.com/hyperstructure/design) (`@hyperstructure/design`: tokens, fonts, the WebGL scenes and the marks, -used by `web/`) and +used by `web/`), [hyperstructure/fctl-site](https://github.com/hyperstructure/fctl-site) (fctl.sh: the landing page, these docs rendered from `docs/`, the installer -and release downloads). +and release downloads) and +[hyperstructure/sandbox](https://github.com/hyperstructure/sandbox) (the +default sandbox image: Debian, git, gh, Python, Rust, Node.js, Bun, claude +and fctl, published to `ghcr.io/hyperstructure/sandbox`). ## Principles @@ -356,6 +358,18 @@ they already pass every Claude message on. A driver turns a `SandboxSpec` (image, CPUs, memory, environment) into a running Linux sandbox and can exec processes in it with piped stdio. +The image is the project's or, without one, the host's: unless `host.toml` +sets another, the default image of the host's own version, +`ghcr.io/hyperstructure/sandbox:`. hyperstructure/sandbox's Image +workflow publishes it for arm64 and amd64 within the hour after every +release, and rebuilds the latest release's when Claude Code has a newer +release, since fctl turns off Claude Code's auto-updater. The host pulls the +image when it starts and when a sandbox needs one it doesn't have, never +over one it has, and falls back to `latest` when its version's can't be +pulled ([Sandbox images](sandbox-images.md)). `fctl host image build` +builds it on the host instead, from that repository's `main`, which it +downloads; the Lima driver's base VM gets the image's `provision.sh`. + | Driver | Isolation | Host | |---|---|---| | `apple` | one lightweight VM per session (Apple `container`) | Apple silicon, macOS 26+ | diff --git a/docs/cli.md b/docs/cli.md index 614189c2..6b3f2470 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -139,7 +139,9 @@ fctl host run # run in the foreground (what the service runs) fctl host status fctl host doctor # check the driver, image, agent binary, connection fctl host logs -n 200 -fctl host image build # (re)build fctl-agent:latest for this driver +fctl host image pull # pull the sandbox image again, for a newer build +fctl host image build # build it here instead (with Lima: the base VM) +fctl host image build --source ~/src/sandbox # from a checkout of hyperstructure/sandbox fctl host restart # sessions keep running fctl host uninstall # sandboxes are kept ``` @@ -156,7 +158,7 @@ server = "https://app.fctl.sh" name = "studio-mac" driver = "apple" # apple | lima | docker | process | auto (picks at every start) capacity = 4 # concurrent sessions -image = "fctl-agent:latest" +# image = "ghcr.io/acme/agent:1" # unset: the published image of the host's version cpus = 4 # per sandbox, when the project sets none memory_mb = 8192 # per sandbox, when the project sets none max_cpus = 8 # the most one sandbox may have (unset: all there is) @@ -164,6 +166,11 @@ max_memory_mb = 12288 keep_stopped_hours = 72 # then remove a stopped session's sandbox (0 keeps them) ``` +Sessions start from their project's image or, without one, the host's: +unless `image` sets another, the published image of the host's own version, +`ghcr.io/hyperstructure/sandbox:`, which the host pulls when it +starts. [Sandbox images](sandbox-images.md) has the details. + A project's Settings → Sandbox can ask for more CPUs or memory than the host's default. Sessions only start on a host whose maximum covers that; when none does, they stay queued and say so ("No runner can give this diff --git a/docs/development.md b/docs/development.md index 52d26faa..bfc5ef92 100644 --- a/docs/development.md +++ b/docs/development.md @@ -102,7 +102,6 @@ production build of the web app. | `crates/fake-claude` | The scripted Claude stand-in | | `xtask` | `cargo xtask`: dev, check, gen, deploy, secrets, dist, publish | | `web` | The web app (React, TanStack Router and Query, Tailwind, WebGL) | -| `images/agent` | The default sandbox image | | `deploy/instances` | Instance descriptions for `cargo xtask deploy` | | `docs` | These docs; `docs/adr` records decisions | @@ -172,7 +171,11 @@ tag, builds the binaries in parallel jobs (`cargo xtask dist build`: fctl for macOS and Linux on arm64 and x86_64, and the Linux agents), makes the archives from them (`cargo xtask dist package`), creates the GitHub release with the notes, publishes to `https://fctl.sh/releases` (`cargo xtask -publish --latest`) and redeploys app.fctl.sh. +publish --latest`) and redeploys app.fctl.sh. Within the hour, +[hyperstructure/sandbox](https://github.com/hyperstructure/sandbox), where +the default sandbox image lives, publishes the release's image to +`ghcr.io/hyperstructure/sandbox`: its Image workflow looks for new releases +on fctl.sh every hour. ```sh cargo xtask release --dry-run # the next version and its notes diff --git a/docs/getting-started.md b/docs/getting-started.md index 45ebc63d..5c346e57 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -88,14 +88,16 @@ Any Mac with Apple silicon (or a Linux box) can be a host. On the Mac: otherwise ask one for a runner token and pass `--token`): ```sh - fctl host install --build-image + fctl host install ``` - This builds the sandbox image (Debian with git, gh, Python, uv, Rust, - Node, TypeScript, Bun and Claude Code), writes - `~/.config/fctl/host.toml`, and installs a launchd agent (`sh.fctl.host`) - that starts at login, restarts if it stops, and keeps the Mac from - sleeping while it is plugged in, so it can start work at any hour. + This writes `~/.config/fctl/host.toml` and installs a launchd agent + (`sh.fctl.host`) that starts at login, restarts if it stops, and keeps + the Mac from sleeping while it is plugged in, so it can start work at any + hour. The host then pulls the [sandbox image](sandbox-images.md) (Debian + with git, gh, Python, uv, Rust, Node, TypeScript, Bun and Claude Code) in + the background. With Lima, add `--build-image`: it prepares the VM that + sessions are cloned from, which takes a few minutes. 3. Check it: diff --git a/docs/sandbox-images.md b/docs/sandbox-images.md new file mode 100644 index 00000000..c6d7d4ca --- /dev/null +++ b/docs/sandbox-images.md @@ -0,0 +1,121 @@ +# Sandbox images + +With the Apple container and Docker drivers, each session runs in a +container made from an image. This page describes the default image, how +hosts get it, and what images built from it can rely on. + +## The default image + +`ghcr.io/hyperstructure/sandbox` is built from +[hyperstructure/sandbox](https://github.com/hyperstructure/sandbox), a +public repository whose README lists the versions: Debian bookworm with +git, the GitHub CLI, build tools, Python and uv, Rust, Node.js, TypeScript, +Bun, Claude Code and fctl. It is published for arm64 (Apple silicon) and +amd64. + +| Tag | Image | +|---|---| +| `0.4.0` | fctl 0.4.0's. Hosts of that version use it. | +| `0.4` | The newest 0.4 release's. | +| `latest` | The newest release's. | + +The sandbox repository's Image workflow builds every tag from its `main` +branch, with that release of fctl and the newest Claude Code. It looks for +new fctl releases every hour, so a release's image follows within the hour. +fctl turns off Claude Code's auto-updater, so an image's Claude Code is as +old as the image: every day, the workflow rebuilds the latest release's +image when Claude Code has a newer release, and once the image is a week +old, for Debian's updates. A change to the image rebuilds it too. A rebuild +moves the tags; to pin one build, add its digest: +`ghcr.io/hyperstructure/sandbox:0.4.0@sha256:…`. + +Its labels say what is inside: + +| Label | Value | +|---|---| +| `org.opencontainers.image.version`, `sh.fctl.version` | fctl's version | +| `sh.fctl.claude-code.version` | Claude Code's version | +| `org.opencontainers.image.revision` | the commit of hyperstructure/sandbox it was built from | +| `org.opencontainers.image.created` | when it was built | + +```sh +docker image inspect ghcr.io/hyperstructure/sandbox:0.4.0 \ + --format '{{ index .Config.Labels "sh.fctl.claude-code.version" }}' +``` + +## How hosts get it + +A host whose `host.toml` sets no `image` uses the default image of its own +version, so upgrading the host (`fctl self update`) moves its new sessions +to the new version's image. The host pulls the image in the background when +it starts, and a session that starts before it has the image pulls it +itself. When the image can't be pulled, as in the hour after a release +before its image is published, the session starts from `latest` instead and +says so in its log. + +The host pulls a tag once. To get a newer build of it, with a newer Claude +Code, run `fctl host image pull`. + +- **Another image.** `image` in `host.toml` (or `fctl host install --image + …`) sets the image for sessions whose project sets none, and a project's + Settings → Sandbox → Image sets one for its own sessions. + `fctl-agent:latest`, the name the default image had when hosts built it + themselves, means the default. +- **Building it.** `fctl host image build` builds the default image on the + host with its driver, from the `main` branch of hyperstructure/sandbox, + under the same name, so sessions use the build: for a host that can't + reach ghcr.io, for instance. `--source DIR` builds from a checkout of the + repository instead, to try changes to the image with fctl. The host never + replaces a build with the published image; `fctl host image pull` does. +- **Lima** sessions clone the `fctl-base` VM instead, which `fctl host + image build` prepares with the image's provisioning script. The process + driver uses no image. +- **Disk.** The images of earlier versions stay on the host until you + remove them: `docker image rm ghcr.io/hyperstructure/sandbox:0.4.0` + (with Apple container, `container image delete`) removes one that no + sandbox uses. + +## Its layout + +Images built `FROM` the default image can rely on its layout, which stays +the same from version to version. The sandbox repository's `check.sh` +checks every build for it: + +- **The user** is `agent`, uid 1000, with the home directory `/home/agent` + and sudo without a password: the sandbox is the boundary. Sessions run as + `agent`, in `~/workspace`. +- **The PATH** starts with `~/.local/bin`, where Claude Code (the native + build) and uv's tools are, `~/.cargo/bin` and `~/.bun/bin`, then + `/opt/fctl/bin`, where fctl copies its supervisor, fctl-agent, at session + start. The image sets it, and `/etc/profile.d/fctl.sh` sets it for login + shells, which setup scripts run in. fctl itself is in `/usr/local/bin`. +- **The tools**: git, gh, Python 3 (`python3` and `python`) with uv, Rust + through rustup with rustfmt and Clippy, Node.js 22 with npm and corepack, + TypeScript (`tsc`), Bun, build-essential, cmake, pkg-config, OpenSSL's + headers, ripgrep, fd, jq, ShellCheck, sqlite3, curl, wget, rsync, zip and + tree. +- **Rust and Bun** are `agent`'s, in `~/.rustup`, `~/.cargo` and `~/.bun`: + run `cargo`, `rustup` and `bun` as `agent`. Python is marked externally + managed, so packages go into a virtual environment (`uv venv`, + `python3 -m venv`). + +An image that installs something as root switches back to `agent` at the +end: + +```dockerfile +FROM ghcr.io/hyperstructure/sandbox:0.4 +USER root +RUN apt-get update \ + && apt-get install -y --no-install-recommends postgresql-client \ + && rm -rf /var/lib/apt/lists/* +USER agent +``` + +## Other images + +An image that doesn't start from the default one needs `sh`, `tail`, git +and Claude Code on the PATH, and a user with a writable home. fctl copies +its supervisor into `/opt/fctl/bin` at session start and runs it as the +image's user, in `~/workspace`. With fctl on the PATH as well, agents name +their sessions; without it, sessions keep the title they start with. Apple +silicon hosts need arm64 images. diff --git a/docs/security.md b/docs/security.md index 583730b1..7b033103 100644 --- a/docs/security.md +++ b/docs/security.md @@ -123,6 +123,14 @@ admins can rotate or revoke. Hosts receive a session's credentials only while it runs, and keep nothing secret on disk but their runner token (`~/.config/fctl/host-token`, mode 0600). +Sessions run in their project's sandbox image or, without one, the host's: +by default `ghcr.io/hyperstructure/sandbox`, which the Image workflow of +the public [hyperstructure/sandbox](https://github.com/hyperstructure/sandbox) +repository builds, so anyone can read what goes into it. A host can use its +own build of it instead (`fctl host image build`) or a copy in another +registry (`image` in `host.toml`); a project's own image still applies to +its sessions ([Sandbox images](sandbox-images.md)). + ## Retention - Deleting a project deletes its sessions with their transcripts (the event diff --git a/docs/self-hosting.md b/docs/self-hosting.md index b33f9c20..9ce2401b 100644 --- a/docs/self-hosting.md +++ b/docs/self-hosting.md @@ -173,21 +173,22 @@ On each machine that runs agents, follow ```sh curl -fsSL https://fctl.sh/install | sh fctl login fctl.acme.dev -fctl host install --build-image +fctl host install ``` Hosts download their release from `https://fctl.sh/releases` by default; set `download_base` in `host.toml` to mirror them elsewhere (`fctl host image -build` installs fctl in the default image from there too). +build` installs fctl in the default image from there too). They pull the +sandbox image from `ghcr.io/hyperstructure/sandbox`; set `image` to use a +copy in your own registry ([Sandbox images](sandbox-images.md)). ## Operating it - **Upgrades.** `git pull && cargo xtask deploy acme`; migrations apply first. Hosts and agents tolerate a control plane one version ahead. Upgrade hosts by running the installer again and `fctl host restart` (running sessions - continue), then `fctl host image build`: it brings the default image's - fctl, which agents name their sessions with, to the host's version (and - its Claude Code up to date). + continue): new sessions start from the sandbox image of the new version, + which the host pulls when it starts. - **Backups.** D1 keeps 30 days of point-in-time history (Time Travel): `npx wrangler d1 time-travel restore`. For a copy, `npx wrangler d1 export`. Session event logs live in Durable Object storage. diff --git a/images/agent/Dockerfile b/images/agent/Dockerfile deleted file mode 100644 index b976b5e3..00000000 --- a/images/agent/Dockerfile +++ /dev/null @@ -1,22 +0,0 @@ -# The default fctl sandbox image: Debian with git, gh, build tools, Python and -# uv, Rust, Node.js, TypeScript, Bun, Claude Code and fctl (README.md lists -# the versions). Sessions run as the `agent` user. -# -# fctl host image build # builds it with your driver (apple or docker) -# docker build -t fctl-agent:latest images/agent -FROM debian:bookworm-slim - -# The fctl release to install and where releases come from; `fctl host -# image build` passes its own version and download_base. Empty: the latest, -# from https://fctl.sh/releases. -ARG FCTL_VERSION= -ARG FCTL_DOWNLOAD= -ENV LANG=C.UTF-8 LC_ALL=C.UTF-8 TZ=UTC -COPY provision.sh /tmp/provision.sh -RUN bash /tmp/provision.sh && rm /tmp/provision.sh - -USER agent -WORKDIR /home/agent -# As /etc/profile.d/fctl.sh (provision.sh) sets it for login shells. -ENV PATH=/home/agent/.local/bin:/home/agent/.cargo/bin:/home/agent/.bun/bin:/opt/fctl/bin:$PATH -CMD ["tail", "-f", "/dev/null"] diff --git a/images/agent/README.md b/images/agent/README.md deleted file mode 100644 index 039cee3d..00000000 --- a/images/agent/README.md +++ /dev/null @@ -1,53 +0,0 @@ -# Agent image - -The default sandbox for fctl sessions: Debian bookworm with the toolchains -agents build and test with, Claude Code (installed for the `agent` user, who -has passwordless sudo: the sandbox is the boundary) and fctl (in -`/usr/local/bin`). - -- Python 3.15.0 as `python3` and `python` for every user (uv's build of - CPython, in `/opt/uv/python`), and uv 0.13.1. -- Rust 1.99.0 through rustup, with rustfmt, Clippy and the - `wasm32-unknown-unknown` target: the toolchain in this repository's - `rust-toolchain.toml`, so sessions working on fctl have nothing to - download. -- Node.js 22 with npm, TypeScript 7.0.2 (`tsc`) and Bun 1.4.3. -- build-essential (gcc, make), cmake, pkg-config and OpenSSL's headers. -- git, the GitHub CLI, ripgrep, fd, jq, ShellCheck, sqlite3, curl, wget, - rsync, lsof, fuser, tree, file, zip, xz and zstd. - -The versions are set at the top of `provision.sh`. A test in -`crates/fctl-host/src/image.rs` fails when Rust's differs from -`rust-toolchain.toml`. - -- Rust and Bun are installed for the agent user (in `~/.rustup` and - `~/.cargo`, and `~/.bun`), so agents add toolchains, targets and global - tools without sudo: `cargo install`, `bun add -g`, and for Python `uv - tool install` and `uv python install`. Images built from this one run - cargo as `agent`. -- Python is marked externally managed: packages go into a virtual - environment (`uv venv`, `python3 -m venv`) or come with `uv run --with`. - Debian's Python 3.11, which Node.js depends on, stays in `/usr/bin`, - after `/usr/local/bin` on the PATH. -- `~/.local/bin`, `~/.cargo/bin`, `~/.bun/bin` and `/opt/fctl/bin` lead the - PATH. The Dockerfile sets it, and `/etc/profile.d/fctl.sh` sets it for - login shells (setup scripts, the Lima VM). fctl-agent passes Claude the - PATH, HOME and locale but not the image's other environment variables, so - every tool here works from the PATH alone. -- npm leaves out its funding and audit notices and its update check - (`/usr/etc/npmrc`); `npm audit` still runs when asked. -- `fctl host image build` builds it locally as `fctl-agent:latest` with the - host's driver (Apple `container build` or `docker build`), or provisions - the `fctl-base` Lima VM with the same `provision.sh`. It installs the - host's own version of fctl (`FCTL_VERSION`; the latest release when that - one is not published). -- Agents use fctl to name and describe their session: `fctl edit --title … - --description …` reaches fctl-agent over the session socket and needs no - sign-in. At each start fctl-agent writes how to do that to `~/AGENTS.md`, - beside the checkout in `~/workspace`, and imports it from Claude's user - memory (`~/.claude/CLAUDE.md`), so it applies in every repository. -- Projects can use any other image (Settings → Sandbox image). It needs - `sh`, `tail`, git and Claude Code on the PATH; fctl copies its supervisor - into `/opt/fctl/bin` at session start. With fctl on the PATH as well, - agents name their sessions; without it, sessions keep the title they - start with. diff --git a/images/agent/provision.sh b/images/agent/provision.sh deleted file mode 100644 index d93f1367..00000000 --- a/images/agent/provision.sh +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/env bash -# shellcheck disable=SC2016 # single-quoted scripts expand in the agent's shell -# Provisions an fctl agent sandbox: the tools agents need, Claude Code and -# fctl. Used by the Dockerfile (container sandboxes) and by `fctl host image -# build --driver lima` (the fctl-base VM). Runs as root. -# -# FCTL_VERSION picks the fctl release and FCTL_DOWNLOAD where releases come -# from (`fctl host image build` passes its own version and download_base); -# empty means the latest, from https://fctl.sh/releases. -set -euo pipefail - -AGENT_USER="${AGENT_USER:-agent}" -# Toolchain versions. Rust is the release this repository builds with -# (rust-toolchain.toml; a test in crates/fctl-host/src/image.rs keeps the two -# in step), so sessions working on fctl have nothing to download. -NODE_MAJOR="${NODE_MAJOR:-22}" -TYPESCRIPT_VERSION="${TYPESCRIPT_VERSION:-7.0.2}" -BUN_VERSION="${BUN_VERSION:-1.4.3}" -UV_VERSION="${UV_VERSION:-0.13.1}" -PYTHON_VERSION="${PYTHON_VERSION:-3.15.0}" -RUST_VERSION="${RUST_VERSION:-1.99.0}" -FCTL_VERSION="${FCTL_VERSION:-}" -FCTL_DOWNLOAD="${FCTL_DOWNLOAD:-}" -export DEBIAN_FRONTEND=noninteractive - -apt-get update -apt-get install -y --no-install-recommends \ - ca-certificates curl wget git gnupg less openssh-client procps psmisc lsof sudo \ - rsync unzip xz-utils zip zstd \ - build-essential cmake pkg-config libssl-dev \ - jq ripgrep fd-find tree file shellcheck sqlite3 -# Debian calls fd `fdfind`. -ln -sf /usr/bin/fdfind /usr/local/bin/fd - -# GitHub CLI -curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg -o /usr/share/keyrings/githubcli-archive-keyring.gpg -echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" \ - > /etc/apt/sources.list.d/github-cli.list - -# Node.js and TypeScript. npm leaves out its funding and audit notices and -# its update check, which only lengthen agents' output. -curl -fsSL "https://deb.nodesource.com/setup_${NODE_MAJOR}.x" | bash - -apt-get install -y --no-install-recommends gh nodejs -corepack enable || true -npm config set --location=global fund=false audit=false update-notifier=false -npm install -g "typescript@$TYPESCRIPT_VERSION" -npm cache clean --force - -# uv, and Python for everyone: uv's build of CPython in /opt/uv/python, as -# python3 and python in /usr/local/bin. -curl -LsSf "https://astral.sh/uv/$UV_VERSION/install.sh" | env UV_INSTALL_DIR=/usr/local/bin UV_NO_MODIFY_PATH=1 sh -env UV_PYTHON_INSTALL_DIR=/opt/uv/python UV_PYTHON_BIN_DIR=/usr/local/bin UV_NO_CACHE=1 \ - uv python install --default --preview-features python-install-default "$PYTHON_VERSION" - -rm -rf /var/lib/apt/lists/* - -# The agent user. The sandbox is the security boundary, so sudo needs no password. -if ! id "$AGENT_USER" >/dev/null 2>&1; then - useradd -m -s /bin/bash -u 1000 "$AGENT_USER" -fi -echo "$AGENT_USER ALL=(ALL) NOPASSWD:ALL" > "/etc/sudoers.d/90-fctl-$AGENT_USER" -chmod 0440 "/etc/sudoers.d/90-fctl-$AGENT_USER" -mkdir -p /opt/fctl/bin -chown -R "$AGENT_USER" /opt/fctl - -# fctl, for everyone on the machine: agents name and describe their session -# with `fctl edit`. A version that is not published (a development build of -# the host) gets the latest release instead. The host copies its own -# fctl-agent in at session start, so the one in the archive goes. -install_fctl() { - curl -fsSL https://fctl.sh/install | - env FCTL_VERSION="$1" FCTL_DOWNLOAD="$FCTL_DOWNLOAD" FCTL_INSTALL_DIR=/usr/local/bin \ - FCTL_NO_COMPLETIONS=1 sh -} -if ! install_fctl "$FCTL_VERSION"; then - [ -n "$FCTL_VERSION" ] || exit 1 - echo "fctl $FCTL_VERSION is not published; installing the latest release" >&2 - install_fctl "" -fi -rm -f /usr/local/bin/fctl-agent-*-linux - -# Claude Code, installed for the agent user (native build, ~/.local/bin/claude). -AGENT_HOME="$(getent passwd "$AGENT_USER" | cut -d: -f6)" -sudo -u "$AGENT_USER" -H bash -c 'curl -fsSL https://claude.ai/install.sh | bash' -sudo -u "$AGENT_USER" -H mkdir -p "$AGENT_HOME/workspace" - -# The agent's PATH: Claude Code and uv's tools in ~/.local/bin, Rust's and -# Bun's tools, then fctl's supervisor. The Dockerfile sets the same; login -# shells (setup scripts, the Lima driver's) get it from here. -cat > /etc/profile.d/fctl.sh <<'EOF' -PATH="$HOME/.local/bin:$HOME/.cargo/bin:$HOME/.bun/bin:/opt/fctl/bin:$PATH" -EOF - -# Runs a script as the agent user in a login shell; it gets the arguments -# after the script as $1…. -as_agent() { - local script="$1" - shift - sudo -u "$AGENT_USER" -H bash -lc "set -euo pipefail; $script" bash "$@" -} - -# Rust, with the components and targets that rust-toolchain.toml lists, and -# Bun, in the agent's home: they find their files through HOME alone -# (fctl-agent passes Claude no RUSTUP_HOME or the like), and agents add -# toolchains, targets and global tools without sudo. -as_agent 'curl --proto "=https" --tlsv1.2 -sSf https://sh.rustup.rs | - sh -s -- -y --no-modify-path --profile minimal --default-toolchain "$1" \ - --component rustfmt,clippy --target wasm32-unknown-unknown' "$RUST_VERSION" -as_agent 'curl -fsSL https://bun.sh/install | bash -s "bun-v$1"' "$BUN_VERSION" -as_agent 'ln -sf bun "$HOME/.bun/bin/bunx"' - -# What sessions find on the PATH. -as_agent 'claude --version; fctl --version; python3 --version; uv --version - rustc --version; cargo --version; node --version; tsc --version; bun --version' diff --git a/web/src/routes/admin.tsx b/web/src/routes/admin.tsx index 5b658b84..8c74796f 100644 --- a/web/src/routes/admin.tsx +++ b/web/src/routes/admin.tsx @@ -369,11 +369,10 @@ function Runners() {
2. Register it as a runner and start the service
-
3. Build the sandbox image (once, a few minutes)
-

- It shows up here as online within seconds. `fctl host doctor` checks everything, including - whether the Mac is set to never sleep. + It shows up here as online within seconds and pulls the sandbox image in the background. With + Lima, prepare the base VM once with `fctl host image build`. `fctl host doctor` checks + everything, including whether the Mac is set to never sleep.

)} diff --git a/web/src/routes/project.tsx b/web/src/routes/project.tsx index 9ebdf2cd..8a3ce6a8 100644 --- a/web/src/routes/project.tsx +++ b/web/src/routes/project.tsx @@ -664,7 +664,7 @@ function Settings({ project }: { project: G.Project }) { value={s.image ?? ""} onChange={(e) => set("image", e.target.value || undefined)} className="font-mono" - placeholder="fctl-agent:latest" + placeholder="ghcr.io/hyperstructure/sandbox" /> )}