The claw code API client lives in rust/crates/api/src/client.rs and serves as the sole interface between the agent runtime and the Anthropic LLM backend. It wraps a reqwest::Client with authentication, base URL configuration, and a configurable retry policy. Every message sent to and received from the Claude API flows through this crate.

AnthropicClient

The AnthropicClient struct is the central type. It holds the HTTP client, authentication source, base URL, and retry configuration. Two primary methods handle all API communication:

常數

常數
DEFAULT_BASE_URLhttps://api.anthropic.com
ANTHROPIC_VERSION2023-06-01
DEFAULT_MAX_RETRIES2
DEFAULT_INITIAL_BACKOFF200ms
DEFAULT_MAX_BACKOFF2s

認證

The claw code API client supports multiple authentication modes through the AuthSource enum:

// AuthSource enum enum AuthSource { None, ApiKey(String), BearerToken(String), ApiKeyAndBearer { api_key: String, bearer_token: String }, }

Two factory methods construct the client from environment state:

OAuth PKCE 流程

For browser-based authentication, the claw code API client implements the full OAuth PKCE (Proof Key for Code Exchange) flow:

  1. generate_pkce_pair() — Creates a cryptographic code verifier and S256 challenge.
  2. loopback_redirect_uri(port) — Constructs the redirect URI pointing to a local callback listener.
  3. The user is directed to the browser for authorization.
  4. A local server captures the callback with the authorization code.
  5. exchange_oauth_code(config, request) — Exchanges the code for tokens.
  6. refresh_oauth_token(config, request) — Refreshes expired tokens.

Credentials are persisted as an OAuthTokenSet containing access_token, refresh_token, expires_at, and scopes. The save operation uses atomic temp-file rename to prevent corruption.

API 型別

MessageRequest

The request payload sent to the Messages API:

Field 型別 說明
modelStringModel identifier (e.g., claude-sonnet-4-20250514)
max_tokensu32Maximum tokens in the response
messagesVec<Message>Conversation history
systemOption<String>System prompt
toolsOption<Vec<Tool>>Available tools for the model
tool_choiceOption<ToolChoice>Tool selection policy
streamboolWhether to stream the response

MessageResponse

Field 型別 說明
idStringUnique message identifier
kindStringMessage type
roleStringAlways "assistant"
contentVec<OutputContentBlock>Response content blocks (text, tool use)
modelStringModel that generated the response
stop_reasonOption<String>Why generation stopped
stop_sequenceOption<String>The stop sequence that triggered, if any
usageUsageToken usage metrics
request_idOption<String>Server-assigned request ID

串流與 SSE 解析

The claw code API client processes streaming responses using Server-Sent Events (SSE). The SseParser handles raw byte chunks from the HTTP response:

StreamEvent 列舉

Variant 說明
MessageStartStream opened, includes initial message metadata
MessageDeltaMessage-level updates (stop reason, usage)
ContentBlockStartNew content block beginning
ContentBlockDeltaIncremental content — TextDelta for text, InputJsonDelta for tool input
ContentBlockStopContent block complete
MessageStopStream complete

使用量追蹤

Every response includes a Usage struct that tracks token consumption across four dimensions:

Field 說明
input_tokensTokens consumed by the input prompt
cache_creation_input_tokensTokens used to create a new cache entry
cache_read_input_tokensTokens served from an existing cache entry
output_tokensTokens generated in the response

The total_tokens() method returns the sum of all four fields.

重試策略

The claw code API client automatically retries failed requests for transient HTTP errors. The following status codes are considered retryable:

// Retryable HTTP status codes 408 // Request Timeout 409 // Conflict 429 // Too Many Requests (rate limit) 500 // Internal Server Error 502 // Bad Gateway 503 // Service Unavailable 504 // Gateway Timeout

Retries use exponential backoff starting at 200ms, capped at 2 seconds, with a maximum of 2 retry attempts by default.

錯誤型別

The ApiError enum covers every failure mode in the API client:

Variant 說明
MissingApiKeyNo API key or token found in environment or saved credentials
ExpiredOAuthTokenOAuth token has expired and refresh failed
AuthAuthentication rejected by the server (401/403)
HttpHTTP transport error (connection, DNS, TLS)
IoFile system I/O error (credential read/write)
JsonJSON serialization/deserialization error
ApiAPI-level error with status, error_type, message, and retryable flag
RetriesExhaustedAll retry attempts failed
InvalidSseFrameMalformed SSE frame during streaming
BackoffOverflowBackoff calculation overflowed (extremely unlikely)