Commit Graph
127 Commits
Author SHA1 Message Date
hanlap0503 6150f7da28 fix(webui): align language flag in toolbar and auto-detect browser language 2026-10-15 10:06:22 +00:00
hanlap0503 1e81532be8 fix(webui): pin login language selector to top-right 2026-10-15 09:55:58 +00:00
hanlap0503 c8501653fd feat(webui): move language selector to far right of toolbar 2026-10-15 09:51:31 +00:00
hanlap0503 184f3127ac feat(webui): borderless flag selector without dropdown arrow 2026-10-15 09:50:13 +00:00
hanlap0503 86ea7dae74 feat(webui): show flag-only language selector aligned with toolbar 2026-10-15 09:46:54 +00:00
hanlap0503 6833a5d7a8 feat(webui): replace language toggle buttons with dropdown selectors 2026-10-15 09:41:14 +00:00
hanlap0503 59eac43e51 feat: add check-models script for model inference testing 2026-10-15 09:40:51 +00:00
hanlap0503 68e7c1bf3e fix(webui): restore flag button styles after css revert 2026-10-15 09:34:43 +00:00
hanlap0503 0c016a1e36 feat(webui): add Vietnamese interface with a runtime language switch
Translate the whole management console and let the operator pick a language
without replacing the shipped copy.

- webui/i18n.js holds the dictionaries only; the Simplified Chinese text stays
  in index.html and app.js and is the fallback for every untranslated string,
  so a new locale never rewrites the original.
- Static text uses data-i18n / data-i18n-attr hooks, JavaScript text goes
  through t(); a locale switch re-renders both without a reload, and the
  choice persists in localStorage under opencode2api.ui.lang.
- The switcher is a flag button in the toolbar and on the login card that
  opens a menu of every supported locale. Flags are inline SVG, because
  Unicode flag emoji renders as plain letters on Windows.
- Ships 简体中文 (original), English and Tiếng Việt.
- README.vi.md translates the full README; all three READMEs cross-link and
  document how to add a locale.
2026-10-15 09:20:28 +00: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.
v1.4.0
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 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