Commit Graph
13 Commits
Author SHA1 Message Date
Jason Xu 4438acb8e7 feat(egress): route free-model traffic through userspace WARP
Free-tier requests now optionally leave through a Cloudflare WARP tunnel that runs inside the gateway process: WireGuard over UDP plus a gVisor netstack, so no TUN device, root, NET_ADMIN, or route changes are needed. Adapted from github.com/sudogeeker/ai-route (MIT).

- warp.enabled/pool_size/stack in config, the WebUI, config.example.json and all READMEs; startup and hot reload fail closed when WARP cannot initialize.
- Anonymous lane, free-model Zen-key fallback, free-model probes and the anonymous catalog refresh send no proxy traffic while enabled; Go keys and paid models keep their proxies.
- Per-attempt leases feed 403/429 rotation and broken-tunnel failures back into the pool; /healthz and /api/monitor expose the pool state and readiness requires an active exit.
- errWARPUnavailable maps to a 503 warp_unavailable response.
2026-10-25 05:51:00 +08:00
Jason Xu 0bb23c7a7f fix(upstream): stop retrying request-level rejections and cap anonymous exits
The anonymous walk now ends on a deterministic 4xx instead of replaying the same context-length rejection through every exit and tier. Static exits are capped by performance.max_anonymous_exits, and an IP-level abuse block marks only its exit; the lane breaker opens only when every exit is blocked, so a single 403 no longer pauses the lane. The Zen key tier is skipped after an IP block while the authenticated Go tier remains available. Add performance.free_tier_block_seconds, make the breaker half-open probe single-flight, and coordinate refreshes and availability probes with the breaker. Update the shipped example to start on the anonymous lane.
2026-10-21 02:52:52 +08:00
Jason Xu f0f064f31d fix: align the v2 free-tier shape with OpenCode 2.0.32
- Use the genuine patchText description and keep the Linux/bash shell sentence.
- Preserve the client's child session id separately from the affinity.
- Scope the anonymous parent session id like every other derived identity.
- Append beta=true only on v2 Anthropic lanes and parse the query safely.
- Remove the redundant v1 project renderer and duplicate anthropic-version.
- Revert the formatting-only churn in opencode_tools.json and update lane docs.
2026-10-20 18:13:56 +08:00
Jason Xu a70e77fe62 Fix audited gateway issues 2026-10-19 05:27:50 +08:00
Jason Xu 81ad2842c7 refactor: drop new prefixes, unify v1/v2 lane naming, audit comments
- Remove the new/New prefix from constructors; rename the colliding
  types semantically (ModelCatalog, RuntimeController, Metrics,
  LogBroker, Redactor, proxyTransports, upstreamNodes, ...).
- Unify upstream lane naming on v1 (/zen, OpenCode 1.x shape) and v2
  (/inference and /zen/go, 2.x CLI shape); add models.IsV1Upstream and
  drop the duplicated lane detection.
- Fix inaccurate, truncated and stale comments across all packages and
  document exported symbols plus non-obvious internals.
- Fix anthropicThinking passing "enabled"/"adaptive" through as an
  effort; derive the level from the budget instead.
- Delete dead code (identity.StableID, unused protocol decoders and
  stream parser wrappers).
- Export EffectiveListeners, rename modelsDev* metadata constants, and
  describe the metadata source as the OpenCode endpoint.
- Rename the forced-collapse log event to stream_collapse_failed and
  add an anonymous field.
- Correct the README upstream.zen default and add upstream.anonymous.
2026-10-19 03:46:09 +08:00
Jason Xu ee0fb53e5d fix(proxy): force fresh tunnels for #pool and stop failing over cooling exits
Three defects kept the anonymous lane returning 502 "all upstream attempts
failed" and kept rotating endpoints pinned to one exit IP:

- Cloning http.DefaultTransport after its first dial inherits the configured
  HTTP/2 ALPN and TLSNextProto map, which ignore DisableKeepAlives and
  Request.Close and multiplex every request over a single CONNECT tunnel. A
  pool transport now installs an explicit empty TLSNextProto map and pins
  ALPN to http/1.1, so each attempt opens a new tunnel and draws a new exit.

- anonymousCursor.Next returned nil as soon as every static proxy was cooling
  or unhealthy, which turned a transient 429 into an immediate "no healthy
  anonymous proxies available" and a 502 for the client. It now tracks the
  nodes this cursor already tried and falls back to the earliest-expiring
  remaining node, mirroring the key pool's earliest-expiry behavior.

- An upstream HTTP response proves the proxy route is reachable, so a 4xx/5xx
  (or a 2xx) now clears an unhealthy flag left by an earlier transient
  timeout instead of leaving the route evicted for up to 15 minutes.

The tier-outer loop also keeps the last upstream response when a later key
tier dies on transport: the previous code dropped it, so a real 429 from the
anonymous lane was replaced by a generic 502.
2026-10-17 04:04:07 +08:00
Jason Xu 260211cd9e feat(proxy): support rotating proxy pools via #pool marker
An endpoint that already rotates exit IPs (Resin and similar gateways) was
handled like a static proxy, which defeated the rotation in three ways:

- the cloned transport kept HTTP/2 and keep-alive enabled, so every request
  reused one CONNECT tunnel and therefore one exit IP, drawing 429s;
- a single slow exit marked the whole entry unhealthy and keys were rebound,
  with scheduled recovery only every 15 minutes;
- any 429/5xx put the anonymous node into a 15s-120s cooldown, and that lane
  has no earliest-expiry fallback, so the request failed with
  "no healthy anonymous proxies available" (HTTP 502).

Mark an entry with a "#pool" fragment (or a "pool+" scheme prefix) to declare
it a rotating pool. Pool entries then open a fresh connection per attempt
(DisableKeepAlives, no HTTP/2, plus Connection: close on the request), are
excluded from cooldown, health eviction, and proxy rebinding, and may be
retried up to retry.max_attempts on the anonymous lane instead of once.

Config validation and redaction work on the clean URL, the marker stays
visible in the operator UI, and deduplication keeps a pool entry next to a
static proxy that dials the same endpoint since they are different routes.
2026-10-17 03:30:25 +08:00
Jason Xu 076451fa31 feat: prefer legacy /zen/v1 anonymous lane with fallback to /inference 2026-10-17 01:02:59 +08:00
Jason XuandCheerC d27a3ec8bf fix: stop the anonymous lane from locking up after quota and network change (#59)
A quota response with a multi-hour Retry-After cooled anonymous exits for
hours, so after a network change gave them a fresh allowance traffic kept
falling through to key lanes until restart. Cap Retry-After on the
anonymous lane at the 8x backoff ceiling, and clear anonymous cooldowns
when their proxy recovers. Key lanes keep honoring Retry-After in full.

Co-authored-by: CheerC <cheerc@gmail.com>
2026-10-15 07:52:23 +08:00
Empty 0204ca1fdf fix: harden the free-tier gate shape and probe lanes (#81 fallout) (#84)
OpenCode's 2026-10-14 gate rejects the gateway on every lane again
(403 FreeTierError) while the official CLI keeps working. Probing
byte-identical CLI v2.0.29 replays against the live endpoint isolated
the deltas this changeset fixes on top of #83:

- identity: derive the session from the new x-opencode-session-id
  signal too, and stop forwarding the legacy x-opencode-request header
  and canonical prj_* project ids upstream — both are instant 403s.
- upstream: the x-opencode-project header keeps one conversation pinned
  to one upstream project but is now hashed into the bare 40-hex shape
  the client sends (a prj_* value 403s).
- refresh: when the configured anonymous upstream has no models route
  (404), fall back to the legacy Zen console listing so the anonymous
  catalog still populates.

The endpoint move, genuine tool definitions, and UA shape came in with
#83; the definitions embedded there were re-verified byte-for-byte
against a fresh CLI v2.0.29 capture, including the smallest passing
toolset (shell + read) and per-tool definition checks.

Validation: live end-to-end against opencode.ai — anonymous lane serves
streaming and plain JSON chat completions on big-pickle and
step-5-preview-free, tool calls pass through, all nine exposed free
models probe available, go vet/build/gofmt clean.
2026-10-15 01:43:14 +08:00
Jason Xu be91f8697a fix: restore free-tier requests and route anonymous probes correctly 2026-10-15 00:06:24 +08:00
haverainlilili 3440273f43 feat: 新增模型轮转、额度看板和密钥管理 2026-09-21 10:18:21 +08:00
Jason Xu 46def7fedc refactor: organize Go packages and remove test files
Move the command to cmd/opencode2api and group production code into
configuration, gateway, protocol, model, admin, telemetry and helper packages.
Keep shared state private behind context, metrics and runtime interfaces.

Remove the requested test files and replace test-only CI jobs with vet/build
checks. Update Docker and release build paths, preserve version injection and
make the WebUI an explicit embedded asset package.

Add directory trees and source reading guides to both READMEs. Anchor binary
ignore rules so the command package is tracked.
2026-09-15 01:28:44 +08:00