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>
Copy decoded JSON maps and slices directly instead of marshalling and
re-parsing on every call. Both callers pass encoding/json trees, so the
result is unchanged; the doc comment now states that contract.
Co-authored-by: sk-dev-ai <githubkrishsk@gmail.com>
Remove package.json, package-lock.json, .prettierrc.json and
.prettierignore. CI no longer installs npm dependencies or runs the
Prettier check; the WebUI syntax check now calls `node --check
webui/app.js` directly. Docs and .gitignore are updated to match.
`npm run format:check` rejects the embedded tool definitions because the file
was generated with single-space indentation, which fails the "Formatting and
WebUI syntax" job on main.
Reformatted with the repo's Prettier config; no content change. Verified locally
with the exact commands the workflow runs: `gofmt -l .`, `npm run
format:check`, `npm run check:web`, `sh -n docker-entrypoint.sh`, `go vet ./...`
and `go build -trimpath ./cmd/opencode2api`.
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.
Upstream now fingerprints the client on every tier. The gateway's request shape
no longer passes, so both the keyless free tier and the keyed lanes come back as
403 {"type":"error","error":{"type":"FreeTierError","message":"OpenCode's
free tier can only be used from within OpenCode..."}}
Reproduced by replaying the gateway's exact request against the live endpoint,
and cross-checked by capturing what the official client (@opencode/cli@2.0.29)
puts on the wire.
Three things are checked, and each one alone is enough to fail the request:
1. Endpoint. Keyless traffic moved off /zen onto https://opencode.ai/inference.
Keyed traffic still uses /zen (or /inference/openai), so the anonymous lane
gets its own `upstream.anonymous` base instead of sharing `upstream.zen`.
2. Header shape. Upstream wants the client's own headers: a
"opencode/<channel>/<version>/cli" User-Agent, x-opencode-session-id, a bare
40-character hex x-opencode-project, and no x-opencode-request. The previous
legacy set — "opencode/1.18.31 (<os> <arch>; <runtime>)" User-Agent, a
"prj_" prefixed project, and the gateway's x-opencode-request — is rejected
on both the keyless and the keyed lanes.
3. Tool definitions. Every tool whose name upstream recognises must carry the
genuine OpenCode definition; a synthesised stub that only reuses the name is
rejected. The gateway now embeds the real definitions captured from the
official client and uses them for the tools it injects, and rewrites any
downstream tool that happens to reuse a recognised name. Unrecognised tool
names still pass through untouched, so downstream function calling keeps
working. `anonymousCoreTools` also drops "bash" in favour of "shell", since
"bash" is a recognised name whose genuine definition the gateway does not
have.
Verified against the live endpoint on both lanes: non-streaming, streaming,
function calling with a downstream tool, /v1/messages and /v1/responses all
return 200. Unit tests cover the request headers, the genuine tool definitions
and the tool rewrite.
The old form marshaled and re-parsed on every call, which is both
slower and lossy: every number decoded as float64 regardless of what
the caller held. The typed clone preserves map, slice, scalar, and
json.Number values, returns nil for nil, and deep-copies nested maps
and slices so callers cannot alias the input.
A downstream disconnect during the upstream attempt loop is not an
upstream failure, but the gateway answered it with 502 upstream_error on
both the message endpoints and System One. Clients that retry on 502
then retried a request nobody cancelled, and telemetry counted a client
behavior as a server failure.
Check wire.ClientCanceled before the generic 502: set meta.Outcome so
the request line reads client_canceled, and answer 499 with a
client_canceled envelope. DeadlineExceeded keeps its 504.
OpenCode's free tier started rejecting gateway requests with 403
FreeTierError ('free tier can only be used from within OpenCode') around
2026-10-11, on every lane (anonymous and Zen keys), while the official
client kept working.
Root cause, isolated against the live endpoint with 30+ controlled probes:
on top of the known agent-shape requirements (stream + core tools present,
canonical ses_ layout), the free tier now validates HOW the session ID's
12-hex time part is encoded. The official client mints session IDs with
Identifier.descending(): the 48-bit value ~(ts_ms << 12 | counter) in hex,
counter 1-48. Probing shows requests whose time part decodes to that layout
pass (timestamps themselves are barely checked; counter 100 or 4095 fails),
and any foreign encoding - the raw sha256 time part this gateway emitted,
or an ascending Identifier - fails with 403.
Fix CanonicalSessionID:
- Keep IDs whose time part already decodes to the client's descending
layout (genuine opencode sessions keep their upstream prompt-cache
affinity).
- Re-encode everything else deterministically: the hash timestamp moves to
the top 36 bits, counter 1 is ORed in, and the word is bitwise-NOT-ed, so
the low 12 hex digits read ffe exactly like the client. Same input still
maps to the same stable session per conversation; only the wire format
changed.
Verified end to end against opencode.ai/zen with an anonymous-lane gateway
build: chat completions (streaming and plain) return 200 across free
models, multi-turn conversations stay on one stable session, and
go build / go vet / go test pass.
Fixes#68
Zen now validates that a session ID's leading 12 hex characters decode to a recent inverted timestamp, ~(unix_ms*0x1000+counter) truncated to its low 48 bits. A digest-derived prefix is classified as a non-OpenCode client, so every free model answers 403 FreeTierError.
Mint the timestamp half from the clock and cache it per downstream conversation, so the same conversation keeps its key and proxy affinity.
Keep manually restored free models enabled until automatic control is selected.
Persist the control mode and expose an authenticated per-model toggle in the WebUI and admin API.
Preserve disable evidence, renew expired 24-hour retries after inconclusive probes, and keep mode changes idempotent.
Validation: local regression checks, go vet/build, formatting and WebUI syntax passed; all five GitHub Checks passed. Test files were removed after validation.
Closes#56
`/v1/models` only advertised context and token limits for models that
OpenCode's capability catalog describes. Everything else fell back to the
defaults a discovery client hardcodes (128k context / 16k output), which
made every such model look identically small to CLIProxyAPI and Pi.
models.dev already publishes `limit.context`, `limit.input` and
`limit.output` for the OpenCode providers, and the gateway already fetched
that file for pricing and deprecation only. Store those limits in the
metadata cache and fill the fields the capability catalog omitted.
The capability catalog stays authoritative: capability flags always come
from it, and a limit it published is never overwritten. This also merges
the other OpenCode provider tiers instead of returning the first provider
alone, so models that only one tier describes keep their cost, anonymous
eligibility and limits.
Clients holding a metadata cache written by an earlier build keep their
old data until the next refresh; deleting config.json.models.dev.json
forces an immediate refetch.
Fill in the Legs field the request log already renders: append one
key:status:ms entry per upstream attempt (anonymized label for the
public lane, redacted key suffix otherwise; timeout/transport markers
for errors). A multi-attempt turn now reads as a single chain instead
of requiring attempt-log correlation.
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.
POST /v1/systemone existed since v1.3.3 with zero README coverage:
add the route to the endpoint table, a usage section (verbatim relay,
no translation, streaming replies relayed without reset recovery) in
both English and Chinese, and soften the absolute no-retry sentence to
match the stale-reasoning repair behavior.
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.
Native opencode sends prompt_cache_key (session-sliced ID), plus
safety_identifier, store, and service_tier. The translator dropped
all four, so proxied turns never rode prompt-cache affinity while
native did. Decode, carry, and re-emit on both Chat and Responses
paths, omit-when-absent. Verified live: same-session turns hit 99%
cached upstream after warm-up.
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.