bugx-cli 0.1.2 → 0.1.4

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.
Files changed (157) hide show
  1. package/README.md +26 -29
  2. package/core/README.md +5 -3
  3. package/core/agent/agent_orchestrator.py +3 -0
  4. package/core/agent/agent_workspace.py +14 -2
  5. package/core/assets/bugx-wechat-group.png +0 -0
  6. package/core/assets/twitter_promo_art.jpg +0 -0
  7. package/core/assets/twitter_promo_card.svg +166 -0
  8. package/core/assets/twitter_promo_clean.jpg +0 -0
  9. package/core/assets/twitter_terminal_real.png +0 -0
  10. package/core/bugx.md +3 -3
  11. package/core/bugx_paths.py +10 -2
  12. package/core/bundled_docs/OVERVIEW.md +310 -0
  13. package/core/bundled_docs/README.md +10 -0
  14. package/core/bundled_docs/README_EN.md +278 -0
  15. package/core/bundled_docs/ai/01_AI_REFERENCE.md +833 -0
  16. package/core/bundled_docs/ai/02_AI_USAGE.md +161 -0
  17. package/core/bundled_docs/ai/03_AI_COMMANDS.md +322 -0
  18. package/core/bundled_docs/guides/01_USER_GUIDE.md +887 -0
  19. package/core/bundled_docs/guides/02_COMMANDS.md +935 -0
  20. package/core/bundled_docs/guides/03_TROUBLESHOOTING.md +763 -0
  21. package/core/bundled_docs/guides/04_CLOUD_AUTH_AND_SYNC_COOKBOOK.md +48 -0
  22. package/core/bundled_docs/guides/05_HOST_MATRIX_AND_DISPATCH.md +23 -0
  23. package/core/bundled_docs/guides/06_PROBES_AND_POC_COOKBOOK.md +49 -0
  24. package/core/bundled_docs/guides/07_LIFECYCLE_AND_RECOVERY_STATES.md +46 -0
  25. package/core/bundled_docs/guides/08_LESSONS_AND_PRIVACY_BOUNDARY.md +35 -0
  26. package/core/bundled_docs/hosts/bugx-claude_SKILL.md +326 -0
  27. package/core/bundled_docs/hosts/bugx-dsh_SKILL.md +229 -0
  28. package/core/bundled_docs/hosts/bugx-opencode_SKILL.md +129 -0
  29. package/core/bundled_docs/hosts/bugx-zcode_SKILL.md +459 -0
  30. package/core/bundled_docs/hosts/bugx_SKILL.md +118 -0
  31. package/core/bundled_docs/hosts/cline_bugx_SKILL.md +69 -0
  32. package/core/bundled_docs/hosts/platform_bugx_SKILL.md +50 -0
  33. package/core/bundled_docs/manifest.json +140 -0
  34. package/core/bundled_docs/reference/01_ENVIRONMENT_VARIABLES.md +421 -0
  35. package/core/bundled_docs/reference/04_REPOSITORY_TOPOLOGY.md +180 -0
  36. package/core/cli-help.txt +7 -3
  37. package/core/cloud_sync/cloud_client.py +81 -2
  38. package/core/cloud_sync/endpoint_router.py +22 -9
  39. package/core/cloud_sync/issue_uploader.py +297 -0
  40. package/core/cloud_sync/sensitive_filter.py +77 -7
  41. package/core/contracts/AGENT_GUIDE.md +3 -9
  42. package/core/contracts/README.md +1 -1
  43. package/core/contracts/bugx-opencode.md +1 -1
  44. package/core/contracts/bugx-runtime-contract.md +10 -20
  45. package/core/contracts/bugx-worker.md +1 -1
  46. package/core/engine-integrity.json +267 -111
  47. package/core/host_acp/antigravity.py +153 -0
  48. package/core/host_acp/kimi.py +175 -0
  49. package/core/host_acp/minimax.py +28 -0
  50. package/core/host_runtime/adapters.py +5 -1
  51. package/core/host_runtime/antigravity.py +162 -0
  52. package/core/host_runtime/host_bootstrap.py +18 -7
  53. package/core/host_runtime/host_evaluators.py +4 -4
  54. package/core/host_runtime/host_registry.py +25 -4
  55. package/core/host_runtime/mcp_process_tracker.py +30 -3
  56. package/core/host_runtime/mcp_registry_gate.py +34 -11
  57. package/core/hosts/antigravity.py +115 -0
  58. package/core/hosts/codex.py +3 -0
  59. package/core/hosts/dsh.py +43 -24
  60. package/core/hosts/kimi.py +293 -0
  61. package/core/hosts/minimax.py +249 -0
  62. package/core/hosts/zcode.py +5 -0
  63. package/core/i18n.py +94 -5
  64. package/core/infra/README.md +1 -1
  65. package/core/infra/build_info.py +30 -5
  66. package/core/launch_phases/README.md +2 -2
  67. package/core/launch_phases/startup_version_gate.py +2 -2
  68. package/core/launch_phases/supervisor_bridge.py +16 -23
  69. package/core/launch_phases/supervisor_degraded.py +7 -5
  70. package/core/ledger/README.md +1 -1
  71. package/core/locales/en-US.json +3 -3
  72. package/core/locales/zh-CN.json +3 -3
  73. package/core/mcp_runtime_support/environment.py +6 -1
  74. package/core/metadata.txt +2 -2
  75. package/core/planning/README.md +1 -1
  76. package/core/planning/prompt_harness.py +2 -2
  77. package/core/probes/codebase_memory_probe.py +43 -24
  78. package/core/probes/probe_registry.py +10 -7
  79. package/core/prompts/command_routing_en.md +6 -5
  80. package/core/prompts/command_routing_zh.md +6 -5
  81. package/core/repair/rsi_rounds.py +3 -0
  82. package/core/repair/self_heal.py +160 -6
  83. package/core/retrieval/README.md +1 -1
  84. package/core/runtime/README.md +1 -1
  85. package/core/runtime/scenario_eval.py +5 -1
  86. package/core/runtime/setup_ui_env.py +4 -7
  87. package/core/runtime/tool_install_targets.py +12 -2
  88. package/core/skills/README.md +4 -2
  89. package/core/skills/bugx_docs_cloud_sync.py +658 -0
  90. package/core/skills/bugx_docs_mcp_server.py +966 -140
  91. package/core/supervisor/README.md +1 -1
  92. package/core/supervisor/cli.py +2 -2
  93. package/core/supervisor/worker_execution.py +16 -3
  94. package/core/webui/docs_session_service.py +40 -2
  95. package/core/webui/mcp_inspector.py +12 -6
  96. package/core/webui/static/index.html +51 -3
  97. package/core/webui/static/manifest.webmanifest +1 -1
  98. package/core/webui/static/project-settings.js +18 -3
  99. package/core/webui/static/robots.txt +36 -0
  100. package/core/webui/static/sitemap.xml +15 -0
  101. package/docs/07_distribution/01_README_NPM.md +26 -29
  102. package/ecosystem/integrations/cline/skills/bugx/SKILL.md +46 -46
  103. package/ecosystem/integrations/dsh/agents/bugx.md +2 -1
  104. package/ecosystem/integrations/dsh/dsh-patch.yml +2 -2
  105. package/ecosystem/integrations/dsh/mcp/package.json +1 -1
  106. package/ecosystem/integrations/dsh/skills/bugx/SKILL.md +6 -6
  107. package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +1 -1
  108. package/ecosystem/integrations/dsh/ui/package.json +1 -1
  109. package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +2 -2
  110. package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
  111. package/ecosystem/integrations/pi/skills/bugx/SKILL.md +6 -6
  112. package/ecosystem/integrations/qoder/CONNECTORS.md +11 -23
  113. package/ecosystem/integrations/qoder/connector-meta.json +9 -9
  114. package/ecosystem/integrations/workbuddy/connector-meta.json +9 -9
  115. package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +8 -7
  116. package/ecosystem/plugins/bugx/.claude-plugin/marketplace.json +2 -2
  117. package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +2 -2
  118. package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +4 -4
  119. package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +2 -2
  120. package/ecosystem/plugins/bugx/agents/bugx-worker.md +14 -18
  121. package/ecosystem/plugins/bugx/agents/bugx.md +45 -49
  122. package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +8 -8
  123. package/ecosystem/plugins/bugx/skills/bugx-claude/SKILL.md +1 -1
  124. package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +1 -1
  125. package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +1 -1
  126. package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +3 -3
  127. package/interfaces/bin/bugx.js +2 -0
  128. package/interfaces/cli/bugx_cli/__init__.py +2 -2
  129. package/interfaces/cli/bugx_cli/cli.py +153 -8
  130. package/interfaces/cli/bugx_cli/commands/agent.py +568 -136
  131. package/interfaces/cli/bugx_cli/commands/cloud.py +42 -1
  132. package/interfaces/cli/bugx_cli/commands/doctor.py +668 -223
  133. package/interfaces/cli/bugx_cli/commands/guide.py +143 -0
  134. package/interfaces/cli/bugx_cli/commands/issue.py +262 -0
  135. package/interfaces/cli/bugx_cli/commands/lifecycle.py +99 -62
  136. package/interfaces/cli/bugx_cli/commands/plugin.py +301 -60
  137. package/interfaces/cli/bugx_cli/commands/plugin_antigravity.py +350 -0
  138. package/interfaces/cli/bugx_cli/commands/plugin_claude.py +27 -13
  139. package/interfaces/cli/bugx_cli/commands/plugin_kimi.py +440 -0
  140. package/interfaces/cli/bugx_cli/commands/plugin_minimax.py +522 -0
  141. package/interfaces/cli/bugx_cli/commands/plugin_qoder.py +3 -4
  142. package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +4 -5
  143. package/interfaces/cli/bugx_cli/commands/system.py +75 -5
  144. package/interfaces/cli/bugx_cli/common.py +135 -15
  145. package/interfaces/cli/bugx_cli/host_adapters.py +190 -7
  146. package/interfaces/cli/bugx_cli/hosts/registry.py +6 -3
  147. package/interfaces/cli/bugx_cli/hosts/template_engine.py +31 -11
  148. package/interfaces/cli/bugx_cli/infra/__init__.py +4 -0
  149. package/interfaces/cli/bugx_cli/infra/ai_advisor.py +14 -12
  150. package/interfaces/cli/bugx_cli/infra/engine_installer.py +76 -10
  151. package/interfaces/cli/bugx_cli/infra/host_sync.py +66 -1
  152. package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +242 -52
  153. package/package.json +38 -13
  154. package/pyproject.toml +57 -13
  155. package/scripts/sync-version.mjs +1 -1
  156. package/skills/README.md +24 -0
  157. package/skills/platform/bugx/SKILL.md +50 -0
@@ -29,7 +29,9 @@ def _config_candidates(root: Path, adapter: HostAdapter) -> tuple[Path, ...]:
29
29
  return adapter.mcp_config_paths(root)
30
30
 
31
31
 
32
- def _read_mcp_document(path: Path, *, require_nested_mcp: bool = False) -> dict:
32
+ def _read_mcp_document(
33
+ path: Path, *, require_nested_mcp: bool = False, container_key: str | None = None,
34
+ ) -> dict:
33
35
  try:
34
36
  if not path.is_file():
35
37
  return {}
@@ -40,6 +42,9 @@ def _read_mcp_document(path: Path, *, require_nested_mcp: bool = False) -> dict:
40
42
  data = json.loads(path.read_text(encoding="utf-8"))
41
43
  if not isinstance(data, dict):
42
44
  return {}
45
+ if container_key is not None:
46
+ servers = data.get(container_key)
47
+ return servers if isinstance(servers, dict) else {}
43
48
  if require_nested_mcp and {"plugin", "permission", "tools", "agent"}.intersection(data):
44
49
  return {}
45
50
  for key in ("mcp", "mcpServers", "mcp_servers"):
@@ -77,10 +82,13 @@ def _read_mcp_config(root: Path, adapter: HostAdapter) -> dict:
77
82
  for path in _config_candidates(root, adapter):
78
83
  for name, value in _read_mcp_document(
79
84
  path, require_nested_mcp=adapter.name == "opencode",
85
+ container_key=adapter.mcp_config_container,
80
86
  ).items():
81
87
  if isinstance(value, dict):
82
- current = merged.setdefault(name, {})
83
- current.update(value)
88
+ if adapter.merge_mcp_config_fields:
89
+ merged.setdefault(name, {}).update(value)
90
+ else:
91
+ merged[name] = value
84
92
  else:
85
93
  merged[name] = {"value": value}
86
94
  return merged
@@ -507,3 +515,22 @@ def active_mcp_process_probe(
507
515
  }
508
516
 
509
517
 
518
+ def probe_remote_docs_mcp(
519
+ mcp_config: Mapping[str, Mapping[str, object]],
520
+ ) -> dict[str, object]:
521
+ """检查宿主配置中 bugx-docs 是否为远程 HTTP URL 模式,防止误报缺本地 stdio 进程 (NEG-09)。"""
522
+ cfg = mcp_config.get("bugx-docs")
523
+ if not isinstance(cfg, Mapping) or cfg.get("enabled", True) is False:
524
+ return {"configured": False, "transport": "missing"}
525
+ raw_url = str(cfg.get("url") or "").strip()
526
+ if not raw_url:
527
+ cmd = _configured_server_command(cfg)
528
+ return {"configured": bool(cmd), "transport": "stdio", "command": cmd}
529
+ from core.cloud_sync.endpoint_router import validate_base_url
530
+ try:
531
+ normalized = validate_base_url(raw_url.split("?", 1)[0])
532
+ return {"configured": True, "transport": "remote-http", "url": normalized, "healthy": True}
533
+ except ValueError as exc:
534
+ return {"configured": True, "transport": "remote-http", "url": raw_url, "healthy": False, "error": str(exc)}
535
+
536
+
@@ -276,14 +276,17 @@ def mcp_tier(name: str) -> str | None:
276
276
  def host_entry_status(root: Path) -> dict[str, object]:
277
277
  """宿主侧入口(skill/MCP 入口文件)就绪性检查(DOC-236 C7)。
278
278
 
279
- 数据源:``.bugx/hosts.json``(由 ``bugx install`` 写入,含 ``bugx_build_id`` 与逐文件
280
- ``sha256``)。这样引擎侧无需依赖 CLI 层即可判定"宿主入口是否已装配/是否过期"。
279
+ 数据源:``.bugx/hosts.json``(由 ``bugx install`` 写入,含语义版本、
280
+ ``bugx_build_id`` 与逐文件 ``sha256``)。语义版本和入口文件完整性是硬门禁;
281
+ Build ID 只是构建身份,日常递增不能单独判定宿主入口不兼容。
281
282
 
282
283
  只读、不装配;任何异常一律返回 ``ready=False``(fail-closed,绝不谎报就绪)。
283
284
  """
284
285
  import hashlib as _hashlib
285
286
 
286
- result: dict[str, object] = {"ready": False, "reason": "", "hosts": [], "stale_files": []}
287
+ result: dict[str, object] = {
288
+ "ready": False, "reason": "", "hosts": [], "stale_files": [], "warnings": [],
289
+ }
287
290
  try:
288
291
  record_path = Path(root) / ".bugx" / "hosts.json"
289
292
  if record_path.is_symlink() or not record_path.is_file():
@@ -301,19 +304,38 @@ def host_entry_status(root: Path) -> dict[str, object]:
301
304
  result["reason"] = "宿主入口登记为空(尚未安装任何宿主入口)"
302
305
  return result
303
306
 
307
+ from core.infra.build_info import BASE_VERSION
308
+
309
+ recorded_version = payload.get("bugx_version")
310
+ if not isinstance(recorded_version, str) or not recorded_version:
311
+ result["reason"] = "宿主入口登记缺少语义版本,无法验证入口契约"
312
+ return result
313
+ if recorded_version != BASE_VERSION:
314
+ result["reason"] = (
315
+ f"宿主入口为 {recorded_version},当前引擎为 {BASE_VERSION}"
316
+ "(语义版本不一致,宿主入口需重新装配并重启)"
317
+ )
318
+ return result
319
+
304
320
  try:
305
321
  from core.infra.build_info import get_build_id as _get_build_id
306
322
  current_build = _get_build_id()
307
- except Exception: # noqa: BLE001 - 读不到 build id 时不谎报就绪
323
+ except Exception: # noqa: BLE001 - Build 仅作诊断;身份不可读时不据此阻断
308
324
  current_build = None
309
325
  recorded_build = payload.get("bugx_build_id")
310
- if (isinstance(recorded_build, int) and isinstance(current_build, int)
311
- and recorded_build != current_build):
312
- result["reason"] = (
313
- f"宿主入口为 build {recorded_build},当前引擎为 build {current_build}"
314
- "(引擎已更新,宿主入口需重新装配并重启)"
326
+ build_matches = (
327
+ isinstance(recorded_build, int) and not isinstance(recorded_build, bool)
328
+ and isinstance(current_build, int) and not isinstance(current_build, bool)
329
+ and recorded_build == current_build
330
+ )
331
+ result["recorded_build_id"] = recorded_build
332
+ result["current_build_id"] = current_build
333
+ result["build_matches"] = build_matches
334
+ if not build_matches:
335
+ result["warnings"].append(
336
+ f"宿主入口装配于 build {recorded_build},当前引擎为 build {current_build}"
337
+ "(构建身份漂移;入口文件与语义契约一致时不阻断)"
315
338
  )
316
- return result
317
339
 
318
340
  stale: list[str] = []
319
341
  hosts: list[str] = []
@@ -345,7 +367,8 @@ def host_entry_status(root: Path) -> dict[str, object]:
345
367
  result["reason"] = "宿主入口文件缺失或被改动:" + ", ".join(stale[:3])
346
368
  return result
347
369
  result["ready"] = True
348
- result["reason"] = f"宿主入口就绪({', '.join(hosts)};build {recorded_build})"
370
+ build_label = str(recorded_build) if build_matches else f"{recorded_build}→{current_build}"
371
+ result["reason"] = f"宿主入口就绪({', '.join(hosts)};build {build_label})"
349
372
  return result
350
373
 
351
374
 
@@ -0,0 +1,115 @@
1
+ """Google Antigravity desktop and ``agy`` review/worker integration.
2
+
3
+ Antigravity has two separate configuration surfaces: the user-level plugin
4
+ contains the Agent and Skill, while the workspace-level ``.agents`` file is
5
+ the only safe place for BugX's project-bound MCP servers. Keeping those
6
+ surfaces separate is important because plugin stdio children do not reliably
7
+ inherit the active workspace as their current directory.
8
+ """
9
+
10
+ from pathlib import Path
11
+
12
+ from .base import (
13
+ AcpFacet, EngineRunFacet, HostPlugin, IdentityFacet,
14
+ InstallFacet, McpWriteFacet, RunContext, STATUS_READY, WorkerRuntimeFacet,
15
+ )
16
+
17
+
18
+ PLUGIN_DIR = ".gemini/config/plugins/bugx-review"
19
+ MANIFEST = "plugin.json"
20
+ AGENT = "agents/bugx-review.md"
21
+ WORKER_AGENT = "agents/bugx-worker.md"
22
+ SKILL = "skills/bugx-review/SKILL.md"
23
+ MCP = "mcp_config.json"
24
+ LOGO = "assets/bugx-avatar.svg"
25
+ PROJECT_MCP = ".agents/mcp_config.json"
26
+ AGENT_ID = "BugX"
27
+
28
+
29
+ def _headless_argv(context: RunContext) -> list[str]:
30
+ """Build the documented ``agy -p`` headless command.
31
+
32
+ The installed BugX Agent is the stable entry point for this host; callers
33
+ may pass a generic engine agent name, so it is deliberately not forwarded
34
+ to ``agy --agent``.
35
+ """
36
+
37
+ command = [
38
+ "agy", "--agent", AGENT_ID, "--mode", "auto",
39
+ "--add-dir", str(context.root), "--output-format", "json",
40
+ "-p", context.prompt,
41
+ ]
42
+ if context.session:
43
+ command[3:3] = ["--conversation", context.session]
44
+ return command
45
+
46
+
47
+ def _autonomous_argv(context: RunContext) -> list[str]:
48
+ """Build the unattended command with Antigravity's official permission flag."""
49
+
50
+ command = [
51
+ "agy", "--agent", AGENT_ID, "--mode", "auto",
52
+ "--dangerously-skip-permissions", "--add-dir", str(context.root),
53
+ "--output-format", "json", "-p", context.prompt,
54
+ ]
55
+ if context.session:
56
+ command[3:3] = ["--conversation", context.session]
57
+ return command
58
+
59
+
60
+ def _mcp_config_paths(root: Path) -> tuple[Path, ...]:
61
+ """Return the workspace MCP file consumed by Antigravity."""
62
+
63
+ return (root / PROJECT_MCP,)
64
+
65
+
66
+ def _agent_config_path(_root: Path) -> Path:
67
+ return Path.home() / PLUGIN_DIR / AGENT
68
+
69
+
70
+ PLUGIN = HostPlugin(
71
+ identity=IdentityFacet(
72
+ name="antigravity", label="Google Antigravity", order=18, executable="agy",
73
+ # Antigravity 的项目级事实入口是工作区 MCP 文件;插件本体位于用户级
74
+ # ``~/.gemini/config/plugins``,不能拿不存在的项目插件镜像路径做识别 marker。
75
+ markers=(PROJECT_MCP,), aliases=("agy",),
76
+ native_question=False,
77
+ ),
78
+ status=STATUS_READY,
79
+ install=InstallFacet(
80
+ kind="plugin", path=f"{PLUGIN_DIR}/{MANIFEST}", entry_mode="user-registration",
81
+ marker=PROJECT_MCP,
82
+ capabilities=frozenset({
83
+ "user-agent-registration", "user-level-plugin", "native-mcp-config",
84
+ }),
85
+ worker_subagent=True,
86
+ worker_entry_path=WORKER_AGENT,
87
+ interaction={"tool": "Antigravity Agent selector"},
88
+ ),
89
+ engine_run=EngineRunFacet(
90
+ supports_headless=True,
91
+ headless_argv=_headless_argv,
92
+ autonomous_argv=_autonomous_argv,
93
+ mcp_config_paths=_mcp_config_paths,
94
+ agent_config_path=_agent_config_path,
95
+ host_surface="desktop",
96
+ ),
97
+ worker_runtime=WorkerRuntimeFacet(
98
+ mode="serial",
99
+ max_concurrency=1,
100
+ requires_process_mode=True,
101
+ runner_module="host_runtime.antigravity",
102
+ provider_key="antigravity",
103
+ pid_required=True,
104
+ autonomous_cli=True,
105
+ ),
106
+ mcp_write=McpWriteFacet(
107
+ container_key="mcpServers", writer_key="antigravity",
108
+ project_relpath=PROJECT_MCP, custom_writer=False, requires_absolutize=True,
109
+ # ``bugx`` imports the complete CLI before handing off to the engine.
110
+ # Antigravity ACP preloads stdio MCP with a short deadline, so the
111
+ # writer must use the direct global-engine script launcher instead.
112
+ entry_extra={"_bugx_direct_engine_script": True},
113
+ ),
114
+ acp=AcpFacet(plugin="antigravity"),
115
+ )
@@ -374,6 +374,9 @@ def _is_bugx_entry(name: str, spec: Mapping[str, Any]) -> bool:
374
374
  """
375
375
 
376
376
  del name
377
+ raw_url = spec.get("url")
378
+ if isinstance(raw_url, str) and "/api/v1/mcp/docs" in raw_url:
379
+ return True
377
380
  tokens = [str(spec.get("command") or "")]
378
381
  tokens.extend(str(arg) for arg in (spec.get("args") or ()))
379
382
  return any(_BUGX_NAME_PREFIX in token.lower() for token in tokens)
package/core/hosts/dsh.py CHANGED
@@ -96,7 +96,7 @@ def _dsh_home() -> Path:
96
96
  import os
97
97
 
98
98
  configured = os.environ.get("DSH_HOME", "").strip()
99
- return Path(configured) if configured else Path.home() / ".dsh"
99
+ return Path(configured).expanduser() if configured else Path.home() / ".dsh"
100
100
 
101
101
 
102
102
  def _profile_patch_path() -> Path:
@@ -250,18 +250,34 @@ def _uninstall_hint() -> str:
250
250
  )
251
251
 
252
252
 
253
- def _mcp_insert_block(root: Path) -> str:
253
+ def _dynamic_mcp_args(argv: list[str]) -> list[str]:
254
+ """Strip ``--root {ROOT}`` / ``--db {ROOT}/...`` for unbound user-global overlays."""
255
+ out: list[str] = []
256
+ skip_next = False
257
+ for token in argv:
258
+ if skip_next:
259
+ skip_next = False
260
+ continue
261
+ if token == "--root":
262
+ skip_next = True
263
+ continue
264
+ if token == "--db":
265
+ skip_next = True
266
+ continue
267
+ out.append(token)
268
+ return out
269
+
270
+
271
+ def _mcp_insert_block(root: Path | None) -> str:
254
272
  """生成官方 ``dsh-mcp-client`` 的三条 stdio 条目(顶层 ``- insert:``),根绝对化。
255
273
 
256
274
  ``serverName`` 是**必填**且必须唯一(README 的 Config 表);缺它会让
257
- ``loader entries failed to apply``。
258
-
259
- 历史缺陷:这里原本写死 ``--root .``,假设 dsh 以自己的项目目录为 cwd 启动。
260
- 真机不成立——MCP server 由**长驻宿主进程** spawn,cwd 是宿主自己的目录,
261
- ``.`` 于是指向那个目录而不是被审计项目,Supervisor 在错的 ``.bugx`` 上跑并
262
- 报「缺少有效的 .bugx 项目运行布局」。根必须写成绝对路径。
275
+ ``loader entries failed to apply``。当 ``root`` 为 None 或指向用户家目录时,
276
+ 写动态工作区解析参数,禁止把用户根目录写死成 ``--root``。
263
277
  """
264
- root_str = str(Path(root).expanduser().resolve())
278
+ home_resolved = Path.home().resolve()
279
+ resolved_root = Path(root).expanduser().resolve() if root is not None else None
280
+ global_unbound = resolved_root is None or resolved_root == home_resolved
265
281
  lines = [_OVERLAY_MARKER, "- insert:"]
266
282
  for server_name, argv in _MCP_SERVERS:
267
283
  lines.extend([
@@ -273,29 +289,32 @@ def _mcp_insert_block(root: Path) -> str:
273
289
  " command: bugx",
274
290
  " args:",
275
291
  ])
276
- lines.extend(f" - '{token.replace('{ROOT}', root_str)}'" for token in argv)
292
+ if global_unbound:
293
+ for token in _dynamic_mcp_args(argv):
294
+ lines.append(f" - '{token}'")
295
+ else:
296
+ root_str = str(resolved_root)
297
+ lines.extend(f" - '{token.replace('{ROOT}', root_str)}'" for token in argv)
277
298
  return "\n".join(lines) + "\n"
278
299
 
279
300
 
280
- def _bootstrap(root: Path, servers) -> dict:
281
- """把三条 BugX MCP 通道写进用户级 profile patch(幂等、根绝对化)。
282
-
283
- dsh 没有项目级配置层:实测 ``dsh --profile headless --dump-config`` 里项目级
284
- ``.dsh/patch.yml`` 与 ``.dsh/mcp.json`` 零命中,真正被 compose 的是
285
- ``$DSH_HOME/profiles/<profile>/cordis.patch.yml``。
286
-
287
- ``root`` 必须真正参与写入(条目里的 ``--root``/``--db`` 要绝对化到本项目);
288
- 并且这里**不能**用「命中就跳过」的幂等:那会让换了项目的用户永远停留在旧根,
289
- Supervisor 于是继续在错的 ``.bugx`` 上跑。已存在的自有 overlay(以
290
- :data:`_OVERLAY_MARKER` 开头、第二行为顶层 ``- insert:``)由引擎全权拥有,
291
- 直接按本次根重写;他人的块逐字保留。
292
- """
301
+ def _bootstrap(root: Path | None, servers) -> dict:
302
+ """把三条 BugX MCP 通道写进用户级 profile patch(幂等、根绝对化)。"""
293
303
  del servers
294
304
  path = _profile_patch_path()
295
305
  path.parent.mkdir(parents=True, exist_ok=True)
296
306
  existing = path.read_text(encoding="utf-8") if path.is_file() else ""
297
- block = _mcp_insert_block(root)
307
+ home_resolved = Path.home().resolve()
308
+ resolved_root = Path(root).expanduser().resolve() if root is not None else None
309
+ global_unbound = resolved_root is None or resolved_root == home_resolved
298
310
  owned = _owned_overlay_span(existing)
311
+ if global_unbound and owned is not None:
312
+ existing_block = existing[owned[0]:owned[1]]
313
+ home_marker = f"'{home_resolved}'"
314
+ if home_marker not in existing_block and "--root" in existing_block:
315
+ # 用户级安装不覆写已有的具体项目绑定。
316
+ return {"path": str(path), "changed": False, "inserted": False}
317
+ block = _mcp_insert_block(root)
299
318
  if owned is not None:
300
319
  begin, finish = owned
301
320
  if existing[begin:finish].rstrip("\n") == block.rstrip("\n"):
@@ -0,0 +1,293 @@
1
+ #!/usr/bin/env python3
2
+ """core/hosts/kimi.py - Kimi Code CLI 插件(DOC-239 六面架构完整适配)。
3
+
4
+ 事实来源(2026-11-23 实测,Kimi Code 1.4.2 / ``KIMI_CODE_HOME``):
5
+
6
+ * identity ← ``kimi --help``:可执行文件名为 ``kimi``,别名 ``kimi-code`` / ``kimicode``;
7
+ 项目标记为 ``.kimi-code/mcp.json`` 与 ``.kimi-code``。
8
+ * install ← ``subagent`` 入口:``.kimi-code/agents/bugx.md`` 与
9
+ ``.kimi-code/agents/bugx-worker.md``;支持项目级与用户级
10
+ ``~/.kimi-code/skills/`` 及原生 ``mcpServers`` 配置。
11
+ * engine_run ← 无头通道为 ``kimi -p <prompt>``,自治执行为
12
+ ``kimi -p <prompt> --output-format stream-json --auto``;
13
+ 支持自定义 subagent 定义(``--agent`` / ``--agent-file``)。
14
+ * worker_runtime← ``mode="multi"``,支持 CLI 并发调度。
15
+ * mcp_write ← 配置容器键为 ``mcpServers``,项目级作用域为 ``.kimi-code/mcp.json``,
16
+ 全局作用域为 ``<KIMI_CODE_HOME>/mcp.json``(默认 ``~/.kimi-code/mcp.json``)。
17
+ * distribution ← 桌面端插件目录为 ``<KIMI_CODE_HOME>/plugins/managed/<id>``,
18
+ 启用注册表为 ``<KIMI_CODE_HOME>/plugins/installed.json``。
19
+ * acp ← ``kimi acp`` 原生支持标准 JSON-RPC 2.0 ACP 协议,由
20
+ ``core/host_acp/kimi.py`` 以 ``status="ready"`` 声明。
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import os
26
+ import platform
27
+ import shutil
28
+ from pathlib import Path
29
+
30
+ from .base import (
31
+ AcpFacet,
32
+ EngineRunFacet,
33
+ HostPlugin,
34
+ IdentityFacet,
35
+ InstallFacet,
36
+ McpWriteFacet,
37
+ RunContext,
38
+ STATUS_READY,
39
+ WorkerRuntimeFacet,
40
+ )
41
+
42
+ __all__ = ["PLUGIN", "is_available", "run_static_degraded"]
43
+
44
+ _NAME = "kimi"
45
+
46
+ _PROJECT_PATHS: tuple[str, ...] = (
47
+ ".kimi-code/agents/bugx.md",
48
+ ".kimi-code/agents/bugx-worker.md",
49
+ )
50
+
51
+ _CUSTOM_TITLE = "# BugX\n\n这是 BugX 的 Kimi Code 审计智能体入口。"
52
+
53
+ _CUSTOM_PREAMBLE = (
54
+ "先读取全局引擎协议:\n"
55
+ "通过 `bugx engine path --name bugx-runtime-contract.md` 读取全局协议,\n"
56
+ "并遵守其中的寿命、Supervisor、证据和报告协议。\n\n"
57
+ "该入口只把任务交给当前 Kimi Code 会话;BugX CLI 只安装资源,不启动 Kimi Code、不执行审计。\n"
58
+ )
59
+
60
+
61
+ def _kimi_code_home() -> Path:
62
+ configured = os.environ.get("KIMI_CODE_HOME")
63
+ if configured and configured.strip():
64
+ return Path(configured).expanduser()
65
+ return Path.home() / ".kimi-code"
66
+
67
+
68
+ def _resolve_kimi_executable() -> str | None:
69
+ found = shutil.which("kimi")
70
+ if found:
71
+ return found
72
+ bin_dir = _kimi_code_home() / "bin"
73
+ names = ("kimi.exe", "kimi.cmd", "kimi.bat", "kimi") if os.name == "nt" else ("kimi",)
74
+ for name in names:
75
+ fallback = bin_dir / name
76
+ if fallback.is_file():
77
+ return str(fallback)
78
+ return None
79
+
80
+
81
+ def _windows_drive_roots() -> tuple[Path, ...]:
82
+ """返回 Windows 当前可用的逻辑驱动器根目录。"""
83
+ if platform.system() != "Windows":
84
+ return ()
85
+ try:
86
+ import ctypes
87
+
88
+ mask = int(ctypes.windll.kernel32.GetLogicalDrives())
89
+ except (AttributeError, OSError, TypeError, ValueError):
90
+ return ()
91
+ return tuple(
92
+ Path(f"{chr(ord('A') + index)}:/")
93
+ for index in range(26)
94
+ if mask & (1 << index)
95
+ )
96
+
97
+
98
+ def _headless_argv(ctx: RunContext) -> list[str]:
99
+ command = [_resolve_kimi_executable() or "kimi", "-p", ctx.prompt]
100
+ if ctx.session:
101
+ command[1:1] = ["--session", ctx.session]
102
+ if ctx.model:
103
+ command += ["-m", ctx.model]
104
+ return command
105
+
106
+
107
+ def _autonomous_argv(ctx: RunContext) -> list[str]:
108
+ command = [_resolve_kimi_executable() or "kimi"]
109
+ if ctx.session:
110
+ command += ["--session", ctx.session]
111
+ if ctx.model:
112
+ command += ["-m", ctx.model]
113
+ command += [
114
+ "-p",
115
+ ctx.prompt,
116
+ "--output-format",
117
+ "stream-json",
118
+ "--auto",
119
+ ]
120
+ return command
121
+
122
+
123
+ def _mcp_config_paths(root: Path) -> tuple[Path, ...]:
124
+ return (root / ".kimi-code" / "mcp.json",)
125
+
126
+
127
+ def _kimi_app_markers() -> tuple[Path, ...]:
128
+ """Kimi 桌面端已知安装位置。"""
129
+ home = Path.home()
130
+ markers: list[Path] = []
131
+ if platform.system() == "Darwin":
132
+ markers.extend((
133
+ Path("/Applications/Kimi.app"),
134
+ Path("/Applications/Kimi Code.app"),
135
+ home / "Applications" / "Kimi.app",
136
+ home / "Applications" / "Kimi Code.app",
137
+ home / "Library" / "Application Support" / "kimi-desktop",
138
+ home / "Library" / "Application Support" / "Kimi Code",
139
+ ))
140
+ elif os.name != "nt":
141
+ markers.extend((
142
+ home / ".local" / "share" / "applications" / "kimi.desktop",
143
+ home / ".local" / "share" / "applications" / "kimi-code.desktop",
144
+ Path("/usr/bin/kimi-desktop"),
145
+ Path("/usr/bin/kimi-code"),
146
+ Path("/opt/Kimi/kimi"),
147
+ Path("/opt/Kimi Code/kimi-code"),
148
+ ))
149
+
150
+ bases: list[Path] = []
151
+ for variable in (
152
+ "LOCALAPPDATA", "APPDATA", "PROGRAMFILES", "PROGRAMFILES(X86)",
153
+ ):
154
+ value = os.environ.get(variable)
155
+ if value:
156
+ bases.append(Path(value))
157
+ bases.extend(_windows_drive_roots())
158
+ for base in bases:
159
+ markers.extend((
160
+ base / "Kimi" / "Kimi.exe",
161
+ base / "kimi-desktop" / "Kimi.exe",
162
+ base / "Kimi Code" / "Kimi Code.exe",
163
+ base / "Programs" / "Kimi" / "Kimi.exe",
164
+ base / "Programs" / "kimi-desktop" / "Kimi.exe",
165
+ base / "Programs" / "Kimi Code" / "Kimi Code.exe",
166
+ base / "Program Files" / "Kimi Code" / "Kimi Code.exe",
167
+ base / "Program Files (x86)" / "Kimi Code" / "Kimi Code.exe",
168
+ ))
169
+ return tuple(markers)
170
+
171
+
172
+ def _agent_config_path(root: Path) -> Path:
173
+ return root / ".kimi-code"
174
+
175
+
176
+ PLUGIN = HostPlugin(
177
+ identity=IdentityFacet(
178
+ name=_NAME,
179
+ label="Kimi Code",
180
+ order=14,
181
+ executable="kimi",
182
+ markers=(".kimi-code/mcp.json", ".kimi-code"),
183
+ aliases=("kimi-code", "kimicode"),
184
+ app_markers=_kimi_app_markers,
185
+ native_question=True,
186
+ ),
187
+ status=STATUS_READY,
188
+ install=InstallFacet(
189
+ kind="subagent",
190
+ path=".kimi-code/agents/bugx.md",
191
+ marker=".kimi-code",
192
+ required_paths=_PROJECT_PATHS,
193
+ capabilities=frozenset(
194
+ {
195
+ "native-mcp-config",
196
+ "extra-tracked-paths",
197
+ "skills",
198
+ "user-agent-registration",
199
+ }
200
+ ),
201
+ interaction={
202
+ "tool": "AskUserQuestion",
203
+ "single_select": "multiSelect=false",
204
+ "multi_select": "tooling:batch 时使用 multiSelect=true",
205
+ },
206
+ tools_line="Bash, Read, Grep, Glob, Edit, Write",
207
+ mcp_relpaths=(".kimi-code/mcp.json",),
208
+ worker_subagent=True,
209
+ worker_entry_path=".kimi-code/agents/bugx-worker.md",
210
+ custom_title=_CUSTOM_TITLE,
211
+ custom_preamble=_CUSTOM_PREAMBLE,
212
+ generated_dirs=(".kimi-code",),
213
+ sweepable=True,
214
+ ),
215
+ engine_run=EngineRunFacet(
216
+ supports_headless=True,
217
+ headless_argv=_headless_argv,
218
+ autonomous_argv=_autonomous_argv,
219
+ mcp_config_paths=_mcp_config_paths,
220
+ agent_config_path=_agent_config_path,
221
+ mcp_health=None,
222
+ host_surface="tui",
223
+ recon_scout_argv=lambda _root, text, _prompt_file, _inventory=None: [
224
+ _resolve_kimi_executable() or "kimi",
225
+ "-p",
226
+ text,
227
+ "--output-format",
228
+ "text",
229
+ "--auto",
230
+ ],
231
+ native_task=True,
232
+ ),
233
+ worker_runtime=WorkerRuntimeFacet(
234
+ mode="multi",
235
+ max_concurrency=None,
236
+ requires_process_mode=False,
237
+ sandbox_sync=(),
238
+ ),
239
+ mcp_write=McpWriteFacet(
240
+ container_key="mcpServers",
241
+ writer_key=_NAME,
242
+ project_relpath=".kimi-code/mcp.json",
243
+ global_scope="~/.kimi-code/mcp.json",
244
+ mirror_relpaths=(),
245
+ requires_absolutize=True,
246
+ entry_extra={},
247
+ ),
248
+ acp=AcpFacet(plugin=_NAME),
249
+ )
250
+
251
+
252
+ def is_available() -> tuple[bool, str]:
253
+ """降级契约:机械探活 Kimi Code CLI 是否安装(零子进程)。"""
254
+ path = _resolve_kimi_executable()
255
+ if path is None:
256
+ return False, "kimi 可执行文件未安装;headless(kimi -p)与 ACP(kimi acp)通道不可用"
257
+ return True, path
258
+
259
+
260
+ def run_static_degraded(root: Path | None = None) -> dict:
261
+ """Kimi Code CLI 缺失时的静态降级输出:只声明插件事实,绝不伪装宿主健康。"""
262
+ available, availability_detail = is_available()
263
+ return {
264
+ "plugin": _NAME,
265
+ "schema_version": 1,
266
+ "success": available,
267
+ "status": "degraded",
268
+ "degraded": True,
269
+ "degraded_reason": (
270
+ "static_facts_only" if available else "kimi_cli_not_installed"
271
+ ),
272
+ "probe_mode": "static_degraded",
273
+ "headless_available": available,
274
+ "native_task_available": bool(available and PLUGIN.engine_run.native_task),
275
+ "identity": {
276
+ "executable": PLUGIN.identity.executable,
277
+ "aliases": list(PLUGIN.identity.aliases),
278
+ "markers": list(PLUGIN.identity.markers),
279
+ },
280
+ "agent_entry": PLUGIN.install.path,
281
+ "mcp_project_relpath": PLUGIN.mcp_write.project_relpath,
282
+ "mcp_global_scope": PLUGIN.mcp_write.global_scope,
283
+ "findings": [],
284
+ "evidence": {
285
+ "availability_detail": availability_detail,
286
+ "project_root": str(root) if root else None,
287
+ },
288
+ "metadata": {
289
+ "degraded_mode": "static_plugin_facts_only",
290
+ "acp": "ready(kimi acp 原生支持标准 ACP,见 core/host_acp/kimi.py)",
291
+ "fallback": "宿主 CLI 缺失时由外层宿主/用户决策接管;BugX 不代装宿主 CLI",
292
+ },
293
+ }