Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:recycle: Declare raw proxy and empty response contracts https://github.com/siyuan-note/siyuan/issues/19378

Daniel276c41973d20
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index 353df5f166..0f4585d5c8 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -4921,6 +4921,8 @@ export interface APIFormData<Request> extends FormData {
}
type APIRequestArgs<C extends APIContract> = C["body"] extends "multipart" | "form"
? [data: APIFormData<C["request"]>]
+ : C["body"] extends "raw"
+ ? [data?: JSONValue | FormData | null]
: C["body"] extends "json" | "structJSON"
? [data: C["request"]]
: [data?: C["request"] | null];
@@ -4931,8 +4933,12 @@ export type APICallbackResponse<R> = R extends {code: infer C extends number}
type APIDirectCallbackResponse<R> = R extends {code: number} ? APICallbackResponse<R> : R;
+type APIEmptyResponse<C> = C extends {emptyResponseStatuses: ReadonlyArray<number>} ? "" : never;
+type APIPostEmptyResponse<C> = C extends {emptyResponseStatuses: infer S extends ReadonlyArray<number>}
+ ? Exclude<S[number], 401 | 403 | 404> extends never ? never : "" : never;
+
type APIPostTail<C extends APIContract> = [
- cb?: (response: C extends {output: "binary"} ? JSONValue : C extends {output: "directJSON"} ? APIDirectCallbackResponse<C["response"]> | (C extends {noContent: true} ? "" : never) : C extends {output: "sse"} ? string | APICallbackResponse<C["response"]> : APICallbackResponse<C["response"]>) => void,
+ cb?: (response: (C extends {output: "binary" | "proxy"} ? JSONValue : C extends {output: "directJSON"} ? APIDirectCallbackResponse<C["response"]> | (C extends {noContent: true} ? "" : never) : C extends {output: "sse"} ? string | APICallbackResponse<C["response"]> : APICallbackResponse<C["response"]>) | APIPostEmptyResponse<C>) => void,
headers?: Record<string, string>,
failCallback?: (response: APIFetchFailure) => void,
signal?: AbortSignal,
@@ -4964,13 +4970,13 @@ export type FetchSyncPost<Legacy = APILegacyResponse> = <Path extends string>(
: Path extends APILegacyPOSTPath ? [data?: any, ...tail: APISyncTail]
: string extends Path ? [data?: any, ...tail: APISyncTail] : never
) => Promise<Path extends keyof APIPOSTRoutes
- ? APIPOSTRoutes[Path] extends {output: "binary"} ? JSONValue : APIPOSTRoutes[Path]["response"] | APITransportError
+ ? APIPOSTRoutes[Path] extends {output: "binary" | "proxy"} ? JSONValue : APIPOSTRoutes[Path]["response"] | APITransportError
: Legacy>;
export type FetchGet<Legacy = APILegacyResponse | string> = <Path extends string>(
url: Path,
...args: Path extends keyof APIGETRoutes
- ? [cb: (response: APIGETRoutes[Path]["response"] | (APIGETRoutes[Path] extends {output: "websocket"} ? string : never)) => void]
+ ? [cb: (response: APIGETRoutes[Path] extends {output: "binary" | "proxy"} ? JSONValue : APIGETRoutes[Path]["response"] | APIEmptyResponse<APIGETRoutes[Path]> | (APIGETRoutes[Path] extends {output: "websocket" | "sse"} ? string : never)) => void]
: Path extends keyof APIPOSTRoutes ? never
: [cb: (response: Legacy) => void]
) => void;
diff --git a/docs/API-CONTRACTS.md b/docs/API-CONTRACTS.md
index 24093a9884..208f92b90d 100644
--- a/docs/API-CONTRACTS.md
+++ b/docs/API-CONTRACTS.md
@@ -92,7 +92,9 @@ Storage contracts keep arbitrary JSON limited to storage values; keys, recent do
## Multipart requests
-SSE endpoints declare each event name and payload with `SSEOptions` and `SSEEvent`. `StreamSSE` executes the existing stream lifecycle within the request; cancellation and cleanup remain inside that lifecycle. HTTP validation distinguishes `text/event-stream` from the declared pre-stream JSON failures, while `ValidateSSEEvent` checks each JSON event payload separately. Generated metadata exposes the event types; buffered fetch helpers still return the complete stream as text.
+SSE endpoints declare each event name and payload with `SSEOptions` and `SSEEvent`. `StreamSSE` executes the existing stream lifecycle within the request; cancellation and cleanup remain inside that lifecycle. HTTP validation distinguishes `text/event-stream` from the declared pre-stream JSON failures, while `ValidateSSEEvent` checks each JSON event payload separately. Generated metadata exposes the event types. `fetchPost` and `fetchGet` buffer streams as text; `fetchSyncPost` continues to parse JSON and is not a stream reader.
+
+Endpoints with an empty HTTP response list its permitted statuses in `EmptyResponseStatuses` and return `EmptyHTTPResponse`; other responses retain their own declared shapes. `RedirectHTTPContent` preserves the standard redirect status, Location header, and escaped HTML body. `RawBody` leaves the original request stream unread for protocol handlers. `ProxyOptions` distinguishes HTTP bytes, EventSource bytes, and WebSocket frames, preserving upstream statuses instead of treating them as kernel business codes. Proxy admission errors and middleware envelopes are validated separately. `ANY` registrations remain one coverage record and expand to the router's nine HTTP methods in generated metadata. Response validation preserves JSON number precision, including certificate integers outside the floating-point range; it does not change request numeric conversion.
Page responses use `HTTPContentOptions` to declare permitted HTTP status and media-type pairs and `SuccessHTTPContent` to preserve their bytes. This uses the existing binary transport and keeps JSON middleware errors separate. `FastJSON` preserves selected large responses' accelerated JSON encoder without changing their typed payloads or response envelope; encoding failures retain the standard encoder fallback.
diff --git a/docs/API-CONTRACTS.zh-CN.md b/docs/API-CONTRACTS.zh-CN.md
index d1625d6a55..901a55a9c0 100644
--- a/docs/API-CONTRACTS.zh-CN.md
+++ b/docs/API-CONTRACTS.zh-CN.md
@@ -94,7 +94,9 @@ SQL 查询契约保留成功信封顶层的 `limit` 和 `truncated`。`SuccessSQ
## 文件上传请求
-SSE 接口通过 `SSEOptions` 和 `SSEEvent` 声明各事件名称及载荷。`StreamSSE` 在请求上下文内执行原有流生命周期,取消与清理仍在该生命周期内完成。HTTP 校验区分 `text/event-stream` 与声明过的流建立前 JSON 错误,`ValidateSSEEvent` 单独校验各事件的 JSON 载荷。生成声明包含事件类型;缓冲式 fetch 辅助函数仍将完整流作为文本返回。
+SSE 接口通过 `SSEOptions` 和 `SSEEvent` 声明各事件名称及载荷。`StreamSSE` 在请求上下文内执行原有流生命周期,取消与清理仍在该生命周期内完成。HTTP 校验区分 `text/event-stream` 与声明过的流建立前 JSON 错误,`ValidateSSEEvent` 单独校验各事件的 JSON 载荷。生成声明包含事件类型。`fetchPost` 和 `fetchGet` 将完整流缓冲为文本,`fetchSyncPost` 仍解析 JSON,不用于读取事件流。
+
+允许空 HTTP 响应的端点通过 `EmptyResponseStatuses` 列出允许状态,并返回 `EmptyHTTPResponse`;其他响应继续使用各自声明的结构。`RedirectHTTPContent` 保留标准重定向状态、Location 响应头和转义后的 HTML 正文。`RawBody` 将未读取的原始请求流留给协议处理函数。`ProxyOptions` 区分 HTTP 字节、EventSource 字节和 WebSocket 帧,保留上游状态,不将其解释为内核业务错误码。代理准入错误与中间件信封分别校验。`ANY` 注册仍按一条记录检查覆盖率,生成元数据时展开为路由器的九种 HTTP 方法。响应校验保留 JSON 数字精度,包括超过浮点范围的证书整数,不改变请求侧的数字转换。
页面响应通过 `HTTPContentOptions` 声明允许的 HTTP 状态与媒体类型组合,通过 `SuccessHTTPContent` 保留原始字节,复用既有二进制传输并单独处理 JSON 中间件错误。`FastJSON` 为指定的大体量响应保留快速 JSON 编码,不改变有类型载荷及响应信封;编码失败时仍回退到标准编码器。
diff --git a/kernel/api/contract.go b/kernel/api/contract.go
index 6c1d88c6a4..fba444b33b 100644
--- a/kernel/api/contract.go
+++ b/kernel/api/contract.go
@@ -55,10 +55,14 @@ func contractHandler[Request, Data any](endpoint apicontract.Endpoint[Request, D
stream(c.Writer, c.Request)
return
}
- if status == 204 {
+ if status == 204 || response.Empty() {
c.Status(status)
return
}
+ if redirect := response.Redirect(); redirect != nil {
+ c.Redirect(status, redirect.Location)
+ return
+ }
if content := response.Binary(); content != nil {
c.Data(status, content.ContentType, content.Bytes)
return
diff --git a/kernel/api/contract_test.go b/kernel/api/contract_test.go
index 09b665fb4c..5fbcd17ca6 100644
--- a/kernel/api/contract_test.go
+++ b/kernel/api/contract_test.go
@@ -81,7 +81,7 @@ func TestAPIContractRouterCoverage(t *testing.T) {
}
}
for _, definition := range apicontract.Definitions() {
- for _, method := range definition.Methods {
+ for _, method := range apicontract.ExpandMethods(definition.Methods) {
expected[method+" "+definition.Path] = true
}
}
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index 65e9790fc4..0ad9b9b957 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -41,8 +41,10 @@ type Definition struct {
NoContent bool
WebSocket *WebSocketDefinition
SSE *SSEDefinition
+ Proxy *ProxyDefinition
ContentVariants []HTTPContentVariant
FastJSON bool
+ EmptyResponseStatuses []int
AdditionalErrorStatuses []int
}
@@ -62,8 +64,10 @@ type ResponseOptions struct {
NoContent bool
WebSocket *WebSocketDefinition
SSE *SSEDefinition
+ Proxy *ProxyDefinition
ContentVariants []HTTPContentVariant
FastJSON bool
+ EmptyResponseStatuses []int
AdditionalErrorStatuses []int
}
@@ -118,8 +122,9 @@ func define[Request, Data any](name, path string, body BodyMode, response Respon
d := Definition{Name: name, Path: path, Methods: methods, Body: body,
Request: reflect.TypeFor[Request](), Data: reflect.TypeFor[Data](),
ErrorCodes: append([]int{-1}, response.AdditionalCodes...), ErrorText: response.Text, DataNonNullable: response.NonNullable, DataOnError: response.DataOnError,
- Output: response.Output, ErrorStatus: response.ErrorStatus, NoContent: response.NoContent, WebSocket: response.WebSocket, SSE: response.SSE,
- AdditionalErrorStatuses: append([]int(nil), response.AdditionalErrorStatuses...), ContentVariants: append([]HTTPContentVariant(nil), response.ContentVariants...), FastJSON: response.FastJSON}
+ Output: response.Output, ErrorStatus: response.ErrorStatus, NoContent: response.NoContent, WebSocket: response.WebSocket, SSE: response.SSE, Proxy: response.Proxy,
+ AdditionalErrorStatuses: append([]int(nil), response.AdditionalErrorStatuses...), ContentVariants: append([]HTTPContentVariant(nil), response.ContentVariants...), FastJSON: response.FastJSON,
+ EmptyResponseStatuses: append([]int(nil), response.EmptyResponseStatuses...)}
definitions = append(definitions, d)
return Endpoint[Request, Data]{definition: d}
}
@@ -846,42 +851,6 @@ var LogoutCloudUser = define[EmptyRequest, Null]("logoutCloudUser", "/api/settin
var Login2faCloudUser = define[SettingLogin2faRequest, Login2faEnvelope]("login2faCloudUser", "/api/setting/login2faCloudUser", JSONBody, ResponseOptions{Output: DirectJSONOutput}, "POST")
var SetEmoji = define[SettingEmojiRequest, Null]("setEmoji", "/api/setting/setEmoji", JSONBody, ResponseOptions{}, "POST")
-var AIChatGPT = define[AIMessageRequest, string]("chatGPT", "/api/ai/chatGPT", JSONBody, ResponseOptions{}, "POST")
-var AIChatGPTWithAction = define[AIActionRequest, string]("chatGPTWithAction", "/api/ai/chatGPTWithAction", JSONBody, ResponseOptions{}, "POST")
-var AIListEditorActions = define[EmptyRequest, []*AIEditorAction]("lsAIEditorActions", "/api/ai/editor/lsActions", NoBody, ResponseOptions{}, "POST")
-var AISaveEditorAction = define[AIEditorActionSaveRequest, *AIEditorAction]("saveAIEditorAction", "/api/ai/editor/saveAction", JSONBody, ResponseOptions{}, "POST")
-var AIRemoveEditorAction = define[AIEditorActionIDRequest, Null]("removeAIEditorAction", "/api/ai/editor/removeAction", JSONBody, ResponseOptions{}, "POST")
-var AITestModel = define[AIModelRequest, AIModelTestData]("testModel", "/api/ai/testModel", JSONBody, ResponseOptions{}, "POST")
-var AITestEmbeddingModel = define[EmptyRequest, AIEmbeddingTestData]("testEmbeddingModel", "/api/ai/testEmbeddingModel", NoBody, ResponseOptions{}, "POST")
-var AITestRerankModel = define[EmptyRequest, AIRerankTestData]("testRerankModel", "/api/ai/testRerankModel", NoBody, ResponseOptions{}, "POST")
-var AIListModels = define[AIProviderRequest, AIModelsData]("listModels", "/api/ai/listModels", JSONBody, ResponseOptions{}, "POST")
-var AIGetEmbeddingStat = define[EmptyRequest, *AIEmbeddingStat]("embeddingStat", "/api/ai/embeddingStat", NoBody, ResponseOptions{}, "POST")
-var AIGetMCPStatus = define[EmptyRequest, []AIMCPStatus]("mcpStatus", "/api/ai/mcpStatus", NoBody, ResponseOptions{}, "POST")
-var AIGetMCPEnvironment = define[EmptyRequest, AIMCPEnvironmentData]("mcpEnvironmentVariables", "/api/ai/mcpEnvironmentVariables", NoBody, ResponseOptions{}, "POST")
-var AIMCPOAuthAuthorize = define[AIMCPIDRequest, Null]("mcpOAuthAuthorize", "/api/ai/mcpOAuthAuthorize", JSONBody, ResponseOptions{}, "POST")
-var AIMCPOAuthDisconnect = define[AIMCPIDRequest, Null]("mcpOAuthDisconnect", "/api/ai/mcpOAuthDisconnect", JSONBody, ResponseOptions{}, "POST")
-var AIReindexEmbedding = define[EmptyRequest, Null]("reindexEmbedding", "/api/ai/reindexEmbedding", NoBody, ResponseOptions{}, "POST")
-var AIRetryFailedEmbedding = define[EmptyRequest, Null]("retryFailedEmbedding", "/api/ai/retryFailedEmbedding", NoBody, ResponseOptions{}, "POST")
-var AIAgentConfirm = define[AIConfirmRequest, Null]("agentChatConfirm", "/api/ai/agent/confirm", StructJSONBody, ResponseOptions{AdditionalErrorStatuses: []int{409}}, "POST")
-var AIAgentSetPermission = define[AIPermissionRequest, AIPermissionData]("setAgentSessionPermission", "/api/ai/agent/setPermission", StructJSONBody, ResponseOptions{}, "POST")
-var AIAgentQuestion = define[AIQuestionRequest, Null]("agentChatQuestion", "/api/ai/agent/question", StructJSONBody, ResponseOptions{AdditionalErrorStatuses: []int{409}}, "POST")
-var AIAgentBrowserCapabilityResult = define[AIBrowserCapabilityResultRequest, Null]("agentChatBrowserCapabilityResult", "/api/ai/agent/browserCapabilityResult", StructJSONBody, ResponseOptions{AdditionalErrorStatuses: []int{409}}, "POST")
-var AIListCapabilities = define[EmptyRequest, []AICapabilityManifest]("lsCapabilities", "/api/ai/lsCapabilities", NoBody, ResponseOptions{}, "POST")
-var AIAgentTitle = define[AITitleRequest, string]("agentChatTitle", "/api/ai/agent/title", StructJSONBody, ResponseOptions{}, "POST")
-var AIListSessions = define[AISessionsRequest, AISessionList]("lsSessions", "/api/ai/agent/lsSessions", StructJSONBody, ResponseOptions{}, "POST")
-var AIRemoveSession = define[AISessionIDRequest, Null]("removeSession", "/api/ai/agent/removeSession", StructJSONBody, ResponseOptions{AdditionalErrorStatuses: []int{409, 500}}, "POST")
-var AIListSkills = define[EmptyRequest, []AISkillInfo]("lsSkills", "/api/ai/agent/lsSkills", NoBody, ResponseOptions{}, "POST")
-var AIListUserSkills = define[EmptyRequest, []AIUserSkillInfo]("lsUserSkills", "/api/ai/agent/lsUserSkills", NoBody, ResponseOptions{}, "POST")
-var AIGetSkill = define[AISkillNameRequest, AISkillData]("getSkill", "/api/ai/agent/getSkill", StructJSONBody, ResponseOptions{}, "POST")
-var AISaveSkill = define[AISkillSaveRequest, Null]("saveSkill", "/api/ai/agent/saveSkill", StructJSONBody, ResponseOptions{}, "POST")
-var AIRemoveSkill = define[AISkillNameRequest, Null]("removeSkill", "/api/ai/agent/removeSkill", StructJSONBody, ResponseOptions{}, "POST")
-var AIRenameSkill = define[AISkillRenameRequest, Null]("renameSkill", "/api/ai/agent/renameSkill", StructJSONBody, ResponseOptions{}, "POST")
-var AIEditorChat = define[AIEditorChatRequest, Null]("aiEditorChat", "/api/ai/editor/chat", StructJSONBody, aiEditorSSEOptions(), "POST")
-var AIAgentChat = define[AIAgentChatRequest, Null]("agentChat", "/api/ai/agent/chat", StructJSONBody, aiAgentSSEOptions(), "POST")
-var AIMCPOAuthCallback = define[EmptyRequest, BinaryContent]("mcpOAuthCallback", "/api/ai/mcp/oauth/callback/:flowID", NoBody, HTTPContentOptions(HTTPContentVariant{Status: 200, ContentType: "text/html"}, HTTPContentVariant{Status: 400, ContentType: "text/html"}, HTTPContentVariant{Status: 403, ContentType: "text/plain"}), "GET")
-var AIGetSession = define[AISessionIDRequest, *AISession]("getSession", "/api/ai/agent/getSession", StructJSONBody, ResponseOptions{AdditionalErrorStatuses: []int{500}}, "POST")
-var AISaveSession = define[AISession, AISessionSaveData]("saveSession", "/api/ai/agent/saveSession", StructJSONBody, ResponseOptions{DataOnError: true, AdditionalErrorStatuses: []int{400, 409, 500}}, "POST")
-
var RemoveUnusedAttributeView = define[RemoveUnusedAttributeViewRequest, AVIDData]("removeUnusedAttributeView", "/api/av/removeUnusedAttributeView", JSONBody, ResponseOptions{}, "POST")
var RemoveUnusedAttributeViews = define[EmptyRequest, AVPathsData]("removeUnusedAttributeViews", "/api/av/removeUnusedAttributeViews", NoBody, ResponseOptions{}, "POST")
var GetUnusedAttributeViews = define[EmptyRequest, []*AssetUnusedItem]("getUnusedAttributeViews", "/api/av/getUnusedAttributeViews", NoBody, ResponseOptions{}, "POST")
@@ -929,3 +898,40 @@ var GetAttributeViewBacklinks = define[GetAttributeViewBacklinksRequest, *AVAttr
var SetAttributeViewBlockAttr = define[SetAttributeViewBlockAttrRequest, AVValueData]("setAttributeViewBlockAttr", "/api/av/setAttributeViewBlockAttr", JSONBody, ResponseOptions{}, "POST")
var BatchSetAttributeViewBlockAttrs = define[BatchSetAttributeViewBlockAttrsRequest, Null]("batchSetAttributeViewBlockAttrs", "/api/av/batchSetAttributeViewBlockAttrs", JSONBody, ResponseOptions{}, "POST")
var GetAttributeViewRowSort = define[GetAttributeViewRowSortRequest, AVRowSortPreview]("getAttributeViewRowSort", "/api/av/getAttributeViewRowSort", StructJSONBody, ResponseOptions{}, "POST")
+
+var AIChatGPT = define[AIMessageRequest, string]("chatGPT", "/api/ai/chatGPT", JSONBody, ResponseOptions{}, "POST")
+var AIChatGPTWithAction = define[AIActionRequest, string]("chatGPTWithAction", "/api/ai/chatGPTWithAction", JSONBody, ResponseOptions{}, "POST")
+var AIListEditorActions = define[EmptyRequest, []*AIEditorAction]("lsAIEditorActions", "/api/ai/editor/lsActions", NoBody, ResponseOptions{}, "POST")
+var AISaveEditorAction = define[AIEditorActionSaveRequest, *AIEditorAction]("saveAIEditorAction", "/api/ai/editor/saveAction", JSONBody, ResponseOptions{}, "POST")
+var AIRemoveEditorAction = define[AIEditorActionIDRequest, Null]("removeAIEditorAction", "/api/ai/editor/removeAction", JSONBody, ResponseOptions{}, "POST")
+var AITestModel = define[AIModelRequest, AIModelTestData]("testModel", "/api/ai/testModel", JSONBody, ResponseOptions{}, "POST")
+var AITestEmbeddingModel = define[EmptyRequest, AIEmbeddingTestData]("testEmbeddingModel", "/api/ai/testEmbeddingModel", NoBody, ResponseOptions{}, "POST")
+var AITestRerankModel = define[EmptyRequest, AIRerankTestData]("testRerankModel", "/api/ai/testRerankModel", NoBody, ResponseOptions{}, "POST")
+var AIListModels = define[AIProviderRequest, AIModelsData]("listModels", "/api/ai/listModels", JSONBody, ResponseOptions{}, "POST")
+var AIGetEmbeddingStat = define[EmptyRequest, *AIEmbeddingStat]("embeddingStat", "/api/ai/embeddingStat", NoBody, ResponseOptions{}, "POST")
+var AIGetMCPStatus = define[EmptyRequest, []AIMCPStatus]("mcpStatus", "/api/ai/mcpStatus", NoBody, ResponseOptions{}, "POST")
+var AIGetMCPEnvironment = define[EmptyRequest, AIMCPEnvironmentData]("mcpEnvironmentVariables", "/api/ai/mcpEnvironmentVariables", NoBody, ResponseOptions{}, "POST")
+var AIMCPOAuthAuthorize = define[AIMCPIDRequest, Null]("mcpOAuthAuthorize", "/api/ai/mcpOAuthAuthorize", JSONBody, ResponseOptions{}, "POST")
+var AIMCPOAuthDisconnect = define[AIMCPIDRequest, Null]("mcpOAuthDisconnect", "/api/ai/mcpOAuthDisconnect", JSONBody, ResponseOptions{}, "POST")
+var AIReindexEmbedding = define[EmptyRequest, Null]("reindexEmbedding", "/api/ai/reindexEmbedding", NoBody, ResponseOptions{}, "POST")
+var AIRetryFailedEmbedding = define[EmptyRequest, Null]("retryFailedEmbedding", "/api/ai/retryFailedEmbedding", NoBody, ResponseOptions{}, "POST")
+var AIAgentConfirm = define[AIConfirmRequest, Null]("agentChatConfirm", "/api/ai/agent/confirm", StructJSONBody, ResponseOptions{AdditionalErrorStatuses: []int{409}}, "POST")
+var AIAgentSetPermission = define[AIPermissionRequest, AIPermissionData]("setAgentSessionPermission", "/api/ai/agent/setPermission", StructJSONBody, ResponseOptions{}, "POST")
+var AIAgentQuestion = define[AIQuestionRequest, Null]("agentChatQuestion", "/api/ai/agent/question", StructJSONBody, ResponseOptions{AdditionalErrorStatuses: []int{409}}, "POST")
+var AIAgentBrowserCapabilityResult = define[AIBrowserCapabilityResultRequest, Null]("agentChatBrowserCapabilityResult", "/api/ai/agent/browserCapabilityResult", StructJSONBody, ResponseOptions{AdditionalErrorStatuses: []int{409}}, "POST")
+var AIListCapabilities = define[EmptyRequest, []AICapabilityManifest]("lsCapabilities", "/api/ai/lsCapabilities", NoBody, ResponseOptions{}, "POST")
+var AIAgentTitle = define[AITitleRequest, string]("agentChatTitle", "/api/ai/agent/title", StructJSONBody, ResponseOptions{}, "POST")
+var AIListSessions = define[AISessionsRequest, AISessionList]("lsSessions", "/api/ai/agent/lsSessions", StructJSONBody, ResponseOptions{}, "POST")
+var AIRemoveSession = define[AISessionIDRequest, Null]("removeSession", "/api/ai/agent/removeSession", StructJSONBody, ResponseOptions{AdditionalErrorStatuses: []int{409, 500}}, "POST")
+var AIListSkills = define[EmptyRequest, []AISkillInfo]("lsSkills", "/api/ai/agent/lsSkills", NoBody, ResponseOptions{}, "POST")
+var AIListUserSkills = define[EmptyRequest, []AIUserSkillInfo]("lsUserSkills", "/api/ai/agent/lsUserSkills", NoBody, ResponseOptions{}, "POST")
+var AIGetSkill = define[AISkillNameRequest, AISkillData]("getSkill", "/api/ai/agent/getSkill", StructJSONBody, ResponseOptions{}, "POST")
+var AISaveSkill = define[AISkillSaveRequest, Null]("saveSkill", "/api/ai/agent/saveSkill", StructJSONBody, ResponseOptions{}, "POST")
+var AIRemoveSkill = define[AISkillNameRequest, Null]("removeSkill", "/api/ai/agent/removeSkill", StructJSONBody, ResponseOptions{}, "POST")
+var AIRenameSkill = define[AISkillRenameRequest, Null]("renameSkill", "/api/ai/agent/renameSkill", StructJSONBody, ResponseOptions{}, "POST")
+
+var AIEditorChat = define[AIEditorChatRequest, Null]("aiEditorChat", "/api/ai/editor/chat", StructJSONBody, aiEditorSSEOptions(), "POST")
+var AIAgentChat = define[AIAgentChatRequest, Null]("agentChat", "/api/ai/agent/chat", StructJSONBody, aiAgentSSEOptions(), "POST")
+var AIMCPOAuthCallback = define[EmptyRequest, BinaryContent]("mcpOAuthCallback", "/api/ai/mcp/oauth/callback/:flowID", NoBody, HTTPContentOptions(HTTPContentVariant{Status: 200, ContentType: "text/html"}, HTTPContentVariant{Status: 400, ContentType: "text/html"}, HTTPContentVariant{Status: 403, ContentType: "text/plain"}), "GET")
+var AIGetSession = define[AISessionIDRequest, *AISession]("getSession", "/api/ai/agent/getSession", StructJSONBody, ResponseOptions{AdditionalErrorStatuses: []int{500}}, "POST")
+var AISaveSession = define[AISession, AISessionSaveData]("saveSession", "/api/ai/agent/saveSession", StructJSONBody, ResponseOptions{DataOnError: true, AdditionalErrorStatuses: []int{400, 409, 500}}, "POST")
diff --git a/kernel/apicontract/decode.go b/kernel/apicontract/decode.go
index 6a55bd07df..d8a19be77d 100644
--- a/kernel/apicontract/decode.go
+++ b/kernel/apicontract/decode.go
@@ -12,7 +12,7 @@ import (
// Decode 按精确的 JSON 字段名绑定请求,缺失、null 和兼容转换由字段声明控制。
func (e Endpoint[Request, Data]) Decode(reader io.Reader) (request Request, err error) {
- if e.definition.Body == NoBody {
+ if e.definition.Body == NoBody || e.definition.Body == RawBody {
return
}
if reader == nil {
diff --git a/kernel/apicontract/empty_response.go b/kernel/apicontract/empty_response.go
new file mode 100644
index 0000000000..e744ff6793
--- /dev/null
+++ b/kernel/apicontract/empty_response.go
@@ -0,0 +1,23 @@
+package apicontract
+
+// EmptyHTTPResponse 保留显式声明的无正文 HTTP 响应。
+func EmptyHTTPResponse[Data any](status int) Response[Data] {
+ if status == 0 {
+ panic("empty response status must be explicit")
+ }
+ return Response[Data]{emptyStatus: status}
+}
+
+func (r Response[Data]) Empty() bool { return r.emptyStatus != 0 }
+
+type HTTPRedirect struct {
+ Status int
+ Location string
+}
+
+// RedirectHTTPContent 由 HTTP 适配器保留标准重定向的 Location 和 HTML 正文。
+func RedirectHTTPContent(status int, location string) Response[BinaryContent] {
+ return Response[BinaryContent]{redirect: &HTTPRedirect{Status: status, Location: location}}
+}
+
+func (r Response[Data]) Redirect() *HTTPRedirect { return r.redirect }
diff --git a/kernel/apicontract/empty_response_test.go b/kernel/apicontract/empty_response_test.go
new file mode 100644
index 0000000000..3f4d567b1e
--- /dev/null
+++ b/kernel/apicontract/empty_response_test.go
@@ -0,0 +1,90 @@
+package apicontract
+
+import (
+ "encoding/json"
+ "testing"
+)
+
+func TestEmptyHTTPResponse(t *testing.T) {
+ previous := definitions
+ t.Cleanup(func() { definitions = previous })
+ endpoint := define[EmptyRequest, string]("optionalBody", "/test/empty", NoBody, ResponseOptions{EmptyResponseStatuses: []int{200, 403}}, "GET")
+ image := define[EmptyRequest, BinaryContent]("optionalImage", "/test/image", NoBody, ResponseOptions{Output: BinaryOutput, ErrorStatus: 200,
+ ContentVariants: []HTTPContentVariant{{200, "image/png"}}, EmptyResponseStatuses: []int{500}}, "GET")
+ bundle, err := BuildBundle()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, status := range []int{200, 403} {
+ response := EmptyHTTPResponse[string](status)
+ if !response.Empty() || endpoint.Status(response) != status {
+ t.Fatal("empty response changed")
+ }
+ if _, err := json.Marshal(response); err == nil {
+ t.Fatal("empty response encoded as JSON")
+ }
+ if err := bundle.ValidateHTTPResponse("GET", "/test/empty", status, "", nil); err != nil {
+ t.Fatal(err)
+ }
+ if err := bundle.ValidateHTTPResponse("GET", "/test/empty", status, "", []byte("body")); err == nil {
+ t.Fatal("undeclared text accepted")
+ }
+ }
+ for _, response := range []Response[string]{Success("value"), Failure[string](-1, "failed")} {
+ payload, _ := json.Marshal(response)
+ if err := bundle.ValidateHTTPResponse("GET", "/test/empty", 200, "application/json", payload); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if image.Status(EmptyHTTPResponse[BinaryContent](500)) != 500 {
+ t.Fatal("image failure status changed")
+ }
+ if err := bundle.ValidateHTTPResponse("GET", "/test/image", 500, "", nil); err != nil {
+ t.Fatal(err)
+ }
+ if err := bundle.ValidateHTTPResponse("GET", "/test/image", 500, "image/png", []byte("invalid")); err == nil {
+ t.Fatal("image failure accepted a body")
+ }
+ t.Run("undeclared status", func(t *testing.T) {
+ defer func() {
+ if recover() == nil {
+ t.Fatal("undeclared status accepted")
+ }
+ }()
+ endpoint.Status(EmptyHTTPResponse[string](500))
+ })
+}
+
+func TestHTTPRedirectResponse(t *testing.T) {
+ previous := definitions
+ t.Cleanup(func() { definitions = previous })
+ endpoint := define[EmptyRequest, BinaryContent]("redirect", "/test/redirect", NoBody,
+ HTTPContentOptions(HTTPContentVariant{302, "text/html"}), "GET")
+ response := RedirectHTTPContent(302, "/target?value=one&other=two")
+ if endpoint.Status(response) != 302 || response.Redirect().Location != "/target?value=one&other=two" {
+ t.Fatal("redirect changed")
+ }
+ if _, err := json.Marshal(response); err == nil {
+ t.Fatal("redirect encoded as JSON")
+ }
+ t.Run("undeclared status", func(t *testing.T) {
+ defer func() {
+ if recover() == nil {
+ t.Fatal("undeclared redirect accepted")
+ }
+ }()
+ endpoint.Status(RedirectHTTPContent(301, "/target"))
+ })
+}
+
+func TestEmptyHTTPResponseDeclaration(t *testing.T) {
+ previous := definitions
+ t.Cleanup(func() { definitions = previous })
+ for _, status := range []int{0, 101, 199, 600} {
+ definitions = previous
+ define[EmptyRequest, Null]("empty", "/test/empty", NoBody, ResponseOptions{EmptyResponseStatuses: []int{status}}, "GET")
+ if _, err := BuildBundle(); err == nil {
+ t.Fatalf("invalid empty status accepted: %d", status)
+ }
+ }
+}
diff --git a/kernel/apicontract/proxy_protocol.go b/kernel/apicontract/proxy_protocol.go
new file mode 100644
index 0000000000..152d36766b
--- /dev/null
+++ b/kernel/apicontract/proxy_protocol.go
@@ -0,0 +1,167 @@
+package apicontract
+
+import (
+ "encoding/json"
+ "fmt"
+ "mime"
+ "net/http"
+ "reflect"
+)
+
+const RawBody BodyMode = "raw"
+const ProxyOutput OutputMode = "proxy"
+
+type ProxyKind string
+
+const (
+ HTTPProxy ProxyKind = "http"
+ EventSourceProxy ProxyKind = "eventSource"
+ WebSocketProxy ProxyKind = "websocket"
+)
+
+// ProxyDefinition 明确上游字节或帧透传,不将上游状态解释为内核业务结果。
+type ProxyDefinition struct {
+ Kind ProxyKind `json:"kind"`
+ ContentType string `json:"contentType,omitempty"`
+ UpstreamStatuses bool `json:"upstreamStatuses"`
+ Frames []string `json:"frames,omitempty"`
+}
+
+type ProxyFailure struct {
+ Code int `json:"code"`
+ Msg string `json:"msg"`
+}
+
+func ProxyOptions(kind ProxyKind) ResponseOptions {
+ definition := &ProxyDefinition{Kind: kind, UpstreamStatuses: true}
+ switch kind {
+ case HTTPProxy:
+ definition.ContentType = "application/octet-stream"
+ case EventSourceProxy:
+ definition.ContentType = "text/event-stream"
+ case WebSocketProxy:
+ definition.UpstreamStatuses = false
+ definition.Frames = []string{"text", "binary", "close"}
+ default:
+ panic("unsupported proxy protocol")
+ }
+ return ResponseOptions{Output: ProxyOutput, Proxy: definition}
+}
+
+func StreamProxy(status int, serve func(http.ResponseWriter, *http.Request)) Response[ProxyFailure] {
+ if serve == nil {
+ panic("proxy response requires a stream lifecycle")
+ }
+ return Response[ProxyFailure]{httpStatus: status, stream: serve}
+}
+
+func RejectProxy(status int, message string) Response[ProxyFailure] {
+ return Response[ProxyFailure]{httpStatus: status, directJSON: true, data: ProxyFailure{Code: -1, Msg: message}}
+}
+
+func (e Endpoint[Request, Data]) proxyStatus(response Response[Data]) int {
+ definition := e.definition.Proxy
+ if e.definition.Output != ProxyOutput || definition == nil {
+ panic("endpoint does not declare proxy output")
+ }
+ if response.stream != nil {
+ if definition.Kind == WebSocketProxy {
+ if response.httpStatus != 101 {
+ panic("WebSocket proxy requires upgrade status")
+ }
+ } else if response.httpStatus < 100 || response.httpStatus > 999 {
+ panic("invalid upstream proxy status")
+ }
+ return response.httpStatus
+ }
+ if response.directJSON {
+ if response.httpStatus != 400 && response.httpStatus != 502 {
+ panic("undeclared proxy rejection status")
+ }
+ return response.httpStatus
+ }
+ if response.code == 0 {
+ panic("proxy response requires a stream or rejection")
+ }
+ return 200
+}
+
+func validateProxyDefinition(definition Definition) error {
+ if (definition.Output == ProxyOutput) != (definition.Proxy != nil) {
+ return fmt.Errorf("proxy output requires a protocol declaration: %s", definition.Name)
+ }
+ if definition.Proxy == nil {
+ return nil
+ }
+ if definition.Proxy.Kind != HTTPProxy && definition.Proxy.Kind != EventSourceProxy && definition.Proxy.Kind != WebSocketProxy {
+ return fmt.Errorf("unsupported proxy protocol: %s", definition.Proxy.Kind)
+ }
+ if definition.Data != reflect.TypeFor[ProxyFailure]() || definition.DataOnError || definition.ErrorStatus != 0 || definition.SSE != nil || definition.WebSocket != nil {
+ return fmt.Errorf("invalid proxy response options: %s", definition.Name)
+ }
+ want := ProxyOptions(definition.Proxy.Kind).Proxy
+ if !reflect.DeepEqual(want, definition.Proxy) {
+ return fmt.Errorf("invalid proxy protocol declaration: %s", definition.Name)
+ }
+ return nil
+}
+
+// validateProxyHTTPResponse 按媒体类型区分上游字节和内核准入失败,同状态不代表同协议。
+func (b *Bundle) validateProxyHTTPResponse(endpoint EndpointSchema, status int, contentType string, payload []byte) error {
+ definition := endpoint.Proxy
+ media, _, _ := mime.ParseMediaType(contentType)
+ if definition.Kind != WebSocketProxy && endpoint.Method == "HEAD" {
+ if len(payload) != 0 {
+ return fmt.Errorf("HEAD proxy response forbids a body")
+ }
+ if status >= 100 && status <= 999 && (media == "" || media == definition.ContentType || media == "application/json") {
+ return nil
+ }
+ }
+ if definition.Kind != WebSocketProxy && (status < 200 || status == 204 || status == 304) && media == "" && status >= 100 && len(payload) == 0 {
+ return nil
+ }
+ if definition.Kind == WebSocketProxy {
+ if status == 101 && len(payload) == 0 {
+ return nil
+ }
+ if (status == 400 || status == 403 || status == 405 || status == 500) && media == "text/plain" {
+ return nil
+ }
+ } else if status >= 100 && status <= 999 && media == definition.ContentType {
+ if (endpoint.Method == "HEAD" || status < 200 || status == 204 || status == 304) && len(payload) != 0 {
+ return fmt.Errorf("proxy response status/method forbids a body")
+ }
+ return nil
+ }
+ if media != "application/json" {
+ return fmt.Errorf("undeclared proxy response media/status: %d %s", status, contentType)
+ }
+ var value any
+ if err := json.Unmarshal(payload, &value); err != nil {
+ return err
+ }
+ if status == 400 || status == 502 {
+ return b.validate(object(map[string]*Schema{"code": {Type: "integer", Enum: []any{-1}}, "msg": {Type: "string"}}, "code", "msg"), value, "$")
+ }
+ if status != 200 {
+ return fmt.Errorf("undeclared proxy middleware status: %d", status)
+ }
+ return b.validate(endpoint.Response.AnyOf[1], value, "$")
+}
+
+func (b *Bundle) ValidateProxyFrame(method, path string, frameType int, payload []byte) error {
+ for _, endpoint := range b.Endpoints {
+ if endpoint.Method != method || endpoint.Path != path {
+ continue
+ }
+ if endpoint.Proxy == nil || endpoint.Proxy.Kind != WebSocketProxy {
+ return fmt.Errorf("endpoint does not declare WebSocket proxy frames")
+ }
+ if frameType != 1 && frameType != 2 && frameType != 8 {
+ return fmt.Errorf("undeclared forwarded WebSocket frame type: %d", frameType)
+ }
+ return nil
+ }
+ return fmt.Errorf("unregistered API contract: %s %s", method, path)
+}
diff --git a/kernel/apicontract/proxy_protocol_test.go b/kernel/apicontract/proxy_protocol_test.go
new file mode 100644
index 0000000000..f7780c7a6d
--- /dev/null
+++ b/kernel/apicontract/proxy_protocol_test.go
@@ -0,0 +1,90 @@
+package apicontract
+
+import (
+ "net/http"
+ "reflect"
+ "strings"
+ "testing"
+)
+
+func TestProxyProtocolResponses(t *testing.T) {
+ previous := definitions
+ t.Cleanup(func() { definitions = previous })
+ endpoint := define[EmptyRequest, ProxyFailure]("proxyTest", "/test/proxy", RawBody, ProxyOptions(HTTPProxy), "ANY")
+ define[EmptyRequest, ProxyFailure]("eventsProxyTest", "/test/eventsProxy", NoBody, ProxyOptions(EventSourceProxy), "GET")
+ define[EmptyRequest, ProxyFailure]("wsProxyTest", "/test/wsProxy", NoBody, ProxyOptions(WebSocketProxy), "GET")
+ bundle, err := BuildBundle()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, tt := range []struct {
+ method, path string
+ status int
+ media, body string
+ valid bool
+ }{
+ {"POST", "/test/proxy", 404, "application/octet-stream", "\x00<html>", true},
+ {"POST", "/test/proxy", 700, "application/octet-stream", "custom status", true},
+ {"POST", "/test/proxy", 999, "application/octet-stream", "custom status", true},
+ {"POST", "/test/proxy", 502, "application/octet-stream", "upstream error", true},
+ {"POST", "/test/proxy", 400, "application/json", `{"code":-1,"msg":"bad"}`, true},
+ {"POST", "/test/proxy", 400, "application/json", `{"code":-1,"msg":"bad","data":null}`, false},
+ {"POST", "/test/proxy", 200, "application/json", `{"code":-1,"msg":"bad","data":null}`, true},
+ {"POST", "/test/proxy", 200, "application/json", `{"code":0,"msg":"","data":null}`, false},
+ {"POST", "/test/proxy", 200, "text/html", "unsafe", false},
+ {"HEAD", "/test/proxy", 404, "application/octet-stream", "", true},
+ {"HEAD", "/test/proxy", 404, "application/octet-stream", "body", false},
+ {"GET", "/test/proxy", 204, "", "", true},
+ {"GET", "/test/proxy", 304, "", "", true},
+ {"GET", "/test/proxy", 204, "application/octet-stream", "body", false},
+ {"GET", "/test/eventsProxy", 403, "text/event-stream; charset=utf-8", ": keepalive\nevent: custom\ndata: not JSON\n\n", true},
+ {"GET", "/test/eventsProxy", 200, "text/event-stream-invalid", "", false},
+ {"GET", "/test/wsProxy", 101, "", "", true},
+ {"GET", "/test/wsProxy", 403, "text/plain; charset=utf-8", "Forbidden\n", true},
+ {"GET", "/test/wsProxy", 502, "application/json", `{"code":-1,"msg":"dial failed"}`, true},
+ {"GET", "/test/wsProxy", 200, "application/octet-stream", "", false},
+ } {
+ if err := bundle.ValidateHTTPResponse(tt.method, tt.path, tt.status, tt.media, []byte(tt.body)); (err == nil) != tt.valid {
+ t.Errorf("%+v: %v", tt, err)
+ }
+ }
+ for _, frame := range []int{1, 2, 8} {
+ if err := bundle.ValidateProxyFrame("GET", "/test/wsProxy", frame, []byte{0, 255}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := bundle.ValidateProxyFrame("GET", "/test/wsProxy", 9, nil); err == nil {
+ t.Fatal("undeclared frame accepted")
+ }
+ raw := strings.NewReader("raw bytes")
+ if _, err := endpoint.Decode(raw); err != nil || raw.Len() != 9 {
+ t.Fatalf("raw decoder consumed payload: %v", err)
+ }
+ stream := StreamProxy(404, func(http.ResponseWriter, *http.Request) {})
+ if endpoint.Status(stream) != 404 || stream.Stream() == nil {
+ t.Fatal("upstream status changed")
+ }
+ if _, err := stream.MarshalJSON(); err == nil {
+ t.Fatal("stream serialized")
+ }
+ reject := RejectProxy(502, "dial failed")
+ encoded, err := reject.MarshalJSON()
+ if err != nil || string(encoded) != `{"code":-1,"msg":"dial failed"}` {
+ t.Fatalf("rejection changed: %s %v", encoded, err)
+ }
+ if endpoint.Status(reject) != 502 {
+ t.Fatal("rejection status changed")
+ }
+}
+
+func TestProxyDefinitionRejectsUnknownProtocol(t *testing.T) {
+ definition := Definition{Name: "invalid", Output: ProxyOutput, Data: reflect.TypeFor[ProxyFailure](), Proxy: &ProxyDefinition{Kind: "unknown"}}
+ if err := validateProxyDefinition(definition); err == nil {
+ t.Fatal("unknown protocol accepted")
+ }
+ definition.Proxy = ProxyOptions(HTTPProxy).Proxy
+ definition.Proxy.ContentType = "text/html"
+ if err := validateProxyDefinition(definition); err == nil {
+ t.Fatal("unsafe media accepted")
+ }
+}
diff --git a/kernel/apicontract/response.go b/kernel/apicontract/response.go
index fbf6dd01f2..68afe7d317 100644
--- a/kernel/apicontract/response.go
+++ b/kernel/apicontract/response.go
@@ -33,6 +33,22 @@ func SuccessNoContent[Data any]() Response[Data] {
// Status 只为显式声明的非 JSON 协议使用独立错误状态。
func (e Endpoint[Request, Data]) Status(r Response[Data]) int {
+ if e.definition.Proxy != nil {
+ return e.proxyStatus(r)
+ }
+ if r.emptyStatus != 0 {
+ if !slices.Contains(e.definition.EmptyResponseStatuses, r.emptyStatus) {
+ panic("endpoint does not declare this empty response status")
+ }
+ return r.emptyStatus
+ }
+ if r.redirect != nil {
+ status := r.redirect.Status
+ if e.definition.Output != BinaryOutput || (status != 301 && status != 302 && status != 303 && status != 307 && status != 308) || !matchesContentVariant(e.definition.ContentVariants, status, "text/html") {
+ panic("endpoint does not declare this redirect response")
+ }
+ return status
+ }
if r.httpStatus != 0 {
if (e.definition.Output != "" && e.definition.Output != SSEOutput) || r.code == 0 || !slices.Contains(e.definition.AdditionalErrorStatuses, r.httpStatus) {
panic("endpoint does not declare this JSON error status")
@@ -135,6 +151,8 @@ type Response[Data any] struct {
websocketFailure bool
httpStatus int
afterWrite func()
+ emptyStatus int
+ redirect *HTTPRedirect
}
// WithAfterWrite 将通知保留到响应写入完成后执行。
@@ -183,6 +201,9 @@ func (r Response[Data]) MarshalJSON() ([]byte, error) {
// MarshalWith 使用指定编码器序列化相同的有类型载荷,供大体量 JSON 响应保留快速编码路径。
func (r Response[Data]) MarshalWith(marshal func(any) ([]byte, error)) ([]byte, error) {
+ if r.Empty() || r.redirect != nil {
+ return nil, fmt.Errorf("raw HTTP response cannot be encoded as JSON")
+ }
if r.stream != nil {
return nil, fmt.Errorf("SSE stream cannot be encoded as JSON")
}
diff --git a/kernel/apicontract/routes.go b/kernel/apicontract/routes.go
index 219088c408..f24aaa4892 100644
--- a/kernel/apicontract/routes.go
+++ b/kernel/apicontract/routes.go
@@ -20,6 +20,19 @@ type Route struct {
func (r Route) Key() string { return r.Method + " " + r.Path }
+// ExpandMethods 按路由器的 Any 注册行为展开实际 HTTP 方法。
+func ExpandMethods(methods []string) []string {
+ var result []string
+ for _, method := range methods {
+ if method == "ANY" {
+ result = append(result, "GET", "POST", "PUT", "PATCH", "HEAD", "OPTIONS", "DELETE", "CONNECT", "TRACE")
+ } else {
+ result = append(result, method)
+ }
+ }
+ return result
+}
+
// ReadRoutes 读取实际路由及处理函数声明,防止契约与独立登记表各自漂移。
func ReadRoutes(apiDir string) ([]Route, map[string]string, error) {
var routes []Route
diff --git a/kernel/apicontract/schema.go b/kernel/apicontract/schema.go
index 65bb50f372..59745db385 100644
--- a/kernel/apicontract/schema.go
+++ b/kernel/apicontract/schema.go
@@ -3,7 +3,6 @@ package apicontract
import (
"encoding/json"
"fmt"
- "math"
"mime"
"mime/multipart"
"reflect"
@@ -18,6 +17,7 @@ type Schema struct {
Format string `json:"format,omitempty"`
Enum []any `json:"enum,omitempty"`
AnyOf []*Schema `json:"anyOf,omitempty"`
+ Not *Schema `json:"not,omitempty"`
Properties map[string]*Schema `json:"properties,omitempty"`
Required []string `json:"required,omitempty"`
Items *Schema `json:"items,omitempty"`
@@ -38,7 +38,9 @@ type EndpointSchema struct {
NoContent bool `json:"noContent,omitempty"`
WebSocket *WebSocketSchema `json:"websocket,omitempty"`
SSE *SSESchema `json:"sse,omitempty"`
+ Proxy *ProxyDefinition `json:"proxy,omitempty"`
ContentVariants []HTTPContentVariant `json:"contentVariants,omitempty"`
+ EmptyResponseStatuses []int `json:"emptyResponseStatuses,omitempty"`
AdditionalErrorStatuses []int `json:"additionalErrorStatuses,omitempty"`
}
@@ -88,9 +90,6 @@ func nonnullable(schema *Schema) *Schema {
}
func (b *schemaBuilder) schema(t reflect.Type, input bool) (*Schema, error) {
- if schema, err := avPayloadSchema(b, t, input); schema != nil || err != nil {
- return schema, err
- }
if t == reflect.TypeFor[*AISession]() {
schema, err := aiSessionPayloadSchema(b, input)
if err != nil {
@@ -104,6 +103,9 @@ func (b *schemaBuilder) schema(t reflect.Type, input bool) (*Schema, error) {
if schema, err := bazaarPayloadSchema(b, t, input); schema != nil || err != nil {
return schema, err
}
+ if schema, err := avPayloadSchema(b, t, input); schema != nil || err != nil {
+ return schema, err
+ }
if t == reflect.TypeFor[PluginRPCMessage]() {
response, err := b.schema(reflect.TypeFor[PluginRPCResponse](), false)
if err != nil {
@@ -518,6 +520,14 @@ func BuildBundle() (*Bundle, error) {
b := &schemaBuilder{definitions: map[string]*Schema{}, owners: map[string]reflect.Type{}}
bundle := &Bundle{Dialect: "https://json-schema.org/draft/2020-12/schema", Definitions: b.definitions}
for _, definition := range Definitions() {
+ if err := validateProxyDefinition(definition); err != nil {
+ return nil, err
+ }
+ for _, status := range definition.EmptyResponseStatuses {
+ if status < 200 || status > 599 {
+ return nil, fmt.Errorf("invalid empty response status: %s", definition.Name)
+ }
+ }
if definition.FastJSON && definition.Output != "" {
return nil, fmt.Errorf("fast JSON requires envelope output: %s", definition.Name)
}
@@ -529,7 +539,7 @@ func BuildBundle() (*Bundle, error) {
return nil, fmt.Errorf("invalid JSON error status: %s", definition.Name)
}
}
- if definition.Output != "" && definition.Output != BinaryOutput && definition.Output != DirectJSONOutput && definition.Output != WebSocketOutput && definition.Output != SSEOutput {
+ if definition.Output != "" && definition.Output != BinaryOutput && definition.Output != DirectJSONOutput && definition.Output != WebSocketOutput && definition.Output != SSEOutput && definition.Output != ProxyOutput {
return nil, fmt.Errorf("unsupported response output: %s", definition.Name)
}
if definition.NoContent && definition.Output != DirectJSONOutput {
@@ -596,6 +606,9 @@ func BuildBundle() (*Bundle, error) {
if err != nil {
return nil, err
}
+ if definition.Body == RawBody {
+ request = &Schema{Type: "string", Format: "binary"}
+ }
data, err := b.schema(definition.Data, false)
if err != nil {
return nil, err
@@ -622,6 +635,12 @@ func BuildBundle() (*Bundle, error) {
if definition.Output == SSEOutput {
success = &Schema{Type: "string"}
}
+ if definition.Output == ProxyOutput {
+ success = &Schema{Type: "string", Format: "binary"}
+ if _, err := b.schema(reflect.TypeFor[JSONValue](), false); err != nil {
+ return nil, err
+ }
+ }
var codes []any
for _, code := range definition.ErrorCodes {
codes = append(codes, code)
@@ -638,10 +657,10 @@ func BuildBundle() (*Bundle, error) {
// 中间件可能使用带命令元数据的统一信封,保留这些额外的顶层字段。
failure.AdditionalProperties = true
response := &Schema{AnyOf: []*Schema{success, failure}}
- for _, method := range definition.Methods {
+ for _, method := range ExpandMethods(definition.Methods) {
bundle.Endpoints = append(bundle.Endpoints, EndpointSchema{Method: method, Path: definition.Path, Handler: definition.Name,
Body: definition.Body, Request: request, Response: response, Output: definition.Output, ErrorStatus: definition.ErrorStatus, NoContent: definition.NoContent, WebSocket: websocket,
- AdditionalErrorStatuses: definition.AdditionalErrorStatuses, SSE: sse, ContentVariants: definition.ContentVariants})
+ AdditionalErrorStatuses: definition.AdditionalErrorStatuses, SSE: sse, Proxy: definition.Proxy, ContentVariants: definition.ContentVariants, EmptyResponseStatuses: definition.EmptyResponseStatuses})
}
}
sort.Slice(bundle.Endpoints, func(i, j int) bool {
@@ -653,7 +672,7 @@ func BuildBundle() (*Bundle, error) {
// ValidateErrorResponse 在原始文件与错误共用 HTTP 状态时,单独验证已知的错误分支。
func (b *Bundle) ValidateErrorResponse(method, path string, payload []byte) error {
var value any
- if err := json.Unmarshal(payload, &value); err != nil {
+ if err := decodeSchemaJSON(payload, &value); err != nil {
return err
}
for _, endpoint := range b.Endpoints {
@@ -666,12 +685,12 @@ func (b *Bundle) ValidateErrorResponse(method, path string, payload []byte) erro
func (b *Bundle) ValidateResponse(method, path string, payload []byte) error {
var value any
- if err := json.Unmarshal(payload, &value); err != nil {
+ if err := decodeSchemaJSON(payload, &value); err != nil {
return err
}
for _, endpoint := range b.Endpoints {
if endpoint.Method == method && endpoint.Path == path {
- if endpoint.Output == BinaryOutput || endpoint.Output == WebSocketOutput || endpoint.Output == SSEOutput {
+ if endpoint.Output == BinaryOutput || endpoint.Output == WebSocketOutput || endpoint.Output == SSEOutput || endpoint.Output == ProxyOutput {
return fmt.Errorf("binary endpoint requires HTTP response validation")
}
return b.validate(endpoint.Response, value, "$")
@@ -686,6 +705,14 @@ func (b *Bundle) ValidateHTTPResponse(method, path string, status int, contentTy
if endpoint.Method != method || endpoint.Path != path {
continue
}
+ if endpoint.Proxy != nil {
+ return b.validateProxyHTTPResponse(endpoint, status, contentType, payload)
+ }
+ for _, emptyStatus := range endpoint.EmptyResponseStatuses {
+ if status == emptyStatus && len(payload) == 0 {
+ return nil
+ }
+ }
if endpoint.NoContent && status == 204 {
if len(payload) != 0 {
return fmt.Errorf("empty response must not contain a body")
@@ -741,7 +768,7 @@ func (b *Bundle) ValidateHTTPResponse(method, path string, status int, contentTy
return fmt.Errorf("unexpected response status or media type: %d %s", status, contentType)
}
var value any
- if err := json.Unmarshal(payload, &value); err != nil {
+ if err := decodeSchemaJSON(payload, &value); err != nil {
return err
}
return b.validate(response, value, "$")
@@ -750,12 +777,13 @@ func (b *Bundle) ValidateHTTPResponse(method, path string, status int, contentTy
}
func (b *Bundle) validate(schema *Schema, value any, path string) error {
+ if schema.Not != nil && b.validate(schema.Not, value, path) == nil {
+ return fmt.Errorf("%s matches an excluded value", path)
+ }
if len(schema.Enum) > 0 {
matched := false
- actual, _ := json.Marshal(value)
for _, option := range schema.Enum {
- expected, _ := json.Marshal(option)
- if string(actual) == string(expected) {
+ if equalSchemaValue(value, option) {
matched = true
break
}
@@ -781,6 +809,8 @@ func (b *Bundle) validate(schema *Schema, value any, path string) error {
}
valid := false
switch schema.Type {
+ case "":
+ valid = true
case "null":
valid = value == nil
case "string":
@@ -788,8 +818,7 @@ func (b *Bundle) validate(schema *Schema, value any, path string) error {
case "boolean":
_, valid = value.(bool)
case "number", "integer":
- number, ok := value.(float64)
- valid = ok && (schema.Type != "integer" || math.Trunc(number) == number)
+ valid = validSchemaNumber(value, schema.Type == "integer")
case "array":
array, ok := value.([]any)
valid = ok
diff --git a/kernel/apicontract/schema_numbers.go b/kernel/apicontract/schema_numbers.go
new file mode 100644
index 0000000000..c128ee475b
--- /dev/null
+++ b/kernel/apicontract/schema_numbers.go
@@ -0,0 +1,55 @@
+package apicontract
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io"
+ "math"
+ "math/big"
+)
+
+// decodeSchemaJSON 保留线协议的数字精度,避免诊断数据中的大整数溢出浮点范围。
+func decodeSchemaJSON(payload []byte, value *any) error {
+ decoder := json.NewDecoder(bytes.NewReader(payload))
+ decoder.UseNumber()
+ if err := decoder.Decode(value); err != nil {
+ return err
+ }
+ var extra any
+ if err := decoder.Decode(&extra); err != io.EOF {
+ if err != nil {
+ return err
+ }
+ return fmt.Errorf("multiple JSON values in response")
+ }
+ return nil
+}
+
+func validSchemaNumber(value any, integer bool) bool {
+ switch number := value.(type) {
+ case json.Number:
+ parsed, ok := new(big.Rat).SetString(string(number))
+ return ok && (!integer || parsed.IsInt())
+ case float64:
+ return !math.IsNaN(number) && !math.IsInf(number, 0) && (!integer || math.Trunc(number) == number)
+ }
+ return false
+}
+
+func equalSchemaValue(actual, expected any) bool {
+ a, err := json.Marshal(actual)
+ if err != nil {
+ return false
+ }
+ b, err := json.Marshal(expected)
+ if err != nil {
+ return false
+ }
+ if bytes.Equal(a, b) {
+ return true
+ }
+ x, xok := new(big.Rat).SetString(string(a))
+ y, yok := new(big.Rat).SetString(string(b))
+ return xok && yok && x.Cmp(y) == 0
+}
diff --git a/kernel/apicontract/schema_numbers_test.go b/kernel/apicontract/schema_numbers_test.go
new file mode 100644
index 0000000000..8288d0cee5
--- /dev/null
+++ b/kernel/apicontract/schema_numbers_test.go
@@ -0,0 +1,36 @@
+package apicontract
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+)
+
+func TestSchemaNumberPrecision(t *testing.T) {
+ bundle := &Bundle{}
+ for _, text := range []string{"1", "1.0", "1e3", "-0.0", strings.Repeat("9", 620)} {
+ var value any
+ if err := decodeSchemaJSON([]byte(text), &value); err != nil {
+ t.Fatal(err)
+ }
+ if err := bundle.validate(&Schema{Type: "integer"}, value, "$"); err != nil {
+ t.Fatalf("integer %s: %v", text, err)
+ }
+ }
+ for _, text := range []string{"1.1", "1e-3"} {
+ if err := bundle.validate(&Schema{Type: "integer"}, json.Number(text), "$"); err == nil {
+ t.Fatalf("fraction accepted as integer: %s", text)
+ }
+ }
+ for _, text := range []string{"1", "1.0", "1e0"} {
+ if err := bundle.validate(&Schema{Type: "integer", Enum: []any{1}}, json.Number(text), "$"); err != nil {
+ t.Fatalf("equivalent enum number rejected: %s: %v", text, err)
+ }
+ }
+ for _, text := range []string{"1 2", "1 trailing", ""} {
+ var value any
+ if err := decodeSchemaJSON([]byte(text), &value); err == nil {
+ t.Fatalf("invalid JSON accepted: %s", text)
+ }
+ }
+}
diff --git a/kernel/apicontract/typescript.go b/kernel/apicontract/typescript.go
index 10289f1c72..68ce5202c7 100644
--- a/kernel/apicontract/typescript.go
+++ b/kernel/apicontract/typescript.go
@@ -127,6 +127,10 @@ func (b *Bundle) TypeScript(legacy []Route) []byte {
var output strings.Builder
output.WriteString("// 此文件由内核契约生成,请运行 pnpm run api:generate 更新。\n\n")
for _, name := range sortedKeys(b.Definitions) {
+ if name == "UnknownTransactionAction" {
+ fmt.Fprintf(&output, "export type %s = string & { readonly __unknownTransactionAction: unique symbol };\n\n", name)
+ continue
+ }
fmt.Fprintf(&output, "export type %s = %s;\n\n", name, b.typeScript(b.Definitions[name]))
}
for _, method := range []string{"GET", "POST"} {
@@ -161,6 +165,10 @@ func (b *Bundle) TypeScript(legacy []Route) []byte {
if endpoint.NoContent {
output.WriteString(" noContent: true;\n")
}
+ if len(endpoint.EmptyResponseStatuses) > 0 {
+ statuses, _ := json.Marshal(endpoint.EmptyResponseStatuses)
+ fmt.Fprintf(&output, " emptyResponseStatuses: %s;\n", statuses)
+ }
if len(endpoint.AdditionalErrorStatuses) > 0 {
statuses, _ := json.Marshal(endpoint.AdditionalErrorStatuses)
fmt.Fprintf(&output, " additionalErrorStatuses: %s;\n", statuses)
@@ -179,6 +187,10 @@ func (b *Bundle) TypeScript(legacy []Route) []byte {
}
output.WriteString("}; };\n")
}
+ if proxy := endpoint.Proxy; proxy != nil {
+ protocol, _ := json.Marshal(proxy)
+ fmt.Fprintf(&output, " proxy: %s;\n", protocol)
+ }
output.WriteString(" };\n")
}
output.WriteString("}\n\n")
@@ -216,6 +228,8 @@ export interface APIFormData<Request> extends FormData {
}
type APIRequestArgs<C extends APIContract> = C["body"] extends "multipart" | "form"
? [data: APIFormData<C["request"]>]
+ : C["body"] extends "raw"
+ ? [data?: JSONValue | FormData | null]
: C["body"] extends "json" | "structJSON"
? [data: C["request"]]
: [data?: C["request"] | null];
@@ -226,8 +240,12 @@ export type APICallbackResponse<R> = R extends {code: infer C extends number}
type APIDirectCallbackResponse<R> = R extends {code: number} ? APICallbackResponse<R> : R;
+type APIEmptyResponse<C> = C extends {emptyResponseStatuses: ReadonlyArray<number>} ? "" : never;
+type APIPostEmptyResponse<C> = C extends {emptyResponseStatuses: infer S extends ReadonlyArray<number>}
+ ? Exclude<S[number], 401 | 403 | 404> extends never ? never : "" : never;
+
type APIPostTail<C extends APIContract> = [
- cb?: (response: C extends {output: "binary"} ? JSONValue : C extends {output: "directJSON"} ? APIDirectCallbackResponse<C["response"]> | (C extends {noContent: true} ? "" : never) : C extends {output: "sse"} ? string | APICallbackResponse<C["response"]> : APICallbackResponse<C["response"]>) => void,
+ cb?: (response: (C extends {output: "binary" | "proxy"} ? JSONValue : C extends {output: "directJSON"} ? APIDirectCallbackResponse<C["response"]> | (C extends {noContent: true} ? "" : never) : C extends {output: "sse"} ? string | APICallbackResponse<C["response"]> : APICallbackResponse<C["response"]>) | APIPostEmptyResponse<C>) => void,
headers?: Record<string, string>,
failCallback?: (response: APIFetchFailure) => void,
signal?: AbortSignal,
@@ -259,13 +277,13 @@ export type FetchSyncPost<Legacy = APILegacyResponse> = <Path extends string>(
: Path extends APILegacyPOSTPath ? [data?: any, ...tail: APISyncTail]
: string extends Path ? [data?: any, ...tail: APISyncTail] : never
) => Promise<Path extends keyof APIPOSTRoutes
- ? APIPOSTRoutes[Path] extends {output: "binary"} ? JSONValue : APIPOSTRoutes[Path]["response"] | APITransportError
+ ? APIPOSTRoutes[Path] extends {output: "binary" | "proxy"} ? JSONValue : APIPOSTRoutes[Path]["response"] | APITransportError
: Legacy>;
export type FetchGet<Legacy = APILegacyResponse | string> = <Path extends string>(
url: Path,
...args: Path extends keyof APIGETRoutes
- ? [cb: (response: APIGETRoutes[Path]["response"] | (APIGETRoutes[Path] extends {output: "websocket"} ? string : never)) => void]
+ ? [cb: (response: APIGETRoutes[Path] extends {output: "binary" | "proxy"} ? JSONValue : APIGETRoutes[Path]["response"] | APIEmptyResponse<APIGETRoutes[Path]> | (APIGETRoutes[Path] extends {output: "websocket" | "sse"} ? string : never)) => void]
: Path extends keyof APIPOSTRoutes ? never
: [cb: (response: Legacy) => void]
) => void;