Automated proxy discovery, testing, and intelligent routing for OpenCode. Fix connectivity issues and IP-based rate limits with Xray/V2Ray on Linux and Windows.
Documentation Website • Key Features • Architecture • Installation • Usage • Technical Guides • Author
OpenCode Router is an automated, open-source proxy discovery and intelligent routing manager built specifically for OpenCode on Linux.
When utilizing command-line AI coding assistants, developers regularly face regional ISP censorship, CDN firewalls, broken TCP sockets, and IP-level HTTP 429 rate limits. Traditional VPN clients attempt to solve this by creating system-wide TUN/TAP network adapters that redirect all operating system traffic—breaking local web servers, Docker bridge networks, database sockets, and active SSH sessions.
OpenCode Router provides a non-disruptive, application-specific alternative. It automatically discovers public V2Ray/Xray proxy configurations from GitHub, executes deterministic 3-stage health checks directly through the installed OpenCode binary, and locks into the fastest responsive node. All proxying operates in unprivileged user space (SOCKS5/HTTP), isolating proxy traffic strictly to OpenCode via a transparent launcher wrapper (bin/opencode-vpn) without modifying system routing tables or network adapters.
OpenCode Router combines an unprivileged headless Xray-core engine with an Express telemetry backend and a modern React 19 web dashboard built with Vite, Tailwind CSS, and Lucide icons.
UI screenshots will be published after a reproducible, fully synthetic demo dataset is available. Until then, see the user guide for the current workflow.
- Automated Configuration Discovery: Crawls, parses, deduplicates, and caches thousands of public anti-censorship nodes from curated GitHub subscriptions.
- Broad Protocol Support: Full native parsing and outbound generation for VLESS (Reality, TLS, WebSocket, gRPC, TCP), VMess (AEAD, WebSocket, TCP), Trojan (TLS, WebSocket, gRPC), and Shadowsocks.
- Deterministic 3-Stage Testing Pipeline:
- Stage 1 (TCP Handshake): Verifies server socket reachability and measures millisecond round-trip latency.
- Stage 2 (Proxy Handshake): Starts the local user-space proxy and probes egress IP reflection via HTTP.
- Stage 3 (Real OpenCode Prompt): Executes an actual non-interactive test prompt (
opencode run "Reply with: OK" --pure) to confirm LLM API completion.
- Intelligent Error Classifier: Distinguishes IP-based rate limits (which trigger automatic node rotation) from account-level quota exhaustion and authentication failures, preventing useless switching loops.
- Isolated Target Execution (
opencode-vpn): Injectshttp_proxy,https_proxy, andall_proxyenvironment variables exclusively into OpenCode, keeping your OS, browsers, and terminal sessions unaffected. - Zero Root Privilege Requirement: Operates completely on high loopback ports (
127.0.0.1:10808SOCKS5,10809HTTP) as a standard user; never prompts for your sudo password during daily use. - Modern Responsive Web GUI: Live status streaming via Server-Sent Events (SSE), search filters, manual node testing, and one-click connection switching.
- Persistent Local Caching: Stores test history, candidate rankings, and subscription sources in a lightweight local SQLite database.
- IP-Level HTTP 429 Throttling: Automatically switches egress IPs when shared public endpoints throttle your IP address.
- Regional Connection Timeouts (
ETIMEDOUT): Tunnels OpenCode traffic through encrypted nodes when direct access to AI provider endpoints is blocked or degraded. - Deep Packet Inspection (DPI) Resets (
ECONNRESET): Utilizes VLESS Reality and TLS masquerading to bypass stateful connection resets. - System-Wide Network Disruption: Replaces disruptive system-wide TUN VPNs with application-specific proxy isolation, preserving local microservices, Docker containers, and SSH sessions.
[GitHub Subscription Sources]
│
▼ (Automated Fetch & Base64 Decode)
[Config Parser & Deduplicator] ──► SQLite Cache (data/opencode-vpn.db)
│
▼ (Ranked Candidates by Latency Score)
[Connection Orchestrator State Machine]
│
├──► Stage 1: Fast TCP Ping
├──► Stage 2: Local Xray Proxy Egress Probe
└──► Stage 3: Real OpenCode Verification Prompt
│
├── If Fails: Classify Error & Try Next Candidate
└── If Success: Lock Node & Export State
│
▼
[bin/opencode-vpn Launcher]
(Injects SOCKS5:10808 & HTTP:10809)
- Discovery & Normalization: The crawler retrieves raw subscription lists, decodes Base64 payloads, normalizes configuration parameters, computes SHA-256 hashes to eliminate duplicates, and discards unencrypted or invalid links.
- Candidate Ranking: Nodes are sorted by historical latency and success rates.
- Failover Execution: When you click Find Working Connection (or invoke the API), the orchestrator tests candidate nodes sequentially until a working proxy completes a real OpenCode session.
- Proxy Lock: The verified configuration is written to
data/active-connection.json, and Xray-core runs in the background ready to accept OpenCode traffic.
OpenCode Router consists of three decoupled layers:
- Backend Service (Express & TypeScript): Manages the SQLite database, runs the discovery crawler, controls Xray child processes, and streams real-time telemetry over Server-Sent Events (SSE).
- Frontend Dashboard (React 19 & Tailwind CSS): Single-page application providing connection controls, live testing logs, diagnostics, and configuration management.
- Dedicated Launcher (
bin/opencode-vpn): A lightweight Bash wrapper that injects proxy environment variables strictly into OpenCode without altering host environment variables.
OpenCode Router provides genuine cross-platform support with dedicated native launchers and process engines on both Linux and Windows:
| Operating System | Compatibility Status | Verification Notes |
|---|---|---|
| Windows 11 (x64) | Tested & Verified | Native PowerShell & CMD launchers; per-user AppData storage; native xray.exe. |
| Windows 10 (x64) | Tested & Verified | Native PowerShell & CMD launchers; build 19041+ supported. |
| Ubuntu 24.04 LTS (x86_64) | Tested & Verified | Primary Linux development and validation environment. |
| Ubuntu 22.04 LTS / Debian 12 | Compatible | Requires Node.js >= 22.12.0 and standard bash. |
| Windows 11 (ARM64) | Implemented (Unverified) | ARM64 asset provisioned; unverified on physical ARM64 hardware. |
| macOS (Apple Silicon / Intel) | Compatible | Native bash launcher and macOS Xray binaries supported. |
Note
No WSL Required: On Windows, OpenCode Router runs directly as a native Windows application using PowerShell, CMD, Node.js, and native xray.exe. Windows Subsystem for Linux (WSL) is neither required nor used.
- Operating System: Windows 10 (Build 19041+) or Windows 11 (64-bit x64 primary target; ARM64 asset implemented)
- Node.js Runtime: v22.12.0+ (Download Node.js) — strictly required by better-sqlite3 and Vite 8
- Shell: Windows PowerShell 5.1+, PowerShell 7+, Windows Terminal, or CMD
- Target Application: OpenCode CLI installed (
npm install -g opencode-ai)
- Operating System: Ubuntu 24.04 LTS / Debian 12 / Compatible Linux (64-bit)
- Node.js Runtime: v22.12.0+ (
node -v) — strictly required by better-sqlite3 and Vite 8 - Package Manager: npm (
npm -v) - Target Application: OpenCode CLI installed (e.g.
/usr/local/bin/opencode)
Open PowerShell in the cloned repository directory:
# 1. Automated per-user installation (installs dependencies, builds frontend, provisions xray.exe)
powershell -ExecutionPolicy Bypass -File scripts\windows\install.ps1
# 2. Launch the router and web control plane
powershell -File scripts\windows\start.ps1The installer will automatically:
- Download the official, checksum-verified Windows Xray-core (
xray.exe,geoip.dat,geosite.dat). - Compile the modern React dashboard into
src/frontend/dist/. - Configure your User
PATHsoopencode-vpnis immediately available in any terminal window. - Initialize local AppData storage at
%LOCALAPPDATA%\OpenCode-Router.
# 1. Clone the Repository
git clone https://github.com/EhsanCreator/OpenCode-Router.git
cd OpenCode-Router
# 2. Install Node Dependencies
npm install
# 3. Launch the Application
./start.shThe Linux startup script will automatically provision Xray-core, build the frontend if missing, start the backend server, and open the dashboard at http://localhost:3000.
OpenCode Router works out of the box with zero required configuration. To customize local settings, copy the example environment template:
cp .env.example .envAvailable environment variables:
PORT: Web dashboard port (default:3000).OPENCODE_HTTP_PROXY_PORT: Local HTTP proxy port (default:10809).OPENCODE_SOCKS_PROXY_PORT: Local SOCKS5 proxy port (default:10808).OPENCODE_BIN: Custom path to OpenCode binary (auto-detected if omitted).MAX_TEST_ATTEMPTS: Max candidate nodes tested per workflow run (default:25).OPENCODE_TIMEOUT_SECONDS: Verification prompt timeout in seconds (default:18).
- Open
http://localhost:3000in your browser. - Click Find Working Connection.
- Watch the live testing feed cycle through ranked nodes.
- Once verified, the dashboard locks in the connection and displays the egress IP and latency.
Once a working node is active in the dashboard, execute OpenCode commands through opencode-vpn:
# Launch interactive terminal-based OpenCode CLI with active proxy
opencode-vpn
# Run non-interactive query through proxy
opencode-vpn run "Explain this codebase"
opencode-vpn run "What is 2 + 2?" --pure
# Version check
opencode-vpn --version# Launch interactive OpenCode terminal through the active proxy
bin/opencode-vpn
# Run non-interactive prompt through the proxy
bin/opencode-vpn run "Explain TypeScript generics"
# Pure machine-readable response
bin/opencode-vpn run "What is 2 + 2? Answer in one word." --pureTo invoke opencode-vpn from any directory:
mkdir -p ~/.local/bin
ln -sf "$(pwd)/bin/opencode-vpn" ~/.local/bin/opencode-vpnTo add OpenCode Router to your Ubuntu Applications menu and Desktop:
./scripts/create-desktop-launcher.shOpenCode Router implements a multi-inbound local loopback proxy listener:
- SOCKS5 Listener:
127.0.0.1:10808(Mapped toall_proxyandALL_PROXY) - HTTP Listener:
127.0.0.1:10809(Mapped tohttp_proxy,https_proxy,HTTP_PROXY,HTTPS_PROXY)
Traffic flow:
bin/opencode-vpnexports loopback proxy variables into the OpenCode process environment.- OpenCode sends API requests to
127.0.0.1:10809or127.0.0.1:10808. - Xray-core encapsulates the request into the active encrypted protocol tunnel (VLESS/VMess/Trojan/SS).
- The remote proxy server forwards the request to the AI provider API and returns the completion.
- All other host applications continue using direct, unproxied internet.
- Default Loopback Binding: The management server binds strictly to
127.0.0.1by default. Remote exposure requires explicit opt-in (ALLOW_REMOTE_ACCESS=true) and triggers high-visibility console warnings. - Mandatory Remote Authentication: Remote binding strictly requires setting
OPENCODE_ROUTER_API_KEY. The server will refuse startup if remote binding is attempted without an API key. Remote requests requireAuthorization: Bearer <key>using constant-time verification (crypto.timingSafeEqual). API keys in query parameters are strictly rejected. - Frictionless Local Execution: Standard local loopback usage (
127.0.0.1) requires zero authentication by default, keeping CLI and local dashboard workflows completely frictionless. - Strict Origin & Host Guard: Replaces unrestricted CORS with an explicit local development allowlist. Blocks DNS rebinding via Host header checks and blocks cross-origin CSRF on state-changing endpoints (
POST,DELETE) withHTTP 403 Forbidden. - Sensitive Token & Credential Redaction: Subscription URLs returned by
/api/sourcesand error reports automatically redact private parameters case-insensitively (token,key,password,auth,api_key,access_token) and sanitize userinfo credentials (***:***@host). Diagnostics endpoints mask personal IPv4 and IPv6 octets. - Restricted File Permissions & Symlink Protection: Generated Xray client configs (
data/active-xray-config.json), active state files, and logs are written with mode0600(user-only read/write), data directories are enforced to0700, and writing through symbolic links is blocked (lstatandO_NOFOLLOW). - User-Space Isolation: No modification of
/etc/resolv.conf,iptables,nftables, or kernel routing tables. - Zero Root Privileges: Runs entirely as a standard unprivileged user on high loopback ports (
127.0.0.1:10808/10809). - Zero External Telemetry: No tracking scripts, analytics, or external telemetry are collected or transmitted.
| Symptom | Probable Cause | Recommended Solution |
|---|---|---|
curl: (7) Failed to connect to 127.0.0.1:10809 |
Proxy engine is stopped or idle. | Open dashboard at http://localhost:3000 and click Find Working Connection. |
Execution of scripts is disabled on this system (PowerShell) |
PowerShell ExecutionPolicy defaults to Restricted. |
Run script with bypass: powershell -ExecutionPolicy Bypass -File scripts\windows\install.ps1. |
'opencode-vpn' is not recognized (Windows) |
Terminal session opened before PATH was modified. | Reopen your PowerShell/Terminal window or check %LOCALAPPDATA%\OpenCode-Router\bin in PATH. |
Error: connect ETIMEDOUT |
Candidate node remote endpoint unreachable. | The orchestrator will automatically fail over; or click Refresh Nodes. |
HTTP 429: insufficient_quota |
Account-level token budget exhausted. | Top up your provider API credits. IP switching cannot fix account balance limits. |
Authentication failure (401) |
Invalid API key in OpenCode configuration. | Verify your API key in ~/.config/opencode/opencode.json (or %APPDATA%\opencode\opencode.json). |
| Port 3000 already in use | Another service is using port 3000. | Linux: PORT=3001 ./start.sh Windows: $env:PORT="3001"; .\scripts\windows\start.ps1. |
For in-depth troubleshooting guides, refer to our Technical Articles.
- Account-Level Quotas: OpenCode Router switches IP addresses to bypass IP-based throttles and regional network blocks. It cannot bypass account-level credit limits, monthly token caps, or invalid API keys.
- Public Node Lifespans: Free public proxy configurations from GitHub may experience variable uptime, congestion, or unexpected termination. OpenCode Router mitigates this via continuous testing and fast failover.
- Scope: Designed specifically for OpenCode and related CLI developer workflows; does not provide system-wide VPN functionality.
OpenCode Router includes automated test suites covering protocol parsing, Xray client generation, process cleanup, cross-platform path resolution, rate-limit classification, and pipeline speed benchmarks:
# Run core acceptance and security tests (Linux & POSIX)
npm test
# Run cross-platform platform abstraction & Windows compatibility tests
npm run test:windows
# Run high-speed 3-stage pipeline & canary benchmark tests
npx tsx tests/pipeline-speed-tests.ts
# Provision official Xray-core binary with SHA256 checksum verification
npm run provision:xray
# Package standalone portable distribution for Windows
npm run package:portableAll 8 acceptance test scenarios (A through G) execute deterministically without requiring root privileges.
To run OpenCode Router in active development mode with hot reloading:
# Terminal 1: Backend service with file watching
npm run dev:backend
# Terminal 2: Frontend Vite dev server
npm run dev:frontend- Automated periodic background health checks for active connection.
- Support for custom private subscription endpoints with password encryption.
- Tray indicator applet for GNOME / Ubuntu Desktop.
- Export verified configurations to Clash / Sing-box format.
Explore our dedicated technical troubleshooting guides:
- How to Fix OpenCode Network Errors on Linux
- How to Fix OpenCode HTTP 429 Rate Limit Errors
- How to Configure a Proxy for OpenCode CLI
- How to Use Xray with OpenCode on Ubuntu
- OpenCode Proxy vs. System-Wide VPN: Understanding the Differences
Contributions are welcome! Please read CONTRIBUTING.md for contribution guidelines, coding standards, and pull-request procedures.
Ehsan Shahriyari
- GitHub: @EhsanCreator
- Repository: https://github.com/EhsanCreator/OpenCode-Router
- Issues & Bug Reports: https://github.com/EhsanCreator/OpenCode-Router/issues
This project is open-source software licensed under the MIT License.