refactor(onebot): declare every action param the handler reads

Action handlers now only see fields from the param table. Extra client
keys are still ignored. Garbage values on declared numbers fail instead
of becoming zero.
This commit is contained in:
DrSmoothl committed 2026-08-30 00:56:01 +08:00
1 parent 117335166f
commit f6adadcd12
14 files changed
+950 -233

No files matched your search

+355 -34
View File
@@ -726,6 +726,24 @@
"type": "integer", "type": "integer",
"minimum": 1 "minimum": 1
} }
},
{
"name": "button_id",
"type": "string",
"required": true,
"schema": {
"type": "string",
"minLength": 1
}
},
{
"name": "callback_data",
"type": "string",
"required": false,
"schema": {
"type": "string"
},
"default": ""
} }
], ],
"invariants": [], "invariants": [],
@@ -745,12 +763,21 @@
"msg_seq": { "msg_seq": {
"type": "integer", "type": "integer",
"minimum": 1 "minimum": 1
},
"button_id": {
"type": "string",
"minLength": 1
},
"callback_data": {
"type": "string",
"default": ""
} }
}, },
"required": [ "required": [
"group_id", "group_id",
"bot_appid", "bot_appid",
"msg_seq" "msg_seq",
"button_id"
], ],
"additionalProperties": true "additionalProperties": true
}, },
@@ -1577,6 +1604,12 @@
"type": "string" "type": "string"
}, },
"default": "" "default": ""
},
{
"name": "headers",
"type": "raw",
"required": false,
"schema": {}
} }
], ],
"invariants": [], "invariants": [],
@@ -1594,7 +1627,8 @@
"name": { "name": {
"type": "string", "type": "string",
"default": "" "default": ""
} },
"headers": {}
}, },
"additionalProperties": true "additionalProperties": true
}, },
@@ -2268,13 +2302,15 @@
"params": [ "params": [
{ {
"name": "message_id", "name": "message_id",
"type": "string", "type": "messageId",
"required": false, "required": true,
"role": "message_id",
"schema": { "schema": {
"type": "string" "type": "integer",
}, "not": {
"default": "", "const": 0
"role": "message_id" }
}
} }
], ],
"invariants": [], "invariants": [],
@@ -2282,11 +2318,16 @@
"type": "object", "type": "object",
"properties": { "properties": {
"message_id": { "message_id": {
"type": "string", "type": "integer",
"default": "", "not": {
"const": 0
},
"x-role": "message_id" "x-role": "message_id"
} }
}, },
"required": [
"message_id"
],
"additionalProperties": true "additionalProperties": true
}, },
"category": "扩展" "category": "扩展"
@@ -3661,6 +3702,14 @@
"schema": { "schema": {
"type": "string" "type": "string"
} }
},
{
"name": "message_id",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
} }
], ],
"invariants": [], "invariants": [],
@@ -3669,6 +3718,9 @@
"properties": { "properties": {
"id": { "id": {
"type": "string" "type": "string"
},
"message_id": {
"type": "string"
} }
}, },
"additionalProperties": true "additionalProperties": true
@@ -4766,9 +4818,11 @@
}, },
{ {
"name": "type", "name": "type",
"type": "raw", "type": "string",
"required": false, "required": false,
"schema": {} "schema": {
"type": "string"
}
} }
], ],
"invariants": [], "invariants": [],
@@ -4781,7 +4835,9 @@
"description": "群号", "description": "群号",
"x-role": "group_id" "x-role": "group_id"
}, },
"type": {} "type": {
"type": "string"
}
}, },
"required": [ "required": [
"group_id" "group_id"
@@ -6138,11 +6194,90 @@
"aliases": [], "aliases": [],
"summary": "获取小程序卡片 ark", "summary": "获取小程序卡片 ark",
"readOnly": true, "readOnly": true,
"params": [], "params": [
{
"name": "type",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "title",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "desc",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "picUrl",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "pic_url",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "jumpUrl",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "jump_url",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
}
],
"invariants": [], "invariants": [],
"inputSchema": { "inputSchema": {
"type": "object", "type": "object",
"properties": {}, "properties": {
"type": {
"type": "string"
},
"title": {
"type": "string"
},
"desc": {
"type": "string"
},
"picUrl": {
"type": "string"
},
"pic_url": {
"type": "string"
},
"jumpUrl": {
"type": "string"
},
"jump_url": {
"type": "string"
}
},
"additionalProperties": true "additionalProperties": true
}, },
"category": "扩展" "category": "扩展"
@@ -8748,6 +8883,62 @@
"schema": { "schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
} }
},
{
"name": "message_type",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "group_id",
"type": "int",
"required": false,
"schema": {
"type": "integer",
"minimum": 0
}
},
{
"name": "user_id",
"type": "int",
"required": false,
"schema": {
"type": "integer",
"minimum": 0
}
},
{
"name": "source",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "summary",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "prompt",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "news",
"type": "raw",
"required": false,
"schema": {}
} }
], ],
"invariants": [], "invariants": [],
@@ -8759,7 +8950,28 @@
}, },
"message": { "message": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
} },
"message_type": {
"type": "string"
},
"group_id": {
"type": "integer",
"minimum": 0
},
"user_id": {
"type": "integer",
"minimum": 0
},
"source": {
"type": "string"
},
"summary": {
"type": "string"
},
"prompt": {
"type": "string"
},
"news": {}
}, },
"additionalProperties": true "additionalProperties": true
}, },
@@ -8917,6 +9129,36 @@
"schema": { "schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
} }
},
{
"name": "source",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "summary",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "prompt",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "news",
"type": "raw",
"required": false,
"schema": {}
} }
], ],
"invariants": [], "invariants": [],
@@ -8934,7 +9176,17 @@
}, },
"message": { "message": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
} },
"source": {
"type": "string"
},
"summary": {
"type": "string"
},
"prompt": {
"type": "string"
},
"news": {}
}, },
"required": [ "required": [
"group_id" "group_id"
@@ -9280,6 +9532,36 @@
"schema": { "schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
} }
},
{
"name": "source",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "summary",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "prompt",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "news",
"type": "raw",
"required": false,
"schema": {}
} }
], ],
"invariants": [], "invariants": [],
@@ -9296,7 +9578,17 @@
}, },
"message": { "message": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
} },
"source": {
"type": "string"
},
"summary": {
"type": "string"
},
"prompt": {
"type": "string"
},
"news": {}
}, },
"required": [ "required": [
"user_id" "user_id"
@@ -9983,15 +10275,19 @@
}, },
{ {
"name": "sub_type", "name": "sub_type",
"type": "raw", "type": "string",
"required": false, "required": false,
"schema": {} "schema": {
"type": "string"
}
}, },
{ {
"name": "type", "name": "type",
"type": "raw", "type": "string",
"required": false, "required": false,
"schema": {} "schema": {
"type": "string"
}
}, },
{ {
"name": "approve", "name": "approve",
@@ -10020,8 +10316,12 @@
"type": "string", "type": "string",
"minLength": 1 "minLength": 1
}, },
"sub_type": {}, "sub_type": {
"type": {}, "type": "string"
},
"type": {
"type": "string"
},
"approve": { "approve": {
"type": "boolean", "type": "boolean",
"default": true "default": true
@@ -11692,23 +11992,31 @@
"params": [ "params": [
{ {
"name": "longNick", "name": "longNick",
"type": "raw", "type": "string",
"required": false, "required": false,
"schema": {} "schema": {
"type": "string"
}
}, },
{ {
"name": "long_nick", "name": "long_nick",
"type": "raw", "type": "string",
"required": false, "required": false,
"schema": {} "schema": {
"type": "string"
}
} }
], ],
"invariants": [], "invariants": [],
"inputSchema": { "inputSchema": {
"type": "object", "type": "object",
"properties": { "properties": {
"longNick": {}, "longNick": {
"long_nick": {} "type": "string"
},
"long_nick": {
"type": "string"
}
}, },
"additionalProperties": true "additionalProperties": true
}, },
@@ -11933,17 +12241,30 @@
"params": [ "params": [
{ {
"name": "words", "name": "words",
"type": "raw", "type": "string[]",
"required": false, "required": true,
"schema": {} "schema": {
"type": "array",
"items": {
"type": "string"
}
}
} }
], ],
"invariants": [], "invariants": [],
"inputSchema": { "inputSchema": {
"type": "object", "type": "object",
"properties": { "properties": {
"words": {} "words": {
"type": "array",
"items": {
"type": "string"
}
}
}, },
"required": [
"words"
],
"additionalProperties": true "additionalProperties": true
}, },
"category": "扩展" "category": "扩展"
+355 -34
View File
@@ -729,6 +729,24 @@ export const ACTIONS: CatalogAction[] = [
"type": "integer", "type": "integer",
"minimum": 1 "minimum": 1
} }
},
{
"name": "button_id",
"type": "string",
"required": true,
"schema": {
"type": "string",
"minLength": 1
}
},
{
"name": "callback_data",
"type": "string",
"required": false,
"schema": {
"type": "string"
},
"default": ""
} }
], ],
"invariants": [], "invariants": [],
@@ -748,12 +766,21 @@ export const ACTIONS: CatalogAction[] = [
"msg_seq": { "msg_seq": {
"type": "integer", "type": "integer",
"minimum": 1 "minimum": 1
},
"button_id": {
"type": "string",
"minLength": 1
},
"callback_data": {
"type": "string",
"default": ""
} }
}, },
"required": [ "required": [
"group_id", "group_id",
"bot_appid", "bot_appid",
"msg_seq" "msg_seq",
"button_id"
], ],
"additionalProperties": true "additionalProperties": true
}, },
@@ -1580,6 +1607,12 @@ export const ACTIONS: CatalogAction[] = [
"type": "string" "type": "string"
}, },
"default": "" "default": ""
},
{
"name": "headers",
"type": "raw",
"required": false,
"schema": {}
} }
], ],
"invariants": [], "invariants": [],
@@ -1597,7 +1630,8 @@ export const ACTIONS: CatalogAction[] = [
"name": { "name": {
"type": "string", "type": "string",
"default": "" "default": ""
} },
"headers": {}
}, },
"additionalProperties": true "additionalProperties": true
}, },
@@ -2271,13 +2305,15 @@ export const ACTIONS: CatalogAction[] = [
"params": [ "params": [
{ {
"name": "message_id", "name": "message_id",
"type": "string", "type": "messageId",
"required": false, "required": true,
"role": "message_id",
"schema": { "schema": {
"type": "string" "type": "integer",
}, "not": {
"default": "", "const": 0
"role": "message_id" }
}
} }
], ],
"invariants": [], "invariants": [],
@@ -2285,11 +2321,16 @@ export const ACTIONS: CatalogAction[] = [
"type": "object", "type": "object",
"properties": { "properties": {
"message_id": { "message_id": {
"type": "string", "type": "integer",
"default": "", "not": {
"const": 0
},
"x-role": "message_id" "x-role": "message_id"
} }
}, },
"required": [
"message_id"
],
"additionalProperties": true "additionalProperties": true
}, },
"category": "扩展" "category": "扩展"
@@ -3664,6 +3705,14 @@ export const ACTIONS: CatalogAction[] = [
"schema": { "schema": {
"type": "string" "type": "string"
} }
},
{
"name": "message_id",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
} }
], ],
"invariants": [], "invariants": [],
@@ -3672,6 +3721,9 @@ export const ACTIONS: CatalogAction[] = [
"properties": { "properties": {
"id": { "id": {
"type": "string" "type": "string"
},
"message_id": {
"type": "string"
} }
}, },
"additionalProperties": true "additionalProperties": true
@@ -4769,9 +4821,11 @@ export const ACTIONS: CatalogAction[] = [
}, },
{ {
"name": "type", "name": "type",
"type": "raw", "type": "string",
"required": false, "required": false,
"schema": {} "schema": {
"type": "string"
}
} }
], ],
"invariants": [], "invariants": [],
@@ -4784,7 +4838,9 @@ export const ACTIONS: CatalogAction[] = [
"description": "群号", "description": "群号",
"x-role": "group_id" "x-role": "group_id"
}, },
"type": {} "type": {
"type": "string"
}
}, },
"required": [ "required": [
"group_id" "group_id"
@@ -6141,11 +6197,90 @@ export const ACTIONS: CatalogAction[] = [
"aliases": [], "aliases": [],
"summary": "获取小程序卡片 ark", "summary": "获取小程序卡片 ark",
"readOnly": true, "readOnly": true,
"params": [], "params": [
{
"name": "type",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "title",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "desc",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "picUrl",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "pic_url",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "jumpUrl",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "jump_url",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
}
],
"invariants": [], "invariants": [],
"inputSchema": { "inputSchema": {
"type": "object", "type": "object",
"properties": {}, "properties": {
"type": {
"type": "string"
},
"title": {
"type": "string"
},
"desc": {
"type": "string"
},
"picUrl": {
"type": "string"
},
"pic_url": {
"type": "string"
},
"jumpUrl": {
"type": "string"
},
"jump_url": {
"type": "string"
}
},
"additionalProperties": true "additionalProperties": true
}, },
"category": "扩展" "category": "扩展"
@@ -8751,6 +8886,62 @@ export const ACTIONS: CatalogAction[] = [
"schema": { "schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
} }
},
{
"name": "message_type",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "group_id",
"type": "int",
"required": false,
"schema": {
"type": "integer",
"minimum": 0
}
},
{
"name": "user_id",
"type": "int",
"required": false,
"schema": {
"type": "integer",
"minimum": 0
}
},
{
"name": "source",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "summary",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "prompt",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "news",
"type": "raw",
"required": false,
"schema": {}
} }
], ],
"invariants": [], "invariants": [],
@@ -8762,7 +8953,28 @@ export const ACTIONS: CatalogAction[] = [
}, },
"message": { "message": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
} },
"message_type": {
"type": "string"
},
"group_id": {
"type": "integer",
"minimum": 0
},
"user_id": {
"type": "integer",
"minimum": 0
},
"source": {
"type": "string"
},
"summary": {
"type": "string"
},
"prompt": {
"type": "string"
},
"news": {}
}, },
"additionalProperties": true "additionalProperties": true
}, },
@@ -8920,6 +9132,36 @@ export const ACTIONS: CatalogAction[] = [
"schema": { "schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
} }
},
{
"name": "source",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "summary",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "prompt",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "news",
"type": "raw",
"required": false,
"schema": {}
} }
], ],
"invariants": [], "invariants": [],
@@ -8937,7 +9179,17 @@ export const ACTIONS: CatalogAction[] = [
}, },
"message": { "message": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
} },
"source": {
"type": "string"
},
"summary": {
"type": "string"
},
"prompt": {
"type": "string"
},
"news": {}
}, },
"required": [ "required": [
"group_id" "group_id"
@@ -9283,6 +9535,36 @@ export const ACTIONS: CatalogAction[] = [
"schema": { "schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
} }
},
{
"name": "source",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "summary",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "prompt",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "news",
"type": "raw",
"required": false,
"schema": {}
} }
], ],
"invariants": [], "invariants": [],
@@ -9299,7 +9581,17 @@ export const ACTIONS: CatalogAction[] = [
}, },
"message": { "message": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
} },
"source": {
"type": "string"
},
"summary": {
"type": "string"
},
"prompt": {
"type": "string"
},
"news": {}
}, },
"required": [ "required": [
"user_id" "user_id"
@@ -9986,15 +10278,19 @@ export const ACTIONS: CatalogAction[] = [
}, },
{ {
"name": "sub_type", "name": "sub_type",
"type": "raw", "type": "string",
"required": false, "required": false,
"schema": {} "schema": {
"type": "string"
}
}, },
{ {
"name": "type", "name": "type",
"type": "raw", "type": "string",
"required": false, "required": false,
"schema": {} "schema": {
"type": "string"
}
}, },
{ {
"name": "approve", "name": "approve",
@@ -10023,8 +10319,12 @@ export const ACTIONS: CatalogAction[] = [
"type": "string", "type": "string",
"minLength": 1 "minLength": 1
}, },
"sub_type": {}, "sub_type": {
"type": {}, "type": "string"
},
"type": {
"type": "string"
},
"approve": { "approve": {
"type": "boolean", "type": "boolean",
"default": true "default": true
@@ -11695,23 +11995,31 @@ export const ACTIONS: CatalogAction[] = [
"params": [ "params": [
{ {
"name": "longNick", "name": "longNick",
"type": "raw", "type": "string",
"required": false, "required": false,
"schema": {} "schema": {
"type": "string"
}
}, },
{ {
"name": "long_nick", "name": "long_nick",
"type": "raw", "type": "string",
"required": false, "required": false,
"schema": {} "schema": {
"type": "string"
}
} }
], ],
"invariants": [], "invariants": [],
"inputSchema": { "inputSchema": {
"type": "object", "type": "object",
"properties": { "properties": {
"longNick": {}, "longNick": {
"long_nick": {} "type": "string"
},
"long_nick": {
"type": "string"
}
}, },
"additionalProperties": true "additionalProperties": true
}, },
@@ -11936,17 +12244,30 @@ export const ACTIONS: CatalogAction[] = [
"params": [ "params": [
{ {
"name": "words", "name": "words",
"type": "raw", "type": "string[]",
"required": false, "required": true,
"schema": {} "schema": {
"type": "array",
"items": {
"type": "string"
}
}
} }
], ],
"invariants": [], "invariants": [],
"inputSchema": { "inputSchema": {
"type": "object", "type": "object",
"properties": { "properties": {
"words": {} "words": {
"type": "array",
"items": {
"type": "string"
}
}
}, },
"required": [
"words"
],
"additionalProperties": true "additionalProperties": true
}, },
"category": "扩展" "category": "扩展"
+5 -9
View File
@@ -483,11 +483,7 @@ interface ActionDef<S extends Spec> {
readOnly?: boolean; readOnly?: boolean;
params: S; params: S;
rules?: (r: RuleBuilders<InferParams<S>>) => readonly CrossFieldRule[]; rules?: (r: RuleBuilders<InferParams<S>>) => readonly CrossFieldRule[];
/** `raw` is the original untouched params — an escape hatch for the run: (p: InferParams<S>, ctx: ApiActionContext) => Promise<ApiResponse> | ApiResponse;
* irregular tail (alias-key fallbacks, arbitrary nested objects). Declared
* fields in `p` remain the validated path; reach for `raw` only for keys
* the spec can't express. */
run: (p: InferParams<S>, ctx: ApiActionContext, raw: JsonObject) => Promise<ApiResponse> | ApiResponse;
} }
const wording = (e: Err): string => (e.field ? `${e.field}: ${e.reason}` : e.reason); const wording = (e: Err): string => (e.field ? `${e.field}: ${e.reason}` : e.reason);
@@ -517,7 +513,7 @@ export function defineAction<S extends Spec>(def: ActionDef<S>): ActionSpec<S> {
const toHandler = (ctx: ApiActionContext): Handler => async (params: JsonObject) => { const toHandler = (ctx: ApiActionContext): Handler => async (params: JsonObject) => {
const r = parse(params); const r = parse(params);
if (!r.ok) return failedResponse(RETCODE.BAD_REQUEST, wording(r)); if (!r.ok) return failedResponse(RETCODE.BAD_REQUEST, wording(r));
return def.run(r.value, ctx, params); return def.run(r.value, ctx);
}; };
return { return {
@@ -571,7 +567,7 @@ interface StreamActionDef<S extends Spec> {
readOnly?: boolean; readOnly?: boolean;
params: S; params: S;
rules?: (r: RuleBuilders<InferParams<S>>) => readonly CrossFieldRule[]; rules?: (r: RuleBuilders<InferParams<S>>) => readonly CrossFieldRule[];
run: (p: InferParams<S>, ctx: ApiActionContext, raw: JsonObject, sink: StreamSink) => Promise<ApiResponse> | ApiResponse; run: (p: InferParams<S>, ctx: ApiActionContext, sink: StreamSink) => Promise<ApiResponse> | ApiResponse;
} }
export interface StreamActionSpec<S extends Spec> extends RegisteredActionSpec { export interface StreamActionSpec<S extends Spec> extends RegisteredActionSpec {
@@ -599,7 +595,7 @@ export function defineStreamAction<S extends Spec>(def: StreamActionDef<S>): Str
const toHandler = (ctx: ApiActionContext): Handler => async (params, sink) => { const toHandler = (ctx: ApiActionContext): Handler => async (params, sink) => {
const r = base.parse(params); const r = base.parse(params);
if (!r.ok) return failedResponse(RETCODE.BAD_REQUEST, wording(r)); if (!r.ok) return failedResponse(RETCODE.BAD_REQUEST, wording(r));
return def.run(r.value, ctx, params, sink ?? NOOP_SINK); return def.run(r.value, ctx, sink ?? NOOP_SINK);
}; };
return { return {
@@ -628,7 +624,7 @@ interface PresetDef<S extends Spec, Extra> {
readOnly?: boolean; readOnly?: boolean;
params?: S; params?: S;
rules?: (r: RuleBuilders<InferParams<S> & Extra>) => readonly CrossFieldRule[]; rules?: (r: RuleBuilders<InferParams<S> & Extra>) => readonly CrossFieldRule[];
run: (p: InferParams<S> & Extra, ctx: ApiActionContext, raw: JsonObject) => Promise<ApiResponse> | ApiResponse; run: (p: InferParams<S> & Extra, ctx: ApiActionContext) => Promise<ApiResponse> | ApiResponse;
} }
/** Pre-seeds `group_id` (uint, required). */ /** Pre-seeds `group_id` (uint, required). */
+129 -63
View File
@@ -6,7 +6,6 @@ import type {
GroupEssenceMessage, GroupEssenceMessage,
} from '@snowluma/protocol/web/group-essence'; } from '@snowluma/protocol/web/group-essence';
import type { ApiActionContext } from '../api-handler'; import type { ApiActionContext } from '../api-handler';
import { asNumber, asString } from '../api-handler';
import type { ForwardPreviewMeta } from '../modules/message-actions'; import type { ForwardPreviewMeta } from '../modules/message-actions';
import { import {
hasAuthoritativeSequence, hasAuthoritativeSequence,
@@ -14,9 +13,10 @@ import {
failedResponse, failedResponse,
okResponse, okResponse,
type JsonObject, type JsonObject,
type JsonValue,
type MessageMeta, type MessageMeta,
} from '../types'; } from '../types';
import { defineAction, groupAction, groupUserAction, f } from '../action-kit'; import { defineAction, groupAction, groupUserAction, f, type Field } from '../action-kit';
import { groupInfoReturnsSchema } from './group-info'; import { groupInfoReturnsSchema } from './group-info';
import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id'; import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id';
@@ -262,19 +262,57 @@ async function saveDownloadBuffer(buf: Buffer, preferredName: string): Promise<s
return resolved; return resolved;
} }
// 从 send_*_forward_msg 的参数里提取 NapCat 兼容的转发预览元信息。四个字段都是可选的——如果没有提供,模块层会根据实际消息节点列表推断出合理的默认值。 function optionalExactString(): Field<string | undefined> {
function readForwardPreviewMeta(params: Record<string, unknown>): ForwardPreviewMeta | undefined { const inner = f.string().optional();
const source = asString(params.source) || undefined; return Object.assign(Object.create(inner) as Field<string | undefined>, {
const summary = asString(params.summary) || undefined; coerce(raw: unknown, field: string) {
const prompt = asString(params.prompt) || undefined; if (typeof raw === 'number' || typeof raw === 'boolean' || raw === null
|| (typeof raw === 'object' && raw !== null)) {
return { ok: false as const, field, reason: 'expected a string' };
}
return inner.coerce(raw as Parameters<Field<string | undefined>['coerce']>[0], field);
},
});
}
function integerFromDecimalString(value: string): number {
if (value.trim() === '') return 0;
const n = Number(value);
return Number.isFinite(n) ? Math.trunc(n) : 0;
}
function primitiveText(value: unknown): string {
if (typeof value === 'string') return value;
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
return '';
}
const forwardPreviewParams = {
source: f.string().optional(),
summary: f.string().optional(),
prompt: f.string().optional(),
news: f.raw(),
};
// NapCat-compatible forward preview. All four fields are optional — if none
// are provided, the message module infers defaults from the node list.
function readForwardPreviewMeta(p: {
source?: string;
summary?: string;
prompt?: string;
news?: JsonValue;
}): ForwardPreviewMeta | undefined {
const source = p.source || undefined;
const summary = p.summary || undefined;
const prompt = p.prompt || undefined;
let news: Array<{ text: string }> | undefined; let news: Array<{ text: string }> | undefined;
if (Array.isArray(params.news)) { if (Array.isArray(p.news)) {
const collected: Array<{ text: string }> = []; const collected: Array<{ text: string }> = [];
for (const item of params.news) { for (const item of p.news) {
if (typeof item === 'string') { if (typeof item === 'string') {
collected.push({ text: item }); collected.push({ text: item });
} else if (item && typeof item === 'object' && !Array.isArray(item)) { } else if (item && typeof item === 'object' && !Array.isArray(item)) {
const text = asString((item as Record<string, unknown>).text); const text = primitiveText((item as Record<string, unknown>).text);
if (text) collected.push({ text }); if (text) collected.push({ text });
} }
} }
@@ -801,13 +839,10 @@ export const actions = [
required: ['text'], required: ['text'],
}, },
params: { params: {
message_id: f.string().default('').role('message_id'), message_id: f.messageId(),
}, },
// `raw` so message_id works whether the client sends a number or a string. run: async (p, ctx) => {
run: async (_p, ctx, raw) => { return okResponse(await ctx.fetchPttText(p.message_id));
const messageId = asNumber(raw.message_id);
if (!messageId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
return okResponse(await ctx.fetchPttText(messageId));
}, },
}), }),
@@ -2268,8 +2303,7 @@ export const actions = [
}, },
}), }),
// ===== 原 legacy registerAction,现并入 kit(ctx 调用与逻辑逐字保留; // ===== 原 legacy registerAction,现并入 kit =====
// 别名键 / 原始参数透传 / 任意对象经 run 第三参 raw 或 f.raw() 表达)=====
defineAction({ defineAction({
name: ['get_rkey', 'nc_get_rkey'], name: ['get_rkey', 'nc_get_rkey'],
@@ -2407,16 +2441,22 @@ export const actions = [
name: 'send_forward_msg', name: 'send_forward_msg',
summary: '发送合并转发(按 message_type/群号自动路由)', summary: '发送合并转发(按 message_type/群号自动路由)',
returns: '{ message_id, res_id, forward_id }', returns: '{ message_id, res_id, forward_id }',
// group_id/user_id 是“路由提示”而非身份字段:原实现用 asNumber + `>0` 判断, // group_id/user_id are routing hints, not identity: 0 means "this branch
// 占位的 0 表示“该分支不适用”、不应报错。故从 raw 读取(保持旧语义), // does not apply" and must not error. int({min:0}) optional, not groupId.
// 只声明 messages/message。 params: {
params: { messages: f.message().optional(), message: f.message().optional() }, messages: f.message().optional(),
run: async (p, ctx, raw) => { message: f.message().optional(),
const messageType = asString(raw.message_type); message_type: f.string().optional(),
const groupId = asNumber(raw.group_id); group_id: f.int({ min: 0 }).optional(),
const userId = asNumber(raw.user_id); user_id: f.int({ min: 0 }).optional(),
...forwardPreviewParams,
},
run: async (p, ctx) => {
const messageType = p.message_type ?? '';
const groupId = p.group_id ?? 0;
const userId = p.user_id ?? 0;
const messages = p.messages ?? p.message; const messages = p.messages ?? p.message;
const meta = readForwardPreviewMeta(raw); const meta = readForwardPreviewMeta(p);
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
if ((messageType === 'group' || groupId > 0) && ctx.sendGroupForwardMsg) { if ((messageType === 'group' || groupId > 0) && ctx.sendGroupForwardMsg) {
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
@@ -2437,11 +2477,15 @@ export const actions = [
name: 'send_group_forward_msg', name: 'send_group_forward_msg',
summary: '发送群合并转发', summary: '发送群合并转发',
returns: '{ message_id, res_id, forward_id }', returns: '{ message_id, res_id, forward_id }',
params: { messages: f.message().optional(), message: f.message().optional() }, params: {
run: async (p, ctx, raw) => { messages: f.message().optional(),
message: f.message().optional(),
...forwardPreviewParams,
},
run: async (p, ctx) => {
const messages = p.messages ?? p.message; const messages = p.messages ?? p.message;
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
const result = await ctx.sendGroupForwardMsg(p.group_id, messages, readForwardPreviewMeta(raw)); const result = await ctx.sendGroupForwardMsg(p.group_id, messages, readForwardPreviewMeta(p));
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId }); return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
}, },
}), }),
@@ -2450,11 +2494,16 @@ export const actions = [
name: 'send_private_forward_msg', name: 'send_private_forward_msg',
summary: '发送私聊合并转发', summary: '发送私聊合并转发',
returns: '{ message_id, res_id, forward_id }', returns: '{ message_id, res_id, forward_id }',
params: { user_id: f.userId(), messages: f.message().optional(), message: f.message().optional() }, params: {
run: async (p, ctx, raw) => { user_id: f.userId(),
messages: f.message().optional(),
message: f.message().optional(),
...forwardPreviewParams,
},
run: async (p, ctx) => {
const messages = p.messages ?? p.message; const messages = p.messages ?? p.message;
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
const result = await ctx.sendPrivateForwardMsg(p.user_id, messages, readForwardPreviewMeta(raw)); const result = await ctx.sendPrivateForwardMsg(p.user_id, messages, readForwardPreviewMeta(p));
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId }); return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
}, },
}), }),
@@ -2471,12 +2520,11 @@ export const actions = [
}, },
required: ['messages'], required: ['messages'],
}, },
params: { id: f.string().optional() }, params: { id: f.string().optional(), message_id: f.string().optional() },
run: async (p, ctx, raw) => { run: async (p, ctx) => {
let id = p.id || ''; let id = p.id || '';
if (!id) { if (!id && p.message_id !== undefined) {
const rawMessageId = raw.message_id; const numericMessageId = integerFromDecimalString(p.message_id);
const numericMessageId = asNumber(rawMessageId);
if (numericMessageId > 0) { if (numericMessageId > 0) {
const event = ctx.getMessage(numericMessageId); const event = ctx.getMessage(numericMessageId);
const segments = Array.isArray(event?.message) ? event.message : []; const segments = Array.isArray(event?.message) ? event.message : [];
@@ -2487,11 +2535,11 @@ export const actions = [
const data = (typeof so.data === 'object' && so.data !== null && !Array.isArray(so.data)) const data = (typeof so.data === 'object' && so.data !== null && !Array.isArray(so.data))
? so.data as Record<string, unknown> ? so.data as Record<string, unknown>
: null; : null;
const candidate = asString(data?.id) || asString(data?.res_id) || asString(data?.forward_id); const candidate = primitiveText(data?.id) || primitiveText(data?.res_id) || primitiveText(data?.forward_id);
if (candidate) { id = candidate; break; } if (candidate) { id = candidate; break; }
} }
} }
if (!id) id = asString(rawMessageId); if (!id) id = p.message_id;
} }
if (!id) return failedResponse(RETCODE.BAD_REQUEST, 'id or message_id is required'); if (!id) return failedResponse(RETCODE.BAD_REQUEST, 'id or message_id is required');
const messages = await ctx.getForwardMsg(id); const messages = await ctx.getForwardMsg(id);
@@ -2503,8 +2551,13 @@ export const actions = [
name: 'download_file', name: 'download_file',
summary: '下载文件(url 或 base64)到 data/downloads', summary: '下载文件(url 或 base64)到 data/downloads',
returns: '{ file }', returns: '{ file }',
params: { url: f.string().default(''), base64: f.string().default(''), name: f.string().default('') }, params: {
run: async (p, _ctx, raw) => { url: f.string().default(''),
base64: f.string().default(''),
name: f.string().default(''),
headers: f.raw(),
},
run: async (p) => {
const url = p.url; const url = p.url;
const base64 = p.base64; const base64 = p.base64;
const name = p.name; const name = p.name;
@@ -2516,7 +2569,7 @@ export const actions = [
buf = Buffer.from(base64, 'base64'); buf = Buffer.from(base64, 'base64');
if (buf.length > DOWNLOAD_FILE_MAX_BYTES) return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: ${buf.length} > ${DOWNLOAD_FILE_MAX_BYTES} bytes`); if (buf.length > DOWNLOAD_FILE_MAX_BYTES) return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: ${buf.length} > ${DOWNLOAD_FILE_MAX_BYTES} bytes`);
} else { } else {
buf = await fetchDownloadFile(url, parseDownloadHeaders(raw.headers), DOWNLOAD_FILE_MAX_BYTES, DOWNLOAD_FILE_TIMEOUT_MS); buf = await fetchDownloadFile(url, parseDownloadHeaders(p.headers), DOWNLOAD_FILE_MAX_BYTES, DOWNLOAD_FILE_TIMEOUT_MS);
} }
try { try {
const safe = await saveDownloadBuffer(buf, name); const safe = await saveDownloadBuffer(buf, name);
@@ -2539,12 +2592,9 @@ export const actions = [
}, },
required: ['words'], required: ['words'],
}, },
params: { words: f.raw() }, params: { words: f.array(f.string()) },
run: async (p, ctx) => { run: async (p, ctx) => {
const rawWords = p.words; const translated = await ctx.bridge.apis.misc.translateEn2Zh(p.words);
if (!Array.isArray(rawWords)) return failedResponse(RETCODE.BAD_REQUEST, 'invalid words array');
const words = rawWords.map((w) => String(w));
const translated = await ctx.bridge.apis.misc.translateEn2Zh(words);
return okResponse({ words: translated }); return okResponse({ words: translated });
}, },
}), }),
@@ -2552,7 +2602,7 @@ export const actions = [
defineAction({ defineAction({
name: 'set_self_longnick', name: 'set_self_longnick',
summary: '设置个性签名(longNick/long_nick,严格 string)', summary: '设置个性签名(longNick/long_nick,严格 string)',
params: { longNick: f.raw(), long_nick: f.raw() }, params: { longNick: optionalExactString(), long_nick: optionalExactString() },
run: async (p, ctx) => { run: async (p, ctx) => {
const longNick = p.longNick !== undefined ? p.longNick : p.long_nick; const longNick = p.longNick !== undefined ? p.longNick : p.long_nick;
if (typeof longNick !== 'string') return failedResponse(RETCODE.BAD_REQUEST, 'invalid longNick'); if (typeof longNick !== 'string') return failedResponse(RETCODE.BAD_REQUEST, 'invalid longNick');
@@ -2565,14 +2615,22 @@ export const actions = [
name: 'get_mini_app_ark', name: 'get_mini_app_ark',
summary: '获取小程序卡片 ark', summary: '获取小程序卡片 ark',
readOnly: true, readOnly: true,
params: {}, params: {
run: async (_p, ctx, raw) => { type: f.string().optional(),
const type = raw.type || 'bili'; title: f.string().optional(),
const title = raw.title || ''; desc: f.string().optional(),
const desc = raw.desc || ''; picUrl: f.string().optional(),
const picUrl = raw.picUrl || raw.pic_url || ''; pic_url: f.string().optional(),
const jumpUrl = raw.jumpUrl || raw.jump_url || ''; jumpUrl: f.string().optional(),
const data = await ctx.bridge.apis.misc.getMiniAppArk(String(type), String(title), String(desc), String(picUrl), String(jumpUrl)); jump_url: f.string().optional(),
},
run: async (p, ctx) => {
const type = p.type || 'bili';
const title = p.title || '';
const desc = p.desc || '';
const picUrl = p.picUrl || p.pic_url || '';
const jumpUrl = p.jumpUrl || p.jump_url || '';
const data = await ctx.bridge.apis.misc.getMiniAppArk(type, title, desc, picUrl, jumpUrl);
return okResponse(data); return okResponse(data);
}, },
}), }),
@@ -2580,12 +2638,20 @@ export const actions = [
groupAction({ groupAction({
name: 'click_inline_keyboard_button', name: 'click_inline_keyboard_button',
summary: '点击内联键盘按钮', summary: '点击内联键盘按钮',
params: { bot_appid: f.uint(), msg_seq: f.uint() }, params: {
run: async (p, ctx, raw) => { bot_appid: f.uint(),
const buttonId = raw.button_id; msg_seq: f.uint(),
const callbackData = raw.callback_data || ''; button_id: f.string({ allowEmpty: false }),
if (!buttonId) return failedResponse(RETCODE.BAD_REQUEST, 'missing required parameters'); callback_data: f.string().default(''),
const data = await ctx.bridge.apis.misc.clickInlineKeyboardButton(p.group_id, p.bot_appid, String(buttonId), String(callbackData), p.msg_seq); },
run: async (p, ctx) => {
const data = await ctx.bridge.apis.misc.clickInlineKeyboardButton(
p.group_id,
p.bot_appid,
p.button_id,
p.callback_data,
p.msg_seq,
);
return okResponse(data); return okResponse(data);
}, },
}), }),
+2 -6
View File
@@ -1,5 +1,4 @@
import { defineAction, groupAction, groupUserAction, f } from '../action-kit'; import { defineAction, groupAction, groupUserAction, f } from '../action-kit';
import { asString } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types'; import { RETCODE, failedResponse, okResponse } from '../types';
import { WebHonorType } from '@snowluma/protocol/web/group-honor'; import { WebHonorType } from '@snowluma/protocol/web/group-honor';
@@ -190,17 +189,14 @@ export const actions = [
}, },
}), }),
// `type` keeps the legacy `asString(x) || 'all'` semantics (absent / non-string
// / empty-string all collapse to 'all'), which a typed string field can't
// replicate exactly — so it stays a raw param coerced in run().
groupAction({ groupAction({
name: 'get_group_honor_info', name: 'get_group_honor_info',
summary: '获取群荣誉信息', summary: '获取群荣誉信息',
readOnly: true, readOnly: true,
params: { type: f.raw() }, params: { type: f.string().optional() },
run: async (p, ctx) => { run: async (p, ctx) => {
const groupId = p.group_id; const groupId = p.group_id;
const typeStr = asString(p.type) || 'all'; const typeStr = p.type || 'all';
const typeValues = Object.values(WebHonorType) as string[]; const typeValues = Object.values(WebHonorType) as string[];
if (!typeValues.includes(typeStr)) { if (!typeValues.includes(typeStr)) {
+4 -6
View File
@@ -1,5 +1,4 @@
import { defineAction, f } from '../action-kit'; import { defineAction, f } from '../action-kit';
import { asString } from '../api-handler';
import { okResponse } from '../types'; import { okResponse } from '../types';
export const actions = [ export const actions = [
@@ -22,15 +21,14 @@ export const actions = [
params: { params: {
// Opaque handle from the original request event; callers must echo it. // Opaque handle from the original request event; callers must echo it.
flag: f.string({ allowEmpty: false }), flag: f.string({ allowEmpty: false }),
// sub_type/type pass through with a nested fallback (sub_type → type → 'add'); // sub_type → type → 'add'. Empty string is kept, not treated as missing.
// kept raw so the original asString resolution is preserved verbatim. sub_type: f.string().optional(),
sub_type: f.raw(), type: f.string().optional(),
type: f.raw(),
approve: f.bool().default(true), approve: f.bool().default(true),
reason: f.string().default(''), reason: f.string().default(''),
}, },
run: async (p, ctx) => { run: async (p, ctx) => {
const subType = asString(p.sub_type, asString(p.type, 'add')); const subType = p.sub_type !== undefined ? p.sub_type : (p.type !== undefined ? p.type : 'add');
await ctx.handleGroupRequest(p.flag, subType, p.approve, p.reason); await ctx.handleGroupRequest(p.flag, subType, p.approve, p.reason);
return okResponse(); return okResponse();
}, },
@@ -361,7 +361,7 @@ const downloadFileStream = defineStreamAction({
summary: '以流式方式下载文件(stream 目录本地文件 / URL / 缓存媒体)', summary: '以流式方式下载文件(stream 目录本地文件 / URL / 缓存媒体)',
returns: '流式帧:file_info → file_chunk* → file_complete', returns: '流式帧:file_info → file_chunk* → file_complete',
params: downloadParams, params: downloadParams,
run: (p, ctx, _raw, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'auto'), run: (p, ctx, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'auto'),
}); });
const downloadFileImageStream = defineStreamAction({ const downloadFileImageStream = defineStreamAction({
@@ -369,7 +369,7 @@ const downloadFileImageStream = defineStreamAction({
summary: '以流式方式下载图片(缓存图片 id / URL / stream 目录本地文件)', summary: '以流式方式下载图片(缓存图片 id / URL / stream 目录本地文件)',
returns: '流式帧:file_info → file_chunk* → file_complete', returns: '流式帧:file_info → file_chunk* → file_complete',
params: downloadParams, params: downloadParams,
run: (p, ctx, _raw, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'image'), run: (p, ctx, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'image'),
}); });
const downloadFileRecordStream = defineStreamAction({ const downloadFileRecordStream = defineStreamAction({
@@ -377,7 +377,7 @@ const downloadFileRecordStream = defineStreamAction({
summary: '以流式方式下载语音(缓存语音 id / URL / stream 目录本地文件)', summary: '以流式方式下载语音(缓存语音 id / URL / stream 目录本地文件)',
returns: '流式帧:file_info → file_chunk* → file_complete', returns: '流式帧:file_info → file_chunk* → file_complete',
params: downloadParams, params: downloadParams,
run: (p, ctx, _raw, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'record'), run: (p, ctx, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'record'),
}); });
const testDownloadStream = defineStreamAction({ const testDownloadStream = defineStreamAction({
@@ -385,7 +385,7 @@ const testDownloadStream = defineStreamAction({
summary: '测试下载流(推送 10 个数据帧,验证流式传输,不触达 QQ)', summary: '测试下载流(推送 10 个数据帧,验证流式传输,不触达 QQ)',
returns: '流式帧:data_chunk*10 → data_complete(error=true 时以 error 帧结束)', returns: '流式帧:data_chunk*10 → data_complete(error=true 时以 error 帧结束)',
params: { error: f.bool().default(false).describe('是否触发测试错误') }, params: { error: f.bool().default(false).describe('是否触发测试错误') },
run: async (p, _ctx, _raw, sink) => { run: async (p, _ctx, sink) => {
for (let i = 0; i < 10; i++) { for (let i = 0; i < 10; i++) {
await sink.send({ type: StreamStatus.Stream, data: `Index-> ${i + 1}`, data_type: 'data_chunk' }); await sink.send({ type: StreamStatus.Stream, data: `Index-> ${i + 1}`, data_type: 'data_chunk' });
} }
-38
View File
@@ -415,26 +415,6 @@ export function asString(value: unknown, fallback = ''): string {
return fallback; return fallback;
} }
export function asNumber(value: unknown): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
if (typeof value === 'string' && value.trim()) {
const n = Number(value);
if (Number.isFinite(n)) return Math.trunc(n);
}
return 0;
}
export function asBoolean(value: unknown, fallback: boolean): boolean {
if (typeof value === 'boolean') return value;
if (typeof value === 'number') return value !== 0;
if (typeof value === 'string') {
const text = value.trim().toLowerCase();
if (text === 'true' || text === '1' || text === 'yes' || text === 'on') return true;
if (text === 'false' || text === '0' || text === 'no' || text === 'off') return false;
}
return fallback;
}
export function toJsonValue(value: unknown): JsonValue { export function toJsonValue(value: unknown): JsonValue {
if (value === null) return null; if (value === null) return null;
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return value; if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return value;
@@ -448,21 +428,3 @@ export function toJsonValue(value: unknown): JsonValue {
} }
return String(value); return String(value);
} }
export function asMessage(value: unknown): import('./types').JsonValue | undefined {
if (value === undefined) return undefined;
if (typeof value === 'string') {
const trimmed = value.trim();
if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
try {
const parsed = JSON.parse(trimmed);
if (Array.isArray(parsed)) {
return toJsonValue(parsed);
}
} catch {
// Fallback to literal text if it just looks like an array but is invalid JSON
}
}
}
return toJsonValue(value);
}
+16 -5
View File
@@ -152,16 +152,27 @@ describe('toHandler — BAD_REQUEST shaping + ctx threading', () => {
}); });
}); });
describe('run raw escape hatch — original params as 3rd arg', () => { describe('run only sees declared fields', () => {
it('exposes untouched params for undeclared keys (alias fallbacks etc.)', async () => { it('lets a declared alias through and ignores undeclared keys', async () => {
const spec = defineAction({ const spec = defineAction({
name: 't', name: 't',
params: { user_id: f.uint() }, params: { user_id: f.uint(), longNick: f.string().optional() },
run: (_p, _ctx, raw) => okResponse({ extra: (raw.long_nick ?? raw.longNick ?? null) as never }), run: (p) => okResponse({ extra: (p.longNick ?? null) as never }),
}); });
const res = await spec.toHandler(ctx)({ user_id: 1, longNick: 'hi' }); const res = await spec.toHandler(ctx)({ user_id: 1, longNick: 'hi', undeclared: 1 });
expect(res).toMatchObject({ status: 'ok', data: { extra: 'hi' } }); expect(res).toMatchObject({ status: 'ok', data: { extra: 'hi' } });
}); });
it('rejects garbage on a declared int instead of treating it as 0', async () => {
const spec = defineAction({
name: 't',
params: { group_id: f.int({ min: 0 }).optional() },
run: (p) => okResponse({ group_id: p.group_id ?? 0 }),
});
const res = await spec.toHandler(ctx)({ group_id: 'nope' });
expect(res.retcode).toBe(RETCODE.BAD_REQUEST);
expect(res.wording).toContain('group_id');
});
}); });
describe('toJsonSchema / inputSchema (for the MCP)', () => { describe('toJsonSchema / inputSchema (for the MCP)', () => {
+31 -29
View File
@@ -241,7 +241,7 @@ describe('set_friend_add_request describe', () => {
}); });
describe('set_group_add_request parse', () => { describe('set_group_add_request parse', () => {
it('requires flag and defaults approve, reason, and the raw type fields', () => { it('requires flag and defaults approve, reason, and the type fields', () => {
expect(setGroupAddRequest.parse({ flag: 'slreq:1:123456:999:22:1' })).toEqual({ expect(setGroupAddRequest.parse({ flag: 'slreq:1:123456:999:22:1' })).toEqual({
ok: true, ok: true,
value: { value: {
@@ -254,22 +254,22 @@ describe('set_group_add_request parse', () => {
}); });
}); });
it('keeps raw sub_type and type values without coercing them', () => { it('rejects non-string sub_type and type values', () => {
expect(setGroupAddRequest.parse({ expect(setGroupAddRequest.parse({
flag: 'flag-group-9', flag: 'flag-group-9',
sub_type: { kind: 'invite' }, sub_type: { kind: 'invite' },
type: [1, 2],
approve: 0,
reason: 404,
})).toEqual({ })).toEqual({
ok: true, ok: false,
value: { field: 'sub_type',
reason: 'expected a string',
});
expect(setGroupAddRequest.parse({
flag: 'flag-group-9', flag: 'flag-group-9',
sub_type: { kind: 'invite' },
type: [1, 2], type: [1, 2],
approve: false, })).toEqual({
reason: '404', ok: false,
}, field: 'type',
reason: 'expected a string',
}); });
}); });
@@ -418,23 +418,25 @@ describe('set_group_add_request toHandler', () => {
}); });
it.each([ it.each([
[{ sub_type: { kind: 'invite' }, type: 'invite' }, 'invite'], [{ sub_type: { kind: 'invite' } }, 'sub_type'],
[{ sub_type: ['invite'], type: 'add' }, 'add'], [{ sub_type: ['invite'] }, 'sub_type'],
[{ sub_type: null, type: 'invite' }, 'invite'], [{ sub_type: null }, 'sub_type'],
[{ sub_type: null, type: null }, 'add'], [{ type: { kind: 'add' } }, 'type'],
[{ type: { kind: 'add' } }, 'add'], [{ type: null }, 'type'],
[{ type: null }, 'add'], ])('rejects a non-string locator %j', async (params, field) => {
])('falls through a non-primitive locator %j to %s', async (params, subType) => {
const { ctx, handleGroupRequest } = groupCtx(); const { ctx, handleGroupRequest } = groupCtx();
await expect(setGroupAddRequest.toHandler(ctx)({ await expect(setGroupAddRequest.toHandler(ctx)({
flag: 'flag-group-9', flag: 'flag-group-9',
...params, ...params,
})).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); })).resolves.toEqual({
status: 'failed',
retcode: 1400,
data: null,
wording: `${field}: expected a string`,
});
expect(handleGroupRequest.mock.calls).toEqual([ expect(handleGroupRequest).not.toHaveBeenCalled();
['flag-group-9', subType, true, ''],
]);
}); });
it('stringifies a numeric flag and reason', async () => { it('stringifies a numeric flag and reason', async () => {
@@ -484,7 +486,7 @@ describe('set_group_add_request toHandler', () => {
}); });
describe('set_group_add_request describe', () => { describe('set_group_add_request describe', () => {
it('documents the group-request params including raw type fields', () => { it('documents the group-request params including type fields', () => {
const doc = setGroupAddRequest.describe(); const doc = setGroupAddRequest.describe();
expect(doc.name).toBe('set_group_add_request'); expect(doc.name).toBe('set_group_add_request');
@@ -504,17 +506,17 @@ describe('set_group_add_request describe', () => {
}, },
{ {
name: 'sub_type', name: 'sub_type',
type: 'raw', type: 'string',
required: false, required: false,
default: undefined, default: undefined,
schema: {}, schema: { type: 'string' },
}, },
{ {
name: 'type', name: 'type',
type: 'raw', type: 'string',
required: false, required: false,
default: undefined, default: undefined,
schema: {}, schema: { type: 'string' },
}, },
{ {
name: 'approve', name: 'approve',
@@ -535,8 +537,8 @@ describe('set_group_add_request describe', () => {
type: 'object', type: 'object',
properties: { properties: {
flag: { type: 'string', minLength: 1 }, flag: { type: 'string', minLength: 1 },
sub_type: {}, sub_type: { type: 'string' },
type: {}, type: { type: 'string' },
approve: { type: 'boolean', default: true }, approve: { type: 'boolean', default: true },
reason: { type: 'string', default: '' }, reason: { type: 'string', default: '' },
}, },
@@ -149,7 +149,7 @@ describe('ApiHandler TRACE lifecycle', () => {
const stream = defineStreamAction({ const stream = defineStreamAction({
name: 'trace_stream', name: 'trace_stream',
params: {}, params: {},
run: async (_params, _ctx, _raw, sink) => { run: async (_params, _ctx, sink) => {
await sink.send({ type: StreamStatus.Stream, chunk: 'complete-frame' }); await sink.send({ type: StreamStatus.Stream, chunk: 'complete-frame' });
return { return {
status: 'ok', status: 'ok',
@@ -149,6 +149,50 @@ function fakeEssenceMessage(
}; };
} }
describe('extended-actions / send_forward_msg', () => {
it('treats group_id 0 as unused', async () => {
const sendForwardMsg = vi.fn(async () => ({ forwardId: 'fwd' }));
const ctx = fakeCtx(fakeBridge(), { sendForwardMsg });
const response = await makeHandler(ctx).handle('send_forward_msg', {
messages: 'hi',
group_id: 0,
});
expect(response).toMatchObject({ status: 'ok', retcode: 0 });
expect(sendForwardMsg).toHaveBeenCalledOnce();
});
it('rejects a non-numeric group_id instead of treating it as 0', async () => {
const sendForwardMsg = vi.fn();
const ctx = fakeCtx(fakeBridge(), { sendForwardMsg });
const response = await makeHandler(ctx).handle('send_forward_msg', {
messages: 'hi',
group_id: 'nope',
});
expect(response).toMatchObject({ status: 'failed', retcode: 1400 });
expect(sendForwardMsg).not.toHaveBeenCalled();
});
});
describe('extended-actions / get_forward_msg', () => {
it('uses a string message_id as the forward id', async () => {
const getForwardMsg = vi.fn(async () => []);
const ctx = fakeCtx(fakeBridge(), { getForwardMsg });
const response = await makeHandler(ctx).handle('get_forward_msg', { message_id: 'resid-1' });
expect(getForwardMsg).toHaveBeenCalledWith('resid-1');
expect(response).toMatchObject({ status: 'ok' });
});
});
describe('extended-actions / fetch_ptt_text', () => {
it('accepts a numeric message_id', async () => {
const fetchPttText = vi.fn(async () => 'hello');
const ctx = fakeCtx(fakeBridge(), { fetchPttText });
const response = await makeHandler(ctx).handle('fetch_ptt_text', { message_id: 12 });
expect(fetchPttText).toHaveBeenCalledWith(12);
expect(response).toMatchObject({ status: 'ok', data: 'hello' });
});
});
describe('extended-actions / set_self_longnick', () => { describe('extended-actions / set_self_longnick', () => {
it('accepts an empty longNick to clear the signature', async () => { it('accepts an empty longNick to clear the signature', async () => {
const setSelfLongNick = vi.fn(async () => undefined); const setSelfLongNick = vi.fn(async () => undefined);
@@ -14,7 +14,7 @@ export function testAction(name: string, run: TestActionRun): RegisteredActionSp
return defineAction({ return defineAction({
name, name,
params: {}, params: {},
run: (_params, context, raw) => run(raw, context), run: (params, context) => run(params, context),
}); });
} }
+3 -3
View File
@@ -22,7 +22,7 @@ describe('Stream API plumbing', () => {
const action = defineStreamAction({ const action = defineStreamAction({
name: 'demo_stream', name: 'demo_stream',
params: { n: f.uint() }, params: { n: f.uint() },
run: async (p, _ctx, _raw, sink) => { run: async (p, _ctx, sink) => {
for (let i = 0; i < p.n; i++) await sink.send({ type: 'stream', index: i }); for (let i = 0; i < p.n; i++) await sink.send({ type: 'stream', index: i });
return okResponse({ type: 'response', total: p.n }); return okResponse({ type: 'response', total: p.n });
}, },
@@ -85,7 +85,7 @@ describe('Stream API plumbing', () => {
const action = defineStreamAction({ const action = defineStreamAction({
name: 'demo_partial', name: 'demo_partial',
params: {}, params: {},
run: async (_p, _ctx, _raw, sink) => { run: async (_p, _ctx, sink) => {
await sink.send({ type: 'stream', index: 0 }); await sink.send({ type: 'stream', index: 0 });
throw new Error('mid'); throw new Error('mid');
}, },
@@ -116,7 +116,7 @@ describe('Stream API plumbing', () => {
const action = defineStreamAction({ const action = defineStreamAction({
name: 'demo_abort', name: 'demo_abort',
params: {}, params: {},
run: async (_p, _ctx, _raw, sink) => { run: async (_p, _ctx, sink) => {
for (let i = 0; i < 5; i++) { await sink.send({ type: 'stream', index: i }); sent++; } for (let i = 0; i < 5; i++) { await sink.send({ type: 'stream', index: i }); sent++; }
return okResponse({ type: 'response' }); return okResponse({ type: 'response' });
}, },