From 45e59e413e803ea63a5a8a8be292355aae090df3 Mon Sep 17 00:00:00 2001 From: Ralph Bean Date: Thu, 12 Nov 2026 16:46:50 -0500 Subject: [PATCH 1/9] feat(harness): mount OCI images in sandboxes Signed-off-by: Ralph Bean --- .github/workflows/sandbox-images.yml | 137 +++++++++++++++++- docs/architecture.md | 4 + docs/cli/run.md | 11 +- docs/contributing/harness-fields.md | 10 +- docs/contributing/runtime-implementation.md | 43 +++++- docs/guides/dev/cli-internals.md | 8 +- docs/guides/user/bring-your-own-agent.md | 30 +++- docs/problems/agent-infrastructure.md | 5 +- docs/reference/harness-reference.md | 5 + images/README.md | 25 +++- images/sandbox/Containerfile | 39 ++++- .../agentnew/templates/policies/base.yaml | 2 +- internal/cli/run.go | 68 +++++++-- internal/cli/run_env_path_test.go | 2 +- internal/cli/run_image_pull.go | 18 +-- internal/cli/run_image_pull_test.go | 2 +- internal/harness/compose.go | 9 +- internal/harness/forge.go | 11 ++ internal/harness/harness.go | 21 +++ internal/harness/image_mount.go | 68 +++++++++ internal/runtime/codex_bootstrap.go | 2 +- internal/runtime/env_data.go | 15 +- internal/runtime/opencode_bootstrap.go | 2 +- internal/runtime/opencode_run.go | 2 +- internal/runtime/pi_bootstrap.go | 4 +- internal/runtime/pi_bootstrap_test.go | 9 +- .../runtime/pi_extension/fullsend-agent.js | 2 +- .../pi_extension/fullsend-agent.test.mjs | 12 +- internal/runtime/pi_extensions_test.go | 4 +- internal/runtime/pi_run_test.go | 6 +- .../codex/golden/launch-delegating.txt | 2 +- .../testdata/codex/golden/launch-gateway.txt | 2 +- .../testdata/codex/golden/launch-hooks.txt | 2 +- .../testdata/codex/golden/launch-nohooks.txt | 2 +- internal/sandbox/sandbox.go | 63 +++++++- .../scripts/fullsend-check-output | 20 ++- 36 files changed, 570 insertions(+), 97 deletions(-) create mode 100644 internal/harness/image_mount.go diff --git a/.github/workflows/sandbox-images.yml b/.github/workflows/sandbox-images.yml index e248ce0e89..e925702945 100644 --- a/.github/workflows/sandbox-images.yml +++ b/.github/workflows/sandbox-images.yml @@ -27,7 +27,7 @@ on: # version. Branch pushes and PRs still respect the paths filter. # Each platform builds on a native runner and pushes by digest only; -# the merge jobs then publish the multi-arch index under the tags below. +# the merge job then publishes the multi-arch indexes under the tags below. # No step pulls from Docker Hub, whose anonymous rate limit failed # release builds (#8289): there is no QEMU (tonistiigi/binfmt), and the # docker-container buildx driver runs BuildKit from mirror.gcr.io @@ -36,6 +36,7 @@ on: env: BUILDKIT_IMAGE: mirror.gcr.io/moby/buildkit:v0.34.0@sha256:b059f8d7226d0b326bc871af489a5dddf65e36af4d20d14251b072974d9ee87c BASE_IMAGE_NAME: ghcr.io/${{ github.repository_owner }}/fullsend-sandbox + TOOLS_IMAGE_NAME: ghcr.io/${{ github.repository_owner }}/fullsend-sandbox-tools CODE_IMAGE_NAME: ghcr.io/${{ github.repository_owner }}/fullsend-code # Shared by every metadata step, so the per-platform labels and the # merged index tags come from one definition. @@ -110,7 +111,80 @@ jobs: if: github.event_name != 'pull_request' uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: digests-sandbox-${{ matrix.arch }} + name: digests-sandbox-base-${{ matrix.arch }} + path: ${{ runner.temp }}/digests/* + if-no-files-found: error + retention-days: 7 + + # Publish the same pinned tools in an OCI root that can be mounted at + # /opt/fullsend. The tools target removes the regular image's /opt/fullsend/usr + # compatibility symlink so the mounted image's own /usr tree is visible. + build-tools: + needs: build-base + runs-on: ${{ matrix.runner }} + strategy: + matrix: + include: + - platform: linux/amd64 + arch: amd64 + runner: ubuntu-24.04 + - platform: linux/arm64 + arch: arm64 + runner: ubuntu-24.04-arm + timeout-minutes: 30 + permissions: + contents: read + packages: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Log in to GitHub Container Registry + uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + with: + driver-opts: image=${{ env.BUILDKIT_IMAGE }} + + - name: Extract metadata + id: meta + uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0 + with: + images: ${{ env.TOOLS_IMAGE_NAME }} + tags: ${{ env.IMAGE_TAGS }} + + - name: Build and push by digest + id: push + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: images/sandbox + file: images/sandbox/Containerfile + target: fullsend-sandbox-tools + platforms: ${{ matrix.platform }} + labels: ${{ steps.meta.outputs.labels }} + outputs: type=image,name=${{ env.TOOLS_IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=${{ github.event_name != 'pull_request' }} + cache-from: | + type=gha,scope=sandbox-${{ matrix.arch }} + type=gha,scope=sandbox-tools-${{ matrix.arch }} + cache-to: type=gha,mode=max,scope=sandbox-tools-${{ matrix.arch }} + + - name: Export digest + if: github.event_name != 'pull_request' + env: + DIGEST: ${{ steps.push.outputs.digest }} + run: | + mkdir -p "${RUNNER_TEMP}/digests" + touch "${RUNNER_TEMP}/digests/${DIGEST#sha256:}" + + - name: Upload digest + if: github.event_name != 'pull_request' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: digests-sandbox-tools-${{ matrix.arch }} path: ${{ runner.temp }}/digests/* if-no-files-found: error retention-days: 7 @@ -121,7 +195,7 @@ jobs: # On PR: the :dev tag (multi-arch, published by non-PR builds) so that # both platform legs of build-code can resolve a base image. merge-base: - needs: build-base + needs: [build-base, build-tools] runs-on: ubuntu-24.04 timeout-minutes: 10 permissions: @@ -135,7 +209,15 @@ jobs: uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: path: ${{ runner.temp }}/digests - pattern: digests-sandbox-* + pattern: digests-sandbox-base-* + merge-multiple: true + + - name: Download tool image digests + if: github.event_name != 'pull_request' + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + path: ${{ runner.temp }}/tool-digests + pattern: digests-sandbox-tools-* merge-multiple: true - name: Log in to GitHub Container Registry @@ -154,6 +236,14 @@ jobs: images: ${{ env.BASE_IMAGE_NAME }} tags: ${{ env.IMAGE_TAGS }} + - name: Extract tool image metadata + if: github.event_name != 'pull_request' + id: tools-meta + uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0 + with: + images: ${{ env.TOOLS_IMAGE_NAME }} + tags: ${{ env.IMAGE_TAGS }} + - name: Create and push manifest list if: github.event_name != 'pull_request' id: index @@ -202,6 +292,45 @@ jobs: fi echo "digest=${digest}" >> "${GITHUB_OUTPUT}" + - name: Create and push tool image manifest list + if: github.event_name != 'pull_request' + working-directory: ${{ runner.temp }}/tool-digests + env: + IMAGE_NAME: ${{ env.TOOLS_IMAGE_NAME }} + META_JSON: ${{ steps.tools-meta.outputs.json }} + run: | + count=$(find . -maxdepth 1 -type f | wc -l) + if [ "${count}" -ne 2 ]; then + echo "::error::expected 2 tool image platform digests, found ${count}" + exit 1 + fi + for hex in *; do + if ! grep -Eqx '[0-9a-f]{64}' <<<"${hex}"; then + echo "::error::not a sha256 digest: ${hex}" + exit 1 + fi + done + mapfile -t tag_args < <(jq -r '.tags[] | "--tag=" + .' <<<"${META_JSON}") + sources=() + for hex in *; do + sources+=("${IMAGE_NAME}@sha256:${hex}") + done + docker buildx imagetools create "${tag_args[@]}" "${sources[@]}" + sha_tag="${IMAGE_NAME}:${GITHUB_SHA::7}" + jq -e --arg t "${sha_tag}" 'any(.tags[]; . == $t)' <<<"${META_JSON}" >/dev/null \ + || { echo "::error::${sha_tag} is not among the published tags"; exit 1; } + digest=$(docker buildx imagetools inspect "${sha_tag}" --format '{{json .Manifest}}' | jq -r '.digest') + [[ "${digest}" =~ ^sha256:[0-9a-f]{64}$ ]] || { echo "::error::no tool image index digest for ${sha_tag}"; exit 1; } + platform_digests='if .manifests then [.manifests[] | select(.platform.os != "unknown") | .digest] else [$self] end | .[]' + want=$(for src in "${sources[@]}"; do + docker buildx imagetools inspect --raw "${src}" | jq -r --arg self "${src#*@}" "${platform_digests}" + done | sort) + got=$(docker buildx imagetools inspect --raw "${IMAGE_NAME}@${digest}" | jq -r --arg self "${digest}" "${platform_digests}" | sort) + if [ "${want}" != "${got}" ]; then + echo "::error::${sha_tag} was moved by another run; expected ${want//$'\n'/ }, got ${got//$'\n'/ }" + exit 1 + fi + - name: Compute base image ref id: ref env: diff --git a/docs/architecture.md b/docs/architecture.md index af834fdd77..2c7e3f0d5b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -100,6 +100,10 @@ each target repository's **`.fullsend/`** directory **Decided:** - Provider-backed policy composition: network access is granted through provider profiles declared in harness files. Policy files define only non-composable sandbox restrictions (filesystem, landlock, process). A single `base.yaml` replaces per-agent policy files in the scaffold. Inline `network_policies` continue to work but providers are the recommended approach ([ADR 0065](ADRs/0065-provider-backed-policy-composition.md)). +- Project tool images: harnesses may mount user-selected OCI images read-only + in the sandbox, separately from the sandbox image, so repositories can + provide coding tools without composing them with Fullsend's dependencies + ([ADR 0173](ADRs/0173-compose-multiple-images-into-agent-sandboxes.md)). ## Agent Harness diff --git a/docs/cli/run.md b/docs/cli/run.md index 884a1fc07e..af97745e60 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -484,11 +484,12 @@ derived from a local PAT — a caller may set it explicitly. `GH_TOKEN`, `PUSH_TOKEN` still receive the minted App identity. The runner itself also reads `GH_WORKFLOW_TOKEN` for one purpose besides provider credential -expansion: before it creates the sandbox, on GitHub Actions, when the harness `image:` is on -`ghcr.io`, it pulls the image with the token through Podman (a run-scoped auth file in a private -temporary directory, removed after the pull), so the image can be a private package. Only the -shipped code and fix workflows grant `packages: read`, so a private image works on code and fix -harnesses; on other agents a private image is denied and sandbox creation fails. The package must also +expansion: before it creates the sandbox, on GitHub Actions, it pulls each `ghcr.io` harness +`image` and `image_mounts[].image` reference with the token through Podman (a run-scoped auth file +in a private temporary directory, removed after the pull), so those images can be private packages. Only the +shipped code and fix workflows grant `packages: read`, so private sandbox and +`image_mounts` images work on code and fix harnesses; on other agents a private +image is denied and sandbox creation fails. The package must also allow Actions access from the repository. If the pull fails, the runner logs a warning and the OpenShell gateway attempts its own unauthenticated pull, so public images keep working. For images on other registries the runner adds no credentials. See diff --git a/docs/contributing/harness-fields.md b/docs/contributing/harness-fields.md index c4b478275c..241c2b5323 100644 --- a/docs/contributing/harness-fields.md +++ b/docs/contributing/harness-fields.md @@ -48,6 +48,7 @@ These fields can appear at the harness top level (as defaults) and inside | `providers` | Providers may need forge-specific entries (e.g., different API endpoints per platform); concatenated (top-level + forge) | | `openshell` | OpenShell profiles may need forge-specific configuration; `profiles` concatenated (top-level + forge) | | `host_files` | Host files may need forge-specific entries (e.g., different credential files per platform); deduplicated by `dest` path (child wins) | +| `image_mounts` | Additional OCI images may provide forge-specific sandbox tools; deduplicated by `dest` path (child wins) | | `env` | Env config (`runner` and `sandbox` sub-maps) may need forge-specific entries (e.g., different token names per forge); sub-maps merged independently, forge/child keys win (ADR-0055) | ### Fields that stay at top level only @@ -97,10 +98,11 @@ references are scalar values, not shell commands. | inline command | Executed via `sh -c` on the host against the allowlisted preflight environment (credential-safe), not resource-resolved | `validation_loop.preflight_check`; top-level `preflight_check` (planned) | | runtime local path | Path to a file or directory in the local configuration, not a command | `pre_script`, `post_script`, `validation_loop.script`, `validation_loop.schema`, `agent_input` (directory), `host_files[].src` (host path, optional `${VAR}` expansion), `api_servers[].script` (path resolved, server startup planned) | | resource reference | Local path or pinned URL resolved/fetched as applicable | `agent`, `base`, `policy`, `skills[].source`, `plugins[].path`, `openshell.profiles[]`; `providers[]` has additional identifier semantics below | +| OCI image reference | Container image pulled by the sandbox backend and mounted at `dest`; the image's environment and entrypoint are ignored | `image_mounts[].image` | | skill override | Key is a path within the skill; value is a local file, pinned URL, or `null` to remove the file | `skills[].overrides[]` | | source metadata path | Describes a path in the source repository; not runtime-resolved or delivered | `doc` | -| destination path | Names a location inside the sandbox, not a host file to resolve | `host_files[].dest` | -| structural | Contains nested fields, lists, maps, or conditions | `forge`, `overlays[]`, `validation_loop`, `host_files[]`, `api_servers[]`, `skills[]`, `plugins[]`, `plugins[].pi`, `openshell`, `security` and its nested scanner/hook/escalation/trace blocks, `runner_env`, `env`, `env.runner`, `env.sandbox`, `privilege_levels`, `api_servers[].env`, `plugins[].env`, `allowed_remote_resources`, `providers` | +| destination path | Names a location inside the sandbox, not a host file to resolve | `host_files[].dest`, `image_mounts[].dest` | +| structural | Contains nested fields, lists, maps, or conditions | `forge`, `overlays[]`, `validation_loop`, `host_files[]`, `image_mounts[]`, `api_servers[]`, `skills[]`, `plugins[]`, `plugins[].pi`, `openshell`, `security` and its nested scanner/hook/escalation/trace blocks, `runner_env`, `env`, `env.runner`, `env.sandbox`, `privilege_levels`, `api_servers[].env`, `plugins[].env`, `allowed_remote_resources`, `providers` | | scalar | Interpreted as a configuration value, never as a path solely because it resembles one | `role`, `slug`, `description`, `image`, `model`, `effort`, `timeout_minutes`, `readonly_repo`, `sandbox_timeout_seconds`, `allow_runtime_fetch`, `max_runtime_fetches`, `trigger` (CEL expression), `schema_version`; `validation_loop.max_iterations`, `validation_loop.feedback_mode`, `host_files[].expand`, `host_files[].optional`, `api_servers[].name`, `api_servers[].port`, `api_servers[].env[]`, `plugins[].env[]`, `plugins[].pi.args[]`, `runner_env[]`, `env.runner[]`, `env.sandbox[]`, `privilege_levels[]`, `allowed_remote_resources[]`, `overlays[].when` (CEL expression); all leaf values under `security` | For local harnesses, relative runtime paths resolve from the `.fullsend` @@ -172,6 +174,7 @@ Two independent precedence axes govern field resolution | `providers` | Concatenated (top-level/base + forge/child) | Absent (nil) = inherit; `providers: []` = no forge-specific additions (top-level providers still apply) | | `openshell` | `profiles` concatenated (top-level/base + forge/child) | Absent (nil) = inherit; empty `profiles: []` = no forge-specific additions | | `host_files` | Concatenated (base + child); deduplicated by `dest` path (child wins) | Absent (nil) = inherit | +| `image_mounts` | Concatenated (base + child); deduplicated by `dest` path (child wins) | Absent (nil) = inherit; an empty list adds nothing and cannot remove an inherited mount | | `plugins` | Concatenated (base + child) | Absent (nil) = inherit | | `api_servers` | Concatenated (base + child) | Absent (nil) = inherit | | `env` | Sub-maps (`runner`, `sandbox`) merged independently; forge/child keys win (ADR-0055) | Absent (nil) = inherit | @@ -190,7 +193,7 @@ use `mergeForgeConfig` to apply their fields onto harness top-level values. ```go // ForgeConfig holds platform-specific harness configuration. // This is purely declarative YAML config — it selects which -// scripts, skills, host files, and env vars to use per platform. It is +// scripts, skills, host files, image mounts, and env vars to use per platform. It is // distinct from the forge.Client interface (internal/forge/), // which is the runtime abstraction for forge API operations. type ForgeConfig struct { @@ -201,6 +204,7 @@ type ForgeConfig struct { Providers []string `yaml:"providers,omitempty"` OpenShell *OpenShellConfig `yaml:"openshell,omitempty"` HostFiles []HostFile `yaml:"host_files,omitempty"` + ImageMounts []ImageMount `yaml:"image_mounts,omitempty"` ValidationLoop *ValidationLoop `yaml:"validation_loop,omitempty"` RunnerEnv map[string]string `yaml:"runner_env,omitempty"` Env *EnvConfig `yaml:"env,omitempty"` diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 805d9242dd..d6960637ed 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -14,6 +14,7 @@ On this page: - [Runtime interface contract](#runtime-interface-contract) - [Sandbox hook contract](#sandbox-hook-contract) — files, wiring, wire protocol, sanitizer scope, fail modes, the accepted shell dialect, Claude Code caveats - [Pinned runtime binaries in the sandbox image](#pinned-runtime-binaries-in-the-sandbox-image) — pin inventory and [vendored dependency checklist](#vendored-dependency-checklist) +- [Fullsend tool image mount contract](#fullsend-tool-image-mount-contract) — `/opt/fullsend` paths and image compatibility - [Sandbox workspace layout](#sandbox-workspace-layout) and [agent rule layering](#agent-rule-layering) - [Dummy runtime operations](#dummy-runtime-operations) - [pi runtime internals (#6464)](#pi-runtime-internals-6464) — verification provenance for the pi backend @@ -445,15 +446,43 @@ Net: after #6358 and #6357, both PreToolUse and PostToolUse halves of the contra |--------|-----|------------------| | Claude Code | `ARG CLAUDE_CODE_VERSION` (npm, Renovate-tracked). The OpenShell base image ships its **own** unpinned Claude Code at `/usr/local/bin/claude` (whatever `curl claude.ai/install.sh` fetched when the base was built), and `/usr/local/bin` precedes npm's `/usr/bin` on the sandbox `PATH` — so the Containerfile replaces that file with a symlink to the npm install and fails the build unless `claude --version` equals the pin (#6612; before that fix the base image's 2.1.156 shadowed every pin). `TestSandboxImageClaudeCodePinWins` guards the step | the [tool-name vocabulary](#tool-name-vocabulary-608); the hook contract caveats above; the alias table — on Vertex, `opus`/`sonnet`/`haiku` resolve from the running CLI's default table, which `ANTHROPIC_DEFAULT_{OPUS,SONNET,HAIKU}_MODEL` steers for the main model and for sub-agents (Agent-tool `model` argument and frontmatter alike); the fleet sets the sonnet pin in fullsend-ai/agents `env/gcp-vertex.env`. A harness or `agents:` entry that needs a specific generation can still name the id. Per-repo `models.aliases` remaps only the parent `--model` ([Claude Code](../runtimes/claude.md) already documents this) and sub-agents follow the env variable until #7031 makes persona models runner-resolved; the inference gateway route's `apiKeyHelper` rules ([Claude Code § Inference gateway route](../runtimes/claude.md#inference-gateway-route)): which headers carry the helper value, when the cache is re-read (TTL, 401/403), that `""` in `--settings` overrides a project helper and project `env`, and that a 500 is not re-read | | pi | `ARG PI_VERSION` (npm, `--ignore-scripts`, Renovate-tracked; `TestSandboxImagePinsAreRenovateTracked`) | `parsePiStream` fixtures (`internal/runtime/testdata/pi/regen.sh`); the extension compatibility notes in [pi runtime internals](#pi-runtime-internals-6464); `piGoogleVertexModels` in `pi_bootstrap.go`, which is the bundled `google-vertex` catalog verbatim and is what the `Agent` tool accepts as a Gemini id — diff `dist/providers/data/google-vertex.json` between the old and new pin, not the generated wrapper, and add any new id; a missed entry makes the `Agent` tool reject a model the running pi serves. `internal/runtime/testdata/pi/check-vertex-catalog.sh` runs exactly that diff against the pinned `PI_VERSION`; the `retry` keys `piSettingsJSON` writes (`core/settings-manager.ts`) and the provider backoff they drive (pi-ai `utils/provider-retry.ts`), see #7191; the edit-repair stopgap, whose removal check is the comment above `ARG PI_VERSION` | -| `pi-anthropic-vertex` | `ARG PI_ANTHROPIC_VERTEX_VERSION` + tarball SHA256, under `/usr/local/share/pi-extensions/anthropic-vertex` | the extension's own CI matrix (pinned `PI_VERSION` + latest pi); no compat file or SDK override to check | -| `pi-xai-vertex` | `ARG PI_XAI_VERTEX_VERSION` + tarball SHA256, under `/usr/local/share/pi-extensions/xai-vertex` | its `peerDependencies` floor (it mirrors no pi internals; declared only — `--omit=peer` never installs it); `piXaiVertexModels` in `pi_bootstrap.go`, the ids it registers and what the `Agent` tool accepts as a Grok id | -| `pi-inference-gateway` | `ARG PI_INFERENCE_GATEWAY_VERSION` + tarball SHA256, under `/usr/local/share/pi-extensions/inference-gateway` (no runtime dependencies, so no `npm ci`). Loaded when `run.go` registers a gateway run for a `gateway/` model (`PrepareGatewayRun`, which calls `SetPiGatewayRun`): the run then gets the `-e` load, the `INFERENCE_GATEWAY_*` clear, the `inference-gateway.json` guard (with the Agent extension's per-dispatch re-check of it) and `INFERENCE_GATEWAY_CONFIG_FILE` (v0.1.2 and later), which names the one config file the extension reads, so no other config-dir file or overlay is read | the extension's own CI matrix (pinned `PI_VERSION` + latest pi) | +| `pi-anthropic-vertex` | `ARG PI_ANTHROPIC_VERTEX_VERSION` + tarball SHA256, installed under `/usr/local/share/pi-extensions/anthropic-vertex`; loaded from `/opt/fullsend/usr/local/share/pi-extensions/anthropic-vertex` | the extension's own CI matrix (pinned `PI_VERSION` + latest pi); no compat file or SDK override to check | +| `pi-xai-vertex` | `ARG PI_XAI_VERTEX_VERSION` + tarball SHA256, installed under `/usr/local/share/pi-extensions/xai-vertex`; loaded from `/opt/fullsend/usr/local/share/pi-extensions/xai-vertex` | its `peerDependencies` floor (it mirrors no pi internals; declared only — `--omit=peer` never installs it); `piXaiVertexModels` in `pi_bootstrap.go`, the ids it registers and what the `Agent` tool accepts as a Grok id | +| `pi-inference-gateway` | `ARG PI_INFERENCE_GATEWAY_VERSION` + tarball SHA256, installed under `/usr/local/share/pi-extensions/inference-gateway` and loaded from `/opt/fullsend/usr/local/share/pi-extensions/inference-gateway` (no runtime dependencies, so no `npm ci`). Loaded when `run.go` registers a gateway run for a `gateway/` model (`PrepareGatewayRun`, which calls `SetPiGatewayRun`): the run then gets the `-e` load, the `INFERENCE_GATEWAY_*` clear, the `inference-gateway.json` guard (with the Agent extension's per-dispatch re-check of it) and `INFERENCE_GATEWAY_CONFIG_FILE` (v0.1.2 and later), which names the one config file the extension reads, so no other config-dir file or overlay is read | the extension's own CI matrix (pinned `PI_VERSION` + latest pi) | | Codex | `ARG CODEX_VERSION` (npm, Renovate-tracked; `TestSandboxImagePinsAreRenovateTracked`). The OpenShell base image already installs `@openai/codex` under the same npm prefix (`/usr`, binary `/usr/bin/codex`) — 0.117.0 on the base pinned today — so the pinned install replaces it in place. `/usr/local/bin/codex` is then symlinked at the npm install and the build fails unless `codex --version` reports `codex-cli `: nothing shadows the pin there today, and the symlink plus assertion make sure nothing can start to, the way the base image's Claude Code did in #6612. `TestSandboxImageCodexPinWins` guards the step | the codex stream parser fixtures (#6920); the JSONL event and hook wire shapes the codex runtime depends on | The run log's `Agent: (vX.Y.Z)` line is the ground truth for which Claude Code version served a run; the Containerfile pin is a claim, the assertion at build time is what makes it true. The image also creates each runtime's config directory when the binary refuses to start without one: `CODEX_HOME` (`sandbox.SandboxCodexConfig`) is created owned by the sandbox user and baked as an `ENV` default, so an ad-hoc `codex` invocation from Bash behaves like the runtime's own `EnvExports()`. `TestSandboxImageCodexDefaults` keeps the path in the image and the Go constant in step (the pi equivalent is `TestSandboxImagePiDefaults`). +## Fullsend tool image mount contract + +The runner looks for its pinned runtime tools under `/opt/fullsend`: + +- `/opt/fullsend/usr/local/bin` — Claude Code, pi, OpenCode, scanners and other Fullsend-installed CLIs. +- `/opt/fullsend/usr/bin` — Node.js, Python and system utilities required by the runtimes and hooks. +- `/opt/fullsend/usr/local/share/pi-extensions` — runner-vetted pi provider extensions. + +An `image_mounts` entry at `/opt/fullsend` makes the OCI image root visible at +those paths. OpenShell ignores the mounted image's `ENV`, user, working +directory and entrypoint. Mounts are read-only. Keep the mounted tool image +and sandbox image on the same OpenShell base image, or verify that their +architecture, ELF loader, glibc ABI, Python standard library and Node runtime +are compatible: executable files run in the sandbox's namespaces, so the +mount does not provide an isolated root filesystem or automatically select +the mounted image's dynamic linker. + +The regular `fullsend-sandbox` image creates `/opt/fullsend/usr -> /usr`, so +the same runner paths work when no tool image is mounted. Its +`fullsend-sandbox-tools` build target removes that link; use that separate +image for a mount because the OCI root is placed at `/opt/fullsend`. The +Claude and Codex links in `/usr/local/bin` are relative so they still resolve +inside the mounted image. The generated base policy allows `/opt/fullsend` +read-only; custom policies must do the same. The current harness PoC passes +Podman image mount configuration to OpenShell, so it is intended for the local +Podman backend. The gateway must enable `allow_driver_config` and disable +resource admission for Podman image mounts. + ### Vendored dependency checklist Before adding or bumping a dependency that runs in the sandbox: @@ -787,7 +816,7 @@ Parity with `claude -p --dangerously-skip-permissions`, verified against pi v0.8 ### Process and exit codes - **Hardening levers in use** - - `Run` executes `pi --print --mode json --no-approve --no-extensions --no-prompt-templates --no-themes --session-dir /sandbox/pi-config/sessions [-e /usr/local/share/pi-extensions/anthropic-vertex | -e /usr/local/share/pi-extensions/xai-vertex] [-e /sandbox/pi-config/fullsend-hooks.js] [-e /sandbox/pi-config/fullsend-agent.js] [-e /sandbox/pi-config/fullsend-edit-repair.js] [--tools ...] --model --thinking '' >/sandbox/workspace/pi-debug.log]`. + - `Run` executes `pi --print --mode json --no-approve --no-extensions --no-prompt-templates --no-themes --session-dir /sandbox/pi-config/sessions [-e /opt/fullsend/usr/local/share/pi-extensions/anthropic-vertex | -e /opt/fullsend/usr/local/share/pi-extensions/xai-vertex] [-e /sandbox/pi-config/fullsend-hooks.js] [-e /sandbox/pi-config/fullsend-agent.js] [-e /sandbox/pi-config/fullsend-edit-repair.js] [--tools ...] --model --thinking '' >/sandbox/workspace/pi-debug.log]`. - `settings.json` sets `defaultProjectTrust: never` (repo-owned `.pi/` never loaded) and `defaultTools: [read, bash, edit, write, grep, find, ls]` — pi alone activates only the first four; `--tools`, when emitted, replaces the set. The `grep` and `find` tools shell out to `rg` and `fd` (pi's `utils/tools-manager.ts`), which the sandbox image ships because `PI_OFFLINE=1` and the egress policy both stop pi's own GitHub-release download. - `settings.json` also raises pi's retry above its defaults (#7191). pi retries at two layers; the settings set both: - **Provider layer** — `retry.provider.maxRetries: 6`, `maxRetryDelayMs: 60000`. Retries a single HTTP request on 408/409/429/5xx and honours `Retry-After` (0.5 to 8 s backoff without it). pi leaves this layer off unless `maxRetries` is set, and it is the only layer that reads `Retry-After`. A `Retry-After` above 60 s fails that request at once. @@ -1004,7 +1033,7 @@ rather than dropping the list silently, the mirror of pi's `plugins:` warning. ### Claude-on-Vertex via a fullsend-owned extension -pi's `google-vertex` provider is Gemini-only and upstream's `anthropic-vertex` provider (earendil-works/pi#5262) is still an open PR, so the sandbox image vendors [`fullsend-ai/pi-anthropic-vertex`](https://github.com/fullsend-ai/pi-anthropic-vertex) under `/usr/local/share/pi-extensions/anthropic-vertex`, pinned by tag + tarball SHA256 (`PI_ANTHROPIC_VERTEX_VERSION`/`_SHA256`). pi never auto-loads it; `Run` passes it with `-e` for the `anthropic-vertex` provider (`runtime.piVertexExtensionPath`). +pi's `google-vertex` provider is Gemini-only and upstream's `anthropic-vertex` provider (earendil-works/pi#5262) is still an open PR, so the sandbox image vendors [`fullsend-ai/pi-anthropic-vertex`](https://github.com/fullsend-ai/pi-anthropic-vertex) under `/usr/local/share/pi-extensions/anthropic-vertex`, pinned by tag + tarball SHA256 (`PI_ANTHROPIC_VERTEX_VERSION`/`_SHA256`). At runtime the runner loads it from `/opt/fullsend/usr/local/share/pi-extensions/anthropic-vertex`; pi never auto-loads it, and `Run` passes it with `-e` for the `anthropic-vertex` provider (`runtime.piVertexExtensionPath`). **How it works.** It registers provider `anthropic-vertex` with pi's own Claude catalog and pi's own Anthropic transport. A `fetch` wrapper rewrites each request the way the Vertex SDK does: the model id moves into the URL path, `anthropic_version` goes into the body, and the Google token becomes an `authorization: Bearer` header. No `@anthropic-ai/*` dependency, no mirrored pi internals. It replaced twoGiants/pi-anthropic-vertex in #7019, which copied pi's `streamSimple` helpers, pinned the Anthropic SDK underneath a cast, and hard-failed `claude-opus-5` from pi 0.84.3. @@ -1024,7 +1053,7 @@ Replace with the upstream provider once #5262 ships in a pinned release. ### Grok-on-Vertex via a fullsend-owned extension -pi's built-in `xai` provider targets xAI's native API (`api.x.ai`, needs `XAI_API_KEY`) and `google-vertex` is Gemini-only, so neither reaches Grok on Vertex, which speaks the OpenAI-completions protocol. The sandbox image vendors [`fullsend-ai/pi-xai-vertex`](https://github.com/fullsend-ai/pi-xai-vertex) (MIT) under `/usr/local/share/pi-extensions/xai-vertex`, pinned by tag + tarball SHA256 (`PI_XAI_VERTEX_VERSION`/`_SHA256`, Renovate-tracked like the Anthropic one) and registering provider `xai-vertex` with model `xai/grok-4.6`. +pi's built-in `xai` provider targets xAI's native API (`api.x.ai`, needs `XAI_API_KEY`) and `google-vertex` is Gemini-only, so neither reaches Grok on Vertex, which speaks the OpenAI-completions protocol. The sandbox image vendors [`fullsend-ai/pi-xai-vertex`](https://github.com/fullsend-ai/pi-xai-vertex) (MIT) under `/usr/local/share/pi-extensions/xai-vertex`, pinned by tag + tarball SHA256 (`PI_XAI_VERTEX_VERSION`/`_SHA256`, Renovate-tracked like the Anthropic one) and registering provider `xai-vertex` with model `xai/grok-4.6`; the runner loads it from `/opt/fullsend/usr/local/share/pi-extensions/xai-vertex`. - **No mirrored internals.** Like the Anthropic extension it registers a public pi API (`openAICompletionsApi()`) and lets pi do streaming, tools and usage — so there is no `sync/compat.json` drift to re-check on a `PI_VERSION` bump; confirm its `peerDependencies` floor instead (declared only — it installs with `--omit=peer` too, so nothing enforces it at build time). - **Auth** is ambient ADC through `google-auth-library` reading `GOOGLE_APPLICATION_CREDENTIALS`, the same WIF `external_account` path as Claude-on-Vertex and under the same `*.googleapis.com` egress allowlist, so no new credential plumbing. @@ -1034,7 +1063,7 @@ pi's built-in `xai` provider targets xAI's native API (`api.x.ai`, needs `XAI_AP ### Binary present but unhooked -The pinned `pi` CLI and the vendored Vertex extensions ship in every sandbox image (so Bootstrap/Run work targets a reviewed version), so an agent on another runtime can invoke `pi -e /usr/local/share/pi-extensions/anthropic-vertex` ad hoc from Bash with none of that runtime's tool hooks — and in a Claude-on-Vertex sandbox the ADC credentials and project id it needs are already in the environment, so that is a working nested agent, not an inert binary. This is the same class of exposure as any interpreter the agent can run (`python`, `node`, `curl` with the same ADC token): the sandbox tool hooks are defense-in-depth and only see the top-level tool call (ADR 0090); the boundary remains the OpenShell sandbox, its L7 egress allowlist and the credential placeholders, which a nested `pi` cannot escape either. The image bakes `PI_OFFLINE=1`/`PI_TELEMETRY=0` and the runner-owned config paths as defaults; treat the `N/A — stub` matrix cells as "not wired", not "cannot run". +The pinned `pi` CLI and the vendored Vertex extensions ship in every sandbox image (so Bootstrap/Run work targets a reviewed version), so an agent on another runtime can invoke `pi -e /opt/fullsend/usr/local/share/pi-extensions/anthropic-vertex` ad hoc from Bash with none of that runtime's tool hooks — and in a Claude-on-Vertex sandbox the ADC credentials and project id it needs are already in the environment, so that is a working nested agent, not an inert binary. This is the same class of exposure as any interpreter the agent can run (`python`, `node`, `curl` with the same ADC token): the sandbox tool hooks are defense-in-depth and only see the top-level tool call (ADR 0090); the boundary remains the OpenShell sandbox, its L7 egress allowlist and the credential placeholders, which a nested `pi` cannot escape either. The image bakes `PI_OFFLINE=1`/`PI_TELEMETRY=0` and the runner-owned config paths as defaults; treat the `N/A — stub` matrix cells as "not wired", not "cannot run". ### Not yet exercised diff --git a/docs/guides/dev/cli-internals.md b/docs/guides/dev/cli-internals.md index d68f1cfc9f..91174104ee 100644 --- a/docs/guides/dev/cli-internals.md +++ b/docs/guides/dev/cli-internals.md @@ -535,9 +535,9 @@ Vendoring commit messages use title + body (upload and stale delete). `admin ins │ │ └── security hooks │ │ │ │ │ │ │ │ bootstrapEnv() writes: │ │ -│ │ ├── PATH=/usr/local/go/bin: │ │ -│ │ │ $HOME/go/bin:$PATH: │ │ -│ │ │ /sandbox/workspace/bin (last) │ │ +│ │ ├── PATH=/opt/fullsend/...: │ │ +│ │ │ /usr/local/go/bin:$HOME/go/bin: │ │ +│ │ │ $PATH:/sandbox/workspace/bin │ │ │ │ ├── readonly FULLSEND_RUNNER_PATH │ │ │ │ ├── CLAUDE_CONFIG_DIR=/sandbox/claude-config│ │ │ │ ├── FULLSEND_OUTPUT_DIR=... │ │ @@ -699,7 +699,7 @@ SandboxWorkspace = "/sandbox/workspace" SandboxClaudeConfig = "/sandbox/claude-config" SandboxCodexConfig = "/sandbox/codex-config" SandboxPiConfig = "/sandbox/pi-config" -SandboxPiExtensionsDir = "/usr/local/share/pi-extensions" // image-baked, read-only pi extensions (loaded only via -e) +SandboxPiExtensionsDir = "/opt/fullsend/usr/local/share/pi-extensions" // image-baked, read-only pi extensions (loaded only via -e) ``` For sandbox workspace layout, agent rule layering, and security scanning diff --git a/docs/guides/user/bring-your-own-agent.md b/docs/guides/user/bring-your-own-agent.md index d8df1ff456..e843fcbf8b 100644 --- a/docs/guides/user/bring-your-own-agent.md +++ b/docs/guides/user/bring-your-own-agent.md @@ -519,6 +519,34 @@ Key patterns to note: For the complete list of harness fields, see the [Harness Field Reference](../../reference/harness-reference.md). +#### Mount the Fullsend runtime tools + +Use `image_mounts` when your sandbox image needs Fullsend's pinned runtime +tools from a separate OCI image: + +```yaml +image_mounts: + - image: ghcr.io/fullsend-ai/fullsend-sandbox-tools@sha256: + dest: /opt/fullsend +``` + +Fullsend mounts the image read-only. Its OCI `ENV`, user, working directory +and entrypoint do not apply. The sandbox policy must include `/opt/fullsend` +in `filesystem_policy.read_only`. The OpenShell Podman gateway must enable +`allow_driver_config` and disable resource admission. The `fullsend-sandbox` +package publishes a matching mount-ready `fullsend-sandbox-tools` image; use +that image rather than mounting the ordinary sandbox image, whose +`/opt/fullsend/usr` compatibility link would point back into the sandbox. +The mount image should use the same +OpenShell sandbox base, or a Linux image with compatible system libraries and +Python/Node runtimes. The local Podman backend supports this PoC; other +backends may reject the mount. For merge behavior and destination rules, see +the [harness merge rules](../../reference/harness-reference.md#field-merge-rules-for-base-and-overlays). +Distinct image mount destinations cannot contain one another (for example, +`/opt/fullsend` and `/opt/fullsend/org-tools`) or overlap a `host_files` +destination. A child can still replace an inherited image mount at the exact +same destination. + ### Agent definitions The agent definition is Markdown with YAML frontmatter: @@ -561,7 +589,7 @@ different filesystem or process rules, for example version: 1 filesystem_policy: include_workdir: true - read_only: [/usr, /lib, /proc, /dev/urandom, /app, /etc, /var/log] + read_only: [/usr, /lib, /proc, /dev/urandom, /app, /etc, /var/log, /opt/fullsend] read_write: [/sandbox, /tmp, /dev/null] landlock: compatibility: best_effort diff --git a/docs/problems/agent-infrastructure.md b/docs/problems/agent-infrastructure.md index 9cafb20949..171abd094c 100644 --- a/docs/problems/agent-infrastructure.md +++ b/docs/problems/agent-infrastructure.md @@ -148,7 +148,10 @@ Many fullsend scenarios skew toward **ephemeral, task-scoped** execution (triage URL decided in [ADR 0156](../ADRs/0156-separate-jira-api-url-from-site-url.md). Other agent resource access remains open. -- Do we need a dedicated “agent runner” image or environment with a known, auditable tool set? +- Do we need a dedicated “agent runner” image or environment with a known, + auditable tool set? Repositories can supply toolchain images separately + from Fullsend's sandbox image; whether Fullsend should maintain a dedicated + base image remains open ([ADR 0173](../ADRs/0173-compose-multiple-images-into-agent-sandboxes.md)). - ~~How do we preserve end-to-end traceability for event-driven agent dispatch in GitHub Actions?~~ Decided in [ADR 0041](../ADRs/0041-synchronous-workflow-call-event-dispatch.md) (synchronous `workflow_call` dispatch for the event path). - How do we compare 3rd party vs internal vs build-our-own on concrete criteria: cost, time to first agent, compliance, and alignment with our security and coordination model? - Who in the org would own and operate agent infrastructure, and how does that align with existing platform or CI ownership? [ADR 0123](../ADRs/0123-tenant-configuration-from-repos-yaml.md) establishes the existing `repos.yaml` v1 format for tenant configuration in a possible centralized offering; the source of truth, service, operational ownership, and infrastructure remain open. diff --git a/docs/reference/harness-reference.md b/docs/reference/harness-reference.md index f54c6a939d..c12a2951b5 100644 --- a/docs/reference/harness-reference.md +++ b/docs/reference/harness-reference.md @@ -20,6 +20,9 @@ base: harness/common-base.yaml # Inherit from another harness (local or URL # ── Sandbox ─────────────────────────────────────────────────── image: ghcr.io/fullsend-ai/fullsend-sandbox:latest +image_mounts: # Read-only OCI images mounted inside the sandbox + - image: ghcr.io/fullsend-ai/fullsend-sandbox-tools@sha256:abc... + dest: /opt/fullsend # Fullsend runtime tools and extensions model: opus # LLM model override effort: high # Reasoning effort (low, medium, high, xhigh, max); claude runtime only # readonly_repo: true # make the checkout read-only (chmod a-w, .git/ excluded); absent = inherit from base; false overrides a base true @@ -148,6 +151,8 @@ Most fields are self-explanatory from the inline comments above. This section ex **`image`** — The sandbox container image. On GitHub Actions a private `ghcr.io` package works on code and fix harnesses, whose shipped workflows grant `packages: read`; see [GitHub Packages credentials](../cli/run.md#github-packages-credentials). +**`image_mounts`** — Additional OCI images mounted read-only inside the sandbox. Each entry requires an `image` reference and an absolute, clean `dest` path. Relative paths and `/` are rejected. An image mount destination may not overlap any `host_files[].dest`. After same-destination entries are merged, distinct image mount destinations may not contain one another. A child harness layer replaces an inherited entry with the same `dest`; there is no syntax for removing an inherited mount. The OCI image's `ENV`, user, working directory and entrypoint are ignored. Fullsend currently passes these mounts to OpenShell's Podman backend; other backends may reject them. OpenShell's Podman image mounts require resource admission to be disabled in the gateway configuration. For the Fullsend tool image, mount at `/opt/fullsend` and allow that path read-only in the sandbox policy. Use an immutable image digest for repeatable runs. The mount image and sandbox image must have compatible Linux ABI and system libraries; see [the tool image contract](../contributing/runtime-implementation.md#fullsend-tool-image-mount-contract). + **`readonly_repo`** — When `true`, the runner makes the checkout read-only in the sandbox before the agent starts: it removes write permission (`chmod a-w`) from every file and directory in the checkout except `.git/`. A harness that leaves the field out inherits it from its `base:`, and gets a writable checkout when no base sets it. An explicit `false` keeps the checkout writable, even when the base sets `true`. **Top level only** — a `readonly_repo` key placed under `overlays:`/`forge:` is silently ignored. The step also runs `chown -R sandbox:sandbox` on `.git/`. If the step fails, for example on an image that has no `sandbox` user, the run stops with `read-only repo enforcement failed`. That applies to a harness that inherits `true` as well. To fix it, build the image on the fullsend sandbox image, which has that user (see [Extending the sandbox image](../guides/user/customizing-agents.md#extending-the-sandbox-image)), or set `readonly_repo: false` in the harness to keep a writable checkout. **`role`** — The agent's identity within fullsend. Dispatch uses the role to match config-registered agents to built-in defaults (same-name config agents take precedence). The role also determines which GitHub App credentials **and permissions** the mint service issues. It must be a role the mint serves: on the hosted mint that is the fixed built-in set (`triage`, `coder`, `review`, `retro`, `prioritize`, `fullsend`); custom roles require your own mint. An unserved role returns `403`. See [Custom Agent Identity](../guides/user/custom-agent-identity.md). diff --git a/images/README.md b/images/README.md index 0486c95a32..c550fe9d1b 100644 --- a/images/README.md +++ b/images/README.md @@ -11,15 +11,38 @@ run dependencies (see [Runner image](#runner-image) below). ``` ghcr.io/nvidia/openshell-community/sandboxes/base (upstream, multi-arch) └── ghcr.io/fullsend-ai/fullsend-sandbox (base sandbox) + ├── ghcr.io/fullsend-ai/fullsend-sandbox-tools (mountable Fullsend tools) └── ghcr.io/fullsend-ai/fullsend-code (code agent) ``` | Image | Directory | Description | |-------|-----------|-------------| | `fullsend-sandbox` | [`images/sandbox/`](sandbox/) | Base sandbox with Claude Code, pi, Codex, ripgrep + fd (pi grep/find backends), jq, acli, gitleaks, tirith, pre-commit, and gitlint. | +| `fullsend-sandbox-tools` | [`images/sandbox/`](sandbox/) | The same pinned tool image with its `/opt/fullsend/usr` compatibility symlink removed, so its OCI root can be mounted at `/opt/fullsend`. | | `fullsend-code` | [`images/code/`](code/) | Extends `fullsend-sandbox` with Go toolchain and scan-secrets wrapper. Used by the code-implementation agent. | -Both images are built for **linux/amd64** and **linux/arm64**. +All sandbox images are built for **linux/amd64** and **linux/arm64**. + +## Mounting the Fullsend tool image + +The `fullsend-sandbox-tools` image provides the runner's pinned tools through +an `image_mounts` entry at `/opt/fullsend`. The runner reads runtime CLIs from +`/opt/fullsend/usr/local/bin`, system tools from `/opt/fullsend/usr/bin`, and +pi provider extensions from `/opt/fullsend/usr/local/share/pi-extensions`. +The OCI image root is visible at that mount point; its `ENV`, user, working +directory and entrypoint are ignored. The mount is read-only. + +The regular sandbox image has `/opt/fullsend/usr -> /usr`, which keeps the +runner paths available when no image is mounted. The tools image removes that +link, so the image mount exposes its own `/usr` tree at `/opt/fullsend/usr`. +Use the same OpenShell base image for both images or verify compatible +architecture, ELF loader, glibc, Python and Node runtimes. Mounted executables +run in the sandbox environment rather than a separate root filesystem. The +prelaunch check runs `/opt/fullsend/usr/bin/node --version` before repository +setup. The harness PoC targets +OpenShell's Podman backend; the sandbox policy must allow `/opt/fullsend` +read-only, and the gateway must enable `allow_driver_config` and disable +resource admission for image mounts. ## Runner image diff --git a/images/sandbox/Containerfile b/images/sandbox/Containerfile index 8cc9130c3d..3cdb0f3725 100644 --- a/images/sandbox/Containerfile +++ b/images/sandbox/Containerfile @@ -27,13 +27,16 @@ # Build: # podman build -t /fullsend-sandbox:v1 \ # -f images/sandbox/Containerfile images/sandbox/ +# podman build --target fullsend-sandbox-tools \ +# -t /fullsend-sandbox-tools:v1 \ +# -f images/sandbox/Containerfile images/sandbox/ # # Per-org images that need extra tools (e.g. Go, Rust) should extend # this base: # FROM /fullsend-sandbox:v1 # RUN apt-get install -y golang -FROM ghcr.io/nvidia/openshell-community/sandboxes/base@sha256:aeef1c63f00e2913ea002ccb3aaf925f338b5c5d70e63576f0d95c16a138044e +FROM ghcr.io/nvidia/openshell-community/sandboxes/base@sha256:aeef1c63f00e2913ea002ccb3aaf925f338b5c5d70e63576f0d95c16a138044e AS fullsend-sandbox-build # The base image runs as the sandbox user (998). Switch to root for # package installation and switch back at the end. @@ -73,7 +76,7 @@ RUN npm install -g @anthropic-ai/claude-code@${CLAUDE_CODE_VERSION} RUN NPM_CLAUDE="$(npm prefix -g)/bin/claude" \ && test -x "${NPM_CLAUDE}" \ && rm -f /usr/local/bin/claude \ - && ln -s "${NPM_CLAUDE}" /usr/local/bin/claude \ + && ln -sr "${NPM_CLAUDE}" /usr/local/bin/claude \ && GOT="$(claude --version | awk '{print $1}')" \ && if [ "${GOT}" != "${CLAUDE_CODE_VERSION}" ]; then \ echo "claude on PATH reports ${GOT}, expected CLAUDE_CODE_VERSION=${CLAUDE_CODE_VERSION}" >&2; \ @@ -282,7 +285,7 @@ RUN npm install -g --ignore-scripts @openai/codex@${CODEX_VERSION} \ RUN NPM_CODEX="$(npm prefix -g)/bin/codex" \ && test -x "${NPM_CODEX}" \ && rm -f /usr/local/bin/codex \ - && ln -s "${NPM_CODEX}" /usr/local/bin/codex \ + && ln -sr "${NPM_CODEX}" /usr/local/bin/codex \ && GOT="$(codex --version)" \ && if [ "${GOT}" != "codex-cli ${CODEX_VERSION}" ]; then \ echo "codex on PATH reports '${GOT}', expected 'codex-cli ${CODEX_VERSION}'" >&2; \ @@ -459,10 +462,13 @@ RUN case "$TARGETARCH" in \ && fd --version | grep -q "^fd ${FD_VERSION}$" # --------------------------------------------------------------------------- -# pre-commit + gitlint — pre-commit runs repo-defined hooks (formatting, -# linting, etc.) on changed files. gitlint validates commit message format. +# pre-commit + gitlint + jsonschema — pre-commit runs repo-defined hooks +# (formatting, linting, etc.) on changed files; gitlint validates commit +# messages; jsonschema backs the agent-facing fullsend-check-output helper. # Baking them in avoids pip installs on every run and ensures availability -# even if pip is network-restricted inside the sandbox. +# even if pip is network-restricted inside the sandbox. Keep jsonschema in a +# dedicated path so the mounted Fullsend Python can load it independently of +# the user-provided sandbox image's Python packages. ARG PRECOMMIT_VERSION=4.5.1 ARG GITLINT_VERSION=0.19.1 ARG JSONSCHEMA_VERSION=4.23.0 @@ -472,6 +478,8 @@ RUN apt-get update \ && pip install --no-cache-dir --break-system-packages \ "pre-commit==${PRECOMMIT_VERSION}" \ "gitlint-core==${GITLINT_VERSION}" \ + && pip install --no-cache-dir --break-system-packages \ + --target /usr/local/share/fullsend/python/site-packages \ "jsonschema==${JSONSCHEMA_VERSION}" # --------------------------------------------------------------------------- @@ -534,5 +542,24 @@ RUN case "$TARGETARCH" in \ && chmod +x /usr/local/bin/acli \ && rm -rf /tmp/acli.tar.gz /tmp/acli_${ACLI_VERSION}_linux_${TARGETARCH} +# In the regular sandbox image, expose the same tool paths the runner uses +# when this image is mounted read-only at /opt/fullsend. The OCI image mount +# covers this directory with the mounted image's root filesystem; without a +# mount, this link resolves to the tools installed in this image. +RUN install -d -o root -g root -m 0755 /opt/fullsend \ + && ln -s /usr /opt/fullsend/usr + # Switch back to the sandbox user. USER sandbox + +# The ordinary sandbox image uses this link so the runner can find the +# installed tools at /opt/fullsend/usr/... without an image mount. A mounted +# OCI root is already exposed at /opt/fullsend, so its own /usr tree must stay +# a real directory. Publish this target separately for image_mounts users. +FROM fullsend-sandbox-build AS fullsend-sandbox-tools +USER root +RUN rm /opt/fullsend/usr +USER sandbox + +# Keep the ordinary fullsend-sandbox image as the default build target. +FROM fullsend-sandbox-build AS fullsend-sandbox diff --git a/internal/agentnew/templates/policies/base.yaml b/internal/agentnew/templates/policies/base.yaml index a5816d1bfb..153e1eb4ba 100644 --- a/internal/agentnew/templates/policies/base.yaml +++ b/internal/agentnew/templates/policies/base.yaml @@ -13,7 +13,7 @@ version: 1 filesystem_policy: include_workdir: true - read_only: [/usr, /lib, /proc, /dev/urandom, /app, /etc, /var/log] + read_only: [/usr, /lib, /proc, /dev/urandom, /app, /etc, /var/log, /opt/fullsend] read_write: [/sandbox, /tmp, /dev/null] landlock: compatibility: best_effort diff --git a/internal/cli/run.go b/internal/cli/run.go index c97e00c203..6d6647a451 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -2120,9 +2120,12 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep return nil } - // 4a. Create sandbox. A private ghcr.io harness image is pulled first - // with the workflow token; the gateway's own pull is anonymous (#9019). + // 4a. Create sandbox. Private ghcr.io sandbox and mounted images are + // pulled first with the workflow token; the gateway's pull is anonymous. prePullGHCRImage(ctx, h.Image, printer) + for _, mount := range h.ImageMounts { + prePullGHCRImage(ctx, mount.Image, printer) + } createStart := time.Now() printer.StepStart("Creating sandbox: " + sandboxName) @@ -2131,7 +2134,11 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep )) readyTimeout := time.Duration(h.SandboxTimeoutSeconds) * time.Second - if err := sandbox.CreateWithRetry(sandboxName, allProviderNames, h.Image, h.Policy, sandbox.DefaultMaxCreateAttempts, readyTimeout, keepSandbox); err != nil { + imageMounts := make([]sandbox.ImageMount, 0, len(h.ImageMounts)) + for _, mount := range h.ImageMounts { + imageMounts = append(imageMounts, sandbox.ImageMount{Source: mount.Image, Target: mount.Dest}) + } + if err := sandbox.CreateWithRetry(sandboxName, allProviderNames, h.Image, h.Policy, sandbox.DefaultMaxCreateAttempts, readyTimeout, keepSandbox, imageMounts...); err != nil { finalizeSandboxSpan(sandboxSpan, err) printer.StepFail("Failed to create sandbox") if keepSandbox { @@ -2140,6 +2147,19 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep return fmt.Errorf("creating sandbox: %w", err) } finalizeSandboxSpan(sandboxSpan, nil) + for _, mount := range h.ImageMounts { + if mount.Dest != sandbox.SandboxFullsendRoot { + continue + } + printer.StepStart("Checking mounted Fullsend Node runtime") + if err := checkMountedFullsendNode(ctx, sandboxName); err != nil { + printer.StepFail("Mounted Fullsend Node runtime cannot start") + discardSandbox(sandboxName, runDir, keepSandbox, printer) + return err + } + printer.StepDone("Mounted Fullsend Node runtime is available") + break + } if len(runScopedProviders) > 0 { // The OpenAI credential only reaches api.openai.com through an @@ -3864,14 +3884,16 @@ func runnerPathRestoreLine() string { return fmt.Sprintf(`export PATH="$%s${PATH:+:$PATH}"`, runnerPathVar) } -// runnerPathLines are the first lines of .env: the runner's PATH, then its -// read-only copy. /sandbox/workspace/bin comes last, after the image's own +// runnerPathLines are the first lines of .env: the Fullsend tool-image paths, +// the sandbox's project toolchain and PATH, then its read-only copy. +// /sandbox/workspace/bin comes last, after the image's own // PATH: host_files can drop files there, so it may add commands (my-tool.sh, // and the runner's own fullsend and fullsend-check-output, which exist only // there) but not replace one the image provides — python3 and tirith for the // security hooks, node for codex and pi, git, find. func runnerPathLines() []string { - pathExport := "export PATH=/usr/local/go/bin" + pathExport := "export PATH=" + sandbox.SandboxFullsendToolPath + pathExport += ":/usr/local/go/bin" pathExport += ":$HOME/go/bin" pathExport += ":$PATH" pathExport += fmt.Sprintf(":%s/bin", sandbox.SandboxWorkspace) @@ -5316,12 +5338,34 @@ var deleteSandboxFn = sandbox.Delete // without a gateway. var collectOpenshellLogsFn = collectOpenshellLogs -// discardSandbox deletes a sandbox that failed a credential egress -// preflight. Those preflights run before the run's own sandbox cleanup -// defer is registered (it must follow the post-script's), so without this -// a failed preflight would leave the sandbox running. Like that defer it -// collects the OpenShell logs first: a policy failure is when they help. -// --keep-sandbox keeps it, as it does for every other failure. +// checkMountedFullsendNode verifies that the mounted image exposes a Node +// executable that can start in the sandbox before repository setup or agent +// launch. This is a basic mount/runtime check, not a full compatibility test. +func checkMountedFullsendNode(ctx context.Context, sandboxName string) error { + command := sandbox.SandboxFullsendBinDir + "/node --version" + stdout, stderr, exitCode, err := sandbox.ExecContext(ctx, sandboxName, command, 10*time.Second) + if err != nil { + return fmt.Errorf("checking mounted Fullsend Node runtime: %w", err) + } + if exitCode != 0 { + detail := strings.TrimSpace(stderr) + if detail == "" { + detail = strings.TrimSpace(stdout) + } + if detail == "" { + detail = fmt.Sprintf("command exited with status %d", exitCode) + } + return fmt.Errorf("checking mounted Fullsend Node runtime failed: %s", detail) + } + return nil +} + +// discardSandbox deletes a sandbox that failed a preflight. Those preflights +// run before the run's own sandbox cleanup defer is registered (it must follow +// the post-script's), so without this a failed preflight would leave the +// sandbox running. Like that defer it collects the OpenShell logs first: +// a policy failure is when they help. --keep-sandbox keeps it, as it does for +// every other failure. func discardSandbox(sandboxName, runDir string, keep bool, printer *ui.Printer) { collectOpenshellLogsFn(sandboxName, runDir, printer) if keep { diff --git a/internal/cli/run_env_path_test.go b/internal/cli/run_env_path_test.go index 192e302e3b..a1c13f0255 100644 --- a/internal/cli/run_env_path_test.go +++ b/internal/cli/run_env_path_test.go @@ -17,7 +17,7 @@ import ( func TestRunnerPathLines(t *testing.T) { t.Parallel() assert.Equal(t, []string{ - "export PATH=/usr/local/go/bin:$HOME/go/bin:$PATH:/sandbox/workspace/bin", + "export PATH=" + sandbox.SandboxFullsendToolPath + ":/usr/local/go/bin:$HOME/go/bin:$PATH:/sandbox/workspace/bin", `if ( FULLSEND_RUNNER_PATH= ) 2>/dev/null; then FULLSEND_RUNNER_PATH="$PATH"; readonly FULLSEND_RUNNER_PATH; fi`, }, runnerPathLines()) assert.Equal(t, `export PATH="$FULLSEND_RUNNER_PATH${PATH:+:$PATH}"`, runnerPathRestoreLine()) diff --git a/internal/cli/run_image_pull.go b/internal/cli/run_image_pull.go index 17fa189c51..e752287c0c 100644 --- a/internal/cli/run_image_pull.go +++ b/internal/cli/run_image_pull.go @@ -41,9 +41,9 @@ func isGHCRImage(image string) bool { return ok && strings.EqualFold(host, ghcrRegistry) } -// prePullGHCRImage pulls a ghcr.io sandbox image into the runner user's -// Podman store with the Actions workflow token, so harness images published -// as private GitHub packages can be used (#9019). +// prePullGHCRImage pulls a ghcr.io sandbox or mounted image into the runner +// user's Podman store with the Actions workflow token, so private GitHub +// packages can be used (#9019). // // At the pinned OpenShell (0.1.4) the Podman driver pulls the sandbox image // through the libpod API without registry credentials, using the "missing" @@ -59,8 +59,8 @@ func isGHCRImage(image string) bool { // other helpers makes the pull run anonymously; it then fails for a private // image and the warning below is the only trace. // -// It runs only on GitHub Actions, for ghcr.io images, when GH_WORKFLOW_TOKEN -// is set. Failures are warnings: the gateway still attempts its own +// It runs only on GitHub Actions, for ghcr.io sandbox and image_mounts images, +// when GH_WORKFLOW_TOKEN is set. Failures are warnings: the gateway still attempts its own // unauthenticated pull, which keeps public images working as before. func prePullGHCRImage(ctx context.Context, image string, printer *ui.Printer) { if os.Getenv("GITHUB_ACTIONS") != "true" || !isGHCRImage(image) { @@ -71,7 +71,7 @@ func prePullGHCRImage(ctx context.Context, image string, printer *ui.Printer) { return } if _, err := imagePullLookPathFn("podman"); err != nil { - printer.StepWarn("podman not found; the sandbox gateway will pull " + image + " without registry credentials") + printer.StepWarn("podman not found; the OpenShell gateway will pull " + image + " without registry credentials") return } @@ -88,7 +88,7 @@ func prePullGHCRImage(ctx context.Context, image string, printer *ui.Printer) { if detail == "" { detail = err.Error() } - printer.StepWarn(fmt.Sprintf("%s failed: %s; the sandbox gateway will pull %s without registry credentials", + printer.StepWarn(fmt.Sprintf("%s failed: %s; the OpenShell gateway will pull %s without registry credentials", step, strings.ReplaceAll(detail, token, "***"), image)) } @@ -107,10 +107,10 @@ func prePullGHCRImage(ctx context.Context, image string, printer *ui.Printer) { return } - printer.StepStart("Pulling sandbox image with the workflow token: " + image) + printer.StepStart("Pulling image with the workflow token: " + image) if out, err := runPodmanFn(ctx, "pull", "--quiet", "--authfile", authFile, image); err != nil { warn("pulling "+image, out, err) return } - printer.StepDone("Pulled sandbox image " + image) + printer.StepDone("Pulled image " + image) } diff --git a/internal/cli/run_image_pull_test.go b/internal/cli/run_image_pull_test.go index c62dd8110c..1adf0734fb 100644 --- a/internal/cli/run_image_pull_test.go +++ b/internal/cli/run_image_pull_test.go @@ -138,7 +138,7 @@ func TestPrePullGHCRImage_PullsWithRunScopedAuthFile(t *testing.T) { _, err = os.Stat(filepath.Dir(fake.authFiles[0])) assert.True(t, os.IsNotExist(err), "auth directory must be removed after a successful pull") - assert.Contains(t, buf.String(), "Pulled sandbox image") + assert.Contains(t, buf.String(), "Pulled image") assert.NotContains(t, buf.String(), testWorkflowToken) } diff --git a/internal/harness/compose.go b/internal/harness/compose.go index 762485a49b..30fecb8b6c 100644 --- a/internal/harness/compose.go +++ b/internal/harness/compose.go @@ -963,6 +963,10 @@ func mergeBaseIntoChild(base, child *Harness) error { if base.HostFiles != nil { child.HostFiles = mergeHostFiles(base.HostFiles, child.HostFiles) } + // ImageMounts: concatenated with last-writer-wins dedup by Dest + if base.ImageMounts != nil { + child.ImageMounts = mergeImageMounts(base.ImageMounts, child.ImageMounts) + } // RunnerEnv: merge maps, child keys win if base.RunnerEnv != nil { @@ -2843,10 +2847,13 @@ func mergeForgeConfigInto(base, child *ForgeConfig) error { child.OpenShell.Profiles = merged } - // HostFiles: concatenated with last-writer-wins dedup by Dest + // HostFiles and image mounts: concatenated with last-writer-wins dedup by Dest if base.HostFiles != nil { child.HostFiles = mergeHostFiles(base.HostFiles, child.HostFiles) } + if base.ImageMounts != nil { + child.ImageMounts = mergeImageMounts(base.ImageMounts, child.ImageMounts) + } // RunnerEnv: merge, child keys win if base.RunnerEnv != nil { diff --git a/internal/harness/forge.go b/internal/harness/forge.go index f0080641a2..487dea1ee8 100644 --- a/internal/harness/forge.go +++ b/internal/harness/forge.go @@ -23,6 +23,7 @@ type ForgeConfig struct { Providers []string `yaml:"providers,omitempty"` OpenShell *OpenShellConfig `yaml:"openshell,omitempty"` HostFiles []HostFile `yaml:"host_files,omitempty"` + ImageMounts []ImageMount `yaml:"image_mounts,omitempty"` ValidationLoop *ValidationLoop `yaml:"validation_loop,omitempty"` RunnerEnv map[string]string `yaml:"runner_env,omitempty"` Env *EnvConfig `yaml:"env,omitempty"` @@ -125,6 +126,9 @@ func (h *Harness) validateForge() error { return fmt.Errorf("forge.%s.host_files[%d].src must be a local path, not a URL", key, i) } } + if err := validateImageMounts(fc.ImageMounts, fc.HostFiles, fmt.Sprintf("forge.%s.image_mounts", key)); err != nil { + return err + } // Field-level merge inherits script from the top-level loop. topHasScript := h.ValidationLoop != nil && h.ValidationLoop.Script != "" if err := validateValidationLoop(fmt.Sprintf("forge.%s", key), fc.ValidationLoop, topHasScript); err != nil { @@ -206,6 +210,9 @@ func validateOverlayForgeConfigInherit(idx int, fc *ForgeConfig, inheritScript b return fmt.Errorf("%s.host_files[%d].src must be a local path, not a URL", prefix, i) } } + if err := validateImageMounts(fc.ImageMounts, fc.HostFiles, prefix+".image_mounts"); err != nil { + return err + } return validateValidationLoop(prefix, fc.ValidationLoop, inheritScript) } @@ -369,6 +376,7 @@ func (h *Harness) ResolveForge(platform string) error { // - Providers: top-level + forge (concatenated) // - OpenShell.Profiles: top-level + forge (concatenated) // - HostFiles: top-level + forge (concatenated with last-writer-wins dedup by Dest) +// - ImageMounts: top-level + forge (deduplicated by Dest; forge wins) // - RunnerEnv: top-level merged with forge; forge keys win // - ValidationLoop: field-level merge; forge non-zero fields win // @@ -413,6 +421,9 @@ func mergeForgeConfig(h *Harness, fc *ForgeConfig) error { if fc.HostFiles != nil { h.HostFiles = mergeHostFiles(h.HostFiles, fc.HostFiles) } + if fc.ImageMounts != nil { + h.ImageMounts = mergeImageMounts(h.ImageMounts, fc.ImageMounts) + } if fc.RunnerEnv != nil { if h.RunnerEnv == nil { diff --git a/internal/harness/harness.go b/internal/harness/harness.go index 3caef28e53..2c4005e200 100644 --- a/internal/harness/harness.go +++ b/internal/harness/harness.go @@ -89,6 +89,14 @@ type HostFile struct { Optional bool `yaml:"optional,omitempty"` // skip if src path is missing or expands to empty } +// ImageMount describes an OCI image mounted read-only into the sandbox. +// Image is an OCI image reference; Dest is the absolute mount point in the +// sandbox. The mounted image's OCI environment and entrypoint are not applied. +type ImageMount struct { + Image string `yaml:"image"` + Dest string `yaml:"dest"` +} + // ProviderDef is a declarative definition of an OpenShell provider. Files in // the experiment's providers/ directory are loaded as ProviderDefs and // reconciled against the gateway before sandbox creation. @@ -382,6 +390,7 @@ type Harness struct { SchemaVersion *schemaVersionValue `yaml:"schema_version,omitempty"` Base string `yaml:"base,omitempty"` Image string `yaml:"image,omitempty"` + ImageMounts []ImageMount `yaml:"image_mounts,omitempty"` Policy string `yaml:"policy,omitempty"` Skills []SkillEntry `yaml:"skills,omitempty"` Plugins []PluginSpec `yaml:"plugins,omitempty"` // runtime-scoped plugin directories (ADR 0094) @@ -499,6 +508,15 @@ func parseRaw(data []byte) (*Harness, error) { if err := yaml.Unmarshal(data, &h); err != nil { return nil, fmt.Errorf("parsing harness YAML: %w", err) } + h.ImageMounts = mergeImageMounts(nil, h.ImageMounts) + for _, fc := range h.Forge { + if fc != nil { + fc.ImageMounts = mergeImageMounts(nil, fc.ImageMounts) + } + } + for i := range h.Overlays { + h.Overlays[i].ImageMounts = mergeImageMounts(nil, h.Overlays[i].ImageMounts) + } if err := validateSchemaVersion(h.SchemaVersion); err != nil { return nil, fmt.Errorf("parsing harness YAML: %w", err) } @@ -586,6 +604,9 @@ func (h *Harness) Validate() error { return fmt.Errorf("host_files[%d]: %w", i, err) } } + if err := validateImageMounts(h.ImageMounts, h.HostFiles, "image_mounts"); err != nil { + return err + } if h.ValidationLoop != nil && h.ValidationLoop.Script == "" { return fmt.Errorf("validation_loop.script is required when validation_loop is set") } diff --git a/internal/harness/image_mount.go b/internal/harness/image_mount.go new file mode 100644 index 0000000000..678361ce27 --- /dev/null +++ b/internal/harness/image_mount.go @@ -0,0 +1,68 @@ +package harness + +import ( + "fmt" + "path" + "strings" + "unicode" +) + +// mergeImageMounts combines inherited and local image mounts. A later entry +// replaces an earlier entry at the same destination while retaining the +// destination's position in the result. +func mergeImageMounts(base, child []ImageMount) []ImageMount { + indexes := make(map[string]int, len(base)+len(child)) + merged := make([]ImageMount, 0, len(base)+len(child)) + for _, mount := range append(append([]ImageMount(nil), base...), child...) { + if index, ok := indexes[mount.Dest]; ok { + merged[index] = mount + continue + } + indexes[mount.Dest] = len(merged) + merged = append(merged, mount) + } + return merged +} + +func validateImageMounts(mounts []ImageMount, hostFiles []HostFile, field string) error { + for i, mount := range mounts { + prefix := fmt.Sprintf("%s[%d]", field, i) + if mount.Image == "" || strings.TrimSpace(mount.Image) != mount.Image || strings.Contains(mount.Image, "${") || strings.IndexFunc(mount.Image, unicode.IsSpace) >= 0 || strings.Contains(mount.Image, "://") { + return fmt.Errorf("%s.image must be an OCI image reference without whitespace or variable expansion", prefix) + } + if mount.Dest == "" { + return fmt.Errorf("%s.dest is required", prefix) + } + if !path.IsAbs(mount.Dest) { + return fmt.Errorf("%s.dest %q must be an absolute path", prefix, mount.Dest) + } + for _, part := range strings.Split(mount.Dest, "/") { + if part == ".." { + return fmt.Errorf("%s.dest %q must not contain a \"..\" path component", prefix, mount.Dest) + } + } + if path.Clean(mount.Dest) != mount.Dest { + return fmt.Errorf("%s.dest %q must use a clean absolute path", prefix, mount.Dest) + } + if mount.Dest == "/" { + return fmt.Errorf("%s.dest must not replace the container root", prefix) + } + for j, hostFile := range hostFiles { + if pathsOverlap(mount.Dest, hostFile.Dest) { + return fmt.Errorf("%s.dest %q overlaps host_files[%d].dest %q", prefix, mount.Dest, j, hostFile.Dest) + } + } + for j := 0; j < i; j++ { + other := mounts[j] + if mount.Dest != other.Dest && pathsOverlap(mount.Dest, other.Dest) { + return fmt.Errorf("%s.dest %q overlaps %s[%d].dest %q", prefix, mount.Dest, field, j, other.Dest) + } + } + } + return nil +} + +func pathsOverlap(a, b string) bool { + a, b = path.Clean(a), path.Clean(b) + return a == b || strings.HasPrefix(a, b+"/") || strings.HasPrefix(b, a+"/") +} diff --git a/internal/runtime/codex_bootstrap.go b/internal/runtime/codex_bootstrap.go index 3486f32ae0..43e4b97245 100644 --- a/internal/runtime/codex_bootstrap.go +++ b/internal/runtime/codex_bootstrap.go @@ -514,7 +514,7 @@ func codexHooksManifestFor(hooksDir string, hooks security.SandboxHookConfig) *c // means the pinned binary is missing or broken in the image, which is reported // before any iteration rather than as an empty transcript. func codexPreflightVersion(sandboxName string) (string, error) { - stdout, stderr, exitCode, err := sandbox.Exec(sandboxName, "codex --version", 30*time.Second) + stdout, stderr, exitCode, err := sandbox.Exec(sandboxName, sandboxFullsendToolPathCommand("codex --version"), 30*time.Second) if err != nil { return "", fmt.Errorf("codex preflight: %w", err) } diff --git a/internal/runtime/env_data.go b/internal/runtime/env_data.go index 80a6b0fd9a..975c5ba650 100644 --- a/internal/runtime/env_data.go +++ b/internal/runtime/env_data.go @@ -93,6 +93,12 @@ func EnvDataControlLines() []string { return envDataControlLines(sandbox.SandboxWorkspace) } +// sandboxFullsendToolPathCommand runs a fixed runner command with the +// mounted Fullsend tool image ahead of the sandbox's ambient PATH. +func sandboxFullsendToolPathCommand(command string) string { + return "PATH=" + shellQuote(sandbox.SandboxFullsendToolPath) + `${PATH:+:$PATH} ` + command +} + func envDataControlLines(workspace string) []string { iteration := workspace + "/.fullsend/iteration.env" return []string{ @@ -115,9 +121,10 @@ func envDataControlLines(workspace string) []string { // again. const envDataWritableAncestor = `while :; do if test -w "$p" || test -O "$p"; then continue 2; fi; case $p in (/) break ;; esac; p=${p%/*}; p=${p:-/}; done` -// envDataTrustedPath records the launch PATH without the directories the -// agent user can write. It runs before anything the agent wrote is read, so -// the PATH it filters is the runner's. A sandbox image can put an +// envDataTrustedPath records the Fullsend tool-image paths followed by the +// launch PATH, without directories the agent user can write. It runs before +// anything the agent wrote is read, so the PATH it filters is the runner's. +// A sandbox image can put an // agent-owned directory first (a virtualenv's bin, say), so a plain PATH // lookup there finds whatever the agent left. Each entry is recorded as its // physical path (`cd -P`, a builtin), so a symlinked entry is judged by the @@ -128,7 +135,7 @@ const envDataWritableAncestor = `while :; do if test -w "$p" || test -O "$p"; th // only relative and empty entries and missing directories are left out. func envDataTrustedPath() string { return `{ readonly ` + envDataTrustedPathVar + `="$(IFS=:; set -f; s=; ` + - `for d in $PATH; do case $d in (/*) ;; (*) continue ;; esac; if ! test -O /; then ` + + `for d in ` + sandbox.SandboxFullsendToolPath + `:$PATH; do case $d in (/*) ;; (*) continue ;; esac; if ! test -O /; then ` + `d="$(cd -P "$d" 2>/dev/null && pwd -P)" || continue; case $d in (*:*) continue ;; esac; p=$d; ` + envDataWritableAncestor + `; fi; ` + `if test -d "$d"; then printf '%s%s' "$s" "$d"; s=:; fi; done)"; }` } diff --git a/internal/runtime/opencode_bootstrap.go b/internal/runtime/opencode_bootstrap.go index cee3a84acb..dbfca86cef 100644 --- a/internal/runtime/opencode_bootstrap.go +++ b/internal/runtime/opencode_bootstrap.go @@ -427,7 +427,7 @@ func openCodeVerifyAgent(sandboxName, agentName string, r OpenCodeRuntime) error // openCodePreflightVersion runs `opencode --version` so a missing or broken // binary is reported before any iteration, not as an empty transcript. func openCodePreflightVersion(sandboxName string) error { - stdout, stderr, exitCode, err := sandbox.Exec(sandboxName, "opencode --version", 30*time.Second) + stdout, stderr, exitCode, err := sandbox.Exec(sandboxName, sandboxFullsendToolPathCommand("opencode --version"), 30*time.Second) if err != nil { return fmt.Errorf("opencode preflight: %w", err) } diff --git a/internal/runtime/opencode_run.go b/internal/runtime/opencode_run.go index 55efce07ec..a9229b6241 100644 --- a/internal/runtime/opencode_run.go +++ b/internal/runtime/opencode_run.go @@ -321,7 +321,7 @@ func openCodeUtilityPin() string { assignments := make([]string, 0, len(utilities)) individualChecks := make([]string, 0, len(utilities)) for _, utility := range utilities { - assignments = append(assignments, utility.variable+`=$(for d in /usr/local/bin /usr/bin /bin; do if test -x "$d/`+utility.name+`"; then printf '%s' "$d/`+utility.name+`"; break; fi; done)`) + assignments = append(assignments, utility.variable+`=$(for d in `+sandbox.SandboxFullsendLocalBinDir+` `+sandbox.SandboxFullsendBinDir+`; do if test -x "$d/`+utility.name+`"; then printf '%s' "$d/`+utility.name+`"; break; fi; done)`) individualChecks = append(individualChecks, `if ! test -n "$`+utility.variable+`"; then echo 'fullsend: required opencode utility not found: `+utility.name+`' >&2; exit 127; fi`) } diff --git a/internal/runtime/pi_bootstrap.go b/internal/runtime/pi_bootstrap.go index e8fe7ea82e..b2235fa56d 100644 --- a/internal/runtime/pi_bootstrap.go +++ b/internal/runtime/pi_bootstrap.go @@ -838,7 +838,7 @@ func piAgentThinking() string { // run and which vendored provider extension directories the image has: // one line for the binary, then one per existing directory. func piAgentProbeCommand() string { - return "command -v pi; for d in " + shellQuote(piVertexExtensionPath) + " " + shellQuote(piXaiVertexExtensionPath) + + return sandboxFullsendToolPathCommand("command -v pi") + "; for d in " + shellQuote(piVertexExtensionPath) + " " + shellQuote(piXaiVertexExtensionPath) + " " + shellQuote(piInferenceGatewayExtensionPath) + `; do test -d "$d" && echo "$d"; done; true` } @@ -948,7 +948,7 @@ func piHooksManifestFor(hooksDir string, hooks security.SandboxHookConfig) *piHo // the pinned binary is missing or broken in the image, which is reported // before any iteration rather than as an empty transcript. func piPreflightVersion(sandboxName string) (string, error) { - stdout, stderr, exitCode, err := sandbox.Exec(sandboxName, "pi --version", 30*time.Second) + stdout, stderr, exitCode, err := sandbox.Exec(sandboxName, sandboxFullsendToolPathCommand("pi --version"), 30*time.Second) if err != nil { return "", fmt.Errorf("pi preflight: %w", err) } diff --git a/internal/runtime/pi_bootstrap_test.go b/internal/runtime/pi_bootstrap_test.go index 3f38ea05b3..7ab113d319 100644 --- a/internal/runtime/pi_bootstrap_test.go +++ b/internal/runtime/pi_bootstrap_test.go @@ -15,6 +15,7 @@ import ( "github.com/stretchr/testify/require" "github.com/fullsend-ai/fullsend/internal/harness" + "github.com/fullsend-ai/fullsend/internal/sandbox" "github.com/fullsend-ai/fullsend/internal/security" "github.com/fullsend-ai/fullsend/internal/ui" ) @@ -54,7 +55,7 @@ if [ "$2" = "exec" ]; then exit $? ;; "pi --version") echo "0.84.2"; exit 0 ;; ` + hookEnvReadStubArm + ` - "command -v pi"*) printf '%s\n' /usr/bin/pi '/usr/local/share/pi-extensions/anthropic-vertex'; exit 0 ;; + "command -v pi"*) printf '%s\n' /opt/fullsend/usr/bin/pi '/opt/fullsend/usr/local/share/pi-extensions/anthropic-vertex'; exit 0 ;; *usage.jsonl*mv*) u='` + storeDir + `'/` + piFakeUsageFile + `; if [ -f "$u" ]; then cat "$u"; mv -f "$u" "$u.read"; fi; exit 0 ;; cat\ *) f=$(printf '%s' "${last#cat }" | tr -d "'" | tr '/' '_'); cat '` + storeDir + `'/"$f"; exit $? ;; *"--print --mode json"*) cat '` + streamFixture + `'; exit 0 ;; @@ -1146,13 +1147,13 @@ func TestPiAgentTool_OpenAISubagent(t *testing.T) { func TestPiAgentProbeCommand(t *testing.T) { t.Parallel() cmd := piAgentProbeCommand() - assert.True(t, strings.HasPrefix(cmd, "command -v pi"), cmd) + assert.True(t, strings.HasPrefix(cmd, "PATH="+shellQuote(sandbox.SandboxFullsendToolPath)), cmd) assert.Contains(t, cmd, shellQuote(piVertexExtensionPath)) assert.Contains(t, cmd, shellQuote(piXaiVertexExtensionPath)) assert.Contains(t, cmd, `test -d "$d" && echo "$d"`) - bin, exts := parsePiAgentProbe("/usr/bin/pi\n/usr/local/share/pi-extensions/xai-vertex\n") - assert.Equal(t, "/usr/bin/pi", bin) + bin, exts := parsePiAgentProbe("/opt/fullsend/usr/bin/pi\n/opt/fullsend/usr/local/share/pi-extensions/xai-vertex\n") + assert.Equal(t, "/opt/fullsend/usr/bin/pi", bin) assert.Equal(t, []string{piXaiVertexExtensionPath}, exts) bin, exts = parsePiAgentProbe("") assert.Equal(t, "pi", bin, "no probe output (the exec failed silently) falls back to PATH lookup at spawn time") diff --git a/internal/runtime/pi_extension/fullsend-agent.js b/internal/runtime/pi_extension/fullsend-agent.js index d7e820d129..0e72e60903 100644 --- a/internal/runtime/pi_extension/fullsend-agent.js +++ b/internal/runtime/pi_extension/fullsend-agent.js @@ -799,7 +799,7 @@ export function createAgentTool(manifest, { spawn = nodeSpawn, log: rawLog = (m) // travel inside the manifest, so the manifest digest covers them: a // rewrite that drops or edits them is itself a manifest drift, caught // first below. The vendored provider extensions under - // /usr/local/share/pi-extensions carry none on purpose — they are + // /opt/fullsend/usr/local/share/pi-extensions carry none on purpose — they are // root-owned and read-only in the image, outside anything the agent can // write, so there is nothing there to re-check. const extensionDigests = Object.entries(agent.extensionDigests ?? {}).filter( diff --git a/internal/runtime/pi_extension/fullsend-agent.test.mjs b/internal/runtime/pi_extension/fullsend-agent.test.mjs index ccd5d0241d..1603a0570b 100644 --- a/internal/runtime/pi_extension/fullsend-agent.test.mjs +++ b/internal/runtime/pi_extension/fullsend-agent.test.mjs @@ -119,7 +119,7 @@ function fixture() { enabled: true, piBin, sessionsDir: join(dir, "sessions"), - extensions: ["/usr/local/share/pi-extensions/anthropic-vertex", "/usr/local/share/pi-extensions/xai-vertex", "/sandbox/pi-config/fullsend-hooks.js"], + extensions: ["/opt/fullsend/usr/local/share/pi-extensions/anthropic-vertex", "/opt/fullsend/usr/local/share/pi-extensions/xai-vertex", "/sandbox/pi-config/fullsend-hooks.js"], models: { default: "anthropic-vertex/claude-opus-4-6", opus: "anthropic-vertex/claude-opus-4-6", @@ -264,9 +264,9 @@ test("resolveModel: openai under a non-openai parent needs a configured openai c test("resolveModel: gateway under a non-gateway parent is admitted by its listed ids (#8280)", () => { const { manifest } = fixture(); - // The child gets the extension as /usr/local/share/pi-extensions/ + // The child gets the extension as /opt/fullsend/usr/local/share/pi-extensions/ // inference-gateway; its basename is not the provider id it registers. - const extensions = [...manifest.agent.extensions, "/usr/local/share/pi-extensions/inference-gateway"]; + const extensions = [...manifest.agent.extensions, "/opt/fullsend/usr/local/share/pi-extensions/inference-gateway"]; for (const parent of ["google-vertex/gemini-3.8-flash", "openai/gpt-5.6-luna", "anthropic-vertex/claude-opus-4-6"]) { // No gateway list (no inference.gateway block): the provider is not // available, even with the extension on the -e list. @@ -378,8 +378,8 @@ test("childArgs mirrors the runner's pi command line, extensions in manifest ord assert.deepEqual(args, [ "--print", "--mode", "json", "--no-approve", "--no-extensions", "--no-prompt-templates", "--no-themes", "--session-dir", join(manifest.agent.sessionsDir, "agent-3"), - "-e", "/usr/local/share/pi-extensions/anthropic-vertex", - "-e", "/usr/local/share/pi-extensions/xai-vertex", + "-e", "/opt/fullsend/usr/local/share/pi-extensions/anthropic-vertex", + "-e", "/opt/fullsend/usr/local/share/pi-extensions/xai-vertex", "-e", "/sandbox/pi-config/fullsend-hooks.js", "--tools", "read,grep", "--model", "anthropic-vertex/claude-sonnet-4-6", @@ -707,7 +707,7 @@ test("run: a hook adapter rewritten after load stops the next dispatch", async ( ...manifest.agent, // The vendored provider extension carries no digest: it is root-owned // and read-only in the image. Only the config-dir file does. - extensions: ["/usr/local/share/pi-extensions/anthropic-vertex", adapter], + extensions: ["/opt/fullsend/usr/local/share/pi-extensions/anthropic-vertex", adapter], extensionDigests: { [adapter]: createHash("sha256").update(bytes).digest("hex") }, }; const { spawn, children } = fakeSpawn(); diff --git a/internal/runtime/pi_extensions_test.go b/internal/runtime/pi_extensions_test.go index 8af0bdbe6f..eab8ba2f27 100644 --- a/internal/runtime/pi_extensions_test.go +++ b/internal/runtime/pi_extensions_test.go @@ -362,7 +362,7 @@ func TestBuildPiRunCommand_Extensions(t *testing.T) { // -e order: provider extension, hook adapter, edit repair (default tool // set includes edit), then declared extensions in harness order with // their args quoted verbatim after the path. - eList := `-e '/usr/local/share/pi-extensions/anthropic-vertex' -e '/sandbox/pi-config/fullsend-hooks.js' -e '/sandbox/pi-config/fullsend-edit-repair.js' -e '/sandbox/pi-config/extensions/go-diagnostics' -e '/sandbox/pi-config/extensions/pi-fff' '--fff-mode' 'over'\''ride'` + eList := `-e '/opt/fullsend/usr/local/share/pi-extensions/anthropic-vertex' -e '/sandbox/pi-config/fullsend-hooks.js' -e '/sandbox/pi-config/fullsend-edit-repair.js' -e '/sandbox/pi-config/extensions/go-diagnostics' -e '/sandbox/pi-config/extensions/pi-fff' '--fff-mode' 'over'\''ride'` assert.Contains(t, cmd, eList, cmd) // env: exported right before pi, after the runtime's own exports, keys @@ -391,7 +391,7 @@ func TestBuildPiRunCommand_Extensions(t *testing.T) { noHooks := buildPiRunCommand(params, m, exts, "") assert.Contains(t, noHooks, guard) assert.NotContains(t, noHooks, "fullsend-hooks.js") - assert.Contains(t, noHooks, `-e '/usr/local/share/pi-extensions/anthropic-vertex' -e '/sandbox/pi-config/extensions/go-diagnostics'`) + assert.Contains(t, noHooks, `-e '/opt/fullsend/usr/local/share/pi-extensions/anthropic-vertex' -e '/sandbox/pi-config/extensions/go-diagnostics'`) } func TestPiRuntimeBootstrap_Extensions(t *testing.T) { diff --git a/internal/runtime/pi_run_test.go b/internal/runtime/pi_run_test.go index e72f9d00a1..5343dd3132 100644 --- a/internal/runtime/pi_run_test.go +++ b/internal/runtime/pi_run_test.go @@ -110,7 +110,7 @@ func TestBuildPiRunCommand_Basic(t *testing.T) { for _, want := range []string{ "--no-approve", "--no-extensions", "--no-prompt-templates", "--no-themes", "--session-dir '/sandbox/pi-config/sessions'", - "-e '/usr/local/share/pi-extensions/anthropic-vertex'", + "-e '/opt/fullsend/usr/local/share/pi-extensions/anthropic-vertex'", "-e '/sandbox/pi-config/fullsend-hooks.js'", "--tools 'bash'", "--model 'anthropic-vertex/claude-opus-5-5'", @@ -827,7 +827,7 @@ func TestBuildPiRunCommand_DirectProviderKeepsAnthropicEnv(t *testing.T) { assert.Contains(t, cmd, "--model 'anthropic/claude-opus-5-5'") assert.NotContains(t, cmd, "unset ANTHROPIC_API_KEY", "direct Anthropic provider needs its key") assert.NotContains(t, cmd, "GOOGLE_CLOUD_PROJECT") - assert.NotContains(t, cmd, "/usr/local/share/pi-extensions/anthropic-vertex", "the Vertex extension is only loaded for the anthropic-vertex provider") + assert.NotContains(t, cmd, "/opt/fullsend/usr/local/share/pi-extensions/anthropic-vertex", "the Vertex extension is only loaded for the anthropic-vertex provider") } func TestBuildPiRunCommand_HarnessOverridesAndFlags(t *testing.T) { @@ -847,7 +847,7 @@ func TestBuildPiRunCommand_HarnessOverridesAndFlags(t *testing.T) { assert.NotContains(t, cmd, "--no-builtin-tools") assert.NotContains(t, cmd, "fullsend-hooks.js", "no hook extension when the runner has security disabled") assert.NotContains(t, cmd, "pi hook adapter or manifest missing", "and no hook guard") - assert.Contains(t, cmd, "-e '/usr/local/share/pi-extensions/anthropic-vertex'") + assert.Contains(t, cmd, "-e '/opt/fullsend/usr/local/share/pi-extensions/anthropic-vertex'") assert.True(t, strings.HasSuffix(cmd, "'Run the agent task' >'/sandbox/workspace/pi-debug.log'"), cmd) } diff --git a/internal/runtime/testdata/codex/golden/launch-delegating.txt b/internal/runtime/testdata/codex/golden/launch-delegating.txt index 2c10b87e78..a4a0ee199e 100644 --- a/internal/runtime/testdata/codex/golden/launch-delegating.txt +++ b/internal/runtime/testdata/codex/golden/launch-delegating.txt @@ -1,5 +1,5 @@ cd '/sandbox/workspace/repo' && -{ readonly FULLSEND_TRUSTED_PATH="$(IFS=:; set -f; s=; for d in $PATH; do case $d in (/*) ;; (*) continue ;; esac; if ! test -O /; then d="$(cd -P "$d" 2>/dev/null && +{ readonly FULLSEND_TRUSTED_PATH="$(IFS=:; set -f; s=; for d in /opt/fullsend/usr/local/bin:/opt/fullsend/usr/bin:$PATH; do case $d in (/*) ;; (*) continue ;; esac; if ! test -O /; then d="$(cd -P "$d" 2>/dev/null && pwd -P)" || continue; case $d in (*:*) continue ;; esac; p=$d; while :; do if test -w "$p" || test -O "$p"; then continue 2; fi; case $p in (/) break ;; esac; p=${p%/*}; p=${p:-/}; done; fi; if test -d "$d"; then printf '%s%s' "$s" "$d"; s=:; fi; done)"; } && { readonly FULLSEND_READLINK="$(IFS=:; set -f; rl=; for d in $FULLSEND_TRUSTED_PATH; do test -f "$d/readlink" && test -x "$d/readlink" || continue; if test -O /; then rl=$d/readlink; break; fi; if test -h "$d/readlink" || test -w "$d/readlink" || test -O "$d/readlink"; then continue; fi; rl=$d/readlink; break; done; test -n "$rl" || echo 'fullsend: no readlink that is a regular file in a PATH directory the agent cannot write' >&2; printf '%s' "$rl")"; } && diff --git a/internal/runtime/testdata/codex/golden/launch-gateway.txt b/internal/runtime/testdata/codex/golden/launch-gateway.txt index bf27c6513f..f645f8bd06 100644 --- a/internal/runtime/testdata/codex/golden/launch-gateway.txt +++ b/internal/runtime/testdata/codex/golden/launch-gateway.txt @@ -1,5 +1,5 @@ cd '/sandbox/workspace/repo' && -{ readonly FULLSEND_TRUSTED_PATH="$(IFS=:; set -f; s=; for d in $PATH; do case $d in (/*) ;; (*) continue ;; esac; if ! test -O /; then d="$(cd -P "$d" 2>/dev/null && +{ readonly FULLSEND_TRUSTED_PATH="$(IFS=:; set -f; s=; for d in /opt/fullsend/usr/local/bin:/opt/fullsend/usr/bin:$PATH; do case $d in (/*) ;; (*) continue ;; esac; if ! test -O /; then d="$(cd -P "$d" 2>/dev/null && pwd -P)" || continue; case $d in (*:*) continue ;; esac; p=$d; while :; do if test -w "$p" || test -O "$p"; then continue 2; fi; case $p in (/) break ;; esac; p=${p%/*}; p=${p:-/}; done; fi; if test -d "$d"; then printf '%s%s' "$s" "$d"; s=:; fi; done)"; } && { readonly FULLSEND_READLINK="$(IFS=:; set -f; rl=; for d in $FULLSEND_TRUSTED_PATH; do test -f "$d/readlink" && test -x "$d/readlink" || continue; if test -O /; then rl=$d/readlink; break; fi; if test -h "$d/readlink" || test -w "$d/readlink" || test -O "$d/readlink"; then continue; fi; rl=$d/readlink; break; done; test -n "$rl" || echo 'fullsend: no readlink that is a regular file in a PATH directory the agent cannot write' >&2; printf '%s' "$rl")"; } && diff --git a/internal/runtime/testdata/codex/golden/launch-hooks.txt b/internal/runtime/testdata/codex/golden/launch-hooks.txt index 3548bd7780..6d65e4dec1 100644 --- a/internal/runtime/testdata/codex/golden/launch-hooks.txt +++ b/internal/runtime/testdata/codex/golden/launch-hooks.txt @@ -1,5 +1,5 @@ cd '/sandbox/workspace/repo' && -{ readonly FULLSEND_TRUSTED_PATH="$(IFS=:; set -f; s=; for d in $PATH; do case $d in (/*) ;; (*) continue ;; esac; if ! test -O /; then d="$(cd -P "$d" 2>/dev/null && +{ readonly FULLSEND_TRUSTED_PATH="$(IFS=:; set -f; s=; for d in /opt/fullsend/usr/local/bin:/opt/fullsend/usr/bin:$PATH; do case $d in (/*) ;; (*) continue ;; esac; if ! test -O /; then d="$(cd -P "$d" 2>/dev/null && pwd -P)" || continue; case $d in (*:*) continue ;; esac; p=$d; while :; do if test -w "$p" || test -O "$p"; then continue 2; fi; case $p in (/) break ;; esac; p=${p%/*}; p=${p:-/}; done; fi; if test -d "$d"; then printf '%s%s' "$s" "$d"; s=:; fi; done)"; } && { readonly FULLSEND_READLINK="$(IFS=:; set -f; rl=; for d in $FULLSEND_TRUSTED_PATH; do test -f "$d/readlink" && test -x "$d/readlink" || continue; if test -O /; then rl=$d/readlink; break; fi; if test -h "$d/readlink" || test -w "$d/readlink" || test -O "$d/readlink"; then continue; fi; rl=$d/readlink; break; done; test -n "$rl" || echo 'fullsend: no readlink that is a regular file in a PATH directory the agent cannot write' >&2; printf '%s' "$rl")"; } && diff --git a/internal/runtime/testdata/codex/golden/launch-nohooks.txt b/internal/runtime/testdata/codex/golden/launch-nohooks.txt index e2024b8b4d..858ff57351 100644 --- a/internal/runtime/testdata/codex/golden/launch-nohooks.txt +++ b/internal/runtime/testdata/codex/golden/launch-nohooks.txt @@ -1,5 +1,5 @@ cd '/sandbox/workspace/repo' && -{ readonly FULLSEND_TRUSTED_PATH="$(IFS=:; set -f; s=; for d in $PATH; do case $d in (/*) ;; (*) continue ;; esac; if ! test -O /; then d="$(cd -P "$d" 2>/dev/null && +{ readonly FULLSEND_TRUSTED_PATH="$(IFS=:; set -f; s=; for d in /opt/fullsend/usr/local/bin:/opt/fullsend/usr/bin:$PATH; do case $d in (/*) ;; (*) continue ;; esac; if ! test -O /; then d="$(cd -P "$d" 2>/dev/null && pwd -P)" || continue; case $d in (*:*) continue ;; esac; p=$d; while :; do if test -w "$p" || test -O "$p"; then continue 2; fi; case $p in (/) break ;; esac; p=${p%/*}; p=${p:-/}; done; fi; if test -d "$d"; then printf '%s%s' "$s" "$d"; s=:; fi; done)"; } && { readonly FULLSEND_READLINK="$(IFS=:; set -f; rl=; for d in $FULLSEND_TRUSTED_PATH; do test -f "$d/readlink" && test -x "$d/readlink" || continue; if test -O /; then rl=$d/readlink; break; fi; if test -h "$d/readlink" || test -w "$d/readlink" || test -O "$d/readlink"; then continue; fi; rl=$d/readlink; break; done; test -n "$rl" || echo 'fullsend: no readlink that is a regular file in a PATH directory the agent cannot write' >&2; printf '%s' "$rl")"; } && diff --git a/internal/sandbox/sandbox.go b/internal/sandbox/sandbox.go index 895590e876..bccd512d76 100644 --- a/internal/sandbox/sandbox.go +++ b/internal/sandbox/sandbox.go @@ -28,6 +28,17 @@ import ( ) const ( + // SandboxFullsendRoot is the mount point for the Fullsend tool image. Its + // root filesystem is mounted here read-only. + SandboxFullsendRoot = "/opt/fullsend" + // SandboxFullsendLocalBinDir holds the Fullsend sandbox's pinned CLIs and + // scanners when its image root is mounted at SandboxFullsendRoot. + SandboxFullsendLocalBinDir = SandboxFullsendRoot + "/usr/local/bin" + // SandboxFullsendBinDir holds system tools from the mounted image. + SandboxFullsendBinDir = SandboxFullsendRoot + "/usr/bin" + // SandboxFullsendToolPath is prepended to PATH so runner-pinned tools + // resolve from the mounted tool image before project-image commands. + SandboxFullsendToolPath = SandboxFullsendLocalBinDir + ":" + SandboxFullsendBinDir // SandboxWorkspace is the workspace directory inside the sandbox. SandboxWorkspace = "/sandbox/workspace" //nolint:gosec // not a credential // SandboxClaudeConfig is the Claude config directory inside the sandbox. @@ -54,7 +65,7 @@ const ( // sandbox image (images/sandbox/Containerfile), root-owned and outside // PI_CODING_AGENT_DIR so pi never auto-loads them; PiRuntime.Run passes // each one explicitly with -e. - SandboxPiExtensionsDir = "/usr/local/share/pi-extensions" + SandboxPiExtensionsDir = SandboxFullsendRoot + "/usr/local/share/pi-extensions" // SandboxOpenCodeConfig is the OpenCode config directory inside the // sandbox. Exported as OPENCODE_CONFIG_DIR (OpenCodeRuntime.EnvExports). // Outside the cloned repo tree, like SandboxClaudeConfig and @@ -1425,8 +1436,14 @@ func effectiveReadyTimeout(override time.Duration) time.Duration { // Create creates a persistent OpenShell sandbox and waits for it to be ready. // It retries up to DefaultMaxCreateAttempts times with exponential backoff, // deleting the failed sandbox between attempts. -func Create(name string, providers []string, image, policy string) error { - return CreateWithRetry(name, providers, image, policy, DefaultMaxCreateAttempts, 0, false) +func Create(name string, providers []string, image, policy string, imageMounts ...ImageMount) error { + return CreateWithRetry(name, providers, image, policy, DefaultMaxCreateAttempts, 0, false, imageMounts...) +} + +// ImageMount is an OCI image mounted read-only into a Podman-backed sandbox. +type ImageMount struct { + Source string // OCI image reference + Target string // absolute mount destination inside the sandbox } // CreateWithRetry creates a sandbox, retrying up to maxAttempts times with @@ -1437,7 +1454,7 @@ func Create(name string, providers []string, image, policy string) error { // If keep is true (--keep-sandbox), a failed attempt is neither deleted nor // retried: retrying would require deleting the sandbox under the same name, // which destroys the state the caller asked to keep for inspection. -func CreateWithRetry(name string, providers []string, image, policy string, maxAttempts int, readyTimeoutOverride time.Duration, keep bool) error { +func CreateWithRetry(name string, providers []string, image, policy string, maxAttempts int, readyTimeoutOverride time.Duration, keep bool, imageMounts ...ImageMount) error { if maxAttempts < 1 { return fmt.Errorf("maxAttempts must be >= 1, got %d", maxAttempts) } @@ -1446,7 +1463,7 @@ func CreateWithRetry(name string, providers []string, image, policy string, maxA var lastErr error for attempt := 1; attempt <= maxAttempts; attempt++ { - lastErr = createOnce(name, providers, image, policy, timeout) + lastErr = createOnce(name, providers, image, policy, timeout, imageMounts...) if lastErr == nil { return nil } @@ -1529,11 +1546,29 @@ func terminalSandboxPhase(output string) string { return "" } +// podmanDriverConfig carries the per-sandbox settings understood by the +// OpenShell Podman backend. +type podmanDriverConfig struct { + Podman podmanDriverSettings `json:"podman"` +} + +type podmanDriverSettings struct { + Mounts []podmanImageMount `json:"mounts"` +} + +type podmanImageMount struct { + Type string `json:"type"` + Source string `json:"source"` + Target string `json:"target"` + ReadOnly bool `json:"read_only"` +} + // createOnce creates a persistent OpenShell sandbox and waits for it to be // ready. If providers are given, they are passed as --provider flags. If image // is non-empty, it is passed as --from to start the sandbox from a container // image. If policy is non-empty, it is applied at creation time via --policy. -func createOnce(name string, providers []string, image, policy string, timeout time.Duration) error { +// Image mounts are passed as read-only Podman driver configuration. +func createOnce(name string, providers []string, image, policy string, timeout time.Duration, imageMounts ...ImageMount) error { ctx, cancel := context.WithTimeout(context.Background(), timeout+readyCtxBuffer) defer cancel() @@ -1550,6 +1585,22 @@ func createOnce(name string, providers []string, image, policy string, timeout t if policy != "" { args = append(args, "--policy", policy) } + if len(imageMounts) > 0 { + mounts := make([]podmanImageMount, 0, len(imageMounts)) + for _, mount := range imageMounts { + mounts = append(mounts, podmanImageMount{ + Type: "image", + Source: mount.Source, + Target: mount.Target, + ReadOnly: true, + }) + } + config, err := json.Marshal(podmanDriverConfig{Podman: podmanDriverSettings{Mounts: mounts}}) + if err != nil { + return fmt.Errorf("encoding Podman image mounts: %w", err) + } + args = append(args, "--driver-config-json", string(config)) + } for _, p := range providers { args = append(args, "--provider", p) } diff --git a/internal/scaffold/fullsend-repo/scripts/fullsend-check-output b/internal/scaffold/fullsend-repo/scripts/fullsend-check-output index 6b10e05fe3..80ed6d896f 100755 --- a/internal/scaffold/fullsend-repo/scripts/fullsend-check-output +++ b/internal/scaffold/fullsend-repo/scripts/fullsend-check-output @@ -18,6 +18,16 @@ set -euo pipefail +# Use Fullsend's mounted Python and its bundled schema dependencies. +fullsend_python() ( + unset PYTHONHOME PYTHONPATH PYTHONUSERBASE PYTHONSTARTUP PYTHONINSPECT + + PYTHONHOME=/opt/fullsend/usr \ + PYTHONPATH=/opt/fullsend/usr/local/share/fullsend/python/site-packages \ + PYTHONNOUSERSITE=1 \ + /opt/fullsend/usr/bin/python3 "$@" +) + if [[ $# -lt 1 ]]; then echo "Usage: fullsend-check-output " exit 1 @@ -48,22 +58,22 @@ if [[ "${_actual}" != "${_expected}" ]]; then exit 1 fi -if ! python3 -c "import jsonschema" 2>/dev/null; then - echo "FAIL: python3 jsonschema package is not installed" +if ! fullsend_python -c "import jsonschema" 2>/dev/null; then + echo "FAIL: mounted Fullsend Python or its jsonschema dependencies are unavailable" exit 1 fi -if ! python3 -m json.tool "${CANDIDATE}" > /dev/null 2>&1; then +if ! fullsend_python -m json.tool "${CANDIDATE}" > /dev/null 2>&1; then echo "FAIL: ${CANDIDATE} is not valid JSON" exit 1 fi -if ! python3 -m json.tool "${FULLSEND_OUTPUT_SCHEMA}" > /dev/null 2>&1; then +if ! fullsend_python -m json.tool "${FULLSEND_OUTPUT_SCHEMA}" > /dev/null 2>&1; then echo "FAIL: schema file is not valid JSON: ${FULLSEND_OUTPUT_SCHEMA}" exit 1 fi -python3 -c " +fullsend_python -c " import json, sys from jsonschema import validate, ValidationError, SchemaError From 2fee05fe95ba5f702189648bcf33d8f867f68f24 Mon Sep 17 00:00:00 2001 From: Ralph Bean Date: Thu, 12 Nov 2026 19:40:35 -0500 Subject: [PATCH 2/9] fix(runtime): resolve Fullsend paths and legacy sandbox assets Signed-off-by: Ralph Bean --- internal/cli/run_env_path_test.go | 2 +- internal/runtime/codex_bootstrap_test.go | 4 +-- internal/runtime/env_data.go | 3 +- internal/runtime/env_data_test.go | 2 +- internal/runtime/opencode_bootstrap_test.go | 2 +- internal/runtime/opencode_run.go | 15 +++++++- internal/runtime/opencode_test.go | 18 +++++++--- internal/runtime/pi.go | 9 +++++ internal/runtime/pi_bootstrap.go | 15 +++++--- internal/runtime/pi_bootstrap_test.go | 15 +++++--- internal/runtime/pi_extensions_test.go | 4 +-- internal/runtime/pi_gateway_run.go | 2 +- internal/runtime/pi_gateway_run_test.go | 6 ++-- internal/runtime/pi_run.go | 31 +++++++++++++--- internal/runtime/pi_run_test.go | 35 ++++++++++++++----- internal/runtime/pi_test.go | 2 +- .../codex/golden/launch-delegating.txt | 2 +- .../testdata/codex/golden/launch-gateway.txt | 2 +- .../testdata/codex/golden/launch-hooks.txt | 2 +- .../testdata/codex/golden/launch-nohooks.txt | 2 +- internal/sandbox/sandbox_claude_image_test.go | 4 +-- internal/sandbox/sandbox_codex_image_test.go | 4 +-- internal/sandbox/sandbox_pi_image_test.go | 4 ++- internal/scaffold/scaffold_test.go | 3 ++ 24 files changed, 138 insertions(+), 50 deletions(-) diff --git a/internal/cli/run_env_path_test.go b/internal/cli/run_env_path_test.go index a1c13f0255..ac3070344c 100644 --- a/internal/cli/run_env_path_test.go +++ b/internal/cli/run_env_path_test.go @@ -168,7 +168,7 @@ func TestEnvFilePath_EnvDCannotShadowRunnerPath(t *testing.T) { require.NotEqual(t, -1, sysAt, printed) require.NotEqual(t, -1, binAt, printed) assert.Less(t, sysAt, binAt, "workspace bin comes after the image PATH") - assert.True(t, strings.HasPrefix(printed, "PATH=/usr/local/go/bin:"), "runner PATH comes first: %s", printed) + assert.True(t, strings.HasPrefix(printed, "PATH="+sandbox.SandboxFullsendToolPath+":/usr/local/go/bin:"), "runner PATH comes first: %s", printed) } }) } diff --git a/internal/runtime/codex_bootstrap_test.go b/internal/runtime/codex_bootstrap_test.go index 97336dfe42..1b5eb4ccb9 100644 --- a/internal/runtime/codex_bootstrap_test.go +++ b/internal/runtime/codex_bootstrap_test.go @@ -67,7 +67,7 @@ if [ "$2" = "exec" ]; then "test -f '/tmp/fs-upload-"*) sh -c 'mkdir() { :; }; mv() { shift; shift; cp -- "$1" '\''` + storeDir + `/'\''"$(printf "%s" "$2" | tr / _)"; }; '"$last" exit $? ;; - "codex --version") echo "` + versionOutput + `"; exit 0 ;; + *"codex --version"*) echo "` + versionOutput + `"; exit 0 ;; "codex debug models --bundled") cat "${FULLSEND_TEST_CATALOG:-testdata/codex/models-bundled-0.166.0.json}"; exit 0 ;; *"` + hookInterpreterSep + `"*) printf '%s` + hookInterpreterSep + `%s\n' /usr/bin/python3 /usr/local/bin:/usr/bin:/bin; exit 0 ;; # What a plain PATH lookup finds in the fleet image; Bootstrap must not use it. @@ -299,7 +299,7 @@ func TestCodexRuntimeBootstrap_PreflightFailureIsReportedEarly(t *testing.T) { if [ "$2" = "exec" ]; then for last; do :; done case "$last" in - "codex --version") echo "codex: command not found" >&2; exit 127 ;; + *"codex --version"*) echo "codex: command not found" >&2; exit 127 ;; esac fi exit 0 diff --git a/internal/runtime/env_data.go b/internal/runtime/env_data.go index 975c5ba650..be61516b7d 100644 --- a/internal/runtime/env_data.go +++ b/internal/runtime/env_data.go @@ -135,7 +135,8 @@ const envDataWritableAncestor = `while :; do if test -w "$p" || test -O "$p"; th // only relative and empty entries and missing directories are left out. func envDataTrustedPath() string { return `{ readonly ` + envDataTrustedPathVar + `="$(IFS=:; set -f; s=; ` + - `for d in ` + sandbox.SandboxFullsendToolPath + `:$PATH; do case $d in (/*) ;; (*) continue ;; esac; if ! test -O /; then ` + + `fullsend_path='` + sandbox.SandboxFullsendToolPath + `'; paths=$fullsend_path${PATH:+:$PATH}; ` + + `for d in $paths; do case $d in (/*) ;; (*) continue ;; esac; if ! test -O /; then ` + `d="$(cd -P "$d" 2>/dev/null && pwd -P)" || continue; case $d in (*:*) continue ;; esac; p=$d; ` + envDataWritableAncestor + `; fi; ` + `if test -d "$d"; then printf '%s%s' "$s" "$d"; s=:; fi; done)"; }` } diff --git a/internal/runtime/env_data_test.go b/internal/runtime/env_data_test.go index ba60fcd247..3bd4441eba 100644 --- a/internal/runtime/env_data_test.go +++ b/internal/runtime/env_data_test.go @@ -15,7 +15,7 @@ import ( // piEnvLoad, codexEnvLoad and openCodeEnvLoad are the .env reads the pi, // codex and OpenCode launches emit where they used to source the file. var ( - piEnvLoad = envDataLoad(sandbox.SandboxWorkspace+"/.env", piBinaryVar, piNodeVar, piHookPythonEnv, piHookPathEnv, piChildBinEnv, piChildNodeEnv) + piEnvLoad = envDataLoad(sandbox.SandboxWorkspace+"/.env", piBinaryVar, piNodeVar, piVertexExtensionVar, piXaiVertexExtensionVar, piGatewayExtensionVar, piHookPythonEnv, piHookPathEnv, piChildBinEnv, piChildNodeEnv) codexEnvLoad = envDataLoad(sandbox.SandboxWorkspace+"/.env", codexBinaryVar, codexNodeVar, codexPathVar) openCodeEnvLoad = envDataLoad(sandbox.SandboxWorkspace+"/.env", openCodeEnvDataDrop...) ) diff --git a/internal/runtime/opencode_bootstrap_test.go b/internal/runtime/opencode_bootstrap_test.go index 941b095eb9..1abb5b44b9 100644 --- a/internal/runtime/opencode_bootstrap_test.go +++ b/internal/runtime/opencode_bootstrap_test.go @@ -311,7 +311,7 @@ func TestOpenCodePreflightVersionFailure(t *testing.T) { if [ "$2" = "exec" ]; then for last; do :; done case "$last" in - "opencode --version") echo "boom" >&2; exit 1 ;; + *"opencode --version"*) echo "boom" >&2; exit 1 ;; esac exit 0 fi diff --git a/internal/runtime/opencode_run.go b/internal/runtime/opencode_run.go index a9229b6241..9bc9f4e56b 100644 --- a/internal/runtime/opencode_run.go +++ b/internal/runtime/opencode_run.go @@ -306,6 +306,15 @@ func openCodeBinaryPin() string { const openCodeCloudLocationExport = `{ _gcl="${GOOGLE_CLOUD_LOCATION:-$CLOUD_ML_REGION}"; [ -n "$_gcl" ] && export GOOGLE_CLOUD_LOCATION="$_gcl" || unset GOOGLE_CLOUD_LOCATION; }` func openCodeUtilityPin() string { + return openCodeUtilityPinFromDirs( + sandbox.SandboxFullsendLocalBinDir, + sandbox.SandboxFullsendBinDir, + "/usr/local/bin", + "/usr/bin", + ) +} + +func openCodeUtilityPinFromDirs(dirs ...string) string { utilities := []struct { variable string name string @@ -321,7 +330,11 @@ func openCodeUtilityPin() string { assignments := make([]string, 0, len(utilities)) individualChecks := make([]string, 0, len(utilities)) for _, utility := range utilities { - assignments = append(assignments, utility.variable+`=$(for d in `+sandbox.SandboxFullsendLocalBinDir+` `+sandbox.SandboxFullsendBinDir+`; do if test -x "$d/`+utility.name+`"; then printf '%s' "$d/`+utility.name+`"; break; fi; done)`) + quotedDirs := make([]string, 0, len(dirs)) + for _, dir := range dirs { + quotedDirs = append(quotedDirs, shellQuote(dir)) + } + assignments = append(assignments, utility.variable+`=$(for d in `+strings.Join(quotedDirs, " ")+`; do if test -x "$d/`+utility.name+`"; then printf '%s' "$d/`+utility.name+`"; break; fi; done)`) individualChecks = append(individualChecks, `if ! test -n "$`+utility.variable+`"; then echo 'fullsend: required opencode utility not found: `+utility.name+`' >&2; exit 127; fi`) } diff --git a/internal/runtime/opencode_test.go b/internal/runtime/opencode_test.go index f04fa5d86d..c51842546a 100644 --- a/internal/runtime/opencode_test.go +++ b/internal/runtime/opencode_test.go @@ -438,7 +438,7 @@ func TestOpenCodeLaunch_HostileEnvDoesNotExecute(t *testing.T) { trusted := openCodeTrustedEnv{ConfigContent: `{"permission":{"*":"deny"}}`, CredentialsPath: "/runner/adc.json"} script := strings.Join([]string{ openCodeBinaryPin(), - openCodeUtilityPin(), + openCodeTestUtilityPin(), openCodeTrustedEnvPin(trusted), envDataLoadWith(f.envFile, control, openCodeEnvDataDrop), strings.Join(OpenCodeRuntime{}.EnvExports(), " && "), @@ -502,12 +502,19 @@ func requirePinnedSha256sum(t *testing.T) { t.Skip("no sha256sum in the pinned utility directories") } +// Unit tests execute the generated pin on the host, where the sandbox's +// /opt/fullsend tree is absent. Keep the generated command identical except +// that its utility search uses the host's standard binary directories. +func openCodeTestUtilityPin() string { + return openCodeUtilityPinFromDirs("/usr/local/bin", "/usr/bin", "/bin") +} + func TestOpenCodeExitPipeline(t *testing.T) { requirePinnedSha256sum(t) rcFile := filepath.Join(t.TempDir(), "run-rc") transcript := filepath.Join(t.TempDir(), "output.jsonl") shadow := `command() { printf FAKE; }; printf() { :; }; tee() { :; }; cat() { printf 0; }; ` - command := openCodeUtilityPin() + " && " + shadow + openCodeExitPipeline( + command := openCodeTestUtilityPin() + " && " + shadow + openCodeExitPipeline( []string{"/bin/sh", "-c", shellQuote("command -p printf real-output; exit 7")}, rcFile, transcript, @@ -526,7 +533,7 @@ func TestOpenCodeHooksGuardUsesUnshadowableCommands(t *testing.T) { requirePinnedSha256sum(t) missing := filepath.Join(t.TempDir(), "missing-hooks.ts") shadow := `command() { return 0; }; test() { return 0; }; printf() { return 0; }; sha256sum() { return 0; }; cut() { return 0; }; ` - cmd := exec.Command("sh", "-c", openCodeUtilityPin()+" && "+shadow+openCodeHooksGuard(missing)) + cmd := exec.Command("sh", "-c", openCodeTestUtilityPin()+" && "+shadow+openCodeHooksGuard(missing)) err := cmd.Run() var exitErr *exec.ExitError require.ErrorAs(t, err, &exitErr) @@ -638,7 +645,8 @@ func TestOpenCodeTrustedEnvReadCommand(t *testing.T) { "export GOOGLE_APPLICATION_CREDENTIALS=" + shellQuote(want.CredentialsPath) + "\n" require.NoError(t, os.WriteFile(envFile, []byte(content), 0o644)) - cmd := exec.Command("sh", "-c", openCodeTrustedEnvReadCommand(envFile)) + command := strings.ReplaceAll(openCodeTrustedEnvReadCommand(envFile), openCodeUtilityPin(), openCodeTestUtilityPin()) + cmd := exec.Command("sh", "-c", command) var stderr strings.Builder cmd.Stderr = &stderr out, err := cmd.Output() @@ -776,7 +784,7 @@ func TestOpenCodeAgentGuard(t *testing.T) { require.NoError(t, os.WriteFile(agent, []byte("trusted"), 0o644)) for content, want := range map[string]int{"trusted": 0, "tampered": openCodeAgentModifiedExit} { require.NoError(t, os.WriteFile(agent, []byte(content), 0o644)) - cmd := exec.Command("sh", "-c", openCodeUtilityPin()+" && "+openCodeAgentGuard(agent, "trusted")) + cmd := exec.Command("sh", "-c", openCodeTestUtilityPin()+" && "+openCodeAgentGuard(agent, "trusted")) cmd.Env = []string{"PATH=/usr/bin:/bin"} err := cmd.Run() got := 0 diff --git a/internal/runtime/pi.go b/internal/runtime/pi.go index 348dccfa9e..2e634fae5e 100644 --- a/internal/runtime/pi.go +++ b/internal/runtime/pi.go @@ -40,6 +40,15 @@ type PiRuntime struct{} // #5262 ships in a pinned pi release. const piVertexExtensionPath = sandbox.SandboxPiExtensionsDir + "/anthropic-vertex" +// Legacy extension paths keep the runner compatible with the currently +// published sandbox image while its Fullsend tool tree moves under +// /opt/fullsend. New images always prefer the paths above. +const ( + piLegacyVertexExtensionPath = "/usr/local/share/pi-extensions/anthropic-vertex" + piLegacyXaiVertexExtensionPath = "/usr/local/share/pi-extensions/xai-vertex" + piLegacyGatewayExtensionPath = "/usr/local/share/pi-extensions/inference-gateway" +) + // piXaiVertexExtensionPath is the Grok-on-Vertex provider for pi // (fullsend-ai/pi-xai-vertex, pinned in the sandbox image by // PI_XAI_VERTEX_VERSION). Grok on Vertex speaks the OpenAI-completions diff --git a/internal/runtime/pi_bootstrap.go b/internal/runtime/pi_bootstrap.go index b2235fa56d..b474b03c54 100644 --- a/internal/runtime/pi_bootstrap.go +++ b/internal/runtime/pi_bootstrap.go @@ -838,9 +838,15 @@ func piAgentThinking() string { // run and which vendored provider extension directories the image has: // one line for the binary, then one per existing directory. func piAgentProbeCommand() string { - return sandboxFullsendToolPathCommand("command -v pi") + "; for d in " + shellQuote(piVertexExtensionPath) + " " + shellQuote(piXaiVertexExtensionPath) + - " " + shellQuote(piInferenceGatewayExtensionPath) + - `; do test -d "$d" && echo "$d"; done; true` + return sandboxFullsendToolPathCommand("command -v pi") + "; " + + piAgentProbeExtension(piVertexExtensionPath, piLegacyVertexExtensionPath) + "; " + + piAgentProbeExtension(piXaiVertexExtensionPath, piLegacyXaiVertexExtensionPath) + "; " + + piAgentProbeExtension(piInferenceGatewayExtensionPath, piLegacyGatewayExtensionPath) + "; true" +} + +func piAgentProbeExtension(primary, legacy string) string { + return "for d in " + shellQuote(primary) + " " + shellQuote(legacy) + + `; do if test -d "$d"; then echo "$d"; break; fi; done` } // parsePiAgentProbe reads the probe output. Only the known provider @@ -857,7 +863,8 @@ func parsePiAgentProbe(stdout string) (piBin string, exts []string) { line = strings.TrimSpace(sanitizeOutput(line)) switch { case line == "": - case line == piVertexExtensionPath || line == piXaiVertexExtensionPath || line == piInferenceGatewayExtensionPath: + case line == piVertexExtensionPath || line == piXaiVertexExtensionPath || line == piInferenceGatewayExtensionPath || + line == piLegacyVertexExtensionPath || line == piLegacyXaiVertexExtensionPath || line == piLegacyGatewayExtensionPath: // When `command -v pi` printed nothing the first line is an // extension path; never mistake it for the binary. exts = append(exts, line) diff --git a/internal/runtime/pi_bootstrap_test.go b/internal/runtime/pi_bootstrap_test.go index 7ab113d319..8584124c5a 100644 --- a/internal/runtime/pi_bootstrap_test.go +++ b/internal/runtime/pi_bootstrap_test.go @@ -53,9 +53,9 @@ if [ "$2" = "exec" ]; then "test -f '/tmp/fs-upload-"*) sh -c 'mkdir() { :; }; mv() { shift; shift; cp -- "$1" '\''` + storeDir + `/'\''"$(printf "%s" "$2" | tr / _)"; }; '"$last" exit $? ;; - "pi --version") echo "0.84.2"; exit 0 ;; + *"pi --version"*) echo "0.84.2"; exit 0 ;; ` + hookEnvReadStubArm + ` - "command -v pi"*) printf '%s\n' /opt/fullsend/usr/bin/pi '/opt/fullsend/usr/local/share/pi-extensions/anthropic-vertex'; exit 0 ;; + *"command -v pi"*) printf '%s\n' /opt/fullsend/usr/bin/pi '/opt/fullsend/usr/local/share/pi-extensions/anthropic-vertex'; exit 0 ;; *usage.jsonl*mv*) u='` + storeDir + `'/` + piFakeUsageFile + `; if [ -f "$u" ]; then cat "$u"; mv -f "$u" "$u.read"; fi; exit 0 ;; cat\ *) f=$(printf '%s' "${last#cat }" | tr -d "'" | tr '/' '_'); cat '` + storeDir + `'/"$f"; exit $? ;; *"--print --mode json"*) cat '` + streamFixture + `'; exit 0 ;; @@ -252,7 +252,7 @@ func TestPiRuntimeBootstrap_AgentNameMatch(t *testing.T) { func TestPiRuntimeBootstrap_PreflightFailure(t *testing.T) { binDir := t.TempDir() - script := "#!/bin/sh\nfor last; do :; done\ncase \"$last\" in \"pi --version\") echo 'sh: pi: not found' >&2; exit 127 ;; esac\nexit 0\n" + script := "#!/bin/sh\nfor last; do :; done\ncase \"$last\" in *\"pi --version\"*) echo 'sh: pi: not found' >&2; exit 127 ;; esac\nexit 0\n" require.NoError(t, os.WriteFile(filepath.Join(binDir, "openshell"), []byte(script), 0o755)) t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH")) @@ -800,7 +800,7 @@ func TestPiAgentTool_ManifestBlock(t *testing.T) { m, store, appendSystem := bootstrap(t, "---\nname: review\nmodel: opus\n---\nReview the PR.", true) require.NotNil(t, m.Agent) assert.True(t, m.Agent.Enabled) - assert.Equal(t, "/usr/bin/pi", m.Agent.PiBin, "resolved by the sandbox probe") + assert.Equal(t, "/opt/fullsend/usr/bin/pi", m.Agent.PiBin, "resolved by the sandbox probe") assert.Equal(t, cfg+"/sessions", m.Agent.SessionsDir) assert.Equal(t, []string{piVertexExtensionPath, cfg + "/fullsend-hooks.js"}, m.Agent.Extensions, "only the provider extensions the image has (the probe found anthropic-vertex, not xai-vertex), then the hook adapter") @@ -1150,11 +1150,16 @@ func TestPiAgentProbeCommand(t *testing.T) { assert.True(t, strings.HasPrefix(cmd, "PATH="+shellQuote(sandbox.SandboxFullsendToolPath)), cmd) assert.Contains(t, cmd, shellQuote(piVertexExtensionPath)) assert.Contains(t, cmd, shellQuote(piXaiVertexExtensionPath)) - assert.Contains(t, cmd, `test -d "$d" && echo "$d"`) + assert.Contains(t, cmd, `if test -d "$d"; then echo "$d"; break; fi`) + assert.Contains(t, cmd, shellQuote(piLegacyVertexExtensionPath)) + assert.Less(t, strings.Index(cmd, shellQuote(piVertexExtensionPath)), strings.Index(cmd, shellQuote(piLegacyVertexExtensionPath)), + "the relocated image tree takes precedence over the legacy image path") bin, exts := parsePiAgentProbe("/opt/fullsend/usr/bin/pi\n/opt/fullsend/usr/local/share/pi-extensions/xai-vertex\n") assert.Equal(t, "/opt/fullsend/usr/bin/pi", bin) assert.Equal(t, []string{piXaiVertexExtensionPath}, exts) + _, exts = parsePiAgentProbe("/usr/bin/pi\n" + piLegacyVertexExtensionPath + "\n" + piLegacyGatewayExtensionPath + "\n") + assert.Equal(t, []string{piLegacyVertexExtensionPath, piLegacyGatewayExtensionPath}, exts) bin, exts = parsePiAgentProbe("") assert.Equal(t, "pi", bin, "no probe output (the exec failed silently) falls back to PATH lookup at spawn time") assert.Empty(t, exts) diff --git a/internal/runtime/pi_extensions_test.go b/internal/runtime/pi_extensions_test.go index eab8ba2f27..871b2158c4 100644 --- a/internal/runtime/pi_extensions_test.go +++ b/internal/runtime/pi_extensions_test.go @@ -362,7 +362,7 @@ func TestBuildPiRunCommand_Extensions(t *testing.T) { // -e order: provider extension, hook adapter, edit repair (default tool // set includes edit), then declared extensions in harness order with // their args quoted verbatim after the path. - eList := `-e '/opt/fullsend/usr/local/share/pi-extensions/anthropic-vertex' -e '/sandbox/pi-config/fullsend-hooks.js' -e '/sandbox/pi-config/fullsend-edit-repair.js' -e '/sandbox/pi-config/extensions/go-diagnostics' -e '/sandbox/pi-config/extensions/pi-fff' '--fff-mode' 'over'\''ride'` + eList := `-e "$` + piVertexExtensionVar + `" -e '/sandbox/pi-config/fullsend-hooks.js' -e '/sandbox/pi-config/fullsend-edit-repair.js' -e '/sandbox/pi-config/extensions/go-diagnostics' -e '/sandbox/pi-config/extensions/pi-fff' '--fff-mode' 'over'\''ride'` assert.Contains(t, cmd, eList, cmd) // env: exported right before pi, after the runtime's own exports, keys @@ -391,7 +391,7 @@ func TestBuildPiRunCommand_Extensions(t *testing.T) { noHooks := buildPiRunCommand(params, m, exts, "") assert.Contains(t, noHooks, guard) assert.NotContains(t, noHooks, "fullsend-hooks.js") - assert.Contains(t, noHooks, `-e '/opt/fullsend/usr/local/share/pi-extensions/anthropic-vertex' -e '/sandbox/pi-config/extensions/go-diagnostics'`) + assert.Contains(t, noHooks, `-e "$`+piVertexExtensionVar+`" -e '/sandbox/pi-config/extensions/go-diagnostics'`) } func TestPiRuntimeBootstrap_Extensions(t *testing.T) { diff --git a/internal/runtime/pi_gateway_run.go b/internal/runtime/pi_gateway_run.go index 35639037bd..517eeeacb1 100644 --- a/internal/runtime/pi_gateway_run.go +++ b/internal/runtime/pi_gateway_run.go @@ -147,7 +147,7 @@ func validatePiGatewayRun(g *PiGatewayRun, plugins []PluginInput) error { func piAgentProviderExtensions(probed []string, gateway bool) []string { exts := []string{} for _, e := range probed { - if e == piInferenceGatewayExtensionPath && !gateway { + if (e == piInferenceGatewayExtensionPath || e == piLegacyGatewayExtensionPath) && !gateway { continue } exts = append(exts, e) diff --git a/internal/runtime/pi_gateway_run_test.go b/internal/runtime/pi_gateway_run_test.go index 3fa798b1ce..fb2ece6ed8 100644 --- a/internal/runtime/pi_gateway_run_test.go +++ b/internal/runtime/pi_gateway_run_test.go @@ -32,7 +32,7 @@ func registerPiGatewayRun(t *testing.T, sandboxName string, run *PiGatewayRun) { func TestBuildPiRunCommand_GatewayExtension(t *testing.T) { t.Setenv("FULLSEND_PI_MODEL", "") t.Setenv("FULLSEND_PI_PROVIDER", "") - gwExt := "-e " + shellQuote(piInferenceGatewayExtensionPath) + gwExt := `-e "$` + piGatewayExtensionVar + `"` params := piTestParams() params.SandboxName = "sb-gw-ext" @@ -42,7 +42,7 @@ func TestBuildPiRunCommand_GatewayExtension(t *testing.T) { params.Model = model cmd := buildPiRunCommand(params, &piManifest{}, nil, "") assert.Contains(t, cmd, gwExt, "model %s loads the extension (prefix is case-folded)", model) - assert.NotContains(t, cmd, "-e "+shellQuote(piVertexExtensionPath)) + assert.NotContains(t, cmd, `-e "$`+piVertexExtensionVar+`"`) } // Parent on Vertex, children admitted on the gateway: the parent loads @@ -63,7 +63,7 @@ func TestBuildPiRunCommand_GatewayUnchangedWithoutBlock(t *testing.T) { for _, model := range []string{"gateway/m1", "anthropic-vertex/claude-opus-4-6"} { params.Model = model cmd := buildPiRunCommand(params, &piManifest{}, exts, "") - assert.NotContains(t, cmd, "-e "+shellQuote(piInferenceGatewayExtensionPath), "no block: the runner does not own the route") + assert.NotContains(t, cmd, `-e "$`+piGatewayExtensionVar+`"`, "no block: the runner does not own the route") assert.NotContains(t, cmd, PiInferenceGatewayConfigFile) assert.NotContains(t, cmd, "unset $(command -p env") assert.Contains(t, cmd, "export INFERENCE_GATEWAY_BASE_URL='http://local'", "plugin env is exported as today") diff --git a/internal/runtime/pi_run.go b/internal/runtime/pi_run.go index 278d955ef4..44f1359103 100644 --- a/internal/runtime/pi_run.go +++ b/internal/runtime/pi_run.go @@ -437,6 +437,15 @@ func buildPiRunCommand(params RunParams, m *piManifest, exts []piManifestExtensi // assignment to the pinned name (envDataLoad's extra drop names). // The launch below uses the path, which no function or alias can shadow. parts = append(parts, "&& "+piBinaryPin()) + if vertex { + parts = append(parts, "&& "+piProviderExtensionPin(piVertexExtensionVar, piVertexExtensionPath, piLegacyVertexExtensionPath)) + } + if xaiVertex { + parts = append(parts, "&& "+piProviderExtensionPin(piXaiVertexExtensionVar, piXaiVertexExtensionPath, piLegacyXaiVertexExtensionPath)) + } + if gateway { + parts = append(parts, "&& "+piProviderExtensionPin(piGatewayExtensionVar, piInferenceGatewayExtensionPath, piLegacyGatewayExtensionPath)) + } if hooksEnabled { // Before .env: that file is agent-writable and could otherwise // shadow the guard's tools with functions or a PATH entry. @@ -485,7 +494,7 @@ func buildPiRunCommand(params RunParams, m *piManifest, exts []piManifestExtensi parts = append(parts, // .env is read as data, never sourced (envDataLoad, #8498); that // also drops LD_PRELOAD, LD_LIBRARY_PATH and LD_AUDIT (#7580). - "&& "+envDataLoad(envFile, piBinaryVar, piNodeVar, piHookPythonEnv, piHookPathEnv, piChildBinEnv, piChildNodeEnv), + "&& "+envDataLoad(envFile, piBinaryVar, piNodeVar, piVertexExtensionVar, piXaiVertexExtensionVar, piGatewayExtensionVar, piHookPythonEnv, piHookPathEnv, piChildBinEnv, piChildNodeEnv), // First thing after the agent-writable .env, on every provider // path: clear the variables that steer the module loaders pi runs // under. JITI_ALIAS alone swaps the file behind an `-e` path @@ -636,13 +645,13 @@ func buildPiRunCommand(params RunParams, m *piManifest, exts []piManifestExtensi if vertex { // The interim Claude-on-Vertex provider is only needed for the // anthropic-vertex model spec; other providers get pi's built-ins. - parts = append(parts, "-e "+shellQuote(piVertexExtensionPath)) + parts = append(parts, "-e \"$"+piVertexExtensionVar+"\"") } if xaiVertex { - parts = append(parts, "-e "+shellQuote(piXaiVertexExtensionPath)) + parts = append(parts, "-e \"$"+piXaiVertexExtensionVar+"\"") } if gateway { - parts = append(parts, "-e "+shellQuote(piInferenceGatewayExtensionPath)) + parts = append(parts, "-e \"$"+piGatewayExtensionVar+"\"") } // The openai provider needs no -e extension and deliberately no // --api-key: that flag outranks auth.json in pi's resolution order and @@ -720,6 +729,12 @@ const piManifestSumEnv = "FULLSEND_PI_MANIFEST_SHA256" // .env is read and marked read-only. const piBinaryVar = "FULLSEND_PI_BIN" +const ( + piVertexExtensionVar = "FULLSEND_PI_VERTEX_EXTENSION" + piXaiVertexExtensionVar = "FULLSEND_PI_XAI_VERTEX_EXTENSION" + piGatewayExtensionVar = "FULLSEND_PI_GATEWAY_EXTENSION" +) + // piNodeVar holds the node that starts pi: pi's CLI is a // `#!/usr/bin/env node` script, so binaryPin pins node by the same rule. const piNodeVar = "FULLSEND_PI_NODE" @@ -815,6 +830,14 @@ func piBinaryPin() string { return binaryPin(piBinaryVar, piNodeVar, "pi") } +// piProviderExtensionPin prefers the relocated extension path and falls +// back to the path in the currently published sandbox image. The selected +// path is read-only before the agent-writable .env is processed. +func piProviderExtensionPin(variable, primary, legacy string) string { + return "if test -d " + shellQuote(primary) + "; then readonly " + variable + "=" + shellQuote(primary) + + "; else readonly " + variable + "=" + shellQuote(legacy) + "; fi" +} + // piPlaceholderPrefix is the namespace of OpenShell gateway placeholders, // assembled from two parts on purpose: OpenShell 0.0.110+ resets any // model request whose body contains the contiguous prefix (it is treated diff --git a/internal/runtime/pi_run_test.go b/internal/runtime/pi_run_test.go index 5343dd3132..581dd200fa 100644 --- a/internal/runtime/pi_run_test.go +++ b/internal/runtime/pi_run_test.go @@ -102,7 +102,7 @@ func TestBuildPiRunCommand_Basic(t *testing.T) { // The guard runs before the agent-writable .env is sourced; the // runner-owned locations are re-pinned right after it. - assert.True(t, strings.HasPrefix(cmd, `cd '/sandbox/workspace/repo' && `+piBinaryPin()+` && `+piHooksGuard("/sandbox/pi-config/fullsend-hooks.js", "/sandbox/pi-config/fullsend-manifest.json")+` && `+piEnvLoad+` && `+piLoaderEnvUnset()+` && `+strings.Join(PiRuntime{}.EnvExports(), " && ")+` && export FULLSEND_PI_MANIFEST='/sandbox/pi-config/fullsend-manifest.json' && export FULLSEND_PI_HOOK_PYTHON="$FULLSEND_ENV_PYTHON" && export FULLSEND_PI_HOOK_PATH="$FULLSEND_TRUSTED_PATH" && export FULLSEND_PI_CHILD_BIN="$FULLSEND_PI_BIN" FULLSEND_PI_CHILD_NODE="$FULLSEND_PI_NODE" && export FULLSEND_RUNTIME=pi && export GOOGLE_CLOUD_LOCATION="${GOOGLE_CLOUD_LOCATION:-$CLOUD_ML_REGION}" && unset ANTHROPIC_API_KEY ANTHROPIC_AUTH_TOKEN ANTHROPIC_OAUTH_TOKEN ANTHROPIC_BASE_URL ANTHROPIC_VERTEX_BASE_URL && export GOOGLE_CLOUD_PROJECT="${ANTHROPIC_VERTEX_PROJECT_ID:-$GOOGLE_CLOUD_PROJECT}" && `+cliLaunch(piBinaryVar, piNodeVar)+` --print --mode json`), cmd) + assert.True(t, strings.HasPrefix(cmd, `cd '/sandbox/workspace/repo' && `+piBinaryPin()+` && `+piProviderExtensionPin(piVertexExtensionVar, piVertexExtensionPath, piLegacyVertexExtensionPath)+` && `+piHooksGuard("/sandbox/pi-config/fullsend-hooks.js", "/sandbox/pi-config/fullsend-manifest.json")+` && `+piEnvLoad+` && `+piLoaderEnvUnset()+` && `+strings.Join(PiRuntime{}.EnvExports(), " && ")+` && export FULLSEND_PI_MANIFEST='/sandbox/pi-config/fullsend-manifest.json' && export FULLSEND_PI_HOOK_PYTHON="$FULLSEND_ENV_PYTHON" && export FULLSEND_PI_HOOK_PATH="$FULLSEND_TRUSTED_PATH" && export FULLSEND_PI_CHILD_BIN="$FULLSEND_PI_BIN" FULLSEND_PI_CHILD_NODE="$FULLSEND_PI_NODE" && export FULLSEND_RUNTIME=pi && export GOOGLE_CLOUD_LOCATION="${GOOGLE_CLOUD_LOCATION:-$CLOUD_ML_REGION}" && unset ANTHROPIC_API_KEY ANTHROPIC_AUTH_TOKEN ANTHROPIC_OAUTH_TOKEN ANTHROPIC_BASE_URL ANTHROPIC_VERTEX_BASE_URL && export GOOGLE_CLOUD_PROJECT="${ANTHROPIC_VERTEX_PROJECT_ID:-$GOOGLE_CLOUD_PROJECT}" && `+cliLaunch(piBinaryVar, piNodeVar)+` --print --mode json`), cmd) // Gemini on Vertex needs GOOGLE_CLOUD_LOCATION; the fleet exports the // region as CLOUD_ML_REGION, so it is mirrored after .env is sourced. assert.Contains(t, cmd, `&& export GOOGLE_CLOUD_LOCATION="${GOOGLE_CLOUD_LOCATION:-$CLOUD_ML_REGION}"`) @@ -110,7 +110,7 @@ func TestBuildPiRunCommand_Basic(t *testing.T) { for _, want := range []string{ "--no-approve", "--no-extensions", "--no-prompt-templates", "--no-themes", "--session-dir '/sandbox/pi-config/sessions'", - "-e '/opt/fullsend/usr/local/share/pi-extensions/anthropic-vertex'", + `-e "$` + piVertexExtensionVar + `"`, "-e '/sandbox/pi-config/fullsend-hooks.js'", "--tools 'bash'", "--model 'anthropic-vertex/claude-opus-5-5'", @@ -160,7 +160,7 @@ func TestBuildPiRunCommand_AgentTool(t *testing.T) { cmd := buildPiRunCommand(params, m, declared, "") assert.Contains(t, cmd, "-e '"+hooksExt+"' -e '"+agentExt+"' -e '"+editExt+"' -e '/sandbox/pi-config/extensions/go-diagnostics'", "load order: hook adapter, Agent extension, edit repair, declared extensions") - assert.Contains(t, cmd, "-e '"+piVertexExtensionPath+"' -e '"+hooksExt+"'", "the provider extension still comes first") + assert.Contains(t, cmd, `-e "$`+piVertexExtensionVar+`" -e '`+hooksExt+`'`, "the provider extension still comes first") assert.NotContains(t, cmd, "-e '"+piXaiVertexExtensionPath+"'", "the parent loads only its own provider; the child list in the manifest is not the parent's") assert.NotContains(t, cmd, "--tools", "no tools: frontmatter → pi's default set plus the extension's tools") guard := piAgentGuard(agentExt) @@ -179,7 +179,7 @@ func TestBuildPiRunCommand_AgentTool(t *testing.T) { cmd = buildPiRunCommand(params, m, nil, "") assert.NotContains(t, cmd, hooksExt) assert.Contains(t, cmd, "&& "+guard+" && "+piEditRepairGuard(editExt)+" && "+piEnvLoad) - assert.Contains(t, cmd, "-e '"+piVertexExtensionPath+"' -e '"+agentExt+"' -e '"+editExt+"' --model") + assert.Contains(t, cmd, `-e "$`+piVertexExtensionVar+`" -e '`+agentExt+`' -e '`+editExt+`' --model`) // A declared tools: list naming Agent carries both names into --tools; // it names no edit, so the edit repair is not loaded. @@ -198,6 +198,23 @@ func TestBuildPiRunCommand_AgentTool(t *testing.T) { assert.NotContains(t, buildPiRunCommand(params, disabled, nil, ""), "fullsend-agent") } +func TestPiProviderExtensionPinPrefersRelocatedPath(t *testing.T) { + primary := filepath.Join(t.TempDir(), "relocated extension") + legacy := filepath.Join(t.TempDir(), "legacy extension") + require.NoError(t, os.Mkdir(primary, 0o755)) + require.NoError(t, os.Mkdir(legacy, 0o755)) + run := func() string { + t.Helper() + cmd := exec.Command("sh", "-c", piProviderExtensionPin("PINNED_EXTENSION", primary, legacy)+` && printf '%s' "$PINNED_EXTENSION"`) + out, err := cmd.Output() + require.NoError(t, err) + return string(out) + } + assert.Equal(t, primary, run(), "the /opt/fullsend image tree is preferred when present") + require.NoError(t, os.Remove(primary)) + assert.Equal(t, legacy, run(), "the published image path remains usable until the image is rebuilt") +} + // TestPiHooksGuard runs the rendered guard under a real sh: it must exit 97 // without running what follows when the adapter is missing or modified, and // fall through when both files are intact. @@ -495,18 +512,18 @@ func TestBuildPiRunCommand_XaiVertex(t *testing.T) { cmd := buildPiRunCommand(params, m, nil, "") assert.Contains(t, cmd, "--model 'xai-vertex/xai/grok-4.6'", "normalized model spec") - assert.Contains(t, cmd, "-e '"+sandbox.SandboxPiExtensionsDir+"/xai-vertex'", "xai-vertex extension is loaded") + assert.Contains(t, cmd, `-e "$`+piXaiVertexExtensionVar+`"`, "xai-vertex extension is loaded") assert.Contains(t, cmd, "&& unset XAI_API_KEY", "XAI_API_KEY is unset") assert.Contains(t, cmd, `&& export XAI_VERTEX_PROJECT_ID="${XAI_VERTEX_PROJECT_ID:-${ANTHROPIC_VERTEX_PROJECT_ID:-$GOOGLE_CLOUD_PROJECT}}"`, "project defaults to the fleet's Vertex project but does not override an explicit XAI_VERTEX_PROJECT_ID") assert.NotContains(t, cmd, "unset ANTHROPIC_API_KEY", "anthropic env hygiene does not fire for xai-vertex") - assert.NotContains(t, cmd, "-e '"+sandbox.SandboxPiExtensionsDir+"/anthropic-vertex'", "anthropic-vertex extension is not loaded") + assert.NotContains(t, cmd, `-e "$`+piVertexExtensionVar+`"`, "anthropic-vertex extension is not loaded") // Long form: xai-vertex/xai/grok-4.6 passes through. params.Model = "xai-vertex/xai/grok-4.6" cmd = buildPiRunCommand(params, m, nil, "") assert.Contains(t, cmd, "--model 'xai-vertex/xai/grok-4.6'") - assert.Contains(t, cmd, "-e '"+sandbox.SandboxPiExtensionsDir+"/xai-vertex'") + assert.Contains(t, cmd, `-e "$`+piXaiVertexExtensionVar+`"`) assert.Contains(t, cmd, "&& unset XAI_API_KEY") // Case variants must all reach the gate. A short form that escapes @@ -517,7 +534,7 @@ func TestBuildPiRunCommand_XaiVertex(t *testing.T) { cmd = buildPiRunCommand(params, m, nil, "") assert.Contains(t, cmd, "--model 'xai-vertex/xai/grok-4.6'", "canonical spec for %s", spec) assert.Contains(t, cmd, "&& unset XAI_API_KEY", "XAI_API_KEY unset for %s", spec) - assert.Contains(t, cmd, "-e '"+sandbox.SandboxPiExtensionsDir+"/xai-vertex'", "extension loaded for %s", spec) + assert.Contains(t, cmd, `-e "$`+piXaiVertexExtensionVar+`"`, "extension loaded for %s", spec) } // unset must run after the agent-writable .env is sourced, or the .env @@ -847,7 +864,7 @@ func TestBuildPiRunCommand_HarnessOverridesAndFlags(t *testing.T) { assert.NotContains(t, cmd, "--no-builtin-tools") assert.NotContains(t, cmd, "fullsend-hooks.js", "no hook extension when the runner has security disabled") assert.NotContains(t, cmd, "pi hook adapter or manifest missing", "and no hook guard") - assert.Contains(t, cmd, "-e '/opt/fullsend/usr/local/share/pi-extensions/anthropic-vertex'") + assert.Contains(t, cmd, `-e "$`+piVertexExtensionVar+`"`) assert.True(t, strings.HasSuffix(cmd, "'Run the agent task' >'/sandbox/workspace/pi-debug.log'"), cmd) } diff --git a/internal/runtime/pi_test.go b/internal/runtime/pi_test.go index 182e6b738c..ea2f517140 100644 --- a/internal/runtime/pi_test.go +++ b/internal/runtime/pi_test.go @@ -36,7 +36,7 @@ func TestPiRuntimeMetadata(t *testing.T) { // denied. func TestPiExtensionDirsWithinSandboxPolicy(t *testing.T) { t.Parallel() - allowedPrefixes := []string{"/usr", "/lib", "/app", "/etc", "/var/log"} + allowedPrefixes := []string{"/usr", "/lib", "/app", "/etc", "/var/log", sandbox.SandboxFullsendRoot} for _, extPath := range []string{piVertexExtensionPath, piXaiVertexExtensionPath, piInferenceGatewayExtensionPath} { var matched bool for _, prefix := range allowedPrefixes { diff --git a/internal/runtime/testdata/codex/golden/launch-delegating.txt b/internal/runtime/testdata/codex/golden/launch-delegating.txt index a4a0ee199e..3a256e8d99 100644 --- a/internal/runtime/testdata/codex/golden/launch-delegating.txt +++ b/internal/runtime/testdata/codex/golden/launch-delegating.txt @@ -1,5 +1,5 @@ cd '/sandbox/workspace/repo' && -{ readonly FULLSEND_TRUSTED_PATH="$(IFS=:; set -f; s=; for d in /opt/fullsend/usr/local/bin:/opt/fullsend/usr/bin:$PATH; do case $d in (/*) ;; (*) continue ;; esac; if ! test -O /; then d="$(cd -P "$d" 2>/dev/null && +{ readonly FULLSEND_TRUSTED_PATH="$(IFS=:; set -f; s=; fullsend_path='/opt/fullsend/usr/local/bin:/opt/fullsend/usr/bin'; paths=$fullsend_path${PATH:+:$PATH}; for d in $paths; do case $d in (/*) ;; (*) continue ;; esac; if ! test -O /; then d="$(cd -P "$d" 2>/dev/null && pwd -P)" || continue; case $d in (*:*) continue ;; esac; p=$d; while :; do if test -w "$p" || test -O "$p"; then continue 2; fi; case $p in (/) break ;; esac; p=${p%/*}; p=${p:-/}; done; fi; if test -d "$d"; then printf '%s%s' "$s" "$d"; s=:; fi; done)"; } && { readonly FULLSEND_READLINK="$(IFS=:; set -f; rl=; for d in $FULLSEND_TRUSTED_PATH; do test -f "$d/readlink" && test -x "$d/readlink" || continue; if test -O /; then rl=$d/readlink; break; fi; if test -h "$d/readlink" || test -w "$d/readlink" || test -O "$d/readlink"; then continue; fi; rl=$d/readlink; break; done; test -n "$rl" || echo 'fullsend: no readlink that is a regular file in a PATH directory the agent cannot write' >&2; printf '%s' "$rl")"; } && diff --git a/internal/runtime/testdata/codex/golden/launch-gateway.txt b/internal/runtime/testdata/codex/golden/launch-gateway.txt index f645f8bd06..ab5b088a3b 100644 --- a/internal/runtime/testdata/codex/golden/launch-gateway.txt +++ b/internal/runtime/testdata/codex/golden/launch-gateway.txt @@ -1,5 +1,5 @@ cd '/sandbox/workspace/repo' && -{ readonly FULLSEND_TRUSTED_PATH="$(IFS=:; set -f; s=; for d in /opt/fullsend/usr/local/bin:/opt/fullsend/usr/bin:$PATH; do case $d in (/*) ;; (*) continue ;; esac; if ! test -O /; then d="$(cd -P "$d" 2>/dev/null && +{ readonly FULLSEND_TRUSTED_PATH="$(IFS=:; set -f; s=; fullsend_path='/opt/fullsend/usr/local/bin:/opt/fullsend/usr/bin'; paths=$fullsend_path${PATH:+:$PATH}; for d in $paths; do case $d in (/*) ;; (*) continue ;; esac; if ! test -O /; then d="$(cd -P "$d" 2>/dev/null && pwd -P)" || continue; case $d in (*:*) continue ;; esac; p=$d; while :; do if test -w "$p" || test -O "$p"; then continue 2; fi; case $p in (/) break ;; esac; p=${p%/*}; p=${p:-/}; done; fi; if test -d "$d"; then printf '%s%s' "$s" "$d"; s=:; fi; done)"; } && { readonly FULLSEND_READLINK="$(IFS=:; set -f; rl=; for d in $FULLSEND_TRUSTED_PATH; do test -f "$d/readlink" && test -x "$d/readlink" || continue; if test -O /; then rl=$d/readlink; break; fi; if test -h "$d/readlink" || test -w "$d/readlink" || test -O "$d/readlink"; then continue; fi; rl=$d/readlink; break; done; test -n "$rl" || echo 'fullsend: no readlink that is a regular file in a PATH directory the agent cannot write' >&2; printf '%s' "$rl")"; } && diff --git a/internal/runtime/testdata/codex/golden/launch-hooks.txt b/internal/runtime/testdata/codex/golden/launch-hooks.txt index 6d65e4dec1..648cd2b150 100644 --- a/internal/runtime/testdata/codex/golden/launch-hooks.txt +++ b/internal/runtime/testdata/codex/golden/launch-hooks.txt @@ -1,5 +1,5 @@ cd '/sandbox/workspace/repo' && -{ readonly FULLSEND_TRUSTED_PATH="$(IFS=:; set -f; s=; for d in /opt/fullsend/usr/local/bin:/opt/fullsend/usr/bin:$PATH; do case $d in (/*) ;; (*) continue ;; esac; if ! test -O /; then d="$(cd -P "$d" 2>/dev/null && +{ readonly FULLSEND_TRUSTED_PATH="$(IFS=:; set -f; s=; fullsend_path='/opt/fullsend/usr/local/bin:/opt/fullsend/usr/bin'; paths=$fullsend_path${PATH:+:$PATH}; for d in $paths; do case $d in (/*) ;; (*) continue ;; esac; if ! test -O /; then d="$(cd -P "$d" 2>/dev/null && pwd -P)" || continue; case $d in (*:*) continue ;; esac; p=$d; while :; do if test -w "$p" || test -O "$p"; then continue 2; fi; case $p in (/) break ;; esac; p=${p%/*}; p=${p:-/}; done; fi; if test -d "$d"; then printf '%s%s' "$s" "$d"; s=:; fi; done)"; } && { readonly FULLSEND_READLINK="$(IFS=:; set -f; rl=; for d in $FULLSEND_TRUSTED_PATH; do test -f "$d/readlink" && test -x "$d/readlink" || continue; if test -O /; then rl=$d/readlink; break; fi; if test -h "$d/readlink" || test -w "$d/readlink" || test -O "$d/readlink"; then continue; fi; rl=$d/readlink; break; done; test -n "$rl" || echo 'fullsend: no readlink that is a regular file in a PATH directory the agent cannot write' >&2; printf '%s' "$rl")"; } && diff --git a/internal/runtime/testdata/codex/golden/launch-nohooks.txt b/internal/runtime/testdata/codex/golden/launch-nohooks.txt index 858ff57351..ba804ae388 100644 --- a/internal/runtime/testdata/codex/golden/launch-nohooks.txt +++ b/internal/runtime/testdata/codex/golden/launch-nohooks.txt @@ -1,5 +1,5 @@ cd '/sandbox/workspace/repo' && -{ readonly FULLSEND_TRUSTED_PATH="$(IFS=:; set -f; s=; for d in /opt/fullsend/usr/local/bin:/opt/fullsend/usr/bin:$PATH; do case $d in (/*) ;; (*) continue ;; esac; if ! test -O /; then d="$(cd -P "$d" 2>/dev/null && +{ readonly FULLSEND_TRUSTED_PATH="$(IFS=:; set -f; s=; fullsend_path='/opt/fullsend/usr/local/bin:/opt/fullsend/usr/bin'; paths=$fullsend_path${PATH:+:$PATH}; for d in $paths; do case $d in (/*) ;; (*) continue ;; esac; if ! test -O /; then d="$(cd -P "$d" 2>/dev/null && pwd -P)" || continue; case $d in (*:*) continue ;; esac; p=$d; while :; do if test -w "$p" || test -O "$p"; then continue 2; fi; case $p in (/) break ;; esac; p=${p%/*}; p=${p:-/}; done; fi; if test -d "$d"; then printf '%s%s' "$s" "$d"; s=:; fi; done)"; } && { readonly FULLSEND_READLINK="$(IFS=:; set -f; rl=; for d in $FULLSEND_TRUSTED_PATH; do test -f "$d/readlink" && test -x "$d/readlink" || continue; if test -O /; then rl=$d/readlink; break; fi; if test -h "$d/readlink" || test -w "$d/readlink" || test -O "$d/readlink"; then continue; fi; rl=$d/readlink; break; done; test -n "$rl" || echo 'fullsend: no readlink that is a regular file in a PATH directory the agent cannot write' >&2; printf '%s' "$rl")"; } && diff --git a/internal/sandbox/sandbox_claude_image_test.go b/internal/sandbox/sandbox_claude_image_test.go index 58ebb0d2ac..b55a7f40d9 100644 --- a/internal/sandbox/sandbox_claude_image_test.go +++ b/internal/sandbox/sandbox_claude_image_test.go @@ -31,7 +31,7 @@ func TestSandboxImageClaudeCodePinWins(t *testing.T) { for _, want := range []string{ `NPM_CLAUDE="$(npm prefix -g)/bin/claude"`, `rm -f /usr/local/bin/claude`, - `ln -s "${NPM_CLAUDE}" /usr/local/bin/claude`, + `ln -sr "${NPM_CLAUDE}" /usr/local/bin/claude`, `GOT="$(claude --version | awk '{print $1}')"`, `if [ "${GOT}" != "${CLAUDE_CODE_VERSION}" ]; then`, } { @@ -40,7 +40,7 @@ func TestSandboxImageClaudeCodePinWins(t *testing.T) { // The symlink + assertion must come after the npm install it points at. install := regexp.MustCompile(`npm install -g @anthropic-ai/claude-code@`).FindStringIndex(containerfile) - link := regexp.MustCompile(`ln -s "\$\{NPM_CLAUDE\}" /usr/local/bin/claude`).FindStringIndex(containerfile) + link := regexp.MustCompile(`ln -sr "\$\{NPM_CLAUDE\}" /usr/local/bin/claude`).FindStringIndex(containerfile) require.NotNil(t, install) require.NotNil(t, link) assert.Less(t, install[0], link[0], "the /usr/local/bin/claude symlink must follow the npm install") diff --git a/internal/sandbox/sandbox_codex_image_test.go b/internal/sandbox/sandbox_codex_image_test.go index 5e386c4a75..3adc1ba8bb 100644 --- a/internal/sandbox/sandbox_codex_image_test.go +++ b/internal/sandbox/sandbox_codex_image_test.go @@ -54,7 +54,7 @@ func TestSandboxImageCodexPinWins(t *testing.T) { for _, want := range []string{ `NPM_CODEX="$(npm prefix -g)/bin/codex"`, `rm -f /usr/local/bin/codex`, - `ln -s "${NPM_CODEX}" /usr/local/bin/codex`, + `ln -sr "${NPM_CODEX}" /usr/local/bin/codex`, `GOT="$(codex --version)"`, // codex --version prints "codex-cli ". `if [ "${GOT}" != "codex-cli ${CODEX_VERSION}" ]; then`, @@ -64,7 +64,7 @@ func TestSandboxImageCodexPinWins(t *testing.T) { // The symlink + assertion must come after the npm install it points at. install := regexp.MustCompile(`npm install -g --ignore-scripts @openai/codex@`).FindStringIndex(containerfile) - link := regexp.MustCompile(`ln -s "\$\{NPM_CODEX\}" /usr/local/bin/codex`).FindStringIndex(containerfile) + link := regexp.MustCompile(`ln -sr "\$\{NPM_CODEX\}" /usr/local/bin/codex`).FindStringIndex(containerfile) require.NotNil(t, install) require.NotNil(t, link) assert.Less(t, install[0], link[0], "the /usr/local/bin/codex symlink must follow the npm install") diff --git a/internal/sandbox/sandbox_pi_image_test.go b/internal/sandbox/sandbox_pi_image_test.go index f927ed7727..3335dfca66 100644 --- a/internal/sandbox/sandbox_pi_image_test.go +++ b/internal/sandbox/sandbox_pi_image_test.go @@ -30,7 +30,9 @@ func TestSandboxImagePiDefaults(t *testing.T) { // runtime.piXaiVertexExtensionPath = SandboxPiExtensionsDir + "/xai-vertex", // runtime.piInferenceGatewayExtensionPath = SandboxPiExtensionsDir + "/inference-gateway", // installed but not loaded until #7480). - `ARG PI_EXTENSIONS_DIR=` + SandboxPiExtensionsDir, + `ARG PI_EXTENSIONS_DIR=/usr/local/share/pi-extensions`, + `ln -s /usr /opt/fullsend/usr`, + `RUN rm /opt/fullsend/usr`, `"${PI_EXTENSIONS_DIR}/anthropic-vertex"`, `"${PI_EXTENSIONS_DIR}/xai-vertex"`, `"${PI_EXTENSIONS_DIR}/inference-gateway"`, diff --git a/internal/scaffold/scaffold_test.go b/internal/scaffold/scaffold_test.go index a82f851e3a..92861b3336 100644 --- a/internal/scaffold/scaffold_test.go +++ b/internal/scaffold/scaffold_test.go @@ -21,6 +21,9 @@ func TestFileModeMatchesFilesystem(t *testing.T) { var onDiskExecutable []string err := filepath.WalkDir(scaffoldRoot, func(path string, d fs.DirEntry, walkErr error) error { if walkErr != nil || d.IsDir() { + if walkErr == nil && d.IsDir() && d.Name() == ".fullsend-cache" { + return filepath.SkipDir + } return walkErr } info, infoErr := d.Info() From 981b462eb979dbc042e529ad914ec941620d565d Mon Sep 17 00:00:00 2001 From: Ralph Bean Date: Fri, 13 Nov 2026 07:06:02 -0500 Subject: [PATCH 3/9] test(harness): cover image mount handling Signed-off-by: Ralph Bean --- internal/harness/image_mount_test.go | 189 +++++++++++++++++++++++++++ internal/sandbox/sandbox_test.go | 44 +++++++ 2 files changed, 233 insertions(+) create mode 100644 internal/harness/image_mount_test.go diff --git a/internal/harness/image_mount_test.go b/internal/harness/image_mount_test.go new file mode 100644 index 0000000000..29fc9e6d4f --- /dev/null +++ b/internal/harness/image_mount_test.go @@ -0,0 +1,189 @@ +package harness + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestMergeImageMountsChildWinsByDestination(t *testing.T) { + base := []ImageMount{ + {Image: "registry.example/base:v1", Dest: "/opt/tools"}, + {Image: "registry.example/config:v1", Dest: "/etc/tool"}, + } + child := []ImageMount{ + {Image: "registry.example/custom-tools:v2", Dest: "/opt/tools"}, + {Image: "registry.example/extra:v1", Dest: "/opt/extra"}, + } + + got := mergeImageMounts(base, child) + require.Equal(t, []ImageMount{ + {Image: "registry.example/custom-tools:v2", Dest: "/opt/tools"}, + {Image: "registry.example/config:v1", Dest: "/etc/tool"}, + {Image: "registry.example/extra:v1", Dest: "/opt/extra"}, + }, got) + assert.Equal(t, "registry.example/base:v1", base[0].Image, "merge must not mutate its inputs") +} + +func TestValidateImageMounts(t *testing.T) { + tests := []struct { + name string + mounts []ImageMount + hostFiles []HostFile + wantError string + }{ + {name: "valid tag", mounts: []ImageMount{{Image: "registry.example/team/tools:2026.11", Dest: "/opt/tools"}}}, + {name: "valid digest", mounts: []ImageMount{{Image: "registry.example/team/tools@sha256:0123456789abcdef", Dest: "/opt/tools"}}}, + {name: "empty image", mounts: []ImageMount{{Dest: "/opt/tools"}}, wantError: "image must be an OCI image reference"}, + {name: "image whitespace", mounts: []ImageMount{{Image: "registry.example/tools:latest ", Dest: "/opt/tools"}}, wantError: "image must be an OCI image reference"}, + {name: "image variable", mounts: []ImageMount{{Image: "registry.example/tools:${TAG}", Dest: "/opt/tools"}}, wantError: "image must be an OCI image reference"}, + {name: "image URL", mounts: []ImageMount{{Image: "https://registry.example/tools", Dest: "/opt/tools"}}, wantError: "image must be an OCI image reference"}, + {name: "missing destination", mounts: []ImageMount{{Image: "registry.example/tools:latest"}}, wantError: "dest is required"}, + {name: "relative destination", mounts: []ImageMount{{Image: "registry.example/tools:latest", Dest: "opt/tools"}}, wantError: "must be an absolute path"}, + {name: "parent component", mounts: []ImageMount{{Image: "registry.example/tools:latest", Dest: "/opt/../etc"}}, wantError: `must not contain a ".." path component`}, + {name: "unclean destination", mounts: []ImageMount{{Image: "registry.example/tools:latest", Dest: "/opt//tools"}}, wantError: "must use a clean absolute path"}, + {name: "container root", mounts: []ImageMount{{Image: "registry.example/tools:latest", Dest: "/"}}, wantError: "must not replace the container root"}, + {name: "same destination allowed for merge", mounts: []ImageMount{ + {Image: "registry.example/base:v1", Dest: "/opt/tools"}, + {Image: "registry.example/child:v1", Dest: "/opt/tools"}, + }}, + {name: "overlapping host file", mounts: []ImageMount{{Image: "registry.example/tools:latest", Dest: "/opt/tools"}}, hostFiles: []HostFile{{Src: "agent.env", Dest: "/opt/tools/env"}}, wantError: "overlaps host_files[0].dest"}, + {name: "overlapping image mounts", mounts: []ImageMount{ + {Image: "registry.example/parent:v1", Dest: "/opt/tools"}, + {Image: "registry.example/child:v1", Dest: "/opt/tools/bin"}, + }, wantError: "overlaps image_mounts[0].dest"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + err := validateImageMounts(tc.mounts, tc.hostFiles, "image_mounts") + if tc.wantError == "" { + require.NoError(t, err) + return + } + require.Error(t, err) + assert.Contains(t, err.Error(), tc.wantError) + }) + } +} + +func TestPathsOverlap(t *testing.T) { + tests := []struct { + a, b string + want bool + }{ + {a: "/opt/tools", b: "/opt/tools", want: true}, + {a: "/opt/tools", b: "/opt/tools/bin", want: true}, + {a: "/opt/tools/bin", b: "/opt/tools", want: true}, + {a: "/opt/tools", b: "/opt/toolsmith", want: false}, + {a: "/opt/tools", b: "/etc/config", want: false}, + } + for _, tc := range tests { + assert.Equal(t, tc.want, pathsOverlap(tc.a, tc.b), "%q and %q", tc.a, tc.b) + } +} + +func TestLoadWithBase_ImageMountsChildOverridesBase(t *testing.T) { + dir := t.TempDir() + writeTestHarness(t, dir, "base.yaml", ` +agent: agents/base.md +role: test +image_mounts: + - image: registry.example/base-tools:v1 + dest: /opt/fullsend + - image: registry.example/config:v1 + dest: /etc/tool +`) + path := writeTestHarness(t, dir, "child.yaml", ` +base: base.yaml +image_mounts: + - image: registry.example/custom-tools:v2 + dest: /opt/fullsend +`) + + h, _, err := LoadWithBase(context.Background(), path, ComposeOpts{}) + require.NoError(t, err) + assert.Equal(t, []ImageMount{ + {Image: "registry.example/custom-tools:v2", Dest: "/opt/fullsend"}, + {Image: "registry.example/config:v1", Dest: "/etc/tool"}, + }, h.ImageMounts) +} + +func TestResolveForge_ImageMountsOverrideByDestination(t *testing.T) { + h := &Harness{ + Agent: "agents/test.md", + ImageMounts: []ImageMount{{Image: "registry.example/base:v1", Dest: "/opt/tools"}}, + Forge: map[string]*ForgeConfig{ + "github": {ImageMounts: []ImageMount{ + {Image: "registry.example/github:v2", Dest: "/opt/tools"}, + {Image: "registry.example/extras:v1", Dest: "/opt/extras"}, + }}, + }, + } + + require.NoError(t, h.ResolveForge("github")) + assert.Equal(t, []ImageMount{ + {Image: "registry.example/github:v2", Dest: "/opt/tools"}, + {Image: "registry.example/extras:v1", Dest: "/opt/extras"}, + }, h.ImageMounts) +} + +func TestResolveOverlays_ImageMountsOverrideByDestination(t *testing.T) { + h := &Harness{ + ImageMounts: []ImageMount{{Image: "registry.example/base:v1", Dest: "/opt/tools"}}, + Overlays: []OverlayEntry{{ + When: "true", + ForgeConfig: ForgeConfig{ImageMounts: []ImageMount{ + {Image: "registry.example/overlay:v2", Dest: "/opt/tools"}, + {Image: "registry.example/extra:v1", Dest: "/opt/extra"}, + }}, + }}, + } + + require.NoError(t, h.ResolveOverlays(nil, "github", nil)) + assert.Equal(t, []ImageMount{ + {Image: "registry.example/overlay:v2", Dest: "/opt/tools"}, + {Image: "registry.example/extra:v1", Dest: "/opt/extra"}, + }, h.ImageMounts) +} + +func TestValidateImageMountsAcrossHarnessLayers(t *testing.T) { + h := &Harness{ + Agent: "agents/test.md", + Role: "test", + ImageMounts: []ImageMount{{Image: "registry.example/tools:v1", Dest: "/tmp/tools"}}, + HostFiles: []HostFile{{Src: "agent.env", Dest: "/tmp/tools/env"}}, + } + err := h.Validate() + require.Error(t, err) + assert.Contains(t, err.Error(), "image_mounts[0].dest") + assert.Contains(t, err.Error(), "overlaps host_files[0].dest") +} + +func TestValidateImageMountsInForgeAndOverlay(t *testing.T) { + for _, tc := range []struct { + name string + forge map[string]*ForgeConfig + overly []OverlayEntry + want string + }{ + { + name: "forge", + forge: map[string]*ForgeConfig{"github": {ImageMounts: []ImageMount{{Image: "registry.example/tools:v1", Dest: "relative"}}}}, + want: "forge.github.image_mounts[0].dest", + }, + { + name: "overlay", + overly: []OverlayEntry{{When: "true", ForgeConfig: ForgeConfig{ImageMounts: []ImageMount{{Image: "registry.example/tools:v1", Dest: "relative"}}}}}, + want: "overlays[0].image_mounts[0].dest", + }, + } { + t.Run(tc.name, func(t *testing.T) { + h := &Harness{Agent: "agents/test.md", Role: "test", Forge: tc.forge, Overlays: tc.overly} + err := h.Validate() + require.Error(t, err) + assert.Contains(t, err.Error(), tc.want) + }) + } +} diff --git a/internal/sandbox/sandbox_test.go b/internal/sandbox/sandbox_test.go index 723e435cd9..290b347eb1 100644 --- a/internal/sandbox/sandbox_test.go +++ b/internal/sandbox/sandbox_test.go @@ -2,6 +2,7 @@ package sandbox import ( "context" + "encoding/json" "errors" "fmt" "os" @@ -2824,6 +2825,49 @@ exit 0 "sandbox create must not use 'true' as the command (breaks OpenShell 0.0.111+)") } +func TestCreate_PassesReadOnlyImageMountsToPodmanDriver(t *testing.T) { + dir := t.TempDir() + argsLog := filepath.Join(dir, "args.log") + script := fmt.Sprintf(`#!/bin/sh +if [ "$2" = "create" ]; then + printf '%%s\n' "$@" >> %s + exit 0 +fi +if [ "$2" = "get" ]; then + echo "Phase: Ready" + exit 0 +fi +exit 0 +`, argsLog) + require.NoError(t, os.WriteFile(filepath.Join(dir, "openshell"), []byte(script), 0o755)) + t.Setenv("PATH", dir) + + mounts := []ImageMount{ + {Source: "registry.example/tools:v1", Target: "/opt/tools"}, + {Source: "registry.example/config:v2", Target: "/etc/tool"}, + } + require.NoError(t, Create("test-sandbox", nil, "", "", mounts...)) + + args, err := os.ReadFile(argsLog) + require.NoError(t, err) + argv := strings.Split(strings.TrimSpace(string(args)), "\n") + index := -1 + for i, arg := range argv { + if arg == "--driver-config-json" { + index = i + break + } + } + require.NotEqual(t, -1, index, "create should pass Podman driver configuration") + require.Less(t, index+1, len(argv)) + var config podmanDriverConfig + require.NoError(t, json.Unmarshal([]byte(argv[index+1]), &config)) + assert.Equal(t, []podmanImageMount{ + {Type: "image", Source: "registry.example/tools:v1", Target: "/opt/tools", ReadOnly: true}, + {Type: "image", Source: "registry.example/config:v2", Target: "/etc/tool", ReadOnly: true}, + }, config.Podman.Mounts) +} + // TestCreateOnce_ReadyFallsBackWhenPhaseFieldAbsent covers output-format // drift: if OpenShell stops emitting a parseable "Phase:" field, anchoring // alone would time out every healthy sandbox, so the historical substring From 49eeb07a45eacc39df302fa7eca2510f2856f142 Mon Sep 17 00:00:00 2001 From: Ralph Bean Date: Fri, 13 Nov 2026 13:35:23 -0500 Subject: [PATCH 4/9] fix(#9396): preserve legacy tool lookup behavior Signed-off-by: Ralph Bean --- internal/runtime/codex_bootstrap.go | 3 +- internal/runtime/codex_bootstrap_test.go | 8 +- internal/runtime/env_data.go | 12 +- internal/runtime/env_data_test.go | 56 +++++ internal/runtime/opencode_bootstrap.go | 7 +- internal/runtime/opencode_bootstrap_test.go | 2 + internal/runtime/opencode_run.go | 1 + internal/runtime/opencode_test.go | 4 + .../scripts/fullsend-check-output | 21 +- .../scaffold/fullsend_check_output_test.go | 227 ++++++++++++++++++ 10 files changed, 327 insertions(+), 14 deletions(-) create mode 100644 internal/scaffold/fullsend_check_output_test.go diff --git a/internal/runtime/codex_bootstrap.go b/internal/runtime/codex_bootstrap.go index 43e4b97245..17c8c3b7ac 100644 --- a/internal/runtime/codex_bootstrap.go +++ b/internal/runtime/codex_bootstrap.go @@ -547,7 +547,8 @@ func codexPreflightVersion(sandboxName string) (string, error) { // image, reported before any iteration. func codexPreflightCatalog(sandboxName string) (codexCatalog, error) { const cmd = "codex debug models --bundled" - stdout, stderr, exitCode, err := sandbox.Exec(sandboxName, cmd, 30*time.Second) + toolPathCmd := sandboxFullsendToolPathCommand(cmd) + stdout, stderr, exitCode, err := sandbox.Exec(sandboxName, toolPathCmd, 30*time.Second) if err != nil { return nil, fmt.Errorf("codex preflight: %w", err) } diff --git a/internal/runtime/codex_bootstrap_test.go b/internal/runtime/codex_bootstrap_test.go index 1b5eb4ccb9..8085ab7ca7 100644 --- a/internal/runtime/codex_bootstrap_test.go +++ b/internal/runtime/codex_bootstrap_test.go @@ -68,7 +68,7 @@ if [ "$2" = "exec" ]; then sh -c 'mkdir() { :; }; mv() { shift; shift; cp -- "$1" '\''` + storeDir + `/'\''"$(printf "%s" "$2" | tr / _)"; }; '"$last" exit $? ;; *"codex --version"*) echo "` + versionOutput + `"; exit 0 ;; - "codex debug models --bundled") cat "${FULLSEND_TEST_CATALOG:-testdata/codex/models-bundled-0.166.0.json}"; exit 0 ;; + *"codex debug models --bundled") cat "${FULLSEND_TEST_CATALOG:-testdata/codex/models-bundled-0.166.0.json}"; exit 0 ;; *"` + hookInterpreterSep + `"*) printf '%s` + hookInterpreterSep + `%s\n' /usr/bin/python3 /usr/local/bin:/usr/bin:/bin; exit 0 ;; # What a plain PATH lookup finds in the fleet image; Bootstrap must not use it. "command -v python3") echo "/sandbox/.venv/bin/python3"; exit 0 ;; @@ -860,10 +860,14 @@ func TestHomeAgentsMDPath(t *testing.T) { // Bootstrap with their own message rather than leaving the gate half decided. func TestCodexPreflightCatalog(t *testing.T) { t.Run("reads the fixture", func(t *testing.T) { - fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "codex-cli 0.152.1") + logPath := filepath.Join(t.TempDir(), "log") + fakeOpenshellCodex(t, logPath, t.TempDir(), "codex-cli 0.152.1") catalog, err := codexPreflightCatalog("sb") require.NoError(t, err) assert.Equal(t, "v1", catalog.collabVersion("gpt-5.6-luna")) + log, err := os.ReadFile(logPath) + require.NoError(t, err) + assert.Contains(t, string(log), "PATH='/opt/fullsend/usr/local/bin:/opt/fullsend/usr/bin'${PATH:+:$PATH} codex debug models --bundled") }) t.Run("command fails", func(t *testing.T) { fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "codex-cli 0.152.1") diff --git a/internal/runtime/env_data.go b/internal/runtime/env_data.go index be61516b7d..69b90e8c21 100644 --- a/internal/runtime/env_data.go +++ b/internal/runtime/env_data.go @@ -96,7 +96,11 @@ func EnvDataControlLines() []string { // sandboxFullsendToolPathCommand runs a fixed runner command with the // mounted Fullsend tool image ahead of the sandbox's ambient PATH. func sandboxFullsendToolPathCommand(command string) string { - return "PATH=" + shellQuote(sandbox.SandboxFullsendToolPath) + `${PATH:+:$PATH} ` + command + return sandboxFullsendToolPathCommandAt(sandbox.SandboxFullsendToolPath, command) +} + +func sandboxFullsendToolPathCommandAt(toolPath, command string) string { + return "PATH=" + shellQuote(toolPath) + `${PATH:+:$PATH} ` + command } func envDataControlLines(workspace string) []string { @@ -134,8 +138,12 @@ const envDataWritableAncestor = `while :; do if test -w "$p" || test -O "$p"; th // the launch runs as the owner of / (root), nothing could be protected, so // only relative and empty entries and missing directories are left out. func envDataTrustedPath() string { + return envDataTrustedPathFor(sandbox.SandboxFullsendToolPath) +} + +func envDataTrustedPathFor(toolPath string) string { return `{ readonly ` + envDataTrustedPathVar + `="$(IFS=:; set -f; s=; ` + - `fullsend_path='` + sandbox.SandboxFullsendToolPath + `'; paths=$fullsend_path${PATH:+:$PATH}; ` + + `fullsend_path=` + shellQuote(toolPath) + `; paths=$fullsend_path${PATH:+:$PATH}; ` + `for d in $paths; do case $d in (/*) ;; (*) continue ;; esac; if ! test -O /; then ` + `d="$(cd -P "$d" 2>/dev/null && pwd -P)" || continue; case $d in (*:*) continue ;; esac; p=$d; ` + envDataWritableAncestor + `; fi; ` + `if test -d "$d"; then printf '%s%s' "$s" "$d"; s=:; fi; done)"; }` diff --git a/internal/runtime/env_data_test.go b/internal/runtime/env_data_test.go index 3bd4441eba..dcbd38f3c0 100644 --- a/internal/runtime/env_data_test.go +++ b/internal/runtime/env_data_test.go @@ -684,6 +684,62 @@ func TestEnvDataTrustedPath_RootDropsRelativeEntries(t *testing.T) { assert.Equal(t, "/usr/bin:/bin", string(out)) } +func TestEnvDataTrustedPath_MountedOnlyToolLookup(t *testing.T) { + root := t.TempDir() + toolDirs := []string{ + filepath.Join(root, "fullsend", "usr", "local", "bin"), + filepath.Join(root, "fullsend", "usr", "bin"), + } + for _, dir := range toolDirs { + require.NoError(t, os.MkdirAll(dir, 0o755)) + } + mountedTool := filepath.Join(toolDirs[0], "fullsend-only") + require.NoError(t, os.WriteFile(mountedTool, []byte("#!/bin/sh\necho mounted\n"), 0o755)) + projectBin := filepath.Join(root, "project", "bin") + require.NoError(t, os.MkdirAll(projectBin, 0o755)) + projectTool := filepath.Join(projectBin, "conflicting") + require.NoError(t, os.WriteFile(projectTool, []byte("#!/bin/sh\necho project\n"), 0o755)) + + // Model an agent account that cannot own or rewrite the mounted image. + // The real filesystem and executable lookup remain in use. + protectedRoot := `test() { if [ "$1" = -O ] && [ "$2" = / ]; then return 0; fi; command test "$@"; }; ` + path := strings.Join([]string{projectBin, os.Getenv("PATH")}, string(os.PathListSeparator)) + cmd := exec.Command("/bin/sh", "-c", protectedRoot+envDataTrustedPathFor(strings.Join(toolDirs, ":"))+` && PATH="$`+envDataTrustedPathVar+`" command -v fullsend-only`) + cmd.Env = []string{"PATH=" + path} + out, err := cmd.Output() + require.NoError(t, err) + assert.Equal(t, mountedTool, strings.TrimSpace(string(out))) + + cmd = exec.Command("/bin/sh", "-c", protectedRoot+envDataTrustedPathFor(strings.Join(toolDirs, ":"))+` && PATH="$`+envDataTrustedPathVar+`" command -v conflicting`) + cmd.Env = []string{"PATH=" + path} + out, err = cmd.Output() + require.NoError(t, err) + assert.Equal(t, projectTool, strings.TrimSpace(string(out)), "ambient project tools remain reachable after mounted-only tools") +} + +func TestSandboxFullsendToolPathCommandAt_PrefersMountedTool(t *testing.T) { + root := t.TempDir() + mountedBin := filepath.Join(root, "mounted") + projectBin := filepath.Join(root, "project") + for _, dir := range []string{mountedBin, projectBin} { + require.NoError(t, os.MkdirAll(dir, 0o755)) + } + for dir, output := range map[string]string{mountedBin: "mounted", projectBin: "project"} { + require.NoError(t, os.WriteFile(filepath.Join(dir, "codex"), []byte("#!/bin/sh\necho "+output+"\n"), 0o755)) + } + cmd := exec.Command("/bin/sh", "-c", sandboxFullsendToolPathCommandAt(mountedBin, "codex")) + cmd.Env = []string{"PATH=" + projectBin + ":/usr/bin:/bin"} + out, err := cmd.Output() + require.NoError(t, err) + assert.Equal(t, "mounted\n", string(out)) + + cmd = exec.Command("/bin/sh", "-c", sandboxFullsendToolPathCommandAt(mountedBin, "codex")) + cmd.Env = []string{"PATH=/usr/bin:/bin"} + out, err = cmd.Output() + require.NoError(t, err) + assert.Equal(t, "mounted\n", string(out), "the command is found when only the mounted image provides it") +} + // The fragment pins python3 before reading .env and runs it isolated. The // trusted PATH it pins with is the one the launch's CLI pin recorded, so // the fragment itself never records it again (a second `readonly` of the diff --git a/internal/runtime/opencode_bootstrap.go b/internal/runtime/opencode_bootstrap.go index dbfca86cef..36c13a8833 100644 --- a/internal/runtime/opencode_bootstrap.go +++ b/internal/runtime/opencode_bootstrap.go @@ -406,10 +406,11 @@ func openCodeBashAllowlistWarning(allowlist []string) string { // loaded as mode "primary". It catches a silent fallback to the default agent // (*:allow) from a frontmatter parse failure or mode:subagent. func openCodeVerifyAgent(sandboxName, agentName string, r OpenCodeRuntime) error { - cmd := fmt.Sprintf("cd %s && OPENCODE_CONFIG_DIR=%s opencode debug agent %s 2>/dev/null", + cmd := fmt.Sprintf("cd %s && %s 2>/dev/null", shellQuote(r.WorkspaceDir()), - shellQuote(r.ConfigDir()), - shellQuote(openCodeValidatedArg(agentName))) + sandboxFullsendToolPathCommand(fmt.Sprintf("OPENCODE_CONFIG_DIR=%s opencode debug agent %s", + shellQuote(r.ConfigDir()), + shellQuote(openCodeValidatedArg(agentName))))) stdout, stderr, exitCode, err := sandbox.Exec(sandboxName, cmd, 30*time.Second) if err != nil { return fmt.Errorf("verifying opencode agent %q: %w", agentName, err) diff --git a/internal/runtime/opencode_bootstrap_test.go b/internal/runtime/opencode_bootstrap_test.go index 1abb5b44b9..7c1305ad4f 100644 --- a/internal/runtime/opencode_bootstrap_test.go +++ b/internal/runtime/opencode_bootstrap_test.go @@ -94,6 +94,8 @@ func TestOpenCodeRuntimeBootstrap_WritesAgentDefinition(t *testing.T) { cfg := r.ConfigDir() assert.Contains(t, logStr, "mkdir -p '"+cfg+"/agent' '"+cfg+"/skills' '"+cfg+"/plugins'") assert.Contains(t, logStr, "opencode --version") + assert.Contains(t, logStr, "PATH='/opt/fullsend/usr/local/bin:/opt/fullsend/usr/bin'${PATH:+:$PATH} OPENCODE_CONFIG_DIR=") + assert.Contains(t, logStr, "opencode debug agent 'triage'") // Skills go through the upload/tar path; the archive lands under skills/. assert.Contains(t, logStr, cfg+"/skills/") trustedEnv, ok := lookupOpenCodeTrustedEnv("sb") diff --git a/internal/runtime/opencode_run.go b/internal/runtime/opencode_run.go index 9bc9f4e56b..f084df3ab5 100644 --- a/internal/runtime/opencode_run.go +++ b/internal/runtime/opencode_run.go @@ -311,6 +311,7 @@ func openCodeUtilityPin() string { sandbox.SandboxFullsendBinDir, "/usr/local/bin", "/usr/bin", + "/bin", ) } diff --git a/internal/runtime/opencode_test.go b/internal/runtime/opencode_test.go index c51842546a..0bfc012bf5 100644 --- a/internal/runtime/opencode_test.go +++ b/internal/runtime/opencode_test.go @@ -490,6 +490,10 @@ func TestOpenCodeCloudLocationExport(t *testing.T) { } } +func TestOpenCodeUtilityPin_IncludesSystemBinFallback(t *testing.T) { + assert.Contains(t, openCodeUtilityPin(), "'/bin'", "production utility lookup retains the legacy /bin fallback") +} + // requirePinnedSha256sum skips tests that run openCodeUtilityPin on hosts // (macOS) where the pinned directories have no sha256sum. func requirePinnedSha256sum(t *testing.T) { diff --git a/internal/scaffold/fullsend-repo/scripts/fullsend-check-output b/internal/scaffold/fullsend-repo/scripts/fullsend-check-output index 80ed6d896f..a116fbda57 100755 --- a/internal/scaffold/fullsend-repo/scripts/fullsend-check-output +++ b/internal/scaffold/fullsend-repo/scripts/fullsend-check-output @@ -18,14 +18,19 @@ set -euo pipefail -# Use Fullsend's mounted Python and its bundled schema dependencies. +# Prefer Fullsend's mounted Python when available. Older pinned sandbox images +# do not have the mounted tool tree, so retain the system-python path. fullsend_python() ( unset PYTHONHOME PYTHONPATH PYTHONUSERBASE PYTHONSTARTUP PYTHONINSPECT - PYTHONHOME=/opt/fullsend/usr \ - PYTHONPATH=/opt/fullsend/usr/local/share/fullsend/python/site-packages \ - PYTHONNOUSERSITE=1 \ - /opt/fullsend/usr/bin/python3 "$@" + if [[ -x /opt/fullsend/usr/bin/python3 ]]; then + PYTHONHOME=/opt/fullsend/usr \ + PYTHONPATH=/opt/fullsend/usr/local/share/fullsend/python/site-packages \ + PYTHONNOUSERSITE=1 \ + /opt/fullsend/usr/bin/python3 "$@" + else + python3 "$@" + fi ) if [[ $# -lt 1 ]]; then @@ -59,7 +64,11 @@ if [[ "${_actual}" != "${_expected}" ]]; then fi if ! fullsend_python -c "import jsonschema" 2>/dev/null; then - echo "FAIL: mounted Fullsend Python or its jsonschema dependencies are unavailable" + if [[ -x /opt/fullsend/usr/bin/python3 ]]; then + echo "FAIL: mounted Fullsend Python or its jsonschema dependencies are unavailable" + else + echo "FAIL: python3 jsonschema package is not installed" + fi exit 1 fi diff --git a/internal/scaffold/fullsend_check_output_test.go b/internal/scaffold/fullsend_check_output_test.go new file mode 100644 index 0000000000..dd7d3527f8 --- /dev/null +++ b/internal/scaffold/fullsend_check_output_test.go @@ -0,0 +1,227 @@ +package scaffold + +import ( + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const outputCheckJSONSchemaStub = `class ValidationError(Exception): + def __init__(self, message): + super().__init__(message) + self.message = message + self.path = ["ok"] + self.context = [] + +class SchemaError(Exception): + def __init__(self, message): + super().__init__(message) + self.message = message + +def validate(instance, schema): + if not isinstance(schema, dict) or schema.get("type") != "object": + raise SchemaError("schema type must be object") + for name in schema.get("required", []): + if name not in instance: + raise ValidationError("'" + name + "' is a required property") +` + +const outputCheckPythonWrapper = `#!/bin/sh +printf '%s\n' "$FAKE_PYTHON_MODE" >> "$FAKE_PYTHON_LOG" +case "$FAKE_PYTHON_MODE" in + mounted) + [ "${PYTHONHOME-}" = "$FAKE_MOUNTED_HOME" ] || exit 41 + [ "${PYTHONPATH-}" = "$FAKE_MOUNTED_PATH" ] || exit 42 + [ "${PYTHONNOUSERSITE-}" = 1 ] || exit 43 + if [ "${FAKE_MOUNT_BROKEN:-0}" = 1 ]; then exit 44; fi + ;; + legacy) + [ -z "${PYTHONHOME+x}" ] || exit 45 + [ -z "${PYTHONPATH+x}" ] || exit 46 + [ -z "${PYTHONUSERBASE+x}" ] || exit 47 + [ -z "${PYTHONSTARTUP+x}" ] || exit 48 + [ -z "${PYTHONINSPECT+x}" ] || exit 49 + ;; +esac +unset PYTHONHOME PYTHONPATH PYTHONNOUSERSITE PYTHONUSERBASE PYTHONSTARTUP PYTHONINSPECT +PYTHONPATH="$FAKE_JSONSCHEMA_SITE" exec "$FAKE_REAL_PYTHON" "$@" +` + +type outputCheckFixture struct { + root string + script string + bin string + mountRoot string + site string + log string + realPython string + schema string + validOutput string +} + +func newOutputCheckFixture(t *testing.T, installSchema, mountedPresent bool) outputCheckFixture { + t.Helper() + _, testFile, _, ok := runtime.Caller(0) + require.True(t, ok) + realPython, err := exec.LookPath("python3") + if err != nil { + t.Skip("python3 is required for output validation fixtures") + } + + root := t.TempDir() + contents, err := os.ReadFile(filepath.Join(filepath.Dir(testFile), "fullsend-repo", "scripts", "fullsend-check-output")) + require.NoError(t, err) + mountRoot := filepath.Join(root, "mount", "opt", "fullsend") + script := filepath.Join(root, "fullsend-check-output") + // Relocate only the fixed production mount path inside this private test + // copy so tests never write into /opt or require a production override. + contents = []byte(strings.ReplaceAll(string(contents), "/opt/fullsend", mountRoot)) + require.NoError(t, os.WriteFile(script, contents, 0o700)) + + bin := filepath.Join(root, "bin") + mountedBin := filepath.Join(mountRoot, "usr", "bin") + site := filepath.Join(root, "site") + dirs := []string{bin, site} + if mountedPresent { + dirs = append(dirs, mountedBin) + } + for _, dir := range dirs { + require.NoError(t, os.MkdirAll(dir, 0o700)) + } + wrapper := []byte(outputCheckPythonWrapper) + require.NoError(t, os.WriteFile(filepath.Join(bin, "python3"), wrapper, 0o700)) + if mountedPresent { + require.NoError(t, os.WriteFile(filepath.Join(mountedBin, "python3"), wrapper, 0o700)) + } + if installSchema { + pkg := filepath.Join(site, "jsonschema") + require.NoError(t, os.MkdirAll(pkg, 0o700)) + require.NoError(t, os.WriteFile(filepath.Join(pkg, "__init__.py"), []byte(outputCheckJSONSchemaStub), 0o600)) + } else { + pkg := filepath.Join(site, "jsonschema") + require.NoError(t, os.MkdirAll(pkg, 0o700)) + require.NoError(t, os.WriteFile(filepath.Join(pkg, "__init__.py"), []byte("raise ImportError('jsonschema is not installed')\n"), 0o600)) + } + + schema := filepath.Join(root, "schema.json") + validOutput := filepath.Join(root, "agent-result.json") + require.NoError(t, os.WriteFile(schema, []byte(`{"type":"object","required":["ok"]}`), 0o600)) + require.NoError(t, os.WriteFile(validOutput, []byte(`{"ok":true}`), 0o600)) + return outputCheckFixture{ + root: root, script: script, bin: bin, mountRoot: mountRoot, site: site, + log: filepath.Join(root, "python.log"), realPython: realPython, + schema: schema, validOutput: validOutput, + } +} + +func (f outputCheckFixture) run(t *testing.T, mounted, brokenMounted bool, candidate string) (string, error, []string) { + t.Helper() + require.NoError(t, os.WriteFile(f.log, nil, 0o600)) + mode := "legacy" + if mounted { + mode = "mounted" + } + cmd := exec.Command("bash", f.script, candidate) + cmd.Env = []string{ + "PATH=" + f.bin + ":/usr/bin:/bin", + "FULLSEND_OUTPUT_SCHEMA=" + f.schema, + "FAKE_PYTHON_MODE=" + mode, + "FAKE_PYTHON_LOG=" + f.log, + "FAKE_REAL_PYTHON=" + f.realPython, + "FAKE_JSONSCHEMA_SITE=" + f.site, + "FAKE_MOUNTED_HOME=" + filepath.Join(f.mountRoot, "usr"), + "FAKE_MOUNTED_PATH=" + filepath.Join(f.mountRoot, "usr", "local", "share", "fullsend", "python", "site-packages"), + "FAKE_MOUNT_BROKEN=" + map[bool]string{true: "1", false: "0"}[brokenMounted], + "PYTHONHOME=/untrusted/python-home", + "PYTHONPATH=/untrusted/python-path", + "PYTHONUSERBASE=/untrusted/user-base", + "PYTHONSTARTUP=/untrusted/startup", + "PYTHONINSPECT=1", + } + output, err := cmd.CombinedOutput() + + rawLog, readErr := os.ReadFile(f.log) + require.NoError(t, readErr) + var calls []string + for _, call := range strings.Split(strings.TrimSpace(string(rawLog)), "\n") { + if call != "" { + calls = append(calls, call) + } + } + return string(output), err, calls +} + +func TestFullsendCheckOutput_MountedAndLegacyPython(t *testing.T) { + for _, mounted := range []bool{true, false} { + mode := "legacy" + if mounted { + mode = "mounted" + } + t.Run(mode, func(t *testing.T) { + f := newOutputCheckFixture(t, true, mounted) + + t.Run("valid output", func(t *testing.T) { + out, err, calls := f.run(t, mounted, false, f.validOutput) + require.NoError(t, err, out) + assert.Contains(t, out, "PASS: output validated against schema") + assert.NotEmpty(t, calls) + for _, call := range calls { + assert.Equal(t, mode, call) + } + }) + + t.Run("schema-invalid output", func(t *testing.T) { + candidate := filepath.Join(f.root, "agent-result.json") + require.NoError(t, os.WriteFile(candidate, []byte(`{"wrong":true}`), 0o600)) + out, err, _ := f.run(t, mounted, false, candidate) + require.Error(t, err) + assert.Contains(t, out, "FAIL: 'ok' is a required property") + }) + + t.Run("malformed JSON", func(t *testing.T) { + candidate := filepath.Join(f.root, "agent-result.json") + require.NoError(t, os.WriteFile(candidate, []byte("{"), 0o600)) + out, err, _ := f.run(t, mounted, false, candidate) + require.Error(t, err) + assert.Contains(t, out, "is not valid JSON") + }) + + t.Run("missing jsonschema reports selected interpreter", func(t *testing.T) { + f := newOutputCheckFixture(t, false, mounted) + out, err, calls := f.run(t, mounted, false, f.validOutput) + require.Error(t, err) + if mounted { + assert.Contains(t, out, "mounted Fullsend Python or its jsonschema dependencies are unavailable") + } else { + assert.Contains(t, out, "python3 jsonschema package is not installed") + } + for _, call := range calls { + assert.Equal(t, mode, call) + } + }) + + t.Run("filename check is unchanged", func(t *testing.T) { + candidate := filepath.Join(f.root, "wrong-name.json") + require.NoError(t, os.WriteFile(candidate, []byte(`{"ok":true}`), 0o600)) + out, err, calls := f.run(t, mounted, false, candidate) + require.Error(t, err) + assert.Contains(t, out, "filename is 'wrong-name.json' but harness expects 'agent-result.json'") + assert.Empty(t, calls, "filename validation precedes interpreter invocation") + }) + }) + } +} + +func TestFullsendCheckOutput_BrokenMountedPythonDoesNotFallback(t *testing.T) { + f := newOutputCheckFixture(t, true, true) + out, err, calls := f.run(t, true, true, f.validOutput) + require.Error(t, err) + assert.Contains(t, out, "mounted Fullsend Python or its jsonschema dependencies are unavailable") + assert.NotContains(t, calls, "legacy", "a present but broken mounted interpreter must not fall back") +} From abfafa5129b5de3e8e15ec13503c7725c162558c Mon Sep 17 00:00:00 2001 From: Ralph Bean Date: Fri, 13 Nov 2026 13:38:32 -0500 Subject: [PATCH 5/9] fix(#9396): preserve project tool PATH Signed-off-by: Ralph Bean --- internal/cli/run.go | 20 ++++++----- internal/cli/run_env_path_test.go | 54 +++++++++++++++++++++++++++-- internal/runtime/binary_pin_test.go | 33 ++++++++++++++++++ internal/runtime/env_data_test.go | 15 ++++++-- 4 files changed, 108 insertions(+), 14 deletions(-) diff --git a/internal/cli/run.go b/internal/cli/run.go index 6d6647a451..3343260f9b 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -3884,19 +3884,21 @@ func runnerPathRestoreLine() string { return fmt.Sprintf(`export PATH="$%s${PATH:+:$PATH}"`, runnerPathVar) } -// runnerPathLines are the first lines of .env: the Fullsend tool-image paths, -// the sandbox's project toolchain and PATH, then its read-only copy. -// /sandbox/workspace/bin comes last, after the image's own -// PATH: host_files can drop files there, so it may add commands (my-tool.sh, -// and the runner's own fullsend and fullsend-check-output, which exist only -// there) but not replace one the image provides — python3 and tirith for the -// security hooks, node for codex and pi, git, find. +// runnerPathLines are the first lines of .env: Go tools, the sandbox image's +// project PATH, workspace helpers, and finally the mounted Fullsend tools as +// a fallback. This lets an agent use the project's Python packages, Node, +// npm, Git, and other tools while keeping helpers in workspace/bin reachable. +// Fixed runner commands and hooks use the trusted PATH recorded separately. func runnerPathLines() []string { - pathExport := "export PATH=" + sandbox.SandboxFullsendToolPath - pathExport += ":/usr/local/go/bin" + return runnerPathLinesFor(sandbox.SandboxFullsendToolPath) +} + +func runnerPathLinesFor(toolPath string) []string { + pathExport := "export PATH=/usr/local/go/bin" pathExport += ":$HOME/go/bin" pathExport += ":$PATH" pathExport += fmt.Sprintf(":%s/bin", sandbox.SandboxWorkspace) + pathExport += ":" + toolPath return []string{pathExport, runnerPathCaptureLine()} } diff --git a/internal/cli/run_env_path_test.go b/internal/cli/run_env_path_test.go index ac3070344c..af11385f40 100644 --- a/internal/cli/run_env_path_test.go +++ b/internal/cli/run_env_path_test.go @@ -17,7 +17,7 @@ import ( func TestRunnerPathLines(t *testing.T) { t.Parallel() assert.Equal(t, []string{ - "export PATH=" + sandbox.SandboxFullsendToolPath + ":/usr/local/go/bin:$HOME/go/bin:$PATH:/sandbox/workspace/bin", + "export PATH=/usr/local/go/bin:$HOME/go/bin:$PATH:/sandbox/workspace/bin:" + sandbox.SandboxFullsendToolPath, `if ( FULLSEND_RUNNER_PATH= ) 2>/dev/null; then FULLSEND_RUNNER_PATH="$PATH"; readonly FULLSEND_RUNNER_PATH; fi`, }, runnerPathLines()) assert.Equal(t, `export PATH="$FULLSEND_RUNNER_PATH${PATH:+:$PATH}"`, runnerPathRestoreLine()) @@ -50,6 +50,56 @@ func TestHarnessEnvLines_RestoresPathAfterHarnessEntries(t *testing.T) { assert.Equal(t, len(lines)-1, iteration, "iteration.env stays the last line") } +func TestRunnerPathLines_PrefersProjectToolsAndKeepsMountedFallback(t *testing.T) { + t.Parallel() + tmp := t.TempDir() + projectBin := filepath.Join(tmp, "project-bin") + workspaceBin := filepath.Join(tmp, "bin") + mountedLocal := filepath.Join(tmp, "mounted", "usr", "local", "bin") + mountedSystem := filepath.Join(tmp, "mounted", "usr", "bin") + mountedPath := mountedLocal + ":" + mountedSystem + for _, dir := range []string{projectBin, workspaceBin, mountedLocal, mountedSystem} { + require.NoError(t, os.MkdirAll(dir, 0o755)) + } + writeTool := func(dir, name, marker string) { + t.Helper() + require.NoError(t, os.WriteFile(filepath.Join(dir, name), []byte("#!/bin/sh\necho "+marker+"\n"), 0o755)) + } + for _, name := range []string{"python3", "node", "npm", "git"} { + writeTool(projectBin, name, "PROJECT-"+name) + writeTool(mountedLocal, name, "MOUNTED-"+name) + } + writeTool(mountedSystem, "mounted-only", "MOUNTED-ONLY") + writeTool(workspaceBin, "workspace-only", "WORKSPACE-ONLY") + + lines := append(runnerPathLinesFor(mountedPath), harnessEnvLines(&harness.Harness{})...) + content := strings.ReplaceAll(strings.Join(lines, "\n")+"\n", sandbox.SandboxWorkspace, tmp) + envFile := filepath.Join(tmp, ".env") + require.NoError(t, os.WriteFile(envFile, []byte(content), 0o644)) + + cmd := exec.Command("/bin/sh", "-c", `. "$ENVFILE" && python3 && node && npm && git && mounted-only && workspace-only && echo "PATH=$PATH"`) + cmd.Env = []string{"PATH=" + projectBin + ":/usr/bin:/bin", "HOME=" + tmp, "ENVFILE=" + envFile} + out, err := cmd.CombinedOutput() + require.NoError(t, err, string(out)) + for _, want := range []string{"PROJECT-python3", "PROJECT-node", "PROJECT-npm", "PROJECT-git", "MOUNTED-ONLY", "WORKSPACE-ONLY"} { + assert.Contains(t, string(out), want) + } + assert.NotContains(t, string(out), "MOUNTED-python3") + assert.NotContains(t, string(out), "MOUNTED-node") + assert.NotContains(t, string(out), "MOUNTED-npm") + assert.NotContains(t, string(out), "MOUNTED-git") + + printed := strings.TrimSpace(string(out)[strings.LastIndex(string(out), "PATH="):]) + projectAt := strings.Index(printed, projectBin+":") + workspaceAt := strings.Index(printed, workspaceBin+":") + mountedAt := strings.Index(printed, mountedLocal+":"+mountedSystem) + require.NotEqual(t, -1, projectAt, printed) + require.NotEqual(t, -1, workspaceAt, printed) + require.NotEqual(t, -1, mountedAt, printed) + assert.Less(t, projectAt, workspaceAt, "project tools precede workspace helpers") + assert.Less(t, workspaceAt, mountedAt, "mounted tools are the fallback after project tools and helpers") +} + // TestEnvFilePath_EnvDCannotShadowRunnerPath sources the generated .env under // a real shell. An .env.d file that prepends a directory to PATH keeps its // extra tools reachable but cannot shadow a name the runner's PATH already @@ -168,7 +218,7 @@ func TestEnvFilePath_EnvDCannotShadowRunnerPath(t *testing.T) { require.NotEqual(t, -1, sysAt, printed) require.NotEqual(t, -1, binAt, printed) assert.Less(t, sysAt, binAt, "workspace bin comes after the image PATH") - assert.True(t, strings.HasPrefix(printed, "PATH="+sandbox.SandboxFullsendToolPath+":/usr/local/go/bin:"), "runner PATH comes first: %s", printed) + assert.True(t, strings.HasPrefix(printed, "PATH=/usr/local/go/bin:"+filepath.Join(tmp, "go", "bin")+":"), "Go tools remain ahead of project PATH: %s", printed) } }) } diff --git a/internal/runtime/binary_pin_test.go b/internal/runtime/binary_pin_test.go index 42b49c4564..4d41f29c3d 100644 --- a/internal/runtime/binary_pin_test.go +++ b/internal/runtime/binary_pin_test.go @@ -213,6 +213,39 @@ func TestBinaryPin_PinsNodeForNodeScripts(t *testing.T) { } } +func TestBinaryPin_PrefersMountedCLIAndNode(t *testing.T) { + t.Parallel() + for _, shell := range pinShells() { + for _, c := range cliPins { + t.Run(filepath.Base(shell)+"/"+c.name, func(t *testing.T) { + t.Parallel() + root := t.TempDir() + mountedLocal := filepath.Join(root, "mounted", "usr", "local", "bin") + mountedSystem := filepath.Join(root, "mounted", "usr", "bin") + projectBin := filepath.Join(root, "project", "bin") + for _, dir := range []string{mountedLocal, mountedSystem, projectBin} { + require.NoError(t, os.MkdirAll(dir, 0o755)) + } + mountedCLI := filepath.Join(mountedLocal, c.name) + require.NoError(t, os.WriteFile(mountedCLI, []byte(nodeShebangInterpreter+"\nconsole.log('mounted cli')\n"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(mountedSystem, "node"), []byte("#!/bin/sh\necho MOUNTED-NODE \"$@\"\n"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(projectBin, c.name), []byte("#!/bin/sh\necho PROJECT-CLI\n"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(projectBin, "node"), []byte("#!/bin/sh\necho PROJECT-NODE\n"), 0o755)) + + toolPath := mountedLocal + ":" + mountedSystem + pin := strings.Replace(c.pin(), envDataTrustedPath(), envDataTrustedPathFor(toolPath), 1) + command := protectedDirsShell(t, filepath.Join(root, "mounted"), filepath.Join(root, "project")) + + pin + " && " + cliLaunch(c.binVar, c.nodeVar) + cmd := exec.Command(shell, "-c", command) + cmd.Env = []string{"PATH=" + projectBin + ":" + os.Getenv("PATH"), "HOME=" + root} + out, err := cmd.CombinedOutput() + require.NoError(t, err, string(out)) + assert.Equal(t, "MOUNTED-NODE "+mountedCLI+"\n", string(out), "both the CLI and its /usr/bin/env node interpreter come from the mount") + }) + } + } +} + // A CLI that starts through env with any other first line is refused: env // would look its interpreter up on the PATH the launch has by then. A CLI // with an absolute interpreter starts directly. diff --git a/internal/runtime/env_data_test.go b/internal/runtime/env_data_test.go index dcbd38f3c0..ad96d60e26 100644 --- a/internal/runtime/env_data_test.go +++ b/internal/runtime/env_data_test.go @@ -695,10 +695,13 @@ func TestEnvDataTrustedPath_MountedOnlyToolLookup(t *testing.T) { } mountedTool := filepath.Join(toolDirs[0], "fullsend-only") require.NoError(t, os.WriteFile(mountedTool, []byte("#!/bin/sh\necho mounted\n"), 0o755)) + mountedConflict := filepath.Join(toolDirs[1], "conflicting") + require.NoError(t, os.WriteFile(mountedConflict, []byte("#!/bin/sh\necho mounted-conflict\n"), 0o755)) projectBin := filepath.Join(root, "project", "bin") require.NoError(t, os.MkdirAll(projectBin, 0o755)) - projectTool := filepath.Join(projectBin, "conflicting") - require.NoError(t, os.WriteFile(projectTool, []byte("#!/bin/sh\necho project\n"), 0o755)) + projectOnlyTool := filepath.Join(projectBin, "project-only") + require.NoError(t, os.WriteFile(projectOnlyTool, []byte("#!/bin/sh\necho project\n"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(projectBin, "conflicting"), []byte("#!/bin/sh\necho project-conflict\n"), 0o755)) // Model an agent account that cannot own or rewrite the mounted image. // The real filesystem and executable lookup remain in use. @@ -714,7 +717,13 @@ func TestEnvDataTrustedPath_MountedOnlyToolLookup(t *testing.T) { cmd.Env = []string{"PATH=" + path} out, err = cmd.Output() require.NoError(t, err) - assert.Equal(t, projectTool, strings.TrimSpace(string(out)), "ambient project tools remain reachable after mounted-only tools") + assert.Equal(t, mountedConflict, strings.TrimSpace(string(out)), "the trusted PATH prefers mounted tools over conflicting ambient tools") + + cmd = exec.Command("/bin/sh", "-c", protectedRoot+envDataTrustedPathFor(strings.Join(toolDirs, ":"))+` && PATH="$`+envDataTrustedPathVar+`" command -v project-only`) + cmd.Env = []string{"PATH=" + path} + out, err = cmd.Output() + require.NoError(t, err) + assert.Equal(t, projectOnlyTool, strings.TrimSpace(string(out)), "ambient tools remain available after mounted-only tools") } func TestSandboxFullsendToolPathCommandAt_PrefersMountedTool(t *testing.T) { From ef95e5ffeab6891fb05b9eeba667c9bfad437690 Mon Sep 17 00:00:00 2001 From: Ralph Bean Date: Fri, 13 Nov 2026 13:42:14 -0500 Subject: [PATCH 6/9] fix(#9396): validate and normalize image mounts Signed-off-by: Ralph Bean --- internal/harness/forge.go | 2 + internal/harness/harness.go | 9 -- internal/harness/image_mount.go | 37 ++++- internal/harness/image_mount_test.go | 197 ++++++++++++++++++++++++++- 4 files changed, 234 insertions(+), 11 deletions(-) diff --git a/internal/harness/forge.go b/internal/harness/forge.go index 487dea1ee8..f70baba5d9 100644 --- a/internal/harness/forge.go +++ b/internal/harness/forge.go @@ -295,6 +295,7 @@ func (h *Harness) validateOverlays() error { // runtime.forge == "github") that fails on key access when event is empty // does not prevent a broader fallback overlay from matching. func (h *Harness) ResolveOverlays(event map[string]any, forgePlatform string, config map[string]any) error { + h.normalizeImageMounts() // Record GITHUB_ISSUE_URL diagnostics before the overlays are consumed // so Lint() still sees non-matching entries (#8742). h.captureDeprecatedIssueURL() @@ -346,6 +347,7 @@ func (h *Harness) ResolveOverlays(event map[string]any, forgePlatform string, co // call sees nil and is a no-op, which is correct because the forge map // was already validated before merging. func (h *Harness) ResolveForge(platform string) error { + h.normalizeImageMounts() // Record GITHUB_ISSUE_URL diagnostics before the forge map is consumed // so Lint() still sees non-matching forge variants (#8742). h.captureDeprecatedIssueURL() diff --git a/internal/harness/harness.go b/internal/harness/harness.go index 2c4005e200..87f6176d8f 100644 --- a/internal/harness/harness.go +++ b/internal/harness/harness.go @@ -508,15 +508,6 @@ func parseRaw(data []byte) (*Harness, error) { if err := yaml.Unmarshal(data, &h); err != nil { return nil, fmt.Errorf("parsing harness YAML: %w", err) } - h.ImageMounts = mergeImageMounts(nil, h.ImageMounts) - for _, fc := range h.Forge { - if fc != nil { - fc.ImageMounts = mergeImageMounts(nil, fc.ImageMounts) - } - } - for i := range h.Overlays { - h.Overlays[i].ImageMounts = mergeImageMounts(nil, h.Overlays[i].ImageMounts) - } if err := validateSchemaVersion(h.SchemaVersion); err != nil { return nil, fmt.Errorf("parsing harness YAML: %w", err) } diff --git a/internal/harness/image_mount.go b/internal/harness/image_mount.go index 678361ce27..1c129a5eda 100644 --- a/internal/harness/image_mount.go +++ b/internal/harness/image_mount.go @@ -24,7 +24,37 @@ func mergeImageMounts(base, child []ImageMount) []ImageMount { return merged } +func (h *Harness) normalizeImageMounts() { + if h.ImageMounts != nil { + h.ImageMounts = mergeImageMounts(nil, h.ImageMounts) + } + for _, config := range h.Forge { + if config != nil && config.ImageMounts != nil { + config.ImageMounts = mergeImageMounts(nil, config.ImageMounts) + } + } + for i := range h.Overlays { + if h.Overlays[i].ImageMounts != nil { + h.Overlays[i].ImageMounts = mergeImageMounts(nil, h.Overlays[i].ImageMounts) + } + } +} + +func reservedImageMountPaths() []string { + paths := []string{reservedHostFileBinDir, "/sandbox/opencode-config"} + paths = append(paths, reservedHostFileExact...) + paths = append(paths, reservedHostFileDirs...) + return paths +} + func validateImageMounts(mounts []ImageMount, hostFiles []HostFile, field string) error { + hostFilesField := "host_files" + if strings.HasSuffix(field, "image_mounts") { + prefix := strings.TrimSuffix(field, "image_mounts") + if prefix != "" { + hostFilesField = prefix + "host_files" + } + } for i, mount := range mounts { prefix := fmt.Sprintf("%s[%d]", field, i) if mount.Image == "" || strings.TrimSpace(mount.Image) != mount.Image || strings.Contains(mount.Image, "${") || strings.IndexFunc(mount.Image, unicode.IsSpace) >= 0 || strings.Contains(mount.Image, "://") { @@ -47,9 +77,14 @@ func validateImageMounts(mounts []ImageMount, hostFiles []HostFile, field string if mount.Dest == "/" { return fmt.Errorf("%s.dest must not replace the container root", prefix) } + for _, reserved := range reservedImageMountPaths() { + if pathsOverlap(mount.Dest, reserved) { + return fmt.Errorf("%s.dest %q overlaps runner-owned path %q", prefix, mount.Dest, reserved) + } + } for j, hostFile := range hostFiles { if pathsOverlap(mount.Dest, hostFile.Dest) { - return fmt.Errorf("%s.dest %q overlaps host_files[%d].dest %q", prefix, mount.Dest, j, hostFile.Dest) + return fmt.Errorf("%s.dest %q overlaps %s[%d].dest %q", prefix, mount.Dest, hostFilesField, j, hostFile.Dest) } } for j := 0; j < i; j++ { diff --git a/internal/harness/image_mount_test.go b/internal/harness/image_mount_test.go index 29fc9e6d4f..12a46af331 100644 --- a/internal/harness/image_mount_test.go +++ b/internal/harness/image_mount_test.go @@ -49,6 +49,15 @@ func TestValidateImageMounts(t *testing.T) { {Image: "registry.example/base:v1", Dest: "/opt/tools"}, {Image: "registry.example/child:v1", Dest: "/opt/tools"}, }}, + {name: "mounted Fullsend tools image", mounts: []ImageMount{{Image: "registry.example/tools:v1", Dest: "/opt/fullsend"}}}, + {name: "reserved workspace binaries", mounts: []ImageMount{{Image: "registry.example/tools:v1", Dest: "/sandbox/workspace/bin"}}, wantError: "overlaps runner-owned path"}, + {name: "reserved workspace environment", mounts: []ImageMount{{Image: "registry.example/tools:v1", Dest: "/sandbox/workspace/.env"}}, wantError: "overlaps runner-owned path"}, + {name: "reserved runtime config", mounts: []ImageMount{{Image: "registry.example/tools:v1", Dest: "/sandbox/claude-config"}}, wantError: "overlaps runner-owned path"}, + {name: "ancestor of runner paths", mounts: []ImageMount{{Image: "registry.example/tools:v1", Dest: "/sandbox"}}, wantError: "overlaps runner-owned path"}, + {name: "descendant of runtime config", mounts: []ImageMount{{Image: "registry.example/tools:v1", Dest: "/sandbox/opencode-config/hooks"}}, wantError: "overlaps runner-owned path"}, + {name: "sibling with similar prefix", mounts: []ImageMount{{Image: "registry.example/tools:v1", Dest: "/sandbox/workspace/bin-tools"}}}, + {name: "reserved workspace metadata", mounts: []ImageMount{{Image: "registry.example/tools:v1", Dest: "/sandbox/workspace/.fullsend/output.json"}}, wantError: "overlaps runner-owned path"}, + {name: "reserved security metadata", mounts: []ImageMount{{Image: "registry.example/tools:v1", Dest: "/sandbox/workspace/.security/findings.json"}}, wantError: "overlaps runner-owned path"}, {name: "overlapping host file", mounts: []ImageMount{{Image: "registry.example/tools:latest", Dest: "/opt/tools"}}, hostFiles: []HostFile{{Src: "agent.env", Dest: "/opt/tools/env"}}, wantError: "overlaps host_files[0].dest"}, {name: "overlapping image mounts", mounts: []ImageMount{ {Image: "registry.example/parent:v1", Dest: "/opt/tools"}, @@ -94,12 +103,16 @@ image_mounts: dest: /opt/fullsend - image: registry.example/config:v1 dest: /etc/tool + - image: registry.example/base-extra:v1 + dest: /opt/extra `) path := writeTestHarness(t, dir, "child.yaml", ` base: base.yaml image_mounts: - image: registry.example/custom-tools:v2 dest: /opt/fullsend + - image: registry.example/custom-extra:v2 + dest: /opt/extra `) h, _, err := LoadWithBase(context.Background(), path, ComposeOpts{}) @@ -107,15 +120,108 @@ image_mounts: assert.Equal(t, []ImageMount{ {Image: "registry.example/custom-tools:v2", Dest: "/opt/fullsend"}, {Image: "registry.example/config:v1", Dest: "/etc/tool"}, + {Image: "registry.example/custom-extra:v2", Dest: "/opt/extra"}, }, h.ImageMounts) } +func TestLoadWithOpts_NormalizesStandaloneImageMounts(t *testing.T) { + path := writeTestHarness(t, t.TempDir(), "standalone.yaml", ` +agent: agents/test.md +role: test +image_mounts: + - image: registry.example/base:v1 + dest: /opt/fullsend + - image: registry.example/extra:v1 + dest: /opt/extra + - image: registry.example/override:v2 + dest: /opt/fullsend +`) + + h, err := LoadWithOpts(path, LoadOpts{}) + require.NoError(t, err) + assert.Equal(t, []ImageMount{ + {Image: "registry.example/override:v2", Dest: "/opt/fullsend"}, + {Image: "registry.example/extra:v1", Dest: "/opt/extra"}, + }, h.ImageMounts) +} + +func TestLoadWithBase_RejectsRunnerOwnedMount(t *testing.T) { + dir := t.TempDir() + writeTestHarness(t, dir, "base.yaml", ` +agent: agents/base.md +role: test +image_mounts: + - image: registry.example/tools:v1 + dest: /sandbox +`) + path := writeTestHarness(t, dir, "child.yaml", ` +base: base.yaml +agent: agents/child.md +role: test +`) + _, _, err := LoadWithBase(context.Background(), path, ComposeOpts{}) + require.Error(t, err) + assert.Contains(t, err.Error(), `image_mounts[0].dest "/sandbox" overlaps runner-owned path`) +} + +func TestLoadRaw_PreservesImageMountOmissionAndDuplicates(t *testing.T) { + dir := t.TempDir() + omitted := writeTestHarness(t, dir, "omitted.yaml", ` +agent: agents/test.md +forge: + github: + pre_script: scripts/github.sh +overlays: + - when: "true" +`) + h, err := LoadRaw(omitted) + require.NoError(t, err) + assert.Nil(t, h.ImageMounts, "raw omission stays nil") + assert.Nil(t, h.Forge["github"].ImageMounts, "raw forge omission stays nil") + assert.Nil(t, h.Overlays[0].ImageMounts, "raw overlay omission stays nil") + + duplicates := writeTestHarness(t, dir, "duplicates.yaml", ` +agent: agents/test.md +image_mounts: + - image: registry.example/base:v1 + dest: /opt/fullsend + - image: registry.example/override:v2 + dest: /opt/fullsend +forge: + github: + image_mounts: + - image: registry.example/forge:v1 + dest: /opt/tools + - image: registry.example/forge-override:v2 + dest: /opt/tools +overlays: + - when: "true" + image_mounts: + - image: registry.example/overlay:v1 + dest: /opt/overlay + - image: registry.example/overlay-override:v2 + dest: /opt/overlay +`) + h, err = LoadRaw(duplicates) + require.NoError(t, err) + require.Len(t, h.ImageMounts, 2) + assert.Equal(t, "registry.example/base:v1", h.ImageMounts[0].Image) + assert.Equal(t, "registry.example/override:v2", h.ImageMounts[1].Image) + require.Len(t, h.Forge["github"].ImageMounts, 2) + assert.Equal(t, "registry.example/forge:v1", h.Forge["github"].ImageMounts[0].Image) + assert.Equal(t, "registry.example/forge-override:v2", h.Forge["github"].ImageMounts[1].Image) + require.Len(t, h.Overlays[0].ImageMounts, 2) + assert.Equal(t, "registry.example/overlay:v1", h.Overlays[0].ImageMounts[0].Image) + assert.Equal(t, "registry.example/overlay-override:v2", h.Overlays[0].ImageMounts[1].Image) +} + func TestResolveForge_ImageMountsOverrideByDestination(t *testing.T) { h := &Harness{ Agent: "agents/test.md", ImageMounts: []ImageMount{{Image: "registry.example/base:v1", Dest: "/opt/tools"}}, Forge: map[string]*ForgeConfig{ "github": {ImageMounts: []ImageMount{ + {Image: "registry.example/old-github:v1", Dest: "/opt/tools"}, {Image: "registry.example/github:v2", Dest: "/opt/tools"}, {Image: "registry.example/extras:v1", Dest: "/opt/extras"}, }}, @@ -131,10 +237,15 @@ func TestResolveForge_ImageMountsOverrideByDestination(t *testing.T) { func TestResolveOverlays_ImageMountsOverrideByDestination(t *testing.T) { h := &Harness{ - ImageMounts: []ImageMount{{Image: "registry.example/base:v1", Dest: "/opt/tools"}}, + ImageMounts: []ImageMount{ + {Image: "registry.example/base:v1", Dest: "/opt/tools"}, + {Image: "registry.example/extra:v1", Dest: "/opt/base-extra"}, + {Image: "registry.example/base-override:v2", Dest: "/opt/tools"}, + }, Overlays: []OverlayEntry{{ When: "true", ForgeConfig: ForgeConfig{ImageMounts: []ImageMount{ + {Image: "registry.example/old-overlay:v1", Dest: "/opt/tools"}, {Image: "registry.example/overlay:v2", Dest: "/opt/tools"}, {Image: "registry.example/extra:v1", Dest: "/opt/extra"}, }}, @@ -144,6 +255,7 @@ func TestResolveOverlays_ImageMountsOverrideByDestination(t *testing.T) { require.NoError(t, h.ResolveOverlays(nil, "github", nil)) assert.Equal(t, []ImageMount{ {Image: "registry.example/overlay:v2", Dest: "/opt/tools"}, + {Image: "registry.example/extra:v1", Dest: "/opt/base-extra"}, {Image: "registry.example/extra:v1", Dest: "/opt/extra"}, }, h.ImageMounts) } @@ -161,6 +273,89 @@ func TestValidateImageMountsAcrossHarnessLayers(t *testing.T) { assert.Contains(t, err.Error(), "overlaps host_files[0].dest") } +func TestValidateImageMountsReservedPathsAcrossConfigs(t *testing.T) { + for _, tc := range []struct { + name string + h *Harness + want string + }{ + { + name: "top-level", + h: &Harness{Agent: "agents/test.md", Role: "test", ImageMounts: []ImageMount{{Image: "registry.example/tools:v1", Dest: "/sandbox/workspace/bin"}}}, + want: "image_mounts[0].dest", + }, + { + name: "forge", + h: &Harness{Agent: "agents/test.md", Role: "test", Forge: map[string]*ForgeConfig{ + "github": {ImageMounts: []ImageMount{{Image: "registry.example/tools:v1", Dest: "/sandbox/codex-config/hooks"}}}, + }}, + want: "forge.github.image_mounts[0].dest", + }, + { + name: "overlay", + h: &Harness{Agent: "agents/test.md", Role: "test", Overlays: []OverlayEntry{{ + When: "true", ForgeConfig: ForgeConfig{ImageMounts: []ImageMount{{Image: "registry.example/tools:v1", Dest: "/sandbox/workspace/.security/log"}}}, + }}}, + want: "overlays[0].image_mounts[0].dest", + }, + } { + t.Run(tc.name, func(t *testing.T) { + err := tc.h.Validate() + require.Error(t, err) + assert.Contains(t, err.Error(), tc.want) + assert.Contains(t, err.Error(), "overlaps runner-owned path") + }) + } +} + +func TestValidateImageMountHostFileDiagnosticPrefixes(t *testing.T) { + for _, tc := range []struct { + name string + err func() error + want string + }{ + { + name: "top-level", + err: func() error { + h := &Harness{Agent: "agents/test.md", Role: "test", + ImageMounts: []ImageMount{{Image: "registry.example/tools:v1", Dest: "/tmp/tools"}}, + HostFiles: []HostFile{{Src: "env", Dest: "/tmp/tools/env"}}, + } + return h.Validate() + }, + want: "host_files[0].dest", + }, + { + name: "forge", + err: func() error { + h := &Harness{Forge: map[string]*ForgeConfig{"github": { + ImageMounts: []ImageMount{{Image: "registry.example/tools:v1", Dest: "/tmp/tools"}}, + HostFiles: []HostFile{{Src: "env", Dest: "/tmp/tools/env"}}, + }}} + return h.validateForge() + }, + want: "forge.github.host_files[0].dest", + }, + { + name: "overlay", + err: func() error { + h := &Harness{Overlays: []OverlayEntry{{When: "true", ForgeConfig: ForgeConfig{ + ImageMounts: []ImageMount{{Image: "registry.example/tools:v1", Dest: "/tmp/tools"}}, + HostFiles: []HostFile{{Src: "env", Dest: "/tmp/tools/env"}}, + }}}} + return h.validateOverlays() + }, + want: "overlays[0].host_files[0].dest", + }, + } { + t.Run(tc.name, func(t *testing.T) { + err := tc.err() + require.Error(t, err) + assert.Contains(t, err.Error(), "overlaps "+tc.want) + }) + } +} + func TestValidateImageMountsInForgeAndOverlay(t *testing.T) { for _, tc := range []struct { name string From 44cca0560725f6f03bd01dfcb788624a21335835 Mon Sep 17 00:00:00 2001 From: Ralph Bean Date: Fri, 13 Nov 2026 14:00:41 -0500 Subject: [PATCH 7/9] fix(#9396): guard image mount gateway setup Signed-off-by: Ralph Bean --- action.yml | 22 +++++++ docs/guides/user/bring-your-own-agent.md | 58 ++++++++++++---- internal/cli/run.go | 13 ++++ internal/cli/run_image_mount_policy.go | 57 ++++++++++++++++ internal/cli/run_image_mount_policy_test.go | 67 +++++++++++++++++++ internal/cli/run_image_pull.go | 10 ++- internal/cli/run_image_pull_test.go | 15 +++++ internal/cli/run_openai_test.go | 51 +++++++++++++- internal/sandbox/sandbox.go | 67 +++++++++++++++++-- internal/sandbox/sandbox_test.go | 73 +++++++++++++++++++++ 10 files changed, 415 insertions(+), 18 deletions(-) create mode 100644 internal/cli/run_image_mount_policy.go create mode 100644 internal/cli/run_image_mount_policy_test.go diff --git a/action.yml b/action.yml index 83cc1fcaa3..3739ef44d2 100644 --- a/action.yml +++ b/action.yml @@ -75,6 +75,13 @@ inputs: description: GCP project ID, used only when the selected agent resolves to Vertex inference. required: false default: "" + allow-image-mounts: + description: >- + Opt in to read-only Podman image mounts on the action's locally generated + OpenShell gateway. This enables caller driver config and disables Podman + resource admission for that local gateway. It does not change remote gateways. + required: false + default: "false" runner_secrets: description: >- JSON object of name → value (the FULLSEND_GITHUB_RUNNER_SECRETS secret). @@ -475,7 +482,14 @@ runs: - name: Configure OpenShell gateway if: steps.sandbox-host.outputs.local == 'true' shell: bash + env: + ALLOW_IMAGE_MOUNTS: ${{ inputs.allow-image-mounts }} run: | + set -euo pipefail + case "${ALLOW_IMAGE_MOUNTS}" in + true|false) ;; + *) echo "::error::allow-image-mounts must be true or false"; exit 1 ;; + esac source "$GITHUB_ACTION_PATH/.github/scripts/openshell-version.sh" mkdir -p $HOME/.config/openshell/ cat > $HOME/.config/openshell/gateway.env << EOF @@ -492,6 +506,14 @@ runs: supervisor_image = "ghcr.io/nvidia/openshell/supervisor:${OPENSHELL_VERSION}" health_check_interval_secs = 10 EOF + if [[ "${ALLOW_IMAGE_MOUNTS}" == "true" ]]; then + cat >> "$HOME/.config/openshell/gateway.toml" << EOF + allow_driver_config = true + + [openshell.drivers.podman.resource_admission] + enabled = false + EOF + fi # The upstream installer needs sudo and starts a local gateway service, so # a remote-gateway runner that already has the CLI skips it. diff --git a/docs/guides/user/bring-your-own-agent.md b/docs/guides/user/bring-your-own-agent.md index e843fcbf8b..8616565afa 100644 --- a/docs/guides/user/bring-your-own-agent.md +++ b/docs/guides/user/bring-your-own-agent.md @@ -531,17 +531,53 @@ image_mounts: ``` Fullsend mounts the image read-only. Its OCI `ENV`, user, working directory -and entrypoint do not apply. The sandbox policy must include `/opt/fullsend` -in `filesystem_policy.read_only`. The OpenShell Podman gateway must enable -`allow_driver_config` and disable resource admission. The `fullsend-sandbox` -package publishes a matching mount-ready `fullsend-sandbox-tools` image; use -that image rather than mounting the ordinary sandbox image, whose -`/opt/fullsend/usr` compatibility link would point back into the sandbox. -The mount image should use the same -OpenShell sandbox base, or a Linux image with compatible system libraries and -Python/Node runtimes. The local Podman backend supports this PoC; other -backends may reject the mount. For merge behavior and destination rules, see -the [harness merge rules](../../reference/harness-reference.md#field-merge-rules-for-base-and-overlays). +and entrypoint do not apply. The effective sandbox policy must grant access to +each mount destination through `filesystem_policy.read_only` or +`filesystem_policy.read_write`; an allowed ancestor also grants access. Earlier +scaffolds and custom policies are not changed automatically. Add `/opt/fullsend` +or an allowed ancestor to the policy used by the harness. Fullsend checks the +effective policy after sandbox creation and before bootstrap, then reports the +policy and mount path when access is missing. + +Image mounts use OpenShell's Podman driver configuration. The local gateway +created by this action keeps mounts disabled by default. Set +`allow-image-mounts: true` on the action to enable `allow_driver_config` and +disable resource admission for that local Podman gateway. Disabling admission +removes its label checks for external attachments, so use this opt-in only when +trusted workflows control the harness. For a remote gateway, its operator must +configure those same settings under `[openshell.drivers.podman]` and +`[openshell.drivers.podman.resource_admission]`; the action leaves remote +configuration untouched. OpenShell 0.1.4 `gateway info --output json` reports +compute-driver names and versions but not these effective settings. A rejected +mount reports the required settings; other backends may not support image +mounts. Set the action input for a local gateway: + +```yaml +with: + allow-image-mounts: true +``` + +For a remote Podman gateway, its operator configures: +```toml +[openshell.drivers.podman] +allow_driver_config = true + +[openshell.drivers.podman.resource_admission] +enabled = false +``` + +On a local gateway, Fullsend can pre-pull private GHCR images with the workflow +token. For a remote gateway it skips runner-local Podman pulls because that +image store is separate. Private images then need registry authentication or a +cached copy on the gateway host; public images can still be pulled there. +Fullsend does not send the workflow token to the gateway or sandbox. + +The `fullsend-sandbox` package publishes a matching mount-ready +`fullsend-sandbox-tools` image; use that image rather than mounting the ordinary +sandbox image, whose `/opt/fullsend/usr` compatibility link would point back +into the sandbox. The mount image should use the same OpenShell sandbox base, or +a Linux image with compatible system libraries and Python/Node runtimes. For +merge behavior and destination rules, see the [harness merge rules](../../reference/harness-reference.md#field-merge-rules-for-base-and-overlays). Distinct image mount destinations cannot contain one another (for example, `/opt/fullsend` and `/opt/fullsend/org-tools`) or overlap a `host_files` destination. A child can still replace an inherited image mount at the exact diff --git a/internal/cli/run.go b/internal/cli/run.go index 3343260f9b..abcab5a096 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -2147,6 +2147,19 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep return fmt.Errorf("creating sandbox: %w", err) } finalizeSandboxSpan(sandboxSpan, nil) + if len(h.ImageMounts) > 0 { + printer.StepStart("Checking image mount filesystem policy") + policy, err := sandbox.EffectivePolicy(ctx, sandboxName) + if err == nil { + err = checkImageMountPolicyAccess(policy, h.Policy, h.ImageMounts) + } + if err != nil { + printer.StepFail("Image mount filesystem policy check failed") + discardSandbox(sandboxName, runDir, keepSandbox, printer) + return err + } + printer.StepDone("Image mount filesystem access is allowed") + } for _, mount := range h.ImageMounts { if mount.Dest != sandbox.SandboxFullsendRoot { continue diff --git a/internal/cli/run_image_mount_policy.go b/internal/cli/run_image_mount_policy.go new file mode 100644 index 0000000000..8713553907 --- /dev/null +++ b/internal/cli/run_image_mount_policy.go @@ -0,0 +1,57 @@ +package cli + +import ( + "fmt" + "path" + "strings" + + "github.com/fullsend-ai/fullsend/internal/harness" + "gopkg.in/yaml.v3" +) + +type imageMountFilesystemPolicy struct { + FilesystemPolicy struct { + ReadOnly []string `yaml:"read_only"` + ReadWrite []string `yaml:"read_write"` + } `yaml:"filesystem_policy"` +} + +// checkImageMountPolicyAccess checks only whether each mount destination is +// covered by an effective read-only or read-write filesystem path. It is not +// a general Landlock policy evaluator; the read-only image mount itself still +// prevents writes. +func checkImageMountPolicyAccess(policyYAML []byte, policyName string, mounts []harness.ImageMount) error { + if len(mounts) == 0 { + return nil + } + var effective imageMountFilesystemPolicy + if err := yaml.Unmarshal(policyYAML, &effective); err != nil { + return fmt.Errorf("parsing effective sandbox policy %q for image mounts: %w", policyName, err) + } + allowedPaths := append(effective.FilesystemPolicy.ReadOnly, effective.FilesystemPolicy.ReadWrite...) + for _, mount := range mounts { + if imageMountPathAllowed(mount.Dest, allowedPaths) { + continue + } + return fmt.Errorf("effective sandbox policy %q does not grant filesystem access to image mount destination %q; add that path or an allowed ancestor to filesystem_policy.read_only or filesystem_policy.read_write", policyName, mount.Dest) + } + return nil +} + +func imageMountPathAllowed(target string, allowedPaths []string) bool { + if !path.IsAbs(target) || path.Clean(target) != target { + return false + } + target = path.Clean(target) + for _, allowed := range allowedPaths { + allowed = strings.TrimSpace(allowed) + if !path.IsAbs(allowed) { + continue + } + allowed = path.Clean(allowed) + if target == allowed || allowed == "/" || strings.HasPrefix(target, strings.TrimSuffix(allowed, "/")+"/") { + return true + } + } + return false +} diff --git a/internal/cli/run_image_mount_policy_test.go b/internal/cli/run_image_mount_policy_test.go new file mode 100644 index 0000000000..6893c5c5f2 --- /dev/null +++ b/internal/cli/run_image_mount_policy_test.go @@ -0,0 +1,67 @@ +package cli + +import ( + "testing" + + "github.com/fullsend-ai/fullsend/internal/harness" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCheckImageMountPolicyAccess(t *testing.T) { + tests := []struct { + name string + policy string + mounts []harness.ImageMount + wantErrPart string + }{ + { + name: "exact read-only path", + policy: "filesystem_policy:\n read_only: [/opt/fullsend]\n", + mounts: []harness.ImageMount{{Dest: "/opt/fullsend"}}, + }, + { + name: "read-only ancestor", + policy: "filesystem_policy:\n read_only: [/opt]\n", + mounts: []harness.ImageMount{{Dest: "/opt/fullsend"}}, + }, + { + name: "read-write ancestor permits access to read-only mount", + policy: "filesystem_policy:\n read_write: [/sandbox]\n", + mounts: []harness.ImageMount{{Dest: "/sandbox/tools"}}, + }, + { + name: "missing access", + policy: "filesystem_policy:\n read_only: [/usr]\n", + mounts: []harness.ImageMount{{Dest: "/opt/fullsend"}}, + wantErrPart: `policy "custom-policy" does not grant filesystem access to image mount destination "/opt/fullsend"`, + }, + { + name: "sibling prefix does not grant access", + policy: "filesystem_policy:\n read_only: [/opt/fullsend-tools]\n", + mounts: []harness.ImageMount{{Dest: "/opt/fullsend"}}, + wantErrPart: "/opt/fullsend", + }, + { + name: "descendant permission does not grant mount root", + policy: "filesystem_policy:\n read_only: [/opt/fullsend/bin]\n", + mounts: []harness.ImageMount{{Dest: "/opt/fullsend"}}, + wantErrPart: "/opt/fullsend", + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + err := checkImageMountPolicyAccess([]byte(tc.policy), "custom-policy", tc.mounts) + if tc.wantErrPart == "" { + require.NoError(t, err) + } else { + require.Error(t, err) + assert.Contains(t, err.Error(), tc.wantErrPart) + } + }) + } +} + +func TestCheckImageMountPolicyAccessNoMountsDoesNotParsePolicy(t *testing.T) { + require.NoError(t, checkImageMountPolicyAccess([]byte("not: [valid"), "legacy", nil)) +} diff --git a/internal/cli/run_image_pull.go b/internal/cli/run_image_pull.go index e752287c0c..f860db239b 100644 --- a/internal/cli/run_image_pull.go +++ b/internal/cli/run_image_pull.go @@ -60,12 +60,18 @@ func isGHCRImage(image string) bool { // image and the warning below is the only trace. // // It runs only on GitHub Actions, for ghcr.io sandbox and image_mounts images, -// when GH_WORKFLOW_TOKEN is set. Failures are warnings: the gateway still attempts its own -// unauthenticated pull, which keeps public images working as before. +// when GH_WORKFLOW_TOKEN is set and the gateway is local. For a remote gateway, +// the runner's Podman store is unrelated to the gateway's image store. +// Failures are warnings: the gateway still attempts its own pull, which keeps +// public images working as before. func prePullGHCRImage(ctx context.Context, image string, printer *ui.Printer) { if os.Getenv("GITHUB_ACTIONS") != "true" || !isGHCRImage(image) { return } + if os.Getenv("OPENSHELL_GATEWAY_ENDPOINT") != "" { + printer.StepWarn("skipping runner-local pull for " + image + " because the OpenShell gateway is remote; private images need gateway-host registry authentication or an image already cached there (public images can still be pulled by the gateway)") + return + } token := os.Getenv(workflowTokenEnv) if token == "" { return diff --git a/internal/cli/run_image_pull_test.go b/internal/cli/run_image_pull_test.go index 1adf0734fb..e370d26b09 100644 --- a/internal/cli/run_image_pull_test.go +++ b/internal/cli/run_image_pull_test.go @@ -87,6 +87,7 @@ func setupImagePull(t *testing.T) (*fakePodman, *bytes.Buffer, *ui.Printer) { }) t.Setenv("GITHUB_ACTIONS", "true") + t.Setenv("OPENSHELL_GATEWAY_ENDPOINT", "") t.Setenv(workflowTokenEnv, testWorkflowToken) t.Setenv("TMPDIR", t.TempDir()) @@ -205,6 +206,20 @@ func TestPrePullGHCRImage_PodmanMissing(t *testing.T) { assert.Contains(t, buf.String(), "podman not found") } +func TestPrePullGHCRImage_RemoteGatewaySkipsLocalPodman(t *testing.T) { + fake, buf, printer := setupImagePull(t) + t.Setenv("OPENSHELL_GATEWAY_ENDPOINT", "https://gateway.example.test") + t.Setenv(workflowTokenEnv, "") + + prePullGHCRImage(context.Background(), privateImage, printer) + + assert.Empty(t, fake.calls) + assert.Contains(t, buf.String(), "gateway is remote") + assert.Contains(t, buf.String(), "gateway-host registry authentication or an image already cached there") + assert.Contains(t, buf.String(), "public images can still be pulled") + assert.NotContains(t, buf.String(), testWorkflowToken) +} + func TestPrePullGHCRImage_TempDirFailure(t *testing.T) { fake, buf, printer := setupImagePull(t) t.Setenv("TMPDIR", filepath.Join(t.TempDir(), "does-not-exist")) diff --git a/internal/cli/run_openai_test.go b/internal/cli/run_openai_test.go index a731140cd2..d5dc0606c8 100644 --- a/internal/cli/run_openai_test.go +++ b/internal/cli/run_openai_test.go @@ -418,7 +418,9 @@ func recordingProvidersStub(t *testing.T) string { " 'sandbox delete') rm -f " + shellQuoteForTest(logPath+".sandbox") + "; exit 0 ;;\n" + " 'sandbox ready') exit 0 ;;\n" + " 'sandbox get') printf 'Status: Ready\nPolicy source: sandbox\nPolicy:\n version: 1\n'; exit 0 ;;\n" + - " 'policy get') printf 'Version: 1\\nStatus: Effective\\n---\\nversion: 1\\nnetwork_policies:\\n _provider_openai:\\n endpoints:\\n - host: api.openai.com\\n port: 443\\n protocol: rest\\n'; exit 0 ;;\n" + + " 'policy get')\n" + + " if [ -n \"${FULLSEND_TEST_EFFECTIVE_POLICY:-}\" ]; then printf 'Version: 1\\nStatus: Effective\\n---\\n%s\\n' \"$FULLSEND_TEST_EFFECTIVE_POLICY\"; exit 0; fi\n" + + " printf 'Version: 1\\nStatus: Effective\\n---\\nversion: 1\\nnetwork_policies:\\n _provider_openai:\\n endpoints:\\n - host: api.openai.com\\n port: 443\\n protocol: rest\\n'; exit 0 ;;\n" + // The first in-sandbox command fails so the run stops right after // sandbox creation and the deferred cleanup runs. " 'sandbox exec') echo 'stub: no sandbox' >&2; exit 1 ;;\n" + @@ -551,6 +553,53 @@ func TestRunAgent_OpenAIProviderSkippedWhenRuntimeDoesNotNeedIt(t *testing.T) { } } +func TestRunAgent_ImageMountPolicyDeniedStopsBeforeBootstrap(t *testing.T) { + logPath := recordingProvidersStub(t) + dir := writeOpenAIFullsendDirFor(t, false, "claude", "opus") + harnessPath := filepath.Join(dir, "harness", "code.yaml") + harnessYAML, err := os.ReadFile(harnessPath) + require.NoError(t, err) + harnessYAML = append(harnessYAML, []byte("image_mounts:\n - image: ghcr.io/example/tools:latest\n dest: /opt/fullsend\n")...) + require.NoError(t, os.WriteFile(harnessPath, harnessYAML, 0o644)) + + var out strings.Builder + rFlags := resolveFlags{maxDepth: 10, maxResources: 50} + err = runAgent(context.Background(), "code", dir, "", t.TempDir(), fakeSandboxBinary(t), nil, false, "", "", "", rFlags, statusOpts{}, ui.New(&out), false, runOverrideFlags{}) + require.Error(t, err) + assert.Contains(t, err.Error(), `policies/base.yaml`) + assert.Contains(t, err.Error(), `/opt/fullsend`) + assert.Contains(t, out.String(), "Image mount filesystem policy check failed") + + data, readErr := os.ReadFile(logPath) + require.NoError(t, readErr) + log := string(data) + assert.Contains(t, log, "sandbox create") + assert.Contains(t, log, "policy get") + assert.Contains(t, log, "sandbox delete", "failed policy preflight deletes the sandbox") + assert.NotContains(t, log, "sandbox exec", "the agent must not bootstrap after the policy check fails") +} + +func TestRunAgent_ImageMountPolicyAllowsAncestor(t *testing.T) { + logPath := recordingProvidersStub(t) + t.Setenv("FULLSEND_TEST_EFFECTIVE_POLICY", "version: 1\nfilesystem_policy:\n read_only: [/opt]\n") + dir := writeOpenAIFullsendDirFor(t, false, "claude", "opus") + harnessPath := filepath.Join(dir, "harness", "code.yaml") + harnessYAML, err := os.ReadFile(harnessPath) + require.NoError(t, err) + harnessYAML = append(harnessYAML, []byte("image_mounts:\n - image: ghcr.io/example/tools:latest\n dest: /opt/fullsend\n")...) + require.NoError(t, os.WriteFile(harnessPath, harnessYAML, 0o644)) + + var out strings.Builder + rFlags := resolveFlags{maxDepth: 10, maxResources: 50} + err = runAgent(context.Background(), "code", dir, "", t.TempDir(), fakeSandboxBinary(t), nil, false, "", "", "", rFlags, statusOpts{}, ui.New(&out), false, runOverrideFlags{}) + require.Error(t, err, "the fake gateway stops the run after sandbox preflight") + assert.Contains(t, out.String(), "Image mount filesystem access is allowed") + + data, readErr := os.ReadFile(logPath) + require.NoError(t, readErr) + assert.Contains(t, string(data), "policy get") +} + // TestRunAgent_OpenAIProviderNeededBySubagent covers #7981: a pi parent on // a Vertex model still needs the run-scoped OpenAI provider when the // repo's agents: entry configures a child (subagents.default here) that diff --git a/internal/sandbox/sandbox.go b/internal/sandbox/sandbox.go index bccd512d76..a99df03454 100644 --- a/internal/sandbox/sandbox.go +++ b/internal/sandbox/sandbox.go @@ -1467,9 +1467,7 @@ func CreateWithRetry(name string, providers []string, image, policy string, maxA if lastErr == nil { return nil } - - // Keep the failed sandbox in place for inspection and stop. - if keep { + if keep && !errors.Is(lastErr, errUnsupportedImageMountConfiguration) { return fmt.Errorf("sandbox creation failed (sandbox kept, not retried): %w", lastErr) } @@ -1483,6 +1481,26 @@ func CreateWithRetry(name string, providers []string, image, policy string, maxA } return lastErr } + if errors.Is(lastErr, errUnsupportedImageMountConfiguration) { + detail := lastErr.Error() + var configErr *imageMountConfigurationError + if errors.As(lastErr, &configErr) { + detail = configErr.detail + } + diagnostic := fmt.Errorf("%w: %s. Image mounts require the Podman backend, allow_driver_config = true, and resource_admission.enabled = false. For this action's generated local gateway, set allow-image-mounts: true; for any other gateway, ask its operator to verify these settings. `openshell gateway info --output json` does not report the effective settings", errUnsupportedImageMountConfiguration, detail) + if keep { + if errors.As(lastErr, &configErr) && configErr.sandboxExists { + return fmt.Errorf("sandbox creation failed (sandbox kept, not retried): %w", diagnostic) + } + return diagnostic + } + if errors.As(lastErr, &configErr) && configErr.sandboxExists { + if delErr := Delete(name); delErr != nil { + fmt.Fprintf(os.Stderr, " Warning: cleanup of sandbox %s failed: %v\n", name, delErr) + } + } + return diagnostic + } if delErr := Delete(name); delErr != nil { fmt.Fprintf(os.Stderr, " Warning: cleanup of sandbox %s failed: %v\n", name, delErr) @@ -1620,7 +1638,11 @@ func createOnce(name string, providers []string, image, policy string, timeout t if err != nil { check := exec.CommandContext(ctx, "openshell", "sandbox", "get", name) - if checkErr := check.Run(); checkErr != nil { + checkErr := check.Run() + if len(imageMounts) > 0 && unsupportedImageMountConfiguration(createOutput) { + return &imageMountConfigurationError{detail: createOutput, sandboxExists: checkErr == nil} + } + if checkErr != nil { // Wrap err too: when openshell cannot execute at all the // combined output is empty and it is the only diagnostic. return fmt.Errorf("sandbox create failed: %w (output: %s)", err, createOutput) @@ -1727,6 +1749,43 @@ func collectCreateFailureLogs(name string) (supervisorLogs, gatewayLogs, contain // classifies it as non-retryable and returns immediately. var errPolicyGlobal = errors.New("sandbox policy source is global, not sandbox-level") +var errUnsupportedImageMountConfiguration = errors.New("OpenShell rejected image-mount driver configuration") + +type imageMountConfigurationError struct { + detail string + sandboxExists bool +} + +func (e *imageMountConfigurationError) Error() string { + return fmt.Sprintf("%s: %s", errUnsupportedImageMountConfiguration, e.detail) +} + +func (e *imageMountConfigurationError) Unwrap() error { + return errUnsupportedImageMountConfiguration +} + +// unsupportedImageMountConfiguration recognizes stable OpenShell create +// failures that cannot be fixed by retrying the same driver config. +func unsupportedImageMountConfiguration(output string) bool { + message := strings.ToLower(output) + if strings.Contains(message, "allow_driver_config") { + return true + } + unsupported := []string{"disabled", "not allowed", "unsupported", "rejected", "requires", "denied", "not supported", "does not support", "doesn't support"} + for _, marker := range unsupported { + if strings.Contains(message, "driver config") && strings.Contains(message, marker) { + return true + } + if strings.Contains(message, "resource admission") && strings.Contains(message, marker) { + return true + } + if strings.Contains(message, "mount") && strings.Contains(message, marker) { + return true + } + } + return false +} + // ErrProviderNotFound is returned by DeleteProvider when the gateway has no // provider of that name — already gone, which callers treat as done. var ErrProviderNotFound = errors.New("provider not found") diff --git a/internal/sandbox/sandbox_test.go b/internal/sandbox/sandbox_test.go index 290b347eb1..598ef64849 100644 --- a/internal/sandbox/sandbox_test.go +++ b/internal/sandbox/sandbox_test.go @@ -3408,6 +3408,79 @@ exit 0 assert.Equal(t, 1, gets, "global policy error must not trigger retries") } +func TestCreateWithRetry_UnsupportedImageMountConfigurationNotRetried(t *testing.T) { + dir := t.TempDir() + createAttempts := filepath.Join(dir, "create-attempts") + script := fmt.Sprintf(`#!/bin/sh +if [ "$2" = "create" ]; then + echo create >> %s + echo "driver config disabled: set allow_driver_config = true" >&2 + exit 1 +fi +if [ "$2" = "get" ]; then exit 1; fi +exit 0 +`, createAttempts) + require.NoError(t, os.WriteFile(filepath.Join(dir, "openshell"), []byte(script), 0o755)) + t.Setenv("PATH", dir) + + orig := RetrySleepFn + RetrySleepFn = func(d time.Duration) { t.Fatalf("unexpected retry sleep: %s", d) } + t.Cleanup(func() { RetrySleepFn = orig }) + + err := CreateWithRetry("test-sandbox", nil, "", "", 3, 5*time.Second, false, + ImageMount{Source: "example/tools:latest", Target: "/opt/tools"}) + require.Error(t, err) + assert.ErrorIs(t, err, errUnsupportedImageMountConfiguration) + assert.Contains(t, err.Error(), "allow-image-mounts: true") + assert.Contains(t, err.Error(), "effective settings") + + data, readErr := os.ReadFile(createAttempts) + require.NoError(t, readErr) + assert.Equal(t, "create\n", string(data), "unsupported gateway config must not be retried") +} + +func TestCreateWithRetry_UnsupportedImageMountConfigurationKeepsSandbox(t *testing.T) { + dir := t.TempDir() + commandsFile := filepath.Join(dir, "commands") + script := fmt.Sprintf(`#!/bin/sh +echo "$2" >> %s +if [ "$2" = "create" ]; then + echo "allow_driver_config is disabled" >&2 + exit 1 +fi +if [ "$2" = "get" ]; then echo "Phase: Error"; exit 0; fi +exit 0 +`, commandsFile) + require.NoError(t, os.WriteFile(filepath.Join(dir, "openshell"), []byte(script), 0o755)) + t.Setenv("PATH", dir) + + err := CreateWithRetry("test-sandbox", nil, "", "", 3, 5*time.Second, true, + ImageMount{Source: "example/tools:latest", Target: "/opt/tools"}) + require.Error(t, err) + assert.ErrorIs(t, err, errUnsupportedImageMountConfiguration) + assert.Contains(t, err.Error(), "sandbox kept, not retried") + assert.Contains(t, err.Error(), "allow-image-mounts: true") + + data, readErr := os.ReadFile(commandsFile) + require.NoError(t, readErr) + assert.Equal(t, "create\nget\n", string(data), "--keep-sandbox must preserve the failed sandbox") +} + +func TestUnsupportedImageMountConfiguration(t *testing.T) { + for _, tc := range []struct { + message string + want bool + }{ + {message: "allow_driver_config is disabled", want: true}, + {message: "resource admission rejected image mount", want: true}, + {message: "image mounts are not supported by this backend", want: true}, + {message: "Podman driver does not support image mounts", want: true}, + {message: "gateway temporarily unavailable", want: false}, + } { + assert.Equal(t, tc.want, unsupportedImageMountConfiguration(tc.message), tc.message) + } +} + func TestVerifyPolicy_OutputIncludedInErrors(t *testing.T) { output := " Name: sb\n Phase: Ready\n" err := verifyPolicy("sb", output, "/path/to/policy.yaml") From f5395f5bace1cf4539bb4706aea5ddfcf9677375 Mon Sep 17 00:00:00 2001 From: Ralph Bean Date: Fri, 13 Nov 2026 14:06:21 -0500 Subject: [PATCH 8/9] chore(#9396): document mounts and harden image CI Signed-off-by: Ralph Bean --- .github/scripts/sandbox-image-digests-test.sh | 42 +++++++++++++++++++ .github/scripts/sandbox-image-digests.sh | 22 ++++++++++ .github/workflows/sandbox-images.yml | 40 +++++++++++------- docs/cli/run.md | 26 +++++++----- docs/contributing/harness-composition.md | 1 + docs/contributing/harness-fields.md | 8 +++- docs/contributing/runtime-implementation.md | 13 ++++-- docs/contributing/sandbox-topology.md | 18 ++++++-- docs/guides/dev/cli-internals.md | 10 +++-- docs/guides/infrastructure/advanced-setup.md | 26 ++++++++++++ docs/guides/user/bring-your-own-agent.md | 8 +++- docs/reference/harness-reference.md | 2 +- images/README.md | 11 +++-- 13 files changed, 183 insertions(+), 44 deletions(-) create mode 100644 .github/scripts/sandbox-image-digests-test.sh create mode 100644 .github/scripts/sandbox-image-digests.sh diff --git a/.github/scripts/sandbox-image-digests-test.sh b/.github/scripts/sandbox-image-digests-test.sh new file mode 100644 index 0000000000..ba17b943ce --- /dev/null +++ b/.github/scripts/sandbox-image-digests-test.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# Focused check for digest validation and safe workflow diagnostics. +set -euo pipefail + +source .github/scripts/sandbox-image-digests.sh + +valid_digest="sha256:$(printf '%064d' 0 | tr '0' 'a')" +if ! sandbox_image_require_digest "$valid_digest" >/dev/null; then + echo "valid digest was rejected" >&2 + exit 1 +fi + +for invalid_digest in \ + "" \ + "sha256:abc" \ + "sha256:$(printf '%064d' 0 | tr '0' 'A')" \ + "sha256:$(printf '%064d' 0 | tr '0' 'a')/extra"; do + if sandbox_image_require_digest "$invalid_digest" >/dev/null 2>&1; then + echo "invalid digest was accepted: $(printf '%q' "$invalid_digest")" >&2 + exit 1 + fi +done + +injected_value=$'bad%value\r\n::error::injected-command' +if diagnostic=$(sandbox_image_require_digest "$injected_value" 2>&1); then + echo "malformed injection value was accepted" >&2 + exit 1 +fi +if [[ "$diagnostic" != $'::error::Sandbox image validation failed\n'* ]]; then + echo "diagnostic did not use the static workflow annotation" >&2 + exit 1 +fi +if [[ "$diagnostic" == *$'\r'* || "$diagnostic" == *$'\n::error::injected-command'* ]]; then + echo "diagnostic contains raw control characters or an injected command" >&2 + exit 1 +fi +if [[ "$diagnostic" != *'bad%value\r\n::error::injected-command'* ]]; then + echo "diagnostic did not safely render the malformed value" >&2 + exit 1 +fi + +echo "sandbox image digest checks passed" diff --git a/.github/scripts/sandbox-image-digests.sh b/.github/scripts/sandbox-image-digests.sh new file mode 100644 index 0000000000..982d81c0bb --- /dev/null +++ b/.github/scripts/sandbox-image-digests.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Helpers shared by the sandbox image publishing workflow and its local check. + +sandbox_image_error() { + # Keep workflow commands static. Render untrusted details as one shell-escaped + # line on stderr so percent signs and control characters cannot add commands. + printf '::error::Sandbox image validation failed\n' + printf 'detail: %q\n' "$*" >&2 +} + +sandbox_image_is_digest() { + [[ "${1-}" =~ ^sha256:[0-9a-f]{64}$ ]] +} + +sandbox_image_require_digest() { + local digest="${1-}" + if sandbox_image_is_digest "$digest"; then + return 0 + fi + sandbox_image_error "invalid sha256 image digest: $digest" + return 1 +} diff --git a/.github/workflows/sandbox-images.yml b/.github/workflows/sandbox-images.yml index e925702945..2db181022b 100644 --- a/.github/workflows/sandbox-images.yml +++ b/.github/workflows/sandbox-images.yml @@ -104,6 +104,8 @@ jobs: env: DIGEST: ${{ steps.push.outputs.digest }} run: | + source "$GITHUB_WORKSPACE/.github/scripts/sandbox-image-digests.sh" + sandbox_image_require_digest "$DIGEST" || exit 1 mkdir -p "${RUNNER_TEMP}/digests" touch "${RUNNER_TEMP}/digests/${DIGEST#sha256:}" @@ -177,6 +179,8 @@ jobs: env: DIGEST: ${{ steps.push.outputs.digest }} run: | + source "$GITHUB_WORKSPACE/.github/scripts/sandbox-image-digests.sh" + sandbox_image_require_digest "$DIGEST" || exit 1 mkdir -p "${RUNNER_TEMP}/digests" touch "${RUNNER_TEMP}/digests/${DIGEST#sha256:}" @@ -204,6 +208,8 @@ jobs: outputs: image-ref: ${{ steps.ref.outputs.value }} steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Download digests if: github.event_name != 'pull_request' uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 @@ -252,15 +258,15 @@ jobs: IMAGE_NAME: ${{ env.BASE_IMAGE_NAME }} META_JSON: ${{ steps.meta.outputs.json }} run: | + source "$GITHUB_WORKSPACE/.github/scripts/sandbox-image-digests.sh" # Never publish a partial index. count=$(find . -maxdepth 1 -type f | wc -l) if [ "${count}" -ne 2 ]; then - echo "::error::expected 2 platform digests, found ${count}" + sandbox_image_error "expected 2 platform digests, found ${count}" exit 1 fi for hex in *; do - if ! grep -Eqx '[0-9a-f]{64}' <<<"${hex}"; then - echo "::error::not a sha256 digest: ${hex}" + if ! sandbox_image_require_digest "sha256:${hex}"; then exit 1 fi done @@ -274,9 +280,9 @@ jobs: # runs can move dev/latest, but only this commit sets this tag. sha_tag="${IMAGE_NAME}:${GITHUB_SHA::7}" jq -e --arg t "${sha_tag}" 'any(.tags[]; . == $t)' <<<"${META_JSON}" >/dev/null \ - || { echo "::error::${sha_tag} is not among the published tags"; exit 1; } + || { sandbox_image_error "${sha_tag} is not among the published tags"; exit 1; } digest=$(docker buildx imagetools inspect "${sha_tag}" --format '{{json .Manifest}}' | jq -r '.digest') - [[ "${digest}" =~ ^sha256:[0-9a-f]{64}$ ]] || { echo "::error::no index digest for ${sha_tag}"; exit 1; } + sandbox_image_require_digest "${digest}" || exit 1 # Another run of the same commit (a release tag on an rc commit) # can move the sha tag. Fail unless the index read back holds # exactly the platform images this run pushed. @@ -287,7 +293,7 @@ jobs: done | sort) got=$(docker buildx imagetools inspect --raw "${IMAGE_NAME}@${digest}" | jq -r --arg self "${digest}" "${platform_digests}" | sort) if [ "${want}" != "${got}" ]; then - echo "::error::${sha_tag} was moved by another run; expected ${want//$'\n'/ }, got ${got//$'\n'/ }" + sandbox_image_error "${sha_tag} was moved by another run; expected ${want//$'\n'/ }, got ${got//$'\n'/ }" exit 1 fi echo "digest=${digest}" >> "${GITHUB_OUTPUT}" @@ -299,14 +305,14 @@ jobs: IMAGE_NAME: ${{ env.TOOLS_IMAGE_NAME }} META_JSON: ${{ steps.tools-meta.outputs.json }} run: | + source "$GITHUB_WORKSPACE/.github/scripts/sandbox-image-digests.sh" count=$(find . -maxdepth 1 -type f | wc -l) if [ "${count}" -ne 2 ]; then - echo "::error::expected 2 tool image platform digests, found ${count}" + sandbox_image_error "expected 2 tool image platform digests, found ${count}" exit 1 fi for hex in *; do - if ! grep -Eqx '[0-9a-f]{64}' <<<"${hex}"; then - echo "::error::not a sha256 digest: ${hex}" + if ! sandbox_image_require_digest "sha256:${hex}"; then exit 1 fi done @@ -318,16 +324,16 @@ jobs: docker buildx imagetools create "${tag_args[@]}" "${sources[@]}" sha_tag="${IMAGE_NAME}:${GITHUB_SHA::7}" jq -e --arg t "${sha_tag}" 'any(.tags[]; . == $t)' <<<"${META_JSON}" >/dev/null \ - || { echo "::error::${sha_tag} is not among the published tags"; exit 1; } + || { sandbox_image_error "${sha_tag} is not among the published tags"; exit 1; } digest=$(docker buildx imagetools inspect "${sha_tag}" --format '{{json .Manifest}}' | jq -r '.digest') - [[ "${digest}" =~ ^sha256:[0-9a-f]{64}$ ]] || { echo "::error::no tool image index digest for ${sha_tag}"; exit 1; } + sandbox_image_require_digest "${digest}" || exit 1 platform_digests='if .manifests then [.manifests[] | select(.platform.os != "unknown") | .digest] else [$self] end | .[]' want=$(for src in "${sources[@]}"; do docker buildx imagetools inspect --raw "${src}" | jq -r --arg self "${src#*@}" "${platform_digests}" done | sort) got=$(docker buildx imagetools inspect --raw "${IMAGE_NAME}@${digest}" | jq -r --arg self "${digest}" "${platform_digests}" | sort) if [ "${want}" != "${got}" ]; then - echo "::error::${sha_tag} was moved by another run; expected ${want//$'\n'/ }, got ${got//$'\n'/ }" + sandbox_image_error "${sha_tag} was moved by another run; expected ${want//$'\n'/ }, got ${got//$'\n'/ }" exit 1 fi @@ -425,6 +431,8 @@ jobs: env: DIGEST: ${{ steps.push.outputs.digest }} run: | + source "$GITHUB_WORKSPACE/.github/scripts/sandbox-image-digests.sh" + sandbox_image_require_digest "$DIGEST" || exit 1 mkdir -p "${RUNNER_TEMP}/digests" touch "${RUNNER_TEMP}/digests/${DIGEST#sha256:}" @@ -448,6 +456,8 @@ jobs: contents: read packages: write steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Download digests uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: @@ -475,15 +485,15 @@ jobs: IMAGE_NAME: ${{ env.CODE_IMAGE_NAME }} META_JSON: ${{ steps.meta.outputs.json }} run: | + source "$GITHUB_WORKSPACE/.github/scripts/sandbox-image-digests.sh" # Never publish a partial index. count=$(find . -maxdepth 1 -type f | wc -l) if [ "${count}" -ne 2 ]; then - echo "::error::expected 2 platform digests, found ${count}" + sandbox_image_error "expected 2 platform digests, found ${count}" exit 1 fi for hex in *; do - if ! grep -Eqx '[0-9a-f]{64}' <<<"${hex}"; then - echo "::error::not a sha256 digest: ${hex}" + if ! sandbox_image_require_digest "sha256:${hex}"; then exit 1 fi done diff --git a/docs/cli/run.md b/docs/cli/run.md index af97745e60..b2b346b0dd 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -483,17 +483,21 @@ derived from a local PAT — a caller may set it explicitly. `GH_TOKEN`, `GITHUB_TOKEN`, `GH_ENTERPRISE_TOKEN`, `GITHUB_ENTERPRISE_TOKEN` and `PUSH_TOKEN` still receive the minted App identity. -The runner itself also reads `GH_WORKFLOW_TOKEN` for one purpose besides provider credential -expansion: before it creates the sandbox, on GitHub Actions, it pulls each `ghcr.io` harness -`image` and `image_mounts[].image` reference with the token through Podman (a run-scoped auth file -in a private temporary directory, removed after the pull), so those images can be private packages. Only the -shipped code and fix workflows grant `packages: read`, so private sandbox and -`image_mounts` images work on code and fix harnesses; on other agents a private -image is denied and sandbox creation fails. The package must also -allow Actions access from the repository. If the pull fails, the runner logs a warning and the -OpenShell gateway attempts its own unauthenticated pull, so public images keep working. For images -on other registries the runner adds no credentials. See -[Extending the sandbox image](../guides/user/customizing-agents.md#extending-the-sandbox-image). +Before creating a sandbox on GitHub Actions, the runner can use +`GH_WORKFLOW_TOKEN` to pull `ghcr.io` harness `image` and +`image_mounts[].image` references through local Podman. It stores the token in +a run-scoped auth file in a private temporary directory and removes the file +after the pull. The package must allow Actions access from the repository and +the workflow must grant `packages: read`. The default local OpenShell gateway +can also pull public images if this pre-pull fails. For a remote gateway, +`OPENSHELL_GATEWAY_ENDPOINT` points the action at a separate image store, so +the runner skips local Podman pulls; private images then need gateway-side +registry authentication or a cached copy on the gateway host. The workflow +token is not sent to the remote gateway or sandbox. For registries other than +GHCR, the runner adds no credentials. See +[remote gateway setup](../guides/infrastructure/advanced-setup.md#runners-that-use-a-remote-openshell-gateway) +the [Fullsend tool image instructions](../guides/user/bring-your-own-agent.md#mount-the-fullsend-runtime-tools), +and [extending the sandbox image](../guides/user/customizing-agents.md#extending-the-sandbox-image). Every mint sets `GH_TOKEN`, `GITHUB_TOKEN`, `GH_ENTERPRISE_TOKEN` and `GITHUB_ENTERPRISE_TOKEN` to the minted token, even when the caller workflow diff --git a/docs/contributing/harness-composition.md b/docs/contributing/harness-composition.md index 33fc1daf98..304e78cdde 100644 --- a/docs/contributing/harness-composition.md +++ b/docs/contributing/harness-composition.md @@ -34,6 +34,7 @@ and update the others as needed. | `mergeForgeConfigInto` | `internal/harness/compose.go` | **Deprecated** — was used to merge base `ForgeConfig` fields into child `ForgeConfig` during `base:` composition; no longer called after #6798 introduced per-layer resolution | | `mergeSkills` | `internal/harness/compose.go` | Deduplicates skills by identity (declared `SKILL.md` name when the directory is on disk, otherwise basename). Child entries override a matching *base* entry and merge file-level override maps (child keys win). A map-form child entry whose absolute path has no `SKILL.md` keeps the base entry's resolved source instead (#6158); if it matches no base key, it can still match the one pinned-URL base entry of its name (ignoring `#fragment` and `?query`); when two or more match, `mergeSkills` returns an error that names them all and asks for the full base URL as the map key (#8973). `mergeForgeConfig` calls `mergeSkills`, so forge and overlay skills follow the same rule. Sibling entries that share a directory basename (nested forge skills such as `skills/issue-labels/github` and `skills/pr-review/github`) are kept; destination collisions fail at bootstrap. | | `mergeHostFiles` | `internal/harness/compose.go` | Deduplicates host files by dest path (base + child) | +| `mergeImageMounts` | `internal/harness/image_mount.go` | Deduplicates mounts by destination; the first occurrence fixes its position and a later entry replaces its value, so child entries win without changing stable order | | `mergeForgeBlocks` | `internal/harness/compose.go` | **Deprecated** — was used to merge `forge:` maps key-by-key across base and child; no longer called after #6798 introduced per-layer resolution | > **Note — layer-by-layer resolution.** Since #6798, each base layer's diff --git a/docs/contributing/harness-fields.md b/docs/contributing/harness-fields.md index 241c2b5323..38375b5c04 100644 --- a/docs/contributing/harness-fields.md +++ b/docs/contributing/harness-fields.md @@ -48,9 +48,15 @@ These fields can appear at the harness top level (as defaults) and inside | `providers` | Providers may need forge-specific entries (e.g., different API endpoints per platform); concatenated (top-level + forge) | | `openshell` | OpenShell profiles may need forge-specific configuration; `profiles` concatenated (top-level + forge) | | `host_files` | Host files may need forge-specific entries (e.g., different credential files per platform); deduplicated by `dest` path (child wins) | -| `image_mounts` | Additional OCI images may provide forge-specific sandbox tools; deduplicated by `dest` path (child wins) | +| `image_mounts` | Additional OCI images may provide forge-specific sandbox tools; deduplicated by `dest` path (later entry wins while retaining the first destination's position) | | `env` | Env config (`runner` and `sandbox` sub-maps) may need forge-specific entries (e.g., different token names per forge); sub-maps merged independently, forge/child keys win (ADR-0055) | +Image mount destinations must be clean absolute non-root paths and may not +overlap runner-owned paths, `host_files` destinations, or other distinct image +mount destinations. Validation runs on top-level, forge, overlay, and final +composed values; same-destination entries are deduplicated before the final +overlap check, with the later value winning at the first entry's position. + ### Fields that stay at top level only These fields cannot be overridden per-forge or per-overlay. A key for one of diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index d6960637ed..49e108ac05 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -478,10 +478,15 @@ the same runner paths work when no tool image is mounted. Its image for a mount because the OCI root is placed at `/opt/fullsend`. The Claude and Codex links in `/usr/local/bin` are relative so they still resolve inside the mounted image. The generated base policy allows `/opt/fullsend` -read-only; custom policies must do the same. The current harness PoC passes -Podman image mount configuration to OpenShell, so it is intended for the local -Podman backend. The gateway must enable `allow_driver_config` and disable -resource admission for Podman image mounts. +read-only; custom policies must allow the mount path through +`filesystem_policy.read_only` or `filesystem_policy.read_write`. Before +bootstrap, Fullsend checks that the effective policy allows the mount path or +an ancestor. The harness uses OpenShell's Podman image mount configuration. +The action leaves local image mounts disabled unless +`allow-image-mounts: true` is set; a remote gateway operator must enable +`allow_driver_config` and disable resource admission. See +[gateway setup](../guides/infrastructure/advanced-setup.md#image-mounts-on-openshell-gateways) +and the [user guide](../guides/user/bring-your-own-agent.md#mount-the-fullsend-runtime-tools). ### Vendored dependency checklist diff --git a/docs/contributing/sandbox-topology.md b/docs/contributing/sandbox-topology.md index ba6f6cade0..f267c6003f 100644 --- a/docs/contributing/sandbox-topology.md +++ b/docs/contributing/sandbox-topology.md @@ -1,15 +1,25 @@ # Sandbox Image Topology -Fullsend agents run inside sandboxed containers. Two images exist in a -parent-child hierarchy; which image an agent uses depends on whether it -needs a compiled-language toolchain. +Fullsend agents run inside sandboxed containers. The regular sandbox image +supports agents that need general tools; the code image adds a compiled-language +toolchain. A separate tools image exposes Fullsend's pinned runtime tools for +read-only mounting into a development image. ``` ghcr.io/nvidia/openshell-community/sandboxes/base (upstream) +-- fullsend-sandbox (base sandbox) - +-- fullsend-code (extends base with Go) + | +-- fullsend-code (extends base with Go) + +-- fullsend-sandbox-tools (mount-only tool root) ``` +`fullsend-sandbox-tools` is built from the same pinned tool stages as +`fullsend-sandbox`, with the compatibility link removed so its root can be +mounted at `/opt/fullsend`. It is not a sandbox `image:` replacement: add it +as an `image_mounts` entry and grant the destination read-only access in the +effective sandbox policy. The mount uses the sandbox's ABI and libraries, so +the development image must be compatible with the tools image. See the +[runtime tool image contract](runtime-implementation.md#fullsend-tool-image-mount-contract). + | Image | Agents | Run frequency | Key additions over parent | |-------|--------|---------------|--------------------------| | `fullsend-sandbox` | triage, prioritize, retro | High (most agent runs) | Claude Code, pi (pinned; opt-in runtime, #6464), Codex (pinned; opt-in runtime, #6920), ripgrep + fd (pi grep/find backends), jq, gitleaks, acli, pre-commit, gitlint, tirith | diff --git a/docs/guides/dev/cli-internals.md b/docs/guides/dev/cli-internals.md index 91174104ee..2ce1baba87 100644 --- a/docs/guides/dev/cli-internals.md +++ b/docs/guides/dev/cli-internals.md @@ -535,9 +535,9 @@ Vendoring commit messages use title + body (upload and stale delete). `admin ins │ │ └── security hooks │ │ │ │ │ │ │ │ bootstrapEnv() writes: │ │ -│ │ ├── PATH=/opt/fullsend/...: │ │ -│ │ │ /usr/local/go/bin:$HOME/go/bin: │ │ -│ │ │ $PATH:/sandbox/workspace/bin │ │ +│ │ ├── PATH=/usr/local/go/bin:$HOME/go/bin │ │ +│ │ │ ::/sandbox/workspace/ │ │ +│ │ │ bin:/opt/fullsend/... │ │ │ │ ├── readonly FULLSEND_RUNNER_PATH │ │ │ │ ├── CLAUDE_CONFIG_DIR=/sandbox/claude-config│ │ │ │ ├── FULLSEND_OUTPUT_DIR=... │ │ @@ -686,6 +686,10 @@ Vendoring commit messages use title + body (upload and stale delete). `admin ins └─────────────────────────────────────────────────────────────────┘ ``` +The agent-facing PATH keeps Go paths first, then the sandbox image's project +tools, workspace helpers, and mounted Fullsend tools as a fallback. Runner +commands and hooks use the separately captured trusted PATH. + The `bootstrapEnv()` writes and the `iteration.env` names in this diagram are the runner's exports. The full, machine-checkable inventory — what every sandbox receives, per gate and per runtime, and what arrives only through diff --git a/docs/guides/infrastructure/advanced-setup.md b/docs/guides/infrastructure/advanced-setup.md index 19acf4d9aa..78cff7cb15 100644 --- a/docs/guides/infrastructure/advanced-setup.md +++ b/docs/guides/infrastructure/advanced-setup.md @@ -120,6 +120,32 @@ output. It skips the install when `python3` can already import the package. On a container image whose Python is an externally managed environment, the action retries the install with `--break-system-packages`. +#### Image mounts on OpenShell gateways + +Harness `image_mounts` use OpenShell's Podman driver configuration. For a +local gateway started by the action, image mounts are disabled by default; +set `allow-image-mounts: true` on the action to enable driver configuration +and disable resource admission for that local gateway. This opt-in also +disables resource-admission label checks for external attachments, so use it +only when trusted workflows control the harness. + +For a remote gateway, the operator must set these values in the gateway +configuration. The action does not modify remote gateway settings: + +```toml +[openshell.drivers.podman] +allow_driver_config = true + +[openshell.drivers.podman.resource_admission] +enabled = false +``` + +OpenShell 0.1.4 `gateway info --output json` reports compute-driver names and +versions, not these effective settings. A rejected mount reports the required +configuration. This support was introduced by PR #9396; add the first +supported release version here when it is cut. See also the +[user guide to mounting Fullsend tools](../user/bring-your-own-agent.md#mount-the-fullsend-runtime-tools). + ### Custom app sets By default, the installer creates GitHub Apps with the `fullsend-ai` prefix (e.g., `fullsend-ai-fullsend`, `fullsend-ai-coder`, `fullsend-ai-review`). Organizations that need their own set of apps — for example, to use org-specific permissions or to register multiple app sets on the same mint — can pass `--app-set` to override the prefix. diff --git a/docs/guides/user/bring-your-own-agent.md b/docs/guides/user/bring-your-own-agent.md index 8616565afa..2ae8f02757 100644 --- a/docs/guides/user/bring-your-own-agent.md +++ b/docs/guides/user/bring-your-own-agent.md @@ -522,7 +522,7 @@ For the complete list of harness fields, see the [Harness Field Reference](../.. #### Mount the Fullsend runtime tools Use `image_mounts` when your sandbox image needs Fullsend's pinned runtime -tools from a separate OCI image: +tools from a separate Open Container Initiative (OCI) image: ```yaml image_mounts: @@ -566,6 +566,9 @@ allow_driver_config = true enabled = false ``` +For remote gateway installation and endpoint setup, see +[Runners that use a remote OpenShell gateway](../infrastructure/advanced-setup.md#runners-that-use-a-remote-openshell-gateway). + On a local gateway, Fullsend can pre-pull private GHCR images with the workflow token. For a remote gateway it skips runner-local Podman pulls because that image store is separate. Private images then need registry authentication or a @@ -583,6 +586,9 @@ Distinct image mount destinations cannot contain one another (for example, destination. A child can still replace an inherited image mount at the exact same destination. +This support was introduced by PR #9396; add the first supported release +version here when it is cut. + ### Agent definitions The agent definition is Markdown with YAML frontmatter: diff --git a/docs/reference/harness-reference.md b/docs/reference/harness-reference.md index c12a2951b5..7e3d798fea 100644 --- a/docs/reference/harness-reference.md +++ b/docs/reference/harness-reference.md @@ -151,7 +151,7 @@ Most fields are self-explanatory from the inline comments above. This section ex **`image`** — The sandbox container image. On GitHub Actions a private `ghcr.io` package works on code and fix harnesses, whose shipped workflows grant `packages: read`; see [GitHub Packages credentials](../cli/run.md#github-packages-credentials). -**`image_mounts`** — Additional OCI images mounted read-only inside the sandbox. Each entry requires an `image` reference and an absolute, clean `dest` path. Relative paths and `/` are rejected. An image mount destination may not overlap any `host_files[].dest`. After same-destination entries are merged, distinct image mount destinations may not contain one another. A child harness layer replaces an inherited entry with the same `dest`; there is no syntax for removing an inherited mount. The OCI image's `ENV`, user, working directory and entrypoint are ignored. Fullsend currently passes these mounts to OpenShell's Podman backend; other backends may reject them. OpenShell's Podman image mounts require resource admission to be disabled in the gateway configuration. For the Fullsend tool image, mount at `/opt/fullsend` and allow that path read-only in the sandbox policy. Use an immutable image digest for repeatable runs. The mount image and sandbox image must have compatible Linux ABI and system libraries; see [the tool image contract](../contributing/runtime-implementation.md#fullsend-tool-image-mount-contract). +**`image_mounts`** — Additional Open Container Initiative (OCI) images mounted read-only inside the sandbox. Each entry requires an image reference without whitespace or variable expansion and an absolute, clean, non-root `dest` path. Destinations may not overlap runner-owned setup paths, any `host_files[].dest`, or one another after same-destination entries are merged. A child harness layer replaces an inherited entry with the same `dest`; later entries win while the destination keeps its first position, and there is no syntax for removing an inherited mount. Validation applies to top-level, forge, overlay, and final composed harness values. The OCI image's `ENV`, user, working directory and entrypoint are ignored. Fullsend currently passes these mounts to OpenShell's Podman backend; other backends may reject them. Podman mounts require `allow_driver_config = true` and resource admission disabled on the gateway; local action gateways require the explicit `allow-image-mounts: true` opt-in, while remote gateway settings remain operator-managed. For the Fullsend tool image, mount at `/opt/fullsend` and allow that path in the effective filesystem policy; Fullsend checks access before bootstrap. Use an immutable image digest for repeatable runs. The mount image and sandbox image must have compatible Linux ABI and system libraries; see [the tool image contract](../contributing/runtime-implementation.md#fullsend-tool-image-mount-contract) and [gateway setup](../guides/infrastructure/advanced-setup.md#image-mounts-on-openshell-gateways). **`readonly_repo`** — When `true`, the runner makes the checkout read-only in the sandbox before the agent starts: it removes write permission (`chmod a-w`) from every file and directory in the checkout except `.git/`. A harness that leaves the field out inherits it from its `base:`, and gets a writable checkout when no base sets it. An explicit `false` keeps the checkout writable, even when the base sets `true`. **Top level only** — a `readonly_repo` key placed under `overlays:`/`forge:` is silently ignored. The step also runs `chown -R sandbox:sandbox` on `.git/`. If the step fails, for example on an image that has no `sandbox` user, the run stops with `read-only repo enforcement failed`. That applies to a harness that inherits `true` as well. To fix it, build the image on the fullsend sandbox image, which has that user (see [Extending the sandbox image](../guides/user/customizing-agents.md#extending-the-sandbox-image)), or set `readonly_repo: false` in the harness to keep a writable checkout. diff --git a/images/README.md b/images/README.md index c550fe9d1b..a926bd0c8c 100644 --- a/images/README.md +++ b/images/README.md @@ -39,10 +39,13 @@ Use the same OpenShell base image for both images or verify compatible architecture, ELF loader, glibc, Python and Node runtimes. Mounted executables run in the sandbox environment rather than a separate root filesystem. The prelaunch check runs `/opt/fullsend/usr/bin/node --version` before repository -setup. The harness PoC targets -OpenShell's Podman backend; the sandbox policy must allow `/opt/fullsend` -read-only, and the gateway must enable `allow_driver_config` and disable -resource admission for image mounts. +setup. The harness supports OpenShell's Podman backend; the effective sandbox +filesystem policy must allow `/opt/fullsend` or an ancestor, and Fullsend checks +that access before bootstrap. Image mounts are disabled by default on a local +action gateway; opt in with `allow-image-mounts: true`. A remote gateway's +operator must enable `allow_driver_config` and disable resource admission, as +described in [advanced setup](../docs/guides/infrastructure/advanced-setup.md#image-mounts-on-openshell-gateways). +The action does not change remote settings or forward registry credentials. ## Runner image From c7d364b260b3f68da91e000c14d3d329c69fe19a Mon Sep 17 00:00:00 2001 From: Ralph Bean Date: Fri, 13 Nov 2026 14:16:21 -0500 Subject: [PATCH 9/9] test(#9396): cover forge image mount merge Signed-off-by: Ralph Bean --- internal/harness/compose_test.go | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/internal/harness/compose_test.go b/internal/harness/compose_test.go index 7b6ae88f00..b88f26d0f2 100644 --- a/internal/harness/compose_test.go +++ b/internal/harness/compose_test.go @@ -5391,6 +5391,27 @@ func TestMergeForgeConfigInto_HostFilesOverriddenByChild(t *testing.T) { assert.Equal(t, "env/child.env", child.HostFiles[0].Src) } +func TestMergeForgeConfigInto_ImageMountsOverriddenByChild(t *testing.T) { + base := &ForgeConfig{ + ImageMounts: []ImageMount{ + {Image: "registry.example/base-tools:v1", Dest: "/opt/base-tools"}, + {Image: "registry.example/base:v1", Dest: "/opt/tools"}, + }, + } + child := &ForgeConfig{ + ImageMounts: []ImageMount{ + {Image: "registry.example/child:v1", Dest: "/opt/tools"}, + }, + } + + require.NoError(t, mergeForgeConfigInto(base, child)) + + require.Len(t, child.ImageMounts, 2) + assert.Equal(t, base.ImageMounts[0], child.ImageMounts[0]) + assert.Equal(t, "registry.example/child:v1", child.ImageMounts[1].Image) + assert.Equal(t, "/opt/tools", child.ImageMounts[1].Dest) +} + func TestLoadWithBase_URLBase_ForgeSkillPathTraversal(t *testing.T) { baseContent := []byte(` agent: agents/remote.md