agentize-bridge 0.2.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.
- agentize_bridge/__init__.py +5 -0
- agentize_bridge/__version__.py +6 -0
- agentize_bridge/adapters/cli/__init__.py +3 -0
- agentize_bridge/adapters/cli/app.py +24 -0
- agentize_bridge/adapters/cli/commands.py +334 -0
- agentize_bridge/adapters/cli/output.py +94 -0
- agentize_bridge/adapters/cli/parser.py +190 -0
- agentize_bridge/adapters/http_client.py +188 -0
- agentize_bridge/adapters/mcp_server.py +118 -0
- agentize_bridge/core/__init__.py +9 -0
- agentize_bridge/core/command.py +82 -0
- agentize_bridge/core/registry.py +27 -0
- agentize_bridge/core/result.py +17 -0
- agentize_bridge/core/schema.py +56 -0
- agentize_bridge/runtime/__init__.py +9 -0
- agentize_bridge/runtime/container.py +24 -0
- agentize_bridge/runtime/executor.py +54 -0
- agentize_bridge/runtime/queues.py +34 -0
- agentize_bridge/runtime/util.py +26 -0
- agentize_bridge/server/__init__.py +3 -0
- agentize_bridge/server/accept.py +38 -0
- agentize_bridge/server/access_log.py +190 -0
- agentize_bridge/server/bridge.py +297 -0
- agentize_bridge/server/credentials.py +120 -0
- agentize_bridge-0.2.0.dist-info/METADATA +98 -0
- agentize_bridge-0.2.0.dist-info/RECORD +30 -0
- agentize_bridge-0.2.0.dist-info/WHEEL +5 -0
- agentize_bridge-0.2.0.dist-info/entry_points.txt +4 -0
- agentize_bridge-0.2.0.dist-info/licenses/LICENSE +21 -0
- agentize_bridge-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
from urllib.request import parse_http_list
|
|
2
|
+
|
|
3
|
+
from ..core.result import BINARY_MEDIA_TYPES
|
|
4
|
+
|
|
5
|
+
JSON_MEDIA_TYPE = "application/json"
|
|
6
|
+
DECLARED_MEDIA_TYPES = {
|
|
7
|
+
"json": frozenset({JSON_MEDIA_TYPE}),
|
|
8
|
+
"binary": BINARY_MEDIA_TYPES,
|
|
9
|
+
}
|
|
10
|
+
_COMMAND_MEDIA_TYPES = BINARY_MEDIA_TYPES | {JSON_MEDIA_TYPE}
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def accepted_media_types(headers: list[str]) -> frozenset[str]:
|
|
14
|
+
"""匹配命令使用的媒体类型,具体媒体范围优先于通配符。"""
|
|
15
|
+
if not headers:
|
|
16
|
+
return _COMMAND_MEDIA_TYPES
|
|
17
|
+
|
|
18
|
+
weights: dict[str, float] = {}
|
|
19
|
+
for item in parse_http_list(",".join(headers)):
|
|
20
|
+
media_range, *parameters = (part.strip() for part in item.lower().split(";"))
|
|
21
|
+
quality = 1.0
|
|
22
|
+
if parameters:
|
|
23
|
+
# Bridge 发出的媒体类型没有参数,媒体协商只需要读取权重。
|
|
24
|
+
name, _, value = parameters[0].partition("=")
|
|
25
|
+
if len(parameters) != 1 or name.strip() != "q":
|
|
26
|
+
continue
|
|
27
|
+
try:
|
|
28
|
+
quality = float(value)
|
|
29
|
+
except ValueError:
|
|
30
|
+
continue
|
|
31
|
+
if 0.0 <= quality <= 1.0:
|
|
32
|
+
weights[media_range] = max(quality, weights.get(media_range, 0.0))
|
|
33
|
+
|
|
34
|
+
wildcard = weights.get("*/*", 0.0)
|
|
35
|
+
return frozenset(
|
|
36
|
+
media_type for media_type in _COMMAND_MEDIA_TYPES
|
|
37
|
+
if weights.get(media_type, weights.get(f"{media_type.split('/')[0]}/*", wildcard)) > 0.0
|
|
38
|
+
)
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
import json
|
|
3
|
+
import logging
|
|
4
|
+
import sys
|
|
5
|
+
import time
|
|
6
|
+
from contextlib import ExitStack
|
|
7
|
+
from contextvars import ContextVar
|
|
8
|
+
from os import PathLike
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Literal
|
|
11
|
+
|
|
12
|
+
from fastapi import FastAPI, Request
|
|
13
|
+
from fastapi.exception_handlers import http_exception_handler
|
|
14
|
+
from starlette.concurrency import run_in_threadpool
|
|
15
|
+
from starlette.exceptions import HTTPException
|
|
16
|
+
from starlette.responses import Response
|
|
17
|
+
from starlette.types import Message, Receive, Scope, Send
|
|
18
|
+
|
|
19
|
+
__all__ = ["AccessLogApp"]
|
|
20
|
+
|
|
21
|
+
LogMode = Literal["simple", "full"]
|
|
22
|
+
|
|
23
|
+
_ACCESS_LOGGER = "agentize_bridge.access_logger"
|
|
24
|
+
_ACCESS_DETAIL = "agentize_bridge.access_detail"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def record_access_detail(scope: Scope, detail: object) -> None:
|
|
28
|
+
"""供内部中间件写入访问日志详情(仅在 AccessLogApp 已激活时生效)。"""
|
|
29
|
+
state = scope.get("state")
|
|
30
|
+
if isinstance(state, dict) and _ACCESS_LOGGER in state:
|
|
31
|
+
state[_ACCESS_DETAIL] = detail
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class AccessLogApp:
|
|
35
|
+
""" 在原应用的 ASGI 入口记录访问日志 """
|
|
36
|
+
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
app: FastAPI,
|
|
40
|
+
*,
|
|
41
|
+
mode: LogMode = "simple",
|
|
42
|
+
file_path: str | PathLike[str] | None = None
|
|
43
|
+
) -> None:
|
|
44
|
+
if mode not in ("simple", "full"):
|
|
45
|
+
raise ValueError(f"无效的日志模式: {mode!r}")
|
|
46
|
+
|
|
47
|
+
self._app = app
|
|
48
|
+
self._console_level = logging.WARNING if mode == "simple" else logging.INFO
|
|
49
|
+
self._path = Path(file_path) if file_path is not None else None
|
|
50
|
+
self._replacing_access = ContextVar("agentize_bridge.replacing_access", default=False)
|
|
51
|
+
self._http_error_handler = app.exception_handlers.get(HTTPException, http_exception_handler)
|
|
52
|
+
app.add_exception_handler(HTTPException, self._handle_http_error)
|
|
53
|
+
|
|
54
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
55
|
+
""" 转发 ASGI 调用,在 HTTP 响应开始时替换原生访问行 """
|
|
56
|
+
if scope["type"] == "lifespan":
|
|
57
|
+
await self._serve_lifespan(scope, receive, send)
|
|
58
|
+
return
|
|
59
|
+
|
|
60
|
+
logger = scope.get("state", {}).get(_ACCESS_LOGGER)
|
|
61
|
+
if scope["type"] != "http" or logger is None:
|
|
62
|
+
await self._app(scope, receive, send)
|
|
63
|
+
return
|
|
64
|
+
|
|
65
|
+
started_at = time.perf_counter()
|
|
66
|
+
|
|
67
|
+
async def send_response(message: Message) -> None:
|
|
68
|
+
if message["type"] != "http.response.start":
|
|
69
|
+
await send(message)
|
|
70
|
+
return
|
|
71
|
+
|
|
72
|
+
elapsed_ms = (time.perf_counter() - started_at) * 1000
|
|
73
|
+
# _serve_lifespan 安装的过滤器只在发送此消息时跳过 Uvicorn 的访问行。
|
|
74
|
+
token = self._replacing_access.set(True)
|
|
75
|
+
try:
|
|
76
|
+
await send(message)
|
|
77
|
+
finally:
|
|
78
|
+
self._replacing_access.reset(token)
|
|
79
|
+
|
|
80
|
+
try:
|
|
81
|
+
self._write_access(logger, scope, message["status"], elapsed_ms)
|
|
82
|
+
except Exception:
|
|
83
|
+
try:
|
|
84
|
+
logging.getLogger(__name__).exception("HTTP 访问日志记录失败")
|
|
85
|
+
except Exception:
|
|
86
|
+
# 即使宿主的诊断输出失败,也要继续发送响应体。
|
|
87
|
+
pass
|
|
88
|
+
|
|
89
|
+
await self._app(scope, receive, send_response)
|
|
90
|
+
|
|
91
|
+
async def _serve_lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
92
|
+
""" 在应用确认启动前安装 logger 和过滤器,由同一个 ExitStack 负责清理 """
|
|
93
|
+
native_access = logging.getLogger("uvicorn.access")
|
|
94
|
+
|
|
95
|
+
def keep_native_access(_record: logging.LogRecord) -> bool:
|
|
96
|
+
return not self._replacing_access.get()
|
|
97
|
+
|
|
98
|
+
with ExitStack() as resources:
|
|
99
|
+
async def send_lifespan(message: Message) -> None:
|
|
100
|
+
if message["type"] == "lifespan.startup.complete":
|
|
101
|
+
state = scope["state"]
|
|
102
|
+
logger = self._open_access_logger(resources)
|
|
103
|
+
|
|
104
|
+
native_access.addFilter(keep_native_access)
|
|
105
|
+
resources.callback(native_access.removeFilter, keep_native_access)
|
|
106
|
+
state[_ACCESS_LOGGER] = logger
|
|
107
|
+
resources.callback(state.pop, _ACCESS_LOGGER, None)
|
|
108
|
+
resources.callback(setattr, logger, "disabled", True)
|
|
109
|
+
|
|
110
|
+
await send(message)
|
|
111
|
+
|
|
112
|
+
await self._app(scope, receive, send_lifespan)
|
|
113
|
+
|
|
114
|
+
def _open_access_logger(self, resources: ExitStack) -> logging.Logger:
|
|
115
|
+
""" 配置控制台和可选文件,并将 handler 的关闭动作登记到应用生命周期 """
|
|
116
|
+
logger = logging.Logger("agentize_bridge.access", level=logging.INFO)
|
|
117
|
+
plain = logging.Formatter("%(levelname)s: %(message)s")
|
|
118
|
+
|
|
119
|
+
console = logging.StreamHandler(sys.stdout)
|
|
120
|
+
resources.callback(console.close)
|
|
121
|
+
console.setLevel(self._console_level)
|
|
122
|
+
console.setFormatter(_ConsoleFormatter() if console.stream.isatty() else plain)
|
|
123
|
+
logger.addHandler(console)
|
|
124
|
+
|
|
125
|
+
if self._path is not None:
|
|
126
|
+
self._path.parent.mkdir(parents=True, exist_ok=True)
|
|
127
|
+
file_handler = logging.FileHandler(self._path, mode="a", encoding="utf-8")
|
|
128
|
+
resources.callback(file_handler.close)
|
|
129
|
+
file_handler.setFormatter(plain)
|
|
130
|
+
logger.addHandler(file_handler)
|
|
131
|
+
|
|
132
|
+
return logger
|
|
133
|
+
|
|
134
|
+
async def _handle_http_error(self, request: Request, exc: HTTPException) -> Response:
|
|
135
|
+
""" 记录 HTTP 异常的业务详情,由原有异常处理器生成响应 """
|
|
136
|
+
state = request.scope.get("state", {})
|
|
137
|
+
if _ACCESS_LOGGER in state:
|
|
138
|
+
detail = exc.detail
|
|
139
|
+
if exc.status_code == 500 and isinstance(detail, str) and exc.__cause__ is not None:
|
|
140
|
+
# 命令路由将 CommandExecutionError 包装为 HTTPException,前者保留原始异常。
|
|
141
|
+
cause = exc.__cause__
|
|
142
|
+
detail = cause.__cause__ if cause.__cause__ is not None else cause
|
|
143
|
+
state[_ACCESS_DETAIL] = detail
|
|
144
|
+
|
|
145
|
+
handler = self._http_error_handler
|
|
146
|
+
if inspect.iscoroutinefunction(handler):
|
|
147
|
+
return await handler(request, exc)
|
|
148
|
+
|
|
149
|
+
response = await run_in_threadpool(handler, request, exc)
|
|
150
|
+
if inspect.isawaitable(response):
|
|
151
|
+
return await response
|
|
152
|
+
return response
|
|
153
|
+
|
|
154
|
+
@staticmethod
|
|
155
|
+
def _write_access(logger: logging.Logger, scope: Scope, status: int, elapsed_ms: float) -> None:
|
|
156
|
+
""" 根据状态码定级,将地址、路径、耗时和详情写成一行 """
|
|
157
|
+
level = logging.INFO
|
|
158
|
+
if status >= 500:
|
|
159
|
+
level = logging.ERROR
|
|
160
|
+
elif status >= 400:
|
|
161
|
+
level = logging.WARNING
|
|
162
|
+
|
|
163
|
+
client = scope.get("client")
|
|
164
|
+
address = f"{client[0]}:{client[1]}" if client else "-"
|
|
165
|
+
target = json.dumps(f'{scope["method"]} {scope["path"]}', ensure_ascii=False)
|
|
166
|
+
|
|
167
|
+
detail = scope.get("state", {}).get(_ACCESS_DETAIL)
|
|
168
|
+
suffix = ""
|
|
169
|
+
if detail is not None:
|
|
170
|
+
if isinstance(detail, BaseException):
|
|
171
|
+
detail = f"{type(detail).__name__}: {detail}"
|
|
172
|
+
try:
|
|
173
|
+
encoded = json.dumps(detail, ensure_ascii=False, default=str)
|
|
174
|
+
except (TypeError, ValueError):
|
|
175
|
+
detail = str(detail)
|
|
176
|
+
encoded = json.dumps(detail, ensure_ascii=False)
|
|
177
|
+
suffix = f" | {encoded[1:-1] if isinstance(detail, str) else encoded}"
|
|
178
|
+
|
|
179
|
+
logger.log(level, "%s - %s %d %.1fms%s", address, target, status, elapsed_ms, suffix)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
class _ConsoleFormatter(logging.Formatter):
|
|
183
|
+
""" 为终端访问日志设置级别颜色,每行独立重置终端样式 """
|
|
184
|
+
|
|
185
|
+
colors = {logging.INFO: "\x1b[32m", logging.WARNING: "\x1b[33m", logging.ERROR: "\x1b[31m"}
|
|
186
|
+
reset = "\x1b[0m"
|
|
187
|
+
|
|
188
|
+
def format(self, record: logging.LogRecord) -> str:
|
|
189
|
+
color = self.colors.get(record.levelno, "")
|
|
190
|
+
return f"{self.reset}{color}{record.levelname}:{self.reset} {record.getMessage()}"
|
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import threading
|
|
3
|
+
import time
|
|
4
|
+
from concurrent.futures import CancelledError, ThreadPoolExecutor
|
|
5
|
+
from datetime import UTC, datetime
|
|
6
|
+
from hmac import compare_digest
|
|
7
|
+
from os import PathLike
|
|
8
|
+
from queue import Empty
|
|
9
|
+
from threading import Thread
|
|
10
|
+
from typing import Any, Mapping
|
|
11
|
+
|
|
12
|
+
import uvicorn
|
|
13
|
+
from fastapi import Body, FastAPI, HTTPException, Query, Request
|
|
14
|
+
from fastapi.middleware.trustedhost import TrustedHostMiddleware
|
|
15
|
+
from fastapi.responses import JSONResponse, Response
|
|
16
|
+
|
|
17
|
+
from .access_log import AccessLogApp, LogMode, record_access_detail
|
|
18
|
+
from .accept import DECLARED_MEDIA_TYPES, JSON_MEDIA_TYPE, accepted_media_types
|
|
19
|
+
from .credentials import AuthSetting, DEFAULT_TOKEN_FILE, load_or_create_credential, parse_auth_setting
|
|
20
|
+
from agentize_bridge import __version__
|
|
21
|
+
from agentize_bridge.runtime import CommandQueue, Container, CommandExecutor, CommandNotFoundError, CommandArgumentsError, CommandExecutionError
|
|
22
|
+
from agentize_bridge.core import BinaryResult, Command, snapshot
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ServerClosedError(RuntimeError):
|
|
26
|
+
""" 服务已关闭:不再受理新请求,已排队的请求会被失败化 """
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class _OutputNotAcceptableError(ValueError):
|
|
30
|
+
def __init__(self, available: frozenset[str], accepted: frozenset[str]) -> None:
|
|
31
|
+
if JSON_MEDIA_TYPE in available:
|
|
32
|
+
detail = "请求已收到,但命令输出为 JSON,未返回可保存的文件"
|
|
33
|
+
elif accepted == DECLARED_MEDIA_TYPES["json"]:
|
|
34
|
+
detail = "请求已收到,但客户端只接收 JSON,二进制文件未保存"
|
|
35
|
+
elif len(available) == 1:
|
|
36
|
+
media_type = next(iter(available))
|
|
37
|
+
detail = f"请求已收到,但客户端不接收 {media_type},文件未保存"
|
|
38
|
+
else:
|
|
39
|
+
detail = "请求已收到,但客户端不接收此命令的二进制输出,文件未保存"
|
|
40
|
+
super().__init__(detail)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class AgentizeServer:
|
|
44
|
+
""" 注册命令并通过共享的 HTTP/MCP 服务器公开它们 """
|
|
45
|
+
|
|
46
|
+
def __init__(
|
|
47
|
+
self,
|
|
48
|
+
name: str = "Agentize Bridge",
|
|
49
|
+
*,
|
|
50
|
+
log_mode: LogMode = "simple",
|
|
51
|
+
log_file: str | PathLike[str] | None = None,
|
|
52
|
+
auth: AuthSetting = False
|
|
53
|
+
):
|
|
54
|
+
enabled, ttl = parse_auth_setting(auth)
|
|
55
|
+
credential = load_or_create_credential(DEFAULT_TOKEN_FILE, ttl) if enabled else None
|
|
56
|
+
|
|
57
|
+
self.name = name
|
|
58
|
+
self.container = Container()
|
|
59
|
+
|
|
60
|
+
self._commands: dict[str, Command] = {}
|
|
61
|
+
self._executor = CommandExecutor(self.container)
|
|
62
|
+
self._queue = CommandQueue()
|
|
63
|
+
self._workers = ThreadPoolExecutor(thread_name_prefix="agentize-worker")
|
|
64
|
+
|
|
65
|
+
self.fastapi_app = FastAPI(title=self.name, version=__version__)
|
|
66
|
+
self._http_app = AccessLogApp(self.fastapi_app, mode=log_mode, file_path=log_file)
|
|
67
|
+
self._http_server: uvicorn.Server | None = None
|
|
68
|
+
self._http_thread: Thread | None = None
|
|
69
|
+
self._closed = False
|
|
70
|
+
self._state_lock = threading.Lock()
|
|
71
|
+
|
|
72
|
+
if credential is not None:
|
|
73
|
+
self._install_token_auth(credential, ttl)
|
|
74
|
+
self._register_routes()
|
|
75
|
+
|
|
76
|
+
def run_pending(self, limit: int | None = None) -> int:
|
|
77
|
+
""" 从队列中消费命令(应用内主线程循环挂载使用);关闭后返回 0 """
|
|
78
|
+
processed = 0
|
|
79
|
+
while limit is None or processed < limit:
|
|
80
|
+
with self._state_lock:
|
|
81
|
+
if self._closed:
|
|
82
|
+
break
|
|
83
|
+
try:
|
|
84
|
+
request = self._queue.get_nowait()
|
|
85
|
+
except Empty:
|
|
86
|
+
break
|
|
87
|
+
|
|
88
|
+
try:
|
|
89
|
+
if not request.future.set_running_or_notify_cancel():
|
|
90
|
+
continue
|
|
91
|
+
command = self._commands.get(request.name)
|
|
92
|
+
if command is None:
|
|
93
|
+
request.future.set_exception(CommandNotFoundError(f"找不到命令 {request.name}"))
|
|
94
|
+
else:
|
|
95
|
+
try:
|
|
96
|
+
result = self._executor.execute(command, request.arguments)
|
|
97
|
+
except Exception as exc:
|
|
98
|
+
request.future.set_exception(exc)
|
|
99
|
+
else:
|
|
100
|
+
request.future.set_result(result)
|
|
101
|
+
finally:
|
|
102
|
+
self._queue.task_done()
|
|
103
|
+
processed += 1
|
|
104
|
+
return processed
|
|
105
|
+
|
|
106
|
+
def start_http(self, *, host: str = "127.0.0.1", port: int = 8765):
|
|
107
|
+
""" 在后台线程中启动 HTTP 服务,使应用程序的主循环保持空闲 """
|
|
108
|
+
with self._state_lock:
|
|
109
|
+
if self._closed:
|
|
110
|
+
raise RuntimeError("AgentizeServer 已关闭")
|
|
111
|
+
if self._http_thread is not None:
|
|
112
|
+
raise RuntimeError("HTTP 服务已经启动")
|
|
113
|
+
|
|
114
|
+
self._commands.update(snapshot())
|
|
115
|
+
|
|
116
|
+
# Host 和 Origin 校验
|
|
117
|
+
self._install_local_guard(host=host, port=port)
|
|
118
|
+
|
|
119
|
+
config = uvicorn.Config(self._http_app, host=host, port=port)
|
|
120
|
+
self._http_server = uvicorn.Server(config)
|
|
121
|
+
self._http_thread = threading.Thread(
|
|
122
|
+
target=self._http_server.run,
|
|
123
|
+
name="agentize-server",
|
|
124
|
+
daemon=True
|
|
125
|
+
)
|
|
126
|
+
self._http_thread.start()
|
|
127
|
+
|
|
128
|
+
deadline = time.monotonic() + 10
|
|
129
|
+
while not self._http_server.started:
|
|
130
|
+
if not self._http_thread.is_alive():
|
|
131
|
+
raise RuntimeError("HTTP 服务器启动失败,请检查配置的主机和端口")
|
|
132
|
+
if time.monotonic() >= deadline:
|
|
133
|
+
self._http_server.should_exit = True
|
|
134
|
+
raise TimeoutError("启动 HTTP 服务器时超时")
|
|
135
|
+
time.sleep(0.01)
|
|
136
|
+
|
|
137
|
+
def close(self, *, wait: bool = True) -> None:
|
|
138
|
+
with self._state_lock:
|
|
139
|
+
if self._closed:
|
|
140
|
+
return
|
|
141
|
+
self._closed = True
|
|
142
|
+
|
|
143
|
+
# 失败化队列中尚未执行的请求,避免调用方一直等到客户端超时
|
|
144
|
+
while True:
|
|
145
|
+
try:
|
|
146
|
+
request = self._queue.get_nowait()
|
|
147
|
+
except Empty:
|
|
148
|
+
break
|
|
149
|
+
if request.future.set_running_or_notify_cancel():
|
|
150
|
+
request.future.set_exception(ServerClosedError("AgentizeServer 已关闭"))
|
|
151
|
+
self._queue.task_done()
|
|
152
|
+
|
|
153
|
+
if self._http_server is not None:
|
|
154
|
+
self._http_server.should_exit = True
|
|
155
|
+
if (
|
|
156
|
+
wait
|
|
157
|
+
and self._http_thread is not None
|
|
158
|
+
and threading.current_thread() != self._http_thread
|
|
159
|
+
):
|
|
160
|
+
self._http_thread.join(timeout=5)
|
|
161
|
+
|
|
162
|
+
self._workers.shutdown(wait, cancel_futures=not wait)
|
|
163
|
+
|
|
164
|
+
def _register_routes(self):
|
|
165
|
+
""" 构建内部的 FastAPI 应用 """
|
|
166
|
+
app = self.fastapi_app
|
|
167
|
+
|
|
168
|
+
@app.get("/health")
|
|
169
|
+
def health() -> dict[str, str]:
|
|
170
|
+
return {"status": "ok"}
|
|
171
|
+
|
|
172
|
+
@app.get("/commands")
|
|
173
|
+
def list_commands() -> list[dict[str, Any]]:
|
|
174
|
+
return [
|
|
175
|
+
{
|
|
176
|
+
"name": command.name,
|
|
177
|
+
"description": command.description,
|
|
178
|
+
"thread": command.thread,
|
|
179
|
+
"input_schema": command.input_schema,
|
|
180
|
+
"output": {"kind": command.output_kind},
|
|
181
|
+
}
|
|
182
|
+
for command in self._commands.values()
|
|
183
|
+
]
|
|
184
|
+
|
|
185
|
+
@app.post("/command/{name}")
|
|
186
|
+
async def execute_command(
|
|
187
|
+
name: str,
|
|
188
|
+
request: Request,
|
|
189
|
+
arguments: dict[str, Any] = Body(...),
|
|
190
|
+
timeout: float | None = Query(default=None, gt=0)
|
|
191
|
+
) -> Any:
|
|
192
|
+
accepted = accepted_media_types(request.headers.getlist("accept"))
|
|
193
|
+
try:
|
|
194
|
+
result = await self._dispatch(name, arguments, timeout=timeout, accepted=accepted)
|
|
195
|
+
if isinstance(result, Response):
|
|
196
|
+
return result
|
|
197
|
+
|
|
198
|
+
media_type = JSON_MEDIA_TYPE
|
|
199
|
+
if isinstance(result, BinaryResult):
|
|
200
|
+
media_type = result.media_type
|
|
201
|
+
result = Response(content=result.data, media_type=media_type)
|
|
202
|
+
|
|
203
|
+
if media_type not in accepted:
|
|
204
|
+
raise _OutputNotAcceptableError(frozenset({media_type}), accepted)
|
|
205
|
+
return result
|
|
206
|
+
except _OutputNotAcceptableError as exc:
|
|
207
|
+
raise HTTPException(status_code=406, detail=str(exc)) from exc
|
|
208
|
+
except ServerClosedError as exc:
|
|
209
|
+
raise HTTPException(status_code=503, detail=str(exc)) from exc
|
|
210
|
+
except CommandNotFoundError as exc:
|
|
211
|
+
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
|
212
|
+
except CommandArgumentsError as exc:
|
|
213
|
+
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
|
214
|
+
except CommandExecutionError as exc:
|
|
215
|
+
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
|
216
|
+
except TimeoutError as exc:
|
|
217
|
+
raise HTTPException(status_code=504, detail=f"command {name!r} timed out") from exc
|
|
218
|
+
|
|
219
|
+
async def _dispatch(
|
|
220
|
+
self,
|
|
221
|
+
name: str,
|
|
222
|
+
arguments: Mapping[str, Any],
|
|
223
|
+
*,
|
|
224
|
+
timeout: float | None = None,
|
|
225
|
+
accepted: frozenset[str] | None = None
|
|
226
|
+
) -> Any:
|
|
227
|
+
with self._state_lock:
|
|
228
|
+
if self._closed:
|
|
229
|
+
raise ServerClosedError("AgentizeServer 已经关闭")
|
|
230
|
+
|
|
231
|
+
command = self._commands.get(name)
|
|
232
|
+
if command is None:
|
|
233
|
+
raise CommandNotFoundError(f"找不到命令 {name}")
|
|
234
|
+
|
|
235
|
+
available = DECLARED_MEDIA_TYPES.get(command.output_kind)
|
|
236
|
+
if accepted is not None and available is not None and available.isdisjoint(accepted):
|
|
237
|
+
raise _OutputNotAcceptableError(available, accepted)
|
|
238
|
+
|
|
239
|
+
args = dict(arguments or {})
|
|
240
|
+
if command.thread == "worker":
|
|
241
|
+
future = self._workers.submit(self._executor.execute, command, args)
|
|
242
|
+
else:
|
|
243
|
+
future = self._queue.submit(name, args)
|
|
244
|
+
|
|
245
|
+
effective_timeout = timeout if timeout is not None else command.timeout
|
|
246
|
+
|
|
247
|
+
try:
|
|
248
|
+
return await asyncio.wait_for(asyncio.wrap_future(future), timeout=effective_timeout)
|
|
249
|
+
except TimeoutError:
|
|
250
|
+
future.cancel()
|
|
251
|
+
raise
|
|
252
|
+
except CancelledError as exc:
|
|
253
|
+
raise ServerClosedError("AgentizeServer 已关闭") from exc
|
|
254
|
+
|
|
255
|
+
def _install_token_auth(self, credential, ttl) -> None:
|
|
256
|
+
expected = credential.token.encode("ascii")
|
|
257
|
+
expires_at = credential.issued_at + ttl if ttl is not None else None
|
|
258
|
+
|
|
259
|
+
@self.fastapi_app.middleware("http")
|
|
260
|
+
async def require_token(request: Request, call_next):
|
|
261
|
+
detail = "缺少有效的访问令牌"
|
|
262
|
+
values = request.headers.getlist("authorization")
|
|
263
|
+
|
|
264
|
+
if len(values) == 1:
|
|
265
|
+
scheme, sep, supplied = values[0].partition(" ")
|
|
266
|
+
if sep and scheme.lower() == "bearer" and compare_digest(
|
|
267
|
+
supplied.encode("utf-8"), expected
|
|
268
|
+
):
|
|
269
|
+
if expires_at is None or datetime.now(UTC) < expires_at:
|
|
270
|
+
return await call_next(request)
|
|
271
|
+
detail = "访问令牌已过期"
|
|
272
|
+
|
|
273
|
+
record_access_detail(request.scope, detail)
|
|
274
|
+
return JSONResponse(
|
|
275
|
+
{"detail": detail},
|
|
276
|
+
status_code=401,
|
|
277
|
+
headers={"WWW-Authenticate": "Bearer"},
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
def _install_local_guard(self, host: str, port: int) -> None:
|
|
281
|
+
allowed_hosts = {"127.0.0.1", "localhost", host}
|
|
282
|
+
allowed_origins = {f"http://{h}:{port}" for h in allowed_hosts}
|
|
283
|
+
|
|
284
|
+
self.fastapi_app.add_middleware(TrustedHostMiddleware, allowed_hosts=sorted(allowed_hosts))
|
|
285
|
+
|
|
286
|
+
@self.fastapi_app.middleware("http")
|
|
287
|
+
async def reject_foreign_origin(request, call_next):
|
|
288
|
+
origin = request.headers.get("origin")
|
|
289
|
+
if origin is not None and origin not in allowed_origins:
|
|
290
|
+
return JSONResponse({"detail": "Origin 不被允许"}, status_code=403)
|
|
291
|
+
return await call_next(request)
|
|
292
|
+
|
|
293
|
+
def __enter__(self):
|
|
294
|
+
return self
|
|
295
|
+
|
|
296
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
297
|
+
self.close()
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import stat
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from datetime import UTC, datetime, timedelta
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from secrets import token_urlsafe
|
|
8
|
+
from tempfile import NamedTemporaryFile
|
|
9
|
+
from typing import Literal
|
|
10
|
+
|
|
11
|
+
AuthSetting = bool | timedelta | Literal["never"]
|
|
12
|
+
|
|
13
|
+
DEFAULT_TOKEN_FILE = Path("bridge-token.json")
|
|
14
|
+
DEFAULT_TOKEN_TTL = timedelta(days=30)
|
|
15
|
+
_MIN_TOKEN_LENGTH = 16
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True, slots=True)
|
|
19
|
+
class Credential:
|
|
20
|
+
token: str
|
|
21
|
+
issued_at: datetime
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _is_valid_token(value: object) -> bool:
|
|
25
|
+
return (
|
|
26
|
+
isinstance(value, str)
|
|
27
|
+
and len(value) >= _MIN_TOKEN_LENGTH
|
|
28
|
+
and value.isascii()
|
|
29
|
+
and all(ch.isprintable() and not ch.isspace() for ch in value)
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def parse_auth_setting(auth: AuthSetting) -> tuple[bool, timedelta | None]:
|
|
34
|
+
"""解析 auth 配置,返回 (是否启用, 有效期);有效期为 None 表示无限期。"""
|
|
35
|
+
if isinstance(auth, bool):
|
|
36
|
+
return auth, (DEFAULT_TOKEN_TTL if auth else None)
|
|
37
|
+
if auth == "never":
|
|
38
|
+
return True, None
|
|
39
|
+
if isinstance(auth, timedelta):
|
|
40
|
+
if auth <= timedelta(0):
|
|
41
|
+
raise ValueError("auth 有效期必须大于 0")
|
|
42
|
+
return True, auth
|
|
43
|
+
raise ValueError("auth 必须是 bool、'never' 或大于 0 的 timedelta")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _read_credential(path: Path) -> Credential:
|
|
47
|
+
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
|
|
48
|
+
with os.fdopen(os.open(path, flags), encoding="utf-8") as file:
|
|
49
|
+
info = os.fstat(file.fileno())
|
|
50
|
+
if not stat.S_ISREG(info.st_mode):
|
|
51
|
+
raise ValueError("令牌文件必须是普通文件")
|
|
52
|
+
if os.name == "posix" and (info.st_uid != os.geteuid() or info.st_mode & 0o077):
|
|
53
|
+
raise PermissionError("令牌文件必须由当前账户持有,且禁止其他账户访问")
|
|
54
|
+
|
|
55
|
+
try:
|
|
56
|
+
data = json.load(file)
|
|
57
|
+
token = data["token"]
|
|
58
|
+
issued_at = datetime.fromisoformat(data["issued_at"])
|
|
59
|
+
if _is_valid_token(token) and issued_at.utcoffset() is not None:
|
|
60
|
+
return Credential(token, issued_at.astimezone(UTC))
|
|
61
|
+
except (KeyError, TypeError, ValueError, OverflowError):
|
|
62
|
+
pass
|
|
63
|
+
|
|
64
|
+
raise ValueError("令牌文件格式无效")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _write_credential(path: Path, credential: Credential, *, replace: bool) -> None:
|
|
68
|
+
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
69
|
+
temporary: Path | None = None
|
|
70
|
+
try:
|
|
71
|
+
with NamedTemporaryFile(
|
|
72
|
+
mode="w",
|
|
73
|
+
encoding="utf-8",
|
|
74
|
+
dir=path.parent,
|
|
75
|
+
prefix=".agentize-token-",
|
|
76
|
+
delete=False,
|
|
77
|
+
) as file:
|
|
78
|
+
temporary = Path(file.name)
|
|
79
|
+
json.dump(
|
|
80
|
+
{"token": credential.token, "issued_at": credential.issued_at.isoformat()},
|
|
81
|
+
file,
|
|
82
|
+
indent=2,
|
|
83
|
+
)
|
|
84
|
+
file.write("\n")
|
|
85
|
+
file.flush()
|
|
86
|
+
os.fsync(file.fileno())
|
|
87
|
+
|
|
88
|
+
if replace:
|
|
89
|
+
temporary.replace(path)
|
|
90
|
+
temporary = None
|
|
91
|
+
else:
|
|
92
|
+
try:
|
|
93
|
+
if os.name == "nt":
|
|
94
|
+
temporary.rename(path)
|
|
95
|
+
temporary = None
|
|
96
|
+
else:
|
|
97
|
+
os.link(temporary, path)
|
|
98
|
+
except FileExistsError:
|
|
99
|
+
pass
|
|
100
|
+
finally:
|
|
101
|
+
if temporary is not None:
|
|
102
|
+
temporary.unlink(missing_ok=True)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def load_or_create_credential(path: Path, ttl: timedelta | None) -> Credential:
|
|
106
|
+
"""读取现有凭据;不存在或按当前 ttl 已过期时自动生成;损坏或权限不符时报错保留现场。"""
|
|
107
|
+
now = datetime.now(UTC)
|
|
108
|
+
try:
|
|
109
|
+
existing = _read_credential(path)
|
|
110
|
+
except FileNotFoundError:
|
|
111
|
+
fresh = Credential(token_urlsafe(32), now)
|
|
112
|
+
_write_credential(path, fresh, replace=False)
|
|
113
|
+
return _read_credential(path)
|
|
114
|
+
|
|
115
|
+
if ttl is None or now < existing.issued_at + ttl:
|
|
116
|
+
return existing
|
|
117
|
+
|
|
118
|
+
rotated = Credential(token_urlsafe(32), now)
|
|
119
|
+
_write_credential(path, rotated, replace=True)
|
|
120
|
+
return rotated
|