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,59 @@
1
+ """SDK 的 wire 辅助:路径编码、查询参数清洗、JSON 收窄。
2
+
3
+ 同步与异步客户端共用这些函数。类型收窄集中在一处,客户端方法里就不必反复写
4
+ ``isinstance`` + ``cast``——那种重复最容易在某一处漏掉 ``cast``,让 strict 模式
5
+ 在无关的位置报错。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from collections.abc import Mapping
12
+ from typing import Any, cast
13
+ from urllib.parse import quote
14
+
15
+ import httpx
16
+
17
+ from braid_ai.types import JsonValue
18
+
19
+ from .errors import BraidApiError
20
+
21
+ __all__ = ["clean_params", "decode_json", "dict_items", "require_dict", "seg"]
22
+
23
+
24
+ def clean_params(params: Mapping[str, Any] | None) -> dict[str, Any] | None:
25
+ """去掉值为 ``None`` 的查询参数。``False`` 与 ``0`` 要保留。"""
26
+ if params is None:
27
+ return None
28
+ return {key: value for key, value in params.items() if value is not None}
29
+
30
+
31
+ def seg(value: str) -> str:
32
+ """路径段编码。空格、中文与斜杠都按字面值转义,不会意外改变路径结构。"""
33
+ return quote(value, safe="")
34
+
35
+
36
+ def require_dict(value: object) -> dict[str, Any]:
37
+ """收窄成 JSON 对象。不是对象就按服务端违约处理。"""
38
+ if not isinstance(value, dict):
39
+ raise BraidApiError(500, "internal", "服务端返回的不是 JSON 对象")
40
+ return cast("dict[str, Any]", value)
41
+
42
+
43
+ def dict_items(value: object) -> list[dict[str, Any]]:
44
+ """把数组里的对象挑出来。非数组返回空列表,非对象元素跳过。"""
45
+ if not isinstance(value, list):
46
+ return []
47
+ items: list[dict[str, Any]] = []
48
+ for item in cast("list[object]", value):
49
+ if isinstance(item, dict):
50
+ items.append(cast("dict[str, Any]", item))
51
+ return items
52
+
53
+
54
+ def decode_json(response: httpx.Response) -> JsonValue:
55
+ """响应体 → JSON 值。不是 JSON 时返回原文,交给错误构造去描述。"""
56
+ try:
57
+ return cast("JsonValue", response.json())
58
+ except json.JSONDecodeError:
59
+ return response.text
@@ -0,0 +1,54 @@
1
+ """HTTP 服务与 Python SDK 的服务端部分。
2
+
3
+ 对外只有三类东西需要被调用方知道:
4
+
5
+ - :func:`create_service`:把注册表、模型目录与 MCP 运行时组成一套接口;
6
+ - :func:`run_http_service` / :func:`serve`:起一个监听端口的服务;
7
+ - :class:`SessionRegistry`:会话的创建、打开与删除。
8
+
9
+ 路由表、请求上下文与 schema 属于实现细节,测试可以直接用,产品代码不必关心。
10
+ """
11
+
12
+ from braid_coding_agent.server.errors import ApiError
13
+ from braid_coding_agent.server.http_server import (
14
+ BraidHTTPServer,
15
+ create_http_server,
16
+ run_http_service,
17
+ )
18
+ from braid_coding_agent.server.registry import SessionRegistry, SessionSummary
19
+ from braid_coding_agent.server.router import (
20
+ Frame,
21
+ HttpRequest,
22
+ QueryParam,
23
+ RequestContext,
24
+ Response,
25
+ Route,
26
+ Router,
27
+ SseStream,
28
+ )
29
+ from braid_coding_agent.server.run import ServerConfigError, ServerOptions, resolve_token, serve
30
+ from braid_coding_agent.server.service import Service, create_service, state_wire
31
+
32
+ __all__ = [
33
+ "ApiError",
34
+ "BraidHTTPServer",
35
+ "Frame",
36
+ "HttpRequest",
37
+ "QueryParam",
38
+ "RequestContext",
39
+ "Response",
40
+ "Route",
41
+ "Router",
42
+ "ServerConfigError",
43
+ "ServerOptions",
44
+ "Service",
45
+ "SessionRegistry",
46
+ "SessionSummary",
47
+ "SseStream",
48
+ "create_http_server",
49
+ "create_service",
50
+ "resolve_token",
51
+ "run_http_service",
52
+ "serve",
53
+ "state_wire",
54
+ ]
@@ -0,0 +1,52 @@
1
+ """HTTP 服务的错误模型。
2
+
3
+ 所有失败都折成 ``{"error": {"code", "message", "details"?}}``,HTTP 状态码由
4
+ :attr:`ApiError.status` 决定。客户端按 ``code`` 分支,``message`` 只给人看:
5
+ 把 Python 异常文本直接当协议字段,客户端就没法区分"会话不存在"与"服务端崩了"。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from braid_ai.types import JsonValue
11
+
12
+ __all__ = ["ApiError", "bad_request", "conflict", "not_found", "unauthorized"]
13
+
14
+
15
+ class ApiError(Exception):
16
+ """一次可以被翻译成 HTTP 响应的失败。"""
17
+
18
+ def __init__(
19
+ self,
20
+ status: int,
21
+ code: str,
22
+ message: str,
23
+ details: dict[str, JsonValue] | None = None,
24
+ ) -> None:
25
+ super().__init__(message)
26
+ self.status = status
27
+ self.code = code
28
+ self.message = message
29
+ self.details = details
30
+
31
+ def to_wire(self) -> dict[str, JsonValue]:
32
+ """错误体。``details`` 只在有内容时出现。"""
33
+ body: dict[str, JsonValue] = {"code": self.code, "message": self.message}
34
+ if self.details is not None:
35
+ body["details"] = self.details
36
+ return {"error": body}
37
+
38
+
39
+ def bad_request(message: str, **details: JsonValue) -> ApiError:
40
+ return ApiError(400, "bad_request", message, details or None)
41
+
42
+
43
+ def unauthorized(message: str = "缺少或无效的 Bearer Token") -> ApiError:
44
+ return ApiError(401, "unauthorized", message)
45
+
46
+
47
+ def not_found(message: str) -> ApiError:
48
+ return ApiError(404, "not_found", message)
49
+
50
+
51
+ def conflict(message: str, **details: JsonValue) -> ApiError:
52
+ return ApiError(409, "conflict", message, details or None)
@@ -0,0 +1,419 @@
1
+ """标准库 HTTP 适配器:把 ``http.server`` 的请求折成路由调用,把结果写回去。
2
+
3
+ ## 为什么用线程而不是 ASGI
4
+
5
+ 会话的全部状态活在一个 asyncio 事件循环上;HTTP 请求来自另一批线程。适配器做
6
+ 的只有一件事:把处理函数投递到那个循环上执行,等在请求线程里拿结果。SSE 反向
7
+ 走:事件在循环上产生,投进订阅者的线程安全队列,请求线程按帧写出。
8
+
9
+ 不引入 ASGI 服务器是一个取舍:少一条依赖链、少一套生命周期,代价是并发模型
10
+ 要自己写。这个文件就是那点代价,全部约四百行。
11
+
12
+ ## 协议细节
13
+
14
+ - **HTTP/1.1 必须自己给长度**:普通响应写 ``Content-Length``,SSE 用
15
+ ``Transfer-Encoding: chunked``。两者都不给,客户端会一直等下一条响应。
16
+ - **请求体上限**:``Content-Length`` 超过 :data:`MAX_REQUEST_BYTES` 直接 413。
17
+ 没有这条限制,一个 ``Content-Length: 10G`` 的请求会把内存吃光。
18
+ - **写失败就是客户端断开**:SSE 的 ``BrokenPipeError`` / ``ConnectionResetError``
19
+ 按断开处理,不记成服务端错误。
20
+ - **认证**:``Authorization: Bearer <token>``,比较用 ``secrets.compare_digest``。
21
+ ``/health`` 不需要令牌,供进程管理器探活;其余路径一律要。
22
+
23
+ ## 错误映射
24
+
25
+ 处理函数抛 ``ApiError`` 就按它的状态码返回;其余异常记一条 traceback,返回 500。
26
+ HTTP 是进程边界:一条请求的缺陷不该让整个服务退出,也不该让连接悬着。
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import asyncio
32
+ import contextlib
33
+ import json
34
+ import logging
35
+ import secrets
36
+ import threading
37
+ from collections.abc import Callable, Coroutine, Mapping
38
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
39
+ from typing import Any, Final
40
+ from urllib.parse import parse_qsl, unquote, urlsplit
41
+
42
+ from braid_coding_agent.modes.lifecycle import TerminationHandler
43
+
44
+ from .errors import ApiError
45
+ from .router import Frame, HttpRequest, RequestContext, Response, SseStream, Transport
46
+ from .service import Service
47
+
48
+ logger = logging.getLogger(__name__)
49
+
50
+ __all__ = ["BraidHTTPServer", "create_http_server", "run_http_service"]
51
+
52
+ #: 单个请求体的字节上限。图片用 base64 传输,给到 32MB。
53
+ MAX_REQUEST_BYTES: Final[int] = 32 * 1024 * 1024
54
+
55
+ #: 不需要令牌的路径。
56
+ PUBLIC_PATHS: Final[frozenset[str]] = frozenset({"/health"})
57
+
58
+
59
+ class LoopBridge:
60
+ """把协程投递到会话所在的事件循环,并在请求线程里等结果。"""
61
+
62
+ def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
63
+ self._loop = loop
64
+
65
+ def run(self, coroutine: Coroutine[Any, Any, Transport], *, timeout: float) -> Transport:
66
+ """执行一个协程。超时会取消它,循环不会留下一个还在跑的孤儿。"""
67
+ if self._loop.is_closed():
68
+ raise ApiError(503, "shutting_down", "服务正在关闭")
69
+ future = asyncio.run_coroutine_threadsafe(coroutine, self._loop)
70
+ try:
71
+ return future.result(timeout=timeout)
72
+ except TimeoutError:
73
+ future.cancel()
74
+ raise ApiError(504, "timeout", f"请求超过 {timeout:.0f} 秒仍未完成") from None
75
+
76
+
77
+ class BraidHTTPServer(ThreadingHTTPServer):
78
+ """带服务对象的线程化 HTTP 服务器。
79
+
80
+ ``daemon_threads``:进程退出时不等正在挂着的 SSE 连接。``allow_reuse_address``
81
+ 让测试反复在同一个端口上启停。
82
+ """
83
+
84
+ daemon_threads = True
85
+ allow_reuse_address = True
86
+
87
+ def __init__(
88
+ self,
89
+ address: tuple[str, int],
90
+ *,
91
+ service: Service,
92
+ bridge: LoopBridge,
93
+ token: str | None,
94
+ cors_origins: tuple[str, ...] = (),
95
+ ) -> None:
96
+ super().__init__(address, _RequestHandler)
97
+ self.service = service
98
+ self.bridge = bridge
99
+ self.token = token
100
+ self.cors_origins = cors_origins
101
+
102
+ def handle_error(self, request: object, client_address: object) -> None:
103
+ """连接层面的异常走日志,不直接往 stderr 打裸 traceback。
104
+
105
+ 客户端在 SSE 中途断开是正常事件;标准库的默认实现会把它打成一段以
106
+ ``Exception occurred during processing of request from`` 开头的堆栈,
107
+ 与真正的服务端缺陷混在一起。真正的处理缺陷在 ``_dispatch`` 里已经记过。
108
+ """
109
+ logger.debug("连接处理异常: %s", client_address, exc_info=True)
110
+
111
+
112
+ class _RequestHandler(BaseHTTPRequestHandler):
113
+ """一条请求一份实例。``server`` 的类型由 :class:`BraidHTTPServer` 保证。"""
114
+
115
+ protocol_version = "HTTP/1.1"
116
+ server_version = "braid"
117
+ sys_version = ""
118
+
119
+ # ------------------------------------------------------------ 方法分发
120
+
121
+ def do_GET(self) -> None:
122
+ self._dispatch("GET")
123
+
124
+ def do_POST(self) -> None:
125
+ self._dispatch("POST")
126
+
127
+ def do_PUT(self) -> None:
128
+ self._dispatch("PUT")
129
+
130
+ def do_DELETE(self) -> None:
131
+ self._dispatch("DELETE")
132
+
133
+ def do_OPTIONS(self) -> None:
134
+ """CORS 预检。没有配置 ``--cors-origin`` 时也返回 204,只是不带允许头。"""
135
+ self.send_response(204)
136
+ self._send_cors_headers()
137
+ self.send_header("Content-Length", "0")
138
+ self.end_headers()
139
+
140
+ def log_message(self, format: str, *args: object) -> None:
141
+ """访问日志走 logging,不直接写 stderr——stdout 要给监听地址那一行。"""
142
+ logger.debug("%s - %s", self.address_string(), format % args)
143
+
144
+ def finish(self) -> None:
145
+ """收尾时刷缓冲。客户端已经断开就没有什么可刷的了。
146
+
147
+ 标准库在 ``finish`` 里 ``flush``,连接被对端重置时抛 ``ConnectionResetError``;
148
+ 那会被 ``socketserver`` 当作处理异常打印一段堆栈。SSE 客户端关页面就是这种
149
+ 情况,属于正常断开。
150
+ """
151
+ with contextlib.suppress(BrokenPipeError, ConnectionResetError):
152
+ super().finish()
153
+
154
+ # -------------------------------------------------------------- 主流程
155
+
156
+ def _dispatch(self, method: str) -> None:
157
+ server = self._braid
158
+ split = urlsplit(self.path)
159
+ path = unquote(split.path or "/")
160
+ query = dict(parse_qsl(split.query, keep_blank_values=False))
161
+ try:
162
+ body = self._read_body()
163
+ if path not in PUBLIC_PATHS:
164
+ self._require_token(server)
165
+ found = server.service.router.match(method, path)
166
+ if found is None:
167
+ allowed = server.service.router.allowed_methods(path)
168
+ if allowed:
169
+ self._write_json(
170
+ 405,
171
+ {
172
+ "error": {
173
+ "code": "method_not_allowed",
174
+ "message": f"支持: {', '.join(allowed)}",
175
+ }
176
+ },
177
+ extra_headers={"Allow": ", ".join(allowed)},
178
+ )
179
+ return
180
+ raise ApiError(404, "not_found", f"没有这条路由: {method} {path}")
181
+ route, params = found
182
+ request = HttpRequest(
183
+ method=method,
184
+ path=path,
185
+ query=query,
186
+ headers={key.lower(): value for key, value in self.headers.items()},
187
+ body=body,
188
+ )
189
+ context = RequestContext(
190
+ request=request,
191
+ params=params,
192
+ service=server.service,
193
+ route=route,
194
+ )
195
+
196
+ async def call() -> Transport:
197
+ return await route.handler(context)
198
+
199
+ transport = server.bridge.run(call(), timeout=route.timeout)
200
+ if isinstance(transport, SseStream):
201
+ self._write_sse(transport)
202
+ else:
203
+ self._write_response(transport)
204
+ except ApiError as exc:
205
+ self._write_json(exc.status, exc.to_wire())
206
+ except (BrokenPipeError, ConnectionResetError):
207
+ # 客户端在响应写完之前断开:记录即可,没有可写的连接了。
208
+ logger.debug("客户端提前断开: %s %s", method, path)
209
+ except Exception as exc:
210
+ # 进程边界:一条请求的处理缺陷记一条 traceback 返回 500,服务继续。
211
+ logger.exception("HTTP 处理失败: %s %s", method, path)
212
+ self._write_json(
213
+ 500, {"error": {"code": "internal", "message": str(exc) or type(exc).__name__}}
214
+ )
215
+
216
+ @property
217
+ def _braid(self) -> BraidHTTPServer:
218
+ server = self.server
219
+ assert isinstance(server, BraidHTTPServer)
220
+ return server
221
+
222
+ def _read_body(self) -> bytes:
223
+ """读请求体。超过上限直接 413,不把它读进内存。"""
224
+ raw_length = self.headers.get("Content-Length")
225
+ if raw_length is None:
226
+ return b""
227
+ try:
228
+ length = int(raw_length)
229
+ except ValueError:
230
+ raise ApiError(400, "bad_request", f"Content-Length 不是整数: {raw_length}") from None
231
+ if length < 0:
232
+ raise ApiError(400, "bad_request", "Content-Length 不能是负数")
233
+ if length > MAX_REQUEST_BYTES:
234
+ raise ApiError(413, "payload_too_large", f"请求体超过 {MAX_REQUEST_BYTES} 字节")
235
+ return self.rfile.read(length)
236
+
237
+ def _require_token(self, server: BraidHTTPServer) -> None:
238
+ """校验 Bearer Token。没有配置令牌时放行(只监听本机时的默认行为)。"""
239
+ expected = server.token
240
+ if expected is None:
241
+ return
242
+ header = self.headers.get("Authorization", "")
243
+ scheme, _, value = header.partition(" ")
244
+ if scheme.lower() != "bearer" or not secrets.compare_digest(value.strip(), expected):
245
+ raise ApiError(401, "unauthorized", "缺少或无效的 Bearer Token")
246
+
247
+ # -------------------------------------------------------------- 写响应
248
+
249
+ def _write_response(self, response: Response) -> None:
250
+ """JSON 响应。204 不写响应体。"""
251
+ if response.status == 204:
252
+ self.send_response(204)
253
+ self._send_cors_headers()
254
+ for key, value in response.headers.items():
255
+ self.send_header(key, value)
256
+ self.send_header("Content-Length", "0")
257
+ self.end_headers()
258
+ return
259
+ self._write_json(response.status, response.body, extra_headers=response.headers)
260
+
261
+ def _write_json(
262
+ self,
263
+ status: int,
264
+ body: Any,
265
+ *,
266
+ extra_headers: Mapping[str, str] | None = None,
267
+ ) -> None:
268
+ payload = json.dumps(body, ensure_ascii=False).encode("utf-8")
269
+ self.send_response(status)
270
+ self._send_cors_headers()
271
+ self.send_header("Content-Type", "application/json; charset=utf-8")
272
+ if extra_headers is not None:
273
+ for key, value in extra_headers.items():
274
+ self.send_header(key, value)
275
+ self.send_header("Content-Length", str(len(payload)))
276
+ self.end_headers()
277
+ self.wfile.write(payload)
278
+
279
+ def _write_sse(self, stream: SseStream) -> None:
280
+ """SSE:chunked 传输,逐帧写出。
281
+
282
+ ``on_close`` 放在 ``finally``:客户端断开、服务端关闭、写响应头失败,三条
283
+ 路径都要把订阅者摘掉,否则会话里会留下一个永远不会被读的队列。写响应头也
284
+ 放在 ``try`` 里面:客户端可能在响应开始之前就断开。
285
+ """
286
+ started = False
287
+ try:
288
+ self.send_response(200)
289
+ self._send_cors_headers()
290
+ self.send_header("Content-Type", "text/event-stream; charset=utf-8")
291
+ self.send_header("Cache-Control", "no-cache")
292
+ self.send_header("Connection", "keep-alive")
293
+ self.send_header("Transfer-Encoding", "chunked")
294
+ for key, value in stream.headers.items():
295
+ self.send_header(key, value)
296
+ self.end_headers()
297
+ started = True
298
+ for frame in stream.frames:
299
+ self._write_chunk(_encode_frame(frame))
300
+ except (BrokenPipeError, ConnectionResetError):
301
+ logger.debug("SSE 客户端断开")
302
+ finally:
303
+ if stream.on_close is not None:
304
+ stream.on_close()
305
+ if not started:
306
+ return
307
+ # 结束分块。客户端已经走了就没什么可写的了。
308
+ with contextlib.suppress(BrokenPipeError, ConnectionResetError):
309
+ self._write_chunk(b"")
310
+ with contextlib.suppress(BrokenPipeError, ConnectionResetError):
311
+ self._write_chunk(b"")
312
+
313
+ def _write_chunk(self, data: bytes) -> None:
314
+ """一个 HTTP chunk。``wfile`` 是无缓冲的,写完即上线路。"""
315
+ self.wfile.write(f"{len(data):X}\r\n".encode("ascii") + data + b"\r\n")
316
+
317
+ def _send_cors_headers(self) -> None:
318
+ """配置了 ``--cors-origin`` 时补允许头。``*`` 表示任何来源。"""
319
+ origins = self._braid.cors_origins
320
+ if not origins:
321
+ return
322
+ request_origin = self.headers.get("Origin")
323
+ allowed: str | None = None
324
+ if "*" in origins:
325
+ allowed = "*"
326
+ elif request_origin is not None and request_origin in origins:
327
+ allowed = request_origin
328
+ if allowed is None:
329
+ return
330
+ self.send_header("Access-Control-Allow-Origin", allowed)
331
+ self.send_header(
332
+ "Access-Control-Allow-Headers", "authorization, content-type, last-event-id"
333
+ )
334
+ self.send_header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
335
+ self.send_header("Access-Control-Max-Age", "600")
336
+
337
+
338
+ def _encode_frame(frame: Frame) -> bytes:
339
+ """一帧 SSE → 字节。
340
+
341
+ ``event`` 为 ``None`` 时写成注释行:SSE 规范里以 ``:`` 开头的行是注释,浏览器
342
+ 的 ``EventSource`` 会忽略它,但 TCP 上确实有数据,中间设备因此不会掐连接。
343
+ """
344
+ if frame.event is None:
345
+ return b": keepalive\n\n"
346
+ lines: list[str] = []
347
+ if frame.id is not None:
348
+ lines.append(f"id: {frame.id}")
349
+ lines.append(f"event: {frame.event}")
350
+ for line in frame.data.split("\n"):
351
+ lines.append(f"data: {line}")
352
+ return ("\n".join(lines) + "\n\n").encode("utf-8")
353
+
354
+
355
+ def create_http_server(
356
+ *,
357
+ service: Service,
358
+ loop: asyncio.AbstractEventLoop,
359
+ host: str,
360
+ port: int,
361
+ token: str | None,
362
+ cors_origins: tuple[str, ...] = (),
363
+ ) -> BraidHTTPServer:
364
+ """建服务器并绑定端口。``port=0`` 由系统分配,``server_address`` 里读实际端口。"""
365
+ return BraidHTTPServer(
366
+ (host, port),
367
+ service=service,
368
+ bridge=LoopBridge(loop),
369
+ token=token,
370
+ cors_origins=cors_origins,
371
+ )
372
+
373
+
374
+ async def run_http_service(
375
+ *,
376
+ service: Service,
377
+ host: str,
378
+ port: int,
379
+ token: str | None,
380
+ cors_origins: tuple[str, ...] = (),
381
+ on_listening: Callable[[BraidHTTPServer], None] | None = None,
382
+ ) -> int:
383
+ """启动服务直到收到终止信号。
384
+
385
+ :param on_listening: 启动完成后的回调。CLI 用它打印监听地址;测试用它拿到
386
+ ``port=0`` 分配到的端口。
387
+ """
388
+ loop = asyncio.get_running_loop()
389
+ server = create_http_server(
390
+ service=service,
391
+ loop=loop,
392
+ host=host,
393
+ port=port,
394
+ token=token,
395
+ cors_origins=cors_origins,
396
+ )
397
+ thread = threading.Thread(target=server.serve_forever, name="braid-http", daemon=True)
398
+ thread.start()
399
+ if on_listening is not None:
400
+ on_listening(server)
401
+
402
+ handler = TerminationHandler()
403
+ handler.install()
404
+ exit_code = 0
405
+ try:
406
+ if handler.installed:
407
+ await handler.wait()
408
+ exit_code = handler.exit_code
409
+ else:
410
+ # 装不上信号处理器(例如在非主线程里跑测试)时,只能等被别人停掉。
411
+ await asyncio.Event().wait()
412
+ finally:
413
+ handler.close()
414
+ # 先停接受循环,再释放会话:SSE 订阅者收到"断开"哨兵后才能把结束分块写出去,
415
+ # 反过来(先关 socket)会让它们撞上一个已经关掉的连接。
416
+ await asyncio.to_thread(server.shutdown)
417
+ await service.close()
418
+ server.server_close()
419
+ return exit_code