Skip to content

The agent that grows with you

feat(pm): `hermes pm install --extra NAME`; one shared hint for missing extras

ethernet029cabb4669a
diff --git a/agent/anthropic_adapter.py b/agent/anthropic_adapter.py
index 432135dd57d..24a7d84488f 100644
--- a/agent/anthropic_adapter.py
+++ b/agent/anthropic_adapter.py
@@ -4,6 +4,7 @@ OpenAI-style internals. Auth: API keys (``sk-ant-api*``) -> x-api-key; OAuth set
payload conversion and credentials live in ``agent/anthropic_{endpoints,message_convert,
credentials}.py``; import them from there."""
+from pm import install_hint
import logging
import math
import os
@@ -60,7 +61,7 @@ def _require_sdk(purpose: str, verb: str = "Install it with"):
sdk = _get_anthropic_sdk()
if sdk is None:
raise ImportError(f"The 'anthropic' package is required for {purpose}. {verb}: "
- "python -c \"from pm import sync_venv; sync_venv(['anthropic'], explicit=True)\"")
+ f"{install_hint('anthropic')}")
return sdk
diff --git a/agent/azure_identity_adapter.py b/agent/azure_identity_adapter.py
index 5bf2ef2b45c..dd89c60ceae 100644
--- a/agent/azure_identity_adapter.py
+++ b/agent/azure_identity_adapter.py
@@ -11,6 +11,7 @@ Reference: https://learn.microsoft.com/azure/ai-foundry/foundry-models/how-to/co
from __future__ import annotations
+from pm import install_hint
import contextvars
import functools
import logging
@@ -32,7 +33,7 @@ SCOPE_AI_AZURE_DEFAULT = "https://ai.azure.com/.default"
_AZURE_IDENTITY_FEATURE = "azure-identity"
_INSTALL_MSG = "The 'azure-identity' package is required for Azure AI Foundry Entra ID authentication. "
_LAZY_INSTALL_HINT = (
- "Run: python -c \"from pm import sync_venv; sync_venv(['azure-identity'], explicit=True)\""
+ f"Run: {install_hint('azure-identity')}"
)
_AUTH_HEADERS = ("Authorization", "authorization", "Api-Key", "api-key", "X-Api-Key", "x-api-key")
diff --git a/agent/bedrock_adapter.py b/agent/bedrock_adapter.py
index 69cb1d967c4..dbc8046d7a0 100644
--- a/agent/bedrock_adapter.py
+++ b/agent/bedrock_adapter.py
@@ -5,6 +5,7 @@ control-plane model discovery. OpenAI-format messages/tools are converted to Con
and responses normalized back to OpenAI-shaped objects.
"""
+from pm import install_hint
import base64
import importlib
import json
@@ -97,7 +98,7 @@ def _require_boto3():
except ImportError:
raise ImportError(
"The 'boto3' package is required for the AWS Bedrock provider. "
- "Run: python -c \"from pm import sync_venv; sync_venv(['bedrock'], explicit=True)\""
+ f"Run: {install_hint('bedrock')}"
)
try:
version = tuple(int(x) for x in boto3.__version__.split(".")[:3])
diff --git a/agent/monitoring/otlp_exporter.py b/agent/monitoring/otlp_exporter.py
index 7ac7a6a82c1..bbd64896828 100644
--- a/agent/monitoring/otlp_exporter.py
+++ b/agent/monitoring/otlp_exporter.py
@@ -9,6 +9,7 @@ subscriber runs fail-isolated on the emitter thread; ``event_filter`` keeps othe
from __future__ import annotations
+from pm import install_hint
import importlib
import logging
import os
@@ -66,7 +67,7 @@ def _require_sdk(names: Iterable[str] = _SPAN_SDK, *, auto_install: bool = True)
except Exception as e: # ImportError or partial install
raise OTLPUnavailable(
"OTLP export requires the optional dependency. Install with:\n"
- " python -c \"from pm import sync_venv; sync_venv(['otlp'], explicit=True)\"\n"
+ f" {install_hint('otlp')}\n"
f"(import error: {e})"
)
diff --git a/agent/trace_upload.py b/agent/trace_upload.py
index 0e8e987a790..7da260ad497 100644
--- a/agent/trace_upload.py
+++ b/agent/trace_upload.py
@@ -7,6 +7,7 @@ programmatic callers use :func:`build_trace_jsonl` + :func:`_do_upload`."""
from __future__ import annotations
+from pm import install_hint
import json
import logging
import os
@@ -195,7 +196,7 @@ def _do_upload(
from huggingface_hub import HfApi
except ImportError:
return ("Hugging Face upload needs the `huggingface_hub` package. Run: "
- "python -c \"from pm import sync_venv; sync_venv(['trace-upload'], explicit=True)\"")
+ f"{install_hint('trace-upload')}")
api = HfApi(token=token)
try:
who = api.whoami()
diff --git a/gateway/platforms/qqbot/adapter.py b/gateway/platforms/qqbot/adapter.py
index 7d8eaf9a150..1db05011f43 100644
--- a/gateway/platforms/qqbot/adapter.py
+++ b/gateway/platforms/qqbot/adapter.py
@@ -10,6 +10,7 @@ tries QQ's free ``asr_refer_text`` first, then the configured STT provider.
from __future__ import annotations
+from pm import install_hint
import asyncio
import contextlib
import json
@@ -189,7 +190,7 @@ class QQAdapter(OwnAccessPolicyMixin, BasePlatformAdapter):
is accepted for interface conformance only (QQBot has no server-side update queue)."""
for ok, code, what, hint in (
(AIOHTTP_AVAILABLE, "qq_missing_dependency", "aiohttp not installed",
- ". Run: python -c \"from pm import sync_venv; sync_venv(['messaging'], explicit=True)\""),
+ f". Run: {install_hint('messaging')}"),
(HTTPX_AVAILABLE, "qq_missing_dependency", "httpx not installed", ". Run: hermes pm repair"),
(self._app_id and self._client_secret, "qq_missing_credentials",
"QQ_APP_ID and QQ_CLIENT_SECRET are required", "")):
@@ -1136,7 +1137,7 @@ class QQAdapter(OwnAccessPolicyMixin, BasePlatformAdapter):
import pilk
except ImportError:
logger.warning("[%s] pilk not installed — cannot decode SILK audio. Run: "
- "python -c \"from pm import sync_venv; sync_venv(['silk'], explicit=True)\"", self._log_tag)
+ f"{install_hint('silk')}", self._log_tag)
return None
silk_path = src_path.rsplit(".", 1)[0] + ".silk"
diff --git a/gateway/platforms/qqbot/onboard.py b/gateway/platforms/qqbot/onboard.py
index 0a3b848accf..73c31f6a46a 100644
--- a/gateway/platforms/qqbot/onboard.py
+++ b/gateway/platforms/qqbot/onboard.py
@@ -3,6 +3,7 @@
from __future__ import annotations
+from pm import install_hint
import logging
import time
from enum import IntEnum
@@ -98,7 +99,7 @@ def qr_register(timeout_seconds: int = 600) -> Optional[dict]:
else:
print(f" Open this URL in QQ on your phone:\n {url}")
print(" For a scannable QR code, run: "
- "python -c \"from pm import sync_venv; sync_venv(['messaging'], explicit=True)\"")
+ f"{install_hint('messaging')}")
print()
while time.monotonic() < deadline:
try:
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index bc7350eb0e0..0e3a7cfab88 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -5,6 +5,7 @@ are imported lazily inside method bodies (import cycle) so ``patch("gateway.run.
from __future__ import annotations
+from pm import install_hint
import logging
from typing import TYPE_CHECKING
import asyncio
@@ -2721,7 +2722,7 @@ class GatewayTurnMixin:
from aiohttp import ClientSession as _AioClientSession, ClientTimeout
except ImportError:
return self._proxy_error_result("⚠️ Proxy mode requires aiohttp. Run: "
- "python -c \"from pm import sync_venv; sync_venv(['messaging'], explicit=True)\"")
+ f"{install_hint('messaging')}")
proxy_url = self._get_proxy_url()
if not proxy_url:
diff --git a/gateway/run_voice.py b/gateway/run_voice.py
index 7441d49ebec..06a8df1137a 100644
--- a/gateway/run_voice.py
+++ b/gateway/run_voice.py
@@ -4,6 +4,7 @@ the MRO). ``gateway.run`` internals are imported lazily inside method bodies (im
from __future__ import annotations
+from pm import install_hint
import asyncio
import functools
import json
@@ -164,7 +165,7 @@ class GatewayVoiceMixin:
if not any(tok in str(e).lower() for tok in ("pynacl", "nacl", "davey")):
return f"Failed to join voice channel: {e}"
return ("Voice dependencies are missing (PyNaCl / davey). "
- "Run: `python -c \"from pm import sync_venv; sync_venv(['discord'], explicit=True)\"`")
+ f"Run: `{install_hint('discord')}`")
if not success:
adapter._voice_input_callback = None
return "Failed to join voice channel. Check bot permissions (Connect + Speak)."
diff --git a/hermes_cli/auth.py b/hermes_cli/auth.py
index 82299e8e412..dca01172eee 100644
--- a/hermes_cli/auth.py
+++ b/hermes_cli/auth.py
@@ -11,6 +11,7 @@
from __future__ import annotations
+from pm import install_hint
import json
import logging
import os
@@ -2090,7 +2091,7 @@ def _get_azure_foundry_auth_status() -> Dict[str, Any]:
"is skipped here. Run `hermes doctor` to verify token acquisition."
) if installed else (
"azure-identity not installed. From the Hermes environment, run: "
- "python -c \"from pm import sync_venv; sync_venv(['azure-identity'], explicit=True)\". "
+ f"{install_hint('azure-identity')}. "
"Then restart Hermes."))
except Exception as exc:
info["logged_in"] = False
diff --git a/hermes_cli/auth_commands.py b/hermes_cli/auth_commands.py
index 02b380afb80..75d52b7aa4d 100644
--- a/hermes_cli/auth_commands.py
+++ b/hermes_cli/auth_commands.py
@@ -1,6 +1,7 @@
"""Credential-pool auth subcommands."""
from __future__ import annotations
+from pm import install_hint
from hermes_cli.cli_output import line_input
import math
@@ -753,7 +754,7 @@ def _print_azure_entra_status() -> None:
if not has_azure_identity_installed():
print(" Status: ⚠ azure-identity not installed")
print(" From the Hermes environment, run: "
- "python -c \"from pm import sync_venv; sync_venv(['azure-identity'], explicit=True)\"")
+ f"{install_hint('azure-identity')}")
print(" Then restart Hermes.")
else:
info = describe_active_credential(config=EntraIdentityConfig(scope=scope), timeout_seconds=10.0)
diff --git a/hermes_cli/doctor_connectivity.py b/hermes_cli/doctor_connectivity.py
index f54af5026b6..f3a939f5fdd 100644
--- a/hermes_cli/doctor_connectivity.py
+++ b/hermes_cli/doctor_connectivity.py
@@ -6,6 +6,7 @@ print and issue strings to append. No printing inside workers — the caller pri
from __future__ import annotations
+from pm import install_hint
import concurrent.futures
import errno
import functools
@@ -279,7 +280,7 @@ def _probe_bedrock() -> ProbeResult:
return _row(name, "ok", f"({auth_var}, {region}, {n} models)", label=label)
except ImportError:
hint = ("From the Hermes environment, run: "
- "python -c \"from pm import sync_venv; sync_venv(['bedrock'], explicit=True)\". "
+ f"{install_hint('bedrock')}. "
"Then restart Hermes.")
return _row(name, "warn", "(boto3 not installed)", [hint], label=label)
except Exception as e:
@@ -313,7 +314,7 @@ def _probe_azure_entra() -> ProbeResult:
return _row(name, "warn", f"(adapter import failed: {exc})", [f"Azure Foundry adapter import failed: {exc}"], label=label)
if not has_azure_identity_installed():
return _row(name, "warn", "(azure-identity not installed)", ["From the Hermes environment, run: "
- "python -c \"from pm import sync_venv; sync_venv(['azure-identity'], explicit=True)\". "
+ f"{install_hint('azure-identity')}. "
"Then restart Hermes."], label=label)
entra_cfg = model_cfg.get("entra") or {}
scope = (str(entra_cfg.get("scope") or "").strip() if isinstance(entra_cfg, dict) else "") or SCOPE_AI_AZURE_DEFAULT
diff --git a/hermes_cli/main_agent_cmds.py b/hermes_cli/main_agent_cmds.py
index 0086a329fab..17a2e49b65a 100644
--- a/hermes_cli/main_agent_cmds.py
+++ b/hermes_cli/main_agent_cmds.py
@@ -4,6 +4,7 @@ Split out of ``hermes_cli/main.py``. Names that still live in main (``PROJECT_RO
are imported lazily inside the functions that use them (avoids an import cycle).
"""
+from pm import install_hint
import sys
@@ -84,7 +85,7 @@ def cmd_acp(args):
except ImportError as e:
print("The ACP server can't start: its protocol packages are missing from this install.", file=sys.stderr)
print("From the Hermes environment, run: "
- "python -c \"from pm import sync_venv; sync_venv(['acp'], explicit=True)\"", file=sys.stderr)
+ f"{install_hint('acp')}", file=sys.stderr)
print("Then restart Hermes.", file=sys.stderr)
print(f"Details: {e}", file=sys.stderr)
sys.exit(1)
diff --git a/hermes_cli/model_setup_flows_azure.py b/hermes_cli/model_setup_flows_azure.py
index 9af67ce3efa..8d32c8daa0f 100644
--- a/hermes_cli/model_setup_flows_azure.py
+++ b/hermes_cli/model_setup_flows_azure.py
@@ -6,6 +6,7 @@ Prompt strings and config write order are behavior.
from __future__ import annotations
+from pm import install_hint
from dataclasses import dataclass, field
from hermes_cli.config import clear_model_endpoint_credentials
@@ -56,7 +57,7 @@ def _azure_entra_preflight(current_entra: dict):
_say("◐ The 'azure-identity' package is not installed yet.",
" The preflight requests it through PM if lazy installs are enabled.",
" To install explicitly, run from the Hermes environment:",
- " python -c \"from pm import sync_venv; sync_venv(['azure-identity'], explicit=True)\"",
+ f" {install_hint('azure-identity')}",
" Then restart Hermes.")
# Only the optional scope override is persisted; identity selection (tenant,
diff --git a/hermes_cli/telegram_managed_bot.py b/hermes_cli/telegram_managed_bot.py
index 9aa9bca65f4..3225e862d5f 100644
--- a/hermes_cli/telegram_managed_bot.py
+++ b/hermes_cli/telegram_managed_bot.py
@@ -3,6 +3,7 @@ service (no BotFather copy-paste); the raw Telegram token is saved locally after
from __future__ import annotations
+from pm import install_hint
import os
import re
import sys
@@ -78,7 +79,7 @@ def print_qr_code(url: str, *, include_link: bool = True) -> None:
"""Print a QR code to stdout, with URL fallback if qrcode is missing."""
print(render_qr_terminal(url) or (
" (QR code unavailable. From the Hermes environment, run: "
- "python -c \"from pm import sync_venv; sync_venv(['messaging'], explicit=True)\". "
+ f"{install_hint('messaging')}. "
"Then restart Hermes.)"))
if include_link:
print(f" Link: {url}")
diff --git a/plugins/platforms/feishu/adapter.py b/plugins/platforms/feishu/adapter.py
index f135178e38c..ab2414bde83 100644
--- a/plugins/platforms/feishu/adapter.py
+++ b/plugins/platforms/feishu/adapter.py
@@ -18,6 +18,7 @@ Session keys prefer union_id (user_id_alt) over open_id (user_id) for stability.
from __future__ import annotations
+from pm import install_hint
import asyncio
import collections
import concurrent.futures
@@ -4236,7 +4237,7 @@ def _qr_register_inner(*, initial_domain: str, timeout_seconds: int) -> Optional
else:
print(f" Open this URL in Feishu / Lark on your phone:\n\n {qr_url}\n")
print(" Tip: from the Hermes environment, run: "
- "python -c \"from pm import sync_venv; sync_venv(['messaging'], explicit=True)\" "
+ f"{install_hint('messaging')} "
"to display a scannable QR code here next time")
print()
result = _poll_registration(
diff --git a/plugins/platforms/wecom/adapter.py b/plugins/platforms/wecom/adapter.py
index a5fdc6b28f4..c7b0ba13fa3 100644
--- a/plugins/platforms/wecom/adapter.py
+++ b/plugins/platforms/wecom/adapter.py
@@ -6,6 +6,7 @@ Config (``platforms.wecom.extra``): ``bot_id``/``secret`` (or WECOM_BOT_ID / WEC
from __future__ import annotations
+from pm import install_hint
import asyncio
import json
import logging
@@ -675,7 +676,7 @@ def qr_scan_for_bot_info(*, timeout_seconds: int = _QR_POLL_TIMEOUT) -> Optional
except Exception:
print(f" Open this URL in WeCom on your phone:\n\n {page_url}\n")
print(" Tip: from the Hermes environment, run: "
- "python -c \"from pm import sync_venv; sync_venv(['messaging'], explicit=True)\" "
+ f"{install_hint('messaging')} "
"to display a scannable QR code here next time")
print("\n Fetching configuration results...", end="", flush=True)
deadline = time.monotonic() + timeout_seconds
diff --git a/pm/__init__.py b/pm/__init__.py
index 03e20e7f729..310eb8e5a96 100644
--- a/pm/__init__.py
+++ b/pm/__init__.py
@@ -31,7 +31,7 @@ _EXPORTS = {
"prepare_tools",
),
"pm.operations": ("environment_python", "python_tool"),
- "pm.extras": ("available", "ensure_import"),
+ "pm.extras": ("available", "ensure_import", "install_hint"),
"pm.lock": ("Facts", "Lockfile"),
"pm.package": ("InstallError", "Package", "Runner", "compose_env"),
"pm.registry": ("all_packages", "get_package", "register", "walk"),
diff --git a/pm/cli.py b/pm/cli.py
index 883b1feadf5..82ceac23fc3 100644
--- a/pm/cli.py
+++ b/pm/cli.py
@@ -164,9 +164,13 @@ def cmd_install(args) -> int:
return 1
# Source-install launchers require the store interpreter, even though
# Python remains optional when provisioning individual tools.
- names = args.names or source_install_packages(_lockfile().names())
+ extras = list(dict.fromkeys(args.extra))
+ if extras and cross_target:
+ print("✗ --extra syncs this install's venv and cannot combine with --target")
+ return 1
+ names = args.names if args.names or extras else source_install_packages(_lockfile().names())
failed = _install_names(names, target=cross_target)
- if not args.names:
+ if extras or not args.names:
from pm.install import sync_venv
try:
@@ -175,8 +179,8 @@ def cmd_install(args) -> int:
# the installers' old `--extra all` did. sync_venv unions, so
# any lazy extras already recorded survive this; it only makes
# a fresh bootstrap match what the first update would do.
- sync_venv(["all"], explicit=True)
- print("✓ venv")
+ sync_venv(extras or ["all"], explicit=True)
+ print(f"✓ venv{' +' + ' +'.join(extras) if extras else ''}")
except InstallError as e:
print(f"✗ {e}")
failed += 1
@@ -543,6 +547,8 @@ def main(argv=None) -> int:
p = sub.add_parser("install", help="install packages (default: all required)")
p.add_argument("names", nargs="*")
+ p.add_argument("--extra", action="append", default=[], metavar="NAME",
+ help="enable a declared dependency extra in the venv (repeatable)")
p.add_argument(
"--target",
help="stage for a cross target (e.g. linux-arm64-bionic on a glibc "
diff --git a/pm/client.py b/pm/client.py
index eff4735da53..114cf079fb1 100644
--- a/pm/client.py
+++ b/pm/client.py
@@ -65,14 +65,22 @@ def _request(operation, arguments, *, callbacks=None, pause_event=None, project_
# PM is itself a missing prerequisite, not permission to bootstrap tools.
try:
command = runtime_command(worker, bootstrap=False, cache=cache)
- except InstallError as exc:
+ except InstallError as cold:
+ exc = cold
+ if arguments.get("extras"):
+ # The user asked for an extra, not for PM's own runtime: name
+ # the command that provisions both.
+ from pm.extras import install_hint
+
+ exc = InstallError(cold.package, f"{cold.cause} while enabling {list(arguments['extras'])}",
+ "run `" + "`, `".join(install_hint(extra) for extra in arguments["extras"]) + "`")
token = receipt.begin("sync")
try:
receipt.record_refusal("lazy-install", str(exc))
receipt.record_step("dependency-sync", False, f"{type(exc).__name__}: {exc}")
finally:
receipt.finalize("failed", 1, token=token)
- raise
+ raise exc from None
environment["HERMES_DISABLE_LAZY_INSTALLS"] = "1"
elif spec.bootstrap == "never":
command = runtime_command(worker, bootstrap=False, cache=cache)
diff --git a/pm/extras.py b/pm/extras.py
index 9f1709a45c9..b7de900db11 100644
--- a/pm/extras.py
+++ b/pm/extras.py
@@ -158,6 +158,11 @@ def extra_supported(extra: str, *, environment: dict[str, str] | None = None,
return True
+def install_hint(extra: str) -> str:
+ """The one command users are told to run for a missing extra."""
+ return f"hermes pm install --extra {extra}"
+
+
def ensure_import(extra: str) -> None:
"""Make an extra available: no-op when the anchor imports, otherwise
sync the venv with the extra enabled. Raises InstallError on failure
diff --git a/tests/agent/test_azure_identity_adapter.py b/tests/agent/test_azure_identity_adapter.py
index 14fb5301d1f..c732155f94d 100644
--- a/tests/agent/test_azure_identity_adapter.py
+++ b/tests/agent/test_azure_identity_adapter.py
@@ -545,7 +545,7 @@ class TestDescribeActiveCredential:
)
assert info["ok"] is False
assert "lazy installs disabled" in info["error"]
- assert "sync_venv(['azure-identity'], explicit=True)" in info["hint"]
+ assert "hermes pm install --extra azure-identity" in info["hint"]
def test_reports_env_sources_for_managed_identity(self, fake_azure_identity, monkeypatch):
from agent.azure_identity_adapter import describe_active_credential
diff --git a/tests/gateway/test_feishu_onboard.py b/tests/gateway/test_feishu_onboard.py
index 1624b41a2a6..2d85ffe2ef8 100644
--- a/tests/gateway/test_feishu_onboard.py
+++ b/tests/gateway/test_feishu_onboard.py
@@ -244,7 +244,7 @@ class TestQrRegister:
output = capsys.readouterr().out
assert "https://example.com/qr" in output
- assert "sync_venv(['messaging'], explicit=True)" in output
+ assert "hermes pm install --extra messaging" in output
assert "pip install" not in output
# -- Contract: expected errors → None, unexpected errors → propagate --
diff --git a/tests/hermes_cli/test_telegram_managed_bot.py b/tests/hermes_cli/test_telegram_managed_bot.py
index b7b10b49f02..c104ff70ca6 100644
--- a/tests/hermes_cli/test_telegram_managed_bot.py
+++ b/tests/hermes_cli/test_telegram_managed_bot.py
@@ -33,7 +33,7 @@ class TestQRCode:
print_qr_code("https://example.com")
output = capsys.readouterr().out
assert "https://example.com" in output
- assert "sync_venv" in output
+ assert "hermes pm install --extra messaging" in output
assert "pip install" not in output
def test_print_qr_code_with_url(self, capsys):
@@ -49,7 +49,7 @@ class TestQRCode:
with patch.dict("sys.modules", {"qrcode": None}):
print_qr_code("https://t.me/newbot/Bot/test_bot")
captured = capsys.readouterr()
- assert "sync_venv(['messaging'], explicit=True)" in captured.out
+ assert "hermes pm install --extra messaging" in captured.out
assert "pip install" not in captured.out
diff --git a/tests/pm/test_install_extra.py b/tests/pm/test_install_extra.py
new file mode 100644
index 00000000000..980ff502328
--- /dev/null
+++ b/tests/pm/test_install_extra.py
@@ -0,0 +1,52 @@
+"""`hermes pm install --extra NAME` is the one command every missing-extra hint names."""
+from types import SimpleNamespace
+
+import pytest
+
+from pm import install_hint
+
+
+def test_hint_names_a_command_the_cli_accepts(monkeypatch):
+ from pm import cli, runtime
+ from pm import install as install_mod
+
+ synced = []
+ monkeypatch.setattr(runtime, "is_runtime", lambda: True)
+ monkeypatch.setattr(install_mod, "sync_venv", lambda extras, **kwargs: synced.append((list(extras), kwargs)))
+ monkeypatch.setattr(cli, "_install_names",
+ lambda names, target=None: 0 if not names else pytest.fail(f"tools installed: {names}"))
+
+ argv = install_hint("anthropic").split()[2:]
+ assert cli.main(argv) == 0
+ assert synced == [(["anthropic"], {"explicit": True})]
+
+
+def test_extra_syncs_only_the_named_extras(monkeypatch):
+ from pm import cli
+ from pm import install as install_mod
+
+ synced = []
+ monkeypatch.setattr(install_mod, "sync_venv", lambda extras, **kwargs: synced.append(list(extras)))
+ monkeypatch.setattr(cli, "_install_names", lambda names, target=None: 0)
+ assert cli.cmd_install(SimpleNamespace(names=[], extra=["otlp", "mcp", "otlp"], target=None)) == 0
+ assert synced == [["otlp", "mcp"]]
+
+
+def test_cold_runtime_refusal_names_the_extra(monkeypatch, tmp_path):
+ import pm.client as client
+ from pm import receipt
+ from pm.package import InstallError
+
+ monkeypatch.setattr("pm.install.lazy_installs_allowed", lambda: False)
+ monkeypatch.setattr(client, "runtime_environment", lambda: {})
+ monkeypatch.setattr("pm.registry.package_definitions", lambda names: [])
+ monkeypatch.setattr(client, "runtime_command", lambda *args, **kwargs: (_ for _ in ()).throw(
+ InstallError("pm-runtime", "not installed or outdated and lazy installs are disabled")))
+ for name in ("begin", "record_refusal", "record_step", "finalize"):
+ monkeypatch.setattr(receipt, name, lambda *args, **kwargs: None)
+
+ with pytest.raises(InstallError) as info:
+ client._request("sync_venv", {"extras": ["bedrock"], "explicit": False, "repair": False},
+ project_root=tmp_path)
+ assert install_hint("bedrock") in info.value.remedy
+ assert "bedrock" in info.value.cause
diff --git a/tests/tools/test_wake_word.py b/tests/tools/test_wake_word.py
index 46d2b354ad7..88e08fce37f 100644
--- a/tests/tools/test_wake_word.py
+++ b/tests/tools/test_wake_word.py
@@ -373,7 +373,7 @@ def test_requirements_lazy_disabled_returns_remedy_not_nameerror(monkeypatch):
r = ww.check_wake_word_requirements({"provider": "openwakeword"})
assert r["available"] is False
assert r["deps_available"] is False
- assert "sync_venv(['wake-openwakeword'], explicit=True)" in r["hint"]
+ assert "hermes pm install --extra wake-openwakeword" in r["hint"]
def test_requirements_deps_present_but_no_audio_hint(monkeypatch):
diff --git a/tools/mcp_oauth.py b/tools/mcp_oauth.py
index fd3827853d0..c0e5d89d82a 100644
--- a/tools/mcp_oauth.py
+++ b/tools/mcp_oauth.py
@@ -8,6 +8,7 @@ Document URL (CIMD) when the server supports it, else RFC 7591 DCR. ``mcp_server
(all optional): client_id, client_secret, scope, redirect_port, redirect_uri (proxy callback),
redirect_host, client_name, client_metadata_url, cimd, user_agent, timeout."""
+from pm import install_hint
import asyncio
import contextlib
import contextvars
@@ -1227,7 +1228,7 @@ def build_oauth_auth(server_name: str, server_url: str, oauth_config: dict | Non
global HermesOAuthClientProvider
if not _OAUTH_AVAILABLE or _sdk_class("OAuthClientProvider") is None:
logger.warning("MCP OAuth requested for '%s' but SDK auth types are not available. Run: "
- "python -c \"from pm import sync_venv; sync_venv(['mcp'], explicit=True)\"", server_name)
+ f"{install_hint('mcp')}", server_name)
return None
from tools.mcp_oauth_provider import build_provider_kwargs, prepare_oauth_config
diff --git a/tools/send_message_senders.py b/tools/send_message_senders.py
index cfa21e4efc5..f53822dfac4 100644
--- a/tools/send_message_senders.py
+++ b/tools/send_message_senders.py
@@ -1,5 +1,6 @@
"""Standalone per-platform senders and error helpers for send_message."""
+from pm import install_hint
import asyncio
import contextlib
import logging
@@ -304,7 +305,7 @@ async def _send_telegram(token, chat_id, message, media_files=None, thread_id=No
return _success("telegram", chat_id, warnings, message_id=str(last_msg.message_id))
except ImportError:
return {"error": "python-telegram-bot not installed. Run: "
- "python -c \"from pm import sync_venv; sync_venv(['telegram'], explicit=True)\""}
+ f"{install_hint('telegram')}"}
except Exception as e:
return _error(f"Telegram send failed: {e}")
@@ -367,7 +368,7 @@ async def _resolve_slack_user_target(token, chat_id):
import aiohttp
except ImportError:
return None, {"error": "aiohttp not installed. Run: "
- "python -c \"from pm import sync_venv; sync_venv(['messaging'], explicit=True)\""}
+ f"{install_hint('messaging')}"}
try:
from gateway.platforms.base import resolve_proxy_url, proxy_kwargs_for_aiohttp
_sess_kw, _req_kw = proxy_kwargs_for_aiohttp(resolve_proxy_url())
@@ -540,7 +541,7 @@ async def _send_matrix_via_adapter(pconfig, chat_id, message, media_files=None,
from plugins.platforms.matrix.adapter import MatrixAdapter
except ImportError:
return {"error": "Matrix dependencies not installed. Run: "
- "python -c \"from pm import sync_venv; sync_venv(['matrix'], explicit=True)\""}
+ f"{install_hint('matrix')}"}
adapter = MatrixAdapter(pconfig)
try:
if not await adapter.connect():
diff --git a/tools/tts_tool.py b/tools/tts_tool.py
index a1d9c9da5be..ab36cf1a1dc 100644
--- a/tools/tts_tool.py
+++ b/tools/tts_tool.py
@@ -8,6 +8,7 @@ Sibling ``tts_tool_*`` modules hold backends/delivery/lifecycle; they read the s
here (config, provider resolution, lazy SDK importers) through ``_origin()`` at call time.
"""
+from pm import install_hint
import asyncio
import contextlib
import datetime
@@ -169,7 +170,7 @@ _FFMPEG_OPUS_PROVIDERS = frozenset({"edge", "neutts", "minimax", "xai", "kittent
_BUILTIN_DISPATCH: Dict[str, tuple] = {
"elevenlabs": (lambda: _importable(_import_elevenlabs), "ElevenLabs", "_generate_elevenlabs",
"ElevenLabs provider selected but 'elevenlabs' package not installed. Run: "
- "python -c \"from pm import sync_venv; sync_venv(['tts-premium'], explicit=True)\""),
+ f"{install_hint('tts-premium')}"),
"openai": (lambda: _importable(_import_openai_client), "OpenAI TTS", "_generate_openai_tts",
"OpenAI provider selected but 'openai' package not installed."),
"deepinfra": (lambda: _importable(_import_openai_client), "DeepInfra TTS", "_generate_deepinfra_tts",
@@ -220,7 +221,7 @@ def _select_builtin_engine(provider: str) -> tuple:
return "neutts", None
return provider, _error_json(
"No TTS provider available. Enable Edge TTS with: "
- "python -c \"from pm import sync_venv; sync_venv(['edge-tts'], explicit=True)\" "
+ f"{install_hint('edge-tts')} "
"or run 'hermes setup tts' and choose NeuTTS for local synthesis.")
diff --git a/tools/wake_word.py b/tools/wake_word.py
index d38e5d12eed..69f68c21509 100644
--- a/tools/wake_word.py
+++ b/tools/wake_word.py
@@ -10,6 +10,7 @@ idle (two input streams on one device is unreliable cross-platform).
from __future__ import annotations
+from pm import install_hint
import logging
import os
import queue
@@ -391,7 +392,7 @@ def check_wake_word_requirements(cfg: Optional[Dict[str, Any]] = None, *,
key_ok = False
hint = "Set PORCUPINE_ACCESS_KEY (free key at https://console.picovoice.ai)."
elif not deps_ok and not lazy_ok:
- hint = f"python -c \"from pm import sync_venv; sync_venv(['{feature}'], explicit=True)\""
+ hint = install_hint(feature)
elif deps_ok and not audio_ok and resolve_capture_mode(cfg) == "local":
hint = "Microphone capture needs sounddevice + numpy and a working audio device."
elif not stt_ok or not tts_ok: