Resolve client environment declarations before protocol conversion and keep a separate snapshot per request. Remove host directory, platform, workspace and Git assumptions, preserving explicit deployment defaults and official client prompts.
Validation: Windows build, go vet, 167 integration checks, and live DeepSeek requests with unknown environment fields.
Preserve Go and Zen OAuth routing while fixing authentication, secret redaction, streaming, transport, and configuration issues.
Refresh README and management guides in four languages while preserving sponsors, LinuxDo acknowledgements, and Linux/Docker quick start instructions.
Add WebUI device authorization, organization selection, persisted token refresh, and fail-closed official Go subscription routing. Preserve manual keys without PAYG fallback and keep OAuth quota unknown.
Validation: offline regression checks, go vet, JavaScript syntax, and Windows/Linux amd64 compilation passed. Live subscription authorization and inference are not yet verified.
Refs #168
- Allow operators to associate Zen and Go credentials with configured proxy
routes via optional proxy_bindings in config.
- Keys are mapped to their 16-hex fingerprint during normalization so
secrets are never stored twice or exposed in diagnostics.
- Bound credentials fail closed: when their assigned proxy becomes unavailable,
they do not silently migrate to other proxies or fall back to direct egress.
- When an assigned proxy recovers, traffic resumes immediately without
changing bindings.
- Removed or invalid proxy references fail config validation, leaving the
previous running runtime untouched on failed reloads.
- Unbound configurations, anonymous routing, and session affinity continue
to behave exactly as before.
- Note in config documentation that binding to a #pool proxy endpoint pins the
transport route and does not guarantee a static public egress IP.
- Add unit and acceptance tests covering binding resolution, fail-closed isolation,
persistence, and secret masking.
Co-authored-by: NekomyaDev <neko@nekomya.dev>
Two client-facing errors were uninformative, and a harness cannot recover
from either.
1. An unknown model was reported as 400 "the model uses an upstream protocol
that opencode2api does not expose". That phrasing is accurate for a model
the catalog KNOWS but cannot serve (a capability or routing problem), and
wrong for a model the upstream has never offered. A model the upstream
retired (it answers 410 Gone) produced this 400, so a harness kept
retrying a model that no longer exists. The catalog can now tell the two
cases apart (ModelCatalog.Known), and an unknown model returns 404 with
code model_not_found.
2. A request whose every attempt failed while WRITING the body was reported
as 504 "upstream request timed out". The upstream never finished reading
the body, so the payload is too large, and a client that can shrink the
request knows to shrink it. Harnesses that recover from an oversized
payload generally key on HTTP 413 (and image rejection on 400), so a 504
sent the same oversized payload around forever. A write-phase failure
while the request budget is still alive now returns 413 with code
payload_too_large; every other phase (headers, first_event) stays a 504,
because a slow upstream or a thinking model is not the client's fault.
Both paths are applied to the chat, responses and messages endpoints as well as
to /v1/systemone.
Tests: the 404 vs 400 split, and the 413 vs 504 split. Both mutation-proved:
reverting either change fails the matching test.
The anonymous free tier now calls the configured v2 /inference origin only; the retired v1 /zen fallback is commented out rather than deleted, so the lane order can be restored in one edit. Catalog refresh and probes follow anonymousUpstreams, so they stop trying /zen too.
A request whose client names no project now gets a fresh 40-hex project id. The free tier ledges quota per project id and egress, and the old per-caller default was one shared bucket that popular exits had already burned.
Response tool names now resolve in the order exact wire name, clint_ prefix, case fold, separator fold. A fold two declared tools share is never guessed between. The stream and JSON rewriters share the resolver, and their fast path now recognizes unprefixed tool-call frames.
Shaped free-model requests now look like an official CLI session on every
lane. Each client tool is renamed to a sanitized, collision-free clint_ name
and the full official tool set for the lane is appended (11 tools on the 1.x
/zen lane, 13 on 2.x /inference and /zen/go). Requests without tools, with an
empty array, or with a legacy functions array receive the official set too,
and tool_choice, function_call and the tool-call history are rewritten to
match.
Responses, streaming and not, are restored to the names the client declared,
including a Chat in a stream split across chunks. Unmapped names pass through,
so an official tool the client never declared is never hidden or replayed.
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.
The v2 gate fingerprints the body as well as the headers, and five details
still differed from a captured 2.1.1 request:
- The client sends max_completion_tokens: 32000 on every chat body. The
gateway now adds it when the caller asked for no ceiling; an explicit
max_tokens or max_completion_tokens still wins.
- Every client tool carries "strict": false, so a tool that omits the field
is byte-different from the client's on every request that carries tools.
- The shell tool description names the shell the client actually has, so a
Windows host advertises a different one than the captured Unix wording.
- Chat bodies keep the client's key order, model first. Go writes map keys
alphabetically, which puts max_completion_tokens at the front where a real
client starts with model.
- Bodies are encoded without HTML escaping. encoding/json writes \u003c,
\u003e and \u0026 by default where JSON.stringify writes the characters,
and tool descriptions are full of both.
The ordered encoder falls back to plain encoding/json for every lane except
the v2 chat one, and both re-encode points in the request path use it.
Co-authored-by: AiFLYF <AiFLYF@users.noreply.github.com>
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.
A flagged free-tier exit keeps answering 403 (IP-level abuse detection)
and retrying only extends the penalty. Add an optional lane-level circuit
breaker, configured with models.anonymous_backoff:
- threshold consecutive failed anonymous attempts, or one 403/429, pause
the whole lane for base_hours, doubling on every further trip up to
max_hours;
- while paused, no proxy is drawn and no upstream request is made, so
routing falls straight through to the authenticated tiers;
- a successful attempt closes the breaker and restores the free lane;
- absent config leaves behavior unchanged;
- availability probes honour the breaker instead of refreshing the block.
The free tier answers an egress IP it flagged with 403 "abusive traffic".
The gateway read that as an ordinary rejection: it tried the second
anonymous lane on the same IP, then the keyed tiers from the same IP, and
remembered nothing, so every later request and every probe repeated the
walk. A single client request produced four upstream 403s on an instance
with one exit.
- classify the three known IP-block wordings (abuse.go) without consuming
the body, so the upstream response stays intact for the caller;
- cool only that exit (proxyTransport.blockedUntil) and leave the lane:
another lane on the same IP cannot help, and neither can a keyed tier;
- keep blocked exits out of anonymousCursor.Next, including its cooldown
fallback, and bring them back after a 15 minute TTL;
- skip the keyed tiers once the anonymous phase reports the block;
- answer clients with 503 free_tier_ip_blocked instead of forwarding the
upstream "turn off your VPN" text;
- record probes as network_abuse_blocked instead of http_403;
- count anonymous attempts, which stayed at zero and broke the telemetry
attempt numbers and the request budget.
Co-Authored-By: Claude Code <noreply@anthropic.com>
- 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.
- 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.
Two callers whose conversations began identically were mapped onto the
same upstream session. Without a client session signal the session was
hashed from the first user turn alone, ignoring the server key and the
system prompt, so two users opening with "你好", or two Codex users in the
same working directory (whose first user turn is the boilerplate
<environment_context> block), shared one x-opencode-session, one sticky
upstream provider, one preferred key and one anonymous proxy exit. Every
caller without a client project also shared one constant project id.
- Mix the authenticated caller (server key fingerprint; Playground gets
its own bucket) into every session and default project the gateway
derives. Official OpenCode ses_ sessions sent by the client are kept
verbatim because the client minted them uniquely.
- Read the session signals mainstream agents already send before falling
back to a content seed: Codex's session_id / conversation_id headers
and the session UUID inside Claude Code's metadata.user_id (underscore
or JSON form). The per-user remainder of user_id is never used as a
session.
- Seed from the system prompt (Anthropic system, Responses instructions,
leading system/developer messages) plus the first user turn instead of
the first user turn alone.
- Correct stale comments: x-opencode-request and the project header do
reach upstream, rendered per lane.
Upgrading re-derives every gateway-made session once, so in-flight
conversations may move to another key or proxy and start with a cold
upstream cache. Conversations under one key that share both the system
prompt and the opening turn can still share affinity; the READMEs now
recommend separate server keys for users who must stay isolated.
The legacy /zen/v1 free-tier gate needs only a single tool named "read":
probing showed [read] alone passes while bash/shell/edit/glob/grep alone
(or any combination without read) return 403 FreeTierError, and neither
the description nor the parameter schema is validated. The v1.3.7-style
pre-injection of the other core tools was therefore unnecessary traffic
and repeated client schemas on the wire.
Legacy lane:
- Drop the bash/edit/glob/grep pre-injection entirely.
- If the client already declares an exact "read" tool, the body is left
untouched.
- Otherwise, a read-related client tool (case-insensitive match such as
"reAd", "read_file", "ReadFile", "file_read", "view_file") is renamed
in place to "read" with its client description and schema preserved,
and the matching tool_choice plus any historical tool call in the
request are rewritten so the outbound body stays self-consistent.
- If no read-related tool exists, a single "read" stub is injected whose
description marks it deprecated, disabled, and not to be called.
Round trip:
- Add protocol.RenameResponseTool for chat tool_calls, Responses
function_call items, and Anthropic tool_use blocks.
- Add protocol.RenameStreamReader, a pull-based SSE rewriter (no goroutine
or io.Pipe, so a disconnected client cannot strand a writer) that
restores the client's original name in streaming replies. Chat deltas
may split or repeat a name fragment, so "read" prefixes are held until
the name resolves, and a continuation past "read" is passed through
verbatim.
- Carry the alias through the new telemetry.RequestMeta.ToolAlias field
and shapeKeyBody's new return value; the /inference lane and non-legacy
upstreams are untouched.
When every attempt died on the proxy route itself, the gateway answered
with a generic 502 "all upstream attempts failed", pointing operators at
the upstream instead of their proxies.
Attempt errors that fail before a connection to the upstream exists
(proxy dial, CONNECT/SOCKS handshake, tunnelled TLS) are now tagged as
proxy failures on real proxies; direct transports are left untouched.
The anonymous lane also reports a proxy failure when no proxy is healthy.
When the final error is such a failure, the inference and System One
handlers return 503 with type "proxy_error". Any upstream HTTP response
is still forwarded as before, so genuine upstream errors are not
mislabelled.
Usage was only broken down by model and tier, so a gateway shared by
several callers could not tell how much each server key consumed.
authenticate now records the fingerprint of the key that matched, and the
monitor keeps requests and tokens per key in usage.server_keys for both
the lifetime and the last hour; the entries sum to the aggregate totals.
/api/api-keys attaches each key's usage and the WebUI shows it in the key
list. Playground traffic borrows the first enabled key, so it is counted
under "playground" instead. Like the rest of the monitor, the figures
survive hot reloads and reset on restart.
Closes#58.
With Zen or Go keys configured, every paid model was exposed and routable.
models.free_only rejects models that are not free in both routing entry
points, so /v1/models, inference, rotation aliases and diagnostics agree.
Free models keep their key fallback. The WebUI gains a toggle so saving
the form no longer resets the field, and the docs note that free models
never require a Zen key.
Closes#66.
Carry the canonical ses_ ID into RequestMeta, the request_routed line, the
recent-request ring, and per-session usage maps in the lifetime and hourly
snapshots, including rotation requests. The lifetime map keeps the 500
most recently seen sessions.
Co-authored-by: sk-dev-ai <githubkrishsk@gmail.com>
attempt_timeout_seconds only reached the transport's
ResponseHeaderTimeout, which starts after the request body is written, so
an exit wedged in dial or request write could consume the whole request
budget. When the option is set, each attempt now also carries a context
deadline covering dial, write, headers and, when enabled, the first SSE
event; a committed stream is never cut. Legs record the phase an attempt
died in. A timeout after the upstream already answered is slow generation,
not a broken proxy, so it does not evict the exit.
Co-authored-by: mcheiyue <2267610721@qq.com>
A downstream disconnect during the upstream attempt loop is not an
upstream failure, but it was answered with 502 upstream_error on both the
message endpoints and System One. Check wire.ClientCanceled before the
generic 502 and answer 499 client_canceled instead; an exhausted request
budget keeps its 504. Cancels log at debug before the request_failed
warning, so disconnects no longer read as upstream outages.
Co-authored-by: sk-dev-ai <githubkrishsk@gmail.com>
transcodeStream, transcodeStreamWithUsage, forwardSSEWithUsage and
forceStreamBody have no callers since the package refactor; the live
paths use the request-aware TranscodeStream/ForwardStream and
prepareAnonymousBody directly. Also fix the stale comment reference.
Log a 240-char snippet of non-2xx upstream bodies (upstream_error_body)
so the 400 class is visible without dumping full payloads; the hub
redactor scrubs configured secrets. Also log skipped fallback tiers
(fallback_tier_skipped) at debug when a non-preferred tier's request
shape fails to prepare, instead of silently dropping the tier.
The dedicated /v1/systemone route is the correct surface, but many
deployments only reach the gateway through an OpenAI-shaped proxy that
pins every request to /v1/responses (sub2api forwards OpenAI-platform
accounts to Responses only). Such a proxy can never address
/v1/systemone, so a System One model stays unreachable even though the
gateway supports it.
Route System One models through the same verbatim relay when they are
requested on /v1/chat/completions or /v1/responses. The payload still
carries state and typed questions; nothing is converted, and models on
another protocol keep their normal bridge path.
Verified through a sub2api group pointed at this gateway:
POST /v1/responses {"model":"jev-1.13-free","state":"...",
"questions":{"is_urgent":{"type":"noul",...}}}
-> 200 {"answers":{"is_urgent":{"noul":0.94}},"cost":"0"}
Sending the decision fields alongside OpenAI message fields does not
work: the proxy rewrites the body and the decision fields are lost, so
the relayed request is rejected upstream.
OpenCode Zen publishes System One models (jev-1.13, jev-1.13-free) on a
/v1/systemone endpoint. A request pairs a free-form state with typed
questions and the reply carries typed answers, so the payload shares no
shape with the chat/responses bridge and cannot be translated.
- protocol: add SystemOne with its endpoint path.
- discovery: read "systemone" rows from the upstream endpoint tables so
those models stop being bucketed as unsupported.
- gateway: add POST /v1/systemone, which relays the body verbatim
through the existing tier and anonymous machinery and returns the
answer document unchanged. Models on another protocol are rejected
with a clear error instead of being forwarded to a message API.
- anonymous lane: keep System One bodies verbatim. Forcing streaming or
injecting the core agent tools, which the free tier requires for chat
traffic, would invalidate a decision request.
Verified end-to-end against the live upstream: jev-1.13-free answers
through the gateway with cost 0, chat and responses models keep working,
and the endpoint rejects mismatched payloads.
Upstream now rejects non-agent-shaped free-tier requests on every lane
with 403 FreeTierError (#29); #31 covered the anonymous lane only, so
keyed-only configs still 403 on bare probes. Mirror the normalization
(stream + core agent tools) for catalog-free models on key tiers; paid
bodies untouched. Non-streaming clients get the same stream collapse
as the anonymous lane. Free check uses catalog pricing metadata, not
the -free name, so nameless free models are covered.
Upstream now rejects anonymous free-tier requests unless they look
like real agent traffic: stream:true plus the core agent tools
(bash/edit/glob/grep/read), returning 403 FreeTierError otherwise.
Normalize the anonymous-lane wire body (force stream:true, inject
minimal definitions for any missing core tools) and collapse the
SSE stream back into the single JSON document non-streaming
clients asked for. Authenticated tiers are untouched.
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.