bugx-cli 0.1.1 → 0.1.2
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.
- package/README.md +13 -9
- package/core/README.md +1 -1
- package/core/assets/README.md +3 -2
- package/core/assets/bugx-social-preview.svg +71 -0
- package/core/assets/bugx-wechat-group.png +0 -0
- package/core/audit_packs/README.md +2 -0
- package/core/audit_packs/pitfalls/auth_crypto.json +64 -0
- package/core/audit_packs/pitfalls/file_ssrf_cmd.json +64 -0
- package/core/audit_packs/pitfalls/go_backend.json +66 -0
- package/core/audit_packs/pitfalls/java_spring.json +64 -0
- package/core/audit_packs/pitfalls/js_ts_web.json +67 -0
- package/core/audit_packs/pitfalls/python_web.json +82 -0
- package/core/bugx.md +1 -1
- package/core/bugx_paths.py +2 -2
- package/core/cloud_sync/cloud_client.py +56 -5
- package/core/cloud_sync/consent.py +33 -3
- package/core/cloud_sync/flywheel_client.py +186 -24
- package/core/contracts/README.md +1 -1
- package/core/contracts/bugx-runtime-contract.md +1 -1
- package/core/contracts/bugx-worker.md +1 -1
- package/core/engine-integrity.json +122 -66
- package/core/infra/README.md +1 -1
- package/core/infra/build_info.py +2 -2
- package/core/launch_phases/README.md +6 -3
- package/core/launch_phases/finding_confirm_phase.py +168 -7
- package/core/launch_phases/post_phase.py +5 -5
- package/core/launch_phases/pre_recon_scout.py +13 -0
- package/core/launch_phases/report_sharing.py +3 -7
- package/core/launch_phases/round_orchestrator.py +114 -26
- package/core/launch_phases/semantic_recon.py +545 -0
- package/core/launch_phases/startup_version_gate.py +6 -2
- package/core/launch_phases/verify_loop.py +767 -0
- package/core/launch_phases/worker_prior.py +115 -0
- package/core/ledger/README.md +2 -1
- package/core/ledger/finding_verification.py +511 -2
- package/core/ledger/fp_ledger.py +255 -0
- package/core/metadata.txt +2 -2
- package/core/planning/README.md +2 -1
- package/core/planning/prompt_harness.py +50 -10
- package/core/planning/prompt_policy_engine.py +386 -0
- package/core/prompts/README.md +4 -2
- package/core/prompts/policies/prompt_policies.json +101 -0
- package/core/prompts/stages/stage_verify.defensive.md +42 -0
- package/core/prompts/stages/stage_verify.md +44 -0
- package/core/report_engine/report_share.py +0 -8
- package/core/retrieval/README.md +2 -1
- package/core/retrieval/pitfall_packs.py +277 -0
- package/core/runtime/README.md +1 -1
- package/core/runtime/global_telemetry.py +20 -0
- package/core/runtime/scenario_eval.py +1 -1
- package/core/supervisor/README.md +1 -1
- package/docs/07_distribution/01_README_NPM.md +13 -9
- package/ecosystem/integrations/dsh/mcp/package.json +1 -1
- package/ecosystem/integrations/dsh/ui/package.json +1 -1
- package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +1 -1
- package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
- package/ecosystem/integrations/qoder/connector-meta.json +1 -1
- package/ecosystem/integrations/workbuddy/connector-meta.json +1 -1
- package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +1 -1
- package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +2 -2
- package/interfaces/bin/bugx.js +7 -7
- package/interfaces/cli/bugx_cli/__init__.py +2 -2
- package/interfaces/cli/bugx_cli/cli.py +163 -67
- package/interfaces/cli/bugx_cli/commands/agent.py +122 -61
- package/interfaces/cli/bugx_cli/commands/audit.py +8 -7
- package/interfaces/cli/bugx_cli/commands/cloud.py +27 -19
- package/interfaces/cli/bugx_cli/commands/knowledge.py +3 -4
- package/interfaces/cli/bugx_cli/commands/plugin.py +3 -3
- package/interfaces/cli/bugx_cli/commands/plugin_claude.py +2 -2
- package/interfaces/cli/bugx_cli/commands/project.py +6 -13
- package/interfaces/cli/bugx_cli/commands/system.py +513 -158
- package/interfaces/cli/bugx_cli/common.py +6 -8
- package/interfaces/cli/bugx_cli/infra/engine_installer.py +21 -10
- package/interfaces/cli/bugx_cli/infra/host_sync.py +1 -1
- package/package.json +29 -15
- package/pyproject.toml +40 -1
- package/scripts/sync-version.mjs +1 -1
- package/core/assets/bugx-hero-cn.png +0 -0
- package/core/assets/bugx-hero-en.png +0 -0
|
@@ -38,19 +38,6 @@ from ..infra.security import _assert_no_symlink_components
|
|
|
38
38
|
from .cloud import _supervisor_deploy, _supervisor_status
|
|
39
39
|
|
|
40
40
|
|
|
41
|
-
_COMPLETION_CHILDREN = {
|
|
42
|
-
"auth": ("login", "status", "set-key", "logout"),
|
|
43
|
-
"cloud": (
|
|
44
|
-
"config", "status", "log-report", "feedback", "sync", "export",
|
|
45
|
-
"upload", "conflicts", "projects", "devices", "onboard",
|
|
46
|
-
),
|
|
47
|
-
"completion": ("bash", "zsh", "fish"),
|
|
48
|
-
"hosts": ("--json", "--root"),
|
|
49
|
-
"install": ("--agent", "--allow-missing", "--force", "--json", "--non-interactive", "--root"),
|
|
50
|
-
"autonomous": ("--agent-timeout", "--host", "--json", "--max-turns", "--max-wall-time", "--root"),
|
|
51
|
-
"skill": ("list", "status", "validate", "rollback"),
|
|
52
|
-
"update": ("--allow-downgrade", "--channel", "--check", "--force", "--repair-assets", "--root"),
|
|
53
|
-
}
|
|
54
41
|
|
|
55
42
|
_ASSET_REPAIR_ATTEMPT_ENV = "BUGX_ASSET_REPAIR_ATTEMPTED"
|
|
56
43
|
# Stable package recovery is a separate trust path from the user's configurable
|
|
@@ -63,78 +50,86 @@ _MAX_PYPI_METADATA_BYTES = 4 * 1024 * 1024
|
|
|
63
50
|
_MAX_PYPI_WHEEL_BYTES = 128 * 1024 * 1024
|
|
64
51
|
|
|
65
52
|
|
|
53
|
+
def completion_tree(parser: argparse.ArgumentParser) -> dict[str, tuple[str, ...]]:
|
|
54
|
+
"""Derive nested commands, enum selectors and options from the CLI parser."""
|
|
55
|
+
tree: dict[str, tuple[str, ...]] = {}
|
|
56
|
+
|
|
57
|
+
def collect(current: argparse.ArgumentParser, route: str) -> None:
|
|
58
|
+
words: set[str] = set()
|
|
59
|
+
for action in current._actions:
|
|
60
|
+
if action.help == argparse.SUPPRESS:
|
|
61
|
+
continue
|
|
62
|
+
if isinstance(action, argparse._SubParsersAction):
|
|
63
|
+
words.update(action.choices)
|
|
64
|
+
for name, child in action.choices.items():
|
|
65
|
+
collect(child, f"{route}/{name}")
|
|
66
|
+
elif action.option_strings:
|
|
67
|
+
words.update(action.option_strings)
|
|
68
|
+
elif action.choices:
|
|
69
|
+
words.update(str(choice) for choice in action.choices)
|
|
70
|
+
tree[route] = tuple(sorted(words))
|
|
71
|
+
|
|
72
|
+
collect(parser, "")
|
|
73
|
+
return tree
|
|
74
|
+
|
|
75
|
+
|
|
66
76
|
def command_completion(args: argparse.Namespace) -> int:
|
|
67
|
-
"""Print
|
|
68
|
-
|
|
69
|
-
if not commands:
|
|
70
|
-
commands = (
|
|
71
|
-
"auth", "autonomous", "cloud", "completion", "daemon", "doctor", "dsh", "help", "hosts",
|
|
72
|
-
"init", "install", "knowledge", "lesson", "log", "logic-analysis",
|
|
73
|
-
"mcp", "mcp-runtime", "mining-audit", "patch-forge", "plugin", "probe",
|
|
74
|
-
"project", "reset", "self-audit", "skill", "stats", "supervisor", "test-audit",
|
|
75
|
-
"test-generate", "test-verify", "uninstall", "update",
|
|
76
|
-
)
|
|
77
|
-
words = " ".join(commands)
|
|
78
|
-
children = {name: " ".join(values) for name, values in _COMPLETION_CHILDREN.items()}
|
|
77
|
+
"""Print shell completions for the same commands and options as help."""
|
|
78
|
+
tree = args.completion_tree
|
|
79
79
|
shell = args.shell
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
_bugx() {{
|
|
107
|
-
local -a commands
|
|
108
|
-
commands=({command_items})
|
|
109
|
-
_arguments '1:command:->command' '*::arg:->args'
|
|
110
|
-
case $state in
|
|
111
|
-
command) _describe 'command' commands ;;
|
|
112
|
-
args)
|
|
113
|
-
case $words[2] in
|
|
114
|
-
auth) _describe 'auth action' ({children['auth'].replace(' ', ' ')}) ;;
|
|
115
|
-
cloud) _describe 'cloud command' ({children['cloud']}) ;;
|
|
116
|
-
completion) _describe 'shell' ({children['completion']}) ;;
|
|
117
|
-
hosts) _describe 'option' ({children['hosts']}) ;;
|
|
118
|
-
install) _describe 'option' ({children['install']}) ;;
|
|
119
|
-
autonomous) _describe 'option' ({children['autonomous']}) ;;
|
|
120
|
-
skill) _describe 'skill action' ({children['skill']}) ;;
|
|
121
|
-
update) _describe 'option' ({children['update']}) ;;
|
|
122
|
-
esac
|
|
123
|
-
;;
|
|
80
|
+
routes = "\n".join(f" '{route}') candidates='{' '.join(words)}' ;;" for route, words in tree.items())
|
|
81
|
+
transitions = "|".join(f"'{route}'" for route in tree if route)
|
|
82
|
+
if shell in {"bash", "zsh"}:
|
|
83
|
+
if shell == "bash":
|
|
84
|
+
init = 'local -a tokens=("${COMP_WORDS[@]}")'
|
|
85
|
+
limit = "COMP_CWORD"
|
|
86
|
+
emit = 'COMPREPLY=( $(compgen -W "$candidates" -- "$cur") )'
|
|
87
|
+
register = "complete -F _bugx_complete bugx"
|
|
88
|
+
start = 1
|
|
89
|
+
else:
|
|
90
|
+
init = 'local -a tokens=("${words[@]}")'
|
|
91
|
+
limit = "CURRENT"
|
|
92
|
+
emit = 'compadd -- $=candidates'
|
|
93
|
+
register = "compdef _bugx_complete bugx"
|
|
94
|
+
start = 2
|
|
95
|
+
print(f"""_bugx_complete() {{
|
|
96
|
+
{init}
|
|
97
|
+
local i route='' candidates='' cur
|
|
98
|
+
for ((i={start}; i<{limit}; i++)); do
|
|
99
|
+
case "$route/${{tokens[i]}}" in
|
|
100
|
+
{transitions}) route="$route/${{tokens[i]}}" ;;
|
|
101
|
+
esac
|
|
102
|
+
done
|
|
103
|
+
cur="${{tokens[i]}}"
|
|
104
|
+
case "$route" in
|
|
105
|
+
{routes}
|
|
124
106
|
esac
|
|
107
|
+
{emit}
|
|
125
108
|
}}
|
|
126
|
-
|
|
109
|
+
{register}""")
|
|
127
110
|
elif shell == "fish":
|
|
128
|
-
print(
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
111
|
+
print("""function __bugx_at
|
|
112
|
+
set -l route ''
|
|
113
|
+
set -l tokens (commandline -opc)
|
|
114
|
+
for token in $tokens[2..-1]
|
|
115
|
+
switch "$route/$token" """)
|
|
116
|
+
fish_routes = " ".join(f"'{route}'" for route in tree if route)
|
|
117
|
+
print(f" case {fish_routes}")
|
|
118
|
+
print(""" set route "$route/$token"
|
|
119
|
+
end
|
|
120
|
+
end
|
|
121
|
+
test "$route/" = "$argv[1]"
|
|
122
|
+
end""")
|
|
123
|
+
for route, words in tree.items():
|
|
124
|
+
for word in words:
|
|
125
|
+
if word.startswith("--"):
|
|
126
|
+
flag = f"-l '{word[2:]}'"
|
|
127
|
+
elif word.startswith("-"):
|
|
128
|
+
flag = f"-s '{word[1:]}'"
|
|
129
|
+
else:
|
|
130
|
+
flag = f"-a '{word}'"
|
|
131
|
+
print(f"complete -c bugx -f -n '__bugx_at {route + '/'}' {flag}")
|
|
132
|
+
else:
|
|
138
133
|
raise CliError(f"不支持的 shell: {shell}")
|
|
139
134
|
return 0
|
|
140
135
|
|
|
@@ -160,6 +155,38 @@ def _update_channel(args: argparse.Namespace) -> str:
|
|
|
160
155
|
return "stable"
|
|
161
156
|
|
|
162
157
|
|
|
158
|
+
def _update_installation_kind() -> tuple[str, str]:
|
|
159
|
+
"""Return (client_kind, artifact_kind) for the running installation.
|
|
160
|
+
|
|
161
|
+
The npm wrapper deliberately owns its Python path and bundled assets, so a
|
|
162
|
+
pip wheel installation is not a valid npm update. Source and editable
|
|
163
|
+
installs are reported explicitly and must not be overwritten by update.
|
|
164
|
+
"""
|
|
165
|
+
if os.environ.get("BUGX_CLI_SOURCE", "").strip().lower() == "npm":
|
|
166
|
+
return "npm", "npm-tarball"
|
|
167
|
+
try:
|
|
168
|
+
distribution = importlib.metadata.distribution("bugx-cli")
|
|
169
|
+
except importlib.metadata.PackageNotFoundError:
|
|
170
|
+
return "source", "python-wheel"
|
|
171
|
+
try:
|
|
172
|
+
direct_url_text = distribution.read_text("direct_url.json")
|
|
173
|
+
if direct_url_text:
|
|
174
|
+
direct_url = json.loads(direct_url_text)
|
|
175
|
+
if isinstance(direct_url, dict):
|
|
176
|
+
dir_info = direct_url.get("dir_info")
|
|
177
|
+
if isinstance(dir_info, dict) and dir_info.get("editable") is True:
|
|
178
|
+
return "editable", "python-wheel"
|
|
179
|
+
except (OSError, UnicodeError, json.JSONDecodeError):
|
|
180
|
+
return "unknown", "python-wheel"
|
|
181
|
+
module_path = Path(__file__).resolve()
|
|
182
|
+
try:
|
|
183
|
+
if (module_path.parents[4] / ".git").exists():
|
|
184
|
+
return "source", "python-wheel"
|
|
185
|
+
except IndexError:
|
|
186
|
+
pass
|
|
187
|
+
return "pip", "python-wheel"
|
|
188
|
+
|
|
189
|
+
|
|
163
190
|
def command_version_check(args: argparse.Namespace) -> int:
|
|
164
191
|
"""bugx update --check:向服务端查询最新版本,提示更新。
|
|
165
192
|
|
|
@@ -172,10 +199,6 @@ def command_version_check(args: argparse.Namespace) -> int:
|
|
|
172
199
|
# 仅供内部复用;公共入口是 bugx update --check。
|
|
173
200
|
print(f"BugX CLI v{__version__}")
|
|
174
201
|
return 0
|
|
175
|
-
if os.environ.get("BUGX_DISABLE_VERSION_CHECK", "").lower() in {"1", "true", "yes"}:
|
|
176
|
-
print("[update] 版本检查已由 BUGX_DISABLE_VERSION_CHECK 禁用")
|
|
177
|
-
return 0
|
|
178
|
-
|
|
179
202
|
try:
|
|
180
203
|
_ensure_core_importable()
|
|
181
204
|
from core.cloud_sync.cloud_client import CloudClient
|
|
@@ -183,10 +206,16 @@ def command_version_check(args: argparse.Namespace) -> int:
|
|
|
183
206
|
print(f"[update] 依赖加载失败: {exc}")
|
|
184
207
|
return 2
|
|
185
208
|
|
|
209
|
+
client_kind, artifact_kind = _update_installation_kind()
|
|
186
210
|
client = CloudClient()
|
|
187
211
|
channel = _update_channel(args)
|
|
188
212
|
try:
|
|
189
|
-
result = client.check_version(
|
|
213
|
+
result = client.check_version(
|
|
214
|
+
current_version=__version__,
|
|
215
|
+
channel=channel,
|
|
216
|
+
client_kind=client_kind,
|
|
217
|
+
artifact_kind=artifact_kind,
|
|
218
|
+
)
|
|
190
219
|
except Exception as exc: # noqa: BLE001
|
|
191
220
|
print(f"[update] 版本检查失败: {exc}")
|
|
192
221
|
_print_version_tls_hint(exc)
|
|
@@ -234,8 +263,14 @@ def command_version_check(args: argparse.Namespace) -> int:
|
|
|
234
263
|
or (min_version is not None and current_version < min_version))
|
|
235
264
|
|
|
236
265
|
if getattr(args, "json", False):
|
|
237
|
-
|
|
238
|
-
|
|
266
|
+
payload = dict(info)
|
|
267
|
+
payload["status"] = (
|
|
268
|
+
"UPDATE_REQUIRED" if update_required
|
|
269
|
+
else "UPDATE_AVAILABLE" if update_available
|
|
270
|
+
else "UP_TO_DATE"
|
|
271
|
+
)
|
|
272
|
+
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
273
|
+
return 1 if update_available or update_required else 0
|
|
239
274
|
|
|
240
275
|
print(f"当前版本: {__version__}")
|
|
241
276
|
if latest:
|
|
@@ -533,8 +568,8 @@ def _download_pypi_stable_wheel(
|
|
|
533
568
|
response.close()
|
|
534
569
|
|
|
535
570
|
|
|
536
|
-
def _prepare_cli_package(path: Path) -> Path:
|
|
537
|
-
"""
|
|
571
|
+
def _prepare_cli_package(path: Path, *, expected_version: str | None = None) -> Path:
|
|
572
|
+
"""Validate a downloaded Python package and give it a pip-safe suffix."""
|
|
538
573
|
try:
|
|
539
574
|
if zipfile.is_zipfile(path):
|
|
540
575
|
with zipfile.ZipFile(path) as archive:
|
|
@@ -555,6 +590,14 @@ def _prepare_cli_package(path: Path) -> Path:
|
|
|
555
590
|
version = str(metadata.get("Version") or "").strip()
|
|
556
591
|
if not name or not version:
|
|
557
592
|
raise CliError(_i18n_exc("system.wheel_name_version_missing", "wheel 包缺少 Name/Version 元数据"))
|
|
593
|
+
normalized_name = re.sub(r"[-_.]+", "-", name).lower()
|
|
594
|
+
if expected_version is not None and (
|
|
595
|
+
normalized_name != "bugx-cli" or version != expected_version
|
|
596
|
+
):
|
|
597
|
+
raise CliError(
|
|
598
|
+
f"wheel 身份不匹配:期望 bugx-cli {expected_version},"
|
|
599
|
+
f"收到 {normalized_name or '未知包'} {version or '未知版本'}"
|
|
600
|
+
)
|
|
558
601
|
tags: list[str] = []
|
|
559
602
|
if wheel_names:
|
|
560
603
|
for line in archive.read(wheel_names[0]).decode(
|
|
@@ -586,6 +629,38 @@ def _prepare_cli_package(path: Path) -> Path:
|
|
|
586
629
|
)), None)
|
|
587
630
|
if root is None:
|
|
588
631
|
raise CliError(_i18n_exc("system.sdist_missing_top_dir", "源码包缺少合法的顶层项目目录"))
|
|
632
|
+
if expected_version is not None:
|
|
633
|
+
metadata_members = [
|
|
634
|
+
member for member in archive.getmembers()
|
|
635
|
+
if member.isfile()
|
|
636
|
+
and PurePosixPath(member.name).name == "PKG-INFO"
|
|
637
|
+
and member.size <= 1024 * 1024
|
|
638
|
+
]
|
|
639
|
+
if not metadata_members:
|
|
640
|
+
raise CliError("源码包缺少 PKG-INFO 元数据")
|
|
641
|
+
metadata_file = archive.extractfile(metadata_members[0])
|
|
642
|
+
if metadata_file is None:
|
|
643
|
+
raise CliError("无法读取源码包 PKG-INFO 元数据")
|
|
644
|
+
metadata = Parser().parsestr(
|
|
645
|
+
metadata_file.read().decode("utf-8", errors="strict")
|
|
646
|
+
)
|
|
647
|
+
package_name = re.sub(
|
|
648
|
+
r"[-_.]+", "-", str(metadata.get("Name") or "")
|
|
649
|
+
).lower()
|
|
650
|
+
package_version = str(metadata.get("Version") or "").strip()
|
|
651
|
+
if package_name != "bugx-cli" or package_version != expected_version:
|
|
652
|
+
raise CliError(
|
|
653
|
+
f"源码包身份不匹配:期望 bugx-cli {expected_version},"
|
|
654
|
+
f"收到 {package_name or '未知包'} {package_version or '未知版本'}"
|
|
655
|
+
)
|
|
656
|
+
expected_root = re.sub(
|
|
657
|
+
r"[-_.+]+", "-", f"bugx-cli-{expected_version}"
|
|
658
|
+
).lower()
|
|
659
|
+
actual_root = re.sub(r"[-_.]+", "-", root).lower()
|
|
660
|
+
if actual_root != expected_root:
|
|
661
|
+
raise CliError(
|
|
662
|
+
f"源码包身份不匹配:期望 {expected_root},实际 {actual_root}"
|
|
663
|
+
)
|
|
589
664
|
target = path.with_name(f"{root}.tar.gz")
|
|
590
665
|
else:
|
|
591
666
|
raise CliError(_i18n_exc("system.unrecognized_package_archive", "下载内容不是可识别的 wheel 或源码包"))
|
|
@@ -604,6 +679,62 @@ def _installed_cli_distribution_version() -> str | None:
|
|
|
604
679
|
return None
|
|
605
680
|
|
|
606
681
|
|
|
682
|
+
def _prepare_npm_package(path: Path, *, expected_version: str) -> Path:
|
|
683
|
+
"""Validate an npm tarball without extracting or executing its scripts."""
|
|
684
|
+
if path.suffix.lower() != ".tgz":
|
|
685
|
+
raise CliError("npm 自动更新只接受 .tgz 制品")
|
|
686
|
+
try:
|
|
687
|
+
with tarfile.open(path, "r:gz") as archive:
|
|
688
|
+
member = archive.getmember("package/package.json")
|
|
689
|
+
if not member.isfile() or member.size > 256 * 1024:
|
|
690
|
+
raise CliError("npm 制品缺少安全的 package/package.json")
|
|
691
|
+
raw = archive.extractfile(member)
|
|
692
|
+
if raw is None:
|
|
693
|
+
raise CliError("无法读取 npm package.json")
|
|
694
|
+
payload = json.loads(raw.read().decode("utf-8", errors="strict"))
|
|
695
|
+
except (OSError, UnicodeError, json.JSONDecodeError, tarfile.TarError, KeyError) as exc:
|
|
696
|
+
raise CliError(f"无法识别 npm 制品:{exc}") from exc
|
|
697
|
+
if not isinstance(payload, dict) or payload.get("name") != "bugx-cli":
|
|
698
|
+
raise CliError("npm 制品 package.name 必须是 bugx-cli")
|
|
699
|
+
actual_version = str(payload.get("version") or "").strip()
|
|
700
|
+
if not actual_version or actual_version != expected_version:
|
|
701
|
+
raise CliError(
|
|
702
|
+
f"npm 制品版本不匹配:期望 {expected_version},实际 {actual_version or '未知'}"
|
|
703
|
+
)
|
|
704
|
+
return path
|
|
705
|
+
|
|
706
|
+
|
|
707
|
+
def _write_update_receipt(payload: dict[str, object]) -> Path | None:
|
|
708
|
+
"""Persist a bounded, non-secret update receipt outside project sources."""
|
|
709
|
+
try:
|
|
710
|
+
from core.report_engine.report_client import atomic_write_nofollow
|
|
711
|
+
|
|
712
|
+
root = Path.home() / ".bugx" / "update" / "receipts"
|
|
713
|
+
root.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
714
|
+
operation_id = str(payload.get("operation_id") or f"upd-{time.time_ns()}")
|
|
715
|
+
destination = root / f"{operation_id}.json"
|
|
716
|
+
atomic_write_nofollow(
|
|
717
|
+
destination,
|
|
718
|
+
(json.dumps(payload, ensure_ascii=False, sort_keys=True, indent=2) + "\n").encode("utf-8"),
|
|
719
|
+
mode=0o600,
|
|
720
|
+
)
|
|
721
|
+
return destination
|
|
722
|
+
except (OSError, ValueError, TypeError, ImportError):
|
|
723
|
+
return None
|
|
724
|
+
|
|
725
|
+
|
|
726
|
+
def _receipt_project_identity(root: Path) -> dict[str, str]:
|
|
727
|
+
"""Return a stable project identity without persisting its absolute path."""
|
|
728
|
+
try:
|
|
729
|
+
normalized = str(root.resolve())
|
|
730
|
+
except (OSError, RuntimeError, ValueError):
|
|
731
|
+
normalized = str(root)
|
|
732
|
+
fingerprint = hashlib.sha256(
|
|
733
|
+
normalized.encode("utf-8", "surrogatepass")
|
|
734
|
+
).hexdigest()[:16]
|
|
735
|
+
return {"project_root_fingerprint": f"sha256:{fingerprint}"}
|
|
736
|
+
|
|
737
|
+
|
|
607
738
|
def _trusted_repair_cloud_client():
|
|
608
739
|
"""Load CloudClient only from a self-consistent installed global engine."""
|
|
609
740
|
engine_root = global_engine_root()
|
|
@@ -1552,13 +1683,18 @@ def command_update(args: argparse.Namespace) -> int:
|
|
|
1552
1683
|
1. GET /api/v1/agent/version 获取最新版本元数据
|
|
1553
1684
|
2. 如果已是最新 → 提示并退出
|
|
1554
1685
|
3. 下载 CLI 包到临时目录
|
|
1555
|
-
4. SHA-256
|
|
1556
|
-
5. pip
|
|
1686
|
+
4. SHA-256 校验并确认制品身份
|
|
1687
|
+
5. 由当前安装类型所属的 pip 或 npm 安装器安装
|
|
1557
1688
|
6. bugx install --agent <已登记宿主> --root . --force --non-interactive(刷新宿主入口)
|
|
1558
1689
|
7. bugx doctor --installation-only 验证
|
|
1559
1690
|
"""
|
|
1560
1691
|
root = getattr(args, "root", Path.cwd()).resolve()
|
|
1561
1692
|
started = time.monotonic()
|
|
1693
|
+
started_epoch = time.time()
|
|
1694
|
+
operation_id = f"upd-{time.time_ns()}"
|
|
1695
|
+
client_kind, artifact_kind = _update_installation_kind()
|
|
1696
|
+
switched = False
|
|
1697
|
+
last_receipt: Path | None = None
|
|
1562
1698
|
|
|
1563
1699
|
if getattr(args, "repair_assets", False):
|
|
1564
1700
|
if getattr(args, "check", False):
|
|
@@ -1588,9 +1724,27 @@ def command_update(args: argparse.Namespace) -> int:
|
|
|
1588
1724
|
restart_cli_after_asset_repair()
|
|
1589
1725
|
|
|
1590
1726
|
def record_failure(message: str, *, phase: str, **fields: object) -> None:
|
|
1727
|
+
nonlocal last_receipt
|
|
1728
|
+
final_state = "RECOVERY_REQUIRED" if switched else "ABORTED"
|
|
1729
|
+
receipt_payload = {
|
|
1730
|
+
"schema_version": 1,
|
|
1731
|
+
"operation_id": operation_id,
|
|
1732
|
+
"started_at_epoch": started_epoch,
|
|
1733
|
+
"finished_at_epoch": time.time(),
|
|
1734
|
+
"current_version": __version__,
|
|
1735
|
+
"client_kind": client_kind,
|
|
1736
|
+
"artifact_kind": artifact_kind,
|
|
1737
|
+
"phase": phase,
|
|
1738
|
+
"final_state": final_state,
|
|
1739
|
+
"message": str(message)[:1000],
|
|
1740
|
+
**_receipt_project_identity(root),
|
|
1741
|
+
**{str(key): value for key, value in fields.items()},
|
|
1742
|
+
}
|
|
1743
|
+
last_receipt = _write_update_receipt(receipt_payload)
|
|
1591
1744
|
_log_update_event(
|
|
1592
1745
|
root, "update_check_failed", message,
|
|
1593
1746
|
phase=phase, duration_ms=round((time.monotonic() - started) * 1000, 1),
|
|
1747
|
+
operation_id=operation_id, final_state=final_state, receipt_path=str(last_receipt or ""),
|
|
1594
1748
|
**fields,
|
|
1595
1749
|
)
|
|
1596
1750
|
|
|
@@ -1609,12 +1763,26 @@ def command_update(args: argparse.Namespace) -> int:
|
|
|
1609
1763
|
if getattr(args, "check", False):
|
|
1610
1764
|
return command_version_check(args)
|
|
1611
1765
|
|
|
1766
|
+
if client_kind in {"source", "editable", "unknown"}:
|
|
1767
|
+
message = (
|
|
1768
|
+
f"当前 CLI 安装方式为 {client_kind},拒绝自动覆盖源码或 editable 环境;"
|
|
1769
|
+
"请使用源码同步、构建 wheel 或宿主专用安装流程更新"
|
|
1770
|
+
)
|
|
1771
|
+
record_failure(message, phase="preflight", failure_kind="unsupported_install_mode")
|
|
1772
|
+
print(f"[update] {message}")
|
|
1773
|
+
return 2
|
|
1774
|
+
|
|
1612
1775
|
client = CloudClient()
|
|
1613
1776
|
|
|
1614
1777
|
# 1. 版本检查(支持指定发布通道)
|
|
1615
1778
|
channel = _update_channel(args)
|
|
1616
1779
|
try:
|
|
1617
|
-
result = client.check_version(
|
|
1780
|
+
result = client.check_version(
|
|
1781
|
+
current_version=__version__,
|
|
1782
|
+
channel=channel,
|
|
1783
|
+
client_kind=client_kind,
|
|
1784
|
+
artifact_kind=artifact_kind,
|
|
1785
|
+
)
|
|
1618
1786
|
except Exception as exc: # noqa: BLE001
|
|
1619
1787
|
record_failure(str(exc), phase="version_check", failure_kind="exception")
|
|
1620
1788
|
print(f"[update] 版本检查失败: {exc}")
|
|
@@ -1642,6 +1810,34 @@ def command_update(args: argparse.Namespace) -> int:
|
|
|
1642
1810
|
min_client = str(info.get("min_client_version") or "").strip()
|
|
1643
1811
|
checksum = str(info.get("checksum_sha256") or "").strip().lower()
|
|
1644
1812
|
notes = str(info.get("release_notes") or "")
|
|
1813
|
+
release_id = str(info.get("release_id") or "").strip()
|
|
1814
|
+
remote_channel = str(info.get("channel") or "").strip()
|
|
1815
|
+
remote_artifact_kind = str(info.get("artifact_kind") or "").strip()
|
|
1816
|
+
artifact_version = str(info.get("artifact_version") or latest).strip()
|
|
1817
|
+
if remote_channel and remote_channel != channel:
|
|
1818
|
+
record_failure(
|
|
1819
|
+
"服务端返回了错误发布通道",
|
|
1820
|
+
phase="version_validation",
|
|
1821
|
+
failure_kind="channel_mismatch",
|
|
1822
|
+
requested_channel=channel,
|
|
1823
|
+
remote_channel=remote_channel,
|
|
1824
|
+
)
|
|
1825
|
+
print(
|
|
1826
|
+
f"[update] 服务端通道不一致:请求 {channel},收到 {remote_channel}"
|
|
1827
|
+
)
|
|
1828
|
+
return 2
|
|
1829
|
+
if remote_artifact_kind and remote_artifact_kind != artifact_kind:
|
|
1830
|
+
record_failure(
|
|
1831
|
+
"服务端返回了错误制品类型",
|
|
1832
|
+
phase="version_validation",
|
|
1833
|
+
failure_kind="artifact_kind_mismatch",
|
|
1834
|
+
expected_artifact_kind=artifact_kind,
|
|
1835
|
+
remote_artifact_kind=remote_artifact_kind,
|
|
1836
|
+
)
|
|
1837
|
+
print(
|
|
1838
|
+
f"[update] 服务端制品类型不一致:期望 {artifact_kind},收到 {remote_artifact_kind}"
|
|
1839
|
+
)
|
|
1840
|
+
return 2
|
|
1645
1841
|
update_available = info.get("update_available") is True
|
|
1646
1842
|
update_required = info.get("update_required") is True
|
|
1647
1843
|
rollback_required = (info.get("rollback_required") is True
|
|
@@ -1698,6 +1894,15 @@ def command_update(args: argparse.Namespace) -> int:
|
|
|
1698
1894
|
failure_kind="missing_checksum", latest_version=latest)
|
|
1699
1895
|
print("[update] 服务端未提供有效 SHA-256 校验值,拒绝安装未校验的升级包")
|
|
1700
1896
|
return 2
|
|
1897
|
+
if not release_id:
|
|
1898
|
+
record_failure(
|
|
1899
|
+
"服务端未提供 release_id,拒绝未绑定发布身份的升级包",
|
|
1900
|
+
phase="package_validation",
|
|
1901
|
+
failure_kind="missing_release_id",
|
|
1902
|
+
latest_version=latest,
|
|
1903
|
+
)
|
|
1904
|
+
print("[update] 服务端未提供 release_id,拒绝安装未绑定发布身份的升级包")
|
|
1905
|
+
return 2
|
|
1701
1906
|
|
|
1702
1907
|
print(f"[update] 当前版本: {__version__}")
|
|
1703
1908
|
print(f"[update] 目标版本: {latest}")
|
|
@@ -1708,10 +1913,16 @@ def command_update(args: argparse.Namespace) -> int:
|
|
|
1708
1913
|
# /agent/download;服务端的 302 由下载器跟随,摘要校验始终在本地完成。
|
|
1709
1914
|
tmpdir = Path(tempfile.mkdtemp(prefix="bugx-update-"))
|
|
1710
1915
|
try:
|
|
1711
|
-
|
|
1916
|
+
suffix = ".tgz" if artifact_kind == "npm-tarball" else ".package"
|
|
1917
|
+
dest = tmpdir / f"bugx-{artifact_version}{suffix}"
|
|
1712
1918
|
print(f"[update] 正在下载 CLI 包...")
|
|
1713
1919
|
ok, msg = client.download_package(
|
|
1714
|
-
dest,
|
|
1920
|
+
dest,
|
|
1921
|
+
expected_sha256=checksum,
|
|
1922
|
+
expected_version=latest,
|
|
1923
|
+
release_id=release_id,
|
|
1924
|
+
channel=channel,
|
|
1925
|
+
artifact_kind=artifact_kind,
|
|
1715
1926
|
)
|
|
1716
1927
|
if not ok:
|
|
1717
1928
|
record_failure(msg, phase="package_download", failure_kind="download")
|
|
@@ -1719,54 +1930,113 @@ def command_update(args: argparse.Namespace) -> int:
|
|
|
1719
1930
|
return 1
|
|
1720
1931
|
print(f"[update] {msg}")
|
|
1721
1932
|
try:
|
|
1722
|
-
|
|
1933
|
+
if artifact_kind == "npm-tarball":
|
|
1934
|
+
package_target = str(
|
|
1935
|
+
_prepare_npm_package(dest, expected_version=artifact_version)
|
|
1936
|
+
)
|
|
1937
|
+
else:
|
|
1938
|
+
package_target = str(
|
|
1939
|
+
_prepare_cli_package(dest, expected_version=artifact_version)
|
|
1940
|
+
)
|
|
1723
1941
|
except (CliError, OSError) as exc:
|
|
1724
1942
|
record_failure(str(exc), phase="package_validation", failure_kind="package_format")
|
|
1725
1943
|
print(f"[update] {exc}")
|
|
1726
1944
|
return 1
|
|
1727
1945
|
|
|
1728
|
-
# 4.
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1946
|
+
# 4. Install through the package manager that owns the running CLI.
|
|
1947
|
+
if client_kind == "npm":
|
|
1948
|
+
npm = shutil.which("npm")
|
|
1949
|
+
if not npm:
|
|
1950
|
+
record_failure(
|
|
1951
|
+
"当前 npm CLI 找不到 npm 可执行文件",
|
|
1952
|
+
phase="package_install",
|
|
1953
|
+
failure_kind="npm_missing",
|
|
1954
|
+
)
|
|
1955
|
+
print("[update] 当前 npm CLI 找不到 npm 可执行文件")
|
|
1956
|
+
return 2
|
|
1957
|
+
install_cmd = [
|
|
1958
|
+
npm, "install", "--global", "--no-audit", "--no-fund",
|
|
1959
|
+
package_target,
|
|
1960
|
+
]
|
|
1961
|
+
print(f"[update] 执行 npm install --global {package_target}...")
|
|
1962
|
+
else:
|
|
1963
|
+
install_cmd = [sys.executable, "-m", "pip", "install", "--upgrade",
|
|
1964
|
+
"--no-input", "--disable-pip-version-check", package_target]
|
|
1965
|
+
if is_rollback:
|
|
1966
|
+
# 回退到更低版本:pip --upgrade 不会降级,改用 --force-reinstall
|
|
1967
|
+
install_cmd = [sys.executable, "-m", "pip", "install",
|
|
1968
|
+
"--force-reinstall", "--no-input",
|
|
1969
|
+
"--disable-pip-version-check", package_target]
|
|
1970
|
+
print(f"[update] 执行 pip install --upgrade {package_target}...")
|
|
1736
1971
|
try:
|
|
1737
|
-
proc = subprocess.run(
|
|
1972
|
+
proc = subprocess.run(install_cmd, capture_output=True, text=True, timeout=180)
|
|
1738
1973
|
except subprocess.TimeoutExpired:
|
|
1739
|
-
record_failure(
|
|
1740
|
-
|
|
1974
|
+
record_failure(
|
|
1975
|
+
f"{client_kind} install 超时(180s)",
|
|
1976
|
+
phase="package_install",
|
|
1977
|
+
failure_kind="timeout",
|
|
1978
|
+
)
|
|
1979
|
+
print(f"[update] {client_kind} install 超时(180s)")
|
|
1741
1980
|
return 1
|
|
1742
1981
|
except OSError as exc:
|
|
1743
1982
|
record_failure(str(exc), phase="package_install", failure_kind="exec")
|
|
1744
|
-
print(f"[update]
|
|
1983
|
+
print(f"[update] {client_kind} install 执行失败: {exc}")
|
|
1745
1984
|
return 1
|
|
1746
1985
|
|
|
1747
1986
|
if proc.returncode != 0:
|
|
1748
1987
|
record_failure(
|
|
1749
|
-
f"
|
|
1988
|
+
f"{client_kind} install exit {proc.returncode}", phase="package_install",
|
|
1750
1989
|
failure_kind="nonzero_exit", exit_code=proc.returncode,
|
|
1751
1990
|
)
|
|
1752
|
-
print(f"[update]
|
|
1991
|
+
print(f"[update] {client_kind} install 失败 (exit {proc.returncode})")
|
|
1753
1992
|
if proc.stderr:
|
|
1754
1993
|
print(proc.stderr[-500:])
|
|
1755
1994
|
return 1
|
|
1756
1995
|
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1996
|
+
if client_kind == "npm":
|
|
1997
|
+
bugx_bin = shutil.which("bugx")
|
|
1998
|
+
if not bugx_bin:
|
|
1999
|
+
record_failure(
|
|
2000
|
+
"npm 安装成功但找不到 bugx wrapper",
|
|
2001
|
+
phase="package_install",
|
|
2002
|
+
failure_kind="wrapper_missing",
|
|
2003
|
+
)
|
|
2004
|
+
print("[update] npm 安装成功但找不到 bugx wrapper")
|
|
2005
|
+
return 1
|
|
2006
|
+
version_proc = subprocess.run(
|
|
2007
|
+
[bugx_bin, "--version"],
|
|
2008
|
+
capture_output=True,
|
|
2009
|
+
text=True,
|
|
2010
|
+
timeout=30,
|
|
1767
2011
|
)
|
|
1768
|
-
|
|
1769
|
-
|
|
2012
|
+
if version_proc.returncode != 0 or latest not in (version_proc.stdout or ""):
|
|
2013
|
+
actual = (version_proc.stdout or version_proc.stderr or "").strip()[-300:]
|
|
2014
|
+
record_failure(
|
|
2015
|
+
"npm 安装后版本校验失败",
|
|
2016
|
+
phase="package_install",
|
|
2017
|
+
failure_kind="version_mismatch",
|
|
2018
|
+
expected_version=latest,
|
|
2019
|
+
observed_version=actual,
|
|
2020
|
+
)
|
|
2021
|
+
print(f"[update] npm 安装后版本校验失败:期望 {latest},实际 {actual or '未知'}")
|
|
2022
|
+
return 1
|
|
2023
|
+
installed_version = latest
|
|
2024
|
+
print(f"[update] npm install 成功,已验证 bugx --version ({latest})")
|
|
2025
|
+
else:
|
|
2026
|
+
installed_version = _installed_cli_distribution_version()
|
|
2027
|
+
if installed_version != latest:
|
|
2028
|
+
record_failure(
|
|
2029
|
+
"安装后版本校验失败", phase="package_install",
|
|
2030
|
+
failure_kind="version_mismatch", expected_version=latest,
|
|
2031
|
+
installed_version=installed_version,
|
|
2032
|
+
)
|
|
2033
|
+
print(
|
|
2034
|
+
f"[update] 安装后版本校验失败:期望 {latest},"
|
|
2035
|
+
f"实际 {installed_version or '未知'}"
|
|
2036
|
+
)
|
|
2037
|
+
return 1
|
|
2038
|
+
print(f"[update] pip install 成功,已安装版本 {installed_version}")
|
|
2039
|
+
switched = True
|
|
1770
2040
|
|
|
1771
2041
|
# 更新全局运行时引擎与宿主登记独立;没有 hosts.json 也必须刷新并验证。
|
|
1772
2042
|
try:
|
|
@@ -1846,7 +2116,34 @@ def command_update(args: argparse.Namespace) -> int:
|
|
|
1846
2116
|
return 1
|
|
1847
2117
|
print("[update] 安装验证通过")
|
|
1848
2118
|
|
|
2119
|
+
# 成功也必须留下与本次发布身份绑定的收据;模型文本、进程退出码
|
|
2120
|
+
# 和宿主文件刷新都不能替代这个最终状态证据。
|
|
2121
|
+
last_receipt = _write_update_receipt({
|
|
2122
|
+
"schema_version": 1,
|
|
2123
|
+
"operation_id": operation_id,
|
|
2124
|
+
"started_at_epoch": started_epoch,
|
|
2125
|
+
"finished_at_epoch": time.time(),
|
|
2126
|
+
"current_version": __version__,
|
|
2127
|
+
"installed_version": latest,
|
|
2128
|
+
"client_kind": client_kind,
|
|
2129
|
+
"artifact_kind": artifact_kind,
|
|
2130
|
+
"release_id": release_id,
|
|
2131
|
+
"channel": channel,
|
|
2132
|
+
"phase": "complete",
|
|
2133
|
+
"final_state": "COMPLETE",
|
|
2134
|
+
**_receipt_project_identity(root),
|
|
2135
|
+
})
|
|
2136
|
+
_log_update_event(
|
|
2137
|
+
root, "update_completed", "CLI update completed",
|
|
2138
|
+
phase="complete", duration_ms=round((time.monotonic() - started) * 1000, 1),
|
|
2139
|
+
operation_id=operation_id, final_state="COMPLETE",
|
|
2140
|
+
receipt_path=str(last_receipt or ""), release_id=release_id,
|
|
2141
|
+
target_version=latest,
|
|
2142
|
+
)
|
|
2143
|
+
|
|
1849
2144
|
print(f"\n✓ BugX 已更新到 {latest}")
|
|
2145
|
+
if last_receipt:
|
|
2146
|
+
print(f"[update] 收据: {last_receipt}")
|
|
1850
2147
|
print("请重新运行 bugx 命令以使用新版本。")
|
|
1851
2148
|
return 0
|
|
1852
2149
|
finally:
|
|
@@ -1884,6 +2181,74 @@ SUPERVISOR_PASSTHROUGH_ACTIONS = (
|
|
|
1884
2181
|
+ SUPERVISOR_REPAIR_ACTIONS
|
|
1885
2182
|
+ SUPERVISOR_DECISION_ACTIONS
|
|
1886
2183
|
)
|
|
2184
|
+
SUPERVISOR_COMMANDS = ("install", "status", "rpc", *SUPERVISOR_PASSTHROUGH_ACTIONS)
|
|
2185
|
+
|
|
2186
|
+
|
|
2187
|
+
def forwarded_help(tokens: list[str]) -> bool:
|
|
2188
|
+
"""Recognize help in a forwarded command's option segment."""
|
|
2189
|
+
for token in tokens:
|
|
2190
|
+
if token == "--":
|
|
2191
|
+
return False
|
|
2192
|
+
if token in {"-h", "--help"}:
|
|
2193
|
+
return True
|
|
2194
|
+
return bool(tokens and (tokens[0] == "help" or tokens[1:] == ["help"]))
|
|
2195
|
+
|
|
2196
|
+
|
|
2197
|
+
def _forwarded_root(root: Path | None, tokens: list[str]) -> tuple[Path | None, list[str]]:
|
|
2198
|
+
"""Resolve one wrapper-owned root before any logging or dispatch."""
|
|
2199
|
+
remaining: list[str] = []
|
|
2200
|
+
tokens = list(tokens)
|
|
2201
|
+
if tokens[:1] == ["--"]:
|
|
2202
|
+
tokens.pop(0)
|
|
2203
|
+
index = 0
|
|
2204
|
+
while index < len(tokens):
|
|
2205
|
+
token = tokens[index]
|
|
2206
|
+
if token == "--":
|
|
2207
|
+
remaining.extend(tokens[index:])
|
|
2208
|
+
break
|
|
2209
|
+
if token == "--root" or token.startswith("--root="):
|
|
2210
|
+
if root is not None:
|
|
2211
|
+
raise CliError("重复指定 --root,请保留一个项目路径。")
|
|
2212
|
+
value = token.partition("=")[2]
|
|
2213
|
+
if token == "--root":
|
|
2214
|
+
index += 1
|
|
2215
|
+
value = tokens[index] if index < len(tokens) else ""
|
|
2216
|
+
if value.startswith("-"):
|
|
2217
|
+
value = ""
|
|
2218
|
+
if not value:
|
|
2219
|
+
raise CliError("--root 缺少项目路径。")
|
|
2220
|
+
root = Path(value)
|
|
2221
|
+
else:
|
|
2222
|
+
remaining.append(token)
|
|
2223
|
+
index += 1
|
|
2224
|
+
return root, remaining
|
|
2225
|
+
|
|
2226
|
+
|
|
2227
|
+
def normalize_engine_target(args: argparse.Namespace) -> None:
|
|
2228
|
+
args.root, args.engine_args = _forwarded_root(args.root, args.engine_args)
|
|
2229
|
+
|
|
2230
|
+
|
|
2231
|
+
def normalize_supervisor_target(args: argparse.Namespace) -> None:
|
|
2232
|
+
args.root, args.supervisor_args = _forwarded_root(args.root, args.supervisor_args)
|
|
2233
|
+
if args.supervisor_command in {"install", "status"} and args.supervisor_args:
|
|
2234
|
+
raise CliError(f"supervisor {args.supervisor_command} 只接受 --root;使用 --help 查看用法。")
|
|
2235
|
+
|
|
2236
|
+
|
|
2237
|
+
def supervisor_help(action: str) -> int:
|
|
2238
|
+
if action in {"install", "status"}:
|
|
2239
|
+
parser = argparse.ArgumentParser(
|
|
2240
|
+
prog=f"bugx supervisor {action}",
|
|
2241
|
+
description="写入 OpenCode 的 Supervisor MCP 配置。" if action == "install"
|
|
2242
|
+
else "查看 Supervisor 运行态和宿主配置。",
|
|
2243
|
+
)
|
|
2244
|
+
parser.add_argument("--root", metavar="ROOT", help="项目根目录(默认当前目录)")
|
|
2245
|
+
parser.print_help()
|
|
2246
|
+
return 0
|
|
2247
|
+
root = Path.cwd()
|
|
2248
|
+
return subprocess.call(
|
|
2249
|
+
[sys.executable, str(_script(root, Path("supervisor") / "cli.py")), action, "--help"],
|
|
2250
|
+
cwd=root, env=_python_environment(),
|
|
2251
|
+
)
|
|
1887
2252
|
|
|
1888
2253
|
|
|
1889
2254
|
def _supervisor_recovery_action(root: Path, action: str, forwarded: list[str]) -> int:
|
|
@@ -1917,39 +2282,15 @@ def _supervisor_recovery_action(root: Path, action: str, forwarded: list[str]) -
|
|
|
1917
2282
|
def command_supervisor(args: argparse.Namespace) -> int:
|
|
1918
2283
|
"""canonical supervisor MCP:install(部署/接线)/ status(部署状态)/ rpc(协议回退通道)。"""
|
|
1919
2284
|
forwarded = list(getattr(args, "supervisor_args", []) or [])
|
|
1920
|
-
# ``supervisor_args`` uses argparse.REMAINDER so rpc options can be passed
|
|
1921
|
-
# through. That also captures ``--root`` when it appears after the action
|
|
1922
|
-
# (for example ``supervisor status --root <project>``). Honor that root for
|
|
1923
|
-
# all actions while leaving rpc's argv intact.
|
|
1924
|
-
root = args.root
|
|
1925
|
-
index = 0
|
|
1926
|
-
while index < len(forwarded):
|
|
1927
|
-
item = forwarded[index]
|
|
1928
|
-
if item == "--root":
|
|
1929
|
-
if index + 1 >= len(forwarded) or not forwarded[index + 1]:
|
|
1930
|
-
print("[supervisor] --root 缺少路径", file=sys.stderr)
|
|
1931
|
-
return 2
|
|
1932
|
-
root = Path(forwarded[index + 1])
|
|
1933
|
-
index += 2
|
|
1934
|
-
continue
|
|
1935
|
-
if item.startswith("--root="):
|
|
1936
|
-
value = item.partition("=")[2]
|
|
1937
|
-
if not value:
|
|
1938
|
-
print("[supervisor] --root 缺少路径", file=sys.stderr)
|
|
1939
|
-
return 2
|
|
1940
|
-
root = Path(value)
|
|
1941
|
-
index += 1
|
|
1942
|
-
root = root.expanduser().resolve()
|
|
1943
2285
|
act = args.supervisor_command
|
|
2286
|
+
if forwarded_help(forwarded):
|
|
2287
|
+
return supervisor_help(act)
|
|
2288
|
+
normalize_supervisor_target(args)
|
|
2289
|
+
forwarded = args.supervisor_args
|
|
2290
|
+
root = (args.root or Path.cwd()).expanduser().resolve()
|
|
1944
2291
|
if act == "rpc":
|
|
1945
2292
|
# PE-20261005-003 集成:worker 协议 CLI 回退通道,一问一答直连引擎
|
|
1946
|
-
|
|
1947
|
-
item == "--root" or item.startswith("--root=")
|
|
1948
|
-
for item in forwarded
|
|
1949
|
-
)
|
|
1950
|
-
if not has_forwarded_root:
|
|
1951
|
-
forwarded = ["--root", str(root), *forwarded]
|
|
1952
|
-
return _run_script(root, Path("supervisor") / "cli.py", ["rpc", *forwarded])
|
|
2293
|
+
return _run_script(root, Path("supervisor") / "cli.py", ["rpc", "--root", str(root), *forwarded])
|
|
1953
2294
|
if act == "install":
|
|
1954
2295
|
return _supervisor_deploy(root)
|
|
1955
2296
|
if act == "status":
|
|
@@ -1984,7 +2325,13 @@ def command_engine(args: argparse.Namespace) -> int:
|
|
|
1984
2325
|
the engine so the same command works from Windows, Linux and macOS even
|
|
1985
2326
|
when the global engine and project live on different volumes.
|
|
1986
2327
|
"""
|
|
1987
|
-
|
|
2328
|
+
normalize_engine_target(args)
|
|
2329
|
+
forwarded = args.engine_args or ["status"]
|
|
2330
|
+
help_requested = forwarded_help(forwarded)
|
|
2331
|
+
if help_requested and (forwarded[0] == "path" or forwarded == ["help", "path"]):
|
|
2332
|
+
print("用法:bugx engine --root <项目> path --name <引擎文件>")
|
|
2333
|
+
return 0
|
|
2334
|
+
root = Path.cwd() if help_requested else resolve_project_root(args.root).resolve()
|
|
1988
2335
|
if not root.is_dir():
|
|
1989
2336
|
# 宿主最容易犯的错是把 `--root` 指到拼错的路径 / 还没 clone 的目录。
|
|
1990
2337
|
# 静默让 subprocess 以 cwd 缺失抛 FileNotFoundError 只会产出一条
|
|
@@ -1993,11 +2340,6 @@ def command_engine(args: argparse.Namespace) -> int:
|
|
|
1993
2340
|
f"项目根目录不存在或不是目录:{root};"
|
|
1994
2341
|
"请用 `--root` 指向已初始化的项目目录(或先在该目录执行 `bugx init`)。"
|
|
1995
2342
|
)
|
|
1996
|
-
forwarded = list(getattr(args, "engine_args", []) or [])
|
|
1997
|
-
if forwarded and forwarded[0] == "--":
|
|
1998
|
-
forwarded = forwarded[1:]
|
|
1999
|
-
if not forwarded:
|
|
2000
|
-
forwarded = ["status"]
|
|
2001
2343
|
if forwarded[0] == "path":
|
|
2002
2344
|
if len(forwarded) != 3 or forwarded[1] not in {"--name", "-n"}:
|
|
2003
2345
|
raise CliError("用法:bugx engine --root <项目> path --name <引擎文件>")
|
|
@@ -2434,13 +2776,18 @@ def _parser_for_command_path(parser: argparse.ArgumentParser,
|
|
|
2434
2776
|
command_path: list[str]) -> argparse.ArgumentParser:
|
|
2435
2777
|
"""Return the argparse parser for a top-level or nested command path."""
|
|
2436
2778
|
current = parser
|
|
2437
|
-
for command in command_path:
|
|
2779
|
+
for index, command in enumerate(command_path):
|
|
2438
2780
|
subparsers = next(
|
|
2439
2781
|
(action for action in current._actions
|
|
2440
2782
|
if isinstance(action, argparse._SubParsersAction)),
|
|
2441
2783
|
None,
|
|
2442
2784
|
)
|
|
2443
2785
|
if subparsers is None or command not in subparsers.choices:
|
|
2786
|
+
if subparsers is None and index + 1 == len(command_path) and any(
|
|
2787
|
+
not action.option_strings and action.choices and command in action.choices
|
|
2788
|
+
for action in current._actions
|
|
2789
|
+
):
|
|
2790
|
+
return current
|
|
2444
2791
|
path = " ".join(command_path)
|
|
2445
2792
|
raise CliError(_i18n_exc("system.unknown_help_topic", f"未知的帮助主题:{path}", path=path))
|
|
2446
2793
|
current = subparsers.choices[command]
|
|
@@ -2451,6 +2798,14 @@ def command_help(parser: argparse.ArgumentParser, args: argparse.Namespace) -> i
|
|
|
2451
2798
|
"""Print root or command-specific help without entering command dispatch."""
|
|
2452
2799
|
command_path = list(getattr(args, "help_command", []))
|
|
2453
2800
|
try:
|
|
2801
|
+
if command_path[:1] == ["engine"]:
|
|
2802
|
+
if len(command_path) > 2:
|
|
2803
|
+
parser.error("用法:bugx help engine [COMMAND]")
|
|
2804
|
+
if command_path[1:] == ["path"]:
|
|
2805
|
+
return command_engine(argparse.Namespace(root=None, engine_args=["path", "--help"]))
|
|
2806
|
+
return command_engine(argparse.Namespace(root=None, engine_args=["help", *command_path[1:]]))
|
|
2807
|
+
if len(command_path) == 2 and command_path[0] == "supervisor" and command_path[1] in SUPERVISOR_COMMANDS:
|
|
2808
|
+
return supervisor_help(command_path[1])
|
|
2454
2809
|
target = _parser_for_command_path(parser, command_path)
|
|
2455
2810
|
except CliError as exc:
|
|
2456
2811
|
parser.error(str(exc))
|