Files
Calcium-Ion 7b857f5a1e feat(plugins): add provider plugins, request plugins and a community marketplace (#8271)
* 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.
2026-11-12 20:50:58 +08:00
..

Task plugin API v1

Task plugins are single-file synchronous ECMAScript modules. The plugin contract is currently unreleased; v1.schema.json and v1.d.ts are the authoritative v1 contract.

Contract and lifecycle

Every plugin exports meta, buildSubmitRequest, parseSubmitResponse, and parseTaskResult. A per_task plugin also exports buildQueryRequest; a batch plugin exports buildBatchQueryRequest and parseBatchResult. meta.author.name is required and meta.author.url, when present, must be an absolute HTTP(S) URL. This is self-declared attribution; a future marketplace's verified publisher identity is a separate host-owned record. Plugins may declare authenticated vendor-native meta.routes and claim host-owned names through meta.protocols. Submit and dynamic routes name a native decoder and presenter; query routes name only a presenter. Protocol bindings are registered once by the host registry, and protocol decoders receive the host-parsed body union plus the pinned model. Shared protocol hooks are synchronous transformations; Go owns connections and wire framing.

The host selects a channel, invokes the request-building hook, validates the returned URL against the channel host, performs HTTP, and gives the decoded response to the matching parse hook. It owns persistence, retries, polling, billing, and settlement. Plugins only transform data and report usage facts. See v1.d.ts for signatures and v1.schema.json for machine-readable shapes.

Plugins that expose task outputs export listArtifacts(task) and buildContentRequest(ctx) together. Artifacts are projected on explicit reads from persisted Task.Data; they are never stored as a second source of truth. The list contains only stable key, type, and optional mimeType fields. The content hook receives the selected key, raw decoded task data, the explicit private upstream task id, the producer plugin version, channel authentication, and a safe client Range/conditional-header subset. Its URL and headers exist only for that proxy request.

When a Responses observation reaches persisted SUCCESS, the host also runs the pinned plugin's listArtifacts and injects a read-only ctx.artifacts[key] = {key, type, mimeType?, url} map into renderEvents or renderFinal. Each url is a long-lived host-signed capability URL, never the provider URL from Task.Data. Nonterminal and failed tasks receive no artifact map. Capability construction or rendering failure fails only that Responses observation; it cannot change the task, billing settlement, or refunds. The absolute URL uses TaskPublicAddress, falling back only to ServerAddress; multi-node deployments must share the effective CRYPTO_SECRET. Dashboard artifact reads return each content_url (or the legacy legacy_content_url) directly, without a temporary URL exchange. Capability generation and verification are stateless and have no expiry; after verification the host still loads the task, owner, and plugin needed to serve the artifact. Rotating CRYPTO_SECRET invalidates issued URLs. The access query is redacted before request logging. Deployment boundaries and concurrency environment variables are documented in v1.md.

The host requires protocols.openai_video.render to return a JSON object and preserves provider extensions, including output URLs and metadata. Plugins may return task.data to expose the latest persisted upstream snapshot. The host still overwrites id, object, model, status, progress, created_at, and completed_at, and removes legacy task_id. This is field-level projection, not byte-for-byte HTTP forwarding: known private task IDs are replaced before rendering, polling may redact inline video data, and retrieval reads the latest saved snapshot rather than issuing a new upstream request. Artifact content endpoints remain available for proxied downloads.

Provider-authenticated content URLs must use the channel base host or a plugin-declared meta.allowedHosts entry. A public dynamic CDN URL may instead set credentialless: true; the host then permits only GET/HEAD with no plugin-supplied headers or body and applies SSRF checks to the initial URL and every redirect.

Registry publication is generation-atomic. A request pins one plugin generation for its full lifetime, while background polling may use a later active plugin version. New versions must continue parsing responses for in-flight tasks. Root administrators can inspect the local node with GET /api/plugin/task/runtime/status. The response includes the node-local generation, a deterministic revision of the active database overrides, the latest rebuild outcome, and plugin-level compile or routing errors. Generation numbers are local to a node; compare database revisions when diagnosing rollout lag between nodes. If the database snapshot is temporarily unavailable, the endpoint keeps serving node-local state and the last known revision with database_error set.

For live diagnosis, start the process with DEBUG=true and filter logs on task_plugin. Plugin registry, routing, endpoint ownership, channel selection, submit durability, polling adapters, and protocol observation emit safe key/value lifecycle events. Request-context events carry the request id; scheduled, background, and context-less work is labeled SYSTEM. Plugin console.log output is also forwarded in DEBUG mode. Hook-time output is prefixed with plugin key/version; module-initialization output may have an empty identity during initial upload validation. Do not print credentials, headers, request bodies, upstream payloads, or private URLs from plugin code; free-form console output cannot be redacted by the host.

Fixtures and dry runs

A fixture case is {name?, hook, member?, args, expected?, expectedError?}. Keep deterministic cases for every exported hook, its main error branch, batch behavior, renderers, usage, and content requests. Run a fixture locally with:

new-api plugin lint plugin.js
new-api plugin test plugin.js --fixture golden.json

Root administrators can open the plugin detail Sandbox tab, choose a hook, and submit an args JSON array. POST /api/plugin/task/:key/dryrun compiles the active database source or factory source in a temporary registry and invokes only that synchronous function. Dry runs never execute a request descriptor and therefore never contact an upstream service.

Upload and release

Upload from the root-only task plugin page or POST /api/plugin/task with {"source":"...","remark":"..."}. The server compiles the module, validates v1 metadata and required exports, and rejects invalid source before saving it. Use semantic plugin versions. Reusing a key/version with different source is rejected; activate or roll back a stored version through the management page.

For a third-party platform, create a channel of type Task Plugin, select the plugin key, provide an explicit base URL, and configure models. Clients may use the plugin's declared native routes. The generic management surface remains POST /v1/tasks/:pluginKey, GET /v1/tasks/:taskId, and GET /v1/tasks/:taskId/artifacts plus GET|HEAD /v1/tasks/:taskId/artifacts/:key/content.

Security boundary

Plugins have no global fetch, filesystem, require, imports, async functions, code compiled from strings (eval and the Function constructors throw an EvalError), or environment access. A few driver hooks may read upstream data with utils.fetch: GET or HEAD only, to the hosts a request descriptor may address. The host limits execution time, concurrency, input size, allowed request hosts, and resolves OAuth credentials outside JavaScript. Multipart files enter JavaScript only as opaque references.

This is not a hard memory-isolation boundary. A plugin sees data needed for the current request and can influence an authenticated upstream request. Uploading a plugin is an administrator-level trust decision equivalent to configuring a channel credential. Review source and version diffs before activation. Never run untrusted plugins merely because they compile.

Usage hooks may return facts such as seconds, resolution, or upstream units, but must never calculate prices or attempt quota settlement. The host owns all pricing and clamps billing conversions.