112 Commits
Author SHA1 Message Date
CheerCandClaude Code fa9a25577e fix(upstream): stop retrying request-level rejections and ignore placeholder keys
A free-tier 400 (context_length_exceeded, invalid_request_error) was
treated as retryable: the gateway walked the second anonymous lane, then
the keyed tier, and the client received whatever the last tier answered.
With the documented placeholder in zen_keys, a 941 KB request that only
needed compaction came back as "401 Invalid credential".

- classify request-level rejections (400/422 with invalid_request_error,
  context_length_exceeded, maximum context length, string_above_max_length
  or prompt is too long) and end the request after the first attempt on
  both the anonymous and keyed lanes, forwarding the original status and
  body; 401/403/429 stay retryable because they can be key-specific;
- read the body once with peekResponseBody so classification does not
  consume what the client eventually receives;
- drop documented placeholder keys (sk-your-zen-key, change-this-local-key)
  during config normalization: they never authenticate, and keeping them
  turns every free-tier fallback into a 401 that hides the real error.

Verified end to end by replaying the recorded request against the built
binary with the original configuration: 400 with the upstream message,
one upstream attempt, an anonymous key_id, and zen/go pools of 0.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-10-20 21:22:25 +08:00
CheerCandClaude Code 3e8318578d fix(upstream): treat the free-tier IP block as terminal for the exit
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>
2026-10-20 21:22:09 +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
byi4 c780e68a4c feat(upstream): mimic the genuine free-tier client on the v2 lane
The v2 lane (/inference) was reached in a shape the real 2.x CLI never
sends: the /zen host was offered first, session affinity was pinned to
the child session, Anthropic requests carried no beta query, and the
tool list still described a Linux shell.

- Prefer the /inference anonymous lane and keep the v1 lane as fallback.
- Append ?beta=true to Anthropic endpoints so the request matches the
  real client.
- Derive session affinity from the canonical parent session id and
  expose it as x-opencode-parent-session-id, while
  x-opencode-session-id keeps the child id.
- Send anthropic-version 2023-06-01 and drop the unused fine-grained
  streaming beta.
- Pass "global" and commit-shaped project ids through v2ProjectID
  untouched.
- Drop the Linux/bash wording from the shell tool description and add
  the patch tool.
2026-10-20 17:00:37 +08:00
cuipengcx90 ea947bc5dc fix(upstream): cap the number of anonymous exits tried per request
doAnonymousUpstream used limit = len(pool), so a request that every exit
rejects (403/429) walked the whole proxyfile, up to two legs per exit,
before failing. With a ~24 exit proxyfile this showed up as requests with
19-77 attempts and 200-660s of wall time, all ending in a 403/429 or a
client cancel.

Cap the static exit walk at 8. The #pool rule is unchanged: when a pool
entry is present the limit still rises to retry.max_attempts, so a single
rotating #pool entry keeps its per-attempt fresh IP.
2026-10-19 11:59:39 +08:00
Jason Xu d04ff337d7 feat(upstream): disguise free-model traffic as the Bun runtime
Both official OpenCode clients (1.x and 2.x) run on Bun, but the gateway
reached /zen and /inference through net/http, whose Go ClientHello, HTTP/2
and header layout no Bun client produces.

- Add httpx.BunTransport: Bun 1.4.3's BoringSSL ClientHello via uTLS
  (JA4 t13d1713h1, X25519MLKEM768, http/1.1-only ALPN), HTTP/1.1 with
  Bun fetch's header order and spelling, and gzip/deflate/br/zstd
  decoding that streams SSE incrementally.
- Support direct, HTTP/HTTPS CONNECT and SOCKS5 proxies with auth;
  proxy failures keep the net/http proxyconnect / socks connect shape so
  proxy health classification is unchanged.
- Pool idle connections per host, drop ones the server closes while
  idle, and retry once when a reused connection is dropped before the
  first response byte.
- Route only free-model traffic on the /zen and /inference lanes
  (anonymous, Zen key and availability probes) through it; /zen/go,
  paid models and metadata requests keep the regular client.
2026-10-19 08:33:12 +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 9aa2133f84 fix(identity): scope derived upstream sessions to the calling server key
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.
2026-10-18 22:04:54 +08:00
TiaraBasori b0a6584825 chore(upstream): sync the /inference lane shape with OpenCode 2.0.32
Report the current CLI release in the User-Agent and use the Linux shell tool description the client ships, so the anonymous fingerprint matches the release the free tier actually sees.
2026-10-18 21:21:40 +08:00
Jason Xu a9470df4fc fix(upstream): alias the client read tool to "read" on the legacy /zen/v1 lane
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.
2026-10-17 07:13:19 +08:00
Jason Xu 2319941a6a fix(upstream): restore v1.3.7 request shape and stub tools on legacy /zen/v1 lane
Commit 076451f preferred the legacy /zen/v1 origin ahead of /inference,
but still applied the 2026-10-14 /inference gate rules to /zen/v1
requests:

- ensureAnonymousTools rewrote any client-declared tool sharing a
  recognised OpenCode 2.x name ("read", "edit", "write", "glob", "grep",
  "shell", etc.) with the embedded CLI 2.x schema from
  opencode_tools.json, clobbering downstream function-calling schemas,
  and anonymousTool injected full 2.x tool schemas for edit/glob/grep/read
  alongside a stub bash tool.
- newUpstreamRequest and FetchModels sent the 2.x CLI User-Agent and
  header set instead of the v1.3.7 OpenCode 1.18.x headers.

Restore the v1.3.7 request shape when targeting the legacy /zen/v1 origin
(LegacyUserAgent, x-opencode-request, prj_* project id, lightweight tool
stubs, and untouched client tool definitions) while keeping the 2.x CLI
fingerprint and genuine tool definitions for the /inference fallback lane.
2026-10-17 06:17:54 +08:00
Jason Xu 8b61b66235 Delete internal/gateway/pool_test.go 2026-10-17 04:11:27 +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 6d83806939 fix(protocol): skip non-function Responses tools during cross-protocol bridging
Closes #95
2026-10-17 02:09:55 +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 Xu a6601da673 fix: report a proxy error when every proxy is down
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.
2026-10-15 20:40:50 +08:00
Jason Xu 25afadd303 feat: split usage by server key (#58)
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.
2026-10-15 08:22:49 +08:00
Jason Xu d434794866 feat: expose cost and reasoning levels in /v1/models (#65)
Discovery clients only saw reasoning: true, so harnesses such as OpenClaw
offered just off and max. Reasoning models now list the levels the gateway
forwards in reasoning_efforts and compat.supportedReasoningEfforts, capped
at the probed ceiling for auto, and report a forced or probed level as
default_reasoning_effort. Models with published pricing carry a cost
object, including cache read and write prices now decoded from models.dev.

Closes #65.
2026-10-15 08:14:11 +08:00
Jason Xu d04a9c750d feat: add models.free_only to expose only free models (#66)
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.
2026-10-15 08:08:01 +08:00
Jason Xuandsk-dev-ai bbfe07133c feat: per-session token burn in logs, monitor rings, and usage snapshots (#77)
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>
2026-10-15 07:52:28 +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
Jason Xuandmcheiyue c7f29b645f fix: bound each upstream attempt by the full attempt deadline (#64)
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>
2026-10-15 07:52:18 +08:00
Jason Xuandahoo 7a6c1f9386 fix: floor responses max_output_tokens to 16 for tiny budgets (#63)
Zen's Responses endpoint rejects max_output_tokens below 16, and clients
such as Claude Code send tiny budgets for background tasks. The 400 was
retried across every anonymous exit before reaching the client. Raise
budgets in (0, 16) to 16 on both the bridged and the same-protocol
Responses paths; nil and larger budgets pass through unchanged.

Co-authored-by: ahoo <ahoo@hroze.org>
2026-10-15 07:52:13 +08:00
Jason Xuandsk-dev-ai 24683057d1 fix: report header-phase client disconnects as 499 client_canceled (#76)
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>
2026-10-15 07:52:07 +08:00
Jason Xuandsk-dev-ai 130545d630 perf: typed CloneMap deep copy without marshal round-trip (#78)
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>
2026-10-15 07:40:02 +08:00
Jason Xu 77818beb02 chore: drop tool image tests merged with #62 2026-10-15 02:30:31 +08:00
Jason Xu 3fad1c6274 Merge pull request #62 from ai-daming/codex/fix-tool-result-images
fix: preserve images in cross-protocol tool results
2026-10-15 02:28:57 +08:00
Jason Xuandai-daming 8dfa7e249b fix: preserve images in cross-protocol tool results (#62)
Closes #60.

Co-authored-by: ai-daming <ai_daming@outlook.com>
2026-10-15 02:24:55 +08:00
FLYF feb4b18d26 style: format opencode_tools.json with Prettier (#85)
`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`.
2026-10-15 01:43:32 +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
Jason Xu 61769a9b9f Delete internal/identity/request_test.go 2026-10-13 15:03:19 +08:00
Empty 7f68c51d1d fix: mint free-tier session IDs with the client's descending Identifier encoding (#70)
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
2026-10-13 15:01:29 +08:00
Kasen Zheng 091329eead fix: mint descending-timestamp session IDs for the Zen free tier (#69)
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.
2026-10-13 14:06:29 +08:00
ai-daming e98f386712 fix: preserve images in cross-protocol tool results 2026-10-10 11:01:03 +08:00
CheerC 1e2702f6e0 fix: preserve manual control of free models (#57)
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
2026-10-08 22:12:40 +08:00
Jason Xu ef2df3f056 fix: correct free-model probes and add adaptive reasoning (#54) 2026-10-08 00:19:40 +08:00
Jason Xu df119c48e4 发布准备:合入 #36、#46、#48、#49、#50、#53;修复 #42、#44、#51、#52,并添加 GPL-3.0-or-later。
保留 reasoning 配置,新增免费模型可用性探测 / 手动恢复、首 SSE 事件超时,元数据改用官方地址。按维护者要求,最终文件树排除测试文件。

验证:本地 Go 回归、go vet / build、Prettier、JS / shell 语法及独立实例管理端验收通过。
2026-10-07 19:55:34 +08:00
Jason Xu 31c35704be Merge pull request #36: model rotation, quotas and API key management 2026-10-07 19:37:30 +08:00
Jason Xu baa9a615c5 Merge pull request #48: improve upstream diagnostics 2026-10-07 19:34:34 +08:00
Jason Xu 3cb9837d25 Merge pull request #49: remove orphaned stream helpers 2026-10-07 19:34:34 +08:00
Jason Xu c6797b73af Merge pull request #50: record per-attempt legs 2026-10-07 19:34:34 +08:00
CheerC 5dddf26d1e feat: fill missing model limits from models.dev
`/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.
2026-10-06 18:03:51 +08:00
sk-dev-ai 4c4e6b10d7 log: record per-attempt legs on the request line
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.
2026-10-04 19:57:11 +05:30
sk-dev-ai 51639af3ef chore: remove orphaned stream helpers
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.
2026-10-04 19:56:41 +05:30
sk-dev-ai 6c7dbfe6ab log: name upstream error class and skipped fallback tiers
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.
2026-10-04 19:55:42 +05:30
asas6661 a65ff83d71 feat: accept decision payloads on message endpoints too
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.
2026-09-23 13:35:30 +08:00
asas6661 4fed6e4d31 feat: serve System One decision models on /v1/systemone
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.
2026-09-23 12:11:45 +08:00