OpenCode2API

repository·main·Indexed 41 days ago

https://github.com/tiarabasori/opencode2api

An OpenAI-compatible API gateway (v1.5.0) that converts a local OpenCode runtime into a standard API. It enables the use of free models such as Kimi, GLM, and MiniMax in standard AI clients, supporting streaming, reasoning control, and tool bridging via the Chat Completions and Responses APIs.

Tokens
13.3K
Snippets
48
Records
60
Agent score
57%

What's inside OpenCode2API

  1. OpenCode2API Documentation Overview

    main

    OpenCode2API is a service that provides documentation and access to OpenCode capabilities. The documentation is organized into several key sections to help users get started, configure the service, and troubleshoot issues.

    Available Documentation Sections:

    • Getting Started: Quick start guide to get the service running.
    • Configuration: Detailed explanation of configuration options.
    • API Reference: Complete documentation of available API interfaces.
    • Docker Deployment: Guide for deploying the service using Docker (recommended).
    • Troubleshooting: Solutions for common issues.
    • Development: Guide for developers working on the project.
  2. Configure and Override Internal Tool Allowlists

    main

    When a request does not include a tools field, the proxy enters internal allowlist mode. In this mode, only tools explicitly declared in the server's allowlist are permitted.

    Server-Side Configuration

    • OPENCODE_INTERNAL_ALLOWED_TOOLS: A comma-separated list of OpenCode built-in tools allowed when no tools are provided in the request.
    • OPENCODE_INTERNAL_WEB_FETCH_ENABLED: A legacy flag. If no explicit allowlist is configured, setting this to true defaults the allowlist to web_fetch.
    • OPENCODE_TOOL_DISCOVERY_FIXTURE: A comma-separated list of fixed tool IDs used for integration testing or local debugging to bypass real tool discovery.

    Request-Level Override

    Clients can attempt to override the server's allowlist by passing an opencode.internal_allowed_tools field in the request body.

    Security Constraint: The request-level list can only shrink (intersect) the server's allowlist, not expand it. effective_allowlist = intersection(server_allowlist, request_allowlist)

    {
      "model": "opencode/kimi-k2.5",
      "messages": [{"role": "user", "content": "Fetch this URL"}],
      "opencode": {
        "internal_allowed_tools": ["web_fetch"]
      }
    }
  3. Implement Two-Step Prompting for Stable Tool Calls

    main

    To ensure high reliability when using agent clients like OpenClaw or Claude Code, it is recommended to use a two-step prompting pattern instead of asking the model to call a tool and answer in a single turn.

    Recommended Workflow:

    1. Step 1 (Tool-only prompt): Send a strict prompt that forces the model to output a tool call without answering the user directly.
      • Example: Call weather_lookup for Tokyo now. Do not answer directly.
    2. Execute Tool: Receive the tool_calls / function_call, execute the tool locally.
    3. Step 2 (Integration prompt): Feed the tool results back to the model with a prompt to synthesize the final answer.
      • Example: Great, now answer the original request using the tool result.

    This pattern stabilizes the bridge between the model and external tools by separating the decision-making (tool call) from the final generation (answer).

  4. How external tools and internal allowlists work

    main

    OpenCode2API manages tools through two distinct modes depending on whether the client provides them in the request.

    1. External Tool Bridging (When tools are provided)

    When a client explicitly passes a tools array in the request:

    • The tools are not registered as OpenCode built-in tools.
    • The proxy virtualizes these tools and passes them to the model.
    • The proxy intercepts model outputs and reformats them into OpenAI-compatible tool_calls or function_call.
    • Conflicts with internal tools are handled via the namespace policy (e.g., a client's web_fetch is isolated from the container's web_fetch).
    • OpenCode built-in tools remain disabled in this mode.

    2. Internal Allowlist Mode (When tools are NOT provided)

    If the request does not contain a tools field, the proxy enters "internal allowlist" mode:

    • Only tools explicitly listed in OPENCODE_INTERNAL_ALLOWED_TOOLS are permitted.
    • The proxy matches requested tools against the backend tool list using exact matches or . <tool> / / <tool> suffixes.
    • If the configured allowlist matches nothing in the backend, the proxy falls back to a safe mode where all built-in tools are disabled.
    • OPENCODE_INTERNAL_WEB_FETCH_ENABLED=true acts as a shortcut: if no explicit allowlist is set, it defaults the allowlist to web_fetch.
  5. Understand External Tool Bridging and Conflict Policies

    main

    OpenCode2API can bridge OpenAI-compatible tools passed by external clients to the proxy layer instead of exposing them as OpenCode internal tools.

    Supported Modes

    • proxy-bridge: The proxy virtualizes external tools and returns OpenAI-compatible tool calling results. This is set via OPENCODE_EXTERNAL_TOOLS_MODE or EXTERNAL_TOOLS_MODE.

    Conflict Resolution

    When an external tool name conflicts with an internal tool, the namespace policy (set via OPENCODE_EXTERNAL_TOOLS_CONFLICT_POLICY or EXTERNAL_TOOLS_CONFLICT_POLICY) is used to isolate them. The proxy uses a namespace like external__web_fetch to prevent collisions. These internal names are not exposed to the client.

  6. Run OpenCode2API in development mode

    main

    To start the development server, which automatically starts the OpenCode backend (if required) and the proxy service, use:

    npm start

    Before starting, you must create your local configuration file by copying the example:

    cp config.json.example config.json
    cp config.json.example config.json
    npm start
  7. Configure OpenCode2API via Environment Variables or config.json

    main

    OpenCode2API supports configuration through three levels of priority: Environment Variables > config.json > Default values.

    Core Configuration

    Use these to set up the proxy and connection to the OpenCode backend:

    • PORT / OPENCODE_PROXY_PORT: Proxy service port (default: 10000).
    • OPENCODE_SERVER_PORT: OpenCode backend service port (default: 10001).
    • API_KEY: Bearer Token authentication key (Required).
    • BIND_HOST: Binding address (default: 0.0.0.0).
    • OPENCODE_SERVER_URL: OpenCode backend address (default: http://127.0.0.1:10001).
    • OPENCODE_SERVER_PASSWORD: OpenCode backend password (Required).

    Functional Configuration

    • DISABLE_TOOLS: Disables OpenCode tool calls (default: true).
    • PROMPT_MODE: Prompt processing mode (standard or plugin-inject).
    • OMIT_SYSTEM_PROMPT: If true, ignores the incoming system prompt.
    • AUTO_CLEANUP_CONVERSATIONS: Enables automatic conversation storage cleanup.
    • REQUEST_TIMEOUT_MS: Request timeout in milliseconds (default: 180000).
    {
        "PORT": 10000,
        "API_KEY": "your-secret-api-key",
        "BIND_HOST": "0.0.0.0",
        "DISABLE_TOOLS": true,
        "OPENCODE_SERVER_URL": "http://127.0.0.1:10001"
    }
  8. Deploy OpenCode2API locally with Node.js

    main

    You can run OpenCode2API locally using Node.js 18+. This method requires installing the opencode-ai CLI globally. Follow these steps to set up the environment and start the service.

    # 1. Clone the project
    git clone https://github.com/TiaraBasori/opencode2api.git
    
    # 2. Enter the directory
    cd opencode2api
    
    # 3. Install dependencies
    npm install
    
    # 4. Copy configuration
    cp config.json.example config.json
    
    # 5. Install the CLI
    npm install -g opencode-ai
    
    # 6. Start the service
    npm start
  9. Deploy OpenCode2API using Docker

    main

    The recommended way to deploy OpenCode2API is via Docker. This requires Docker 20.10+ and the latest version of Docker Compose. Follow these steps to clone the repository, configure your environment, and start the service.

    # 1. Clone the project
    git clone https://github.com/TiaraBasori/opencode2api.git
    
    # 2. Enter the directory
    cd opencode2api
    
    # 3. Copy configuration
    cp .env.example .env
    
    # 4. Start the service
    docker compose up -d
  10. Deploy OpenCode2API via Docker (Recommended)

    main

    The recommended way to deploy OpenCode2API is using Docker, which automatically starts the OpenCode backend.

    1. Clone the repository and prepare the environment:
      git clone https://github.com/TiaraBasori/opencode2api.git
      cd opencode2api
      cp .env.example .env
    2. Configure your .env file. You must set the following variables:
      • API_KEY: Your Bearer Token for authentication.
      • OPENCODE_SERVER_PASSWORD: The password for the OpenCode backend.
    3. Start the services:
      docker compose up -d
    4. Verify the deployment by checking the health endpoint:
      curl http://127.0.0.1:10000/health

    Note: The default docker-compose.yml does not mount the host project directory to the container to avoid overwriting node_modules. For local source code hot-reloading, use a development-specific Compose configuration.

    # 1. 克隆并配置
    git clone https://github.com/TiaraBasori/opencode2api.git
    cd opencode2api
    cp .env.example .env
    
    # 2. 编辑 .env 设置你的配置
    # 必填: API_KEY, OPENCODE_SERVER_PASSWORD
    
    # 3. 启动
    docker compose up -d
    
    # 4. 测试
    curl http://127.0.0.1:10000/health
  11. Deploy OpenCode2API via Node.js (Local Development)

    main

    For local development or custom integrations, you can run OpenCode2API directly using Node.js. This requires the OpenCode CLI to be installed on your system.

    1. Install the OpenCode CLI:
      • Linux/macOS: curl -fsSL https://opencode.ai/install | bash
      • npm: npm install -g opencode-ai
    2. Clone and run the project:
      git clone https://github.com/TiaraBasori/opencode2api.git
      cd opencode2api
      npm install
      cp config.json.example config.json
      npm start
    # 1. 安装 OpenCode CLI
    npm install -g opencode-ai
    # Linux/macOS: curl -fsSL https://opencode.ai/install | bash
    
    # 2. 克隆并运行
    git clone https://github.com/TiaraBasori/opencode2api.git
    cd opencode2api
    npm install
    cp config.json.example config.json
    npm start
  12. Recommended Production and Development Configurations

    main

    Production Environment (Docker/CLI)

    Use these settings for a secure, high-performance production deployment:

    DISABLE_TOOLS=true
    OPENCODE_EXTERNAL_TOOLS_MODE=proxy-bridge
    OPENCODE_EXTERNAL_TOOLS_CONFLICT_POLICY=namespace
    OPENCODE_INTERNAL_ALLOWED_TOOLS=web_fetch
    OPENCODE_INTERNAL_TOOL_METRICS_ENABLED=true
    OPENCODE_TOOL_DISCOVERY_FIXTURE=
    OPENCODE_HEALTH_DETAILS_ENABLED=true
    OPENCODE_HEALTH_DETAILS_REQUIRE_AUTH=true
    OPENCODE_METRICS_ENABLED=false
    OPENCODE_METRICS_REQUIRE_AUTH=true
    OPENCODE_PROXY_PROMPT_MODE=plugin-inject
    OPENCODE_PROXY_OMIT_SYSTEM_PROMPT=true
    OPENCODE_PROXY_AUTO_CLEANUP_CONVERSATIONS=true

    Local Development

    Use these settings to enable debugging and tool access during development:

    DISABLE_TOOLS=false
    OPENCODE_PROXY_DEBUG=true
    # Production Example
    DISABLE_TOOLS=true
    OPENCODE_EXTERNAL_TOOLS_MODE=proxy-bridge
    OPENCODE_EXTERNAL_TOOLS_CONFLICT_POLICY=namespace
    OPENCODE_INTERNAL_ALLOWED_TOOLS=web_fetch
    OPENCODE_INTERNAL_TOOL_METRICS_ENABLED=true
    OPENCODE_TOOL_DISCOVERY_FIXTURE=
    OPENCODE_HEALTH_DETAILS_ENABLED=true
    OPENCODE_HEALTH_DETAILS_REQUIRE_AUTH=true
    OPENCODE_METRICS_ENABLED=false
    OPENCODE_METRICS_REQUIRE_AUTH=true
    OPENCODE_PROXY_PROMPT_MODE=plugin-inject
    OPENCODE_PROXY_OMIT_SYSTEM_PROMPT=true
    OPENCODE_PROXY_AUTO_CLEANUP_CONVERSATIONS=true