auto-code

内容来源:README.md(说明文档) · 原始地址 · 查看安装指南

原始内容

Autonomous Coding Agent

Note: This project is a modified fork of the autonomous-coding quickstart from claude-quickstarts.

A reusable package for running long-running autonomous coding sessions with the Claude Agent SDK. This package implements a two-agent pattern (initializer + coding agent) that can build complete applications from specifications over multiple sessions.

Installation

From PyPI (Recommended)

# Basic installation
pip install auto-code

# With rich terminal output (recommended)
pip install auto-code[rich]

# With Google Gemini support
pip install auto-code[google]

# With all optional features
pip install auto-code[all]

From Source

For development or to use unreleased features:

# Clone the repository
git clone https://github.com/AhamSammich/auto-code.git
cd auto-code

# Install in editable mode
pip install -e .

# With development dependencies
pip install -e ".[dev]"

# With Google ADK support
pip install -e ".[google]"

Prerequisites

Claude Code CLI: Install the latest version (for Claude provider):

npm install -g @anthropic-ai/claude-code

ripgrep: Required for Google provider's glob and grep tools:

# macOS
brew install ripgrep

# Ubuntu/Debian
sudo apt install ripgrep

# Windows (via scoop)
scoop install ripgrep

Authentication: Set environment variables for your chosen provider:

# Claude Provider (default)
# Option 1: API Key (from console.anthropic.com)
export ANTHROPIC_API_KEY='your-api-key-here'

# Option 2: OAuth Token (for Claude Pro/Max users)
export CLAUDE_CODE_OAUTH_TOKEN='your-oauth-token'
# (Generate with: claude setup-token)

# Google Provider
export GOOGLE_API_KEY='your-google-api-key'

Usage

Quick Start

# Build a new application
auto-code build ./my_app_spec.txt

# Add features to existing project
auto-code extend ./features.txt

# Create isolated worktree for testing
auto-code worktree ../experiment --run

Commands

Command Description
build Build a new application from scratch (greenfield mode)
extend Add features to an existing project
worktree Create an isolated git worktree with dependencies installed
container Build and run agent sessions in Docker containers
install Install Claude Code skills
version Show version information

Build Command (Greenfield Mode)

Build a new application from a specification:

# Basic usage
auto-code build ./spec.txt

# Custom output directory
auto-code build ./spec.txt -o ./my-project

# Limit sessions and use rich output
auto-code build ./spec.txt -n 10 --format rich

# With MCP servers
auto-code build ./spec.txt --mcp-config ./mcp.json

Options:

  • -o, --output DIR - Output directory (default: ./autonomous_project)
  • -n, --max-sessions N - Maximum sessions (default: unlimited)
  • --provider - LLM provider: claude (default) or google
  • --model - Specific model to use
  • --mcp-config FILE - MCP configuration file
  • --format - Output format: rich (default), plain, or json
  • --no-cleanup - Keep session files
  • --debug-log - Save debug output

Extend Command

Add features to an existing project:

# With features specification
auto-code extend ./features.txt

# In specific project directory
auto-code extend ./features.txt -p ./my-project

# Using app spec for comparison (generates feature list)
auto-code extend --app-spec ./app.txt

# With options
auto-code extend ./features.txt -n 5 --format rich

Options:

  • -p, --project DIR - Project directory (default: current directory)
  • --app-spec FILE - Original app spec for comparison
  • Same common options as build command

Worktree Command

Create an isolated git worktree for autonomous coding:

# Basic usage - auto-detects spec file
auto-code worktree ../my-feature

# Copy additional files
auto-code worktree ./experiment --include .env,.mcp_config.json

# Custom branch name
auto-code worktree ./new-feature --branch feature/my-feature

# Skip dependency installation
auto-code worktree ./quick-test --no-deps --no-venv

# Auto-run agent after setup
auto-code worktree ../experiment --run

What it does:

  1. Creates a new git worktree with auto-generated branch name
  2. Copies spec file and any additional files you specify
  3. Installs dependencies (npm/pnpm/bun/deno)
  4. Sets up Python venv and installs auto-code
  5. Optionally launches the agent immediately

Options:

  • --include FILES - Comma-separated files/dirs to copy
  • --spec FILE - Spec file (auto-detected if not specified)
  • --branch NAME - Custom branch name
  • --no-deps - Skip dependency installation
  • --no-venv - Skip Python venv creation
  • --run - Auto-run agent after setup

Requirements:

  • Requires access to auto-code source code
  • Install as editable: pip install -e /path/to/auto-code
  • Or set environment variable: export AUTO_CODE_SOURCE=/path/to/auto-code

Container Command

Run agent sessions in isolated Docker containers for stronger isolation or remote execution:

# Build the Docker image (do once)
auto-code container build

# Run agent in container
auto-code container run ./my-worktree

# With custom image tag
auto-code container run ./my-worktree --image auto-code:dev

# With additional environment variables
auto-code container run ./my-worktree --env DEBUG=1

# With environment file
auto-code container run ./my-worktree --env-file .env.local

# Clean up stopped containers
auto-code container cleanup

Subcommands:

  • build - Build the auto-code Docker image
  • run <worktree> - Run agent in container with worktree mounted
  • cleanup - Remove stopped auto-code containers

Options for container run:

  • --image TAG - Docker image to use (default: auto-code:latest)
  • --spec FILE - Spec file (auto-detected if not specified)
  • --network MODE - Docker network mode (default: bridge)
  • --env KEY=VALUE - Additional environment variables (repeatable)
  • --env-file FILE - Read environment variables from file (repeatable)

What it does:

  1. Mounts your worktree directory into the container (changes persist)
  2. Passes Claude API credentials from your environment
  3. Forwards SSH agent for git authentication
  4. Runs the agent in an isolated environment
  5. Automatically cleans up the container on exit

Requirements:

  • Docker must be installed and running
  • Build the image first: auto-code container build

See docs/features/containerization.md for detailed documentation.

Python Library

from autonomous_coding import run_autonomous_agent
import asyncio
from pathlib import Path

# Greenfield mode - build new app
asyncio.run(run_autonomous_agent(
    project_dir=Path("./my_project"),
    spec_path=Path("./my_app_spec.txt"),
    mode="greenfield"  # default
))

# Extension mode - add features with explicit features spec
asyncio.run(run_autonomous_agent(
    project_dir=Path("."),  # current directory
    mode="extend",
    features_spec_path=Path("./features.txt")
))

# Extension mode - use app spec for comparison
asyncio.run(run_autonomous_agent(
    project_dir=Path("."),
    spec_path=Path("./app_spec.txt"),
    mode="extend"
))

Claude Code Skills

Install skills for use in Claude Code:

auto-code install

Then invoke from Claude Code:

/generate-spec
/generate-feature-spec

Environment Variables

Variable Description
AUTO_CODE_DEFAULT_PROVIDER Default provider: claude or google
AUTO_CODE_OUTPUT_FORMAT Default output format: rich, plain, or json
AUTO_CODE_NO_CLEANUP Set to true to disable session file cleanup
ANTHROPIC_API_KEY API key for Claude provider
CLAUDE_CODE_OAUTH_TOKEN OAuth token for Claude Pro users
GOOGLE_API_KEY API key for Google provider

How It Works

Two-Agent Pattern

Both modes use a two-agent pattern:

Greenfield Mode:

  1. Initializer Agent (Session 1): Creates feature_list.json with 200+ test cases, sets up project structure, and initializes git.
  2. Coding Agent (Sessions 2+): Implements features one by one, marks them as passing.

Extension Mode:

  1. Extension Initializer (Session 1): Analyzes existing codebase, creates codebase-analysis.md, then generates feature_list.json for new features only.
  2. Extension Coding Agent (Sessions 2+): Implements new features following existing patterns, ensures no regressions.

Extension Mode Details

When using the extend command:

  • Codebase Analysis: First session explores and documents the existing architecture
  • Pattern Matching: Agent follows existing code style and conventions
  • Regression Testing: Verifies existing features still work after changes
  • Minimal Changes: Only modifies what's necessary for new features
  • Integration Focus: Ensures new features work with existing functionality

Features Specification (Extension Mode)

When providing a features specification file, you give an explicit list of features to implement. This gives you precise control over what the agent builds.

Format: Structured markdown with ## headers for each feature:

## User Authentication
Add login and logout functionality with session management.
Support email/password authentication.

## Dark Mode Toggle
Allow users to switch between light and dark themes.
- Persist preference in localStorage
- Apply theme on page load

## Export to PDF
Add ability to export data to PDF format.

With features spec (auto-code extend ./features.txt): The agent implements ONLY the features listed in the file, one entry per ## Section. No additional recommendations are added.

Without features spec (auto-code extend --app-spec ./app.txt): The agent analyzes the codebase, compares it to app_spec.txt, and generates a feature list based on what's missing (up to ~20 features).

Session Management

  • Each session runs with a fresh context window
  • Progress is persisted via feature_list.json and git commits
  • The agent auto-continues between sessions (3 second delay)
  • Press Ctrl+C to pause; run the same command to resume

MCP Configuration

Configure additional MCP servers (like Supabase, Postgres, etc.) using --mcp-config:

auto-code build ./spec.txt --mcp-config ./mcp.json
auto-code extend ./features.txt --mcp-config ./mcp.json

Config format (mcp.json):

{
  "servers": {
    "supabase": {
      "command": "npx",
      "args": ["@supabase/mcp-server"]
    },
    "postgres": {
      "command": "npx",
      "args": ["@modelcontextprotocol/server-postgres"],
      "env": {
        "DATABASE_URL": "${DATABASE_URL}"
      }
    }
  },
  "allowed_tools": [
    "mcp__supabase__list_tables",
    "mcp__supabase__apply_migration",
    "mcp__supabase__run_sql",
    "mcp__postgres__query"
  ]
}

Fields:

  • servers: MCP server definitions (same format as Claude Code)
  • allowed_tools: Explicit list of MCP tools to permit (required for security)

Environment variables: Use ${VAR} syntax in args/env for dynamic values.

The default Puppeteer MCP is always included. Additional MCPs from your config are merged with the defaults.

Provider Selection

Choose between Claude and Google providers:

# Use Claude (default)
auto-code build ./spec.txt

# Use Google Gemini via ADK
auto-code build ./spec.txt --provider google

# Or set default via environment
export AUTO_CODE_DEFAULT_PROVIDER=google
auto-code build ./spec.txt
Provider Model Default Built-in Tools
claude claude-sonnet-4-5-20250929 Via Claude Agent SDK
google gemini-3-flash-preview read, write, edit, list, glob, grep, bash

Google Provider Notes:

  • Requires GOOGLE_API_KEY environment variable
  • Requires ripgrep binary for glob/grep tools
  • Install with: pip install -e ".[google]"

Important Timing Expectations

Note: This runs for a long time!

  • First session (initialization): Generates 200 test cases. Takes several minutes and may appear to hang - this is normal.
  • Subsequent sessions: Each coding iteration takes 5-15 minutes depending on complexity.
  • Full app: Building all 200 features typically requires many hours across multiple sessions.

Security Model

This package uses defense-in-depth security (see security.py):

  1. OS-level Sandbox: Bash commands run in an isolated environment
  2. Filesystem Restrictions: File operations restricted to the project directory only
  3. Bash Allowlist: Only specific commands are permitted:
    • File inspection: ls, cat, head, tail, wc, grep
    • Node.js: npm, node
    • Version control: git
    • Process management: ps, lsof, sleep, pkill (dev processes only)

Package Structure

auto-code/
├── pyproject.toml                # Package configuration
├── docker/                       # Docker containerization
│   ├── Dockerfile                # Base image definition
│   └── .dockerignore             # Build context exclusions
├── src/autonomous_coding/        # Package source
│   ├── __init__.py               # Public API
│   ├── agent.py                  # Agent session logic
│   ├── cli.py                    # CLI entry point
│   ├── client.py                 # Claude SDK client configuration
│   ├── container.py              # Docker container management
│   ├── security.py               # Bash command allowlist
│   ├── progress.py               # Progress tracking utilities
│   ├── worktree.py               # Git worktree setup utilities
│   ├── prompts.py                # Prompt loading utilities
│   └── prompts/                  # Bundled prompt templates
│       ├── initializer_prompt.md         # Greenfield mode - session 1
│       ├── coding_prompt.md              # Greenfield mode - sessions 2+
│       ├── extension_initializer_prompt.md  # Extend mode - session 1
│       └── extension_coding_prompt.md       # Extend mode - sessions 2+
├── skill/                        # Claude Code skill definition
│   ├── auto-code/
│   ├── generate-spec/
│   └── generate-feature-spec/
├── docs/                         # Documentation
│   └── features/                 # Feature documentation
│       ├── containerization.md   # Docker container feature
│       └── multi-provider.md     # Multi-provider support
└── tests/                        # Security tests
    └── test_security.py

Generated Project Structure

After running, your project directory will contain:

my_project/
├── feature_list.json         # Test cases (source of truth)
├── app_spec.txt              # Copied specification
├── init.sh                   # Environment setup script
├── claude-progress.txt       # Session progress notes
├── .claude_settings.json     # Security settings
└── [application files]       # Generated application code

Running the Generated Application

After the agent completes (or pauses):

cd my_project

# Run the setup script created by the agent
./init.sh

# Or manually (typical for Node.js apps):
npm install
npm run dev

Creating Your Own Specification

Create a text file describing your application. Include:

  • Project overview and goals
  • Technology stack requirements
  • Database schema (if applicable)
  • API endpoints
  • UI/UX requirements
  • Feature list

See the example specs in the claude-quickstarts repository for reference.

Troubleshooting

"Appears to hang on first run" This is normal. The initializer agent is generating 200+ detailed test cases.

"Command blocked by security hook" The agent tried to run a command not in the allowlist. This is the security system working as intended.

"No authentication found" Set either ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN in your environment.

API Reference

run_autonomous_agent(project_dir, spec_path, model, max_iterations, mode, features_spec_path, mcp_config_path, provider_name, renderer, cleanup, debug_log)

Run the autonomous agent loop.

Parameters:

  • project_dir (Path): Directory for the project
  • spec_path (Path, optional): Path to the application specification file. Required for greenfield mode. Optional in extend mode when features_spec_path is provided.
  • model (str, optional): Model to use. Default: provider's default model
  • max_iterations (int, optional): Maximum iterations. Default: 20
  • mode (str, optional): "greenfield" (new app) or "extend" (existing project). Default: "greenfield"
  • features_spec_path (Path, optional): Path to features specification file (extend mode only). Default: None
  • mcp_config_path (Path, optional): Path to MCP configuration JSON file. Default: None
  • provider_name (str, optional): LLM provider to use ("claude" or "google"). Default: "claude"
  • renderer (BaseRenderer, optional): Output renderer instance. Default: PlainTextRenderer
  • cleanup (bool, optional): Whether to run cleanup after completion. Default: True
  • debug_log (bool, optional): Whether to save agent output log to .auto-code/<timestamp>/agent_output.log. Default: False

run_agent_session(client, message, project_dir)

Run a single agent session.

count_passing_tests(project_dir)

Count passing and total tests in feature_list.json.

Returns: (passing_count, total_count)

License

MIT