Commit Graph
6530 Commits
Author SHA1 Message Date
Seefs 2b85a8fc67 fix(auth): show legal consent warning on password login (#7771) 2026-10-12 18:25:54 +08:00
Seefs 2ed058795b fix(ci): stabilize checks and configure Bun dependency updates (#7765) 2026-10-12 18:19:04 +08:00
JohnUncle 9948b1ef14 fix(pricing): accept declared endpoint arrays in pricing conversion (#7724) 2026-10-12 17:57:53 +08:00
Richard Wang 4bfcf28121 chore(web): bump @lobehub/icons to 5.22.0 (#7764) 2026-10-12 17:55:13 +08:00
Seefs fc08b76f0f fix(web): preserve recorded billing tiers in usage log previews (#7763) 2026-10-12 17:47:28 +08:00
Shawn Wang ba0e478e06 fix(relaykit): preserve assistant text with tool calls (#6871) 2026-10-12 17:34:30 +08:00
Seefs 34b1942123 fix(pricing): allow root access when the model square is disabled (#7761) 2026-10-12 17:19:42 +08:00
feitianbubu b22a43b6e8 fix: mark task settlement logs with is_task for tiered billing display (#7446) 2026-10-12 16:58:16 +08:00
Seefs bbf60b49f6 fix(logs): vertically align billing source icons on mobile (#7760) 2026-10-12 16:54:24 +08:00
jimmyleocn 3f926c3ef4 fix(metrics): count completed streams after context cancellation (#7638) 2026-10-12 16:47:43 +08:00
Richard Wang 3827fd8307 fix(web): show cache read price on expression model cards (#7757) 2026-10-12 16:35:23 +08:00
Richard Wang 42e694eb60 fix(web): map Meta Muse Spark models to Meta icon (#7734) 2026-10-11 19:26:38 +08:00
CaIon c10780e054 fix(relayconvert): keep JSON Schema constraints in tools and structured output sent to Gemini
Requests converted for Gemini had their tool parameters and structured
output schemas forced into Gemini's typed Schema, and anything it cannot
hold was dropped silently: const, oneOf, $ref and $defs lost their
meaning, non-string enum values were removed from tool parameters, and
structured output with type arrays or non-string enum values got a 400
from Gemini.

A schema the typed Schema holds is sent exactly as before. Any other
schema now goes unchanged in parametersJsonSchema or responseJsonSchema,
which Vertex AI and the Gemini API v1beta accept. When a model is set to
Gemini API v1, which has no parametersJsonSchema, the schema is cleaned
as before and a conversion warning names what was dropped.
additionalProperties and $schema alone still do not switch fields, so
Claude Code, Codex and MCP tools and OpenAI strict structured output are
sent unchanged. Responses custom tools keep their typed parameters.

Fixes #7455
Refs #7704
relaykit/v0.3.3
2026-10-11 17:16:17 +08:00
CaIon 801456a061 fix(relay): send a close frame when a Responses WebSocket session ends
When a Responses WebSocket session ended on the server side, for example
because the upstream closed or reset its connection, a request timed out
or failed, or a token was rejected, new-api dropped the client socket
without a close frame, so clients such as Codex reported a connection
reset without a closing handshake.

Every way the session ends now sends a close frame first: 1008 for a
rejected token or a disabled channel, the upstream's own 1000 or 1001
when an idle upstream closes normally, 1011 when a request is cut off or
fails, and 1000 to the upstream when the client closes. Each frame waits
at most one second and never waits for a busy writer. Completed turns
still reuse the connection, and billing is unchanged.

Refs #7642
2026-10-11 17:10:53 +08:00
赵瑞哲 4b13d9388e fix(relayconvert): drop non-string enum values when converting OpenAI tool schemas (#7729)
Gemini's legacy parameters (Schema) only accepts string enum elements, so
an OpenAI tool schema like {"type": "boolean", "enum": [true]} was
forwarded as-is and rejected upstream with HTTP 400 (TYPE_STRING). Keep
the enum constraint only when every element is a string, otherwise drop
it while preserving the declared type, in both the deep and the
depth-capped shallow cleaner. String enums pass through untouched.

Fixes #7704.
2026-10-11 17:08:44 +08:00
CaIon 93ea55f3c3 feat(web): pick dates and times down to the second
The date-time picker (expiry times, announcements, log cleanup and the
dashboard filters) and the date range filter on the log pages stopped
at the minute: editing a time reset its seconds to zero, and confirming
a range again dropped the seconds it had. Both now show and keep
seconds, and the range filter button shows them too.

Emptying the time field, for example with Backspace on one part of it,
sent out an invalid date. The field now goes back to its current time
instead.
relaykit/v0.3.2
2026-10-11 14:19:10 +08:00
CaIon 96275d224b fix(web): show date pickers and relative times in the interface language
The date pickers looked up their calendar language under "zh", but the
interface uses zhCN and zhTW, so both Chinese interfaces showed English
month and weekday names. They now use the Simplified and Traditional
Chinese calendars.

Relative times on the passkey card, the login session list and the
announcement list were always English, so a Chinese page showed
"2 hours ago". They now follow the interface language through the
shared formatter; English announcements read "5 minutes ago" instead of
"5m ago".

Refs #7654
2026-10-11 13:57:00 +08:00
CaIon 06dd76a9d3 fix(playground): keep each account's Playground data separate
Playground settings and messages were stored under fixed browser keys,
so after switching accounts in the same browser the next user saw the
previous user's chat history.

They are now stored per user ID. Data saved under the old shared keys
has no known owner and is deleted, so existing Playground history is
cleared once.

Fixes #7713
2026-10-11 13:57:00 +08:00
CaIon 1fb6d07fee perf(web): stop loading the whole Simple Icons pack on four pages
The wallet, security and OAuth callback pages and the user binding
dialog imported a few brand icons from react-icons/si, which pulled the
whole pack (about 3,400 icons, 5 MB, 2 MB gzipped) into their routes.
They now use the brand icons already in the project, plus a new Alipay
icon, and Linux DO bindings show the Linux DO logo instead of the Linux
penguin. The wallet page now loads 535 KB of scripts instead of 5.6 MB.

Payment method icons configured by name still load their pack on
demand.

Refs #7634
2026-10-11 13:56:59 +08:00
CaIon b892a6b2e4 fix(web): reload once when a page's code fails to load
When a route's script or style chunk failed to load, for example on a
flaky connection, the console showed the error page with a large "500"
although no request had returned 500, and it stayed there until the
user reloaded by hand.

The error page now reloads the page once after a chunk load failure; if
the chunk still fails, the error page stays. It no longer shows a status
code for errors that have none. Rate-limit errors still show 429.

Fixes #7634
2026-10-11 13:56:59 +08:00
CaIon 977450a3e8 fix(rate-limit): explain model rate-limit rejections without Redis
Without Redis, the in-memory model request limiter rejected requests
with a bare 429: no error body and no log line. Clients could not tell
it from an upstream 429, and operators could not see which user hit the
limit.

It now returns the same error message and writes the same log line as
the Redis limiter, for both the total and the success limit.

Fixes #7721
2026-10-11 13:56:49 +08:00
CaIon 5ac7562840 fix(relayconvert): keep answer text that shares a stream chunk with reasoning
Some OpenAI-compatible upstreams put the last reasoning token and the
first answer text in one stream chunk. The Chat to Claude Messages
stream converter emitted only the thinking delta for such a chunk and
dropped the text, so Claude clients lost the start of the answer.

Such a chunk now emits the thinking delta, closes the thinking block,
opens a text block and emits the text delta. Usage, stop reason and the
closing events are unchanged.

Refs #7664
2026-10-11 13:56:49 +08:00
CaIon 13c8e90b8f fix(relayconvert): send Responses image URLs to Chat upstreams as objects
A Responses input_image carries image_url as a string, while Chat
Completions defines image_url as an object with a url field. The
converter forwarded the string unchanged, so Chat upstreams that follow
the documented shape, such as vLLM and strict gateways, rejected
requests with images, for example Codex screenshots and images returned
by tools.

A string image_url is now wrapped as {"url": ...}. The detail beside it
is still left out, because Chat upstreams that validate it with older
OpenAI SDKs reject newer values such as "original". Object values and
file_id parts are unchanged.

Fixes #7578
2026-10-11 13:56:49 +08:00
CaIon 036ba376da fix(relaykit): match Claude effort and Gemini 2.5 budgets to each model
RelayKit sent some Claude effort levels that the target model does not
accept. A request with an effort but no thinking reached Opus 4.5 with
max or xhigh. Sonnet 4.5, Haiku 4.5 and other models without effort
support received an effort anyway. When a model-name suffix or modifier
turned thinking off, the client's output_config.effort stayed in the
request unchecked. Opus 5 and Haiku 5.5 then got disabled thinking at
xhigh or max, and Sonnet 5.5 got between_tools at those levels. The API
rejects these combinations with a 400.

Known Claude models now get the nearest effort level they accept, and no
effort when they accept none. Effort works without thinking, so a
thinking-off request keeps the client's effort within those limits. On
Opus 5, Haiku 5.5 and Sonnet 5.5 it is capped at high. Fable, Mythos
and Mythos Preview are now marked as taking effort. These models cannot
turn thinking off, so a thinking-off request runs them at low effort,
as Opus 5.5 already does. The new reasoning.ClaudeEffort returns the
effort a model accepts for a requested level. Native requests without a
suffix or modifier still pass through unchanged, and models RelayKit
does not know keep the effort they were sent.

Claude Haiku 5.5 joins the capability table: adaptive thinking only, on
by default, all five effort levels, and medium as the default effort.
Converted requests no longer send it manual thinking with budget_tokens,
which it rejects. They also drop temperature, top_p and top_k, which it
accepts only at their defaults.

Gemini 2.5 Pro takes thinking budgets up to 32768, but xhigh and max
were rendered as 24576. They now get the model's largest budget: 32768
on 2.5 Pro, and 24576 on 2.5 Flash and Flash-Lite as before. high stays
at 24576, as in Google's OpenAI-compatible mapping.
relaykit/v0.3.1
2026-10-11 12:42:17 +08:00
CaIon 0f38a14a5e fix(web): restore browser sans-serif for Auto font 2026-10-10 20:29:04 +08:00
CaIon 1ca79d57e7 fix(pricing): show recent status samples without gaps
Fetch the latest 24 nonempty hourly samples within 7 days for the visible models, while preserving the 24-hour summary metrics. Render only available samples without gray placeholders.

Validated perf-metrics tests with SQLite 3.50.4, MySQL 5.7.44, and PostgreSQL 9.6.24; Go build; 36 frontend tests; frontend typecheck, lint, formatting, and production build.
2026-10-10 19:24:32 +08:00
CaIon c6741c36a9 feat(channel): add a per-channel switch to skip upstream TLS verification
Until now only the global TLS_INSECURE_SKIP_VERIFY setting could accept a
self-signed upstream certificate. A channel's tls_insecure_skip_verify
setting now does it for that channel's API requests: relay and the Responses
and Realtime WebSocket dialer, task submission and polling, plugin fetches,
balance, usage and model-list queries, and media proxied through the channel
proxy. Credential exchanges (Codex OAuth refresh, Vertex and plugin
service-account tokens) keep verifying certificates. The channel drawer shows
the switch under the HTTP protocol settings.
v1.0.0-rc.43
2026-10-10 14:02:06 +08:00
CaIon c8d234baa1 fix(xai): bill video edits and extensions by their output resolution
The "source" resolution tier was not an xAI price. xAI bills edits and
extensions at the output resolution, which keeps the input video's
resolution capped at 720p and is reported nowhere. xai 1.1.0 reserves 720p,
then reads the output MP4's track header with ranged utils.fetch calls to
vidgen.x.ai and settles at 480p when the shorter side is at most 480 pixels.
If the header cannot be read, the task settles at 720p.
2026-10-10 13:40:04 +08:00
CaIon ba3b2c015a refactor(jsplugin): stop requiring json-clone@1 and submit-sse-delta@1
utils.json.clone is available to every plugin, and a plugin that exports
parseSubmitEventDelta without parseSubmitEvent now gets the delta hook
without declaring anything. Both capability strings stay accepted for
plugins written for earlier hosts, and a plugin exporting both hooks keeps
the snapshot hook unless it declares submit-sse-delta@1. alibaba drops both
declarations.
2026-10-10 13:40:04 +08:00
CaIon 3f02244783 feat(web): show the request domains a plugin declares when uploading it 2026-10-10 13:39:55 +08:00
CaIon 66c3e14282 fix(hailuo): download MiniMax v1 videos through the file retrieve link
The plugin pointed content requests at /v1/files/download, which MiniMax
does not serve, so v1 video downloads returned 410. hailuo 1.2.1 looks the
file up with /v1/files/retrieve through utils.fetch and proxies the signed
download_url without the channel key, using GET for HEAD clients because the
link is signed for GET.

Fixes #7709
2026-10-10 13:39:55 +08:00
CaIon 29509776ef feat(jsplugin): let driver hooks read upstream data with utils.fetch
utils.fetch is a synchronous, read-only GET or HEAD to the channel Base URL
host or the plugin's allowedHosts, through the channel proxy used for
polling. It is available in buildSubmitRequest, the query and batch build
and parse hooks, and buildContentRequest; every other hook throws. Each hook
call gets at most 4 fetches, 15 s per fetch, 30 s in total and 1 MiB per
body. Redirects are returned, not followed. responseType "bytes" returns an
ArrayBuffer for binary data such as a media file header.

While a fetch waits, the runtime gives up its execution slot and the
watchdog pauses. BuildContentRequest now receives the request context, and
the media proxy shares the plugin request header rules.
2026-10-10 13:39:55 +08:00
CaIon b66674ac23 feat(task-plugin): let Seedance and wan3.0 pick the video duration with -1
A plugin that declares duration-auto@1 may receive a duration of -1 (the
vendor picks the length) anywhere in the request; other negative values and
values above the limit are still rejected, and usage facts stay
non-negative. A declaring plugin reserves the model's longest duration and
settles on the usage the vendor reports.

- doubao 1.3.0 declares it, forwards -1 to Ark and reserves each model's
  longest duration (12 s for Seedance 1.0 and 1.5 pro, 15 s for 2.0, 30 s for
  2.5). A JSON duration on /v1/videos now reaches Ark.
- alibaba 1.4.2 declares it, so wan3.0 smart duration also works on
  /v1/video/generations.

Fixes #7700
2026-10-10 13:39:44 +08:00
CaIon 1d4328e974 docs(relaykit): rewrite README for the current conversion API
Describe the conversion result diagnostics and loss policy, the
reasoning-state handoff and thinking suffix parsing, hosted web search
and Responses custom tool handling, the usage and cache token fields,
the Responses stream failure and sequence_number options, the JSON
codec and logging hooks, and the full option list. Plain product-page
wording.
2026-10-09 22:59:20 +08:00
Calcium-Ion 128089fa7d feat(i18n): translate web console messages in the frontend and AI-client errors in the backend (#7712)
* feat(i18n): translate web console messages in the frontend and AI-client errors in the backend

Chinese text was hard-coded in API messages, stored log content, emails and
server logs, so it reached users of every interface language.

Text is now translated where its reader is:

- Web console APIs return the English source text as message_key with
  message_params, and the web console translates it in all seven languages.
  message keeps the English text for other API callers.
- Errors returned to AI clients, emails and notifications are translated by
  the backend (en, zh-CN, zh-TW) in the language saved on the account, then
  the language of the request's Accept-Language header.
- A reader who states no language still gets the original Chinese text of the
  messages that were Chinese before, word for word. Gateways that use another
  new-api as their upstream match that text, for example to disable a channel
  whose account ran out of quota.
- Usage, top-up and system log content is stored as content_parts (key and
  params) and rendered in the viewer's language. Task fail reasons and refund
  reasons written by the gateway are English keys. Rows written earlier are
  shown as before.
- Server logs are English.

Also:

- The saved interface language zhTW, and zh-HK, zh-MO and zh-Hant, now select
  Traditional Chinese in the backend instead of Simplified Chinese.
- The built-in group descriptions are translated; descriptions an
  administrator saved are shown as written.
- .agents/rules/i18n.md records the conventions. Tests in i18n/ fail on a
  non-English string literal, on a web console message without translations
  and on a locale key without a constant.

* feat(i18n): print server logs in Chinese when LOG_LANGUAGE asks for it

Server log lines are English by default. With LOG_LANGUAGE=zh-CN, the lines
that were Chinese before print their original Chinese text.

common.LogText formats a log line from its English format, which is also the
key of its Chinese text in common/log_text.zh-CN.json. A line without an entry
prints in English. go vet checks the arguments of every call, and
TestServerLogTexts checks that each entry still matches a call and has the
same verbs as its key.

* docs: list LOG_LANGUAGE in the docker compose example

* feat(i18n): translate every server log line and add DEFAULT_LANGUAGE

Every line the gateway prints goes through common.LogText. With
DEFAULT_LANGUAGE=zh-CN, the lines that have a Chinese text in
common/log_text.zh-CN.json print it and the others print English.

DEFAULT_LANGUAGE replaces LOG_LANGUAGE. It also sets the language of
backend messages, emails and notifications for a reader who states no
language: en, zh-CN or zh-TW, English when unset. The list of messages
that stayed Chinese for such readers is removed.

Review fixes:
- Channel test logs store the token name "Model test"; the console shows
  it in the interface language.
- Task fail reasons written by the gateway are fixed sentences the console
  translates. The HTTP status and the upstream detail go to the server log
  when a polled task is failed.
- The auto-disable reason of a slow channel is written in DEFAULT_LANGUAGE.

Also:
- Drop the repository-scanning lint tests, the i18n rules file and its
  read gate. AGENTS.md keeps the conventions in four lines.
- Payment error toasts keep their previous text and only add the
  translated message key.
- Remove guards and helpers that no caller needs.

* fix(i18n): address review on language lookup, notices and error responses

- Relay requests no longer load the user a second time to find the
  language: the settings TokenAuth put into the request are used as they
  are, also when they hold no language.
- Upstream model update notices are rendered in each recipient's saved
  language, DEFAULT_LANGUAGE when none.
- /api/usage/token and /api/log/token answer with backend-translated
  messages again, with the keys and status codes used before this PR.
  Their callers are scripts, not the web console.
- Webhook notifications fill {{value}} placeholders like the other
  senders. Running the rendered text through Sprintf appended
  %!(EXTRA ...) and broke %2F in links.
- RootUserLanguage reads the setting of the root user it already loaded.
- zh_TW and zh_HK are read as Traditional Chinese.
- Add common.ApiErrorStatus for error responses under another HTTP status
  and use it where those responses were built by hand.
- Remove middleware.GetLanguage, which had no callers.
2026-10-09 21:39:51 +08:00
CaIon e0483122c7 fix(relayconvert): drop trailing assistant text from Responses input on Claude and Gemini
In Responses, assistant output at the end of input is history and the
model answers with a new item. Claude and Gemini continue a final
assistant turn as a prefill instead, and Claude 4.6 and later and Gemini
3.6 Flash, 3.5 Flash-Lite and later reject it with a 400. Codex sends
such input when it retries a stream that failed after an assistant
message completed: the retry is rebuilt from history, so the received
reasoning and answer end the input.

The Responses converters for Claude and Gemini now drop the assistant
turns without tool calls that follow the last user message or tool
result, and record a trailing_assistant_omitted warning. Input that ends
in a tool call still waiting for its result, or holds only assistant
turns, is sent unchanged. Chat and Messages requests keep their prefill.
relaykit/v0.3.0
2026-10-09 19:53:38 +08:00
指短琴长andCaIon 7aa3531ef4 fix(task-plugin): set multipart content type for upstream requests (#7655)
* fix(task-plugin): set multipart content type for upstream requests

* refactor(task-plugin): copy the rebuilt multipart Content-Type as is

BuildRequestBody stores writer.FormDataContentType() on the client
request right before BuildRequestHeader runs, so the media type and
boundary checks could never fail. Copy the value directly, as the sora
adaptor did before task plugins.

The test plugin now forwards the client's Content-Type, whose boundary
differs from the rebuilt body, so the test also fails if a plugin header
wins over the host value.

---------

Co-authored-by: CaIon <i@caion.me>
2026-10-08 23:52:03 +08:00
CaIon 6370b29424 feat(jsplugin): keep JSON member order for plugins that declare json-order@1
The host decoded plugin request bodies into Go maps, so hooks saw their
members sorted and the upstream body was written sorted. TypeSafe Jev
reads the state object as written, and the reordering changed its scores
against calling TypeSafe directly.

A plugin that declares the json-order@1 capability now gets the client's
order end to end: its decoders receive the JSON body as text, its decoded
requestBody is kept as JSON.stringify text for the driver hooks, and its
request descriptors are decoded with Unmarshal so the body reaches the
upstream as that text. Other plugins keep the Go-map path unchanged, and
billing bounds still validate the decoded requestBody.

RawJSON hook arguments, top-level or nested, are now parsed in place with
ParseJSONString instead of being copied first; every caller passes bytes
it never changes afterwards.
v1.0.0-rc.42
2026-10-08 18:04:56 +08:00
CaIon 192802ee06 build: build release binaries with moejs's PGO profile
moejs ships a default.pgo recorded from plugin workloads. Go only uses a
profile found in the main package directory, so the Docker image, the
release workflow and the Electron builds now pass it with -pgo.
2026-10-08 18:04:56 +08:00
CaIon b23471112d build: upgrade moejs to v0.1.0-alpha.6
alpha.6 adds json.RawMessage arguments and targets, ParseJSONString and
a faster interpreter. new-api builds and its plugin tests pass on it
without host changes. On moejs's new-api gate the BenchmarkTaskPlugin
rows are 4.3 % faster on geomean (HookCall -13 %, Submit 8 MiB -8.6 %)
with allocations unchanged.
2026-10-08 18:04:56 +08:00
CaIon bc82357929 test(relaykit): keep format-conversion tests out of the repository
Format-conversion tests for relaykit are maintained outside the
repository. Remove the conversion tests added in 78bd5b1cb (Gemini
tool-output media and the Opus 5.5 default effort) and c6bac617d
(thinking suffix aliases), and restore the tests those commits extended
to their earlier form. Usage tests such as dto/usage_merge_test.go
stay.
2026-10-08 18:04:56 +08:00
CaIon 0cce21db02 perf(jsplugin): stop rebuilding the usage-key replacer and request body on every hook call
canonicalUsageLimit built a new strings.Replacer for every usage key it
normalized, which took about a third of the CPU and most allocations on
passthrough task submissions; the replacer is now built once. The task
adaptor also normalized the same request body again on every hook call
of a request. Hooks never write into the body, so the normalized value
is now cached per request body and reused. In the task plugin
benchmarks, passthrough submissions run 42-60% faster with 85% fewer
bytes allocated, and large-body submissions about 1.5% faster.
2026-10-08 18:04:56 +08:00
CaIon d10f11ffff feat(gemini): bill Google Search grounding per query or per grounded prompt
Gemini responses grounded with Google Search billed one google_search
call per response on every model. Google bills Gemini 3 per unique
search query ($14 per 1,000) and Gemini 2.5 and older per grounded
prompt ($35 per 1,000). A counter now collects the unique non-empty web
and image search queries across every stream frame and candidate of a
response. It records google_search as that query count and
google_search_grounded_prompt as one grounded prompt, and the tool price
table decides which of the two costs money for a model. The native
generateContent handler now counts grounding too. Google reports no
billed count in the response, so the unique query set is the best
available evidence, not a guaranteed match.

Built-in prices make queries free and grounded prompts $35 per 1,000 on
gemini-2.5*, gemini-2.0*, and gemini-1.5*; other models keep
google_search at $14 per query. Because built-in model-prefix prices
take precedence over a tool default, an operator's own google_search
price no longer applies to those older models; to keep search free
there, set google_search_grounded_prompt:gemini-2.5* (and the 2.0* and
1.5* keys) to 0.
2026-10-08 18:04:55 +08:00
Seefs 04c597bf6c feat: support regex conditions in advanced parameter overrides (#7698) 2026-10-08 16:07:03 +08:00
CaIon 45094bdf41 fix(web): 修复 OriginOS 6 设备渠道页白屏
用户环境:vivo X300 Ultra,OriginOS 6(Android 16),Chrome 和
Via 浏览器均出现渠道页白屏,控制台无错误。

保留页面模糊过渡,将入场终点由 blur(0px) 改为 blur(0.01px),
动画结束后设置 filter: none,避免零半径 blur 在受影响设备上
触发白屏。补充页面入场和路由切换的回归测试。

验证:受影响测试 2 项通过,typecheck、相关文件 lint 和格式检查
通过;测试实例已由用户在故障设备上复测,确认页面正常。
2026-10-07 23:40:17 +08:00
Calcium-Ion acb347a197 feat(relay): web search encoding per channel and vendor-reported search billing (#7690)
* feat(channels): convert Claude and Gemini requests to OpenAI Responses on Advanced Custom channels

Advanced Custom channels could convert Claude Messages and Gemini
generateContent requests only to OpenAI Chat. Two converters,
claude_messages_to_openai_responses and
gemini_generate_content_to_openai_responses, now send them to an OpenAI
Responses upstream and convert the response back to the client's
format. The channel form offers them with the /v1/responses upstream
path and bearer auth by default, and the backend validates their
incoming paths like the existing converters. The IDs keep the values the
relay already uses for these conversions.

* feat(moonshot): forward Responses requests to Kimi unchanged

Moonshot channels answered /v1/responses with "not implemented". They
now forward the request body unchanged to {base}/v1/responses. Kimi
serves only kimi-k3 on that endpoint today; other models are rejected
by the upstream, not by the gateway.

* fix(relay): bill completed image_generation calls when a Responses request ends failed or incomplete

An image_generation call that completed before a response.failed,
response.incomplete, or cancelled terminal had already reached the
client, but the stream accumulator reset the image count to zero on
those terminals, and the non-stream handler skipped image outputs when
the response status was failed, cancelled, or incomplete. Completed
images now bill on every terminal, as they already did when the client
disconnected; image items that never completed still bill nothing.

* feat(relay): let channels encode hosted web search and bill vendor-reported search counts

Converted requests always encoded hosted web search the OpenAI way:
web_search_options on Chat and the native hosted tool on Responses,
Claude, and Gemini. Zhipu and DashScope compatible-mode Chat take their
own search fields, and the search counts that Azure, xAI, and DashScope
report in usage were ignored; only web_search_call items were billed.

relaykit gains a WebSearchEncoder option that a channel adaptor sets in
Init; without one, the default encodings stay. Zhipu sends the GLM
web_search tool with search_std, and Gemini clients on Zhipu now convert
through Chat. DashScope compatible-mode Chat sends enable_search and
search_options with the default turbo strategy and maps allowed domains
to assigned_site_list (up to 25 sites). DashScope Anthropic-compatible
requests that carry a web search tool get the cc_entrypoint system
marker DashScope requires before it searches. Zhipu and DashScope Chat
responses report no search usage, so a forced search bills one call,
which is dropped again if the request retries on another channel; a
Zhipu non-stream response that returns search results also bills one.
Several hosted web search definitions on a Chat target now drop the
extras with a diagnostic instead of failing the request.

Vendor-reported counts replace the counted web_search_call items under
the vendor's price key: Azure tool_usage.web_search.num_requests as
bing_web_search, xAI server_side_tool_usage_details (web_search_calls as
web_search, priced for grok models, plus x_search posts and profiles),
and DashScope usage.x_tools on Responses and server_tool_use on its
Anthropic endpoint as search_strategy_agent. Claude server_tool_use also
counts web_fetch, code_execution, and tool_search, which bill only once
an operator prices them. Tool names with a built-in price and these
Claude server tools are reserved, so a client function of the same name
is never billed under them. The Claude and Gemini search counts move
from gin context keys into the per-request tool counts, and every tool
count is capped at 10,000 at settlement.

Built-in prices are seeded for these keys in each vendor's list currency
(Zhipu and DashScope in CNY, Azure and xAI in USD) and listed on the
tool price settings page. DashScope Responses requests move to
/compatible-mode/v1/responses, because the old /api/v2/apps/protocols
endpoint is no longer maintained.
2026-10-07 23:29:24 +08:00
CaIon 0a03088e0e fix(relayconvert): fix lossy conversions and converted-stream failure billing
A review of the cross-protocol conversions found requests that the
upstream rejected or misread after conversion. Gemini function schemas
in its OpenAPI subset (uppercase types, nullable, propertyOrdering)
reached OpenAI, Claude, and Responses targets unchanged; they are now
rewritten as JSON Schema, and keywords without an equivalent are dropped
with a diagnostic. Media is mapped by MIME type instead of being sent as
an image: Gemini inline and file data, Claude image and document
sources, Responses input_file, and Chat file parts reach each target as
the image, PDF, text, or audio part it accepts. Media a target cannot
carry is omitted with an unsupported_media_type diagnostic instead of
reaching the upstream in a shape it rejects. Chat image_url objects no
longer carry a stray MimeType key, and Responses tool outputs that hold
content parts become Claude tool_result blocks instead of a JSON string
with base64 inside.

Codex declares tools in namespaces and in additional_tools input items.
They are now flattened to functions named <namespace>__<name> (tools in
the default functions namespace keep their names), and calls get their
namespace back on the Responses side; only names that collide are
dropped. When no tool reaches the target, tool_choice and
parallel_tool_calls are omitted. A forced tool_choice is sent as auto
when manual extended thinking is enabled on Claude, which rejects that
combination. A disable intent renders as adaptive thinking at low effort
on Claude Opus 5.5, which cannot turn thinking off, and as between_tools
on Claude Sonnet 5.5.

Converted streams (Chat via Responses and Responses via Chat) now follow
the native Responses billing rule. A client that disconnects mid-stream
settles the output it received instead of failing the request. An
upstream failure before any output reached the client is not charged;
after output it bills the upstream usage, or the estimate of the
delivered text, reasoning, and tool arguments. Stopping a stream with a
typed nil error no longer panics.
2026-10-07 22:56:12 +08:00
CaIon 0a532f7f7d feat(plugins): add an xAI Grok Imagine video plugin
xAI-type channels could only serve chat. The new built-in xai plugin
serves grok-imagine-video, grok-imagine-video-1.5, and
grok-imagine-video-1.5-lite through the native /xai/v1/videos routes
(generations, edits, extensions, and status), /v1/videos, and
/v1/responses, on xAI channels and on New API channels that bind it.

Usage bills output seconds by model and resolution, input images, and
the input video seconds of edits and extensions on grok-imagine-video.
Edits and extensions keep the input video's resolution, which xAI does
not report, so they bill under a separate "same as input video"
resolution. xAI still charges for a video its moderation filters after
generation and for a failed request that reports a cost, so those tasks
settle as charged with the moderated fact set instead of being refunded.
The native status route presents such a failure as a moderated result,
so a chained New API gateway charges it too. Other failures are refunded
as before.
2026-10-07 22:55:39 +08:00
CaIon bb28f2ccad feat(tokenkit): move token counting into a module calibrated on agent traffic
Token estimates badly undercounted agent requests. Claude tool
definitions, Responses function calls and their outputs, Chat assistant
tool calls, and Gemini system instructions, function calls, function
responses, and tools never reached the counter; Chat tool schemas were
counted as Go map syntax and Claude tool results as escaped JSON.
Measured against upstream usage on 54 real Claude Code and Codex
conversation windows, native prompt estimates were 31-93% low, and the
Claude and Gemini completion fallbacks about 90% low because streamed
tool calls were not counted.

All of these now reach the counter. The completion fallbacks count tool
names and arguments, plus 40 tokens per Claude tool_use block. The
estimator weights are refitted per tokenizer: Claude before Opus 4.7,
Claude 4.7 and later (about 30% more tokens for the same text), GPT, and
Gemini. Prompt estimates now land within 1% bias and 3-4% mean error for
each family.

Token counting moves into tokenkit, an independent module like
relaykit, so other gateways can use it. It also replaces the flat
520-token image estimate with each provider's sizing rules, checked
against upstream usage on sizes outside the test table: OpenAI patch and
tile rules per model and detail level (gpt-5.5 and later default to
original detail, and their high detail is billed as measured, not as
documented), Claude's two resolution tiers, and Gemini 3 media
resolution and Gemini 2.x tiles. Chat image_url parts without detail
no longer default to high in ParseContent, so they estimate as the
upstream default auto; no converter sent that value upstream.

tiktoken-go moves to v0.8.1, about twice as fast on ordinary text. It
requires Go 1.26, so the root module and tokenkit move to Go 1.26;
relaykit stays on 1.25.1. In every version BPE cost grows with the
square of a pre-tokenized piece, so 100,000 Chinese characters without
punctuation took 21.6 s to count during pre-consume. Count now cuts
single-class runs longer than 1024 bytes, which leaves ordinary text
unchanged and brings that input down to 106 ms. The encoder cache no
longer grows with client-supplied model names.
2026-10-07 21:26:35 +08:00
CaIon 0908d9e7b9 fix(epay): upgrade go-epay to v0.0.5 2026-10-07 21:26:35 +08:00