Files
YMeng-CC-New-API/controller/plugin_protocol_sdk_test.go
Calcium-Ion c59f6fd553 feat(plugins): serve task plugins at the vendors' own paths and answer as the vendors do (#8117)
* feat(plugins): serve task plugins at the vendors' own paths

A vendor SDK or plain HTTP client can now point at the gateway and keep the
vendor's official paths. Every plugin route is also served under
/{plugin key}, and that address always runs that plugin.

- Plugins declare the vendor's official paths and the gateway adds the
  /{key} copy. Existing prefixed addresses keep working, including /ali
  for Alibaba Bailian.
- Several plugins may declare the same path. A submit runs on the plugin
  whose channel is selected; a query is answered by the plugin that owns
  the task.
- Under the gateway's own path segments (/api, /v1, /v1beta and so on)
  only built-in plugins get top-level paths; other plugins are served at
  their /{key} address. Plugin keys cannot reuse these segments.
- Jimeng uses the official Bearer API (/api/common/v3/submit_task_v2 and
  get_result_v2). The /jimeng/ route, which requests could not reach, is
  removed.
- MiniMax supports the official v1 query with ?task_id= and
  /v1/files/retrieve. The unimplemented GET /v1/files/{id} placeholder is
  removed. Vertex AI also accepts v1beta1 paths.
- Vidu routes accept Authorization: Token, and Google routes accept
  x-goog-api-key and ?key=. The key is redacted from logs.
- Gemini Veo results are read from generatedSamples, so their videos
  download again. Vertex AI videos returned inline are fetched again when
  downloaded.
- GET /v1/videos/{id} answers tasks created on xAI's routes in xAI's
  format, and :predictLongRunning requests reach the Veo plugin.
- Enabling, activating or promoting a plugin version is refused when it
  conflicts with another plugin, and force no longer skips that check.
- The plugin page lists each endpoint once, with a switch between the
  vendor path and the /{key} address. Legacy addresses are folded away.

* fix(logging): use the shared query credential masking for key=

The access log already masks credentials passed in the query string,
key included. A second redaction for the Gemini ?key= form rewrote it to
key=[REDACTED], so the log showed two masking styles and the masking
tests failed. Only the shared masking remains.

The Gemini native routes take ?key= out of the URL. With no query left,
the log fell back to the path gin recorded on arrival, which still
carried the key. The log now writes the path alone in that case, and the
plugin API document no longer says the key is logged as key=[REDACTED].

* feat(plugins): answer native plugin routes as the vendors do

A request sent to a vendor's own path now reaches the vendor as the client
wrote it, and the client gets the vendor's reply shape and status. The
gateway answers a native request with its own 400 only when it cannot tell
the model, cannot price the request, or cannot provide the feature; the
vendor checks everything else.

- New gateway rejections of that kind on native routes: callback_url on
  Ark, Kling, Vidu and MiniMax; Kling external_task_id and a body with
  model but no model_name; xAI storage_options, which was dropped
  silently; and for Jimeng, req_json on get_result_v2, a req_key the
  plugin cannot price, and frames other than 121 or 241. A value the
  plugin cannot read reserves the model's dearest tier, and settlement is
  unchanged.
- Native bodies are sent as the client wrote them. Plugins no longer fill
  in MiniMax-H3's duration, resolution and ratio or Vidu's
  movement_amplitude and images: null, drop Vidu's bgm: false, turn
  Jimeng's image and images into image_urls, or merge Ark's content.
  Kling requests no longer carry an added aspect_ratio 1:1, cfg_scale 0.5
  or model field; without a size Kling uses its own 16:9. DashScope
  requests go to the endpoint the client called.
- Replies keep each vendor's shapes and error codes. A native presenter
  may answer with the vendor's own status through a reply wrapper
  ({__status, __headers, __body}): xAI answers a pending video with 202,
  DashScope an unknown task with 200 UNKNOWN. A task the gateway failed
  shows as failed instead of still running. xAI's native query shows a
  video that failed but was charged as failed with xAI's usage, instead of
  done; billing is unchanged.
- A native client that asks the vendor for a stream (Seedream with
  stream: true, Wan interleaved output with X-DashScope-Sse: enable) gets
  the vendor's events as they arrive. Once an event has reached the
  client the task settles and is never refunded: a finished stream bills
  what was delivered, and a stream that stopped early bills the
  reservation and cuts the client's connection, so a downstream gateway
  keeps its reservation too. The client leaving does not cancel the
  upstream request, which TASK_PLUGIN_PROTOCOL_TIMEOUT_SECONDS bounds. A
  JSON reply from an older new-api upstream is still accepted.
- Routes that keep no result (retainResult: false) accept replies up to
  MAX_FILE_DOWNLOAD_MB, so b64_json images fit.
- Native decoders get the client's request headers, without gateway
  credentials, as ctx.requestHeaders.
- Native routes accept a channel's model aliases and case variants of
  model names, as the gateway's own formats do, also on routes that list
  their models.
- Kling lists kling-v2-5-turbo, kling-v2-6 and kling-v3, priced in units
  per mode, sound and voice; Kling retired kling-v1, kling-v1-6 and
  kling-v2-master on 2026-09-15. Vidu lists its current models, from
  viduq4-preview to vidu1.5.
- Clients of /v1/videos and the other gateway formats can no longer pass
  a native body through the field the plugins use for it internally.

* feat(plugins): add Kling 4.0 to the kling plugin

Kling 4.0 takes the model in the path and has its own request shape, so
the plugin serves POST /text-to-video/kling-4.0, /image-to-video/kling-4.0
and /omni-video/kling-4.0 as native routes, and answers GET
/tasks?task_ids= for their tasks. /v1/videos and the Responses API send
kling-4.0 as text-to-video or image-to-video, with size picking 720p or
1080p.

Billing follows Kling's price list: units per output second by
resolution, or, with an input video, twice the output, or input plus
output when the input is longer. Kling picks the length when the request
has none and only Kling knows how long an input video is, so the
reservation covers the longest of each. A task settles on the units Kling
deducted, or, when Kling took cash, on the durations it reports.

Kling 4.0 Flash has no published price yet and is left out.

* chore(plugins): bump the task plugins this branch changes

Each of these plugins now declares its vendor's own paths and answers
native requests as the vendor does; kling also adds Kling 4.0. That is
new behavior in every one of them, so each takes a minor version:
alibaba 1.5.0, doubao 1.4.0, google 1.2.0, hailuo 1.4.0, jimeng 1.2.0,
kling 1.2.0, vertex-ai 1.2.0, vidu 1.2.0 and xai 1.2.0.
2026-10-30 21:28:16 +08:00

306 lines
11 KiB
Go

package controller
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/model"
pluginruntime "github.com/QuantumNous/new-api/pkg/jsplugin"
builtinplugins "github.com/QuantumNous/new-api/plugins"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/gin-gonic/gin"
"github.com/openai/openai-go"
"github.com/openai/openai-go/option"
"github.com/openai/openai-go/responses"
"github.com/openai/openai-go/shared"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestTaskPluginResponsesNonStreamDecodesWithOfficialGoSDK(t *testing.T) {
pinned := compilePluginProtocolTestEndpoint(t, "official-sdk-non-stream", `
export const protocols = {openai_responses: {
renderEvents: function() { throw new Error("non-stream called renderEvents"); },
renderFinal: function() {
return {
output: [{
type: "message",
status: "completed",
role: "assistant",
content: [{
type: "output_text",
text: "official-sdk-final",
annotations: [],
logprobs: []
}]
}]
};
}
}};
`)
deps := pluginProtocolTestDeps()
deps.submit = func(_ *gin.Context, info *relaycommon.RelayInfo) (*taskSubmissionOutcome, *dto.TaskError) {
return pluginProtocolTestOutcome(info, pinned.Plugin.Meta.Key, "task_sdk_final", nil), nil
}
deps.loadTask = func(context.Context, int, constant.TaskPlatform, string) (*model.Task, bool, error) {
return &model.Task{
TaskID: "task_sdk_final",
UserId: 71,
Platform: constant.TaskPlatform(pinned.Plugin.Meta.Key),
Status: model.TaskStatusSuccess,
}, true, nil
}
server := newPluginProtocolSDKTestServer(t, pinned, deps)
defer server.Close()
client := openai.NewClient(
option.WithAPIKey("test-key"),
option.WithBaseURL(server.URL+"/v1/"),
option.WithMaxRetries(0),
)
requestContext, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
response, err := client.Responses.New(requestContext, responses.ResponseNewParams{
Model: shared.ResponsesModel("video-model"),
Input: responses.ResponseNewParamsInputUnion{
OfString: openai.String("create a video"),
},
})
require.NoError(t, err)
assert.Equal(t, "resp_sdk_final", response.ID)
assert.Equal(t, responses.ResponseStatusCompleted, response.Status)
assert.Equal(t, "video-model", response.Model)
assert.Equal(t, "official-sdk-final", response.OutputText())
assert.Equal(t, "task_sdk_final", response.Metadata["task_id"])
}
func TestTaskPluginResponsesStreamDecodesWithOfficialGoSDK(t *testing.T) {
pinned := compilePluginProtocolTestEndpoint(t, "official-sdk-stream", `
export const protocols = {openai_responses: {
renderEvents: function() {
return {events: [{type: "output", data: "official-sdk-stream"}], done: true};
},
renderFinal: function() { throw new Error("stream called renderFinal"); }
}};
`)
deps := pluginProtocolTestDeps()
deps.submit = func(_ *gin.Context, info *relaycommon.RelayInfo) (*taskSubmissionOutcome, *dto.TaskError) {
return pluginProtocolTestOutcome(info, pinned.Plugin.Meta.Key, "task_sdk_stream", nil), nil
}
deps.loadTask = func(context.Context, int, constant.TaskPlatform, string) (*model.Task, bool, error) {
return &model.Task{
TaskID: "task_sdk_stream",
UserId: 71,
Platform: constant.TaskPlatform(pinned.Plugin.Meta.Key),
Status: model.TaskStatusSuccess,
}, true, nil
}
server := newPluginProtocolSDKTestServer(t, pinned, deps)
defer server.Close()
client := openai.NewClient(
option.WithAPIKey("test-key"),
option.WithBaseURL(server.URL+"/v1/"),
option.WithMaxRetries(0),
)
requestContext, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
stream := client.Responses.NewStreaming(requestContext, responses.ResponseNewParams{
Model: shared.ResponsesModel("video-model"),
Input: responses.ResponseNewParamsInputUnion{
OfString: openai.String("create a video"),
},
})
defer stream.Close()
eventTypes := make([]string, 0, 8)
sequenceNumbers := make([]int64, 0, 8)
var completedText string
for stream.Next() {
event := stream.Current()
eventTypes = append(eventTypes, event.Type)
sequenceNumbers = append(sequenceNumbers, event.SequenceNumber)
if event.Type == "response.completed" {
completedText = event.Response.OutputText()
}
}
require.NoError(t, stream.Err())
assert.Equal(t, []string{
"response.created",
"response.output_item.added",
"response.content_part.added",
"response.output_text.delta",
"response.output_text.done",
"response.content_part.done",
"response.output_item.done",
"response.completed",
}, eventTypes)
assert.Equal(t, []int64{0, 1, 2, 3, 4, 5, 6, 7}, sequenceNumbers)
assert.Equal(t, "official-sdk-stream", completedText)
}
func TestBuiltInKlingResponsesNonStreamDecodesWithOfficialGoSDK(t *testing.T) {
pinned, deps := builtInKlingProtocolSDKFixture(t, "task_kling_sdk_final")
server := newPluginProtocolSDKTestServer(t, pinned, deps)
defer server.Close()
client := openai.NewClient(
option.WithAPIKey("test-key"),
option.WithBaseURL(server.URL+"/v1/"),
option.WithMaxRetries(0),
)
requestContext, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
response, err := client.Responses.New(requestContext, responses.ResponseNewParams{
Model: shared.ResponsesModel("kling-v3"),
Input: responses.ResponseNewParamsInputUnion{
OfString: openai.String("camera orbit"),
},
})
require.NoError(t, err)
assert.Equal(t, responses.ResponseStatusCompleted, response.Status)
assert.Equal(t, "kling-v3", response.Model)
assert.Contains(t, response.OutputText(), "https://gateway.example/v1/tasks/task_kling_sdk_final/artifacts/video/content")
assert.NotContains(t, response.OutputText(), "upstream.example")
assert.Equal(t, "kling", response.Metadata["vendor"])
assert.Equal(t, "task_kling_sdk_final", response.Metadata["task_id"])
}
func TestBuiltInKlingResponsesStreamDecodesWithOfficialGoSDK(t *testing.T) {
pinned, deps := builtInKlingProtocolSDKFixture(t, "task_kling_sdk_stream")
server := newPluginProtocolSDKTestServer(t, pinned, deps)
defer server.Close()
client := openai.NewClient(
option.WithAPIKey("test-key"),
option.WithBaseURL(server.URL+"/v1/"),
option.WithMaxRetries(0),
)
requestContext, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
stream := client.Responses.NewStreaming(requestContext, responses.ResponseNewParams{
Model: shared.ResponsesModel("kling-v3"),
Input: responses.ResponseNewParamsInputUnion{
OfString: openai.String("camera orbit"),
},
})
defer stream.Close()
eventTypes := make([]string, 0, 8)
sequenceNumbers := make([]int64, 0, 8)
var completedText string
for stream.Next() {
event := stream.Current()
eventTypes = append(eventTypes, event.Type)
sequenceNumbers = append(sequenceNumbers, event.SequenceNumber)
if event.Type == "response.completed" {
completedText = event.Response.OutputText()
}
}
require.NoError(t, stream.Err())
assert.Equal(t, []string{
"response.created",
"response.output_item.added",
"response.content_part.added",
"response.output_text.delta",
"response.output_text.done",
"response.content_part.done",
"response.output_item.done",
"response.completed",
}, eventTypes)
assert.Equal(t, []int64{0, 1, 2, 3, 4, 5, 6, 7}, sequenceNumbers)
assert.Contains(t, completedText, "https://gateway.example/v1/tasks/task_kling_sdk_stream/artifacts/video/content")
assert.NotContains(t, completedText, "upstream.example")
}
func builtInKlingProtocolSDKFixture(t *testing.T, taskID string) (pluginruntime.PinnedEndpoint, pluginProtocolBridgeDeps) {
t.Helper()
source, err := builtinplugins.Source("kling")
require.NoError(t, err)
registry := pluginruntime.NewRegistry()
plugin, err := registry.RegisterFactory(source, pluginruntime.Options{Key: "kling"})
require.NoError(t, err)
binding, found := registry.Generation().LookupEndpoint(http.MethodPost, "/v1/responses", "kling-v3")
require.True(t, found)
pinned := pluginruntime.PinnedEndpoint{
Generation: registry.Generation(),
Plugin: plugin,
Protocol: binding.Protocol,
Operation: binding.Operation,
Model: binding.Model,
Candidates: []pluginruntime.ProtocolBinding{binding},
}
deps := pluginProtocolTestDeps()
deps.submit = func(_ *gin.Context, info *relaycommon.RelayInfo) (*taskSubmissionOutcome, *dto.TaskError) {
return pluginProtocolTestOutcome(info, plugin.Meta.Key, taskID, nil), nil
}
deps.loadTask = func(context.Context, int, constant.TaskPlatform, string) (*model.Task, bool, error) {
task := &model.Task{
TaskID: taskID, Platform: constant.TaskPlatform(plugin.Meta.Key), UserId: 71,
Status: model.TaskStatusSuccess, Progress: "100%", CreatedAt: 1_710_000_000,
}
task.SetData(map[string]any{
"code": 0,
"data": map[string]any{
"task_id": "upstream-private",
"task_status": "succeed",
"task_result": map[string]any{
"videos": []any{map[string]any{"url": "https://upstream.example/private-video.mp4"}},
},
},
})
return task, true, nil
}
deps.artifactContentURL = func(publicTaskID, artifactKey string) (string, error) {
return "https://gateway.example/v1/tasks/" + publicTaskID + "/artifacts/" + artifactKey + "/content", nil
}
return pinned, deps
}
func newPluginProtocolSDKTestServer(
t *testing.T,
pinned pluginruntime.PinnedEndpoint,
deps pluginProtocolBridgeDeps,
) *httptest.Server {
t.Helper()
return httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
if request.Method != http.MethodPost || request.URL.Path != "/v1/responses" {
http.NotFound(writer, request)
return
}
var requestBody map[string]any
if err := common.DecodeJson(request.Body, &requestBody); err != nil {
http.Error(writer, "invalid request", http.StatusBadRequest)
return
}
modelName, _ := requestBody["model"].(string)
stream, _ := requestBody["stream"].(bool)
c, _ := gin.CreateTestContext(writer)
c.Request = request
common.SetContextKey(c, constant.ContextKeyUserId, 71)
common.SetContextKey(c, constant.ContextKeyTokenId, 81)
common.SetContextKey(c, constant.ContextKeyUsingGroup, "default")
c.Set("resolved_task_model", modelName)
c.Set(pluginruntime.ContextKeyProtocolRequest, pluginruntime.ProtocolRequestContext{
RouteRequestContext: pluginruntime.RouteRequestContext{
Path: request.URL.Path,
Method: request.Method,
Params: map[string]string{},
Query: request.URL.Query(),
RequestBody: requestBody,
},
Protocol: pinned.Protocol,
Stream: stream,
})
serveTaskPluginProtocol(c, pinned, deps)
}))
}