agentize-bridge 0.2.0__tar.gz
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-0.2.0/LICENSE +21 -0
- agentize_bridge-0.2.0/PKG-INFO +98 -0
- agentize_bridge-0.2.0/README.md +83 -0
- agentize_bridge-0.2.0/pyproject.toml +41 -0
- agentize_bridge-0.2.0/setup.cfg +4 -0
- agentize_bridge-0.2.0/src/agentize_bridge/__init__.py +5 -0
- agentize_bridge-0.2.0/src/agentize_bridge/__version__.py +6 -0
- agentize_bridge-0.2.0/src/agentize_bridge/adapters/cli/__init__.py +3 -0
- agentize_bridge-0.2.0/src/agentize_bridge/adapters/cli/app.py +24 -0
- agentize_bridge-0.2.0/src/agentize_bridge/adapters/cli/commands.py +334 -0
- agentize_bridge-0.2.0/src/agentize_bridge/adapters/cli/output.py +94 -0
- agentize_bridge-0.2.0/src/agentize_bridge/adapters/cli/parser.py +190 -0
- agentize_bridge-0.2.0/src/agentize_bridge/adapters/http_client.py +188 -0
- agentize_bridge-0.2.0/src/agentize_bridge/adapters/mcp_server.py +118 -0
- agentize_bridge-0.2.0/src/agentize_bridge/core/__init__.py +9 -0
- agentize_bridge-0.2.0/src/agentize_bridge/core/command.py +82 -0
- agentize_bridge-0.2.0/src/agentize_bridge/core/registry.py +27 -0
- agentize_bridge-0.2.0/src/agentize_bridge/core/result.py +17 -0
- agentize_bridge-0.2.0/src/agentize_bridge/core/schema.py +56 -0
- agentize_bridge-0.2.0/src/agentize_bridge/runtime/__init__.py +9 -0
- agentize_bridge-0.2.0/src/agentize_bridge/runtime/container.py +24 -0
- agentize_bridge-0.2.0/src/agentize_bridge/runtime/executor.py +54 -0
- agentize_bridge-0.2.0/src/agentize_bridge/runtime/queues.py +34 -0
- agentize_bridge-0.2.0/src/agentize_bridge/runtime/util.py +26 -0
- agentize_bridge-0.2.0/src/agentize_bridge/server/__init__.py +3 -0
- agentize_bridge-0.2.0/src/agentize_bridge/server/accept.py +38 -0
- agentize_bridge-0.2.0/src/agentize_bridge/server/access_log.py +190 -0
- agentize_bridge-0.2.0/src/agentize_bridge/server/bridge.py +297 -0
- agentize_bridge-0.2.0/src/agentize_bridge/server/credentials.py +120 -0
- agentize_bridge-0.2.0/src/agentize_bridge.egg-info/PKG-INFO +98 -0
- agentize_bridge-0.2.0/src/agentize_bridge.egg-info/SOURCES.txt +34 -0
- agentize_bridge-0.2.0/src/agentize_bridge.egg-info/dependency_links.txt +1 -0
- agentize_bridge-0.2.0/src/agentize_bridge.egg-info/entry_points.txt +4 -0
- agentize_bridge-0.2.0/src/agentize_bridge.egg-info/requires.txt +4 -0
- agentize_bridge-0.2.0/src/agentize_bridge.egg-info/top_level.txt +1 -0
- agentize_bridge-0.2.0/tests/test_integration.py +400 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ewoaoo
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agentize-bridge
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: 一个轻量级框架,用于通过 HTTP、CLI 和 MCP 暴露现有的 Python 应用程序命令。
|
|
5
|
+
Author: ewoaoo
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Requires-Python: >=3.11
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Dist: fastapi>=0.162.0
|
|
11
|
+
Requires-Dist: mcp>=2.3.0
|
|
12
|
+
Requires-Dist: pydantic>=2.7.4
|
|
13
|
+
Requires-Dist: uvicorn>=0.54.0
|
|
14
|
+
Dynamic: license-file
|
|
15
|
+
|
|
16
|
+
<div align="center">
|
|
17
|
+
|
|
18
|
+
# agentize-bridge
|
|
19
|
+
|
|
20
|
+
**让运行中的 Python 应用,成为 AI 代理可以调用的工具。**
|
|
21
|
+
|
|
22
|
+
一个装饰器注册命令,同时获得 HTTP、CLI、MCP 三个入口,并支持在宿主程序的主线程中执行命令。
|
|
23
|
+
|
|
24
|
+
[](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/getting-started.md#安装)
|
|
25
|
+
[](https://github.com/ewoaoo/agentize-bridge/blob/main/LICENSE)
|
|
26
|
+
|
|
27
|
+
[**文档**](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/README.md) · [快速开始](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/getting-started.md) · [MCP 接入](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/mcp.md) · [安全](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/security.md)
|
|
28
|
+
|
|
29
|
+
</div>
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
桌面 GUI、DCC 软件等程序的状态只能在主线程中读写,无法直接接入 Web 框架,AI 代理因而无法调用它们。
|
|
34
|
+
使用 `agentize-bridge` 时,只需注册命令,参数校验、线程调度与对外暴露由框架负责。
|
|
35
|
+
|
|
36
|
+
命令也可以用 `BinaryResult` 返回文件或程序生成的二进制数据。HTTP 和 CLI 可以保存原始字节,MCP 也可将 PNG 和 JPEG 作为图像工具结果返回。 [返回二进制数据](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/commands.md#返回二进制数据)
|
|
37
|
+
|
|
38
|
+
CLI 和 MCP 都通过 HTTP 调用宿主程序里注册的命令。宿主程序可以在线程池中执行命令,也可以在主循环中调用 `run_pending()`,在主线程执行队列里的命令。 [架构图](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/README.md#它是怎么工作的)
|
|
39
|
+
|
|
40
|
+
## 快速开始
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
git clone https://github.com/ewoaoo/agentize-bridge.git
|
|
44
|
+
cd agentize-bridge
|
|
45
|
+
uv sync # 或:pip install -e .
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
import time
|
|
50
|
+
|
|
51
|
+
from agentize_bridge import AgentizeServer, command
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@command()
|
|
55
|
+
def add(a: int, b: int = 2) -> int:
|
|
56
|
+
"""把两个数字相加。"""
|
|
57
|
+
return a + b
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
if __name__ == "__main__":
|
|
61
|
+
server = AgentizeServer("My App")
|
|
62
|
+
server.start_http(host="127.0.0.1", port=8765)
|
|
63
|
+
try:
|
|
64
|
+
while True:
|
|
65
|
+
server.run_pending() # 在主线程中执行 thread="main" 的命令
|
|
66
|
+
time.sleep(0.01)
|
|
67
|
+
except KeyboardInterrupt:
|
|
68
|
+
server.close()
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
curl -X POST http://127.0.0.1:8765/command/add \
|
|
73
|
+
-H 'Content-Type: application/json' -d '{"a": 2, "b": 3}' # 5
|
|
74
|
+
|
|
75
|
+
azb call add -a '{"a": 2, "b": 3}' # 5
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
控制台默认只显示失败请求的访问记录。设置 `AgentizeServer("My App", log_mode="full")` 可查看成功请求。文件输出配置见[访问日志](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/getting-started.md#访问日志)。
|
|
79
|
+
|
|
80
|
+
## 文档
|
|
81
|
+
|
|
82
|
+
[**完整文档 →**](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/README.md) 位于仓库的 `docs/` 目录,下面是常用入口:
|
|
83
|
+
|
|
84
|
+
| | 说明 |
|
|
85
|
+
| --- | --- |
|
|
86
|
+
| [定义命令](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/commands.md) | 参数、类型校验与二进制返回值 |
|
|
87
|
+
| [线程模型](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/threading.md) | `worker` 与 `main`,接入主循环 |
|
|
88
|
+
| [实例方法](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/instance-methods.md) | 暴露已有对象的方法 |
|
|
89
|
+
| [HTTP API](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/http-api.md) · [CLI](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/cli.md) · [MCP](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/mcp.md) | 三种调用方式 |
|
|
90
|
+
| [安全与限制](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/security.md) | 默认防护与已知缺口 |
|
|
91
|
+
| [开发](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/development.md) | 测试、构建与代码结构 |
|
|
92
|
+
|
|
93
|
+
> [!WARNING]
|
|
94
|
+
> **身份验证默认关闭。** 此时,任何能访问端口的人都能调用已注册的命令。本机使用建议保持默认的 `127.0.0.1`。跨机使用时,请开启鉴权并通过 HTTPS 或加密隧道连接。 [安全与限制](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/security.md)
|
|
95
|
+
|
|
96
|
+
## License
|
|
97
|
+
|
|
98
|
+
[MIT](https://github.com/ewoaoo/agentize-bridge/blob/main/LICENSE)
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
<div align="center">
|
|
2
|
+
|
|
3
|
+
# agentize-bridge
|
|
4
|
+
|
|
5
|
+
**让运行中的 Python 应用,成为 AI 代理可以调用的工具。**
|
|
6
|
+
|
|
7
|
+
一个装饰器注册命令,同时获得 HTTP、CLI、MCP 三个入口,并支持在宿主程序的主线程中执行命令。
|
|
8
|
+
|
|
9
|
+
[](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/getting-started.md#安装)
|
|
10
|
+
[](https://github.com/ewoaoo/agentize-bridge/blob/main/LICENSE)
|
|
11
|
+
|
|
12
|
+
[**文档**](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/README.md) · [快速开始](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/getting-started.md) · [MCP 接入](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/mcp.md) · [安全](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/security.md)
|
|
13
|
+
|
|
14
|
+
</div>
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
桌面 GUI、DCC 软件等程序的状态只能在主线程中读写,无法直接接入 Web 框架,AI 代理因而无法调用它们。
|
|
19
|
+
使用 `agentize-bridge` 时,只需注册命令,参数校验、线程调度与对外暴露由框架负责。
|
|
20
|
+
|
|
21
|
+
命令也可以用 `BinaryResult` 返回文件或程序生成的二进制数据。HTTP 和 CLI 可以保存原始字节,MCP 也可将 PNG 和 JPEG 作为图像工具结果返回。 [返回二进制数据](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/commands.md#返回二进制数据)
|
|
22
|
+
|
|
23
|
+
CLI 和 MCP 都通过 HTTP 调用宿主程序里注册的命令。宿主程序可以在线程池中执行命令,也可以在主循环中调用 `run_pending()`,在主线程执行队列里的命令。 [架构图](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/README.md#它是怎么工作的)
|
|
24
|
+
|
|
25
|
+
## 快速开始
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
git clone https://github.com/ewoaoo/agentize-bridge.git
|
|
29
|
+
cd agentize-bridge
|
|
30
|
+
uv sync # 或:pip install -e .
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
import time
|
|
35
|
+
|
|
36
|
+
from agentize_bridge import AgentizeServer, command
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@command()
|
|
40
|
+
def add(a: int, b: int = 2) -> int:
|
|
41
|
+
"""把两个数字相加。"""
|
|
42
|
+
return a + b
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
if __name__ == "__main__":
|
|
46
|
+
server = AgentizeServer("My App")
|
|
47
|
+
server.start_http(host="127.0.0.1", port=8765)
|
|
48
|
+
try:
|
|
49
|
+
while True:
|
|
50
|
+
server.run_pending() # 在主线程中执行 thread="main" 的命令
|
|
51
|
+
time.sleep(0.01)
|
|
52
|
+
except KeyboardInterrupt:
|
|
53
|
+
server.close()
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
curl -X POST http://127.0.0.1:8765/command/add \
|
|
58
|
+
-H 'Content-Type: application/json' -d '{"a": 2, "b": 3}' # 5
|
|
59
|
+
|
|
60
|
+
azb call add -a '{"a": 2, "b": 3}' # 5
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
控制台默认只显示失败请求的访问记录。设置 `AgentizeServer("My App", log_mode="full")` 可查看成功请求。文件输出配置见[访问日志](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/getting-started.md#访问日志)。
|
|
64
|
+
|
|
65
|
+
## 文档
|
|
66
|
+
|
|
67
|
+
[**完整文档 →**](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/README.md) 位于仓库的 `docs/` 目录,下面是常用入口:
|
|
68
|
+
|
|
69
|
+
| | 说明 |
|
|
70
|
+
| --- | --- |
|
|
71
|
+
| [定义命令](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/commands.md) | 参数、类型校验与二进制返回值 |
|
|
72
|
+
| [线程模型](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/threading.md) | `worker` 与 `main`,接入主循环 |
|
|
73
|
+
| [实例方法](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/instance-methods.md) | 暴露已有对象的方法 |
|
|
74
|
+
| [HTTP API](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/http-api.md) · [CLI](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/cli.md) · [MCP](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/mcp.md) | 三种调用方式 |
|
|
75
|
+
| [安全与限制](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/security.md) | 默认防护与已知缺口 |
|
|
76
|
+
| [开发](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/development.md) | 测试、构建与代码结构 |
|
|
77
|
+
|
|
78
|
+
> [!WARNING]
|
|
79
|
+
> **身份验证默认关闭。** 此时,任何能访问端口的人都能调用已注册的命令。本机使用建议保持默认的 `127.0.0.1`。跨机使用时,请开启鉴权并通过 HTTPS 或加密隧道连接。 [安全与限制](https://github.com/ewoaoo/agentize-bridge/blob/main/docs/security.md)
|
|
80
|
+
|
|
81
|
+
## License
|
|
82
|
+
|
|
83
|
+
[MIT](https://github.com/ewoaoo/agentize-bridge/blob/main/LICENSE)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "agentize-bridge"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "一个轻量级框架,用于通过 HTTP、CLI 和 MCP 暴露现有的 Python 应用程序命令。"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
authors = [{ name = "ewoaoo" }]
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
requires-python = ">=3.11"
|
|
14
|
+
dependencies = [
|
|
15
|
+
"fastapi>=0.162.0",
|
|
16
|
+
"mcp>=2.3.0",
|
|
17
|
+
"pydantic>=2.7.4",
|
|
18
|
+
"uvicorn>=0.54.0",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.scripts]
|
|
22
|
+
agentize-bridge = "agentize_bridge.adapters.cli:main"
|
|
23
|
+
azb = "agentize_bridge.adapters.cli:main"
|
|
24
|
+
agentize-bridge-mcp = "agentize_bridge.adapters.mcp_server:main"
|
|
25
|
+
|
|
26
|
+
[dependency-groups]
|
|
27
|
+
dev = [
|
|
28
|
+
"build>=1.6.1",
|
|
29
|
+
]
|
|
30
|
+
test = [
|
|
31
|
+
"pytest>=9.1.1",
|
|
32
|
+
"pytest-cov>=7.1.0",
|
|
33
|
+
"jsonschema>=4.20.0"
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
[tool.uv]
|
|
37
|
+
default-groups = "all"
|
|
38
|
+
|
|
39
|
+
[tool.setuptools.packages.find]
|
|
40
|
+
where = ["src"]
|
|
41
|
+
include = ["agentize_bridge*"]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
from .commands import Executor
|
|
5
|
+
from .output import emit
|
|
6
|
+
from .parser import create_parser
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def run_cli(argv: list[str] | None = None, *, prog: str = "agentize-bridge") -> int:
|
|
10
|
+
parser = create_parser(prog)
|
|
11
|
+
argv = sys.argv[1:] if argv is None else argv
|
|
12
|
+
if not argv:
|
|
13
|
+
parser.print_help(file=sys.stdout)
|
|
14
|
+
parser.exit()
|
|
15
|
+
|
|
16
|
+
options = parser.parse_args(argv)
|
|
17
|
+
result = Executor(prog).execute(options, is_terminal=sys.stdout.isatty())
|
|
18
|
+
emit(result)
|
|
19
|
+
return result.exit_code
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def main() -> int:
|
|
23
|
+
prog = Path(sys.argv[0]).name.removesuffix(".exe")
|
|
24
|
+
return run_cli(prog=prog)
|
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import shlex
|
|
4
|
+
from argparse import Namespace
|
|
5
|
+
from contextlib import suppress
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from tempfile import NamedTemporaryFile
|
|
9
|
+
|
|
10
|
+
from ..http_client import (
|
|
11
|
+
BINARY_MEDIA_TYPES,
|
|
12
|
+
BRIDGE_URL_ENV,
|
|
13
|
+
DEFAULT_BRIDGE_URL,
|
|
14
|
+
TOKEN_ENV,
|
|
15
|
+
TOKEN_FILE_ENV,
|
|
16
|
+
HttpClient,
|
|
17
|
+
HttpClientError,
|
|
18
|
+
resolve_auth_from_env,
|
|
19
|
+
)
|
|
20
|
+
from .output import CommandDetails, ParameterDetails, Result
|
|
21
|
+
|
|
22
|
+
_BINARY_ACCEPT = ", ".join(sorted(BINARY_MEDIA_TYPES))
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class _Request:
|
|
27
|
+
action: str
|
|
28
|
+
url: str
|
|
29
|
+
url_source: str
|
|
30
|
+
explicit_url: str | None
|
|
31
|
+
token_file: Path | None
|
|
32
|
+
timeout: float
|
|
33
|
+
command: str | None
|
|
34
|
+
arguments: str
|
|
35
|
+
list_format: str
|
|
36
|
+
output_file: Path | None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Executor:
|
|
40
|
+
DEFAULT_URL = DEFAULT_BRIDGE_URL
|
|
41
|
+
URL_ENV = BRIDGE_URL_ENV
|
|
42
|
+
DEFAULT_TIMEOUT = 30
|
|
43
|
+
COMMAND_TIMEOUTS = {"status": 3}
|
|
44
|
+
DEFAULT_ARGUMENTS = "{}"
|
|
45
|
+
TERMINAL_LIST_FORMAT = "table"
|
|
46
|
+
PIPE_LIST_FORMAT = "json"
|
|
47
|
+
|
|
48
|
+
def __init__(self, prog: str):
|
|
49
|
+
self.prog = prog
|
|
50
|
+
|
|
51
|
+
@classmethod
|
|
52
|
+
def default_timeout(cls, action: str) -> int:
|
|
53
|
+
return cls.COMMAND_TIMEOUTS.get(action, cls.DEFAULT_TIMEOUT)
|
|
54
|
+
|
|
55
|
+
def execute(self, options: Namespace, *, is_terminal: bool) -> Result:
|
|
56
|
+
handlers = {
|
|
57
|
+
"status": self.execute_status,
|
|
58
|
+
"list": self.execute_list,
|
|
59
|
+
"describe": self.execute_describe,
|
|
60
|
+
"call": self.execute_call,
|
|
61
|
+
}
|
|
62
|
+
handler = handlers[options.action]
|
|
63
|
+
request = self._resolve(options, is_terminal=is_terminal)
|
|
64
|
+
try:
|
|
65
|
+
auth = (
|
|
66
|
+
{"token_file": request.token_file}
|
|
67
|
+
if request.token_file is not None
|
|
68
|
+
else resolve_auth_from_env(request.url)
|
|
69
|
+
)
|
|
70
|
+
client = HttpClient(request.url, timeout=request.timeout, **auth)
|
|
71
|
+
return handler(request, client)
|
|
72
|
+
except HttpClientError as exc:
|
|
73
|
+
return self._http_failure(request, exc)
|
|
74
|
+
except ValueError as exc:
|
|
75
|
+
return Result("text", str(exc), exit_code=1)
|
|
76
|
+
|
|
77
|
+
def _resolve(self, options: Namespace, *, is_terminal: bool) -> _Request:
|
|
78
|
+
explicit_url = getattr(options, "url", None)
|
|
79
|
+
if explicit_url is not None:
|
|
80
|
+
url, source = explicit_url, "--url"
|
|
81
|
+
elif (env_url := os.getenv(self.URL_ENV)) is not None:
|
|
82
|
+
url, source = env_url, self.URL_ENV
|
|
83
|
+
else:
|
|
84
|
+
url, source = self.DEFAULT_URL, "默认地址"
|
|
85
|
+
|
|
86
|
+
default_timeout = self.default_timeout(options.action)
|
|
87
|
+
default_format = self.TERMINAL_LIST_FORMAT if is_terminal else self.PIPE_LIST_FORMAT
|
|
88
|
+
return _Request(
|
|
89
|
+
action=options.action,
|
|
90
|
+
url=url,
|
|
91
|
+
url_source=source,
|
|
92
|
+
explicit_url=explicit_url,
|
|
93
|
+
token_file=getattr(options, "token_file", None),
|
|
94
|
+
timeout=getattr(options, "timeout", default_timeout),
|
|
95
|
+
command=getattr(options, "command", None),
|
|
96
|
+
arguments=getattr(options, "args", self.DEFAULT_ARGUMENTS),
|
|
97
|
+
list_format=getattr(options, "output", default_format),
|
|
98
|
+
output_file=getattr(options, "output_file", None),
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
def execute_status(self, request: _Request, client: HttpClient) -> Result:
|
|
102
|
+
health = client.get("/health")
|
|
103
|
+
if not isinstance(health, dict) or health.get("status") != "ok":
|
|
104
|
+
message = f"{client.base_url} 的 /health 响应不符合 Bridge 约定"
|
|
105
|
+
return Result("text", message, exit_code=1)
|
|
106
|
+
return Result("text", f"连接正常 {client.base_url}({request.url_source})")
|
|
107
|
+
|
|
108
|
+
def execute_list(self, request: _Request, client: HttpClient) -> Result:
|
|
109
|
+
commands = self._fetch_commands(client)
|
|
110
|
+
if request.list_format == "json":
|
|
111
|
+
return Result("json", commands)
|
|
112
|
+
if not commands:
|
|
113
|
+
return Result("text", "暂无可用命令")
|
|
114
|
+
|
|
115
|
+
rows = []
|
|
116
|
+
for command in commands:
|
|
117
|
+
description = command.get("description")
|
|
118
|
+
summary = " ".join(description.split()) if isinstance(description, str) else ""
|
|
119
|
+
rows.append((command["name"], summary))
|
|
120
|
+
return Result("table", (("命令", "说明"), rows))
|
|
121
|
+
|
|
122
|
+
def execute_describe(self, request: _Request, client: HttpClient) -> Result:
|
|
123
|
+
for command in self._fetch_commands(client):
|
|
124
|
+
if command["name"] == request.command:
|
|
125
|
+
break
|
|
126
|
+
else:
|
|
127
|
+
listing = self._invocation("list", url=request.explicit_url, token_file=request.token_file)
|
|
128
|
+
return Result("text", f"找不到命令 {request.command!r}。用 {listing} 查看命令名称。",
|
|
129
|
+
exit_code=1)
|
|
130
|
+
|
|
131
|
+
output = command.get("output")
|
|
132
|
+
kind = output.get("kind") if isinstance(output, dict) else None
|
|
133
|
+
|
|
134
|
+
schema = command.get("input_schema")
|
|
135
|
+
parameters = None
|
|
136
|
+
example_args = None
|
|
137
|
+
requires_arguments = True
|
|
138
|
+
if isinstance(schema, dict):
|
|
139
|
+
properties = schema.get("properties", {})
|
|
140
|
+
required = set(schema.get("required", []))
|
|
141
|
+
requires_arguments = bool(required)
|
|
142
|
+
parameters = [
|
|
143
|
+
ParameterDetails(
|
|
144
|
+
name=name,
|
|
145
|
+
type_name=_schema_type(field),
|
|
146
|
+
required=name in required,
|
|
147
|
+
has_default="default" in field,
|
|
148
|
+
default=field.get("default"),
|
|
149
|
+
description=field.get("description"),
|
|
150
|
+
)
|
|
151
|
+
for name, field in properties.items()
|
|
152
|
+
]
|
|
153
|
+
if parameters:
|
|
154
|
+
for value in schema.get("examples", []):
|
|
155
|
+
if isinstance(value, dict) and required <= value.keys() <= properties.keys():
|
|
156
|
+
example_args = value
|
|
157
|
+
break
|
|
158
|
+
|
|
159
|
+
example = None
|
|
160
|
+
if example_args is not None or (kind == "binary" and not requires_arguments):
|
|
161
|
+
example = self._invocation(
|
|
162
|
+
"call",
|
|
163
|
+
url=request.explicit_url,
|
|
164
|
+
token_file=request.token_file,
|
|
165
|
+
command=request.command,
|
|
166
|
+
arguments=json.dumps(example_args, ensure_ascii=False) if example_args is not None else None,
|
|
167
|
+
output_file="PATH" if kind == "binary" else None,
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
output_label = "由运行结果决定"
|
|
171
|
+
if kind == "json":
|
|
172
|
+
output_label = "JSON"
|
|
173
|
+
elif kind == "binary":
|
|
174
|
+
output_label = "二进制文件" if example else "二进制文件,用 -o PATH 保存"
|
|
175
|
+
|
|
176
|
+
return Result("details", CommandDetails(
|
|
177
|
+
name=command["name"],
|
|
178
|
+
description=command.get("description"),
|
|
179
|
+
thread=command.get("thread"),
|
|
180
|
+
output_label=output_label,
|
|
181
|
+
parameters=parameters,
|
|
182
|
+
example=example,
|
|
183
|
+
))
|
|
184
|
+
|
|
185
|
+
def execute_call(self, request: _Request, client: HttpClient) -> Result:
|
|
186
|
+
try:
|
|
187
|
+
arguments = json.loads(request.arguments, parse_constant=_reject_json_constant)
|
|
188
|
+
except json.JSONDecodeError as exc:
|
|
189
|
+
message = f"--args 的 JSON 格式无效(第 {exc.lineno} 行,第 {exc.colno} 列): {exc.msg}"
|
|
190
|
+
return Result("text", message, exit_code=1)
|
|
191
|
+
if not isinstance(arguments, dict):
|
|
192
|
+
return Result("text", "--args 必须是一个 JSON 对象", exit_code=1)
|
|
193
|
+
|
|
194
|
+
accept = _BINARY_ACCEPT if request.output_file is not None else "application/json"
|
|
195
|
+
try:
|
|
196
|
+
value = client.call_command(request.command, arguments, timeout=request.timeout, accept=accept)
|
|
197
|
+
except HttpClientError as exc:
|
|
198
|
+
if exc.status_code == 404:
|
|
199
|
+
listing = self._invocation("list", url=request.explicit_url, token_file=request.token_file)
|
|
200
|
+
hint = f"用 {listing} 查看命令名称。"
|
|
201
|
+
elif exc.status_code == 406:
|
|
202
|
+
hint = "用 -o PATH 保存二进制结果。"
|
|
203
|
+
if request.output_file is not None:
|
|
204
|
+
hint = "去掉 -o 后接收 JSON 结果。"
|
|
205
|
+
elif exc.status_code == 422:
|
|
206
|
+
describe = self._invocation(
|
|
207
|
+
"describe",
|
|
208
|
+
url=request.explicit_url,
|
|
209
|
+
token_file=request.token_file,
|
|
210
|
+
command=request.command,
|
|
211
|
+
)
|
|
212
|
+
hint = f"用 {describe} 查看参数。"
|
|
213
|
+
elif exc.status_code == 504:
|
|
214
|
+
hint = f"已开始执行的命令 {request.command!r} 可能仍在运行。"
|
|
215
|
+
else:
|
|
216
|
+
raise
|
|
217
|
+
return self._http_failure(request, exc, hint=hint)
|
|
218
|
+
|
|
219
|
+
if isinstance(value, tuple):
|
|
220
|
+
output_file = request.output_file
|
|
221
|
+
if output_file is None:
|
|
222
|
+
return Result("text", "请用 --output PATH 保存二进制结果", exit_code=1)
|
|
223
|
+
data, _ = value
|
|
224
|
+
try:
|
|
225
|
+
_write_binary_file(output_file, data)
|
|
226
|
+
except OSError as exc:
|
|
227
|
+
return Result("text", f"保存失败:{exc}", exit_code=1)
|
|
228
|
+
return Result("text", f"已保存到 {output_file}")
|
|
229
|
+
|
|
230
|
+
if request.output_file is not None:
|
|
231
|
+
return Result("text", "--output 用于保存二进制结果", exit_code=1)
|
|
232
|
+
return Result("json", value)
|
|
233
|
+
|
|
234
|
+
@staticmethod
|
|
235
|
+
def _fetch_commands(client: HttpClient) -> list[dict]:
|
|
236
|
+
commands = client.get("/commands")
|
|
237
|
+
if not isinstance(commands, list) or any(
|
|
238
|
+
not isinstance(command, dict) or not isinstance(command.get("name"), str)
|
|
239
|
+
for command in commands
|
|
240
|
+
):
|
|
241
|
+
raise ValueError("/commands 响应不符合 Bridge 约定")
|
|
242
|
+
return commands
|
|
243
|
+
|
|
244
|
+
def _http_failure(
|
|
245
|
+
self, request: _Request, exc: HttpClientError, *, hint: str | None = None,
|
|
246
|
+
) -> Result:
|
|
247
|
+
if exc.status_code is None:
|
|
248
|
+
message = f"{request.url} · {exc}"
|
|
249
|
+
if exc.kind == "connection" and request.action != "status":
|
|
250
|
+
check = self._invocation("status", url=request.url, token_file=request.token_file)
|
|
251
|
+
hint = f"可用 {check} 检查连接。"
|
|
252
|
+
return Result("text", message, exit_code=1, hint=hint)
|
|
253
|
+
|
|
254
|
+
detail = exc.detail
|
|
255
|
+
if isinstance(detail, list):
|
|
256
|
+
fields = []
|
|
257
|
+
for item in detail:
|
|
258
|
+
if isinstance(item, dict) and isinstance(item.get("msg"), str):
|
|
259
|
+
location = item.get("loc", [])
|
|
260
|
+
field = ".".join(map(str, location)) if isinstance(location, list) else ""
|
|
261
|
+
fields.append(f"{field}: {item['msg']}" if field else item["msg"])
|
|
262
|
+
detail = "\n".join(fields)
|
|
263
|
+
|
|
264
|
+
if exc.status_code == 401 and hint is None:
|
|
265
|
+
hint = (
|
|
266
|
+
f"请检查 --token-file,也可将 {TOKEN_ENV} 或 "
|
|
267
|
+
f"{TOKEN_FILE_ENV} 与 {self.URL_ENV} 一起设置。"
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
message = f"HTTP {exc.status_code}"
|
|
271
|
+
if detail:
|
|
272
|
+
message += f" · {detail}"
|
|
273
|
+
if request.action != "call":
|
|
274
|
+
message = f"{request.url} · {message}"
|
|
275
|
+
return Result("text", message, exit_code=1, hint=hint)
|
|
276
|
+
|
|
277
|
+
def _invocation(
|
|
278
|
+
self,
|
|
279
|
+
action: str,
|
|
280
|
+
*,
|
|
281
|
+
url: str | None = None,
|
|
282
|
+
token_file: Path | None = None,
|
|
283
|
+
command: str | None = None,
|
|
284
|
+
arguments: str | None = None,
|
|
285
|
+
output_file: str | None = None,
|
|
286
|
+
) -> str:
|
|
287
|
+
tokens = [self.prog, action]
|
|
288
|
+
if url is not None:
|
|
289
|
+
tokens.extend(["--url", url])
|
|
290
|
+
if token_file is not None:
|
|
291
|
+
tokens.extend(["--token-file", str(token_file)])
|
|
292
|
+
if arguments is not None:
|
|
293
|
+
tokens.extend(["-a", arguments])
|
|
294
|
+
if output_file is not None:
|
|
295
|
+
tokens.extend(["-o", output_file])
|
|
296
|
+
if command is not None:
|
|
297
|
+
if command.startswith("-"):
|
|
298
|
+
tokens.extend(["--", command])
|
|
299
|
+
else:
|
|
300
|
+
tokens.insert(2, command)
|
|
301
|
+
return shlex.join(tokens)
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _write_binary_file(path: Path, data: bytes) -> None:
|
|
305
|
+
temporary_path: Path | None = None
|
|
306
|
+
try:
|
|
307
|
+
with NamedTemporaryFile(dir=path.parent, prefix=".agentize-", delete=False) as file:
|
|
308
|
+
temporary_path = Path(file.name)
|
|
309
|
+
file.write(data)
|
|
310
|
+
temporary_path.replace(path)
|
|
311
|
+
temporary_path = None
|
|
312
|
+
finally:
|
|
313
|
+
if temporary_path is not None:
|
|
314
|
+
with suppress(OSError):
|
|
315
|
+
temporary_path.unlink(missing_ok=True)
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _reject_json_constant(value: str) -> None:
|
|
319
|
+
raise ValueError(f"--args 的 JSON 格式无效,不支持 {value}")
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _schema_type(schema: dict) -> str:
|
|
323
|
+
if "$ref" in schema:
|
|
324
|
+
return schema["$ref"].rsplit("/", 1)[-1]
|
|
325
|
+
for key in ("anyOf", "oneOf"):
|
|
326
|
+
if key in schema:
|
|
327
|
+
return " | ".join(_schema_type(item) for item in schema[key])
|
|
328
|
+
|
|
329
|
+
kind = schema.get("type", "任意")
|
|
330
|
+
if isinstance(kind, list):
|
|
331
|
+
return " | ".join(kind)
|
|
332
|
+
if kind == "array" and isinstance(schema.get("items"), dict):
|
|
333
|
+
return f"array<{_schema_type(schema['items'])}>"
|
|
334
|
+
return kind
|