Skip to content

Add declarative bring-your-own agent support (#191 Phase 1) - #200

Merged
JAORMX merged 2 commits into
mainfrom
feat/191-byo-agents-phase1
Jun 29, 2026
Merged

JAORMX merged 2 commits into
mainfrom
feat/191-byo-agents-phase1

Conversation

@JAORMX

@JAORMX JAORMX commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

Summary

Implements Phase 1 of #191 — run arbitrary coding agents from global config with no Go code, no fork, and no Dockerfile in this repo. This is the issue's "first useful iteration" acceptance criteria:

agents:
  aider:
    image: ghcr.io/acme/aider-bbox:latest
    command: ["aider"]
    env_forward: [OPENAI_API_KEY, "AIDER_*"]
    mcp:
      mode: env
$ bbox agents doctor aider
[PASS] config validation: name, image, command, paths, egress all valid
[PASS] required env OPENAI_API_KEY present
$ bbox aider     # boots the image, runs the command

What's included

  • Extended AgentOverride (pkg/domain/config): description, default_env, env_required, credentials.persist, settings entries, per-profile egress_hosts, mcp.mode.
  • Pure mapping + validation: AgentFromOverride (config→agent.Agent) and ValidateCustomAgent are pure, table-tested domain functions. The image-ref parser is injected as a closure from the composition root, keeping go-containerregistry out of the domain layer.
  • Universal BBOX_* env (agent.BuildUniversalEnv) injected into every VM: BBOX_AGENT_NAME, BBOX_WORKSPACE, BBOX_HOME, BBOX_SESSION_ID, BBOX_GIT_TOKEN_AVAILABLE, BBOX_SSH_AGENT_AVAILABLE, plus BBOX_MCP_URL/BBOX_MCP_AUTHZ_PROFILE when MCP is active. Applied after forwarded host vars so it's authoritative. BBOX_MCP_URL uses a new shared config.MCPEndpointPath (/mcp) constant — de-duplicating the path previously hardcoded in the proxy and all five built-in clients.
  • mcp.mode: env: enables the proxy without a config-file injector; the agent discovers it via BBOX_MCP_URL. (mcp.mode: config is rejected with a clear message.)
  • bbox agents list | inspect | doctor: inspect shows field provenance (built-in/global/workspace) and env names only, never values; doctor exits non-zero on invalid config or missing required env. bbox list remains a shared alias.

Defaults & security

  • Safer-than-built-in defaults for custom agents: empty env_forward (forward nothing), egress profile standard (must declare hosts or set permissive), MCP authz safe-tools.
  • Workspace-local .broodbox.yaml is tighten-only: it can never add a custom agent or new credential paths, repoint an existing agent's image/command, or widen env_forward (subset-coverage enforcement prevents secret exfiltration). Credential/settings paths are validated relative and cannot escape the home dir.
  • A guard test pins go-microvm's topology.GatewayIP to the literal pkg/sandbox uses for BBOX_MCP_URL, catching drift.

Out of scope (deliberate follow-ups)

agents import/export, OCI-embedded manifests, mcp.mode: config, agents add/init scaffolding, and trusted host-side plugins.

Verification

  • task fmt clean, task lint 0 issues, full task test (race) passes.
  • End-to-end smoke-tested: agents list shows custom agents; inspect renders provenance + MISSING required-env markers without leaking values; doctor passes with required env set (exit 0), fails without it (exit 1), and rejects mcp.mode: config (exit 1); bbox list unchanged.
  • Strict DDD layering preserved (pure domain mapping/validation; I/O only in infra/cmd).

How it was built

Produced via a multi-agent orchestration loop: architect → implement → 5-axis panel review (architecture / security / correctness / api-ux / tests) → fix, iterated 3 rounds. All findings were resolved; the final state was independently re-verified and reviewed before this PR.

🤖 Generated with Claude Code

@JAORMX JAORMX left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Panel review — 3 axes, 5 reviewers

Ran a three-axis panel review (Spec / Standards / Domain) with the Domain axis fanned out to secure-code-reviewer, software-architect, devex-reviewer, and ux-reviewer. Findings are inline as line-anchored comments; summary below. (software-architect and devex-reviewer reached their turn limits mid-investigation; their partial findings are folded into the summary where confirmed, and the DDD-layer purity check — the most important invariant — was completed by the Standards axis.)

Spec — ⚠️ one Wrong finding against the acceptance criteria

  • [High] The issue's canonical Phase 1 aider example (only image/command/env_forward/mcp.mode: env, no egress) is rejected by ValidateCustomAgent — standard egress profile requires egress_hosts, so the exact config the issue says should work doesn't boot. Needs either a looser validation or an updated acceptance example. custom_agent.go:283.
  • Scope creep (noted, acceptable): dropping local-only agent keys and ignoring local image/command during merge silently changes pre-existing workspace override semantics for all agents, not just custom ones. Justified as security #7, but it's a contract change.

Standards — ✅ clean (one soft note)

DDD layer purity verified — the most important invariant:

  • pkg/domain/config/custom_agent.go imports only stdlib + sibling domain packages. The image-ref parser is correctly injected as imageRefValidator func(string) error (closure supplied at cmd/bbox/main.go via name.ParseReference) — go-containerregistry stays out of domain. ✓
  • pkg/domain/agent/env_bbox.go is pure domain, no I/O. ✓
  • pkg/sandbox/sandbox.go new imports are only domain packages. ✓
  • pkg/clients/*/mcp.go new imports are pkg/domain/config (a domain package) — permitted; no internal/infra import. ✓

SPDX headers present on all new .go files. log/slog exclusively. Errors wrapped with %w. Table-driven tests alongside code. No business logic added to internal/infra/. One soft note: commit subject is 58 chars > 50 (CLAUDE.md convention) — judgement call, not a blocker.

Domain — 1 High, 2 Medium, 6 Low/Info

Ship-blockers (1)

  • [High] (Spec, above) Canonical acceptance example rejected by validation.

Mechanical fixes (2)

  • [Medium — secure-code-reviewer] CWE-862 Workspace-local .broodbox.yaml can override a per-agent mcp.mode to "env", suppressing a built-in's config-file injector — fail-open from untrusted input. The only per-agent MCP field where local changes built-in behavior rather than tightening. Fix: ignore local.MCP.Mode (treat like Image/Command). config.go:1198.
  • [Medium — ux-reviewer] env_required is not enforced at run time — only by agents doctor. A user who forgets to export a required env var gets a full VM boot then an opaque in-VM failure. Fix: gate in Prepare, fail fast before boot. agents.go:315.

Judgement calls (3)

  • [Low — secure-code-reviewer] CWE-862/A05 Workspace-local can re-enable a per-agent MCP proxy the operator disabled globally (via config, not --no-mcp). Breaks the "local can only tighten" invariant; inconsistent with SettingsImport.Enabled. Fix: tighten-only on MCP.Enabled. config.go:1194.
  • [Medium — ux-reviewer] bbox <declared-but-skipped-agent> dead-ends on "agent not found" with no mention of the earlier validation warning or bbox agents doctor. The merged config still carries the key, so run() can detect "declared but not registered" and route to doctor. main.go:1206.
  • [Low — ux-reviewer] agents inspect MISSING marker names the problem but not the fix. agents.go:145.

Polish (3)

  • [Low — ux-reviewer] agents list doesn't distinguish built-in from custom — add a TYPE column or section break. agents.go:64.
  • [Low — ux-reviewer] Provenance labels exist only for Image and Command — extend to egress profile / env_forward at minimum. agents.go:131.
  • [Low — ux-reviewer] "unknown agent %q" in inspect/doctor points nowhere — append run 'bbox agents list'. agents.go:100.

Verified security claims (secure-code-reviewer, no action required)

For the record, since the PR body makes explicit security claims I verified each:

  1. ✓ Tighten-only merge (env_forward subset-coverage with glob patterns is sound — AIDER_SECRET_* ⊆ AIDER_* covered, reverse rejected)
  2. ✓ Path validation rejects ../../etc/shadow, /etc/shadow (defense-in-depth in FSStore/FSInjector too)
  3. ✓ env_forward rejects empty/bare-*/leading-star at every load site (global, workspace, CLI, SDK)
  4. ✓ BBOX_* env applied after forwarded host vars (authoritative; regression test at sandbox_test.go:1182)
  5. ✓ MCP authz profile tighten-only (workspace cannot widen to full-access)
  6. ✓ agents inspect never leaks env values (names/patterns + present/MISSING only; regression test at agents_test.go:140)
  7. ✓ Image-ref parser injection has no injection vector (syntactic validation only, no network I/O, not constructible from config)

Gaps

  • software-architect and devex-reviewer hit turn limits mid-investigation. The DDD-layer purity check (their primary focus) was completed by the Standards axis and is clean. Any deeper architectural concerns about the SandboxConfig contract changes or BuildUniversalEnv signature ergonomics would need a follow-up pass.

Most important single issue: the High spec mismatch — the acceptance example doesn't boot. The Medium mcp.mode override (secure-code-reviewer) is the highest-confidence security finding since it's the only field that breaks the PR's own advertised "local may only tighten" invariant.

🤖 Generated with Claude Code

Comment thread pkg/domain/config/custom_agent.go Resolved
Comment thread pkg/domain/config/config.go Resolved
Comment thread pkg/domain/config/config.go Resolved
Comment thread cmd/bbox/main.go Resolved
Comment thread cmd/bbox/agents.go Resolved
Comment thread cmd/bbox/agents.go Resolved
Comment thread cmd/bbox/agents.go Resolved
Comment thread cmd/bbox/agents.go Resolved
Comment thread cmd/bbox/agents.go Resolved
@JAORMX
JAORMX enabled auto-merge (squash) June 29, 2026 19:07
JAORMX and others added 2 commits June 29, 2026 22:17
Let users run arbitrary coding agents from global config with no Go code,
no fork, and no Dockerfile in this repo — the issue's "first useful
iteration" acceptance criteria:

  agents:
    aider:
      image: ghcr.io/acme/aider-bbox:latest
      command: ["aider"]
      env_forward: [OPENAI_API_KEY, "AIDER_*"]
      mcp:
        mode: env

Then `bbox agents doctor aider` and `bbox aider` work.

Changes:
- Extend AgentOverride with description, default_env, env_required,
  credentials.persist, settings entries, per-profile egress_hosts, and
  mcp.mode. Add AgentFromOverride (pure config->Agent mapping) and
  ValidateCustomAgent (pure load-time checks; image-ref parser injected
  as a closure to keep the domain free of go-containerregistry).
- Inject universal BBOX_* env vars into every VM via
  agent.BuildUniversalEnv, applied authoritatively after forwarded host
  vars. BBOX_MCP_URL uses a new shared config.MCPEndpointPath ("/mcp")
  constant, de-duplicating the path previously hardcoded in the proxy and
  all five built-in clients.
- mcp.mode: env enables the proxy without a config-file injector; the
  agent discovers it via BBOX_MCP_URL. mcp.mode: config is rejected.
- Add `bbox agents list|inspect|doctor`. inspect shows field provenance
  and env names only (never values); doctor exits non-zero on invalid
  config or missing required env. `bbox list` stays a shared alias.
- Safer defaults for custom agents: empty env_forward, egress profile
  standard, MCP authz safe-tools.
- Security: workspace-local config can never add a custom agent or new
  credential paths, repoint an existing agent's image/command, or widen
  its env_forward — tighten-only (mergeAgentOverride). Validate
  credential/settings paths are relative and cannot escape the home dir.
- Add a guard test pinning go-microvm's gateway IP to the literal
  pkg/sandbox uses for BBOX_MCP_URL.

Deferred to follow-ups: agents import/export, OCI-embedded manifests,
mcp.mode: config, agents add/init, and trusted host-side plugins.

Implemented via an architect -> implement -> 5-axis panel review -> fix
orchestration loop.

Fixes #191

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VP887qH8BMW4PMUXBuEqGc
- custom_agent.go: ValidateCustomAgent skips the egress_hosts gate when
  mcp.mode=env so the issue #191 canonical aider example passes
- sandbox.go: at runtime, mcp.mode=env + hostless non-permissive profile
  yields an empty (gateway-only) restricted policy instead of failing
  egress.Resolve, so the canonical example actually boots (all external
  egress still blocked; proxy is the only path out)
- sandbox.go: Prepare enforces env_required presence before booting the
  VM, failing fast with a pointer to 'bbox agents doctor'
- config.go: mergeAgentOverride ignores workspace-local MCP.Mode (#2,
  CWE-862) and makes per-agent MCP.Enabled tighten-only (#3, CWE-862)
- main.go: not-found path for declared-but-skipped agents points at
  'bbox agents doctor' instead of the generic available-agents list
- agents.go: TYPE column in list; provenance brackets for EnvForward and
  Egress profile; MISSING marker and doctor missing-env name the remedy;
  unknown-agent errors point at 'bbox agents list'
- tests: new runtime boot test, canonical-example validation test,
  tighten-only MCP.Enabled test; renamed MCPModeOverride test to
  LocalMCPModeIgnored
@JAORMX
JAORMX force-pushed the feat/191-byo-agents-phase1 branch from e65e4fa to 015b6c3 Compare June 29, 2026 19:18
@JAORMX
JAORMX merged commit 9b35a13 into main Jun 29, 2026
8 checks passed
@JAORMX
JAORMX deleted the feat/191-byo-agents-phase1 branch June 29, 2026 19:22
JAORMX added a commit that referenced this pull request Jul 1, 2026
* Add bbox run-image ephemeral one-shot command

Implements #205: `bbox run-image IMAGE [flags] -- CMD` boots an
arbitrary OCI image once, without editing config or registering an
agent. Builds an in-memory agent.Agent from flags via the existing
config.AgentFromOverride path (#200) and runs it through the normal
SandboxRunner — no config-file mutation, no registry persistence.

Ephemeral defaults (safer-than-custom): credential persistence off,
settings import off, env forwarding empty, MCP off, git token / SSH
agent forwarding off. Egress defaults to permissive with a stderr
disclosure so the bare example boots; tighten with
--egress-profile/--allow-host. --mcp forces mcp.mode=env and
inherits the safe-tools custom-agent authz default.

Reuses run() by extracting a shared runSandbox(...) tail. The
in-memory agent is registered data-only (nil Plugin) so
isCustomAgent/applyCustomAgentAuthzDefault apply the safe-tools
default. Name derives from the image repo basename when --name is
unset.

docs/run-image.md documents the minimum image contract (shell at
/bin/sh, command on PATH, CA bundle, sandbox user UID 1000) and
the ephemeral defaults.

* Fix run-image egress allow-host and MCP flag UX

Fold --allow-host into the run-image agent override so the
ValidateCustomAgent gate sees hosts for a non-permissive egress
profile. Previously --allow-host flowed only into RunOpts.AllowHosts
(applied at VM start), so the load-time validation rejected
--egress-profile standard/locked unless --mcp was also set, breaking
the documented example. Hosts are parsed via egress.ParseHostFlag and
filed under override.EgressHosts[profile]; runFlags.allowHosts is
cleared to avoid filing them twice.

Warn when MCP sub-flags (--mcp-authz-profile, --mcp-group, --mcp-port,
--mcp-config, --mcp-session-ttl) are set without --mcp, which is off by
default for run-image. They were silently dropped, misleading the
operator into thinking they tightened tool access.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Jakub Hrozek <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
JAORMX added a commit that referenced this pull request Jul 2, 2026
Phase 2 of bring-your-own agents: author a custom agent without hand-
editing YAML.

- `agents add NAME --image ... --command ...` appends a validated custom
  agent to the GLOBAL config, refusing to overwrite a built-in or existing
  custom agent unless --force. Reuses the pure AgentFromOverride and
  ValidateCustomAgent from #200.
- `agents init [NAME]` prints a commented starter agents: stanza to stdout,
  reusing the default config template's documentation.
- UpsertAgent (infra) performs a comment-preserving YAML node round-trip;
  a comment-only file (the `config init` template) is kept verbatim and the
  stanza appended, so documentation is never dropped.
- Both `agents add` and `agents doctor --json` emit a machine-readable
  receipt: agent summary, env vars by name only, MCP state, validator
  version, before/after config fingerprints, and explicit non-effects.

Custom agents remain global-only; the domain stays pure (writing is I/O in
internal/infra/config + cmd/bbox).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FAvtCCPrzJgL7z7WMPsLTG
JAORMX added a commit that referenced this pull request Jul 2, 2026
* Add bbox agents add/init scaffolding (#201)

Phase 2 of bring-your-own agents: author a custom agent without hand-
editing YAML.

- `agents add NAME --image ... --command ...` appends a validated custom
  agent to the GLOBAL config, refusing to overwrite a built-in or existing
  custom agent unless --force. Reuses the pure AgentFromOverride and
  ValidateCustomAgent from #200.
- `agents init [NAME]` prints a commented starter agents: stanza to stdout,
  reusing the default config template's documentation.
- UpsertAgent (infra) performs a comment-preserving YAML node round-trip;
  a comment-only file (the `config init` template) is kept verbatim and the
  stanza appended, so documentation is never dropped.
- Both `agents add` and `agents doctor --json` emit a machine-readable
  receipt: agent summary, env vars by name only, MCP state, validator
  version, before/after config fingerprints, and explicit non-effects.

Custom agents remain global-only; the domain stays pure (writing is I/O in
internal/infra/config + cmd/bbox).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FAvtCCPrzJgL7z7WMPsLTG

* Document bbox agents add/init commands

CLAUDE.md's custom-agent section still listed only list|inspect|doctor;
add and init were added in a prior PR but never mentioned.

* Reject --mcp-authz-profile without --mcp

buildAddAgentOverride only applied the authz profile inside the
--mcp branch, so setting --mcp-authz-profile without --mcp silently
had no effect and the receipt showed no mcp section at all.

* Harden UpsertAgent against races and multi-doc YAML

Two concurrent `bbox agents add` invocations could silently lose one
write (last-writer-wins, no error) since the read-modify-write had no
locking. Serialize it with a blocking advisory flock on a sidecar
file, matching the pattern already used in internal/infra/vm/firmware.go,
and make the write itself atomic via temp-file-plus-rename so a crash
mid-write can't corrupt the config or leave a torn file visible to
readers.

Also detect "---"-separated multi-document YAML in rootMapping and
error instead of silently dropping every document after the first,
which yaml.Unmarshal would otherwise do on re-encode.

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: Jakub Hrozek <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant