Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 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. */ 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
4 changes: 4 additions & 0 deletions docs/plugin-api/v1.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ Routes stay out of the reserved namespaces `/v1/tasks`, `/assets` and the consol

`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. 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
58 changes: 46 additions & 12 deletions middleware/task_plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -1478,20 +1478,30 @@ func renderTaskPluginQuery(
for _, task := range tasks {
tasksByID[task.TaskID] = task
}
collectMissing := multiple && pinned.Route.Missing == pluginruntime.RouteMissingCollect
views := make([]dto.TaskView, 0, len(taskIDs))
var missed []string
seenMissed := map[string]struct{}{}
for _, taskID := range taskIDs {
task := tasksByID[taskID]
if task == nil || !task.ResultRetrievable() {
logger.LogDebug(
c,
"task_plugin subsystem=query event=lookup_failed generation=%d plugin=%q reason=task_not_found requested=%d found=%d",
generation,
pinned.Plugin.Meta.Key,
len(taskIDs),
len(tasks),
)
abortTaskPluginRouteError(c, http.StatusNotFound)
return
if !collectMissing {
logger.LogDebug(
c,
"task_plugin subsystem=query event=lookup_failed generation=%d plugin=%q reason=task_not_found requested=%d found=%d",
generation,
pinned.Plugin.Meta.Key,
len(taskIDs),
len(tasks),
)
abortTaskPluginRouteError(c, http.StatusNotFound)
return
}
if _, seen := seenMissed[taskID]; !seen {
seenMissed[taskID] = struct{}{}
missed = append(missed, taskID)
}
continue
}
view, viewErr := service.BuildTaskPluginView(task)
if viewErr != nil {
Expand Down Expand Up @@ -1523,6 +1533,12 @@ func renderTaskPluginQuery(
}
}
presenterContext["artifacts"] = artifacts
if collectMissing {
if missed == nil {
missed = []string{}
}
presenterContext["missedTaskIds"] = missed
}
renderStarted := time.Now()
result, err := pinned.Plugin.Engine.CallPath(c.Request.Context(), "native", []string{renderer}, presenterContext, pluginruntime.RawJSON(encoded))
if err != nil {
Expand Down Expand Up @@ -1629,6 +1645,20 @@ func WriteNativeReply(c *gin.Context, status int, value any) error {
return nil
}

// taskUpstreamErrorValue is the vendor response a passthrough submit route's
// error presenter reads. A JSON body stays a value; anything else stays text.
func taskUpstreamErrorValue(reply *dto.TaskUpstreamReply) map[string]any {
var body any
if len(strings.TrimSpace(string(reply.Body))) > 0 && common.Unmarshal(reply.Body, &body) != nil {
body = string(reply.Body)
}
value := map[string]any{"status": reply.StatusCode, "body": body}
if reply.RetryAfter != "" {
value["retryAfter"] = reply.RetryAfter
}
return value
}

// RespondTaskPluginError gives a pinned plugin a sanitized error DTO and writes
// its native error body with the host's status, unless the body is a reply
// wrapper that answers with the vendor's own status.
Expand All @@ -1652,13 +1682,17 @@ func RespondTaskPluginError(c *gin.Context, taskErr *dto.TaskError) bool {
requestValue, exists := c.Get(pluginruntime.ContextKeyRouteRequest)
requestContext, ok := requestValue.(pluginruntime.RouteRequestContext)
if err == nil && hasRenderer && exists && ok {
body, callErr := pinned.Plugin.Engine.CallMember(c.Request.Context(), "native", "error", requestContext.JSValue(), map[string]any{
errorValue := map[string]any{
"code": sanitized.Code,
"message": sanitized.Message,
"httpStatus": sanitized.HTTPStatus,
"retryable": sanitized.Retryable,
"requestId": requestID,
})
}
if pinned.Route.UpstreamError == pluginruntime.RouteUpstreamErrorPassthrough && taskErr.UpstreamReply != nil {
errorValue["upstream"] = taskUpstreamErrorValue(taskErr.UpstreamReply)
}
body, callErr := pinned.Plugin.Engine.CallMember(c.Request.Context(), "native", "error", requestContext.JSValue(), errorValue)
if callErr == nil {
callErr = WriteNativeReply(c, sanitized.HTTPStatus, body)
}
Expand Down
Loading