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,188 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
from http.client import HTTPException, HTTPResponse
|
|
4
|
+
from os import PathLike
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from urllib.error import HTTPError, URLError
|
|
7
|
+
from urllib.request import Request, urlopen
|
|
8
|
+
from urllib.parse import quote
|
|
9
|
+
|
|
10
|
+
_MARGIN_SECONDS = 5.0
|
|
11
|
+
_MAX_BINARY_BYTES = 16 * 1024 * 1024
|
|
12
|
+
IMAGE_MEDIA_TYPES = frozenset({"image/png", "image/jpeg"})
|
|
13
|
+
BINARY_MEDIA_TYPES = IMAGE_MEDIA_TYPES | {"application/octet-stream"}
|
|
14
|
+
DEFAULT_BRIDGE_URL = "http://127.0.0.1:8765"
|
|
15
|
+
BRIDGE_URL_ENV = "AGENTIZE_BRIDGE_URL"
|
|
16
|
+
TOKEN_ENV = "AGENTIZE_BRIDGE_TOKEN"
|
|
17
|
+
TOKEN_FILE_ENV = "AGENTIZE_BRIDGE_TOKEN_FILE"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _is_valid_token(value: object) -> bool:
|
|
21
|
+
return (
|
|
22
|
+
isinstance(value, str)
|
|
23
|
+
and bool(value)
|
|
24
|
+
and value.isascii()
|
|
25
|
+
and all(ch.isprintable() and not ch.isspace() for ch in value)
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def resolve_auth_from_env(base_url: str) -> dict[str, str | Path]:
|
|
30
|
+
"""读取为当前目标配置的凭据,令牌字符串优先于令牌文件。"""
|
|
31
|
+
configured_url = os.environ.get(BRIDGE_URL_ENV, DEFAULT_BRIDGE_URL)
|
|
32
|
+
if base_url.rstrip("/") != configured_url.rstrip("/"):
|
|
33
|
+
return {}
|
|
34
|
+
if token := os.environ.get(TOKEN_ENV):
|
|
35
|
+
return {"token": token}
|
|
36
|
+
if token_file := os.environ.get(TOKEN_FILE_ENV):
|
|
37
|
+
return {"token_file": Path(token_file).expanduser()}
|
|
38
|
+
return {}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _read_token_file(path: Path) -> str:
|
|
42
|
+
try:
|
|
43
|
+
token = json.loads(path.read_text(encoding="utf-8"))["token"]
|
|
44
|
+
if _is_valid_token(token):
|
|
45
|
+
return token
|
|
46
|
+
except (OSError, KeyError, TypeError, ValueError):
|
|
47
|
+
pass
|
|
48
|
+
raise HttpClientError(f"无法读取有效的令牌文件 {path}")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class HttpClientError(Exception):
|
|
52
|
+
def __init__(
|
|
53
|
+
self,
|
|
54
|
+
message: str,
|
|
55
|
+
*,
|
|
56
|
+
status_code: int | None = None,
|
|
57
|
+
detail: str | list | None = None,
|
|
58
|
+
kind: str = "request",
|
|
59
|
+
):
|
|
60
|
+
super().__init__(message)
|
|
61
|
+
self.status_code = status_code
|
|
62
|
+
self.detail = detail
|
|
63
|
+
self.kind = kind
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _error_detail(body: str) -> str | list | None:
|
|
67
|
+
try:
|
|
68
|
+
payload = json.loads(body)
|
|
69
|
+
except ValueError:
|
|
70
|
+
text = " ".join(body.split())
|
|
71
|
+
return text if text and not text.startswith("<") else None
|
|
72
|
+
|
|
73
|
+
detail = payload.get("detail") if isinstance(payload, dict) else None
|
|
74
|
+
return detail if isinstance(detail, (str, list)) else None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _read_binary_response(response: HTTPResponse) -> bytes:
|
|
78
|
+
content_length = response.headers.get("Content-Length")
|
|
79
|
+
try:
|
|
80
|
+
expected_length = int(content_length) if content_length is not None else None
|
|
81
|
+
except ValueError as exc:
|
|
82
|
+
raise HttpClientError("无效的二进制响应长度", kind="response") from exc
|
|
83
|
+
if expected_length is not None and expected_length < 0:
|
|
84
|
+
raise HttpClientError("无效的二进制响应长度", kind="response")
|
|
85
|
+
if expected_length is not None and expected_length > _MAX_BINARY_BYTES:
|
|
86
|
+
raise HttpClientError("二进制响应超过 16 MiB 读取上限", kind="response")
|
|
87
|
+
|
|
88
|
+
data = response.read(_MAX_BINARY_BYTES + 1)
|
|
89
|
+
if len(data) > _MAX_BINARY_BYTES:
|
|
90
|
+
raise HttpClientError("二进制响应超过 16 MiB 读取上限", kind="response")
|
|
91
|
+
if expected_length is not None and len(data) != expected_length:
|
|
92
|
+
raise HttpClientError("二进制响应长度不完整", kind="response")
|
|
93
|
+
return data
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class HttpClient:
|
|
97
|
+
def __init__(
|
|
98
|
+
self,
|
|
99
|
+
base_url: str,
|
|
100
|
+
timeout: float = 30,
|
|
101
|
+
margin: float = _MARGIN_SECONDS,
|
|
102
|
+
*,
|
|
103
|
+
token: str | None = None,
|
|
104
|
+
token_file: str | PathLike[str] | None = None,
|
|
105
|
+
):
|
|
106
|
+
if token is not None and token_file is not None:
|
|
107
|
+
raise ValueError("token 和 token_file 不能同时指定")
|
|
108
|
+
if token is not None and not _is_valid_token(token):
|
|
109
|
+
raise ValueError("token 必须是非空、无空白字符的可见 ASCII 字符串")
|
|
110
|
+
self.base_url = base_url.rstrip("/")
|
|
111
|
+
self.timeout = timeout
|
|
112
|
+
self.margin = margin
|
|
113
|
+
self._token = token
|
|
114
|
+
self._token_file = Path(token_file).expanduser() if token_file is not None else None
|
|
115
|
+
|
|
116
|
+
def request(
|
|
117
|
+
self,
|
|
118
|
+
method: str,
|
|
119
|
+
path: str,
|
|
120
|
+
body: dict | None = None,
|
|
121
|
+
timeout: float | None = None,
|
|
122
|
+
*,
|
|
123
|
+
allow_binary: bool = False,
|
|
124
|
+
accept: str | None = None
|
|
125
|
+
):
|
|
126
|
+
url = f"{self.base_url}/{path.lstrip('/')}"
|
|
127
|
+
data = json.dumps(body).encode("utf-8") if body is not None else None
|
|
128
|
+
socket_timeout = self.timeout if timeout is None else timeout
|
|
129
|
+
headers = {"Content-Type": "application/json"}
|
|
130
|
+
if accept is not None:
|
|
131
|
+
headers["Accept"] = accept
|
|
132
|
+
bearer = self._token
|
|
133
|
+
if bearer is None and self._token_file is not None:
|
|
134
|
+
bearer = _read_token_file(self._token_file)
|
|
135
|
+
|
|
136
|
+
try:
|
|
137
|
+
request = Request(
|
|
138
|
+
url,
|
|
139
|
+
data=data,
|
|
140
|
+
headers=headers,
|
|
141
|
+
method=method
|
|
142
|
+
)
|
|
143
|
+
if bearer is not None:
|
|
144
|
+
request.add_unredirected_header("Authorization", f"Bearer {bearer}")
|
|
145
|
+
with urlopen(request, timeout=socket_timeout) as response:
|
|
146
|
+
if allow_binary:
|
|
147
|
+
media_type = response.headers.get_content_type()
|
|
148
|
+
if media_type in BINARY_MEDIA_TYPES:
|
|
149
|
+
return _read_binary_response(response), media_type
|
|
150
|
+
content = response.read()
|
|
151
|
+
except HTTPError as exc:
|
|
152
|
+
with exc:
|
|
153
|
+
try:
|
|
154
|
+
body = exc.read().decode("utf-8", errors="replace")
|
|
155
|
+
except (OSError, HTTPException):
|
|
156
|
+
body = ""
|
|
157
|
+
raise HttpClientError(
|
|
158
|
+
f"HTTP {exc.code}: {body or exc.reason}",
|
|
159
|
+
status_code=exc.code,
|
|
160
|
+
detail=_error_detail(body)
|
|
161
|
+
) from exc
|
|
162
|
+
except OverflowError as exc:
|
|
163
|
+
raise HttpClientError("超时值超出客户端可用范围") from exc
|
|
164
|
+
except URLError as exc:
|
|
165
|
+
raise HttpClientError(f"HTTP 请求失败: {exc.reason}", kind="connection") from exc
|
|
166
|
+
except (OSError, HTTPException) as exc:
|
|
167
|
+
raise HttpClientError(f"HTTP 请求失败: {exc}", kind="connection") from exc
|
|
168
|
+
except ValueError as exc:
|
|
169
|
+
raise HttpClientError(f"HTTP 请求失败: {exc}") from exc
|
|
170
|
+
|
|
171
|
+
if not content:
|
|
172
|
+
return None
|
|
173
|
+
|
|
174
|
+
try:
|
|
175
|
+
return json.loads(content)
|
|
176
|
+
except ValueError as exc:
|
|
177
|
+
raise HttpClientError("无效的 JSON 响应", kind="response") from exc
|
|
178
|
+
|
|
179
|
+
def get(self, path: str, timeout: float | None = None):
|
|
180
|
+
return self.request("GET", path, timeout=timeout)
|
|
181
|
+
|
|
182
|
+
def post(self, path: str, body: dict | None = None, timeout: float | None = None):
|
|
183
|
+
return self.request("POST", path, body, timeout=timeout)
|
|
184
|
+
|
|
185
|
+
def call_command(self, name: str, arguments: dict, timeout: float, *, accept: str | None = None):
|
|
186
|
+
"""返回解析后的 JSON 值,或二进制响应的 (bytes, media_type) 元组。"""
|
|
187
|
+
path = f"/command/{quote(name, safe='')}?timeout={timeout}"
|
|
188
|
+
return self.request("POST", path, arguments, timeout=timeout + self.margin, allow_binary=True, accept=accept)
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import asyncio
|
|
3
|
+
import base64
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from mcp.server import Server, ServerRequestContext
|
|
10
|
+
from mcp.server.stdio import stdio_server
|
|
11
|
+
from mcp.types import (
|
|
12
|
+
CallToolRequestParams,
|
|
13
|
+
CallToolResult,
|
|
14
|
+
ImageContent,
|
|
15
|
+
ListToolsResult,
|
|
16
|
+
PaginatedRequestParams,
|
|
17
|
+
TextContent,
|
|
18
|
+
Tool
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
from .. import __version__
|
|
22
|
+
from .http_client import (
|
|
23
|
+
BRIDGE_URL_ENV,
|
|
24
|
+
DEFAULT_BRIDGE_URL,
|
|
25
|
+
IMAGE_MEDIA_TYPES,
|
|
26
|
+
HttpClient,
|
|
27
|
+
HttpClientError,
|
|
28
|
+
resolve_auth_from_env,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
_MAX_IMAGE_BASE64_BYTES = 1024 * 1024
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _tool_error(message: str) -> CallToolResult:
|
|
35
|
+
return CallToolResult(content=[TextContent(type="text", text=message)], is_error=True)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _create_server(client: HttpClient, commands: list[dict[str, Any]], timeout: float) -> Server:
|
|
39
|
+
"""用 /commands 返回的元数据构建 MCP Server。
|
|
40
|
+
|
|
41
|
+
input_schema 原样透传;参数校验只由 HTTP 服务端负责。
|
|
42
|
+
"""
|
|
43
|
+
tools = {
|
|
44
|
+
command["name"]: Tool(
|
|
45
|
+
name=command["name"],
|
|
46
|
+
description=command.get("description", ""),
|
|
47
|
+
input_schema=command.get("input_schema", {"type": "object", "properties": {}}),
|
|
48
|
+
)
|
|
49
|
+
for command in commands
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async def list_tools(ctx: ServerRequestContext, params: PaginatedRequestParams | None) -> ListToolsResult:
|
|
53
|
+
return ListToolsResult(tools=list(tools.values()))
|
|
54
|
+
|
|
55
|
+
async def call_tool(ctx: ServerRequestContext, params: CallToolRequestParams) -> CallToolResult:
|
|
56
|
+
if params.name not in tools:
|
|
57
|
+
raise ValueError(f"未知的工具: {params.name}")
|
|
58
|
+
try:
|
|
59
|
+
result = await asyncio.to_thread(client.call_command, params.name, params.arguments or {}, timeout)
|
|
60
|
+
except HttpClientError as exc:
|
|
61
|
+
# 低层 Server 会把 handler 里抛出的异常变成通用的协议错误,模型读不到原因;
|
|
62
|
+
# 这里改为返回 is_error 结果,让模型看到服务端的校验信息并自行重试。
|
|
63
|
+
return _tool_error(str(exc))
|
|
64
|
+
|
|
65
|
+
if not isinstance(result, tuple):
|
|
66
|
+
return CallToolResult(content=[TextContent(type="text", text=json.dumps(result, ensure_ascii=False))])
|
|
67
|
+
|
|
68
|
+
data, media_type = result
|
|
69
|
+
if media_type not in IMAGE_MEDIA_TYPES:
|
|
70
|
+
return _tool_error("此命令返回二进制文件,请使用 CLI 的 --output 保存")
|
|
71
|
+
if not data:
|
|
72
|
+
return _tool_error("命令返回了空图片")
|
|
73
|
+
|
|
74
|
+
encoded_size = 4 * ((len(data) + 2) // 3)
|
|
75
|
+
if encoded_size > _MAX_IMAGE_BASE64_BYTES:
|
|
76
|
+
return _tool_error("图片编码后超过 1 MiB,请请求更小的图片或使用 CLI 的 --output 保存")
|
|
77
|
+
|
|
78
|
+
return CallToolResult(content=[
|
|
79
|
+
ImageContent(
|
|
80
|
+
type="image",
|
|
81
|
+
data=base64.b64encode(data).decode("ascii"),
|
|
82
|
+
mime_type=media_type,
|
|
83
|
+
),
|
|
84
|
+
])
|
|
85
|
+
|
|
86
|
+
return Server("agentize-bridge-mcp", version=__version__, on_list_tools=list_tools, on_call_tool=call_tool)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
async def _serve(base_url: str, *, timeout: float = 30, token_file: Path | None = None) -> None:
|
|
90
|
+
auth = {"token_file": token_file} if token_file is not None else resolve_auth_from_env(base_url)
|
|
91
|
+
client = HttpClient(base_url, timeout=timeout, **auth)
|
|
92
|
+
commands = await asyncio.to_thread(client.get, "/commands")
|
|
93
|
+
server = _create_server(client, commands, timeout)
|
|
94
|
+
async with stdio_server() as (read_stream, write_stream):
|
|
95
|
+
await server.run(read_stream, write_stream, server.create_initialization_options())
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def main() -> None:
|
|
99
|
+
parser = argparse.ArgumentParser(prog="agentize-bridge-mcp")
|
|
100
|
+
parser.add_argument(
|
|
101
|
+
"--url",
|
|
102
|
+
default=os.environ.get(BRIDGE_URL_ENV, DEFAULT_BRIDGE_URL),
|
|
103
|
+
help="正在运行的 Agentize Bridge 服务器的基础 URL",
|
|
104
|
+
)
|
|
105
|
+
parser.add_argument(
|
|
106
|
+
"--token-file",
|
|
107
|
+
type=Path,
|
|
108
|
+
default=None,
|
|
109
|
+
help="从指定文件读取访问令牌,优先于环境变量",
|
|
110
|
+
)
|
|
111
|
+
parser.add_argument("--timeout", type=float, default=30, help="command timeout in seconds")
|
|
112
|
+
options = parser.parse_args()
|
|
113
|
+
serve_kwargs = {"token_file": options.token_file} if options.token_file is not None else {}
|
|
114
|
+
asyncio.run(_serve(options.url, timeout=options.timeout, **serve_kwargs))
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
if __name__ == "__main__":
|
|
118
|
+
main()
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
import math
|
|
3
|
+
from concurrent.futures import Future
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Annotated, Any, Callable, Literal, get_args, get_origin
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel
|
|
8
|
+
|
|
9
|
+
from .result import BinaryResult
|
|
10
|
+
from .schema import build_args_model_and_return_type, input_schema
|
|
11
|
+
|
|
12
|
+
ThreadMode = Literal["main", "worker"]
|
|
13
|
+
OutputKind = Literal["json", "binary", "unknown"]
|
|
14
|
+
|
|
15
|
+
DEFAULT_TIMEOUT: float = 30.0
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class Command:
|
|
20
|
+
name: str
|
|
21
|
+
fn: Callable[..., Any]
|
|
22
|
+
description: str
|
|
23
|
+
input_schema: dict[str, Any]
|
|
24
|
+
thread: ThreadMode # "main": 只能在主线程执行; "worker": 可以在工作线程上执行
|
|
25
|
+
timeout: float
|
|
26
|
+
args_model: type[BaseModel] # 同一个模型:既生成 schema,也用来校验参数
|
|
27
|
+
output_kind: OutputKind
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(slots=True)
|
|
31
|
+
class CommandRequest:
|
|
32
|
+
name: str
|
|
33
|
+
arguments: dict[str, Any]
|
|
34
|
+
future: Future[Any]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def create_command(
|
|
38
|
+
fn: Callable[..., Any],
|
|
39
|
+
*,
|
|
40
|
+
name: str = "",
|
|
41
|
+
description: str = "",
|
|
42
|
+
thread: ThreadMode = "worker",
|
|
43
|
+
timeout: float = DEFAULT_TIMEOUT
|
|
44
|
+
):
|
|
45
|
+
if thread not in ("main", "worker"):
|
|
46
|
+
raise ValueError("线程必须是 'main' 或 'worker' 其中之一")
|
|
47
|
+
if not isinstance(timeout, (int, float)) or not math.isfinite(timeout) or timeout <= 0:
|
|
48
|
+
raise ValueError("timeout 必须是大于 0 的有点数字")
|
|
49
|
+
if not callable(fn):
|
|
50
|
+
raise TypeError("命令必须是可调用的")
|
|
51
|
+
if inspect.iscoroutinefunction(fn) and thread == "main":
|
|
52
|
+
raise TypeError("异步命令不能使用 thread='main';请使用 thread='worker',以便协程可以在工作线程上运行")
|
|
53
|
+
|
|
54
|
+
args_model, return_type = build_args_model_and_return_type(fn)
|
|
55
|
+
|
|
56
|
+
doc = inspect.getdoc(fn) or ""
|
|
57
|
+
resolved_name = name or fn.__name__
|
|
58
|
+
if not resolved_name or not all(c.isascii() and (c.isalnum() or c in "_.-") for c in resolved_name):
|
|
59
|
+
raise ValueError(f"无效的命令名称: {resolved_name!r}")
|
|
60
|
+
return Command(
|
|
61
|
+
name=resolved_name,
|
|
62
|
+
fn=fn,
|
|
63
|
+
description=description or doc.splitlines()[0] if (description or doc) else resolved_name,
|
|
64
|
+
input_schema=input_schema(args_model),
|
|
65
|
+
thread=thread,
|
|
66
|
+
timeout=timeout,
|
|
67
|
+
args_model=args_model,
|
|
68
|
+
output_kind=_infer_output_kind(return_type)
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _infer_output_kind(annotation: Any) -> OutputKind:
|
|
73
|
+
while get_origin(annotation) is Annotated:
|
|
74
|
+
annotation = get_args(annotation)[0]
|
|
75
|
+
|
|
76
|
+
result_type = get_origin(annotation) or annotation
|
|
77
|
+
if isinstance(result_type, type):
|
|
78
|
+
if issubclass(result_type, BinaryResult):
|
|
79
|
+
return "binary"
|
|
80
|
+
if issubclass(result_type, (BaseModel, dict, list, tuple, str, int, float, type(None))):
|
|
81
|
+
return "json"
|
|
82
|
+
return "unknown"
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
from .command import Command, ThreadMode, DEFAULT_TIMEOUT, create_command
|
|
2
|
+
|
|
3
|
+
_pending: dict[str, Command] = {}
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def command(
|
|
7
|
+
name: str = "",
|
|
8
|
+
description: str = "",
|
|
9
|
+
thread: ThreadMode = "worker",
|
|
10
|
+
timeout: float = DEFAULT_TIMEOUT
|
|
11
|
+
):
|
|
12
|
+
def decorator(fn):
|
|
13
|
+
cmd = create_command(fn, name=name, description=description, thread=thread, timeout=timeout)
|
|
14
|
+
if cmd.name in _pending:
|
|
15
|
+
raise ValueError(f"命令 {cmd.name} 已经被注册")
|
|
16
|
+
_pending[cmd.name] = cmd
|
|
17
|
+
return fn
|
|
18
|
+
|
|
19
|
+
return decorator
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def snapshot() -> dict[str, Command]:
|
|
23
|
+
return dict(_pending)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def clear() -> None:
|
|
27
|
+
_pending.clear()
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
|
|
3
|
+
BINARY_MEDIA_TYPES = frozenset({"image/png", "image/jpeg", "application/octet-stream"})
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass(frozen=True)
|
|
7
|
+
class BinaryResult:
|
|
8
|
+
"""命令返回的原始文件字节及其媒体类型。"""
|
|
9
|
+
|
|
10
|
+
data: bytes
|
|
11
|
+
media_type: str = "application/octet-stream"
|
|
12
|
+
|
|
13
|
+
def __post_init__(self) -> None:
|
|
14
|
+
if not isinstance(self.data, bytes):
|
|
15
|
+
raise TypeError("BinaryResult.data 必须是 bytes")
|
|
16
|
+
if not isinstance(self.media_type, str) or self.media_type not in BINARY_MEDIA_TYPES:
|
|
17
|
+
raise ValueError(f"不支持的二进制媒体类型: {self.media_type}")
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
from typing import Callable, Any, get_type_hints
|
|
3
|
+
|
|
4
|
+
from pydantic import BaseModel, create_model, ConfigDict
|
|
5
|
+
|
|
6
|
+
_DATA_KEYS = ("default", "enum", "const", "examples")
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def build_args_model(fn: Callable[..., Any]) -> type[BaseModel]:
|
|
10
|
+
model, _ = build_args_model_and_return_type(fn)
|
|
11
|
+
return model
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def build_args_model_and_return_type(fn: Callable[..., Any]) -> tuple[type[BaseModel], Any]:
|
|
15
|
+
signature = inspect.signature(fn)
|
|
16
|
+
hints = get_type_hints(fn, include_extras=True)
|
|
17
|
+
|
|
18
|
+
fields: dict[str, Any] = {}
|
|
19
|
+
for param in signature.parameters.values():
|
|
20
|
+
if param.name == "self":
|
|
21
|
+
continue
|
|
22
|
+
|
|
23
|
+
if param.kind in (param.POSITIONAL_ONLY, param.VAR_POSITIONAL, param.VAR_KEYWORD):
|
|
24
|
+
raise TypeError(f"命令参数 {param.name!r} 必须是一个具名关键字参数; 仅位置参数和 *args/**kwargs 不被支持")
|
|
25
|
+
if param.name not in hints:
|
|
26
|
+
raise TypeError(f"参数 {param.name!r} 缺少类型注解(需要任意类型请显式标注 Any)")
|
|
27
|
+
fields[param.name] = (hints[param.name], ... if param.default is param.empty else param.default)
|
|
28
|
+
|
|
29
|
+
model = create_model("CommandArguments", __config__=ConfigDict(extra="forbid"), **fields)
|
|
30
|
+
return model, hints.get("return")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def input_schema(model: type[BaseModel]) -> dict[str, Any]:
|
|
34
|
+
schema = _clean(model.model_json_schema())
|
|
35
|
+
if not schema.get("required"):
|
|
36
|
+
schema.pop("required", None)
|
|
37
|
+
return schema
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _clean(node: Any) -> Any:
|
|
41
|
+
"""去掉 Pydantic 自动加的 title;不碰参数名,也不碰 default/enum 里的数据。"""
|
|
42
|
+
if isinstance(node, list):
|
|
43
|
+
return [_clean(item) for item in node]
|
|
44
|
+
if not isinstance(node, dict):
|
|
45
|
+
return node
|
|
46
|
+
out: dict[str, Any] = {}
|
|
47
|
+
for key, value in node.items():
|
|
48
|
+
if key == "title" and isinstance(value, str):
|
|
49
|
+
continue
|
|
50
|
+
if key in _DATA_KEYS:
|
|
51
|
+
out[key] = value
|
|
52
|
+
elif key == "properties" and isinstance(value, dict):
|
|
53
|
+
out[key] = {name: _clean(sub) for name, sub in value.items()}
|
|
54
|
+
else:
|
|
55
|
+
out[key] = _clean(value)
|
|
56
|
+
return out
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
from .container import Container
|
|
2
|
+
from .executor import CommandExecutor, CommandArgumentsError, CommandExecutionError, CommandNotFoundError
|
|
3
|
+
from .queues import CommandQueue
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"Container",
|
|
7
|
+
"CommandExecutor", "CommandArgumentsError", "CommandExecutionError", "CommandNotFoundError",
|
|
8
|
+
"CommandQueue"
|
|
9
|
+
]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import threading
|
|
2
|
+
from typing import Dict, Any
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class Container:
|
|
6
|
+
def __init__(self):
|
|
7
|
+
self._lock = threading.RLock()
|
|
8
|
+
self._instances: Dict[str, Any] = {}
|
|
9
|
+
|
|
10
|
+
def register(self, name: str, instance: Any) -> None:
|
|
11
|
+
with self._lock:
|
|
12
|
+
if name in self._instances:
|
|
13
|
+
raise ValueError(f"{name!r} 已经被注册")
|
|
14
|
+
self._instances[name] = instance
|
|
15
|
+
|
|
16
|
+
def unregister(self, name: str) -> None:
|
|
17
|
+
with self._lock:
|
|
18
|
+
self._instances.pop(name, None)
|
|
19
|
+
|
|
20
|
+
def resolve(self, name: str) -> Any:
|
|
21
|
+
with self._lock:
|
|
22
|
+
if name not in self._instances:
|
|
23
|
+
raise KeyError(f"{name!r} 不存在")
|
|
24
|
+
return self._instances[name]
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import inspect
|
|
3
|
+
from types import FunctionType
|
|
4
|
+
from typing import Any, Mapping, cast
|
|
5
|
+
|
|
6
|
+
from pydantic import ValidationError
|
|
7
|
+
|
|
8
|
+
from .container import Container
|
|
9
|
+
from .util import get_instance_class_name
|
|
10
|
+
from agentize_bridge.core import Command
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class CommandNotFoundError(LookupError):
|
|
14
|
+
pass
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class CommandArgumentsError(ValueError):
|
|
18
|
+
pass
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class CommandExecutionError(RuntimeError):
|
|
22
|
+
pass
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class CommandExecutor:
|
|
26
|
+
def __init__(self, container: Container):
|
|
27
|
+
self.container = container
|
|
28
|
+
|
|
29
|
+
def execute(self, command: Command, arguments: Mapping[str, Any]) -> Any:
|
|
30
|
+
if not isinstance(arguments, Mapping):
|
|
31
|
+
raise CommandArgumentsError("命令参数必须是一个 JSON 对象")
|
|
32
|
+
|
|
33
|
+
try:
|
|
34
|
+
validated = command.args_model.model_validate(dict(arguments))
|
|
35
|
+
except ValidationError as exc:
|
|
36
|
+
summary = "; ".join(f"{'.'.join(map(str, e['loc'])) or '<root>'}: {e['msg']}" for e in exc.errors())
|
|
37
|
+
raise CommandArgumentsError(f"参数无效: {summary}") from exc
|
|
38
|
+
# getattr 而不是 model_dump():保留嵌套模型 / dataclass 实例
|
|
39
|
+
kwargs = {name: getattr(validated, name) for name in type(validated).model_fields}
|
|
40
|
+
|
|
41
|
+
try:
|
|
42
|
+
fn = command.fn
|
|
43
|
+
|
|
44
|
+
class_name = get_instance_class_name(fn)
|
|
45
|
+
if class_name:
|
|
46
|
+
instance = self.container.resolve(class_name)
|
|
47
|
+
fn = cast(FunctionType, fn).__get__(instance)
|
|
48
|
+
|
|
49
|
+
result = fn(**kwargs)
|
|
50
|
+
if inspect.iscoroutine(result):
|
|
51
|
+
result = asyncio.run(result)
|
|
52
|
+
return result
|
|
53
|
+
except Exception as exc:
|
|
54
|
+
raise CommandExecutionError(f"命令 {command.name!r} 运行失败: {exc}") from exc
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
from concurrent.futures import Future
|
|
2
|
+
from queue import Queue, Full
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from fastapi import HTTPException
|
|
6
|
+
|
|
7
|
+
from agentize_bridge.core import CommandRequest
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class CommandQueue:
|
|
11
|
+
def __init__(self, maxsize: int = 64):
|
|
12
|
+
if maxsize <= 0 or maxsize > 64:
|
|
13
|
+
raise ValueError("maxsize 必须在 1 到 64 之间")
|
|
14
|
+
self._queue: Queue[CommandRequest] = Queue(maxsize=maxsize)
|
|
15
|
+
|
|
16
|
+
def submit(self, name: str, arguments: dict[str, Any]) -> Future:
|
|
17
|
+
future: Future[Any] = Future()
|
|
18
|
+
try:
|
|
19
|
+
self._queue.put_nowait(CommandRequest(name, arguments, future))
|
|
20
|
+
except Full as exc:
|
|
21
|
+
raise HTTPException(status_code=503, detail="命令队列已满") from exc
|
|
22
|
+
return future
|
|
23
|
+
|
|
24
|
+
def get_nowait(self) -> CommandRequest:
|
|
25
|
+
return self._queue.get_nowait()
|
|
26
|
+
|
|
27
|
+
def task_done(self) -> None:
|
|
28
|
+
self._queue.task_done()
|
|
29
|
+
|
|
30
|
+
def empty(self) -> bool:
|
|
31
|
+
return self._queue.empty()
|
|
32
|
+
|
|
33
|
+
def qsize(self) -> int:
|
|
34
|
+
return self._queue.qsize()
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
from typing import Callable, Optional
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def get_instance_class_name(fn: Callable) -> Optional[str]:
|
|
6
|
+
"""
|
|
7
|
+
如果是未绑定的实例方法(第一个参数为 self),返回其类名。
|
|
8
|
+
否则(普通函数、静态方法、类方法等)返回 None。
|
|
9
|
+
"""
|
|
10
|
+
qualname = getattr(fn, "__qualname__", "")
|
|
11
|
+
|
|
12
|
+
# 1. 必须有类名限定(排除模块级普通函数、嵌套函数)
|
|
13
|
+
if "." not in qualname or "<locals>" in qualname:
|
|
14
|
+
return None
|
|
15
|
+
|
|
16
|
+
# 2. 检查第一个参数是不是 self
|
|
17
|
+
try:
|
|
18
|
+
sig = inspect.signature(fn)
|
|
19
|
+
params = list(sig.parameters.values())
|
|
20
|
+
if params and params[0].name == "self":
|
|
21
|
+
# 提取类名:例如 "MyClass.do_work" -> "MyClass"
|
|
22
|
+
return qualname.split(".")[-2]
|
|
23
|
+
except (ValueError, TypeError):
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
return None
|