Commit Graph
116 Commits
Author SHA1 Message Date
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 Xu cf104d8f17 Merge pull request #77 from SK-DEV-AI/pr/session-burn
feat: per-session token burn in logs, monitor rings, and usage snapshots
2026-10-15 07:52:28 +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 Xu 16f68b84e8 Merge pull request #59 from cheerc/fix/anonymous-cooldown-lockup
fix: stop anonymous lane from locking up after quota+network change
2026-10-15 07:52:24 +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 Xu 0569f953a8 Merge pull request #64 from mcheiyue/fix/attempt-deadline
fix: bound each upstream attempt by the full attempt deadline
2026-10-15 07:52:18 +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 Xu 05f0fafde2 Merge pull request #63 from ahoo/fix/responses-max-output-floor
fix: floor responses max_output_tokens to 16 for tiny budgets
2026-10-15 07:52:13 +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 Xu 9a5b4e23e5 Merge pull request #76 from SK-DEV-AI/pr/client-cancel-499
fix: report header-phase client disconnects as 499 client_canceled, not 502
2026-10-15 07:52:07 +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 Xu 55f26e96ad Merge pull request #78 from SK-DEV-AI/pr/typed-clonemap
perf: typed CloneMap deep copy without marshal round-trip
2026-10-15 07:40:02 +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
Jason Xu 0973fb83e6 chore: drop npm and Prettier tooling
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.
2026-10-15 01:55:56 +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 ebb4a7f90d Merge pull request #83 from AiFLYF/fix/anonymous-free-tier-endpoint
Retain anonymous probe routing fixes and omit test files from the merged tree.
v1.3.9
2026-10-15 00:07:11 +08:00
Jason Xu be91f8697a fix: restore free-tier requests and route anonymous probes correctly 2026-10-15 00:06:24 +08:00
FLYF f8e996dc66 fix: mirror the OpenCode client fingerprint so upstream stops rejecting requests
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.
2026-10-14 23:38:14 +08:00
sk-dev-ai 2dd89196fb perf: typed CloneMap deep copy without marshal round-trip
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.
2026-10-14 17:32:42 +05:30
sk-dev-ai 773b64bf9e feat: per-session token burn in logs, monitor rings, and usage snapshots
Every anonymous-lane session draws from one shared upstream IP bucket,
but nothing showed which conversation was draining it. Carry the
canonical ses_ ID into RequestMeta and the request_routed line, the
recent-request ring, and per-model/per-tier style usageSessions maps in
both lifetime and hourly snapshots.

The lifetime sessions map is capped at 500 entries (smallest-first
eviction): session IDs are high-cardinality and an unbounded map grows
forever. Buckets and snapshots are short-lived and stay uncapped.
2026-10-14 17:31:40 +05:30
sk-dev-ai 406107b053 fix: report header-phase client disconnects as 499 client_canceled, not 502
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.
2026-10-14 17:26:33 +05:30
CheerC 74d6a7c71e fix: stop anonymous lane from locking up after quota+network change
Cap Retry-After at 8x base cooldown in both MarkFailure paths, add
anonymousPool.RestoreProxy, and clear anonymous cooldowns when a proxy
recovers, so a new IP's fresh quota is reachable without a restart.
2026-10-13 16:02:37 +08:00
CheerC 79195d8767 test: reproduce anonymous 401 lockup after quota+network change
RED: Retry-After honored without cap; anonymous pool has no RestoreProxy.
2026-10-13 16:02:37 +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.
v1.3.8
2026-10-13 14:06:29 +08:00
mcheiyue 5076226ac2 fix: bound each upstream attempt by the full attempt deadline
performance.attempt_timeout_seconds only maps to
http.Transport.ResponseHeaderTimeout, which starts after the request
body is written and stops at the response headers. An exit that wedges
during dial or request-write hangs with no timer running and can consume
the entire request budget on its own; the attempts that follow are then
fired against an already-expired context.

Wrap every attempt in a context deadline covering dial + request write +
response headers + first event. Release it atomically the moment a
response is committed so the deadline can never cut an established
stream (a stop-the-timer race at the first-event boundary is closed by
deciding "deadline fired" vs "commit response" under one lock).

Also tag each failed attempt with the phase it died in (dial / write /
headers / first_event) so a hung exit is attributable from the request
log alone, and classify the attempt timeout as its own leg instead of
the generic transport bucket.

Adds unit tests for the deadline cut, the release-after-first-event
boundary, the phase classification and error unwrapping.
2026-10-11 19:42:51 +08:00
ahoo a8c4a78174 fix: floor responses max_output_tokens to 16 for tiny budgets 2026-10-10 15:59:51 +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) v1.3.7 2026-10-08 00:19:40 +08:00
Jason Xu ab2451da2a fix: include GPL license in Docker build context v1.3.6 2026-10-07 20:02:24 +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 ba07ae1ae3 Merge pull request #46: document System One 2026-10-07 19:34:35 +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
Jason Xu 2603eff66a Merge pull request #53: fill missing model limits 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
sk-dev-ai 437fab54ea docs: document System One endpoint and stream-retry semantics
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.
2026-10-04 19:54:18 +05:30
Jason Xu 79a208a467 Merge pull request #41 from asas6661/feat/systemone-protocol
feat: serve System One decision models on /v1/systemone
v1.3.5
2026-09-23 14:05:01 +08:00
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