Commit Graph
150 Commits
Author SHA1 Message Date
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
Jason Xu cece86bb22 Merge pull request #126 from TiaraBasori/chore/opencode-2.0.32-shape
chore(upstream): sync the /inference lane shape with OpenCode 2.0.32
2026-10-18 21:53:16 +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 83d623d541 fix(webui): prevent duplicate v prefix in version and link to GitHub repo 2026-10-17 19:45:45 +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.
v1.4.1
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 a46de6fe29 Merge branch 'pr-89'
# Conflicts:
#	.github/workflows/checks.yml
#	README.md
#	README.zh-CN.md
#	docs/management.zh-CN.md
#	webui/app.js
#	webui/embed.go
#	webui/index.html
#	webui/styles.css
2026-10-17 01:54:21 +08:00
Jason Xu d4f1e136ed Merge branch 'pr-98'
# Conflicts:
#	webui/styles.css
2026-10-17 01:11:21 +08:00
Jason Xu 7bd517efb5 Merge branch 'pr-100' 2026-10-17 01:08:23 +08:00
Jason Xu 076451fa31 feat: prefer legacy /zen/v1 anonymous lane with fallback to /inference 2026-10-17 01:02:59 +08:00
WengeLiu101 6c9be9037f fix(webui): make sidebar nav reachable on short viewports and stop overflow on narrow screens 2026-10-16 19:35:31 +08:00
michaelliunsky e6797dab22 fix(webui): drop the zero timestamp from the quota catalog line
An unset catalog timestamp is the Go zero time; format it as a "not
ready" placeholder instead of rendering 0001-01-01.
2026-10-16 18:34:03 +08:00
michaelliunsky a0da31ed08 feat(webui): rebuild console with tabbed pages
Replace the single-file frontend (app.js, styles.css) with a multi-file
ES module structure served from go:embed, and reorganize the 13 pages
into 8 tabbed pages under 4 navigation groups: runtime (overview,
diagnostics), integrations (access guide, API keys), models (quotas,
rotation), and system (configuration, account).

The redesign adopts a monochrome light/dark design system driven by
prefers-color-scheme, replaces prompt()/confirm() flows with in-page
dialogs, and keeps every management API call and deep link (old hashes
alias to the new pages).

Behavior changes: the log SSE connection now spans the whole console
session and buffers while the stream tab is hidden; quota polling runs
only while its tab is active; the first-run checklist appears on the
overview page and hides once ready.

Also fixes a crash on the rotation page: the persisted state serializes
empty orders and maps as JSON null, which is now normalized before
rendering, with the same defensive handling in the quota and API key
pages.

CI now syntax-checks the ES modules via node --input-type=module, and
the README structure notes are updated.
2026-10-16 18:09:42 +08:00
hanlap0503 6648db99ee Merge pull request #1 from hanlap0503/fix/rotation-anonymous-2026-10-16
Fix/rotation anonymous 2026 10 16
2026-10-16 13:43:29 +07:00
hanlap0503 2626f49fbb fix: update check-models script to save working models and handle empty responses 2026-10-16 06:41:31 +00:00
hanlap0503 f99600e7b9 fix: simplify rotation manager configuration and add test for model exclusion 2026-10-16 06:41:19 +00:00
hanlap0503andCopilot b7be5ed7d0 fix: route rotation aliases through anonymous lane
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-16 06:35:01 +00:00
hanlap0503 d15aec3d2e Merge branch 'jasonxu114514:main' into main 2026-10-16 08:08:41 +07: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
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