Commit Graph
41 Commits
Author SHA1 Message Date
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
Jason Xu 683b7e9af0 feat: expose configurable reasoning effort 2026-09-21 14:34:00 +08:00
haverainlilili 3440273f43 feat: 新增模型轮转、额度看板和密钥管理 2026-09-21 10:18:21 +08:00
Jason Xu e5f4e3a583 fix: shape key-tier free-model bodies to agent shape
Merge pull request #33
2026-09-19 13:05:54 +08:00
Jason Xu 41b9453d42 fix: demote phantom tool_use stop when no tool block was assembled
Merge pull request #27
2026-09-19 13:05:36 +08:00
Jason Xu b689a5b3a6 fix: preserve Chat usage for shaped free requests 2026-09-19 12:46:32 +08:00
Jason Xu 82e88f2b7f fix: filter phantom non-stream tool blocks 2026-09-19 12:46:32 +08:00
sk-dev-ai 3f8763d9da feat: forward native cache-affinity knobs (prompt_cache_key et al)
Native opencode sends prompt_cache_key (session-sliced ID), plus
safety_identifier, store, and service_tier. The translator dropped
all four, so proxied turns never rode prompt-cache affinity while
native did. Decode, carry, and re-emit on both Chat and Responses
paths, omit-when-absent. Verified live: same-session turns hit 99%
cached upstream after warm-up.
2026-09-18 19:39:17 +05:30
sk-dev-ai 79378c8744 fix: shape key-tier free-model bodies to agent shape
Upstream now rejects non-agent-shaped free-tier requests on every lane
with 403 FreeTierError (#29); #31 covered the anonymous lane only, so
keyed-only configs still 403 on bare probes. Mirror the normalization
(stream + core agent tools) for catalog-free models on key tiers; paid
bodies untouched. Non-streaming clients get the same stream collapse
as the anonymous lane. Free check uses catalog pricing metadata, not
the -free name, so nameless free models are covered.
2026-09-18 19:38:29 +05:30
58 2ce1f9e44b fix: serve anonymous free tier as agent-shaped streams
Upstream now rejects anonymous free-tier requests unless they look
like real agent traffic: stream:true plus the core agent tools
(bash/edit/glob/grep/read), returning 403 FreeTierError otherwise.

Normalize the anonymous-lane wire body (force stream:true, inject
minimal definitions for any missing core tools) and collapse the
SSE stream back into the single JSON document non-streaming
clients asked for. Authenticated tiers are untouched.
2026-09-18 09:09:20 +08:00
58 8185202382 fix: use canonical OpenCode session IDs for Zen free tier
Upstream began rejecting anonymous free-tier requests whose
x-opencode-session does not match ses_[0-9a-f]{12}[0-9A-Za-z]{14}
with 403 FreeTierError. Map every downstream identity into that
shape deterministically (preserving native sessions), and bump
the impersonated client version to 1.18.31.
2026-09-17 14:07:36 +08:00
xiechen 278b0bb8e2 fix: demote phantom tool_use stop when no tool block was assembled
Upstream Chat/Responses turns sometimes end with finish_reason
tool_calls while delivering no usable tool call (empty tool_calls
array, or deltas without a name). The bridge forwarded that as
stop_reason tool_use with zero tool_use content blocks. Strict
clients then end the turn running nothing and reporting no error,
which stalls agent loops mid-task with no visible failure.

Guard both the streaming (Finish) and non-streaming
(encodeBridgeResponse) paths: a tool stop with no assembled tool is
demoted to a plain stop so the client treats it as text end-of-turn
and continues.
2026-09-15 18:06:45 +08:00
Jason Xu 46def7fedc refactor: organize Go packages and remove test files
Move the command to cmd/opencode2api and group production code into
configuration, gateway, protocol, model, admin, telemetry and helper packages.
Keep shared state private behind context, metrics and runtime interfaces.

Remove the requested test files and replace test-only CI jobs with vet/build
checks. Update Docker and release build paths, preserve version injection and
make the WebUI an explicit embedded asset package.

Add directory trees and source reading guides to both READMEs. Anchor binary
ignore rules so the command package is tracked.
2026-09-15 01:28:44 +08:00