* feat(plugins): add provider plugins, request plugins and a community marketplace
- Provider plugins turn an upstream vendor into a channel type: routes,
protocol conversion, models, static keys, sign-in flows with token
refresh, balance queries, per-channel config and a scheduled hook.
- Request plugins run on requests and replies (ingress, request,
outbound, egress, reply, report), with instances by scope, model
ranges, dry runs and per-log records. Built-ins: request filter,
request redaction, parameter override, auto reasoning effort, image
compression and content moderation. Sensitive words move into a
request filter instance on first start.
- Node sync: a system_sync_topics table lets every node reload settings,
channels, plugins and other data within seconds, and the system info
page shows each node's state.
- Marketplace: a community source next to the official one, lookup by
plugin code for official and community plugins, key rules for
community plugins, install counts and takedown warnings.
* docs(plugins): name request protocols and host-only members in the plugin API
- Protocol names: ctx.format and samples use relaykit's protocol names.
The spec lists the client paths and body of each name, so every host
passes the same names to plugins.
- Host-specific members: channel, group, user, token, channelTypes,
channelOther and utils.paramOverride exist only on new-api. The types
mark them optional.
- Relay routes: the spec now writes out the route keys and the converters
each incoming path accepts. The schema lists the converter names.
* feat(plugins): show recommended plugins from the official list too
The site now marks official plugins as recommended in its index. The
built-in official and community lists both get a Recommended group;
lists added by the administrator still cannot recommend plugins.
* feat(plugins): fall back to www.newapi.pro when www.newapi.ai does not answer
Plugin lists, plugin files and logos from www.newapi.ai are downloaded
from www.newapi.pro, the mainland China site, when newapi.ai gives no
answer within 10 seconds; the browser remembers this for a day. The
marketplace toolbar has a download site picker: Auto, or Mainland China
to always use www.newapi.pro. Saved source addresses stay on newapi.ai,
and every file is still checked against its sha256.
Community install counts go to newapi.ai first and to newapi.pro when
newapi.ai cannot be reached.
* fix(plugins): leaving the page does not switch the plugin site to www.newapi.pro
Reloading or leaving the marketplace cancels requests still running.
That was read as www.newapi.ai not answering, so the browser moved to
www.newapi.pro for a day although newapi.ai was reachable. Requests
cut off by leaving the page are no longer counted.
* feat(plugins): choose the plugin download site by hand
The marketplace no longer switches between plugin sites by itself. The
toolbar menu lists the main site www.newapi.ai, the backup site
www.newapi.pro and the other plugin lists; picking an entry is the only
thing that changes where plugins are downloaded from, and the main site
can always be picked again.
A browser that the earlier automatic switch had moved to www.newapi.pro
opens on the main site again. The download site, the source choice and
managing sources now share one menu in the list header.
* feat(plugins): show plugin usage guides and require README and changelog
Every marketplace plugin version now ships a usage guide, README.md, and a
changelog, CHANGELOG.md, next to plugin.js. The install dialog shows the
guide in the reader's language when a translation is listed, falls back to
English, and links to the source file. A guide or changelog that breaks the
format is reported with its file, line and rule instead of being shown.
The plugin API document describes both formats, the translations they may
list, and the checks the community marketplace runs before it accepts a
version: readme_missing, readme_invalid, changelog_missing and
changelog_invalid. Versions accepted before these checks are not checked
again.
* fix(plugins): address review findings on plugin parts, limits and access
- Only the root user reads request plugin instance configs; an admin who
may bind instances to channels gets them without configs.
- Outbound hooks that grow the body are held to MAX_REQUEST_BODY_MB, as
ingress hooks are, and answer 413 without a retry.
- An admin who cannot read plugin options keeps the balance and model
list actions on plugin channels; the server answers whether they work.
- Reading the parts of a plugin source gives up when the source does not
parse or code elsewhere refers to meta, as the meta preview does.
* fix(plugins): address review findings on request processing, documents and node sync
- PDF checks resolve indirect parameters and bound every value the parser
allocates or loops on: predictor columns, object stream counts, nested
object streams, cross-reference streams and ToUnicode ranges. Font and
CMap work checks the deadline.
- A WebP frame must match its declared canvas, and keyword search stops at
its match limit.
- Request processing treats a body as JSON whenever the gateway parses it
as JSON, keeps Gemini reply parts in place, scopes instances by the
settled auto group, hides channel header overrides from plugin param
overrides, and captures replies only for report instances in scope.
- Request processing no longer follows the plugin master switch, which now
covers plugin tasks and channels only.
- json.patch copies stop at MAX_REQUEST_BODY_MB, and provider prepareRequest
effects past it answer 413.
- Image billing reads the count from the final upstream body, including the
count members of SiliconFlow, Imagen and Replicate and the Imagen default.
- Automatic channel status changes no longer reload every node's channel
cache. A credential refresh holds no channel lock while it waits on the
vendor. A key that needs login is disabled and the request can retry.
- Balance requests must go to the channel host or allowedHosts, and provider
stream events a plugin drops keep the stream alive.
- Node sync: OAuth provider writes bump inside their transaction, a failed
startup load is retried, and each node is judged by its own topics.
- request-filter checks the text the old sensitive-word check did,
request-redact and content-moderation handle large inputs, and
image-compress lossless mode leaves JPEG and WebP alone.
* fix(plugins): address the second review on balances, egress and routes
- Channel other_info writes (status changes, balance queries and manual
multi-key actions) only land while other_info is still the value read,
and retry otherwise, so a write on one node no longer overwrites another
node's balance or status reason. They write only their own columns.
- On the Responses path egress reads the body after the channel finalizes
it, which is the body sent upstream.
- The Vertex AI plugin picks the region by the model the client asked for,
as the built-in Vertex AI channel does.
- /request-processing and /security are reserved route namespaces, and a
test checks that every console page is reserved.
- The plugin API docs say what egress reads on a provider plugin channel.
* feat(channels): run the balance update as a system task with progress
"Update all balances" now queues a channel_balance system task instead of
starting a goroutine guarded by an in-process flag. The task row holds the
progress (enabled channels queried of total), so any node can answer it,
and its active key keeps one run at a time across nodes. The
CHANNEL_UPDATE_FREQUENCY schedule becomes the same task's schedule, so
manual and scheduled runs no longer overlap.
GET /api/channel/update_balance answers with the task id, and with the
running one when a run is already queued. GET
/api/channel/update_balance/task/:task_id, under the same channel
permission, returns the status, progress and failure of balance update
tasks only. The channel list follows the task, reloads as more channels
are queried and once more at the end, and reports how the run ended.
* feat(system): sync nodes through system tasks and clean up task history
Node sync no longer needs its own table. A write to synced data adds a
pending sync_<topic> system task. Every node polls the newest task of each
topic it keeps every 3 s and reloads when that task is newer than the one
it applied. Custom OAuth providers still add their task inside the write
transaction, and lock the newest task of the topic first, so tasks commit
in id order. The master marks a sync task succeeded once every online node
that keeps the topic has applied it. Until then the task shows how many
nodes have applied it and why the others have not. The
system_sync_topics table is gone.
A composite (type, id) index answers the newest task of a type from the
index. The latest-per-type and earliest-pending queries now read ids first,
because MySQL 5.7 scanned the whole table for them.
A daily system_task_cleanup task deletes finished system tasks older than
system_task_setting.retention_days (default 30, at least 1), in batches.
It never deletes active tasks or the newest task of any type. The
retention is set under Operations > Log maintenance.
* perf: read and edit request JSON and base64 with moego
Switch gjson/sjson to moego/ojson and base64 on media, file and plugin
paths to moego/base64. Both keep the same results on valid input.
- Param overrides apply every edit to one ojson.Doc and write the body
once, instead of copying the whole body for each edit.
- The video proxy and the audio check validate base64 without decoding
it; plugin icons and inlined plugin files build data URLs directly.
- Login, password, OAuth and signature code keeps gjson and
encoding/base64.
* perf: rewrite request fields without re-encoding the whole body
Removing disabled fields, the Responses WebSocket create event, AWS Mantle
and pass-through bodies, the OpenAI usage patch, alpha search, video result
redaction and image SSE events now edit the body with ojson.Doc instead of
decoding it into a map and encoding it again. Everything the gateway does
not touch keeps the client's member order, number spelling and characters.
- A key the client repeats is removed or rewritten in every copy, so an
upstream that reads the last copy sees the same value the gateway routed
and billed. A key that appears once is rewritten in place.
- Image responses and the video proxy read large values without copying
them.
* perf: keep member order in param override merges and prune_objects
Merging an object (append/prepend) now replaces existing members where
they stand and appends new members, sorted by key, at the end. prune_objects
deletes the matching objects from the body in place instead of encoding
the pruned part, or the whole body, again. Everything else keeps the
client's member order, number spelling and characters.
OpenAI added a 12-hour prompt cache to the Responses API on 2026-10-20
(prompt_cache_options.ttl "12h", GPT-5.6 and later). A 12-hour write
costs 2.5x the input price, twice the 30-minute write. We already
forwarded the option but billed every cache write at the 30-minute price.
- Read cache_write_tokens_details from Responses usage and keep the split
through streaming, compaction and format conversion.
- Ratio pricing bills 12-hour writes at twice the cache write ratio, the
same way Claude 1-hour writes use 6/3.75.
- Expressions get a cc12h price. When an expression leaves the long-lived
price out, 12-hour writes cost twice the cc price and Claude 1-hour
writes 6/3.75 times it; without a cc price they bill as input. Claude
cache writes are no longer free when an expression omits cc or cc1h.
- gpt-6-astra prices 12-hour writes at $25 ($50 above 272K tokens).
- GPT models with a cache write ratio convert to expressions with cc12h.
- Chat Completions forwards prompt_cache_options.
- The pricing editor, cost estimator, pricing pages and usage log details
show the 12-hour price and tokens.
Before billing, the gateway walked the whole decoded request of a task
plugin and rejected duration, seconds and count members that were out
of range at any depth, including vendor parameters passed through
metadata. A plugin had to declare duration-auto@1 for the gateway to let
a duration of -1 through.
The gateway no longer reads billing quantities from the request. It
still bounds every usage fact a plugin returns before quota is
calculated: second facts at most 3600, count facts at most 128, token and
credit facts saturated at the quota limit. Each plugin validates its own
request and derives its facts from the request it sends upstream.
duration-auto@1 is still accepted and has no effect.
Kling now bills the duration it sends. metadata.duration, which is the
whole body on native routes, overrides the top-level duration and must be
a whole number of seconds from 1 to 3600. Before, a metadata duration of
10 was sent upstream while 5 seconds were billed.
An unchanged model expression or provider override of a single-plugin
model stays saveable after the plugin drops a fact from its profile, so
a full pricing save is no longer blocked by existing prices. Shared
models still follow each provider's profile.
The task pricing table reads a dropped fact at the value a plugin keeps
reporting: price terms on dropped counts are omitted, tiers requiring a
dropped boolean to be true are skipped, and other conditions on dropped
facts are removed with the first matching tier kept. Existing prices
open in the table with only the remaining fields.
Add the synchronous openai_image host protocol so a task plugin can claim
POST /v1/images/generations and /v1/images/edits; the host submits the
task, polls it inside the request and lets the plugin render the OpenAI
image response. Unclaimed models still fall back to the HTTP image relay.
- Migrate Ali (Bailian) image models to the alibaba plugin and remove the
ali channel image/wan adaptors and the qwen model setting
- Add Doubao Seedream image generation to the doubao plugin
- Support retainResult on routes and indexed multipart file references
- Settle image counts from upstream usage or image payloads; document the
rule in the billing conventions and plugin API docs
- Show billing source and task artifacts in usage logs; rename the
DoubaoVideo channel display name to Doubao and refresh the favicon
Add tier(name, fixed(usd)) pricing leaves to conditional token expressions,
with static validation, token/request billing metadata, and safe settlement
when successful requests have missing or zero token usage. Preserve group
and request multipliers, separate tool charges, and explicit zero prices.
Reject fixed expressions on unsupported Realtime and task-usage entrances.
Expose per-token and per-call tier editing, preserve both drafts, and show
request units consistently in pricing summaries and consume logs. Retain
matched-branch metadata and update all seven frontend locales.
Validation passed:
- go test ./pkg/billingexpr ./relay/helper ./service ./setting/billing_setting ./relay -count=1
- Frontend pricing, model-pricing, editor and usage-log regression suites
- Typecheck, scoped lint, protected-header formatting, i18n validation and build
- go test ./service -run TestFixedPriceBillingDatabaseMatrix -count=1 -v
with TEST_FIXED_MYSQL_DSN and TEST_FIXED_POSTGRES_DSN set to isolated local
test databases: SQLite 3.50.4, MySQL 8.0.46, PostgreSQL 16.15.
All 39 database cases passed, including reserve/settle/refund, zero price,
missing usage, branch changes and insufficient-quota handling.
No production database schema or migration changes.
* test(relayconvert): add golden snapshot matrix and relaykit boundary guard
Phase 0 of the relaykit extraction plan: pin byte-level output of every
registered (from,to) request/response/stream conversion route, and
forbid kit-bound packages from growing host-only imports.
* wip(relayconvert): drop gin.Context from converter signatures; add convmeta draft
Phase 1 in progress: relayconvert now takes context.Context; host media
resolver adapts gin.Context back at the service boundary.
* refactor(relayconvert): decouple converters from RelayInfo, gin, and settings
Phase 1 of the relaykit extraction plan:
- converters now depend on convmeta.Meta (implemented by RelayInfo) instead
of *relaycommon.RelayInfo; ClaudeConvertInfo and the format guesser move
to convmeta with aliases left behind
- host settings reach converters via a convmeta.Options snapshot built in
RelayInfo.ConvOptions; no more model_setting/reasoning global reads inside
the conversion layer
- effort-suffix helpers move to service/relayconvert/reasoning (old package
forwards); chat-to-responses upgrade policy moves to service (host routing
logic, not conversion)
- golden conversion matrix unchanged
* test(relayconvert): tighten boundary — kit packages now free of gin/setting imports
* refactor(dto): drop gin and logger dependencies
Phase 2 (part 1): dto.Request.IsStream now takes *http.Request instead of
*gin.Context (Gemini's impl reads query/path off the std request); dto's
three logger calls become common.SysError. Boundary test allowlist is now
empty — kit-bound packages import no gin/setting/logger/model.
* refactor(kit): extract dependency-free kitutil; dto/types/relayconvert stop importing common
Phase 2 of the relaykit extraction plan:
- new service/relayconvert/kitutil holds the pure helpers the kit needs
(JSON wrappers, pointer/string/uuid/timestamp utils, MaskSensitiveInfo,
pluggable LogInfo/LogError hooks, Debug flag)
- dto, types, and all relayconvert packages now use kitutil; their only
remaining internal deps are dto/types/constant
- common keeps every original symbol (MaskSensitiveInfo delegates to
kitutil) so host code is untouched; main.go routes kit logging into
common.SysLog/SysError and mirrors DebugEnabled
- golden conversion matrix unchanged
* refactor(kit): move EndpointType/FinishReason to types; OpenRouter dialect via Options
Kit packages (dto/types/relayconvert/reasonmap) no longer import constant:
- EndpointType and finish-reason values live in types; constant re-exports
- the OpenRouter special-case in claude->openai request conversion reads
Options.OpenRouterDialect, set by the host from the channel type;
InitChannelMeta invalidates the cached snapshot on channel switch
* refactor: extract relaykit submodule (dto/types/relayconvert/reasonmap)
Phase 3 of the relaykit extraction plan:
- new go module github.com/QuantumNous/new-api/relaykit containing dto
(minus task family), types, relayconvert (with convmeta/kitutil/reasoning),
and reasonmap; host consumes it via require + replace, go.work for dev
- task-family dto (task/suno/midjourney/video) stays in the host dto
package; dual-consumer host files alias it as taskdto
- relaykit builds and tests standalone (GOWORK=off): no host imports,
no gin, no DB, no settings
- golden conversion matrix unchanged
* build(docker): copy relaykit/go.mod before go mod download
The local-replace submodule's go.mod must exist inside the build context
for the main module graph to resolve.
* fix: address relaykit extraction regressions
* fix: address relaykit review regressions
* docs: document Meta nil receiver contract
* fix(relaykit): fail OpenAI→Claude conversion without max_tokens; reject negative default_max_tokens
The Claude Messages API requires max_tokens (omitting it is a 400
"Field required"), but with a nil Options.Claude.DefaultMaxTokens hook
the converters silently emitted a request the upstream is guaranteed to
reject. Both OpenAI Chat and Responses → Claude conversions now return
sharedclaude.ErrMissingMaxTokens when no path (client value, default
hook, thinking-adapter floor) supplied one. Unreachable in the host,
which always configures the hook.
Host side, claude.default_max_tokens now rejects negative values at the
option API before persisting — they would wrap into huge unsigned values
during conversion. Zero stays allowed: the current API treats
max_tokens: 0 as cache pre-warming.
* fix: make Gemini safety settings read path race-free
Thread int32 saturation clamps from tiered settlement and video task
recompute into the consume/task logs under admin_info, so oversized or
malformed billing inputs stay auditable. Clamp negative audio duration
before token conversion and gate the saturation UI markers on admin.
Bound max-tokens fields across all relay format validators, saturate
tiered-expression rounding and audio/tool/task token conversions, and
route legacy remix ratios through the guarded setter.
- Introduced a new rule for the Billing Expression System, emphasizing the importance of reading `pkg/billingexpr/expr.md` for dynamic billing.
- Updated the billing expression logic to support new variables and improved handling of image and audio tokens.
- Enhanced the tiered billing functionality with versioning support for expressions and refined quota calculations.
- Added tests to validate the new billing expression features and ensure correctness in pricing calculations.
- Adjusted billing calculations in tests and core logic to incorporate a new QuotaPerUnit field.
- Modified estimated quota calculations to reflect changes in tiered billing logic.
- Updated related tests to ensure accuracy with the new quota calculations.
- Enhanced dynamic pricing components to align with updated billing expressions.
- Introduced new fields for billing mode and expression in the Pricing model.
- Implemented dynamic pricing breakdown component to display tiered billing details.
- Updated various components to support and render tiered billing information.
- Enhanced pricing calculation logic to accommodate dynamic pricing scenarios.
- Added tests for new billing expression functionalities and UI components.
- Added support for tiered billing expressions in the billing system.
- Introduced new types and functions for handling billing expressions, including caching and execution.
- Updated existing billing logic to accommodate tiered billing scenarios.
- Enhanced request handling to support incoming billing expression requests.
- Added tests for tiered billing functionality to ensure correctness.