@sakanano-moe/agenthelm 6.8.0 → 6.11.0-rc.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 +1 -1
- package/README.zh-CN.md +2 -0
- package/package.json +1 -1
- package/runtime/index.json +6 -6
- package/runtime/plugins/agent-pack/.codex-plugin/plugin.json +1 -1
- package/runtime/plugins/agent-pack/hooks/hooks.json +32 -0
- package/runtime/plugins/agent-pack/plugin.json +1 -1
- package/runtime/plugins/agent-pack/references/local-only.md +126 -0
- package/runtime/plugins/agent-pack/references/nudge.en.md +58 -0
- package/runtime/plugins/agent-pack/references/nudge.md +58 -0
- package/runtime/plugins/agent-pack/runtime/agent_pack_nudge.py +613 -0
- package/runtime/plugins/agent-pack/runtime/agenthelm.py +1271 -221
- package/runtime/plugins/agent-pack/runtime/agenthelm_runtime.py +114 -65
- package/runtime/plugins/agent-pack/runtime/i18n_agent_pack.py +78 -0
- package/runtime/plugins/agent-pack/runtime/local_only.py +1132 -0
- package/runtime/plugins/agent-pack/runtime/locale/en.json +569 -0
- package/runtime/plugins/agent-pack/runtime/mcp_server.py +25 -0
- package/runtime/plugins/agent-pack/runtime/nudge_text.py +127 -0
- package/runtime/plugins/agent-pack/runtime/user_settings.py +275 -0
- package/runtime/plugins/agent-pack/skills/agent-pack/SKILL.md +11 -1
- package/runtime/plugins/agents-init/.codex-plugin/plugin.json +1 -1
- package/runtime/plugins/agents-init/content.json +4 -4
- package/runtime/plugins/agents-init/plugin.json +1 -1
- package/runtime/plugins/agents-init/skills/agents-init/AGENT.template.md +141 -5
- package/runtime/plugins/agents-init/skills/agents-init/SKILL.md +41 -8
- package/runtime/plugins/agents-init/skills/agents-init/project.schema.json +408 -80
- package/runtime/plugins/agents-init/skills/agents-init/scripts/adopt.py +615 -0
- package/runtime/plugins/agents-init/skills/agents-init/scripts/baseline.py +221 -0
- package/runtime/plugins/agents-init/skills/agents-init/scripts/i18n_init.py +78 -0
- package/runtime/plugins/agents-init/skills/agents-init/scripts/init_project.py +748 -159
- package/runtime/plugins/agents-init/skills/agents-init/scripts/locale/en.json +289 -0
- package/runtime/plugins/agents-init/skills/agents-init/scripts/merge3.py +149 -0
- package/runtime/plugins/agents-init/skills/agents-init/scripts/regions.py +99 -0
- package/runtime/plugins/agents-init/skills/agents-init/scripts/scaffold.py +594 -90
- package/runtime/plugins/agents-init/skills/agents-init/skeleton.json +2 -0
- package/runtime/plugins/agents-init/skills/agents-init/skill.json +1 -1
- package/runtime/plugins/opinion-manager/.codex-plugin/plugin.json +1 -1
- package/runtime/plugins/opinion-manager/plugin.json +1 -1
- package/runtime/plugins/opinion-manager/references/inbox.en.md +48 -0
- package/runtime/plugins/opinion-manager/references/inbox.md +48 -0
- package/runtime/plugins/opinion-manager/runtime/context.py +31 -26
- package/runtime/plugins/opinion-manager/runtime/i18n_opinion.py +78 -0
- package/runtime/plugins/opinion-manager/runtime/inbox.py +398 -0
- package/runtime/plugins/opinion-manager/runtime/inbox_text.py +114 -0
- package/runtime/plugins/opinion-manager/runtime/lifecycle.py +45 -44
- package/runtime/plugins/opinion-manager/runtime/locale/en.json +193 -0
- package/runtime/plugins/opinion-manager/runtime/opinion_manager.py +55 -50
- package/runtime/plugins/opinion-manager/runtime/versioned.py +90 -85
- package/runtime/plugins/opinion-manager/skills/opinion-manager/SKILL.md +15 -2
- package/runtime/plugins/project-orchestrator/.codex-plugin/plugin.json +1 -1
- package/runtime/plugins/project-orchestrator/content.json +30 -3
- package/runtime/plugins/project-orchestrator/plugin.json +1 -1
- package/runtime/plugins/project-orchestrator/references/case-workspaces.md +9 -1
- package/runtime/plugins/project-orchestrator/references/case.schema.json +1 -0
- package/runtime/plugins/project-orchestrator/references/sop-interview.md +83 -0
- package/runtime/plugins/project-orchestrator/references/sop.md +156 -0
- package/runtime/plugins/project-orchestrator/runtime/assets.py +52 -57
- package/runtime/plugins/project-orchestrator/runtime/case.py +139 -80
- package/runtime/plugins/project-orchestrator/runtime/case_structure.py +71 -0
- package/runtime/plugins/project-orchestrator/runtime/case_workspace.py +47 -46
- package/runtime/plugins/project-orchestrator/runtime/i18n_orchestrator.py +78 -0
- package/runtime/plugins/project-orchestrator/runtime/locale/en.json +1450 -0
- package/runtime/plugins/project-orchestrator/runtime/memory.py +45 -45
- package/runtime/plugins/project-orchestrator/runtime/private_paths.py +119 -0
- package/runtime/plugins/project-orchestrator/runtime/project_base.py +37 -19
- package/runtime/plugins/project-orchestrator/runtime/project_cli.py +307 -195
- package/runtime/plugins/project-orchestrator/runtime/project_demo.py +130 -48
- package/runtime/plugins/project-orchestrator/runtime/project_maintain.py +328 -221
- package/runtime/plugins/project-orchestrator/runtime/project_menu.py +167 -89
- package/runtime/plugins/project-orchestrator/runtime/project_real.py +187 -105
- package/runtime/plugins/project-orchestrator/runtime/project_write.py +58 -55
- package/runtime/plugins/project-orchestrator/runtime/sop.py +1670 -0
- package/runtime/plugins/project-orchestrator/runtime/sop_structure.py +226 -0
- package/runtime/plugins/project-orchestrator/runtime/wf.py +74 -70
- package/runtime/plugins/project-orchestrator/skills/project-orchestrator/SKILL.md +22 -0
- package/runtime/plugins/project-orchestrator/sop-templates/blank/SOP.en.md +57 -0
- package/runtime/plugins/project-orchestrator/sop-templates/blank/SOP.md +57 -0
- package/runtime/plugins/project-orchestrator/sop-templates/knowledge-digest/SOP.en.md +77 -0
- package/runtime/plugins/project-orchestrator/sop-templates/knowledge-digest/SOP.md +77 -0
- package/runtime/plugins/project-orchestrator/sop-templates/knowledge-digest/templates/digest.en.md +11 -0
- package/runtime/plugins/project-orchestrator/sop-templates/knowledge-digest/templates/digest.md +11 -0
- package/runtime/plugins/project-orchestrator/sop-templates/video-to-transcript/SOP.en.md +87 -0
- package/runtime/plugins/project-orchestrator/sop-templates/video-to-transcript/SOP.md +87 -0
- package/runtime/plugins/project-orchestrator/sop-templates/weekly-review/SOP.en.md +75 -0
- package/runtime/plugins/project-orchestrator/sop-templates/weekly-review/SOP.md +75 -0
- package/runtime/plugins/project-orchestrator/sop-templates/weekly-review/templates/review.en.md +11 -0
- package/runtime/plugins/project-orchestrator/sop-templates/weekly-review/templates/review.md +12 -0
- package/runtime/plugins/project-orchestrator/templates/CASE.en.md +39 -0
- package/runtime/plugins/agents-init/skills/agents-init/scripts/test_init_project.py +0 -678
- package/runtime/plugins/agents-init/skills/agents-init/scripts/test_scaffold.py +0 -551
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"""agenthelm:在 Claude Code、Codex、Cursor 间安装、检查与更新 agenthelm 插件。
|
|
3
3
|
|
|
4
4
|
``project`` 打开不需要 AI Agent 的项目自助入口(由 project-orchestrator 实现);``runtime``
|
|
5
|
-
|
|
5
|
+
管理用户级运行时;``nudge`` 是各客户端 hook 调用的观点候选采集与未决事项提示(见 references/nudge.md)。``check`` 只读:比较各客户端已安装的插件版本、项目里由模板渲染的文件,
|
|
6
6
|
以及 Opinion 来源与云端 ``latest.json``。``install``、``update``、``migrate``
|
|
7
7
|
默认只预览,``--apply`` 才执行。通过 ``npx @sakanano-moe/agenthelm <命令>`` 或
|
|
8
8
|
``python3 <agent-pack>/runtime/agenthelm.py <命令>`` 运行。``--hook`` 供会话开始时静默调用:
|
|
@@ -28,6 +28,7 @@ from dataclasses import dataclass, field
|
|
|
28
28
|
from datetime import UTC, datetime
|
|
29
29
|
from pathlib import Path
|
|
30
30
|
from typing import Any
|
|
31
|
+
from i18n_agent_pack import _, N_ # noqa: E402
|
|
31
32
|
|
|
32
33
|
MARKETPLACE = "agenthelm"
|
|
33
34
|
CLI = "npx @sakanano-moe/agenthelm"
|
|
@@ -52,6 +53,10 @@ class CheckError(Exception):
|
|
|
52
53
|
pass
|
|
53
54
|
|
|
54
55
|
|
|
56
|
+
class Unavailable(CheckError):
|
|
57
|
+
"""A client cannot be handled on this run for a reason outside the update itself (not a failed update)."""
|
|
58
|
+
|
|
59
|
+
|
|
55
60
|
def version_key(value: str) -> tuple[int, ...] | None:
|
|
56
61
|
match = re.fullmatch(r"(\d+)\.(\d+)\.(\d+)(?:[-+].*)?", value or "")
|
|
57
62
|
return tuple(int(part) for part in match.groups()) if match else None
|
|
@@ -67,6 +72,8 @@ def read_json(path: Path) -> Any:
|
|
|
67
72
|
|
|
68
73
|
|
|
69
74
|
def write_json_atomic(path: Path, data: Any) -> None:
|
|
75
|
+
# A symlinked dotfile (hooks.json, settings.json) keeps being a symlink: write to its target, temp file beside it.
|
|
76
|
+
path = Path(os.path.realpath(path))
|
|
70
77
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
71
78
|
temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp")
|
|
72
79
|
temporary.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
@@ -160,28 +167,42 @@ def _fetch(url: str, timeout: float = FETCH_TIMEOUT_SECONDS) -> dict:
|
|
|
160
167
|
def load_latest(env: Env, source: str | None = None, *, offline: bool = False,
|
|
161
168
|
max_age: int = CACHE_TTL_SECONDS, timeout: float = FETCH_TIMEOUT_SECONDS,
|
|
162
169
|
backoff: bool = False) -> tuple[dict, dict]:
|
|
163
|
-
"""Return (latest, origin). A local path is read directly; URLs go through a daily cache.
|
|
170
|
+
"""Return (latest, origin). A local path is read directly; URLs go through a daily cache.
|
|
171
|
+
|
|
172
|
+
The cache is used only when it came from one of the sources this call would fetch: an explicit
|
|
173
|
+
``--latest`` / ``AGENTHELM_LATEST_URL`` that differs from the cached source ignores the cache (and the
|
|
174
|
+
origin says so), it is never answered with another source's content.
|
|
175
|
+
"""
|
|
164
176
|
source = source or env.get(ENV_LATEST)
|
|
165
177
|
if source and not re.match(r"https?://", source):
|
|
166
178
|
return read_json(Path(source).expanduser()), {"source": source, "cached": False}
|
|
167
179
|
urls = (source,) if source else DEFAULT_LATEST_URLS
|
|
168
180
|
cache_file = env.cache_dir / "latest.json"
|
|
169
181
|
cached = None
|
|
182
|
+
ignored_cache = None
|
|
170
183
|
try:
|
|
171
184
|
cached = read_json(cache_file)
|
|
172
185
|
except (OSError, ValueError):
|
|
173
186
|
pass
|
|
187
|
+
if not isinstance(cached, dict) or "latest" not in cached:
|
|
188
|
+
cached = None
|
|
189
|
+
if cached and cached.get("url") not in urls:
|
|
190
|
+
ignored_cache, cached = cached.get("url"), None
|
|
191
|
+
extra = {"ignored_cache": ignored_cache} if ignored_cache else {}
|
|
174
192
|
if cached and (offline or time.time() - cached.get("fetched_at", 0) < max_age):
|
|
175
193
|
return cached["latest"], {"source": cached.get("url"), "cached": True, "fetched_at": cached.get("fetched_at")}
|
|
176
194
|
if offline:
|
|
177
|
-
|
|
195
|
+
if ignored_cache:
|
|
196
|
+
raise CheckError(_("离线,且缓存来自另一个来源({0}),不能代替 {1}").format(ignored_cache, urls[0]))
|
|
197
|
+
raise CheckError(_("离线且没有缓存的 latest.json"))
|
|
178
198
|
failure_file = env.cache_dir / "last_failure.json"
|
|
179
199
|
if backoff:
|
|
180
200
|
try:
|
|
181
201
|
if time.time() - read_json(failure_file).get("at", 0) < FAILURE_BACKOFF_SECONDS:
|
|
182
202
|
if cached:
|
|
183
|
-
return cached["latest"], {"source": cached.get("url"), "cached": True, "stale": True
|
|
184
|
-
|
|
203
|
+
return cached["latest"], {"source": cached.get("url"), "cached": True, "stale": True,
|
|
204
|
+
"fetched_at": cached.get("fetched_at")}
|
|
205
|
+
raise CheckError(_("最近联网失败,稍后再试"))
|
|
185
206
|
except (OSError, ValueError, AttributeError):
|
|
186
207
|
pass
|
|
187
208
|
errors = []
|
|
@@ -195,7 +216,7 @@ def load_latest(env: Env, source: str | None = None, *, offline: bool = False,
|
|
|
195
216
|
write_json_atomic(cache_file, {"url": url, "fetched_at": time.time(), "latest": latest})
|
|
196
217
|
except OSError:
|
|
197
218
|
pass
|
|
198
|
-
return latest, {"source": url, "cached": False}
|
|
219
|
+
return latest, {"source": url, "cached": False, **extra}
|
|
199
220
|
try:
|
|
200
221
|
write_json_atomic(failure_file, {"at": time.time()})
|
|
201
222
|
except OSError:
|
|
@@ -203,7 +224,20 @@ def load_latest(env: Env, source: str | None = None, *, offline: bool = False,
|
|
|
203
224
|
if cached:
|
|
204
225
|
return cached["latest"], {"source": cached.get("url"), "cached": True, "stale": True,
|
|
205
226
|
"fetched_at": cached.get("fetched_at")}
|
|
206
|
-
raise CheckError("无法获取 latest.json:" + "; ".join(errors))
|
|
227
|
+
raise CheckError(_("无法获取 latest.json:") + "; ".join(errors))
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def origin_line(origin: dict) -> str:
|
|
231
|
+
"""The version source a run actually used, and whether it came from the cache."""
|
|
232
|
+
line = _("云端版本源:{0}").format(origin.get("source"))
|
|
233
|
+
if origin.get("cached"):
|
|
234
|
+
when = ""
|
|
235
|
+
if origin.get("fetched_at"):
|
|
236
|
+
when = _(",获取于 {0}").format(datetime.fromtimestamp(origin["fetched_at"], UTC).strftime("%Y-%m-%d %H:%M UTC"))
|
|
237
|
+
line += (_("(缓存,已过期,联网失败{0})") if origin.get("stale") else _("(缓存{0})")).format(when)
|
|
238
|
+
if origin.get("ignored_cache"):
|
|
239
|
+
line += _("(已忽略来自 {0} 的缓存)").format(origin["ignored_cache"])
|
|
240
|
+
return line
|
|
207
241
|
|
|
208
242
|
|
|
209
243
|
# ---------------------------------------------------------------- installed plugins
|
|
@@ -215,49 +249,152 @@ def _manifest_version(path: Path) -> str | None:
|
|
|
215
249
|
return None
|
|
216
250
|
|
|
217
251
|
|
|
218
|
-
def
|
|
219
|
-
found: list[dict] = []
|
|
252
|
+
def _claude_records(env: Env) -> dict:
|
|
220
253
|
try:
|
|
221
254
|
record = read_json(env.claude_dir / "plugins" / "installed_plugins.json").get("plugins", {})
|
|
222
255
|
except (OSError, ValueError, AttributeError):
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
256
|
+
return {}
|
|
257
|
+
return record if isinstance(record, dict) else {}
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _local_directory_marketplace(env: Env) -> bool:
|
|
261
|
+
"""True when Claude Code's own record says the ``agenthelm`` marketplace comes from a local directory or file.
|
|
262
|
+
|
|
263
|
+
Unverified against a real client: this relies on ``plugins/known_marketplaces.json`` keeping a ``source`` object
|
|
264
|
+
whose ``source`` field is ``directory`` or ``file`` for such marketplaces."""
|
|
265
|
+
try:
|
|
266
|
+
record = read_json(env.claude_dir / "plugins" / "known_marketplaces.json")[MARKETPLACE]
|
|
267
|
+
return str(record["source"]["source"]) in {"directory", "file"}
|
|
268
|
+
except (OSError, ValueError, KeyError, TypeError, AttributeError):
|
|
269
|
+
return False
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _dev_reason(path: Path, *, local_marketplace: bool = False) -> str | None:
|
|
273
|
+
"""Why an install under the ``agenthelm`` marketplace is a development install (None: it is a normal one)."""
|
|
274
|
+
if path.is_symlink():
|
|
275
|
+
return "symlink"
|
|
276
|
+
if local_marketplace:
|
|
277
|
+
return "local-directory-marketplace"
|
|
278
|
+
return None
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def installed_plugins(env: Env, names: set[str]) -> list[dict]:
|
|
282
|
+
"""Installs the ``agenthelm`` marketplace manages. A symlinked install, or one from a local-directory marketplace,
|
|
283
|
+
carries ``dev`` (the reason): it is reported and left alone. Installs from other marketplaces: see ``other_installs``."""
|
|
284
|
+
found: list[dict] = []
|
|
285
|
+
local_marketplace = _local_directory_marketplace(env)
|
|
286
|
+
for key, entries in sorted(_claude_records(env).items()):
|
|
287
|
+
plugin, _sep, market = key.partition("@")
|
|
288
|
+
if market != MARKETPLACE or plugin not in names or not isinstance(entries, list):
|
|
227
289
|
continue
|
|
228
290
|
for entry in entries:
|
|
229
291
|
path = Path(str(entry.get("installPath", "")))
|
|
230
292
|
# A git-SHA version means the entry had no version; fall back to the manifest.
|
|
231
293
|
version = entry.get("version") if version_key(str(entry.get("version"))) else _manifest_version(path)
|
|
232
|
-
|
|
233
|
-
|
|
294
|
+
item = {"client": "claude", "plugin": plugin, "version": version, "path": str(path),
|
|
295
|
+
"scope": entry.get("scope")}
|
|
296
|
+
dev = _dev_reason(path, local_marketplace=local_marketplace)
|
|
297
|
+
if dev:
|
|
298
|
+
item["dev"] = dev
|
|
299
|
+
found.append(item)
|
|
234
300
|
codex_cache = env.codex_dir / "plugins" / "cache" / MARKETPLACE
|
|
235
301
|
for plugin in sorted(names):
|
|
236
302
|
directories = [path for path in (codex_cache / plugin).glob("*") if (path / "plugin.json").is_file()]
|
|
237
303
|
if directories:
|
|
238
304
|
newest = max(directories, key=lambda path: version_key(path.name) or (0,))
|
|
239
|
-
|
|
240
|
-
|
|
305
|
+
item = {"client": "codex", "plugin": plugin, "version": _manifest_version(newest), "path": str(newest)}
|
|
306
|
+
if _dev_reason(newest) or _dev_reason(codex_cache / plugin):
|
|
307
|
+
item["dev"] = "symlink"
|
|
308
|
+
found.append(item)
|
|
241
309
|
for client, base in (("cursor", env.home / ".cursor" / "plugins" / "local"),
|
|
242
310
|
("legacy", env.home / ".agents" / "plugins" / "plugins"),
|
|
243
311
|
("legacy", env.home / ".claude" / "agent-pack" / "plugins")):
|
|
244
312
|
for plugin in sorted(names):
|
|
245
313
|
path = base / plugin
|
|
246
314
|
if (path / "plugin.json").is_file():
|
|
247
|
-
|
|
248
|
-
|
|
315
|
+
item = {"client": client, "plugin": plugin, "version": _manifest_version(path), "path": str(path)}
|
|
316
|
+
# A symlinked Cursor entry points at a working copy; a real directory is what `install` writes.
|
|
317
|
+
if client == "cursor" and path.is_symlink():
|
|
318
|
+
item["dev"] = "symlink"
|
|
319
|
+
found.append(item)
|
|
320
|
+
return found
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def legacy_owner(env: Env, item: dict) -> str | None:
|
|
324
|
+
"""The client a legacy (pre-marketplace) entry belongs to, judged from its recorded path; None when unknown.
|
|
325
|
+
|
|
326
|
+
``~/.claude/...`` is Claude Code's; ``~/.agents/...`` is the Codex personal marketplace the old bootstrap wrote
|
|
327
|
+
(``[plugins."<name>@personal"]`` in Codex's config). Anything else, or a path that cannot be read, has no owner.
|
|
328
|
+
"""
|
|
329
|
+
try:
|
|
330
|
+
path = Path(str(item.get("path", ""))).expanduser().resolve()
|
|
331
|
+
roots = {"claude": [env.home / ".claude", env.claude_dir], "codex": [env.home / ".agents", env.codex_dir]}
|
|
332
|
+
for client, candidates in roots.items():
|
|
333
|
+
if any(path == root.resolve() or root.resolve() in path.parents for root in candidates):
|
|
334
|
+
return client
|
|
335
|
+
except (OSError, RuntimeError, ValueError):
|
|
336
|
+
pass
|
|
337
|
+
return None
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def other_installs(env: Env, names: set[str]) -> list[dict]:
|
|
341
|
+
"""Installs of agenthelm plugins that no ``agenthelm`` marketplace manages: another marketplace name (a fork, a
|
|
342
|
+
local-directory marketplace under its own name). Not found here: a Claude Code ``--plugin-dir`` session (it
|
|
343
|
+
leaves no record we know of — unverified) and how Codex / Cursor record local development installs (unverified)."""
|
|
344
|
+
found: list[dict] = []
|
|
345
|
+
for key, entries in sorted(_claude_records(env).items()):
|
|
346
|
+
plugin, _sep, market = key.partition("@")
|
|
347
|
+
if not market or market == MARKETPLACE or plugin not in names or not isinstance(entries, list):
|
|
348
|
+
continue
|
|
349
|
+
for entry in entries:
|
|
350
|
+
path = Path(str(entry.get("installPath", "")))
|
|
351
|
+
version = entry.get("version") if version_key(str(entry.get("version"))) else _manifest_version(path)
|
|
352
|
+
found.append({"client": "claude", "plugin": plugin, "version": version, "path": str(path),
|
|
353
|
+
"scope": entry.get("scope"), "marketplace": market, "dev": "other-marketplace"})
|
|
354
|
+
codex_cache = env.codex_dir / "plugins" / "cache"
|
|
355
|
+
for market_dir in sorted(path for path in codex_cache.glob("*") if path.is_dir()) if codex_cache.is_dir() else []:
|
|
356
|
+
if market_dir.name in {MARKETPLACE, "personal"}: # "personal" is the legacy bootstrap, handled as legacy
|
|
357
|
+
continue
|
|
358
|
+
for plugin in sorted(names):
|
|
359
|
+
directories = [path for path in (market_dir / plugin).glob("*") if (path / "plugin.json").is_file()]
|
|
360
|
+
if directories:
|
|
361
|
+
newest = max(directories, key=lambda path: version_key(path.name) or (0,))
|
|
362
|
+
found.append({"client": "codex", "plugin": plugin, "version": _manifest_version(newest),
|
|
363
|
+
"path": str(newest), "marketplace": market_dir.name, "dev": "other-marketplace"})
|
|
364
|
+
return found
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def declared_marketplaces(env: Env, project: Path | None) -> list[dict]:
|
|
368
|
+
"""The ``extraKnownMarketplaces.agenthelm`` declarations in Claude Code's user and project settings files.
|
|
369
|
+
The tool only reads them; it never edits a settings file."""
|
|
370
|
+
files = [("user", env.claude_dir / "settings.json")]
|
|
371
|
+
if project is not None:
|
|
372
|
+
files += [("project", project / ".claude" / "settings.json"), ("local", project / ".claude" / "settings.local.json")]
|
|
373
|
+
found = []
|
|
374
|
+
for scope, path in files:
|
|
375
|
+
try:
|
|
376
|
+
declared = read_json(path).get("extraKnownMarketplaces", {}).get(MARKETPLACE)
|
|
377
|
+
except (OSError, ValueError, AttributeError):
|
|
378
|
+
continue
|
|
379
|
+
if declared is not None:
|
|
380
|
+
found.append({"scope": scope, "file": str(path),
|
|
381
|
+
"source": declared.get("source") if isinstance(declared, dict) and "source" in declared and isinstance(declared.get("source"), dict) else declared})
|
|
249
382
|
return found
|
|
250
383
|
|
|
251
384
|
|
|
252
385
|
def migrations_between(latest: dict, plugin: str, current: str, target: str) -> list[dict]:
|
|
253
|
-
steps
|
|
386
|
+
"""The steps from ``current`` to ``target``; when two entries end at the same version (a span kept for the
|
|
387
|
+
release gate and the single steps inside it) the narrower one, with the newer ``from``, is shown."""
|
|
388
|
+
steps: dict[str, dict] = {}
|
|
254
389
|
for entry in latest.get("migrations", []):
|
|
255
390
|
if entry.get("plugin") != plugin:
|
|
256
391
|
continue
|
|
257
392
|
to = str(entry.get("to"))
|
|
258
393
|
if is_newer(to, current) and not is_newer(to, target):
|
|
259
|
-
steps.
|
|
260
|
-
|
|
394
|
+
kept = steps.get(to)
|
|
395
|
+
if kept is None or is_newer(str(entry.get("from")), str(kept.get("from"))):
|
|
396
|
+
steps[to] = entry
|
|
397
|
+
return sorted(steps.values(), key=lambda entry: version_key(str(entry.get("to"))) or (0,))
|
|
261
398
|
|
|
262
399
|
|
|
263
400
|
def plugin_findings(latest: dict, installed: list[dict]) -> list[dict]:
|
|
@@ -267,6 +404,8 @@ def plugin_findings(latest: dict, installed: list[dict]) -> list[dict]:
|
|
|
267
404
|
current = item.get("version") or ""
|
|
268
405
|
if item["client"] == "legacy":
|
|
269
406
|
status = "legacy" # a pre-marketplace copy: it gets migrated, not updated
|
|
407
|
+
elif item.get("dev"):
|
|
408
|
+
status = "dev" # a development / local install: reported, never updated or migrated
|
|
270
409
|
elif target is None:
|
|
271
410
|
status = "unknown"
|
|
272
411
|
elif is_newer(target, current):
|
|
@@ -292,6 +431,203 @@ def plugin_findings(latest: dict, installed: list[dict]) -> list[dict]:
|
|
|
292
431
|
return findings
|
|
293
432
|
|
|
294
433
|
|
|
434
|
+
# ---------------------------------------------------------------- install state (#31)
|
|
435
|
+
|
|
436
|
+
INSTALL_STATES = ("none", "partial", "marketplace", "dev", "legacy", "mixed", "market-conflict")
|
|
437
|
+
STATE_LABELS = {"none": N_("未安装"), "partial": N_("部分安装"), "marketplace": N_("市场安装"), "dev": N_("开发版/本地安装"),
|
|
438
|
+
"legacy": N_("旧方式安装"), "mixed": N_("多处安装"), "market-conflict": N_("市场冲突")}
|
|
439
|
+
ORIGIN_LABELS = {"symlink": N_("指向别处的软链"), "local-directory-marketplace": N_("本地目录市场"),
|
|
440
|
+
"other-marketplace": N_("其他市场")}
|
|
441
|
+
# Where the client keeps what a replacement moves away ("" = nothing is replaced).
|
|
442
|
+
RECOVERY_HINTS = {
|
|
443
|
+
"claude": N_("Claude Code 升级后把旧版本目录留在 ~/.claude/plugins/cache/agenthelm/<插件>/<旧版本>/(客户端行为,agenthelm 不清理)"),
|
|
444
|
+
"codex": N_("由 Codex 管理,agenthelm 不备份;需要回退时用 codex 重新安装指定版本"),
|
|
445
|
+
"cursor": N_("被替换的目录备份在 ~/.agent-pack/recovery/<时间>-cursor-<插件>/replaced-plugin/<插件>/"),
|
|
446
|
+
"legacy": N_("旧安装移入 ~/.agent-pack/recovery/<时间>-agenthelm-migrate/(含 migration.json 清单,可按清单恢复)"),
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def declared_source_text(source: Any) -> str:
|
|
451
|
+
"""A declared marketplace source in the form ``--marketplace-source`` takes: ``owner/repo[#ref]``, a URL or a path."""
|
|
452
|
+
if not isinstance(source, dict):
|
|
453
|
+
return str(source)
|
|
454
|
+
kind = source.get("source")
|
|
455
|
+
target = source.get("repo") or source.get("url") or source.get("path") or ""
|
|
456
|
+
ref = source.get("ref")
|
|
457
|
+
return f"{target}#{ref}" if ref and kind in {"github", "git", "url"} else str(target)
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def market_conflict(latest: dict, declared: list[dict]) -> dict | None:
|
|
461
|
+
"""Claude Code refuses ``marketplace add`` for a name whose declared source differs (issue #31 comment, measured on
|
|
462
|
+
macOS): flag a declaration that points elsewhere, or that pins a ref (a later `marketplace add` without it is refused)."""
|
|
463
|
+
try:
|
|
464
|
+
slug = github_slug(latest)
|
|
465
|
+
except CheckError:
|
|
466
|
+
slug = ""
|
|
467
|
+
for item in declared:
|
|
468
|
+
source = item["source"]
|
|
469
|
+
if not isinstance(source, dict):
|
|
470
|
+
return {**item, "reason": "points-elsewhere", "declared": declared_source_text(source), "ref": None}
|
|
471
|
+
target = str(source.get("repo") or source.get("url") or source.get("path") or "")
|
|
472
|
+
same = source.get("source") == "github" and target == slug or (
|
|
473
|
+
source.get("source") in {"git", "url"} and slug and slug in target)
|
|
474
|
+
if not same:
|
|
475
|
+
return {**item, "reason": "points-elsewhere", "declared": declared_source_text(source), "ref": source.get("ref")}
|
|
476
|
+
if source.get("ref"):
|
|
477
|
+
return {**item, "reason": "pinned", "declared": declared_source_text(source), "ref": source.get("ref")}
|
|
478
|
+
return None
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def _install_record(item: dict) -> dict:
|
|
482
|
+
kind = "legacy" if item["client"] == "legacy" else "dev" if item.get("dev") else "marketplace"
|
|
483
|
+
origin = (f"other-marketplace:{item['marketplace']}" if item.get("dev") == "other-marketplace"
|
|
484
|
+
else item.get("dev") or MARKETPLACE)
|
|
485
|
+
return {"plugin": item["plugin"], "version": item.get("version"), "path": item["path"], "kind": kind,
|
|
486
|
+
"origin": origin, "scope": item.get("scope"), "status": item.get("status")}
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def _origin_text(record: dict) -> str:
|
|
490
|
+
base, _sep, extra = record["origin"].partition(":")
|
|
491
|
+
text = _(ORIGIN_LABELS[base]) if base in ORIGIN_LABELS else _("市场安装")
|
|
492
|
+
return f"{text} {extra}" if extra else text
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def diagnose_client(client: str, latest: dict, findings: list[dict], others: list[dict], conflict: dict | None) -> dict:
|
|
496
|
+
names = sorted(latest.get("plugins", {}))
|
|
497
|
+
legacy = [item for item in findings if item["client"] == "legacy"] if client in {"claude", "codex"} else []
|
|
498
|
+
records = [_install_record(item) for item in findings if item["client"] == client]
|
|
499
|
+
records += [_install_record({**item, "status": "dev"}) for item in others if item["client"] == client]
|
|
500
|
+
records += [_install_record(item) for item in legacy]
|
|
501
|
+
present = sorted({item["plugin"] for item in records if item["kind"] != "legacy"})
|
|
502
|
+
missing = [name for name in names if name not in present]
|
|
503
|
+
managed = [item for item in records if item["kind"] == "marketplace"]
|
|
504
|
+
dev = [item for item in records if item["kind"] == "dev"]
|
|
505
|
+
old = [item for item in records if item["kind"] == "legacy"]
|
|
506
|
+
# Several places for one plugin only clash when they come from different sources (two scopes of the same market are fine).
|
|
507
|
+
clashes = []
|
|
508
|
+
for plugin in sorted({item["plugin"] for item in records}):
|
|
509
|
+
mine = [item for item in records if item["plugin"] == plugin]
|
|
510
|
+
if len({(item["kind"], item["origin"]) for item in mine}) > 1:
|
|
511
|
+
clashes.append({"plugin": plugin, "installs": mine,
|
|
512
|
+
"versions_differ": len({item["version"] for item in mine}) > 1})
|
|
513
|
+
sub = None
|
|
514
|
+
if managed:
|
|
515
|
+
statuses = {item["status"] for item in managed}
|
|
516
|
+
sub = "behind" if "behind" in statuses else "ahead" if "ahead" in statuses else \
|
|
517
|
+
"current" if statuses == {"current"} else "unknown"
|
|
518
|
+
if clashes:
|
|
519
|
+
base = "mixed"
|
|
520
|
+
elif dev:
|
|
521
|
+
base = "dev"
|
|
522
|
+
elif old and not managed:
|
|
523
|
+
base = "legacy"
|
|
524
|
+
elif not records:
|
|
525
|
+
base = "none"
|
|
526
|
+
elif missing:
|
|
527
|
+
base = "partial"
|
|
528
|
+
else:
|
|
529
|
+
base = "marketplace"
|
|
530
|
+
state = "market-conflict" if conflict and base in {"none", "partial", "marketplace", "legacy"} else base
|
|
531
|
+
diag = {"client": client, "state": state, "base_state": base, "sub_status": sub, "installed": present,
|
|
532
|
+
"missing": missing, "installs": records,
|
|
533
|
+
"conflicts": [{"plugin": c["plugin"], "versions_differ": c["versions_differ"],
|
|
534
|
+
"effective": None} for c in clashes],
|
|
535
|
+
"market_conflict": {k: conflict[k] for k in ("scope", "file", "reason", "declared", "ref")} if conflict else None,
|
|
536
|
+
"untouched": [{"plugin": item["plugin"], "path": item["path"], "origin": item["origin"]} for item in dev]}
|
|
537
|
+
diag.update(_advice(diag, client))
|
|
538
|
+
return diag
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def _advice(diag: dict, client: str) -> dict:
|
|
542
|
+
"""The one-sentence conclusion, the next command (a preview), whether it changes an existing install, and where originals go."""
|
|
543
|
+
name = CLIENT_NAMES[client]
|
|
544
|
+
state, base = diag["state"], diag["base_state"]
|
|
545
|
+
missing = _("、").join(diag["missing"])
|
|
546
|
+
install = f"{CLI} install --client {client}"
|
|
547
|
+
update = f"{CLI} update --client {client}"
|
|
548
|
+
recovery = None
|
|
549
|
+
changes = False
|
|
550
|
+
command: str | None
|
|
551
|
+
if state == "none":
|
|
552
|
+
summary, command = _("{0} 里没有任何 agenthelm 插件。").format(name), install
|
|
553
|
+
elif state == "partial":
|
|
554
|
+
summary = _("{0} 只装了一部分,缺 {1}。").format(name, missing)
|
|
555
|
+
if "agents-init" in diag["installed"]:
|
|
556
|
+
summary += _("agents-init 依赖其余插件,缺失时它无法完整工作。")
|
|
557
|
+
command = install
|
|
558
|
+
if client == "cursor": # Cursor's install rewrites every plugin it installs
|
|
559
|
+
changes, recovery = True, _(RECOVERY_HINTS["cursor"])
|
|
560
|
+
elif state == "marketplace":
|
|
561
|
+
sub = diag["sub_status"]
|
|
562
|
+
if sub == "behind":
|
|
563
|
+
summary, command, changes = _("{0} 通过 agenthelm 市场安装,有插件落后于云端。").format(name), update, True
|
|
564
|
+
recovery = _(RECOVERY_HINTS[client])
|
|
565
|
+
elif sub == "ahead":
|
|
566
|
+
summary, command = _("{0} 通过 agenthelm 市场安装,版本高于云端(可能是预发布)。").format(name), None
|
|
567
|
+
elif sub == "current":
|
|
568
|
+
summary, command = _("{0} 通过 agenthelm 市场安装,已是最新。").format(name), None
|
|
569
|
+
else:
|
|
570
|
+
summary, command = _("{0} 通过 agenthelm 市场安装,但读不到版本,无法比较。").format(name), None
|
|
571
|
+
elif state == "dev":
|
|
572
|
+
where = _(";").join(_("{0}({1}:{2})").format(item['plugin'], _origin_text(item), item['path']) for item in diag["untouched"])
|
|
573
|
+
summary = _("{0} 有开发版/本地安装:{1}。update / migrate 默认不改动它们,由你决定是否纳入市场管理。").format(name, where)
|
|
574
|
+
command = update # the preview names the untouched installs
|
|
575
|
+
changes = any(item["status"] == "behind" for item in diag["installs"] if item["kind"] == "marketplace")
|
|
576
|
+
if missing:
|
|
577
|
+
summary += _("还缺 {0},可用 install 补装(不会改动已有的安装)。").format(missing)
|
|
578
|
+
elif state == "legacy":
|
|
579
|
+
summary = _("{0} 只有旧方式安装(复制 + 软链),不会自动更新。").format(name)
|
|
580
|
+
command, changes, recovery = f"{CLI} migrate --install", True, _(RECOVERY_HINTS["legacy"])
|
|
581
|
+
elif state == "mixed":
|
|
582
|
+
plugins = _("、").join(c["plugin"] for c in diag["conflicts"])
|
|
583
|
+
skew = any(c["versions_differ"] for c in diag["conflicts"])
|
|
584
|
+
summary = _("{0} 里 {1} 有多处安装{2};哪一处生效由客户端决定(未确认),建议保留一处。").format(
|
|
585
|
+
name, plugins, _(",版本不一致") if skew else "")
|
|
586
|
+
legacy_involved = any(item["kind"] == "legacy" for item in diag["installs"])
|
|
587
|
+
command = f"{CLI} migrate" if legacy_involved else f"{CLI} doctor"
|
|
588
|
+
if legacy_involved:
|
|
589
|
+
changes, recovery = True, _(RECOVERY_HINTS["legacy"])
|
|
590
|
+
else: # market-conflict
|
|
591
|
+
conflict = diag["market_conflict"]
|
|
592
|
+
if conflict["reason"] == "pinned":
|
|
593
|
+
summary = _("{0} 的 settings 把 agenthelm 市场固定在 {1}({2}):不带它的 marketplace add 会被拒绝,update 也只会跟随这个 ref。").format(
|
|
594
|
+
name, conflict["ref"], conflict["file"])
|
|
595
|
+
else:
|
|
596
|
+
summary = _("{0} 的 settings 声明 agenthelm 市场指向 {1}({2}),与 agenthelm 默认来源不同:用默认来源 marketplace add 会被拒绝。").format(
|
|
597
|
+
name, conflict["declared"], conflict["file"])
|
|
598
|
+
summary += _("agenthelm 不会修改 settings.json:要么改那处声明,要么让 --marketplace-source 与它一致。")
|
|
599
|
+
command = f'{install} --marketplace-source "{conflict["declared"]}"'
|
|
600
|
+
if base == "legacy":
|
|
601
|
+
changes, recovery = True, _(RECOVERY_HINTS["legacy"])
|
|
602
|
+
result = {"summary": summary, "next_command": command, "modifies_existing": changes,
|
|
603
|
+
"modifies_note": (_("会改动已有的安装") if changes else _("不会改动已有的安装")) if command else None,
|
|
604
|
+
"recovery": recovery}
|
|
605
|
+
if diag["untouched"] and result["modifies_note"]:
|
|
606
|
+
result["modifies_note"] += _(";开发版/本地安装不会改动")
|
|
607
|
+
return result
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def install_state(env: Env, latest: dict, findings: list[dict], others: list[dict], declared: list[dict],
|
|
611
|
+
clients: list[str]) -> dict:
|
|
612
|
+
"""Per selected client: none / partial / marketplace(current|behind|ahead) / dev / legacy / mixed / market-conflict."""
|
|
613
|
+
detected = set(detect_clients(env))
|
|
614
|
+
conflict = market_conflict(latest, declared)
|
|
615
|
+
result: dict = {"clients": {}, "unconfirmed": [
|
|
616
|
+
"claude marketplace add on a same-named marketplace beyond the measured declared-source mismatch",
|
|
617
|
+
"claude --plugin-dir leaves no record in installed_plugins.json",
|
|
618
|
+
"codex and cursor local development install forms, and a Codex-side marketplace declaration"]}
|
|
619
|
+
for client in clients:
|
|
620
|
+
mine = [item for item in [*findings, *others] if item["client"] in {client, "legacy"}]
|
|
621
|
+
if client not in detected and not any(item["client"] == client for item in mine):
|
|
622
|
+
continue
|
|
623
|
+
# A legacy entry belongs to the client its path says (same rule as the summary count); unknown owner: both.
|
|
624
|
+
scoped = [item for item in findings
|
|
625
|
+
if item["client"] != "legacy" or legacy_owner(env, item) in {client, None}]
|
|
626
|
+
result["clients"][client] = diagnose_client(client, latest, scoped, others,
|
|
627
|
+
conflict if client == "claude" else None)
|
|
628
|
+
return result
|
|
629
|
+
|
|
630
|
+
|
|
295
631
|
# ---------------------------------------------------------------- project content
|
|
296
632
|
|
|
297
633
|
def content_findings(project: Path, latest: dict) -> list[dict]:
|
|
@@ -301,7 +637,7 @@ def content_findings(project: Path, latest: dict) -> list[dict]:
|
|
|
301
637
|
try:
|
|
302
638
|
lock = read_json(lock_path)
|
|
303
639
|
except (OSError, ValueError) as exc:
|
|
304
|
-
return [{"pack": None, "status": "error", "error":
|
|
640
|
+
return [{"pack": None, "status": "error", "error": _("{0} 无法解析:{1}").format(CONTENT_LOCK, exc)}]
|
|
305
641
|
findings = []
|
|
306
642
|
for pack_id, entry in sorted(lock.get("packs", {}).items()):
|
|
307
643
|
plugin = entry.get("plugin") or pack_id.split("/", 1)[0]
|
|
@@ -342,11 +678,11 @@ def opinion_findings(project: Path, installed: list[dict]) -> list[dict]:
|
|
|
342
678
|
return []
|
|
343
679
|
manager = locate_companion("opinion-manager", installed)
|
|
344
680
|
if manager is None:
|
|
345
|
-
return [{"status": "unknown", "error": "未找到已安装的 opinion-manager"}]
|
|
681
|
+
return [{"status": "unknown", "error": _("未找到已安装的 opinion-manager")}]
|
|
346
682
|
try:
|
|
347
683
|
profile = read_json(lock_path)["profile"]
|
|
348
684
|
except (OSError, ValueError, KeyError, TypeError) as exc:
|
|
349
|
-
return [{"status": "error", "error":
|
|
685
|
+
return [{"status": "error", "error": _("{0} 无法解析:{1}").format(OPINION_LOCK, exc)}]
|
|
350
686
|
with tempfile.TemporaryDirectory() as temporary:
|
|
351
687
|
# macOS temporary paths live under /var, a symlink opinion-manager refuses.
|
|
352
688
|
profile_file = Path(temporary).resolve() / "profile.json"
|
|
@@ -361,7 +697,7 @@ def opinion_findings(project: Path, installed: list[dict]) -> list[dict]:
|
|
|
361
697
|
except ValueError:
|
|
362
698
|
return [{"status": "error", "error": (completed.stderr or completed.stdout).strip()[:300]}]
|
|
363
699
|
if not result.get("ok", False):
|
|
364
|
-
return [{"status": "error", "error": result.get("error", "opinion-manager updates 失败")}]
|
|
700
|
+
return [{"status": "error", "error": result.get("error", _("opinion-manager updates 失败"))}]
|
|
365
701
|
return [{"status": "update-available" if result["updates"] else "current", "updates": result["updates"]}]
|
|
366
702
|
|
|
367
703
|
|
|
@@ -408,7 +744,7 @@ def scaffold_report(env: Env, project: Path | None, *, reprompt: bool = False) -
|
|
|
408
744
|
base = {"available": False, "root": str(root), "findings": [], "skipped": [], "error": ""}
|
|
409
745
|
module = scaffold_module(env)
|
|
410
746
|
if module is None:
|
|
411
|
-
return {**base, "error": "已安装的 agents-init 没有脚手架检查(更新 agents-init 后再检查)"}
|
|
747
|
+
return {**base, "error": _("已安装的 agents-init 没有脚手架检查(更新 agents-init 后再检查)")}
|
|
412
748
|
try:
|
|
413
749
|
return {**module.check(root, state_dir=env.state_dir, reprompt=reprompt), "available": True,
|
|
414
750
|
"root": str(root), "error": ""}
|
|
@@ -416,12 +752,16 @@ def scaffold_report(env: Env, project: Path | None, *, reprompt: bool = False) -
|
|
|
416
752
|
return {**base, "error": str(exc)}
|
|
417
753
|
|
|
418
754
|
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
(
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
755
|
+
def _local_only() -> Any:
|
|
756
|
+
"""local_only 模块(与本文件同目录,只用标准库)。"""
|
|
757
|
+
if str(RUNTIME_DIR) not in sys.path:
|
|
758
|
+
sys.path.insert(0, str(RUNTIME_DIR))
|
|
759
|
+
import local_only # noqa: PLC0415 - shipped next to this file
|
|
760
|
+
|
|
761
|
+
return local_only
|
|
762
|
+
|
|
763
|
+
|
|
764
|
+
SYNC_SERVICES = tuple((name, pattern) for _identifier, name, pattern in _local_only().SYNC_SERVICES)
|
|
425
765
|
REBUILDABLE_DIRS = {"node_modules", ".venv", "venv", "__pycache__", ".pytest_cache", ".cache", "dist", "build", "target",
|
|
426
766
|
".tox", ".next", ".gradle"}
|
|
427
767
|
|
|
@@ -445,7 +785,7 @@ def sync_folder(root: Path) -> dict | None:
|
|
|
445
785
|
return {"service": service, "path": str(resolved), "rebuildable": sorted(found)}
|
|
446
786
|
|
|
447
787
|
|
|
448
|
-
def machine_findings(env: Env, project: Path | None, *, reprompt: bool = False) -> dict:
|
|
788
|
+
def machine_findings(env: Env, project: Path | None, *, reprompt: bool = False, quick: bool = False) -> dict:
|
|
449
789
|
"""Findings about this machine only (no user-level runtime ...); their decisions live in the user state directory."""
|
|
450
790
|
root = profile_root(project)
|
|
451
791
|
result: dict = {"findings": [], "skipped": []}
|
|
@@ -458,19 +798,29 @@ def machine_findings(env: Env, project: Path | None, *, reprompt: bool = False)
|
|
|
458
798
|
if data["current"] is None:
|
|
459
799
|
text = agenthelm_runtime.missing_text(data, agenthelm_runtime.command_status())
|
|
460
800
|
findings.append({"id": "local:runtime-missing", "kind": "runtime-missing", "level": "suggest", "scope": "machine",
|
|
461
|
-
"title": "这台机器还没有安装用户级运行时", "reason": text["reason"], "impact": text["impact"],
|
|
801
|
+
"title": _("这台机器还没有安装用户级运行时"), "reason": text["reason"], "impact": text["impact"],
|
|
462
802
|
"fingerprint": "runtime-missing", "fix": "install-runtime", "next": text["label"]})
|
|
463
803
|
where = sync_folder(root)
|
|
464
804
|
if where is not None:
|
|
465
|
-
extra =
|
|
805
|
+
extra = _(";其中有可重建目录:{0}").format(_('、').join(where['rebuildable'][:6])) if where["rebuildable"] else ""
|
|
466
806
|
findings.append({"id": "local:sync-folder", "kind": "sync-folder", "level": "suggest", "scope": "machine",
|
|
467
|
-
"title":
|
|
807
|
+
"title": _("项目位于同步盘({0})").format(where['service']),
|
|
468
808
|
"reason": f"{where['path']}{extra}",
|
|
469
|
-
"impact": "多台机器共用同一份项目时:项目文件随同步盘走,但运行时、缓存与 wf 的台账是每台机器各一份;"
|
|
470
|
-
"可重建目录(依赖、构建产物)同步很慢,也容易产生冲突副本",
|
|
809
|
+
"impact": _("多台机器共用同一份项目时:项目文件随同步盘走,但运行时、缓存与 wf 的台账是每台机器各一份;"
|
|
810
|
+
"可重建目录(依赖、构建产物)同步很慢,也容易产生冲突副本"),
|
|
471
811
|
"fingerprint": sha256_text(where["service"]), "fix": "sync-folder",
|
|
472
|
-
"next": "运行 agenthelm fix sync-folder 查看指引(只给方案,不改文件、不删内容);不需要就 fix --skip local:sync-folder",
|
|
812
|
+
"next": _("运行 agenthelm fix sync-folder 查看指引(只给方案,不改文件、不删内容);不需要就 fix --skip local:sync-folder"),
|
|
473
813
|
"sync": where})
|
|
814
|
+
# local-only:同步盘里的本机专属目录、外置链接、HOME、体积……没有同步服务也没有配置时不扫描。
|
|
815
|
+
try:
|
|
816
|
+
engine = _local_only().check(root, home=env.home, environ=env.variables, mode="quick" if quick else "standard",
|
|
817
|
+
user_config=env.config_file)
|
|
818
|
+
findings.extend(engine["findings"])
|
|
819
|
+
except Exception as exc: # noqa: BLE001 - 本机目录检查出错不能拖垮插件与脚手架检查
|
|
820
|
+
findings.append({"id": "local:local-only-error", "kind": "error", "level": "suggest", "scope": "machine",
|
|
821
|
+
"title": _("无法检查本机专属目录"), "reason": str(exc), "impact": _("只影响同步盘相关提示"),
|
|
822
|
+
"fingerprint": sha256_text(str(exc)), "fix": None, "attention": False, "options": [],
|
|
823
|
+
"next": _("运行 agenthelm local-only check 查看详情")})
|
|
474
824
|
module = scaffold_module(env)
|
|
475
825
|
if module is None or not findings:
|
|
476
826
|
result["findings"] = findings
|
|
@@ -480,8 +830,41 @@ def machine_findings(env: Env, project: Path | None, *, reprompt: bool = False)
|
|
|
480
830
|
return result
|
|
481
831
|
|
|
482
832
|
|
|
833
|
+
def local_only_report(env: Env, project: Path | None, *, mode: str = "full", reprompt: bool = False) -> dict:
|
|
834
|
+
"""local-only 的完整检查结果(供 ``agenthelm local-only check`` 与 MCP 工具),已套用这台机器上记录的决定。"""
|
|
835
|
+
module = _local_only()
|
|
836
|
+
base = (project or Path.cwd()).resolve()
|
|
837
|
+
root = profile_root(base) or base
|
|
838
|
+
report = module.check(root, home=env.home, environ=env.variables, mode=mode, user_config=env.config_file)
|
|
839
|
+
report["skipped"] = []
|
|
840
|
+
scaffold = scaffold_module(env)
|
|
841
|
+
if scaffold is not None and report["findings"]:
|
|
842
|
+
decisions = scaffold.load_decisions(root, env.state_dir)
|
|
843
|
+
report["findings"], skipped = scaffold.partition(report["findings"], decisions, reprompt=reprompt)
|
|
844
|
+
report["skipped"] = [{"id": item["id"], "decision": item["decision"]} for item in skipped]
|
|
845
|
+
report["summary"] = {"findings": len(report["findings"]),
|
|
846
|
+
"attention": sum(1 for item in report["findings"] if item.get("attention"))}
|
|
847
|
+
return report
|
|
848
|
+
|
|
849
|
+
|
|
850
|
+
def local_only_plan(env: Env, project: Path | None, **options: Any) -> dict:
|
|
851
|
+
"""``agenthelm local-only fix`` 的预览(不写任何东西);原因不能处理时抛出 LocalOnlyError。"""
|
|
852
|
+
base = (project or Path.cwd()).resolve()
|
|
853
|
+
return _local_only().plan_fix(profile_root(base) or base, home=env.home, environ=env.variables,
|
|
854
|
+
user_config=env.config_file, **options)
|
|
855
|
+
|
|
856
|
+
|
|
483
857
|
# ---------------------------------------------------------------- report
|
|
484
858
|
|
|
859
|
+
def baseline_less_differences(env: Env, project: Path | None) -> int:
|
|
860
|
+
"""How many project files differ from the template with no baseline in the content lock (check's content-differs findings)."""
|
|
861
|
+
try:
|
|
862
|
+
report = scaffold_report(env, project)
|
|
863
|
+
except Exception: # noqa: BLE001 - a hint only; never let it break update
|
|
864
|
+
return 0
|
|
865
|
+
return sum(1 for item in (report or {}).get("findings", []) if item.get("kind") == "content-differs")
|
|
866
|
+
|
|
867
|
+
|
|
485
868
|
def scaffold_fingerprint(env: Env, scaffold: dict | None) -> dict | None:
|
|
486
869
|
module = scaffold_module(env)
|
|
487
870
|
if scaffold is None or module is None or not scaffold.get("available"):
|
|
@@ -489,43 +872,127 @@ def scaffold_fingerprint(env: Env, scaffold: dict | None) -> dict | None:
|
|
|
489
872
|
return module.fingerprint(scaffold)
|
|
490
873
|
|
|
491
874
|
|
|
875
|
+
CLIENT_NAMES = {"claude": "Claude Code", "codex": "Codex", "cursor": "Cursor"}
|
|
876
|
+
CLIENT_KEYS = ("claude", "codex", "cursor")
|
|
877
|
+
|
|
878
|
+
|
|
879
|
+
def ignored_clients(env: Env) -> list[str]:
|
|
880
|
+
"""The clients the user chose to ignore (user config ``ignored_clients``); unknown names are dropped."""
|
|
881
|
+
try:
|
|
882
|
+
value = read_json(env.config_file).get("ignored_clients", [])
|
|
883
|
+
except (OSError, ValueError, AttributeError):
|
|
884
|
+
return []
|
|
885
|
+
return [name for name in CLIENT_KEYS if isinstance(value, list) and name in value]
|
|
886
|
+
|
|
887
|
+
|
|
888
|
+
def select_clients(env: Env, explicit: list[str] | None) -> dict:
|
|
889
|
+
"""Which clients a run covers. ``--client`` wins over the ignore setting; without it, ignored ones are left out."""
|
|
890
|
+
ignored = ignored_clients(env)
|
|
891
|
+
if explicit:
|
|
892
|
+
chosen = [name for name in CLIENT_KEYS if name in explicit]
|
|
893
|
+
return {"explicit": chosen, "active": chosen, "ignored": [], "excluded": [n for n in CLIENT_KEYS if n not in chosen]}
|
|
894
|
+
return {"explicit": None, "active": [n for n in CLIENT_KEYS if n not in ignored], "ignored": ignored, "excluded": []}
|
|
895
|
+
|
|
896
|
+
|
|
897
|
+
def active_clients(env: Env, explicit: list[str] | None = None) -> list[str]:
|
|
898
|
+
"""Detected clients minus ignored ones (an explicit ``--client`` list is used as given)."""
|
|
899
|
+
if explicit:
|
|
900
|
+
return list(explicit)
|
|
901
|
+
return [name for name in detect_clients(env) if name not in ignored_clients(env)]
|
|
902
|
+
|
|
903
|
+
|
|
904
|
+
def unused_client_hints(env: Env, plugins: list[dict], ignored: list[str]) -> list[str]:
|
|
905
|
+
"""Detected clients that look unused: with several clients around, one that has no agenthelm plugin installed or
|
|
906
|
+
whose agenthelm plugins are all behind. The caller shows each hint once."""
|
|
907
|
+
detected = [name for name in detect_clients(env)]
|
|
908
|
+
if len(detected) < 2:
|
|
909
|
+
return []
|
|
910
|
+
hints = []
|
|
911
|
+
for name in detected:
|
|
912
|
+
if name in ignored:
|
|
913
|
+
continue
|
|
914
|
+
mine = [item for item in plugins if item["client"] == name]
|
|
915
|
+
if not mine or all(item["status"] == "behind" for item in mine):
|
|
916
|
+
hints.append(name)
|
|
917
|
+
return hints
|
|
918
|
+
|
|
919
|
+
|
|
492
920
|
def run_check(env: Env, project: Path | None, *, latest_source: str | None = None, offline: bool = False,
|
|
493
|
-
max_age: int = CACHE_TTL_SECONDS, hook_mode: bool = False, reprompt: bool = False
|
|
921
|
+
max_age: int = CACHE_TTL_SECONDS, hook_mode: bool = False, reprompt: bool = False,
|
|
922
|
+
clients: list[str] | None = None) -> dict:
|
|
494
923
|
latest, origin = load_latest(
|
|
495
924
|
env, latest_source, offline=offline, max_age=max_age,
|
|
496
925
|
timeout=HOOK_FETCH_TIMEOUT_SECONDS if hook_mode else FETCH_TIMEOUT_SECONDS, backoff=hook_mode,
|
|
497
926
|
)
|
|
498
927
|
names = set(latest.get("plugins", {}))
|
|
499
928
|
installed = installed_plugins(env, names)
|
|
500
|
-
|
|
929
|
+
selection = select_clients(env, clients)
|
|
930
|
+
everything = plugin_findings(latest, installed)
|
|
931
|
+
# A legacy copy belongs to no client: it stays visible whichever clients are selected.
|
|
932
|
+
plugins = [item for item in everything if item["client"] == "legacy" or item["client"] in selection["active"]]
|
|
933
|
+
ignored_plugins = [item for item in everything if item["client"] in selection["ignored"]]
|
|
934
|
+
others = other_installs(env, names)
|
|
935
|
+
state = install_state(env, latest, everything, others, declared_marketplaces(env, project), selection["active"])
|
|
501
936
|
content = content_findings(project, latest) if project else []
|
|
502
937
|
opinion = opinion_findings(project, installed) if project else []
|
|
503
938
|
scaffold = scaffold_report(env, project, reprompt=reprompt)
|
|
504
|
-
machine = machine_findings(env, project, reprompt=reprompt)
|
|
939
|
+
machine = machine_findings(env, project, reprompt=reprompt, quick=hook_mode)
|
|
940
|
+
local_attention = sum(1 for item in machine["findings"] if item.get("attention"))
|
|
505
941
|
scaffold_active = len(scaffold["findings"]) if scaffold else 0
|
|
942
|
+
# 只有“需要处理”的脚手架发现(level must)参与 up_to_date、--strict 与会话开始提示;旧版 agents-init 没有分级时按可选处理。
|
|
943
|
+
scaffold_required = sum(1 for item in (scaffold["findings"] if scaffold else []) if item.get("level") == "must")
|
|
506
944
|
behind = [item for item in plugins if item["status"] == "behind"]
|
|
507
|
-
legacy
|
|
945
|
+
# With --client, a legacy entry stays listed (it is a migration risk) but counts toward up_to_date only when its
|
|
946
|
+
# path says it belongs to a selected client; an entry whose owner cannot be told is listed and not counted.
|
|
947
|
+
for item in plugins:
|
|
948
|
+
if item["client"] == "legacy":
|
|
949
|
+
item["owner"] = legacy_owner(env, item)
|
|
950
|
+
legacy = [item for item in plugins if item["client"] == "legacy"
|
|
951
|
+
and (not selection["explicit"] or item["owner"] in selection["active"])]
|
|
952
|
+
legacy_unattributed = sum(1 for item in plugins if item["client"] == "legacy") - len(legacy)
|
|
953
|
+
by_client = {name: {"behind": sum(1 for item in plugins if item["client"] == name and item["status"] == "behind"),
|
|
954
|
+
"total": sum(1 for item in plugins if item["client"] == name)}
|
|
955
|
+
for name in selection["active"] if any(item["client"] == name for item in plugins)}
|
|
508
956
|
content_updates = [item for item in content if item["status"] in {"update-available", "conflict"}]
|
|
957
|
+
content_errors = [item for item in content if item["status"] == "error"] # 内容锁无法解析:无法判断,不能当作“已是最新”
|
|
509
958
|
opinion_updates = [item for item in opinion if item["status"] == "update-available"]
|
|
959
|
+
settings = user_settings_module()
|
|
960
|
+
language = settings.report_section(env.variables, settings.read_settings(env.config_file)[0], scaffold)
|
|
510
961
|
return {
|
|
511
962
|
"ok": True,
|
|
512
963
|
"latest": {"source": origin, "released_at": latest.get("released_at")},
|
|
513
964
|
"_latest": latest,
|
|
514
965
|
"plugins": plugins,
|
|
966
|
+
"ignored_plugins": ignored_plugins,
|
|
967
|
+
"install_state": state,
|
|
968
|
+
"clients": {"selected": selection["explicit"], "ignored": selection["ignored"],
|
|
969
|
+
"excluded": selection["excluded"],
|
|
970
|
+
"unused": [] if (hook_mode or selection["explicit"])
|
|
971
|
+
else unused_client_hints(env, everything, selection["ignored"])},
|
|
515
972
|
"content": content,
|
|
516
973
|
"opinion": opinion,
|
|
517
974
|
"scaffold": scaffold,
|
|
518
975
|
"machine": machine,
|
|
976
|
+
"language": language,
|
|
519
977
|
"summary": {
|
|
520
978
|
"scaffold_findings": scaffold_active,
|
|
979
|
+
"scaffold_required": scaffold_required,
|
|
980
|
+
"scaffold_optional": sum(1 for item in (scaffold["findings"] if scaffold else []) if item.get("level", "suggest") == "suggest"),
|
|
981
|
+
"scaffold_info": sum(1 for item in (scaffold["findings"] if scaffold else []) if item.get("level") == "info"),
|
|
521
982
|
"scaffold_skipped": len(scaffold["skipped"]) if scaffold else 0,
|
|
983
|
+
"local_only_attention": local_attention,
|
|
522
984
|
"plugins_behind": len(behind),
|
|
985
|
+
"by_client": by_client,
|
|
523
986
|
"breaking": any(item["breaking"] for item in behind),
|
|
524
987
|
"content_updates": len(content_updates),
|
|
988
|
+
"content_errors": len(content_errors),
|
|
525
989
|
"content_conflicts": sum(1 for item in content if item["status"] == "conflict"),
|
|
526
990
|
"opinion_updates": len(opinion_updates),
|
|
527
991
|
"legacy_installs": len(legacy),
|
|
528
|
-
"
|
|
992
|
+
"legacy_other_clients": legacy_unattributed,
|
|
993
|
+
"install_states": {name: item["state"] for name, item in state["clients"].items()},
|
|
994
|
+
"up_to_date": not (behind or content_updates or content_errors or opinion_updates or legacy or scaffold_required
|
|
995
|
+
or local_attention),
|
|
529
996
|
},
|
|
530
997
|
}
|
|
531
998
|
|
|
@@ -544,110 +1011,224 @@ def one_line(report: dict) -> str | None:
|
|
|
544
1011
|
return None
|
|
545
1012
|
parts = []
|
|
546
1013
|
if summary["plugins_behind"]:
|
|
547
|
-
|
|
1014
|
+
text = _("{0} 个插件可更新").format(summary['plugins_behind']) + (_("(含不兼容变更)") if summary["breaking"] else "")
|
|
1015
|
+
per_client = summary.get("by_client") or {}
|
|
1016
|
+
if per_client:
|
|
1017
|
+
text += _("(") + _(";").join(
|
|
1018
|
+
(_("{0}:{1} 个可更新").format(CLIENT_NAMES[name], item["behind"]) if item["behind"]
|
|
1019
|
+
else _("{0}:已是最新").format(CLIENT_NAMES[name])) for name, item in per_client.items()) + _(")")
|
|
1020
|
+
parts.append(text)
|
|
548
1021
|
if summary["content_updates"]:
|
|
549
|
-
parts.append(
|
|
550
|
-
+ (
|
|
1022
|
+
parts.append(_("{0} 个模板/样例包可更新").format(summary['content_updates'])
|
|
1023
|
+
+ (_("({0} 个本地有改动,更新时逐文件确认)").format(summary['content_conflicts']) if summary["content_conflicts"] else ""))
|
|
1024
|
+
if summary.get("content_errors"):
|
|
1025
|
+
parts.append(_("项目内容锁无法解析,没能检查模板/样例包"))
|
|
551
1026
|
if summary["opinion_updates"]:
|
|
552
|
-
parts.append("Opinion 有新版本模板或规则")
|
|
1027
|
+
parts.append(_("Opinion 有新版本模板或规则"))
|
|
553
1028
|
if summary["legacy_installs"]:
|
|
554
|
-
parts.append(
|
|
555
|
-
if summary["
|
|
556
|
-
parts.append(
|
|
557
|
-
|
|
1029
|
+
parts.append(_("{0} 个旧方式安装待迁移").format(summary['legacy_installs']))
|
|
1030
|
+
if summary["scaffold_required"]:
|
|
1031
|
+
parts.append(_("项目脚手架有 {0} 项需要处理的差异").format(summary['scaffold_required']))
|
|
1032
|
+
if summary.get("local_only_attention"):
|
|
1033
|
+
parts.append(_("同步目录里有 {0} 项本机专属目录需要处理").format(summary['local_only_attention']))
|
|
1034
|
+
return _("agenthelm:") + _(",").join(parts) + _("。运行 `{0} check` 查看详情;更新前会先预览,由你决定。").format(CLI)
|
|
558
1035
|
|
|
559
1036
|
|
|
560
|
-
def
|
|
1037
|
+
def render_profile_notes(scaffold: dict, show_extras: bool) -> list[str]:
|
|
1038
|
+
"""Information only (never a finding, never the exit code): values that no longer fit the schema, and fields it does not declare."""
|
|
1039
|
+
lines = []
|
|
1040
|
+
for item in scaffold.get("profile_conflicts") or []:
|
|
1041
|
+
lines.append(_(" [脚手架·信息] {0}").format(item["message"]))
|
|
1042
|
+
summary = scaffold.get("profile_extras") or {}
|
|
1043
|
+
if not summary.get("total"):
|
|
1044
|
+
return lines
|
|
1045
|
+
parts = [_("项目自有 {0}").format(summary["own"])]
|
|
1046
|
+
if summary.get("suspected_typo"):
|
|
1047
|
+
parts.append(_("疑似拼写错误 {0}").format(summary["suspected_typo"]))
|
|
1048
|
+
if summary.get("read_by_plugin"):
|
|
1049
|
+
parts.append(_("已被其他插件读取、schema 尚未声明 {0}").format(summary["read_by_plugin"]))
|
|
1050
|
+
lines.append(_(" [脚手架·信息] Profile 中有 {0} 个 schema 未声明的字段({1};工具不读取、不比较){2}").format(
|
|
1051
|
+
summary["total"], _(",").join(parts), "" if show_extras else _(":check --show-extras 展开")))
|
|
1052
|
+
if show_extras:
|
|
1053
|
+
for item in scaffold.get("extras") or []:
|
|
1054
|
+
if item.get("kind") != "project-field":
|
|
1055
|
+
continue
|
|
1056
|
+
if item["category"] == "suspected-typo":
|
|
1057
|
+
note = _("疑似拼写错误,是不是想写 {0}?").format(item["similar_to"])
|
|
1058
|
+
elif item["category"] == "read-by-plugin":
|
|
1059
|
+
note = _("{0} 会读取它,但 schema 尚未声明").format(item["plugin"])
|
|
1060
|
+
else:
|
|
1061
|
+
note = _("项目自有")
|
|
1062
|
+
lines.append(_(" - {0}({1})").format(item['path'], note))
|
|
1063
|
+
return lines
|
|
1064
|
+
|
|
1065
|
+
|
|
1066
|
+
def level_tag(level: str) -> str:
|
|
1067
|
+
return {"must": _("需要处理"), "suggest": _("可选"), "info": _("信息")}.get(level, level)
|
|
1068
|
+
|
|
1069
|
+
|
|
1070
|
+
CATEGORY_COMMANDS = {
|
|
1071
|
+
"skeleton": ("fix add-skeleton", None), "content": ("fix update-content", None), "region": ("fix update-region", None),
|
|
1072
|
+
"profile": ("fix profile", None), "case-naming": ("fix case-naming", None), "lock": ("fix repair-lock", None),
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
|
|
1076
|
+
def _scaffold_item_lines(item: dict) -> str:
|
|
1077
|
+
mark = _("(稍后)") if item.get("deferred") else _("(期望内容已变化,重新提示)") if item.get("changed_since_decision") else ""
|
|
1078
|
+
fix = _(" 处理:fix {0}").format(item['fix']) if item.get("fix") else _(" 需要你自己处理")
|
|
1079
|
+
return _(" [脚手架] {0}{1}:{2}\n ID {3}{4}").format(item['title'], mark, item['reason'], item['id'], fix)
|
|
1080
|
+
|
|
1081
|
+
|
|
1082
|
+
def render_scaffold_groups(scaffold: dict, details: bool) -> list[str]:
|
|
1083
|
+
"""需要处理的逐项列出;可选与信息性的按类别各合并一行(--details 时逐项展开)。"""
|
|
1084
|
+
lines = []
|
|
1085
|
+
groups = {(row["level"], row["category"]): row for row in scaffold.get("categories", [])}
|
|
1086
|
+
by_key: dict[tuple[str, str], list[dict]] = {}
|
|
1087
|
+
for item in scaffold["findings"]:
|
|
1088
|
+
by_key.setdefault((item.get("level", "suggest"), item.get("category") or item["kind"]), []).append(item)
|
|
1089
|
+
for key, members in by_key.items():
|
|
1090
|
+
level, category = key
|
|
1091
|
+
if level == "must" or details or key not in groups:
|
|
1092
|
+
lines += [_scaffold_item_lines(item) for item in members]
|
|
1093
|
+
continue
|
|
1094
|
+
verb = CATEGORY_COMMANDS.get(category)
|
|
1095
|
+
handle = _(";处理:{0}").format(f"{CLI} {verb[0]}") if verb else ""
|
|
1096
|
+
lines.append(_(" [脚手架·{0}] {1}(查看:{2} check --details{3})").format(
|
|
1097
|
+
level_tag(level), groups[key]["label"], CLI, handle))
|
|
1098
|
+
optional = sum(len(m) for k, m in by_key.items() if k[0] != "must")
|
|
1099
|
+
if optional:
|
|
1100
|
+
lines.append(_(" 这 {0} 项都不需要?一次接受现状:{1} fix --accept-current --reason \"<原因>\"(先预览,--apply 写入;之后只提示新出现的差异)").format(optional, CLI))
|
|
1101
|
+
return lines
|
|
1102
|
+
|
|
1103
|
+
|
|
1104
|
+
def render_scaffold(report: dict, show_skipped: bool, details: bool = False, show_extras: bool = False) -> list[str]:
|
|
561
1105
|
scaffold = report.get("scaffold")
|
|
562
1106
|
lines = []
|
|
563
1107
|
if scaffold is None:
|
|
564
1108
|
return lines
|
|
565
1109
|
if scaffold.get("error"):
|
|
566
|
-
lines.append(
|
|
1110
|
+
lines.append(_(" [脚手架] 无法检查:{0}").format(scaffold['error']))
|
|
567
1111
|
return lines
|
|
568
|
-
|
|
569
|
-
mark = "(稍后)" if item.get("deferred") else "(期望内容已变化,重新提示)" if item.get("changed_since_decision") else ""
|
|
570
|
-
fix = f" 处理:fix {item['fix']}" if item.get("fix") else " 需要你自己处理"
|
|
571
|
-
lines.append(f" [脚手架] {item['title']}{mark}:{item['reason']}\n ID {item['id']}{fix}")
|
|
1112
|
+
lines += render_scaffold_groups(scaffold, details)
|
|
572
1113
|
for message in scaffold["decisions"]["errors"]:
|
|
573
|
-
lines.append(
|
|
1114
|
+
lines.append(_(" [脚手架] 决定文件有问题:{0}").format(message))
|
|
574
1115
|
if scaffold["decisions"]["conflict_copies"]:
|
|
575
|
-
lines.append(" [脚手架] 同步服务留下了决定文件的冲突副本:"
|
|
576
|
-
+ "、".join(scaffold["decisions"]["conflict_copies"]) + "(合并到 check-decisions.json 后删除)")
|
|
1116
|
+
lines.append(_(" [脚手架] 同步服务留下了决定文件的冲突副本:")
|
|
1117
|
+
+ _("、").join(scaffold["decisions"]["conflict_copies"]) + _("(合并到 check-decisions.json 后删除)"))
|
|
577
1118
|
if not scaffold["findings"] and not scaffold["decisions"]["errors"]:
|
|
578
|
-
lines.append(" [脚手架] 与期望一致" + (
|
|
1119
|
+
lines.append(_(" [脚手架] 与期望一致") + (_("({0} 项已跳过)").format(len(scaffold['skipped'])) if scaffold["skipped"] else ""))
|
|
1120
|
+
lines += render_profile_notes(scaffold, show_extras)
|
|
579
1121
|
skipped = [*scaffold["skipped"], *report.get("machine", {}).get("skipped", [])]
|
|
580
1122
|
if show_skipped:
|
|
581
1123
|
for item in skipped:
|
|
582
1124
|
decision = item["decision"]
|
|
583
|
-
lines.append(
|
|
584
|
-
f" {decision.get('decided_at', '')}")
|
|
1125
|
+
lines.append(_(" [已跳过·{0}] {1}:{2} {3}").format(decision['decision'], item['id'], decision.get('reason') or _('(未写理由)'), decision.get('decided_at', '')))
|
|
585
1126
|
if not skipped:
|
|
586
|
-
lines.append(" 没有被跳过的项。")
|
|
1127
|
+
lines.append(_(" 没有被跳过的项。"))
|
|
587
1128
|
elif skipped:
|
|
588
|
-
lines.append(
|
|
1129
|
+
lines.append(_(" (另有 {0} 项已被你跳过:check --show-skipped 查看)").format(len(skipped)))
|
|
589
1130
|
return lines
|
|
590
1131
|
|
|
591
1132
|
|
|
592
1133
|
def render_machine(report: dict) -> list[str]:
|
|
593
1134
|
lines = []
|
|
594
1135
|
for item in report.get("machine", {}).get("findings", []):
|
|
595
|
-
lines.append(
|
|
596
|
-
|
|
1136
|
+
lines.append(_(" [本机] {0}:{1}\n 影响:{2}\n 处理:{3}\n ID {4}(只记在这台机器上;fix --skip {5} --reason …)").format(item['title'], item['reason'], item['impact'], item['next'], item['id'], item['id']))
|
|
1137
|
+
return lines
|
|
1138
|
+
|
|
1139
|
+
|
|
1140
|
+
def render_install_state(state: dict) -> list[str]:
|
|
1141
|
+
"""The install-state diagnosis at the head of ``check``: a conclusion first, then the next command and its reach."""
|
|
1142
|
+
clients = state.get("clients") or {}
|
|
1143
|
+
if not clients:
|
|
1144
|
+
return []
|
|
1145
|
+
lines = [_("安装状态:")]
|
|
1146
|
+
for name, diag in clients.items():
|
|
1147
|
+
label = _(STATE_LABELS[diag["state"]])
|
|
1148
|
+
if diag["state"] == "marketplace" and diag.get("sub_status"):
|
|
1149
|
+
label += "·" + {"current": _("最新"), "behind": _("落后"), "ahead": _("高于云端"), "unknown": _("版本未知")}[diag["sub_status"]]
|
|
1150
|
+
lines.append(f" [{CLIENT_NAMES[name]}·{label}] {diag['summary']}")
|
|
1151
|
+
for conflict in diag["conflicts"]:
|
|
1152
|
+
for record in [r for r in diag["installs"] if r["plugin"] == conflict["plugin"]]:
|
|
1153
|
+
lines.append(_(" {0} {1}:{2} {3}({4})").format(
|
|
1154
|
+
record["plugin"], _("旧方式安装") if record["kind"] == "legacy" else _origin_text(record),
|
|
1155
|
+
record.get("version"), record["path"], record["scope"] or "-"))
|
|
1156
|
+
if diag["next_command"]:
|
|
1157
|
+
lines.append(_(" 下一步(预览):{0}").format(diag["next_command"]))
|
|
1158
|
+
lines.append(f" {diag['modifies_note']}")
|
|
1159
|
+
if diag["recovery"]:
|
|
1160
|
+
lines.append(_(" 原件恢复位置:{0}").format(diag["recovery"]))
|
|
597
1161
|
return lines
|
|
598
1162
|
|
|
599
1163
|
|
|
600
|
-
def render_text(report: dict, *, show_skipped: bool = False) -> str:
|
|
1164
|
+
def render_text(report: dict, *, show_skipped: bool = False, details: bool = False, show_extras: bool = False) -> str:
|
|
601
1165
|
lines = []
|
|
602
1166
|
origin = report["latest"]["source"]
|
|
603
|
-
lines.append(
|
|
1167
|
+
lines.append(origin_line(origin))
|
|
1168
|
+
clients = report.get("clients") or {}
|
|
1169
|
+
if clients.get("selected"):
|
|
1170
|
+
lines.append(_("只处理所选客户端:{0}").format(_("、").join(CLIENT_NAMES[name] for name in clients["selected"])))
|
|
1171
|
+
for name in clients.get("ignored", []):
|
|
1172
|
+
shown = [item for item in report.get("ignored_plugins", []) if item["client"] == name]
|
|
1173
|
+
lines.append(_(" [已忽略] {0}(用户配置 ignored_clients;不参与检查与更新)").format(CLIENT_NAMES[name]))
|
|
1174
|
+
if show_skipped:
|
|
1175
|
+
for item in shown:
|
|
1176
|
+
lines.append(_(" {0} {1} → {2}(未检查)").format(item["plugin"], item.get("version"), item.get("latest")))
|
|
1177
|
+
lines += render_install_state(report.get("install_state") or {})
|
|
604
1178
|
if not report["plugins"]:
|
|
605
|
-
lines.append("未发现已安装的 agenthelm 插件。")
|
|
1179
|
+
lines.append(_("未发现已安装的 agenthelm 插件。"))
|
|
606
1180
|
for item in report["plugins"]:
|
|
607
|
-
label = {"behind": "可更新", "current": "最新", "ahead": "高于云端", "unknown": "版本未知",
|
|
608
|
-
"legacy": "旧方式安装,待迁移"}[item["status"]]
|
|
1181
|
+
label = {"behind": _("可更新"), "current": _("最新"), "ahead": _("高于云端"), "unknown": _("版本未知"),
|
|
1182
|
+
"legacy": _("旧方式安装,待迁移"), "dev": _("开发版/本地安装,不会被 update / migrate 改动")}[item["status"]]
|
|
609
1183
|
if item["status"] == "legacy":
|
|
610
|
-
lines.append(
|
|
1184
|
+
lines.append(_(" [旧方式] {0} {1} {2}").format(item['plugin'], item.get('version'), label))
|
|
1185
|
+
continue
|
|
1186
|
+
if item["status"] == "dev":
|
|
1187
|
+
lines.append(_(" [{0}] {1} {2} {3}({4})").format(item['client'], item['plugin'], item.get('version'), label, item['path']))
|
|
611
1188
|
continue
|
|
612
1189
|
line = f" [{item['client']}] {item['plugin']} {item.get('version')} → {item.get('latest')} {label}"
|
|
613
1190
|
if item["status"] == "behind":
|
|
614
|
-
kinds = {"code": "代码", "content": "仅模板/样例", "both": "代码与模板"}
|
|
1191
|
+
kinds = {"code": _("代码"), "content": _("仅模板/样例"), "both": _("代码与模板")}
|
|
615
1192
|
if item["change_kinds"]:
|
|
616
|
-
line += "(" + "、".join(kinds[kind] for kind in item["change_kinds"]) + ")"
|
|
1193
|
+
line += _("(") + _("、").join(kinds[kind] for kind in item["change_kinds"]) + _(")")
|
|
617
1194
|
if item["breaking"]:
|
|
618
|
-
line += "(含不兼容变更)"
|
|
1195
|
+
line += _("(含不兼容变更)")
|
|
619
1196
|
for step in item["steps"]:
|
|
620
1197
|
if step.get("breaking"):
|
|
621
|
-
line +=
|
|
1198
|
+
line += _("\n {0} 不兼容:{1}").format(step['to'], step.get('summary'))
|
|
622
1199
|
line += "".join(f"\n - {action}" for action in step.get("actions") or [])
|
|
623
1200
|
hint = UPDATE_HINTS.get(item["client"])
|
|
624
1201
|
if hint:
|
|
625
|
-
line +=
|
|
1202
|
+
line += _("\n 更新:{0}").format(hint.format(plugin=item['plugin']))
|
|
626
1203
|
lines.append(line)
|
|
627
1204
|
for item in report["content"]:
|
|
628
1205
|
if item.get("pack") is None:
|
|
629
|
-
lines.append(
|
|
1206
|
+
lines.append(_(" 内容锁:{0}").format(item.get('error')))
|
|
630
1207
|
continue
|
|
631
|
-
label = {"current": "最新", "update-available": "可更新(本地未改动)",
|
|
632
|
-
"conflict": "可更新(本地有改动,更新时逐文件确认)", "unknown": "云端未列出"}[item["status"]]
|
|
633
|
-
line =
|
|
1208
|
+
label = {"current": _("最新"), "update-available": _("可更新(本地未改动)"),
|
|
1209
|
+
"conflict": _("可更新(本地有改动,更新时逐文件确认)"), "unknown": _("云端未列出")}[item["status"]]
|
|
1210
|
+
line = _(" [内容] {0} {1} → {2} {3}").format(item['pack'], item['version'], item.get('latest'), label)
|
|
634
1211
|
if item["locally_changed"]:
|
|
635
|
-
line += "\n 本地已改动:" + "、".join(item["locally_changed"])
|
|
1212
|
+
line += _("\n 本地已改动:") + _("、").join(item["locally_changed"])
|
|
636
1213
|
lines.append(line)
|
|
637
1214
|
for item in report["opinion"]:
|
|
638
1215
|
if item["status"] == "update-available":
|
|
639
|
-
refs = ";".join(f"{update['current']} → {update['available'][-1]}" for update in item["updates"])
|
|
640
|
-
lines.append(
|
|
1216
|
+
refs = _(";").join(f"{update['current']} → {update['available'][-1]}" for update in item["updates"])
|
|
1217
|
+
lines.append(_(" [Opinion] 有新版本:{0}(用 opinion-manager 预览后确认)").format(refs))
|
|
641
1218
|
elif item["status"] in {"error", "unknown"}:
|
|
642
1219
|
lines.append(f" [Opinion] {item.get('error')}")
|
|
643
|
-
lines += render_scaffold(report, show_skipped)
|
|
1220
|
+
lines += render_scaffold(report, show_skipped, details, show_extras)
|
|
644
1221
|
lines += render_machine(report)
|
|
1222
|
+
lines += [_(" [语言] {0}").format(hint) for hint in (report.get("language") or {}).get("hints", [])]
|
|
645
1223
|
if not report["plugins"]:
|
|
646
|
-
lines.append(
|
|
1224
|
+
lines.append(_("运行 `{0} install` 预览安装。").format(CLI))
|
|
647
1225
|
else:
|
|
648
1226
|
if any(item["status"] == "legacy" for item in report["plugins"]):
|
|
649
|
-
lines.append(
|
|
650
|
-
|
|
1227
|
+
lines.append(_("旧方式安装可用 `{0}` 预览迁移。").format(UPDATE_HINTS['legacy']))
|
|
1228
|
+
if report["summary"].get("legacy_other_clients"):
|
|
1229
|
+
lines.append(_("其中 {0} 个旧方式安装不属于所选客户端(或无法判断归属),已列出但未计入“是否最新”。").format(
|
|
1230
|
+
report["summary"]["legacy_other_clients"]))
|
|
1231
|
+
lines.append(one_line(report) or _("全部为最新。"))
|
|
651
1232
|
return "\n".join(lines) + "\n"
|
|
652
1233
|
|
|
653
1234
|
|
|
@@ -668,15 +1249,82 @@ def notice_due(env: Env, message: str) -> bool:
|
|
|
668
1249
|
return True
|
|
669
1250
|
|
|
670
1251
|
|
|
1252
|
+
# ---------------------------------------------------------------- last hook error (diagnosability)
|
|
1253
|
+
|
|
1254
|
+
HOOK_ERROR_LIMIT = 5
|
|
1255
|
+
HOOK_ERROR_TEXT_CHARS = 160
|
|
1256
|
+
|
|
1257
|
+
|
|
1258
|
+
def hook_error_file(env: Env) -> Path:
|
|
1259
|
+
return env.state_dir / "agenthelm" / "hook-errors.json"
|
|
1260
|
+
|
|
1261
|
+
|
|
1262
|
+
def summarize_error(env: Env, error: BaseException | str) -> tuple[str, str]:
|
|
1263
|
+
"""Exception type and a one-line, truncated message; the home directory is shortened to ``~``. Never user input."""
|
|
1264
|
+
kind = type(error).__name__ if isinstance(error, BaseException) else "Error"
|
|
1265
|
+
text = str(error) if error is not None else ""
|
|
1266
|
+
text = next((line.strip() for line in text.splitlines() if line.strip()), "")
|
|
1267
|
+
text = text.replace(str(env.home), "~")
|
|
1268
|
+
text = "".join(ch if ch.isprintable() else " " for ch in text)
|
|
1269
|
+
return kind, text[:HOOK_ERROR_TEXT_CHARS]
|
|
1270
|
+
|
|
1271
|
+
|
|
1272
|
+
def record_hook_error(env: Env, hook_name: str, error: BaseException | str) -> None:
|
|
1273
|
+
"""Remember the latest hook failures (newest last, at most HOOK_ERROR_LIMIT) in the user state dir.
|
|
1274
|
+
Hooks must stay silent, so every failure here is swallowed too."""
|
|
1275
|
+
try:
|
|
1276
|
+
kind, message = summarize_error(env, error)
|
|
1277
|
+
path = hook_error_file(env)
|
|
1278
|
+
try:
|
|
1279
|
+
data = read_json(path)
|
|
1280
|
+
entries = data.get("errors") if isinstance(data, dict) else []
|
|
1281
|
+
entries = [item for item in entries if isinstance(item, dict)] if isinstance(entries, list) else []
|
|
1282
|
+
except (OSError, ValueError):
|
|
1283
|
+
entries = []
|
|
1284
|
+
entries.append({"at": time.strftime("%Y-%m-%dT%H:%M:%S%z"), "hook": str(hook_name)[:40],
|
|
1285
|
+
"type": kind[:60], "message": message})
|
|
1286
|
+
write_json_atomic(path, {"errors": entries[-HOOK_ERROR_LIMIT:]})
|
|
1287
|
+
except Exception: # noqa: BLE001 - recording a failure must never itself fail a session
|
|
1288
|
+
pass
|
|
1289
|
+
|
|
1290
|
+
|
|
1291
|
+
def read_hook_errors(env: Env) -> list[dict]:
|
|
1292
|
+
try:
|
|
1293
|
+
data = read_json(hook_error_file(env))
|
|
1294
|
+
except (OSError, ValueError):
|
|
1295
|
+
return []
|
|
1296
|
+
entries = data.get("errors") if isinstance(data, dict) else None
|
|
1297
|
+
return [item for item in entries if isinstance(item, dict)] if isinstance(entries, list) else []
|
|
1298
|
+
|
|
1299
|
+
|
|
1300
|
+
def last_hook_error(env: Env) -> dict | None:
|
|
1301
|
+
"""Stable shape for status/doctor JSON: {at, hook, type, message, count} or None."""
|
|
1302
|
+
entries = read_hook_errors(env)
|
|
1303
|
+
if not entries:
|
|
1304
|
+
return None
|
|
1305
|
+
last = entries[-1]
|
|
1306
|
+
return {"at": str(last.get("at", "")), "hook": str(last.get("hook", "")), "type": str(last.get("type", "")),
|
|
1307
|
+
"message": str(last.get("message", "")), "count": len(entries)}
|
|
1308
|
+
|
|
1309
|
+
|
|
1310
|
+
def clear_hook_errors(env: Env) -> bool:
|
|
1311
|
+
try:
|
|
1312
|
+
hook_error_file(env).unlink()
|
|
1313
|
+
return True
|
|
1314
|
+
except OSError:
|
|
1315
|
+
return False
|
|
1316
|
+
|
|
1317
|
+
|
|
671
1318
|
def hook(env: Env, project: Path | None, output: str) -> int:
|
|
672
1319
|
"""Session-start entry: silent unless something is behind; never fails the session."""
|
|
673
1320
|
if not update_check_enabled(env):
|
|
674
1321
|
return 0
|
|
675
1322
|
try:
|
|
676
1323
|
report = run_check(env, project, hook_mode=True)
|
|
677
|
-
except Exception: # noqa: BLE001 - an update notice must never break a session
|
|
1324
|
+
except Exception as exc: # noqa: BLE001 - an update notice must never break a session
|
|
1325
|
+
record_hook_error(env, "update-check", exc)
|
|
678
1326
|
return 0
|
|
679
|
-
message = one_line(report)
|
|
1327
|
+
message = "\n".join(part for part in (one_line(report), (report.get("language") or {}).get("session_hint")) if part) or None
|
|
680
1328
|
if message is None or not notice_due(env, message):
|
|
681
1329
|
return 0
|
|
682
1330
|
if output == "claude-hook":
|
|
@@ -695,7 +1343,7 @@ CLIENTS = ("claude", "codex", "cursor")
|
|
|
695
1343
|
def github_slug(latest: dict) -> str:
|
|
696
1344
|
match = re.match(r"https://github\.com/([^/]+/[^/]+?)(?:\.git)?/?$", str(latest.get("repository", "")))
|
|
697
1345
|
if not match:
|
|
698
|
-
raise CheckError(
|
|
1346
|
+
raise CheckError(_("latest.json 的 repository 不是 GitHub 仓库:{0}").format(latest.get('repository')))
|
|
699
1347
|
return match.group(1)
|
|
700
1348
|
|
|
701
1349
|
|
|
@@ -715,9 +1363,9 @@ def _safe_extract(archive: Path, destination: Path) -> None:
|
|
|
715
1363
|
for member in bundle.getmembers():
|
|
716
1364
|
target = (destination / member.name).resolve()
|
|
717
1365
|
if destination.resolve() not in target.parents and target != destination.resolve():
|
|
718
|
-
raise CheckError(
|
|
1366
|
+
raise CheckError(_("发布包含越界路径:{0}").format(member.name))
|
|
719
1367
|
if not (member.isfile() or member.isdir()):
|
|
720
|
-
raise CheckError(
|
|
1368
|
+
raise CheckError(_("发布包含不支持的条目:{0}").format(member.name))
|
|
721
1369
|
try:
|
|
722
1370
|
bundle.extractall(destination, filter="data") # noqa: S202 - members validated above
|
|
723
1371
|
except TypeError: # Python without extraction filters
|
|
@@ -748,25 +1396,25 @@ def release_source(latest: dict, workdir: Path, source: Path | None = None) -> P
|
|
|
748
1396
|
if source is not None:
|
|
749
1397
|
root = source.expanduser().resolve()
|
|
750
1398
|
if not (root / "plugins").is_dir():
|
|
751
|
-
raise CheckError(
|
|
1399
|
+
raise CheckError(_("{0} 不含 plugins/ 目录").format(root))
|
|
752
1400
|
return root
|
|
753
1401
|
release = latest.get("release") or github_release(latest)
|
|
754
1402
|
tag, digest = release.get("tag"), release.get("tarball_sha256")
|
|
755
1403
|
if not tag or not digest:
|
|
756
|
-
raise
|
|
1404
|
+
raise Unavailable(_("云端 latest.json 没有发布 tag 与摘要;请用 --source 指定本地仓库"))
|
|
757
1405
|
url = release.get("tarball_url") or f"https://github.com/{github_slug(latest)}/releases/download/{tag}/agenthelm-{tag}.tar.gz"
|
|
758
1406
|
archive = workdir / "release.tar.gz"
|
|
759
1407
|
request = urllib.request.Request(url, headers={"User-Agent": "agenthelm"})
|
|
760
1408
|
with urllib.request.urlopen(request, timeout=60) as response, archive.open("wb") as handle: # noqa: S310
|
|
761
1409
|
shutil.copyfileobj(response, handle)
|
|
762
1410
|
if sha256_file(archive) != digest:
|
|
763
|
-
raise CheckError(
|
|
1411
|
+
raise CheckError(_("发布包摘要不符:{0}").format(url))
|
|
764
1412
|
extracted = workdir / "release"
|
|
765
1413
|
extracted.mkdir()
|
|
766
1414
|
_safe_extract(archive, extracted)
|
|
767
1415
|
roots = [path for path in extracted.iterdir() if path.is_dir()]
|
|
768
1416
|
if len(roots) != 1 or not (roots[0] / "plugins").is_dir():
|
|
769
|
-
raise CheckError("发布包结构不符合预期")
|
|
1417
|
+
raise CheckError(_("发布包结构不符合预期"))
|
|
770
1418
|
return roots[0]
|
|
771
1419
|
|
|
772
1420
|
|
|
@@ -779,7 +1427,11 @@ def _agent_pack_config():
|
|
|
779
1427
|
|
|
780
1428
|
@dataclass
|
|
781
1429
|
class Step:
|
|
782
|
-
"""One planned action; ``command`` runs a client CLI, ``action`` runs in-process.
|
|
1430
|
+
"""One planned action; ``command`` runs a client CLI, ``action`` runs in-process.
|
|
1431
|
+
|
|
1432
|
+
``verify`` lists the plugins whose installed version is read back before and after the step (``targets`` holds
|
|
1433
|
+
the version each is expected to reach); ``skipped`` marks a step that has nothing to do and why.
|
|
1434
|
+
"""
|
|
783
1435
|
|
|
784
1436
|
kind: str
|
|
785
1437
|
client: str | None
|
|
@@ -787,6 +1439,12 @@ class Step:
|
|
|
787
1439
|
command: list[str] | None = None
|
|
788
1440
|
action: Any = None
|
|
789
1441
|
blocked: str | None = None
|
|
1442
|
+
verify: list[str] | None = None
|
|
1443
|
+
targets: dict[str, str | None] = field(default_factory=dict)
|
|
1444
|
+
scope: str | None = None
|
|
1445
|
+
skipped: str | None = None
|
|
1446
|
+
note: str | None = None
|
|
1447
|
+
untouched: bool = False # an install the tool recognises but leaves alone (development / local)
|
|
790
1448
|
|
|
791
1449
|
def view(self) -> dict:
|
|
792
1450
|
data = {"kind": self.kind, "client": self.client, "description": self.description}
|
|
@@ -794,9 +1452,31 @@ class Step:
|
|
|
794
1452
|
data["command"] = " ".join(self.command)
|
|
795
1453
|
if self.blocked:
|
|
796
1454
|
data["blocked"] = self.blocked
|
|
1455
|
+
if self.skipped:
|
|
1456
|
+
data["skipped"] = self.skipped
|
|
1457
|
+
if self.note:
|
|
1458
|
+
data["note"] = self.note
|
|
1459
|
+
if self.untouched:
|
|
1460
|
+
data["untouched"] = True
|
|
797
1461
|
return data
|
|
798
1462
|
|
|
799
1463
|
|
|
1464
|
+
def untouched_steps(env: Env, names: set[str], clients: list[str], kind: str = "update") -> list[Step]:
|
|
1465
|
+
"""Steps that only say "this install is not touched": development / local installs of agenthelm plugins."""
|
|
1466
|
+
steps = []
|
|
1467
|
+
found = [item for item in installed_plugins(env, names) if item.get("dev")] + other_installs(env, names)
|
|
1468
|
+
for item in found:
|
|
1469
|
+
if item["client"] not in clients:
|
|
1470
|
+
continue
|
|
1471
|
+
source = item.get("marketplace")
|
|
1472
|
+
origin = _origin_text(_install_record(item))
|
|
1473
|
+
steps.append(Step(kind, item["client"], _("{0} {1} {2}({3}:{4})").format(
|
|
1474
|
+
CLIENT_NAMES[item["client"]], item["plugin"], item.get("version") or "?", origin, item["path"]) + (f" [{source}]" if source else ""),
|
|
1475
|
+
skipped=_("不会改动:开发版/本地安装默认不被 update / migrate 改动;想纳入市场管理,请自行卸载这处安装后运行 `{0} install`").format(CLI),
|
|
1476
|
+
untouched=True))
|
|
1477
|
+
return steps
|
|
1478
|
+
|
|
1479
|
+
|
|
800
1480
|
def known_cli_locations(env: Env, name: str) -> list[Path]:
|
|
801
1481
|
"""Where a client's command line lives when it is not on PATH (GUI apps, per-user installs)."""
|
|
802
1482
|
home = env.home
|
|
@@ -824,32 +1504,59 @@ def find_cli(env: Env, name: str) -> str | None:
|
|
|
824
1504
|
def _cli(env: Env, name: str, *args: str) -> tuple[list[str], str | None]:
|
|
825
1505
|
"""The command (using the resolved executable) and why it cannot run, if it cannot."""
|
|
826
1506
|
found = find_cli(env, name)
|
|
827
|
-
return [found or name, *args], (None if found else
|
|
1507
|
+
return [found or name, *args], (None if found else _("未找到 {0} 命令(已查 PATH 与常见安装位置;可用 AGENTHELM_{1} 指定)").format(name, name.upper()))
|
|
1508
|
+
|
|
1509
|
+
|
|
1510
|
+
def installed_versions(env: Env, client: str | None, plugins: list[str], scope: str | None = None) -> dict[str, str | None]:
|
|
1511
|
+
"""The version of each plugin installed in ``client`` right now (None: not installed or unreadable)."""
|
|
1512
|
+
found: dict[str, str | None] = {}
|
|
1513
|
+
for item in installed_plugins(env, set(plugins)):
|
|
1514
|
+
if item["client"] != client or (scope and item.get("scope") and item["scope"] != scope):
|
|
1515
|
+
continue
|
|
1516
|
+
kept = found.get(item["plugin"])
|
|
1517
|
+
if item["plugin"] not in found or (version_key(item.get("version") or "") or (0,)) > (version_key(kept or "") or (0,)):
|
|
1518
|
+
found[item["plugin"]] = item.get("version")
|
|
1519
|
+
return {plugin: found.get(plugin) for plugin in plugins}
|
|
1520
|
+
|
|
1521
|
+
|
|
1522
|
+
def already_installed_reason(version: str | None, target: str | None) -> str:
|
|
1523
|
+
if version and target and is_newer(target, version):
|
|
1524
|
+
return _("已安装 {0},云端是 {1}:install 不会升级已安装的插件,请用 `{2} update`").format(version, target, CLI)
|
|
1525
|
+
if version and target and is_newer(version, target):
|
|
1526
|
+
return _("已安装 {0}(高于云端的 {1}):install 不会改动已安装的插件").format(version, target)
|
|
1527
|
+
return _("已安装 {0},已是最新:install 不会改动已安装的插件").format(version)
|
|
828
1528
|
|
|
829
1529
|
|
|
830
1530
|
def install_steps(env: Env, latest: dict, clients: list[str], plugins: list[str], source: Path | None,
|
|
831
1531
|
home: Path, marketplace_source: str | None = None) -> list[Step]:
|
|
832
1532
|
slug = marketplace_source or github_slug(latest)
|
|
1533
|
+
targets = {plugin: latest.get("plugins", {}).get(plugin, {}).get("version") for plugin in plugins}
|
|
833
1534
|
steps: list[Step] = []
|
|
1535
|
+
foreign = {(item["client"], item["plugin"]) for item in other_installs(env, set(plugins))}
|
|
834
1536
|
for client in clients:
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
steps.append(Step("install", "claude", f"Claude Code 安装 {plugin}", command, blocked=blocked))
|
|
841
|
-
elif client == "codex":
|
|
842
|
-
command, blocked = _cli(env, "codex", "plugin", "marketplace", "add", slug)
|
|
843
|
-
steps.append(Step("install", "codex", f"Codex 添加 agenthelm 市场({slug})", command, blocked=blocked))
|
|
1537
|
+
present = installed_versions(env, client, plugins)
|
|
1538
|
+
if client in ("claude", "codex"):
|
|
1539
|
+
name = CLIENT_NAMES[client]
|
|
1540
|
+
command, blocked = _cli(env, client, "plugin", "marketplace", "add", slug)
|
|
1541
|
+
steps.append(Step("install", client, _("{0} 添加 agenthelm 市场({1})").format(name, slug), command, blocked=blocked))
|
|
844
1542
|
for plugin in plugins:
|
|
845
|
-
|
|
846
|
-
|
|
1543
|
+
add = ("plugin", "install") if client == "claude" else ("plugin", "add")
|
|
1544
|
+
command, blocked = _cli(env, client, *add, f"{plugin}@{MARKETPLACE}")
|
|
1545
|
+
keep_foreign = (client, plugin) in foreign and not present[plugin] # nothing runs, so a missing CLI is irrelevant
|
|
1546
|
+
steps.append(Step("install", client, _("{0} 安装 {1}").format(name, plugin), command,
|
|
1547
|
+
blocked=None if keep_foreign else blocked,
|
|
1548
|
+
verify=[plugin], targets={plugin: targets[plugin]},
|
|
1549
|
+
skipped=(already_installed_reason(present[plugin], targets[plugin]) if present[plugin] else
|
|
1550
|
+
_("不会改动:已有来自其他市场的开发版/本地安装,不再重复安装(想改用 agenthelm 市场,请自行卸载后重试)")
|
|
1551
|
+
if (client, plugin) in foreign else None),
|
|
1552
|
+
untouched=keep_foreign))
|
|
847
1553
|
elif client == "cursor":
|
|
848
|
-
steps.append(cursor_step(latest, plugins, source, home, "安装"))
|
|
1554
|
+
steps.append(cursor_step(latest, plugins, source, home, _("安装"), env=env))
|
|
849
1555
|
return steps
|
|
850
1556
|
|
|
851
1557
|
|
|
852
|
-
def cursor_step(latest: dict, plugins: list[str], source: Path | None, home: Path, verb: str
|
|
1558
|
+
def cursor_step(latest: dict, plugins: list[str], source: Path | None, home: Path, verb: str,
|
|
1559
|
+
env: Env | None = None) -> Step:
|
|
853
1560
|
def run(apply: bool, recovery_root: Path | None) -> list[dict]:
|
|
854
1561
|
config = _agent_pack_config()
|
|
855
1562
|
with tempfile.TemporaryDirectory(prefix="agenthelm-") as temporary:
|
|
@@ -857,13 +1564,20 @@ def cursor_step(latest: dict, plugins: list[str], source: Path | None, home: Pat
|
|
|
857
1564
|
return [config.install_plugin(root / "plugins" / plugin, "cursor", home=home, apply=apply,
|
|
858
1565
|
replace=True, recovery_root=recovery_root)
|
|
859
1566
|
for plugin in plugins]
|
|
860
|
-
|
|
861
|
-
|
|
1567
|
+
note = None
|
|
1568
|
+
if env is not None:
|
|
1569
|
+
present = {plugin: version for plugin, version in installed_versions(env, "cursor", plugins).items() if version}
|
|
1570
|
+
if present:
|
|
1571
|
+
note = _("已安装 {0};会用发布包里的版本覆盖它们").format(
|
|
1572
|
+
_("、").join(f"{plugin} {version}" for plugin, version in present.items()))
|
|
1573
|
+
return Step("install", "cursor", _("Cursor {0} {1} 到 ~/.cursor/plugins/local(重启 Cursor 生效)").format(verb, _('、').join(plugins)),
|
|
1574
|
+
action=run, verify=list(plugins),
|
|
1575
|
+
targets={plugin: latest.get("plugins", {}).get(plugin, {}).get("version") for plugin in plugins}, note=note)
|
|
862
1576
|
|
|
863
1577
|
|
|
864
1578
|
def update_steps(env: Env, report: dict, project: Path | None, source: Path | None, home: Path,
|
|
865
1579
|
accept: list[str], keep: list[str], recovery_dir: Path | None,
|
|
866
|
-
only: str | None) -> list[Step]:
|
|
1580
|
+
only: str | None, *, content_flags: list[str] | None = None) -> list[Step]:
|
|
867
1581
|
latest = report["_latest"]
|
|
868
1582
|
steps: list[Step] = []
|
|
869
1583
|
behind = [item for item in report["plugins"] if item["status"] == "behind"]
|
|
@@ -871,44 +1585,52 @@ def update_steps(env: Env, report: dict, project: Path | None, source: Path | No
|
|
|
871
1585
|
claude = sorted({item["plugin"] for item in behind if item["client"] == "claude"})
|
|
872
1586
|
if claude:
|
|
873
1587
|
command, blocked = _cli(env, "claude", "plugin", "marketplace", "update", MARKETPLACE)
|
|
874
|
-
steps.append(Step("update", "claude", "刷新 Claude Code 的 agenthelm 市场", command, blocked=blocked))
|
|
1588
|
+
steps.append(Step("update", "claude", _("刷新 Claude Code 的 agenthelm 市场"), command, blocked=blocked))
|
|
875
1589
|
for item in [entry for entry in behind if entry["client"] == "claude"]:
|
|
876
1590
|
extra = ["--scope", item["scope"]] if item.get("scope") and item["scope"] != "user" else []
|
|
877
1591
|
command, blocked = _cli(env, "claude", "plugin", "update", f"{item['plugin']}@{MARKETPLACE}", *extra)
|
|
878
|
-
steps.append(Step("update", "claude",
|
|
879
|
-
command, blocked=blocked
|
|
880
|
-
|
|
1592
|
+
steps.append(Step("update", "claude", _("Claude Code 更新 {0} → {1}").format(item['plugin'], item['latest']),
|
|
1593
|
+
command, blocked=blocked, verify=[item["plugin"]],
|
|
1594
|
+
targets={item["plugin"]: item["latest"]}, scope=item.get("scope")))
|
|
1595
|
+
codex = [item for item in behind if item["client"] == "codex"]
|
|
1596
|
+
if codex:
|
|
881
1597
|
command, blocked = _cli(env, "codex", "plugin", "marketplace", "upgrade", MARKETPLACE)
|
|
882
|
-
steps.append(Step("update", "codex", "Codex 升级 agenthelm 市场与已装插件", command, blocked=blocked
|
|
1598
|
+
steps.append(Step("update", "codex", _("Codex 升级 agenthelm 市场与已装插件"), command, blocked=blocked,
|
|
1599
|
+
verify=sorted({item["plugin"] for item in codex}),
|
|
1600
|
+
targets={item["plugin"]: item["latest"] for item in codex}))
|
|
883
1601
|
cursor = sorted({item["plugin"] for item in behind if item["client"] == "cursor"})
|
|
884
1602
|
if cursor:
|
|
885
|
-
steps.append(cursor_step(latest, cursor, source, home, "更新"))
|
|
1603
|
+
steps.append(cursor_step(latest, cursor, source, home, _("更新"), env=env))
|
|
1604
|
+
steps[-1].targets = {item["plugin"]: item["latest"] for item in behind if item["client"] == "cursor"}
|
|
1605
|
+
if only in (None, "plugins"):
|
|
1606
|
+
steps += untouched_steps(env, set(latest.get("plugins", {})), list((report.get("install_state") or {}).get("clients", {})))
|
|
886
1607
|
if only in (None, "content") and project is not None:
|
|
887
1608
|
for item in report["content"]:
|
|
888
1609
|
if item.get("status") not in {"update-available", "conflict"}:
|
|
889
1610
|
continue
|
|
890
|
-
steps.append(content_step(env, item, report, project, accept, keep, recovery_dir))
|
|
1611
|
+
steps.append(content_step(env, item, report, project, accept, keep, recovery_dir, content_flags=content_flags))
|
|
891
1612
|
return steps
|
|
892
1613
|
|
|
893
1614
|
|
|
894
1615
|
def content_step(env: Env, item: dict, report: dict, project: Path, accept: list[str], keep: list[str],
|
|
895
|
-
recovery_dir: Path | None) -> Step:
|
|
1616
|
+
recovery_dir: Path | None, *, content_flags: list[str] | None = None) -> Step:
|
|
896
1617
|
if item["plugin"] != "agents-init":
|
|
897
|
-
return Step("content", None,
|
|
1618
|
+
return Step("content", None, _("{0}:没有可用的刷新工具").format(item['pack']), blocked="unsupported")
|
|
898
1619
|
stale = any(entry["plugin"] == "agents-init" and entry["status"] == "behind" for entry in report["plugins"])
|
|
899
|
-
description =
|
|
1620
|
+
description = _("重新渲染 {0} {1} → {2}").format(item['pack'], item['version'], item['latest'])
|
|
900
1621
|
|
|
901
1622
|
def run(apply: bool, _recovery_root: Path | None) -> dict:
|
|
902
1623
|
installed = installed_plugins(env, {"agents-init"})
|
|
903
1624
|
manager = locate_companion("agents-init", installed)
|
|
904
1625
|
if manager is None:
|
|
905
|
-
raise CheckError("未找到已安装的 agents-init")
|
|
1626
|
+
raise CheckError(_("未找到已安装的 agents-init"))
|
|
906
1627
|
command = [sys.executable, str(manager / "skills/agents-init/scripts/init_project.py"),
|
|
907
1628
|
"--project", str(project), "--mode", "refresh", "--output", "json"]
|
|
908
1629
|
for path in accept:
|
|
909
1630
|
command += ["--accept", path]
|
|
910
1631
|
for path in keep:
|
|
911
1632
|
command += ["--keep", path]
|
|
1633
|
+
command += content_flags or [] # --append / --confirm-discard / --diff
|
|
912
1634
|
if recovery_dir is not None:
|
|
913
1635
|
command += ["--recovery-dir", str(recovery_dir)]
|
|
914
1636
|
if apply:
|
|
@@ -916,41 +1638,195 @@ def content_step(env: Env, item: dict, report: dict, project: Path, accept: list
|
|
|
916
1638
|
completed = subprocess.run(command, capture_output=True, text=True, check=False,
|
|
917
1639
|
env=env.child_environment())
|
|
918
1640
|
try:
|
|
919
|
-
|
|
1641
|
+
outcome = json.loads(completed.stdout)
|
|
920
1642
|
except ValueError as exc:
|
|
921
1643
|
raise CheckError((completed.stderr or completed.stdout).strip()[:300]) from exc
|
|
1644
|
+
if completed.returncode not in (0, 1) and isinstance(outcome, dict) and outcome.get("error"):
|
|
1645
|
+
# Exit 1 is a normal "blocked, choose per file"; anything else (e.g. no usable backup folder) is a failure.
|
|
1646
|
+
raise CheckError(str(outcome["error"]))
|
|
1647
|
+
return outcome
|
|
922
1648
|
|
|
923
|
-
blocked = "先更新 agents-init 插件,再用新模板预览" if stale else None
|
|
1649
|
+
blocked = _("先更新 agents-init 插件,再用新模板预览") if stale else None
|
|
924
1650
|
return Step("content", None, description, action=run, blocked=blocked)
|
|
925
1651
|
|
|
926
1652
|
|
|
1653
|
+
STDERR_LINES = 20
|
|
1654
|
+
|
|
1655
|
+
# Failure texts the client CLIs are known to print: (pattern, what it means, what to do next).
|
|
1656
|
+
KNOWN_FAILURES = (
|
|
1657
|
+
(re.compile(r"network source differs|differs from the one declared", re.I),
|
|
1658
|
+
N_("市场来源与 settings.json 里的声明不一致:Claude Code 要求这个市场名下的来源,与 settings 里 extraKnownMarketplaces 为它声明的来源一致。"),
|
|
1659
|
+
N_("把 --marketplace-source 改成与 ~/.claude/settings.json 里 extraKnownMarketplaces.agenthelm 声明相同的来源(含 ref),"
|
|
1660
|
+
"或先修改那处声明,再重试。")),
|
|
1661
|
+
)
|
|
1662
|
+
|
|
1663
|
+
|
|
1664
|
+
def explain_failure(stderr: str) -> tuple[str, str] | None:
|
|
1665
|
+
for pattern, reason, advice in KNOWN_FAILURES:
|
|
1666
|
+
if pattern.search(stderr):
|
|
1667
|
+
return _(reason), _(advice)
|
|
1668
|
+
return None
|
|
1669
|
+
|
|
1670
|
+
|
|
1671
|
+
def tail_lines(text: str, limit: int = STDERR_LINES) -> str:
|
|
1672
|
+
lines = text.strip().splitlines()
|
|
1673
|
+
if len(lines) <= limit:
|
|
1674
|
+
return "\n".join(lines)
|
|
1675
|
+
return _("…(前面省略 {0} 行)").format(len(lines) - limit) + "\n" + "\n".join(lines[-limit:])
|
|
1676
|
+
|
|
1677
|
+
|
|
1678
|
+
UNCHANGED_REASONS = {
|
|
1679
|
+
"claude": N_("该客户端的市场条目 version 没有变(Claude Code 只看市场条目的 version 判断是否有更新),或市场没有固定到这个版本"),
|
|
1680
|
+
"codex": N_("该客户端的市场没有固定到此版本(可能在跟随默认分支,升级到的是那里的版本)"),
|
|
1681
|
+
"cursor": N_("发布包里的版本与已装的相同,文件已按发布包重写"),
|
|
1682
|
+
}
|
|
1683
|
+
|
|
1684
|
+
|
|
1685
|
+
def verify_step(step: Step, record: dict, before: dict, after: dict) -> None:
|
|
1686
|
+
"""Compare the versions read back around a step that ran fine; say whether it took effect and why not."""
|
|
1687
|
+
changes = []
|
|
1688
|
+
for plugin in step.verify or []:
|
|
1689
|
+
target = step.targets.get(plugin)
|
|
1690
|
+
entry = {"plugin": plugin, "before": before.get(plugin), "after": after.get(plugin), "target": target}
|
|
1691
|
+
entry["changed"] = entry["before"] != entry["after"]
|
|
1692
|
+
changes.append(entry)
|
|
1693
|
+
record["changes"] = changes
|
|
1694
|
+
if len(changes) == 1:
|
|
1695
|
+
record["before"], record["after"] = changes[0]["before"], changes[0]["after"]
|
|
1696
|
+
unchanged = [entry for entry in changes if not entry["changed"]]
|
|
1697
|
+
if not unchanged:
|
|
1698
|
+
return
|
|
1699
|
+
record["status"] = "unchanged"
|
|
1700
|
+
if all(entry["after"] is None for entry in unchanged):
|
|
1701
|
+
record["reason"] = _("命令成功,但读不到该客户端里这个插件的版本,无法确认是否生效")
|
|
1702
|
+
elif all(entry["target"] and entry["after"] == entry["target"] for entry in unchanged):
|
|
1703
|
+
record["reason"] = _("已经是目标版本")
|
|
1704
|
+
else:
|
|
1705
|
+
record["reason"] = _(UNCHANGED_REASONS.get(step.client or "", N_("版本没有变化,原因未知")))
|
|
1706
|
+
|
|
1707
|
+
|
|
927
1708
|
def execute_steps(steps: list[Step], *, apply: bool, recovery_root: Path | None,
|
|
928
|
-
child_env: dict[str, str] | None = None) -> list[dict]:
|
|
1709
|
+
child_env: dict[str, str] | None = None, env: Env | None = None) -> list[dict]:
|
|
1710
|
+
"""Run (or preview) the steps. After a failure the same client's remaining steps are not run, other clients' are.
|
|
1711
|
+
|
|
1712
|
+
With ``env`` the installed versions of the plugins a step changes are read back around it, so ``applied`` means the
|
|
1713
|
+
version really moved and ``unchanged`` means the command succeeded but nothing changed.
|
|
1714
|
+
"""
|
|
929
1715
|
results = []
|
|
1716
|
+
failed_clients: dict[str | None, str] = {}
|
|
930
1717
|
for step in steps:
|
|
931
1718
|
record = step.view()
|
|
932
|
-
if step.blocked:
|
|
1719
|
+
if apply and step.client is not None and step.client in failed_clients and not step.blocked:
|
|
1720
|
+
record["status"] = "not_run"
|
|
1721
|
+
record["reason"] = _("同一客户端前面的步骤失败({0}),这一步没有执行").format(failed_clients[step.client])
|
|
1722
|
+
elif step.skipped:
|
|
1723
|
+
# Nothing would run, so a missing client command is irrelevant: skipped wins over blocked.
|
|
1724
|
+
record["status"] = "skipped"
|
|
1725
|
+
record.pop("blocked", None)
|
|
1726
|
+
elif step.blocked:
|
|
933
1727
|
record["status"] = "blocked"
|
|
934
|
-
elif step.action is not None:
|
|
935
|
-
try:
|
|
936
|
-
record["result"] = step.action(apply, recovery_root)
|
|
937
|
-
record["status"] = "applied" if apply else "preview"
|
|
938
|
-
except Exception as exc: # noqa: BLE001 - report every step, stop nothing silently
|
|
939
|
-
record["status"], record["error"] = "failed", str(exc)
|
|
940
|
-
elif apply:
|
|
941
|
-
completed = subprocess.run(step.command, capture_output=True, text=True, check=False, env=child_env)
|
|
942
|
-
record["status"] = "applied" if completed.returncode == 0 else "failed"
|
|
943
|
-
output = (completed.stdout + completed.stderr).strip()
|
|
944
|
-
if output:
|
|
945
|
-
record["output"] = output[-600:]
|
|
946
1728
|
else:
|
|
947
|
-
|
|
1729
|
+
before = installed_versions(env, step.client, step.verify, step.scope) if apply and env and step.verify else {}
|
|
1730
|
+
if step.action is not None:
|
|
1731
|
+
try:
|
|
1732
|
+
record["result"] = step.action(apply, recovery_root)
|
|
1733
|
+
record["status"] = "applied" if apply else "preview"
|
|
1734
|
+
outcome = record["result"]
|
|
1735
|
+
if apply and isinstance(outcome, dict) and outcome.get("applied") is False and outcome.get("blocked"):
|
|
1736
|
+
# Files still wait for a choice: nothing was written, so this is not "done".
|
|
1737
|
+
record["status"], record["needs_choice"] = "blocked", True
|
|
1738
|
+
except Unavailable as exc:
|
|
1739
|
+
record["status"], record["error"] = "unavailable", str(exc)
|
|
1740
|
+
if step.client == "cursor":
|
|
1741
|
+
record["next"] = _("用 --source <本地仓库> 指向本地检出;不使用 Cursor 时用 --client 只选其他客户端,"
|
|
1742
|
+
"或长期忽略:{0} config ignore-client cursor --apply").format(CLI)
|
|
1743
|
+
except Exception as exc: # noqa: BLE001 - report every step, stop nothing silently
|
|
1744
|
+
record["status"], record["error"] = "failed", str(exc)
|
|
1745
|
+
elif apply:
|
|
1746
|
+
try:
|
|
1747
|
+
completed = subprocess.run(step.command, capture_output=True, text=True, check=False, env=child_env)
|
|
1748
|
+
except OSError as exc:
|
|
1749
|
+
record.update({"status": "failed", "exit_code": None, "stderr": "", "error": str(exc)})
|
|
1750
|
+
else:
|
|
1751
|
+
record["status"] = "applied" if completed.returncode == 0 else "failed"
|
|
1752
|
+
record["exit_code"] = completed.returncode
|
|
1753
|
+
output = (completed.stdout + completed.stderr).strip()
|
|
1754
|
+
if output and completed.returncode == 0:
|
|
1755
|
+
record["output"] = output[-600:]
|
|
1756
|
+
if completed.returncode != 0:
|
|
1757
|
+
record["stderr"] = tail_lines(completed.stderr)
|
|
1758
|
+
last = next((line.strip() for line in reversed(completed.stderr.splitlines()) if line.strip()), "")
|
|
1759
|
+
record["error"] = _("命令退出码 {0}").format(completed.returncode) + (_(":{0}").format(last) if last else "")
|
|
1760
|
+
known = explain_failure(completed.stderr)
|
|
1761
|
+
if known:
|
|
1762
|
+
record["reason"], record["next"] = known
|
|
1763
|
+
else:
|
|
1764
|
+
record["status"] = "preview"
|
|
1765
|
+
if apply and env and step.verify and record["status"] == "applied":
|
|
1766
|
+
verify_step(step, record, before, installed_versions(env, step.client, step.verify, step.scope))
|
|
948
1767
|
results.append(record)
|
|
949
1768
|
if apply and record["status"] == "failed":
|
|
950
|
-
|
|
1769
|
+
failed_clients.setdefault(step.client, step.description)
|
|
951
1770
|
return results
|
|
952
1771
|
|
|
953
1772
|
|
|
1773
|
+
CLIENT_ORDER = {name: index for index, name in enumerate(CLIENT_KEYS)}
|
|
1774
|
+
|
|
1775
|
+
|
|
1776
|
+
def step_outcome_ok(results: list[dict]) -> bool:
|
|
1777
|
+
"""False when a step failed, ran without effect, or still waits for a choice."""
|
|
1778
|
+
return not any(r["status"] in {"failed", "unchanged"} or r.get("needs_choice") for r in results)
|
|
1779
|
+
|
|
1780
|
+
|
|
1781
|
+
def outcome_summary(results: list[dict]) -> dict:
|
|
1782
|
+
"""Per-client outcome of an applied run, so one client's trouble neither hides nor taints the others."""
|
|
1783
|
+
rank = {"failed": 0, "unchanged": 1, "unavailable": 2, "blocked": 3, "ok": 4, "skipped": 5}
|
|
1784
|
+
clients: dict[str, dict] = {}
|
|
1785
|
+
for record in results:
|
|
1786
|
+
name = record.get("client") or "content"
|
|
1787
|
+
status = {"applied": "ok", "failed": "failed", "unchanged": "unchanged", "unavailable": "unavailable",
|
|
1788
|
+
"blocked": "blocked", "skipped": "skipped", "not_run": "failed"}.get(record["status"], "ok")
|
|
1789
|
+
entry = clients.setdefault(name, {"status": "skipped", "steps": 0, "applied": 0, "failed": 0, "unchanged": 0,
|
|
1790
|
+
"not_run": 0})
|
|
1791
|
+
entry["steps"] += 1
|
|
1792
|
+
entry["applied"] += record["status"] == "applied"
|
|
1793
|
+
entry["failed"] += record["status"] == "failed"
|
|
1794
|
+
entry["unchanged"] += record["status"] == "unchanged"
|
|
1795
|
+
entry["not_run"] += record["status"] == "not_run"
|
|
1796
|
+
if rank[status] < rank[entry["status"]]:
|
|
1797
|
+
entry["status"] = status
|
|
1798
|
+
if status in {"unavailable"} and record.get("error"):
|
|
1799
|
+
entry["reason"] = record["error"]
|
|
1800
|
+
return {"ok": step_outcome_ok(results), "clients": clients}
|
|
1801
|
+
|
|
1802
|
+
|
|
1803
|
+
def render_outcome(results: list[dict]) -> list[str]:
|
|
1804
|
+
"""The closing lines of an applied run: what took effect, what did not, and which clients are unaffected."""
|
|
1805
|
+
summary = outcome_summary(results)
|
|
1806
|
+
names = {**CLIENT_NAMES, "content": _("项目内容")}
|
|
1807
|
+
lines = [_("汇总:")]
|
|
1808
|
+
labels = {"ok": _("已完成"), "failed": _("失败"), "unchanged": _("命令成功但版本没有变化"),
|
|
1809
|
+
"unavailable": _("不可用"), "blocked": _("未执行(阻塞)"), "skipped": _("无需操作")}
|
|
1810
|
+
ordered = sorted(summary["clients"].items(), key=lambda item: CLIENT_ORDER.get(item[0], 9))
|
|
1811
|
+
for name, entry in ordered:
|
|
1812
|
+
text = _(" {0}:{1}").format(names.get(name, name), labels[entry['status']])
|
|
1813
|
+
if entry.get("reason"):
|
|
1814
|
+
text += _("({0})").format(entry["reason"])
|
|
1815
|
+
if entry["not_run"]:
|
|
1816
|
+
text += _(";其后 {0} 步没有执行").format(entry["not_run"])
|
|
1817
|
+
lines.append(text)
|
|
1818
|
+
bad = [names.get(n, n) for n, e in ordered if e["status"] in {"failed", "unchanged"}]
|
|
1819
|
+
good = [names.get(n, n) for n, e in ordered if e["status"] == "ok"]
|
|
1820
|
+
if bad:
|
|
1821
|
+
lines.append(_("整体:没有全部成功——{0} 需要处理;{1}").format(
|
|
1822
|
+
_("、").join(bad), (_("其他已完成:{0}。").format(_("、").join(good)) if good else _("没有其他客户端完成。"))))
|
|
1823
|
+
elif any(r.get("needs_choice") for r in results):
|
|
1824
|
+
lines.append(_("整体:还有文件等你选择,尚未完成。"))
|
|
1825
|
+
elif summary["ok"] and good:
|
|
1826
|
+
lines.append(_("整体:已完成。"))
|
|
1827
|
+
return lines
|
|
1828
|
+
|
|
1829
|
+
|
|
954
1830
|
# ---------------------------------------------------------------- legacy migration
|
|
955
1831
|
|
|
956
1832
|
def _personal_marketplace_entries(env: Env, names: set[str]) -> list[str]:
|
|
@@ -1113,6 +1989,13 @@ def locate(env: Env, plugin: str, version: str | None = None, *, include_legacy:
|
|
|
1113
1989
|
"path": found[0]["path"] if found else None, "installs": found}
|
|
1114
1990
|
|
|
1115
1991
|
|
|
1992
|
+
INFORMATIONAL_ISSUES = ("update-check-disabled", "hook-error")
|
|
1993
|
+
|
|
1994
|
+
|
|
1995
|
+
def hook_error_line(failure: dict) -> str:
|
|
1996
|
+
return f"{failure['at']} [{failure['hook']}] {failure['type']}: {failure['message']}".rstrip(": ")
|
|
1997
|
+
|
|
1998
|
+
|
|
1116
1999
|
def doctor(env: Env, report: dict) -> dict:
|
|
1117
2000
|
issues = []
|
|
1118
2001
|
by_plugin: dict[str, list[dict]] = {}
|
|
@@ -1122,112 +2005,178 @@ def doctor(env: Env, report: dict) -> dict:
|
|
|
1122
2005
|
clients = [item["client"] for item in items]
|
|
1123
2006
|
if "legacy" in clients and any(client in {"claude", "codex"} for client in clients):
|
|
1124
2007
|
issues.append({"plugin": plugin, "issue": "duplicate",
|
|
1125
|
-
"detail":
|
|
2008
|
+
"detail": _("同时存在市场安装与旧方式安装,运行 {0} migrate").format(CLI)})
|
|
1126
2009
|
versions = {item.get("version") for item in items if item["client"] != "legacy"}
|
|
1127
2010
|
if len(versions) > 1:
|
|
1128
2011
|
issues.append({"plugin": plugin, "issue": "version-skew",
|
|
1129
|
-
"detail": "各客户端版本不一致:" + "、".join(f"{i['client']}={i.get('version')}" for i in items)})
|
|
2012
|
+
"detail": _("各客户端版本不一致:") + _("、").join(f"{i['client']}={i.get('version')}" for i in items)})
|
|
1130
2013
|
names = set(report["_latest"].get("plugins", {}))
|
|
1131
2014
|
installed_names = {item["plugin"] for item in report["plugins"] if item["client"] != "legacy"}
|
|
1132
2015
|
if installed_names and installed_names != names:
|
|
1133
2016
|
issues.append({"plugin": None, "issue": "incomplete",
|
|
1134
|
-
"detail": "缺少:" + "、".join(sorted(names - installed_names))})
|
|
2017
|
+
"detail": _("缺少:") + _("、").join(sorted(names - installed_names))})
|
|
1135
2018
|
if not update_check_enabled(env):
|
|
1136
|
-
issues.append({"plugin": None, "issue": "update-check-disabled", "detail": "会话内更新检查已关闭"})
|
|
1137
|
-
|
|
1138
|
-
|
|
2019
|
+
issues.append({"plugin": None, "issue": "update-check-disabled", "detail": _("会话内更新检查已关闭")})
|
|
2020
|
+
failure = last_hook_error(env)
|
|
2021
|
+
if failure:
|
|
2022
|
+
issues.append({"plugin": None, "issue": "hook-error", "detail": _("最近一次钩子错误:{0}").format(hook_error_line(failure))
|
|
2023
|
+
+ _(";运行 {0} nudge status --clear-errors 清除").format(CLI)})
|
|
2024
|
+
return {"ok": not [issue for issue in issues if issue["issue"] not in INFORMATIONAL_ISSUES],
|
|
2025
|
+
"issues": issues, "legacy": legacy_artifacts(env, names), "summary": report["summary"],
|
|
2026
|
+
"last_hook_error": failure}
|
|
1139
2027
|
|
|
1140
2028
|
|
|
1141
2029
|
def parser() -> argparse.ArgumentParser:
|
|
1142
|
-
result = argparse.ArgumentParser(prog="agenthelm", description=
|
|
2030
|
+
result = argparse.ArgumentParser(prog="agenthelm", description=_("agenthelm:在 Claude Code、Codex、Cursor 间安装、检查与更新 agenthelm 插件。"))
|
|
1143
2031
|
sub = result.add_subparsers(dest="command", required=True)
|
|
1144
2032
|
|
|
2033
|
+
def refresh(command: argparse.ArgumentParser) -> None:
|
|
2034
|
+
command.add_argument("--refresh", action="store_true", help=_("忽略一天的缓存,立即联网"))
|
|
2035
|
+
|
|
2036
|
+
def client_filter(command: argparse.ArgumentParser, help_text: str | None = None) -> None:
|
|
2037
|
+
command.add_argument("--client", action="append", choices=CLIENTS,
|
|
2038
|
+
help=help_text or _("只处理这个客户端(可重复);默认处理检测到的全部客户端(用户配置 ignored_clients 里的除外)"))
|
|
2039
|
+
|
|
1145
2040
|
def common(command: argparse.ArgumentParser, *, project: bool = True) -> None:
|
|
1146
|
-
command.add_argument("--latest", help="latest.json 的 URL 或本地路径(测试、离线镜像)")
|
|
2041
|
+
command.add_argument("--latest", help=_("latest.json 的 URL 或本地路径(测试、离线镜像)"))
|
|
1147
2042
|
command.add_argument("--output", choices=("text", "json"), default="text")
|
|
1148
2043
|
command.add_argument("--home", type=Path, help=argparse.SUPPRESS)
|
|
1149
2044
|
if project:
|
|
1150
|
-
command.add_argument("--project", type=Path, default=None, help="项目目录;默认当前目录")
|
|
1151
|
-
command.add_argument("--no-project", action="store_true", help="不检查项目内容")
|
|
2045
|
+
command.add_argument("--project", type=Path, default=None, help=_("项目目录;默认当前目录"))
|
|
2046
|
+
command.add_argument("--no-project", action="store_true", help=_("不检查项目内容"))
|
|
1152
2047
|
|
|
1153
|
-
check = sub.add_parser("check", help="只读检查插件、模板/样例与 Opinion 是否落后于云端")
|
|
2048
|
+
check = sub.add_parser("check", help=_("只读检查插件、模板/样例与 Opinion 是否落后于云端"))
|
|
1154
2049
|
common(check)
|
|
1155
|
-
check.add_argument("--offline", action="store_true", help="只用缓存,不联网")
|
|
1156
|
-
check
|
|
1157
|
-
check
|
|
2050
|
+
check.add_argument("--offline", action="store_true", help=_("只用缓存,不联网"))
|
|
2051
|
+
refresh(check)
|
|
2052
|
+
client_filter(check)
|
|
2053
|
+
check.add_argument("--hook", action="store_true", help=_("会话开始时静默调用:有更新才输出一行"))
|
|
1158
2054
|
check.add_argument("--hook-format", choices=("text", "claude-hook"), default="text")
|
|
1159
|
-
check.add_argument("--strict", action="store_true", help="
|
|
1160
|
-
check.add_argument("--show-skipped", action="store_true", help="列出被你跳过的项及理由")
|
|
1161
|
-
check.add_argument("--
|
|
2055
|
+
check.add_argument("--strict", action="store_true", help=_("有可更新项或必须处理的脚手架差异时退出码为 1(CI 用;可选与信息性的差异不算)"))
|
|
2056
|
+
check.add_argument("--show-skipped", action="store_true", help=_("列出被你跳过的项及理由"))
|
|
2057
|
+
check.add_argument("--show-extras", action="store_true", help=_("展开 Profile 中 schema 未声明的字段(项目自有、疑似拼写错误、已被其他插件读取)"))
|
|
2058
|
+
check.add_argument("--details", action="store_true", help=_("脚手架差异逐项展开(默认同类合并为一行)"))
|
|
2059
|
+
check.add_argument("--reprompt", action="store_true", help=_("忽略已记录的决定,重新评估全部脚手架差异"))
|
|
1162
2060
|
check.add_argument("--fingerprint", action="store_true",
|
|
1163
|
-
help="输出脚手架指纹(骨架状态 + 受检 Profile 字段 + 内容锁 + 命名规则;不含 Opinion、自有字段、已跳过项)")
|
|
1164
|
-
check.add_argument("--explain", nargs="?", const="-", metavar="对方的 JSON",
|
|
1165
|
-
help="与 --fingerprint 合用:不带参数时逐项列出这台的明细;带另一台机器 check --fingerprint "
|
|
1166
|
-
"--output json 的输出文件时,指出两台差在哪里(有差异退出码 1)")
|
|
2061
|
+
help=_("输出脚手架指纹(骨架状态 + 受检 Profile 字段 + 内容锁 + 命名规则;不含 Opinion、自有字段、已跳过项)"))
|
|
2062
|
+
check.add_argument("--explain", nargs="?", const="-", metavar=_("对方的 JSON"),
|
|
2063
|
+
help=_("与 --fingerprint 合用:不带参数时逐项列出这台的明细;带另一台机器 check --fingerprint "
|
|
2064
|
+
"--output json 的输出文件时,指出两台差在哪里(有差异退出码 1)"))
|
|
1167
2065
|
|
|
1168
|
-
install = sub.add_parser("install", help="经各客户端的原生市场安装 agenthelm 插件(默认预览)")
|
|
2066
|
+
install = sub.add_parser("install", help=_("经各客户端的原生市场安装 agenthelm 插件(默认预览)"))
|
|
1169
2067
|
common(install, project=False)
|
|
1170
|
-
install
|
|
1171
|
-
install
|
|
1172
|
-
install.add_argument("--
|
|
1173
|
-
install.add_argument("--
|
|
2068
|
+
client_filter(install, _("只安装到这个客户端(可重复);默认安装到检测到的全部客户端(用户配置 ignored_clients 里的除外)"))
|
|
2069
|
+
refresh(install)
|
|
2070
|
+
install.add_argument("--plugin", action="append", help=_("默认安装全部插件"))
|
|
2071
|
+
install.add_argument("--source", type=Path, help=_("Cursor 安装用的本地仓库(默认下载发布包)"))
|
|
2072
|
+
install.add_argument("--marketplace-source", help=_("市场来源(默认 latest.json 的 GitHub 仓库;可用镜像或本地路径)"))
|
|
1174
2073
|
install.add_argument("--apply", action="store_true")
|
|
1175
2074
|
|
|
1176
|
-
update = sub.add_parser("update", help="更新落后的插件与模板/样例(默认预览,确认后 --apply)")
|
|
2075
|
+
update = sub.add_parser("update", help=_("更新落后的插件与模板/样例(默认预览,确认后 --apply)"))
|
|
1177
2076
|
common(update)
|
|
2077
|
+
client_filter(update)
|
|
2078
|
+
refresh(update)
|
|
1178
2079
|
update.add_argument("--only", choices=("plugins", "content"))
|
|
1179
|
-
update.add_argument("--accept", action="append", default=[], help="内容更新:用新模板替换这个本地已改动的文件")
|
|
1180
|
-
update.add_argument("--keep", action="append", default=[], help="内容更新:保留这个文件的本地内容")
|
|
1181
|
-
update.add_argument("--
|
|
1182
|
-
|
|
2080
|
+
update.add_argument("--accept", action="append", default=[], help=_("内容更新:用新模板替换这个本地已改动的文件"))
|
|
2081
|
+
update.add_argument("--keep", action="append", default=[], help=_("内容更新:保留这个文件的本地内容"))
|
|
2082
|
+
update.add_argument("--append", action="append", default=[],
|
|
2083
|
+
help=_("内容更新:保留 AGENTS.md / CLAUDE.md 的本地内容,只在末尾追加带标记的区块(先备份)"))
|
|
2084
|
+
update.add_argument("--confirm-discard", action="append", default=[], dest="confirm_discard",
|
|
2085
|
+
help=_("内容更新:确认 --accept 会丢弃这个文件里的本地内容"))
|
|
2086
|
+
update.add_argument("--diff", action="append", default=[], help=_("内容更新:只查看这个文件与新模板的完整差异,不写入"))
|
|
2087
|
+
update.add_argument("--merge", action="append", default=[],
|
|
2088
|
+
help=_("内容更新:三方合并这个文件(用旧版本包还原出升级前的基线,保留你的改动并带入新模板的变化;--apply 前先备份)"))
|
|
2089
|
+
update.add_argument("--pick", action="append", default=[], metavar=_("文件#块=mine|theirs|both"),
|
|
2090
|
+
help=_("内容更新:为 --merge 的冲突块选择 mine(保留你的)、theirs(取新模板)或 both(两边都留)"))
|
|
2091
|
+
update.add_argument("--recovery-dir", type=Path, help=_("被替换文件的备份目录(项目外),缺省 ~/.agent-pack/recovery/"))
|
|
2092
|
+
update.add_argument("--source", type=Path, help=_("Cursor 更新用的本地仓库(默认下载发布包)"))
|
|
1183
2093
|
update.add_argument("--apply", action="store_true")
|
|
1184
2094
|
|
|
1185
|
-
migrate = sub.add_parser("migrate", help="把旧方式安装(agent-pack 复制 + 软链)迁到市场安装(默认预览)")
|
|
2095
|
+
migrate = sub.add_parser("migrate", help=_("把旧方式安装(agent-pack 复制 + 软链)迁到市场安装(默认预览)"))
|
|
1186
2096
|
common(migrate, project=False)
|
|
1187
|
-
migrate.add_argument("--install", action="store_true", help="先经市场安装到检测到的客户端")
|
|
1188
|
-
migrate
|
|
2097
|
+
migrate.add_argument("--install", action="store_true", help=_("先经市场安装到检测到的客户端"))
|
|
2098
|
+
client_filter(migrate)
|
|
2099
|
+
refresh(migrate)
|
|
1189
2100
|
migrate.add_argument("--source", type=Path)
|
|
1190
2101
|
migrate.add_argument("--marketplace-source")
|
|
1191
2102
|
migrate.add_argument("--apply", action="store_true")
|
|
1192
2103
|
|
|
1193
|
-
doctor_parser = sub.add_parser("doctor", help="报告重复安装、版本不一致、旧方式残留与检查开关")
|
|
2104
|
+
doctor_parser = sub.add_parser("doctor", help=_("报告重复安装、版本不一致、旧方式残留与检查开关"))
|
|
1194
2105
|
common(doctor_parser)
|
|
1195
2106
|
|
|
1196
2107
|
sub.add_parser("fix", add_help=False,
|
|
1197
|
-
help="修复项目脚手架差异与更新(等同 project fix;默认预览,--apply 写入;--skip/--unskip 记录决定)")
|
|
2108
|
+
help=_("修复项目脚手架差异与更新(等同 project fix;默认预览,--apply 写入;--skip/--unskip 记录决定)"))
|
|
2109
|
+
sub.add_parser("local-only", add_help=False,
|
|
2110
|
+
help=_("只属于这台机器的目录(.venv、node_modules、缓存)不进云同步盘:check / fix / config(详见 local-only --help)"))
|
|
1198
2111
|
sub.add_parser("runtime", add_help=False,
|
|
1199
|
-
help="用户级运行时:install / update / use / status(日常只需要 Python,不经过 npx)")
|
|
2112
|
+
help=_("用户级运行时:install / update / use / status(日常只需要 Python,不经过 npx)"))
|
|
2113
|
+
sub.add_parser("config", add_help=False,
|
|
2114
|
+
help=_("用户级设置:界面语言、语言提示、项目文件语言(config show / language / language-hint / project-language;默认只预览)"))
|
|
1200
2115
|
sub.add_parser("project", add_help=False,
|
|
1201
|
-
help="项目自助入口:找资料、看进展、项目指南、检查(不需要 AI Agent;详见 project --help)")
|
|
1202
|
-
locate_parser = sub.add_parser("locate", help="输出插件的已安装位置(最新优先),供下游脚本查找")
|
|
2116
|
+
help=_("项目自助入口:找资料、看进展、项目指南、检查(不需要 AI Agent;详见 project --help)"))
|
|
2117
|
+
locate_parser = sub.add_parser("locate", help=_("输出插件的已安装位置(最新优先),供下游脚本查找"))
|
|
1203
2118
|
locate_parser.add_argument("plugin")
|
|
1204
|
-
locate_parser.add_argument("--version", help="只要这个版本")
|
|
2119
|
+
locate_parser.add_argument("--version", help=_("只要这个版本"))
|
|
1205
2120
|
locate_parser.add_argument("--include-legacy", action="store_true",
|
|
1206
|
-
help="也列出旧方式安装(默认不列,避免清理后才失效)")
|
|
2121
|
+
help=_("也列出旧方式安装(默认不列,避免清理后才失效)"))
|
|
1207
2122
|
locate_parser.add_argument("--output", choices=("text", "json"), default="json")
|
|
1208
2123
|
locate_parser.add_argument("--home", type=Path, help=argparse.SUPPRESS)
|
|
1209
2124
|
return result
|
|
1210
2125
|
|
|
1211
2126
|
|
|
1212
2127
|
def _print_steps(results: list[dict], apply: bool) -> None:
|
|
1213
|
-
labels = {"preview": "预览", "applied": "完成", "blocked": "阻塞", "failed": "失败"
|
|
2128
|
+
labels = {"preview": _("预览"), "applied": _("完成"), "blocked": _("阻塞"), "failed": _("失败"),
|
|
2129
|
+
"unchanged": _("完成,无变化"), "skipped": _("跳过"), "unavailable": _("不可用"), "not_run": _("未执行")}
|
|
1214
2130
|
for record in results:
|
|
1215
2131
|
line = f" [{labels.get(record['status'], record['status'])}] {record['description']}"
|
|
1216
2132
|
if record.get("command"):
|
|
1217
2133
|
line += f"\n $ {record['command']}"
|
|
2134
|
+
if record.get("note"):
|
|
2135
|
+
line += f"\n {record['note']}"
|
|
1218
2136
|
if record.get("blocked"):
|
|
1219
2137
|
line += f"\n {record['blocked']}"
|
|
1220
|
-
if record.get("
|
|
2138
|
+
if record.get("skipped"):
|
|
2139
|
+
line += f"\n {record['skipped']}"
|
|
2140
|
+
if record["status"] in {"failed", "unavailable"}:
|
|
2141
|
+
if record.get("exit_code") is not None:
|
|
2142
|
+
line += _("\n 退出码:{0}").format(record["exit_code"])
|
|
2143
|
+
if record.get("error"):
|
|
2144
|
+
line += _("\n 错误:{0}").format(record["error"])
|
|
2145
|
+
if record.get("reason"):
|
|
2146
|
+
line += _("\n 原因:{0}").format(record["reason"])
|
|
2147
|
+
if record.get("next"):
|
|
2148
|
+
line += _("\n 下一步:{0}").format(record["next"])
|
|
2149
|
+
if record.get("stderr"):
|
|
2150
|
+
line += _("\n 客户端 stderr(最多 {0} 行):").format(STDERR_LINES)
|
|
2151
|
+
line += "".join(f"\n {text}" for text in record["stderr"].splitlines())
|
|
2152
|
+
elif record.get("error"):
|
|
1221
2153
|
line += f"\n {record['error']}"
|
|
2154
|
+
if record["status"] == "not_run":
|
|
2155
|
+
line += f"\n {record['reason']}"
|
|
2156
|
+
for change in record.get("changes", []) if record["status"] in {"applied", "unchanged"} else []:
|
|
2157
|
+
prefix = f"{change['plugin']}: " if len(record["changes"]) > 1 else ""
|
|
2158
|
+
if change["changed"]:
|
|
2159
|
+
line += f"\n {prefix}{change['before'] or _('(未安装)')} → {change['after']}" + (
|
|
2160
|
+
_("(目标 {0})").format(change["target"]) if change.get("target") and change["after"] != change["target"] else "")
|
|
2161
|
+
else:
|
|
2162
|
+
line += _("\n {0}仍是 {1}(目标 {2})").format(prefix, change["after"] or _("(读不到)"), change.get("target") or "?")
|
|
2163
|
+
if record["status"] == "unchanged":
|
|
2164
|
+
line += _("\n 原因:{0}").format(record["reason"])
|
|
1222
2165
|
result = record.get("result")
|
|
1223
2166
|
if isinstance(result, dict) and result.get("mode") == "refresh":
|
|
1224
2167
|
for item in result.get("files", []):
|
|
1225
2168
|
line += f"\n {item['action']:8} {item['path']} [{item['state']}]"
|
|
2169
|
+
for note in item.get("note", []):
|
|
2170
|
+
line += f"\n {note}"
|
|
2171
|
+
for path, diff in (result.get("diffs") or {}).items():
|
|
2172
|
+
line += "\n" + (diff.rstrip("\n") if diff else _("({0} 与新模板没有差异)").format(path))
|
|
1226
2173
|
if result.get("hint"):
|
|
1227
|
-
line +=
|
|
2174
|
+
line += "\n" + "\n".join(f" {hint}" for hint in result["hint"].splitlines())
|
|
1228
2175
|
print(line)
|
|
2176
|
+
if apply and results:
|
|
2177
|
+
print("\n".join(render_outcome(results)))
|
|
1229
2178
|
if not apply and results:
|
|
1230
|
-
print("以上为预览;确认后追加 --apply 执行。")
|
|
2179
|
+
print(_("以上为预览;确认后追加 --apply 执行。"))
|
|
1231
2180
|
|
|
1232
2181
|
|
|
1233
2182
|
def run_project(argv: list[str]) -> int:
|
|
@@ -1238,9 +2187,8 @@ def run_project(argv: list[str]) -> int:
|
|
|
1238
2187
|
usable = [path for path in copies if (path / "runtime" / "project_cli.py").is_file()]
|
|
1239
2188
|
if not usable:
|
|
1240
2189
|
stale = any((path / "plugin.json").is_file() for path in copies)
|
|
1241
|
-
found = "(已安装的 project-orchestrator 版本过旧)" if stale else ""
|
|
1242
|
-
print(
|
|
1243
|
-
f" · 更新插件:{CLI} update,或从发布包安装运行时(见 INSTALL.md)", file=sys.stderr)
|
|
2190
|
+
found = _("(已安装的 project-orchestrator 版本过旧)") if stale else ""
|
|
2191
|
+
print(_("agenthelm project 需要 project-orchestrator 的项目入口,但没有找到{0}。\n · 更新插件:{1} update,或从发布包安装运行时(见 INSTALL.md)").format(found, CLI), file=sys.stderr)
|
|
1244
2192
|
return 3
|
|
1245
2193
|
# Prefer the copy shipped next to this agent-pack (same release), then the newest installed one.
|
|
1246
2194
|
sibling = PLUGIN_ROOT.parent / "project-orchestrator"
|
|
@@ -1253,6 +2201,31 @@ def run_project(argv: list[str]) -> int:
|
|
|
1253
2201
|
return project_cli.main(argv)
|
|
1254
2202
|
|
|
1255
2203
|
|
|
2204
|
+
def run_nudge(argv: list[str]) -> int:
|
|
2205
|
+
"""``agenthelm nudge``: hooks that collect opinion candidates and surface unconfirmed items."""
|
|
2206
|
+
sys.path.insert(0, str(RUNTIME_DIR))
|
|
2207
|
+
import agent_pack_nudge # noqa: PLC0415 - shipped next to this file
|
|
2208
|
+
|
|
2209
|
+
return agent_pack_nudge.main(argv, sys.modules[__name__])
|
|
2210
|
+
|
|
2211
|
+
|
|
2212
|
+
def user_settings_module():
|
|
2213
|
+
sys.path.insert(0, str(RUNTIME_DIR))
|
|
2214
|
+
import user_settings # noqa: PLC0415 - shipped next to this file
|
|
2215
|
+
|
|
2216
|
+
return user_settings
|
|
2217
|
+
|
|
2218
|
+
|
|
2219
|
+
def run_config(argv: list[str]) -> int:
|
|
2220
|
+
"""``agenthelm config``: interface language, the language hint and the project file language."""
|
|
2221
|
+
return user_settings_module().main(argv, sys.modules[__name__])
|
|
2222
|
+
|
|
2223
|
+
|
|
2224
|
+
def run_local_only(argv: list[str]) -> int:
|
|
2225
|
+
"""``agenthelm local-only``: keep rebuildable directories out of cloud-synced folders."""
|
|
2226
|
+
return _local_only().main(argv, sys.modules[__name__])
|
|
2227
|
+
|
|
2228
|
+
|
|
1256
2229
|
def run_runtime(argv: list[str]) -> int:
|
|
1257
2230
|
"""``agenthelm runtime``: the user-level runtime that project launchers use without any AI client."""
|
|
1258
2231
|
sys.path.insert(0, str(RUNTIME_DIR))
|
|
@@ -1261,35 +2234,51 @@ def run_runtime(argv: list[str]) -> int:
|
|
|
1261
2234
|
return agenthelm_runtime.main(argv, sys.modules[__name__])
|
|
1262
2235
|
|
|
1263
2236
|
|
|
1264
|
-
def print_fingerprint(env: Env, report: dict, args: argparse.Namespace) -> int:
|
|
2237
|
+
def print_fingerprint(env: Env, report: dict, args: argparse.Namespace, project: Path | None = None) -> int:
|
|
1265
2238
|
"""``check --fingerprint [--explain [file]]``: the scaffold fingerprint, and where two machines differ."""
|
|
1266
2239
|
result = scaffold_fingerprint(env, report.get("scaffold"))
|
|
1267
2240
|
if result is None:
|
|
1268
|
-
reason = (report.get("scaffold") or {}).get("error") or "当前目录不在 agenthelm 项目里"
|
|
2241
|
+
reason = (report.get("scaffold") or {}).get("error") or _("当前目录不在 agenthelm 项目里")
|
|
1269
2242
|
print(json.dumps({"ok": False, "error": reason}, ensure_ascii=False) if args.output == "json"
|
|
1270
|
-
else
|
|
2243
|
+
else _("无法计算脚手架指纹:{0}").format(reason), file=sys.stderr if args.output != "json" else sys.stdout)
|
|
1271
2244
|
return 4
|
|
1272
2245
|
payload: dict = {"ok": True, "fingerprint": result["fingerprint"], "detail": result["detail"]}
|
|
1273
|
-
lines = [
|
|
2246
|
+
lines = [_("脚手架指纹 {0}").format(result['fingerprint'])]
|
|
2247
|
+
mine_local: dict = {}
|
|
2248
|
+
if project is not None:
|
|
2249
|
+
# 本机环境(外置链接、HOME)单独成段:没有 local-only 配置的项目,输出与以前完全一样。
|
|
2250
|
+
mine_local = local_only_report(env, project, mode="quick")["fingerprint"]
|
|
2251
|
+
if mine_local["detail"]:
|
|
2252
|
+
payload["local_only"] = mine_local
|
|
2253
|
+
lines.append(_("本机环境指纹 {0}").format(mine_local['fingerprint']))
|
|
1274
2254
|
differences: list[str] = []
|
|
1275
2255
|
if args.explain and args.explain != "-":
|
|
1276
2256
|
try:
|
|
1277
2257
|
other = read_json(Path(args.explain).expanduser())
|
|
1278
2258
|
except (OSError, ValueError) as exc:
|
|
1279
|
-
print(
|
|
2259
|
+
print(_("读不了对方的输出:{0}").format(exc), file=sys.stderr)
|
|
1280
2260
|
return 2
|
|
1281
2261
|
theirs = other.get("detail") or (other.get("scaffold_fingerprint") or {}).get("detail") or other.get("fingerprint", {}).get("detail")
|
|
1282
2262
|
if not isinstance(theirs, dict):
|
|
1283
|
-
print("对方的文件里没有指纹明细:请在对方机器运行 agenthelm check --fingerprint --output json 并保存输出", file=sys.stderr)
|
|
2263
|
+
print(_("对方的文件里没有指纹明细:请在对方机器运行 agenthelm check --fingerprint --output json 并保存输出"), file=sys.stderr)
|
|
1284
2264
|
return 2
|
|
1285
2265
|
module = scaffold_module(env)
|
|
1286
2266
|
differences = module.explain(result["detail"], theirs)
|
|
2267
|
+
their_local = (other.get("local_only") or {}).get("detail") or {}
|
|
2268
|
+
if mine_local.get("detail") or their_local:
|
|
2269
|
+
if not their_local:
|
|
2270
|
+
differences.append(_("本机环境:对方没有 local-only 明细(对方的 agent-pack 较旧或项目还没配置)"))
|
|
2271
|
+
elif not mine_local.get("detail"):
|
|
2272
|
+
differences.append(_("本机环境:这台没有 local-only 配置,对方有"))
|
|
2273
|
+
else:
|
|
2274
|
+
differences += _local_only().explain(mine_local["detail"], their_local)
|
|
1287
2275
|
payload["same"] = not differences
|
|
1288
2276
|
payload["differences"] = differences
|
|
1289
|
-
lines.append("两台机器的脚手架一致。" if not differences else
|
|
2277
|
+
lines.append(_("两台机器的脚手架一致。") if not differences else _("有 {0} 处不同:").format(len(differences)))
|
|
1290
2278
|
lines += [f" {item}" for item in differences]
|
|
1291
2279
|
elif args.explain:
|
|
1292
2280
|
lines += [f" {key} = {value}" for key, value in result["detail"].items()]
|
|
2281
|
+
lines += [f" local-only {key} = {value}" for key, value in mine_local.get("detail", {}).items()]
|
|
1293
2282
|
if args.output == "json":
|
|
1294
2283
|
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
1295
2284
|
else:
|
|
@@ -1297,6 +2286,26 @@ def print_fingerprint(env: Env, report: dict, args: argparse.Namespace) -> int:
|
|
|
1297
2286
|
return 1 if differences else 0
|
|
1298
2287
|
|
|
1299
2288
|
|
|
2289
|
+
def client_hint_text(env: Env, report: dict) -> str:
|
|
2290
|
+
"""One-time hint for a detected client that looks unused, with the command that ignores it. Recorded once shown."""
|
|
2291
|
+
pending = (report.get("clients") or {}).get("unused") or []
|
|
2292
|
+
state_file = env.state_dir / "agenthelm" / "client-hints.json"
|
|
2293
|
+
try:
|
|
2294
|
+
seen = read_json(state_file).get("shown", [])
|
|
2295
|
+
except (OSError, ValueError, AttributeError):
|
|
2296
|
+
seen = []
|
|
2297
|
+
fresh = [name for name in pending if name not in seen]
|
|
2298
|
+
if not fresh:
|
|
2299
|
+
return ""
|
|
2300
|
+
try:
|
|
2301
|
+
write_json_atomic(state_file, {"shown": sorted({*seen, *fresh})})
|
|
2302
|
+
except OSError:
|
|
2303
|
+
pass
|
|
2304
|
+
return "".join(_("提示:检测到 {0},但没有看到你在用它(没有装 agenthelm 插件,或插件都落后)。不使用的话可以忽略它,之后 check / update / "
|
|
2305
|
+
"会话开始提示都不再统计:{1} config ignore-client {2}(预览;加 --apply 写入)。这条提示只显示一次。\n").format(
|
|
2306
|
+
CLIENT_NAMES[name], CLI, name) for name in fresh)
|
|
2307
|
+
|
|
2308
|
+
|
|
1300
2309
|
def main(argv: list[str] | None = None) -> int:
|
|
1301
2310
|
argv = list(sys.argv[1:] if argv is None else argv)
|
|
1302
2311
|
if argv[:1] == ["project"]:
|
|
@@ -1305,6 +2314,12 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
1305
2314
|
return run_project(["fix", *argv[1:]])
|
|
1306
2315
|
if argv[:1] == ["runtime"]:
|
|
1307
2316
|
return run_runtime(argv[1:])
|
|
2317
|
+
if argv[:1] == ["nudge"]:
|
|
2318
|
+
return run_nudge(argv[1:])
|
|
2319
|
+
if argv[:1] == ["config"]:
|
|
2320
|
+
return run_config(argv[1:])
|
|
2321
|
+
if argv[:1] == ["local-only"]:
|
|
2322
|
+
return run_local_only(argv[1:])
|
|
1308
2323
|
args = parser().parse_args(argv)
|
|
1309
2324
|
env = current_env(args.home)
|
|
1310
2325
|
home = env.home
|
|
@@ -1323,14 +2338,16 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
1323
2338
|
try:
|
|
1324
2339
|
if args.command == "check":
|
|
1325
2340
|
report = run_check(env, project, latest_source=args.latest, offline=args.offline,
|
|
1326
|
-
max_age=0 if args.refresh else CACHE_TTL_SECONDS, reprompt=args.reprompt
|
|
2341
|
+
max_age=0 if args.refresh else CACHE_TTL_SECONDS, reprompt=args.reprompt,
|
|
2342
|
+
clients=args.client)
|
|
1327
2343
|
report.pop("_latest")
|
|
1328
2344
|
if args.fingerprint or args.explain:
|
|
1329
|
-
return print_fingerprint(env, report, args)
|
|
2345
|
+
return print_fingerprint(env, report, args, project)
|
|
1330
2346
|
if args.output == "json":
|
|
1331
2347
|
print(json.dumps(report, ensure_ascii=False, indent=2))
|
|
1332
2348
|
else:
|
|
1333
|
-
sys.stdout.write(render_text(report, show_skipped=args.show_skipped))
|
|
2349
|
+
sys.stdout.write(render_text(report, show_skipped=args.show_skipped, details=args.details, show_extras=args.show_extras))
|
|
2350
|
+
sys.stdout.write(client_hint_text(env, report))
|
|
1334
2351
|
return 1 if args.strict and not report["summary"]["up_to_date"] else 0
|
|
1335
2352
|
if args.command == "doctor":
|
|
1336
2353
|
result = doctor(env, run_check(env, project, latest_source=args.latest))
|
|
@@ -1341,38 +2358,65 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
1341
2358
|
print(f" [{issue['issue']}] {issue.get('plugin') or ''} {issue['detail']}".rstrip())
|
|
1342
2359
|
for item in result["legacy"]:
|
|
1343
2360
|
print(f" [legacy] {item['kind']} {item['name']}: {item['path']}")
|
|
1344
|
-
print("没有发现问题。" if result["ok"] and not result["legacy"] else "")
|
|
2361
|
+
print(_("没有发现问题。") if result["ok"] and not result["legacy"] else "")
|
|
1345
2362
|
return 0 if result["ok"] else 1
|
|
1346
|
-
|
|
2363
|
+
# install / update / migrate change things, so they always fetch fresh data; --refresh is accepted for symmetry.
|
|
2364
|
+
latest, origin = load_latest(env, args.latest, max_age=0)
|
|
1347
2365
|
if args.command == "install":
|
|
1348
|
-
clients = args.client
|
|
2366
|
+
clients = active_clients(env, args.client)
|
|
1349
2367
|
plugins = args.plugin or sorted(latest.get("plugins", {}))
|
|
1350
2368
|
steps = install_steps(env, latest, clients, plugins, args.source, home, args.marketplace_source)
|
|
1351
2369
|
results = execute_steps(steps, apply=args.apply, recovery_root=None,
|
|
1352
|
-
child_env=env.child_environment())
|
|
1353
|
-
payload: dict = {"ok":
|
|
2370
|
+
child_env=env.child_environment(), env=env)
|
|
2371
|
+
payload: dict = {"ok": step_outcome_ok(results), "applied": args.apply, "latest": origin,
|
|
1354
2372
|
"clients": clients, "steps": results}
|
|
1355
2373
|
elif args.command == "update":
|
|
1356
|
-
report = run_check(env, project, latest_source=args.latest, max_age=0)
|
|
2374
|
+
report = run_check(env, project, latest_source=args.latest, max_age=0, clients=args.client)
|
|
2375
|
+
origin = report["latest"]["source"]
|
|
1357
2376
|
recovery = args.recovery_dir
|
|
1358
2377
|
if args.apply and recovery is None and project is not None:
|
|
1359
2378
|
recovery = recovery_dir_for(env, "content")
|
|
2379
|
+
if args.diff and args.apply:
|
|
2380
|
+
raise CheckError(_("--diff 只用于查看,不能与 --apply 同用"))
|
|
2381
|
+
flags = [value for flag, paths in (("--append", args.append), ("--confirm-discard", args.confirm_discard),
|
|
2382
|
+
("--diff", args.diff), ("--merge", args.merge), ("--pick", args.pick))
|
|
2383
|
+
for path in paths for value in (flag, path)]
|
|
1360
2384
|
steps = update_steps(env, report, project, args.source, home, args.accept, args.keep,
|
|
1361
|
-
recovery, args.only)
|
|
2385
|
+
recovery, args.only, content_flags=flags)
|
|
1362
2386
|
results = execute_steps(steps, apply=args.apply, recovery_root=None,
|
|
1363
|
-
child_env=env.child_environment())
|
|
1364
|
-
payload = {"ok":
|
|
2387
|
+
child_env=env.child_environment(), env=env)
|
|
2388
|
+
payload = {"ok": step_outcome_ok(results), "applied": args.apply, "latest": origin,
|
|
1365
2389
|
"steps": results, "summary": report["summary"]}
|
|
2390
|
+
backups = [record["result"] for record in results
|
|
2391
|
+
if isinstance(record.get("result"), dict) and record["result"].get("recovery")]
|
|
2392
|
+
if args.apply and backups:
|
|
2393
|
+
payload["recovery"] = backups[0]["recovery"]
|
|
2394
|
+
payload["recovery_files"] = [path for item in backups for path in item.get("recovery_files", [])]
|
|
1366
2395
|
if not steps:
|
|
1367
|
-
|
|
2396
|
+
content_errors = [item for item in report["content"] if item["status"] == "error"] if args.only != "plugins" else []
|
|
2397
|
+
chosen = args.accept or args.keep or args.append or args.confirm_discard or args.diff or args.merge or args.pick
|
|
2398
|
+
if content_errors: # 内容锁坏了不是“没有需要更新的内容”:说明原因并以非零退出
|
|
2399
|
+
payload["ok"] = False
|
|
2400
|
+
payload["message"] = _("项目内容没有检查:{0}。修复或移走这个文件后重试;没有改动任何文件。").format(content_errors[0]["error"])
|
|
2401
|
+
elif chosen and args.only != "plugins": # 用户点名了文件,却没有任何待更新内容:不能装作处理过
|
|
2402
|
+
payload["message"] = _("没有需要更新的内容,--accept / --keep / --append / --diff / --merge 指定的文件没有被处理(项目内容已是最新,或项目没有内容锁);没有改动任何文件。"
|
|
2403
|
+
"没有内容锁的项目用 {0} fix update-content。").format(CLI)
|
|
2404
|
+
else:
|
|
2405
|
+
payload["message"] = _("没有需要更新的内容。")
|
|
2406
|
+
differing = baseline_less_differences(env, project) if args.only != "plugins" else 0
|
|
2407
|
+
if differing: # check lists them (no baseline in the lock); update has nothing to render for them
|
|
2408
|
+
payload["message"] += _("有 {0} 项无基线差异(内容与模板不同,内容锁里没有基线),"
|
|
2409
|
+
"请用 {1} fix update-content(或 update --only content --keep/--append/--accept …)逐个处理。").format(differing, CLI)
|
|
1368
2410
|
else: # migrate
|
|
1369
2411
|
names = set(latest.get("plugins", {}))
|
|
1370
2412
|
artifacts = legacy_artifacts(env, names)
|
|
1371
|
-
|
|
2413
|
+
selected = active_clients(env, args.client)
|
|
2414
|
+
steps = install_steps(env, latest, selected, sorted(names),
|
|
1372
2415
|
args.source, home, args.marketplace_source) if args.install else []
|
|
2416
|
+
steps += untouched_steps(env, names, selected, kind="migrate")
|
|
1373
2417
|
results = execute_steps(steps, apply=args.apply, recovery_root=None,
|
|
1374
|
-
child_env=env.child_environment())
|
|
1375
|
-
payload = {"ok":
|
|
2418
|
+
child_env=env.child_environment(), env=env)
|
|
2419
|
+
payload = {"ok": step_outcome_ok(results), "applied": args.apply, "latest": origin,
|
|
1376
2420
|
"steps": results, "legacy": artifacts}
|
|
1377
2421
|
if args.apply and payload["ok"] and artifacts:
|
|
1378
2422
|
recovery = recovery_dir_for(env, "migrate")
|
|
@@ -1387,13 +2431,19 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
1387
2431
|
if args.output == "json":
|
|
1388
2432
|
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
1389
2433
|
else:
|
|
2434
|
+
print(origin_line(payload["latest"]))
|
|
1390
2435
|
if payload.get("message"):
|
|
1391
2436
|
print(payload["message"])
|
|
1392
2437
|
_print_steps(payload["steps"], args.apply)
|
|
1393
2438
|
for item in payload.get("legacy", []):
|
|
1394
|
-
print(
|
|
1395
|
-
if payload.get("recovery"):
|
|
1396
|
-
print(
|
|
2439
|
+
print(_(" [旧安装] {0} {1}: {2}").format(item['kind'], item['name'], item['path']) + (_("(需手动处理)") if item.get("manual") else ""))
|
|
2440
|
+
if payload.get("recovery") and args.command == "update":
|
|
2441
|
+
print(_("被替换文件的原件已备份到:{0}").format(payload['recovery']))
|
|
2442
|
+
for path in payload.get("recovery_files", []):
|
|
2443
|
+
print(f" {path}")
|
|
2444
|
+
print(_("还原:把备份目录里的文件按相同的相对路径复制回项目目录(cp -p <备份目录>/<文件> <项目目录>/<文件>)。"))
|
|
2445
|
+
elif payload.get("recovery"):
|
|
2446
|
+
print(_("旧安装已移入:{0}(含 migration.json 清单,可按清单恢复)").format(payload['recovery']))
|
|
1397
2447
|
return 0 if payload["ok"] else 1
|
|
1398
2448
|
|
|
1399
2449
|
|