Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions controller/relay_task_plugin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -652,6 +652,22 @@ export function buildQueryRequest(){throw new Error("completed submissions must
}
}

func TestPassthroughSubmitKeepsAuthErrorRetry(t *testing.T) {
c := taskSubmissionTestContext()
unauthorized := &dto.TaskError{StatusCode: http.StatusUnauthorized}
forbidden := &dto.TaskError{StatusCode: http.StatusForbidden}
assert.Equal(t, "retry", decideTaskRetry(c, unauthorized, 1).Action)
assert.Equal(t, "retry", decideTaskRetry(c, forbidden, 1).Action)
c.Set(pluginruntime.ContextKeyPinnedRoute, pluginruntime.PinnedRoute{
Route: pluginruntime.Route{UpstreamError: pluginruntime.RouteUpstreamErrorPassthrough},
})
assert.Equal(t, "retry", decideTaskRetry(c, unauthorized, 1).Action)
assert.Equal(t, "retry", decideTaskRetry(c, forbidden, 1).Action)
assert.Equal(t, service.PolicyDecision{Action: "stop", Reason: "status_not_retryable", Source: "system"}, decideTaskRetry(c, &dto.TaskError{StatusCode: http.StatusBadRequest}, 1))
assert.Equal(t, "retry", decideTaskRetry(c, &dto.TaskError{StatusCode: http.StatusTooManyRequests}, 1).Action)
assert.Equal(t, "retry", decideTaskRetry(c, &dto.TaskError{StatusCode: http.StatusInternalServerError}, 1).Action)
}

func TestAcceptedSubmitStreamNeverRetries(t *testing.T) {
c := taskSubmissionTestContext()
assert.Equal(t, service.PolicyDecision{Action: "stop", Reason: "task_accepted", Source: "system"}, decideTaskRetry(c, &dto.TaskError{StatusCode: 502, LocalError: true, NoRetry: true}, 3))
Expand Down
8 changes: 4 additions & 4 deletions docs/plugin-api/v1.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export interface ProtocolDecodeContext extends NativeDecodeContext {protocol: Pr
export type SubmitIntent = {kind: "submit"; model: string; action?: string; requestBody?: unknown; originTaskIds?: readonly string[]};
export type QueryIntent = {kind: "query"; taskIds: readonly string[]};
export type TaskIntent = SubmitIntent | QueryIntent;
export interface NativeRoute {method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; /** The vendor's own path; the host also serves it under /{key} unless its first segment is the key or a proper prefix of it. */ path: string; type: "submit" | "query" | "dynamic"; action?: string; /** Query routes: the path parameter carrying the gateway task id or, when the path has none, the query-string parameter of that name. Default "task_id". */ taskIdParam?: string; decode?: string; render: string; models?: readonly string[]; retainResult?: boolean}
export interface NativeRoute {method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; /** The vendor's own path; the host also serves it under /{key} unless its first segment is the key or a proper prefix of it. */ path: string; type: "submit" | "query" | "dynamic"; action?: string; /** Query routes: the path parameter carrying the gateway task id or, when the path has none, the query-string parameter of that name. Default "task_id". */ taskIdParam?: string; decode?: string; render: string; models?: readonly string[]; retainResult?: boolean; /** Dynamic routes only. "collect" renders found tasks and reports the rest on ctx.missedTaskIds. On a shared path, a batch split across plugins is not found. */ missing?: "collect"; /** Submit routes only. "passthrough" gives the error presenter the vendor's non-2xx status, body, and Retry-After. */ upstreamError?: "passthrough"}
export type ProtocolName = "openai_responses" | "openai_video" | "openai_image";
export type ResponsesMode = "stream" | "sync" | "background";
export type ProtocolClaim =
Expand Down Expand Up @@ -124,11 +124,11 @@ export interface UpstreamResponse {statusCode: number; headers: Readonly<Record<
export interface NormalizedTaskResult {taskId?: string; status: "NOT_START" | "SUBMITTED" | "QUEUED" | "IN_PROGRESS" | "SUCCESS" | "FAILURE" | "UNKNOWN"; progress?: string; reason?: string; url?: string; remoteUrl?: string; completionTokens?: number; totalTokens?: number}
export interface TaskArtifact {key: string; type: "video" | "audio" | "image" | "file"; mimeType?: string}
export declare const meta: Meta;
/** A query presenter's context: artifacts holds the gateway download addresses of one task in SUCCESS (from listArtifacts) and is empty otherwise. Throwing "artifact_not_found" answers 404. */
export interface NativeQueryContext extends NativeDecodeContext {artifacts: Readonly<Record<string, {key: string; type: string; url: string; mimeType?: string}>>}
/** A query presenter's context: artifacts holds the gateway download addresses of one task in SUCCESS (from listArtifacts) and is empty otherwise. Throwing "artifact_not_found" answers 404. missedTaskIds is set only for a dynamic route that declares missing: "collect". */
export interface NativeQueryContext extends NativeDecodeContext {artifacts: Readonly<Record<string, {key: string; type: string; url: string; mimeType?: string}>>; missedTaskIds?: readonly string[]}
/** A native presenter's reply with the vendor's own HTTP status (200–599); only Location and Retry-After may be set, and a reply without __body has no body. Any other value is the JSON body of a 200 reply, or of the host's status for the error presenter. */
export type NativeReply = {__status: number; __headers?: {Location?: string; "Retry-After"?: string}; __body?: unknown};
export declare const native: Record<string, ((ctx: NativeDecodeContext) => TaskIntent) | ((ctx: NativeQueryContext, task: TaskView | readonly TaskView[]) => unknown | NativeReply)> & {error?: (ctx: NativeDecodeContext, error: {code: string; message: string; httpStatus: number; retryable: boolean; requestId: string}) => unknown | NativeReply};
export declare const native: Record<string, ((ctx: NativeDecodeContext) => TaskIntent) | ((ctx: NativeQueryContext, task: TaskView | readonly TaskView[]) => unknown | NativeReply)> & {error?: (ctx: NativeDecodeContext, error: {code: string; message: string; httpStatus: number; retryable: boolean; requestId: string; upstream?: {status: number; body: unknown; retryAfter?: string}}) => unknown | NativeReply};
export declare const protocols: {
openai_responses?: {decodeRequest(ctx: ProtocolDecodeContext): SubmitIntent; renderEvents?(ctx: unknown, task: TaskView, previousState: unknown): unknown; renderFinal?(ctx: unknown, task: TaskView): unknown};
openai_video?: {decodeRequest(ctx: ProtocolDecodeContext): SubmitIntent; render(ctx: unknown, task: TaskView): unknown};
Expand Down
6 changes: 5 additions & 1 deletion docs/plugin-api/v1.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,16 @@ export const meta = {

A plugin declares its vendor's own paths. The gateway serves each route at that path and again under `/{key}`: doubao's `POST /api/v3/contents/generations/tasks` is also `POST /doubao/api/v3/contents/generations/tasks`, which reaches doubao alone. A route whose first segment is the key, or a proper prefix of it, is already the plugin's own address and gets no copy: alibaba's `/ali/...`, sunoapi's `/suno/...`, `/hailuo/...` for hailuo. The own prefixes of the built-in plugins are protected: another plugin may not take one as its key, and its top-level routes under one are not served.

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.
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. `missing: "collect"` still requires that plugin to own every id any candidate can retrieve. 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[].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[].missing` is the optional string `"collect"` on a `dynamic` route. A query intent on that route renders the tasks this caller can retrieve and passes the other public ids, in request order and without duplicates, as `ctx.missedTaskIds` (an empty array when every id was found). A task owned by someone else, or one whose result was discarded, is missed the same way as an unknown id. On a path several plugins declare, the first plugin that can retrieve every id any of them can retrieve answers and reports the rest as missed. A batch split across those plugins, and a batch none of them can retrieve, are not found. Each plugin's own `/{key}` address still collects either batch. Without the field, any missing id fails the whole request with 404, which remains the behavior of every route that does not declare it. `submit` and `query` routes reject the field.

`routes[].upstreamError` is the optional string `"passthrough"` on a `submit` route. A non-2xx upstream response is still a failed submission: the reservation is refunded and `parseSubmitResponse` does not run. The error presenter additionally receives `error.upstream` as `{status, body, retryAfter?}`, where `body` is the parsed JSON value when the response is JSON and the raw text otherwise, and `retryAfter` is the vendor's `Retry-After` header when it sent one. The presenter can answer with a reply wrapper using that status, body, and header. The field does not change which statuses the gateway retries: `400` and `408` still stop, while `401`, `403`, `429`, and `5xx` keep the usual retry budget so another channel can be tried. The response the client finally sees is whatever the presenter returns for the last attempt. Routes that omit the field keep the sanitized gateway error and do not receive `error.upstream`. `query` and `dynamic` routes reject the field. Both fields are additive apiVersion 1 extensions: older hosts reject the unknown field.

`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.

Each `protocols` entry claims a host protocol. A protocol that defines modes must be claimed in object form with an explicit `supports`; the bare-string form is valid only for protocols without modes (`openai_video`, `openai_image`). `supports` declares which client request forms the plugin accepts on `openai_responses`: `"stream"` (`stream: true`), `"sync"` (neither flag; the call blocks until the terminal Response), `"background"` (`background: true`; the create returns a pending Response immediately). An unsupported request form is rejected with a 400 at channel selection, before any plugin hook runs and before billing. Retrieval (`GET /v1/responses/:response_id`) is not a mode: every created response is always retrievable.
Expand Down
2 changes: 1 addition & 1 deletion docs/plugin-api/v1.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@
"maxBytes": {"type": "integer", "exclusiveMinimum": 0}
}
},
"route": {"type": "object", "additionalProperties": false, "required": ["method", "path", "type", "render"], "properties": {"method": {"enum": ["GET", "POST", "PUT", "PATCH", "DELETE"]}, "path": {"type": "string", "pattern": "^/"}, "type": {"enum": ["submit", "query", "dynamic"]}, "action": {"type": "string"}, "taskIdParam": {"type": "string"}, "retainResult": {"type": "boolean"}, "decode": {"type": "string"}, "render": {"type": "string"}, "models": {"type": "array", "minItems": 1, "uniqueItems": true, "items": {"type": "string", "minLength": 1}}}, "allOf": [{"if": {"properties": {"type": {"const": "query"}}}, "then": {"allOf": [{"not": {"required": ["decode"]}}, {"not": {"required": ["models"]}}, {"not": {"required": ["retainResult"]}}]}}, {"if": {"properties": {"type": {"enum": ["submit", "dynamic"]}}}, "then": {"required": ["decode"]}}]},
"route": {"type": "object", "additionalProperties": false, "required": ["method", "path", "type", "render"], "properties": {"method": {"enum": ["GET", "POST", "PUT", "PATCH", "DELETE"]}, "path": {"type": "string", "pattern": "^/"}, "type": {"enum": ["submit", "query", "dynamic"]}, "action": {"type": "string"}, "taskIdParam": {"type": "string"}, "retainResult": {"type": "boolean"}, "missing": {"const": "collect"}, "upstreamError": {"const": "passthrough"}, "decode": {"type": "string"}, "render": {"type": "string"}, "models": {"type": "array", "minItems": 1, "uniqueItems": true, "items": {"type": "string", "minLength": 1}}}, "allOf": [{"if": {"properties": {"type": {"const": "query"}}}, "then": {"allOf": [{"not": {"required": ["decode"]}}, {"not": {"required": ["models"]}}, {"not": {"required": ["retainResult"]}}, {"not": {"required": ["missing"]}}, {"not": {"required": ["upstreamError"]}}]}}, {"if": {"properties": {"type": {"const": "submit"}}}, "then": {"not": {"required": ["missing"]}}}, {"if": {"properties": {"type": {"const": "dynamic"}}}, "then": {"not": {"required": ["upstreamError"]}}}, {"if": {"properties": {"type": {"enum": ["submit", "dynamic"]}}}, "then": {"required": ["decode"]}}]},
"relayRoute": {
"type": "object",
"additionalProperties": false,
Expand Down
24 changes: 17 additions & 7 deletions dto/task.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,25 @@ import (
"encoding/json"
)

// TaskUpstreamReply is a vendor's non-2xx submit response kept for a route
// that declares upstreamError passthrough. It is not part of the JSON body
// the gateway writes for every other task error.
type TaskUpstreamReply struct {
StatusCode int
Body []byte
RetryAfter string
}

type TaskError struct {
// NoRetry prevents duplicate upstream work after a response has been accepted.
NoRetry bool `json:"-"`
Code string `json:"code"`
Message string `json:"message"`
Data any `json:"data"`
StatusCode int `json:"-"`
LocalError bool `json:"-"`
Error error `json:"-"`
NoRetry bool `json:"-"`
Code string `json:"code"`
Message string `json:"message"`
Data any `json:"data"`
StatusCode int `json:"-"`
LocalError bool `json:"-"`
Error error `json:"-"`
UpstreamReply *TaskUpstreamReply `json:"-"`
}

type TaskData interface {
Expand Down
Loading