Compare commits

..
21 Commits
Author SHA1 Message Date
super c49a5fea42 fix(gemini): 修复文本与音频混合输出漏计费
候选用量缺失时合并文本和 PCM 音频估算,保留已报告的思考用量,并验证阶梯计费的音频拆分。
2026-11-30 23:32:56 +08:00
super b6ee14ddd3 merge: 同步 new-api 上游 v1.0.0-rc.52
纳入自 6627f0e3f 起的 19 个上游提交。将 NovaLink 监控保留路由迁移至网关配置并同步 pluginkit 保留键,按键合并七种语言的文案。
2026-11-30 22:40:59 +08:00
CaIon 04dfcbb712 docs(agents): fix stale facts and trim repeated rules in agent instructions
- web/AGENTS.md: translation keys are English source strings, not
  dotted paths; drop the E2E tools and 80% coverage target the project
  does not use; drop the changelog section.
- vercel-react-best-practices: describe the Rsbuild SPA instead of
  Next.js, Server Components and SWR.
- billing.md: Kling deduction field is final_unit_deduction in the
  plugin.
- AGENTS.md: core maintainers write issues without the agent template,
  as for PRs; replace the all-caps commentary line with a plain one.
- CLAUDE.md, i18n-translate, shadcn-ui: state each rule once and drop
  copied upstream promo text.
2026-11-28 01:12:36 +08:00
Calcium-Ion 944464420b feat(plugin): 插件渠道可按渠道开关提供商插件的路由 (#8482)
同一个提供商插件绑到多个类型 61 渠道时,各渠道的路由完全相同,无法只在部分渠道上
开启某条转换路由。#8478 用 enabled_by 指向 channelConfig 里的 boolean 字段,已回退;
这里改为由渠道直接保存路由开关,插件不用为每条路由声明配置字段。

- meta.relay 的路由新增 default_enabled(默认 true),写 false 的路由新渠道默认不提供;
  管理路由(/v1/models、余额)始终开启,不能写 false。
- 渠道的 other_settings.plugin_routes 保存路由开关,键为 incoming_path,
  带 models 时追加 "|" 和逗号连接的模型名;保存时只保留与默认值不同的项,
  不认识的键丢弃。
- 选渠道、Responses WebSocket 判断、转发、提供商适配器绑定路由、渠道测试选端点、
  上游模型列表和定价端点都只看对该渠道开启的路由;同一路径的其他路由照常匹配。
- 插件选项接口返回 relayRoutes;渠道编辑「路由与映射」页签顶部列出插件路由,
  每条一个开关,补齐七种语言词条。
- pluginkit/v1.md、v1.d.ts、v1.schema.json 补充 default_enabled 与 plugin_routes。

Refs #8466
2026-11-27 23:25:50 +08:00
CaIon d35242c55f chore(plugins): release Kling 1.2.1 2026-11-27 23:19:10 +08:00
Calcium-Ion 50a9767024 fix(relay): return 404 for models missing from all eligible groups (#8480) 2026-11-27 21:37:26 +08:00
Calcium-Ion 5456425f98 Revert "feat(plugin): 提供商插件的路由可按渠道配置开关(enabled_by) (#8478)" (#8479)
This reverts commit 92866e5eac.
2026-11-27 21:00:03 +08:00
Calcium-Ionandzwen 92866e5eac feat(plugin): 提供商插件的路由可按渠道配置开关(enabled_by) (#8478)
同一个提供商插件绑到多个类型 61 渠道时,各渠道的路由完全相同,无法只在部分渠道上
开启某条转换路由(例如只让部分渠道接受 /v1/responses)。

- meta.relay 的路由新增 enabled_by:指向 meta.channelConfig 顶层的一个 boolean 字段;
  加载时校验字段存在且为 boolean,管理路由(/v1/models、余额)不能使用。
- 渠道插件配置(按 schema 默认值补齐后)中该字段不为 true 时,这条路由对该渠道不存在:
  选渠道、Responses WebSocket 判断、转发、提供商适配器绑定路由和渠道测试选端点
  都按渠道配置判断。同一路径的其他路由照常匹配。
- 插件级的 RelayRoute 保持清单原样。enabled_by 只存在于插件清单
  (Meta.RelayEnabledBy,与 Relay 下标对齐),不改高级自定义路由结构。
- 插件 API 文档、v1.d.ts、v1.schema.json 补充 enabled_by。

Closes #8466

Co-authored-by: zwen <49605455+zwenooo@users.noreply.github.com>
2026-11-27 20:33:29 +08:00
zwenooo bea3616473 feat(relay): 路由转换器支持 OpenAI Responses 转 Anthropic Messages (#8465)
relaykit 已注册 openai_responses_to_claude_messages(请求、响应、流式三侧都有实现),
普通 Claude 渠道收到 /v1/responses 时也已经在用它,但高级自定义渠道和提供商插件共用的
路由转换器白名单里没有登记,这两类渠道无法把 /v1/responses 路由到 Anthropic Messages 上游,
插件只能用 converter: "plugin" 在 JS 里重写整套转换。

- relaykit/dto:白名单登记该转换器,incoming_path 限定为 /v1/responses。
- 高级自定义适配器:请求经 ConvertRequestByID 转成 Claude 请求;响应交给 Claude 适配器
  按客户端协议转回 Responses(含流式);发送 anthropic-version 等 Claude 请求头。
- 插件 API 文档、v1.d.ts、v1.schema.json 的转换器表补上该转换器及其 +plugin 链式写法。
- 前端高级自定义路由的转换器选项、默认上游路径(/v1/messages + x-api-key)与路径校验,
  七种语言的选项文案。
2026-11-27 20:13:18 +08:00
feitianbubu d6ab606bd3 feat(hailuo): support MiniMax-H3-Max with its own durations, resolutions and usage profile (#8453) 2026-11-27 20:07:06 +08:00
Calcium-Ion dc2750cd5d fix(pluginkit): 单独构建时使用仓库内的 relaykit (#8477)
pluginkit/go.mod 增加 replace,指向 ../relaykit。之前在 pluginkit 目录
单独构建或测试(CI 与 make test 都会这样跑)时,用的是已发布的
relaykit v0.3.8,同一个 PR 里对 relaykit 的改动在这里看不到,例如新增
的转换器会报 not registered。根模块本来就把 relaykit 替换为 ./relaykit,
所以发布的二进制不受影响;外部依赖 pluginkit 时会忽略这条 replace,
仍按 require 的版本解析。
2026-11-27 19:57:08 +08:00
Calcium-Ion 5ff8157dd2 fix(relaykit): flatten top-level oneOf/anyOf/allOf in Claude input_schema (#8476)
Claude rejects tools whose input_schema has oneOf, anyOf or allOf at the
top level (400 "input_schema does not support oneOf, allOf, or anyOf at
the top level"). Codex Desktop's automation_update tool has such a schema,
so every Responses -> Claude turn that carried it failed.

FunctionParametersToInputSchema now merges the branches into one object
schema: properties are combined (differing same-name schemas go into a
nested anyOf), required is the intersection for oneOf/anyOf and the union
for allOf plus the top level's, and other top-level keywords are kept.
The tool conversion reports claude_top_level_schema_union_flattened.
Schemas without a top-level union are returned byte for byte.
2026-11-27 19:16:11 +08:00
Calcium-Ion 0c1be7b1a9 refactor(plugins): 把插件 API v1 拆成独立模块 pluginkit (#8475)
插件 API v1 的元数据校验、utils、moejs 执行层和任务钩子的结果解析搬到
嵌套模块 github.com/QuantumNous/new-api/pluginkit,按 pluginkit/vX.Y.Z
打标签发布,其他宿主可以直接引用同一份实现。

- pkg/jsplugin 只留注册表、路由和 CLI,现有导出名通过别名保留,行为不变
- 文档 v1.md、v1.d.ts、v1.schema.json 移到 pluginkit/,schema 和类型由模块内嵌
- 请求处理钩子新增宿主专有的 ctx.client、ctx.session,new-api 不提供
- 导出 MaxPluginKeyLength、NewAPIReservedKeys 和 CallPathJSONInto
- CI、Makefile、Dockerfile 和 AGENTS.md 按 relaykit 的方式加上 pluginkit
2026-11-27 19:12:59 +08:00
Seefs caa32a3012 fix(relay): remove trailing newline from ClaudeChunkData data frame (#8474) 2026-11-27 19:12:18 +08:00
videogen-artandseefs001 3333fc6766 fix(gemini): bill audio inlineData by length, not as images, when usage is missing (#8193)
* fix(gemini): bill audio inlineData by length, not as images, when usage is missing

When upstream reported no completion tokens (no usageMetadata, or
prompt-only usageMetadata), every inlineData part with a non-empty
mimeType was counted as an image and backfilled with 1400 completion
tokens. A relay that answered a text request with thousands of
audio/l16 TTS chunks was billed millions of output tokens.

Estimate inline output from the payload instead, on the stream and
non-stream paths alike:
- image* parts (case-insensitive) keep the 1400-token estimate;
- PCM audio (audio/l16 or audio/pcm with a rate) counts 25 tokens per
  second, Gemini's audio token rate, measured from the decoded byte
  count of valid base64 holding whole 16-bit samples, and is recorded
  as audio output so tiered expressions price it with ao; on the
  prompt-only path it replaces any upstream AUDIO candidate entry;
- audio without a measurable length and other media add nothing.

Responses that report completion tokens are unchanged.

* fix(gemini): harden inline media usage fallback and avoid redundant scan

- Parse inlineData MIME types once with mime.ParseMediaType and ignore empty image payloads
- Gate BillingUsage AUDIO detail replacement on inline fallback application so stale AUDIO entries are cleared when estimating images
- Defer inline media observation in buildUsageFromGeminiResponse until completion tokens are missing
- Saturate audio token conversion inside audioTokens via common.QuotaFromFloat without bare int casts
- Add regression cases for empty image payloads, stale AUDIO clearing on image fallback, and preserving upstream completion counts

---------

Co-authored-by: seefs001 <i@seefs.me>
2026-11-27 19:12:07 +08:00
5f8525d83c fix(claude): map output_tokens_details.thinking_tokens to reasoning_tokens (#8431)
* fix(claude): map output_tokens_details.thinking_tokens to reasoning_tokens

Anthropic reports thinking tokens in usage.output_tokens_details.thinking_tokens,
a subset of output_tokens. ClaudeUsage had no such field, so OpenAI-format
responses converted from a Claude channel always reported
completion_tokens_details.reasoning_tokens = 0.

Decode the field and carry it into CompletionTokenDetails.ReasoningTokens for
non-stream responses and stream message_start/message_delta usage, bounded by
output_tokens. completion_tokens and billing are unchanged.

* fix(claude): apply reported zero thinking_tokens on message_delta

message_delta usage is cumulative. When output_tokens_details is present, use its thinking_tokens even if zero; keep the earlier count only when the breakdown is absent.

* fix(claude): bound delta thinking_tokens by merged output and preserve on merge

- Clamp message_delta thinking_tokens against accumulated completion_tokens so deltas omitting output_tokens do not zero out reasoning_tokens.
- Copy incoming OutputTokensDetails in MergeClaudeUsageNonZero to preserve or replace the breakdown across usage merges.

---------

Co-authored-by: forgottener <8578113+forgottener@users.noreply.github.com>
Co-authored-by: seefs001 <i@seefs.me>
2026-11-27 19:11:48 +08:00
Seefs 00056f5db7 Merge commit from fork
* fix(auth): enforce exact email matching and stored address on password reset

Enforce exact normalized email comparison in Go in GetUniqueUserByEmail (and FillUserByEmail) without premature SQL LIMIT 2, preventing accent-insensitive database collations from matching look-alike email addresses.

Send password reset emails, key reset codes, and build query-escaped reset URLs strictly using the stored normalized user email, revoking generated codes if delivery fails. Atomically verify and consume reset tokens in constant time via common.ConsumeCodeWithKey to prevent replay, and decode the reset payload via common.DecodeJson.

Add regression tests covering look-alike email rejection, stored-email delivery, single-use token enforcement, failed delivery cleanup, and token expiry (OWASP ASVS v4.0.3 2.5.1/2.5.2/2.5.3/2.5.6).

* fix(auth): preserve reset recipients and enforce exact email lookup at login
2026-11-27 19:11:25 +08:00
Nick Old fde819b05a fix(groups): 匿名请求公开分组接口时跳过用户分组查询 (#8461) (#8463) 2026-11-27 18:13:13 +08:00
Calcium-Ion 81c1fd20ef fix(models): 打开排序弹窗时再读取系统选项 (#8454)
* fix(models): 打开排序弹窗时再读取系统选项

* fix(models): 读取已保存排序后再启用编辑
2026-11-26 13:51:26 +08:00
CaIon c27abf3626 feat(pricing): 模型广场支持推荐顺序和按用量排序
- 模型广场的排序新增「推荐」「请求最多」「Token 最多」,默认按推荐排序;未设置时与原来的按名称排序一致
- 模型管理新增「模型广场排序」,可选手动排序、使用最多、置顶 + 使用最多,按请求数或 Token 统计近 1/7/30 天用量
- 公开的定价接口只返回排序结果,不返回各模型的用量
2026-11-26 00:29:07 +08:00
CaIon def76a60d6 feat(plugins): 放宽插件响应和 JSON 克隆的大小限制 2026-11-26 00:01:58 +08:00
168 changed files with 10473 additions and 5849 deletions

No files matched your search

+1 -1
View File
@@ -10,7 +10,7 @@ Mandatory conventions for quota, pricing, pre-consume, settlement, refund, and u
- Every user-controlled quantity that becomes a billing multiplier (image `n`, video `seconds`/`duration`, resolution/quality ratios, batch counts) MUST be bounded before it reaches quota calculation. Reject out-of-range values at request validation with a 400. Existing bounds: `dto.MaxImageN` for image generation count, `relaycommon.MaxTaskDurationSeconds` for task video duration, `maxTokensLimit` (`relay/helper/valid_request.go`) for `max_tokens`-family fields on every relay format (OpenAI, Claude, Gemini, Responses). Reuse these constants instead of introducing new ad hoc limits for the same concepts. When adding a new relay format or request DTO, bound its max-tokens and count fields in its validator from day one.
- Watch for validation bypass paths: passthrough fields (e.g. `Extra["parameters"]`), task `metadata` maps, and multipart form fields can carry the same quantities around the standard DTO validation. Any adaptor that reads a multiplier from such a path must enforce the same bound (or clamp) locally. Task plugins validate their own requests: the host bounds every usage fact a plugin returns before quota calculation and does not interpret request members. A plugin MUST derive its facts from the request it sends upstream, including values merged from `metadata` or other passthrough maps, and MUST bound any request quantity it turns into a token or credit fact; the host caps `second` and `count` facts but only saturates `token` and `credit` facts at the int32 quota boundary. A plugin that forwards a duration of -1 (the vendor picks the length) must reserve the model's longest duration and settle on the usage the vendor reports.
- Durations parsed from media metadata are user/upstream-controlled too: audio file headers (transcription token counting, TTS response duration) and upstream deduction numbers (e.g. Kling `FinalUnitDeduction`) can claim absurd values. Convert them with saturation before they become token counts.
- Durations parsed from media metadata are user/upstream-controlled too: audio file headers (transcription token counting, TTS response duration) and upstream deduction numbers (e.g. Kling `final_unit_deduction` in `plugins/tasks/kling/plugin.js`) can claim absurd values. Convert them with saturation before they become token counts.
- Never convert a computed quota or token count to `int` with a bare cast like `int(float64(quota) * ratio)`, `int(math.Round(...))` on unbounded input, or `int(decimal.IntPart())`. All quota rounding/conversion is centralized in `common/quota_math.go`; use those helpers: `common.QuotaFromFloat` (truncating) for float products, `common.QuotaRound` (half-away-from-zero) where rounding is intended, and `common.QuotaFromDecimal` for decimal products. `billingexpr.QuotaRound` delegates to `common.QuotaRound`. Do not reintroduce local conversion helpers or bare casts. Single-request saturation stays at the int32 boundary so batch accumulation cannot approach 64-bit wraparound; wallet/top-up conversion uses `common.WalletQuotaFromDecimalStrict` with the JavaScript-safe `common.MaxWalletQuota` boundary. Every clamp/NaN fallback is logged via `common.SysError`.
- Saturation events are also audited: each helper has a `*Checked` variant (`common.QuotaFromFloatChecked` / `QuotaRoundChecked` / `QuotaFromDecimalChecked`) that additionally returns a `*common.QuotaClamp` when clamping occurred. Billing paths that compute a charge capture that clamp onto `relayInfo.QuotaClamp` (or thread it into task settlement) and, right before writing the consume/task log, call `attachQuotaSaturation` (in `service/log_info_generate.go`) which nests the marker under the log's `other.admin_info.quota_saturation` and emits a request-correlated `logger.LogWarn`. Nesting under `admin_info` makes it admin-only for free (non-admin log views strip `admin_info`). When adding a new billing path, use the `*Checked` variant and surface the clamp the same way so the anomaly stays auditable in both the admin log UI and backend logs.
- Multiplier maps go through `types.PriceData.AddOtherRatio`, which rejects non-positive, NaN, and +Inf ratios. Do not write to `PriceData.OtherRatios` directly, and do not weaken these guards.
+2 -3
View File
@@ -56,7 +56,7 @@ Do not skip this workflow because the fix is "just one key".
For a single known missing key (still script-only, no direct JSON edits):
1. Confirm the exact key at the call site and verify it is absent from all locale files.
2. Add the key via `add-missing-keys.mjs`, populating its `newKeys` object for every supported locale: `en`, `zh`, `zh-TW`, `fr`, `ja`, `ru`, `vi`. Even one key goes through the script; do not hand-edit the JSON.
2. Add the key via `add-missing-keys.mjs`, populating its `newKeys` object for every supported locale: `en`, `zh`, `zh-TW`, `fr`, `ja`, `ru`, `vi`.
3. The script preserves the flat `"translation"` object and keeps keys alphabetically sorted automatically.
4. Run a targeted search for the key in code and locale files.
5. Run `bun run i18n:sync` to normalize file order. This step is mandatory, not optional.
@@ -196,7 +196,7 @@ for (const locale of locales) {
### Step 4: Add translations
This script is the ONLY sanctioned way to write locale values. You MUST NOT bypass it by hand-filling the JSON files. Create `web/scripts/add-missing-keys.mjs` with this exact structure:
Create `web/scripts/add-missing-keys.mjs` with this exact structure:
```javascript
import fs from 'node:fs/promises'
@@ -311,4 +311,3 @@ Delete temporary scripts after completion.
4. Always run `bun run i18n:sync` as the final step
5. Delete temporary scripts after completion
6. The `{{variable}}` placeholders in keys must be preserved in all translations
7. NEVER edit `locales/*.json` directly. Any non-script write to a locale file (StrReplace, Write, manual JSON edit) is non-compliant, including single-key fixes.
+3 -19
View File
@@ -14,34 +14,18 @@ description: >-
Skills give AI assistants project-aware context about shadcn/ui. When used, the assistant knows how to find, install, compose, and customize components using the correct APIs and patterns for your project.
For example, you can ask:
- _"Add a login form with email and password fields."_
- _"Create a settings page with a form for updating profile information."_
- _"Build a dashboard with a sidebar, stats cards, and a data table."_
- _"Switch to --preset [CODE]"_
- _"Can you add a hero from @tailark?"_
The skill reads your project's `components.json` and provides your framework, aliases, installed components, icon library, and base library so it can generate correct code on the first try.
Project context comes from `web/components.json` (framework, aliases, installed components, icon library, base library).
---
## Install (ecosystem vs this repo)
## Running the CLI
Official install from [Skills — shadcn/ui](https://ui.shadcn.com/docs/skills.md):
```bash
npx skills add shadcn/ui
```
That installs the skill where the `skills` CLI is available. **This repository** keeps the same intent under `.agents/skills/shadcn-ui/` (overview here + **vendored** upstream docs in [`vendor/shadcn/`](./vendor/shadcn/)) and runs the shadcn CLI from the frontend app root:
Run the shadcn CLI from the frontend app root:
```bash
cd web && bunx shadcn@latest info --json
```
Learn more about skills at [skills.sh](https://skills.sh).
---
## What's included (and where)
@@ -1,11 +1,11 @@
---
name: vercel-react-best-practices
description: React and Next.js performance optimization guidelines from Vercel Engineering. Use when writing, reviewing, or refactoring React/Next.js code involving components, Next.js pages, Server Components, Server Actions, data fetching, bundle size, rendering behavior, or performance improvements.
description: React performance optimization guidelines from Vercel Engineering. Use when writing, reviewing, or refactoring React components in web/ for data fetching, bundle size, re-renders, rendering behavior, or performance improvements.
---
# Vercel React Best Practices
Use this skill for React and Next.js performance work. The full Vercel guide is stored in `references/full-guide.md`; do not read the whole file by default.
Use this skill for React performance work. This project is a client-side Rsbuild SPA (no Next.js, no Server Components, no SWR); skip guide sections that only apply to those. The full Vercel guide is stored in `references/full-guide.md`; do not read the whole file by default.
## Workflow
@@ -18,12 +18,11 @@ Use this skill for React and Next.js performance work. The full Vercel guide is
1. Eliminating waterfalls: sequential async work, API route chains, missing `Promise.all`, Suspense boundaries.
2. Bundle size optimization: barrel imports, heavy client modules, dynamic imports, deferred third-party libraries.
3. Server-side performance: Server Actions auth, RSC serialization, per-request deduplication, cross-request caching, `after()`.
4. Client-side data fetching: SWR deduplication, global listeners, passive scroll listeners, localStorage schema.
5. Re-render optimization: derived state, effect dependencies, memo boundaries, functional state updates, transitions, refs.
6. Rendering performance: hydration mismatches, long lists, static JSX, SVG precision, resource hints, script loading.
7. JavaScript performance: repeated lookups, array passes, storage reads, layout thrashing, sort/min-max choices.
8. Advanced patterns: one-time initialization, stable callback refs, effect events.
3. Client-side data fetching: TanStack Query deduplication, global listeners, passive scroll listeners, localStorage schema.
4. Re-render optimization: derived state, effect dependencies, memo boundaries, functional state updates, transitions, refs.
5. Rendering performance: long lists, static JSX, SVG precision, resource hints, script loading.
6. JavaScript performance: repeated lookups, array passes, storage reads, layout thrashing, sort/min-max choices.
7. Advanced patterns: one-time initialization, stable callback refs, effect events.
## Reference
+10 -1
View File
@@ -37,6 +37,7 @@ jobs:
go.sum
relaykit/go.sum
tokenkit/go.sum
pluginkit/go.sum
- name: Create frontend embed placeholder
run: |
@@ -54,6 +55,10 @@ jobs:
working-directory: tokenkit
run: go vet ./...
- name: Vet pluginkit independently
working-directory: pluginkit
run: go vet ./...
- name: Build root module
run: go build ./...
@@ -65,7 +70,11 @@ jobs:
working-directory: tokenkit
run: go build ./...
- name: Test root, relaykit, and tokenkit modules
- name: Build pluginkit independently
working-directory: pluginkit
run: go build ./...
- name: Test root, relaykit, tokenkit, and pluginkit modules
run: make test
frontend:
+10 -9
View File
@@ -1,6 +1,6 @@
# AGENTS.md — Project Conventions for new-api
DO NOT send optional commentary
Keep replies to what the task needs; leave out unrequested asides and suggestions.
## Overview
@@ -8,7 +8,7 @@ This is an AI API gateway/proxy built with Go. It aggregates 40+ upstream AI pro
## Tech Stack
- **Backend**: Go 1.26 for the root module and `tokenkit/`, Go 1.25.1 for `relaykit/` (see each module’s `go.mod`), Gin web framework, GORM v2 ORM
- **Backend**: Go 1.26 for the root module and `tokenkit/`, Go 1.25.1 for `relaykit/` and `pluginkit/` (see each module’s `go.mod`), Gin web framework, GORM v2 ORM
- **Frontend**: React 19, TypeScript, Rsbuild 2, TanStack Router/Query/Table, Zustand, Base UI, Tailwind CSS 4
- **Databases**: SQLite, MySQL, PostgreSQL for the primary database (all three must be supported); a separately configured log database also supports ClickHouse
- **Cache**: Redis (go-redis) + in-memory cache
@@ -25,7 +25,8 @@ This is an AI API gateway/proxy built with Go. It aggregates 40+ upstream AI pro
- Reward policy edits use whole minutes while persisted delays and historical payout timestamps retain exact seconds. Record each published referral mode change in the policy transaction with the saved version and authenticated actor. Import old transitions only from verifiable policy or cutover facts. Reward policy and withdrawal forms show amounts in the site's display currency, fall back to USD in Token mode, and map edits to integer wallet quota. Withdrawal payouts use the server's CNY quote at the site exchange rate.
- `relaykit/` is an independent Go module for protocol DTOs and conversions; transport, authentication, database access, and billing stay in the host.
- `tokenkit/` is an independent Go module for text and image token counting and estimation; request parsing, file loading, and billing stay in the host.
- JavaScript task plugins live in `plugins/tasks/`, run through `pkg/jsplugin/`, and integrate with host task polling and settlement.
- `pluginkit/` is an independent Go module for the plugin API v1 contract, its documents, the plugin utilities and the moejs execution layer; `pkg/jsplugin/` keeps the registry, routing and CLI and re-exports pluginkit's names.
- JavaScript task plugins live in `plugins/tasks/`, run through `pluginkit/` and `pkg/jsplugin/`, and integrate with host task polling and settlement.
- `web/` is the React frontend (see `web/AGENTS.md`); `electron/` is the desktop wrapper.
- Upstream monitoring uses `model/upstream_monitor*.go`, `service/upstream_monitor*.go`, `controller/upstream_monitor.go`, and `web/src/features/upstream-monitor/`. The browser executor is the separate `NovaLink-browser-bridge` project. Configure and record collection flows in the extension side panel; the dashboard only displays flows and issues tasks. Versioned extraction rules select requests and map response fields into account identity, balances, groups and model prices, with optional top-ups. Configure from the core data targets (account identity, balance and groups) and optional model-price/top-up targets, showing relevant response candidates first. Each selected request records its actual source page URLs, including safe view/pagination parameters. Compile missing source-page navigation into the browser plan while preserving recorded login, interaction and pagination steps; show a page-based collection summary before publishing. A task visits those pages, buffers multiple responses only in extension memory, extracts arrays/dictionaries and merges their fields, including models nested under each group via bounded `nested_array`/`child_root` rules and explicit `parent` field references, previews one standard JSON result, then submits that structured result once. Save rules on this server after the administrator previews them; subsequent collections run those mappings without model parsing or repeated field confirmation. Ordinary websites use simple explicit field mappings, including nested group/model lists, direct cross-response scalar sources and bounded unit conversions. When an upstream list has no billing discriminator, operators may explicitly configure a model mapping's `billing.rules`: at most eight rules, each with at most eight current-row numeric/existence conditions and an explicit token, request or unsupported outcome. Evaluate all rules and require exactly one match; missing or invalid numeric fields, unmatched rows and overlapping rules stay incomplete. Zero prices remain valid values, never implicit type evidence. Request outcomes select a captured per-call price path and optional positive scale; unsupported units require a note and never enter cost comparisons. These rules classify rows without dropping them, using local model prices or inferring units from field names. NewAPI and Sub2API use separate installed browser adapters with independently verified response schemas and pricing semantics; do not generalize their business joins, membership expansion, ratios or conditional-record rules into ordinary mappings. An extraction's optional `adapter` is either `newapi` or `sub2api`; dedicated adapters have selected browser request/page bindings and no field mappings. Missing `adapter` denotes ordinary mapping. Captured upstream quotes remain the primary procurement source. Official-reference estimation belongs exclusively to the server's cost-comparison layer: an account may explicitly opt into a versioned server-owned vendor catalog with reviewed model/group selections. Apply official prices and captured account group ratios only when comparing models whose purchase quotes are absent; never send catalog policies/prices to the executor, fill browser results, or write derived estimates into captured snapshots. Preserve captured zero prices, partial quotes, native rules, pending/conflicting quotes and known unsupported billing without fallback. Require exact or reviewed model correspondence, retain official source URLs/version/verification dates and identify the captured ratio snapshot on derived estimates. Keep estimate configuration on this site, separate from browser flow configuration; changing it can recompute comparison from existing valid captures without rewriting them. Core capture completeness requires actual selected responses, identity, balances and groups; absence of an optional model-price source may remain an explicit unavailable pricing status without discarding valid captured account data. Failed selected sources and invalid account/group facts remain incomplete. Never treat the catalog as proof that an upstream supports a model, silently enable estimates, or substitute local selling prices or generic billing hints. All other billing units and procurement prices come from captured upstream data or explicit operator unit choices. Preserve unsupported units explicitly. Keep site/account configuration, encrypted credentials, workflows, schedules, structured results and cost analysis on this server. The extension holds only transient task drafts and response inputs, never a local business store. Each browser executor startup authenticates its paired device, discovers server-owned running/awaiting-user task IDs via `/bridge/restart`, then confirms interruption for that exact list before polling for new work. Discovery never mutates/claims tasks, confirmation never affects different or queued tasks, and retries retain the exact old IDs. Do not rely on storage.session surviving Line truncated
@@ -90,10 +91,10 @@ Upstream procurement captures may include structured price tiers or a native bil
- Remove ineffective `omitempty` tags on non-pointer struct fields only after confirming the active JSON encoder preserves the same output. Do not change field types or omission behavior as part of a style cleanup; optional relay scalar fields must still follow the pointer rules below.
- Format modified Go files with `gofmt` and remove unused imports after these changes.
**relaykit and tokenkit module independence:** The `relaykit/` and `tokenkit/` Go modules MUST remain independently buildable.
**relaykit, tokenkit and pluginkit module independence:** The `relaykit/`, `tokenkit/` and `pluginkit/` Go modules MUST remain independently buildable.
- Code under `relaykit/` or `tokenkit/` MUST NOT import or depend on packages from the root `new-api` module, or rely on root-only configuration, generated files, or workspace wiring. `tokenkit/` also MUST NOT depend on `relaykit/`.
- Any change affecting `relaykit/`, `tokenkit/`, or their public APIs MUST be verified with `GOWORK=off go build ./...` inside that module; a successful root-module build is not sufficient.
- Code under `relaykit/`, `tokenkit/` or `pluginkit/` MUST NOT import or depend on packages from the root `new-api` module, or rely on root-only configuration, generated files, or workspace wiring. `tokenkit/` also MUST NOT depend on `relaykit/`; `pluginkit/` may. Host settings reach `pluginkit/` through `pluginkit.Configure`.
- Any change affecting `relaykit/`, `tokenkit/`, `pluginkit/`, or their public APIs MUST be verified with `GOWORK=off go build ./...` inside that module; a successful root-module build is not sufficient.
**JSON package:** In the root Go module, all JSON marshal/unmarshal operations MUST use the wrapper functions in `common/json.go`:
@@ -105,7 +106,7 @@ Upstream procurement captures may include structured price tiers or a native bil
Do NOT directly import or call `encoding/json` in business code. `json.RawMessage`, `json.Number`, and other type definitions from `encoding/json` may still be referenced as types, but actual marshal/unmarshal calls must go through `common.*`.
Inside `relaykit/`, use `kitutil.*` from `relaykit/relayconvert/kitutil/json.go`, never host `common`. Direct encoder calls belong only in codec implementations.
Inside `relaykit/`, use `kitutil.*` from `relaykit/relayconvert/kitutil/json.go`, never host `common`. Inside `pluginkit/`, use the functions in `pluginkit/json.go`. Direct encoder calls belong only in codec implementations.
**Database compatibility:** All database code MUST work with SQLite, MySQL >= 5.7.8, and PostgreSQL >= 9.6 simultaneously.
@@ -135,7 +136,7 @@ Inside `relaykit/`, use `kitutil.*` from `relaykit/relayconvert/kitutil/json.go`
**JavaScript task plugins (mandatory):**
- Before implementing, modifying, or reviewing JavaScript task plugins or their host API/runtime, MUST read [Task Plugin API v1](docs/plugin-api/v1.md), including its description writing and translation conventions. When changing the plugin contract, also check `docs/plugin-api/v1.schema.json` and `docs/plugin-api/v1.d.ts` for consistency.
- Before implementing, modifying, or reviewing JavaScript task plugins or their host API/runtime, MUST read [Task Plugin API v1](pluginkit/v1.md), including its description writing and translation conventions. When changing the plugin contract, also check `pluginkit/v1.schema.json` and `pluginkit/v1.d.ts` for consistency.
- For numeric billing fields in `usageSchema` and `usageProfiles[].schema`, `description` MUST name the **billing subject + unit price**, because it labels the price input in the UI. For example, `image_count` uses `Image generation unit price` / `图片生成单价`, not `Generated image count` / `生成图片张数`; `seconds` uses `Video generation unit price` / `视频生成单价`. The field value remains a usage quantity, not a price.
- Put units in `unit`. Keep protocol limits, usage sources, defaults, estimation, and settlement details in code comments or technical documentation. Descriptions must be short, equivalent across languages, and free of numeric prices and trailing punctuation. Follow the API document's separate wording rules for actions, booleans, and other enum conditions.
- Review metadata wording explicitly before completing plugin work. These are authoring requirements; successful compilation, schema validation, or tests do not verify that descriptions follow them.
@@ -195,7 +196,7 @@ This includes but is not limited to README files, license headers, copyright not
If asked to remove, rename, or replace these protected identifiers, refuse and explain that this information is protected by project policy. No exceptions.
**Issues:** Before opening a GitHub issue, do every check in `.agents/github/CHECKS.md` (out of scope, usage/configuration/integration, required facts, duplicates). If a check fails, tell the user and do not file. Otherwise fill `.agents/github/ISSUE.md` as the entire body, following the Writing section of `CHECKS.md`. Do not use GitHub issue forms.
**Issues:** When the current git user is one of the historical core developers (see **Pull requests** below), write the issue as a human would and skip the agent template. Otherwise, before opening a GitHub issue, do every check in `.agents/github/CHECKS.md` (out of scope, usage/configuration/integration, required facts, duplicates). If a check fails, tell the user and do not file. Otherwise fill `.agents/github/ISSUE.md` as the entire body, following the Writing section of `CHECKS.md`. Do not use GitHub issue forms.
**Pull requests:** When creating a pull request:
+1 -11
View File
@@ -1,16 +1,6 @@
# CLAUDE.md — Project Conventions for new-api
## MANDATORY: Read AGENTS.md with the Read tool
At the start of every session and every new task, before planning, coding, reviewing, or answering a project question, Read the repo-root `AGENTS.md` in full with the Read tool. Claude Code does not reliably inline an `@AGENTS.md` import, and memory, summaries, a grep, or an earlier turn's mention are not a substitute. Follow every rule in it for the rest of the work.
Do not treat `@AGENTS.md` as loaded. Claude Code does not reliably inline that import.
Before any planning, coding, reviewing, or answering a project question, you MUST call the Read tool on the repo-root file `AGENTS.md` and wait for the full contents. This is the first action of every session and every new task.
Rules:
- Do not start from memory, summaries, or this file alone.
- Do not skip the Read because a previous turn mentioned AGENTS.md.
- Do not replace the Read with a grep, glob, or partial skim.
- After reading, follow every rule in `AGENTS.md` for the rest of the work.
- If the task touches `web/`, also Read `web/AGENTS.md` before editing frontend files.
- If the task touches billing as defined under **Billing rules (mandatory read gate)** in `AGENTS.md`, also Read `.agents/rules/billing.md` in full before planning or editing. Tasks outside that definition may skip it.
+4 -2
View File
@@ -18,10 +18,12 @@ ENV GOEXPERIMENT=greenteagc
WORKDIR /build
ADD go.mod go.sum ./
# relaykit and tokenkit are local submodules referenced via replace; their
# go.mod files must be present for go mod download to resolve the main module graph.
# relaykit, tokenkit and pluginkit are local submodules referenced via replace;
# their go.mod files must be present for go mod download to resolve the main
# module graph.
ADD relaykit/go.mod ./relaykit/go.mod
ADD tokenkit/go.mod ./tokenkit/go.mod
ADD pluginkit/go.mod ./pluginkit/go.mod
RUN go mod download
COPY . .
+4 -2
View File
@@ -12,10 +12,12 @@ ENV GOEXPERIMENT=greenteagc
WORKDIR /build
ADD go.mod go.sum ./
# relaykit and tokenkit are local submodules referenced via replace; their
# go.mod files must be present for go mod download to resolve the main module graph.
# relaykit, tokenkit and pluginkit are local submodules referenced via replace;
# their go.mod files must be present for go mod download to resolve the main
# module graph.
ADD relaykit/go.mod ./relaykit/go.mod
ADD tokenkit/go.mod ./tokenkit/go.mod
ADD pluginkit/go.mod ./pluginkit/go.mod
RUN go mod download
COPY . .
+1 -1
View File
@@ -282,7 +282,7 @@ Open [http://localhost:5173](http://localhost:5173); the development server prox
| `relay/` | Upstream adapters and request routing |
| `service/`, `model/` | Business logic and persistence |
| [relaykit/](./relaykit/README.md) | Independently buildable Go module for protocol DTOs and conversions |
| [plugins/tasks/](./plugins/tasks/) | JavaScript task plugins; see [Task Plugin API v1](./docs/plugin-api/v1.md) for authoring and host boundaries |
| [plugins/tasks/](./plugins/tasks/) | JavaScript task plugins; see [Task Plugin API v1](./pluginkit/v1.md) for authoring and host boundaries |
| `web/` | Web console; see [frontend conventions](./web/AGENTS.md) |
| [electron/](./electron/README.md) | Desktop wrapper and packaging |
+1 -1
View File
@@ -263,7 +263,7 @@ Ouvrez [http://localhost:5173](http://localhost:5173) ; les requêtes API sont r
| `relay/` | Adaptateurs amont et routage des requêtes |
| `service/`, `model/` | Logique métier et persistance |
| [relaykit/](./relaykit/README.md) | Module Go autonome pour les DTO et conversions de protocoles |
| [plugins/tasks/](./plugins/tasks/) | Extensions de tâches JavaScript ; contrat et limites de l'hôte dans [Task Plugin API v1](./docs/plugin-api/v1.md) |
| [plugins/tasks/](./plugins/tasks/) | Extensions de tâches JavaScript ; contrat et limites de l'hôte dans [Task Plugin API v1](./pluginkit/v1.md) |
| `web/` | Console web ; voir les [conventions frontend](./web/AGENTS.md) |
| [electron/](./electron/README.md) | Application de bureau et packaging |
+1 -1
View File
@@ -263,7 +263,7 @@ bun run dev -- --port 5173
| `relay/` | 上流アダプターとリクエストのルーティング |
| `service/`、`model/` | ビジネスロジックと永続化 |
| [relaykit/](./relaykit/README.md) | プロトコル DTO と変換を提供する、独立してビルド可能な Go モジュール |
| [plugins/tasks/](./plugins/tasks/) | JavaScript タスクプラグイン。作成方法とホストの境界は [Task Plugin API v1](./docs/plugin-api/v1.md) を参照 |
| [plugins/tasks/](./plugins/tasks/) | JavaScript タスクプラグイン。作成方法とホストの境界は [Task Plugin API v1](./pluginkit/v1.md) を参照 |
| `web/` | Web 管理画面。[フロントエンドの規約](./web/AGENTS.md)を参照 |
| [electron/](./electron/README.md) | デスクトップアプリのラッパーとパッケージング |
+1 -1
View File
@@ -278,7 +278,7 @@ Open [http://localhost:5173](http://localhost:5173); the development server prox
| `relay/` | Upstream adapters and request routing |
| `service/`, `model/` | Business logic and persistence |
| [relaykit/](./relaykit/README.md) | Independently buildable Go module for protocol DTOs and conversions |
| [plugins/tasks/](./plugins/tasks/) | JavaScript task plugins; see [Task Plugin API v1](./docs/plugin-api/v1.md) for authoring and host boundaries |
| [plugins/tasks/](./plugins/tasks/) | JavaScript task plugins; see [Task Plugin API v1](./pluginkit/v1.md) for authoring and host boundaries |
| `web/` | Web console; see [frontend conventions](./web/AGENTS.md) |
| [electron/](./electron/README.md) | Desktop wrapper and packaging |
+1 -1
View File
@@ -278,7 +278,7 @@ bun run dev -- --port 5173
| `relay/` | 上游适配与请求调度 |
| `service/`、`model/` | 业务逻辑与持久化 |
| [relaykit/](./relaykit/README.md) | 可独立构建的协议 DTO 与转换 Go 模块 |
| [plugins/tasks/](./plugins/tasks/) | JavaScript 任务插件;编写方式与宿主边界见 [Task Plugin API v1](./docs/plugin-api/v1.md) |
| [plugins/tasks/](./plugins/tasks/) | JavaScript 任务插件;编写方式与宿主边界见 [Task Plugin API v1](./pluginkit/v1.md) |
| `web/` | Web 控制台,参阅[前端开发约定](./web/AGENTS.md) |
| [electron/](./electron/README.md) | 桌面封装与打包 |
+1 -1
View File
@@ -262,7 +262,7 @@ bun run dev -- --port 5173
| `relay/` | 上游介接與請求調度 |
| `service/`、`model/` | 業務邏輯與持久化 |
| [relaykit/](./relaykit/README.md) | 可獨立建置的協定 DTO 與轉換 Go 模組 |
| [plugins/tasks/](./plugins/tasks/) | JavaScript 任務外掛;編寫方式與宿主邊界見 [Task Plugin API v1](./docs/plugin-api/v1.md) |
| [plugins/tasks/](./plugins/tasks/) | JavaScript 任務外掛;編寫方式與宿主邊界見 [Task Plugin API v1](./pluginkit/v1.md) |
| `web/` | Web 控制台,參閱[前端開發約定](./web/AGENTS.md) |
| [electron/](./electron/README.md) | 桌面封裝與打包 |
+1
View File
@@ -525,6 +525,7 @@
"failed to invalidate tokens cache for user %d: %s": "清除用户 %d 的令牌缓存失败: %s",
"failed to invalidate user cache after hard deleting user %d: %v": "永久删除用户 %d 后清除用户缓存失败: %v",
"failed to load custom OAuth providers: %s": "加载自定义 OAuth 提供商失败: %s",
"failed to load model usage for the model square: %s": "加载模型广场的模型用量失败: %s",
"failed to load options from database: %s": "从数据库加载设置失败: %s",
"failed to load tool prices, using hardcoded fallbacks: %s": "加载工具价格失败,将使用硬编码兜底: %s",
"failed to marshal gemini response: %s": "序列化 Gemini 响应失败: %s",
+23 -1
View File
@@ -1,6 +1,7 @@
package common
import (
"crypto/subtle"
"strings"
"sync"
"time"
@@ -52,7 +53,28 @@ func VerifyCodeWithKey(key string, code string, purpose string) bool {
if !okay || int(now.Sub(value.time).Seconds()) >= VerificationValidMinutes*60 {
return false
}
return code == value.code
return subtle.ConstantTimeCompare([]byte(code), []byte(value.code)) == 1
}
// ConsumeCodeWithKey atomically verifies and removes a single-use code so
// concurrent requests cannot replay the same token.
func ConsumeCodeWithKey(key string, code string, purpose string) bool {
verificationMutex.Lock()
defer verificationMutex.Unlock()
mapKey := purpose + key
value, okay := verificationMap[mapKey]
now := time.Now()
if !okay || int(now.Sub(value.time).Seconds()) >= VerificationValidMinutes*60 {
if okay {
delete(verificationMap, mapKey)
}
return false
}
if subtle.ConstantTimeCompare([]byte(code), []byte(value.code)) != 1 {
return false
}
delete(verificationMap, mapKey)
return true
}
func DeleteKey(key string, purpose string) {
+7 -6
View File
@@ -67,15 +67,16 @@ var providerTestEndpoints = []constant.EndpointType{
}
// providerTestEndpoint returns the endpoint a task plugin channel test uses
// for model instead of requestPath, which meta's relay routes do not serve.
// ok is false when they serve requestPath or none of the test endpoints.
func providerTestEndpoint(meta jsplugin.Meta, requestPath, model string) (endpoint constant.EndpointType, ok bool) {
if _, served := meta.RelayRoute(requestPath, model); served {
// for model instead of requestPath, which meta's relay routes that are on for
// the channel (toggles are its plugin_routes) do not serve. ok is false when
// they serve requestPath or none of the test endpoints.
func providerTestEndpoint(meta jsplugin.Meta, toggles map[string]bool, requestPath, model string) (endpoint constant.EndpointType, ok bool) {
if _, served := meta.ChannelRelayRoute(toggles, requestPath, model); served {
return "", false
}
for _, endpoint := range providerTestEndpoints {
info, _ := common.GetDefaultEndpointInfo(endpoint)
if _, served := meta.RelayRoute(strings.ReplaceAll(info.Path, "{model}", model), model); served {
if _, served := meta.ChannelRelayRoute(toggles, strings.ReplaceAll(info.Path, "{model}", model), model); served {
return endpoint, true
}
}
@@ -181,7 +182,7 @@ func testChannel(ctx context.Context, channel *model.Channel, testUserID int, te
// A task plugin channel tests on an endpoint its relay routes serve for the
// model: the default one when they serve it, else the first they serve.
if providerChannel && endpointType == "" {
if endpoint, ok := providerTestEndpoint(plugin.Meta, requestPath, testModel); ok {
if endpoint, ok := providerTestEndpoint(plugin.Meta, channel.GetOtherSettings().PluginRoutes, requestPath, testModel); ok {
endpointType = string(endpoint)
endpointInfo, _ := common.GetDefaultEndpointInfo(endpoint)
requestPath = strings.ReplaceAll(endpointInfo.Path, "{model}", testModel)
+6 -2
View File
@@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
"maps"
"net/http"
"slices"
"strconv"
@@ -559,7 +560,8 @@ const maxTaskExtendPluginKeys = 32
// normalizePluginConfig validates the plugin config in the channel's settings
// and stores it as the schema reads it: declared properties only, defaults
// left to the read.
// left to the read. It keeps the plugin_routes entries that switch a relay
// route of the plugin away from its default.
func normalizePluginConfig(channel *model.Channel, plugin *jsplugin.LoadedPlugin) error {
otherSettings := channel.GetOtherSettings()
config, err := plugin.ValidateChannelConfig(otherSettings.PluginConfig)
@@ -569,8 +571,10 @@ func normalizePluginConfig(channel *model.Channel, plugin *jsplugin.LoadedPlugin
if plugin.Meta.ChannelConfig == nil || string(config) == "{}" {
config = nil
}
if !bytes.Equal(config, otherSettings.PluginConfig) {
routes := plugin.Meta.NormalizeRouteToggles(otherSettings.PluginRoutes)
if !bytes.Equal(config, otherSettings.PluginConfig) || !maps.Equal(routes, otherSettings.PluginRoutes) {
otherSettings.PluginConfig = config
otherSettings.PluginRoutes = routes
channel.SetOtherSettings(otherSettings)
}
return nil
+17 -2
View File
@@ -28,7 +28,10 @@ const (
// configPluginSource declares a channel config and checks typed-in keys.
configPluginSource = `
export const meta = {apiVersion: 1, key: "%KEY%", name: "Config", version: "1.0.0", author: {name: "Test"},
relay: [{incoming_path: "/v1/chat/completions", upstream_path: "/chat"}],
relay: [
{incoming_path: "/v1/chat/completions", upstream_path: "/chat"},
{incoming_path: "/v1/responses", upstream_path: "/chat", converter: "openai_responses_to_openai_chat_completions", default_enabled: false},
],
channelConfig: {type: "object", properties: {
region: {type: "string", title: {en: "Region"}, enum: ["us", "eu"], default: "us"},
timeout: {type: "integer", title: {en: "Timeout"}, minimum: 1, default: 30},
@@ -173,6 +176,18 @@ func TestGapsChannelConfigAndKeyCheckOnSave(t *testing.T) {
require.True(t, response.Success, raw)
assert.JSONEq(t, `{"region":"eu"}`, string(storedGapsChannel(t, channel.Id).GetOtherSettings().PluginConfig))
})
t.Run("update keeps only route switches that differ from the defaults", func(t *testing.T) {
channel := insertPluginChannel(t, "gaps-config", "https://vendor.example", "good-1", false)
settings := `{\"plugin_routes\":{\"/v1/responses\":true,\"/v1/chat/completions\":true,\"/v1/unknown\":false}}`
response, raw := callChannelAPI(t, UpdateChannel, http.MethodPut, "/api/channel", fmt.Sprintf(`{"id":%d,"settings":"%s"}`, channel.Id, settings))
require.True(t, response.Success, raw)
assert.Equal(t, map[string]bool{"/v1/responses": true}, storedGapsChannel(t, channel.Id).GetOtherSettings().PluginRoutes)
response, raw = callChannelAPI(t, UpdateChannel, http.MethodPut, "/api/channel", fmt.Sprintf(`{"id":%d,"settings":"{\"plugin_routes\":{\"/v1/responses\":false}}"}`, channel.Id))
require.True(t, response.Success, raw)
assert.Nil(t, storedGapsChannel(t, channel.Id).GetOtherSettings().PluginRoutes, "switching back to the default stores nothing")
})
}
// balanceServer answers the balance request of each key with the reply set
@@ -445,7 +460,7 @@ func TestGapsProviderTestEndpoint(t *testing.T) {
{"no test endpoint is served", routes(route("/v1/videos")), "/v1/chat/completions", "m", "", false},
} {
t.Run(tc.name, func(t *testing.T) {
endpoint, ok := providerTestEndpoint(tc.meta, tc.requestPath, tc.model)
endpoint, ok := providerTestEndpoint(tc.meta, nil, tc.requestPath, tc.model)
assert.Equal(t, tc.wantOK, ok)
assert.Equal(t, tc.wantEndpoint, endpoint)
})
+1 -1
View File
@@ -528,7 +528,7 @@ func fetchProviderPluginUpstreamModelIDs(channel *model.Channel, plugin *jsplugi
return nil, err
}
settings := channel.GetOtherSettings()
settings.AdvancedCustom = plugin.Meta.ChannelRelayConfig(plugin.ChannelConfigFor(settings.PluginConfig))
settings.AdvancedCustom = plugin.Meta.ChannelRelayConfig(plugin.ChannelConfigFor(settings.PluginConfig), settings.PluginRoutes)
info := &relaycommon.RelayInfo{
RelayFormat: types.RelayFormatOpenAI,
RelayMode: relayconstant.RelayModeUnknown,
+156
View File
@@ -5,12 +5,16 @@ import (
"io"
"net/http"
"net/http/httptest"
"net/url"
"regexp"
"strconv"
"strings"
"testing"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/i18n"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/setting/system_setting"
"github.com/gin-gonic/gin"
"github.com/glebarez/sqlite"
"github.com/stretchr/testify/assert"
@@ -249,3 +253,155 @@ func TestEmailKeyStatusIsDerivedAndReadOnly(t *testing.T) {
assert.Contains(t, response.Body.String(), `"success":false`)
assert.Contains(t, response.Body.String(), "read-only")
}
func TestPasswordResetUsesStoredEmailAndSingleUseToken(t *testing.T) {
require.NoError(t, i18n.Init())
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, db.AutoMigrate(&model.User{}, &model.UserSession{}))
previousDB, previousRedis, previousServerAddress, previousValidMinutes := model.DB, common.RedisEnabled, system_setting.ServerAddress, common.VerificationValidMinutes
model.DB, common.RedisEnabled, system_setting.ServerAddress = db, false, "https://gateway.example"
t.Cleanup(func() {
model.DB = previousDB
common.RedisEnabled = previousRedis
system_setting.ServerAddress = previousServerAddress
common.VerificationValidMinutes = previousValidMinutes
common.DeleteKey("victim+tag@example.com", common.PasswordResetPurpose)
common.DeleteKey("victim+tag@exámple.com", common.PasswordResetPurpose)
})
originalHash, err := common.HashAccountPassword("OriginalPass123!")
require.NoError(t, err)
victim := model.User{
Username: "victim",
Password: originalHash,
Email: "Victim+Tag@Example.com",
AffCode: "vic1",
Status: common.UserStatusEnabled,
AuthVersion: 1,
}
require.NoError(t, db.Create(&victim).Error)
// Also ensure a look-alike email stored alongside does not confuse lookup.
require.NoError(t, db.Create(&model.User{
Username: "other",
Password: originalHash,
Email: "victim+tag@exàmple.com",
AffCode: "oth1",
Status: common.UserStatusEnabled,
}).Error)
type deliveredEmail struct {
To []string
HTML string
}
var delivered []deliveredEmail
failDelivery := false
var replacementCode string
configureEmailDelivery(t, map[string]string{
"EmailProvider": "resend",
"ResendApiKey": "test-key",
"ResendFrom": "sender@example.com",
})
http.DefaultTransport = emailHTTPTransport(func(request *http.Request) (*http.Response, error) {
var body struct {
To []string `json:"to"`
HTML string `json:"html"`
}
require.NoError(t, common.DecodeJson(request.Body, &body))
delivered = append(delivered, deliveredEmail{To: body.To, HTML: body.HTML})
if failDelivery {
if replacementCode != "" {
common.RegisterVerificationCodeWithKey(model.NormalizeEmail(victim.Email), replacementCode, common.PasswordResetPurpose)
}
return &http.Response{StatusCode: http.StatusInternalServerError, Body: io.NopCloser(strings.NewReader(`{"message":"smtp down"}`)), Header: make(http.Header)}, nil
}
return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(`{"id":"email-1"}`)), Header: make(http.Header)}, nil
})
tokenRe := regexp.MustCompile(`https://gateway\.example/user/reset\?email=([^&'"<\s]+)&token=([0-9a-f]+)`)
// 1. Accent look-alike address does not match victim and sends no mail.
resp := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(resp)
ctx.Request = httptest.NewRequest(http.MethodGet, "/api/reset_password?email="+url.QueryEscape("victim+tag@exámple.com"), nil)
SendPasswordResetEmail(ctx)
require.Equal(t, http.StatusOK, resp.Code)
assert.Contains(t, resp.Body.String(), `"success":true`)
assert.Empty(t, delivered)
// 2. Preserve the mailbox on file for delivery, but use the normalized key in the URL.
resp = httptest.NewRecorder()
ctx, _ = gin.CreateTestContext(resp)
ctx.Request = httptest.NewRequest(http.MethodGet, "/api/reset_password?email="+url.QueryEscape("VICTIM+TAG@EXAMPLE.COM"), nil)
SendPasswordResetEmail(ctx)
require.Equal(t, http.StatusOK, resp.Code)
require.Len(t, delivered, 1)
assert.Equal(t, []string{victim.Email}, delivered[0].To)
matches := tokenRe.FindStringSubmatch(delivered[0].HTML)
require.Len(t, matches, 3)
assert.Equal(t, url.QueryEscape("victim+tag@example.com"), matches[1])
token := matches[2]
// 3. Redeeming with look-alike email fails even with the real token.
resp = httptest.NewRecorder()
ctx, _ = gin.CreateTestContext(resp)
ctx.Request = httptest.NewRequest(http.MethodPost, "/api/user/reset", strings.NewReader(`{"email":"victim+tag@exámple.com","token":"`+token+`"}`))
ResetPassword(ctx)
assert.Contains(t, resp.Body.String(), `"success":false`)
// 4. Redeeming once with the real email resets the password and rotates auth version.
resp = httptest.NewRecorder()
ctx, _ = gin.CreateTestContext(resp)
ctx.Request = httptest.NewRequest(http.MethodPost, "/api/user/reset", strings.NewReader(`{"email":"Victim+Tag@Example.com","token":"`+token+`"}`))
ResetPassword(ctx)
require.Equal(t, http.StatusOK, resp.Code)
var resetResp struct {
Success bool `json:"success"`
Data string `json:"data"`
}
require.NoError(t, common.Unmarshal(resp.Body.Bytes(), &resetResp))
require.True(t, resetResp.Success)
require.NotEmpty(t, resetResp.Data)
var updated model.User
require.NoError(t, db.First(&updated, victim.Id).Error)
assert.True(t, common.ValidatePasswordAndHash(resetResp.Data, updated.Password))
assert.False(t, common.ValidatePasswordAndHash("OriginalPass123!", updated.Password))
assert.Equal(t, int64(2), updated.AuthVersion)
// 5. Replaying the same token is rejected.
resp = httptest.NewRecorder()
ctx, _ = gin.CreateTestContext(resp)
ctx.Request = httptest.NewRequest(http.MethodPost, "/api/user/reset", strings.NewReader(`{"email":"victim+tag@example.com","token":"`+token+`"}`))
ResetPassword(ctx)
assert.Contains(t, resp.Body.String(), `"success":false`)
// 6. Failed delivery revokes the generated token so no undelivered code remains active.
failDelivery = true
resp = httptest.NewRecorder()
ctx, _ = gin.CreateTestContext(resp)
ctx.Request = httptest.NewRequest(http.MethodGet, "/api/reset_password?email="+url.QueryEscape("victim+tag@example.com"), nil)
SendPasswordResetEmail(ctx)
require.Len(t, delivered, 2)
failedMatches := tokenRe.FindStringSubmatch(delivered[1].HTML)
require.Len(t, failedMatches, 3)
assert.False(t, common.VerifyCodeWithKey("victim+tag@example.com", failedMatches[2], common.PasswordResetPurpose))
// A late delivery failure must not revoke the code issued by a newer request.
replacementCode = common.GenerateVerificationCode(0)
ctx, _ = gin.CreateTestContext(httptest.NewRecorder())
ctx.Request = httptest.NewRequest(http.MethodGet, "/api/reset_password?email="+url.QueryEscape(victim.Email), nil)
SendPasswordResetEmail(ctx)
require.Len(t, delivered, 3)
assert.True(t, common.ConsumeCodeWithKey(model.NormalizeEmail(victim.Email), replacementCode, common.PasswordResetPurpose))
// 7. Expired token is rejected and cleared.
failDelivery = false
common.VerificationValidMinutes = 0
common.RegisterVerificationCodeWithKey("victim+tag@example.com", "expired-token-value", common.PasswordResetPurpose)
resp = httptest.NewRecorder()
ctx, _ = gin.CreateTestContext(resp)
ctx.Request = httptest.NewRequest(http.MethodPost, "/api/user/reset", strings.NewReader(`{"email":"victim+tag@example.com","token":"expired-token-value"}`))
ResetPassword(ctx)
assert.Contains(t, resp.Body.String(), `"success":false`)
}
+4 -2
View File
@@ -26,8 +26,10 @@ func GetGroups(c *gin.Context) {
func GetUserGroups(c *gin.Context) {
usableGroups := make(map[string]map[string]any)
userGroup := ""
userId := c.GetInt("id")
userGroup, _ = model.GetUserGroup(userId, false)
// /api/user/groups is public, so anonymous requests have no user id and use the public groups
if userId := c.GetInt("id"); userId > 0 {
userGroup, _ = model.GetUserGroup(userId, false)
}
userUsableGroups := service.GetUserUsableGroups(userGroup)
for groupName, _ := range ratio_setting.GetGroupRatioCopy() {
// UserUsableGroups contains the groups that the user can use
+31 -25
View File
@@ -1,10 +1,11 @@
package controller
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
@@ -258,27 +259,33 @@ func SendPasswordResetEmail(c *gin.Context) {
return
}
if user, err := model.GetUniqueUserByEmail(email); err == nil {
code := common.GenerateVerificationCode(0)
common.RegisterVerificationCodeWithKey(email, code, common.PasswordResetPurpose)
link := fmt.Sprintf("%s/user/reset?email=%s&token=%s", system_setting.ServerAddress, email, code)
lang := user.GetSetting().Language
if lang == "" {
lang = i18n.StatedLang(c)
}
systemName := map[string]any{"SystemName": common.SystemName}
linkParams := map[string]any{"Link": link}
subject := i18n.Translate(lang, i18n.MsgEmailPasswordResetSubject, systemName)
content := fmt.Sprintf("<p>%s</p>"+
"<p>%s</p>"+
"<p>%s </p>"+
"<p>%s</p>",
i18n.Translate(lang, i18n.MsgEmailPasswordResetGreeting, systemName),
i18n.Translate(lang, i18n.MsgEmailPasswordResetLink, linkParams),
i18n.Translate(lang, i18n.MsgEmailPasswordResetLinkFallback, linkParams),
i18n.Translate(lang, i18n.MsgEmailPasswordResetValidity, map[string]any{"Minutes": common.VerificationValidMinutes}))
err := common.SendEmail(subject, email, content)
if err != nil {
logger.LogError(c.Request.Context(), common.LogText("failed to send password reset email to %s: %s", email, err.Error()))
storedEmail := model.NormalizeEmail(user.Email)
if storedEmail != "" && storedEmail == email {
code := common.GenerateVerificationCode(0)
common.RegisterVerificationCodeWithKey(storedEmail, code, common.PasswordResetPurpose)
link := fmt.Sprintf("%s/user/reset?email=%s&token=%s", system_setting.ServerAddress, url.QueryEscape(storedEmail), url.QueryEscape(code))
lang := user.GetSetting().Language
if lang == "" {
lang = i18n.StatedLang(c)
}
systemName := map[string]any{"SystemName": common.SystemName}
linkParams := map[string]any{"Link": link}
subject := i18n.Translate(lang, i18n.MsgEmailPasswordResetSubject, systemName)
content := fmt.Sprintf("<p>%s</p>"+
"<p>%s</p>"+
"<p>%s </p>"+
"<p>%s</p>",
i18n.Translate(lang, i18n.MsgEmailPasswordResetGreeting, systemName),
i18n.Translate(lang, i18n.MsgEmailPasswordResetLink, linkParams),
i18n.Translate(lang, i18n.MsgEmailPasswordResetLinkFallback, linkParams),
i18n.Translate(lang, i18n.MsgEmailPasswordResetValidity, map[string]any{"Minutes": common.VerificationValidMinutes}))
// Keep the mailbox spelling on file for delivery, including legacy mixed-case local parts.
err := common.SendEmail(subject, strings.TrimSpace(user.Email), content)
if err != nil {
// A newer delivery may already have replaced this code.
common.ConsumeCodeWithKey(storedEmail, code, common.PasswordResetPurpose)
logger.LogError(c.Request.Context(), common.LogText("failed to send password reset email to %s: %s", storedEmail, err.Error()))
}
}
} else if err != nil && !errors.Is(err, model.ErrEmailNotFound) {
logger.LogWarn(c.Request.Context(), common.LogText("skip password reset email for %s: %s", email, err.Error()))
@@ -296,7 +303,7 @@ type PasswordResetRequest struct {
func ResetPassword(c *gin.Context) {
var req PasswordResetRequest
err := json.NewDecoder(c.Request.Body).Decode(&req)
err := common.DecodeJson(c.Request.Body, &req)
if err != nil {
common.ApiError(c, err)
return
@@ -306,7 +313,7 @@ func ResetPassword(c *gin.Context) {
common.ApiErrorT(c, "Invalid parameters")
return
}
if !common.VerifyCodeWithKey(req.Email, req.Token, common.PasswordResetPurpose) {
if !common.ConsumeCodeWithKey(req.Email, req.Token, common.PasswordResetPurpose) {
common.ApiErrorT(c, "Password reset link is invalid or has expired")
return
}
@@ -320,7 +327,6 @@ func ResetPassword(c *gin.Context) {
common.ApiError(c, err)
return
}
common.DeleteKey(req.Email, common.PasswordResetPurpose)
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "",
+91
View File
@@ -261,6 +261,97 @@ func TestModelSquareGroupVisibility(t *testing.T) {
}
}
func TestModelSquareOrderFollowsSavedSetting(t *testing.T) {
originalGroups := setting.UserUsableGroups2JSONString()
originalOrder := *operation_setting.GetModelSquareSetting()
originalDataExport := common.DataExportEnabled
t.Cleanup(func() {
require.NoError(t, setting.UpdateUserUsableGroupsByJSONString(originalGroups))
*operation_setting.GetModelSquareSetting() = originalOrder
common.DataExportEnabled = originalDataExport
})
for _, dialect := range []struct{ kind, env string }{{"sqlite", ""}, {"mysql", "TEST_MYSQL_DSN"}, {"postgres", "TEST_POSTGRES_DSN"}} {
t.Run(dialect.kind, func(t *testing.T) {
if dialect.env != "" && os.Getenv(dialect.env) == "" {
t.Skip("set " + dialect.env + " to run this database")
}
db := modelManagementDB(t, dialect.kind, os.Getenv(dialect.env))
// The service caches usage across databases, so usage ordering is
// covered in the service tests and the query is checked directly below.
common.DataExportEnabled = false
*operation_setting.GetModelSquareSetting() = operation_setting.ModelSquareSetting{SortMode: "manual", SortMetric: "tokens", SortDays: 7, SortModels: []string{}}
require.NoError(t, setting.UpdateUserUsableGroupsByJSONString(`{"default":"Public"}`))
vendor := model.Vendor{Name: "Acme", Icon: "Acme.Color"}
require.NoError(t, db.Create(&vendor).Error)
require.NoError(t, db.Create(&model.Model{ModelName: "vip-only", Icon: "Vip.Color", VendorID: vendor.Id, Status: 1}).Error)
require.NoError(t, db.Create(&[]model.Ability{
{Model: "alpha", Group: "default", ChannelId: 1, Enabled: true},
{Model: "gamma", Group: "default", ChannelId: 1, Enabled: true},
{Model: "vip-only", Group: "vip", ChannelId: 1, Enabled: true},
}).Error)
model.InvalidatePricingCache()
t.Cleanup(model.InvalidatePricingCache)
manual := []string{"gamma", "alpha"}
for _, step := range []struct {
key, value string
rejected bool
want []string
}{
{want: []string{}},
{key: "model_square_setting.sort_models", value: `["gamma","vip-only","alpha","gamma"]`, want: manual},
{key: "model_square_setting.sort_mode", value: "random", rejected: true, want: manual},
{key: "model_square_setting.sort_metric", value: "cost", rejected: true, want: manual},
{key: "model_square_setting.sort_days", value: "3", rejected: true, want: manual},
{key: "model_square_setting.sort_models", value: `"gamma"`, rejected: true, want: manual},
} {
if step.key != "" {
err := model.UpdateOption(step.key, step.value)
if step.rejected {
require.Error(t, err, step.key)
} else {
require.NoError(t, err, step.key)
}
}
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Request = httptest.NewRequest(http.MethodGet, "/api/pricing", nil)
GetPricing(ctx)
require.Equal(t, http.StatusOK, recorder.Code)
var response struct {
ModelOrder map[string][]string `json:"model_order"`
}
require.NoError(t, common.Unmarshal(recorder.Body.Bytes(), &response))
assert.Equal(t, map[string][]string{"recommended": step.want, "requests": {}, "tokens": {}}, response.ModelOrder, step.key)
}
// The admin preview offers the models of every group.
assert.ElementsMatch(t, []modelSquareUsage{
{ModelName: "alpha"},
{ModelName: "gamma"},
{ModelName: "vip-only", Icon: "Vip.Color", VendorName: "Acme", VendorIcon: "Acme.Color"},
}, modelSquareData[[]modelSquareUsage](t, GetModelSquareUsage, "/api/models/square_usage?days=7", ""))
require.NoError(t, db.AutoMigrate(&model.QuotaData{}))
now := time.Now().Unix()
require.NoError(t, db.Create(&[]model.QuotaData{
{UserID: 1, Username: "a", ModelName: "alpha", CreatedAt: now - 3600, Count: 3, TokenUsed: 100},
{UserID: 2, Username: "b", ModelName: "alpha", CreatedAt: now - 7200, Count: 2},
{UserID: 1, Username: "a", ModelName: "vip-only", CreatedAt: now - 3600, Count: 1},
{UserID: 1, Username: "a", ModelName: "gamma", CreatedAt: now - 8*24*3600, Count: 9, TokenUsed: 900},
{UserID: 1, Username: "a", ModelName: "", CreatedAt: now - 3600, Count: 4, TokenUsed: 40},
}).Error)
totals, err := model.GetModelUsageTotals(now-7*24*3600, now)
require.NoError(t, err)
assert.ElementsMatch(t, []model.ModelUsageTotal{
{ModelName: "alpha", Requests: 5, Tokens: 100},
{ModelName: "vip-only", Requests: 1},
}, totals)
})
}
}
func decodeUserModelsResponse(t *testing.T, recorder *httptest.ResponseRecorder) []string {
t.Helper()
+15 -5
View File
@@ -1736,6 +1736,7 @@ func TestServeTaskPluginImageProtocolAppliesChannelOverrides(t *testing.T) {
prompts []string
multipart bool
async bool
inlineImage string
wantParameters map[string]any
wantB64 bool
wantCount float64
@@ -1764,6 +1765,7 @@ func TestServeTaskPluginImageProtocolAppliesChannelOverrides(t *testing.T) {
{name: "return error stops submission", overrides: []string{`{"operations":[{"mode":"return_error","value":{"message":"blocked by image rule","status_code":429,"code":"image_rule_blocked"}}]}`}, wantStatus: 429, wantCode: "image_rule_blocked", wantNoRetry: true},
{name: "alibaba/no overrides preserves URL", pluginKey: "alibaba", overrides: []string{`{}`}},
{name: "alibaba/client Base64 without overrides", pluginKey: "alibaba", clientFormat: "b64_json", overrides: []string{`{}`}, wantB64: true},
{name: "alibaba/large inline image", pluginKey: "alibaba", clientFormat: "b64_json", overrides: []string{`{}`}, inlineImage: strings.Repeat("QUFB", (1<<18)+1)},
{name: "alibaba/Seedream condition does not match", pluginKey: "alibaba", overrides: []string{force}},
{name: "alibaba/original alias condition", pluginKey: "alibaba", model: "bailian-image", overrides: []string{bailian}, wantB64: true},
{name: "alibaba/mapped model condition", pluginKey: "alibaba", model: "bailian-image", overrides: []string{strings.Replace(strings.Replace(force, `"original_model"`, `"model"`, 1), `"value":"seedream"`, `"value":"qwen-image"`, 1)}, wantB64: true},
@@ -1901,6 +1903,9 @@ func TestServeTaskPluginImageProtocolAppliesChannelOverrides(t *testing.T) {
task.SetData(map[string]any{"data": []any{map[string]any{"url": "https://cdn.example/image.png"}}})
if pluginKey == "alibaba" {
result := `{"request_id":"request_image","output":{"choices":[{"message":{"content":[{"image":"https://cdn.example/image.png"}]}}]},"usage":{"output_image_count":1}}`
if tc.inlineImage != "" {
result = strings.Replace(result, "https://cdn.example/image.png", "data:image/png;base64,"+tc.inlineImage, 1)
}
if tc.async {
result = `{"output":{"task_id":"upstream_image","task_status":"PENDING"}}`
}
@@ -1970,13 +1975,15 @@ func TestServeTaskPluginImageProtocolAppliesChannelOverrides(t *testing.T) {
}
require.NoError(t, common.Unmarshal(recorder.Body.Bytes(), &response))
require.Len(t, response.Data, 1)
wantB64, wantDownloads := "", 0
if tc.wantB64 {
wantURL, wantB64, wantDownloads := "https://cdn.example/image.png", "", 0
if tc.inlineImage != "" {
wantURL, wantB64 = "", tc.inlineImage
} else if tc.wantB64 {
wantB64, wantDownloads = "QUFB", 1
}
assert.Equal(t, wantDownloads, downloads)
assert.Equal(t, wantB64, response.Data[0].B64)
assert.Equal(t, "https://cdn.example/image.png", response.Data[0].URL)
assert.Equal(t, wantURL, response.Data[0].URL)
if pluginKey == "alibaba" {
assert.Contains(t, response.Metadata, "output", "vendor metadata remains available with Base64 output")
usage, ok := response.Metadata["usage"].(map[string]any)
@@ -2100,6 +2107,7 @@ func TestServeTaskPluginImageProtocolSubmissionErrorUsesOpenAIEnvelope(t *testin
// cancel that call or refund a durable result: the task row, its settlement
// and its consume log stay, and nothing is written to the closed connection.
func TestServeTaskPluginImageProtocolDisconnectDuringSubmissionKeepsDurableSettlement(t *testing.T) {
image := "data:image/png;base64," + strings.Repeat("QUFB", (1<<18)+1)
events := make([]string, 0, 3)
database := setupTaskSubmissionDatabase(t, true, &events)
previousLogConsumeEnabled := common.LogConsumeEnabled
@@ -2139,8 +2147,8 @@ func TestServeTaskPluginImageProtocolDisconnectDuringSubmissionKeepsDurableSettl
UpstreamTaskID: "task_image_disconnect",
Platform: constant.TaskPlatform(pinned.Plugin.Meta.Key),
Quota: 7,
TaskData: []byte(`{"images":["https://cdn.example/1.png"]}`),
Immediate: &relaycommon.TaskInfo{Status: model.TaskStatusSuccess, Progress: "100%"},
TaskData: []byte(`{"images":["` + image + `"]}`),
Immediate: &relaycommon.TaskInfo{Status: model.TaskStatusSuccess, Progress: "100%", Url: image},
}, nil
})
}
@@ -2169,6 +2177,8 @@ func TestServeTaskPluginImageProtocolDisconnectDuringSubmissionKeepsDurableSettl
assert.Equal(t, model.TaskStatus(model.TaskStatusSuccess), persisted.Status)
assert.Equal(t, 7, persisted.Quota)
assert.True(t, persisted.PrivateData.ResultDiscarded, "the inline image result is not retained after the barrier")
assert.Empty(t, persisted.Data)
assert.Empty(t, persisted.PrivateData.ResultURL)
assert.Zero(t, polls, "an immediate result is never polled")
assert.False(t, c.Writer.Written())
assert.Empty(t, recorder.Body.String())
+53
View File
@@ -1,10 +1,14 @@
package controller
import (
"net/http"
"strconv"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/setting/operation_setting"
"github.com/QuantumNous/new-api/setting/ratio_setting"
"github.com/gin-gonic/gin"
@@ -60,10 +64,59 @@ func GetPricing(c *gin.Context) {
"usable_group": usableGroup,
"supported_endpoint": model.GetSupportedEndpointMap(),
"auto_groups": service.GetUserAutoGroup(userGroup),
"model_order": service.BuildModelSquareOrder(pricing),
"pricing_version": "a42d372ccf0b5dd13ecf71203521f9d2",
})
}
type modelSquareUsage struct {
ModelName string `json:"model_name"`
Icon string `json:"icon,omitempty"`
VendorName string `json:"vendor_name,omitempty"`
VendorIcon string `json:"vendor_icon,omitempty"`
Requests int64 `json:"requests"`
Tokens int64 `json:"tokens"`
}
// GetModelSquareUsage lists every model of the model square, whichever group
// can see it, with its usage for the order preview.
func GetModelSquareUsage(c *gin.Context) {
days := c.DefaultQuery("days", "7")
if err := operation_setting.ValidateModelSquareOption("model_square_setting.sort_days", days); err != nil {
common.ApiErrorStatus(c, http.StatusBadRequest, err)
return
}
dayCount, _ := strconv.Atoi(days)
totals, err := service.GetModelUsageTotals(dayCount)
if err != nil {
common.ApiError(c, err)
return
}
usage := make(map[string]model.ModelUsageTotal, len(totals))
for _, total := range totals {
usage[total.ModelName] = total
}
pricing := model.GetPricing()
vendors := make(map[int]model.PricingVendor)
for _, vendor := range model.GetVendors() {
vendors[vendor.ID] = vendor
}
rows := make([]modelSquareUsage, 0, len(pricing))
for _, item := range pricing {
vendor := vendors[item.VendorID]
total := usage[item.ModelName]
rows = append(rows, modelSquareUsage{
ModelName: item.ModelName,
Icon: item.Icon,
VendorName: vendor.Name,
VendorIcon: vendor.Icon,
Requests: total.Requests,
Tokens: total.Tokens,
})
}
common.ApiSuccess(c, rows)
}
func ResetModelRatio(c *gin.Context) {
defaultStr := ratio_setting.DefaultModelRatio2JSONString()
err := model.UpdateOption("ModelRatio", defaultStr)
+6 -21
View File
@@ -849,31 +849,16 @@ func executeTaskSubmissionWith(
task.PrivateData.ResultURL = taskcommon.BuildProxyURL(task.TaskID)
}
}
// A native submit route may declare retainResult: false. It applies only
// to immediate terminal results: the client receives the complete response
// once, the upstream snapshot is never persisted, and the task is not
// retrievable afterwards. An asynchronous result on such a route keeps its
// snapshot because polling and retrieval need it. The OpenAI Images
// protocol delivers its images inline in the same HTTP response, so its
// immediate results follow the same rule; an asynchronous image task is
// expected there and is polled inside the request.
// The presenter reads the in-memory snapshot. Asynchronous tasks also
// need it in storage for polling and retrieval.
var insertOmits []string
immediateTerminal := result.Immediate != nil && (result.Immediate.Status == model.TaskStatusSuccess || result.Immediate.Status == model.TaskStatusFailure)
if pinnedValue, exists := c.Get(pluginruntime.ContextKeyPinnedRoute); exists {
pinned, ok := pinnedValue.(pluginruntime.PinnedRoute)
if ok && pinned.Route.RetainResult != nil && !*pinned.Route.RetainResult {
if immediateTerminal {
task.PrivateData.ResultDiscarded = true
insertOmits = append(insertOmits, "data")
} else {
logger.LogWarn(c, common.LogText("task plugin route %s %s declares retainResult: false but returned an asynchronous result; retaining task %s", pinned.Route.Method, pinned.Route.Path, task.TaskID))
}
}
}
if pinnedValue, exists := c.Get(pluginruntime.ContextKeyPinnedEndpoint); exists && immediateTerminal {
if pinned, ok := pinnedValue.(pluginruntime.PinnedEndpoint); ok && pinned.Protocol == pluginruntime.ProtocolOpenAIImage {
if pluginruntime.DiscardsImmediateResult(c) {
if immediateTerminal {
task.PrivateData.ResultDiscarded = true
insertOmits = append(insertOmits, "data")
} else if pinned, ok := common.GetContextKeyType[pluginruntime.PinnedRoute](c, pluginruntime.ContextKeyPinnedRoute); ok {
logger.LogWarn(c, common.LogText("task plugin route %s %s declares retainResult: false but returned an asynchronous result; retaining task %s", pinned.Route.Method, pinned.Route.Path, task.TaskID))
}
}
if immediateTerminal && relayInfo.WalletUsageKey != "" {
+24
View File
@@ -23,6 +23,7 @@ import (
"github.com/QuantumNous/new-api/pkg/jsplugin"
"github.com/QuantumNous/new-api/plugins"
"github.com/QuantumNous/new-api/relay/requestplugin"
"github.com/QuantumNous/new-api/relaykit/dto"
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/setting"
"github.com/gin-gonic/gin"
@@ -921,6 +922,28 @@ func relayPaths(meta jsplugin.Meta) []string {
return paths
}
// relayRouteOptions lists the relay routes a channel of the plugin can switch
// on or off, management routes left out. key is the plugin_routes key and
// default_enabled whether a channel that has not switched it serves it.
func relayRouteOptions(meta jsplugin.Meta) []gin.H {
routes := make([]gin.H, 0, len(meta.Relay))
for index, route := range meta.Relay {
path := strings.TrimSpace(route.IncomingPath)
if path == dto.AdvancedCustomModelListPath || path == dto.AdvancedCustomBalancePath {
continue
}
routes = append(routes, gin.H{
"key": jsplugin.RelayRouteKey(route),
"incoming_path": path,
"upstream_path": route.UpstreamPath,
"converter": strings.TrimSpace(route.Converter),
"models": route.Models,
"default_enabled": meta.RelayRouteDefault(index),
})
}
return routes
}
func GetTaskPluginOptions(c *gin.Context) {
snapshot := jsplugin.DefaultRegistry.Snapshot()
seen := make(map[string]bool)
@@ -989,6 +1012,7 @@ func GetTaskPluginOptions(c *gin.Context) {
"checkKey": loaded.HasProviderHook("checkKey"),
"balance": loaded.HasProviderHook("buildBalanceRequest") && loaded.HasProviderHook("parseBalance"),
"relayPaths": relayPaths(loaded.Meta),
"relayRoutes": relayRouteOptions(loaded.Meta),
"responsesWebsocket": loaded.Meta.ServesResponsesWebSocket(""),
}
if len(loaded.Meta.KeyHint) > 0 {
+6 -144
View File
@@ -1,146 +1,8 @@
# Task plugin API v1
# Plugin API
Task plugins are single-file synchronous ECMAScript modules. The plugin contract
is currently unreleased; [`v1.schema.json`](./v1.schema.json) and
[`v1.d.ts`](./v1.d.ts) are the authoritative v1 contract.
The plugin API v1 documents moved to the [`pluginkit`](../../pluginkit/) module:
## 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](./v1.d.ts) for signatures and
[v1.schema.json](./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](./v1.md#generic-task-management-api).
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:
```sh
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`](./v1.md#reading-upstream-data-with-utilsfetch):
`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.
- [README.md](../../pluginkit/README.md): overview of task plugins
- [v1.md](../../pluginkit/v1.md): the API v1 reference
- [v1.schema.json](../../pluginkit/v1.schema.json): JSON Schema of the manifest
- [v1.d.ts](../../pluginkit/v1.d.ts): TypeScript declarations
+5 -2
View File
@@ -131,7 +131,7 @@ require (
github.com/jfreymuth/vorbis v1.0.2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
@@ -170,10 +170,13 @@ require (
github.com/ClickHouse/clickhouse-go/v2 v2.46.0
github.com/MoeForge/moego v0.1.0-alpha.5
github.com/MoeForge/moejs v0.1.0
github.com/QuantumNous/new-api/relaykit v0.0.0
github.com/QuantumNous/new-api/pluginkit v0.0.0
github.com/QuantumNous/new-api/relaykit v0.3.8
github.com/QuantumNous/new-api/tokenkit v0.0.0
)
replace github.com/QuantumNous/new-api/pluginkit => ./pluginkit
replace github.com/QuantumNous/new-api/relaykit => ./relaykit
replace github.com/QuantumNous/new-api/tokenkit => ./tokenkit
+1
View File
@@ -31,6 +31,7 @@ const (
MsgDistributorInvalidPlayground = "distributor.invalid_playground_request"
MsgDistributorGroupAccessDenied = "distributor.group_access_denied"
MsgDistributorGetChannelFailed = "distributor.get_channel_failed"
MsgDistributorModelNotFound = "distributor.model_not_found"
MsgDistributorNoAvailableChannel = "distributor.no_available_channel"
MsgDistributorNoAvailableChannelTaskPlugin = "distributor.no_available_channel_task_plugin"
MsgDistributorInvalidParseModel = "distributor.invalid_request_parse_model"
+1
View File
@@ -23,6 +23,7 @@ distributor.model_name_required: "Model name not specified, model name cannot be
distributor.invalid_playground_request: "Invalid playground request: {{.Error}}"
distributor.group_access_denied: "No permission to access this group"
distributor.get_channel_failed: "Failed to get available channel for model {{.Model}} under group {{.Group}} (distributor): {{.Error}}"
distributor.model_not_found: "Model {{.Model}} is not configured for any group available to this request"
distributor.no_available_channel: "No available channel for model {{.Model}} under group {{.Group}} (distributor)"
distributor.no_available_channel_task_plugin: "No available channel for model {{.Model}} under group {{.Group}}: the model is claimed by a task plugin, which has no enabled channel serving it (distributor)"
distributor.invalid_request_parse_model: "unable to parse model"
+1
View File
@@ -24,6 +24,7 @@ distributor.model_name_required: "未指定模型名称,模型名称不能为
distributor.invalid_playground_request: "无效的playground请求,{{.Error}}"
distributor.group_access_denied: "无权访问该分组"
distributor.get_channel_failed: "获取分组 {{.Group}} 下模型 {{.Model}} 的可用渠道失败(distributor):{{.Error}}"
distributor.model_not_found: "当前请求可用的分组中未配置模型 {{.Model}}"
distributor.no_available_channel: "分组 {{.Group}} 下模型 {{.Model}} 无可用渠道(distributor)"
distributor.no_available_channel_task_plugin: "分组 {{.Group}} 下模型 {{.Model}} 无可用渠道:该模型由任务插件认领,但当前没有启用的渠道可服务此模型(distributor)"
distributor.invalid_request_parse_model: "无法解析模型"
+1
View File
@@ -24,6 +24,7 @@ distributor.model_name_required: "未指定模型名稱,模型名稱不能為
distributor.invalid_playground_request: "無效的playground請求,{{.Error}}"
distributor.group_access_denied: "無權存取該分組"
distributor.get_channel_failed: "獲取分組 {{.Group}} 下模型 {{.Model}} 的可用管道失敗(distributor):{{.Error}}"
distributor.model_not_found: "目前請求可用的分組中未設定模型 {{.Model}}"
distributor.no_available_channel: "分組 {{.Group}} 下模型 {{.Model}} 無可用管道(distributor)"
distributor.no_available_channel_task_plugin: "分組 {{.Group}} 下模型 {{.Model}} 無可用管道:該模型由任務插件認領,但目前沒有啟用的管道可服務此模型(distributor)"
distributor.invalid_request_parse_model: "無法解析模型"
+2
View File
@@ -49,6 +49,8 @@ test:
@cd relaykit && GOWORK=off go test ./...
@echo "Testing tokenkit Go module..."
@cd tokenkit && GOWORK=off go test ./...
@echo "Testing pluginkit Go module..."
@cd pluginkit && GOWORK=off go test ./...
reset-setup:
@echo "Resetting local setup wizard state..."
+1
View File
@@ -326,6 +326,7 @@ var accessTokenRouteRules = map[string]accessTokenRouteRule{
"POST /api/models/sync_upstream": accessTokenScopeRule("model:write"),
"POST /api/models/delete": accessTokenScopeRule("model:write"),
"GET /api/models/missing": accessTokenScopeRule("model:read"),
"GET /api/models/square_usage": accessTokenScopeRule("log:read"),
"GET /api/models/": accessTokenScopeRule("model:read"),
"GET /api/models/search": accessTokenScopeRule("model:read"),
"GET /api/models/:id": accessTokenScopeRule("model:read"),
+9 -8
View File
@@ -122,7 +122,7 @@ func Distribute() func(c *gin.Context) {
}
message := selectErr.Message
if selectErr.NoAvailableChannel {
message = noAvailableChannelMessage(c, usingGroup, modelRequest.Model)
message = noAvailableChannelMessage(c, usingGroup, modelRequest.Model, selectErr.MessageID)
} else if selectErr.MessageID != "" {
message = i18n.T(c, selectErr.MessageID, selectErr.Params)
}
@@ -139,10 +139,9 @@ func Distribute() func(c *gin.Context) {
}
}
// noAvailableChannelMessage explains a 503 for a task-plugin-claimed model.
// The response tells the caller the model is plugin-claimed without naming the
// plugin; the candidate plugin keys go to the server log under the request id.
func noAvailableChannelMessage(c *gin.Context, group, modelName string) string {
// noAvailableChannelMessage logs candidate plugin keys under the request ID.
// A 503 also tells the caller when a task plugin claims the model.
func noAvailableChannelMessage(c *gin.Context, group, modelName, messageID string) string {
value, exists := c.Get(jsplugin.ContextKeyPinnedPlugin)
pinned, ok := value.(jsplugin.PinnedPlugin)
if exists && ok && pinned.Plugin != nil {
@@ -156,9 +155,11 @@ func noAvailableChannelMessage(c *gin.Context, group, modelName string) string {
}
}
logger.LogWarn(c, common.LogText("task_plugin subsystem=distribution event=no_available_channel group=%q model=%q plugins=%q reason=no_eligible_channel", group, modelName, strings.Join(keys, ",")))
return i18n.T(c, i18n.MsgDistributorNoAvailableChannelTaskPlugin, map[string]any{"Group": group, "Model": modelName})
if messageID == i18n.MsgDistributorNoAvailableChannel {
messageID = i18n.MsgDistributorNoAvailableChannelTaskPlugin
}
}
return i18n.T(c, i18n.MsgDistributorNoAvailableChannel, map[string]any{"Group": group, "Model": modelName})
return i18n.T(c, messageID, map[string]any{"Group": group, "Model": modelName})
}
func channelMatchesExpectedTaskPlugin(c *gin.Context, channel *model.Channel, expected string) bool {
@@ -683,7 +684,7 @@ func SetupContextForSelectedChannel(c *gin.Context, channel *model.Channel, mode
generation := jsplugin.DefaultRegistry.Generation()
if plugin, ok := generation.Get(channel.GetSetting().TaskPluginKey); ok && plugin.Meta.HasProviderPart() {
providerPlugin = jsplugin.PinnedPlugin{Generation: generation, Plugin: plugin}
otherSettings.AdvancedCustom = plugin.Meta.ChannelRelayConfig(plugin.ChannelConfigFor(otherSettings.PluginConfig))
otherSettings.AdvancedCustom = plugin.Meta.ChannelRelayConfig(plugin.ChannelConfigFor(otherSettings.PluginConfig), otherSettings.PluginRoutes)
}
}
common.SetContextKey(c, constant.ContextKeyChannelOtherSetting, otherSettings)
+100 -5
View File
@@ -16,10 +16,13 @@ import (
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/pkg/jsplugin"
"github.com/QuantumNous/new-api/relaykit/dto"
"github.com/QuantumNous/new-api/setting"
"github.com/QuantumNous/new-api/setting/model_setting"
"github.com/QuantumNous/new-api/setting/ratio_setting"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
)
type streamedBodyStorage struct {
@@ -326,13 +329,105 @@ func TestTokenModelLimitAllowsExemptAtNameByFullName(t *testing.T) {
assert.False(t, TokenModelLimitAllows(baseOnly, "opaque@sha256:deadbeef"))
}
func TestDistributeModelAvailability(t *testing.T) {
require.NoError(t, i18n.Init())
autoGroups := setting.AutoGroups2JsonString()
usableGroups := setting.UserUsableGroups2JSONString()
groupRatios := ratio_setting.GroupRatio2JSONString()
t.Cleanup(func() {
require.NoError(t, setting.UpdateAutoGroupsByJsonString(autoGroups))
require.NoError(t, setting.UpdateUserUsableGroupsByJSONString(usableGroups))
require.NoError(t, ratio_setting.UpdateGroupRatioByJSONString(groupRatios))
})
require.NoError(t, setting.UpdateAutoGroupsByJsonString(`["default","vip"]`))
require.NoError(t, setting.UpdateUserUsableGroupsByJSONString(`{"default":"Default","vip":"VIP"}`))
require.NoError(t, ratio_setting.UpdateGroupRatioByJSONString(`{"default":1,"vip":1}`))
for _, dialect := range []string{"sqlite", "mysql", "postgres"} {
t.Run(dialect, func(t *testing.T) {
db := setupChannelRoutingTestDB(t, dialect)
for _, channel := range []*model.Channel{
{Group: "default", Models: "online", Status: common.ChannelStatusEnabled},
{Group: "default", Models: "auto-paused", Status: common.ChannelStatusAutoDisabled},
{Group: "vip", Models: "deepseek-flash", Status: common.ChannelStatusManuallyDisabled},
{Group: "private", Models: "private-only", Status: common.ChannelStatusEnabled},
} {
channel.Type = constant.ChannelTypeOpenAI
channel.Key = "routing-test"
require.NoError(t, db.Create(channel).Error)
require.NoError(t, channel.AddAbilities(db))
}
for _, cache := range []bool{false, true} {
common.MemoryCacheEnabled = cache
model.InitChannelCache()
for _, tc := range []struct {
name, group, model, path string
tokenGroups []string
status int
lookupFailure bool
}{
{name: "unknown", group: "default", model: "unknown", status: http.StatusNotFound},
{name: "other group only", path: "/v1/messages", group: "default", model: "private-only", status: http.StatusNotFound},
{name: "manually disabled", path: "/v1/messages", group: "vip", model: "deepseek-flash", status: http.StatusServiceUnavailable},
{name: "automatically disabled", group: "default", model: "auto-paused", status: http.StatusServiceUnavailable},
{name: "normalized model in later auto group", group: "auto", model: "deepseek-flash@effort:max", status: http.StatusServiceUnavailable},
{name: "restricted auto groups", group: "auto", tokenGroups: []string{"default"}, model: "deepseek-flash", status: http.StatusNotFound},
{name: "enabled", group: "auto", model: "online", status: http.StatusNoContent},
{name: "lookup error", group: "auto", model: "unknown", status: http.StatusServiceUnavailable, lookupFailure: true},
{name: "healthy group after lookup error", group: "auto", tokenGroups: []string{"vip", "default"}, model: "online", status: http.StatusNoContent, lookupFailure: true},
} {
t.Run(fmt.Sprintf("cache=%t/%s", cache, tc.name), func(t *testing.T) {
if tc.lookupFailure {
failNext := true
queries := db.Callback().Query()
abilityTable := db.NamingStrategy.TableName("Ability")
const callback = "test:fail_first_route_lookup"
require.NoError(t, queries.Before("gorm:query").Register(callback, func(tx *gorm.DB) {
if failNext && tx.Statement.Table == abilityTable {
failNext = false
tx.AddError(errors.New("channel lookup failed"))
}
}))
t.Cleanup(func() {
require.NoError(t, queries.Remove(callback))
assert.Equal(t, cache && tc.status == http.StatusNoContent, failNext)
})
}
path := common.GetStringIfEmpty(tc.path, "/v1/chat/completions")
router := gin.New()
router.POST(path, func(c *gin.Context) {
common.SetContextKey(c, constant.ContextKeyUsingGroup, tc.group)
common.SetContextKey(c, constant.ContextKeyUserGroup, "default")
if tc.tokenGroups != nil {
common.SetContextKey(c, constant.ContextKeyTokenAutoGroups, tc.tokenGroups)
}
}, Distribute(), func(c *gin.Context) { c.Status(http.StatusNoContent) })
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(fmt.Sprintf(`{"model":%q}`, tc.model)))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept-Language", "en")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
require.Equal(t, tc.status, w.Code, w.Body.String())
if tc.status == http.StatusNotFound {
assert.Contains(t, w.Body.String(), `"code":"model_not_found"`)
assert.Contains(t, w.Body.String(), "Model "+tc.model+" is not configured for any group available to this request")
}
})
}
}
})
}
}
func TestDistributeHidesTaskPluginDetailsButLogsDiagnostics(t *testing.T) {
require.NoError(t, i18n.Init())
previousCacheEnabled := common.MemoryCacheEnabled
common.MemoryCacheEnabled = true
t.Cleanup(func() { common.MemoryCacheEnabled = previousCacheEnabled })
const group = "private-plugin-error-test-group"
db := setupChannelRoutingTestDB(t, "sqlite")
channel := &model.Channel{Type: constant.ChannelTypeKling, Group: group, Models: "task-model", Status: common.ChannelStatusManuallyDisabled}
require.NoError(t, db.Create(channel).Error)
require.NoError(t, channel.AddAbilities(db))
common.MemoryCacheEnabled = true
model.InitChannelCache()
for _, locale := range []struct{ language, message string }{
{"en", "No available channel for model task-model under group " + group + ": the model is claimed by a task plugin, which has no enabled channel serving it (distributor)"},
{"zh-CN", "分组 " + group + " 下模型 task-model 无可用渠道:该模型由任务插件认领,但当前没有启用的渠道可服务此模型(distributor)"},
@@ -407,7 +502,7 @@ func TestNoAvailableChannelMessageWithoutPlugin(t *testing.T) {
plain, _ := gin.CreateTestContext(nil)
plain.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
plain.Request.Header.Set("Accept-Language", "en")
generic := noAvailableChannelMessage(plain, "default", "gpt-4o")
generic := noAvailableChannelMessage(plain, "default", "gpt-4o", i18n.MsgDistributorNoAvailableChannel)
assert.NotContains(t, generic, "task plugin")
assert.Contains(t, generic, "gpt-4o")
}
+6 -13
View File
@@ -232,16 +232,13 @@ func PrepareTaskPluginRoute() gin.HandlerFunc {
if !allowed {
reason, detail = "model_not_allowed", fmt.Sprintf("model %q is not allowed on this route", claimedModel)
} else {
value, text, callErr := candidate.Plugin.Engine.CallPathWithMemberJSON(
c.Request.Context(), 0, candidate.Plugin.Meta.JSONTextMember("requestBody"),
"native", []string{candidate.Route.Decode}, candidateContext.JSValueFor(candidate.Plugin.Meta),
)
decoded, callErr := candidate.Plugin.CallRouteDecode(c.Request.Context(), 0, candidate.Route.Decode, candidateContext)
if callErr != nil {
reason, detail = "hook_failed", taskPluginHookDetail(callErr)
} else {
result, _ = value.(map[string]any)
bodyText = text
intent, reason, detail = checkTaskPluginRouteIntent(pinned.Generation, candidate, value)
result = decoded.Result
bodyText = decoded.RequestBodyText
intent, reason, detail = checkTaskPluginRouteIntent(pinned.Generation, candidate, decoded.Value)
}
}
if reason == "" && intent.kind == string(pluginruntime.RouteTypeQuery) {
@@ -865,12 +862,8 @@ func PrepareTaskPluginEndpoint() gin.HandlerFunc {
candidateContext.Operation = candidate.Operation.Name
// Parsing belongs to durable submission; disconnecting only stops
// the later Responses observation.
resolvedValue, requestBodyText, callErr := candidate.Plugin.Engine.CallPathWithMemberJSON(
context.WithoutCancel(c.Request.Context()), pluginruntime.DefaultCallTimeout,
candidate.Plugin.Meta.JSONTextMember("requestBody"),
"protocols", []string{candidate.Protocol, "decodeRequest"}, candidateContext.JSValueFor(candidate.Plugin.Meta),
)
result, resultOK := resolvedValue.(map[string]any)
decoded, callErr := candidate.Plugin.CallProtocolDecode(context.WithoutCancel(c.Request.Context()), pluginruntime.DefaultCallTimeout, candidate.Protocol, candidateContext)
result, resultOK, requestBodyText := decoded.Result, decoded.Result != nil, decoded.RequestBodyText
detail := ""
reason := ""
if callErr != nil {
+50 -44
View File
@@ -2098,54 +2098,60 @@ func TestPrepareTaskPluginEndpointFiltersEachSharedCandidate(t *testing.T) {
}
}
func setupChannelRoutingTestDB(t *testing.T, dialect string) *gorm.DB {
t.Helper()
dsn := ""
if dialect != "sqlite" {
dsn = os.Getenv("TEST_" + strings.ToUpper(dialect) + "_DSN")
if dsn == "" {
t.Skip("database test DSN not configured")
}
}
previousDB, previousMain, previousLog := model.DB, common.MainDatabaseType(), common.LogDatabaseType()
previousPath, previousMaster := common.SQLitePath, common.IsMasterNode
previousCache, previousRedis := common.MemoryCacheEnabled, common.RedisEnabled
common.SQLitePath, common.IsMasterNode = t.TempDir()+"/routing.db", false
common.RedisEnabled = false
t.Setenv("SQL_DSN", dsn)
require.NoError(t, model.InitDB())
database := model.DB
// Every table belongs to this run, including when a developer points
// a test DSN at a database shared with another test suite.
database.Config.NamingStrategy = schema.NamingStrategy{TablePrefix: "endpoint_route_" + common.GetUUID() + "_"}
require.NoError(t, database.AutoMigrate(&model.Channel{}, &model.Ability{}, &model.Task{}))
t.Cleanup(func() {
for _, table := range []any{&model.Ability{}, &model.Channel{}, &model.Task{}} {
require.NoError(t, database.Session(&gorm.Session{AllowGlobalUpdate: true}).Delete(table).Error)
}
common.MemoryCacheEnabled = true
model.InitChannelCache()
require.NoError(t, database.Migrator().DropTable(&model.Ability{}, &model.Channel{}, &model.Task{}))
model.DB = previousDB
common.SetDatabaseTypes(previousMain, previousLog)
common.SQLitePath, common.IsMasterNode = previousPath, previousMaster
common.MemoryCacheEnabled, common.RedisEnabled = previousCache, previousRedis
if previousDB != nil {
model.InitChannelCache()
}
sqlDB, err := database.DB()
require.NoError(t, err)
require.NoError(t, sqlDB.Close())
})
query := "SELECT version()"
if dialect == "sqlite" {
query = "SELECT sqlite_version()"
}
var version string
require.NoError(t, database.Raw(query).Scan(&version).Error)
t.Logf("database version: %s", version)
return database
}
func TestRouteTaskPluginEndpointUsesSelectedChannel(t *testing.T) {
require.NoError(t, appI18n.Init())
for _, dialect := range []string{"sqlite", "mysql", "postgres"} {
t.Run(dialect, func(t *testing.T) {
dsn := ""
if dialect != "sqlite" {
dsn = os.Getenv("TEST_" + strings.ToUpper(dialect) + "_DSN")
if dsn == "" {
t.Skip("database test DSN not configured")
}
}
previousDB, previousMain, previousLog := model.DB, common.MainDatabaseType(), common.LogDatabaseType()
previousPath, previousMaster := common.SQLitePath, common.IsMasterNode
previousCache, previousRedis := common.MemoryCacheEnabled, common.RedisEnabled
common.SQLitePath, common.IsMasterNode = t.TempDir()+"/routing.db", false
common.RedisEnabled = false
t.Setenv("SQL_DSN", dsn)
require.NoError(t, model.InitDB())
database := model.DB
// Every table belongs to this run, including when a developer points
// a test DSN at a database shared with another test suite.
database.Config.NamingStrategy = schema.NamingStrategy{TablePrefix: "endpoint_route_" + common.GetUUID() + "_"}
require.NoError(t, database.AutoMigrate(&model.Channel{}, &model.Ability{}, &model.Task{}))
t.Cleanup(func() {
for _, table := range []any{&model.Ability{}, &model.Channel{}, &model.Task{}} {
require.NoError(t, database.Session(&gorm.Session{AllowGlobalUpdate: true}).Delete(table).Error)
}
common.MemoryCacheEnabled = true
model.InitChannelCache()
require.NoError(t, database.Migrator().DropTable(&model.Ability{}, &model.Channel{}, &model.Task{}))
model.DB = previousDB
common.SetDatabaseTypes(previousMain, previousLog)
common.SQLitePath, common.IsMasterNode = previousPath, previousMaster
common.MemoryCacheEnabled, common.RedisEnabled = previousCache, previousRedis
if previousDB != nil {
model.InitChannelCache()
}
sqlDB, err := database.DB()
require.NoError(t, err)
require.NoError(t, sqlDB.Close())
})
query := "SELECT version()"
if dialect == "sqlite" {
query = "SELECT sqlite_version()"
}
var version string
require.NoError(t, database.Raw(query).Scan(&version).Error)
t.Logf("database version: %s", version)
database := setupChannelRoutingTestDB(t, dialect)
for _, memoryCache := range []bool{false, true} {
t.Run(fmt.Sprintf("memory_cache=%t", memoryCache), func(t *testing.T) {
+12
View File
@@ -47,6 +47,18 @@ func GetGroupEnabledModels(group string) []string {
return models
}
// IsModelConfiguredForGroups checks enabled and disabled channel abilities for
// the requested model and its routing name.
func IsModelConfiguredForGroups(groups []string, modelName string) (bool, error) {
names := []string{modelName}
if normalized := ratio_setting.RoutingMatchModelName(modelName); normalized != "" && normalized != modelName {
names = append(names, normalized)
}
var ability Ability
result := DB.Select("channel_id").Where(map[string]any{"group": groups, "model": names}).Limit(1).Find(&ability)
return result.RowsAffected > 0, result.Error
}
func GetEnabledModels() []string {
var models []string
// Find distinct models
+2 -2
View File
@@ -139,7 +139,7 @@ func channelMatchesFilter(ch *Channel, modelName string, filter dto.ChannelFilte
case constant.ChannelTypeTaskPlugin:
// The same rule on the relay routes of the channel's plugin.
plugin, ok := jsplugin.DefaultRegistry.Get(ch.GetSetting().TaskPluginKey)
return ok && plugin.Meta.ServesResponsesWebSocket(modelName)
return ok && plugin.Meta.ChannelServesResponsesWebSocket(ch.GetOtherSettings().PluginRoutes, modelName)
default:
return false
}
@@ -159,6 +159,6 @@ func providerChannelServes(ch *Channel, requestPath, modelName string) bool {
if !ok || !plugin.Meta.HasProviderPart() {
return false
}
_, ok = plugin.Meta.RelayRoute(requestPath, modelName)
_, ok = plugin.Meta.ChannelRelayRoute(ch.GetOtherSettings().PluginRoutes, requestPath, modelName)
return ok
}
+8 -4
View File
@@ -216,9 +216,9 @@ func CacheUpdateChannelKey(id int, key string) {
}
// channelRelayConfig returns the relay routes of a task plugin channel's
// plugin, nil for any other channel. It reads the setting without GetSetting,
// which clears the stored setting when it is invalid, so a pricing read never
// writes the channel.
// plugin that are on for the channel, nil for any other channel. It reads the
// settings without GetSetting or GetOtherSettings, which clear a stored
// setting when it is invalid, so a pricing read never writes the channel.
func channelRelayConfig(ch *Channel) *dto.AdvancedCustomConfig {
var setting dto.ChannelSettings
if ch.Type != constant.ChannelTypeTaskPlugin || ch.Setting == nil || common.UnmarshalJsonStr(*ch.Setting, &setting) != nil {
@@ -228,7 +228,11 @@ func channelRelayConfig(ch *Channel) *dto.AdvancedCustomConfig {
if !ok {
return nil
}
return plugin.Meta.RelayConfig()
var otherSettings dto.ChannelOtherSettings
if ch.OtherSettings != "" {
_ = common.UnmarshalJsonStr(ch.OtherSettings, &otherSettings)
}
return plugin.Meta.ChannelRelayConfig(nil, otherSettings.PluginRoutes)
}
// UpdateScheduledChannelLocked persists a completed scheduled result. update
+48
View File
@@ -191,6 +191,54 @@ func TestProviderChannelSelectionFollowsRelayRoutes(t *testing.T) {
}
}
// Two channels bound to one plugin: the /v1/responses route declared
// default_enabled: false serves only the channel whose plugin_routes turn it on.
func TestProviderChannelSelectionFollowsChannelRouteToggles(t *testing.T) {
truncateTables(t)
registerModelTestPlugin(t, `
export const meta = {apiVersion: 1, key: "%KEY%", name: "Toggles", version: "1.0.0", author: {name: "Test"},
relay: [
{incoming_path: "/v1/chat/completions", upstream_path: "/chat"},
{incoming_path: "/v1/responses", upstream_path: "/chat", converter: "openai_responses_to_openai_chat_completions", default_enabled: false}
]};
`, "select-toggles")
originalMemoryCache := common.MemoryCacheEnabled
t.Cleanup(func() { common.MemoryCacheEnabled = originalMemoryCache; InitChannelCache() })
priority := int64(0)
weight := uint(1)
setting := `{"task_plugin_key":"select-toggles"}`
for _, channel := range []Channel{
{Id: 960011, Type: constant.ChannelTypeTaskPlugin, Status: common.ChannelStatusEnabled, Name: "off", Models: "m", Group: "default", Priority: &priority, Weight: &weight, Setting: &setting},
{Id: 960012, Type: constant.ChannelTypeTaskPlugin, Status: common.ChannelStatusEnabled, Name: "on", Models: "m", Group: "default", Priority: &priority, Weight: &weight, Setting: &setting,
OtherSettings: `{"plugin_routes":{"/v1/responses":true}}`},
} {
require.NoError(t, channel.Insert())
}
for _, tc := range []struct {
id int
path string
wantServes bool
}{
{id: 960011, path: "/v1/responses", wantServes: false},
{id: 960012, path: "/v1/responses", wantServes: true},
{id: 960011, path: "/v1/chat/completions", wantServes: true},
{id: 960012, path: "/v1/chat/completions", wantServes: true},
} {
channel, err := GetChannelById(tc.id, true)
require.NoError(t, err)
assert.Equal(t, tc.wantServes, providerChannelServes(channel, tc.path, "m"), "%s %s", channel.Name, tc.path)
}
for _, memoryCache := range []bool{false, true} {
common.MemoryCacheEnabled = memoryCache
InitChannelCache()
selected, err := GetChannel("default", "m", 0, []dto.ChannelFilter{{Kind: dto.FilterTaskPluginIdentity, RequestPath: "/v1/responses"}})
require.NoError(t, err)
require.NotNil(t, selected, "memory cache %v", memoryCache)
assert.Equal(t, "on", selected.Name, "memory cache %v", memoryCache)
}
}
func TestPricingProviderChannelUsesRelayRoutes(t *testing.T) {
resetPricingEndpointTestTables(t)
registerModelTestPlugin(t, dualPluginSource, "pricing-dual")
+3
View File
@@ -246,6 +246,9 @@ func validateOptionValue(key string, value string) error {
if err := operation_setting.ValidateEpaySignOption(key, value); err != nil {
return err
}
if err := operation_setting.ValidateModelSquareOption(key, value); err != nil {
return err
}
if key == "EmailProvider" || key == "ResendApiKey" || key == "ResendFrom" {
if key == "EmailProvider" && value != "smtp" && value != "resend" {
return common.NewMessage("Email sending method must be SMTP or Resend")
+7 -4
View File
@@ -138,10 +138,8 @@ type TaskPrivateData struct {
PluginState json.RawMessage `json:"plugin_state,omitempty"`
// PollFailures counts consecutive unrecognized or transient poll outcomes.
PollFailures int `json:"poll_failures,omitempty"`
// ResultDiscarded marks an immediate terminal result whose submit route
// declared retainResult: false. The upstream snapshot was never written
// and every retrieval surface treats the task as not found. The zero
// value keeps historical rows retained and retrievable.
// ResultDiscarded marks an immediate result delivered inline by openai_image
// or a route with retainResult: false. Retrieval treats the task as missing.
ResultDiscarded bool `json:"result_discarded,omitempty"`
// CredentialAccount is the account of the plugin credential that
// submitted the task, which polls the task and fetches its content.
@@ -258,6 +256,11 @@ func (p *TaskPrivateData) Scan(val any) error {
}
func (p TaskPrivateData) Value() (driver.Value, error) {
if p.ResultDiscarded {
// A plugin can return the inline image itself as the result URL.
// The submit presenter and report still have the in-memory result.
p.ResultURL = ""
}
if p.Key == "" && p.UpstreamTaskID == "" && p.ResultURL == "" &&
p.Execution == nil && p.BillingSource == "" && p.SubscriptionId == 0 &&
p.TokenId == 0 && p.NodeName == "" && p.BillingContext == nil &&
+19
View File
@@ -31,6 +31,25 @@ func GetRankingQuotaTotals(startTime int64, endTime int64) ([]RankingQuotaTotal,
return rows, err
}
type ModelUsageTotal struct {
ModelName string `json:"model_name"`
Requests int64 `json:"requests"`
Tokens int64 `json:"tokens"`
}
// GetModelUsageTotals sums requests and tokens per model, including models
// that used no tokens.
func GetModelUsageTotals(startTime int64, endTime int64) ([]ModelUsageTotal, error) {
var rows []ModelUsageTotal
query := DB.Table("quota_data").
Select("model_name, sum(count) as requests, sum(token_used) as tokens").
Where("model_name <> ''").
Group("model_name")
query = applyRankingQuotaTimeRange(query, startTime, endTime)
err := query.Find(&rows).Error
return rows, err
}
func GetRankingQuotaBuckets(startTime int64, endTime int64, bucketSize int64) ([]RankingQuotaBucket, error) {
if bucketSize <= 0 {
bucketSize = 3600
+29 -13
View File
@@ -1059,10 +1059,14 @@ func (user *User) ValidateAndFill() (err error) {
if username == "" || password == "" {
return ErrUserEmptyCredentials
}
// find by username or email
err = DB.Where("username = ? OR email = ?", username, username).First(user).Error
// Preserve username lookup semantics; email must identify one exact account.
err = DB.Where("username = ?", username).First(user).Error
if errors.Is(err, gorm.ErrRecordNotFound) && strings.Contains(username, "@") {
user.Email = username
err = user.FillUserByEmail()
}
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
if errors.Is(err, gorm.ErrRecordNotFound) || errors.Is(err, ErrEmailNotFound) || errors.Is(err, ErrEmailAmbiguous) {
return ErrInvalidCredentials
}
return fmt.Errorf("%w: %v", ErrDatabase, err)
@@ -1089,7 +1093,11 @@ func (user *User) FillUserByEmail() error {
if user.Email == "" {
return common.NewMessage("Email is empty!")
}
DB.Where(User{Email: user.Email}).First(user)
matched, err := GetUniqueUserByEmail(user.Email)
if err != nil {
return err
}
*user = *matched
return nil
}
@@ -1146,18 +1154,26 @@ func GetUniqueUserByEmail(email string) (*User, error) {
if email == "" {
return nil, ErrEmailNotFound
}
var users []User
if err := DB.Where("LOWER(email) = ?", email).Limit(2).Find(&users).Error; err != nil {
var candidates []User
if err := DB.Where("LOWER(email) = ?", email).Find(&candidates).Error; err != nil {
return nil, err
}
switch len(users) {
case 0:
return nil, ErrEmailNotFound
case 1:
return &users[0], nil
default:
return nil, ErrEmailAmbiguous
// Compare normalized emails in Go so accent-insensitive database collations
// (such as MySQL's utf8mb4_0900_ai_ci) cannot match look-alike addresses.
var matched *User
for i := range candidates {
if NormalizeEmail(candidates[i].Email) != email {
continue
}
if matched != nil {
return nil, ErrEmailAmbiguous
}
matched = &candidates[i]
}
if matched == nil {
return nil, ErrEmailNotFound
}
return matched, nil
}
func IsWeChatIdAlreadyTaken(wechatId string) bool {
+59
View File
@@ -2,6 +2,7 @@ package model
import (
"errors"
"os"
"strconv"
"testing"
"time"
@@ -9,8 +10,11 @@ import (
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/relaykit/dto"
"github.com/glebarez/sqlite"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
@@ -362,6 +366,61 @@ func TestValidateAndFillRejectsPasswordlessUser(t *testing.T) {
assert.Empty(t, stored.Password)
}
func TestExactAccountEmailLookup(t *testing.T) {
for _, dialect := range []string{"sqlite", "mysql", "postgres"} {
t.Run(dialect, func(t *testing.T) {
var driver gorm.Dialector = sqlite.Open(":memory:")
emailType := "varchar(80)"
switch dialect {
case "mysql":
dsn := os.Getenv("TEST_MYSQL_DSN")
if dsn == "" {
t.Skip("TEST_MYSQL_DSN is not configured")
}
driver = mysql.Open(dsn)
emailType += " CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
case "postgres":
dsn := os.Getenv("TEST_POSTGRES_DSN")
if dsn == "" {
t.Skip("TEST_POSTGRES_DSN is not configured")
}
driver = postgres.Open(dsn)
}
db, err := gorm.Open(driver, &gorm.Config{})
require.NoError(t, err)
sqlDB, err := db.DB()
require.NoError(t, err)
sqlDB.SetMaxOpenConns(1) // Keep the temporary users table on one connection.
previous := DB
DB = db
t.Cleanup(func() { DB = previous; assert.NoError(t, sqlDB.Close()) })
require.NoError(t, db.Exec("CREATE TEMPORARY TABLE users (id integer primary key, username varchar(20), email "+emailType+", password varchar(256), status integer, deleted_at timestamp null)").Error)
password := "test-lookup-password"
hash, err := common.HashAccountPassword(password)
require.NoError(t, err)
const domain = "@" + "example.test"
address := "cafe" + domain
for i, local := range []string{"café", "cafè"} {
require.NoError(t, db.Exec("INSERT INTO users (id, email) VALUES (?, ?)", i+1, local+domain).Error)
}
lookup := User{Email: address}
require.ErrorIs(t, lookup.FillUserByEmail(), ErrEmailNotFound)
require.NoError(t, db.Exec("INSERT INTO users (id, username, email, password, status) VALUES (3, ?, ?, ?, ?)", "member", address, hash, common.UserStatusEnabled).Error)
require.NoError(t, lookup.FillUserByEmail())
assert.Equal(t, 3, lookup.Id)
for _, identifier := range []string{"member", "CAFE" + domain} {
login := User{Username: identifier, Password: password}
require.NoError(t, login.ValidateAndFill())
assert.Equal(t, 3, login.Id)
}
require.NoError(t, db.Exec("INSERT INTO users (id, email) VALUES (4, ?)", address).Error)
require.ErrorIs(t, lookup.FillUserByEmail(), ErrEmailAmbiguous)
login := User{Username: address, Password: password}
require.ErrorIs(t, login.ValidateAndFill(), ErrInvalidCredentials)
})
}
}
func TestResetUserPasswordByEmailRequiresSingleActiveMatch(t *testing.T) {
setupUserUpdateTestState(t)
+177
View File
@@ -0,0 +1,177 @@
package jsplugin
import "github.com/QuantumNous/new-api/pluginkit"
// The plugin API v1 contract, host utilities and execution engine live in
// the pluginkit module. These names keep the package surface new-api code
// has always used.
type (
Attachment = pluginkit.Attachment
AuthMeta = pluginkit.AuthMeta
AuthorMeta = pluginkit.AuthorMeta
BalanceResult = pluginkit.BalanceResult
BalanceStep = pluginkit.BalanceStep
BalanceWindow = pluginkit.BalanceWindow
BodyKind = pluginkit.BodyKind
ConfigSchema = pluginkit.ConfigSchema
ConvertInput = pluginkit.ConvertInput
ConvertedForm = pluginkit.ConvertedForm
ConvertedFormFile = pluginkit.ConvertedFormFile
ConvertedRequest = pluginkit.ConvertedRequest
ConvertedResponse = pluginkit.ConvertedResponse
Credential = pluginkit.Credential
CredentialContext = pluginkit.CredentialContext
CredentialResult = pluginkit.CredentialResult
CredentialSummary = pluginkit.CredentialSummary
Engine = pluginkit.Engine
ExchangedToken = pluginkit.ExchangedToken
FetchRequest = pluginkit.FetchRequest
FetchResponse = pluginkit.FetchResponse
Fetcher = pluginkit.Fetcher
Fixture = pluginkit.Fixture
FixtureCase = pluginkit.FixtureCase
FixtureReport = pluginkit.FixtureReport
HookContext = pluginkit.HookContext
HookError = pluginkit.HookError
HostProtocolDefinition = pluginkit.HostProtocolDefinition
HostProtocolOperation = pluginkit.HostProtocolOperation
JSONState = pluginkit.JSONState
LoadedPlugin = pluginkit.LoadedPlugin
LocalizedText = pluginkit.LocalizedText
LoginContext = pluginkit.LoginContext
LoginField = pluginkit.LoginField
LoginStep = pluginkit.LoginStep
MediaInfo = pluginkit.MediaInfo
MediaSource = pluginkit.MediaSource
MediaText = pluginkit.MediaText
Meta = pluginkit.Meta
Options = pluginkit.Options
ParamOverrideFunc = pluginkit.ParamOverrideFunc
PrepareInput = pluginkit.PrepareInput
PreparedRequest = pluginkit.PreparedRequest
ProtocolClaim = pluginkit.ProtocolClaim
ProtocolMode = pluginkit.ProtocolMode
ProtocolRequestContext = pluginkit.ProtocolRequestContext
RawJSON = pluginkit.RawJSON
ReplyMask = pluginkit.ReplyMask
ReplyOutput = pluginkit.ReplyOutput
ReplyResult = pluginkit.ReplyResult
RequestFile = pluginkit.RequestFile
RequestForm = pluginkit.RequestForm
ResultError = pluginkit.ResultError
Route = pluginkit.Route
RouteBinding = pluginkit.RouteBinding
RouteRequestContext = pluginkit.RouteRequestContext
RouteType = pluginkit.RouteType
Sample = pluginkit.Sample
ScheduledContext = pluginkit.ScheduledContext
ScheduledResult = pluginkit.ScheduledResult
SignResult = pluginkit.SignResult
StreamEvent = pluginkit.StreamEvent
StreamResult = pluginkit.StreamResult
TransformChannel = pluginkit.TransformChannel
TransformContext = pluginkit.TransformContext
TransformError = pluginkit.TransformError
TransformFinding = pluginkit.TransformFinding
TransformInstance = pluginkit.TransformInstance
TransformMedia = pluginkit.TransformMedia
TransformRequest = pluginkit.TransformRequest
TransformResult = pluginkit.TransformResult
TransformScope = pluginkit.TransformScope
TransformSummary = pluginkit.TransformSummary
TransformToken = pluginkit.TransformToken
TransformUser = pluginkit.TransformUser
UnknownMetaFieldError = pluginkit.UnknownMetaFieldError
UpstreamError = pluginkit.UpstreamError
UpstreamResponse = pluginkit.UpstreamResponse
UsageExample = pluginkit.UsageExample
UsageFieldSchema = pluginkit.UsageFieldSchema
UsageProfile = pluginkit.UsageProfile
WebSocketMessage = pluginkit.WebSocketMessage
WebSocketRequest = pluginkit.WebSocketRequest
)
const (
APIVersion1 = pluginkit.APIVersion1
BodyForm = pluginkit.BodyForm
BodyJSON = pluginkit.BodyJSON
BodyMultipart = pluginkit.BodyMultipart
BodyNone = pluginkit.BodyNone
CapabilityDurationAuto = pluginkit.CapabilityDurationAuto
CapabilityJSONClone = pluginkit.CapabilityJSONClone
CapabilityJSONOrder = pluginkit.CapabilityJSONOrder
CapabilitySubmitSSEDelta = pluginkit.CapabilitySubmitSSEDelta
CredentialType = pluginkit.CredentialType
DefaultCallTimeout = pluginkit.DefaultCallTimeout
DefaultConcurrency = pluginkit.DefaultConcurrency
LoginStepDevice = pluginkit.LoginStepDevice
LoginStepDone = pluginkit.LoginStepDone
LoginStepFields = pluginkit.LoginStepFields
LoginStepPaste = pluginkit.LoginStepPaste
LoginStepPending = pluginkit.LoginStepPending
LoginStepRedirect = pluginkit.LoginStepRedirect
MaxCheckKeyMessageRunes = pluginkit.MaxCheckKeyMessageRunes
MaxCredentialBytes = pluginkit.MaxCredentialBytes
MaxFetchBodyBytes = pluginkit.MaxFetchBodyBytes
MaxIconDataURIBytes = pluginkit.MaxIconDataURIBytes
MaxJSONToolBytes = pluginkit.MaxJSONToolBytes
MaxLoginSessionBytes = pluginkit.MaxLoginSessionBytes
MaxMediaTextChars = pluginkit.MaxMediaTextChars
MaxMetaBaseURLLength = pluginkit.MaxMetaBaseURLLength
MaxRejectedBodyBytes = pluginkit.MaxRejectedBodyBytes
ProtocolOpenAIImage = pluginkit.ProtocolOpenAIImage
ProviderConverter = pluginkit.ProviderConverter
ReplyHook = pluginkit.ReplyHook
ReportHook = pluginkit.ReportHook
RouteTypeDynamic = pluginkit.RouteTypeDynamic
RouteTypeQuery = pluginkit.RouteTypeQuery
RouteTypeSubmit = pluginkit.RouteTypeSubmit
TransformErrorCanceled = pluginkit.TransformErrorCanceled
TransformErrorFailed = pluginkit.TransformErrorFailed
TransformErrorMemory = pluginkit.TransformErrorMemory
TransformErrorResult = pluginkit.TransformErrorResult
TransformErrorThrow = pluginkit.TransformErrorThrow
TransformErrorTimeout = pluginkit.TransformErrorTimeout
UpstreamKindNewAPI = pluginkit.UpstreamKindNewAPI
UpstreamKindVendor = pluginkit.UpstreamKindVendor
)
var (
ErrCallAdmissionTimeout = pluginkit.ErrCallAdmissionTimeout
ProviderHooks = pluginkit.ProviderHooks
TransformStages = pluginkit.TransformStages
ASCIIFold = pluginkit.ASCIIFold
ChannelConfigURL = pluginkit.ChannelConfigURL
CloneUsageExamples = pluginkit.CloneUsageExamples
CloneUsageSchema = pluginkit.CloneUsageSchema
Compile = pluginkit.Compile
CompilePlugin = pluginkit.CompilePlugin
DecodeIconDataURI = pluginkit.DecodeIconDataURI
FileReference = pluginkit.FileReference
HasCapability = pluginkit.HasCapability
HostProtocol = pluginkit.HostProtocol
HostProtocols = pluginkit.HostProtocols
LookupHostProtocolOperation = pluginkit.LookupHostProtocolOperation
NewJSONState = pluginkit.NewJSONState
NormalizeRoutePath = pluginkit.NormalizeRoutePath
ParseCredential = pluginkit.ParseCredential
ParseFileReference = pluginkit.ParseFileReference
PluginRouteBindings = pluginkit.PluginRouteBindings
RedactCredentialLines = pluginkit.RedactCredentialLines
RelayRouteKey = pluginkit.RelayRouteKey
ResolveRouteAction = pluginkit.ResolveRouteAction
SetParamOverrideFunc = pluginkit.SetParamOverrideFunc
SplitProviderConverter = pluginkit.SplitProviderConverter
SupportsHostProtocol = pluginkit.SupportsHostProtocol
UTF16Len = pluginkit.UTF16Len
UsesSubmitEventDelta = pluginkit.UsesSubmitEventDelta
ValidPluginKey = pluginkit.ValidPluginKey
ValidateIconImage = pluginkit.ValidateIconImage
ValidateJSONPath = pluginkit.ValidateJSONPath
ValidateRequestHeaders = pluginkit.ValidateRequestHeaders
ValidateRequestURL = pluginkit.ValidateRequestURL
ValidateServiceURL = pluginkit.ValidateServiceURL
ValidateV1Meta = pluginkit.ValidateV1Meta
WithFetcher = pluginkit.WithFetcher
)
+79
View File
@@ -0,0 +1,79 @@
package jsplugin
import (
"context"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/logger"
"github.com/QuantumNous/new-api/pluginkit"
)
// reservedRouteNamespaces are host paths a plugin route may never enter:
// console pages, assets and the generic task routes. The other host
// namespaces, such as /api, follow the outer router's static routes and are
// decided at admission.
var reservedRouteNamespaces = []string{
"/assets",
"/setup",
"/v1/tasks",
"/console",
"/login",
"/forbidden",
"/sign-in",
"/sign-up",
"/forgot-password",
"/oauth",
"/otp",
"/register",
"/reset",
"/privacy-policy",
"/user-agreement",
"/about",
"/pricing",
"/rankings",
"/user",
"/401",
"/403",
"/404",
"/500",
"/503",
"/chat2link",
"/system-settings",
"/channels",
"/chat",
"/dashboard",
"/errors",
"/keys",
"/models",
"/playground",
"/profile",
"/redemption-codes",
"/request-processing",
"/security",
"/subscriptions",
"/system-info",
"/task-plugins",
"/upstream-monitor",
"/usage-logs",
"/users",
"/wallet",
}
// The settings are read on every use, so values loaded from the environment
// after this runs still apply.
func init() {
pluginkit.Configure(pluginkit.Host{
MemoryLimit: func() int64 { return int64(max(constant.PluginMemoryLimitMB, 0)) << 20 },
MaxRequestBodyBytes: func() int { return constant.MaxRequestBodyMB << 20 },
MaxStreamEventBytes: func() int { return constant.StreamScannerMaxBufferMB << 20 },
ReservedRouteNamespaces: reservedRouteNamespaces,
ReservedKeys: []string{"api"},
Debug: logger.LogDebug,
})
}
// ReplayFixture compiles a plugin, admits its routes as the registry does, and
// runs every fixture case in declaration order (pluginkit.ReplayFixture).
func ReplayFixture(ctx context.Context, source string, data []byte) (FixtureReport, error) {
return pluginkit.ReplayFixtureWith(ctx, NewRegistry().Register, source, data)
}
+122
View File
@@ -0,0 +1,122 @@
package jsplugin
import (
"bytes"
"context"
"testing"
"github.com/MoeForge/moejs"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/pluginkit"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// pluginkit owns the plugin contract's copies of these host values; they
// must not drift from new-api's.
func TestPluginkitConstantsMatchHost(t *testing.T) {
assert.Equal(t, constant.ChannelTypeNewAPI, pluginkit.ChannelTypeNewAPI)
assert.Equal(t, constant.ChannelTypeTaskPlugin, pluginkit.ChannelTypeTaskPlugin)
assert.Equal(t, relaycommon.MaxTaskDurationSeconds, pluginkit.MaxUsageSeconds)
assert.Equal(t, common.MaxQuota, pluginkit.MaxUsageQuota)
}
func TestEngineConsoleLogUsesDebugLoggerAndRequestContext(t *testing.T) {
previousDebug := common.DebugEnabled
common.DebugEnabled = false
t.Cleanup(func() { common.DebugEnabled = previousDebug })
var output bytes.Buffer
common.LogWriterMu.Lock()
previousWriter := gin.DefaultErrorWriter
gin.DefaultErrorWriter = &output
common.LogWriterMu.Unlock()
t.Cleanup(func() {
common.LogWriterMu.Lock()
gin.DefaultErrorWriter = previousWriter
common.LogWriterMu.Unlock()
})
plugin, err := CompilePlugin(`
export const meta = {
apiVersion: 1,
key: "console-debug",
name: "Console debug",
version: "1.2.3",
author: {name: "Test"},
models: ["debug-model"],
fetchMode: "per_task",
};
export function run(label) {
console.log("checkpoint", label);
return true;
}
export function buildSubmitRequest() { return {url: "https://example.com"}; }
export function parseSubmitResponse() { return {taskId: "one"}; }
export function buildQueryRequest() { return {url: "https://example.com"}; }
export function parseTaskResult() { return {status: "SUCCESS"}; }
`, Options{})
require.NoError(t, err)
engine := plugin.Engine
disabledContext := context.WithValue(context.Background(), common.RequestIdKey, "plugin-console-disabled")
_, err = engine.Call(disabledContext, "run", "disabled")
require.NoError(t, err)
assert.Empty(t, output.String())
common.DebugEnabled = true
contextA := context.WithValue(context.Background(), common.RequestIdKey, "plugin-console-request-a")
_, err = engine.Call(contextA, "run", "context-a")
require.NoError(t, err)
logA := output.String()
output.Reset()
contextB := context.WithValue(context.Background(), common.RequestIdKey, "plugin-console-request-b")
_, err = engine.Call(contextB, "run", "context-b")
require.NoError(t, err)
logB := output.String()
output.Reset()
_, err = engine.Call(context.Background(), "run", "background")
require.NoError(t, err)
logBackground := output.String()
assert.Contains(t, logA, "plugin-console-request-a")
assert.NotContains(t, logA, "plugin-console-request-b")
assert.Contains(t, logA, "task_plugin subsystem=runtime event=console")
assert.Contains(t, logA, "[plugin:console-debug@1.2.3] checkpoint context-a")
assert.NotContains(t, logA, "disabled")
assert.Contains(t, logB, "plugin-console-request-b")
assert.NotContains(t, logB, "plugin-console-request-a")
assert.Contains(t, logB, "[plugin:console-debug@1.2.3] checkpoint context-b")
assert.Contains(t, logBackground, "| SYSTEM |")
assert.NotContains(t, logBackground, "plugin-console-request-a")
assert.NotContains(t, logBackground, "plugin-console-request-b")
assert.Contains(t, logBackground, "[plugin:console-debug@1.2.3] checkpoint background")
}
func TestEngineMemoryLimitFollowsSetting(t *testing.T) {
previous := constant.PluginMemoryLimitMB
t.Cleanup(func() { constant.PluginMemoryLimitMB = previous })
// Many small objects: past the limit the runtime stops the call, where a
// single large ArrayBuffer would throw a RangeError instead.
const source = `export function run(n) { const keep = []; for (let i = 0; i < n; i++) keep.push({i}); return keep.length; }`
constant.PluginMemoryLimitMB = 8
limited, err := Compile(source, Options{Key: "memory", Version: "1", Concurrency: 1})
require.NoError(t, err)
_, err = limited.Call(t.Context(), "run", 400_000)
require.ErrorIs(t, err, moejs.ErrMemoryLimit)
constant.PluginMemoryLimitMB = 0
unlimited, err := Compile(source, Options{Key: "memory", Version: "1", Concurrency: 1})
require.NoError(t, err)
value, err := unlimited.Call(t.Context(), "run", 400_000)
require.NoError(t, err, "0 means no limit")
assert.Equal(t, int64(400_000), value)
}
+5 -199
View File
@@ -4,180 +4,10 @@ import (
"fmt"
"testing"
"github.com/QuantumNous/new-api/common"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const (
responsesDecodeOnly = `export const protocols = {openai_responses: {
decodeRequest: function(ctx) { return ctx; }
}};`
responsesDecodeEvents = `export const protocols = {openai_responses: {
decodeRequest: function(ctx) { return ctx; },
renderEvents: function() { return {events: [], state: null, done: false}; }
}};`
responsesDecodeFinal = `export const protocols = {openai_responses: {
decodeRequest: function(ctx) { return ctx; },
renderFinal: function(ctx, task) { return task; }
}};`
responsesDecodeBoth = `export const protocols = {openai_responses: {
decodeRequest: function(ctx) { return ctx; },
renderEvents: function() { return {events: [], state: null, done: false}; },
renderFinal: function(ctx, task) { return task; }
}};`
videoProtocolExport = `export const protocols = {openai_video: {
decodeRequest: function(ctx) { return ctx; },
render: function(ctx, task) { return task; }
}};
export function listArtifacts() { return []; }
export function buildContentRequest() { return {}; }`
)
func TestProtocolSupportsLoadErrors(t *testing.T) {
tests := []struct {
name string
protocols string
exports string
err string
}{
{
name: "bare string",
protocols: `["openai_responses"]`,
exports: responsesDecodeBoth,
err: `plugin acme protocol "openai_responses" must declare supports; replace the bare string with {name: "openai_responses", supports: [...]} choosing from "stream", "sync", "background"`,
},
{
name: "object without supports",
protocols: `[{name: "openai_responses"}]`,
exports: responsesDecodeBoth,
err: `plugin acme protocol "openai_responses" must declare supports; add supports: [...] choosing from "stream", "sync", "background"`,
},
{
name: "supports sync but only renderEvents",
protocols: `[{name: "openai_responses", supports: ["sync"]}]`,
exports: responsesDecodeEvents,
err: `plugin acme protocol "openai_responses" supports "sync" but does not export protocols.openai_responses.renderFinal; implement it or declare supports: ["stream"]`,
},
{
name: "supports sync with only decodeRequest",
protocols: `[{name: "openai_responses", supports: ["sync"]}]`,
exports: responsesDecodeOnly,
err: `plugin acme protocol "openai_responses" supports "sync" but does not export protocols.openai_responses.renderFinal; implement it`,
},
{
name: "supports stream but also exports renderFinal",
protocols: `[{name: "openai_responses", supports: ["stream"]}]`,
exports: responsesDecodeBoth,
err: `plugin acme protocol "openai_responses" exports protocols.openai_responses.renderFinal but no supported mode uses it; add "sync" or "background" to supports or remove the hook`,
},
{
name: "supports sync and background but also exports renderEvents",
protocols: `[{name: "openai_responses", supports: ["sync", "background"]}]`,
exports: responsesDecodeBoth,
err: `plugin acme protocol "openai_responses" exports protocols.openai_responses.renderEvents but no supported mode uses it; add "stream" to supports or remove the hook`,
},
{
name: "empty supports",
protocols: `[{name: "openai_responses", supports: []}]`,
exports: responsesDecodeBoth,
err: `plugin acme protocol "openai_responses" supports must contain at least one of "stream", "sync", "background"`,
},
{
name: "duplicate supports",
protocols: `[{name: "openai_responses", supports: ["stream", "stream"]}]`,
exports: responsesDecodeBoth,
err: `plugin acme protocol "openai_responses" supports must be unique`,
},
{
name: "retrieve is not a mode",
protocols: `[{name: "openai_responses", supports: ["retrieve"]}]`,
exports: responsesDecodeBoth,
err: `plugin acme protocol "openai_responses" has no mode "retrieve"; retrieval of a created response is always available and is never declared`,
},
{
name: "openai_video forbids supports",
protocols: `[{name: "openai_video", supports: ["stream"]}]`,
exports: videoProtocolExport,
err: `plugin acme protocol "openai_video" does not define modes; supports is not allowed`,
},
{
name: "unknown protocol forbids supports",
protocols: `[{name: "openai_custom", supports: ["stream"]}]`,
err: `plugin acme protocol "openai_custom" does not define modes; supports is not allowed`,
},
}
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
_, err := compileProtocolPlugin(t, "acme", `["model"]`, testCase.protocols, testCase.exports)
require.ErrorContains(t, err, testCase.err)
})
}
}
func TestProtocolSupportsHappyPaths(t *testing.T) {
tests := []struct {
name string
models string
protocols string
exports string
wantProtocols []ProtocolClaim
}{
{
name: "stream only with renderEvents",
models: `["model"]`,
protocols: `[{name: "openai_responses", supports: ["stream"]}]`,
exports: responsesDecodeEvents,
wantProtocols: []ProtocolClaim{
{Name: "openai_responses", Supports: []string{"stream"}, objectForm: true},
},
},
{
name: "sync and background with renderFinal",
models: `["model"]`,
protocols: `[{name: "openai_responses", supports: ["sync", "background"]}]`,
exports: responsesDecodeFinal,
wantProtocols: []ProtocolClaim{
{Name: "openai_responses", Supports: []string{"sync", "background"}, objectForm: true},
},
},
{
name: "all modes normalize to table order",
models: `["model"]`,
protocols: `[{name: "openai_responses", supports: ["background", "stream", "sync"]}]`,
exports: responsesDecodeBoth,
wantProtocols: []ProtocolClaim{
{Name: "openai_responses", Supports: []string{"stream", "sync", "background"}, objectForm: true},
},
},
{
name: "openai_video object without supports",
models: `["gpt-5.5", "gpt-5.6"]`,
protocols: `[{name: "openai_video", models: ["gpt-5.5"]}]`,
exports: videoProtocolExport,
wantProtocols: []ProtocolClaim{
{Name: "openai_video", Models: []string{"gpt-5.5"}, objectForm: true},
},
},
{
name: "bare openai_video",
models: `["model"]`,
protocols: `["openai_video"]`,
exports: videoProtocolExport,
wantProtocols: []ProtocolClaim{
{Name: "openai_video"},
},
},
}
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
plugin, err := compileProtocolPlugin(t, "acme", testCase.models, testCase.protocols, testCase.exports)
require.NoError(t, err)
require.Equal(t, testCase.wantProtocols, plugin.Meta.Protocols)
})
}
}
func TestCloneMetaDeepCopiesSupports(t *testing.T) {
registry := NewRegistry()
_, err := registry.Register(protocolPluginSource(
@@ -198,35 +28,11 @@ func TestCloneMetaDeepCopiesSupports(t *testing.T) {
assert.Equal(t, []string{"stream", "sync", "background"}, plugin.Meta.Protocols[0].Supports)
}
func TestMetaProtocolSupports(t *testing.T) {
streamOnly, err := compileProtocolPlugin(t, "acme", `["model"]`,
`[{name: "openai_responses", supports: ["stream"]}]`, responsesDecodeEvents)
require.NoError(t, err)
assert.True(t, streamOnly.Meta.ProtocolSupports("openai_responses", "stream"))
assert.False(t, streamOnly.Meta.ProtocolSupports("openai_responses", "sync"))
assert.False(t, streamOnly.Meta.ProtocolSupports("openai_responses", "background"))
assert.False(t, streamOnly.Meta.ProtocolSupports("openai_responses", "retrieve"))
assert.False(t, streamOnly.Meta.ProtocolSupports("openai_video", "stream"))
assert.False(t, streamOnly.Meta.ProtocolSupports("missing", "stream"))
video, err := compileProtocolPlugin(t, "acme-video", `["model"]`, `["openai_video"]`, videoProtocolExport)
require.NoError(t, err)
assert.False(t, video.Meta.ProtocolSupports("openai_video", "stream"))
}
func TestProtocolClaimMarshalEmitsSupportsInTableOrder(t *testing.T) {
plugin, err := compileProtocolPlugin(t, "acme", `["model"]`,
`[{name: "openai_responses", supports: ["background", "sync", "stream"]}]`, responsesDecodeBoth)
require.NoError(t, err)
encoded, err := common.Marshal(plugin.Meta.Protocols[0])
require.NoError(t, err)
assert.Equal(t, `{"name":"openai_responses","supports":["stream","sync","background"]}`, string(encoded))
}
func compileProtocolPlugin(t *testing.T, key, models, protocols, exports string) (*LoadedPlugin, error) {
t.Helper()
return CompilePlugin(protocolPluginSource(key, models, protocols, exports), Options{})
}
const responsesDecodeBoth = `export const protocols = {openai_responses: {
decodeRequest: function(ctx) { return ctx; },
renderEvents: function() { return {events: [], state: null, done: false}; },
renderFinal: function(ctx, task) { return task; }
}};`
func protocolPluginSource(key, models, protocols, exports string) string {
return fmt.Sprintf(`
+2 -2106
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+22 -633
View File
@@ -1,7 +1,6 @@
package jsplugin
import (
"encoding/json"
"fmt"
"maps"
"net/http"
@@ -11,208 +10,11 @@ import (
"strings"
"time"
"github.com/MoeForge/moego/regexp"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/pluginkit"
"github.com/gin-gonic/gin"
)
type RouteType string
const (
RouteTypeSubmit RouteType = "submit"
RouteTypeQuery RouteType = "query"
RouteTypeDynamic RouteType = "dynamic"
)
type Route struct {
Method string `json:"method"`
Path string `json:"path"`
Type RouteType `json:"type"`
Action string `json:"action,omitempty"`
Decode string `json:"decode,omitempty"`
Render string `json:"render,omitempty"`
TaskIDParam string `json:"taskIdParam,omitempty"`
// RetainResult, when explicitly false on a submit or dynamic route, tells
// the host not to persist the upstream snapshot of an immediate terminal
// result and to treat the task as not found on every retrieval surface
// afterwards. nil means the route did not declare it (retain).
RetainResult *bool `json:"retainResult,omitempty"`
// Models restricts this route to the listed models. The host matches the
// canonical top-level "model" body field before any JS hook runs; empty
// means unrestricted. Must be a subset of meta.models.
Models []string `json:"models,omitempty"`
}
// ProtocolClaim is one entry of meta.protocols. Models narrows the protocol's
// endpoint bindings to a subset of meta.models; empty binds every model.
// Supports names the request forms a mode-bearing protocol accepts; decode
// and normalize rewrite it into host-table order.
type ProtocolClaim struct {
Name string `json:"name"`
Models []string `json:"models,omitempty"`
Supports []string `json:"supports,omitempty"`
objectForm bool
}
// ProtocolMode is one client request form a host protocol operation accepts
// and the plugin hook that implements it.
type ProtocolMode struct {
Name string
Hook string
}
type BodyKind string
const (
BodyNone BodyKind = "none"
BodyJSON BodyKind = "json"
BodyForm BodyKind = "form"
BodyMultipart BodyKind = "multipart"
)
type HostProtocolOperation struct {
Name string
Methods []string
Path string
BodyKinds []BodyKind
ModelField string
RequiredProtocolMembers []string
Modes []ProtocolMode
RequiredDriverHooks []string
}
type HostProtocolDefinition struct {
Name string
Operations []HostProtocolOperation
}
var hostProtocols = []HostProtocolDefinition{
{Name: "openai_responses", Operations: []HostProtocolOperation{
{Name: "create", Methods: []string{http.MethodPost}, Path: "/v1/responses", BodyKinds: []BodyKind{BodyJSON}, ModelField: "model", RequiredProtocolMembers: []string{"decodeRequest"}, Modes: []ProtocolMode{{Name: "stream", Hook: "renderEvents"}, {Name: "sync", Hook: "renderFinal"}, {Name: "background", Hook: "renderFinal"}}},
{Name: "retrieve", Methods: []string{http.MethodGet}, Path: "/v1/responses/:response_id", BodyKinds: []BodyKind{BodyNone}},
}},
{Name: "openai_video", Operations: []HostProtocolOperation{
{Name: "create", Methods: []string{http.MethodPost}, Path: "/v1/videos", BodyKinds: []BodyKind{BodyJSON, BodyMultipart}, ModelField: "model", RequiredProtocolMembers: []string{"decodeRequest"}},
{Name: "retrieve", Methods: []string{http.MethodGet}, Path: "/v1/videos/:task_id", BodyKinds: []BodyKind{BodyNone}, RequiredProtocolMembers: []string{"render"}},
{Name: "content", Methods: []string{http.MethodGet, http.MethodHead}, Path: "/v1/videos/:task_id/content", BodyKinds: []BodyKind{BodyNone}, RequiredDriverHooks: []string{"listArtifacts", "buildContentRequest"}},
}},
// The OpenAI Images API is synchronous: both operations create a task and
// the host answers with the rendered image response once the task is
// terminal, so there is no retrieve operation and no request modes.
{Name: ProtocolOpenAIImage, Operations: []HostProtocolOperation{
{Name: "generate", Methods: []string{http.MethodPost}, Path: "/v1/images/generations", BodyKinds: []BodyKind{BodyJSON}, ModelField: "model", RequiredProtocolMembers: []string{"decodeRequest", "render"}},
{Name: "edit", Methods: []string{http.MethodPost}, Path: "/v1/images/edits", BodyKinds: []BodyKind{BodyJSON, BodyMultipart}, ModelField: "model", RequiredProtocolMembers: []string{"decodeRequest", "render"}},
}},
}
// ProtocolOpenAIImage is the host protocol that serves the OpenAI Images API
// (`POST /v1/images/generations` and `POST /v1/images/edits`) from a plugin.
const ProtocolOpenAIImage = "openai_image"
func HostProtocol(name string) (HostProtocolDefinition, bool) {
for _, definition := range hostProtocols {
if definition.Name == name {
return definition, true
}
}
return HostProtocolDefinition{}, false
}
func HostProtocols() []HostProtocolDefinition {
definitions := make([]HostProtocolDefinition, len(hostProtocols))
for index, definition := range hostProtocols {
definitions[index] = definition
definitions[index].Operations = append([]HostProtocolOperation(nil), definition.Operations...)
for operationIndex := range definitions[index].Operations {
operation := &definitions[index].Operations[operationIndex]
operation.Methods = append([]string(nil), operation.Methods...)
operation.BodyKinds = append([]BodyKind(nil), operation.BodyKinds...)
operation.RequiredProtocolMembers = append([]string(nil), operation.RequiredProtocolMembers...)
operation.Modes = append([]ProtocolMode(nil), operation.Modes...)
operation.RequiredDriverHooks = append([]string(nil), operation.RequiredDriverHooks...)
}
}
return definitions
}
// DefinedModes returns each distinct mode on the protocol in host-table order.
func (d HostProtocolDefinition) DefinedModes() []ProtocolMode {
seen := make(map[string]struct{})
modes := make([]ProtocolMode, 0)
for _, operation := range d.Operations {
for _, mode := range operation.Modes {
if _, exists := seen[mode.Name]; exists {
continue
}
seen[mode.Name] = struct{}{}
modes = append(modes, mode)
}
}
return modes
}
func orderProtocolSupports(protocol string, supports []string) []string {
if len(supports) == 0 {
return supports
}
definition, ok := HostProtocol(protocol)
if !ok {
return supports
}
rank := make(map[string]int)
for index, mode := range definition.DefinedModes() {
rank[mode.Name] = index
}
ordered := append([]string(nil), supports...)
slices.SortStableFunc(ordered, func(left, right string) int {
leftRank, leftKnown := rank[left]
rightRank, rightKnown := rank[right]
switch {
case leftKnown && rightKnown:
if leftRank < rightRank {
return -1
}
if leftRank > rightRank {
return 1
}
return 0
case leftKnown:
return -1
case rightKnown:
return 1
default:
return 0
}
})
return ordered
}
func LookupHostProtocolOperation(method, path string) (string, HostProtocolOperation, bool) {
method = strings.ToUpper(strings.TrimSpace(method))
for _, definition := range hostProtocols {
for _, operation := range definition.Operations {
if operation.Path != path || operation.ModelField == "" {
continue
}
if slices.Contains(operation.Methods, method) {
return definition.Name, operation, true
}
}
}
return "", HostProtocolOperation{}, false
}
// RouteBinding is one address a plugin serves. Besides each declared route the
// host registers its copy under /{key} (Pinned), which always reaches this
// plugin. A declared route whose first segment is the key, or a proper prefix
// of it (/ali for alibaba, /suno for sunoapi), already does (OwnPrefix) and
// gets no copy.
type RouteBinding struct {
Plugin *LoadedPlugin
Route Route
Pinned bool
OwnPrefix bool
}
// RouteGroup is one method and path shape of the inner router with every
// binding that serves it, in ascending key order. GinPath names each wildcard
// by its segment position (:s2, *s3), so bindings that name the same position
@@ -292,132 +94,17 @@ type PinnedEndpoint struct {
Candidates []ProtocolBinding
}
// FileReference returns the opaque ref of the index-th uploaded file in a
// multipart field. The first file keeps the historical `request_file:<field>`
// spelling; later files in the same repeated field (`image[]`, `image[]`)
// append `#<index>` so a plugin can address each of them.
func FileReference(field string, index int) string {
if index <= 0 {
return "request_file:" + field
// DiscardsImmediateResult reports whether this submission delivers a terminal
// result inline and omits its task data from storage.
func DiscardsImmediateResult(c *gin.Context) bool {
route, _ := common.GetContextKeyType[PinnedRoute](c, ContextKeyPinnedRoute)
if route.Route.RetainResult != nil && !*route.Route.RetainResult {
return true
}
return "request_file:" + field + "#" + strconv.Itoa(index)
endpoint, _ := common.GetContextKeyType[PinnedEndpoint](c, ContextKeyPinnedEndpoint)
return endpoint.Protocol == ProtocolOpenAIImage
}
// ParseFileReference resolves a ref produced by FileReference back to the
// multipart field and the zero-based file index within that field.
func ParseFileReference(ref string) (field string, index int, ok bool) {
rest, found := strings.CutPrefix(ref, "request_file:")
if !found || rest == "" {
return "", 0, false
}
field, suffix, hasIndex := strings.Cut(rest, "#")
if field == "" {
return "", 0, false
}
if !hasIndex {
return field, 0, true
}
parsed, err := strconv.Atoi(suffix)
if err != nil || parsed < 0 || strconv.Itoa(parsed) != suffix {
return "", 0, false
}
return field, parsed, true
}
// RouteRequestContext is the canonical request view exposed to declarative
// routing hooks. RequestBody contains decoded JSON or multipart text fields;
// raw binary and multipart file bytes remain host-owned.
type RouteRequestContext struct {
Path string `json:"path"`
Method string `json:"method"`
Params map[string]string `json:"params"`
Query map[string][]string `json:"query"`
Body any `json:"body"`
// Headers is the client's request headers without gateway credentials,
// which hooks read as requestHeaders.
Headers map[string]string `json:"-"`
Files []map[string]any `json:"-"`
RequestBody any `json:"-"`
// BodyText is the JSON body as the client sent it, which JSValueFor
// gives to plugins that preserve JSON order; Body stays the Go value the
// host reads. Body storage never changes these bytes, which the engine
// parses in place.
BodyText json.RawMessage `json:"-"`
}
// JSValue shares the request with hooks without copying it: the engine never
// writes JavaScript changes back into Go values, so the request must only stay
// unchanged while a hook runs. Missing params, query and headers still reach
// hooks as empty objects rather than null.
func (r RouteRequestContext) JSValue() map[string]any {
params, query, headers := r.Params, r.Query, r.Headers
if params == nil {
params = map[string]string{}
}
if query == nil {
query = map[string][]string{}
}
if headers == nil {
headers = map[string]string{}
}
return map[string]any{
"path": r.Path,
"method": r.Method,
"params": params,
"query": query,
"requestHeaders": headers,
"body": r.Body,
}
}
// JSValueFor is JSValue for the decode hooks of the plugin meta describes. A
// plugin that preserves JSON order receives a JSON body as its text, which the
// engine parses in place, members in the client's order: a decoder reads the
// body, so it is parsed for every call.
func (r RouteRequestContext) JSValueFor(meta Meta) map[string]any {
value := r.JSValue()
if len(r.BodyText) > 0 && meta.PreservesJSONOrder() {
value["body"] = map[string]any{"kind": string(BodyJSON), "value": RawJSON(r.BodyText)}
}
return value
}
type ProtocolRequestContext struct {
RouteRequestContext
Protocol string `json:"protocol"`
Operation string `json:"operation"`
Model string `json:"model"`
// UpstreamModel is the declared machine identity when Model is a
// channel-mapping alias; empty otherwise. Decode hooks that key rate
// tables or request shaping by model must use it over Model.
UpstreamModel string `json:"upstreamModel,omitempty"`
Stream bool `json:"stream"`
}
func (p ProtocolRequestContext) JSValue() map[string]any {
return p.withProtocol(p.RouteRequestContext.JSValue())
}
// JSValueFor is RouteRequestContext.JSValueFor with the protocol fields.
func (p ProtocolRequestContext) JSValueFor(meta Meta) map[string]any {
return p.withProtocol(p.RouteRequestContext.JSValueFor(meta))
}
func (p ProtocolRequestContext) withProtocol(value map[string]any) map[string]any {
value["protocol"] = p.Protocol
value["operation"] = p.Operation
value["model"] = p.Model
if p.UpstreamModel != "" {
value["upstreamModel"] = p.UpstreamModel
}
value["stream"] = p.Stream
return value
}
// SupportsHostProtocol reports whether the current host release has a
// concrete wire/state machine for an otherwise valid manifest endpoint.
func SupportsHostProtocol(protocol string) bool { _, ok := HostProtocol(protocol); return ok }
// RoutingGeneration is an immutable, request-pinnable view of all effective
// plugins and their deterministic routing indexes.
type RoutingGeneration struct {
@@ -441,64 +128,6 @@ type RoutingGeneration struct {
skipped []SkippedRoute
}
var (
routeMethodPattern = regexp.MustCompile(`^(GET|POST|PUT|PATCH|DELETE)$`)
pathNamePattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
staticSegment = regexp.MustCompile(`^[A-Za-z0-9._~-]+$`)
memberNamePattern = regexp.MustCompile(`^[A-Za-z_$][A-Za-z0-9_$]*$`)
)
// reservedRouteNamespaces are host paths a plugin route may never enter:
// console pages, assets and the generic task routes. The other host
// namespaces, such as /api, follow the outer router's static routes and are
// decided at admission.
var reservedRouteNamespaces = []string{
"/assets",
"/setup",
"/v1/tasks",
"/console",
"/login",
"/forbidden",
"/sign-in",
"/sign-up",
"/forgot-password",
"/oauth",
"/otp",
"/register",
"/reset",
"/privacy-policy",
"/user-agreement",
"/about",
"/pricing",
"/rankings",
"/user",
"/401",
"/403",
"/404",
"/500",
"/503",
"/chat2link",
"/system-settings",
"/channels",
"/chat",
"/dashboard",
"/errors",
"/keys",
"/models",
"/playground",
"/profile",
"/redemption-codes",
"/request-processing",
"/security",
"/subscriptions",
"/system-info",
"/task-plugins",
"/upstream-monitor",
"/usage-logs",
"/users",
"/wallet",
}
func (g *RoutingGeneration) Get(key string) (*LoadedPlugin, bool) {
if g == nil {
return nil, false
@@ -553,7 +182,7 @@ func (g *RoutingGeneration) CanonicalModel(model string) (string, bool) {
if _, ok := g.byModel[model]; ok {
return model, true
}
declared, ok := g.canonicalModelByFold[asciiFold(model)]
declared, ok := g.canonicalModelByFold[ASCIIFold(model)]
return declared, ok
}
@@ -574,11 +203,11 @@ func (g *RoutingGeneration) LookupDeclaredRoutes(method, path string) []RouteBin
if g == nil {
return nil
}
normalizedMethod, err := normalizeRouteMethod(method)
normalizedMethod, err := pluginkit.NormalizeRouteMethod(method)
if err != nil {
return nil
}
shape, err := routePathShape(path)
shape, err := pluginkit.RoutePathShape(path)
if err != nil {
return nil
}
@@ -589,7 +218,7 @@ func (g *RoutingGeneration) LookupEndpoint(method, path, model string) (Protocol
if g == nil {
return ProtocolBinding{}, false
}
normalizedMethod, err := normalizeRouteMethod(method)
normalizedMethod, err := pluginkit.NormalizeRouteMethod(method)
if err != nil {
return ProtocolBinding{}, false
}
@@ -606,7 +235,7 @@ func (g *RoutingGeneration) LookupEndpointCandidates(method, path, model string)
if g == nil {
return nil
}
normalizedMethod, err := normalizeRouteMethod(method)
normalizedMethod, err := pluginkit.NormalizeRouteMethod(method)
if err != nil {
return nil
}
@@ -644,7 +273,7 @@ func (g *RoutingGeneration) RouteGroups() []RouteGroup {
if _, skip := skipped[binding.Plugin.Meta.Key+" "+binding.Route.Method+" "+binding.Route.Path]; skip {
continue
}
shape, err := routePathShape(binding.Route.Path)
shape, err := pluginkit.RoutePathShape(binding.Route.Path)
if err != nil {
continue
}
@@ -785,250 +414,6 @@ func cloneStringSet(source map[string]struct{}) map[string]struct{} {
return clone
}
func normalizeRouteMethod(method string) (string, error) {
method = strings.ToUpper(strings.TrimSpace(method))
if !routeMethodPattern.MatchString(method) {
return "", fmt.Errorf("plugin route method %q is not supported", method)
}
return method, nil
}
// NormalizeRoutePath validates the canonical path syntax used by plugin route
// declarations. A trailing slash is allowed and remains significant.
func NormalizeRoutePath(routePath string) (string, error) {
if routePath == "" || routePath[0] != '/' {
return "", fmt.Errorf("plugin route path must start with /")
}
if routePath == "/" {
return "", fmt.Errorf("plugin route path / is reserved")
}
if strings.ContainsAny(routePath, "?#%") {
return "", fmt.Errorf("plugin route path %q must not contain a query, fragment, or percent-encoding", routePath)
}
if strings.Contains(routePath, "//") {
return "", fmt.Errorf("plugin route path %q must not contain empty segments", routePath)
}
segments := strings.Split(strings.TrimPrefix(routePath, "/"), "/")
seenNames := make(map[string]struct{})
for index, segment := range segments {
if segment == "" && index == len(segments)-1 {
continue
}
if segment == "." || segment == ".." {
return "", fmt.Errorf("plugin route path %q must not contain dot segments", routePath)
}
if after, ok := strings.CutPrefix(segment, ":"); ok {
name := after
if !pathNamePattern.MatchString(name) {
return "", fmt.Errorf("plugin route path %q has invalid parameter %q", routePath, segment)
}
if _, exists := seenNames[name]; exists {
return "", fmt.Errorf("plugin route path %q repeats parameter %q", routePath, name)
}
seenNames[name] = struct{}{}
continue
}
if after, ok := strings.CutPrefix(segment, "*"); ok {
name := after
if index != len(segments)-1 || !pathNamePattern.MatchString(name) {
return "", fmt.Errorf("plugin route path %q has an invalid catch-all segment", routePath)
}
if _, exists := seenNames[name]; exists {
return "", fmt.Errorf("plugin route path %q repeats parameter %q", routePath, name)
}
seenNames[name] = struct{}{}
continue
}
if !staticSegment.MatchString(segment) {
return "", fmt.Errorf("plugin route path %q has invalid segment %q", routePath, segment)
}
}
return routePath, nil
}
func routePathShape(routePath string) (string, error) {
normalized, err := NormalizeRoutePath(routePath)
if err != nil {
return "", err
}
segments := strings.Split(strings.TrimPrefix(normalized, "/"), "/")
for index, segment := range segments {
if strings.HasPrefix(segment, ":") {
segments[index] = ":"
} else if strings.HasPrefix(segment, "*") {
segments[index] = "*"
}
}
return "/" + strings.Join(segments, "/"), nil
}
func endpointIndexKey(method, path, model string) string {
return method + "\x00" + path + "\x00" + model
}
func intersectingReservedNamespace(routePath string) (string, bool) {
for _, namespace := range reservedRouteNamespaces {
if routePatternIntersectsNamespace(routePath, namespace) {
return namespace, true
}
}
return "", false
}
func routePatternIntersectsNamespace(routePath, namespace string) bool {
routeSegments := strings.Split(strings.Trim(strings.TrimPrefix(routePath, "/"), "/"), "/")
namespaceSegments := strings.Split(strings.TrimPrefix(namespace, "/"), "/")
for index, namespaceSegment := range namespaceSegments {
if index >= len(routeSegments) {
return false
}
routeSegment := routeSegments[index]
if strings.HasPrefix(routeSegment, "*") {
return true
}
if !strings.HasPrefix(routeSegment, ":") && routeSegment != namespaceSegment {
return false
}
}
return true
}
func validateRoute(route *Route) error {
if route.Method != strings.ToUpper(strings.TrimSpace(route.Method)) {
return fmt.Errorf("plugin route method %q must use canonical uppercase spelling", route.Method)
}
method, err := normalizeRouteMethod(route.Method)
if err != nil {
return err
}
route.Method = method
route.Path, err = NormalizeRoutePath(route.Path)
if err != nil {
return err
}
if namespace, reserved := intersectingReservedNamespace(route.Path); reserved {
return fmt.Errorf("plugin route path %q intersects reserved namespace %s", route.Path, namespace)
}
switch route.Type {
case RouteTypeSubmit:
if route.Decode == "" || route.Render == "" || route.TaskIDParam != "" {
return fmt.Errorf("submit route %s %s must declare decode and render and must not declare taskIdParam", route.Method, route.Path)
}
case RouteTypeQuery:
if route.Decode != "" || strings.TrimSpace(route.Render) == "" {
return fmt.Errorf("query route %s %s must declare render and must not declare decode", route.Method, route.Path)
}
if route.Action != "" {
return fmt.Errorf("query route %s %s must not declare action", route.Method, route.Path)
}
if route.RetainResult != nil {
return fmt.Errorf("query route %s %s must not declare retainResult", route.Method, route.Path)
}
if route.TaskIDParam == "" {
route.TaskIDParam = "task_id"
}
if !pathNamePattern.MatchString(route.TaskIDParam) {
return fmt.Errorf("query route %s %s has invalid taskIdParam %q", route.Method, route.Path, route.TaskIDParam)
}
case RouteTypeDynamic:
if route.Decode == "" || route.Render == "" || route.TaskIDParam != "" {
return fmt.Errorf("dynamic route %s %s must declare decode and render and must not declare taskIdParam", route.Method, route.Path)
}
default:
return fmt.Errorf("plugin route %s %s has unsupported type %q", route.Method, route.Path, route.Type)
}
if route.Decode != "" && !memberNamePattern.MatchString(route.Decode) {
return fmt.Errorf("plugin route %s %s has invalid decode %q", route.Method, route.Path, route.Decode)
}
if route.Render != "" && !memberNamePattern.MatchString(route.Render) {
return fmt.Errorf("plugin route %s %s has invalid render %q", route.Method, route.Path, route.Render)
}
if strings.TrimSpace(route.Action) != route.Action {
return fmt.Errorf("plugin route %s %s action must not have surrounding whitespace", route.Method, route.Path)
}
if len(route.Models) > 0 {
if route.Type == RouteTypeQuery {
return fmt.Errorf("query route %s %s must not declare models", route.Method, route.Path)
}
if err := validateModelScope(route.Models, fmt.Sprintf("route %s %s", route.Method, route.Path)); err != nil {
return err
}
}
return nil
}
// validateModelScope enforces the shared rules for route.models and
// per-protocol models entries: non-empty canonical names, no duplicates.
func validateModelScope(models []string, subject string) error {
seen := make(map[string]struct{}, len(models))
for _, model := range models {
if strings.TrimSpace(model) == "" || strings.TrimSpace(model) != model {
return fmt.Errorf("plugin %s models must contain non-empty canonical names", subject)
}
folded := asciiFold(model)
if _, duplicate := seen[folded]; duplicate {
return fmt.Errorf("plugin %s models must be unique case-insensitively", subject)
}
seen[folded] = struct{}{}
}
return nil
}
func pathHasParameter(routePath, name string) bool {
return slices.Contains(strings.Split(routePath, "/"), ":"+name)
}
// TaskIDInQuery reports whether a query route reads its task id from the
// query string, as the MiniMax v1 query does (?task_id=): the route's path
// has no parameter named taskIdParam.
func (r Route) TaskIDInQuery() bool {
return r.Type == RouteTypeQuery && !pathHasParameter(r.Path, r.TaskIDParam)
}
// routeHasOwnPrefix reports whether a declared route already lives under the
// plugin's own address: its first segment is the key or a proper prefix of it.
func routeHasOwnPrefix(key, routePath string) bool {
first, _, _ := strings.Cut(strings.TrimPrefix(routePath, "/"), "/")
return first != "" && strings.HasPrefix(key, first)
}
// PluginRouteBindings returns the addresses plugin serves: each declared route
// and, unless the route lives under the plugin's own prefix, its /{key} copy.
// A plugin that declares the copy's address itself (TypeSafe 1.2.0 declares
// /v1/systemone and /typesafe/v1/systemone) serves it by that declaration.
func PluginRouteBindings(plugin *LoadedPlugin) []RouteBinding {
key := plugin.Meta.Key
declared := make(map[string]struct{}, len(plugin.Meta.Routes))
for _, route := range plugin.Meta.Routes {
// Declared paths were validated at load.
shape, _ := routePathShape(route.Path)
declared[route.Method+" "+shape] = struct{}{}
}
bindings := make([]RouteBinding, 0, 2*len(plugin.Meta.Routes))
for _, route := range plugin.Meta.Routes {
if routeHasOwnPrefix(key, route.Path) {
bindings = append(bindings, RouteBinding{Plugin: plugin, Route: route, OwnPrefix: true})
continue
}
bindings = append(bindings, RouteBinding{Plugin: plugin, Route: route})
pinned := route
pinned.Path = "/" + key + route.Path
shape, _ := routePathShape(pinned.Path)
if _, exists := declared[route.Method+" "+shape]; !exists {
bindings = append(bindings, RouteBinding{Plugin: plugin, Route: pinned, Pinned: true})
}
}
return bindings
}
func ResolveRouteAction(route Route, resolvedAction string) string {
if strings.TrimSpace(resolvedAction) != "" {
return resolvedAction
}
return route.Action
}
func buildRoutingGeneration(factory, override map[string]*LoadedPlugin, number uint64) (*RoutingGeneration, error) {
effective := effectivePlugins(factory, override)
return buildRoutingGenerationFromPlugins(effective, number)
@@ -1148,7 +533,7 @@ func buildRoutingGenerationFromPlugins(effective map[string]*LoadedPlugin, numbe
if _, exists := generation.byModel[model]; !exists {
generation.byModel[model] = plugin
}
folded := asciiFold(model)
folded := ASCIIFold(model)
if existing, exists := generation.canonicalModelByFold[folded]; exists {
if existing != model {
otherKey := plugin.Meta.Key
@@ -1171,7 +556,7 @@ func buildRoutingGenerationFromPlugins(effective map[string]*LoadedPlugin, numbe
// Plugins may share a path shape; the request resolves which one
// serves it (see PinnedRoute).
for _, binding := range PluginRouteBindings(plugin) {
shape, err := routePathShape(binding.Route.Path)
shape, err := pluginkit.RoutePathShape(binding.Route.Path)
if err != nil {
return nil, err
}
@@ -1230,3 +615,7 @@ func PreflightRoutingConflict(current *RoutingGeneration, candidate *LoadedPlugi
_, err := buildRoutingGenerationFromPlugins(effective, number)
return err
}
func endpointIndexKey(method, path, model string) string {
return method + "\x00" + path + "\x00" + model
}
-583
View File
@@ -9,7 +9,6 @@ import (
"os"
"strings"
"testing"
"time"
"github.com/QuantumNous/new-api/constant"
"github.com/gin-gonic/gin"
@@ -81,27 +80,6 @@ func TestRegistryIndexesSharedEndpointCandidatesForDistinctLegacyProviders(t *te
assert.Empty(t, registry.RoutingErrors())
}
func TestSupportsRegisteredHostProtocols(t *testing.T) {
assert.True(t, SupportsHostProtocol("openai_responses"))
assert.True(t, SupportsHostProtocol("openai_video"))
assert.True(t, SupportsHostProtocol(ProtocolOpenAIImage))
assert.False(t, SupportsHostProtocol("plugin_owned_wire"))
}
func TestLookupHostProtocolOperationExcludesRetrieveWithoutModelField(t *testing.T) {
_, _, ok := LookupHostProtocolOperation(http.MethodGet, "/v1/responses/:response_id")
assert.False(t, ok)
_, _, ok = LookupHostProtocolOperation(http.MethodPost, "/v1/responses")
assert.True(t, ok)
for _, path := range []string{"/v1/images/generations", "/v1/images/edits"} {
protocol, operation, found := LookupHostProtocolOperation(http.MethodPost, path)
require.True(t, found, path)
assert.Equal(t, ProtocolOpenAIImage, protocol)
assert.Equal(t, "model", operation.ModelField)
assert.Empty(t, operation.Modes, "the synchronous image protocol has no request modes")
}
}
// The OpenAI Images protocol is claimed in bare-string form, binds both image
// endpoints for every declared model, and requires the render hook that shapes
// the synchronous response.
@@ -136,30 +114,6 @@ func TestOpenAIImageProtocolClaimBindsBothEndpointsAndRequiresRender(t *testing.
require.ErrorContains(t, err, "does not define modes")
}
func TestFileReferenceRoundTripAddressesRepeatedFieldFiles(t *testing.T) {
assert.Equal(t, "request_file:image[]", FileReference("image[]", 0))
assert.Equal(t, "request_file:image[]#2", FileReference("image[]", 2))
for _, tc := range []struct {
ref string
field string
index int
ok bool
}{
{"request_file:input_reference", "input_reference", 0, true},
{"request_file:image[]#1", "image[]", 1, true},
{"request_file:image[]#01", "", 0, false},
{"request_file:image[]#-1", "", 0, false},
{"request_file:#1", "", 0, false},
{"request_file:", "", 0, false},
{"image", "", 0, false},
} {
field, index, ok := ParseFileReference(tc.ref)
assert.Equal(t, tc.ok, ok, tc.ref)
assert.Equal(t, tc.field, field, tc.ref)
assert.Equal(t, tc.index, index, tc.ref)
}
}
func TestPerProtocolModelsNarrowEndpointBindings(t *testing.T) {
registry := NewRegistry()
plugin := mustCompileRoutingPlugin(t, "narrow-protocol", 50, `["gpt-5.5", "gpt-5.6"]`,
@@ -254,246 +208,6 @@ func TestPerProtocolModelsAcceptSharedPluginClaims(t *testing.T) {
}
}
func TestProtocolClaimDecodeAndValidation(t *testing.T) {
tests := []struct {
name string
models string
metaFields string
exports string
errContains string
wantProtocols []ProtocolClaim
}{
{
name: "string and object entries mix",
models: `["gpt-5.5", "gpt-5.6"]`,
metaFields: `protocols: [{name: "openai_responses", supports: ["stream", "sync", "background"]}, {name: "openai_video", models: ["gpt-5.5"]}],`,
exports: `export const protocols = {
openai_responses: {
decodeRequest: function(ctx) { return ctx; },
renderEvents: function() { return {events: [], state: null, done: false}; },
renderFinal: function(ctx, task) { return task; }
},
openai_video: {
decodeRequest: function(ctx) { return ctx; },
render: function(ctx, task) { return task; }
}
};
export function listArtifacts() { return []; }
export function buildContentRequest() { return {}; }`,
wantProtocols: []ProtocolClaim{
{Name: "openai_responses", Supports: []string{"stream", "sync", "background"}, objectForm: true},
{Name: "openai_video", Models: []string{"gpt-5.5"}, objectForm: true},
},
},
{
name: "absent protocols is fine",
models: `["gpt-5.5"]`,
wantProtocols: []ProtocolClaim{},
},
{
name: "object with unknown field",
models: `["gpt-5.5"]`,
metaFields: `protocols: [{name: "openai_responses", models: ["gpt-5.5"], extra: true}],`,
errContains: `unknown field "extra"`,
},
{
name: "model outside meta models",
models: `["gpt-5.5"]`,
metaFields: `protocols: [{name: "openai_responses", models: ["gpt-9.9"], supports: ["stream", "sync", "background"]}],`,
errContains: "is not declared in plugin meta models",
},
{
name: "duplicate models in claim",
models: `["gpt-5.5"]`,
metaFields: `protocols: [{name: "openai_responses", models: ["gpt-5.5", "gpt-5.5"], supports: ["stream", "sync", "background"]}],`,
errContains: "models must be unique",
},
{
name: "blank model in claim",
models: `["gpt-5.5"]`,
metaFields: `protocols: [{name: "openai_responses", models: [" "], supports: ["stream", "sync", "background"]}],`,
errContains: "non-empty canonical names",
},
{
name: "empty models rejected",
models: `["gpt-5.5"]`,
metaFields: `protocols: [{name: "openai_responses", models: []}],`,
errContains: "models must contain at least one model",
},
{
name: "explicit null protocols",
models: `["gpt-5.5"]`,
metaFields: `protocols: null,`,
errContains: "must be an array",
},
}
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
exports := testCase.exports
if exports == "" && testCase.errContains != "" {
exports = routingProtocolExport("openai_responses")
}
plugin, err := CompilePlugin(
routingTestPluginSource("claim-decode", 0, testCase.models, testCase.metaFields, exports),
Options{},
)
if testCase.errContains != "" {
require.ErrorContains(t, err, testCase.errContains)
return
}
require.NoError(t, err)
require.Equal(t, testCase.wantProtocols, plugin.Meta.Protocols)
})
}
}
func TestRouteModelsDecodeAndValidation(t *testing.T) {
routeExports := `export const native = {
decodeJob: function(ctx) { return {kind: "submit", model: "gpt-5.5", requestBody: ctx.body.value}; },
jobCreated: function(ctx, task) { return task; },
jobStatus: function(ctx, task) { return task; }
};`
tests := []struct {
name string
models string
metaFields string
errContains string
}{
{
name: "submit route with models",
models: `["gpt-5.5", "gpt-5.6"]`,
metaFields: `routes: [{method: "POST", path: "/v1/batch", type: "submit", models: ["gpt-5.5"], decode: "decodeJob", render: "jobCreated"}],`,
},
{
name: "query route rejects models",
models: `["gpt-5.5"]`,
metaFields: `routes: [{method: "GET", path: "/v1/batch/:task_id", type: "query", models: ["gpt-5.5"], render: "jobStatus"}],`,
errContains: "must not declare models",
},
{
name: "model outside meta models",
models: `["gpt-5.5"]`,
metaFields: `routes: [{method: "POST", path: "/v1/batch", type: "submit", models: ["gpt-9.9"], decode: "decodeJob", render: "jobCreated"}],`,
errContains: "is not declared in plugin meta models",
},
{
name: "duplicate models",
models: `["gpt-5.5"]`,
metaFields: `routes: [{method: "POST", path: "/v1/batch", type: "submit", models: ["gpt-5.5", "gpt-5.5"], decode: "decodeJob", render: "jobCreated"}],`,
errContains: "models must be unique",
},
{
name: "blank model entry",
models: `["gpt-5.5"]`,
metaFields: `routes: [{method: "POST", path: "/v1/batch", type: "submit", models: [" "], decode: "decodeJob", render: "jobCreated"}],`,
errContains: "non-empty canonical names",
},
{
name: "empty models rejected",
models: `["gpt-5.5"]`,
metaFields: `routes: [{method: "POST", path: "/v1/batch", type: "submit", models: [], decode: "decodeJob", render: "jobCreated"}],`,
errContains: "models must contain at least one model",
},
{
name: "query route empty models rejected",
models: `["gpt-5.5"]`,
metaFields: `routes: [{method: "GET", path: "/v1/batch/:task_id", type: "query", models: [], render: "jobStatus"}],`,
errContains: "models must contain at least one model",
},
}
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
plugin, err := CompilePlugin(
routingTestPluginSource("route-models", 0, testCase.models, testCase.metaFields, routeExports),
Options{},
)
if testCase.errContains != "" {
require.ErrorContains(t, err, testCase.errContains)
return
}
require.NoError(t, err)
require.Len(t, plugin.Meta.Routes, 1)
assert.Equal(t, []string{"gpt-5.5"}, plugin.Meta.Routes[0].Models)
})
}
}
func TestRouteRetainResultDecodeAndValidation(t *testing.T) {
routeExports := `export const native = {
decodeJob: function(ctx) { return {kind: "submit", model: "gpt-5.5", requestBody: ctx.body.value}; },
jobCreated: function(ctx, task) { return task; },
jobStatus: function(ctx, task) { return task; }
};`
falseValue := false
tests := []struct {
name string
metaFields string
want *bool
errContains string
}{
{
name: "undeclared route retains",
metaFields: `routes: [{method: "POST", path: "/v1/batch", type: "submit", decode: "decodeJob", render: "jobCreated"}],`,
},
{
name: "submit route declines retention",
metaFields: `routes: [{method: "POST", path: "/v1/batch", type: "submit", decode: "decodeJob", render: "jobCreated", retainResult: false}],`,
want: &falseValue,
},
{
name: "query route rejects retainResult",
metaFields: `routes: [{method: "GET", path: "/v1/batch/:task_id", type: "query", render: "jobStatus", retainResult: true}],`,
errContains: "must not declare retainResult",
},
{
name: "non-boolean value",
metaFields: `routes: [{method: "POST", path: "/v1/batch", type: "submit", decode: "decodeJob", render: "jobCreated", retainResult: "no"}],`,
errContains: "retainResult must be a boolean",
},
}
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
plugin, err := CompilePlugin(
routingTestPluginSource("route-retain", 0, `["gpt-5.5"]`, testCase.metaFields, routeExports),
Options{},
)
if testCase.errContains != "" {
require.ErrorContains(t, err, testCase.errContains)
return
}
require.NoError(t, err)
require.Len(t, plugin.Meta.Routes, 1)
assert.Equal(t, testCase.want, plugin.Meta.Routes[0].RetainResult)
})
}
}
func TestRouteRequestContextKeepsFormAndMultipartValuesAcrossDecoderWrites(t *testing.T) {
plugin, err := CompilePlugin(routingTestPluginSource("route-request-writes", 0, `["gpt-5.5"]`, "", `
export function decodeJob(ctx) {
const seen = {
prompt: ctx.body.fields.prompt[0],
filename: ctx.body.files[0].filename,
params: Object.keys(ctx.params).length,
query: Object.keys(ctx.query).length
};
ctx.body.fields.prompt[0] = "mutated";
ctx.body.files[0].filename = "mutated.png";
return seen;
}`), Options{})
require.NoError(t, err)
fields := map[string][]string{"prompt": {"original"}}
files := []map[string]any{{"ref": "request_file:image", "filename": "safe.png"}}
request := RouteRequestContext{Body: map[string]any{"kind": "multipart", "fields": fields, "files": files}}
for range 2 {
seen, err := plugin.Engine.Call(context.Background(), "decodeJob", request.JSValue())
require.NoError(t, err)
assert.Equal(t, map[string]any{"prompt": "original", "filename": "safe.png", "params": int64(0), "query": int64(0)}, seen)
}
assert.Equal(t, "original", fields["prompt"][0])
assert.Equal(t, "safe.png", files[0]["filename"])
}
func TestRegistryNoOpMutationsKeepCurrentGeneration(t *testing.T) {
registry := NewRegistry()
plugin := mustCompileRoutingPlugin(t, "stable-generation", 0, `["model"]`, "", "")
@@ -799,297 +513,6 @@ func TestGenericChannelTypesDoNotCreateLegacyIdentityConflicts(t *testing.T) {
}
}
func TestDeclarativeRouteValidationProtectsNamespacesAndCanonicalSyntax(t *testing.T) {
tests := []struct {
name string
route Route
expectedError string
}{
{
name: "static assets",
route: Route{Method: "GET", Path: "/assets/x", Type: RouteTypeQuery, Render: "native"},
expectedError: "reserved namespace /assets",
},
{
name: "generic task management",
route: Route{Method: "GET", Path: "/v1/tasks/:task_id", Type: RouteTypeQuery, Render: "native"},
expectedError: "reserved namespace /v1/tasks",
},
{
name: "SPA root",
route: Route{Method: "POST", Path: "/console/jobs", Type: RouteTypeSubmit},
expectedError: "reserved namespace /console",
},
{
name: "request processing page",
route: Route{Method: "GET", Path: "/request-processing", Type: RouteTypeQuery, Render: "native"},
expectedError: "reserved namespace /request-processing",
},
{
name: "security page",
route: Route{Method: "GET", Path: "/security/:section", Type: RouteTypeQuery, Render: "native"},
expectedError: "reserved namespace /security",
},
{
name: "dynamic root can claim reserved subtree",
route: Route{Method: "POST", Path: "/:root/jobs", Type: RouteTypeSubmit},
expectedError: "intersects reserved namespace",
},
{
name: "dynamic v1 namespace can claim task management",
route: Route{Method: "POST", Path: "/v1/:namespace", Type: RouteTypeSubmit},
expectedError: "reserved namespace /v1/tasks",
},
{
name: "root catch-all can claim reserved subtree",
route: Route{Method: "POST", Path: "/*rest", Type: RouteTypeSubmit},
expectedError: "intersects reserved namespace",
},
{
name: "repeated slash",
route: Route{Method: "POST", Path: "/vendor//jobs", Type: RouteTypeSubmit},
expectedError: "empty segments",
},
{
name: "noncanonical method",
route: Route{Method: " post ", Path: "/vendor/jobs", Type: RouteTypeSubmit},
expectedError: "canonical uppercase",
},
{
name: "non-terminal catch-all",
route: Route{Method: "POST", Path: "/vendor/*rest/jobs", Type: RouteTypeSubmit},
expectedError: "invalid catch-all",
},
{
name: "query declares decoder",
route: Route{Method: "GET", Path: "/vendor/jobs/:task_id", Type: RouteTypeQuery, Decode: "decode", Render: "show"},
expectedError: "must not declare decode",
},
{
name: "submit missing presenter",
route: Route{Method: "POST", Path: "/vendor/jobs", Type: RouteTypeSubmit, Decode: "decode"},
expectedError: "must declare decode and render",
},
{
name: "dynamic missing decoder",
route: Route{Method: "POST", Path: "/vendor/query", Type: RouteTypeDynamic, Render: "show"},
expectedError: "must declare decode and render",
},
{
name: "dynamic missing presenter",
route: Route{Method: "POST", Path: "/vendor/query", Type: RouteTypeDynamic, Decode: "decode"},
expectedError: "must declare decode and render",
},
{
name: "query declares action",
route: Route{Method: "GET", Path: "/vendor/jobs/:task_id", Type: RouteTypeQuery, Render: "show", Action: "retrieve"},
expectedError: "must not declare action",
},
{
name: "submit declares task id parameter",
route: Route{Method: "POST", Path: "/vendor/jobs", Type: RouteTypeSubmit, Decode: "decode", Render: "created", TaskIDParam: "task_id"},
expectedError: "must not declare taskIdParam",
},
{
name: "dynamic declares task id parameter",
route: Route{Method: "POST", Path: "/vendor/query", Type: RouteTypeDynamic, Decode: "decode", Render: "show", TaskIDParam: "task_id"},
expectedError: "must not declare taskIdParam",
},
}
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
meta := Meta{APIVersion: 1, Key: "validation", Name: "Validation", Version: "1.0.0", Author: AuthorMeta{Name: "Test"}, Models: []string{"model"}, FetchMode: "per_task", Routes: []Route{testCase.route}}
require.ErrorContains(t, ValidateV1Meta(meta), testCase.expectedError)
})
}
}
func TestRemovedEndpointsAndProtocolHooksAreValidatedAtCompileTime(t *testing.T) {
removed := routingTestPluginSource(
"removed-endpoint",
0,
`["model"]`,
`endpoints: [{method: "POST", path: "/v1/chat/completions", protocol: "chat"}],`,
routingProtocolExport("chat"),
)
_, err := CompilePlugin(removed, Options{})
require.ErrorContains(t, err, "endpoints is no longer supported")
unknown := routingTestPluginSource("unknown-protocol", 0, `["model"]`, `protocols: ["chat"],`, ``)
_, err = CompilePlugin(unknown, Options{})
require.ErrorContains(t, err, `protocol "chat" is unknown`)
missingHook := routingTestPluginSource(
"bad-protocol",
0,
`["model"]`,
`protocols: ["openai_responses"],`,
`export const protocols = {openai_responses: {
decodeRequest: function() { return {}; },
renderEvents: function() { return {events: [], done: false}; }
}};`,
)
_, err = CompilePlugin(missingHook, Options{})
require.ErrorContains(t, err, `plugin bad-protocol protocol "openai_responses" must declare supports; replace the bare string with {name: "openai_responses", supports: [...]} choosing from "stream", "sync", "background"`)
for _, removedExport := range []string{"renderers", "renderError", "resolveRequest"} {
t.Run("removed export "+removedExport, func(t *testing.T) {
source := routingTestPluginSource("removed-export", 0, `["model"]`, "", `export const `+removedExport+` = {};`)
_, compileErr := CompilePlugin(source, Options{})
require.ErrorContains(t, compileErr, `export "`+removedExport+`" is no longer supported`)
})
}
t.Run("removed route renderer", func(t *testing.T) {
source := routingTestPluginSource(
"removed-route-renderer", 0, `["model"]`,
`routes: [{method:"GET",path:"/vendor/:task_id",type:"query",render:"show",renderer:"legacy"}],`,
`export const native = {show: function(ctx, task) { return task; }};`,
)
_, compileErr := CompilePlugin(source, Options{})
require.ErrorContains(t, compileErr, "field renderer is no longer supported")
})
}
func TestRegistryRejectsPrototypeInheritedHooks(t *testing.T) {
for _, member := range []string{"constructor", "toString", "__proto__"} {
t.Run("native "+member, func(t *testing.T) {
source := routingTestPluginSource(
"inherited-renderer",
0,
`["model"]`,
fmt.Sprintf(`routes: [{method: "GET", path: "/vendor/jobs/:task_id", type: "query", render: %q}],`, member),
`const nativePrototype = {
constructor: function(task) { return task; },
toString: function(task) { return task; },
["__proto__"]: function(task) { return task; },
};
export const native = Object.create(nativePrototype);`,
)
_, err := CompilePlugin(source, Options{})
require.ErrorContains(t, err, fmt.Sprintf(`references missing native render %q`, member))
})
}
t.Run("protocol object", func(t *testing.T) {
source := routingTestPluginSource(
"inherited-protocol",
0,
`["model"]`,
`protocols: [{name: "openai_responses", supports: ["stream", "sync", "background"]}],`,
`const protocol = {
decodeRequest: function(ctx) { return ctx; },
renderEvents: function() { return {events: [], state: null, done: false}; },
renderFinal: function(ctx, task) { return task; },
};
export const protocols = Object.create({openai_responses: protocol});`,
)
_, err := CompilePlugin(source, Options{})
require.ErrorContains(t, err, `protocol "openai_responses" is missing hook "decodeRequest"`)
})
t.Run("protocol hook", func(t *testing.T) {
source := routingTestPluginSource(
"inherited-protocol-hook",
0,
`["model"]`,
`protocols: [{name: "openai_responses", supports: ["stream", "sync", "background"]}],`,
`const protocolPrototype = {
decodeRequest: function(ctx) { return ctx; },
renderEvents: function() { return {events: [], state: null, done: false}; },
renderFinal: function(ctx, task) { return task; },
};
export const protocols = {openai_responses: Object.create(protocolPrototype)};`,
)
_, err := CompilePlugin(source, Options{})
require.ErrorContains(t, err, `protocol "openai_responses" is missing hook "decodeRequest"`)
})
}
func TestMetaDecoderRejectsLossyOrUnknownRoutingFields(t *testing.T) {
tests := []struct {
name string
metaFields string
expectedError string
}{
{
name: "fractional channel type",
metaFields: `channelTypes: [50.5],`,
expectedError: "channelTypes element 1 must be an integer",
},
{
name: "non-string model",
metaFields: `models: ["model", 2],`,
expectedError: "models must be an array of strings",
},
{
name: "unknown route field",
metaFields: `routes: [{method: "POST", path: "/vendor/jobs", type: "submit", auth: false}],`,
expectedError: `unknown field "auth"`,
},
}
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
source := fmt.Sprintf(`
export const meta = {
apiVersion: 1, key: "strict-meta", name: "Strict", version: "1.0.0",
author: {name: "Test"},
models: ["model"], fetchMode: "per_task", %s
};
export function buildSubmitRequest() { return {}; }
export function parseSubmitResponse() { return {}; }
export function buildQueryRequest() { return {}; }
export function parseTaskResult() { return {}; }
export function resolveRequest() { return {kind: "submit", model: "model"}; }
`, testCase.metaFields)
_, err := CompilePlugin(source, Options{})
require.ErrorContains(t, err, testCase.expectedError)
})
}
}
func TestProtocolHookInspectionIsDeadlineBounded(t *testing.T) {
source := `
export const meta = {
apiVersion: 1, key: "getter-timeout", name: "Getter", version: "1.0.0",
author: {name: "Test"},
models: ["model"], fetchMode: "per_task",
protocols: [{name: "openai_responses", supports: ["stream", "sync", "background"]}],
};
export function buildSubmitRequest() { return {}; }
export function parseSubmitResponse() { return {}; }
export function buildQueryRequest() { return {}; }
export function parseTaskResult() { return {}; }
export const protocols = {
get openai_responses() { while (true) {} }
};
`
_, err := CompilePlugin(source, Options{Timeout: 20 * time.Millisecond})
require.ErrorContains(t, err, "inspection interrupted")
}
func TestReservedNamespaceChecksUseSegmentBoundaries(t *testing.T) {
// The host namespaces the outer router reveals, /api among them, are
// decided at admission, so these routes compile.
for _, routePath := range []string{"/apiary/jobs", "/api/plugin", "/api/:version/jobs", "/api/v3/contents/generations/tasks", "/api/common/v3/submit_task_v2"} {
meta := Meta{
APIVersion: 1,
Key: "apiary",
Name: "Apiary",
Version: "1.0.0",
Author: AuthorMeta{Name: "Test"},
Models: []string{"model"},
FetchMode: "per_task",
Routes: []Route{{Method: "POST", Path: routePath, Type: RouteTypeSubmit, Decode: "decode", Render: "render"}},
}
require.NoError(t, ValidateV1Meta(meta), routePath)
}
}
// The gateway serves a plugin's routes under /{key}, so a key may not name a
// host namespace. A plugin may declare one of those addresses itself, as
// TypeSafe 1.2.0 declares /v1/systemone and /typesafe/v1/systemone; the
@@ -1197,12 +620,6 @@ func TestRoutingGenerationServesDeclaredRoutesAndKeyCopies(t *testing.T) {
require.NoError(t, PreflightRoutingConflict(alphaOnly.Generation(), beta), "a shared route shape is not a conflict")
}
func TestResolveRouteActionPrefersResolvedAction(t *testing.T) {
route := Route{Action: "manifest-action"}
assert.Equal(t, "hook-action", ResolveRouteAction(route, "hook-action"))
assert.Equal(t, "manifest-action", ResolveRouteAction(route, ""))
}
func mustCompileRoutingPlugin(t *testing.T, key string, channelType int, models, metaFields, exports string) *LoadedPlugin {
t.Helper()
plugin, err := CompilePlugin(routingTestPluginSource(key, channelType, models, metaFields, exports), Options{})
+146
View File
@@ -0,0 +1,146 @@
# Task plugin API v1
Task plugins are single-file synchronous ECMAScript modules. The plugin contract
is currently unreleased; [`v1.schema.json`](./v1.schema.json) and
[`v1.d.ts`](./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](./v1.d.ts) for signatures and
[v1.schema.json](./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](./v1.md#generic-task-management-api).
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:
```sh
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`](./v1.md#reading-upstream-data-with-utilsfetch):
`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.
@@ -1,4 +1,4 @@
package jsplugin
package pluginkit
import (
"encoding/json"
@@ -96,7 +96,7 @@ func TestConfigAddressRoutes(t *testing.T) {
require.NoError(t, err)
paths := func(config string) []string {
var upstream []string
for _, route := range plugin.Meta.ChannelRelayConfig(plugin.ChannelConfigFor(json.RawMessage(config))).Routes {
for _, route := range plugin.Meta.ChannelRelayConfig(plugin.ChannelConfigFor(json.RawMessage(config)), nil).Routes {
upstream = append(upstream, route.UpstreamPath)
}
return upstream
@@ -1,4 +1,4 @@
package jsplugin
package pluginkit
import (
"bytes"
@@ -15,7 +15,6 @@ import (
"unicode/utf8"
"github.com/MoeForge/moego/regexp"
"github.com/QuantumNous/new-api/common"
"github.com/tidwall/gjson"
)
@@ -113,7 +112,7 @@ func (p *LoadedPlugin) ConfigURLHosts(config json.RawMessage) []string {
return nil
}
var value any
if err := common.Unmarshal(config, &value); err != nil {
if err := unmarshalJSON(config, &value); err != nil {
return nil
}
return p.Meta.ConfigSchema.root.urlHosts(value, nil)
@@ -160,7 +159,7 @@ func (p *LoadedPlugin) ValidateConfig(config json.RawMessage) (json.RawMessage,
config = json.RawMessage("{}")
}
var value any
if err := common.Unmarshal(config, &value); err != nil {
if err := unmarshalJSON(config, &value); err != nil {
return nil, fmt.Errorf("config must be a JSON object")
}
object, ok := value.(map[string]any)
@@ -177,7 +176,7 @@ func (p *LoadedPlugin) ValidateConfig(config json.RawMessage) (json.RawMessage,
if err != nil {
return nil, err
}
if validated, err = common.Marshal(value); err != nil {
if validated, err = marshalJSON(value); err != nil {
return nil, err
}
}
@@ -195,7 +194,7 @@ func (p *LoadedPlugin) ValidateConfig(config json.RawMessage) (json.RawMessage,
switch {
case errors.As(err, &hookErr):
return nil, errors.New(truncateRunes(hookErr.Message, maxValidateConfigMessageRunes))
case errors.Is(err, errCallTimeout), errors.Is(err, ErrCallAdmissionTimeout), errors.Is(err, context.DeadlineExceeded):
case errors.Is(err, ErrCallTimeout), errors.Is(err, ErrCallAdmissionTimeout), errors.Is(err, context.DeadlineExceeded):
return nil, fmt.Errorf("plugin %s validateConfig timed out", p.Meta.Key)
}
return nil, fmt.Errorf("plugin %s validateConfig failed", p.Meta.Key)
@@ -242,7 +241,7 @@ func (p *LoadedPlugin) ValidateChannelConfig(config json.RawMessage) (json.RawMe
delete(validated, name)
}
}
return common.Marshal(validated)
return marshalJSON(validated)
}
// ChannelConfigFor returns a channel's stored plugin config as its hooks get
@@ -269,21 +268,21 @@ func (p *LoadedPlugin) ChannelConfigFor(stored json.RawMessage) json.RawMessage
continue
}
var item any
if common.Unmarshal(property.field.Default, &item) == nil {
if unmarshalJSON(property.field.Default, &item) == nil {
object[property.name] = item
}
}
// validate normalizes url values in place; a rejected config keeps them
// as stored.
if encoded, err := common.Marshal(object); err == nil {
if encoded, err := marshalJSON(object); err == nil {
var checked map[string]any
if common.Unmarshal(encoded, &checked) == nil {
if unmarshalJSON(encoded, &checked) == nil {
if value, validateErr := schema.root.validate(checked, "plugin_config"); validateErr == nil {
object = value.(map[string]any)
}
}
}
encoded, err := common.Marshal(object)
encoded, err := marshalJSON(object)
if err != nil {
return json.RawMessage("{}")
}
@@ -310,7 +309,7 @@ func configObject(config json.RawMessage) (map[string]any, error) {
return map[string]any{}, nil
}
var value any
if err := common.Unmarshal(config, &value); err != nil {
if err := unmarshalJSON(config, &value); err != nil {
return nil, fmt.Errorf("plugin_config must be a JSON object")
}
object, ok := value.(map[string]any)
@@ -383,11 +382,11 @@ func (p configProperties) MarshalJSON() ([]byte, error) {
if index > 0 {
encoded.WriteByte(',')
}
name, err := common.Marshal(property.name)
name, err := marshalJSON(property.name)
if err != nil {
return nil, err
}
field, err := common.Marshal(property.field)
field, err := marshalJSON(property.field)
if err != nil {
return nil, err
}
@@ -417,7 +416,7 @@ func decodeSchema(text []byte, subject string, channel bool) (*ConfigSchema, err
if err != nil {
return nil, err
}
normalized, err := common.Marshal(root)
normalized, err := marshalJSON(root)
if err != nil {
return nil, err
}
@@ -674,7 +673,7 @@ func decodeConfigField(value gjson.Result, subject string, depth int, channel bo
field.Default = json.RawMessage(member.Raw)
// A channel address default reads as a saved address does.
if address, ok := channelAddress(member.Str); ok && field.channel && field.Format == "url" {
field.Default, _ = common.Marshal(address)
field.Default, _ = marshalJSON(address)
}
}
if member, exists := members["examples"]; exists {
@@ -718,7 +717,7 @@ func configCount(members map[string]gjson.Result, name, subject string) (*int, e
// example.
func (f *configField) checkValue(raw string, path string) error {
var value any
if err := common.UnmarshalJsonStr(raw, &value); err != nil {
if err := unmarshalJSONString(raw, &value); err != nil {
return fmt.Errorf("%s must be JSON", path)
}
_, err := f.validate(value, path)
@@ -852,7 +851,7 @@ func (f *configField) validate(value any, path string) (any, error) {
continue
}
// The host codec writes maps sorted, so equal values encode equally.
encoded, err := common.Marshal(items[index])
encoded, err := marshalJSON(items[index])
if err != nil {
return nil, err
}
@@ -896,7 +895,7 @@ func (f *configField) validate(value any, path string) (any, error) {
continue
}
// A fresh copy: the result must not share the schema's default.
if err := common.Unmarshal(property.field.Default, &item); err != nil {
if err := unmarshalJSON(property.field.Default, &item); err != nil {
return nil, err
}
}
+20 -22
View File
@@ -1,4 +1,4 @@
package jsplugin
package pluginkit
import (
"context"
@@ -17,9 +17,6 @@ import (
"github.com/MoeForge/moego/regexp"
"github.com/MoeForge/moejs"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/logger"
)
const (
@@ -27,20 +24,14 @@ const (
DefaultConcurrency = 8
)
// callMemoryLimit is the memory, in bytes, the JavaScript of one hook call may
// keep before the runtime stops it; 0 means no limit. When the call's
// allocations reach it, the runtime measures what is still in use, so garbage
// does not count. It is part of the published plugin contract
// (docs/plugin-api/v1.md) and set by PLUGIN_MEMORY_LIMIT_MB. Each call starts
// a new budget.
func callMemoryLimit() int64 {
return int64(max(constant.PluginMemoryLimitMB, 0)) << 20
}
var ErrCallAdmissionTimeout = errors.New("plugin call admission timed out")
// errCallTimeout is what interrupts a hook that runs past the call timeout.
var errCallTimeout = errors.New("plugin call timed out")
// ErrCallTimeout is what interrupts a hook that runs past the call timeout.
var ErrCallTimeout = errors.New("plugin call timed out")
// ErrMemoryLimit is what stops a hook whose JavaScript keeps more memory
// than Host.MemoryLimit allows.
var ErrMemoryLimit = moejs.ErrMemoryLimit
const hookErrorMessageLimit = 512
@@ -379,6 +370,13 @@ func (e *Engine) CallPathInto(ctx context.Context, target any, exportName string
return err
}
// CallPathJSONInto is CallJSONInto for a function nested below an exported
// object, such as native.render: objects keep their member order.
func (e *Engine) CallPathJSONInto(ctx context.Context, target any, exportName string, members []string, args ...any) error {
_, _, err := e.call(ctx, callOptions{target: target, stringify: true}, exportName, members, args...)
return err
}
// CallPathWithAdmissionTimeout gives long-lived observers a separate bound for
// waiting on JavaScript capacity. Once admitted, the hook receives the
// engine's full execution timeout instead of inheriting time already spent in
@@ -481,7 +479,7 @@ func (e *Engine) call(ctx context.Context, opts callOptions, exportName string,
} else if converted, err = instance.runtime.ParseJSONString(unsafe.String(unsafe.SliceData(raw), len(raw))); err != nil {
// JSON.parse stops at a lower nesting depth than the host codec.
var decoded any
if err = common.Unmarshal(raw, &decoded); err == nil {
if err = unmarshalJSON(raw, &decoded); err == nil {
converted, err = instance.runtime.FromGo(decoded)
}
}
@@ -491,7 +489,7 @@ func (e *Engine) call(ctx context.Context, opts callOptions, exportName string,
callArgs = append(callArgs, converted)
}
call.watchdog = watchRuntimeContext(instance.runtime, ctx, e.timeout, errCallTimeout)
call.watchdog = watchRuntimeContext(instance.runtime, ctx, e.timeout, ErrCallTimeout)
// utils.fetch pauses and restarts the watchdog; stop whichever watch is
// current when the call ends.
defer call.watchdog.stop()
@@ -676,7 +674,7 @@ func pluginValue(rt *moejs.Runtime, v any, depth int) (converted any, changed bo
}
// JSON.parse stops at a lower nesting depth than the host codec.
var decoded any
if err := common.Unmarshal(typed, &decoded); err != nil {
if err := unmarshalJSON(typed, &decoded); err != nil {
return v, false
}
return decoded, true
@@ -747,12 +745,12 @@ func pluginValue(rt *moejs.Runtime, v any, depth int) (converted any, changed bo
}
}
}
data, err := common.Marshal(v)
data, err := marshalJSON(v)
if err != nil {
return v, false
}
var decoded any
if err = common.Unmarshal(data, &decoded); err != nil {
if err = unmarshalJSON(data, &decoded); err != nil {
return v, false
}
return decoded, true
@@ -879,7 +877,7 @@ func (e *Engine) newRuntime(ctx context.Context) (*runtimeInstance, error) {
logOutput := e.log
if logOutput == nil {
logOutput = func(message string) {
logger.LogDebug(logContext.context, "task_plugin subsystem=runtime event=console message=%q", message)
debugLog(logContext.context, "task_plugin subsystem=runtime event=console message=%q", message)
}
}
if err := injectGlobals(runtime, func() string {
@@ -1,4 +1,4 @@
package jsplugin
package pluginkit
import (
"bytes"
@@ -17,8 +17,6 @@ import (
"math"
"net/http"
"net/url"
"os"
"os/exec"
"runtime"
"strings"
"sync/atomic"
@@ -29,12 +27,7 @@ import (
"weak"
"github.com/MoeForge/moejs"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/relaykit/relayconvert/kitutil"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
jsoniter "github.com/json-iterator/go"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -271,7 +264,10 @@ export function invalid(kind) {
case "bigint": value=1n; break;
case "date": value=new Date(); break;
case "sparse": value=[,1]; break;
case "size": value="<".repeat(200000); break;
case "depth":
value = null;
for (let i = 0; i < 33; i++) value = [value];
break;
case "nodes": value=new Array(32768).fill(0); break;
}
return utils.json.clone(value);
@@ -291,7 +287,7 @@ export function invalid(kind) {
assert.Equal(t, map[string]any{"marker": "data"}, cloned["__proto__"])
assert.True(t, math.Signbit(cloned["zero"].(float64)))
assert.Equal(t, []any{map[string]any{"text": "original"}}, input["items"])
for _, kind := range []string{"cycle", "function", "undefined", "nan", "bigint", "date", "sparse", "size", "nodes"} {
for _, kind := range []string{"cycle", "function", "undefined", "nan", "bigint", "date", "sparse", "depth", "nodes"} {
t.Run(kind, func(t *testing.T) {
_, err := engine.Call(t.Context(), "invalid", kind)
require.Error(t, err)
@@ -326,7 +322,7 @@ export function describe(...values) {
return seen.join(" ");
}`, Options{})
require.NoError(t, err)
// Hosts pass text written by common.Marshal, where both paths agree on
// Hosts pass text written by the host JSON codec, where both paths agree on
// key order, numbers and strings.
values := map[string]any{
"object": map[string]any{
@@ -344,10 +340,10 @@ export function describe(...values) {
}
for name, value := range values {
t.Run(name, func(t *testing.T) {
text, err := common.Marshal(value)
text, err := marshalJSON(value)
require.NoError(t, err)
var decoded any
require.NoError(t, common.Unmarshal(text, &decoded))
require.NoError(t, unmarshalJSON(text, &decoded))
want, err := engine.Call(t.Context(), "describe", decoded)
require.NoError(t, err)
got, err := engine.Call(t.Context(), "describe", RawJSON(text))
@@ -376,11 +372,11 @@ func TestJSONStateChangesAndEncodedLimits(t *testing.T) {
{"op":"set","path":["nested","a<b"],"value":{}}]
]`
var frames []any
require.NoError(t, common.UnmarshalJsonStr(changes, &frames))
require.NoError(t, unmarshalJSONString(changes, &frames))
const expected = `{"text":"<&\n\"图像😀\u2028","parts":[{"text":"ab","enabled":false}],"nested":{"value":[0,2],"a<b":{}}}`
var want any
require.NoError(t, common.UnmarshalJsonStr(expected, &want))
encoded, err := common.Marshal(want)
require.NoError(t, unmarshalJSONString(expected, &want))
encoded, err := marshalJSON(want)
require.NoError(t, err)
state := NewJSONState(len(encoded))
for _, frame := range frames {
@@ -444,7 +440,7 @@ func TestJSONStateChangesAndEncodedLimits(t *testing.T) {
state := NewJSONState(1024)
require.NoError(t, state.Apply(t.Context(), frames[0]))
var changes any
require.NoError(t, common.UnmarshalJsonStr(invalid, &changes))
require.NoError(t, unmarshalJSONString(invalid, &changes))
require.Error(t, state.Apply(t.Context(), changes))
_, err := state.Value()
require.Error(t, err)
@@ -452,38 +448,7 @@ func TestJSONStateChangesAndEncodedLimits(t *testing.T) {
}
}
type bytePreservingJSONCodec struct {
jsoniter.API
}
func (c bytePreservingJSONCodec) Decode(reader io.Reader, value any) error {
return c.NewDecoder(reader).Decode(value)
}
func TestJSONStateUTF8Normalization(t *testing.T) {
const codecEnv = "JSPLUGIN_TEST_BYTE_PRESERVING_JSON"
if os.Getenv(codecEnv) == "1" {
// Only this test runs in the child process; the parent's codec and
// parallel tests are unaffected. Disabling HTML escaping in jsoniter
// also preserves invalid UTF-8, independently of Sonic's platform support.
kitutil.SetCodec(bytePreservingJSONCodec{jsoniter.Config{SortMapKeys: true}.Froze()})
encoded, err := common.Marshal("\xff\xfe")
require.NoError(t, err)
require.Equal(t, []byte("\"\xff\xfe\""), encoded)
var decoded any
require.NoError(t, common.Unmarshal(encoded, &decoded))
require.Equal(t, "\xff\xfe", decoded)
} else {
t.Run("byte preserving codec", func(t *testing.T) {
executable, err := os.Executable()
require.NoError(t, err)
command := exec.CommandContext(t.Context(), executable, "-test.run=^TestJSONStateUTF8Normalization$", "-test.v")
command.Env = append(os.Environ(), codecEnv+"=1")
output, err := command.CombinedOutput()
require.NoError(t, err, "%s", output)
})
}
const raw = "图像\xff\xfe😀<&\n\"\\\u2028"
const normalized = "图像\ufffd\ufffd😀<&\n\"\\\u2028"
for _, tc := range []struct {
@@ -500,7 +465,7 @@ func TestJSONStateUTF8Normalization(t *testing.T) {
{"separate invalid bytes", "appendText", []any{}, "\xff", "\xfe", "\ufffd\ufffd"},
} {
t.Run(tc.name, func(t *testing.T) {
encoded, err := common.Marshal(tc.want)
encoded, err := marshalJSON(tc.want)
require.NoError(t, err)
for _, shortBy := range []int{0, 1} {
state := NewJSONState(len(encoded) - shortBy)
@@ -535,9 +500,9 @@ func TestJSONStateUTF8Normalization(t *testing.T) {
assert.Equal(t, map[string]any{"text": normalized, "items": []any{int64(0), false, normalized}}, value)
assert.Equal(t, raw, input["text"])
encoded, err := common.Marshal(normalized)
encoded, err := marshalJSON(normalized)
require.NoError(t, err)
padding := strings.Repeat("x", MaxJSONToolBytes-len(encoded))
padding := strings.Repeat("x", (4<<20)-len(encoded))
value, err = engine.Call(t.Context(), "clone", raw+padding)
require.NoError(t, err, "normalized clone must fit exactly")
assert.Equal(t, normalized, strings.TrimSuffix(value.(string), padding))
@@ -563,82 +528,6 @@ func TestJSONStateUTF8Normalization(t *testing.T) {
})
}
func TestEngineConsoleLogUsesDebugLoggerAndRequestContext(t *testing.T) {
previousDebug := common.DebugEnabled
common.DebugEnabled = false
t.Cleanup(func() { common.DebugEnabled = previousDebug })
var output bytes.Buffer
common.LogWriterMu.Lock()
previousWriter := gin.DefaultErrorWriter
gin.DefaultErrorWriter = &output
common.LogWriterMu.Unlock()
t.Cleanup(func() {
common.LogWriterMu.Lock()
gin.DefaultErrorWriter = previousWriter
common.LogWriterMu.Unlock()
})
plugin, err := CompilePlugin(`
export const meta = {
apiVersion: 1,
key: "console-debug",
name: "Console debug",
version: "1.2.3",
author: {name: "Test"},
models: ["debug-model"],
fetchMode: "per_task",
};
export function run(label) {
console.log("checkpoint", label);
return true;
}
export function buildSubmitRequest() { return {url: "https://example.com"}; }
export function parseSubmitResponse() { return {taskId: "one"}; }
export function buildQueryRequest() { return {url: "https://example.com"}; }
export function parseTaskResult() { return {status: "SUCCESS"}; }
`, Options{})
require.NoError(t, err)
engine := plugin.Engine
disabledContext := context.WithValue(context.Background(), common.RequestIdKey, "plugin-console-disabled")
_, err = engine.Call(disabledContext, "run", "disabled")
require.NoError(t, err)
assert.Empty(t, output.String())
common.DebugEnabled = true
contextA := context.WithValue(context.Background(), common.RequestIdKey, "plugin-console-request-a")
_, err = engine.Call(contextA, "run", "context-a")
require.NoError(t, err)
logA := output.String()
output.Reset()
contextB := context.WithValue(context.Background(), common.RequestIdKey, "plugin-console-request-b")
_, err = engine.Call(contextB, "run", "context-b")
require.NoError(t, err)
logB := output.String()
output.Reset()
_, err = engine.Call(context.Background(), "run", "background")
require.NoError(t, err)
logBackground := output.String()
assert.Contains(t, logA, "plugin-console-request-a")
assert.NotContains(t, logA, "plugin-console-request-b")
assert.Contains(t, logA, "task_plugin subsystem=runtime event=console")
assert.Contains(t, logA, "[plugin:console-debug@1.2.3] checkpoint context-a")
assert.NotContains(t, logA, "disabled")
assert.Contains(t, logB, "plugin-console-request-b")
assert.NotContains(t, logB, "plugin-console-request-a")
assert.Contains(t, logB, "[plugin:console-debug@1.2.3] checkpoint context-b")
assert.Contains(t, logBackground, "| SYSTEM |")
assert.NotContains(t, logBackground, "plugin-console-request-a")
assert.NotContains(t, logBackground, "plugin-console-request-b")
assert.Contains(t, logBackground, "[plugin:console-debug@1.2.3] checkpoint background")
}
func TestCompileRejectsAsynchronousAndImportedPlugins(t *testing.T) {
t.Parallel()
for name, source := range map[string]string{
@@ -732,27 +621,6 @@ export function run(mib) {
assert.Equal(t, int64(1), value, "a runtime stopped by the memory limit is discarded")
}
func TestEngineMemoryLimitFollowsSetting(t *testing.T) {
previous := constant.PluginMemoryLimitMB
t.Cleanup(func() { constant.PluginMemoryLimitMB = previous })
// Many small objects: past the limit the runtime stops the call, where a
// single large ArrayBuffer would throw a RangeError instead.
const source = `export function run(n) { const keep = []; for (let i = 0; i < n; i++) keep.push({i}); return keep.length; }`
constant.PluginMemoryLimitMB = 8
limited, err := Compile(source, Options{Key: "memory", Version: "1", Concurrency: 1})
require.NoError(t, err)
_, err = limited.Call(t.Context(), "run", 400_000)
require.ErrorIs(t, err, moejs.ErrMemoryLimit)
constant.PluginMemoryLimitMB = 0
unlimited, err := Compile(source, Options{Key: "memory", Version: "1", Concurrency: 1})
require.NoError(t, err)
value, err := unlimited.Call(t.Context(), "run", 400_000)
require.NoError(t, err, "0 means no limit")
assert.Equal(t, int64(400_000), value)
}
func TestEngineDoesNotReinitializeIdleRuntimeAfterGC(t *testing.T) {
var initialized atomic.Int64
engine, err := Compile(`console.log("initialized"); export function run(){return 42;}`, Options{
@@ -877,6 +745,12 @@ func TestEngineFetchContract(t *testing.T) {
engine, err := Compile(`
export function run(request) { return utils.fetch(request); }
export function fetchBytes(url) { return Array.from(new Uint8Array(utils.fetch({url: url, responseType: "bytes"}).body)); }
export function fetchSizes(paths) {
return paths.map(path => {
try { return utils.fetch({url: "https://api.example/" + path, responseType: "bytes"}).body.byteLength; }
catch (e) { return e.message; }
});
}
export function fetchFiveTimes() {
const failures = [];
for (let i = 0; i < 5; i++) {
@@ -886,6 +760,8 @@ export function fetchFiveTimes() {
}`, Options{Key: "fetch"})
require.NoError(t, err)
var requests []FetchRequest
const fullResponse = 4 << 20
payload := make([]byte, fullResponse+1)
ctx := WithFetcher(t.Context(), func(_ context.Context, request FetchRequest) (FetchResponse, error) {
requests = append(requests, request)
switch request.URL {
@@ -895,8 +771,12 @@ export function fetchFiveTimes() {
return FetchResponse{Status: http.StatusNotFound, Body: []byte("not found")}, nil
case "https://api.example/bytes":
return FetchResponse{Status: http.StatusPartialContent, Body: []byte{0, 0x80, 0xff, '{'}}, nil
case "https://api.example/full":
return FetchResponse{Status: http.StatusOK, Body: payload[:fullResponse]}, nil
case "https://api.example/partial":
return FetchResponse{Body: payload[:fullResponse-1]}, io.ErrUnexpectedEOF
case "https://api.example/large":
return FetchResponse{Status: http.StatusOK, Body: bytes.Repeat([]byte("a"), MaxFetchBodyBytes+1)}, nil
return FetchResponse{Status: http.StatusOK, Body: payload}, nil
case "https://api.example/down?token=secret":
return FetchResponse{}, &url.Error{Op: "Get", URL: request.URL, Err: errors.New("connection refused")}
}
@@ -946,7 +826,21 @@ export function fetchFiveTimes() {
assert.Len(t, requests, sent, "rejected requests must not reach the fetcher")
_, err = engine.Call(ctx, "run", map[string]any{"url": "https://api.example/large"})
assert.ErrorContains(t, err, "utils.fetch response from api.example exceeds 1048576 bytes")
assert.ErrorContains(t, err, "utils.fetch response from api.example exceeds 4194304 bytes")
const budgetError = "utils.fetch allows at most 8388608 response bytes per hook call"
sent = len(requests)
value, err = engine.Call(ctx, "fetchSizes", []string{"full", "full", "bytes"})
require.NoError(t, err)
assert.Equal(t, []any{int64(fullResponse), int64(fullResponse), budgetError}, value)
assert.Len(t, requests, sent+2, "exhausting the byte budget stops further network calls")
sent = len(requests)
value, err = engine.Call(ctx, "fetchSizes", []string{"partial", "full", "bytes", "json"})
require.NoError(t, err)
assert.Equal(t, []any{"utils.fetch to api.example failed: unexpected EOF", int64(fullResponse), budgetError, budgetError}, value)
require.Len(t, requests, sent+3)
assert.Equal(t, int64(1), requests[sent+2].ResponseBodyLimit(), "the transport can read one more response byte")
_, err = engine.Call(ctx, "run", map[string]any{"url": "https://api.example/down?token=secret"})
var hookErr *HookError
@@ -1305,3 +1199,11 @@ func TestValidateRequestURL(t *testing.T) {
})
}
}
func TestEngineCallPathJSONIntoKeepsMemberOrder(t *testing.T) {
engine, err := Compile(`export const native = {render(view) { return {zeta: view.id, alpha: undefined, mid: {b: 2, a: 1}}; }};`, Options{Key: "order", Version: "1"})
require.NoError(t, err)
var text json.RawMessage
require.NoError(t, engine.CallPathJSONInto(t.Context(), &text, "native", []string{"render"}, map[string]any{"id": "x"}))
assert.Equal(t, `{"zeta":"x","mid":{"b":2,"a":1}}`, string(text))
}
+40 -17
View File
@@ -1,4 +1,4 @@
package jsplugin
package pluginkit
import (
"context"
@@ -13,9 +13,9 @@ import (
"github.com/MoeForge/moejs"
)
// Fetcher sends one utils.fetch request for the hook call whose context
// carries it. The host binds it to the executing channel; the engine passes a
// context already bounded by the call's fetch budget, so the fetcher only sends.
// Fetcher sends one utils.fetch request with the network deadline in ctx.
// It reads at most request.ResponseBodyLimit()+1 bytes and returns any
// bytes it read before an error so the engine can count them.
type Fetcher func(ctx context.Context, request FetchRequest) (FetchResponse, error)
type FetchRequest struct {
@@ -30,6 +30,13 @@ type FetchRequest struct {
// bytes long.
BodyStream io.Reader
BodySize int64
// priorResponseBytes counts the bytes read by earlier fetches in this hook.
priorResponseBytes int64
}
// ResponseBodyLimit is the number of response bytes this fetch can accept.
func (r FetchRequest) ResponseBodyLimit() int64 {
return min(maxFetchResponseBytes, maxFetchResponseBytesPerCall-r.priorResponseBytes)
}
type FetchResponse struct {
@@ -39,16 +46,20 @@ type FetchResponse struct {
}
// The utils.fetch limits are part of the published plugin contract
// (docs/plugin-api/v1.md). A fetcher reads at most MaxFetchBodyBytes+1 bytes
// so that the engine can reject a longer body.
// (v1.md). MaxFetchBodyBytes applies to the POST body
// before the host expands media references.
const (
maxFetchesPerCall = 4
fetchTimeout = 15 * time.Second
maxFetchTimePerCall = 30 * time.Second
MaxFetchBodyBytes = 1 << 20
maxFetchURLBytes = 64 << 10
maxFetchesPerCall = 4
fetchTimeout = 15 * time.Second
maxFetchTimePerCall = 30 * time.Second
MaxFetchBodyBytes = 1 << 20
maxFetchResponseBytes = 4 << 20
maxFetchResponseBytesPerCall = 8 << 20
maxFetchURLBytes = 64 << 10
)
var errFetchResponseBudget = fmt.Errorf("utils.fetch allows at most %d response bytes per hook call", maxFetchResponseBytesPerCall)
type fetcherContextKey struct{}
// postFetchHooks may POST through utils.fetch for credential exchanges,
@@ -74,10 +85,11 @@ type runtimeCall struct {
watchdog *runtimeWatchdog
// holdsSlot and parked are what the call holds of the engine's
// semaphore and parked tokens; release returns exactly that.
holdsSlot bool
parked bool
fetches int
fetchTime time.Duration
holdsSlot bool
parked bool
fetches int
fetchTime time.Duration
fetchResponseBytes int64
}
func (c *runtimeCall) release() {
@@ -107,6 +119,11 @@ func (c *runtimeCall) fetch(r *moejs.Realm, argument moejs.Value) (moejs.Value,
if c.fetches >= maxFetchesPerCall {
return moejs.Undefined(), fmt.Errorf("utils.fetch allows at most %d requests per hook call", maxFetchesPerCall)
}
remainingBytes := maxFetchResponseBytesPerCall - c.fetchResponseBytes
if remainingBytes == 0 {
return moejs.Undefined(), errFetchResponseBudget
}
request.priorResponseBytes = c.fetchResponseBytes
remaining := maxFetchTimePerCall - c.fetchTime
if remaining <= 0 {
return moejs.Undefined(), fmt.Errorf("utils.fetch requests used up their %s per hook call", maxFetchTimePerCall)
@@ -139,6 +156,9 @@ func (c *runtimeCall) fetch(r *moejs.Realm, argument moejs.Value) (moejs.Value,
return moejs.Undefined(), interrupted
}
// Partial and oversized responses also consume the hook's byte budget.
size := int64(len(response.Body))
c.fetchResponseBytes += min(size, remainingBytes)
if err != nil {
var transportErr *url.Error
if errors.As(err, &transportErr) {
@@ -146,8 +166,11 @@ func (c *runtimeCall) fetch(r *moejs.Realm, argument moejs.Value) (moejs.Value,
}
return moejs.Undefined(), fmt.Errorf("utils.fetch to %s failed: %v", host, err)
}
if len(response.Body) > MaxFetchBodyBytes {
return moejs.Undefined(), fmt.Errorf("utils.fetch response from %s exceeds %d bytes", host, MaxFetchBodyBytes)
if size > maxFetchResponseBytes {
return moejs.Undefined(), fmt.Errorf("utils.fetch response from %s exceeds %d bytes", host, maxFetchResponseBytes)
}
if size > remainingBytes {
return moejs.Undefined(), errFetchResponseBudget
}
// The result is built from JavaScript objects, not a host map: a hook may
// return it, or part of it, as it is.
@@ -1,4 +1,4 @@
package jsplugin
package pluginkit
import (
"context"
@@ -7,8 +7,6 @@ import (
"reflect"
"strings"
"time"
"github.com/QuantumNous/new-api/common"
)
// Fixture describes deterministic calls into a plugin. Arguments and expected
@@ -37,8 +35,15 @@ type FixtureReport struct {
// order. unixNow is fixed by the fixture to keep signing and timestamp hooks
// reproducible.
func ReplayFixture(ctx context.Context, source string, data []byte) (FixtureReport, error) {
return ReplayFixtureWith(ctx, CompilePlugin, source, data)
}
// ReplayFixtureWith is ReplayFixture with the host's own admission: compile
// loads the plugin, for example CompilePlugin followed by the host's route
// checks.
func ReplayFixtureWith(ctx context.Context, compile func(source string, options Options) (*LoadedPlugin, error), source string, data []byte) (FixtureReport, error) {
var fixture Fixture
if err := common.Unmarshal(data, &fixture); err != nil {
if err := unmarshalJSON(data, &fixture); err != nil {
return FixtureReport{}, fmt.Errorf("decode fixture: %w", err)
}
if len(fixture.Cases) == 0 {
@@ -50,7 +55,7 @@ func ReplayFixture(ctx context.Context, source string, data []byte) (FixtureRepo
fixed := time.Unix(*fixture.UnixNow, 0)
options.Now = func() time.Time { return fixed }
}
plugin, err := NewRegistry().Register(source, options)
plugin, err := compile(source, options)
if err != nil {
return FixtureReport{}, fmt.Errorf("compile plugin: %w", err)
}
@@ -67,7 +72,7 @@ func ReplayFixture(ctx context.Context, source string, data []byte) (FixtureRepo
args := make([]any, len(testCase.Args))
for argumentIndex, raw := range testCase.Args {
if err = common.Unmarshal(raw, &args[argumentIndex]); err != nil {
if err = unmarshalJSON(raw, &args[argumentIndex]); err != nil {
return report, fmt.Errorf("%s: decode argument %d: %w", caseName, argumentIndex+1, err)
}
}
@@ -96,15 +101,15 @@ func ReplayFixture(ctx context.Context, source string, data []byte) (FixtureRepo
return report, fmt.Errorf("%s: expected is required when expectedError is empty", caseName)
}
var expected any
if err = common.Unmarshal(testCase.Expected, &expected); err != nil {
if err = unmarshalJSON(testCase.Expected, &expected); err != nil {
return report, fmt.Errorf("%s: decode expected value: %w", caseName, err)
}
actualData, marshalErr := common.Marshal(result)
actualData, marshalErr := marshalJSON(result)
if marshalErr != nil {
return report, fmt.Errorf("%s: encode actual value: %w", caseName, marshalErr)
}
var actual any
if err = common.Unmarshal(actualData, &actual); err != nil {
if err = unmarshalJSON(actualData, &actual); err != nil {
return report, fmt.Errorf("%s: normalize actual value: %w", caseName, err)
}
if !reflect.DeepEqual(expected, actual) {
@@ -1,4 +1,4 @@
package jsplugin
package pluginkit
import (
"context"
+27
View File
@@ -0,0 +1,27 @@
module github.com/QuantumNous/new-api/pluginkit
go 1.25.1
require (
github.com/MoeForge/moego v0.1.0-alpha.5
github.com/MoeForge/moejs v0.1.0
github.com/QuantumNous/new-api/relaykit v0.3.8
github.com/anknown/ahocorasick v0.0.0-20190904063843-d75dbd5169c0
github.com/golang-jwt/jwt/v5 v5.3.0
github.com/google/uuid v1.6.0
github.com/stretchr/testify v1.12.1
github.com/tidwall/gjson v1.19.0
github.com/tidwall/sjson v1.2.5
golang.org/x/net v0.55.0
)
require (
github.com/anknown/darts v0.0.0-20151216065714-83ff685239e6 // indirect
github.com/samber/lo v1.53.0 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.1 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/text v0.37.0 // indirect
)
replace github.com/QuantumNous/new-api/relaykit => ../relaykit
+32
View File
@@ -0,0 +1,32 @@
github.com/MoeForge/moego v0.1.0-alpha.5 h1:/pFyEhm0GYdOGfwawNjzLx+DoDQVoCI0dLsu8Sbpac8=
github.com/MoeForge/moego v0.1.0-alpha.5/go.mod h1:SBNiQjCpWC3IEBMKFBOwOyhhQ3jywMrISqCwJTdr4aA=
github.com/MoeForge/moejs v0.1.0 h1:w5/bM4wVRrnMdLbQG32BM+yVcoA9wjQqdGlX3XekzG4=
github.com/MoeForge/moejs v0.1.0/go.mod h1:GDaH0vQSxKDN7FCyBaLEZgqsGKRyIYBfje/p74aZQ3k=
github.com/anknown/ahocorasick v0.0.0-20190904063843-d75dbd5169c0 h1:onfun1RA+KcxaMk1lfrRnwCd1UUuOjJM/lri5eM1qMs=
github.com/anknown/ahocorasick v0.0.0-20190904063843-d75dbd5169c0/go.mod h1:4yg+jNTYlDEzBjhGS96v+zjyA3lfXlFd5CiTLIkPBLI=
github.com/anknown/darts v0.0.0-20151216065714-83ff685239e6 h1:HblK3eJHq54yET63qPCTJnks3loDse5xRmmqHgHzwoI=
github.com/anknown/darts v0.0.0-20151216065714-83ff685239e6/go.mod h1:pbiaLIeYLUbgMY1kwEAdwO6UKD5ZNwdPGQlwokS9fe8=
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/samber/lo v1.53.0 h1:t975lj2py4kJPQ6haz1QMgtId2gtmfktACxIXArw3HM=
github.com/samber/lo v1.53.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/gjson v1.19.0 h1:xwxm7n691Uf3u5OFjzngavjGTh55KX5q/9w9xHW88JU=
github.com/tidwall/gjson v1.19.0/go.mod h1:V37/opeE/JbLUOfH0QTXiNez2l0RUjYUhpT4szFQAfc=
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
+153
View File
@@ -0,0 +1,153 @@
package pluginkit
import (
"context"
_ "embed"
"math"
"slices"
"sync/atomic"
"github.com/QuantumNous/new-api/relaykit/dto"
)
// SchemaV1 is the JSON Schema of the API v1 manifest (v1.schema.json).
//
//go:embed v1.schema.json
var SchemaV1 []byte
// TypesV1 is the TypeScript declaration of API v1 (v1.d.ts).
//
//go:embed v1.d.ts
var TypesV1 []byte
// New API channel types a plugin may not declare in meta.channelTypes: a
// type-61 channel binds a plugin by key, and a type-60 New API channel
// extends with plugins through its own setting.
const (
ChannelTypeNewAPI = 60
ChannelTypeTaskPlugin = 61
)
// MaxPluginKeyLength is the longest plugin key, in bytes.
const MaxPluginKeyLength = 30
// newAPIReservedKeys are the keys new-api refuses because /{key} would collide
// with its own paths: api, the first segments of its routes and reserved route
// namespaces, and the route prefixes its built-in plugins own. A root-module
// test derives the set from new-api's routers and checks this list.
var newAPIReservedKeys = []string{
"401", "403", "404", "500", "503", "about", "ali", "api", "assets", "channels", "chat", "chat2link",
"console", "dashboard", "errors", "forbidden", "forgot-password", "keys", "login", "mj", "models",
"oauth", "otp", "pg", "playground", "pricing", "privacy-policy", "profile", "rankings",
"redemption-codes", "register", "request-processing", "reset", "security", "setup", "sign-in",
"sign-up", "subscriptions", "suno", "system-info", "system-settings", "task-plugins", "upstream-monitor", "usage-logs",
"user", "user-agreement", "users", "v1", "v1beta", "wallet",
}
// NewAPIReservedKeys returns, sorted, the plugin keys new-api refuses because
// they collide with its own paths, for another host that warns authors of
// plugins meant for new-api too. Each call returns a new slice.
func NewAPIReservedKeys() []string {
return slices.Clone(newAPIReservedKeys)
}
// Bounds of the usage facts a plugin reports and of its usage examples:
// second facts at most MaxUsageSeconds, count facts at most MaxUsageCount,
// token and credit facts at most MaxUsageQuota.
const (
MaxUsageSeconds = 3600
MaxUsageCount = dto.MaxImageN
MaxUsageQuota = math.MaxInt32
)
// Host is what the gateway running the plugins sets for all of them. A zero
// member keeps the default the API v1 document gives.
type Host struct {
// MemoryLimit is the memory, in bytes, the JavaScript of one hook call
// may keep; 0 or less means no limit. Nil keeps 512 MiB. It is read when
// a runtime is created.
MemoryLimit func() int64
// MaxRequestBodyBytes bounds a request a converter builds; 0 or less
// keeps 128 MiB. It is read on every conversion.
MaxRequestBodyBytes func() int
// MaxStreamEventBytes bounds a converter's state and the event data of
// one call; 0 or less keeps 128 MiB. It is read on every conversion.
MaxStreamEventBytes func() int
// ReservedRouteNamespaces are host paths a plugin route may not enter,
// such as "/v1/tasks". A key may not be the first segment of one.
ReservedRouteNamespaces []string
// ReservedKeys are other keys a plugin may not take, such as "api".
ReservedKeys []string
// ParamOverride runs utils.paramOverride; nil leaves the utility
// unavailable on this host.
ParamOverride ParamOverrideFunc
// Debug receives the console output of plugins and other debug lines;
// nil discards them.
Debug func(ctx context.Context, format string, args ...any)
}
var defaultHost = Host{
ReservedRouteNamespaces: []string{"/assets", "/v1/tasks"},
ReservedKeys: []string{"api"},
}
var currentHost atomic.Pointer[Host]
func init() {
currentHost.Store(&defaultHost)
}
// Configure sets the host for every plugin. A host calls it at startup,
// before it compiles plugins; the namespaces and keys apply to plugins
// compiled after the call.
func Configure(host Host) {
currentHost.Store(&host)
}
// SetParamOverrideFunc sets the function utils.paramOverride calls and keeps
// the rest of the host; nil removes it.
func SetParamOverrideFunc(fn ParamOverrideFunc) {
host := *hostConfig()
host.ParamOverride = fn
currentHost.Store(&host)
}
func hostConfig() *Host {
return currentHost.Load()
}
// callMemoryLimit is the memory, in bytes, the JavaScript of one hook call may
// keep before the runtime stops it; 0 means no limit. When the call's
// allocations reach it, the runtime measures what is still in use, so garbage
// does not count. Each call starts a new budget.
func callMemoryLimit() int64 {
limit := hostConfig().MemoryLimit
if limit == nil {
return 512 << 20
}
return max(limit(), 0)
}
func maxConvertedBodyBytes() int {
if limit := hostConfig().MaxRequestBodyBytes; limit != nil {
if bytes := limit(); bytes > 0 {
return bytes
}
}
return 128 << 20
}
func maxConvertedEventBytes() int {
if limit := hostConfig().MaxStreamEventBytes; limit != nil {
if bytes := limit(); bytes > 0 {
return bytes
}
}
return 128 << 20
}
func debugLog(ctx context.Context, format string, args ...any) {
if debug := hostConfig().Debug; debug != nil {
debug(ctx, format, args...)
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
package jsplugin
package pluginkit
import (
"bytes"
+24
View File
@@ -0,0 +1,24 @@
package pluginkit
import (
"unsafe"
"github.com/MoeForge/moego/json"
)
// The module's JSON goes through these functions and nothing else. The codec
// is fixed to moego/json, which is what new-api's common JSON helpers use:
// key order, escaping and number forms of encoded values are part of what
// hooks receive, so every host gets the same bytes.
func marshalJSON(v any) ([]byte, error) {
return json.Marshal(v)
}
func unmarshalJSON(data []byte, v any) error {
return json.Unmarshal(data, v)
}
func unmarshalJSONString(data string, v any) error {
return json.Unmarshal(unsafe.Slice(unsafe.StringData(data), len(data)), v)
}
@@ -1,4 +1,4 @@
package jsplugin
package pluginkit
import (
"context"
@@ -8,7 +8,6 @@ import (
"unicode/utf8"
"github.com/MoeForge/moejs/engine"
"github.com/QuantumNous/new-api/common"
)
const (
@@ -16,7 +15,8 @@ const (
CapabilitySubmitSSEDelta = "submit-sse-delta@1"
CapabilityJSONOrder = "json-order@1"
CapabilityDurationAuto = "duration-auto@1"
MaxJSONToolBytes = 1 << 20
MaxJSONToolBytes = 1 << 20 // Encoded JSON held by the submit SSE accumulator.
maxJSONCloneBytes = 4 << 20
maxJSONToolDepth = 32
maxJSONToolNodes = 32768
maxJSONChanges = 256
@@ -182,7 +182,7 @@ func newJSONStateNode(value any, depth int, budget *jsonStateBudget) (*jsonState
if !utf8.ValidString(key) || len(key) > budget.bytes {
return nil, fmt.Errorf("invalid or oversized JSON object key")
}
encoded, err := common.Marshal(key)
encoded, err := marshalJSON(key)
if err != nil {
return nil, err
}
@@ -236,7 +236,7 @@ func newJSONStateNode(value any, depth int, budget *jsonStateBudget) (*jsonState
default:
return nil, fmt.Errorf("value must contain only JSON objects, arrays and scalars")
}
encoded, err := common.Marshal(value)
encoded, err := marshalJSON(value)
if err != nil {
return nil, err
}
@@ -336,7 +336,7 @@ func (s *JSONState) Apply(ctx context.Context, changes any) (err error) {
if target != nil {
oldBytes, oldNodes = target.bytes, target.nodes
} else {
encodedKey, err := common.Marshal(key)
encodedKey, err := marshalJSON(key)
if err != nil {
return err
}
@@ -385,7 +385,7 @@ func (s *JSONState) Apply(ctx context.Context, changes any) (err error) {
if !utf8.ValidString(text) {
text = string([]rune(text))
}
encoded, err := common.Marshal(text)
encoded, err := marshalJSON(text)
if err != nil {
return err
}
@@ -418,7 +418,7 @@ func (s *JSONState) Value() (any, error) {
return nil, s.failed
}
value := s.root.value()
encoded, err := common.Marshal(value)
encoded, err := marshalJSON(value)
if err != nil {
return nil, err
}
@@ -1,4 +1,4 @@
package jsplugin
package pluginkit
import (
"crypto/sha256"
@@ -1,4 +1,4 @@
package jsplugin
package pluginkit
import (
"context"
+1 -1
View File
@@ -1,4 +1,4 @@
package jsplugin
package pluginkit
import (
"context"
+2246
View File
File diff suppressed because it is too large. Load diff
+997
View File
@@ -0,0 +1,997 @@
package pluginkit
import (
"encoding/base64"
"encoding/json"
"fmt"
"maps"
"slices"
"strings"
"testing"
"time"
"unicode/utf8"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestValidateV1MetaEnforcesTaskPluginKeyLength(t *testing.T) {
meta := Meta{APIVersion: 1, Key: strings.Repeat("a", 30), Name: "Test", Version: "1.0.0", Author: AuthorMeta{Name: "Test"}, Models: []string{"model"}, FetchMode: "per_task"}
require.NoError(t, ValidateV1Meta(meta))
meta.Key += "a"
require.ErrorContains(t, ValidateV1Meta(meta), "must not exceed 30 characters")
}
func TestRegistryRequiresValidPluginAuthor(t *testing.T) {
missing := strings.Replace(
routingTestPluginSource("missing-author", 0, `["model"]`, "", ""),
`author: {name: "Test"},`,
"",
1,
)
_, err := CompilePlugin(missing, Options{})
require.ErrorContains(t, err, "author must be an object")
meta := Meta{
APIVersion: 1,
Key: "author-url",
Name: "Author URL",
Version: "1.0.0",
Author: AuthorMeta{Name: "Test", URL: "ftp://example.com/profile"},
Models: []string{"model"},
FetchMode: "per_task",
}
require.ErrorContains(t, ValidateV1Meta(meta), "absolute HTTP(S)")
meta.Author.URL = "https://example.com/profile"
require.NoError(t, ValidateV1Meta(meta))
}
func TestRegistryRequiresArtifactHooksAsPair(t *testing.T) {
for _, hook := range []string{"listArtifacts", "buildContentRequest"} {
t.Run(hook, func(t *testing.T) {
source := routingTestPluginSource(
"artifact-hook-pair",
0,
`["model"]`,
"",
"export function "+hook+"() { return []; }",
)
_, err := CompilePlugin(source, Options{})
require.ErrorContains(t, err, "must export listArtifacts and buildContentRequest together")
})
}
}
func TestRegistryDecodesAndValidatesUsageSchema(t *testing.T) {
withoutSchema, err := CompilePlugin(
routingTestPluginSource("usage-schema-absent", 0, `["model"]`, "", ""),
Options{},
)
require.NoError(t, err)
assert.Nil(t, withoutSchema.Meta.UsageSchema)
valid := routingTestPluginSource(
"usage-schema",
0,
`["model"]`,
`usageSchema: {
duration: {type: "number", unit: "second", description: "Generated video duration."},
count: {type: "number", unit: "count"},
tokens: {type: "number", unit: "token", description: "Upstream billing tokens."},
credits: {type: "number", unit: "credit", description: "Vendor resource-pack units."},
mode: {enum: ["std", "pro"], description: "Provider quality tier."},
generate_audio: {type: "boolean", description: "Whether audio is generated."},
},
usageExamples: [{label: "std · 1s", facts: {duration: 1, count: 1, tokens: 1, credits: 1, mode: "std", generate_audio: true}}],`,
"",
)
plugin, err := CompilePlugin(valid, Options{})
require.NoError(t, err)
assert.Equal(t, "number", plugin.Meta.UsageSchema["duration"].Type)
assert.Equal(t, "second", plugin.Meta.UsageSchema["duration"].Unit)
assert.Equal(t, LocalizedText{"en": "Generated video duration."}, plugin.Meta.UsageSchema["duration"].Description)
assert.Equal(t, "number", plugin.Meta.UsageSchema["count"].Type)
assert.Equal(t, "count", plugin.Meta.UsageSchema["count"].Unit)
assert.Equal(t, "number", plugin.Meta.UsageSchema["tokens"].Type)
assert.Equal(t, "token", plugin.Meta.UsageSchema["tokens"].Unit)
assert.Equal(t, LocalizedText{"en": "Upstream billing tokens."}, plugin.Meta.UsageSchema["tokens"].Description)
assert.Equal(t, "number", plugin.Meta.UsageSchema["credits"].Type)
assert.Equal(t, "credit", plugin.Meta.UsageSchema["credits"].Unit)
assert.Equal(t, LocalizedText{"en": "Vendor resource-pack units."}, plugin.Meta.UsageSchema["credits"].Description)
assert.Equal(t, []string{"std", "pro"}, plugin.Meta.UsageSchema["mode"].Enum)
assert.Equal(t, LocalizedText{"en": "Provider quality tier."}, plugin.Meta.UsageSchema["mode"].Description)
assert.Equal(t, "boolean", plugin.Meta.UsageSchema["generate_audio"].Type)
assert.Equal(t, LocalizedText{"en": "Whether audio is generated."}, plugin.Meta.UsageSchema["generate_audio"].Description)
require.Len(t, plugin.Meta.UsageExamples, 1)
assert.Equal(t, "std · 1s", plugin.Meta.UsageExamples[0].Label)
assert.Equal(t, int64(1), plugin.Meta.UsageExamples[0].Facts["tokens"])
tests := []struct {
name string
declaration string
expectedError string
}{
{
name: "unsupported numeric unit",
declaration: `{type: "number", unit: "minute"}`,
expectedError: "unit must be second, count, token, or credit",
},
{
name: "boolean cannot mix unit",
declaration: `{type: "boolean", unit: "second"}`,
expectedError: "cannot combine boolean with unit",
},
{
name: "enum cannot mix numeric shape",
declaration: `{type: "number", unit: "second", enum: ["std"]}`,
expectedError: "cannot combine enum with type or unit",
},
{
name: "enum values must be unique",
declaration: `{enum: ["std", "std"]}`,
expectedError: "enum values must be unique",
},
{
name: "enum must not be empty",
declaration: `{enum: []}`,
expectedError: "enum must contain at least one value",
},
{
name: "empty enum cannot be hidden in numeric shape",
declaration: `{type: "number", unit: "second", enum: []}`,
expectedError: "cannot combine enum with type or unit",
},
{
name: "unknown property",
declaration: `{type: "number", unit: "second", maximum: 5}`,
expectedError: `unknown property "maximum"`,
},
{
name: "description must be a string or object",
declaration: `{type: "number", unit: "second", description: 5}`,
expectedError: "description must be a string or object",
},
{
name: "description is bounded",
declaration: `{type: "number", unit: "second", description: "` + strings.Repeat("x", 257) + `"}`,
expectedError: "description must not exceed 256 characters",
},
}
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
source := routingTestPluginSource(
"invalid-usage-schema",
0,
`["model"]`,
`usageSchema: {value: `+testCase.declaration+`},`,
"",
)
_, err := CompilePlugin(source, Options{})
require.ErrorContains(t, err, testCase.expectedError)
})
}
for _, testCase := range []struct {
name string
metaFields string
expectedError string
}{
{
name: "explicit null",
metaFields: `usageSchema: null,`,
expectedError: "usageSchema must be an object",
},
{
name: "leading whitespace in key",
metaFields: `usageSchema: {" duration": {type: "number", unit: "second"}},`,
expectedError: "keys must be non-empty canonical names",
},
{
name: "trailing whitespace in key",
metaFields: `usageSchema: {"duration ": {type: "number", unit: "second"}},`,
expectedError: "keys must be non-empty canonical names",
},
} {
t.Run(testCase.name, func(t *testing.T) {
source := routingTestPluginSource(
"invalid-usage-schema",
0,
`["model"]`,
testCase.metaFields,
"",
)
_, err := CompilePlugin(source, Options{})
require.ErrorContains(t, err, testCase.expectedError)
})
}
t.Run("second-only schema may omit usageExamples", func(t *testing.T) {
plugin, err := CompilePlugin(
routingTestPluginSource(
"usage-examples-optional",
0,
`["model"]`,
`usageSchema: {seconds: {type: "number", unit: "second"}},`,
"",
),
Options{},
)
require.NoError(t, err)
assert.Empty(t, plugin.Meta.UsageExamples)
})
t.Run("ValidateV1Meta preserves explicit empty enum presence", func(t *testing.T) {
meta := Meta{
APIVersion: 1,
Key: "invalid-usage-schema",
Name: "Invalid Usage Schema",
Version: "1.0.0",
Author: AuthorMeta{Name: "Test"},
Models: []string{"model"},
FetchMode: "per_task",
UsageSchema: map[string]UsageFieldSchema{
"duration": {Type: "number", Unit: "second", Enum: []string{}},
},
}
require.ErrorContains(t, ValidateV1Meta(meta), "cannot combine enum with type or unit")
})
}
func TestRegistryValidatesUsageExamples(t *testing.T) {
tokenSchema := `usageSchema: {tokens: {type: "number", unit: "token"}, mode: {enum: ["std", "pro"]}},`
validExample := `{label: "std · 1 token", facts: {tokens: 1, mode: "std"}}`
for _, testCase := range []struct {
name string
metaFields string
expectedError string
}{
{
name: "missing schema key",
metaFields: tokenSchema + `usageExamples: [{label: "std", facts: {tokens: 1}}],`,
expectedError: `facts missing key "mode"`,
},
{
name: "undeclared facts key",
metaFields: tokenSchema + `usageExamples: [{label: "std", facts: {tokens: 1, mode: "std", extra: 1}}],`,
expectedError: `undeclared key "extra"`,
},
{
name: "enum value must be declared",
metaFields: tokenSchema + `usageExamples: [{label: "ultra", facts: {tokens: 1, mode: "ultra"}}],`,
expectedError: "enum is not an allowed value",
},
{
name: "token unit requires at least one example",
metaFields: `usageSchema: {tokens: {type: "number", unit: "token"}},`,
expectedError: "usageExamples is required when usageSchema declares a token unit",
},
{
name: "cap is 16 examples",
metaFields: tokenSchema + `usageExamples: [` + strings.Repeat(validExample+",", 16) + validExample + `],`,
expectedError: "must not exceed 16 entries",
},
{
name: "label must be non-empty",
metaFields: tokenSchema + `usageExamples: [{label: " ", facts: {tokens: 1, mode: "std"}}],`,
expectedError: "label is required",
},
{
name: "label is bounded",
metaFields: tokenSchema + `usageExamples: [{label: "` + strings.Repeat("x", 49) + `", facts: {tokens: 1, mode: "std"}}],`,
expectedError: "label must not exceed 48 characters",
},
{
name: "usageExamples requires usageSchema",
metaFields: `usageExamples: [{label: "std", facts: {tokens: 1}}],`,
expectedError: "usageExamples requires usageSchema",
},
{
name: "token value must stay within the int32 bound",
metaFields: tokenSchema + `usageExamples: [{label: "overflow", facts: {tokens: 2147483648, mode: "std"}}],`,
expectedError: "exceeds the host limit",
},
{
name: "second value must stay within the duration bound",
metaFields: `usageSchema: {seconds: {type: "number", unit: "second"}}, usageExamples: [{label: "too long", facts: {seconds: 3601}}],`,
expectedError: "exceeds the host limit",
},
{
name: "negative number is rejected",
metaFields: tokenSchema + `usageExamples: [{label: "neg", facts: {tokens: -1, mode: "std"}}],`,
expectedError: "finite non-negative number",
},
} {
t.Run(testCase.name, func(t *testing.T) {
source := routingTestPluginSource(
"invalid-usage-examples",
0,
`["model"]`,
testCase.metaFields,
"",
)
_, err := CompilePlugin(source, Options{})
require.ErrorContains(t, err, testCase.expectedError)
})
}
t.Run("accepts a complete token example vector", func(t *testing.T) {
plugin, err := CompilePlugin(
routingTestPluginSource(
"valid-usage-examples",
0,
`["model"]`,
tokenSchema+`usageExamples: [`+validExample+`],`,
"",
),
Options{},
)
require.NoError(t, err)
require.Len(t, plugin.Meta.UsageExamples, 1)
assert.Equal(t, "std · 1 token", plugin.Meta.UsageExamples[0].Label)
assert.Equal(t, "std", plugin.Meta.UsageExamples[0].Facts["mode"])
})
t.Run("ValidateV1Meta rejects a token schema without examples", func(t *testing.T) {
meta := Meta{
APIVersion: 1,
Key: "token-examples",
Name: "Token Examples",
Version: "1.0.0",
Author: AuthorMeta{Name: "Test"},
Models: []string{"model"},
FetchMode: "per_task",
UsageSchema: map[string]UsageFieldSchema{
"tokens": {Type: "number", Unit: "token"},
},
}
require.ErrorContains(t, ValidateV1Meta(meta), "usageExamples is required when usageSchema declares a token unit")
meta.UsageExamples = []UsageExample{{Label: "1 token", Facts: map[string]any{"tokens": 1}}}
require.NoError(t, ValidateV1Meta(meta))
})
}
func TestRegistryValidatesChannelTypes(t *testing.T) {
base := Meta{
APIVersion: 1,
Key: "compat",
Name: "Compat",
Version: "1.0.0",
Author: AuthorMeta{Name: "Test"},
Models: []string{"model"},
FetchMode: "per_task",
}
for _, testCase := range []struct {
name string
channelTypes []int
wantErr string
}{
{name: "valid list", channelTypes: []int{55, 1}},
{name: "empty list", channelTypes: nil},
{name: "zero rejected", channelTypes: []int{0}, wantErr: "positive channel types"},
{name: "negative rejected", channelTypes: []int{-1}, wantErr: "positive channel types"},
{name: "task plugin type rejected", channelTypes: []int{ChannelTypeTaskPlugin}, wantErr: "task plugin channel type"},
{name: "new api type rejected", channelTypes: []int{ChannelTypeNewAPI}, wantErr: "New API channel type"},
{name: "duplicates rejected", channelTypes: []int{1, 1}, wantErr: "must be unique"},
} {
t.Run(testCase.name, func(t *testing.T) {
meta := base
meta.ChannelTypes = testCase.channelTypes
err := ValidateV1Meta(meta)
if testCase.wantErr == "" {
require.NoError(t, err)
return
}
require.ErrorContains(t, err, testCase.wantErr)
})
}
for _, testCase := range []struct {
name string
metaFields string
expectedError string
}{
{
name: "removed channelType field",
metaFields: `channelType: 55,`,
expectedError: "channelType is no longer supported; declare channelTypes instead",
},
{
name: "removed compatibleChannelTypes field",
metaFields: `compatibleChannelTypes: [1],`,
expectedError: "compatibleChannelTypes is no longer supported; declare channelTypes instead",
},
} {
t.Run(testCase.name, func(t *testing.T) {
source := fmt.Sprintf(`
export const meta = {
apiVersion: 1, key: "legacy-field", name: "Legacy", version: "1.0.0",
author: {name: "Test"}, models: ["model"], fetchMode: "per_task", %s
};
export function buildSubmitRequest() { return {}; }
export function parseSubmitResponse() { return {}; }
export function buildQueryRequest() { return {}; }
export function parseTaskResult() { return {}; }
`, testCase.metaFields)
_, err := CompilePlugin(source, Options{})
require.ErrorContains(t, err, testCase.expectedError)
})
}
}
func TestRegistryNormalizesBaseURL(t *testing.T) {
absent, err := CompilePlugin(routingTestPluginSource("base-url-absent", 0, `["model"]`, "", ""), Options{})
require.NoError(t, err)
assert.Empty(t, absent.Meta.BaseURL)
_, err = CompilePlugin(routingTestPluginSource("base-url-type", 0, `["model"]`, "baseUrl: 1,", ""), Options{})
require.ErrorContains(t, err, "baseUrl must be a string")
tests := []struct {
name string
input string
want string
wantError string
}{
{name: "https accepted", input: "https://api.example.com", want: "https://api.example.com"},
{name: "http accepted", input: "http://api.example.com", want: "http://api.example.com"},
{name: "loopback with port accepted", input: "http://127.0.0.1:8000", want: "http://127.0.0.1:8000"},
{name: "ipv6 literal with port and path accepted", input: "http://[::1]:8000/api/", want: "http://[::1]:8000/api"},
{name: "trailing slashes stripped", input: "https://api.example.com/v1//", want: "https://api.example.com/v1"},
{name: "scheme and host lowercased, path preserved", input: "HTTPS://API.Example.COM/V1", want: "https://api.example.com/V1"},
{name: "userinfo rejected", input: "https://user:pass@api.example.com", wantError: "credentials"},
{name: "query rejected", input: "https://api.example.com/?x=1", wantError: "query or fragment"},
{name: "fragment rejected", input: "https://api.example.com/#x", wantError: "query or fragment"},
{name: "non-http scheme rejected", input: "ftp://api.example.com", wantError: "http or https"},
{name: "relative value rejected", input: "/v1", wantError: "absolute"},
{name: "non-ascii host rejected", input: "https://例子.com", wantError: "ASCII"},
{name: "embedded whitespace rejected", input: "https://api.example.com/a b", wantError: "whitespace"},
{name: "192 characters rejected", input: "https://api.example.com/" + strings.Repeat("a", 168), wantError: "191"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
loaded, err := CompilePlugin(routingTestPluginSource("base-url", 0, `["model"]`, fmt.Sprintf("baseUrl: %q,", test.input), ""), Options{})
if test.wantError != "" {
require.ErrorContains(t, err, test.wantError)
return
}
require.NoError(t, err)
assert.Equal(t, test.want, loaded.Meta.BaseURL)
})
}
}
func TestRegistryNormalizesAllowedHosts(t *testing.T) {
tests := []struct {
name string
hosts string
want []string
wantError string
}{
{name: "hostname lowercased", hosts: `["Upload.Example.com"]`, want: []string{"upload.example.com"}},
{name: "host with port accepted", hosts: `["upload.example.com:8443"]`, want: []string{"upload.example.com:8443"}},
{name: "bracketed ipv6 with port accepted", hosts: `["[::1]:8080"]`, want: []string{"[::1]:8080"}},
{name: "bracketed ipv6 accepted", hosts: `["[::1]"]`, want: []string{"[::1]"}},
{name: "bare ipv6 normalized to brackets", hosts: `["::1"]`, want: []string{"[::1]"}},
{name: "scheme rejected", hosts: `["https://upload.example.com"]`, wantError: "without schemes"},
{name: "path rejected", hosts: `["upload.example.com/v1"]`, wantError: "without schemes"},
{name: "credentials rejected", hosts: `["user@upload.example.com"]`, wantError: "without schemes"},
{name: "port out of range rejected", hosts: `["upload.example.com:99999"]`, wantError: "between 1 and 65535"},
{name: "non-numeric port rejected", hosts: `["upload.example.com:abc"]`, wantError: "between 1 and 65535"},
{name: "malformed ipv6 rejected", hosts: `["fe80::1::2"]`, wantError: "bracketed"},
{name: "duplicate after normalization rejected", hosts: `["a.example.com", "A.example.com"]`, wantError: "unique"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
loaded, err := CompilePlugin(routingTestPluginSource("hosts", 0, `["model"]`, "allowedHosts: "+test.hosts+",", ""), Options{})
if test.wantError != "" {
require.ErrorContains(t, err, test.wantError)
return
}
require.NoError(t, err)
assert.Equal(t, test.want, loaded.Meta.AllowedHosts)
})
}
}
func TestRegistryRejectsImageReferencesInMetaIcon(t *testing.T) {
for _, icon := range []string{"data:image/png;base64,iVBORw0KGgo=", "https://example.com/icon.png"} {
_, err := CompilePlugin(routingTestPluginSource("icon-ref", 0, `["model"]`, fmt.Sprintf("icon: %q,", icon), ""), Options{})
require.ErrorContains(t, err, "icon.svg or icon.png file")
}
}
func TestDecodeIconDataURI(t *testing.T) {
svg := func(body string) string {
return "data:image/svg+xml;base64," + base64.StdEncoding.EncodeToString([]byte(body))
}
pngBytes := append([]byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'}, make([]byte, 16)...)
tests := []struct {
name string
icon string
wantType string
wantError string
}{
{name: "small svg accepted", icon: svg(`<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 16 16"><defs><circle id="a" cx="8" cy="8" r="6" fill="#0af"/></defs><use xlink:href="#a"/><style>@media (prefers-color-scheme: dark) { circle { fill: #fff } }</style></svg>`), wantType: "image/svg+xml"},
{name: "small png accepted", icon: "data:image/png;base64," + base64.StdEncoding.EncodeToString(pngBytes), wantType: "image/png"},
{name: "svg script element rejected", icon: svg(`<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>`), wantError: "script"},
{name: "svg foreignObject rejected", icon: svg(`<svg xmlns="http://www.w3.org/2000/svg"><foreignObject><div/></foreignObject></svg>`), wantError: "foreignObject"},
{name: "svg event handler attribute rejected", icon: svg(`<svg xmlns="http://www.w3.org/2000/svg" onload="alert(1)"/>`), wantError: "event handler"},
{name: "svg external image href rejected", icon: svg(`<svg xmlns="http://www.w3.org/2000/svg"><image href="https://evil.example/a.png"/></svg>`), wantError: "external"},
{name: "svg javascript href with entity split rejected", icon: svg(`<svg xmlns="http://www.w3.org/2000/svg"><a href="java&#10;script:alert(1)"><text>x</text></a></svg>`), wantError: "external"},
{name: "svg style import rejected", icon: svg(`<svg xmlns="http://www.w3.org/2000/svg"><style>@import url(evil.css)</style></svg>`), wantError: "external"},
{name: "svg doctype rejected", icon: svg(`<!DOCTYPE svg [<!ENTITY x "y">]><svg xmlns="http://www.w3.org/2000/svg"/>`), wantError: "DOCTYPE"},
{name: "non-svg root rejected", icon: svg(`<html><svg/></html>`), wantError: "root element"},
{name: "malformed svg rejected", icon: svg(`<svg xmlns="http://www.w3.org/2000/svg"><g></svg>`), wantError: "well-formed"},
{name: "non-image media type rejected", icon: "data:text/html;base64," + base64.StdEncoding.EncodeToString([]byte("<b>x</b>")), wantError: "image/png"},
{name: "charset parameter rejected", icon: "data:image/svg+xml;charset=utf-8;base64," + base64.StdEncoding.EncodeToString([]byte("<svg/>")), wantError: "image/png"},
{name: "missing data prefix rejected", icon: "image/png;base64,iVBORw0KGgo=", wantError: "image/png"},
{name: "malformed base64 rejected", icon: "data:image/png;base64,@@@", wantError: "base64"},
{name: "png signature enforced", icon: "data:image/png;base64," + base64.StdEncoding.EncodeToString([]byte("not a png")), wantError: "not a PNG"},
{name: "oversize payload rejected", icon: svg(`<svg xmlns="http://www.w3.org/2000/svg">` + strings.Repeat("<g/>", 140000) + `</svg>`), wantError: "must not exceed"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
mediaType, data, err := DecodeIconDataURI(test.icon)
if test.wantError != "" {
require.ErrorContains(t, err, test.wantError)
return
}
require.NoError(t, err)
assert.Equal(t, test.wantType, mediaType)
assert.NotEmpty(t, data)
})
}
}
func TestPluginDisplayMetadata(t *testing.T) {
for _, tc := range []struct {
name, fields string
priority int
website string
invalid bool
}{
{name: "omitted"},
{name: "zero and empty", fields: `sortPriority: 0, website: "",`},
{name: "positive", fields: `sortPriority: 20, website: " https://example.com/docs?q=1#intro ",`, priority: 20, website: "https://example.com/docs?q=1#intro"},
{name: "minimum", fields: `sortPriority: -2147483648,`, priority: -2147483648},
{name: "maximum", fields: `sortPriority: 2147483647,`, priority: 2147483647},
{name: "underflow", fields: `sortPriority: -2147483649,`, invalid: true},
{name: "overflow", fields: `sortPriority: 2147483648,`, invalid: true},
{name: "fraction", fields: `sortPriority: 1.5,`, invalid: true},
{name: "numeric string", fields: `sortPriority: "1",`, invalid: true},
{name: "null priority", fields: `sortPriority: null,`, invalid: true},
{name: "nonfinite", fields: `sortPriority: Infinity,`, invalid: true},
{name: "website type", fields: `website: 1,`, invalid: true},
{name: "http", fields: `website: "http://example.com",`, invalid: true},
{name: "relative", fields: `website: "/docs",`, invalid: true},
{name: "missing host", fields: `website: "https:///docs",`, invalid: true},
{name: "credentials", fields: `website: "https://user:pass@example.com",`, invalid: true},
{name: "empty credentials", fields: `website: "https://@example.com",`, invalid: true},
{name: "javascript", fields: `website: "javascript:alert(1)",`, invalid: true},
{name: "invalid host", fields: `website: "https://-example.com",`, invalid: true},
{name: "invalid port", fields: `website: "https://example.com:99999",`, invalid: true},
{name: "whitespace", fields: `website: "https://example.com/a b",`, invalid: true},
} {
t.Run(tc.name, func(t *testing.T) {
loaded, err := CompilePlugin(routingTestPluginSource("display", 0, `["model"]`, tc.fields, ""), Options{})
if tc.invalid {
require.Error(t, err)
return
}
require.NoError(t, err)
assert.Equal(t, tc.priority, loaded.Meta.SortPriority)
assert.Equal(t, tc.website, loaded.Meta.Website)
encoded, err := marshalJSON(loaded.Meta)
require.NoError(t, err)
var decoded Meta
require.NoError(t, unmarshalJSON(encoded, &decoded))
assert.Equal(t, tc.priority, decoded.SortPriority)
assert.Equal(t, tc.website, decoded.Website)
})
}
}
func TestRegistryRejectsInvalidUsageProfiles(t *testing.T) {
for _, tc := range []struct {
name, profiles, errorText string
}{
{"null", `null`, "usageProfiles must be an array"},
{"object", `{}`, "usageProfiles must be an array"},
{"invalid entry", `[null]`, "must be an object"},
{"unknown property", `[{models:["image"], schema:{}, extra:true}]`, "unknown field"},
{"missing models", `[{schema:{}}]`, "at least one model"},
{"empty models", `[{models:[], schema:{}}]`, "at least one model"},
{"unknown model", `[{models:["other"], schema:{}}]`, "not declared"},
{"noncanonical model", `[{models:[" image"], schema:{}}]`, "canonical names"},
{"wrong declared spelling", `[{models:["IMAGE"], schema:{}}]`, "not declared"},
{"duplicate models", `[{models:["image","IMAGE"], schema:{}}]`, "unique case-insensitively"},
{"overlapping profiles", `[{models:["image"], schema:{}}, {models:["image"], schema:{}}]`, "multiple profiles"},
{"missing schema", `[{models:["image"]}]`, "must be an object"},
{"invalid field", `[{models:["image"], schema:{n:{type:"number", unit:"invalid"}}}]`, "unit must be"},
{"noncanonical field", `[{models:["image"], schema:{" n":{type:"number", unit:"count"}}}]`, "canonical names"},
{"tokens need examples", `[{models:["image"], schema:{tokens:{type:"number", unit:"token"}}}]`, "usageExamples is required"},
{"examples use own schema", `[{models:["image"], schema:{n:{type:"number", unit:"count"}}, examples:[{label:"wrong", facts:{seconds:1}}]}]`, "usageProfiles[0]"},
} {
t.Run(tc.name, func(t *testing.T) {
source := routingTestPluginSource("invalid-profile", 0, `["image", "video"]`,
`usageSchema: {seconds: {type:"number", unit:"second"}}, usageExamples: [{label:"default", facts:{seconds:1}}], usageProfiles: `+tc.profiles+`,`, "")
_, err := CompilePlugin(source, Options{})
require.ErrorContains(t, err, tc.errorText)
})
}
plugin, err := CompilePlugin(routingTestPluginSource("token-profile", 0, `["image"]`, `
usageProfiles: [{models:["image"], schema:{tokens:{type:"number", unit:"token"}}, examples:[{label:"one token", facts:{tokens:1}}]}],`, ""), Options{})
require.NoError(t, err)
schema, examples := plugin.Meta.UsageForModel("image")
assert.Equal(t, "token", schema["tokens"].Unit)
require.Len(t, examples, 1)
assert.EqualValues(t, 1, examples[0].Facts["tokens"])
plugin.Meta.UsageProfiles[0].Schema = nil
require.ErrorContains(t, ValidateV1Meta(plugin.Meta), "schema must be an object")
}
func TestUpstreamsManifestContract(t *testing.T) {
for _, tc := range []struct {
name, metadata string
valid, newAPI bool
}{
{"omitted implies vendor", "", true, false},
{"vendor only", `upstreams:["vendor"],`, true, false},
{"vendor and new api", `upstreams:["vendor","new_api"],`, true, true},
{"new api only still serves its vendor", `upstreams:["new_api"],`, true, true},
{"unknown kind", `upstreams:["gateway"],`, false, false},
{"duplicate", `upstreams:["new_api","new_api"],`, false, false},
{"null", `upstreams:null,`, false, false},
} {
t.Run(tc.name, func(t *testing.T) {
plugin, err := CompilePlugin(routingTestPluginSource("upstreams", 0, `["model"]`, tc.metadata, ""), Options{})
if !tc.valid {
require.Error(t, err)
return
}
require.NoError(t, err)
require.NoError(t, ValidateV1Meta(plugin.Meta))
assert.True(t, plugin.Meta.SupportsUpstream(UpstreamKindVendor))
assert.Equal(t, tc.newAPI, plugin.Meta.SupportsUpstream(UpstreamKindNewAPI))
})
}
}
func TestSubmitResponseTypesContract(t *testing.T) {
for _, tc := range []struct {
name, metadata, hook string
valid bool
}{
{"legacy JSON", "", "", true},
{"SSE declared", `submitResponseTypes:["json","sse"],`, `export function parseSubmitEvent(){return {state:null,done:true};}`, true},
{"host JSON utility", `requiredCapabilities:["json-clone@1"],`, "", true},
{"SSE delta", `submitResponseTypes:["sse"],requiredCapabilities:["submit-sse-delta@1"],`, `export function parseSubmitEventDelta(){return {changes:[],state:null,done:true};}`, true},
{"SSE delta missing hook", `submitResponseTypes:["sse"],requiredCapabilities:["submit-sse-delta@1"],`, `export function parseSubmitEvent(){return {state:null,done:true};}`, false},
{"SSE delta hook without declaration", `submitResponseTypes:["sse"],`, `export function parseSubmitEventDelta(){return {changes:[],state:null,done:true};}`, true},
{"SSE snapshot and delta hooks", `submitResponseTypes:["sse"],`, `export function parseSubmitEvent(){return {state:null,done:true};}
export function parseSubmitEventDelta(){return {changes:[],state:null,done:true};}`, true},
{"delta requires SSE", `requiredCapabilities:["submit-sse-delta@1"],`, "", false},
{"unsupported capability version", `requiredCapabilities:["json-clone@2"],`, "", false},
{"duplicate capability", `requiredCapabilities:["json-clone@1","json-clone@1"],`, "", false},
{"null capabilities", `requiredCapabilities:null,`, "", false},
{"missing hook", `submitResponseTypes:["sse"],`, "", false},
{"unknown type", `submitResponseTypes:["xml"],`, "", false},
{"duplicate", `submitResponseTypes:["json","json"],`, "", false},
{"empty", `submitResponseTypes:[],`, "", false},
{"null", `submitResponseTypes:null,`, "", false},
} {
t.Run(tc.name, func(t *testing.T) {
source := routingTestPluginSource("submit-types", 0, `["model"]`, tc.metadata, "") + tc.hook
plugin, err := CompilePlugin(source, Options{})
if tc.valid {
require.NoError(t, err)
require.NoError(t, ValidateV1Meta(plugin.Meta))
} else {
require.Error(t, err)
}
})
}
}
func compileConfigPlugin(schema string) (*LoadedPlugin, error) {
return CompilePlugin(`export const meta = {apiVersion: 1, key: "redact", name: "Redact", version: "1.0.0", author: {name: "Test"}, configSchema: `+schema+`};
export function ingress() { return {action: "continue"}; }`, Options{})
}
func TestConfigSchemaContract(t *testing.T) {
// The normalized schema keeps the declared property order and writes
// every LocalizedText as an object.
plugin, err := compileConfigPlugin(`{type: "object", required: ["rules"], properties: {
rules: {type: "array", title: "Rules", items: {type: "object", title: "Rule", properties: {
pattern: {type: "string", title: {en: "Pattern", zh: "规则"}, format: "regex", minLength: 1},
mode: {type: "string", title: "Mode", enum: ["keyword", "regex"], enumTitles: ["Keyword", {en: "Regex", "ZH-cn": "正则"}], default: "keyword"},
}, required: ["pattern"]}},
message: {type: "string", title: "Message", format: "textarea", examples: ["Blocked"]},
extra: {type: "object", title: "Extra", format: "json"},
}}`)
require.NoError(t, err)
assert.Equal(t, `{"type":"object","properties":{`+
`"rules":{"type":"array","title":{"en":"Rules"},"items":{"type":"object","title":{"en":"Rule"},"properties":{`+
`"pattern":{"type":"string","title":{"en":"Pattern","zh":"规则"},"minLength":1,"format":"regex"},`+
`"mode":{"type":"string","title":{"en":"Mode"},"default":"keyword","enum":["keyword","regex"],"enumTitles":[{"en":"Keyword"},{"en":"Regex","zh-CN":"正则"}]}},`+
`"required":["pattern"]}},`+
`"message":{"type":"string","title":{"en":"Message"},"examples":["Blocked"],"format":"textarea"},`+
`"extra":{"type":"object","title":{"en":"Extra"},"format":"json"}},"required":["rules"]}`, string(plugin.Meta.ConfigSchemaJSON()))
encoded, err := marshalJSON(plugin.Meta)
require.NoError(t, err)
assert.Contains(t, string(encoded), `"configSchema":{"type":"object","properties":{"rules":`)
// unit and visibleWhen are display hints: the normalized schema writes
// every visibleWhen value as a list, and a hidden property is still
// checked and gets its default.
plugin, err = compileConfigPlugin(`{type: "object", properties: {
mode: {type: "string", title: "Mode", enum: ["lossless", "lossy"], default: "lossless"},
level: {type: "integer", title: "Level", enum: [1, 2, 3]},
strict: {type: "boolean", title: "Strict"},
maxSide: {type: "integer", title: "Maximum side", minimum: 16, default: 2048, unit: "pixel", visibleWhen: {mode: "lossy"}},
minBytes: {type: "number", title: "Minimum size", unit: "byte", visibleWhen: {strict: true, mode: ["lossy", "lossless"], level: [1, 3]}},
rules: {type: "array", title: "Rules", items: {type: "object", title: "Rule", properties: {
kind: {type: "string", title: "Kind", enum: ["keyword", "regex"]},
flags: {type: "string", title: "Flags", visibleWhen: {kind: "regex"}},
}}},
}}`)
require.NoError(t, err)
assert.Equal(t, `{"type":"object","properties":{`+
`"mode":{"type":"string","title":{"en":"Mode"},"default":"lossless","enum":["lossless","lossy"]},`+
`"level":{"type":"integer","title":{"en":"Level"},"enum":[1,2,3]},`+
`"strict":{"type":"boolean","title":{"en":"Strict"}},`+
`"maxSide":{"type":"integer","title":{"en":"Maximum side"},"default":2048,"minimum":16,"unit":"pixel","visibleWhen":{"mode":["lossy"]}},`+
`"minBytes":{"type":"number","title":{"en":"Minimum size"},"unit":"byte","visibleWhen":{"level":[1,3],"mode":["lossy","lossless"],"strict":[true]}},`+
`"rules":{"type":"array","title":{"en":"Rules"},"items":{"type":"object","title":{"en":"Rule"},"properties":{`+
`"kind":{"type":"string","title":{"en":"Kind"},"enum":["keyword","regex"]},`+
`"flags":{"type":"string","title":{"en":"Flags"},"visibleWhen":{"kind":["regex"]}}}}}}}`, string(plugin.Meta.ConfigSchemaJSON()))
validated, err := plugin.ValidateConfig(json.RawMessage(`{}`))
require.NoError(t, err)
assert.Equal(t, `{"maxSide":2048,"mode":"lossless"}`, string(validated))
_, err = plugin.ValidateConfig(json.RawMessage(`{"mode":"lossless","maxSide":8}`))
require.ErrorContains(t, err, "config.maxSide must be at least 16")
for name, tc := range map[string]struct{ schema, message string }{
"unknown member": {`{type: "object", properties: {a: {type: "string", title: "A", placeholder: "x"}}}`, `properties.a has unknown member "placeholder"`},
"unknown schema member": {`{type: "object", properties: {}, title: "Config"}`, `configSchema has unknown member "title"`},
"member of another type": {`{type: "object", properties: {a: {type: "number", title: "A", pattern: "x"}}}`, "pattern does not apply to a field of type number"},
"missing title": {`{type: "object", properties: {a: {type: "string"}}}`, "properties.a.title is required"},
"title without en": {`{type: "object", properties: {a: {type: "string", title: {zh: "甲"}}}}`, `must include a non-empty "en" value`},
"too deep": {`{type: "object", properties: {a: {type: "array", title: "A", items: {type: "object", title: "B", properties: {c: {type: "array", title: "C", items: {type: "array", title: "D", items: {type: "string", title: "E"}}}}}}}}`, "nests deeper than 4 levels"},
"enumTitles length": {`{type: "object", properties: {a: {type: "string", title: "A", enum: ["x", "y"], enumTitles: ["X"]}}}`, "enumTitles must be an array as long as enum"},
"enumTitles without enum": {`{type: "object", properties: {a: {type: "string", title: "A", enumTitles: ["X"]}}}`, "enumTitles must be an array as long as enum"},
"enum of another type": {`{type: "object", properties: {a: {type: "integer", title: "A", enum: [1, 1.5]}}}`, "enum values must be of type integer"},
"bad pattern": {`{type: "object", properties: {a: {type: "string", title: "A", pattern: "(?<=a)b"}}}`, "pattern is not a valid RE2 regular expression"},
"bad format": {`{type: "object", properties: {a: {type: "string", title: "A", format: "json"}}}`, "format must be one of textarea, regex, url, password, keywords for a field of type string"},
"url default": {`{type: "object", properties: {a: {type: "string", title: "A", format: "url", default: "api.example.com/v1"}}}`, "properties.a.default must be an absolute http or https URL without credentials or fragment"},
"invalid default": {`{type: "object", properties: {a: {type: "integer", title: "A", minimum: 1, default: 0}}}`, "properties.a.default must be at least 1"},
"required not declared": {`{type: "object", properties: {a: {type: "string", title: "A"}}, required: ["b"]}`, "required must be an array of declared property names"},
"schema not an object": {`{type: "array", properties: {}}`, `configSchema must be {type: "object", properties: {...}}`},
"unit on a string": {`{type: "object", properties: {a: {type: "string", title: "A", unit: "byte"}}}`, "properties.a.unit does not apply to a field of type string"},
"unknown unit": {`{type: "object", properties: {a: {type: "integer", title: "A", unit: "meter"}}}`, "properties.a.unit must be one of byte, pixel, character, second"},
"visibleWhen on the schema": {`{type: "object", properties: {a: {type: "string", title: "A"}}, visibleWhen: {a: "x"}}`, `configSchema has unknown member "visibleWhen"`},
"visibleWhen on items": {`{type: "object", properties: {mode: {type: "string", title: "Mode"}, a: {type: "array", title: "A", items: {type: "string", title: "B", visibleWhen: {mode: "x"}}}}}`, "properties.a.items.visibleWhen applies only to a property"},
"visibleWhen unknown sibling": {`{type: "object", properties: {mode: {type: "string", title: "Mode"}, a: {type: "array", title: "A", items: {type: "object", title: "B", properties: {c: {type: "string", title: "C", visibleWhen: {mode: "x"}}}}}}}`, "properties.a.items.properties.c.visibleWhen.mode must name another property of the same object"},
"visibleWhen on itself": {`{type: "object", properties: {a: {type: "string", title: "A", visibleWhen: {a: "x"}}}}`, "properties.a.visibleWhen.a must name another property of the same object"},
"visibleWhen sibling of type array": {`{type: "object", properties: {tags: {type: "array", title: "Tags"}, a: {type: "string", title: "A", visibleWhen: {tags: "x"}}}}`, "properties.a.visibleWhen.tags must name a property of type string, number, integer or boolean"},
"visibleWhen sibling of type object": {`{type: "object", properties: {extra: {type: "object", title: "Extra"}, a: {type: "string", title: "A", visibleWhen: {extra: {}}}}}`, "properties.a.visibleWhen.extra must name a property of type string, number, integer or boolean"},
"visibleWhen value outside enum": {`{type: "object", properties: {mode: {type: "string", title: "Mode", enum: ["a", "b"]}, x: {type: "string", title: "X", visibleWhen: {mode: ["a", "c"]}}}}`, "properties.x.visibleWhen.mode[1] must be one of the listed values"},
"visibleWhen value type": {`{type: "object", properties: {on: {type: "boolean", title: "On"}, x: {type: "string", title: "X", visibleWhen: {on: "yes"}}}}`, "properties.x.visibleWhen.on must be a boolean"},
"visibleWhen empty": {`{type: "object", properties: {mode: {type: "string", title: "Mode"}, x: {type: "string", title: "X", visibleWhen: {}}}}`, "properties.x.visibleWhen must be a non-empty object"},
"visibleWhen empty list": {`{type: "object", properties: {mode: {type: "string", title: "Mode"}, x: {type: "string", title: "X", visibleWhen: {mode: []}}}}`, "properties.x.visibleWhen.mode must be a value or a non-empty array of values"},
"visibleWhen repeated value": {`{type: "object", properties: {level: {type: "integer", title: "Level"}, x: {type: "string", title: "X", visibleWhen: {level: [1, 2, 1]}}}}`, "properties.x.visibleWhen.level values must be unique"},
} {
t.Run(name, func(t *testing.T) {
_, err := compileConfigPlugin(tc.schema)
require.ErrorContains(t, err, tc.message)
})
}
_, err = CompilePlugin(`export const meta = {apiVersion: 1, key: "relay", name: "Relay", version: "1.0.0", author: {name: "Test"},
relay: [{incoming_path: "/v1/chat/completions", upstream_path: "/v1/chat/completions"}], configSchema: {type: "object", properties: {}}};`, Options{})
require.ErrorContains(t, err, "configSchema belongs to the request processing part")
}
// meta.optional is a boolean of a plugin with a request processing part.
func TestOptionalManifestField(t *testing.T) {
const head = `export const meta = {apiVersion: 1, key: "opt", name: "Opt", version: "1.0.0", author: {name: "Test"}%s};`
const relay = `, relay: [{incoming_path: "/v1/chat/completions", upstream_path: "/v1/chat/completions"}]`
for name, tc := range map[string]struct {
manifest, exports, message string
optional bool
}{
"declared": {manifest: `, optional: true`, exports: `export function ingress() {}`, optional: true},
"not declared": {exports: `export function outbound() {}`},
"report alone": {manifest: `, optional: true`, exports: `export function report() {}`, optional: true},
"not a boolean": {manifest: `, optional: "yes"`, exports: `export function ingress() {}`, message: "plugin meta optional must be a boolean"},
"no request processing part": {manifest: relay + `, optional: false`, message: "plugin opt meta optional belongs to the request processing part"},
} {
t.Run(name, func(t *testing.T) {
plugin, err := CompilePlugin(fmt.Sprintf(head, tc.manifest)+tc.exports, Options{})
if tc.message != "" {
require.ErrorContains(t, err, tc.message)
return
}
require.NoError(t, err)
assert.Equal(t, tc.optional, plugin.Meta.Optional)
})
}
}
func TestScopeManifestField(t *testing.T) {
const head = `export const meta = {apiVersion: 1, key: "scoped", name: "Scoped", version: "1.0.0", author: {name: "Test"}%s};`
const relay = `, relay: [{incoming_path: "/v1/chat/completions", upstream_path: "/v1/chat/completions"}]`
const ingress = `export function ingress() {}`
for name, tc := range map[string]struct {
manifest, exports, message string
scope *TransformScope
}{
"models and channel types": {manifest: `, scope: {models: ["gpt-4o", "claude"], channelTypes: [1, 14]}`, exports: ingress, scope: &TransformScope{Models: []string{"gpt-4o", "claude"}, ChannelTypes: []int{1, 14}}},
"models alone": {manifest: `, scope: {models: ["gpt-4o"]}`, exports: ingress, scope: &TransformScope{Models: []string{"gpt-4o"}}},
"channel types alone": {manifest: `, scope: {channelTypes: [3]}`, exports: ingress, scope: &TransformScope{ChannelTypes: []int{3}}},
"not declared": {exports: ingress},
"every request": {manifest: `, scope: {}`, exports: ingress, message: "plugin meta scope must list at least one model or channel type"},
"empty lists": {manifest: `, scope: {models: [], channelTypes: []}`, exports: ingress, message: "must list at least one model or channel type"},
"unknown field": {manifest: `, scope: {groups: ["vip"]}`, exports: ingress, message: `plugin meta scope has unknown field "groups"`},
"not an object": {manifest: `, scope: ["gpt-4o"]`, exports: ingress, message: "plugin meta scope must be an object"},
"blank model": {manifest: `, scope: {models: [" gpt"]}`, exports: ingress, message: "scope.models must hold names of 1 to 128 characters"},
"repeated model": {manifest: `, scope: {models: ["gpt", "gpt"]}`, exports: ingress, message: `scope.models lists "gpt" twice`},
"zero channel type": {manifest: `, scope: {channelTypes: [0]}`, exports: ingress, message: "scope.channelTypes must hold positive channel types"},
"text channel type": {manifest: `, scope: {channelTypes: ["1"]}`, exports: ingress, message: "scope.channelTypes must be an array of integers"},
"no request processing part": {manifest: relay + `, scope: {models: ["gpt"]}`, message: "plugin scoped meta scope belongs to the request processing part"},
} {
t.Run(name, func(t *testing.T) {
plugin, err := CompilePlugin(fmt.Sprintf(head, tc.manifest)+tc.exports, Options{})
if tc.message != "" {
require.ErrorContains(t, err, tc.message)
return
}
require.NoError(t, err)
assert.Equal(t, tc.scope, plugin.Meta.Scope)
})
}
}
func TestValidateConfig(t *testing.T) {
plugin, err := compileConfigPlugin(`{type: "object", properties: {
rules: {type: "array", title: "Rules", maxItems: 2, items: {type: "object", title: "Rule", properties: {
pattern: {type: "string", title: "Pattern", pattern: "^[a-z]+$"},
caseSensitive: {type: "boolean", title: "Case sensitive", default: false},
}, required: ["pattern"]}},
quality: {type: "integer", title: "Quality", minimum: 1, maximum: 100, default: 85},
format: {type: "string", title: "Format", enum: ["auto", "jpeg"], default: "auto"},
tags: {type: "array", title: "Tags", uniqueItems: true, items: {type: "string", title: "Tag"}},
override: {type: "object", title: "Override", format: "json"},
endpoint: {type: "string", title: "Endpoint", format: "url"},
apiKey: {type: "string", title: "API key", format: "password"},
}, required: ["rules"]}`)
require.NoError(t, err)
for name, tc := range map[string]struct{ config, want, message string }{
"url and password": {config: `{"rules":[],"endpoint":"http://127.0.0.1:8080/v1/moderations?x=1","apiKey":"sk-1"}`, want: `{"apiKey":"sk-1","endpoint":"http://127.0.0.1:8080/v1/moderations?x=1","format":"auto","quality":85,"rules":[]}`},
"empty url": {config: `{"rules":[],"endpoint":""}`, want: `{"endpoint":"","format":"auto","quality":85,"rules":[]}`},
"url without scheme": {config: `{"rules":[],"endpoint":"api.example.com/v1"}`, message: "config.endpoint must be an absolute http or https URL without credentials or fragment"},
"url of another kind": {config: `{"rules":[],"endpoint":"ftp://api.example.com/v1"}`, message: "config.endpoint must be an absolute http or https URL"},
"url credentials": {config: `{"rules":[],"endpoint":"https://user:pass@api.example.com/v1"}`, message: "config.endpoint must be an absolute http or https URL"},
"url fragment": {config: `{"rules":[],"endpoint":"https://api.example.com/v1#top"}`, message: "config.endpoint must be an absolute http or https URL"},
"defaults applied": {config: `{"rules":[{"pattern":"abc"}]}`, want: `{"format":"auto","quality":85,"rules":[{"caseSensitive":false,"pattern":"abc"}]}`},
"values kept": {config: `{"rules":[],"quality":100,"format":"jpeg","tags":["a","b"],"override":{"operations":[1]}}`, want: `{"format":"jpeg","override":{"operations":[1]},"quality":100,"rules":[],"tags":["a","b"]}`},
"required missing": {config: `{}`, message: "config.rules is required"},
"string type": {config: `{"rules":[{"pattern":1}]}`, message: "config.rules[0].pattern must be a string"},
"integer type": {config: `{"rules":[],"quality":1.5}`, message: "config.quality must be an integer"},
"maximum": {config: `{"rules":[],"quality":101}`, message: "config.quality must not exceed 100"},
"enum": {config: `{"rules":[],"format":"png"}`, message: "config.format must be one of the listed values"},
"pattern": {config: `{"rules":[{"pattern":"ABC"}]}`, message: "config.rules[0].pattern does not match the required pattern"},
"maxItems": {config: `{"rules":[{"pattern":"a"},{"pattern":"b"},{"pattern":"c"}]}`, message: "config.rules must not have more than 2 items"},
"uniqueItems": {config: `{"rules":[],"tags":["a","a"]}`, message: "config.tags[1] repeats an earlier item"},
"unknown property": {config: `{"rules":[],"limit":1}`, message: `config has unknown property "limit"`},
"nested unknown": {config: `{"rules":[{"pattern":"a","flags":"i"}]}`, message: `config.rules[0] has unknown property "flags"`},
"object type": {config: `{"rules":[],"override":[]}`, message: "config.override must be an object"},
"config not object": {config: `[]`, message: "config must be a JSON object"},
"config not JSON": {config: `{`, message: "config must be a JSON object"},
"null property value": {config: `{"rules":null}`, message: "config.rules must be an array"},
} {
t.Run(name, func(t *testing.T) {
validated, err := plugin.ValidateConfig(json.RawMessage(tc.config))
if tc.message != "" {
require.ErrorContains(t, err, tc.message)
return
}
require.NoError(t, err)
assert.Equal(t, tc.want, string(validated))
})
}
// The host and port of each url value, nested ones included, are hosts
// utils.fetch may address; other strings are not.
withURLs, err := compileConfigPlugin(`{type: "object", properties: {
endpoint: {type: "string", title: "Endpoint", format: "url"},
plain: {type: "string", title: "Plain"},
sinks: {type: "array", title: "Sinks", items: {type: "object", title: "Sink", properties: {url: {type: "string", title: "URL", format: "url"}}}},
}}`)
require.NoError(t, err)
assert.Equal(t, []string{"api.example.com", "127.0.0.1:3100"}, withURLs.ConfigURLHosts(json.RawMessage(
`{"endpoint":"https://api.example.com/v1","plain":"https://other.example/","sinks":[{"url":"http://127.0.0.1:3100/ingest"},{"url":""}]}`)))
withoutSchema, err := CompilePlugin(`export const meta = {apiVersion: 1, key: "plain", name: "Plain", version: "1.0.0", author: {name: "Test"}};
export function egress() { return {action: "continue"}; }`, Options{})
require.NoError(t, err)
assert.Nil(t, withoutSchema.Meta.ConfigSchemaJSON())
for _, config := range []string{`{}`, ` `, ``} {
validated, err := withoutSchema.ValidateConfig(json.RawMessage(config))
require.NoError(t, err, config)
assert.Equal(t, `{}`, string(validated))
}
_, err = withoutSchema.ValidateConfig(json.RawMessage(`{"a":1}`))
require.ErrorContains(t, err, "plugin plain takes no config; config must be {}")
}
// An exported validateConfig runs after the schema check, on the config with
// its defaults, and its throw is the error the administrator sees.
func TestValidateConfigExport(t *testing.T) {
const head = `export const meta = {apiVersion: 1, key: "checked", name: "Checked", version: "1.0.0", author: {name: "Test"}, %s};
export function ingress() { return {action: "continue"}; }
`
const schema = `configSchema: {type: "object", properties: {pattern: {type: "string", title: "Pattern", default: "a+"}, limit: {type: "integer", title: "Limit", maximum: 10}}}`
plugin, err := CompilePlugin(fmt.Sprintf(head, schema)+`export function validateConfig(config) {
if (config.pattern === undefined) throw new Error("defaults were not applied");
if (config.pattern === "(") throw new Error("Rule has an invalid regular expression");
if (config.limit === 6) while (true) {}
if (config.limit === 7) throw new Error("x".repeat(300));
if (config.limit === 8) utils.fetch({url: "https://example.com"});
if (config.limit === 9) utils.paramOverride({}, {});
}`, Options{Timeout: 200 * time.Millisecond})
require.NoError(t, err)
for name, tc := range map[string]struct{ config, want, message string }{
"passes with defaults": {config: `{}`, want: `{"pattern":"a+"}`},
"passes": {config: `{"pattern":"b+","limit":1}`, want: `{"limit":1,"pattern":"b+"}`},
"schema check first": {config: `{"limit":11}`, message: "config.limit must not exceed 10"},
"throw is the error": {config: `{"pattern":"("}`, message: "Rule has an invalid regular expression"},
"utils.fetch throws": {config: `{"limit":8}`, message: "utils.fetch is not available in validateConfig"},
"paramOverride throws": {config: `{"limit":9}`, message: "utils.paramOverride is not available in validateConfig"},
"timeout": {config: `{"limit":6}`, message: "plugin checked validateConfig timed out"},
} {
t.Run(name, func(t *testing.T) {
validated, err := plugin.ValidateConfig(json.RawMessage(tc.config))
if tc.message != "" {
require.ErrorContains(t, err, tc.message)
return
}
require.NoError(t, err)
assert.Equal(t, tc.want, string(validated))
})
}
_, err = plugin.ValidateConfig(json.RawMessage(`{"limit":7}`))
require.Error(t, err)
assert.Equal(t, 256, utf8.RuneCountInString(err.Error()), "a long thrown message is cut to 256 characters")
withoutSchema, err := CompilePlugin(fmt.Sprintf(head, `description: "No config"`)+`export function validateConfig(config) {
if (Object.keys(config).length !== 0) throw new Error("expected {}");
throw new Error("refused");
}`, Options{})
require.NoError(t, err)
_, err = withoutSchema.ValidateConfig(nil)
require.EqualError(t, err, "refused")
for name, tc := range map[string]struct{ source, message string }{
"not a function": {fmt.Sprintf(head, schema) + `export const validateConfig = 1;`, `plugin checked export "validateConfig" is not a function`},
"no request processing part": {`export const meta = {apiVersion: 1, key: "checked", name: "Checked", version: "1.0.0", author: {name: "Test"},
relay: [{incoming_path: "/v1/chat/completions", upstream_path: "/v1/chat/completions"}]};
export function validateConfig() {}`, "export validateConfig belongs to the request processing part"},
} {
t.Run(name, func(t *testing.T) {
_, err := CompilePlugin(tc.source, Options{})
require.ErrorContains(t, err, tc.message)
})
}
}
func TestMetaFieldsMatchSchemaProperties(t *testing.T) {
var schema struct {
Properties map[string]json.RawMessage `json:"properties"`
}
require.NoError(t, unmarshalJSON(SchemaV1, &schema))
assert.ElementsMatch(t, slices.Collect(maps.Keys(schema.Properties)), metaFields)
}
@@ -1,4 +1,4 @@
package jsplugin
package pluginkit
// asciiFold maps only 'A'–'Z' onto 'a'–'z'. Every other byte is unchanged.
// Unicode case folding is intentionally not applied: U+212A (KELVIN SIGN)
@@ -0,0 +1,224 @@
package pluginkit
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const (
responsesDecodeOnly = `export const protocols = {openai_responses: {
decodeRequest: function(ctx) { return ctx; }
}};`
responsesDecodeEvents = `export const protocols = {openai_responses: {
decodeRequest: function(ctx) { return ctx; },
renderEvents: function() { return {events: [], state: null, done: false}; }
}};`
responsesDecodeFinal = `export const protocols = {openai_responses: {
decodeRequest: function(ctx) { return ctx; },
renderFinal: function(ctx, task) { return task; }
}};`
responsesDecodeBoth = `export const protocols = {openai_responses: {
decodeRequest: function(ctx) { return ctx; },
renderEvents: function() { return {events: [], state: null, done: false}; },
renderFinal: function(ctx, task) { return task; }
}};`
videoProtocolExport = `export const protocols = {openai_video: {
decodeRequest: function(ctx) { return ctx; },
render: function(ctx, task) { return task; }
}};
export function listArtifacts() { return []; }
export function buildContentRequest() { return {}; }`
)
func TestProtocolSupportsLoadErrors(t *testing.T) {
tests := []struct {
name string
protocols string
exports string
err string
}{
{
name: "bare string",
protocols: `["openai_responses"]`,
exports: responsesDecodeBoth,
err: `plugin acme protocol "openai_responses" must declare supports; replace the bare string with {name: "openai_responses", supports: [...]} choosing from "stream", "sync", "background"`,
},
{
name: "object without supports",
protocols: `[{name: "openai_responses"}]`,
exports: responsesDecodeBoth,
err: `plugin acme protocol "openai_responses" must declare supports; add supports: [...] choosing from "stream", "sync", "background"`,
},
{
name: "supports sync but only renderEvents",
protocols: `[{name: "openai_responses", supports: ["sync"]}]`,
exports: responsesDecodeEvents,
err: `plugin acme protocol "openai_responses" supports "sync" but does not export protocols.openai_responses.renderFinal; implement it or declare supports: ["stream"]`,
},
{
name: "supports sync with only decodeRequest",
protocols: `[{name: "openai_responses", supports: ["sync"]}]`,
exports: responsesDecodeOnly,
err: `plugin acme protocol "openai_responses" supports "sync" but does not export protocols.openai_responses.renderFinal; implement it`,
},
{
name: "supports stream but also exports renderFinal",
protocols: `[{name: "openai_responses", supports: ["stream"]}]`,
exports: responsesDecodeBoth,
err: `plugin acme protocol "openai_responses" exports protocols.openai_responses.renderFinal but no supported mode uses it; add "sync" or "background" to supports or remove the hook`,
},
{
name: "supports sync and background but also exports renderEvents",
protocols: `[{name: "openai_responses", supports: ["sync", "background"]}]`,
exports: responsesDecodeBoth,
err: `plugin acme protocol "openai_responses" exports protocols.openai_responses.renderEvents but no supported mode uses it; add "stream" to supports or remove the hook`,
},
{
name: "empty supports",
protocols: `[{name: "openai_responses", supports: []}]`,
exports: responsesDecodeBoth,
err: `plugin acme protocol "openai_responses" supports must contain at least one of "stream", "sync", "background"`,
},
{
name: "duplicate supports",
protocols: `[{name: "openai_responses", supports: ["stream", "stream"]}]`,
exports: responsesDecodeBoth,
err: `plugin acme protocol "openai_responses" supports must be unique`,
},
{
name: "retrieve is not a mode",
protocols: `[{name: "openai_responses", supports: ["retrieve"]}]`,
exports: responsesDecodeBoth,
err: `plugin acme protocol "openai_responses" has no mode "retrieve"; retrieval of a created response is always available and is never declared`,
},
{
name: "openai_video forbids supports",
protocols: `[{name: "openai_video", supports: ["stream"]}]`,
exports: videoProtocolExport,
err: `plugin acme protocol "openai_video" does not define modes; supports is not allowed`,
},
{
name: "unknown protocol forbids supports",
protocols: `[{name: "openai_custom", supports: ["stream"]}]`,
err: `plugin acme protocol "openai_custom" does not define modes; supports is not allowed`,
},
}
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
_, err := compileProtocolPlugin(t, "acme", `["model"]`, testCase.protocols, testCase.exports)
require.ErrorContains(t, err, testCase.err)
})
}
}
func TestProtocolSupportsHappyPaths(t *testing.T) {
tests := []struct {
name string
models string
protocols string
exports string
wantProtocols []ProtocolClaim
}{
{
name: "stream only with renderEvents",
models: `["model"]`,
protocols: `[{name: "openai_responses", supports: ["stream"]}]`,
exports: responsesDecodeEvents,
wantProtocols: []ProtocolClaim{
{Name: "openai_responses", Supports: []string{"stream"}, objectForm: true},
},
},
{
name: "sync and background with renderFinal",
models: `["model"]`,
protocols: `[{name: "openai_responses", supports: ["sync", "background"]}]`,
exports: responsesDecodeFinal,
wantProtocols: []ProtocolClaim{
{Name: "openai_responses", Supports: []string{"sync", "background"}, objectForm: true},
},
},
{
name: "all modes normalize to table order",
models: `["model"]`,
protocols: `[{name: "openai_responses", supports: ["background", "stream", "sync"]}]`,
exports: responsesDecodeBoth,
wantProtocols: []ProtocolClaim{
{Name: "openai_responses", Supports: []string{"stream", "sync", "background"}, objectForm: true},
},
},
{
name: "openai_video object without supports",
models: `["gpt-5.5", "gpt-5.6"]`,
protocols: `[{name: "openai_video", models: ["gpt-5.5"]}]`,
exports: videoProtocolExport,
wantProtocols: []ProtocolClaim{
{Name: "openai_video", Models: []string{"gpt-5.5"}, objectForm: true},
},
},
{
name: "bare openai_video",
models: `["model"]`,
protocols: `["openai_video"]`,
exports: videoProtocolExport,
wantProtocols: []ProtocolClaim{
{Name: "openai_video"},
},
},
}
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
plugin, err := compileProtocolPlugin(t, "acme", testCase.models, testCase.protocols, testCase.exports)
require.NoError(t, err)
require.Equal(t, testCase.wantProtocols, plugin.Meta.Protocols)
})
}
}
func TestMetaProtocolSupports(t *testing.T) {
streamOnly, err := compileProtocolPlugin(t, "acme", `["model"]`,
`[{name: "openai_responses", supports: ["stream"]}]`, responsesDecodeEvents)
require.NoError(t, err)
assert.True(t, streamOnly.Meta.ProtocolSupports("openai_responses", "stream"))
assert.False(t, streamOnly.Meta.ProtocolSupports("openai_responses", "sync"))
assert.False(t, streamOnly.Meta.ProtocolSupports("openai_responses", "background"))
assert.False(t, streamOnly.Meta.ProtocolSupports("openai_responses", "retrieve"))
assert.False(t, streamOnly.Meta.ProtocolSupports("openai_video", "stream"))
assert.False(t, streamOnly.Meta.ProtocolSupports("missing", "stream"))
video, err := compileProtocolPlugin(t, "acme-video", `["model"]`, `["openai_video"]`, videoProtocolExport)
require.NoError(t, err)
assert.False(t, video.Meta.ProtocolSupports("openai_video", "stream"))
}
func TestProtocolClaimMarshalEmitsSupportsInTableOrder(t *testing.T) {
plugin, err := compileProtocolPlugin(t, "acme", `["model"]`,
`[{name: "openai_responses", supports: ["background", "sync", "stream"]}]`, responsesDecodeBoth)
require.NoError(t, err)
encoded, err := marshalJSON(plugin.Meta.Protocols[0])
require.NoError(t, err)
assert.Equal(t, `{"name":"openai_responses","supports":["stream","sync","background"]}`, string(encoded))
}
func compileProtocolPlugin(t *testing.T, key, models, protocols, exports string) (*LoadedPlugin, error) {
t.Helper()
return CompilePlugin(protocolPluginSource(key, models, protocols, exports), Options{})
}
func protocolPluginSource(key, models, protocols, exports string) string {
return fmt.Sprintf(`
export const meta = {
apiVersion: 1, key: %q, name: %q, version: "1.0.0",
author: {name: "Test"},
models: %s, fetchMode: "per_task",
protocols: %s,
};
export function buildSubmitRequest() { return {}; }
export function parseSubmitResponse() { return {}; }
export function buildQueryRequest() { return {}; }
export function parseTaskResult() { return {}; }
%s
`, key, key, models, protocols, exports)
}
@@ -1,4 +1,4 @@
package jsplugin
package pluginkit
import (
"context"
@@ -14,8 +14,6 @@ import (
"unicode/utf8"
"github.com/MoeForge/moego/regexp"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
)
// CredentialType marks a channel key line that holds a plugin credential.
@@ -77,7 +75,7 @@ func ParseCredential(line string) (*Credential, bool) {
return nil, false
}
var credential Credential
if err := common.Unmarshal([]byte(trimmed), &credential); err != nil {
if err := unmarshalJSON([]byte(trimmed), &credential); err != nil {
return nil, false
}
if credential.Type != CredentialType || credential.Plugin == "" {
@@ -98,7 +96,7 @@ func (c Credential) Line() (string, error) {
if len(c.Data) == 0 {
c.Data = json.RawMessage("null")
}
encoded, err := common.Marshal(c)
encoded, err := marshalJSON(c)
if err != nil {
return "", err
}
@@ -148,7 +146,7 @@ func RedactCredentialLines(key string) string {
if !ok {
continue
}
encoded, err := common.Marshal(credential.Summary())
encoded, err := marshalJSON(credential.Summary())
if err != nil {
lines[index] = ""
continue
@@ -398,7 +396,7 @@ func (p *LoadedPlugin) CallScheduled(ctx context.Context, hookCtx ScheduledConte
if len(hookCtx.Credential) == 0 {
return ScheduledResult{}, fmt.Errorf("%s credential requires a plugin credential", subject)
}
scheduled.Credential, err = common.Marshal(raw)
scheduled.Credential, err = marshalJSON(raw)
if err != nil || len(scheduled.Credential) > MaxCredentialBytes {
return ScheduledResult{}, fmt.Errorf("%s credential must be JSON of at most %d bytes", subject, MaxCredentialBytes)
}
@@ -426,7 +424,7 @@ func (p *LoadedPlugin) CallScheduled(ctx context.Context, hookCtx ScheduledConte
if err != nil {
return ScheduledResult{}, err
}
encoded, err := common.Marshal(scheduled.Notify)
encoded, err := marshalJSON(scheduled.Notify)
if err != nil || len(encoded) > maxScheduledNotifyBytes {
return ScheduledResult{}, fmt.Errorf("%s notify must be at most %d bytes", subject, maxScheduledNotifyBytes)
}
@@ -844,7 +842,7 @@ func stateMember(object map[string]any, subject string) (json.RawMessage, error)
if !exists {
return nil, nil
}
state, err := common.Marshal(value)
state, err := marshalJSON(value)
if err != nil {
return nil, fmt.Errorf("%s state must be JSON: %v", subject, err)
}
@@ -1306,7 +1304,7 @@ func (p *LoadedPlugin) CallConvertStreamEvent(ctx context.Context, hookCtx HookC
}
if err == nil {
if value, exists := object["state"]; exists {
if state, err = common.Marshal(value); err == nil && len(state) > maxConvertedEventBytes() {
if state, err = marshalJSON(value); err == nil && len(state) > maxConvertedEventBytes() {
err = fmt.Errorf("convertStreamEvent result state exceeds %d bytes", maxConvertedEventBytes())
}
}
@@ -1397,20 +1395,6 @@ func decodeChunks(value any) ([][]byte, error) {
return chunks, nil
}
func maxConvertedBodyBytes() int {
if constant.MaxRequestBodyMB > 0 {
return constant.MaxRequestBodyMB << 20
}
return 128 << 20
}
func maxConvertedEventBytes() int {
if constant.StreamScannerMaxBufferMB > 0 {
return constant.StreamScannerMaxBufferMB << 20
}
return 128 << 20
}
// convertedBody reads the body member of a convert result: a string is the
// body text, any other value is sent as the JSON text JSON.stringify writes.
func convertedBody(object map[string]any, text json.RawMessage, subject string, limit int) ([]byte, error) {
@@ -1484,7 +1468,7 @@ func truncateRunes(text string, limit int) string {
func decodeStreamEvents(text json.RawMessage) ([]StreamEvent, error) {
var items []map[string]json.RawMessage
if err := common.Unmarshal(text, &items); err != nil {
if err := unmarshalJSON(text, &items); err != nil {
return nil, fmt.Errorf("convertStreamEvent result events must be an array of objects")
}
if len(items) > maxStreamEvents {
@@ -1497,12 +1481,12 @@ func decodeStreamEvents(text json.RawMessage) ([]StreamEvent, error) {
for name, raw := range item {
switch name {
case "event":
if err := common.Unmarshal(raw, &event.Event); err != nil || strings.ContainsAny(event.Event, "\r\n") {
if err := unmarshalJSON(raw, &event.Event); err != nil || strings.ContainsAny(event.Event, "\r\n") {
return nil, fmt.Errorf("convertStreamEvent result events[%d].event must be a single-line string", index)
}
case "data":
if len(raw) > 0 && raw[0] == '"' {
if err := common.Unmarshal(raw, &event.Data); err != nil {
if err := unmarshalJSON(raw, &event.Data); err != nil {
return nil, fmt.Errorf("convertStreamEvent result events[%d].data is invalid", index)
}
} else if string(raw) != "null" {
@@ -1535,7 +1519,7 @@ func decodeLoginStep(result any) (LoginStep, error) {
}
step := LoginStep{Type: stepType}
if value, exists := object["session"]; exists && stepType != LoginStepDone {
encoded, encodeErr := common.Marshal(value)
encoded, encodeErr := marshalJSON(value)
if encodeErr != nil {
return LoginStep{}, fmt.Errorf("session must be JSON: %v", encodeErr)
}
@@ -1682,7 +1666,7 @@ func decodeCredentialResult(object map[string]any, subject string) (CredentialRe
}
var result CredentialResult
var err error
if result.Credential, err = common.Marshal(value); err != nil {
if result.Credential, err = marshalJSON(value); err != nil {
return CredentialResult{}, fmt.Errorf("%s credential must be JSON: %v", strings.TrimSpace(subject), err)
}
if result.Headers, err = requestHeadersMember(object, "headers", subject); err != nil {
@@ -1899,7 +1883,7 @@ func (p *LoadedPlugin) CallExchangeKey(ctx context.Context, hookCtx CredentialCo
if err == nil {
if object["token"] == nil {
err = fmt.Errorf("%s token is required", subject)
} else if exchanged.Token, err = common.Marshal(object["token"]); err == nil && len(exchanged.Token) > MaxCredentialBytes {
} else if exchanged.Token, err = marshalJSON(object["token"]); err == nil && len(exchanged.Token) > MaxCredentialBytes {
err = fmt.Errorf("%s token exceeds %d bytes", subject, MaxCredentialBytes)
}
}
@@ -1,4 +1,4 @@
package jsplugin
package pluginkit
import (
"context"
@@ -8,8 +8,6 @@ import (
"testing"
"time"
"github.com/QuantumNous/new-api/common"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -205,8 +203,10 @@ func TestRelayConfigAcceptsAdvancedCustomConverters(t *testing.T) {
plugin := compileProviderPlugin(t, `[
{incoming_path: "/v1/chat/completions", upstream_path: "/{model}/generate", converter: "openai_chat_completions_to_openai_responses", models: ["re:^a-"], auth: {type: "header", name: "X-Key", value: "{api_key}"}},
{incoming_path: "/v1/chat/completions", upstream_path: "/other"},
{incoming_path: "/v1/responses", upstream_path: "/v1/messages", converter: "openai_responses_to_claude_messages"},
{incoming_path: "/v1/models", upstream_path: "/v1/models"}
]`, "")
require.NoError(t, plugin.Meta.RelayConfig().Validate())
route, ok := plugin.Meta.RelayRoute("/v1/chat/completions", "a-1")
require.True(t, ok)
@@ -214,6 +214,9 @@ func TestRelayConfigAcceptsAdvancedCustomConverters(t *testing.T) {
route, ok = plugin.Meta.RelayRoute("/v1/chat/completions", "b-1")
require.True(t, ok)
assert.Equal(t, "/other", route.UpstreamPath)
route, ok = plugin.Meta.RelayRoute("/v1/responses", "claude-1")
require.True(t, ok)
assert.Equal(t, "openai_responses_to_claude_messages", route.Converter)
_, ok = plugin.Meta.RelayRoute("/v1/embeddings", "a-1")
assert.False(t, ok)
}
@@ -1161,7 +1164,7 @@ func TestSamplesLoadAsWritten(t *testing.T) {
{name: {en: "Any", zh: "任意"}, format: "gemini", body: {contents: [{parts: [{text: "hi"}]}]}}
]`), Options{})
require.NoError(t, err)
encoded, err := common.Marshal(plugin.Meta.Samples)
encoded, err := marshalJSON(plugin.Meta.Samples)
require.NoError(t, err)
assert.JSONEq(t, `[
{"name":{"en":"Plain chat"},"lang":"en","format":"openai","body":{"model":"gpt","messages":[{"role":"user","content":[{"type":"text","text":"What is this?"},"[sample-image]"]}]},"reply":"A cat"},
@@ -1,4 +1,4 @@
package jsplugin
package pluginkit
import (
"fmt"
+93
View File
@@ -0,0 +1,93 @@
package pluginkit
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// toggleRelay serves chat always, Responses for model a off by default with a
// catch-all Responses route after it, and lists models.
const toggleRelay = `[
{incoming_path: "/v1/chat/completions", upstream_path: "/chat"},
{incoming_path: "/v1/responses", upstream_path: "/chat", models: ["a"], converter: "openai_responses_to_openai_chat_completions", default_enabled: false},
{incoming_path: "/v1/responses", upstream_path: "/responses"},
{incoming_path: "/v1/models", upstream_path: "/models"},
]`
func compileToggles(t *testing.T) *LoadedPlugin {
t.Helper()
plugin, err := CompilePlugin(`export const meta = {`+providerMeta+`, relay: `+toggleRelay+`};`, Options{})
require.NoError(t, err)
return plugin
}
func TestRelayRouteKeyNamesPathAndModels(t *testing.T) {
plugin := compileToggles(t)
keys := make([]string, 0, len(plugin.Meta.Relay))
for _, route := range plugin.Meta.Relay {
keys = append(keys, RelayRouteKey(route))
}
assert.Equal(t, []string{"/v1/chat/completions", "/v1/responses|a", "/v1/responses", "/v1/models"}, keys)
}
func TestDefaultEnabledFalseRouteIsOffUntilTheChannelTurnsItOn(t *testing.T) {
plugin := compileToggles(t)
assert.Equal(t, []bool{false, true, false, false}, plugin.Meta.RelayDefaultOff)
route, ok := plugin.Meta.ChannelRelayRoute(nil, "/v1/responses", "a")
require.True(t, ok, "the catch-all route still serves model a")
assert.Equal(t, "/responses", route.UpstreamPath)
route, ok = plugin.Meta.ChannelRelayRoute(map[string]bool{"/v1/responses|a": true}, "/v1/responses", "a")
require.True(t, ok)
assert.Equal(t, "/chat", route.UpstreamPath)
assert.Len(t, plugin.Meta.ChannelRelayConfig(nil, map[string]bool{"/v1/responses|a": true}).Routes, 4)
assert.Len(t, plugin.Meta.ChannelRelayConfig(nil, nil).Routes, 3)
}
func TestChannelCanSwitchOffADefaultOnRoute(t *testing.T) {
plugin := compileToggles(t)
toggles := map[string]bool{"/v1/responses": false}
_, ok := plugin.Meta.ChannelRelayRoute(toggles, "/v1/responses", "b")
assert.False(t, ok)
_, ok = plugin.Meta.ChannelRelayRoute(toggles, "/v1/chat/completions", "b")
assert.True(t, ok, "other paths are untouched")
assert.False(t, plugin.Meta.ChannelServesResponsesWebSocket(toggles, "b"))
assert.True(t, plugin.Meta.ChannelServesResponsesWebSocket(nil, "b"))
}
func TestManagementRoutesCannotBeSwitchedOff(t *testing.T) {
plugin := compileToggles(t)
_, ok := plugin.Meta.ChannelRelayConfig(nil, map[string]bool{"/v1/models": false}).ModelListRoute()
assert.True(t, ok)
_, err := CompilePlugin(`export const meta = {`+providerMeta+`, relay: [
{incoming_path: "/v1/models", upstream_path: "/models", default_enabled: false},
]};`, Options{})
require.Error(t, err)
assert.Contains(t, err.Error(), "default_enabled is not allowed on /v1/models")
}
func TestDefaultEnabledMustBeBoolean(t *testing.T) {
_, err := CompilePlugin(`export const meta = {`+providerMeta+`, relay: [
{incoming_path: "/v1/chat/completions", upstream_path: "/chat", default_enabled: "no"},
]};`, Options{})
require.Error(t, err)
assert.Contains(t, err.Error(), "relay[0].default_enabled must be a boolean")
}
func TestNormalizeRouteTogglesKeepsOnlyChangesFromDefaults(t *testing.T) {
plugin := compileToggles(t)
normalized := plugin.Meta.NormalizeRouteToggles(map[string]bool{
"/v1/chat/completions": true, // its default
"/v1/responses|a": true, // differs
"/v1/responses": false, // differs
"/v1/models": false, // management route
"/v1/unknown": false, // no such route
})
assert.Equal(t, map[string]bool{"/v1/responses|a": true, "/v1/responses": false}, normalized)
assert.Nil(t, plugin.Meta.NormalizeRouteToggles(map[string]bool{"/v1/chat/completions": true}))
}
+588
View File
@@ -0,0 +1,588 @@
package pluginkit
import (
"encoding/json"
"fmt"
"net/http"
"slices"
"strconv"
"strings"
"github.com/MoeForge/moego/regexp"
)
type RouteType string
const (
RouteTypeSubmit RouteType = "submit"
RouteTypeQuery RouteType = "query"
RouteTypeDynamic RouteType = "dynamic"
)
type Route struct {
Method string `json:"method"`
Path string `json:"path"`
Type RouteType `json:"type"`
Action string `json:"action,omitempty"`
Decode string `json:"decode,omitempty"`
Render string `json:"render,omitempty"`
TaskIDParam string `json:"taskIdParam,omitempty"`
// RetainResult, when explicitly false on a submit or dynamic route, tells
// the host not to persist the upstream snapshot of an immediate terminal
// result and to treat the task as not found on every retrieval surface
// afterwards. nil means the route did not declare it (retain).
RetainResult *bool `json:"retainResult,omitempty"`
// Models restricts this route to the listed models. The host matches the
// canonical top-level "model" body field before any JS hook runs; empty
// means unrestricted. Must be a subset of meta.models.
Models []string `json:"models,omitempty"`
}
// ProtocolClaim is one entry of meta.protocols. Models narrows the protocol's
// endpoint bindings to a subset of meta.models; empty binds every model.
// Supports names the request forms a mode-bearing protocol accepts; decode
// and normalize rewrite it into host-table order.
type ProtocolClaim struct {
Name string `json:"name"`
Models []string `json:"models,omitempty"`
Supports []string `json:"supports,omitempty"`
objectForm bool
}
// ProtocolMode is one client request form a host protocol operation accepts
// and the plugin hook that implements it.
type ProtocolMode struct {
Name string
Hook string
}
type BodyKind string
const (
BodyNone BodyKind = "none"
BodyJSON BodyKind = "json"
BodyForm BodyKind = "form"
BodyMultipart BodyKind = "multipart"
)
type HostProtocolOperation struct {
Name string
Methods []string
Path string
BodyKinds []BodyKind
ModelField string
RequiredProtocolMembers []string
Modes []ProtocolMode
RequiredDriverHooks []string
}
type HostProtocolDefinition struct {
Name string
Operations []HostProtocolOperation
}
var hostProtocols = []HostProtocolDefinition{
{Name: "openai_responses", Operations: []HostProtocolOperation{
{Name: "create", Methods: []string{http.MethodPost}, Path: "/v1/responses", BodyKinds: []BodyKind{BodyJSON}, ModelField: "model", RequiredProtocolMembers: []string{"decodeRequest"}, Modes: []ProtocolMode{{Name: "stream", Hook: "renderEvents"}, {Name: "sync", Hook: "renderFinal"}, {Name: "background", Hook: "renderFinal"}}},
{Name: "retrieve", Methods: []string{http.MethodGet}, Path: "/v1/responses/:response_id", BodyKinds: []BodyKind{BodyNone}},
}},
{Name: "openai_video", Operations: []HostProtocolOperation{
{Name: "create", Methods: []string{http.MethodPost}, Path: "/v1/videos", BodyKinds: []BodyKind{BodyJSON, BodyMultipart}, ModelField: "model", RequiredProtocolMembers: []string{"decodeRequest"}},
{Name: "retrieve", Methods: []string{http.MethodGet}, Path: "/v1/videos/:task_id", BodyKinds: []BodyKind{BodyNone}, RequiredProtocolMembers: []string{"render"}},
{Name: "content", Methods: []string{http.MethodGet, http.MethodHead}, Path: "/v1/videos/:task_id/content", BodyKinds: []BodyKind{BodyNone}, RequiredDriverHooks: []string{"listArtifacts", "buildContentRequest"}},
}},
// The OpenAI Images API is synchronous: both operations create a task and
// the host answers with the rendered image response once the task is
// terminal, so there is no retrieve operation and no request modes.
{Name: ProtocolOpenAIImage, Operations: []HostProtocolOperation{
{Name: "generate", Methods: []string{http.MethodPost}, Path: "/v1/images/generations", BodyKinds: []BodyKind{BodyJSON}, ModelField: "model", RequiredProtocolMembers: []string{"decodeRequest", "render"}},
{Name: "edit", Methods: []string{http.MethodPost}, Path: "/v1/images/edits", BodyKinds: []BodyKind{BodyJSON, BodyMultipart}, ModelField: "model", RequiredProtocolMembers: []string{"decodeRequest", "render"}},
}},
}
// ProtocolOpenAIImage is the host protocol that serves the OpenAI Images API
// (`POST /v1/images/generations` and `POST /v1/images/edits`) from a plugin.
const ProtocolOpenAIImage = "openai_image"
func HostProtocol(name string) (HostProtocolDefinition, bool) {
for _, definition := range hostProtocols {
if definition.Name == name {
return definition, true
}
}
return HostProtocolDefinition{}, false
}
func HostProtocols() []HostProtocolDefinition {
definitions := make([]HostProtocolDefinition, len(hostProtocols))
for index, definition := range hostProtocols {
definitions[index] = definition
definitions[index].Operations = append([]HostProtocolOperation(nil), definition.Operations...)
for operationIndex := range definitions[index].Operations {
operation := &definitions[index].Operations[operationIndex]
operation.Methods = append([]string(nil), operation.Methods...)
operation.BodyKinds = append([]BodyKind(nil), operation.BodyKinds...)
operation.RequiredProtocolMembers = append([]string(nil), operation.RequiredProtocolMembers...)
operation.Modes = append([]ProtocolMode(nil), operation.Modes...)
operation.RequiredDriverHooks = append([]string(nil), operation.RequiredDriverHooks...)
}
}
return definitions
}
// DefinedModes returns each distinct mode on the protocol in host-table order.
func (d HostProtocolDefinition) DefinedModes() []ProtocolMode {
seen := make(map[string]struct{})
modes := make([]ProtocolMode, 0)
for _, operation := range d.Operations {
for _, mode := range operation.Modes {
if _, exists := seen[mode.Name]; exists {
continue
}
seen[mode.Name] = struct{}{}
modes = append(modes, mode)
}
}
return modes
}
func orderProtocolSupports(protocol string, supports []string) []string {
if len(supports) == 0 {
return supports
}
definition, ok := HostProtocol(protocol)
if !ok {
return supports
}
rank := make(map[string]int)
for index, mode := range definition.DefinedModes() {
rank[mode.Name] = index
}
ordered := append([]string(nil), supports...)
slices.SortStableFunc(ordered, func(left, right string) int {
leftRank, leftKnown := rank[left]
rightRank, rightKnown := rank[right]
switch {
case leftKnown && rightKnown:
if leftRank < rightRank {
return -1
}
if leftRank > rightRank {
return 1
}
return 0
case leftKnown:
return -1
case rightKnown:
return 1
default:
return 0
}
})
return ordered
}
func LookupHostProtocolOperation(method, path string) (string, HostProtocolOperation, bool) {
method = strings.ToUpper(strings.TrimSpace(method))
for _, definition := range hostProtocols {
for _, operation := range definition.Operations {
if operation.Path != path || operation.ModelField == "" {
continue
}
if slices.Contains(operation.Methods, method) {
return definition.Name, operation, true
}
}
}
return "", HostProtocolOperation{}, false
}
// RouteBinding is one address a plugin serves. Besides each declared route the
// host registers its copy under /{key} (Pinned), which always reaches this
// plugin. A declared route whose first segment is the key, or a proper prefix
// of it (/ali for alibaba, /suno for sunoapi), already does (OwnPrefix) and
// gets no copy.
type RouteBinding struct {
Plugin *LoadedPlugin
Route Route
Pinned bool
OwnPrefix bool
}
// FileReference returns the opaque ref of the index-th uploaded file in a
// multipart field. The first file keeps the historical `request_file:<field>`
// spelling; later files in the same repeated field (`image[]`, `image[]`)
// append `#<index>` so a plugin can address each of them.
func FileReference(field string, index int) string {
if index <= 0 {
return "request_file:" + field
}
return "request_file:" + field + "#" + strconv.Itoa(index)
}
// ParseFileReference resolves a ref produced by FileReference back to the
// multipart field and the zero-based file index within that field.
func ParseFileReference(ref string) (field string, index int, ok bool) {
rest, found := strings.CutPrefix(ref, "request_file:")
if !found || rest == "" {
return "", 0, false
}
field, suffix, hasIndex := strings.Cut(rest, "#")
if field == "" {
return "", 0, false
}
if !hasIndex {
return field, 0, true
}
parsed, err := strconv.Atoi(suffix)
if err != nil || parsed < 0 || strconv.Itoa(parsed) != suffix {
return "", 0, false
}
return field, parsed, true
}
// RouteRequestContext is the canonical request view exposed to declarative
// routing hooks. RequestBody contains decoded JSON or multipart text fields;
// raw binary and multipart file bytes remain host-owned.
type RouteRequestContext struct {
Path string `json:"path"`
Method string `json:"method"`
Params map[string]string `json:"params"`
Query map[string][]string `json:"query"`
Body any `json:"body"`
// Headers is the client's request headers without gateway credentials,
// which hooks read as requestHeaders.
Headers map[string]string `json:"-"`
Files []map[string]any `json:"-"`
RequestBody any `json:"-"`
// BodyText is the JSON body as the client sent it, which JSValueFor
// gives to plugins that preserve JSON order; Body stays the Go value the
// host reads. Body storage never changes these bytes, which the engine
// parses in place.
BodyText json.RawMessage `json:"-"`
}
// JSValue shares the request with hooks without copying it: the engine never
// writes JavaScript changes back into Go values, so the request must only stay
// unchanged while a hook runs. Missing params, query and headers still reach
// hooks as empty objects rather than null.
func (r RouteRequestContext) JSValue() map[string]any {
params, query, headers := r.Params, r.Query, r.Headers
if params == nil {
params = map[string]string{}
}
if query == nil {
query = map[string][]string{}
}
if headers == nil {
headers = map[string]string{}
}
return map[string]any{
"path": r.Path,
"method": r.Method,
"params": params,
"query": query,
"requestHeaders": headers,
"body": r.Body,
}
}
// JSValueFor is JSValue for the decode hooks of the plugin meta describes. A
// plugin that preserves JSON order receives a JSON body as its text, which the
// engine parses in place, members in the client's order: a decoder reads the
// body, so it is parsed for every call.
func (r RouteRequestContext) JSValueFor(meta Meta) map[string]any {
value := r.JSValue()
if len(r.BodyText) > 0 && meta.PreservesJSONOrder() {
value["body"] = map[string]any{"kind": string(BodyJSON), "value": RawJSON(r.BodyText)}
}
return value
}
type ProtocolRequestContext struct {
RouteRequestContext
Protocol string `json:"protocol"`
Operation string `json:"operation"`
Model string `json:"model"`
// UpstreamModel is the declared machine identity when Model is a
// channel-mapping alias; empty otherwise. Decode hooks that key rate
// tables or request shaping by model must use it over Model.
UpstreamModel string `json:"upstreamModel,omitempty"`
Stream bool `json:"stream"`
}
func (p ProtocolRequestContext) JSValue() map[string]any {
return p.withProtocol(p.RouteRequestContext.JSValue())
}
// JSValueFor is RouteRequestContext.JSValueFor with the protocol fields.
func (p ProtocolRequestContext) JSValueFor(meta Meta) map[string]any {
return p.withProtocol(p.RouteRequestContext.JSValueFor(meta))
}
func (p ProtocolRequestContext) withProtocol(value map[string]any) map[string]any {
value["protocol"] = p.Protocol
value["operation"] = p.Operation
value["model"] = p.Model
if p.UpstreamModel != "" {
value["upstreamModel"] = p.UpstreamModel
}
value["stream"] = p.Stream
return value
}
// SupportsHostProtocol reports whether the current host release has a
// concrete wire/state machine for an otherwise valid manifest endpoint.
func SupportsHostProtocol(protocol string) bool { _, ok := HostProtocol(protocol); return ok }
var (
routeMethodPattern = regexp.MustCompile(`^(GET|POST|PUT|PATCH|DELETE)$`)
pathNamePattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
staticSegment = regexp.MustCompile(`^[A-Za-z0-9._~-]+$`)
memberNamePattern = regexp.MustCompile(`^[A-Za-z_$][A-Za-z0-9_$]*$`)
)
// NormalizeRouteMethod returns the canonical spelling of a plugin route
// method, rejecting methods routes may not use.
func NormalizeRouteMethod(method string) (string, error) {
method = strings.ToUpper(strings.TrimSpace(method))
if !routeMethodPattern.MatchString(method) {
return "", fmt.Errorf("plugin route method %q is not supported", method)
}
return method, nil
}
// NormalizeRoutePath validates the canonical path syntax used by plugin route
// declarations. A trailing slash is allowed and remains significant.
func NormalizeRoutePath(routePath string) (string, error) {
if routePath == "" || routePath[0] != '/' {
return "", fmt.Errorf("plugin route path must start with /")
}
if routePath == "/" {
return "", fmt.Errorf("plugin route path / is reserved")
}
if strings.ContainsAny(routePath, "?#%") {
return "", fmt.Errorf("plugin route path %q must not contain a query, fragment, or percent-encoding", routePath)
}
if strings.Contains(routePath, "//") {
return "", fmt.Errorf("plugin route path %q must not contain empty segments", routePath)
}
segments := strings.Split(strings.TrimPrefix(routePath, "/"), "/")
seenNames := make(map[string]struct{})
for index, segment := range segments {
if segment == "" && index == len(segments)-1 {
continue
}
if segment == "." || segment == ".." {
return "", fmt.Errorf("plugin route path %q must not contain dot segments", routePath)
}
if after, ok := strings.CutPrefix(segment, ":"); ok {
name := after
if !pathNamePattern.MatchString(name) {
return "", fmt.Errorf("plugin route path %q has invalid parameter %q", routePath, segment)
}
if _, exists := seenNames[name]; exists {
return "", fmt.Errorf("plugin route path %q repeats parameter %q", routePath, name)
}
seenNames[name] = struct{}{}
continue
}
if after, ok := strings.CutPrefix(segment, "*"); ok {
name := after
if index != len(segments)-1 || !pathNamePattern.MatchString(name) {
return "", fmt.Errorf("plugin route path %q has an invalid catch-all segment", routePath)
}
if _, exists := seenNames[name]; exists {
return "", fmt.Errorf("plugin route path %q repeats parameter %q", routePath, name)
}
seenNames[name] = struct{}{}
continue
}
if !staticSegment.MatchString(segment) {
return "", fmt.Errorf("plugin route path %q has invalid segment %q", routePath, segment)
}
}
return routePath, nil
}
// RoutePathShape is a route path with every parameter name left out (":"
// for a parameter, "*" for a catch-all): two routes of one method and shape
// match the same requests.
func RoutePathShape(routePath string) (string, error) {
normalized, err := NormalizeRoutePath(routePath)
if err != nil {
return "", err
}
segments := strings.Split(strings.TrimPrefix(normalized, "/"), "/")
for index, segment := range segments {
if strings.HasPrefix(segment, ":") {
segments[index] = ":"
} else if strings.HasPrefix(segment, "*") {
segments[index] = "*"
}
}
return "/" + strings.Join(segments, "/"), nil
}
func intersectingReservedNamespace(routePath string) (string, bool) {
for _, namespace := range hostConfig().ReservedRouteNamespaces {
if routePatternIntersectsNamespace(routePath, namespace) {
return namespace, true
}
}
return "", false
}
func routePatternIntersectsNamespace(routePath, namespace string) bool {
routeSegments := strings.Split(strings.Trim(strings.TrimPrefix(routePath, "/"), "/"), "/")
namespaceSegments := strings.Split(strings.TrimPrefix(namespace, "/"), "/")
for index, namespaceSegment := range namespaceSegments {
if index >= len(routeSegments) {
return false
}
routeSegment := routeSegments[index]
if strings.HasPrefix(routeSegment, "*") {
return true
}
if !strings.HasPrefix(routeSegment, ":") && routeSegment != namespaceSegment {
return false
}
}
return true
}
func validateRoute(route *Route) error {
if route.Method != strings.ToUpper(strings.TrimSpace(route.Method)) {
return fmt.Errorf("plugin route method %q must use canonical uppercase spelling", route.Method)
}
method, err := NormalizeRouteMethod(route.Method)
if err != nil {
return err
}
route.Method = method
route.Path, err = NormalizeRoutePath(route.Path)
if err != nil {
return err
}
if namespace, reserved := intersectingReservedNamespace(route.Path); reserved {
return fmt.Errorf("plugin route path %q intersects reserved namespace %s", route.Path, namespace)
}
switch route.Type {
case RouteTypeSubmit:
if route.Decode == "" || route.Render == "" || route.TaskIDParam != "" {
return fmt.Errorf("submit route %s %s must declare decode and render and must not declare taskIdParam", route.Method, route.Path)
}
case RouteTypeQuery:
if route.Decode != "" || strings.TrimSpace(route.Render) == "" {
return fmt.Errorf("query route %s %s must declare render and must not declare decode", route.Method, route.Path)
}
if route.Action != "" {
return fmt.Errorf("query route %s %s must not declare action", route.Method, route.Path)
}
if route.RetainResult != nil {
return fmt.Errorf("query route %s %s must not declare retainResult", route.Method, route.Path)
}
if route.TaskIDParam == "" {
route.TaskIDParam = "task_id"
}
if !pathNamePattern.MatchString(route.TaskIDParam) {
return fmt.Errorf("query route %s %s has invalid taskIdParam %q", route.Method, route.Path, route.TaskIDParam)
}
case RouteTypeDynamic:
if route.Decode == "" || route.Render == "" || route.TaskIDParam != "" {
return fmt.Errorf("dynamic route %s %s must declare decode and render and must not declare taskIdParam", route.Method, route.Path)
}
default:
return fmt.Errorf("plugin route %s %s has unsupported type %q", route.Method, route.Path, route.Type)
}
if route.Decode != "" && !memberNamePattern.MatchString(route.Decode) {
return fmt.Errorf("plugin route %s %s has invalid decode %q", route.Method, route.Path, route.Decode)
}
if route.Render != "" && !memberNamePattern.MatchString(route.Render) {
return fmt.Errorf("plugin route %s %s has invalid render %q", route.Method, route.Path, route.Render)
}
if strings.TrimSpace(route.Action) != route.Action {
return fmt.Errorf("plugin route %s %s action must not have surrounding whitespace", route.Method, route.Path)
}
if len(route.Models) > 0 {
if route.Type == RouteTypeQuery {
return fmt.Errorf("query route %s %s must not declare models", route.Method, route.Path)
}
if err := validateModelScope(route.Models, fmt.Sprintf("route %s %s", route.Method, route.Path)); err != nil {
return err
}
}
return nil
}
// validateModelScope enforces the shared rules for route.models and
// per-protocol models entries: non-empty canonical names, no duplicates.
func validateModelScope(models []string, subject string) error {
seen := make(map[string]struct{}, len(models))
for _, model := range models {
if strings.TrimSpace(model) == "" || strings.TrimSpace(model) != model {
return fmt.Errorf("plugin %s models must contain non-empty canonical names", subject)
}
folded := asciiFold(model)
if _, duplicate := seen[folded]; duplicate {
return fmt.Errorf("plugin %s models must be unique case-insensitively", subject)
}
seen[folded] = struct{}{}
}
return nil
}
func pathHasParameter(routePath, name string) bool {
return slices.Contains(strings.Split(routePath, "/"), ":"+name)
}
// TaskIDInQuery reports whether a query route reads its task id from the
// query string, as the MiniMax v1 query does (?task_id=): the route's path
// has no parameter named taskIdParam.
func (r Route) TaskIDInQuery() bool {
return r.Type == RouteTypeQuery && !pathHasParameter(r.Path, r.TaskIDParam)
}
// routeHasOwnPrefix reports whether a declared route already lives under the
// plugin's own address: its first segment is the key or a proper prefix of it.
func routeHasOwnPrefix(key, routePath string) bool {
first, _, _ := strings.Cut(strings.TrimPrefix(routePath, "/"), "/")
return first != "" && strings.HasPrefix(key, first)
}
// PluginRouteBindings returns the addresses plugin serves: each declared route
// and, unless the route lives under the plugin's own prefix, its /{key} copy.
// A plugin that declares the copy's address itself (TypeSafe 1.2.0 declares
// /v1/systemone and /typesafe/v1/systemone) serves it by that declaration.
func PluginRouteBindings(plugin *LoadedPlugin) []RouteBinding {
key := plugin.Meta.Key
declared := make(map[string]struct{}, len(plugin.Meta.Routes))
for _, route := range plugin.Meta.Routes {
// Declared paths were validated at load.
shape, _ := RoutePathShape(route.Path)
declared[route.Method+" "+shape] = struct{}{}
}
bindings := make([]RouteBinding, 0, 2*len(plugin.Meta.Routes))
for _, route := range plugin.Meta.Routes {
if routeHasOwnPrefix(key, route.Path) {
bindings = append(bindings, RouteBinding{Plugin: plugin, Route: route, OwnPrefix: true})
continue
}
bindings = append(bindings, RouteBinding{Plugin: plugin, Route: route})
pinned := route
pinned.Path = "/" + key + route.Path
shape, _ := RoutePathShape(pinned.Path)
if _, exists := declared[route.Method+" "+shape]; !exists {
bindings = append(bindings, RouteBinding{Plugin: plugin, Route: pinned, Pinned: true})
}
}
return bindings
}
func ResolveRouteAction(route Route, resolvedAction string) string {
if strings.TrimSpace(resolvedAction) != "" {
return resolvedAction
}
return route.Action
}
+639
View File
@@ -0,0 +1,639 @@
package pluginkit
import (
"context"
"fmt"
"net/http"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestSupportsRegisteredHostProtocols(t *testing.T) {
assert.True(t, SupportsHostProtocol("openai_responses"))
assert.True(t, SupportsHostProtocol("openai_video"))
assert.True(t, SupportsHostProtocol(ProtocolOpenAIImage))
assert.False(t, SupportsHostProtocol("plugin_owned_wire"))
}
func TestLookupHostProtocolOperationExcludesRetrieveWithoutModelField(t *testing.T) {
_, _, ok := LookupHostProtocolOperation(http.MethodGet, "/v1/responses/:response_id")
assert.False(t, ok)
_, _, ok = LookupHostProtocolOperation(http.MethodPost, "/v1/responses")
assert.True(t, ok)
for _, path := range []string{"/v1/images/generations", "/v1/images/edits"} {
protocol, operation, found := LookupHostProtocolOperation(http.MethodPost, path)
require.True(t, found, path)
assert.Equal(t, ProtocolOpenAIImage, protocol)
assert.Equal(t, "model", operation.ModelField)
assert.Empty(t, operation.Modes, "the synchronous image protocol has no request modes")
}
}
func TestFileReferenceRoundTripAddressesRepeatedFieldFiles(t *testing.T) {
assert.Equal(t, "request_file:image[]", FileReference("image[]", 0))
assert.Equal(t, "request_file:image[]#2", FileReference("image[]", 2))
for _, tc := range []struct {
ref string
field string
index int
ok bool
}{
{"request_file:input_reference", "input_reference", 0, true},
{"request_file:image[]#1", "image[]", 1, true},
{"request_file:image[]#01", "", 0, false},
{"request_file:image[]#-1", "", 0, false},
{"request_file:#1", "", 0, false},
{"request_file:", "", 0, false},
{"image", "", 0, false},
} {
field, index, ok := ParseFileReference(tc.ref)
assert.Equal(t, tc.ok, ok, tc.ref)
assert.Equal(t, tc.field, field, tc.ref)
assert.Equal(t, tc.index, index, tc.ref)
}
}
func TestProtocolClaimDecodeAndValidation(t *testing.T) {
tests := []struct {
name string
models string
metaFields string
exports string
errContains string
wantProtocols []ProtocolClaim
}{
{
name: "string and object entries mix",
models: `["gpt-5.5", "gpt-5.6"]`,
metaFields: `protocols: [{name: "openai_responses", supports: ["stream", "sync", "background"]}, {name: "openai_video", models: ["gpt-5.5"]}],`,
exports: `export const protocols = {
openai_responses: {
decodeRequest: function(ctx) { return ctx; },
renderEvents: function() { return {events: [], state: null, done: false}; },
renderFinal: function(ctx, task) { return task; }
},
openai_video: {
decodeRequest: function(ctx) { return ctx; },
render: function(ctx, task) { return task; }
}
};
export function listArtifacts() { return []; }
export function buildContentRequest() { return {}; }`,
wantProtocols: []ProtocolClaim{
{Name: "openai_responses", Supports: []string{"stream", "sync", "background"}, objectForm: true},
{Name: "openai_video", Models: []string{"gpt-5.5"}, objectForm: true},
},
},
{
name: "absent protocols is fine",
models: `["gpt-5.5"]`,
wantProtocols: []ProtocolClaim{},
},
{
name: "object with unknown field",
models: `["gpt-5.5"]`,
metaFields: `protocols: [{name: "openai_responses", models: ["gpt-5.5"], extra: true}],`,
errContains: `unknown field "extra"`,
},
{
name: "model outside meta models",
models: `["gpt-5.5"]`,
metaFields: `protocols: [{name: "openai_responses", models: ["gpt-9.9"], supports: ["stream", "sync", "background"]}],`,
errContains: "is not declared in plugin meta models",
},
{
name: "duplicate models in claim",
models: `["gpt-5.5"]`,
metaFields: `protocols: [{name: "openai_responses", models: ["gpt-5.5", "gpt-5.5"], supports: ["stream", "sync", "background"]}],`,
errContains: "models must be unique",
},
{
name: "blank model in claim",
models: `["gpt-5.5"]`,
metaFields: `protocols: [{name: "openai_responses", models: [" "], supports: ["stream", "sync", "background"]}],`,
errContains: "non-empty canonical names",
},
{
name: "empty models rejected",
models: `["gpt-5.5"]`,
metaFields: `protocols: [{name: "openai_responses", models: []}],`,
errContains: "models must contain at least one model",
},
{
name: "explicit null protocols",
models: `["gpt-5.5"]`,
metaFields: `protocols: null,`,
errContains: "must be an array",
},
}
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
exports := testCase.exports
if exports == "" && testCase.errContains != "" {
exports = routingProtocolExport("openai_responses")
}
plugin, err := CompilePlugin(
routingTestPluginSource("claim-decode", 0, testCase.models, testCase.metaFields, exports),
Options{},
)
if testCase.errContains != "" {
require.ErrorContains(t, err, testCase.errContains)
return
}
require.NoError(t, err)
require.Equal(t, testCase.wantProtocols, plugin.Meta.Protocols)
})
}
}
func TestRouteModelsDecodeAndValidation(t *testing.T) {
routeExports := `export const native = {
decodeJob: function(ctx) { return {kind: "submit", model: "gpt-5.5", requestBody: ctx.body.value}; },
jobCreated: function(ctx, task) { return task; },
jobStatus: function(ctx, task) { return task; }
};`
tests := []struct {
name string
models string
metaFields string
errContains string
}{
{
name: "submit route with models",
models: `["gpt-5.5", "gpt-5.6"]`,
metaFields: `routes: [{method: "POST", path: "/v1/batch", type: "submit", models: ["gpt-5.5"], decode: "decodeJob", render: "jobCreated"}],`,
},
{
name: "query route rejects models",
models: `["gpt-5.5"]`,
metaFields: `routes: [{method: "GET", path: "/v1/batch/:task_id", type: "query", models: ["gpt-5.5"], render: "jobStatus"}],`,
errContains: "must not declare models",
},
{
name: "model outside meta models",
models: `["gpt-5.5"]`,
metaFields: `routes: [{method: "POST", path: "/v1/batch", type: "submit", models: ["gpt-9.9"], decode: "decodeJob", render: "jobCreated"}],`,
errContains: "is not declared in plugin meta models",
},
{
name: "duplicate models",
models: `["gpt-5.5"]`,
metaFields: `routes: [{method: "POST", path: "/v1/batch", type: "submit", models: ["gpt-5.5", "gpt-5.5"], decode: "decodeJob", render: "jobCreated"}],`,
errContains: "models must be unique",
},
{
name: "blank model entry",
models: `["gpt-5.5"]`,
metaFields: `routes: [{method: "POST", path: "/v1/batch", type: "submit", models: [" "], decode: "decodeJob", render: "jobCreated"}],`,
errContains: "non-empty canonical names",
},
{
name: "empty models rejected",
models: `["gpt-5.5"]`,
metaFields: `routes: [{method: "POST", path: "/v1/batch", type: "submit", models: [], decode: "decodeJob", render: "jobCreated"}],`,
errContains: "models must contain at least one model",
},
{
name: "query route empty models rejected",
models: `["gpt-5.5"]`,
metaFields: `routes: [{method: "GET", path: "/v1/batch/:task_id", type: "query", models: [], render: "jobStatus"}],`,
errContains: "models must contain at least one model",
},
}
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
plugin, err := CompilePlugin(
routingTestPluginSource("route-models", 0, testCase.models, testCase.metaFields, routeExports),
Options{},
)
if testCase.errContains != "" {
require.ErrorContains(t, err, testCase.errContains)
return
}
require.NoError(t, err)
require.Len(t, plugin.Meta.Routes, 1)
assert.Equal(t, []string{"gpt-5.5"}, plugin.Meta.Routes[0].Models)
})
}
}
func TestRouteRetainResultDecodeAndValidation(t *testing.T) {
routeExports := `export const native = {
decodeJob: function(ctx) { return {kind: "submit", model: "gpt-5.5", requestBody: ctx.body.value}; },
jobCreated: function(ctx, task) { return task; },
jobStatus: function(ctx, task) { return task; }
};`
falseValue := false
tests := []struct {
name string
metaFields string
want *bool
errContains string
}{
{
name: "undeclared route retains",
metaFields: `routes: [{method: "POST", path: "/v1/batch", type: "submit", decode: "decodeJob", render: "jobCreated"}],`,
},
{
name: "submit route declines retention",
metaFields: `routes: [{method: "POST", path: "/v1/batch", type: "submit", decode: "decodeJob", render: "jobCreated", retainResult: false}],`,
want: &falseValue,
},
{
name: "query route rejects retainResult",
metaFields: `routes: [{method: "GET", path: "/v1/batch/:task_id", type: "query", render: "jobStatus", retainResult: true}],`,
errContains: "must not declare retainResult",
},
{
name: "non-boolean value",
metaFields: `routes: [{method: "POST", path: "/v1/batch", type: "submit", decode: "decodeJob", render: "jobCreated", retainResult: "no"}],`,
errContains: "retainResult must be a boolean",
},
}
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
plugin, err := CompilePlugin(
routingTestPluginSource("route-retain", 0, `["gpt-5.5"]`, testCase.metaFields, routeExports),
Options{},
)
if testCase.errContains != "" {
require.ErrorContains(t, err, testCase.errContains)
return
}
require.NoError(t, err)
require.Len(t, plugin.Meta.Routes, 1)
assert.Equal(t, testCase.want, plugin.Meta.Routes[0].RetainResult)
})
}
}
func TestRouteRequestContextKeepsFormAndMultipartValuesAcrossDecoderWrites(t *testing.T) {
plugin, err := CompilePlugin(routingTestPluginSource("route-request-writes", 0, `["gpt-5.5"]`, "", `
export function decodeJob(ctx) {
const seen = {
prompt: ctx.body.fields.prompt[0],
filename: ctx.body.files[0].filename,
params: Object.keys(ctx.params).length,
query: Object.keys(ctx.query).length
};
ctx.body.fields.prompt[0] = "mutated";
ctx.body.files[0].filename = "mutated.png";
return seen;
}`), Options{})
require.NoError(t, err)
fields := map[string][]string{"prompt": {"original"}}
files := []map[string]any{{"ref": "request_file:image", "filename": "safe.png"}}
request := RouteRequestContext{Body: map[string]any{"kind": "multipart", "fields": fields, "files": files}}
for range 2 {
seen, err := plugin.Engine.Call(context.Background(), "decodeJob", request.JSValue())
require.NoError(t, err)
assert.Equal(t, map[string]any{"prompt": "original", "filename": "safe.png", "params": int64(0), "query": int64(0)}, seen)
}
assert.Equal(t, "original", fields["prompt"][0])
assert.Equal(t, "safe.png", files[0]["filename"])
}
// configureTestHost sets the host for one test and restores the previous one.
func configureTestHost(t *testing.T, host Host) {
t.Helper()
previous := *hostConfig()
Configure(host)
t.Cleanup(func() { Configure(previous) })
}
func TestDeclarativeRouteValidationProtectsNamespacesAndCanonicalSyntax(t *testing.T) {
configureTestHost(t, Host{
ReservedRouteNamespaces: []string{"/assets", "/v1/tasks", "/console", "/request-processing", "/security"},
ReservedKeys: []string{"api"},
})
tests := []struct {
name string
route Route
expectedError string
}{
{
name: "static assets",
route: Route{Method: "GET", Path: "/assets/x", Type: RouteTypeQuery, Render: "native"},
expectedError: "reserved namespace /assets",
},
{
name: "generic task management",
route: Route{Method: "GET", Path: "/v1/tasks/:task_id", Type: RouteTypeQuery, Render: "native"},
expectedError: "reserved namespace /v1/tasks",
},
{
name: "SPA root",
route: Route{Method: "POST", Path: "/console/jobs", Type: RouteTypeSubmit},
expectedError: "reserved namespace /console",
},
{
name: "request processing page",
route: Route{Method: "GET", Path: "/request-processing", Type: RouteTypeQuery, Render: "native"},
expectedError: "reserved namespace /request-processing",
},
{
name: "security page",
route: Route{Method: "GET", Path: "/security/:section", Type: RouteTypeQuery, Render: "native"},
expectedError: "reserved namespace /security",
},
{
name: "dynamic root can claim reserved subtree",
route: Route{Method: "POST", Path: "/:root/jobs", Type: RouteTypeSubmit},
expectedError: "intersects reserved namespace",
},
{
name: "dynamic v1 namespace can claim task management",
route: Route{Method: "POST", Path: "/v1/:namespace", Type: RouteTypeSubmit},
expectedError: "reserved namespace /v1/tasks",
},
{
name: "root catch-all can claim reserved subtree",
route: Route{Method: "POST", Path: "/*rest", Type: RouteTypeSubmit},
expectedError: "intersects reserved namespace",
},
{
name: "repeated slash",
route: Route{Method: "POST", Path: "/vendor//jobs", Type: RouteTypeSubmit},
expectedError: "empty segments",
},
{
name: "noncanonical method",
route: Route{Method: " post ", Path: "/vendor/jobs", Type: RouteTypeSubmit},
expectedError: "canonical uppercase",
},
{
name: "non-terminal catch-all",
route: Route{Method: "POST", Path: "/vendor/*rest/jobs", Type: RouteTypeSubmit},
expectedError: "invalid catch-all",
},
{
name: "query declares decoder",
route: Route{Method: "GET", Path: "/vendor/jobs/:task_id", Type: RouteTypeQuery, Decode: "decode", Render: "show"},
expectedError: "must not declare decode",
},
{
name: "submit missing presenter",
route: Route{Method: "POST", Path: "/vendor/jobs", Type: RouteTypeSubmit, Decode: "decode"},
expectedError: "must declare decode and render",
},
{
name: "dynamic missing decoder",
route: Route{Method: "POST", Path: "/vendor/query", Type: RouteTypeDynamic, Render: "show"},
expectedError: "must declare decode and render",
},
{
name: "dynamic missing presenter",
route: Route{Method: "POST", Path: "/vendor/query", Type: RouteTypeDynamic, Decode: "decode"},
expectedError: "must declare decode and render",
},
{
name: "query declares action",
route: Route{Method: "GET", Path: "/vendor/jobs/:task_id", Type: RouteTypeQuery, Render: "show", Action: "retrieve"},
expectedError: "must not declare action",
},
{
name: "submit declares task id parameter",
route: Route{Method: "POST", Path: "/vendor/jobs", Type: RouteTypeSubmit, Decode: "decode", Render: "created", TaskIDParam: "task_id"},
expectedError: "must not declare taskIdParam",
},
{
name: "dynamic declares task id parameter",
route: Route{Method: "POST", Path: "/vendor/query", Type: RouteTypeDynamic, Decode: "decode", Render: "show", TaskIDParam: "task_id"},
expectedError: "must not declare taskIdParam",
},
}
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
meta := Meta{APIVersion: 1, Key: "validation", Name: "Validation", Version: "1.0.0", Author: AuthorMeta{Name: "Test"}, Models: []string{"model"}, FetchMode: "per_task", Routes: []Route{testCase.route}}
require.ErrorContains(t, ValidateV1Meta(meta), testCase.expectedError)
})
}
}
func TestRemovedEndpointsAndProtocolHooksAreValidatedAtCompileTime(t *testing.T) {
removed := routingTestPluginSource(
"removed-endpoint",
0,
`["model"]`,
`endpoints: [{method: "POST", path: "/v1/chat/completions", protocol: "chat"}],`,
routingProtocolExport("chat"),
)
_, err := CompilePlugin(removed, Options{})
require.ErrorContains(t, err, "endpoints is no longer supported")
unknown := routingTestPluginSource("unknown-protocol", 0, `["model"]`, `protocols: ["chat"],`, ``)
_, err = CompilePlugin(unknown, Options{})
require.ErrorContains(t, err, `protocol "chat" is unknown`)
missingHook := routingTestPluginSource(
"bad-protocol",
0,
`["model"]`,
`protocols: ["openai_responses"],`,
`export const protocols = {openai_responses: {
decodeRequest: function() { return {}; },
renderEvents: function() { return {events: [], done: false}; }
}};`,
)
_, err = CompilePlugin(missingHook, Options{})
require.ErrorContains(t, err, `plugin bad-protocol protocol "openai_responses" must declare supports; replace the bare string with {name: "openai_responses", supports: [...]} choosing from "stream", "sync", "background"`)
for _, removedExport := range []string{"renderers", "renderError", "resolveRequest"} {
t.Run("removed export "+removedExport, func(t *testing.T) {
source := routingTestPluginSource("removed-export", 0, `["model"]`, "", `export const `+removedExport+` = {};`)
_, compileErr := CompilePlugin(source, Options{})
require.ErrorContains(t, compileErr, `export "`+removedExport+`" is no longer supported`)
})
}
t.Run("removed route renderer", func(t *testing.T) {
source := routingTestPluginSource(
"removed-route-renderer", 0, `["model"]`,
`routes: [{method:"GET",path:"/vendor/:task_id",type:"query",render:"show",renderer:"legacy"}],`,
`export const native = {show: function(ctx, task) { return task; }};`,
)
_, compileErr := CompilePlugin(source, Options{})
require.ErrorContains(t, compileErr, "field renderer is no longer supported")
})
}
func TestRegistryRejectsPrototypeInheritedHooks(t *testing.T) {
for _, member := range []string{"constructor", "toString", "__proto__"} {
t.Run("native "+member, func(t *testing.T) {
source := routingTestPluginSource(
"inherited-renderer",
0,
`["model"]`,
fmt.Sprintf(`routes: [{method: "GET", path: "/vendor/jobs/:task_id", type: "query", render: %q}],`, member),
`const nativePrototype = {
constructor: function(task) { return task; },
toString: function(task) { return task; },
["__proto__"]: function(task) { return task; },
};
export const native = Object.create(nativePrototype);`,
)
_, err := CompilePlugin(source, Options{})
require.ErrorContains(t, err, fmt.Sprintf(`references missing native render %q`, member))
})
}
t.Run("protocol object", func(t *testing.T) {
source := routingTestPluginSource(
"inherited-protocol",
0,
`["model"]`,
`protocols: [{name: "openai_responses", supports: ["stream", "sync", "background"]}],`,
`const protocol = {
decodeRequest: function(ctx) { return ctx; },
renderEvents: function() { return {events: [], state: null, done: false}; },
renderFinal: function(ctx, task) { return task; },
};
export const protocols = Object.create({openai_responses: protocol});`,
)
_, err := CompilePlugin(source, Options{})
require.ErrorContains(t, err, `protocol "openai_responses" is missing hook "decodeRequest"`)
})
t.Run("protocol hook", func(t *testing.T) {
source := routingTestPluginSource(
"inherited-protocol-hook",
0,
`["model"]`,
`protocols: [{name: "openai_responses", supports: ["stream", "sync", "background"]}],`,
`const protocolPrototype = {
decodeRequest: function(ctx) { return ctx; },
renderEvents: function() { return {events: [], state: null, done: false}; },
renderFinal: function(ctx, task) { return task; },
};
export const protocols = {openai_responses: Object.create(protocolPrototype)};`,
)
_, err := CompilePlugin(source, Options{})
require.ErrorContains(t, err, `protocol "openai_responses" is missing hook "decodeRequest"`)
})
}
func TestMetaDecoderRejectsLossyOrUnknownRoutingFields(t *testing.T) {
tests := []struct {
name string
metaFields string
expectedError string
}{
{
name: "fractional channel type",
metaFields: `channelTypes: [50.5],`,
expectedError: "channelTypes element 1 must be an integer",
},
{
name: "non-string model",
metaFields: `models: ["model", 2],`,
expectedError: "models must be an array of strings",
},
{
name: "unknown route field",
metaFields: `routes: [{method: "POST", path: "/vendor/jobs", type: "submit", auth: false}],`,
expectedError: `unknown field "auth"`,
},
}
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
source := fmt.Sprintf(`
export const meta = {
apiVersion: 1, key: "strict-meta", name: "Strict", version: "1.0.0",
author: {name: "Test"},
models: ["model"], fetchMode: "per_task", %s
};
export function buildSubmitRequest() { return {}; }
export function parseSubmitResponse() { return {}; }
export function buildQueryRequest() { return {}; }
export function parseTaskResult() { return {}; }
export function resolveRequest() { return {kind: "submit", model: "model"}; }
`, testCase.metaFields)
_, err := CompilePlugin(source, Options{})
require.ErrorContains(t, err, testCase.expectedError)
})
}
}
func TestProtocolHookInspectionIsDeadlineBounded(t *testing.T) {
source := `
export const meta = {
apiVersion: 1, key: "getter-timeout", name: "Getter", version: "1.0.0",
author: {name: "Test"},
models: ["model"], fetchMode: "per_task",
protocols: [{name: "openai_responses", supports: ["stream", "sync", "background"]}],
};
export function buildSubmitRequest() { return {}; }
export function parseSubmitResponse() { return {}; }
export function buildQueryRequest() { return {}; }
export function parseTaskResult() { return {}; }
export const protocols = {
get openai_responses() { while (true) {} }
};
`
_, err := CompilePlugin(source, Options{Timeout: 20 * time.Millisecond})
require.ErrorContains(t, err, "inspection interrupted")
}
func TestReservedNamespaceChecksUseSegmentBoundaries(t *testing.T) {
// The host namespaces the outer router reveals, /api among them, are
// decided at admission, so these routes compile.
for _, routePath := range []string{"/apiary/jobs", "/api/plugin", "/api/:version/jobs", "/api/v3/contents/generations/tasks", "/api/common/v3/submit_task_v2"} {
meta := Meta{
APIVersion: 1,
Key: "apiary",
Name: "Apiary",
Version: "1.0.0",
Author: AuthorMeta{Name: "Test"},
Models: []string{"model"},
FetchMode: "per_task",
Routes: []Route{{Method: "POST", Path: routePath, Type: RouteTypeSubmit, Decode: "decode", Render: "render"}},
}
require.NoError(t, ValidateV1Meta(meta), routePath)
}
}
func TestResolveRouteActionPrefersResolvedAction(t *testing.T) {
route := Route{Action: "manifest-action"}
assert.Equal(t, "hook-action", ResolveRouteAction(route, "hook-action"))
assert.Equal(t, "manifest-action", ResolveRouteAction(route, ""))
}
func routingTestPluginSource(key string, channelType int, models, metaFields, exports string) string {
channelTypesField := ""
if channelType > 0 && channelType != ChannelTypeTaskPlugin {
channelTypesField = fmt.Sprintf("channelTypes: [%d],", channelType)
}
return fmt.Sprintf(`
export const meta = {
apiVersion: 1,
key: %q,
name: %q,
version: "1.0.0",
author: {name: "Test"},
%s
models: %s,
fetchMode: "per_task",
%s
};
export function buildSubmitRequest() { return {}; }
export function parseSubmitResponse() { return {}; }
export function buildQueryRequest() { return {}; }
export function parseTaskResult() { return {}; }
%s
`, key, key, channelTypesField, models, metaFields, exports)
}
func routingProtocolExport(name string) string {
return fmt.Sprintf(`export const protocols = {%s: {
decodeRequest: function(ctx) { return ctx; },
renderEvents: function() { return {events: [], state: null, done: false}; },
renderFinal: function(ctx, task) { return task; }
}};`, name)
}
@@ -1,4 +1,4 @@
package jsplugin
package pluginkit
import (
"encoding/json"
@@ -9,12 +9,11 @@ import (
"unicode/utf8"
"github.com/MoeForge/moego/regexp"
"github.com/QuantumNous/new-api/common"
"github.com/tidwall/gjson"
)
// Limits of meta.samples, part of the published plugin contract
// (docs/plugin-api/v1.md).
// (v1.md).
const (
maxSamples = 8
maxSamplesPerLang = 3
@@ -72,7 +71,7 @@ func decodeSamples(text []byte) ([]Sample, error) {
return nil, fmt.Errorf("%s must be an object", subject)
}
var object map[string]any
if err := common.UnmarshalJsonStr(item.Raw, &object); err != nil {
if err := unmarshalJSONString(item.Raw, &object); err != nil {
return nil, fmt.Errorf("%s must be an object", subject)
}
for member := range object {
+587
View File
@@ -0,0 +1,587 @@
package pluginkit
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"mime/multipart"
"net/http"
"slices"
"strings"
"time"
"github.com/MoeForge/moego/base64"
"github.com/MoeForge/moego/regexp"
)
// MaxSubmitStateBytes bounds the JSON state of a submission stream and the
// result parseSubmitEventDelta accumulates; MaxSubmitControlStateBytes bounds
// the control state parseSubmitEventDelta passes to its next event.
const (
MaxSubmitStateBytes = 1 << 20
MaxSubmitControlStateBytes = 64 << 10
)
// MaxTaskArtifacts is the most artifacts listArtifacts may return.
const MaxTaskArtifacts = 64
var taskArtifactKeyPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$`)
// ErrSubmitClientResponse is the error of a parseSubmitResponse result that
// carries the removed clientResponse member.
var ErrSubmitClientResponse = errors.New("parseSubmitResponse must not return clientResponse")
// RequestDescriptor is the request a request-building hook returns
// (buildSubmitRequest, buildQueryRequest, buildBatchQueryRequest,
// buildContentRequest).
type RequestDescriptor struct {
ResponseType string `json:"responseType"`
URL string `json:"url"`
Method string `json:"method"`
Headers map[string]string `json:"headers"`
Body any `json:"body"`
Credentialless bool `json:"credentialless"`
Action string `json:"action"`
Model string `json:"model"`
RewriteModel string `json:"rewriteModel"`
BodyType string `json:"bodyType"`
Parts []RequestPart `json:"parts"`
// ContentPath and MimeType are read from buildContentRequest only: the
// artifact's bytes are a base64 string at that path of the JSON reply.
ContentPath []any `json:"contentPath"`
MimeType string `json:"mimeType"`
// BodyText is the body as JSON.stringify wrote it, for a plugin that
// preserves JSON order: the upstream gets the members in that order.
BodyText json.RawMessage `json:"-"`
}
// orderedRequestDescriptor is RequestDescriptor as a plugin that preserves
// JSON order returns it: decoded from the JSON.stringify text of the result,
// with the body kept as that text.
type orderedRequestDescriptor struct {
ResponseType string `json:"responseType"`
URL string `json:"url"`
Method string `json:"method"`
Headers map[string]string `json:"headers"`
Body json.RawMessage `json:"body"`
Credentialless bool `json:"credentialless"`
Action string `json:"action"`
Model string `json:"model"`
RewriteModel string `json:"rewriteModel"`
BodyType string `json:"bodyType"`
Parts []RequestPart `json:"parts"`
ContentPath []any `json:"contentPath"`
MimeType string `json:"mimeType"`
}
// RequestPart is one part of a multipart request descriptor.
type RequestPart struct {
Name string `json:"name"`
Value any `json:"value"`
FileRef string `json:"fileRef"`
Filename string `json:"filename"`
}
// CallRequestDescriptor runs a request-building hook. A plugin that preserves
// JSON order has its descriptor decoded from the JSON.stringify text of the
// result, with the body kept as that text (BodyText) for the upstream.
func (p *LoadedPlugin) CallRequestDescriptor(ctx context.Context, hook string, args ...any) (RequestDescriptor, error) {
if !p.Meta.PreservesJSONOrder() {
var descriptor RequestDescriptor
err := p.Engine.CallInto(ctx, &descriptor, hook, args...)
return descriptor, err
}
var ordered orderedRequestDescriptor
if err := p.Engine.CallJSONInto(ctx, &ordered, hook, args...); err != nil {
return RequestDescriptor{}, err
}
descriptor := RequestDescriptor{
ResponseType: ordered.ResponseType, URL: ordered.URL, Method: ordered.Method, Headers: ordered.Headers,
Credentialless: ordered.Credentialless, Action: ordered.Action, Model: ordered.Model,
RewriteModel: ordered.RewriteModel, BodyType: ordered.BodyType, Parts: ordered.Parts,
ContentPath: ordered.ContentPath, MimeType: ordered.MimeType,
}
switch {
case len(ordered.Body) == 0 || string(ordered.Body) == "null":
case ordered.Body[0] == '"':
// A string body is the plugin's own text, sent as it is.
var text string
if err := unmarshalJSON(ordered.Body, &text); err != nil {
return RequestDescriptor{}, err
}
descriptor.Body = text
default:
descriptor.Body, descriptor.BodyText = ordered.Body, ordered.Body
}
return descriptor, nil
}
// TaskResult is the task state parseTaskResult returns, and the immediate
// result of parseSubmitResponse. The token counts are the plugin's numbers,
// unbounded; the host converts them.
type TaskResult struct {
Code int `json:"code"`
TaskID string `json:"taskId"`
Status string `json:"status"`
Progress string `json:"progress"`
Reason string `json:"reason"`
URL string `json:"url"`
RemoteURL string `json:"remoteUrl"`
CompletionTokens float64 `json:"completionTokens"`
TotalTokens float64 `json:"totalTokens"`
// State is the JSON of the returned state; nil when the result has
// none, a null one or one that does not encode.
State json.RawMessage `json:"-"`
}
// SubmitResponse is the upstream reply parseSubmitResponse reads.
type SubmitResponse struct {
StatusCode int
Headers map[string][]string
Body any
}
// SubmitResult is what parseSubmitResponse returns. TaskData is the hook's
// value, which may be a host value.
type SubmitResult struct {
TaskID string
TaskData any
Immediate *TaskResult
// State is the JSON of the returned state; nil when the result has
// none, a null one or one that does not encode.
State json.RawMessage
}
// CallParseSubmitResponse runs parseSubmitResponse with the driver context.
// A result of the wrong shape, without a taskId or with clientResponse
// (ErrSubmitClientResponse) is a *ResultError; other errors are the hook's.
func (p *LoadedPlugin) CallParseSubmitResponse(ctx context.Context, driver map[string]any, response SubmitResponse) (SubmitResult, error) {
value, err := p.Engine.Call(ctx, "parseSubmitResponse", driver, map[string]any{"statusCode": response.StatusCode, "headers": response.Headers, "body": response.Body})
if err != nil {
return SubmitResult{}, err
}
if object, ok := value.(map[string]any); ok {
if _, forbidden := object["clientResponse"]; forbidden {
return SubmitResult{}, &ResultError{err: ErrSubmitClientResponse}
}
}
var parsed struct {
TaskID string `json:"taskId"`
TaskData any `json:"taskData"`
Immediate *TaskResult `json:"immediate"`
}
if err = convertJSON(value, &parsed); err != nil {
return SubmitResult{}, &ResultError{err: err}
}
if strings.TrimSpace(parsed.TaskID) == "" {
return SubmitResult{}, &ResultError{err: fmt.Errorf("plugin returned an empty taskId")}
}
state, _ := returnedState(value)
return SubmitResult{TaskID: parsed.TaskID, TaskData: parsed.TaskData, Immediate: parsed.Immediate, State: state}, nil
}
// HookHTTPResponse is the {status, headers} argument of the parse hooks for
// an upstream reply: the first value of each header.
func HookHTTPResponse(resp *http.Response) map[string]any {
headers := map[string]string{}
status := 0
if resp != nil {
status = resp.StatusCode
for name, values := range resp.Header {
if len(values) > 0 {
headers[name] = values[0]
}
}
}
return map[string]any{"status": status, "headers": headers}
}
// CallParseTaskResult runs parseTaskResult with the task query context, the
// upstream body (parsed JSON, else text) and HookHTTPResponse. A result of
// the wrong shape is a *ResultError; other errors are the hook's.
func (p *LoadedPlugin) CallParseTaskResult(ctx context.Context, query map[string]any, body any, response map[string]any) (TaskResult, error) {
value, err := p.Engine.Call(ctx, "parseTaskResult", query, body, response)
if err != nil {
return TaskResult{}, err
}
var parsed TaskResult
if err = convertJSON(value, &parsed); err != nil {
return TaskResult{}, &ResultError{err: err}
}
parsed.State, _ = returnedState(value)
return parsed, nil
}
// BatchResultItem is one task of a parseBatchResult result. State is the
// hook's value, which may be a host value.
type BatchResultItem struct {
TaskID string `json:"taskId"`
Action string `json:"action"`
Status string `json:"status"`
Progress string `json:"progress"`
Reason string `json:"reason"`
URL string `json:"url"`
SubmitTime int64 `json:"submitTime"`
StartTime int64 `json:"startTime"`
FinishTime int64 `json:"finishTime"`
Data any `json:"data"`
State any `json:"state"`
}
// CallParseBatchResult runs parseBatchResult with the batch query context,
// the upstream body and HookHTTPResponse. A result of the wrong shape is a
// *ResultError; other errors are the hook's.
func (p *LoadedPlugin) CallParseBatchResult(ctx context.Context, batch map[string]any, body any, response map[string]any) ([]BatchResultItem, error) {
var items []BatchResultItem
if err := p.Engine.CallInto(ctx, &items, "parseBatchResult", batch, body, response); err != nil {
return nil, err
}
return items, nil
}
// errUsageNotObject is the error of a usage hook result that is neither an
// object nor null.
var errUsageNotObject = errors.New("plugin usage hook must return an object")
// CallUsage runs a usage hook (extractUsage, extractUsageOnSubmit,
// extractUsageOnComplete) and returns its facts as the plugin reported them:
// nil for a null or undefined result. The host validates and bounds them. A
// result that is not an object is a *ResultError; other errors are the
// hook's.
func (p *LoadedPlugin) CallUsage(ctx context.Context, hook string, args ...any) (map[string]any, error) {
value, err := p.Engine.Call(ctx, hook, args...)
if err != nil {
return nil, err
}
if value == nil {
return nil, nil
}
facts, ok := value.(map[string]any)
if !ok {
return nil, &ResultError{err: errUsageNotObject}
}
return facts, nil
}
// SubmitEvent is one server-sent event of a submission stream.
type SubmitEvent struct {
Event string
ID string
Data string
}
// SubmitEventResult is what parseSubmitEvent or parseSubmitEventDelta
// returns. State is the hook's value, which may be a host value, and
// StateJSON its encoding. Changes is set by parseSubmitEventDelta only.
type SubmitEventResult struct {
State any
StateJSON json.RawMessage
Done bool
Changes any
}
// CallSubmitEvent runs hook, parseSubmitEvent or parseSubmitEventDelta (see
// UsesSubmitEventDelta), on one event with the previous state, and checks
// the result's shape and state size. Errors are those of the hook or of an
// invalid result.
func (p *LoadedPlugin) CallSubmitEvent(ctx context.Context, hook string, driver map[string]any, event SubmitEvent, previous any) (SubmitEventResult, error) {
value, err := p.Engine.Call(ctx, hook, driver, map[string]any{"event": event.Event, "id": event.ID, "data": event.Data}, previous)
if err != nil {
return SubmitEventResult{}, err
}
result, ok := value.(map[string]any)
if !ok {
return SubmitEventResult{}, fmt.Errorf("%s must return an object", hook)
}
state, hasState := result["state"]
done, hasDone := result["done"].(bool)
if !hasState || !hasDone {
return SubmitEventResult{}, fmt.Errorf("%s must return state and a boolean done", hook)
}
encoded, err := marshalJSON(state)
if err != nil {
return SubmitEventResult{}, fmt.Errorf("invalid submit stream state: %w", err)
}
if len(encoded) > MaxSubmitStateBytes {
return SubmitEventResult{}, fmt.Errorf("task submit stream state exceeds size limit")
}
parsed := SubmitEventResult{State: state, StateJSON: encoded, Done: done}
if hook == "parseSubmitEventDelta" {
if len(result) != 3 {
return SubmitEventResult{}, fmt.Errorf("parseSubmitEventDelta must return only changes, state and done")
}
// Control state is separate from the full result and is the only
// snapshot passed back to JS on the next event.
if len(encoded) > MaxSubmitControlStateBytes {
return SubmitEventResult{}, fmt.Errorf("task submit stream control state exceeds size limit")
}
parsed.Changes = result["changes"]
}
return parsed, nil
}
// Artifact is one artifact listArtifacts names.
type Artifact struct {
Key string
Type string
MimeType string
}
// CallListArtifacts runs listArtifacts with the artifact context of a task
// and validates the list. An invalid list is a *ResultError; other errors
// are the hook's.
func (p *LoadedPlugin) CallListArtifacts(ctx context.Context, task map[string]any) ([]Artifact, error) {
value, err := p.Engine.Call(ctx, "listArtifacts", task)
if err != nil {
return nil, err
}
artifacts, err := validateArtifacts(value)
if err != nil {
return nil, &ResultError{err: err}
}
return artifacts, nil
}
func validateArtifacts(value any) ([]Artifact, error) {
encoded, err := marshalJSON(value)
if err != nil {
return nil, fmt.Errorf("plugin returned invalid artifacts")
}
if trimmed := strings.TrimSpace(string(encoded)); trimmed == "" || trimmed[0] != '[' {
return nil, fmt.Errorf("plugin listArtifacts must return an array")
}
var items []map[string]any
if err = unmarshalJSON(encoded, &items); err != nil {
return nil, fmt.Errorf("plugin listArtifacts must return an array")
}
if len(items) > MaxTaskArtifacts {
return nil, fmt.Errorf("plugin returned too many artifacts")
}
artifacts := make([]Artifact, 0, len(items))
keys := make(map[string]struct{}, len(items))
for _, item := range items {
for field := range item {
if field != "key" && field != "type" && field != "mimeType" {
return nil, fmt.Errorf("plugin artifact contains unsupported field %q", field)
}
}
key, keyOK := item["key"].(string)
artifactType, typeOK := item["type"].(string)
if !keyOK || !taskArtifactKeyPattern.MatchString(key) {
return nil, fmt.Errorf("plugin artifact has invalid key")
}
if _, exists := keys[key]; exists {
return nil, fmt.Errorf("plugin artifact keys must be unique")
}
keys[key] = struct{}{}
switch artifactType {
case "video", "audio", "image", "file":
default:
if !typeOK {
return nil, fmt.Errorf("plugin artifact has invalid type")
}
return nil, fmt.Errorf("plugin artifact has unsupported type")
}
mimeType := ""
if rawMimeType, exists := item["mimeType"]; exists {
var mimeTypeOK bool
mimeType, mimeTypeOK = rawMimeType.(string)
if !mimeTypeOK || len(mimeType) > 255 || strings.ContainsAny(mimeType, "\r\n") {
return nil, fmt.Errorf("plugin artifact has invalid mimeType")
}
}
artifacts = append(artifacts, Artifact{Key: key, Type: artifactType, MimeType: mimeType})
}
return artifacts, nil
}
// gatewayCredentialHeaders carry the client's gateway credentials. Driver
// hooks receive every other request header.
var gatewayCredentialHeaders = []string{"Authorization", "Proxy-Authorization", "Cookie", "X-Api-Key", "X-Goog-Api-Key", "Mj-Api-Secret"}
// ClientRequestHeaders is the client's request headers as decoders and driver
// hooks receive them: the first value of each under its canonical name,
// without the headers that carry gateway credentials, and with Content-Type
// and Accept always present.
func ClientRequestHeaders(header http.Header) map[string]string {
headers := make(map[string]string, len(header)+2)
for name, values := range header {
name = http.CanonicalHeaderKey(name)
if len(values) > 0 && !slices.Contains(gatewayCredentialHeaders, name) {
headers[name] = values[0]
}
}
headers["Content-Type"] = header.Get("Content-Type")
headers["Accept"] = header.Get("Accept")
return headers
}
// EncodeFilePlaceholders replaces, in body itself, each file placeholder of
// a JSON request descriptor body with the encoded bytes of the uploaded file
// it names, and returns the result. limit bounds each file and all of them
// together. body must be the host's own copy: its maps and slices change.
func EncodeFilePlaceholders(body any, form *multipart.Form, limit int64) (any, error) {
var total int64
return replaceFilePlaceholders(body, form, limit, &total)
}
func replaceFilePlaceholders(value any, form *multipart.Form, limit int64, total *int64) (any, error) {
switch typed := value.(type) {
case map[string]any:
if _, isPlaceholder := typed["__fileRef"]; isPlaceholder {
return encodeFilePlaceholder(typed, form, limit, total)
}
for key, item := range typed {
replaced, err := replaceFilePlaceholders(item, form, limit, total)
if err != nil {
return nil, err
}
typed[key] = replaced
}
return typed, nil
case []any:
for index, item := range typed {
replaced, err := replaceFilePlaceholders(item, form, limit, total)
if err != nil {
return nil, err
}
typed[index] = replaced
}
return typed, nil
default:
return value, nil
}
}
func encodeFilePlaceholder(placeholder map[string]any, form *multipart.Form, limit int64, total *int64) (string, error) {
for key := range placeholder {
switch key {
case "__fileRef", "encoding", "mimeType", "maxBytes":
default:
return "", fmt.Errorf("invalid file placeholder")
}
}
ref, _ := placeholder["__fileRef"].(string)
if strings.TrimSpace(ref) == "" {
return "", fmt.Errorf("unknown file reference %q", ref)
}
encoding, _ := placeholder["encoding"].(string)
if encoding != "base64" && encoding != "dataUrl" {
return "", fmt.Errorf("file placeholder encoding must be \"base64\" or \"dataUrl\"")
}
if form == nil {
return "", fmt.Errorf("unknown file reference %q", ref)
}
field, index, validRef := ParseFileReference(ref)
files := form.File[field]
if !validRef || index >= len(files) {
return "", fmt.Errorf("unknown file reference %q", ref)
}
header := files[index]
maxBytes := limit
if raw, exists := placeholder["maxBytes"]; exists {
n, ok := usageExampleNumber(raw)
if !ok || n <= 0 || n != math.Trunc(n) {
return "", fmt.Errorf("invalid file placeholder")
}
if int64(n) < maxBytes {
maxBytes = int64(n)
}
}
if header.Size > maxBytes {
return "", fmt.Errorf("file %q exceeds the %d byte limit", ref, maxBytes)
}
file, openErr := header.Open()
if openErr != nil {
return "", openErr
}
data, readErr := io.ReadAll(io.LimitReader(file, maxBytes+1))
file.Close()
if readErr != nil {
return "", readErr
}
if int64(len(data)) > maxBytes {
return "", fmt.Errorf("file %q exceeds the %d byte limit", ref, maxBytes)
}
if *total+int64(len(data)) > limit {
return "", fmt.Errorf("inlined files exceed the %d byte limit", limit)
}
*total += int64(len(data))
if encoding == "base64" {
return base64.StdEncoding.EncodeToString(data), nil
}
mimeType := "application/octet-stream"
if override, ok := placeholder["mimeType"].(string); ok && strings.TrimSpace(override) != "" {
mimeType = override
} else if contentType := header.Header.Get("Content-Type"); contentType != "" {
mimeType = contentType
}
return base64.EncodeDataURL(mimeType, data), nil
}
// returnedState is the JSON of a hook result's state member, which the host
// stores only when the hook returns one: not when it is absent or null.
func returnedState(value any) ([]byte, bool) {
object, ok := value.(map[string]any)
if !ok {
return nil, false
}
state, exists := object["state"]
if !exists || state == nil {
return nil, false
}
data, err := marshalJSON(state)
if err != nil {
return nil, false
}
return data, true
}
func convertJSON(value any, target any) error {
data, err := marshalJSON(value)
if err != nil {
return err
}
return unmarshalJSON(data, target)
}
// ValidArtifactKey reports whether key may name a task artifact.
func ValidArtifactKey(key string) bool {
return taskArtifactKeyPattern.MatchString(key)
}
// DecodedRequest is what a decoder returns: a native route's decode hook or
// a protocol's decodeRequest.
type DecodedRequest struct {
// Value is the hook's result and Result the same value when it is an
// object, else nil.
Value any
Result map[string]any
// RequestBodyText is the JSON.stringify text of the result's
// requestBody for a plugin that preserves JSON order, else nil.
RequestBodyText json.RawMessage
}
// CallRouteDecode runs native[decode] on the request of a native route.
// admissionTimeout is as for Engine.CallPathWithAdmissionTimeout; 0 is the
// default.
func (p *LoadedPlugin) CallRouteDecode(ctx context.Context, admissionTimeout time.Duration, decode string, request RouteRequestContext) (DecodedRequest, error) {
return p.callDecode(ctx, admissionTimeout, "native", []string{decode}, request.JSValueFor(p.Meta))
}
// CallProtocolDecode runs protocols[protocol].decodeRequest on the request of
// a host protocol.
func (p *LoadedPlugin) CallProtocolDecode(ctx context.Context, admissionTimeout time.Duration, protocol string, request ProtocolRequestContext) (DecodedRequest, error) {
return p.callDecode(ctx, admissionTimeout, "protocols", []string{protocol, "decodeRequest"}, request.JSValueFor(p.Meta))
}
func (p *LoadedPlugin) callDecode(ctx context.Context, admissionTimeout time.Duration, exportName string, members []string, request map[string]any) (DecodedRequest, error) {
value, text, err := p.Engine.CallPathWithMemberJSON(ctx, admissionTimeout, p.Meta.JSONTextMember("requestBody"), exportName, members, request)
result, _ := value.(map[string]any)
return DecodedRequest{Value: value, Result: result, RequestBodyText: text}, err
}
@@ -1,4 +1,4 @@
package jsplugin
package pluginkit
import (
"context"
@@ -7,7 +7,6 @@ import (
"fmt"
"slices"
"strings"
"sync/atomic"
"unicode/utf8"
"github.com/MoeForge/moego/regexp"
@@ -29,7 +28,7 @@ const ReportHook = "report"
const ReplyHook = "reply"
// Limits on a stage hook result, part of the published plugin contract
// (docs/plugin-api/v1.md).
// (v1.md).
const (
maxTransformFindings = 64
maxTransformTextRunes = 256
@@ -142,6 +141,13 @@ type TransformUser struct {
Username string `json:"username"`
}
// TransformSession is the client session a request belongs to, on a host
// that recognizes sessions.
type TransformSession struct {
ID string `json:"id"`
Turn int `json:"turn"`
}
// TransformToken is the API token a request comes with.
type TransformToken struct {
ID int `json:"id"`
@@ -151,17 +157,24 @@ type TransformToken struct {
// TransformContext is the ctx a stage hook receives. Config is the instance
// config with the schema defaults applied (ValidateConfig).
type TransformContext struct {
Stage string `json:"stage"`
Format string `json:"format"`
Path string `json:"path"`
Model string `json:"model"`
UpstreamModel string `json:"upstreamModel,omitempty"`
Group string `json:"group"`
Channel *TransformChannel `json:"channel,omitempty"`
Attempt int `json:"attempt"`
User TransformUser `json:"user"`
Stage string `json:"stage"`
Format string `json:"format"`
Path string `json:"path"`
Model string `json:"model"`
UpstreamModel string `json:"upstreamModel,omitempty"`
// Group and User are left zero by a host without user groups or users,
// and hooks then receive no ctx.group or ctx.user.
Group string `json:"group,omitempty"`
Channel *TransformChannel `json:"channel,omitempty"`
Attempt int `json:"attempt"`
User TransformUser `json:"user,omitzero"`
// Token is nil when the request has none.
Token *TransformToken `json:"token,omitempty"`
Token *TransformToken `json:"token,omitempty"`
// Client and Session are host-specific: the client the host recognized
// (empty, or "unknown", when none) and the client session (nil when
// none). new-api leaves them unset.
Client string `json:"client,omitempty"`
Session *TransformSession `json:"session,omitempty"`
Instance TransformInstance `json:"instance"`
Config json.RawMessage `json:"config"`
// Media gives the hook's utils the request's attachments; nil when the
@@ -359,12 +372,22 @@ func (p *LoadedPlugin) transformHookContext(tctx *TransformContext) map[string]a
"format": tctx.Format,
"path": tctx.Path,
"model": tctx.Model,
"group": tctx.Group,
"attempt": tctx.Attempt,
"user": map[string]any{"id": tctx.User.ID, "username": tctx.User.Username},
"instance": map[string]any{"id": tctx.Instance.ID, "name": tctx.Instance.Name},
"config": RawJSON(config),
}
if tctx.Group != "" {
hookCtx["group"] = tctx.Group
}
if tctx.User != (TransformUser{}) {
hookCtx["user"] = map[string]any{"id": tctx.User.ID, "username": tctx.User.Username}
}
if tctx.Client != "" && tctx.Client != "unknown" {
hookCtx["client"] = tctx.Client
}
if tctx.Session != nil && tctx.Session.ID != "" {
hookCtx["session"] = map[string]any{"id": tctx.Session.ID, "turn": tctx.Session.Turn}
}
if tctx.Token != nil {
hookCtx["token"] = map[string]any{"id": tctx.Token.ID, "name": tctx.Token.Name}
}
@@ -386,7 +409,7 @@ func (e *TransformError) classify(err error) {
e.Class, e.Thrown = TransformErrorThrow, hookErr.Message
case errors.Is(err, moejs.ErrMemoryLimit):
e.Class = TransformErrorMemory
case errors.Is(err, errCallTimeout), errors.Is(err, ErrCallAdmissionTimeout), errors.Is(err, context.DeadlineExceeded):
case errors.Is(err, ErrCallTimeout), errors.Is(err, ErrCallAdmissionTimeout), errors.Is(err, context.DeadlineExceeded):
e.Class = TransformErrorTimeout
case errors.Is(err, context.Canceled):
e.Class = TransformErrorCanceled
@@ -659,25 +682,13 @@ func UTF16Len(text string) int {
// returns to JS: {body, headers?} or {reject}.
type ParamOverrideFunc func(ctx TransformContext, body json.RawMessage, override json.RawMessage) (result json.RawMessage, err error)
var paramOverrideFunc atomic.Pointer[ParamOverrideFunc]
// SetParamOverrideFunc sets the function utils.paramOverride calls; nil
// removes it.
func SetParamOverrideFunc(fn ParamOverrideFunc) {
if fn == nil {
paramOverrideFunc.Store(nil)
return
}
paramOverrideFunc.Store(&fn)
}
// paramOverride is utils.paramOverride(body, override): the host parameter
// override, in an outbound hook only. The Go function bounds its own work.
func (c *runtimeCall) paramOverride(r *moejs.Realm, body, override moejs.Value) (moejs.Value, error) {
if c.transform == nil || c.transform.Stage != "outbound" || c.hook != "outbound" {
return moejs.Undefined(), fmt.Errorf("utils.paramOverride is not available in %s", c.hook)
}
fn := paramOverrideFunc.Load()
fn := hostConfig().ParamOverride
if fn == nil {
return moejs.Undefined(), fmt.Errorf("utils.paramOverride is not available on this host")
}
@@ -699,7 +710,7 @@ func (c *runtimeCall) paramOverride(r *moejs.Realm, body, override moejs.Value)
}
texts = append(texts, text)
}
result, err := (*fn)(*c.transform, texts[0], texts[1])
result, err := fn(*c.transform, texts[0], texts[1])
if err != nil {
return moejs.Undefined(), err
}
+30
View File
@@ -0,0 +1,30 @@
package pluginkit
import (
"context"
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// The members a host fills only when it has them reach hooks only then.
func TestTransformContextHostSpecificMembers(t *testing.T) {
plugin, err := CompilePlugin(`export const meta = {apiVersion: 1, key: "rp-host-members", name: "Host members", version: "1.0.0", author: {name: "Test"}};
export function ingress(ctx) {
const seen = ["group", "user", "client", "session"].filter((name) => name in ctx).map((name) => name + "=" + JSON.stringify(ctx[name]));
return {action: "reject", code: "seen", message: seen.join(" ")};
}`, Options{})
require.NoError(t, err)
call := func(tctx TransformContext) string {
tctx.Stage, tctx.Config = "ingress", json.RawMessage(`{}`)
result, err := plugin.CallTransform(context.Background(), tctx, TransformRequest{Body: json.RawMessage(`{}`)})
require.NoError(t, err)
return result.Message
}
assert.Equal(t, "", call(TransformContext{Client: "unknown", Session: &TransformSession{Turn: 2}}))
assert.Equal(t,
`group="default" user={"id":7,"username":"alice"} client="claude_code" session={"id":"s1","turn":3}`,
call(TransformContext{Group: "default", User: TransformUser{ID: 7, Username: "alice"}, Client: "claude_code", Session: &TransformSession{ID: "s1", Turn: 3}}))
}
+2 -2
View File
@@ -1,4 +1,4 @@
package jsplugin
package pluginkit
import (
"bytes"
@@ -48,7 +48,7 @@ func injectGlobals(runtime *moejs.Runtime, identity func() string, now func() ti
if moejs.Arg(args, 0).IsUndefined() {
return moejs.Undefined(), r.TypeError("json.clone requires a JSON value")
}
budget := &jsonStateBudget{ctx: context.Background(), bytes: MaxJSONToolBytes, nodes: maxJSONToolNodes, realm: r}
budget := &jsonStateBudget{ctx: context.Background(), bytes: maxJSONCloneBytes, nodes: maxJSONToolNodes, realm: r}
value, err := newJSONStateNode(moejs.Arg(args, 0), 0, budget)
if err != nil {
var exception *moejs.Exception
+12 -6
View File
@@ -8,7 +8,7 @@ export interface UpstreamContext {kind: UpstreamKind}
export type MutableJSON<T> = T extends readonly (infer Item)[] ? MutableJSON<Item>[] : T extends object ? {-readonly [Key in keyof T]: MutableJSON<T[Key]>} : T;
export interface HostUtils {
hasCapability(name: string): boolean;
/** Independent native JS containers; at most 1 MiB encoded JSON, depth 32 and 32,768 nodes. */
/** Returns a JSON value with independent, mutable JS objects and arrays. Limits are 4 MiB of encoded JSON, 32 levels below the root and 32,768 nodes. */
json: {clone<T extends JSONValue>(value: T): MutableJSON<T>};
unixNow(): number;
uuid(): string;
@@ -23,7 +23,12 @@ export interface HostUtils {
base64URL(value: string): string;
base64URLDecode(value: string): string;
volcSignV4(request: {method: string; url: string; headers?: Record<string, string>; body?: string; accessKey: string; secretKey: string; region?: string; service?: string; timestamp?: number}): Record<string, string>;
/** Synchronous request. Driver hooks address the channel Base URL host or allowedHosts, read-only outside login, refresh, revoke, exchangeKey and scheduled. ingress, egress, reply and report address allowedHosts and the hosts of the instance's url config values, and may POST. At most 4 per hook call, 15 s each, 30 s in total, 1 MiB per body; redirects are returned, not followed. In a stage hook, each JSON string value of body that equals a "[media:N]" ref of the call is sent as that file's data URL, streamed from the request: at most 8 refs and 32 MiB of file data per body. */
/** Sends a synchronous request and returns redirects to the caller.
* Driver hooks can read from the channel Base URL host and allowedHosts. login, refresh, revoke, exchangeKey and scheduled can also POST.
* ingress, egress, reply and report may POST to allowedHosts and the hosts of the instance's url config values.
* Each hook call allows up to 4 fetches, 15 s per fetch and 30 s in total.
* Response bodies may use up to 4 MiB each and 8 MiB in total, including bytes read from failed responses.
* In a stage hook, the host streams each "[media:N]" ref used as a JSON string value in the body as that file's data URL, up to 8 refs and 32 MiB of file data per body. */
fetch(request: FetchRequest): FetchResponse;
/** new-api only: outbound hooks only, runs the new-api channel parameter override language on body, with conditions reading ctx. A return_error operation comes back as reject. On a host without it, it is missing or throws "utils.paramOverride is not available on this host". */
paramOverride?(body: Readonly<Record<string, JSONValue>>, override: Readonly<Record<string, JSONValue>>): {body: Record<string, JSONValue>; headers?: {set?: Record<string, string>; remove?: string[]}} | {reject: {code: string; message: string}};
@@ -89,11 +94,11 @@ export type UsageProfile = {models: readonly string[]; schema: Readonly<Record<s
/** Protocol names of request bodies: relaykit's types.RelayFormat, the same on every host. See Protocol names in v1.md. Names may be added under apiVersion 1, never renamed. */
export type RelayFormat = "openai" | "openai_responses" | "openai_responses_compaction" | "claude" | "gemini" | "embedding" | "rerank" | "openai_image" | "openai_audio" | "openai_realtime" | "openai_alpha_search" | "deepseek_tools" | "task" | "mj_proxy";
/** Relay route converters: relaykit's converter IDs, spelled as relaykit registers them. See Relay routes in v1.md for the incoming_path each accepts and its upstream protocol. */
export type RelayConverterName = "openai_chat_completions_to_anthropic_messages" | "openai_chat_completions_to_openai_responses" | "openai_chat_completions_to_gemini_generate_content" | "openai_responses_to_openai_chat_completions" | "openai_responses_to_gemini_generate_content" | "anthropic_messages_to_openai_chat_completions" | "claude_messages_to_openai_responses" | "gemini_generate_content_to_openai_chat_completions" | "gemini_generate_content_to_openai_responses" | "jina_rerank_to_sglang";
export type RelayConverterName = "openai_chat_completions_to_anthropic_messages" | "openai_chat_completions_to_openai_responses" | "openai_chat_completions_to_gemini_generate_content" | "openai_responses_to_openai_chat_completions" | "openai_responses_to_gemini_generate_content" | "openai_responses_to_claude_messages" | "anthropic_messages_to_openai_chat_completions" | "claude_messages_to_openai_responses" | "gemini_generate_content_to_openai_chat_completions" | "gemini_generate_content_to_openai_responses" | "jina_rerank_to_sglang";
/** none (default), a converter, "plugin" for the plugin's convert hooks, or "<converter>+plugin" for that converter's upstream protocol converted by the hooks. */
export type RelayConverter = "none" | RelayConverterName | "plugin" | `${RelayConverterName}+plugin`;
/** One meta.relay route. incoming_path: the client path, starting with /, without a query; {model} may stand for one path segment, once; a :generateContent path also serves :streamGenerateContent. upstream_path: a path starting with a single /, joined to the channel Base URL, or an absolute http(s) URL; {model} is replaced with the upstream model; it may start with {config.<name>}, a format url field of meta.channelConfig, and an empty address is the channel Base URL. models: names, or "re:" and an RE2 expression; an empty list is the route for every other model of its path, one per path, last. auth: without it the key is sent as Authorization: Bearer; {api_key} in value stands for the key. pass_through_body_enabled: only with converter none or jina_rerank_to_sglang. /v1/models and /v1/dashboard/billing/credit_grants take at most one route each, without models, {model} or pass-through; on /v1/models "plugin" runs convertResponse alone. These are the rules of a new-api Advanced Custom channel route. */
export interface RelayRoute {incoming_path: string; upstream_path: string; converter?: RelayConverter; models?: readonly string[]; auth?: {type: "none" | "header" | "query"; name?: string; value?: string}; pass_through_body_enabled?: boolean}
/** One meta.relay route. incoming_path: the client path, starting with /, without a query; {model} may stand for one path segment, once; a :generateContent path also serves :streamGenerateContent. upstream_path: a path starting with a single /, joined to the channel Base URL, or an absolute http(s) URL; {model} is replaced with the upstream model; it may start with {config.<name>}, a format url field of meta.channelConfig, and an empty address is the channel Base URL. models: names, or "re:" and an RE2 expression; an empty list is the route for every other model of its path, one per path, last. auth: without it the key is sent as Authorization: Bearer; {api_key} in value stands for the key. pass_through_body_enabled: only with converter none or jina_rerank_to_sglang. /v1/models and /v1/dashboard/billing/credit_grants take at most one route each, without models, {model} or pass-through; on /v1/models "plugin" runs convertResponse alone. default_enabled (true by default): whether a channel serves the route before an administrator switches it on the channel; the management routes are always on. These are the rules of a new-api Advanced Custom channel route, plus default_enabled. */
export interface RelayRoute {incoming_path: string; upstream_path: string; converter?: RelayConverter; models?: readonly string[]; auth?: {type: "none" | "header" | "query"; name?: string; value?: string}; pass_through_body_enabled?: boolean; default_enabled?: boolean}
/** One field of an instance config: a JSON Schema subset. title is required; nesting is at most 4 levels; unit, visibleWhen and every format but url are form hints that never change the check, the defaults or the config. A non-empty url value must be an absolute http(s) URL without credentials or fragment, and its host is one utils.fetch may address in ingress, egress, reply and report; password marks a secret the form hides. The form shows a slider for an integer field whose minimum and maximum are both set and at most 100 apart. */
export interface ConfigField {type: "string" | "number" | "integer" | "boolean" | "array" | "object"; title: LocalizedText; description?: LocalizedText; default?: JSONValue; examples?: readonly JSONValue[]; enum?: readonly (string | number)[]; enumTitles?: readonly LocalizedText[]; minimum?: number; maximum?: number; /** number and integer fields: byte values get a KB/MB choice (1000-based, stored in bytes), the others a suffix. */ unit?: "byte" | "pixel" | "character" | "second"; minLength?: number; maxLength?: number; /** RE2 regular expression. */ pattern?: string; /** string: textarea, regex, url, password, keywords (a property of the schema itself only); object: json. */ format?: "textarea" | "regex" | "url" | "password" | "keywords" | "json"; items?: ConfigField; minItems?: number; maxItems?: number; uniqueItems?: boolean; properties?: Readonly<Record<string, ConfigField>>; required?: readonly string[]; /** meta.channelConfig only, on an object field without properties: a value per model, keyed by model name. A string, number, integer or boolean field without default or visibleWhen. */ additionalProperties?: ConfigField; /** A property only, not an items field: shown while every named sibling property (string, number, integer or boolean) holds one of the listed values. Values must be valid for that sibling; lists are non-empty without repeats. API responses always write lists. */ visibleWhen?: Readonly<Record<string, string | number | boolean | readonly (string | number | boolean)[]>>}
/** The schema of a request processing instance's config. Without it the config is {}. */
@@ -145,6 +150,7 @@ export interface SubmitEventDeltaResult {changes: readonly JSONChange[]; state:
/** With submit-sse-delta@1, state is small control data; changes build the separate response body. */
export declare function parseSubmitEventDelta(ctx: DriverContext, event: SubmitEvent, previousState: JSONValue | null): SubmitEventDeltaResult;
export declare function parseSubmitEvent(ctx: DriverContext, event: SubmitEvent, previousState: JSONValue | null): {state: JSONValue; done: boolean};
/** Retained taskData and plugin state each have a 1 MiB limit. Immediate terminal taskData on openai_image or a native route with retainResult: false may reach MAX_FILE_DOWNLOAD_MB (default 64 MiB). */
export declare function parseSubmitResponse(ctx: DriverContext, response: UpstreamResponse): {taskId: string; taskData?: unknown; immediate?: NormalizedTaskResult; state?: unknown};
/** Query redirects retain credentials only within the channel host and meta.allowedHosts; SSRF checks and HTTPS downgrade protection still apply. */
export declare function buildQueryRequest(ctx: TaskQueryContext): RequestDescriptor;
@@ -249,7 +255,7 @@ export interface ScheduledResult {
export declare function scheduled(ctx: ScheduledContext): ScheduledResult;
export type TransformStage = "ingress" | "request" | "outbound" | "egress";
/** ctx of the stage hooks, of reply and of report. config is the instance config with the schema defaults applied. format is "task" on task submissions ("openai_responses" or "openai_image" at ingress when a task plugin serves those APIs) and "mj_proxy" on Midjourney submissions. In a Realtime session, format is "openai_responses" at ingress and "openai_realtime" in reply and report, path is "/v1/realtime", and channel is set from ingress on. upstreamModel and channel are set from request on, and in the late ingress of an instance the channel binds or of a group settled at channel selection, which runs on each attempt before outbound, on the upstream body (on a task submission, on the client body before the attempt is priced). In reply, format is the client's format. In report they are those of the last attempt, absent when the request reached no channel. user and token are those of the report record; token is absent without one. In a dry run, user is the administrator and there is no token. */
export interface TransformContext {stage: TransformStage | "reply" | "report"; /** The protocol name of req.body. A hook returns continue for a name it does not handle. */ format: RelayFormat | (string & {}); path: string; model: string; upstreamModel?: string; /** new-api only. */ group?: string; /** new-api only. */ channel?: {id: number; type: number}; attempt: number; /** new-api only. */ user?: {id: number; username: string}; /** new-api only. */ token?: {id: number; name: string}; instance: {id: string; name: string}; /** A property of format "keywords" reads as a KeywordsSummary. */ config: Readonly<Record<string, JSONValue>>}
export interface TransformContext {stage: TransformStage | "reply" | "report"; /** The protocol name of req.body. A hook returns continue for a name it does not handle. */ format: RelayFormat | (string & {}); path: string; model: string; upstreamModel?: string; /** new-api only. */ group?: string; /** new-api only. */ channel?: {id: number; type: number}; attempt: number; /** new-api only. */ user?: {id: number; username: string}; /** new-api only. */ token?: {id: number; name: string}; /** Host-specific: the client application the host recognized; new-api never sets it. */ client?: string; /** Host-specific: the client session; new-api never sets it. */ session?: {id: string; turn: number}; instance: {id: string; name: string}; /** A property of format "keywords" reads as a KeywordsSummary. */ config: Readonly<Record<string, JSONValue>>}
/** An inline image of req.body, which holds "[media:<index>]" in its place. path is its JSON Pointer; bytes is its decoded size; width and height are given at outbound only. */
export interface TransformMedia {index: number; path: string; mimeType: string; bytes: number; width?: number; height?: number}
/** headers: outbound and egress, the headers earlier instances of the attempt set with header.patch. summary: request only; reasoningEffort is "" when the client and the model modifiers set none. form: ingress, set when body is the text fields of a multipart form body, each a string or, for a repeated field, an array of strings; its only effects are json.patch replace operations that set a field to a string, and media.text, which leaves a form file as it is. */
+34 -10
View File
@@ -34,9 +34,11 @@ A plugin declares its vendor's own paths. The gateway serves each route at that
Several plugins may declare the same method and path shape, for the same model as well. Every plugin declaring a `submit` path decodes the request, in ascending key order; the first that accepts it names the model, the others that accept the same model stay candidates, and the selected channel decides which plugin executes, as on a shared host protocol, billing the task at that plugin's `<pluginKey>::<model>` expression. A decoder's `model` is matched as on the host protocols: a case variant stands for the declared model and the task takes the declared spelling; an alias that an enabled channel lists and maps through `model_mapping` stays the task's model, and the driver reads the mapped name from `ctx.upstreamModel`. A single candidate's rejection reaches the client as it is; when all of several reject, the client gets each message prefixed with the plugin keys that gave it. A `query` path answers through the task's own plugin, the first in key order owning it; a task none of them owns is not found, like a missing one. A `dynamic` path answers a query through the first plugin owning the tasks and otherwise continues as a submit. Each plugin reads the path parameters under the names it declares, so `/v1/videos/:request_id` and `/v1/videos/:task_id` share a path. A catch-all (`*name`) beside another plugin's literal segment at the same position cannot be served together; the gateway then excludes one plugin with a routing error.
Routes stay out of the reserved namespaces `/v1/tasks`, `/assets` and the console pages, and a key may not be `api` or the first segment of one of them: such a plugin fails to compile. Every plugin, built-in or uploaded, is served at its top-level paths, such as `POST /v1/systemone`, except where a host route of the same method, or the trailing-slash redirect it causes, answers first, or where the first segment is another plugin's key or a built-in plugin's own prefix. Such a route is still served under `/{key}`, and the plugin list (`GET /api/plugin/task`) and detail name it in `skipped_routes` (`"GET /v1/models"`). A plugin whose key is `api`, the first segment of a host route (`v1`, `v1beta`, `mj`, `pg`, `dashboard`) or a built-in plugin's own prefix is excluded with a routing error. A `query` route's task-id parameter only receives gateway task ids, so it never meets a literal host segment: `GET /v1/videos/text2video/:task_id` is free beside the host's `GET /v1/videos/:task_id/content`. Two host routes offer matching requests to plugin routes first, so plugin routes may overlap them. `GET /v1/videos/:task_id` answers through the task's own plugin when the task was submitted on one of that plugin's native routes (at the vendor path, under `/{key}` or under its own prefix) and the plugin serves a `query` route matching the request; every other task gets the OpenAI video object. `POST /v1beta/models/{model}:predictLongRunning` goes to the matching plugin route before the Gemini relay's authentication, rate limit and channel selection; other Gemini actions, and requests no plugin route matches, stay with the relay.
Routes stay out of the reserved namespaces `/v1/tasks`, `/assets` and the console pages, and a key may not be `api` or the first segment of one of them: such a plugin fails to compile. Every plugin, built-in or uploaded, is served at its top-level paths, such as `POST /v1/systemone`, except where a host route of the same method, or the trailing-slash redirect it causes, answers first, or where the first segment is another plugin's key or a built-in plugin's own prefix. Such a route is still served under `/{key}`, and the plugin list (`GET /api/plugin/task`) and detail name it in `skipped_routes` (`"GET /v1/models"`). A plugin whose key is `api`, the first segment of a host route (`v1`, `v1beta`, `mj`, `pg`, `dashboard`) or a built-in plugin's own prefix is excluded with a routing error. Go hosts embedding pluginkit read the key limit as `pluginkit.MaxPluginKeyLength` and the keys new-api refuses as `pluginkit.NewAPIReservedKeys()`. A `query` route's task-id parameter only receives gateway task ids, so it never meets a literal host segment: `GET /v1/videos/text2video/:task_id` is free beside the host's `GET /v1/videos/:task_id/content`. Two host routes offer matching requests to plugin routes first, so plugin routes may overlap them. `GET /v1/videos/:task_id` answers through the task's own plugin when the task was submitted on one of that plugin's native routes (at the vendor path, under `/{key}` or under its own prefix) and the plugin serves a `query` route matching the request; every other task gets the OpenAI video object. `POST /v1beta/models/{model}:predictLongRunning` goes to the matching plugin route before the Gemini relay's authentication, rate limit and channel selection; other Gemini actions, and requests no plugin route matches, stay with the relay.
`routes[].retainResult` is an optional boolean on `submit` and `dynamic` routes, default `true`. Declare `retainResult: false` only on routes where every successful submission completes immediately (`parseSubmitResponse` returns a terminal `immediate`), typically a vendor's synchronous image API that has no task to re-query. For such a result the host does not persist `task.data`, and the task is thereafter not found on every retrieval surface: the plugin's own `query` routes, `GET /v1/responses/:response_id`, `GET /v1/videos/:task_id` and its content, and artifact listing and content. The task row remains for billing and the task log. The submit presenter still receives the complete in-memory `task.data`, and `extractUsageOnComplete` runs before persistence, so settlement is unchanged. Because nothing is persisted, the submit reply of such a route, each of its SSE events and its in-memory `task.data` may be as large as `MAX_FILE_DOWNLOAD_MB` (default 64 MB) instead of 1 MiB, which lets a vendor answer with Base64 images; plugin state keeps its 1 MiB limit. An asynchronous result on a declaring route is retained and retrievable as usual and logs a warning. `query` routes reject the field. `openai_responses` and `openai_video` always retain their results because their deliverables are served through host artifact URLs; a plugin that wants previews with less storage should instead return a compact `taskData` from `parseSubmitResponse`. `openai_image` delivers its images inline in the create response, so an immediate terminal result on that protocol is discarded exactly as with `retainResult: false`, while a result completed by in-request polling keeps the snapshot the poller wrote. This is an additive apiVersion 1 extension: older hosts reject the unknown field.
`routes[].retainResult` is an optional boolean on `submit` and `dynamic` routes, default `true`. Declare `retainResult: false` only on routes where every successful submission completes immediately (`parseSubmitResponse` returns a terminal `immediate`), typically a vendor's synchronous image API that has no task to re-query. The host omits `task.data` from storage for an immediate terminal result. Later lookups return task not found on the plugin's `query` routes, `GET /v1/responses/:response_id`, `GET /v1/videos/:task_id`, video content, and artifact listing and content. The task row remains for billing and the task log. The submit presenter receives the complete in-memory `task.data`, and `extractUsageOnComplete` runs before persistence. If a declaring route returns an asynchronous result, the host stores it for retrieval and logs a warning. `query` routes reject the field. Older API v1 hosts reject it as an unknown field.
`openai_image` also delivers immediate terminal results inline. On this protocol and native routes with `retainResult: false`, the submit reply, each SSE event and the `taskData` of an immediate terminal result may be as large as `MAX_FILE_DOWNLOAD_MB` (default 64 MiB). The host keeps a discarded result's snapshot and result URL in memory for the submit call, so a vendor can return Base64 images inline. Retained submit `taskData` and plugin `state` each have a 1 MiB limit. An `openai_image` task completed by in-request polling keeps the snapshot the poller wrote. `openai_responses` and `openai_video` retain their results for host artifact URLs. Plugins can return compact `taskData` from `parseSubmitResponse` to store a preview.
`routes[].models` optionally restricts a `submit` or `dynamic` route to a subset of `meta.models`. The host matches the canonical top-level `model` body field before any JS hook runs, counting a case variant or a channel alias of a listed model as listed; a missing, non-string, or unlisted model is rejected with 400 (plugin routes are exclusive paths, so there is no relay fallback). Declare it only when the model lives at the body top level — vendor formats that nest the model elsewhere should omit `models` and filter inside `decode`. `query` routes have no body and reject the field.
@@ -517,7 +519,7 @@ arrays, null, booleans, finite numbers and strings. Undefined, functions,
BigInt, dates, sparse arrays and cyclic structures are rejected. Object keys
such as `__proto__` remain ordinary own data properties. The tool uses the
host's JSON number and string normalization and preserves explicit zero and
false values. Limits are 1 MiB of encoded JSON, 32 levels below the root and
false values. Limits are 4 MiB of encoded JSON, 32 levels below the root and
32,768 total nodes, including containers and scalar values. It performs no I/O.
`json-order@1` keeps JSON member order for upstreams that treat it as
@@ -610,8 +612,10 @@ body.
- Redirects are not followed. A 3xx response is returned as it is; fetching its
`Location` is a new request, checked and counted again.
- HTTP error statuses are returned, not thrown.
- Limits: at most 4 fetches per hook call, 15 seconds per fetch, 30 seconds
for all fetches of one hook call, and 1 MiB per response body.
- A hook call may make up to 4 fetches, with 15 seconds per fetch and 30
seconds in total. Each response body may be up to 4 MiB. All response
bodies read in one hook call share an 8 MiB limit. Bytes read from an
oversized or interrupted response count toward the limit.
`utils.fetch` throws when:
@@ -629,7 +633,9 @@ body.
`Transfer-Encoding` or `Upgrade`;
- the host is not allowed;
- the fetch times out, or the call runs out of fetches or fetch time;
- the response body exceeds 1 MiB;
- the response body exceeds 4 MiB or the bytes remaining in the hook's 8 MiB
budget. Once the budget is exhausted, a further fetch throws before sending
a request.
- the transport fails.
Hook errors reach API callers, so these messages name the host only, never the
@@ -965,10 +971,11 @@ state is still only the `state` returned by `parseSubmitResponse`.
EOF without `done`, invalid framing/state, read failures, hook failures and size
limits fail submission, except on a native route once an event has reached the
client (see below). Events, accumulated JSON state and persisted task data
are each limited to 1 MiB, events to `MAX_FILE_DOWNLOAD_MB` on a route that
declares `retainResult: false`; data is never truncated. The existing streaming idle
timeout applies (30 seconds if unset), as do the submission context deadline
client (see below). The host accepts events up to `MAX_FILE_DOWNLOAD_MB` on
`openai_image` and native routes with `retainResult: false`, and up to 1 MiB
on other routes. Accumulated JSON state and retained submit data each have a
1 MiB limit. The streaming idle timeout applies (30 seconds if unset),
as do the submission context deadline
and per-hook execution timeout. Once a successful SSE HTTP response is accepted,
failures are non-retryable, including 5xx-shaped local errors: starting the
provider operation again could duplicate billable work. A request that selects
@@ -1122,6 +1129,8 @@ checks these members before it uses them and works without them.
| `ctx.group` | The user group of the request | Absent |
| `ctx.user`, `record.user` | The user who sent the request | Absent |
| `ctx.token`, `record.token` | The API token of the request | Absent |
| `ctx.client` of the request processing hooks | Absent | A host that recognizes the client application may set its name, such as `"claude_code"`; absent when it recognizes none |
| `ctx.session` of the request processing hooks | Absent | A host that tracks client sessions may set `{id, turn}`: the session id and the turn number within it; absent outside a session |
| `meta.channelTypes`, `meta.scope.channelTypes`, `ctx.channelOther` | new-api built-in channel type numbers, and the raw `other` field of such a channel | Ignored, and `ctx.channelOther` absent |
| `utils.paramOverride` | The new-api channel parameter override language (see utils.paramOverride) | Missing, or throws `utils.paramOverride is not available on this host` |
@@ -1196,6 +1205,20 @@ route.
it standing for the key.
- `pass_through_body_enabled`: sends the client body as it came. Only with
converter `none` or `jina_rerank_to_sglang`.
- `default_enabled`: whether a channel serves the route before an
administrator switches it, `true` by default. Every route but the management
routes has a switch on the channel form, stored per channel in
`plugin_routes` only when it differs from this default. A channel does not
take requests for a route that is off for it: selection skips the channel
for that path and model, and the relay, the channel test and the Responses
WebSocket check do not see the route. Another route of the same path still
serves the models it accepts. The management routes are always on and cannot
have `default_enabled: false`. Only a plugin route has this key.
A channel's `plugin_routes` names each route by its `incoming_path`, followed by
`|` and its `models` joined with `,` when it lists models. A switch whose name
matches no route, after an update of the plugin, is dropped the next time the
channel is saved.
`/v1/models` and `/v1/dashboard/billing/credit_grants` are management routes:
at most one each, with no `models`, converter `none` (`/v1/models` also takes
@@ -1210,6 +1233,7 @@ at most one each, with no `models`, converter `none` (`/v1/models` also takes
| `openai_chat_completions_to_gemini_generate_content` | `/v1/chat/completions` | `gemini` |
| `openai_responses_to_openai_chat_completions` | `/v1/responses` | `openai` |
| `openai_responses_to_gemini_generate_content` | `/v1/responses` | `gemini` |
| `openai_responses_to_claude_messages` | `/v1/responses` | `claude` |
| `anthropic_messages_to_openai_chat_completions` | `/v1/messages` | `openai` |
| `claude_messages_to_openai_responses` | `/v1/messages` | `openai_responses` |
| `gemini_generate_content_to_openai_chat_completions` | A path with `:generateContent` or `:streamGenerateContent` | `openai` |
@@ -1,6 +1,6 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/QuantumNous/new-api/docs/plugin-api/v1.schema.json",
"$id": "https://github.com/QuantumNous/new-api/pluginkit/v1.schema.json",
"title": "new-api Task Plugin v1 manifest",
"type": "object",
"additionalProperties": false,
@@ -172,7 +172,7 @@
"properties": {
"incoming_path": {"type": "string", "pattern": "^/"},
"upstream_path": {"type": "string", "minLength": 1},
"converter": {"enum": ["none", "openai_chat_completions_to_anthropic_messages", "openai_chat_completions_to_openai_responses", "openai_chat_completions_to_gemini_generate_content", "openai_responses_to_openai_chat_completions", "openai_responses_to_gemini_generate_content", "anthropic_messages_to_openai_chat_completions", "claude_messages_to_openai_responses", "gemini_generate_content_to_openai_chat_completions", "gemini_generate_content_to_openai_responses", "jina_rerank_to_sglang", "plugin", "openai_chat_completions_to_anthropic_messages+plugin", "openai_chat_completions_to_openai_responses+plugin", "openai_chat_completions_to_gemini_generate_content+plugin", "openai_responses_to_openai_chat_completions+plugin", "openai_responses_to_gemini_generate_content+plugin", "anthropic_messages_to_openai_chat_completions+plugin", "claude_messages_to_openai_responses+plugin", "gemini_generate_content_to_openai_chat_completions+plugin", "gemini_generate_content_to_openai_responses+plugin", "jina_rerank_to_sglang+plugin"], "description": "none (default), a relaykit converter ID, plugin for the plugin's convert hooks, or <converter>+plugin for that converter's upstream protocol converted by the hooks. See Relay routes in v1.md for the incoming_path each converter accepts."},
"converter": {"enum": ["none", "openai_chat_completions_to_anthropic_messages", "openai_chat_completions_to_openai_responses", "openai_chat_completions_to_gemini_generate_content", "openai_responses_to_openai_chat_completions", "openai_responses_to_gemini_generate_content", "openai_responses_to_claude_messages", "anthropic_messages_to_openai_chat_completions", "claude_messages_to_openai_responses", "gemini_generate_content_to_openai_chat_completions", "gemini_generate_content_to_openai_responses", "jina_rerank_to_sglang", "plugin", "openai_chat_completions_to_anthropic_messages+plugin", "openai_chat_completions_to_openai_responses+plugin", "openai_chat_completions_to_gemini_generate_content+plugin", "openai_responses_to_openai_chat_completions+plugin", "openai_responses_to_gemini_generate_content+plugin", "openai_responses_to_claude_messages+plugin", "anthropic_messages_to_openai_chat_completions+plugin", "claude_messages_to_openai_responses+plugin", "gemini_generate_content_to_openai_chat_completions+plugin", "gemini_generate_content_to_openai_responses+plugin", "jina_rerank_to_sglang+plugin"], "description": "none (default), a relaykit converter ID, plugin for the plugin's convert hooks, or <converter>+plugin for that converter's upstream protocol converted by the hooks. See Relay routes in v1.md for the incoming_path each converter accepts."},
"models": {"type": "array", "items": {"type": "string"}},
"auth": {
"type": "object",
@@ -180,9 +180,10 @@
"required": ["type"],
"properties": {"type": {"enum": ["none", "header", "query"]}, "name": {"type": "string"}, "value": {"type": "string"}}
},
"pass_through_body_enabled": {"type": "boolean"}
"pass_through_body_enabled": {"type": "boolean"},
"default_enabled": {"type": "boolean", "default": true, "description": "Whether a channel serves the route before an administrator switches it on the channel. Not false on /v1/models or /v1/dashboard/billing/credit_grants."}
},
"description": "The keys of an Advanced Custom channel route; the host applies the same validation rules."
"description": "The keys of an Advanced Custom channel route, plus default_enabled; the host applies the same validation rules."
},
"upstreamKind": {"enum": ["vendor", "new_api"]},
"upstreamContext": {
+33
View File
@@ -63,6 +63,11 @@ func TestHailuoUsageProfilesPerModel(t *testing.T) {
fields: []string{"input_images", "input_video_seconds", "resolution", "seconds"},
resolutions: []string{"768P", "2K"},
},
{
models: []string{"MiniMax-H3-Max"},
fields: []string{"input_images", "input_video_seconds", "resolution", "seconds"},
resolutions: []string{"480P", "768P"},
},
{
models: []string{"MiniMax-Hailuo-2.3", "MiniMax-Hailuo-2.3-Fast"},
fields: []string{"resolution", "seconds"},
@@ -399,6 +404,21 @@ func TestHailuoH3RejectsOutOfContractRequests(t *testing.T) {
require.ErrorContains(t, err, testCase.wantErr)
})
}
for _, testCase := range []struct {
name string
request map[string]any
wantErr string
}{
{"H3-Max duration below its minimum", map[string]any{"prompt": "p", "duration": 4}, "MiniMax-H3-Max duration must be an integer between 5 and 15"},
{"H3-Max does not render 2K", map[string]any{"prompt": "p", "size": "2K"}, "MiniMax-H3-Max resolution must be 480P or 768P"},
} {
t.Run(testCase.name, func(t *testing.T) {
ctx := hailuoH3SubmitContext(testCase.request)
ctx["upstreamModel"] = "MiniMax-H3-Max"
_, err := plugin.Engine.Call(t.Context(), "buildSubmitRequest", ctx)
require.ErrorContains(t, err, testCase.wantErr)
})
}
}
// The /v1 models keep the flat request shape and endpoint.
@@ -526,6 +546,14 @@ func TestHailuoExtractUsageFacts(t *testing.T) {
}}, map[string]any{
"seconds": float64(5), "resolution": "768P", "input_images": float64(0), "input_video_seconds": float64(15),
}},
{"H3-Max 480P", "MiniMax-H3-Max", map[string]any{"prompt": "p", "duration": 5, "size": "480P"}, map[string]any{
"seconds": float64(5), "resolution": "480P", "input_images": float64(0), "input_video_seconds": float64(0),
}},
{"H3-Max native body reserves an unreadable resolution at its dearest", "MiniMax-H3-Max", map[string]any{"vendorBody": map[string]any{
"model": "MiniMax-H3-Max", "duration": 5, "resolution": "2K", "content": []any{map[string]any{"type": "text", "text": "p"}},
}}, map[string]any{
"seconds": float64(5), "resolution": "768P", "input_images": float64(0), "input_video_seconds": float64(0),
}},
{"legacy model", "MiniMax-Hailuo-2.3", map[string]any{"prompt": "p", "duration": 10}, map[string]any{
"seconds": float64(10), "resolution": "768P", "input_images": float64(0), "input_video_seconds": float64(0),
}},
@@ -557,6 +585,11 @@ func TestHailuoH3CompletionUsageFacts(t *testing.T) {
body: `{"task":{"id":"1","status":"succeeded","resolution":"768P","usage":{"output_seconds":4,"input_seconds":0,"input_image_count":0}}}`,
want: map[string]any{"seconds": float64(4), "resolution": "768P", "input_images": float64(0), "input_video_seconds": float64(0)},
},
{
name: "H3-Max settles at 480P",
body: `{"task":{"id":"1","status":"succeeded","resolution":"480P","usage":{"output_seconds":5,"input_seconds":0,"input_image_count":0}}}`,
want: map[string]any{"seconds": float64(5), "resolution": "480P", "input_images": float64(0), "input_video_seconds": float64(0)},
},
{
name: "zero output cannot erase the submission reservation",
body: `{"task":{"id":"1","status":"succeeded","resolution":"768P","usage":{"output_seconds":0,"input_seconds":0,"input_image_count":0}}}`,
+51 -20
View File
@@ -29,6 +29,14 @@ const H3_USAGE_SCHEMA = {
},
};
// MiniMax-H3-Max allows duration 5 to 15 and renders 480P or 768P.
const H3_MAX_USAGE_SCHEMA = Object.assign({}, H3_USAGE_SCHEMA, {
resolution: {
enum: ["480P", "768P"],
description: RESOLUTION_DESCRIPTION,
},
});
// Hailuo 2.3 and 2.3-Fast allow duration 6 or 10 at 768P or 1080P.
const HAILUO_23_USAGE_SCHEMA = {
seconds: VIDEO_SECONDS_FIELD,
@@ -55,6 +63,13 @@ const HAILUO_01_USAGE_SCHEMA = {
// MiniMax serves MiniMax-H3 on its /v2 video API and every other model on /v1.
const H3_MODEL = "MiniMax-H3";
// The models of that API, their resolutions from the cheapest to the dearest
// (platform.minimax.io/docs/api-reference/video-generation-v2-create).
const H3_SPECS = {
"MiniMax-H3": { minDuration: 4, resolutions: ["768P", "2K"] },
"MiniMax-H3-Max": { minDuration: 5, resolutions: ["480P", "768P"] },
};
const H3_MODELS = Object.keys(H3_SPECS);
const V1_MODELS = [
"MiniMax-Hailuo-2.3",
"MiniMax-Hailuo-2.3-Fast",
@@ -89,17 +104,17 @@ export const meta = {
en: "MiniMax Hailuo video generation (text-to-video, image-to-video, and MiniMax-H3 multimodal reference)",
zh: "MiniMax 海螺视频生成(文生视频、图生视频、MiniMax-H3 多模态参考生视频)",
},
version: "1.4.0",
version: "1.5.0",
author: { name: "QuantumNous" },
channelTypes: [35],
models: [H3_MODEL].concat(V1_MODELS),
models: H3_MODELS.concat(V1_MODELS),
fetchMode: "per_task",
upstreams: ["vendor", "new_api"],
// Fallback for a channel alias that resolves to more than one model: the
// union of every family's fields and resolutions.
usageSchema: Object.assign({}, H3_USAGE_SCHEMA, {
resolution: {
enum: ["512P", "768P", "720P", "1080P", "2K"],
enum: ["480P", "512P", "768P", "720P", "1080P", "2K"],
description: RESOLUTION_DESCRIPTION,
},
}),
@@ -125,6 +140,16 @@ export const meta = {
{ label: "H3 2K 5s · input video", facts: { seconds: 5, resolution: "2K", input_images: 0, input_video_seconds: 15 } },
],
},
{
models: ["MiniMax-H3-Max"],
schema: H3_MAX_USAGE_SCHEMA,
examples: [
{ label: "H3-Max 480P 5s", facts: { seconds: 5, resolution: "480P", input_images: 0, input_video_seconds: 0 } },
{ label: "H3-Max 768P 5s", facts: { seconds: 5, resolution: "768P", input_images: 0, input_video_seconds: 0 } },
{ label: "H3-Max 768P 5s · 9 images", facts: { seconds: 5, resolution: "768P", input_images: 9, input_video_seconds: 0 } },
{ label: "H3-Max 768P 5s · input video", facts: { seconds: 5, resolution: "768P", input_images: 0, input_video_seconds: 15 } },
],
},
{
models: ["MiniMax-Hailuo-2.3", "MiniMax-Hailuo-2.3-Fast"],
schema: HAILUO_23_USAGE_SCHEMA,
@@ -162,7 +187,7 @@ export const meta = {
{ method: "GET", path: "/hailuo/v1/query/video_generation/:task_id", type: "query", render: "taskStatus" },
// The video of a /v1 task, under the file id its query reports.
{ method: "GET", path: "/v1/files/retrieve", type: "query", taskIdParam: "file_id", render: "fileRetrieve" },
{ method: "POST", path: "/v2/video_generation", type: "submit", decode: "createH3Task", render: "taskCreated", models: [H3_MODEL] },
{ method: "POST", path: "/v2/video_generation", type: "submit", decode: "createH3Task", render: "taskCreated", models: H3_MODELS },
{ method: "GET", path: "/v2/query/video_generation/:task_id", type: "query", render: "h3TaskStatus" },
],
protocols: [{ name: "openai_responses", supports: ["stream", "sync", "background"] }, "openai_video"],
@@ -276,27 +301,30 @@ const H3_MAX_INPUT_VIDEO_SECONDS = 15;
// array instead of flat frame fields, an explicit `ratio`, 768P/2K resolutions,
// a task id path parameter on query, and a `{task: {...}}` query envelope.
function isH3(model) {
return model === H3_MODEL;
return H3_MODELS.includes(model);
}
// MiniMax-H3 renders 4 to 15 seconds; the host protocols default to 5.
function h3Duration(raw) {
function h3Duration(raw, model) {
if (raw === undefined || raw === null || raw === "") return H3_DEFAULT_DURATION;
const seconds = Number(raw);
if (!Number.isInteger(seconds) || seconds < H3_MIN_DURATION || seconds > H3_MAX_DURATION) {
throw new Error(H3_MODEL + " duration must be an integer between " + H3_MIN_DURATION + " and " + H3_MAX_DURATION + " seconds");
const minimum = H3_SPECS[model].minDuration;
if (!Number.isInteger(seconds) || seconds < minimum || seconds > H3_MAX_DURATION) {
throw new Error(model + " duration must be an integer between " + minimum + " and " + H3_MAX_DURATION + " seconds");
}
return seconds;
}
function h3Resolution(req) {
function h3Resolution(req, model) {
const metadata = req.metadata || {};
const raw = trimmed(metadata.resolution) || trimmed(req.resolution) || trimmed(req.size);
if (!raw) return "768P";
const value = raw.toUpperCase();
if (value.includes("2K")) return "2K";
if (value.includes("768")) return "768P";
throw new Error(H3_MODEL + " resolution must be 768P or 2K");
const resolutions = H3_SPECS[model].resolutions;
for (const resolution of resolutions) {
if (value.includes(resolution.replace("P", ""))) return resolution;
}
throw new Error(model + " resolution must be " + resolutions.join(" or "));
}
function h3MediaItem(type, url, role) {
@@ -438,14 +466,16 @@ function h3Ratio(req, content) {
// protocols build from prompt, images, size and metadata, with defaults, or a
// native body's own. MiniMax checks a native body; a duration or resolution
// it leaves out or the plugin cannot read is reserved at the dearest.
function h3Request(req) {
function h3Request(req, model) {
const body = req.vendorBody;
if (!body) return { content: h3Content(req), duration: h3Duration(req.duration), resolution: h3Resolution(req) };
if (!body) return { content: h3Content(req), duration: h3Duration(req.duration, model), resolution: h3Resolution(req, model) };
const missing = body.duration === undefined || body.duration === null || body.duration === "";
const resolutions = H3_SPECS[model].resolutions;
const resolution = trimmed(body.resolution).toUpperCase();
return {
content: validateH3Content(body.content),
duration: missing ? H3_MAX_DURATION : h3Duration(body.duration),
resolution: trimmed(body.resolution).toUpperCase() === "768P" ? "768P" : "2K",
duration: missing ? H3_MAX_DURATION : h3Duration(body.duration, model),
resolution: resolutions.includes(resolution) ? resolution : resolutions[resolutions.length - 1],
};
}
@@ -565,7 +595,8 @@ export const native = {
refuseCallback(body);
if (!Array.isArray(body.content)) throw new Error("content must be an array");
const content = validateH3Content(body.content);
h3Duration(body.duration);
// The widest range; the request builder checks the model the channel sends.
h3Duration(body.duration, H3_MODEL);
return { kind: "submit", model: body.model, action: h3HasVisualContent(content) ? "image_to_video" : "text_to_video", requestBody: { model: body.model, vendorBody: body } };
},
// MiniMax answers /v1 with a base_resp envelope and /v2 with a bare task_id.
@@ -627,7 +658,7 @@ export function buildSubmitRequest(ctx) {
const model = ctx.upstreamModel;
const metadata = req.metadata || {};
if (isH3(model)) {
const h3 = h3Request(req);
const h3 = h3Request(req, model);
const content = h3.content;
const h3Body = req.vendorBody
? Object.assign({}, req.vendorBody, { model: model })
@@ -690,7 +721,7 @@ export function extractUsage(ctx) {
const req = ctx.requestBody || {};
const model = ctx.upstreamModel || req.model;
if (isH3(model)) {
const h3 = h3Request(req);
const h3 = h3Request(req, model);
const content = h3.content;
return {
seconds: h3.duration,
@@ -824,7 +855,7 @@ export function extractUsageOnComplete(_task, _taskResult, body) {
if (h3Task) {
const resolution = trimmed(h3Task.resolution).toUpperCase();
const facts = {};
if (resolution === "2K" || resolution === "768P") facts.resolution = resolution;
if (["480P", "768P", "2K"].includes(resolution)) facts.resolution = resolution;
const usage = h3Task.usage && typeof h3Task.usage === "object" && !Array.isArray(h3Task.usage) ? h3Task.usage : {};
const fields = [
{ key: "seconds", value: usage.output_seconds, minimum: H3_MIN_DURATION, maximum: H3_MAX_DURATION, integer: false },
+1 -1
View File
@@ -7,7 +7,7 @@ export const meta = {
en: "Kuaishou Kling video generation (text-to-video and image-to-video)",
zh: "快手可灵视频生成(文生视频、图生视频)",
},
version: "1.2.0",
version: "1.2.1",
author: { name: "QuantumNous" },
channelTypes: [50],
models: ["kling-v2-5-turbo", "kling-v2-6", "kling-v3", "kling-4.0"],
+13 -1
View File
@@ -128,6 +128,16 @@ func (a *Adaptor) ConvertOpenAIResponsesRequest(c *gin.Context, info *relaycommo
return nil, fmt.Errorf("expected Gemini generateContent request, got %T", result.Value)
}
return geminiRequest, nil
case relayconvert.ConverterOpenAIResponsesToClaudeMessages:
result, err := service.ConvertRequestByID(c, info, converter, request)
if err != nil {
return nil, err
}
claudeRequest, ok := result.Value.(*dto.ClaudeRequest)
if !ok {
return nil, fmt.Errorf("expected Anthropic Messages request, got %T", result.Value)
}
return claudeRequest, nil
default:
return nil, fmt.Errorf("converter %q does not support OpenAI Responses requests", converter)
}
@@ -325,7 +335,8 @@ func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycom
case relayconvert.ConverterClaudeMessagesToOpenAIChat,
relayconvert.ConverterGeminiContentToOpenAIChat:
return a.openaiAdaptor.DoResponse(c, resp, info)
case relayconvert.ConverterOpenAIChatToClaudeMessages:
case relayconvert.ConverterOpenAIChatToClaudeMessages,
relayconvert.ConverterOpenAIResponsesToClaudeMessages:
return a.claudeAdaptor.DoResponse(c, resp, info)
case relayconvert.ConverterOpenAIChatToGeminiContent:
return a.geminiAdaptor.DoResponse(c, resp, info)
@@ -540,6 +551,7 @@ func useGeminiStreamGenerateContentURL(parsedURL *url.URL) {
func shouldApplyClaudeHeaders(converter string, info *relaycommon.RelayInfo) bool {
return converter == relayconvert.ConverterOpenAIChatToClaudeMessages ||
converter == relayconvert.ConverterOpenAIResponsesToClaudeMessages ||
(converter == relayconvert.ConverterNone && info != nil && info.RelayFormat == types.RelayFormatClaude)
}
@@ -739,6 +739,107 @@ func TestAdaptorResponsesToGeminiAddsThoughtSignatureForFunctionCallHistory(t *t
assert.Empty(t, geminiReq.Contents[2].Parts[0].ThoughtSignature)
}
// A /v1/responses route to Anthropic Messages converts the request, sends the
// Claude headers and turns the Messages reply, plain or streamed, back into
// OpenAI Responses.
func TestAdaptorResponsesToClaudeMessages(t *testing.T) {
previousTimeout := constant.StreamingTimeout
constant.StreamingTimeout = 30
t.Cleanup(func() { constant.StreamingTimeout = previousTimeout })
config := &dto.AdvancedCustomConfig{
Routes: []dto.AdvancedCustomRoute{
{
IncomingPath: "/v1/responses",
UpstreamPath: "/v1/messages",
Converter: relayconvert.ConverterOpenAIResponsesToClaudeMessages,
Auth: &dto.AdvancedCustomRouteAuth{
Type: dto.AdvancedCustomAuthTypeHeader,
Name: "x-api-key",
Value: "{api_key}",
},
},
},
}
responsesInfo := func(stream bool) *relaycommon.RelayInfo {
info := advancedCustomRelayInfo(config)
info.RelayFormat = types.RelayFormatOpenAIResponses
info.RelayMode = relayconstant.RelayModeResponses
info.RequestURLPath = "/v1/responses"
info.OriginModelName = "claude-test"
info.UpstreamModelName = "claude-test"
info.IsStream = stream
info.DisablePing = true
return info
}
adaptor := &Adaptor{}
info := responsesInfo(false)
c := advancedCustomGinContext("/v1/responses")
converted, err := adaptor.ConvertOpenAIResponsesRequest(c, info, dto.OpenAIResponsesRequest{
Model: "claude-test",
Instructions: mustAdvancedCustomRawMessage(t, "be brief"),
Input: mustAdvancedCustomRawMessage(t, "hello"),
})
require.NoError(t, err)
claudeReq, ok := converted.(*dto.ClaudeRequest)
require.True(t, ok)
assert.Equal(t, "claude-test", claudeReq.Model)
assert.NotNil(t, claudeReq.System)
require.Len(t, claudeReq.Messages, 1)
assert.Equal(t, "user", claudeReq.Messages[0].Role)
requestURL, err := adaptor.GetRequestURL(info)
require.NoError(t, err)
assert.Equal(t, "https://fallback.example/v1/messages", requestURL)
header := http.Header{}
require.NoError(t, adaptor.SetupRequestHeader(c, &header, info))
assert.Equal(t, "sk-test", header.Get("x-api-key"))
assert.Equal(t, "2023-06-01", header.Get("anthropic-version"))
assert.Empty(t, header.Get("Authorization"))
claudeBody := `{"id":"msg_1","type":"message","model":"claude-test","role":"assistant","content":[{"type":"text","text":"hi"}],"stop_reason":"end_turn","usage":{"input_tokens":2,"output_tokens":3}}`
recorder := httptest.NewRecorder()
plain, _ := gin.CreateTestContext(recorder)
plain.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil)
plainAdaptor := &Adaptor{}
usage, apiErr := plainAdaptor.DoResponse(plain, &http.Response{
StatusCode: http.StatusOK,
Header: make(http.Header),
Body: io.NopCloser(strings.NewReader(claudeBody)),
}, responsesInfo(false))
require.Nil(t, apiErr)
assert.Equal(t, 5, usage.(*dto.Usage).TotalTokens)
body := recorder.Body.String()
assert.Contains(t, body, `"object":"response"`)
assert.Contains(t, body, `"type":"output_text"`)
assert.Contains(t, body, `"text":"hi"`)
assert.NotContains(t, body, `"stop_reason"`)
claudeStream := "data: " + `{"type":"message_start","message":{"id":"msg_1","type":"message","model":"claude-test","role":"assistant","content":[],"usage":{"input_tokens":2,"output_tokens":0}}}` + "\n\n" +
"data: " + `{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}` + "\n\n" +
"data: " + `{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi"}}` + "\n\n" +
"data: " + `{"type":"content_block_stop","index":0}` + "\n\n" +
"data: " + `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":3}}` + "\n\n" +
"data: " + `{"type":"message_stop"}` + "\n\n"
streamRecorder := httptest.NewRecorder()
streamCtx, _ := gin.CreateTestContext(streamRecorder)
streamCtx.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil)
streamAdaptor := &Adaptor{}
usage, apiErr = streamAdaptor.DoResponse(streamCtx, &http.Response{
StatusCode: http.StatusOK,
Header: make(http.Header),
Body: io.NopCloser(strings.NewReader(claudeStream)),
}, responsesInfo(true))
require.Nil(t, apiErr)
assert.Equal(t, 5, usage.(*dto.Usage).TotalTokens)
events := streamRecorder.Body.String()
assert.Contains(t, events, `"type":"response.created"`)
assert.Contains(t, events, `"type":"response.output_text.delta"`)
assert.Contains(t, events, `"delta":"hi"`)
assert.Contains(t, events, `"type":"response.completed"`)
assert.NotContains(t, events, `"message_start"`)
}
func TestAdaptorConvertsOpenAIChatRequestToResponsesUpstream(t *testing.T) {
adaptor := &Adaptor{}
info := advancedCustomRelayInfo(&dto.AdvancedCustomConfig{
+1
View File
@@ -382,6 +382,7 @@ func HandleClaudeResponseData(c *gin.Context, info *relaycommon.RelayInfo, claud
claudeInfo.Usage.PromptTokensDetails.CachedCreationTokens = claudeResponse.Usage.CacheCreationInputTokens
claudeInfo.Usage.ClaudeCacheCreation5mTokens = claudeResponse.Usage.GetCacheCreation5mTokens()
claudeInfo.Usage.ClaudeCacheCreation1hTokens = claudeResponse.Usage.GetCacheCreation1hTokens()
claudeInfo.Usage.CompletionTokenDetails.ReasoningTokens = claudeResponse.Usage.GetThinkingTokens()
}
var responseData []byte
switch info.RelayFormat {
+72
View File
@@ -502,3 +502,75 @@ func TestClaudeResponsePassesInputTransformationsThrough(t *testing.T) {
require.Nil(t, HandleStreamResponseData(c, info, &ClaudeResponseInfo{Usage: &dto.Usage{}}, event))
assert.Contains(t, w.Body.String(), "data: "+event+"\n")
}
func TestClaudeThinkingTokensMapToOpenAIReasoningTokens(t *testing.T) {
gin.SetMode(gin.TestMode)
t.Run("non-stream", func(t *testing.T) {
info := &relaycommon.RelayInfo{
RelayFormat: types.RelayFormatOpenAI,
ChannelMeta: &relaycommon.ChannelMeta{UpstreamModelName: "claude-opus-5-5"},
}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
body := `{"id":"msg_1","type":"message","role":"assistant","model":"claude-opus-5-5",` +
`"content":[{"type":"thinking","thinking":"short summary","signature":"sig"},{"type":"text","text":"hi"}],` +
`"stop_reason":"end_turn","usage":{"input_tokens":4,"output_tokens":120,"output_tokens_details":{"thinking_tokens":40}}}`
claudeInfo := &ClaudeResponseInfo{Usage: &dto.Usage{}}
require.Nil(t, HandleClaudeResponseData(c, info, claudeInfo, nil, []byte(body)))
var resp dto.OpenAITextResponse
require.NoError(t, common.Unmarshal(w.Body.Bytes(), &resp))
assert.Equal(t, 120, resp.Usage.CompletionTokens)
assert.Equal(t, 40, resp.Usage.CompletionTokenDetails.ReasoningTokens)
})
t.Run("stream message_delta", func(t *testing.T) {
claudeInfo := &ClaudeResponseInfo{Usage: &dto.Usage{PromptTokens: 4, CompletionTokens: 2}}
ok := FormatClaudeResponseInfo(&dto.ClaudeResponse{
Type: "message_delta",
Usage: &dto.ClaudeUsage{
OutputTokens: 300,
OutputTokensDetails: &dto.ClaudeOutputTokensDetails{ThinkingTokens: 75},
},
}, nil, claudeInfo)
require.True(t, ok)
usage := buildOpenAIStyleUsageFromClaudeUsage(claudeInfo.Usage)
assert.Equal(t, 300, usage.CompletionTokens)
assert.Equal(t, 75, usage.CompletionTokenDetails.ReasoningTokens)
})
t.Run("stream message_delta reported zero replaces, absent keeps", func(t *testing.T) {
for _, tc := range []struct {
name string
details *dto.ClaudeOutputTokensDetails
want int
}{
{name: "explicit zero", details: &dto.ClaudeOutputTokensDetails{ThinkingTokens: 0}, want: 0},
{name: "absent", details: nil, want: 40},
} {
claudeInfo := &ClaudeResponseInfo{Usage: &dto.Usage{PromptTokens: 4, CompletionTokens: 50}}
claudeInfo.Usage.CompletionTokenDetails.ReasoningTokens = 40
require.True(t, FormatClaudeResponseInfo(&dto.ClaudeResponse{
Type: "message_delta",
Usage: &dto.ClaudeUsage{OutputTokens: 120, OutputTokensDetails: tc.details},
}, nil, claudeInfo))
assert.Equal(t, tc.want, claudeInfo.Usage.CompletionTokenDetails.ReasoningTokens, tc.name)
}
})
t.Run("bounded by output_tokens", func(t *testing.T) {
for _, tc := range []struct{ thinking, output, want int }{
{thinking: 500, output: 100, want: 100},
{thinking: -5, output: 100, want: 0},
} {
usage := relayconvert.UsageFromClaudeAPIUsage(&dto.ClaudeUsage{
InputTokens: 1,
OutputTokens: tc.output,
OutputTokensDetails: &dto.ClaudeOutputTokensDetails{ThinkingTokens: tc.thinking},
})
assert.Equal(t, tc.want, usage.CompletionTokenDetails.ReasoningTokens)
}
})
}
Loaded 100 of 168 files, more files were not shown because too many files have changed in this diff. Show more