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.
@@ -0,0 +1,5 @@
1
+ from .__version__ import __version__ # 必须在最顶上,内部程序会从这里取版本
2
+ from .core import BinaryResult, command
3
+ from .server import AgentizeServer
4
+
5
+ __all__ = ["AgentizeServer", "BinaryResult", "command"]
@@ -0,0 +1,6 @@
1
+ from importlib.metadata import PackageNotFoundError, version
2
+
3
+ try:
4
+ __version__ = version("agentize-bridge")
5
+ except PackageNotFoundError: # 未安装、直接从源码目录运行时
6
+ __version__ = "0+unknown"
@@ -0,0 +1,3 @@
1
+ from .app import main
2
+
3
+ __all__ = ["main"]
@@ -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
@@ -0,0 +1,94 @@
1
+ import json
2
+ import sys
3
+ from dataclasses import dataclass
4
+ from typing import Any, Literal
5
+ from unicodedata import combining, east_asian_width
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class Result:
10
+ format: Literal["text", "json", "table", "details"]
11
+ data: Any
12
+ exit_code: int = 0
13
+ hint: str | None = None
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class ParameterDetails:
18
+ name: str
19
+ type_name: str
20
+ required: bool
21
+ has_default: bool
22
+ default: Any
23
+ description: str | None
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class CommandDetails:
28
+ name: str
29
+ description: str | None
30
+ thread: str | None
31
+ output_label: str
32
+ parameters: list[ParameterDetails] | None
33
+ example: str | None
34
+
35
+
36
+ def emit(result: Result) -> None:
37
+ if result.format == "json":
38
+ text = json.dumps(result.data, ensure_ascii=False, indent=2)
39
+ elif result.format == "table":
40
+ text = _render_table(*result.data)
41
+ elif result.format == "details":
42
+ text = _render_details(result.data)
43
+ else:
44
+ text = result.data
45
+
46
+ stream = sys.stdout
47
+ if result.exit_code:
48
+ text = f"错误: {text}"
49
+ stream = sys.stderr
50
+ if result.hint:
51
+ text += f"\n{result.hint}"
52
+ print(text, file=stream)
53
+
54
+
55
+ def _render_table(headings: tuple[str, ...], rows: list[tuple[str, ...]]) -> str:
56
+ widths = [max(map(_display_width, column)) for column in zip(headings, *rows)]
57
+ lines = []
58
+ for row in (headings, *rows):
59
+ cells = [cell + " " * (width - _display_width(cell)) for cell, width in zip(row, widths)]
60
+ lines.append(" ".join(cells).rstrip())
61
+ return "\n".join(lines)
62
+
63
+
64
+ def _display_width(text: str) -> int:
65
+ return sum(2 if east_asian_width(char) in {"W", "F"} else 1 for char in text if not combining(char))
66
+
67
+
68
+ def _render_details(details: CommandDetails) -> str:
69
+ lines = [details.name]
70
+ if details.description:
71
+ lines.append(details.description)
72
+ if details.thread:
73
+ lines.extend(["", f"执行线程: {details.thread}"])
74
+
75
+ lines.extend(["", f"输出类型: {details.output_label}", ""])
76
+
77
+ if details.parameters is None:
78
+ lines.append("参数: 服务端未提供 Schema")
79
+ elif not details.parameters:
80
+ lines.append("参数: 无")
81
+ else:
82
+ lines.append("参数:")
83
+ for parameter in details.parameters:
84
+ presence = "必填" if parameter.required else "可选"
85
+ text = f" {parameter.name} {parameter.type_name} {presence}"
86
+ if parameter.has_default:
87
+ text += f" 默认: {json.dumps(parameter.default, ensure_ascii=False)}"
88
+ if parameter.description:
89
+ text += f" {parameter.description}"
90
+ lines.append(text)
91
+
92
+ if details.example:
93
+ lines.extend(["", "示例:", f" {details.example}"])
94
+ return "\n".join(lines)
@@ -0,0 +1,190 @@
1
+ import math
2
+ import re
3
+ from argparse import ArgumentParser, ArgumentTypeError, RawDescriptionHelpFormatter, SUPPRESS, Action, _MutuallyExclusiveGroup, _SubParsersAction
4
+ from pathlib import Path
5
+ from typing import Iterable
6
+ from unicodedata import combining, east_asian_width
7
+
8
+ from ... import __version__
9
+ from .commands import Executor
10
+
11
+
12
+ def _positive_seconds(value: str) -> float:
13
+ try:
14
+ seconds = float(value)
15
+ except ValueError as exc:
16
+ raise ArgumentTypeError("请输入以秒为单位的数字") from exc
17
+
18
+ if not math.isfinite(seconds) or seconds <= 0:
19
+ raise ArgumentTypeError("超时必须是大于 0 的有限数字")
20
+ return seconds
21
+
22
+
23
+ def _add_connection_options(group, *, action: str | None = None) -> None:
24
+ # 子命令未传此选项时,保留顶层解析出的值。
25
+ group.add_argument(
26
+ "-u", "--url", metavar="URL", default=SUPPRESS,
27
+ help=f"Bridge 地址,默认 {Executor.DEFAULT_URL}\n也可设置环境变量 {Executor.URL_ENV}",
28
+ )
29
+ group.add_argument(
30
+ "-T", "--token-file", metavar="PATH", type=Path, default=SUPPRESS,
31
+ help="从指定文件读取本次调用的令牌,优先于环境变量",
32
+ )
33
+ if action is None:
34
+ timeouts = [f"{name} 默认 {seconds}" for name, seconds in Executor.COMMAND_TIMEOUTS.items()]
35
+ timeouts.append(f"其他命令默认 {Executor.DEFAULT_TIMEOUT}")
36
+ timeout_help = "等待上限(秒)," + ",".join(timeouts)
37
+ else:
38
+ label = {"status": "探测等待上限", "call": "服务端等待上限"}.get(action, "请求等待上限")
39
+ timeout_help = f"{label}(秒),默认 {Executor.default_timeout(action)}"
40
+
41
+ group.add_argument(
42
+ "-t", "--timeout", metavar="SEC", type=_positive_seconds, default=SUPPRESS,
43
+ help=timeout_help,
44
+ )
45
+
46
+
47
+ def _epilog(prog: str, *examples: tuple[str, ...], note: str | None = None) -> str:
48
+ """ 每个 example 是 (注释, 命令, 命令, ...),命令不含程序名。"""
49
+ lines = ["示例:"]
50
+ for index, (comment, *commands) in enumerate(examples):
51
+ if index:
52
+ lines.append("")
53
+ lines.append(f" # {comment}")
54
+ lines.extend(f" $ {prog} {command}" for command in commands)
55
+ if note:
56
+ lines.extend(["", f"注:{note}"])
57
+ return "\n".join(lines)
58
+
59
+
60
+ def create_parser(prog: str) -> ArgumentParser:
61
+ parser = ArgumentParser(
62
+ prog=prog,
63
+ usage="%(prog)s [选项] <命令> [参数...]",
64
+ description="连接运行中的 Agentize Bridge,查看并调用宿主应用的命令",
65
+ formatter_class=HelpFormatter,
66
+ epilog=_epilog(
67
+ prog,
68
+ ("检查连接(指定端口)", "status -u http://127.0.0.1:9000"),
69
+ ("列出命令、查看某个命令的参数", "list", "describe add"),
70
+ ("调用命令,-a 传入 JSON 参数", """call add -a '{"a": 2, "b": 3}'"""),
71
+ ) + f"\n\n更多信息:{prog} <命令> -h",
72
+ add_help=False
73
+ )
74
+ commands = parser.add_subparsers(dest="action", required=True, title="命令", metavar="命令", prog=prog)
75
+
76
+ options = parser.add_argument_group("选项")
77
+ _add_connection_options(options)
78
+ options.add_argument("-v", "--version", action="version", version=f"%(prog)s {__version__}",
79
+ help="显示本地客户端版本并退出")
80
+ _add_help_option(options)
81
+
82
+ def add_command(name, *, help, description, usage, epilog):
83
+ return commands.add_parser(
84
+ name, help=help, description=description, usage=usage, epilog=epilog,
85
+ formatter_class=HelpFormatter, add_help=False
86
+ )
87
+
88
+ status = add_command(
89
+ "status", help="检查 Bridge 连接",
90
+ description="请求目标地址的 /health,并检查响应状态。",
91
+ usage="%(prog)s [选项]",
92
+ epilog=_epilog(prog, ("检查默认地址", "status"), ("检查指定端口", "status -u http://127.0.0.1:9000"))
93
+ )
94
+ format_names = {"table": "命令摘要", "json": "完整 JSON"}
95
+ listing = add_command(
96
+ "list", help="列出可用命令",
97
+ description=(
98
+ f"终端默认输出{format_names[Executor.TERMINAL_LIST_FORMAT]},"
99
+ f"管道和重定向默认输出{format_names[Executor.PIPE_LIST_FORMAT]}。"
100
+ ),
101
+ usage="%(prog)s [选项]",
102
+ epilog=_epilog(prog, ("按当前输出环境选择格式", "list"), ("强制输出完整 JSON", "list --json"))
103
+ )
104
+ describe = add_command(
105
+ "describe", help="查看单个命令的参数和输出类别",
106
+ description="查看指定命令的参数类型、必填项、默认值和输出类别。",
107
+ usage="%(prog)s [选项] NAME",
108
+ epilog=_epilog(
109
+ prog,
110
+ ("查看 export_file 的参数和输出类别", "describe export_file"),
111
+ ("调用命令并保存二进制结果", "call export_file -o export.bin")
112
+ )
113
+ )
114
+ call = add_command(
115
+ "call", help="执行指定命令",
116
+ description="执行宿主应用的命令,输出 JSON 或保存二进制结果。",
117
+ usage="%(prog)s [选项] NAME",
118
+ epilog=_epilog(
119
+ prog, ("调用 add,-a 传入 JSON 参数", """call add -a '{"a": 2, "b": 3}'"""),
120
+ note="call 的等待上限会发送给服务端,客户端另保留约 5 秒网络余量。"
121
+ )
122
+ )
123
+
124
+ describe.add_argument_group("参数").add_argument("command", metavar="NAME", help="用 list 查看可用命令名")
125
+ call.add_argument_group("参数").add_argument("command", metavar="NAME", help="要执行的命令名")
126
+ # 先放各命令特有的选项,再放连接选项和 -h,帮助里的顺序就是这样
127
+ groups = {
128
+ name: command_parser.add_argument_group("选项")
129
+ for name, command_parser in (("status", status), ("list", listing), ("describe", describe), ("call", call))
130
+ }
131
+
132
+ output = groups["list"].add_mutually_exclusive_group()
133
+ output.add_argument("--json", dest="output", action="store_const", const="json", default=SUPPRESS,
134
+ help="输出完整命令元数据和参数 Schema")
135
+ output.add_argument("--table", dest="output", action="store_const", const="table", default=SUPPRESS,
136
+ help="输出命令名和简介")
137
+ groups["call"].add_argument("-a", "--args", metavar="JSON", default=SUPPRESS,
138
+ help=f"命令参数,必须是 JSON 对象,默认 {Executor.DEFAULT_ARGUMENTS}")
139
+ groups["call"].add_argument("-o", "--output", dest="output_file", metavar="PATH", type=Path,
140
+ help="将二进制结果保存到指定文件")
141
+
142
+ for action, group in groups.items():
143
+ _add_connection_options(group, action=action)
144
+ _add_help_option(group)
145
+
146
+ return parser
147
+
148
+
149
+ def _add_help_option(group) -> None:
150
+ group.add_argument("-h", "--help", action="help", default=SUPPRESS, help="显示本帮助并退出")
151
+
152
+
153
+ class HelpFormatter(RawDescriptionHelpFormatter):
154
+ """ 让 help 排版更为规整 """
155
+
156
+ def __init__(self, prog: str, **kwargs):
157
+ kwargs.setdefault("max_help_position", 28)
158
+ super().__init__(prog, **kwargs)
159
+
160
+ def add_usage(self, usage: str | None, actions: Iterable[Action], groups: Iterable[_MutuallyExclusiveGroup], prefix: str | None = None) -> None:
161
+ super().add_usage(usage, actions, groups, "用法: " if prefix is None else prefix)
162
+
163
+ def _split_lines(self, text: str, width: int) -> list[str]:
164
+ lines = []
165
+ for paragraph in text.splitlines():
166
+ line = separator = ""
167
+ columns = 0
168
+ # 中文可逐字折行,句末标点跟随前一个词,ASCII 词保持完整。
169
+ for token in re.findall(r"(?:[!-~]+|\S)[,。!?、;:)】》]*|[^\S\n]+", paragraph):
170
+ if token.isspace():
171
+ separator = " " if line else ""
172
+ continue
173
+
174
+ token_width = sum(2 if east_asian_width(char) in {"W", "F"} else 1
175
+ for char in token if not combining(char))
176
+ if line and columns + len(separator) + token_width > width:
177
+ lines.append(line)
178
+ line = separator = ""
179
+ columns = 0
180
+
181
+ line += separator + token
182
+ columns += len(separator) + token_width
183
+ separator = ""
184
+ lines.append(line)
185
+ return lines
186
+
187
+ def _format_action(self, action):
188
+ if isinstance(action, _SubParsersAction):
189
+ return "".join(self._format_action(sub) for sub in action._get_subactions())
190
+ return super()._format_action(action)