@sakanano-moe/agenthelm 6.12.0 → 6.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/package.json +1 -1
  2. package/runtime/index.json +5 -5
  3. package/runtime/plugins/agent-pack/.codex-plugin/plugin.json +1 -1
  4. package/runtime/plugins/agent-pack/plugin.json +1 -1
  5. package/runtime/plugins/agent-pack/references/capability-config.md +32 -1
  6. package/runtime/plugins/agent-pack/references/nudge.en.md +1 -1
  7. package/runtime/plugins/agent-pack/references/nudge.md +1 -1
  8. package/runtime/plugins/agent-pack/runtime/agent_pack_claude.py +172 -20
  9. package/runtime/plugins/agent-pack/runtime/agent_pack_config.py +286 -35
  10. package/runtime/plugins/agent-pack/runtime/agent_pack_nudge.py +65 -2
  11. package/runtime/plugins/agent-pack/runtime/agenthelm.py +99 -9
  12. package/runtime/plugins/agent-pack/runtime/locale/en.json +15 -1
  13. package/runtime/plugins/agent-pack/runtime/mcp_env_launcher.py +26 -4
  14. package/runtime/plugins/agent-pack/runtime/mcp_server.py +15 -1
  15. package/runtime/plugins/agent-pack/runtime/nudge_text.py +17 -4
  16. package/runtime/plugins/agent-pack/runtime/user_settings.py +25 -6
  17. package/runtime/plugins/agents-init/.codex-plugin/plugin.json +1 -1
  18. package/runtime/plugins/agents-init/plugin.json +1 -1
  19. package/runtime/plugins/agents-init/skills/agents-init/scripts/init_project.py +25 -0
  20. package/runtime/plugins/agents-init/skills/agents-init/skill.json +1 -1
  21. package/runtime/plugins/opinion-manager/.codex-plugin/plugin.json +1 -1
  22. package/runtime/plugins/opinion-manager/plugin.json +1 -1
  23. package/runtime/plugins/opinion-manager/references/inbox.en.md +7 -2
  24. package/runtime/plugins/opinion-manager/references/inbox.md +7 -2
  25. package/runtime/plugins/opinion-manager/runtime/inbox.py +155 -7
  26. package/runtime/plugins/opinion-manager/runtime/inbox_text.py +19 -6
  27. package/runtime/plugins/opinion-manager/skills/opinion-manager/SKILL.md +4 -3
@@ -9,6 +9,7 @@ Writes are always opt-in through ``apply=True`` and collisions fail closed.
9
9
  from __future__ import annotations
10
10
 
11
11
  import argparse
12
+ import getpass
12
13
  import hashlib
13
14
  import json
14
15
  import os
@@ -59,6 +60,18 @@ def looks_like_token(name: str) -> bool:
59
60
  and any(c.isdigit() for c in name))
60
61
 
61
62
 
63
+ # A path-shaped argument (absolute, ``~``, drive letter, or one of our own path placeholders) names
64
+ # a location. Directory names such as ``credential`` or ``token`` in it say nothing about a secret
65
+ # value (#90), so only the value-shaped patterns apply to such arguments.
66
+ PATH_SHAPED_RE = re.compile(r"^(?:[/~]|[A-Za-z]:[\\/]|__PROJECT_DIR__|__REPO_ROOT__|\$\{(?:PLUGIN_ROOT|PLUGIN_DATA|HOME)\})")
67
+
68
+
69
+ def _secret_like_arg(text: str) -> bool:
70
+ if SECRET_VALUE_RE.search(text):
71
+ return True
72
+ return not PATH_SHAPED_RE.match(text) and bool(SECRET_NAME_RE.search(text))
73
+
74
+
62
75
  def _safe_env_reference(text: str) -> bool:
63
76
  """A value made of ``${NAME}`` references with nothing credential-like in the names or around them."""
64
77
  references = ENV_REFERENCE_RE.findall(text)
@@ -68,6 +81,14 @@ def _safe_env_reference(text: str) -> bool:
68
81
  # client-managed writable state). They are never credentials and must not
69
82
  # trigger the credential-env-file requirement or env-launcher wrapping.
70
83
  RESERVED_ENV_PLACEHOLDERS = {"PLUGIN_ROOT", "PLUGIN_DATA"}
84
+ # Process / system variables. They describe the machine, not a credential, so they are never
85
+ # required in the credential env file. ``sync`` expands them to this machine's values while
86
+ # rendering the package (each machine syncs for itself), so ``${HOME}/tools/x.js`` is portable.
87
+ SYSTEM_ENV_PLACEHOLDERS = frozenset({
88
+ "HOME", "USER", "LOGNAME", "TMPDIR",
89
+ "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME",
90
+ })
91
+ PLUGIN_ROOT_REF_RE = re.compile(r"\$\{PLUGIN_ROOT\}(/[\w./@+-]*)?")
71
92
  COPY_IGNORE = {".git", ".venv", "__pycache__", "node_modules", ".DS_Store"}
72
93
  PLUGIN_FIELDS = {
73
94
  "$schema", "name", "version", "description", "author", "homepage",
@@ -96,6 +117,7 @@ class McpRecord:
96
117
  portable: bool
97
118
  issues: tuple[str, ...] = ()
98
119
  authority: str = "portable"
120
+ root: str = "" # directory ``${PLUGIN_ROOT}`` means for this entry (its own source's plugin directory)
99
121
 
100
122
 
101
123
  @dataclass
@@ -396,7 +418,7 @@ def _portable_mcp(name: str, raw: Any) -> McpRecord:
396
418
  for index, value in enumerate(args):
397
419
  rendered = str(value)
398
420
  safe_reference = _safe_env_reference(rendered)
399
- if (SECRET_NAME_RE.search(rendered) or SECRET_VALUE_RE.search(rendered)) and not safe_reference:
421
+ if _secret_like_arg(rendered) and not safe_reference:
400
422
  issues.append(f"possible secret reference in args[{index}]")
401
423
  elif any(looks_like_token(name) for name in ENV_REFERENCE_RE.findall(rendered)):
402
424
  issues.append(f"possible secret reference in args[{index}]")
@@ -466,7 +488,8 @@ def _inventory_plugin(plugin_root: Path, source: str) -> Inventory:
466
488
  for name, raw in sorted(servers.items()):
467
489
  record = _portable_mcp(name, raw)
468
490
  inventory.mcps.append(McpRecord(
469
- record.name, record.config, source, record.portable, record.issues, "portable"
491
+ record.name, record.config, source, record.portable, record.issues, "portable",
492
+ str(plugin_root),
470
493
  ))
471
494
  except AgentPackError as exc:
472
495
  inventory.issues.append(str(exc))
@@ -531,7 +554,8 @@ def inventory_project(project: Path) -> Inventory:
531
554
  record = _portable_mcp(name, raw)
532
555
  authority = "native" if mcp_source in layout.native_mcp_sources else "portable"
533
556
  inventory.mcps.append(McpRecord(
534
- record.name, record.config, str(mcp_source), record.portable, record.issues, authority
557
+ record.name, record.config, str(mcp_source), record.portable, record.issues, authority,
558
+ str(mcp_source.parent),
535
559
  ))
536
560
  known_mcp_names.add(name)
537
561
  except AgentPackError as exc:
@@ -864,7 +888,7 @@ def _mcp_allowed(layout: ProjectLayout, name: str, client: str) -> bool:
864
888
 
865
889
  def _env_references(value: Any) -> set[str]:
866
890
  if isinstance(value, str):
867
- return set(ENV_REFERENCE_RE.findall(value)) - RESERVED_ENV_PLACEHOLDERS
891
+ return set(ENV_REFERENCE_RE.findall(value)) - RESERVED_ENV_PLACEHOLDERS - SYSTEM_ENV_PLACEHOLDERS
868
892
  if isinstance(value, list):
869
893
  result: set[str] = set()
870
894
  for item in value:
@@ -901,12 +925,95 @@ def _dotenv_keys(path: Path) -> set[str]:
901
925
  return keys
902
926
 
903
927
 
928
+ def _system_env_values(home: Path | None) -> dict[str, str]:
929
+ """This machine's value for every name in SYSTEM_ENV_PLACEHOLDERS (``home`` is the user's home)."""
930
+ base = (home or Path.home()).expanduser().resolve()
931
+ try:
932
+ user = os.environ.get("USER") or getpass.getuser()
933
+ except (KeyError, OSError):
934
+ user = ""
935
+ values = {
936
+ "HOME": str(base),
937
+ "USER": user,
938
+ "LOGNAME": os.environ.get("LOGNAME") or user,
939
+ "TMPDIR": os.environ.get("TMPDIR") or tempfile.gettempdir(),
940
+ "XDG_CONFIG_HOME": os.environ.get("XDG_CONFIG_HOME") or str(base / ".config"),
941
+ "XDG_DATA_HOME": os.environ.get("XDG_DATA_HOME") or str(base / ".local" / "share"),
942
+ "XDG_CACHE_HOME": os.environ.get("XDG_CACHE_HOME") or str(base / ".cache"),
943
+ "XDG_STATE_HOME": os.environ.get("XDG_STATE_HOME") or str(base / ".local" / "state"),
944
+ }
945
+ return {name: value for name, value in values.items() if value}
946
+
947
+
948
+ def _package_provides(inventory: Inventory, relative: str) -> bool:
949
+ """Whether the merged project package contains ``relative`` (the files it is built from)."""
950
+ parts = Path(relative).parts
951
+ if not parts or ".." in parts:
952
+ return False
953
+ if len(parts) == 1:
954
+ return parts[0] in {"plugin.json", "mcp.json"}
955
+ if parts[0] == "runtime":
956
+ return parts[1:] == ("mcp_env_launcher.py",)
957
+ if parts[0] == "skills":
958
+ for skill in inventory.skills:
959
+ if skill.portable and skill.name == parts[1]:
960
+ return len(parts) == 2 or (Path(skill.path) / Path(*parts[2:])).exists()
961
+ return False
962
+
963
+
964
+ def _resolve_plugin_root(item: McpRecord, text: str, inventory: Inventory) -> str:
965
+ """Resolve ``${PLUGIN_ROOT}/<path>`` against the entry's own source directory.
966
+
967
+ The merged package holds only the Skills, ``mcp.json`` and the launcher, so a path that is
968
+ not one of those cannot live under the package root. If the entry's source directory has the
969
+ file, the reference becomes that file's absolute path; otherwise the entry is blocked.
970
+ """
971
+ def replace(match: re.Match[str]) -> str:
972
+ relative = (match.group(1) or "").strip("/")
973
+ if not relative or _package_provides(inventory, relative):
974
+ return match.group(0)
975
+ if not item.root:
976
+ return match.group(0) # not a project entry: nothing to resolve against
977
+ source_dir = Path(item.root)
978
+ candidate = source_dir / relative
979
+ if ".." not in Path(relative).parts and candidate.exists():
980
+ return str(candidate.resolve())
981
+ raise AgentPackError(
982
+ f"MCP {item.name} references ${{PLUGIN_ROOT}}/{relative}, which exists "
983
+ f"neither in the merged package nor in its source directory {source_dir}"
984
+ )
985
+
986
+ return PLUGIN_ROOT_REF_RE.sub(replace, text)
987
+
988
+
989
+ def _mcp_plugin_root_problems(item: McpRecord, inventory: Inventory) -> list[str]:
990
+ """Every unresolvable ``${PLUGIN_ROOT}`` path of one entry (what sync would block on)."""
991
+ problems: list[str] = []
992
+
993
+ def walk(value: Any) -> None:
994
+ if isinstance(value, str):
995
+ try:
996
+ _resolve_plugin_root(item, value, inventory)
997
+ except AgentPackError as exc:
998
+ problems.append(str(exc))
999
+ elif isinstance(value, list):
1000
+ for child in value:
1001
+ walk(child)
1002
+ elif isinstance(value, dict):
1003
+ for child in value.values():
1004
+ walk(child)
1005
+
1006
+ walk(item.config)
1007
+ return problems
1008
+
1009
+
904
1010
  def _portable_package_from_inventory(
905
1011
  inventory: Inventory,
906
1012
  package_name: str,
907
1013
  destination: Path,
908
1014
  *,
909
1015
  client: str | None = None,
1016
+ home: Path | None = None,
910
1017
  ) -> None:
911
1018
  invalid = [item.name for item in inventory.skills if not item.portable]
912
1019
  invalid += [
@@ -933,11 +1040,19 @@ def _portable_package_from_inventory(
933
1040
  for item in inventory.skills:
934
1041
  _copy_skill(Path(item.path), skills_root / item.name, allowed_root=project_root)
935
1042
 
1043
+ system_env = _system_env_values(home)
1044
+
936
1045
  def project_mcp_config(item: McpRecord) -> dict[str, Any]:
937
1046
  source_path = Path(item.source)
938
1047
 
939
1048
  def expand(value: Any) -> Any:
940
1049
  if isinstance(value, str):
1050
+ value = _resolve_plugin_root(item, value, inventory)
1051
+ value = ENV_REFERENCE_RE.sub(
1052
+ lambda match: system_env.get(match.group(1), match.group(0))
1053
+ if match.group(1) in SYSTEM_ENV_PLACEHOLDERS else match.group(0),
1054
+ value,
1055
+ )
941
1056
  if "__PROJECT_DIR__" in value:
942
1057
  if not source_path.is_file():
943
1058
  raise AgentPackError(f"cannot resolve __PROJECT_DIR__ for MCP {item.name}")
@@ -992,17 +1107,17 @@ def _portable_package_from_inventory(
992
1107
  config_name = hashlib.sha256(item.name.encode("utf-8")).hexdigest()[:16] + ".json"
993
1108
  _write_json_atomic(runtime_root / config_name, config)
994
1109
  assert layout is not None and layout.credential_env_file is not None
995
- rendered_mcps[item.name] = {
996
- "type": "stdio",
997
- "command": "python3",
998
- "args": [
999
- "${PLUGIN_ROOT}/runtime/mcp_env_launcher.py",
1000
- "--env-file",
1001
- str(layout.credential_env_file.resolve()),
1002
- "--config",
1003
- f"${{PLUGIN_ROOT}}/runtime/{config_name}",
1004
- ],
1005
- }
1110
+ launcher_args = [
1111
+ "${PLUGIN_ROOT}/runtime/mcp_env_launcher.py",
1112
+ "--env-file",
1113
+ str(layout.credential_env_file.resolve()),
1114
+ "--config",
1115
+ f"${{PLUGIN_ROOT}}/runtime/{config_name}",
1116
+ ]
1117
+ if "${PLUGIN_DATA}" in json.dumps(config):
1118
+ # The client expands placeholders in the launcher's own args, not in the config file it reads (#91).
1119
+ launcher_args += ["--plugin-data", "${PLUGIN_DATA}"]
1120
+ rendered_mcps[item.name] = {"type": "stdio", "command": "python3", "args": launcher_args}
1006
1121
 
1007
1122
  _write_json_atomic(destination / "mcp.json", {
1008
1123
  "$schema": AGENT_PLUGIN_MCP_SCHEMA,
@@ -1145,9 +1260,10 @@ def _source_matches_client_destination(
1145
1260
  return _source_matches_destination(staged, destination)
1146
1261
 
1147
1262
 
1148
- def _build_package(inventory: Inventory, package_name: str, parent: Path, client: str) -> Path:
1263
+ def _build_package(inventory: Inventory, package_name: str, parent: Path, client: str,
1264
+ home: Path | None = None) -> Path:
1149
1265
  package = parent / package_name
1150
- _portable_package_from_inventory(inventory, package_name, package, client=client)
1266
+ _portable_package_from_inventory(inventory, package_name, package, client=client, home=home)
1151
1267
  if client == "codex":
1152
1268
  _codex_adapter(package, native_remote=True)
1153
1269
  return package
@@ -1451,6 +1567,63 @@ def _component_state(
1451
1567
  return states
1452
1568
 
1453
1569
 
1570
+ def _marketplace_without(text: str, name: str) -> str:
1571
+ """The marketplace file text without the entry named ``name``; other entries and layout are kept."""
1572
+ payload = json.loads(text)
1573
+ payload["plugins"] = [item for item in payload["plugins"]
1574
+ if not (isinstance(item, dict) and item.get("name") == name)]
1575
+ indent = 2
1576
+ match = re.search(r"\n([ \t]+)\S", text)
1577
+ if match:
1578
+ indent = "\t" if match.group(1).startswith("\t") else len(match.group(1))
1579
+ return json.dumps(payload, indent=indent, ensure_ascii=False) + ("\n" if text.endswith("\n") else "")
1580
+
1581
+
1582
+ def _codex_retirement_extras(home: Path, name: str, primary: Path) -> tuple[list[dict[str, str]], list[dict[str, str]]]:
1583
+ """Codex keeps a retired plugin in a personal copy, a marketplace entry, a cache and config.toml.
1584
+
1585
+ The copy and the marketplace entry are archived and removed; the cache versions and the user's
1586
+ config.toml are listed as residuals with a manual step.
1587
+ """
1588
+ operations: list[dict[str, str]] = []
1589
+ residuals: list[dict[str, str]] = []
1590
+ copy = _client_package_destination("codex", home, name)
1591
+ if (copy.exists() or copy.is_symlink()) and copy.resolve() != primary.resolve():
1592
+ operations.append({"action": "archive-plugin-copy", "name": name, "from": str(copy)})
1593
+ market = home / ".agents" / "plugins" / "marketplace.json"
1594
+ if market.is_symlink():
1595
+ residuals.append({"client": "codex", "kind": "marketplace-entry", "name": name, "path": str(market),
1596
+ "manual": f"remove the {name} entry from this file by hand (symlinked file, not edited automatically)"})
1597
+ elif market.is_file():
1598
+ try:
1599
+ plugins = json.loads(market.read_text(encoding="utf-8")).get("plugins", [])
1600
+ listed = isinstance(plugins, list) and any(isinstance(item, dict) and item.get("name") == name for item in plugins)
1601
+ except (OSError, ValueError, AttributeError):
1602
+ listed = False
1603
+ residuals.append({"client": "codex", "kind": "marketplace-entry", "name": name, "path": str(market),
1604
+ "manual": f"unreadable marketplace file; remove the {name} entry by hand if present"})
1605
+ if listed:
1606
+ operations.append({"action": "remove-marketplace-entry", "name": name, "from": str(market)})
1607
+ cache = home / ".codex" / "plugins" / "cache"
1608
+ if cache.is_dir() and not cache.is_symlink():
1609
+ for market_dir in sorted(path for path in cache.iterdir() if path.is_dir()):
1610
+ plugin_dir = market_dir / name
1611
+ if plugin_dir.is_dir():
1612
+ left = [path for path in sorted(plugin_dir.iterdir()) if path.resolve() != primary.resolve()]
1613
+ if left:
1614
+ residuals.append({"client": "codex", "kind": "cache", "name": name, "path": str(plugin_dir),
1615
+ "manual": "other cached versions or copies remain; delete the directory when no longer needed"})
1616
+ config = home / ".codex" / "config.toml"
1617
+ try:
1618
+ mentioned = config.is_file() and f"{name}@" in config.read_text(encoding="utf-8", errors="replace")
1619
+ except OSError:
1620
+ mentioned = False
1621
+ if mentioned:
1622
+ residuals.append({"client": "codex", "kind": "config", "name": name, "path": str(config),
1623
+ "manual": f"remove the [plugins.\"{name}@...\"] table by hand (user configuration, not edited automatically)"})
1624
+ return operations, residuals
1625
+
1626
+
1454
1627
  def reconcile_project(
1455
1628
  project: Path,
1456
1629
  client: str,
@@ -1463,9 +1636,16 @@ def reconcile_project(
1463
1636
  retire_only: bool = False,
1464
1637
  replace: bool = False,
1465
1638
  reset_overrides: bool = False,
1639
+ only: Iterable[str] | None = None,
1640
+ replace_mcp: bool = False,
1641
+ replace_skills: bool = False,
1466
1642
  ) -> dict[str, Any]:
1467
1643
  """Reconcile one project package and explicitly selected legacy components.
1468
1644
 
1645
+ ``only`` (``plugins`` / ``skills`` / ``mcp``) and ``replace_mcp`` / ``replace_skills`` scope a Claude sync
1646
+ to those types (#68). Codex and Cursor install one package that holds every type, so they accept the full
1647
+ selection only.
1648
+
1469
1649
  ``retire_only`` archives the selected legacy components without installing
1470
1650
  or replacing the project package itself. Claude Code is handled by
1471
1651
  ``agent_pack_claude`` (dedicated package, MCP entries, Skill links);
@@ -1477,7 +1657,18 @@ def reconcile_project(
1477
1657
  return agent_pack_claude.sync_project(
1478
1658
  project, home=home, apply=apply, replace=replace, reset_overrides=reset_overrides,
1479
1659
  recovery_root=recovery_root, retire_skills=retire_skills, retire_plugins=retire_plugins,
1480
- retire_only=retire_only)
1660
+ retire_only=retire_only, only=only, replace_mcp=replace_mcp, replace_skills=replace_skills)
1661
+ import agent_pack_claude # noqa: PLC0415 - shipped next to this file
1662
+
1663
+ if agent_pack_claude.normalize_only(only) != frozenset(agent_pack_claude.SYNC_TYPES) and not retire_only:
1664
+ raise AgentPackError(
1665
+ f"--only mcp|skills|plugins is supported for the claude client only: {client} installs one package "
1666
+ "that holds Skills, MCP servers and the manifest together")
1667
+ if replace_skills or (replace_mcp and client != "codex"):
1668
+ raise AgentPackError(
1669
+ "--replace-skills / --replace-mcp are supported for the claude client only"
1670
+ " (codex also accepts --replace-mcp for its native remote MCP entries)")
1671
+ replace = replace or replace_mcp
1481
1672
  layout = load_project_layout(project)
1482
1673
  authority = inventory_project(layout.root)
1483
1674
  package_name = _package_name(layout.root)
@@ -1516,14 +1707,18 @@ def reconcile_project(
1516
1707
  needs_package = not retire_only
1517
1708
  if retire_only:
1518
1709
  package_action = "skip-plugin"
1519
- elif destination.exists() or destination.is_symlink():
1710
+ else:
1711
+ # Build the package in a scratch directory for every preview and apply, so the
1712
+ # portability, secret and credential-key checks run before anything is written and a
1713
+ # preview reports exactly what ``--apply`` would (same ok, exit code and message).
1520
1714
  with tempfile.TemporaryDirectory(prefix="agent-pack-plan-") as temporary:
1521
- expected = _build_package(authority, package_name, Path(temporary), client)
1522
- if _tree_fingerprint(expected) == _tree_fingerprint(destination):
1523
- package_action = "keep-plugin"
1524
- needs_package = False
1525
- else:
1526
- package_action = "replace-plugin"
1715
+ expected = _build_package(authority, package_name, Path(temporary), client, home)
1716
+ if destination.exists() or destination.is_symlink():
1717
+ if _tree_fingerprint(expected) == _tree_fingerprint(destination):
1718
+ package_action = "keep-plugin"
1719
+ needs_package = False
1720
+ else:
1721
+ package_action = "replace-plugin"
1527
1722
 
1528
1723
  native_plan = None
1529
1724
  if client == "codex" and not retire_only:
@@ -1532,14 +1727,18 @@ def reconcile_project(
1532
1727
  operations: list[dict[str, str]] = [] if retire_only else [
1533
1728
  {"action": package_action, "client": client, "name": package_name, "to": str(destination)}
1534
1729
  ]
1535
- operations.extend(
1536
- {"action": "archive-" + kind, "name": name, "from": str(path)}
1537
- for kind, name, path in retirement_targets
1538
- )
1730
+ residuals: list[dict[str, str]] = []
1731
+ for kind, name, path in retirement_targets:
1732
+ operations.append({"action": "archive-" + kind, "name": name, "from": str(path)})
1733
+ if kind == "plugin" and client == "codex":
1734
+ extra_operations, extra_residuals = _codex_retirement_extras(home, name, path)
1735
+ operations.extend(extra_operations)
1736
+ residuals.extend(extra_residuals)
1539
1737
  if native_plan is not None:
1540
1738
  operations.extend(native_plan["operations"])
1739
+ extras = {"residuals": residuals} if residuals else {}
1541
1740
  if not apply:
1542
- return {"ok": True, "applied": False, "states": states, "operations": operations}
1741
+ return {"ok": True, "applied": False, "states": states, "operations": operations, **extras}
1543
1742
 
1544
1743
  recovery_base = (recovery_root or home / ".agent-pack" / "recovery").expanduser().resolve()
1545
1744
  recovery_base.mkdir(parents=True, exist_ok=True)
@@ -1549,6 +1748,7 @@ def reconcile_project(
1549
1748
  moved: list[tuple[Path, Path]] = []
1550
1749
  installed = False
1551
1750
  native_applied = False
1751
+ marketplace_backup: tuple[Path, bytes] | None = None
1552
1752
  try:
1553
1753
  if needs_package:
1554
1754
  destination.parent.mkdir(parents=True, exist_ok=True)
@@ -1559,7 +1759,7 @@ def reconcile_project(
1559
1759
  moved.append((archived, destination))
1560
1760
  staging_parent = Path(tempfile.mkdtemp(prefix=".agent-pack-", dir=destination.parent))
1561
1761
  try:
1562
- staged = _build_package(authority, package_name, staging_parent, client)
1762
+ staged = _build_package(authority, package_name, staging_parent, client, home)
1563
1763
  os.replace(staged, destination)
1564
1764
  installed = True
1565
1765
  finally:
@@ -1572,6 +1772,21 @@ def reconcile_project(
1572
1772
  archived.parent.mkdir(parents=True, exist_ok=True)
1573
1773
  os.replace(path, archived)
1574
1774
  moved.append((archived, path))
1775
+ for operation in operations:
1776
+ if operation["action"] == "archive-plugin-copy":
1777
+ copy = Path(operation["from"])
1778
+ archived = transaction / "plugin-copies" / operation["name"]
1779
+ archived.parent.mkdir(parents=True, exist_ok=True)
1780
+ os.replace(copy, archived)
1781
+ moved.append((archived, copy))
1782
+ elif operation["action"] == "remove-marketplace-entry":
1783
+ market = Path(operation["from"])
1784
+ original_bytes = market.read_bytes()
1785
+ marketplace_backup = (market, original_bytes)
1786
+ (transaction / "marketplace").mkdir(parents=True, exist_ok=True)
1787
+ shutil.copy2(market, transaction / "marketplace" / market.name)
1788
+ market.write_text(_marketplace_without(original_bytes.decode("utf-8"), operation["name"]),
1789
+ encoding="utf-8")
1575
1790
  if native_plan is not None:
1576
1791
  agent_pack_codex_mcp.apply(native_plan, transaction)
1577
1792
  native_applied = True
@@ -1580,6 +1795,8 @@ def reconcile_project(
1580
1795
  except Exception as exc:
1581
1796
  if native_applied:
1582
1797
  agent_pack_codex_mcp.rollback(native_plan)
1798
+ if marketplace_backup is not None:
1799
+ marketplace_backup[0].write_bytes(marketplace_backup[1])
1583
1800
  if installed and destination.exists():
1584
1801
  shutil.rmtree(destination)
1585
1802
  for archived, original in reversed(moved):
@@ -1589,7 +1806,7 @@ def reconcile_project(
1589
1806
  raise AgentPackError(f"reconcile rolled back: {exc}") from exc
1590
1807
  return {
1591
1808
  "ok": True, "applied": True, "states": states, "operations": operations,
1592
- "recovery": str(transaction),
1809
+ "recovery": str(transaction), **extras,
1593
1810
  }
1594
1811
 
1595
1812
 
@@ -1602,9 +1819,13 @@ def sync_project(
1602
1819
  replace: bool = False,
1603
1820
  reset_overrides: bool = False,
1604
1821
  recovery_root: Path | None = None,
1822
+ only: Iterable[str] | None = None,
1823
+ replace_mcp: bool = False,
1824
+ replace_skills: bool = False,
1605
1825
  ) -> dict[str, Any]:
1606
1826
  return reconcile_project(project, client, home=home, apply=apply, replace=replace,
1607
- reset_overrides=reset_overrides, recovery_root=recovery_root)
1827
+ reset_overrides=reset_overrides, recovery_root=recovery_root,
1828
+ only=only, replace_mcp=replace_mcp, replace_skills=replace_skills)
1608
1829
 
1609
1830
 
1610
1831
  def _update_personal_marketplace(home: Path, package_name: str) -> None:
@@ -1683,7 +1904,7 @@ def client_drift(project: Path, client: str, home: Path | None = None) -> dict[s
1683
1904
  report["excluded"] = sorted(item.name for item in authority.mcps
1684
1905
  if item.portable and not _mcp_allowed(layout, item.name, client))
1685
1906
  with tempfile.TemporaryDirectory(prefix="agent-pack-drift-") as temporary:
1686
- expected = _build_package(authority, name, Path(temporary), client)
1907
+ expected = _build_package(authority, name, Path(temporary), client, home)
1687
1908
  if destination.is_symlink() and not destination.exists():
1688
1909
  report["dangling"].append(f"package {name}: {destination}")
1689
1910
  elif not destination.is_dir():
@@ -1746,6 +1967,9 @@ def doctor(project: Path, clients: Iterable[str] = (), home: Path | None = None)
1746
1967
  f"plugin {plugin['name']}: Codex adapter version {adapter_version!r} "
1747
1968
  f"does not match plugin.json version {plugin['version']!r}"
1748
1969
  )
1970
+ for item in inventory.mcps:
1971
+ if item.portable:
1972
+ issues.extend(_mcp_plugin_root_problems(item, inventory))
1749
1973
  required_env: set[str] = set()
1750
1974
  for item in inventory.mcps:
1751
1975
  if item.portable and item.config.get("type") == "stdio":
@@ -1798,15 +2022,32 @@ def _print(value: dict[str, Any], output: str) -> None:
1798
2022
  counts = value.get("counts")
1799
2023
  if isinstance(counts, dict):
1800
2024
  print("counts: " + ", ".join(f"{key}={number}" for key, number in counts.items()))
2025
+ summary = value.get("conflicts")
2026
+ if isinstance(summary, dict):
2027
+ print("conflicts: " + ", ".join(f"{key}={number}" for key, number in summary.items()))
1801
2028
  for operation in value.get("operations", []):
1802
2029
  target = operation.get("to") or operation.get("from", "")
1803
2030
  print(f"- {operation['action']}: {operation.get('name', '')} -> {target}")
2031
+ for item in value.get("residuals", []):
2032
+ print(f"! residual {item['kind']}: {item['name']} -> {item['path']} ({item['manual']})")
1804
2033
  for issue in value.get("issues", []):
1805
2034
  print(f"! {issue}")
1806
2035
  for warning in value.get("warnings", []):
1807
2036
  print(f"~ {warning}")
1808
2037
 
1809
2038
 
2039
+ def _add_scope_arguments(parser: argparse.ArgumentParser) -> None:
2040
+ parser.add_argument("--only", action="append", default=[], metavar="TYPE",
2041
+ help="claude: sync only these types (repeat or comma separate): mcp, skills, plugins; "
2042
+ "default is all. plugins = the package and its install record. Other types are left untouched")
2043
+ parser.add_argument("--replace-mcp", action="store_true",
2044
+ help="claude: replace only conflicting user-scope MCP entries this package did not install "
2045
+ "(--replace covers every type)")
2046
+ parser.add_argument("--replace-skills", action="store_true",
2047
+ help="claude: replace only conflicting user-level Skills this package did not install; they "
2048
+ "apply to every project (--replace covers every type)")
2049
+
2050
+
1810
2051
  def build_parser() -> argparse.ArgumentParser:
1811
2052
  parser = argparse.ArgumentParser(prog="agent-pack")
1812
2053
  parser.add_argument("--output", choices=("text", "json"), default="text")
@@ -1842,6 +2083,7 @@ def build_parser() -> argparse.ArgumentParser:
1842
2083
  sync_parser.add_argument("--reset-overrides", action="store_true",
1843
2084
  help="claude: drop local credential values (headers / env) instead of keeping them")
1844
2085
  sync_parser.add_argument("--recovery-root", type=Path)
2086
+ _add_scope_arguments(sync_parser)
1845
2087
 
1846
2088
  bootstrap_parser = sub.add_parser("bootstrap")
1847
2089
  bootstrap_parser.add_argument("--plugin", type=Path, required=True)
@@ -1871,6 +2113,7 @@ def build_parser() -> argparse.ArgumentParser:
1871
2113
  help="archive the selected legacy components without installing the project package",
1872
2114
  )
1873
2115
  reconcile_parser.add_argument("--apply", action="store_true")
2116
+ _add_scope_arguments(reconcile_parser)
1874
2117
  return parser
1875
2118
 
1876
2119
 
@@ -1898,6 +2141,7 @@ def main(argv: list[str] | None = None) -> int:
1898
2141
  result = sync_project(
1899
2142
  args.project, args.client, home=args.home, apply=args.apply, replace=args.replace,
1900
2143
  reset_overrides=args.reset_overrides, recovery_root=args.recovery_root,
2144
+ only=args.only, replace_mcp=args.replace_mcp, replace_skills=args.replace_skills,
1901
2145
  )
1902
2146
  elif args.command == "bootstrap":
1903
2147
  result = install_plugin(
@@ -1923,6 +2167,7 @@ def main(argv: list[str] | None = None) -> int:
1923
2167
  retire_only=args.retire_only,
1924
2168
  replace=args.replace,
1925
2169
  reset_overrides=args.reset_overrides,
2170
+ only=args.only, replace_mcp=args.replace_mcp, replace_skills=args.replace_skills,
1926
2171
  )
1927
2172
  _print(result, args.output)
1928
2173
  return 0 if result.get("ok", True) else 1
@@ -1935,4 +2180,10 @@ def main(argv: list[str] | None = None) -> int:
1935
2180
 
1936
2181
 
1937
2182
  if __name__ == "__main__":
1938
- raise SystemExit(main())
2183
+ # Run through the importable module, not ``__main__``: ``agent_pack_claude`` and
2184
+ # ``agent_pack_codex_mcp`` do ``import agent_pack_config``, which would otherwise load a
2185
+ # second copy of this file whose ``AgentPackError`` is a different class, so ``main()``'s
2186
+ # ``except AgentPackError`` could not catch what they raise (a stack trace, exit 1).
2187
+ import agent_pack_config as _module # noqa: PLC0415
2188
+
2189
+ raise SystemExit(_module.main())
@@ -487,6 +487,55 @@ def cursor_commands(runtime: Path) -> dict[str, dict]:
487
487
  "stop": {"command": f"{base} stop", "timeout": 10}}
488
488
 
489
489
 
490
+ # ---------------------------------------------------------------- a stable runtime path for the hook command
491
+
492
+ # Directory names that package runners use for a throw-away copy of a package; the cache can be emptied at any time.
493
+ # npm / npx: <npm cache>/_npx/<hash>/node_modules/... (cache: ~/.npm on macOS and Linux, %LocalAppData%\npm-cache on Windows;
494
+ # the ``_npx`` folder name is the same everywhere, and npm_config_cache only moves its parent)
495
+ # pnpm dlx: <pnpm cache>/dlx/<hash>/... (a path that also has a pnpm component)
496
+ # yarn dlx: <tmp>/xfs-<hash>/dlx-<pid>/...
497
+ # bunx: <tmp>/bunx-<uid>-<package>@<version>/...
498
+ # Only npm's layout is confirmed on a real machine (macOS, issue #81); the others come from the tools' documented behaviour
499
+ # and are not run here.
500
+ EPHEMERAL_PARTS = ("_npx",)
501
+ BUNX_PART = re.compile(r"^bunx-\d+-")
502
+
503
+
504
+ def is_ephemeral_runtime(path: Any) -> bool:
505
+ """True when ``path`` lies in a package runner's disposable cache. A pure function of the path text: POSIX and Windows
506
+ separators and letter case are both accepted, so the same answer comes out on every platform."""
507
+ parts = [part.lower() for part in re.split(r"[\\/]+", str(path)) if part]
508
+ if any(part in EPHEMERAL_PARTS for part in parts):
509
+ return True
510
+ if any(BUNX_PART.match(part) for part in parts):
511
+ return True
512
+ if any(part.startswith("dlx-") for part in parts) and any(part.startswith("xfs-") for part in parts):
513
+ return True
514
+ return "dlx" in parts and any("pnpm" in part for part in parts)
515
+
516
+
517
+ def running_runtime() -> Path:
518
+ """The agenthelm.py next to this module (the one that is running)."""
519
+ return Path(__file__).resolve().with_name("agenthelm.py")
520
+
521
+
522
+ def stable_runtime(env: Any, running: Path) -> tuple[Path | None, dict]:
523
+ """The agenthelm.py a hook command should call: this file when it is not in a disposable cache, otherwise an installed
524
+ copy (Cursor's plugin directory, then the ``runtime install`` data directory); None when there is none."""
525
+ if not is_ephemeral_runtime(running):
526
+ return running, {"source": "running-file", "ephemeral": None, "searched": []}
527
+ candidates = [("cursor-plugin", env.home / ".cursor" / "plugins" / "local" / "agent-pack" / "runtime" / "agenthelm.py")]
528
+ try:
529
+ import agenthelm_runtime # noqa: PLC0415 - shipped next to this file
530
+ candidates.append(("runtime-current", agenthelm_runtime.current_link(env) / "plugins" / "agent-pack" / "runtime" / "agenthelm.py"))
531
+ except Exception: # noqa: BLE001 - the data directory is optional
532
+ pass
533
+ for source, path in candidates:
534
+ if path.is_file() and not is_ephemeral_runtime(path):
535
+ return path, {"source": source, "ephemeral": str(running), "searched": [str(item) for _, item in candidates]}
536
+ return None, {"source": None, "ephemeral": str(running), "searched": [str(item) for _, item in candidates]}
537
+
538
+
490
539
  def merged_cursor_hooks(existing: dict, runtime: Path, remove: bool) -> dict:
491
540
  data = json.loads(json.dumps(existing)) if existing else {}
492
541
  data.setdefault("version", 1)
@@ -518,11 +567,19 @@ def install_hooks(args: argparse.Namespace, host: Any) -> dict:
518
567
  raise host.CheckError(say("err_hooks_json", lang, target=target, error=exc)) from exc
519
568
  if not isinstance(existing, dict):
520
569
  raise host.CheckError(say("err_hooks_root", lang, target=target))
521
- runtime = Path(__file__).resolve().with_name("agenthelm.py")
570
+ running = running_runtime()
571
+ runtime, where = (running, {"source": "running-file", "ephemeral": None, "searched": []}) if args.remove else stable_runtime(env, running)
572
+ if runtime is None: # nothing stable to point the hooks at: writing would leave hooks that break when the cache is cleaned
573
+ searched = ", ".join(where["searched"])
574
+ message = say("err_unstable_runtime", lang, runtime=where["ephemeral"], searched=searched)
575
+ if args.apply:
576
+ raise host.CheckError(message)
577
+ return {"ok": True, "applied": False, "target": str(target), "changed": False, "remove": False, "blocked": message,
578
+ "runtime": where, "hooks": existing.get("hooks", {}), "note": say("note_cursor", lang), "lang": lang}
522
579
  merged = merged_cursor_hooks(existing, runtime, args.remove)
523
580
  changed = merged != existing
524
581
  result = {"ok": True, "applied": False, "target": str(target), "changed": changed, "remove": args.remove,
525
- "hooks": merged.get("hooks", {})}
582
+ "runtime": {**where, "path": str(runtime)}, "hooks": merged.get("hooks", {})}
526
583
  if args.apply and changed:
527
584
  if target.is_file():
528
585
  backup = target.with_name(target.name + ".agenthelm-bak")
@@ -606,8 +663,14 @@ def main(argv: list[str], host: Any) -> int:
606
663
  print("\n".join(lines))
607
664
  else:
608
665
  lang = result["lang"]
666
+ if result.get("blocked"):
667
+ print(say("install_line", lang, verb=say("install_blocked", lang), target=result["target"]))
668
+ print(result["blocked"])
669
+ return 0
609
670
  verb = say("install_written" if result["applied"] else ("install_unchanged" if not result["changed"] else "install_preview"), lang)
610
671
  print(say("install_line", lang, verb=verb, target=result["target"]))
672
+ if result["runtime"].get("ephemeral"):
673
+ print(say("note_runtime_replaced", lang, ephemeral=result["runtime"]["ephemeral"], stable=result["runtime"]["path"]))
611
674
  print(json.dumps(result["hooks"], ensure_ascii=False, indent=2))
612
675
  print(result["note"])
613
676
  return 0