braid-coding-agent 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. braid_coding_agent/__init__.py +13 -0
  2. braid_coding_agent/assembly.py +460 -0
  3. braid_coding_agent/cancellation.py +25 -0
  4. braid_coding_agent/checkpoint/__init__.py +106 -0
  5. braid_coding_agent/checkpoint/git.py +305 -0
  6. braid_coding_agent/checkpoint/settings.py +26 -0
  7. braid_coding_agent/checkpoint/store.py +1261 -0
  8. braid_coding_agent/checkpoint/workspace.py +220 -0
  9. braid_coding_agent/cli.py +2168 -0
  10. braid_coding_agent/commands/__init__.py +50 -0
  11. braid_coding_agent/commands/auth.py +161 -0
  12. braid_coding_agent/commands/config.py +180 -0
  13. braid_coding_agent/commands/doctor.py +511 -0
  14. braid_coding_agent/commands/mcp.py +928 -0
  15. braid_coding_agent/commands/models.py +95 -0
  16. braid_coding_agent/commands/setup.py +89 -0
  17. braid_coding_agent/commands/uninstall.py +277 -0
  18. braid_coding_agent/commands/upgrade.py +381 -0
  19. braid_coding_agent/compaction/__init__.py +174 -0
  20. braid_coding_agent/compaction/prepare.py +430 -0
  21. braid_coding_agent/compaction/summarize.py +542 -0
  22. braid_coding_agent/compaction/tokens.py +204 -0
  23. braid_coding_agent/compaction/tool_results.py +196 -0
  24. braid_coding_agent/compaction/utils.py +181 -0
  25. braid_coding_agent/config.py +2776 -0
  26. braid_coding_agent/config_files.py +191 -0
  27. braid_coding_agent/credentials.py +252 -0
  28. braid_coding_agent/discovery.py +415 -0
  29. braid_coding_agent/extensions/__init__.py +77 -0
  30. braid_coding_agent/extensions/api.py +480 -0
  31. braid_coding_agent/extensions/runner.py +553 -0
  32. braid_coding_agent/formatting/__init__.py +62 -0
  33. braid_coding_agent/formatting/settings.py +87 -0
  34. braid_coding_agent/formatting/tool.py +179 -0
  35. braid_coding_agent/lsp/__init__.py +105 -0
  36. braid_coding_agent/lsp/client.py +546 -0
  37. braid_coding_agent/lsp/manager.py +187 -0
  38. braid_coding_agent/lsp/model.py +316 -0
  39. braid_coding_agent/lsp/protocol.py +105 -0
  40. braid_coding_agent/lsp/settings.py +120 -0
  41. braid_coding_agent/lsp/tool.py +429 -0
  42. braid_coding_agent/mcp/__init__.py +101 -0
  43. braid_coding_agent/mcp/cache.py +230 -0
  44. braid_coding_agent/mcp/catalog.py +108 -0
  45. braid_coding_agent/mcp/config.py +664 -0
  46. braid_coding_agent/mcp/config_store.py +142 -0
  47. braid_coding_agent/mcp/inspector.py +85 -0
  48. braid_coding_agent/mcp/panel.py +254 -0
  49. braid_coding_agent/mcp/runtime.py +1060 -0
  50. braid_coding_agent/mcp/tools.py +579 -0
  51. braid_coding_agent/mcp/trust.py +150 -0
  52. braid_coding_agent/mcp/tui_panel.py +444 -0
  53. braid_coding_agent/messages.py +152 -0
  54. braid_coding_agent/models_view.py +105 -0
  55. braid_coding_agent/modes/__init__.py +64 -0
  56. braid_coding_agent/modes/json_mode.py +480 -0
  57. braid_coding_agent/modes/lifecycle.py +217 -0
  58. braid_coding_agent/modes/print_mode.py +257 -0
  59. braid_coding_agent/modes/repl.py +2687 -0
  60. braid_coding_agent/modes/repl_commands.py +263 -0
  61. braid_coding_agent/modes/rpc.py +953 -0
  62. braid_coding_agent/modes/skill_commands.py +88 -0
  63. braid_coding_agent/modes/tui.py +2226 -0
  64. braid_coding_agent/modes/tui_control.py +90 -0
  65. braid_coding_agent/modes/tui_model.py +1043 -0
  66. braid_coding_agent/modes/tui_render.py +327 -0
  67. braid_coding_agent/modes/tui_rich.py +751 -0
  68. braid_coding_agent/modes/tui_style.py +42 -0
  69. braid_coding_agent/modes/wire.py +81 -0
  70. braid_coding_agent/netsafe.py +82 -0
  71. braid_coding_agent/network/__init__.py +20 -0
  72. braid_coding_agent/network/cache.py +77 -0
  73. braid_coding_agent/network/fetch.py +311 -0
  74. braid_coding_agent/network/html_text.py +160 -0
  75. braid_coding_agent/network/search.py +347 -0
  76. braid_coding_agent/network/settings.py +103 -0
  77. braid_coding_agent/network/urls.py +89 -0
  78. braid_coding_agent/observability/__init__.py +101 -0
  79. braid_coding_agent/observability/audit.py +124 -0
  80. braid_coding_agent/observability/collector.py +314 -0
  81. braid_coding_agent/observability/exporter.py +74 -0
  82. braid_coding_agent/observability/logging_setup.py +149 -0
  83. braid_coding_agent/observability/redaction.py +96 -0
  84. braid_coding_agent/observability/settings.py +29 -0
  85. braid_coding_agent/observability/spans.py +239 -0
  86. braid_coding_agent/permissions/__init__.py +185 -0
  87. braid_coding_agent/permissions/command.py +586 -0
  88. braid_coding_agent/permissions/engine.py +522 -0
  89. braid_coding_agent/permissions/evaluate.py +309 -0
  90. braid_coding_agent/permissions/matching.py +233 -0
  91. braid_coding_agent/permissions/model.py +278 -0
  92. braid_coding_agent/permissions/policy.py +99 -0
  93. braid_coding_agent/permissions/readonly.py +236 -0
  94. braid_coding_agent/permissions/store.py +379 -0
  95. braid_coding_agent/project_init.py +313 -0
  96. braid_coding_agent/prompt/__init__.py +98 -0
  97. braid_coding_agent/prompt/context_files.py +253 -0
  98. braid_coding_agent/prompt/project_context.py +172 -0
  99. braid_coding_agent/prompt/system_prompt.py +378 -0
  100. braid_coding_agent/questions.py +71 -0
  101. braid_coding_agent/render/__init__.py +56 -0
  102. braid_coding_agent/render/batch.py +66 -0
  103. braid_coding_agent/render/history.py +143 -0
  104. braid_coding_agent/render/stream.py +823 -0
  105. braid_coding_agent/render/theme.py +243 -0
  106. braid_coding_agent/sandbox/__init__.py +89 -0
  107. braid_coding_agent/sandbox/backend.py +184 -0
  108. braid_coding_agent/sandbox/bubblewrap.py +96 -0
  109. braid_coding_agent/sandbox/operations.py +301 -0
  110. braid_coding_agent/sandbox/policy.py +221 -0
  111. braid_coding_agent/sandbox/proxy.py +320 -0
  112. braid_coding_agent/sandbox/seatbelt.py +222 -0
  113. braid_coding_agent/sdk/__init__.py +31 -0
  114. braid_coding_agent/sdk/async_client.py +366 -0
  115. braid_coding_agent/sdk/client.py +386 -0
  116. braid_coding_agent/sdk/errors.py +52 -0
  117. braid_coding_agent/sdk/events.py +162 -0
  118. braid_coding_agent/sdk/types.py +63 -0
  119. braid_coding_agent/sdk/wire.py +59 -0
  120. braid_coding_agent/server/__init__.py +54 -0
  121. braid_coding_agent/server/errors.py +52 -0
  122. braid_coding_agent/server/http_server.py +419 -0
  123. braid_coding_agent/server/hub.py +530 -0
  124. braid_coding_agent/server/openapi.py +157 -0
  125. braid_coding_agent/server/registry.py +354 -0
  126. braid_coding_agent/server/router.py +275 -0
  127. braid_coding_agent/server/run.py +148 -0
  128. braid_coding_agent/server/schema.py +194 -0
  129. braid_coding_agent/server/service.py +975 -0
  130. braid_coding_agent/session/__init__.py +293 -0
  131. braid_coding_agent/session/agent_session.py +2706 -0
  132. braid_coding_agent/session/context_breakdown.py +302 -0
  133. braid_coding_agent/session/discovery.py +212 -0
  134. braid_coding_agent/session/entries.py +809 -0
  135. braid_coding_agent/session/evidence.py +295 -0
  136. braid_coding_agent/session/lock.py +176 -0
  137. braid_coding_agent/session/manager.py +1185 -0
  138. braid_coding_agent/session/plan.py +243 -0
  139. braid_coding_agent/session/plan_mode.py +423 -0
  140. braid_coding_agent/session/projection.py +262 -0
  141. braid_coding_agent/session/rewind.py +257 -0
  142. braid_coding_agent/session/status.py +240 -0
  143. braid_coding_agent/settings.py +94 -0
  144. braid_coding_agent/skills/__init__.py +70 -0
  145. braid_coding_agent/skills/loader.py +681 -0
  146. braid_coding_agent/startup/__init__.py +76 -0
  147. braid_coding_agent/startup/cache.py +72 -0
  148. braid_coding_agent/startup/diagnostics.py +37 -0
  149. braid_coding_agent/startup/monitor.py +245 -0
  150. braid_coding_agent/startup/phases.py +79 -0
  151. braid_coding_agent/startup/project.py +165 -0
  152. braid_coding_agent/startup/report.py +560 -0
  153. braid_coding_agent/startup/scheduler.py +347 -0
  154. braid_coding_agent/statusline.py +163 -0
  155. braid_coding_agent/subagents/__init__.py +22 -0
  156. braid_coding_agent/subagents/contract.py +75 -0
  157. braid_coding_agent/subagents/definitions.py +583 -0
  158. braid_coding_agent/subagents/registry.py +277 -0
  159. braid_coding_agent/subagents/runtime.py +610 -0
  160. braid_coding_agent/subagents/settings.py +156 -0
  161. braid_coding_agent/subagents/worktree.py +63 -0
  162. braid_coding_agent/tools/__init__.py +327 -0
  163. braid_coding_agent/tools/args.py +87 -0
  164. braid_coding_agent/tools/bash.py +359 -0
  165. braid_coding_agent/tools/edit.py +298 -0
  166. braid_coding_agent/tools/edit_diff.py +344 -0
  167. braid_coding_agent/tools/find.py +158 -0
  168. braid_coding_agent/tools/grep.py +305 -0
  169. braid_coding_agent/tools/ignore.py +198 -0
  170. braid_coding_agent/tools/ls.py +127 -0
  171. braid_coding_agent/tools/mutation_queue.py +90 -0
  172. braid_coding_agent/tools/operations.py +274 -0
  173. braid_coding_agent/tools/output_accumulator.py +282 -0
  174. braid_coding_agent/tools/output_store.py +244 -0
  175. braid_coding_agent/tools/path_utils.py +91 -0
  176. braid_coding_agent/tools/plan.py +141 -0
  177. braid_coding_agent/tools/prompt_notes.py +52 -0
  178. braid_coding_agent/tools/question.py +180 -0
  179. braid_coding_agent/tools/read.py +223 -0
  180. braid_coding_agent/tools/submit_plan.py +102 -0
  181. braid_coding_agent/tools/truncate.py +423 -0
  182. braid_coding_agent/tools/write.py +100 -0
  183. braid_coding_agent/untrusted.py +50 -0
  184. braid_coding_agent/verify/__init__.py +78 -0
  185. braid_coding_agent/verify/runner.py +260 -0
  186. braid_coding_agent/verify/settings.py +64 -0
  187. braid_coding_agent/verify/tool.py +143 -0
  188. braid_coding_agent-0.1.0.dist-info/METADATA +19 -0
  189. braid_coding_agent-0.1.0.dist-info/RECORD +192 -0
  190. braid_coding_agent-0.1.0.dist-info/WHEEL +4 -0
  191. braid_coding_agent-0.1.0.dist-info/entry_points.txt +3 -0
  192. braid_coding_agent-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,148 @@
1
+ """``braid serve`` 的启动流程:令牌检查、注册表、服务对象、监听行。
2
+
3
+ CLI 负责把装配参数准备好(模型、工具、权限、MCP 都在那边),这里只把它们变成
4
+ 一个长期运行的服务。两者的边界是 :class:`~braid_coding_agent.assembly.SessionAssembler`:
5
+ 服务端不重新解释命令行参数,也不自己造工具。
6
+
7
+ ## 监听地址与令牌
8
+
9
+ 默认只监听 ``127.0.0.1``。监听其他地址时必须给出令牌:一个把 Agent 的读写能力
10
+ 暴露到局域网的 HTTP 服务,没有令牌就等于没有认证。令牌来源是 ``--token`` 或
11
+ ``BRAID_SERVER_TOKEN``,两者都没有又监听非本机地址时直接拒绝启动。
12
+
13
+ 已经配置令牌时,``/health`` 仍然不需要它——进程管理器探活不该依赖业务凭证。
14
+
15
+ ## 启动行
16
+
17
+ stdout 上打印一行 JSON,脚本与测试据此拿到实际端口(``--port 0`` 由系统分配):
18
+
19
+ ```json
20
+ {"type":"listening","url":"http://127.0.0.1:4096","host":"127.0.0.1","port":4096,"auth":"token"}
21
+ ```
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import ipaddress
27
+ import json
28
+ import os
29
+ import sys
30
+ from dataclasses import dataclass
31
+
32
+ from braid_ai import Models
33
+ from braid_ai.utils.clock import Clock
34
+ from braid_coding_agent.assembly import SessionAssembler
35
+ from braid_coding_agent.mcp import McpRuntime
36
+ from braid_coding_agent.server.http_server import BraidHTTPServer, run_http_service
37
+ from braid_coding_agent.server.registry import SessionRegistry
38
+ from braid_coding_agent.server.service import create_service
39
+
40
+ __all__ = ["ServerConfigError", "resolve_token", "serve"]
41
+
42
+ #: 令牌的环境变量名。
43
+ TOKEN_ENV = "BRAID_SERVER_TOKEN"
44
+
45
+
46
+ class ServerConfigError(Exception):
47
+ """服务启动参数不成立(监听地址、端口、令牌)。CLI 翻成退出码 1。"""
48
+
49
+
50
+ @dataclass(slots=True)
51
+ class ServerOptions:
52
+ """启动服务的全部参数。"""
53
+
54
+ host: str = "127.0.0.1"
55
+ port: int = 4096
56
+ token: str | None = None
57
+ cors_origins: tuple[str, ...] = ()
58
+
59
+
60
+ def resolve_token(host: str, explicit: str | None) -> str | None:
61
+ """定下这次运行使用的令牌。
62
+
63
+ :raises ServerConfigError: 监听非本机地址又没有令牌。
64
+ """
65
+ token = explicit if explicit is not None else os.environ.get(TOKEN_ENV)
66
+ if token is not None and not token.strip():
67
+ raise ServerConfigError("令牌不能是空字符串")
68
+ if token is None and not _is_loopback(host):
69
+ raise ServerConfigError(
70
+ f"监听 {host} 时必须配置令牌:用 --token 或环境变量 {TOKEN_ENV}。"
71
+ "否则任何能访问这个端口的人都能读写你的工作区"
72
+ )
73
+ return token
74
+
75
+
76
+ def _is_loopback(host: str) -> bool:
77
+ """主机名或地址是否是本机回环。"""
78
+ if host in ("localhost", ""):
79
+ return True
80
+ try:
81
+ return ipaddress.ip_address(host).is_loopback
82
+ except ValueError:
83
+ # 不是 IP 字面量:一个主机名可能解析到本机,也可能不是。按"不是本机"处理,
84
+ # 于是这类地址必须配令牌——失败关闭。
85
+ return False
86
+
87
+
88
+ async def serve(
89
+ *,
90
+ assembler: SessionAssembler,
91
+ models: Models,
92
+ mcp: McpRuntime | None,
93
+ cwd: str,
94
+ session_dir: str | None,
95
+ clock: Clock,
96
+ version: str,
97
+ options: ServerOptions,
98
+ ) -> int:
99
+ """启动 HTTP 服务,直到收到 ``SIGTERM`` / ``SIGHUP``。
100
+
101
+ :param session_dir: ``None`` 表示只保留内存会话(``--no-session``)。
102
+ :param options: 监听地址、端口、令牌与 CORS 来源。
103
+ """
104
+ token = resolve_token(options.host, options.token)
105
+ if not 0 <= options.port <= 65535:
106
+ raise ServerConfigError(f"端口必须在 0 到 65535 之间,收到 {options.port}")
107
+ registry = SessionRegistry(
108
+ assembler=assembler,
109
+ cwd=cwd,
110
+ session_dir=session_dir,
111
+ clock=clock,
112
+ )
113
+ service = create_service(
114
+ registry=registry,
115
+ models=models,
116
+ mcp=mcp,
117
+ cwd=cwd,
118
+ version=version,
119
+ auth="token" if token is not None else "none",
120
+ )
121
+
122
+ def announce(server: BraidHTTPServer) -> None:
123
+ """把实际监听地址写给调用方。``--port 0`` 时这里才是真实端口。"""
124
+ host, port = server.server_address[0], server.server_address[1]
125
+ record = {
126
+ "type": "listening",
127
+ "url": f"http://{host}:{port}",
128
+ "host": host,
129
+ "port": port,
130
+ "auth": "token" if token is not None else "none",
131
+ }
132
+ print(json.dumps(record, ensure_ascii=False), file=sys.stdout, flush=True)
133
+ if token is not None:
134
+ print(
135
+ f"braid: 使用 Authorization: Bearer <token> 访问(令牌来自 "
136
+ f"--token 或 {TOKEN_ENV})",
137
+ file=sys.stderr,
138
+ flush=True,
139
+ )
140
+
141
+ return await run_http_service(
142
+ service=service,
143
+ host=options.host,
144
+ port=options.port,
145
+ token=token,
146
+ cors_origins=options.cors_origins,
147
+ on_listening=announce,
148
+ )
@@ -0,0 +1,194 @@
1
+ """从 dataclass 与类型注解生成 JSON Schema,并按同一份注解校验请求体。
2
+
3
+ 只用标准库:请求体形状就是 dataclass 的字段声明,OpenAPI 文档与运行时校验读的是
4
+ 同一份注解。两处各写一遍(一份文档、一份手写校验)是这类服务最常见的漂移来源,
5
+ 表现为"文档说这个字段可选,服务端却回 400"。
6
+
7
+ 支持的类型足够覆盖本服务的 API:``str`` / ``int`` / ``float`` / ``bool`` /
8
+ ``list[T]`` / ``dict[str, T]`` / ``X | None`` / ``Literal[...]``。注解里出现别的
9
+ 类型时生成空 Schema(合法,表示"任意值"),运行时不额外校验——**不假装支持**。
10
+
11
+ 未知字段一律拒绝:拼错的 ``modelId`` 被静默忽略,调用方会以为切换成功了。
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import dataclasses
17
+ import types
18
+ import typing
19
+ from enum import Enum
20
+ from typing import Any, Literal, Union, get_args, get_origin, get_type_hints
21
+
22
+ from braid_ai.types import JsonValue
23
+
24
+ from .errors import ApiError, bad_request
25
+
26
+ __all__ = ["SCHEMA_KEY", "decode_body", "describe", "schema_for"]
27
+
28
+ #: dataclass 字段的 ``metadata`` 键,值是给人看的字段说明。
29
+ SCHEMA_KEY = "description"
30
+
31
+
32
+ def schema_for(annotation: object) -> dict[str, Any]:
33
+ """一个类型注解 → JSON Schema 片段。无法识别的注解返回空 Schema。
34
+
35
+ 返回值用 ``dict[str, Any]`` 而不是 ``JsonValue``:Schema 是递归结构,按
36
+ ``JsonValue`` 标注会撞上 ``list`` 与 ``dict`` 的类型参数不变性,读起来全是
37
+ 类型体操。它与 ``json_mode`` 里的 wire 构造保持同一种写法。
38
+ """
39
+ if annotation is None or annotation is type(None):
40
+ return {"type": "null"}
41
+ if annotation is Any or annotation is object:
42
+ return {}
43
+ if isinstance(annotation, type) and issubclass(annotation, Enum):
44
+ values = [member.value for member in annotation]
45
+ return {"enum": _json_values(values)}
46
+ origin = get_origin(annotation)
47
+ if origin is Literal:
48
+ return {"enum": _json_values(list(get_args(annotation)))}
49
+ if origin in (Union, types.UnionType):
50
+ return {"anyOf": [schema_for(item) for item in get_args(annotation)]}
51
+ if origin in (list, set, tuple):
52
+ args = get_args(annotation)
53
+ item = schema_for(args[0]) if args else {}
54
+ return {"type": "array", "items": item}
55
+ if origin is dict:
56
+ args = get_args(annotation)
57
+ value_schema = schema_for(args[1]) if len(args) == 2 else {}
58
+ return {"type": "object", "additionalProperties": value_schema}
59
+ if annotation is str:
60
+ return {"type": "string"}
61
+ if annotation is bool:
62
+ return {"type": "boolean"}
63
+ if annotation is int:
64
+ return {"type": "integer"}
65
+ if annotation is float:
66
+ return {"type": "number"}
67
+ if isinstance(annotation, type) and dataclasses.is_dataclass(annotation):
68
+ return object_schema(annotation)
69
+ return {}
70
+
71
+
72
+ def object_schema(cls: type) -> dict[str, Any]:
73
+ """dataclass → 对象 Schema。字段说明取 ``field(metadata={...})``。"""
74
+ hints = get_type_hints(cls)
75
+ properties: dict[str, Any] = {}
76
+ required: list[str] = []
77
+ for field in dataclasses.fields(cls):
78
+ annotation = hints.get(field.name, field.type)
79
+ piece = schema_for(annotation)
80
+ description = field.metadata.get(SCHEMA_KEY)
81
+ if isinstance(description, str):
82
+ piece = {**piece, "description": description}
83
+ properties[field.name] = piece
84
+ if field.default is dataclasses.MISSING and field.default_factory is dataclasses.MISSING:
85
+ required.append(field.name)
86
+ return {
87
+ "type": "object",
88
+ "properties": properties,
89
+ "required": required,
90
+ "additionalProperties": False,
91
+ }
92
+
93
+
94
+ def describe(cls: type) -> dict[str, Any]:
95
+ """请求体的 Schema,供 OpenAPI 文档使用。"""
96
+ return object_schema(cls)
97
+
98
+
99
+ def decode_body(cls: type, payload: JsonValue | None) -> object:
100
+ """把 JSON 值按 dataclass 注解解成一个实例。
101
+
102
+ :raises ApiError: 400,消息里带字段路径(``body.timeout`` 这类)。
103
+ """
104
+ if payload is None:
105
+ payload = {}
106
+ if not isinstance(payload, dict):
107
+ raise bad_request(f"请求体必须是一个 JSON 对象,收到 {type(payload).__name__}")
108
+ hints = get_type_hints(cls)
109
+ known = {field.name for field in dataclasses.fields(cls)}
110
+ unknown = sorted(set(payload) - known)
111
+ if unknown:
112
+ raise bad_request(f"未知字段: {', '.join(unknown)}")
113
+ values: dict[str, object] = {}
114
+ for field in dataclasses.fields(cls):
115
+ if field.name not in payload:
116
+ if (
117
+ field.default is dataclasses.MISSING
118
+ and field.default_factory is dataclasses.MISSING
119
+ ):
120
+ raise bad_request(f"缺少必填字段: {field.name}")
121
+ continue
122
+ raw = payload[field.name]
123
+ values[field.name] = _coerce(hints.get(field.name, field.type), raw, field.name)
124
+ return cls(**values)
125
+
126
+
127
+ def _coerce(annotation: object, value: JsonValue, path: str) -> object:
128
+ """按注解校验并转换一个 JSON 值。"""
129
+ origin = get_origin(annotation)
130
+ if origin in (Union, types.UnionType):
131
+ args = get_args(annotation)
132
+ if value is None and type(None) in args:
133
+ return None
134
+ errors: list[ApiError] = []
135
+ for candidate in args:
136
+ if candidate is type(None):
137
+ continue
138
+ try:
139
+ return _coerce(candidate, value, path)
140
+ except ApiError as exc:
141
+ errors.append(exc)
142
+ detail = errors[0].message if errors else "类型不匹配"
143
+ raise bad_request(f"{path}: {detail}")
144
+ if origin is Literal:
145
+ options = list(get_args(annotation))
146
+ if value not in options:
147
+ raise bad_request(f"{path}: 必须是 {', '.join(map(str, options))} 之一")
148
+ return value
149
+ if origin in (list, set, tuple):
150
+ if not isinstance(value, list):
151
+ raise bad_request(f"{path}: 必须是数组")
152
+ args = get_args(annotation)
153
+ if not args:
154
+ return value
155
+ return [_coerce(args[0], item, f"{path}[{index}]") for index, item in enumerate(value)]
156
+ if origin is dict:
157
+ if not isinstance(value, dict):
158
+ raise bad_request(f"{path}: 必须是对象")
159
+ args = get_args(annotation)
160
+ if len(args) != 2:
161
+ return value
162
+ return {key: _coerce(args[1], item, f"{path}.{key}") for key, item in value.items()}
163
+ if annotation is bool:
164
+ if not isinstance(value, bool):
165
+ raise bad_request(f"{path}: 必须是布尔值")
166
+ return value
167
+ if annotation is int:
168
+ if isinstance(value, bool) or not isinstance(value, int):
169
+ raise bad_request(f"{path}: 必须是整数")
170
+ return value
171
+ if annotation is float:
172
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
173
+ raise bad_request(f"{path}: 必须是数字")
174
+ return float(value)
175
+ if annotation is str:
176
+ if not isinstance(value, str):
177
+ raise bad_request(f"{path}: 必须是字符串")
178
+ return value
179
+ if isinstance(annotation, type) and dataclasses.is_dataclass(annotation):
180
+ if not isinstance(value, dict):
181
+ raise bad_request(f"{path}: 必须是对象")
182
+ return decode_body(annotation, typing.cast("JsonValue", value))
183
+ return value
184
+
185
+
186
+ def _json_values(values: list[object]) -> list[Any]:
187
+ """枚举值 → JSON 值。非 JSON 类型(例如 ``Enum`` 的自定义值)按字符串处理。"""
188
+ converted: list[Any] = []
189
+ for value in values:
190
+ if isinstance(value, (str, int, float, bool)) or value is None:
191
+ converted.append(value)
192
+ else:
193
+ converted.append(str(value))
194
+ return converted