claude-code-proxy/config.yaml.example
sid 8e550b9785 Local fork: hardening + ops improvements (timeout knob, demotion, /livez, drain)
This commit captures both the prior accumulated work-in-progress
(framework migration web/→svelte/, postgres storage, conversation
viewer, dashboard auth, OpenAPI spec, integration tests) AND today's
operational improvements layered on top. History wasn't checkpointed
incrementally; happy to split it via interactive rebase if a reviewer
wants smaller commits.

Today's changes (in addition to the older WIP):

1. Configurable upstream response-header timeout
   - ANTHROPIC_RESPONSE_HEADER_TIMEOUT env (default 300s)
   - Replaces hardcoded 300s in provider/anthropic.go that was firing
     on opus + 1M-context + extended thinking non-streaming requests
   - Files: internal/config/config.go, internal/provider/anthropic.go

2. Structured forward-error diagnostic logging
   - When a forward to Anthropic fails, log a single key=value line
     with request_id, model, stream, body_bytes, has_thinking,
     anthropic_beta, query, elapsed, ctx_err — alongside the existing
     human-readable error line for back-compat
   - Files: internal/handler/handlers.go (logForwardFailure)

3. Full SSE protocol passthrough + Flusher fix
   - handler/handlers.go: forward all SSE lines verbatim (event:, id:,
     retry:, : comments, blank-line terminators), not only data:.
     Previous code produced malformed SSE for strict parsers.
   - middleware/logging.go: explicit Flush() method on responseWriter.
     Embedding http.ResponseWriter (interface) does not auto-promote
     Flush(), so every w.(http.Flusher) check in the streaming
     handler was returning ok=false and SSE writes buffered in net/http
     until the body closed.

4. Non-streaming → streaming demotion (feature-flagged)
   - ANTHROPIC_DEMOTE_NONSTREAMING env (default false)
   - When enabled and the routed provider is anthropic, force stream=true
     upstream for clients that asked for stream=false. Receive SSE,
     accumulate via accumulateSSEToMessage (handles text, tool_use with
     partial_json reassembly, thinking, signature, citations_delta,
     usage merge), and synthesize a single non-streaming JSON response.
   - Eliminates the ResponseHeaderTimeout class of failure entirely.
   - Body rewrite uses json.Decoder + UseNumber() to preserve integer
     precision in unknown nested fields (tool inputs from prior turns).
   - Files: internal/config/config.go, internal/handler/handlers.go,
     cmd/proxy/main.go, cmd/proxy/main_test.go

5. Live operational state: /livez gauge + graceful drain
   - New internal/runtime package: atomic in-flight counter + draining flag
   - New middleware/inflight.go: increments runtime gauge, applied to
     /v1/* subrouter so Messages, ChatCompletions, and ProxyPassthrough
     are all counted
   - /v1/* moved to a gorilla/mux subrouter so the InFlight middleware
     applies surgically; /health, /livez, /openapi.* remain on parent
     router (unauthenticated, uncounted)
   - Health handler returns 503 draining when runtime.IsDraining() is
     true, so Traefik stops routing to a slot before drain begins
   - New /livez handler returns {status, in_flight, draining, timestamp}
   - SIGTERM handler in main.go: SetDraining(true), poll for in_flight==0
     with 32-min ceiling and 1s tick (logs every 10s), then srv.Shutdown
   - Auth bypass list extended with /livez
   - Files: internal/runtime/runtime.go (new),
     internal/middleware/inflight.go (new),
     internal/middleware/auth.go,
     internal/handler/handlers.go (Health, Livez, runtime import),
     cmd/proxy/main.go (subrouter, drain loop)

6. OpenAPI spec updates
   - Document Health 503 response and new DrainingResponse schema
   - Add /livez path with LivezResponse schema
   - Files: internal/handler/openapi.go

Verified: go build ./... clean, go test ./... all pass, go vet clean.
Three rounds of codex peer review across changes 1-5; all feedback
addressed (citations_delta, json.Number precision, drain-loop logging
via lastLog timestamp, PathPrefix tightened to "/v1/").
2026-05-02 15:15:58 -06:00

212 lines
7.2 KiB
Text

# LLM Proxy Configuration Example
# This file demonstrates all available configuration options
# Copy this file to config.yaml and customize as needed
# Server configuration
server:
# Bind host for the proxy server.
# Example local-only value. The current built-in default is 0.0.0.0, but
# startup validation rejects public binds unless auth is enabled or
# TRUST_PROXY=true is set for a reverse-proxy deployment.
host: 127.0.0.1
# Port to listen on (default: 3001)
port: 3001
# Timeout configurations
timeouts:
# Maximum duration for reading the entire request, including the body
read: 10m
# Maximum duration before timing out writes of the response
write: 10m
# Maximum amount of time to wait for the next request when keep-alives are enabled
idle: 10m
# Provider configurations
providers:
# Anthropic Claude configuration
anthropic:
# Base URL for Anthropic API (can be changed for custom endpoints)
base_url: "https://api.anthropic.com"
# Maximum number of retries for failed requests
max_retries: 3
# OpenAI configuration
openai:
# API key for OpenAI
# Can also be set via OPENAI_API_KEY environment variable
# api_key: "..."
# Base URL for OpenAI API (can be changed for custom endpoints)
# Can also be set via OPENAI_BASE_URL environment variable
# base_url: "https://api.openai.com"
# Allow clients to provide their own API key via header
# Can also be set via OPENAI_ALLOW_CLIENT_API_KEY environment variable
allow_client_api_key: false
# Header name for client-provided API key (default: x-openai-api-key)
# Can also be set via OPENAI_CLIENT_API_KEY_HEADER environment variable
client_api_key_header: "x-openai-api-key"
# CORS Configuration
# Controls Cross-Origin Resource Sharing for the web UI
cors:
# Allowed origins. The built-in defaults are permissive, so set these
# explicitly if you want tighter browser access.
# Can also be set via CORS_ALLOWED_ORIGINS environment variable (comma-separated)
allowed_origins:
- "http://localhost:3000"
- "http://127.0.0.1:3000"
- "http://localhost:5174"
- "http://127.0.0.1:5174"
# Allowed HTTP methods
# Can also be set via CORS_ALLOWED_METHODS environment variable (comma-separated)
allowed_methods:
- "GET"
- "POST"
- "DELETE"
- "OPTIONS"
# Allowed headers
# Can also be set via CORS_ALLOWED_HEADERS environment variable (comma-separated)
allowed_headers:
- "Accept"
- "Authorization"
- "Content-Type"
- "Anthropic-Version"
- "Anthropic-Beta"
- "X-API-Key"
- "X-Requested-With"
# Auth Configuration
# When enabled, all non-health endpoints require bearer token or X-API-Key auth.
auth:
# Enable auth for non-health endpoints
# Public/non-loopback binds must enable auth and set a token.
enabled: false
# Shared secret used for Authorization: Bearer <token> or X-API-Key: <token>
token: ""
# Header name used for API-key style auth
api_key_header: "x-api-key"
# Allow requests from localhost to bypass auth when enabled
allow_localhost_bypass: true
# Optional dashboard-only password. When set, the Svelte dashboard and
# dashboard data endpoints require HTTP basic auth with username "admin".
dashboard_password: ""
# Set to true when running behind a trusted reverse proxy and you want to
# skip the public-bind auth requirement enforced at startup.
trust_proxy: false
# Storage configuration
storage:
# Storage backend. Supported values: sqlite, postgres
db_type: "sqlite"
# SQLite database path for storing request history
db_path: "requests.db"
# PostgreSQL connection string used when db_type=postgres
database_url: ""
# Keep request bodies in storage. Disable for metadata-only tracking.
capture_request_body: true
# Keep response bodies and streaming chunks in storage.
capture_response_body: true
# Store only request/response metadata, not payload bodies.
metadata_only: false
# Delete records older than this many days on write. 0 disables cleanup.
retention_days: 0
# JSON payload fields to redact before storage.
redacted_fields:
- api_key
- authorization
- token
- password
- secret
- access_token
- refresh_token
- client_secret
# Directory for storing request files (if needed in future)
# requests_dir: "./requests"
# Subagent Configuration (Optional)
# Enable this feature if you want to route specific Claude Code agents to different LLM providers
# For subagent setup instructions, see: https://docs.anthropic.com/en/docs/claude-code/sub-agents
subagents:
# Enable subagent routing (default: false)
enable: false
# Maps subagent types to specific models
# Only used when enable: true
mappings:
# Code review specialist (example)
# code-reviewer: "gpt-4o"
# Data analysis expert (example)
# data-analyst: "o3"
# Documentation writer (example)
# doc-writer: "gpt-3.5-turbo"
# Environment variable overrides:
# The following environment variables will override the YAML configuration:
#
# Server:
# SERVER_HOST - Bind host (default: 127.0.0.1)
# PORT - Server port
# READ_TIMEOUT - Read timeout duration
# WRITE_TIMEOUT - Write timeout duration
# IDLE_TIMEOUT - Idle timeout duration
#
# Anthropic:
# ANTHROPIC_FORWARD_URL - Anthropic base URL
# ANTHROPIC_VERSION - Anthropic API version
# ANTHROPIC_MAX_RETRIES - Maximum retries for Anthropic requests
#
# OpenAI:
# OPENAI_API_KEY - OpenAI API key
# OPENAI_BASE_URL - OpenAI base URL
# OPENAI_ALLOW_CLIENT_API_KEY - Allow client-provided API keys (true/false)
# OPENAI_CLIENT_API_KEY_HEADER - Header name for client API key
#
# Auth:
# AUTH_ENABLED - Enable auth for non-health endpoints (true/false)
# AUTH_TOKEN - Shared secret for bearer / API-key auth
# AUTH_API_KEY_HEADER - Header name for API-key style auth
# AUTH_ALLOW_LOCALHOST_BYPASS - Allow loopback requests to bypass auth (true/false)
# DASHBOARD_PASSWORD - Dashboard HTTP basic auth password
# TRUST_PROXY - Skip public-bind auth enforcement behind a reverse proxy
#
# Storage:
# DB_TYPE - Storage backend (sqlite/postgres)
# DATABASE_URL - PostgreSQL connection string
# DB_PATH - Database file path
# STORAGE_CAPTURE_REQUEST_BODY - Keep request bodies (true/false)
# STORAGE_CAPTURE_RESPONSE_BODY - Keep response bodies (true/false)
# STORAGE_METADATA_ONLY - Store metadata only (true/false)
# STORAGE_RETENTION_DAYS - Delete rows older than N days
# STORAGE_REDACTED_FIELDS - Comma-separated payload fields to redact
#
# CORS:
# CORS_ALLOWED_ORIGINS - Comma-separated allowed origins
# CORS_ALLOWED_METHODS - Comma-separated allowed methods
# CORS_ALLOWED_HEADERS - Comma-separated allowed headers
#
# Subagents:
# SUBAGENT_MAPPINGS - Comma-separated subagent:model pairs
# Example: "code-reviewer:claude-3-5-sonnet"