From 3ead722c196b30dce39546ad1d560b25fa9793c7 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" Date: Sun, 18 Oct 2026 02:31:07 +0000 Subject: [PATCH 01/10] ci: publish the sandbox image to GHCR for arm64 and amd64 The Image workflow builds images/agent at a release's tag on a native runner per architecture, checks each build with images/agent/check.sh, and tags both as ghcr.io/hyperstructure/fctl-agent:, and :. and :latest when that release is the newest they cover. The Release workflow starts it for every release; a daily run rebuilds the latest release's image when Claude Code has a newer release than the one inside or the image is a week old. Pull requests that change the image build it without publishing. provision.sh installs the Claude Code version it is given, so both architectures get the one the image is labelled with. Refs #2 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/image.yml | 262 ++++++++++++++++++++++++++++++++++ .github/workflows/release.yml | 11 +- images/agent/Dockerfile | 7 +- images/agent/check.sh | 43 ++++++ images/agent/provision.sh | 8 +- 5 files changed, 325 insertions(+), 6 deletions(-) create mode 100644 .github/workflows/image.yml create mode 100644 images/agent/check.sh diff --git a/.github/workflows/image.yml b/.github/workflows/image.yml new file mode 100644 index 00000000..c6072020 --- /dev/null +++ b/.github/workflows/image.yml @@ -0,0 +1,262 @@ +# Publishes the default sandbox image, images/agent, for arm64 and amd64 as +# ghcr.io/hyperstructure/fctl-agent:, :. and :latest +# (docs/sandbox-images.md). Each release gets its own: built from the +# release's tag, with that release of fctl and the newest Claude Code. +# +# - The Release workflow starts it for every release. +# - Every day it rebuilds the latest release's image when Claude Code has a +# newer release than the one inside, or when the image is a week old (for +# Debian's updates): fctl turns off Claude Code's auto-updater, so an +# image's Claude Code is as old as the image. +# - `gh workflow run image.yml -f tag=v0.2.1 -f force=true` rebuilds one. +# - Pull requests that change the image build it without publishing. +# +# Each architecture builds on its own runner and is pushed by digest, without +# a tag, then checked with images/agent/check.sh; the last job tags the two +# as one image. Moving tags move only to the newest release they cover. +name: Image + +on: + pull_request: + paths: + - images/agent/** + - .github/workflows/image.yml + schedule: + - cron: "41 5 * * *" + workflow_dispatch: + inputs: + tag: + description: The release to build, like v0.2.1 (default the latest) + required: false + force: + description: Build even when the published image is current + type: boolean + default: false + +permissions: + contents: read + +concurrency: + group: image-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} + cancel-in-progress: true + +env: + IMAGE: ghcr.io/hyperstructure/fctl-agent + +jobs: + plan: + name: What to build + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: read + packages: read + outputs: + ref: ${{ steps.plan.outputs.ref }} + version: ${{ steps.plan.outputs.version }} + claude: ${{ steps.plan.outputs.claude }} + tags: ${{ steps.plan.outputs.tags }} + created: ${{ steps.plan.outputs.created }} + build: ${{ steps.plan.outputs.build }} + push: ${{ steps.plan.outputs.push }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + fetch-tags: true + - name: Versions and tags + id: plan + env: + EVENT: ${{ github.event_name }} + TAG: ${{ inputs.tag }} + FORCE: ${{ inputs.force && 'yes' || '' }} + GH_TOKEN: ${{ github.token }} + run: | + semver='^[0-9]+\.[0-9]+\.[0-9]+$' + latest=$(curl -fsS --retry 3 https://fctl.sh/releases/latest | tr -d '[:space:]') + [[ $latest =~ $semver ]] || { echo "::error::fctl.sh/releases/latest says '$latest'"; exit 1; } + # What https://claude.ai/install.sh installs; every architecture gets this one. + claude=$(curl -fsS --retry 3 https://downloads.claude.ai/claude-code-releases/latest | tr -d '[:space:]') + [[ $claude =~ $semver ]] || { echo "::error::downloads.claude.ai says the latest Claude Code is '$claude'"; exit 1; } + + if [ "$EVENT" = pull_request ]; then + # This change's images/agent with the latest fctl; nothing is pushed. + ref=$GITHUB_SHA version=$latest push=no + else + tag=${TAG:-$latest} tag=v${tag#v} + [[ ${tag#v} =~ $semver ]] || { echo "::error::$tag is not a release tag like v0.2.1"; exit 1; } + git rev-parse -q --verify "refs/tags/$tag" >/dev/null || { echo "::error::there is no tag $tag"; exit 1; } + ref=$tag version=${tag#v} push=yes + fi + + minor=${version%.*} + newest_minor=$({ git tag -l "v$minor.*" | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' || true; } | sort -V | tail -n 1) + tags="$IMAGE:$version" + if [ "$newest_minor" = "v$version" ]; then tags="$tags $IMAGE:$minor"; fi + if [ "$version" = "$latest" ]; then tags="$tags $IMAGE:latest"; fi + + build=yes why="fctl $version with Claude Code $claude" + if [ "$push" = yes ] && [ -z "$FORCE" ]; then + echo "$GH_TOKEN" | docker login ghcr.io -u "$GITHUB_ACTOR" --password-stdin >/dev/null + if index=$(docker buildx imagetools inspect --raw "$IMAGE:$version" 2>/dev/null); then + have=$(jq -r '.annotations["sh.fctl.claude-code.version"] // ""' <<<"$index") + built=$(jq -r '.annotations["org.opencontainers.image.created"] // "1970-01-01"' <<<"$index") + age=$(( ($(date +%s) - $(date -d "$built" +%s 2>/dev/null || echo 0)) / 86400 )) + if [ "$have" = "$claude" ] && [ "$age" -lt 7 ]; then + build=no why="$IMAGE:$version already has Claude Code $claude and is $age days old" + fi + fi + fi + + { + echo "ref=$ref" + echo "version=$version" + echo "claude=$claude" + echo "tags=$tags" + echo "created=$(date -u +%Y-%m-%dT%H:%M:%SZ)" + echo "build=$build" + echo "push=$push" + } >> "$GITHUB_OUTPUT" + { + if [ "$build" = no ]; then + echo "Nothing to build: $why." + elif [ "$push" = yes ]; then + echo "Building $why from \`$ref\` for $tags." + else + echo "Building $why from this pull request, without publishing it." + fi + } >> "$GITHUB_STEP_SUMMARY" + + build: + name: Build (${{ matrix.arch }}) + needs: plan + if: needs.plan.outputs.build == 'yes' + strategy: + matrix: + include: + - arch: amd64 + runner: ubuntu-24.04 + - arch: arm64 + runner: ubuntu-24.04-arm + runs-on: ${{ matrix.runner }} + timeout-minutes: 45 + permissions: + contents: read + packages: write + env: + REF: ${{ needs.plan.outputs.ref }} + VERSION: ${{ needs.plan.outputs.version }} + CLAUDE: ${{ needs.plan.outputs.claude }} + CREATED: ${{ needs.plan.outputs.created }} + PUSH: ${{ needs.plan.outputs.push }} + steps: + # This workflow's commit, for check.sh, and the image's sources at the release. + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ needs.plan.outputs.ref }} + path: release + - name: Build + id: build + env: + GH_TOKEN: ${{ github.token }} + ARCH: ${{ matrix.arch }} + run: | + docker buildx create --name fctl --driver docker-container --use >/dev/null + if [ "$PUSH" = yes ]; then + echo "$GH_TOKEN" | docker login ghcr.io -u "$GITHUB_ACTOR" --password-stdin >/dev/null + output="type=image,name=$IMAGE,push-by-digest=true,name-canonical=true,push=true" + else + output="type=docker,name=fctl-agent:check" + fi + docker buildx build release/images/agent \ + --platform "linux/$ARCH" --pull --provenance=false \ + --build-arg "FCTL_VERSION=$VERSION" \ + --build-arg "CLAUDE_VERSION=$CLAUDE" \ + --label "org.opencontainers.image.title=fctl-agent" \ + --label "org.opencontainers.image.description=The default sandbox for fctl sessions" \ + --label "org.opencontainers.image.url=https://fctl.sh/docs/sandbox-images/" \ + --label "org.opencontainers.image.source=https://github.com/hyperstructure/fctl" \ + --label "org.opencontainers.image.licenses=MIT" \ + --label "org.opencontainers.image.version=$VERSION" \ + --label "org.opencontainers.image.revision=$(git -C release rev-parse HEAD)" \ + --label "org.opencontainers.image.created=$CREATED" \ + --label "sh.fctl.version=$VERSION" \ + --label "sh.fctl.claude-code.version=$CLAUDE" \ + --output "$output" \ + --metadata-file "$RUNNER_TEMP/build.json" + if [ "$PUSH" = yes ]; then + digest=$(jq -r '."containerimage.digest"' "$RUNNER_TEMP/build.json") + echo "digest=$digest" >> "$GITHUB_OUTPUT" + echo "image=$IMAGE@$digest" >> "$GITHUB_OUTPUT" + else + echo "image=fctl-agent:check" >> "$GITHUB_OUTPUT" + fi + - name: Check it + env: + CHECK: ${{ steps.build.outputs.image }} + ARCH: ${{ matrix.arch }} + run: | + docker run --rm -i -e FCTL_VERSION="$VERSION" -e CLAUDE_VERSION="$CLAUDE" "$CHECK" sh -s < images/agent/check.sh + docker image inspect --format '{{.Size}}' "$CHECK" | + awk -v arch="$ARCH" '{ printf "%s: %.2f GB\n", arch, $1 / 1e9 }' >> "$GITHUB_STEP_SUMMARY" + - name: Note its digest + if: needs.plan.outputs.push == 'yes' + env: + DIGEST: ${{ steps.build.outputs.digest }} + run: | + mkdir -p "$RUNNER_TEMP/digests" + touch "$RUNNER_TEMP/digests/${DIGEST#sha256:}" + - if: needs.plan.outputs.push == 'yes' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: digest-${{ matrix.arch }} + path: ${{ runner.temp }}/digests/* + if-no-files-found: error + retention-days: 1 + + publish: + name: Publish + needs: [plan, build] + if: needs.plan.outputs.push == 'yes' + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: read + packages: write + env: + VERSION: ${{ needs.plan.outputs.version }} + CLAUDE: ${{ needs.plan.outputs.claude }} + CREATED: ${{ needs.plan.outputs.created }} + TAGS: ${{ needs.plan.outputs.tags }} + steps: + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: digest-* + path: ${{ runner.temp }}/digests + merge-multiple: true + - name: Tag both architectures as one image + env: + GH_TOKEN: ${{ github.token }} + run: | + echo "$GH_TOKEN" | docker login ghcr.io -u "$GITHUB_ACTOR" --password-stdin >/dev/null + sources=() + for file in "$RUNNER_TEMP"/digests/*; do sources+=("$IMAGE@sha256:$(basename "$file")"); done + [ "${#sources[@]}" = 2 ] || { echo "::error::expected a digest for each architecture, got ${sources[*]}"; exit 1; } + tags=() + for tag in $TAGS; do tags+=(--tag "$tag"); done + # On the index too: GHCR shows these, and the daily run reads the + # Claude Code version and the date from them. + docker buildx imagetools create "${tags[@]}" \ + --annotation "index:org.opencontainers.image.description=The default sandbox for fctl sessions" \ + --annotation "index:org.opencontainers.image.source=https://github.com/hyperstructure/fctl" \ + --annotation "index:org.opencontainers.image.licenses=MIT" \ + --annotation "index:org.opencontainers.image.version=$VERSION" \ + --annotation "index:org.opencontainers.image.created=$CREATED" \ + --annotation "index:sh.fctl.claude-code.version=$CLAUDE" \ + "${sources[@]}" + docker buildx imagetools inspect "$IMAGE:$VERSION" + { + echo "Published fctl $VERSION with Claude Code $CLAUDE as:" + for tag in $TAGS; do echo "- \`$tag\`"; done + } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5584aa63..1a349f09 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -5,8 +5,9 @@ # since the last tag (`cargo xtask release`), writes CHANGELOG.md and the # version, and pushes the release commit and tag to main. "Build and publish" # then builds the archives, 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` +# to https://fctl.sh/releases, starts the Image workflow (the release's sandbox +# image, ghcr.io/hyperstructure/fctl-agent) 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. @@ -150,6 +151,12 @@ jobs: test "$(curl -fsS https://fctl.sh/releases/latest)" = "${TAG#v}" curl -fsSL https://fctl.sh/install | FCTL_INSTALL_DIR="$RUNNER_TEMP/bin" sh "$RUNNER_TEMP/bin/fctl" --version + - name: Publish the sandbox image + env: + GH_TOKEN: ${{ github.token }} + # Hosts pull the image with their own version's tag. It installs fctl + # from fctl.sh/releases, so it is built once the release is there. + run: gh workflow run image.yml --ref main -f tag="$TAG" - name: Redeploy app.fctl.sh on the release commit if: inputs.tag == '' env: diff --git a/images/agent/Dockerfile b/images/agent/Dockerfile index e6c3a36c..a1524019 100644 --- a/images/agent/Dockerfile +++ b/images/agent/Dockerfile @@ -1,15 +1,18 @@ # The default fctl sandbox image: Debian with git, gh, Node.js, Python (uv), # build tools, Claude Code and fctl. Sessions run as the `agent` user. +# .github/workflows/image.yml publishes it as ghcr.io/hyperstructure/fctl-agent. # # fctl host image build # builds it with your driver (apple or docker) -# docker build -t fctl-agent:latest images/agent +# docker build -t fctl-agent:dev 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. +# from https://fctl.sh/releases. CLAUDE_VERSION pins Claude Code (empty: the +# latest release). ARG FCTL_VERSION= ARG FCTL_DOWNLOAD= +ARG CLAUDE_VERSION= 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 diff --git a/images/agent/check.sh b/images/agent/check.sh new file mode 100644 index 00000000..17120375 --- /dev/null +++ b/images/agent/check.sh @@ -0,0 +1,43 @@ +#!/bin/sh +# Checks an image built from this directory for what fctl and images built +# FROM it rely on (docs/sandbox-images.md): the agent user, sudo, the PATH and +# the tools. Runs inside the image as its user; the image workflow runs it on +# every build: +# +# docker run --rm -i -e FCTL_VERSION=0.3.0 -e CLAUDE_VERSION=2.1.302 IMAGE sh -s < images/agent/check.sh +# +# FCTL_VERSION and CLAUDE_VERSION, when set, are the versions it must have. +set -eu + +fail() { + echo "check.sh: $*" >&2 + exit 1 +} + +[ "$(id -un)" = agent ] || fail "runs as $(id -un), not agent" +[ "$(id -u)" = 1000 ] || fail "agent has uid $(id -u), not 1000" +[ "$HOME" = /home/agent ] || fail "HOME is $HOME, not /home/agent" +sudo -n true 2>/dev/null || fail "agent cannot use sudo without a password" +for dir in "$HOME/.local/bin" /opt/fctl/bin; do + case ":$PATH:" in + *":$dir:"*) ;; + *) fail "$dir is not on the PATH ($PATH)" ;; + esac +done +[ -d /opt/fctl/bin ] || fail "/opt/fctl/bin is missing" +[ -d "$HOME/workspace" ] && [ -w "$HOME/workspace" ] || fail "$HOME/workspace is missing or not writable" +for tool in sh tail git gh claude fctl node npm python3 uv rg jq curl make cc; do + command -v "$tool" >/dev/null 2>&1 || fail "$tool is not on the PATH" +done +[ "$(command -v claude)" = "$HOME/.local/bin/claude" ] || fail "claude is $(command -v claude), not ~/.local/bin/claude" + +# `2.1.302 (Claude Code)` and `fctl 0.3.0`. +claude=$(claude --version) +claude=${claude%% *} +fctl=$(fctl --version) +fctl=${fctl#fctl } +[ -z "${CLAUDE_VERSION:-}" ] || [ "$claude" = "$CLAUDE_VERSION" ] || + fail "Claude Code is $claude, not $CLAUDE_VERSION" +[ -z "${FCTL_VERSION:-}" ] || [ "$fctl" = "$FCTL_VERSION" ] || + fail "fctl is $fctl, not $FCTL_VERSION" +echo "The image is as expected, with fctl $fctl and Claude Code $claude." diff --git a/images/agent/provision.sh b/images/agent/provision.sh index e68261ee..805ec57e 100644 --- a/images/agent/provision.sh +++ b/images/agent/provision.sh @@ -5,13 +5,16 @@ # # 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. +# empty means the latest, from https://fctl.sh/releases. CLAUDE_VERSION +# picks Claude Code's (empty: the latest); the image workflow passes the one +# it labels the image with, so that every architecture gets the same. set -euo pipefail AGENT_USER="${AGENT_USER:-agent}" NODE_MAJOR="${NODE_MAJOR:-22}" FCTL_VERSION="${FCTL_VERSION:-}" FCTL_DOWNLOAD="${FCTL_DOWNLOAD:-}" +CLAUDE_VERSION="${CLAUDE_VERSION:-}" export DEBIAN_FRONTEND=noninteractive apt-get update @@ -62,7 +65,8 @@ 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 env CLAUDE_VERSION="$CLAUDE_VERSION" \ + bash -c 'curl -fsSL https://claude.ai/install.sh | bash -s -- ${CLAUDE_VERSION:+"$CLAUDE_VERSION"}' sudo -u "$AGENT_USER" -H mkdir -p "$AGENT_HOME/workspace" grep -q '.local/bin' "$AGENT_HOME/.profile" 2>/dev/null || echo 'export PATH="$HOME/.local/bin:/opt/fctl/bin:$PATH"' >> "$AGENT_HOME/.profile" "$AGENT_HOME/.local/bin/claude" --version From 9af66af91882b4686c749321b8ea9a53060b65e9 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" Date: Sun, 18 Oct 2026 02:50:02 +0000 Subject: [PATCH 02/10] feat(host): use the published sandbox image of the host's version A host whose host.toml sets no image now runs sessions from ghcr.io/hyperstructure/fctl-agent:, so upgrading the host moves new sessions to the new version's image. `image` is optional in host.toml; the old default's name, fctl-agent:latest, which every host installed until now has there, means the default again, for the host and for projects. - The daemon pulls the host's image in the background when it starts and the image isn't there. Sessions pull a missing image themselves, never over one that is there, so a local build is kept. - A session on the default image whose version can't be pulled (in the minutes before a release's image is published) starts from :latest and says so in its log. Failures other than a missing image no longer try a pull. - Apple's container pulls only the host's platform: without --platform it downloads every platform of an image. - `fctl host image pull` pulls the host's image again, for a newer build of its tag; `fctl host image build` builds it under the host's image name; install, status and doctor show the image. - The web app's runner steps no longer ask to build the image. Refs #2 Co-Authored-By: Claude Opus 5.5 --- crates/fctl-host/src/config.rs | 77 +++++- crates/fctl-host/src/daemon.rs | 23 +- crates/fctl-host/src/driver/container.rs | 297 +++++++++++++++++++++-- crates/fctl-host/src/driver/mod.rs | 24 ++ crates/fctl-host/src/login.rs | 3 +- crates/fctl-host/src/session.rs | 13 +- crates/fctl/src/cmd/host.rs | 77 ++++-- web/src/routes/admin.tsx | 7 +- web/src/routes/project.tsx | 2 +- 9 files changed, 472 insertions(+), 51 deletions(-) diff --git a/crates/fctl-host/src/config.rs b/crates/fctl-host/src/config.rs index d808b1e8..0181a932 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, `images/agent`, is published +/// (.github/workflows/image.yml): a tag for every release. +pub const IMAGE_REPOSITORY: &str = "ghcr.io/hyperstructure/fctl-agent"; + +/// 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/fctl-agent:{}", + 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/fctl-agent: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 2d7206cf..8381d552 100644 --- a/crates/fctl-host/src/daemon.rs +++ b/crates/fctl-host/src/daemon.rs @@ -82,6 +82,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. async fn recover(&mut self) { match self.ctx.driver.list().await { @@ -167,13 +187,14 @@ 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.refresh_sandbox_limits().await), } } pub async fn run(mut self) -> Result<()> { keep_awake(); + self.prefetch_image(); self.recover().await; self.sweep_stopped().await; let url = format!( diff --git a/crates/fctl-host/src/driver/container.rs b/crates/fctl-host/src/driver/container.rs index d2bcf5a0..4fc71f88 100644 --- a/crates/fctl-host/src/driver/container.rs +++ b/crates/fctl-host/src/driver/container.rs @@ -27,6 +27,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 { @@ -178,6 +185,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)), @@ -198,28 +232,52 @@ 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(()); + }; + if self.has_image(image).await { + return Err(failed(e)); } - Ok(sb) + 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(()) } pub async fn install_agent(&self, sb: &Sandbox, binary: &Path) -> Result<()> { @@ -344,6 +402,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(); @@ -387,6 +454,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/fctl-agent:0.3.0"; + const LATEST_IMAGE: &str = "ghcr.io/hyperstructure/fctl-agent: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 5a033f16..b9d5a202 100644 --- a/crates/fctl-host/src/driver/mod.rs +++ b/crates/fctl-host/src/driver/mod.rs @@ -22,6 +22,8 @@ use tokio::io::{AsyncRead, AsyncWrite}; 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, } @@ -138,6 +140,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/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 dedd39d8..b5af8d6f 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::{Driver, Sandbox, SandboxSpec, sandbox_name}; use crate::files; use crate::uplink::Uplink; @@ -265,16 +265,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/src/cmd/host.rs b/crates/fctl/src/cmd/host.rs index f28d98c5..5d9af9a3 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,12 +71,14 @@ 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, }, @@ -112,7 +117,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 +150,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).await?; } let info = d.probe().await; if !info.available { @@ -189,14 +194,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 +234,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 +243,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 +265,34 @@ pub async fn run(server: Option<&str>, cmd: HostCmd, json: bool) -> Result<()> { } Ok(()) } + 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 }) => { 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).await } HostCmd::Restart => { service::restart()?; @@ -327,6 +359,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/web/src/routes/admin.tsx b/web/src/routes/admin.tsx index 5b658b84..747e4177 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 while it waits for its + first session. 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 8ed9b6de..09d56611 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/fctl-agent" /> )} From 5fa0f68de919572ea90f53886b8c9951394f927f Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" Date: Sun, 18 Oct 2026 02:50:02 +0000 Subject: [PATCH 03/10] docs: describe the published sandbox image and its layout docs/sandbox-images.md says where the default image is published, its tags and labels, how hosts get it, and the layout images built FROM it rely on: the agent user (uid 1000, passwordless sudo), ~/.local/bin and /opt/fctl/bin first on the PATH, and the tools. Getting started, the CLI, self-hosting, security, the architecture and the release skill follow: hosts pull the image instead of building it. Refs #2 Co-Authored-By: Claude Opus 5.5 --- .claude/skills/release/SKILL.md | 21 ++++++- README.md | 2 +- ROADMAP.md | 2 +- docs/README.md | 1 + docs/architecture.md | 12 +++- docs/cli.md | 10 ++- docs/development.md | 7 ++- docs/getting-started.md | 14 +++-- docs/sandbox-images.md | 108 ++++++++++++++++++++++++++++++++ docs/security.md | 7 +++ docs/self-hosting.md | 11 ++-- images/agent/README.md | 26 +++++--- 12 files changed, 191 insertions(+), 30 deletions(-) create mode 100644 docs/sandbox-images.md diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md index cd9d8b26..c0113ab0 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 and the sandbox image to GHCR, 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. --- # Releasing fctl @@ -53,8 +53,15 @@ It runs two jobs: 2. **Build and publish**: builds fctl for macOS and Linux (arm64 and x86_64) and the Linux agents, creates the GitHub release with the notes, publishes the files to https://fctl.sh/releases (moving - `latest`), installs it with the installer as a check, and starts CI on - `main`, which redeploys app.fctl.sh. + `latest`), installs it with the installer as a check, starts the + **Image** workflow, and starts CI on `main`, which redeploys + app.fctl.sh. + +The Image workflow (`.github/workflows/image.yml`) builds the release's +sandbox image from its tag, for arm64 and amd64, and publishes it as +`ghcr.io/hyperstructure/fctl-agent:X.Y.Z`, moving `X.Y` and `latest`. +Hosts of the new version pull it; until it is there, their sessions start +from `latest`. Follow it with `gh run watch` or in the Actions tab; it takes about 20 minutes. @@ -65,6 +72,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. +- The Image workflow's run for the tag passed (`gh run list --workflow + image.yml`), and `docker buildx imagetools inspect + ghcr.io/hyperstructure/fctl-agent:X.Y.Z` lists linux/amd64 and + linux/arm64. - Hosts update with `fctl self update` (it restarts the host service; running sessions keep going). @@ -76,6 +87,10 @@ minutes. infrastructure, rebuild the tag 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** (the Image workflow failed): fix the cause in a pull + request if it is the workflow, then start it again for the tag: + `gh workflow run image.yml --ref main -f tag=vX.Y.Z`. It builds from the + tag, so a broken `images/agent` needs a patch release. - Never move or delete a published tag or its files on fctl.sh: installed CLIs and hosts download releases by version. 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 1361cd2e..4fac6323 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) - [ ] Notifications when a session waits for you or fails (email, web push) (#4) - [ ] Homebrew tap: `brew install hyperstructure/tap/fctl` (#5) 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/architecture.md b/docs/architecture.md index bde1d789..5a6f6800 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -42,7 +42,7 @@ 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). Served by fctl-control. | browser | -| `images/agent` | The default sandbox image (Debian, git, gh, node, python, claude, fctl). | sandboxes | +| `images/agent` | The default sandbox image (Debian, git, gh, node, python, claude, fctl), published to `ghcr.io/hyperstructure/fctl-agent`. | sandboxes | Two more repositories complete the picture: [hyperstructure/design](https://github.com/hyperstructure/design) @@ -280,6 +280,16 @@ until the limit resets. 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/fctl-agent:`. The Image workflow +(`.github/workflows/image.yml`) publishes it for arm64 and amd64 with 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)). + | 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 b594e246..c52d8e7f 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -118,7 +118,8 @@ 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 restart # sessions keep running fctl host uninstall # sandboxes are kept ``` @@ -135,7 +136,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) @@ -143,6 +144,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/fctl-agent:`, 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 bbfccf09..3c5525b6 100644 --- a/docs/development.md +++ b/docs/development.md @@ -145,7 +145,12 @@ last tag, adds the notes to `CHANGELOG.md`, pushes the release commit and tag, builds the archives (`cargo xtask dist`: fctl for macOS and Linux on arm64 and x86_64, and the Linux agents), creates the GitHub release with the notes, publishes to `https://fctl.sh/releases` (`cargo xtask publish ---latest`) and redeploys app.fctl.sh. +--latest`), starts the **Image** workflow, which publishes the release's +sandbox image to `ghcr.io/hyperstructure/fctl-agent`, and redeploys +app.fctl.sh. The Image workflow also runs every day, to rebuild the latest +release's image when Claude Code has a newer release, and on pull requests +that change `images/agent`, which it builds for both architectures and +checks with `images/agent/check.sh` without publishing. ```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 96343eec..e059992a 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -69,14 +69,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, Node, Python, uv 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, Node, Python, uv 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..185af49a --- /dev/null +++ b/docs/sandbox-images.md @@ -0,0 +1,108 @@ +# 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/fctl-agent` is built from +[`images/agent`](../images/agent): Debian bookworm with git, the GitHub CLI, +Node.js 22, Python 3 with uv, build tools, ripgrep, Claude Code and fctl. It +is published for arm64 (Apple silicon) and amd64. + +| Tag | Image | +|---|---| +| `0.3.0` | fctl 0.3.0's. Hosts of that version use it. | +| `0.3` | The newest 0.3 release's. | +| `latest` | The newest release's. | + +Each release's image is published a few minutes after the release, by the +Image workflow (`.github/workflows/image.yml`). 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 rebuild +moves the tags; to pin one build, add its digest: +`ghcr.io/hyperstructure/fctl-agent:0.3.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 it was built from | +| `org.opencontainers.image.created` | when it was built | + +```sh +docker image inspect ghcr.io/hyperstructure/fctl-agent:0.3.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 minutes before a +release's 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 default image's name before it was published, + means the default. +- **Building it.** `fctl host image build` builds the default image on the + host with its driver, under the same name, so sessions use the build: for + a host that can't reach ghcr.io, or to try changes to `images/agent` with + an fctl built from them. 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 same 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/fctl-agent:0.2.1` + (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. `images/agent/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 is (the native + build), and `/opt/fctl/bin`, where fctl copies its supervisor, fctl-agent, + at session start. fctl itself is in `/usr/local/bin`. +- **The tools**: git, gh, Node.js 22 with npm and corepack, Python 3 with + pip, venv and uv, build-essential, pkg-config, ripgrep, fd (as `fdfind`), + jq, curl, zip and tree. + +An image that installs something as root switches back to `agent` at the +end: + +```dockerfile +FROM ghcr.io/hyperstructure/fctl-agent:0.3 +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 4ee004bc..246b0a7a 100644 --- a/docs/security.md +++ b/docs/security.md @@ -114,6 +114,13 @@ 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/fctl-agent`, which this repository's +Image workflow builds from `images/agent`. 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 d5705a34..8912f32e 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/fctl-agent`; 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/README.md b/images/agent/README.md index df9bc4f3..53e2db0f 100644 --- a/images/agent/README.md +++ b/images/agent/README.md @@ -4,19 +4,25 @@ The default sandbox for fctl sessions: Debian bookworm with git, the GitHub CLI, Node.js 22, Python 3 with uv, build tools, ripgrep, Claude Code (installed for the `agent` user, who has passwordless sudo: the sandbox is the boundary) and fctl (in `/usr/local/bin`). +[Sandbox images](../../docs/sandbox-images.md) describes it for the people +who run it or build images from it. -- `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). +- The Image workflow (`.github/workflows/image.yml`) publishes it as + `ghcr.io/hyperstructure/fctl-agent` for arm64 and amd64: a release's + image is built from its tag, with that release of fctl and the newest + Claude Code (`CLAUDE_VERSION`), and the latest release's is rebuilt when + Claude Code has a newer release. Hosts pull the tag of their own version. +- Images built `FROM` it rely on its layout: the `agent` user (uid 1000, + passwordless sudo), `~/.local/bin` and `/opt/fctl/bin` first on the PATH, + and the tools. `check.sh` checks every build for it; keep it, or change + it together with the docs. +- `fctl host image build` builds it on a host instead, under the host's + image name, 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. From d14c49a6a0b63ce6390850c4aed7952ae2b7d564 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" Date: Sun, 18 Oct 2026 02:59:56 +0000 Subject: [PATCH 04/10] ci: push OCI images and start the image after the redeploy The image workflow pushes each architecture with OCI media types, so the index it tags them under, which carries annotations, doesn't mix them with Docker's. The Release workflow starts it after starting CI, so that a failed dispatch can't hold back the redeploy of app.fctl.sh. The runner dialog says the host pulls the image in the background. Refs #2 Co-Authored-By: Claude Opus 5.5 --- .claude/skills/release/SKILL.md | 5 ++--- .github/workflows/image.yml | 2 +- .github/workflows/release.yml | 18 +++++++++--------- docs/development.md | 12 ++++++------ web/src/routes/admin.tsx | 6 +++--- 5 files changed, 21 insertions(+), 22 deletions(-) diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md index c0113ab0..5feefc69 100644 --- a/.claude/skills/release/SKILL.md +++ b/.claude/skills/release/SKILL.md @@ -53,9 +53,8 @@ It runs two jobs: 2. **Build and publish**: builds fctl for macOS and Linux (arm64 and x86_64) and the Linux agents, creates the GitHub release with the notes, publishes the files to https://fctl.sh/releases (moving - `latest`), installs it with the installer as a check, starts the - **Image** workflow, and starts CI on `main`, which redeploys - app.fctl.sh. + `latest`), installs it with the installer as a check, starts CI on + `main`, which redeploys app.fctl.sh, and starts the **Image** workflow. The Image workflow (`.github/workflows/image.yml`) builds the release's sandbox image from its tag, for arm64 and amd64, and publishes it as diff --git a/.github/workflows/image.yml b/.github/workflows/image.yml index c6072020..5062cb11 100644 --- a/.github/workflows/image.yml +++ b/.github/workflows/image.yml @@ -165,7 +165,7 @@ jobs: docker buildx create --name fctl --driver docker-container --use >/dev/null if [ "$PUSH" = yes ]; then echo "$GH_TOKEN" | docker login ghcr.io -u "$GITHUB_ACTOR" --password-stdin >/dev/null - output="type=image,name=$IMAGE,push-by-digest=true,name-canonical=true,push=true" + output="type=image,name=$IMAGE,push-by-digest=true,name-canonical=true,push=true,oci-mediatypes=true" else output="type=docker,name=fctl-agent:check" fi diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1a349f09..4365d872 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -5,9 +5,9 @@ # since the last tag (`cargo xtask release`), writes CHANGELOG.md and the # version, and pushes the release commit and tag to main. "Build and publish" # then builds the archives, makes the GitHub release with the notes, publishes -# to https://fctl.sh/releases, starts the Image workflow (the release's sandbox -# image, ghcr.io/hyperstructure/fctl-agent) and starts CI on main, which -# redeploys app.fctl.sh. `tag` rebuilds an existing release tag from main; `dry_run` +# to https://fctl.sh/releases, starts CI on main, which redeploys app.fctl.sh, +# and starts the Image workflow, which publishes the release's sandbox image to +# ghcr.io/hyperstructure/fctl-agent. `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. @@ -151,15 +151,15 @@ jobs: test "$(curl -fsS https://fctl.sh/releases/latest)" = "${TAG#v}" curl -fsSL https://fctl.sh/install | FCTL_INSTALL_DIR="$RUNNER_TEMP/bin" sh "$RUNNER_TEMP/bin/fctl" --version - - name: Publish the sandbox image - env: - GH_TOKEN: ${{ github.token }} - # Hosts pull the image with their own version's tag. It installs fctl - # from fctl.sh/releases, so it is built once the release is there. - run: gh workflow run image.yml --ref main -f tag="$TAG" - name: Redeploy app.fctl.sh on the release commit if: inputs.tag == '' env: GH_TOKEN: ${{ github.token }} # Pushes made with this workflow's token start no workflows; a dispatch does. run: gh workflow run ci.yml --ref main + - name: Publish the sandbox image + env: + GH_TOKEN: ${{ github.token }} + # Hosts pull the image with their own version's tag. It installs fctl + # from fctl.sh/releases, so it is built once the release is there. + run: gh workflow run image.yml --ref main -f tag="$TAG" diff --git a/docs/development.md b/docs/development.md index 3c5525b6..8f550fc8 100644 --- a/docs/development.md +++ b/docs/development.md @@ -145,12 +145,12 @@ last tag, adds the notes to `CHANGELOG.md`, pushes the release commit and tag, builds the archives (`cargo xtask dist`: fctl for macOS and Linux on arm64 and x86_64, and the Linux agents), creates the GitHub release with the notes, publishes to `https://fctl.sh/releases` (`cargo xtask publish ---latest`), starts the **Image** workflow, which publishes the release's -sandbox image to `ghcr.io/hyperstructure/fctl-agent`, and redeploys -app.fctl.sh. The Image workflow also runs every day, to rebuild the latest -release's image when Claude Code has a newer release, and on pull requests -that change `images/agent`, which it builds for both architectures and -checks with `images/agent/check.sh` without publishing. +--latest`), redeploys app.fctl.sh, and starts the **Image** workflow, which +publishes the release's sandbox image to `ghcr.io/hyperstructure/fctl-agent`. +The Image workflow also runs every day, to rebuild the latest release's +image when Claude Code has a newer release, and on pull requests that change +`images/agent`, which it builds for both architectures and checks with +`images/agent/check.sh` without publishing. ```sh cargo xtask release --dry-run # the next version and its notes diff --git a/web/src/routes/admin.tsx b/web/src/routes/admin.tsx index 747e4177..8c74796f 100644 --- a/web/src/routes/admin.tsx +++ b/web/src/routes/admin.tsx @@ -370,9 +370,9 @@ function Runners() {
2. Register it as a runner and start the service

- It shows up here as online within seconds, and pulls the sandbox image while it waits for its - first session. 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. + 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.

)} From 7771600ae297eb855b431676011209d2b32b15fa Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" Date: Sun, 18 Oct 2026 03:00:37 +0000 Subject: [PATCH 05/10] ci: drop an unused variable from the image build Refs #2 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/image.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/image.yml b/.github/workflows/image.yml index 5062cb11..43cfce87 100644 --- a/.github/workflows/image.yml +++ b/.github/workflows/image.yml @@ -144,7 +144,6 @@ jobs: contents: read packages: write env: - REF: ${{ needs.plan.outputs.ref }} VERSION: ${{ needs.plan.outputs.version }} CLAUDE: ${{ needs.plan.outputs.claude }} CREATED: ${{ needs.plan.outputs.created }} From ca87d0825015935599e0db439edb422cd721bd69 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" Date: Sun, 18 Oct 2026 03:31:32 +0000 Subject: [PATCH 06/10] docs: list the image's new tools and PATH on the sandbox images page #45 added Python 3.15, Rust, Bun, TypeScript and more Debian tools to the image, and ~/.cargo/bin and ~/.bun/bin to the PATH, which /etc/profile.d/fctl.sh now also sets for login shells. The layout section is what images built FROM the default rely on, so it lists them, and says that Rust and Bun belong to the agent user and that Python is externally managed. 0.3.0 shipped without this branch, so its hosts still build the image themselves; the examples use 0.4.0, the first release whose hosts pull it. Co-Authored-By: Claude Opus 5.5 --- docs/sandbox-images.md | 39 ++++++++++++++++++++++++--------------- 1 file changed, 24 insertions(+), 15 deletions(-) diff --git a/docs/sandbox-images.md b/docs/sandbox-images.md index 185af49a..8c4fb68c 100644 --- a/docs/sandbox-images.md +++ b/docs/sandbox-images.md @@ -7,14 +7,15 @@ hosts get it, and what images built from it can rely on. ## The default image `ghcr.io/hyperstructure/fctl-agent` is built from -[`images/agent`](../images/agent): Debian bookworm with git, the GitHub CLI, -Node.js 22, Python 3 with uv, build tools, ripgrep, Claude Code and fctl. It -is published for arm64 (Apple silicon) and amd64. +[`images/agent`](../images/agent), which 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.3.0` | fctl 0.3.0's. Hosts of that version use it. | -| `0.3` | The newest 0.3 release's. | +| `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. | Each release's image is published a few minutes after the release, by the @@ -23,7 +24,7 @@ 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 rebuild moves the tags; to pin one build, add its digest: -`ghcr.io/hyperstructure/fctl-agent:0.3.0@sha256:…`. +`ghcr.io/hyperstructure/fctl-agent:0.4.0@sha256:…`. Its labels say what is inside: @@ -35,7 +36,7 @@ Its labels say what is inside: | `org.opencontainers.image.created` | when it was built | ```sh -docker image inspect ghcr.io/hyperstructure/fctl-agent:0.3.0 \ +docker image inspect ghcr.io/hyperstructure/fctl-agent:0.4.0 \ --format '{{ index .Config.Labels "sh.fctl.claude-code.version" }}' ``` @@ -66,7 +67,7 @@ Code, run `fctl host image pull`. image build` prepares with the same 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/fctl-agent:0.2.1` + remove them: `docker image rm ghcr.io/hyperstructure/fctl-agent:0.4.0` (with Apple container, `container image delete`) removes one that no sandbox uses. @@ -79,18 +80,26 @@ 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 is (the native - build), and `/opt/fctl/bin`, where fctl copies its supervisor, fctl-agent, - at session start. fctl itself is in `/usr/local/bin`. -- **The tools**: git, gh, Node.js 22 with npm and corepack, Python 3 with - pip, venv and uv, build-essential, pkg-config, ripgrep, fd (as `fdfind`), - jq, curl, zip and tree. +- **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/fctl-agent:0.3 +FROM ghcr.io/hyperstructure/fctl-agent:0.4 USER root RUN apt-get update \ && apt-get install -y --no-install-recommends postgresql-client \ From 9950a4b3d6967031ba37da882941ce935f04baac Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" Date: Sun, 18 Oct 2026 03:31:32 +0000 Subject: [PATCH 07/10] ci: check images for the new tools with their release's check.sh check.sh now checks what docs/sandbox-images.md lists since #45: the four directories that lead the PATH, in the image and in login shells (from /etc/profile.d/fctl.sh); Python, Rust, TypeScript, Bun and the other tools; that rustup's proxies, Bun and tsc run from HOME and the PATH alone; and OpenSSL's headers. The Image workflow ran this commit's check.sh against images built from a release's tag. Once main's images/agent gains a tool and check.sh checks for it, the daily rebuild of the latest release, which lacks it, would fail until the next release. A build now runs its release's own check.sh, and this commit's only for releases from before check.sh (v0.3.0 and earlier). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/image.yml | 14 ++++++++++---- images/agent/check.sh | 24 ++++++++++++++++++------ 2 files changed, 28 insertions(+), 10 deletions(-) diff --git a/.github/workflows/image.yml b/.github/workflows/image.yml index 43cfce87..7216f428 100644 --- a/.github/workflows/image.yml +++ b/.github/workflows/image.yml @@ -12,8 +12,9 @@ # - Pull requests that change the image build it without publishing. # # Each architecture builds on its own runner and is pushed by digest, without -# a tag, then checked with images/agent/check.sh; the last job tags the two -# as one image. Moving tags move only to the newest release they cover. +# a tag, then checked with the release's images/agent/check.sh (this commit's +# for releases from before it); the last job tags the two as one image. Moving +# tags move only to the newest release they cover. name: Image on: @@ -149,7 +150,8 @@ jobs: CREATED: ${{ needs.plan.outputs.created }} PUSH: ${{ needs.plan.outputs.push }} steps: - # This workflow's commit, for check.sh, and the image's sources at the release. + # This workflow's commit, for releases without check.sh, and the image's + # sources at the release. - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -196,7 +198,11 @@ jobs: CHECK: ${{ steps.build.outputs.image }} ARCH: ${{ matrix.arch }} run: | - docker run --rm -i -e FCTL_VERSION="$VERSION" -e CLAUDE_VERSION="$CLAUDE" "$CHECK" sh -s < images/agent/check.sh + # A release's own check.sh describes the image built from its tree, so + # rebuilds of it pass however images/agent changes on main since. + script=release/images/agent/check.sh + [ -f "$script" ] || script=images/agent/check.sh + docker run --rm -i -e FCTL_VERSION="$VERSION" -e CLAUDE_VERSION="$CLAUDE" "$CHECK" sh -s < "$script" docker image inspect --format '{{.Size}}' "$CHECK" | awk -v arch="$ARCH" '{ printf "%s: %.2f GB\n", arch, $1 / 1e9 }' >> "$GITHUB_STEP_SUMMARY" - name: Note its digest diff --git a/images/agent/check.sh b/images/agent/check.sh index 17120375..dd46e098 100644 --- a/images/agent/check.sh +++ b/images/agent/check.sh @@ -18,18 +18,30 @@ fail() { [ "$(id -u)" = 1000 ] || fail "agent has uid $(id -u), not 1000" [ "$HOME" = /home/agent ] || fail "HOME is $HOME, not /home/agent" sudo -n true 2>/dev/null || fail "agent cannot use sudo without a password" -for dir in "$HOME/.local/bin" /opt/fctl/bin; do - case ":$PATH:" in - *":$dir:"*) ;; - *) fail "$dir is not on the PATH ($PATH)" ;; - esac +# The image's PATH, and login shells', which setup scripts run in and which get +# it from /etc/profile.d/fctl.sh. +login_path=$(bash -lc 'printf %s "$PATH"') +for dir in "$HOME/.local/bin" "$HOME/.cargo/bin" "$HOME/.bun/bin" /opt/fctl/bin; do + for path in "$PATH" "$login_path"; do + case ":$path:" in + *":$dir:"*) ;; + *) fail "$dir is not on the PATH ($path)" ;; + esac + done done [ -d /opt/fctl/bin ] || fail "/opt/fctl/bin is missing" [ -d "$HOME/workspace" ] && [ -w "$HOME/workspace" ] || fail "$HOME/workspace is missing or not writable" -for tool in sh tail git gh claude fctl node npm python3 uv rg jq curl make cc; do +for tool in sh tail git gh claude fctl python3 python uv rustup cargo rustc node npm corepack tsc bun \ + make cc cmake pkg-config rg fd jq shellcheck sqlite3 curl wget rsync zip tree; do command -v "$tool" >/dev/null 2>&1 || fail "$tool is not on the PATH" done [ "$(command -v claude)" = "$HOME/.local/bin/claude" ] || fail "claude is $(command -v claude), not ~/.local/bin/claude" +# rustup's proxies are there even without a toolchain; these run from HOME +# and the PATH alone, as Claude's shell has them. +for tool in cargo rustc rustfmt cargo-clippy python3 tsc bun; do + "$tool" --version >/dev/null 2>&1 || fail "$tool --version fails" +done +pkg-config --exists openssl || fail "OpenSSL's headers are missing" # `2.1.302 (Claude Code)` and `fctl 0.3.0`. claude=$(claude --version) From 0ec0aa45bca92071e1e9eb3c9aa3eca25770542c Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" Date: Sun, 18 Oct 2026 11:39:42 +0000 Subject: [PATCH 08/10] feat(host): use ghcr.io/hyperstructure/sandbox, built from its own repository The default sandbox image moves to hyperstructure/sandbox, a public repository whose Image workflow publishes it as ghcr.io/hyperstructure/sandbox, with the tags #39 gave it: one per fctl release, plus . and latest. Hosts on the default image pull : and fall back to :latest; fctl-agent:latest in host.toml or a project still means the default. images/agent leaves this repository. `fctl host image build` downloads an archive of the sandbox's main branch and builds its Dockerfile with the archive's root as the context, or gives the Lima VM its provision.sh, so a host builds what is published. `--source DIR` builds from a checkout instead, to try changes to the image with fctl. The process driver says there is nothing to build before downloading anything. The test that kept provision.sh's Rust in step with rust-toolchain.toml goes with the file; AGENTS.md here and in the sandbox say to bump both together. A sandbox without fctl now points at the default image instead of `fctl host image build`, and the web app's image placeholder names the new image. flate2 and tar become workspace dependencies, shared by the CLI and the host. Refs #2 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 2 + Cargo.toml | 2 + crates/fctl-agent/src/supervisor.rs | 2 +- crates/fctl-host/Cargo.toml | 2 + crates/fctl-host/src/config.rs | 10 +- crates/fctl-host/src/driver/container.rs | 4 +- crates/fctl-host/src/image.rs | 213 ++++++++++++++++------- crates/fctl/Cargo.toml | 4 +- crates/fctl/src/cmd/host.rs | 14 +- images/agent/Dockerfile | 25 --- images/agent/README.md | 57 ------ images/agent/check.sh | 55 ------ images/agent/provision.sh | 118 ------------- web/src/routes/project.tsx | 2 +- 14 files changed, 177 insertions(+), 333 deletions(-) delete mode 100644 images/agent/Dockerfile delete mode 100644 images/agent/README.md delete mode 100644 images/agent/check.sh delete mode 100644 images/agent/provision.sh 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/crates/fctl-agent/src/supervisor.rs b/crates/fctl-agent/src/supervisor.rs index 2719c49a..979487cd 100644 --- a/crates/fctl-agent/src/supervisor.rs +++ b/crates/fctl-agent/src/supervisor.rs @@ -641,7 +641,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 0181a932..55c63ad4 100644 --- a/crates/fctl-host/src/config.rs +++ b/crates/fctl-host/src/config.rs @@ -19,9 +19,9 @@ use fctl_proto::runner::{SandboxLimits, SandboxSize}; use serde::{Deserialize, Serialize}; use std::path::{Path, PathBuf}; -/// Where the default sandbox image, `images/agent`, is published -/// (.github/workflows/image.yml): a tag for every release. -pub const IMAGE_REPOSITORY: &str = "ghcr.io/hyperstructure/fctl-agent"; +/// 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. @@ -270,7 +270,7 @@ mod tests { #[test] fn hosts_on_the_default_image_follow_their_version() -> Result<()> { let published = format!( - "ghcr.io/hyperstructure/fctl-agent:{}", + "ghcr.io/hyperstructure/sandbox:{}", crate::agentbin::VERSION ); // Unset, empty, or the default's name from before it was published. @@ -280,7 +280,7 @@ mod tests { assert_eq!(cfg.image(), published); assert_eq!( cfg.fallback_image().as_deref(), - Some("ghcr.io/hyperstructure/fctl-agent:latest") + Some("ghcr.io/hyperstructure/sandbox:latest") ); } let cfg = HostConfig::from_toml("image = \"ghcr.io/acme/agent:1\"")?; diff --git a/crates/fctl-host/src/driver/container.rs b/crates/fctl-host/src/driver/container.rs index 4fc71f88..99bc6dcc 100644 --- a/crates/fctl-host/src/driver/container.rs +++ b/crates/fctl-host/src/driver/container.rs @@ -549,8 +549,8 @@ esac use std::sync::{Mutex, PoisonError}; - const VERSION_IMAGE: &str = "ghcr.io/hyperstructure/fctl-agent:0.3.0"; - const LATEST_IMAGE: &str = "ghcr.io/hyperstructure/fctl-agent:latest"; + 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 { 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/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 5d9af9a3..7f12c08d 100644 --- a/crates/fctl/src/cmd/host.rs +++ b/crates/fctl/src/cmd/host.rs @@ -81,6 +81,10 @@ pub enum ImageCmd { /// 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, }, } @@ -150,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 { @@ -287,12 +291,16 @@ pub async fn run(server: Option<&str>, cmd: HostCmd, json: bool) -> Result<()> { println!("{} Pulled {image}", style::accent("✓")); Ok(()) } - HostCmd::Image(ImageCmd::Build { driver, tag }) => { + 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?; let tag = tag.unwrap_or_else(|| cfg.image()); - fctl_host::image::build(&d, &tag, &cfg.download_base).await + fctl_host::image::build(&d, &tag, &cfg.download_base, source.as_deref()).await } HostCmd::Restart => { service::restart()?; diff --git a/images/agent/Dockerfile b/images/agent/Dockerfile deleted file mode 100644 index 47b41e5b..00000000 --- a/images/agent/Dockerfile +++ /dev/null @@ -1,25 +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. -# .github/workflows/image.yml publishes it as ghcr.io/hyperstructure/fctl-agent. -# -# fctl host image build # builds it with your driver (apple or docker) -# docker build -t fctl-agent:dev 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. CLAUDE_VERSION pins Claude Code (empty: the -# latest release). -ARG FCTL_VERSION= -ARG FCTL_DOWNLOAD= -ARG CLAUDE_VERSION= -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 3d3d2c86..00000000 --- a/images/agent/README.md +++ /dev/null @@ -1,57 +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`). [Sandbox images](../../docs/sandbox-images.md) describes -it for the people who run it or build images from it. - -- 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. -- The Image workflow (`.github/workflows/image.yml`) publishes it as - `ghcr.io/hyperstructure/fctl-agent` for arm64 and amd64: a release's - image is built from its tag, with that release of fctl and the newest - Claude Code (`CLAUDE_VERSION`), and the latest release's is rebuilt when - Claude Code has a newer release. Hosts pull the tag of their own version. -- Images built `FROM` it rely on its layout: the `agent` user (uid 1000, - passwordless sudo), the PATH above and the tools. `check.sh` checks every - build for it; keep it, or change it together with the docs. -- `fctl host image build` builds it on a host instead, under the host's - image name, 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. diff --git a/images/agent/check.sh b/images/agent/check.sh deleted file mode 100644 index dd46e098..00000000 --- a/images/agent/check.sh +++ /dev/null @@ -1,55 +0,0 @@ -#!/bin/sh -# Checks an image built from this directory for what fctl and images built -# FROM it rely on (docs/sandbox-images.md): the agent user, sudo, the PATH and -# the tools. Runs inside the image as its user; the image workflow runs it on -# every build: -# -# docker run --rm -i -e FCTL_VERSION=0.3.0 -e CLAUDE_VERSION=2.1.302 IMAGE sh -s < images/agent/check.sh -# -# FCTL_VERSION and CLAUDE_VERSION, when set, are the versions it must have. -set -eu - -fail() { - echo "check.sh: $*" >&2 - exit 1 -} - -[ "$(id -un)" = agent ] || fail "runs as $(id -un), not agent" -[ "$(id -u)" = 1000 ] || fail "agent has uid $(id -u), not 1000" -[ "$HOME" = /home/agent ] || fail "HOME is $HOME, not /home/agent" -sudo -n true 2>/dev/null || fail "agent cannot use sudo without a password" -# The image's PATH, and login shells', which setup scripts run in and which get -# it from /etc/profile.d/fctl.sh. -login_path=$(bash -lc 'printf %s "$PATH"') -for dir in "$HOME/.local/bin" "$HOME/.cargo/bin" "$HOME/.bun/bin" /opt/fctl/bin; do - for path in "$PATH" "$login_path"; do - case ":$path:" in - *":$dir:"*) ;; - *) fail "$dir is not on the PATH ($path)" ;; - esac - done -done -[ -d /opt/fctl/bin ] || fail "/opt/fctl/bin is missing" -[ -d "$HOME/workspace" ] && [ -w "$HOME/workspace" ] || fail "$HOME/workspace is missing or not writable" -for tool in sh tail git gh claude fctl python3 python uv rustup cargo rustc node npm corepack tsc bun \ - make cc cmake pkg-config rg fd jq shellcheck sqlite3 curl wget rsync zip tree; do - command -v "$tool" >/dev/null 2>&1 || fail "$tool is not on the PATH" -done -[ "$(command -v claude)" = "$HOME/.local/bin/claude" ] || fail "claude is $(command -v claude), not ~/.local/bin/claude" -# rustup's proxies are there even without a toolchain; these run from HOME -# and the PATH alone, as Claude's shell has them. -for tool in cargo rustc rustfmt cargo-clippy python3 tsc bun; do - "$tool" --version >/dev/null 2>&1 || fail "$tool --version fails" -done -pkg-config --exists openssl || fail "OpenSSL's headers are missing" - -# `2.1.302 (Claude Code)` and `fctl 0.3.0`. -claude=$(claude --version) -claude=${claude%% *} -fctl=$(fctl --version) -fctl=${fctl#fctl } -[ -z "${CLAUDE_VERSION:-}" ] || [ "$claude" = "$CLAUDE_VERSION" ] || - fail "Claude Code is $claude, not $CLAUDE_VERSION" -[ -z "${FCTL_VERSION:-}" ] || [ "$fctl" = "$FCTL_VERSION" ] || - fail "fctl is $fctl, not $FCTL_VERSION" -echo "The image is as expected, with fctl $fctl and Claude Code $claude." diff --git a/images/agent/provision.sh b/images/agent/provision.sh deleted file mode 100644 index 5dda000a..00000000 --- a/images/agent/provision.sh +++ /dev/null @@ -1,118 +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. CLAUDE_VERSION -# picks Claude Code's (empty: the latest); the image workflow passes the one -# it labels the image with, so that every architecture gets the same. -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:-}" -CLAUDE_VERSION="${CLAUDE_VERSION:-}" -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 env CLAUDE_VERSION="$CLAUDE_VERSION" \ - bash -c 'curl -fsSL https://claude.ai/install.sh | bash -s -- ${CLAUDE_VERSION:+"$CLAUDE_VERSION"}' -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/project.tsx b/web/src/routes/project.tsx index e4a707e0..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="ghcr.io/hyperstructure/fctl-agent" + placeholder="ghcr.io/hyperstructure/sandbox" /> )} From 1b1e4f44708a74a3b4a70790e8316455410f209f Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" Date: Sun, 18 Oct 2026 11:39:42 +0000 Subject: [PATCH 09/10] ci: leave publishing the sandbox image to hyperstructure/sandbox The Image workflow moves to hyperstructure/sandbox with the image, and the Release workflow no longer starts it: its token can't start workflows in another repository. The sandbox's workflow looks for new releases on fctl.sh every hour instead. Refs #2 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/image.yml | 267 ---------------------------------- .github/workflows/release.yml | 12 +- 2 files changed, 3 insertions(+), 276 deletions(-) delete mode 100644 .github/workflows/image.yml diff --git a/.github/workflows/image.yml b/.github/workflows/image.yml deleted file mode 100644 index 7216f428..00000000 --- a/.github/workflows/image.yml +++ /dev/null @@ -1,267 +0,0 @@ -# Publishes the default sandbox image, images/agent, for arm64 and amd64 as -# ghcr.io/hyperstructure/fctl-agent:, :. and :latest -# (docs/sandbox-images.md). Each release gets its own: built from the -# release's tag, with that release of fctl and the newest Claude Code. -# -# - The Release workflow starts it for every release. -# - Every day it rebuilds the latest release's image when Claude Code has a -# newer release than the one inside, or when the image is a week old (for -# Debian's updates): fctl turns off Claude Code's auto-updater, so an -# image's Claude Code is as old as the image. -# - `gh workflow run image.yml -f tag=v0.2.1 -f force=true` rebuilds one. -# - Pull requests that change the image build it without publishing. -# -# Each architecture builds on its own runner and is pushed by digest, without -# a tag, then checked with the release's images/agent/check.sh (this commit's -# for releases from before it); the last job tags the two as one image. Moving -# tags move only to the newest release they cover. -name: Image - -on: - pull_request: - paths: - - images/agent/** - - .github/workflows/image.yml - schedule: - - cron: "41 5 * * *" - workflow_dispatch: - inputs: - tag: - description: The release to build, like v0.2.1 (default the latest) - required: false - force: - description: Build even when the published image is current - type: boolean - default: false - -permissions: - contents: read - -concurrency: - group: image-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: true - -env: - IMAGE: ghcr.io/hyperstructure/fctl-agent - -jobs: - plan: - name: What to build - runs-on: ubuntu-24.04 - timeout-minutes: 10 - permissions: - contents: read - packages: read - outputs: - ref: ${{ steps.plan.outputs.ref }} - version: ${{ steps.plan.outputs.version }} - claude: ${{ steps.plan.outputs.claude }} - tags: ${{ steps.plan.outputs.tags }} - created: ${{ steps.plan.outputs.created }} - build: ${{ steps.plan.outputs.build }} - push: ${{ steps.plan.outputs.push }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - fetch-depth: 0 - fetch-tags: true - - name: Versions and tags - id: plan - env: - EVENT: ${{ github.event_name }} - TAG: ${{ inputs.tag }} - FORCE: ${{ inputs.force && 'yes' || '' }} - GH_TOKEN: ${{ github.token }} - run: | - semver='^[0-9]+\.[0-9]+\.[0-9]+$' - latest=$(curl -fsS --retry 3 https://fctl.sh/releases/latest | tr -d '[:space:]') - [[ $latest =~ $semver ]] || { echo "::error::fctl.sh/releases/latest says '$latest'"; exit 1; } - # What https://claude.ai/install.sh installs; every architecture gets this one. - claude=$(curl -fsS --retry 3 https://downloads.claude.ai/claude-code-releases/latest | tr -d '[:space:]') - [[ $claude =~ $semver ]] || { echo "::error::downloads.claude.ai says the latest Claude Code is '$claude'"; exit 1; } - - if [ "$EVENT" = pull_request ]; then - # This change's images/agent with the latest fctl; nothing is pushed. - ref=$GITHUB_SHA version=$latest push=no - else - tag=${TAG:-$latest} tag=v${tag#v} - [[ ${tag#v} =~ $semver ]] || { echo "::error::$tag is not a release tag like v0.2.1"; exit 1; } - git rev-parse -q --verify "refs/tags/$tag" >/dev/null || { echo "::error::there is no tag $tag"; exit 1; } - ref=$tag version=${tag#v} push=yes - fi - - minor=${version%.*} - newest_minor=$({ git tag -l "v$minor.*" | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' || true; } | sort -V | tail -n 1) - tags="$IMAGE:$version" - if [ "$newest_minor" = "v$version" ]; then tags="$tags $IMAGE:$minor"; fi - if [ "$version" = "$latest" ]; then tags="$tags $IMAGE:latest"; fi - - build=yes why="fctl $version with Claude Code $claude" - if [ "$push" = yes ] && [ -z "$FORCE" ]; then - echo "$GH_TOKEN" | docker login ghcr.io -u "$GITHUB_ACTOR" --password-stdin >/dev/null - if index=$(docker buildx imagetools inspect --raw "$IMAGE:$version" 2>/dev/null); then - have=$(jq -r '.annotations["sh.fctl.claude-code.version"] // ""' <<<"$index") - built=$(jq -r '.annotations["org.opencontainers.image.created"] // "1970-01-01"' <<<"$index") - age=$(( ($(date +%s) - $(date -d "$built" +%s 2>/dev/null || echo 0)) / 86400 )) - if [ "$have" = "$claude" ] && [ "$age" -lt 7 ]; then - build=no why="$IMAGE:$version already has Claude Code $claude and is $age days old" - fi - fi - fi - - { - echo "ref=$ref" - echo "version=$version" - echo "claude=$claude" - echo "tags=$tags" - echo "created=$(date -u +%Y-%m-%dT%H:%M:%SZ)" - echo "build=$build" - echo "push=$push" - } >> "$GITHUB_OUTPUT" - { - if [ "$build" = no ]; then - echo "Nothing to build: $why." - elif [ "$push" = yes ]; then - echo "Building $why from \`$ref\` for $tags." - else - echo "Building $why from this pull request, without publishing it." - fi - } >> "$GITHUB_STEP_SUMMARY" - - build: - name: Build (${{ matrix.arch }}) - needs: plan - if: needs.plan.outputs.build == 'yes' - strategy: - matrix: - include: - - arch: amd64 - runner: ubuntu-24.04 - - arch: arm64 - runner: ubuntu-24.04-arm - runs-on: ${{ matrix.runner }} - timeout-minutes: 45 - permissions: - contents: read - packages: write - env: - VERSION: ${{ needs.plan.outputs.version }} - CLAUDE: ${{ needs.plan.outputs.claude }} - CREATED: ${{ needs.plan.outputs.created }} - PUSH: ${{ needs.plan.outputs.push }} - steps: - # This workflow's commit, for releases without check.sh, and the image's - # sources at the release. - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: ${{ needs.plan.outputs.ref }} - path: release - - name: Build - id: build - env: - GH_TOKEN: ${{ github.token }} - ARCH: ${{ matrix.arch }} - run: | - docker buildx create --name fctl --driver docker-container --use >/dev/null - if [ "$PUSH" = yes ]; then - echo "$GH_TOKEN" | docker login ghcr.io -u "$GITHUB_ACTOR" --password-stdin >/dev/null - output="type=image,name=$IMAGE,push-by-digest=true,name-canonical=true,push=true,oci-mediatypes=true" - else - output="type=docker,name=fctl-agent:check" - fi - docker buildx build release/images/agent \ - --platform "linux/$ARCH" --pull --provenance=false \ - --build-arg "FCTL_VERSION=$VERSION" \ - --build-arg "CLAUDE_VERSION=$CLAUDE" \ - --label "org.opencontainers.image.title=fctl-agent" \ - --label "org.opencontainers.image.description=The default sandbox for fctl sessions" \ - --label "org.opencontainers.image.url=https://fctl.sh/docs/sandbox-images/" \ - --label "org.opencontainers.image.source=https://github.com/hyperstructure/fctl" \ - --label "org.opencontainers.image.licenses=MIT" \ - --label "org.opencontainers.image.version=$VERSION" \ - --label "org.opencontainers.image.revision=$(git -C release rev-parse HEAD)" \ - --label "org.opencontainers.image.created=$CREATED" \ - --label "sh.fctl.version=$VERSION" \ - --label "sh.fctl.claude-code.version=$CLAUDE" \ - --output "$output" \ - --metadata-file "$RUNNER_TEMP/build.json" - if [ "$PUSH" = yes ]; then - digest=$(jq -r '."containerimage.digest"' "$RUNNER_TEMP/build.json") - echo "digest=$digest" >> "$GITHUB_OUTPUT" - echo "image=$IMAGE@$digest" >> "$GITHUB_OUTPUT" - else - echo "image=fctl-agent:check" >> "$GITHUB_OUTPUT" - fi - - name: Check it - env: - CHECK: ${{ steps.build.outputs.image }} - ARCH: ${{ matrix.arch }} - run: | - # A release's own check.sh describes the image built from its tree, so - # rebuilds of it pass however images/agent changes on main since. - script=release/images/agent/check.sh - [ -f "$script" ] || script=images/agent/check.sh - docker run --rm -i -e FCTL_VERSION="$VERSION" -e CLAUDE_VERSION="$CLAUDE" "$CHECK" sh -s < "$script" - docker image inspect --format '{{.Size}}' "$CHECK" | - awk -v arch="$ARCH" '{ printf "%s: %.2f GB\n", arch, $1 / 1e9 }' >> "$GITHUB_STEP_SUMMARY" - - name: Note its digest - if: needs.plan.outputs.push == 'yes' - env: - DIGEST: ${{ steps.build.outputs.digest }} - run: | - mkdir -p "$RUNNER_TEMP/digests" - touch "$RUNNER_TEMP/digests/${DIGEST#sha256:}" - - if: needs.plan.outputs.push == 'yes' - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: digest-${{ matrix.arch }} - path: ${{ runner.temp }}/digests/* - if-no-files-found: error - retention-days: 1 - - publish: - name: Publish - needs: [plan, build] - if: needs.plan.outputs.push == 'yes' - runs-on: ubuntu-24.04 - timeout-minutes: 10 - permissions: - contents: read - packages: write - env: - VERSION: ${{ needs.plan.outputs.version }} - CLAUDE: ${{ needs.plan.outputs.claude }} - CREATED: ${{ needs.plan.outputs.created }} - TAGS: ${{ needs.plan.outputs.tags }} - steps: - - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 - with: - pattern: digest-* - path: ${{ runner.temp }}/digests - merge-multiple: true - - name: Tag both architectures as one image - env: - GH_TOKEN: ${{ github.token }} - run: | - echo "$GH_TOKEN" | docker login ghcr.io -u "$GITHUB_ACTOR" --password-stdin >/dev/null - sources=() - for file in "$RUNNER_TEMP"/digests/*; do sources+=("$IMAGE@sha256:$(basename "$file")"); done - [ "${#sources[@]}" = 2 ] || { echo "::error::expected a digest for each architecture, got ${sources[*]}"; exit 1; } - tags=() - for tag in $TAGS; do tags+=(--tag "$tag"); done - # On the index too: GHCR shows these, and the daily run reads the - # Claude Code version and the date from them. - docker buildx imagetools create "${tags[@]}" \ - --annotation "index:org.opencontainers.image.description=The default sandbox for fctl sessions" \ - --annotation "index:org.opencontainers.image.source=https://github.com/hyperstructure/fctl" \ - --annotation "index:org.opencontainers.image.licenses=MIT" \ - --annotation "index:org.opencontainers.image.version=$VERSION" \ - --annotation "index:org.opencontainers.image.created=$CREATED" \ - --annotation "index:sh.fctl.claude-code.version=$CLAUDE" \ - "${sources[@]}" - docker buildx imagetools inspect "$IMAGE:$VERSION" - { - echo "Published fctl $VERSION with Claude Code $CLAUDE as:" - for tag in $TAGS; do echo "- \`$tag\`"; done - } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d0362237..08f5d808 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -6,9 +6,9 @@ # version, and pushes the release commit and tag to main. The "Build" jobs # 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, starts CI on -# main, which redeploys app.fctl.sh, and starts the Image workflow, which -# publishes the release's sandbox image to ghcr.io/hyperstructure/fctl-agent. +# release with the notes, publishes to https://fctl.sh/releases and starts CI +# 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 @@ -214,9 +214,3 @@ jobs: GH_TOKEN: ${{ github.token }} # Pushes made with this workflow's token start no workflows; a dispatch does. run: gh workflow run ci.yml --ref main - - name: Publish the sandbox image - env: - GH_TOKEN: ${{ github.token }} - # Hosts pull the image with their own version's tag. It installs fctl - # from fctl.sh/releases, so it is built once the release is there. - run: gh workflow run image.yml --ref main -f tag="$TAG" From bb395a78c57b3101266e21eea724e92edf79aa30 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" Date: Sun, 18 Oct 2026 11:39:42 +0000 Subject: [PATCH 10/10] docs: describe the sandbox image's new home and record why it moved The Sandbox images page, the architecture, the CLI, development, self-hosting and security pages, AGENTS.md and the release and issues skills say that the default image is ghcr.io/hyperstructure/sandbox, built and published by the public hyperstructure/sandbox repository within the hour after each release, and that `fctl host image build` builds its main branch (or a checkout, with --source). ADR 0012 records the decision: the image needs to be public and has a cadence of its own, so it lives in its own repository, connected to fctl through fctl.sh. It amends 0005. (0011 is taken by #55.) Refs #2 Co-Authored-By: Claude Opus 5.5 --- .claude/skills/issues/SKILL.md | 5 +- .claude/skills/release/SKILL.md | 38 +++++++----- AGENTS.md | 18 ++++-- ...mage-lives-in-its-own-public-repository.md | 59 +++++++++++++++++++ docs/adr/README.md | 1 + docs/architecture.md | 20 ++++--- docs/cli.md | 3 +- docs/development.md | 12 ++-- docs/sandbox-images.md | 56 ++++++++++-------- docs/security.md | 11 ++-- docs/self-hosting.md | 4 +- 11 files changed, 155 insertions(+), 72 deletions(-) create mode 100644 docs/adr/0012-the-sandbox-image-lives-in-its-own-public-repository.md 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 37aa50e5..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 and the sandbox image to GHCR, 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 @@ -56,14 +56,16 @@ It runs in three steps: 3. **Publish**: makes the archives from those binaries (`cargo xtask dist package`), creates the GitHub release with the notes, publishes the files to https://fctl.sh/releases (moving `latest`), installs it with - the installer as a check, starts CI on `main`, which redeploys - app.fctl.sh, and starts the **Image** workflow. + the installer as a check, and starts CI on `main`, which redeploys + app.fctl.sh. -The Image workflow (`.github/workflows/image.yml`) builds the release's -sandbox image from its tag, for arm64 and amd64, and publishes it as -`ghcr.io/hyperstructure/fctl-agent:X.Y.Z`, moving `X.Y` and `latest`. -Hosts of the new version pull it; until it is there, their sessions start -from `latest`. +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. @@ -74,10 +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. -- The Image workflow's run for the tag passed (`gh run list --workflow - image.yml`), and `docker buildx imagetools inspect - ghcr.io/hyperstructure/fctl-agent:X.Y.Z` lists linux/amd64 and - linux/arm64. +- 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). @@ -92,10 +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** (the Image workflow failed): fix the cause in a pull - request if it is the workflow, then start it again for the tag: - `gh workflow run image.yml --ref main -f tag=vX.Y.Z`. It builds from the - tag, so a broken `images/agent` needs a patch release. +- **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. @@ -104,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/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/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 61d9e9cf..42c1ad8d 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), published to `ghcr.io/hyperstructure/fctl-agent`. | 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 @@ -328,13 +330,15 @@ 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/fctl-agent:`. The Image workflow -(`.github/workflows/image.yml`) publishes it for arm64 and amd64 with every -release and rebuilds the latest release's when Claude Code has a newer +`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)). +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 | |---|---|---| diff --git a/docs/cli.md b/docs/cli.md index 860fbf30..ff6ee184 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -141,6 +141,7 @@ fctl host doctor # check the driver, image, agent binary, connec fctl host logs -n 200 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 ``` @@ -167,7 +168,7 @@ 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/fctl-agent:`, which the host pulls when it +`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 diff --git a/docs/development.md b/docs/development.md index 0b3b45da..182509e9 100644 --- a/docs/development.md +++ b/docs/development.md @@ -94,7 +94,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 | @@ -164,12 +163,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`), redeploys app.fctl.sh, and starts the **Image** -workflow, which publishes the release's sandbox image to -`ghcr.io/hyperstructure/fctl-agent`. The Image workflow also runs every day, -to rebuild the latest release's image when Claude Code has a newer release, -and on pull requests that change `images/agent`, which it builds for both -architectures and checks with `images/agent/check.sh` without publishing. +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/sandbox-images.md b/docs/sandbox-images.md index 8c4fb68c..c6d7d4ca 100644 --- a/docs/sandbox-images.md +++ b/docs/sandbox-images.md @@ -6,11 +6,12 @@ hosts get it, and what images built from it can rely on. ## The default image -`ghcr.io/hyperstructure/fctl-agent` is built from -[`images/agent`](../images/agent), which 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. +`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 | |---|---| @@ -18,13 +19,15 @@ silicon) and amd64. | `0.4` | The newest 0.4 release's. | | `latest` | The newest release's. | -Each release's image is published a few minutes after the release, by the -Image workflow (`.github/workflows/image.yml`). 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 rebuild +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/fctl-agent:0.4.0@sha256:…`. +`ghcr.io/hyperstructure/sandbox:0.4.0@sha256:…`. Its labels say what is inside: @@ -32,11 +35,11 @@ Its labels say what is inside: |---|---| | `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 it was built from | +| `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/fctl-agent:0.4.0 \ +docker image inspect ghcr.io/hyperstructure/sandbox:0.4.0 \ --format '{{ index .Config.Labels "sh.fctl.claude-code.version" }}' ``` @@ -46,8 +49,8 @@ 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 minutes before a -release's image is published, the session starts from `latest` instead and +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 @@ -56,26 +59,27 @@ 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 default image's name before it was published, - means the default. + `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, under the same name, so sessions use the build: for - a host that can't reach ghcr.io, or to try changes to `images/agent` with - an fctl built from them. The host never replaces a build with the - published image; `fctl host image pull` does. + 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 same provisioning script. The process + 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/fctl-agent:0.4.0` + 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. `images/agent/check.sh` checks every -build for it: +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 @@ -99,7 +103,7 @@ An image that installs something as root switches back to `agent` at the end: ```dockerfile -FROM ghcr.io/hyperstructure/fctl-agent:0.4 +FROM ghcr.io/hyperstructure/sandbox:0.4 USER root RUN apt-get update \ && apt-get install -y --no-install-recommends postgresql-client \ diff --git a/docs/security.md b/docs/security.md index 3fd79970..7b033103 100644 --- a/docs/security.md +++ b/docs/security.md @@ -124,11 +124,12 @@ 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/fctl-agent`, which this repository's -Image workflow builds from `images/agent`. 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)). +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 diff --git a/docs/self-hosting.md b/docs/self-hosting.md index 24e4b54e..9ce2401b 100644 --- a/docs/self-hosting.md +++ b/docs/self-hosting.md @@ -179,8 +179,8 @@ 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). They pull the -sandbox image from `ghcr.io/hyperstructure/fctl-agent`; set `image` to use -a copy in your own registry ([Sandbox images](sandbox-images.md)). +sandbox image from `ghcr.io/hyperstructure/sandbox`; set `image` to use a +copy in your own registry ([Sandbox images](sandbox-images.md)). ## Operating it