AAnvio
Reference ArchiveADRs

ADR 0009: Runtime OAuth Authentication (Vendor-Native Agents)

Accepted

6 min read

This is a migrated reference document from the original Anvio source repo. Content is preserved as-is; canonical documentation lives in the sections above in the sidebar.

Original path: docs/adr/0009-runtime-oauth-authentication.md

Status

Accepted

Context

Anvio supports multiple runtime providers (local, claude-code, cursor, codex, future antigravity) in addition to direct model providers (anthropic, openai, …).

Today, Claude is accessed primarily via @anthropic-ai/sdk and ANTHROPIC_API_KEY. External runtimes (claude-code, cursor, codex, antigravity) were stubs. Product direction requires:

  • Vendor-native runtimes authenticate through the official app/CLI OAuth or session (Pro/Max subscription), not Anvio-managed API keys.
  • local runtime continues to use API keys / credential pools for direct provider access and fallback.
  • Vendor-native parity shipped for Cursor (ACP + app session), OpenAI Codex CLI, and Google Antigravity CLI — see "(implemented)" sections below.

Anthropic policy note: third-party products must not host claude.ai login UI or resell subscription rate limits. Anvio therefore delegates login to the official Claude Code CLI (claude setup-token) and only stores the resulting token locally (encrypted connection broker).

Decision

Adopt a two-layer auth model:

LayerAuth mechanismWhen used
Runtime providerOAuth token / app session via official vendor toolingagent.spec.runtime.provider ∈ \{ claude-code, cursor, codex, antigravity \}
Model providerAPI key / credential poollocal runtime (default) and explicit model routing

Claude Code (implemented)

  1. Use @anthropic-ai/claude-agent-sdk inside ClaudeCodeRuntimeProvider.
  2. Resolve auth in order:
    • Encrypted connection broker payload (service: claude-code)
    • CLAUDE_CODE_OAUTH_TOKEN environment variable
    • Interactive CLI cache (SDK fallback when neither is set and user already ran claude login)
  3. Never pass ANTHROPIC_API_KEY into the Agent SDK subprocess env when OAuth mode is active — API key shadows OAuth and bills API credits instead of subscription quota.
  4. User onboarding:
    anvio setup-token --claude    # wraps official `claude setup-token`
    anvio setup-token --cursor    # wraps official `agent login`
    anvio setup-token --codex     # wraps official `codex login`
    anvio setup-token --list      # show supported vendors
    Legacy alias: anvio connect login claude-code → anvio setup-token --claude.
  5. Agent binding:
    spec:
      runtime:
        provider: claude-code
        fallback: local
      model:
        provider: anthropic   # used only when fallback: local
        model: claude-sonnet-4-20250514

Cursor (implemented)

  • Auth via Cursor agent CLI (agent login) or ACP (anvio acp serve).
  • anvio setup-token --cursor stores CLI session in connection broker.
  • CursorRuntimeProvider uses ACP when ANVIO_ACP_ENDPOINT is set; otherwise agent -p.

Codex (implemented)

  • Auth via OpenAI Codex CLI (codex login) → broker stores ~/.codex/auth.json snapshot.
  • CodexRuntimeProvider runs codex exec with isolated auth home; strips OPENAI_API_KEY.

Antigravity (implemented)

  • Official Antigravity CLI (agy) — Google Sign-In via system keyring.
  • anvio setup-token --antigravity wraps agy auth login (auto-installs CLI if missing).
  • AntigravityRuntimeProvider runs agy -p; strips GEMINI_API_KEY; optional ANTIGRAVITY_TOKEN for CI.

Platform routing

RuntimeRoutingAgentRuntime selects external runtime when configured; otherwise DefaultAgentRuntime (model provider + tool loop).

Runtime fallback (cross-vendor)

Fallback walks an ordered chain A → B → C when a runtime is not configured or fails at runtime with auth errors (token expired, 401, OAuth not set).

# Chain: claude-code → cursor → codex → local
spec:
  runtime:
    provider: claude-code
    fallbacks: [cursor, codex, local]
  model:
    provider: anthropic   # used only when fallback reaches `local`
    model: claude-sonnet-4-20250514

Shorthand (single hop) still works: fallback: local → [provider, local].

TriggerBehavior
Primary not configured (isConfigured())Skip to next in chain
Primary auth failure mid-runRetry next in chain (OAuth expired, 401, login required)
Non-auth errorFail immediately (no failover)

Per-agent and per-user runtime

ScopeMechanismExample
Per agentagent.spec.runtime in agent YAML/MDarchitect → claude-code, coder → codex
Per userConnection broker key channel:userId:serviceAlice OAuth Claude, Bob OAuth Codex
# Multi-user OAuth on one workspace
export ANVIO_CONNECTION_ENCRYPTION_KEY=your-secret
anvio setup-token --claude --user alice
anvio setup-token --codex  --user bob

Agent-to-agent collaboration uses orchestration (delegate_task, supervisor pattern, mixture_of_agents, workflows) — not a shared chat thread by default.

Docker, server, and headless OAuth

Vendor OAuth flows expect a browser. Headless servers and containers should not run interactive login inside the container on first boot.

Run login on a machine with a browser, then ship encrypted broker state to the server.

# On laptop / bastion (has browser)
export ANVIO_CONNECTION_ENCRYPTION_KEY="${ANVIO_CONNECTION_ENCRYPTION_KEY}"
anvio setup-token --claude --user alice
anvio setup-token --codex  --user bob

# Copy to server (includes workspace/connections/_state/*.json)
rsync -av ./workspace/connections/ user@server:/opt/anvio/workspace/connections/

docker-compose worker/gateway snippet:

services:
  worker:
    environment:
      ANVIO_WORKSPACE: /workspace
      ANVIO_CONNECTION_ENCRYPTION_KEY: ${ANVIO_CONNECTION_ENCRYPTION_KEY}
      # Optional global fallback when broker miss:
      # CLAUDE_CODE_OAUTH_TOKEN: ${CLAUDE_CODE_OAUTH_TOKEN}
    volumes:
      - ./workspace:/workspace
    # Do NOT bake tokens into the image layer

Enable broker in workspace/harness/defaults.yaml:

connectBroker:
  enabled: true
  encryptionKeyEnv: ANVIO_CONNECTION_ENCRYPTION_KEY

Pattern 2 — Environment variables (single-tenant)

Inject tokens via secrets manager / .env (never commit):

environment:
  CLAUDE_CODE_OAUTH_TOKEN: ${CLAUDE_CODE_OAUTH_TOKEN}
  CODEX_ACCESS_TOKEN: ${CODEX_ACCESS_TOKEN}   # optional Codex path

Platform resolves Claude OAuth from env when broker is disabled or empty.

Pattern 3 — Headless vendor CLI

VendorHeadless commandNotes
Codexcodex login --device-authOpen device URL on another machine
CursorNO_OPEN_BROWSER=1 agent loginPaste URL manually
Claude Codeclaude setup-token on bastionCopy token → Pattern 1 or 2

After Codex device login, copy ~/.codex/auth.json or run anvio setup-token --codex --user bob on the bastion.

Pattern 4 — local runtime + API key (simplest for Docker)

Existing production compose uses API keys for local fallback:

environment:
  ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY}

Agents with runtime.fallback: local work without vendor OAuth. Use when subscription OAuth is not required in the container.

Pattern 5 — Mount vendor credential dirs (dev/staging only)

volumes:
  - ${HOME}/.codex:/root/.codex:ro

Weak isolation — acceptable for single-developer staging, not recommended for multi-tenant production.

Multi-user in Docker

Map channel userId to broker entries provisioned offline:

Usersetup-tokenAgent example
alice--claude --user alicearchitect (claude-code)
bob--codex --user bobcoder (codex)

Sessions must use matching userId (auth plugin or defaultUserId override per channel). Each user gets isolated OAuth from broker; same agent definition can serve both if runtime resolves per user token.

Security checklist

  • Never commit ANVIO_CONNECTION_ENCRYPTION_KEY or OAuth tokens to git.

  • Rotate encryption key only with a migration plan (existing blobs become unreadable).

  • Prefer secrets manager (Vault, K8s Secret, Docker Secret) over plain .env in production.

  • Do not run anvio setup-token in CI without a dedicated service account token path.

  • Claude Code agents can run on Pro/Max subscription quota without ANTHROPIC_API_KEY.

  • local fallback still requires API keys — unchanged Level-1 behavior.

  • Connection broker stores runtime OAuth tokens separately from MCP/channel tokens (service discriminator).

  • Compliance: login UX stays on vendor CLI; Anvio stores tokens locally only.

Alternatives Rejected

  • Custom claude.ai OAuth UI in Anvio — violates Anthropic third-party policy; rejected.
  • Single API-key path for all runtimes — double billing risk; doesn't use subscription quota.
  • Hard-require API key on every agent — blocks vendor-native runtime goal.

References

Edit on GitHub

Last updated on

On this page