kiro-rs

repository·master·Indexed 23 days ago

https://github.com/hank9999/kiro.rs

A Rust-based proxy service (version 2026.3.1) that makes the Kiro API compatible with the Anthropic Claude API format. It supports streaming responses (SSE), automatic OAuth token refreshing, multi-credential failover, load balancing, and Claude's extended thinking mode. The service includes standard /v1 endpoints and Claude Code compatible /cc/v1 endpoints, along with an Admin API and Web UI for credential management.

Tokens
12.8K
Snippets
26
Records
76
Agent score
80%

What's inside kiro-rs

  1. What is kiro-rs

    master
    kiro-rs is a proxy service written in Rust that provides an Anthropic Claude API compatible interface. It acts as a bridge, converting Anthropic API requests into Kiro API requests. It supports features like streaming responses (SSE), automatic OAuth token refreshing, multi-credential failover, load balancing, and Claude's extended thinking mode.
  2. Understand the kiro-rs project structure

    master

    The kiro-rs project is organized into several core functional modules:

    • src/anthropic/: Provides an Anthropic API compatibility layer, including routing, request handlers, authentication middleware, and protocol converters.
    • src/kiro/: Contains the core Kiro API client logic, including provider management, token management, machine ID generation, and an AWS Event Stream parser for streaming responses.
    • src/admin/: Implements the Admin API module with its own routing, handlers, and business logic services.
    • src/admin_ui/: Handles the routing for embedded static files from the Admin UI.
    • admin-ui/: The frontend source for the Admin UI; its build artifacts are embedded directly into the final binary.
    • src/model/: Defines application configuration and command-line argument models.
    • config.example.json: A template for the required configuration file.
  3. Manage multiple credentials in `credentials.json`

    master

    The credentials.json file stores authentication tokens. It supports both a single object (legacy) and an array of objects (multi-credential mode). Multi-credential mode enables automatic failover and automatic writing of refreshed tokens back to the file.

    Multi-credential features:

    • Priority: Credentials are sorted by the priority field (lower numbers have higher priority; default is 0).
    • Failover: If a credential fails, the service automatically tries the next available one. The service performs up to 3 retries per credential and up to 9 retries per request.
    • Auth Method: Use authMethod: "idc" for IdC, Builder-ID, or IAM login types.

    Credential-level Overrides: Credentials can override global config.json settings for region, authRegion, apiRegion, and proxyUrl. Setting proxyUrl: "direct" explicitly disables proxies for that specific credential.

    [
       {
          "refreshToken": "第一个凭据的刷新token",
          "expiresAt": "2025-12-31T02:32:45.144Z",
          "authMethod": "social",
          "priority": 0
       },
       {
          "refreshToken": "第二个凭据的刷新token",
          "expiresAt": "2025-12-31T02:32:45.144Z",
          "authMethod": "idc",
          "clientId": "xxxxxxxxx",
          "clientSecret": "xxxxxxxxx",
          "region": "us-east-2",
          "priority": 1,
          "proxyUrl": "socks5://proxy.example.com:1080",
          "proxyUsername": "user",
          "proxyPassword": "pass"
       },
       {
          "refreshToken": "第三个凭据(显式不走代理)",
          "expiresAt": "2025-12-31T02:32:45.144Z",
          "authMethod": "social",
          "priority": 2,
          "proxyUrl": "direct"
       }
    ]
  4. Compile kiro-rs from source

    master

    To compile the project, you must first build the Admin UI frontend to embed it into the binary. Then, use Cargo to build the release version.

    Prerequisites:

    1. Build the Admin UI:
    cd admin-ui && pnpm install && pnpm build
    1. Build the Rust binary:
    cargo build --release

    Alternatively, you can download pre-built binaries from the Releases page.

    cd admin-ui && pnpm install && pnpm build
    # then
    cargo build --release
  5. How Kiro endpoints and providers work together

    master

    Kiro uses an abstraction layer to handle different service endpoints (such as ide or cli) that share common logic like credential pooling, token refreshing, and retry mechanisms but differ in their URLs, headers, and request bodies.

    • KiroEndpoint: An abstraction that defines how a specific endpoint handles its unique requirements, such as its API/MCP URLs, header decoration, and body transformations.
    • KiroProvider: Manages a registry of these endpoints. It selects the correct KiroEndpoint implementation at runtime based on the endpoint field found in the user's credentials or the config.defaultEndpoint setting.

    This architecture allows the system to seamlessly switch between different service implementations while maintaining a unified request lifecycle.

    /// Kiro 端点
    ///
    /// 同一个 `KiroProvider` 可持有多个 endpoint 实现,按凭据级字段切换。
    pub trait KiroEndpoint: Send + Sync {
        // ...
    }
  6. Represent conversation history with Message enum

    master

    The Message enum is used to represent items in the history array of a ConversationState. It is an untagged enum that can be either a User message or an Assistant message.

    • Message::User(HistoryUserMessage): Contains a UserMessage (content, model_id, origin, images, and context).
    • Message::Assistant(HistoryAssistantMessage): Contains an AssistantMessage (content and optional tool_uses).
    let history = vec![
        Message::User(HistoryUserMessage::new("Hello", "claude-3-5-sonnet")),
        Message::Assistant(HistoryAssistantMessage::new("Hi! How can I help you?")),
    ];
  7. How EventStreamDecoder state machine works

    master

    The EventStreamDecoder operates using a four-state model to manage the lifecycle of stream parsing and error recovery:

    1. Ready: The initial state where the decoder is waiting for data via feed().
    2. Parsing: The state entered when decode() is called to attempt parsing a frame.
    3. Recovering: Entered when a parsing error occurs. The decoder attempts to skip corrupted bytes or frames to find the next valid boundary.
    4. Stopped: The terminal state entered when the max_errors threshold (default: 5) is exceeded. Once stopped, the decoder will return ParseError::TooManyErrors on subsequent calls.

    If the decoder is in the Recovering state, calling feed() will transition it back to Ready.

  8. Understand AWS Event Stream HeaderValue types

    master

    The AWS Event Stream protocol supports 10 specific value types. When parsing, these are represented by the HeaderValueType enum and mapped to the HeaderValue enum:

    TypeHeaderValueType IDHeaderValue VariantDescription
    Bool TrueBoolTrue (0)Bool(true)Boolean true
    Bool FalseBoolFalse (1)Bool(false)Boolean false
    ByteByte (2)Byte(i8)1-byte signed integer
    ShortShort (3)Short(i16)2-byte signed integer
    IntegerInteger (4)Integer(i32)4-byte signed integer
    LongLong (5)Long(i64)8-byte signed integer
    ByteArrayByteArray (6)ByteArray(Vec<u8>)Byte array (prefixed with 2-byte length)
    StringString (7)String(String)UTF-8 string (prefixed with 2-byte length)
    TimestampTimestamp (8)Timestamp(i64)8-byte signed integer (timestamp)
    UUIDUuid (9)Uuid([u8; 16])16-byte UUID
  9. How credential region and proxy settings are resolved

    master

    Kiro uses a hierarchical resolution strategy for regions and proxies. Credential-specific settings always take precedence over global config.json settings.

    Region Resolution

    • Auth Region (for token refresh): credential.authRegion > credential.region > config.authRegion > config.region.
    • API Region (for API requests): credential.apiRegion > config.apiRegion > config.region.

    Proxy Resolution

    • Proxy URL: credential.proxyUrl > Global Proxy Configuration.
    • Bypassing Proxy: If credential.proxyUrl is set to the string "direct" (case-insensitive), the credential will explicitly bypass any global proxy settings.