Skip to content

The agent that grows with you

refactor(hermes_cli): hug closing brackets in plugin CLI modules (AST-identical)

Teknium761686347cc1
diff --git a/hermes_cli/plugin_capabilities.py b/hermes_cli/plugin_capabilities.py
index 095d1e1ffe1..b7f862a945e 100644
--- a/hermes_cli/plugin_capabilities.py
+++ b/hermes_cli/plugin_capabilities.py
@@ -44,8 +44,7 @@ _CAPABILITY_ROWS = (
"task lanes"),
("gateway.platform_actions", ("allow_platform_actions",),
"Act on connected chat platforms as the gateway bot "
- "(add reactions, rename threads) via ctx.platform_actions"),
-)
+ "(add reactions, rename threads) via ctx.platform_actions"))
CAPABILITY_REGISTRY: Dict[str, CapabilitySpec] = {
cid: CapabilitySpec(cid, path, desc) for cid, path, desc in _CAPABILITY_ROWS
}
@@ -67,8 +66,7 @@ def parse_declared_capabilities(raw: Any, plugin_name: str = "?") -> List[str]:
if not isinstance(raw, (list, tuple)):
logger.warning(
"Plugin %s: manifest 'capabilities' must be a list, got %s — ignoring",
- plugin_name, type(raw).__name__,
- )
+ plugin_name, type(raw).__name__)
return []
out: List[str] = []
for item in raw:
@@ -79,8 +77,7 @@ def parse_declared_capabilities(raw: Any, plugin_name: str = "?") -> List[str]:
if cap not in VALID_CAPABILITY_IDS:
logger.warning(
"Plugin %s: unknown capability %r (known: %s) — ignoring",
- plugin_name, cap, ", ".join(sorted(VALID_CAPABILITY_IDS)),
- )
+ plugin_name, cap, ", ".join(sorted(VALID_CAPABILITY_IDS)))
elif cap not in out:
out.append(cap)
return out
@@ -148,8 +145,7 @@ def plugin_capability_granted(plugin_id: str, capability: str, config: Optional[
allowed, evidence = False, "not granted"
logger.info( # audit trail for capability gate decisions
"capability_check plugin=%s capability=%s decision=%s checked_by=plugin_capability_granted evidence=%s",
- plugin_id, capability, "allow" if allowed else "deny", evidence,
- )
+ plugin_id, capability, "allow" if allowed else "deny", evidence)
return allowed
@@ -191,8 +187,7 @@ def record_consent(plugin_id: str, granted: Iterable[str], declared: Iterable[st
save_config(config)
logger.info(
"capability_consent plugin=%s granted=%s declared_hash=%s", plugin_id,
- ",".join(entry[GRANTED_KEY]) or "(none)", entry[CONSENT_KEY]["hash"][:12],
- )
+ ",".join(entry[GRANTED_KEY]) or "(none)", entry[CONSENT_KEY]["hash"][:12])
def consent_hash(plugin_id: str, config: Optional[Mapping[str, Any]] = None) -> Optional[str]:
diff --git a/hermes_cli/plugin_dev.py b/hermes_cli/plugin_dev.py
index 2a68609daa8..8c432559761 100644
--- a/hermes_cli/plugin_dev.py
+++ b/hermes_cli/plugin_dev.py
@@ -46,8 +46,7 @@ def _doctor_runtime(plugin_path: Path):
copied = plugins_root / plugin_path.name
shutil.copytree(
plugin_path, copied,
- ignore=shutil.ignore_patterns(".git", "__pycache__", ".pytest_cache", "*.pyc"),
- )
+ ignore=shutil.ignore_patterns(".git", "__pycache__", ".pytest_cache", "*.pyc"))
stack.enter_context(patch.dict(os.environ, {
"HERMES_HOME": str(home),
"HERMES_BUNDLED_PLUGINS": str(bundled),
@@ -72,8 +71,7 @@ def _doctor_runtime(plugin_path: Path):
raise _DoctorLoadError(f"Hermes discovery found no valid plugin manifest under {copied}")
if len(manifests) != 1:
raise _DoctorLoadError(
- f"Expected one plugin manifest, discovered {len(manifests)} under {copied}"
- )
+ f"Expected one plugin manifest, discovered {len(manifests)} under {copied}")
manifest = manifests[0]
manager._load_plugin(manifest)
loaded = manager._plugins.get(manifest.key or manifest.name)
@@ -85,8 +83,7 @@ def _doctor_runtime(plugin_path: Path):
raise _DoctorLoadError("Plugin registration did not enable the runtime record")
yield SimpleNamespace(
manifest=manifest, manager=manager, registered_tools=tuple(sorted(loaded.tools_registered)),
- registered_hooks=tuple(loaded.hooks_registered),
- )
+ registered_hooks=tuple(loaded.hooks_registered))
finally:
entries_after = {entry.name: entry for entry in registry._snapshot_entries()}
changed_names = {
@@ -144,15 +141,13 @@ class DoctorReport:
if self.manifest is not None:
lines.append(
f" manifest: {self.manifest.name} "
- f"{self.manifest.version or '(no version)'} ({self.manifest.kind})"
- )
+ f"{self.manifest.version or '(no version)'} ({self.manifest.kind})")
for finding in self.findings:
lines.append(f" {'ERROR' if finding.level == 'error' else 'WARN'}: {finding.message}")
if self.ok:
lines.append(" OK: runtime discovery, manifest parsing, import, and registration passed")
lines.append(
- f" registrations: {len(self.registered_tools)} tool(s), {len(self.registered_hooks)} hook(s)",
- )
+ f" registrations: {len(self.registered_tools)} tool(s), {len(self.registered_hooks)} hook(s)")
return "\n".join(lines)
@@ -212,8 +207,7 @@ def resolve_plugin_path(target: str | os.PathLike[str] | None = None) -> Path:
raise FileNotFoundError(
f"{direct.resolve()} holds no plugin manifest "
f"({', '.join(_MANIFEST_NAMES)}), and {raw!r} is not an installed "
- "plugin id. Point Doctor at a plugin directory."
- )
+ "plugin id. Point Doctor at a plugin directory.")
raise FileNotFoundError(f"Plugin {raw!r} was not found as a path or installed plugin id")
@@ -234,8 +228,7 @@ def _check_manifest_v2(report: "DoctorReport", manifest: Any) -> None:
if mv > SUPPORTED_MANIFEST_VERSION:
report.warning(
f"manifest_version {mv} is newer than this Hermes supports "
- f"({SUPPORTED_MANIFEST_VERSION}); unknown fields are ignored"
- )
+ f"({SUPPORTED_MANIFEST_VERSION}); unknown fields are ignored")
api_version = getattr(manifest, "api_version", None)
if api_version is not None and api_version < 1:
@@ -250,8 +243,7 @@ def _check_manifest_v2(report: "DoctorReport", manifest: Any) -> None:
if vr:
report.warning(
f"requires plugin {dep_id!r} ({vr}) — version ranges are "
- "advisory; a missing dependency logs a warning at load"
- )
+ "advisory; a missing dependency logs a warning at load")
pydeps = getattr(manifest, "python_dependencies", []) or []
missing: list[str] = []
@@ -271,14 +263,12 @@ def _check_manifest_v2(report: "DoctorReport", manifest: Any) -> None:
for req in unpinned:
report.warning(
f"python_dependencies entry {req!r} has no upper bound — "
- "pin an upper bound (e.g. 'pkg>=1.0,<2') per the dependency policy"
- )
+ "pin an upper bound (e.g. 'pkg>=1.0,<2') per the dependency policy")
if missing:
report.warning(
"declared python_dependencies not installed: " + ", ".join(missing)
+ " — Hermes never auto-installs plugin dependencies; install manually: pip install "
- + " ".join(f"'{m}'" for m in missing)
- )
+ + " ".join(f"'{m}'" for m in missing))
schema = getattr(manifest, "config_schema", {}) or {}
if schema:
@@ -330,8 +320,7 @@ def doctor_plugin(target: str | os.PathLike[str] | None = None) -> DoctorReport:
callback_name = getattr(callback, "__name__", repr(callback))
report.error(
f"hook callback {callback_name!r} for {hook_name!r} "
- "must accept **kwargs for forward compatibility"
- )
+ "must accept **kwargs for forward compatibility")
for kind, declared, registered in (
("hook", declared_hooks, host.registered_hooks),
diff --git a/hermes_cli/plugin_index.py b/hermes_cli/plugin_index.py
index 2bae200a090..00b87cb6e32 100644
--- a/hermes_cli/plugin_index.py
+++ b/hermes_cli/plugin_index.py
@@ -27,8 +27,7 @@ _MAX_INDEX_BYTES = 5 * 1024 * 1024 # refuse absurdly large index payloads
SECURITY_FOOTER = (
"Indexed \u2260 audited: inclusion in the index is a metadata review only, "
- "not a code audit. Review a plugin before enabling it."
-)
+ "not a code audit. Review a plugin before enabling it.")
@dataclass
@@ -118,8 +117,7 @@ def _parse_entries(raw: Any) -> List[PluginIndexEntry]:
homepage=str(item["homepage"]) if item.get("homepage") else None,
capabilities=[str(c) for c in item.get("capabilities") or []],
api_version=int(api_version) if isinstance(api_version, (int, str)) and str(api_version).isdigit() else None,
- added_at=str(item["added_at"]) if item.get("added_at") else None,
- ))
+ added_at=str(item["added_at"]) if item.get("added_at") else None))
return entries
@@ -202,8 +200,7 @@ def _score_entry(entry: PluginIndexEntry, term: str) -> float:
signals = (
(term in name, 80.0), (term in tags, 70.0), (any(term in t for t in tags), 55.0),
(term in entry.description.lower(), 50.0), (term in entry.author.lower(), 40.0),
- (ratio >= 0.6, ratio * 60.0),
- )
+ (ratio >= 0.6, ratio * 60.0))
return max((points for hit, points in signals if hit), default=0.0)
diff --git a/hermes_cli/plugin_packs.py b/hermes_cli/plugin_packs.py
index 793992dd29b..d7ceb6c50ad 100644
--- a/hermes_cli/plugin_packs.py
+++ b/hermes_cli/plugin_packs.py
@@ -106,8 +106,7 @@ def validate_config_seed(plugin_id: str, seed: Any) -> dict[str, Any]:
reserved consent keys, ``allow_*`` trust gates, and secret-shaped keys."""
if not isinstance(seed, dict):
raise PackError(
- f"Pack config for plugin '{plugin_id}' must be a mapping of plugins.entries.{plugin_id} keys.",
- )
+ f"Pack config for plugin '{plugin_id}' must be a mapping of plugins.entries.{plugin_id} keys.")
for key in seed:
if not isinstance(key, str) or not key.strip():
raise PackError(f"Pack config for plugin '{plugin_id}' has an invalid key: {key!r}.")
@@ -115,14 +114,12 @@ def validate_config_seed(plugin_id: str, seed: Any) -> dict[str, Any]:
raise PackError(
f"Pack config for plugin '{plugin_id}' sets reserved key "
f"'{key}': packs cannot pre-grant capabilities or trust gates. "
- "Capability consent happens interactively at install time."
- )
+ "Capability consent happens interactively at install time.")
if _SECRET_KEY_RE.search(key):
raise PackError(
f"Pack config for plugin '{plugin_id}' sets secret-shaped key "
f"'{key}': secrets never travel in packs. Declare the secret in "
- "the plugin's requires_env instead — it is prompted at install."
- )
+ "the plugin's requires_env instead — it is prompted at install.")
return dict(seed)
@@ -158,8 +155,7 @@ def parse_pack(text: str, *, source: str = "<pack>") -> PluginPack:
return PluginPack(
name=name.strip(), description=str(meta.get("description") or ""),
author=str(meta.get("author") or ""), version=str(meta.get("version") or ""), plugins=entries,
- config=config, skills=[str(s).strip() for s in skills_raw if str(s).strip()],
- )
+ config=config, skills=[str(s).strip() for s in skills_raw if str(s).strip()])
def _parse_pack_entry(item: Any, label: str) -> PackPluginEntry:
@@ -176,22 +172,19 @@ def _parse_pack_entry(item: Any, label: str) -> PackPluginEntry:
if not entry_name and not entry_repo:
raise PackError(
f"Pack plugin entry {label} needs either 'name' (community "
- "index) or 'repo' (owner/repo or git URL)."
- )
+ "index) or 'repo' (owner/repo or git URL).")
ref = item.get("ref") or item.get("version")
if not isinstance(ref, str) or not _EXACT_SHA_RE.fullmatch(ref.strip()):
raise PackError(
f"Pack plugin entry {label} has ref {ref!r}: refs must be "
"exact 40-character commit SHAs (tags and branch names are "
- "rejected — pin the commit for reproducible installs)."
- )
+ "rejected — pin the commit for reproducible installs).")
subdir = item.get("subdir")
if subdir is not None and (not isinstance(subdir, str) or not subdir.strip("/")):
raise PackError(f"Pack plugin entry {label} has an invalid 'subdir'.")
return PackPluginEntry(
ref=ref.strip().lower(), name=entry_name, repo=entry_repo,
- subdir=subdir.strip("/") if isinstance(subdir, str) else None,
- )
+ subdir=subdir.strip("/") if isinstance(subdir, str) else None)
def load_pack(path_or_url: str) -> PluginPack:
@@ -248,19 +241,16 @@ def resolve_pack_plugins(pack: PluginPack) -> List[ResolvedPackPlugin]:
match, candidates = resolve_name(index_entries, entry.name or "")
except Exception as exc: # index load must not crash pack handling
resolved.append(ResolvedPackPlugin(
- entry=entry, identifier=None, resolve_error=f"community index unavailable: {exc}",
- ))
+ entry=entry, identifier=None, resolve_error=f"community index unavailable: {exc}"))
continue
if match is None:
detail = "ambiguous" if len(candidates) > 1 else "not found"
resolved.append(ResolvedPackPlugin(
- entry=entry, identifier=None, resolve_error=f"{detail} in the community index",
- ))
+ entry=entry, identifier=None, resolve_error=f"{detail} in the community index"))
continue
resolved.append(ResolvedPackPlugin(
entry=entry, identifier=match.install_identifier,
- index_capabilities=list(match.capabilities),
- ))
+ index_capabilities=list(match.capabilities)))
return resolved
@@ -292,14 +282,12 @@ def render_pack_review(console, pack: PluginPack, resolved: List[ResolvedPackPlu
console.print(f" {plugin_id}.{key} = {value!r}")
if pack.skills:
console.print(
- "[yellow]Pack lists skills (NOT auto-installed yet):[/yellow] " + ", ".join(pack.skills)
- )
+ "[yellow]Pack lists skills (NOT auto-installed yet):[/yellow] " + ", ".join(pack.skills))
console.print("[dim]Install them manually, e.g. `hermes skills install <id>`.[/dim]")
console.print(
"\n[dim]Installing a pack runs third-party code × "
f"{len(resolved)} plugins. Each plugin's declared capabilities still "
- "require individual consent after install — a pack never bulk-grants.[/dim]"
- )
+ "require individual consent after install — a pack never bulk-grants.[/dim]")
# ---------------------------------------------------------------------------
@@ -325,8 +313,7 @@ def _seed_plugin_config(plugin_id: str, seed: dict[str, Any], console) -> None:
if not isinstance(entry, dict):
console.print(
f"[yellow]Warning:[/yellow] plugins.entries.{plugin_id} is not a "
- "mapping; skipping pack config seed."
- )
+ "mapping; skipping pack config seed.")
return
wrote = False
for key, value in seed.items():
@@ -378,8 +365,7 @@ def install_pack_plugins(
console.print(f"[dim]Installing {display} @ {rp.entry.ref[:12]}...[/dim]")
try:
target, manifest, installed_name = _install_plugin_core(
- rp.identifier, force=force, ref=rp.entry.ref
- )
+ rp.identifier, force=force, ref=rp.entry.ref)
except PluginOperationError as exc:
_fail(display, str(exc))
continue
@@ -481,8 +467,7 @@ def export_pack(*, enabled_only: bool = False, pack_name: str = "my-hermes-pack"
if not repo or not isinstance(revision, str) or not _EXACT_SHA_RE.fullmatch(revision):
warnings.append(
f"{plugin_id}: no Git provenance (local-only or pre-metadata "
- "install) — listed as a comment, not installable from this pack."
- )
+ "install) — listed as a comment, not installable from this pack.")
continue
entry: dict[str, Any] = {"repo": repo, "ref": revision.lower()}
if subdir:
@@ -532,8 +517,7 @@ def cmd_pack_show(source: str) -> None:
if unresolved:
console.print(
f"\n[yellow]{len(unresolved)} entr{'y' if len(unresolved) == 1 else 'ies'} "
- "could not be resolved — install would skip them and exit non-zero.[/yellow]"
- )
+ "could not be resolved — install would skip them and exit non-zero.[/yellow]")
console.print("\n[dim]Dry run only. Install with `hermes plugins pack install ...`.[/dim]")
@@ -548,13 +532,11 @@ def cmd_pack_install(source: str, *, force: bool = False) -> None:
if not (sys.stdin.isatty() and sys.stdout.isatty()):
console.print(
"[red]Error:[/red] Pack install requires an interactive terminal "
- "to review and confirm the pack contents (no --yes in v1)."
- )
+ "to review and confirm the pack contents (no --yes in v1).")
sys.exit(1)
try:
answer = console.input(
- f"\nInstall {len(resolved)} plugin(s) from pack '{pack.name}'? [y/N] ",
- ).strip().lower()
+ f"\nInstall {len(resolved)} plugin(s) from pack '{pack.name}'? [y/N] ").strip().lower()
except (EOFError, KeyboardInterrupt):
answer = ""
if answer not in {"y", "yes"}:
@@ -602,7 +584,6 @@ _PACK_ACTIONS = {
"install": lambda args: cmd_pack_install(args.source, force=getattr(args, "force", False)),
"export": lambda args: cmd_pack_export(
enabled_only=getattr(args, "enabled_only", False),
- name=getattr(args, "name", None) or "my-hermes-pack",
- ),
+ name=getattr(args, "name", None) or "my-hermes-pack"),
"show": lambda args: cmd_pack_show(args.source),
}
diff --git a/hermes_cli/plugins_cmd.py b/hermes_cli/plugins_cmd.py
index 293dc9d3780..55764006ed5 100644
--- a/hermes_cli/plugins_cmd.py
+++ b/hermes_cli/plugins_cmd.py
@@ -153,8 +153,7 @@ def _scan_plugin_tree(plugin_dir: Path, identifier: str, *, force: bool, scan_de
"Review the findings above. Install only plugins from sources "
"you trust. (Scanning can be configured via "
"plugins.scan_on_install in config.yaml.)",
- scan_result=result,
- )
+ scan_result=result)
logger.info("plugin scan passed for %s: %s", plugin_dir.name, reason)
return result
@@ -237,8 +236,7 @@ def _resolve_git_url(identifier: str) -> tuple[str, Optional[str]]:
raise ValueError(
f"Invalid plugin identifier: '{identifier}'. "
"Use a Git URL or 'owner/repo' shorthand (optionally with a subdirectory: "
- "'owner/repo/path/to/plugin')."
- )
+ "'owner/repo/path/to/plugin').")
def _resolve_subdir_within(clone_root: Path, subdir: str) -> Path:
@@ -310,8 +308,7 @@ def _looks_like_plugin_dir(target: Path) -> bool:
return (
_native_manifest_file(target) is not None
or (target / "plugin.json").exists()
- or (target / "__init__.py").exists()
- )
+ or (target / "__init__.py").exists())
def _copy_example_files(plugin_dir: Path, console) -> None:
@@ -364,8 +361,7 @@ def _print_python_dependencies(manifest: dict, console) -> None:
for dep in deps:
console.print(f" - {dep}")
console.print(
- f"[dim]Install them yourself if needed: pip install {' '.join(repr(d) for d in deps)}[/dim]\n",
- )
+ f"[dim]Install them yourself if needed: pip install {' '.join(repr(d) for d in deps)}[/dim]\n")
def _prompt_plugin_env_vars(manifest: dict, console) -> None:
@@ -457,8 +453,7 @@ def _write_install_metadata(metadata: dict[str, dict[str, object]]) -> None:
"""Atomically replace the profile-local plugin install metadata sidecar."""
path = _install_metadata_path()
atomic_write_text(
- path, json.dumps(metadata, indent=2, sort_keys=True) + "\n", tmp_prefix=f"{path.name}.tmp-",
- )
+ path, json.dumps(metadata, indent=2, sort_keys=True) + "\n", tmp_prefix=f"{path.name}.tmp-")
def _normalize_exact_revision(ref: str) -> str:
@@ -500,14 +495,11 @@ def _checkout_exact_revision(repo: Path, git_exe: str, revision: str) -> None:
(
("fetch", "--depth", "1", "origin", revision),
f"Git fetch of commit '{revision}' timed out after 60 seconds.",
- f"Git commit '{revision}' could not be fetched:\n",
- ),
+ f"Git commit '{revision}' could not be fetched:\n"),
(
("checkout", "--detach", revision),
f"Git checkout of commit '{revision}' timed out after 60 seconds.",
- f"Git checkout of commit '{revision}' failed:\n",
- ),
- )
+ f"Git checkout of commit '{revision}' failed:\n"))
for args, timeout_msg, failure_prefix in steps:
try:
_git_or_raise(git_exe, repo, *args, failure_prefix=failure_prefix)
@@ -516,8 +508,7 @@ def _checkout_exact_revision(repo: Path, git_exe: str, revision: str) -> None:
actual = _git_head_revision(repo, git_exe)
if actual != revision:
raise PluginOperationError(
- f"Checked-out revision '{actual}' does not match requested commit '{revision}'."
- )
+ f"Checked-out revision '{actual}' does not match requested commit '{revision}'.")
def _scrub_git_url(git_url: str) -> str:
@@ -542,8 +533,7 @@ def _scrub_cloned_origin(repo: Path, git_exe: str, git_url: str) -> None:
if scrubbed != git_url:
_git_or_raise(
git_exe, repo, "remote", "set-url", "origin", scrubbed, timeout=15,
- failure_prefix="Could not sanitize installed Git remote:\n", source_url=git_url,
- )
+ failure_prefix="Could not sanitize installed Git remote:\n", source_url=git_url)
def _check_manifest_version(manifest: dict, plugin_name: str) -> None:
@@ -657,8 +647,7 @@ def _install_plugin_core(
tmp_target = _resolve_subdir_within(tmp_clone, subdir) if subdir else tmp_clone
manifest = _read_manifest_for_install(tmp_target)
plugin_name = manifest.get("name") or (
- subdir.rstrip("/").rsplit("/", 1)[-1] if subdir else _repo_name_from_url(git_url)
- )
+ subdir.rstrip("/").rsplit("/", 1)[-1] if subdir else _repo_name_from_url(git_url))
try:
target = _sanitize_plugin_name(plugin_name, plugins_dir)
except ValueError as e:
@@ -670,8 +659,7 @@ def _install_plugin_core(
if target.exists() and not force:
raise PluginOperationError(
f"Plugin '{plugin_name}' already exists. Use force reinstall "
- f"or run `hermes plugins update {plugin_name}`."
- )
+ f"or run `hermes plugins update {plugin_name}`.")
prior = old_metadata.get(plugin_name)
if (
target.exists()
@@ -681,8 +669,7 @@ def _install_plugin_core(
):
raise PluginOperationError(
f"Plugin '{plugin_name}' is pinned. Reinstall it with an explicit "
- "--ref <40-character commit SHA> to change its source or revision."
- )
+ "--ref <40-character commit SHA> to change its source or revision.")
new_metadata = {
**old_metadata,
@@ -716,8 +703,7 @@ def _resolve_index_name(identifier: str, console) -> tuple[str, Optional[str]]:
if len(candidates) > 1:
console.print(
f"[red]Error:[/red] Plugin name '{identifier}' is ambiguous in the "
- f"community index ({source}). Candidates:"
- )
+ f"community index ({source}). Candidates:")
for c in candidates:
console.print(f" {c.name} → {c.install_identifier}")
console.print("Re-run with the exact name or the owner/repo identifier.")
@@ -725,8 +711,7 @@ def _resolve_index_name(identifier: str, console) -> tuple[str, Optional[str]]:
console.print(
f"[red]Error:[/red] Plugin '{identifier}' was not found in the "
f"community index ({source}). Use `hermes plugins search <term>` to "
- "browse, or install directly with an owner/repo identifier."
- )
+ "browse, or install directly with an owner/repo identifier.")
sys.exit(1)
pinned_ref: Optional[str] = None
@@ -735,13 +720,11 @@ def _resolve_index_name(identifier: str, console) -> tuple[str, Optional[str]]:
elif entry.ref:
console.print(
f"[dim]Index pins ref '{entry.ref}' (not an exact commit SHA); "
- "installing the default branch head instead.[/dim]"
- )
+ "installing the default branch head instead.[/dim]")
console.print(
f"[dim]Resolved '{entry.name}' via community index ({source}) → "
f"{entry.install_identifier}"
- + (f" @ {pinned_ref[:12]}[/dim]" if pinned_ref else "[/dim]")
- )
+ + (f" @ {pinned_ref[:12]}[/dim]" if pinned_ref else "[/dim]"))
console.print(f"[dim]{SECURITY_FOOTER}[/dim]")
return entry.install_identifier, pinned_ref
@@ -770,8 +753,7 @@ def cmd_install(
if git_url.startswith(("http://", "file://")):
console.print(
"[yellow]Warning:[/yellow] Using insecure/local URL scheme. "
- "Consider using https:// or git@ for production installs.",
- )
+ "Consider using https:// or git@ for production installs.")
console.print(f"[dim]Cloning {git_url}{f' (subdir: {_subdir})' if _subdir else ''}...[/dim]")
@@ -785,15 +767,13 @@ def cmd_install(
try:
target, installed_manifest, installed_name = _install_plugin_core(
- identifier, force=force, ref=ref, scan_decision_cb=_interactive_scan_decision,
- )
+ identifier, force=force, ref=ref, scan_decision_cb=_interactive_scan_decision)
except PluginOperationError as e:
_fail(console, f"[red]{'Blocked' if isinstance(e, PluginScanBlocked) else 'Error'}:[/red] {e}")
if not _looks_like_plugin_dir(target):
console.print(
f"[yellow]Warning:[/yellow] {installed_name} doesn't contain plugin.yaml, "
- f"plugin.json, or __init__.py. It may not be a valid Hermes plugin.",
- )
+ f"plugin.json, or __init__.py. It may not be a valid Hermes plugin.")
_prompt_plugin_env_vars(installed_manifest, console)
_print_python_dependencies(installed_manifest, console)
_display_after_install(target, identifier)
@@ -806,8 +786,7 @@ def cmd_install(
else:
console.print(
f"[dim]Plugin installed but not enabled. "
- f"Run `hermes plugins enable {installed_name}` to activate.[/dim]",
- )
+ f"Run `hermes plugins enable {installed_name}` to activate.[/dim]")
# Non-interactive installs and declines leave declared capabilities ungranted (fail closed).
declared_caps = _declared_capabilities_from_manifest(installed_manifest, installed_name)
@@ -848,11 +827,9 @@ def cmd_update(name: str) -> None:
lambda rec: (
f"Plugin '{name}' is pinned to {rec.get('revision')}. To move it, run "
f"`hermes plugins install {escape(str(rec.get('source', '<source>')))} --force "
- "--ref <40-character commit SHA>`."
- ),
+ "--ref <40-character commit SHA>`."),
lambda: f"Plugin '{name}' was not installed from git (no .git directory). Cannot update.",
- before_pull=lambda: console.print(f"[dim]Updating {name}...[/dim]"),
- )
+ before_pull=lambda: console.print(f"[dim]Updating {name}...[/dim]"))
except PluginOperationError as exc:
_fail(console, f"[red]Error:[/red] {exc}")
# Re-scan: an update can introduce malicious content. The pull has already mutated the
@@ -872,8 +849,7 @@ def cmd_update(name: str) -> None:
console.print(
f"[red]Plugin '{name}' has been disabled.[/red] Review the "
f"findings, then re-enable with `hermes plugins enable {name}` "
- f"if you trust them.",
- )
+ f"if you trust them.")
_post_pull_housekeeping(target, console)
@@ -1055,8 +1031,7 @@ def cmd_enable(name: str, allow_tool_override: Optional[bool] = None) -> None:
if plugin in LEGACY_RELAY_PLUGIN_KEYS:
_fail(console, (
f"[red]Plugin '{plugin}' was removed.[/red] Relay lifecycle is owned "
- f"by Hermes core; configure {RELAY_PLUGINS_CONFIG_ENV} instead."
- ))
+ f"by Hermes core; configure {RELAY_PLUGINS_CONFIG_ENV} instead."))
_refuse_legacy_relay(name)
resolved = _resolve_plugin_key_and_source(name)
@@ -1157,31 +1132,27 @@ def _run_capability_consent(
console.print(
" [dim]Granting trusts the plugin author with these host surfaces. "
"This is consent, not a sandbox — plugins run as regular Python "
- "in-process.[/dim]"
- )
+ "in-process.[/dim]")
if not _is_tty():
console.print(
" [yellow]Non-interactive session: capabilities NOT granted "
"(fail closed).[/yellow] Run "
f"`hermes plugins capabilities {plugin_id}` to review and "
- f"`hermes plugins enable {plugin_id}` to grant interactively."
- )
+ f"`hermes plugins enable {plugin_id}` to grant interactively.")
return False
if _ask_yes(" Grant these capabilities? [y/N] ", console.input):
record_consent(plugin_id, pending, declared)
console.print(
f" [green]✓[/green] Granted: {', '.join(pending)} "
- f"([dim]plugins.entries.{plugin_id}.granted_capabilities[/dim])"
- )
+ f"([dim]plugins.entries.{plugin_id}.granted_capabilities[/dim])")
return True
console.print(
f" [dim]Declined. {plugin_id} stays enabled with these capabilities "
"off; it should degrade gracefully (ctx.has_capability()). Re-run "
- f"`hermes plugins enable {plugin_id}` to grant later.[/dim]"
- )
+ f"`hermes plugins enable {plugin_id}` to grant later.[/dim]")
return False
@@ -1247,14 +1218,12 @@ def _resolve_tool_override_grant(
console.print(
f"[green]✓[/green] Granted [bold]{key}[/bold] permission to "
"override built-in tools "
- f"([dim]plugins.entries.{key}.allow_tool_override: true[/dim])."
- )
+ f"([dim]plugins.entries.{key}.allow_tool_override: true[/dim]).")
else:
console.print(
f"[dim]{key} may not override built-in tools. Re-run "
f"`hermes plugins enable {key} --allow-tool-override` to grant "
- "this later.[/dim]"
- )
+ "this later.[/dim]")
def cmd_disable(name: str) -> None:
@@ -1273,8 +1242,7 @@ def cmd_disable(name: str) -> None:
disabled.add(key)
_save_plugin_sets(enabled, disabled)
console.print(
- f"[yellow]\u2298[/yellow] Plugin [bold]{key}[/bold] disabled. Takes effect on next session.",
- )
+ f"[yellow]\u2298[/yellow] Plugin [bold]{key}[/bold] disabled. Takes effect on next session.")
def _read_manifest_info(d: Path, prefix: str):
@@ -1513,16 +1481,14 @@ _PROVIDER_CATEGORY_SPECS = (
("Memory Provider", "built-in", "", lambda: _get_current_memory_provider(),
lambda: _discover_memory_providers(), lambda v: _save_memory_provider(v)),
("Context Engine", "compressor", "compressor", lambda: _get_current_context_engine(),
- lambda: _discover_context_engines(), lambda v: _save_context_engine(v)),
-)
+ lambda: _discover_context_engines(), lambda v: _save_context_engine(v)))
def _configure_category_spec(spec) -> bool:
"""Launch the radio picker for one ``_PROVIDER_CATEGORY_SPECS`` row. Returns True if changed."""
title, default_label, default_name, current, discover, save = spec
return _configure_provider_category(
- f"{title} (select one)", f"{default_label} (default)", default_name, current(), discover(), save,
- )
+ f"{title} (select one)", f"{default_label} (default)", default_name, current(), discover(), save)
def _provider_categories() -> list:
@@ -1709,8 +1675,7 @@ def _run_composite_ui(curses, plugin_keys, plugin_labels, plugin_selected,
_put(
stdscr, 1, 0,
" ↑↓/j/k navigate PgUp/PgDn page SPACE toggle ENTER configure/confirm ESC done",
- max_x, curses.A_DIM,
- )
+ max_x, curses.A_DIM)
visible_rows = max_y - 4
if cursor < scroll_offset:
scroll_offset = cursor
@@ -1745,15 +1710,13 @@ def _run_composite_ui(curses, plugin_keys, plugin_labels, plugin_selected,
if changed:
console.print(
f"\n[green]\u2713[/green] General plugins: {len(new_enabled)} enabled, "
- f"{len(plugin_keys) - len(new_enabled)} disabled."
- )
+ f"{len(plugin_keys) - len(new_enabled)} disabled.")
elif n_plugins > 0:
console.print("\n[dim]General plugins unchanged.[/dim]")
if providers_changed:
console.print(
f"[green]\u2713[/green] Memory provider: [bold]{_get_current_memory_provider() or 'built-in'}[/bold] "
- f"Context engine: [bold]{_get_current_context_engine()}[/bold]"
- )
+ f"Context engine: [bold]{_get_current_context_engine()}[/bold]")
if n_plugins > 0 or providers_changed:
console.print("[dim]Changes take effect on next session.[/dim]")
console.print()
@@ -1943,10 +1906,8 @@ def dashboard_update_user_plugin(name: str) -> dict[str, Any]:
lambda rec: (
f"Plugin '{name}' is pinned to {rec.get('revision')}; "
f"run `hermes plugins install {rec.get('source', '<source>')} --force "
- "--ref <40-character commit SHA>` to move it."
- ),
- lambda: f"Plugin '{name}' is not a git checkout; cannot pull updates.",
- )
+ "--ref <40-character commit SHA>` to move it."),
+ lambda: f"Plugin '{name}' is not a git checkout; cannot pull updates.")
except PluginOperationError as exc:
return {"ok": False, "error": str(exc)}
_post_pull_housekeeping(target, _console())
@@ -1977,8 +1938,7 @@ def _run_plugin_git(
"""Run one git command inside a plugin checkout (non-interactive)."""
return subprocess.run(
[git_exe, *args], capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=timeout,
- cwd=str(target), stdin=subprocess.DEVNULL, env=noninteractive_git_env(),
- )
+ cwd=str(target), stdin=subprocess.DEVNULL, env=noninteractive_git_env())
def _stash_ref(git_exe: str, target: Path) -> str:
@@ -2011,8 +1971,7 @@ def _git_pull_plugin_dir(target: Path) -> tuple[bool, str]:
pre_stash = _stash_ref(git_exe, target)
push = _run_plugin_git(
git_exe, target, "stash", "push", "--include-untracked", "-m",
- "hermes-plugin-update-autostash",
- )
+ "hermes-plugin-update-autostash")
post_stash = _stash_ref(git_exe, target)
stash_created = bool(post_stash) and post_stash != pre_stash
if not stash_created:
@@ -2021,8 +1980,7 @@ def _git_pull_plugin_dir(target: Path) -> tuple[bool, str]:
return False, (
"Local changes in the plugin checkout could not be "
"stashed; update aborted before touching the checkout."
- + (f"\n{err}" if err else "")
- )
+ + (f"\n{err}" if err else ""))
if push.returncode != 0:
# Saved-but-couldn't-clean (undeletable untracked files):
# the stash entry is complete; reset tracked mods so the
@@ -2055,8 +2013,7 @@ def _git_pull_plugin_dir(target: Path) -> tuple[bool, str]:
"\n⚠ Local changes in this plugin conflicted with the update and "
"were NOT re-applied. They are preserved in git stash — inspect "
"with `git stash show -p stash@{0}` and re-apply with "
- f"`git stash pop` inside {target}."
- )
+ f"`git stash pop` inside {target}.")
except FileNotFoundError:
return False, "git is not installed or not in PATH."
except subprocess.TimeoutExpired:
@@ -2149,22 +2106,19 @@ _PLUGIN_ACTIONS = {
args.identifier,
force=getattr(args, "force", False),
enable=_tri_state_flag(args, "enable", "no_enable"),
- ref=getattr(args, "ref", None),
- ),
+ ref=getattr(args, "ref", None)),
"search": lambda args: cmd_search(
getattr(args, "term", "") or "",
json_output=getattr(args, "json", False),
capability=getattr(args, "capability", None),
- refresh=getattr(args, "refresh", False),
- ),
+ refresh=getattr(args, "refresh", False)),
"update": lambda args: cmd_update(args.name),
"remove": lambda args: cmd_remove(args.name),
"rm": lambda args: cmd_remove(args.name),
"uninstall": lambda args: cmd_remove(args.name),
"enable": lambda args: cmd_enable(
args.name,
- allow_tool_override=_tri_state_flag(args, "allow_tool_override", "no_allow_tool_override"),
- ),
+ allow_tool_override=_tri_state_flag(args, "allow_tool_override", "no_allow_tool_override")),
"disable": lambda args: cmd_disable(args.name),
"capabilities": lambda args: cmd_capabilities(getattr(args, "name", None)),
"list": lambda args: cmd_list(args),
diff --git a/hermes_cli/plugins_dispatch.py b/hermes_cli/plugins_dispatch.py
index 4028d3e2eb8..0ab832883b7 100644
--- a/hermes_cli/plugins_dispatch.py
+++ b/hermes_cli/plugins_dispatch.py
@@ -62,8 +62,7 @@ def format_system_prompt_section(section_id: str, content: str) -> str:
"""Render an auditable, length-framed block recoverable from the full prompt."""
return (
f"{_SYSTEM_PROMPT_SECTION_HEADING_PREFIX}{section_id}\n"
- f"<!-- hermes-plugin-section-chars:{len(content)} -->\n\n{content}"
- )
+ f"<!-- hermes-plugin-section-chars:{len(content)} -->\n\n{content}")
def format_system_prompt_sections(sections: list) -> str:
@@ -190,8 +189,7 @@ class PluginDispatchMixin:
results.append(ret)
except Exception as exc:
logger.warning(
- "Hook '%s' callback %s raised: %s", hook_name, getattr(cb, "__name__", repr(cb)), exc,
- )
+ "Hook '%s' callback %s raised: %s", hook_name, getattr(cb, "__name__", repr(cb)), exc)
return results
def _run_hook_callback_bounded(
@@ -209,8 +207,7 @@ class PluginDispatchMixin:
if (suppressed_until is not None and suppressed_until > time.monotonic()) or running:
logger.warning(
"Hook '%s' callback %s skipped after previous "
- "timeout or while still running", hook_name, callback_name,
- )
+ "timeout or while still running", hook_name, callback_name)
return _HOOK_SKIPPED
if suppressed_until is not None:
self._hook_timeout_suppressed_until.pop(callback_key, None)
@@ -237,11 +234,9 @@ class PluginDispatchMixin:
if not done.wait(timeout=timeout): # do not join — that would reintroduce the hang
with self._hook_timeout_lock:
self._hook_timeout_suppressed_until[callback_key] = (
- time.monotonic() + self._hook_timeout_suppression_seconds
- )
+ time.monotonic() + self._hook_timeout_suppression_seconds)
logger.warning(
- "Hook '%s' callback %s timed out after %gs — skipping", hook_name, callback_name, timeout,
- )
+ "Hook '%s' callback %s timed out after %gs — skipping", hook_name, callback_name, timeout)
return _HOOK_SKIPPED
if "exc" in failure:
raise failure["exc"]
@@ -322,8 +317,7 @@ class PluginDispatchMixin:
except Exception as exc:
logger.warning(
"Event '%s' subscriber %s raised: %s", item.event,
- getattr(callback, "__name__", repr(callback)), exc,
- )
+ getattr(callback, "__name__", repr(callback)), exc)
finally:
self._emit_depth.value = previous_depth
@@ -332,8 +326,7 @@ class PluginDispatchMixin:
with self._event_idle:
generation = self._event_generation
return self._event_idle.wait_for(
- lambda: self._event_pending_by_generation.get(generation, 0) == 0, timeout=timeout,
- )
+ lambda: self._event_pending_by_generation.get(generation, 0) == 0, timeout=timeout)
def _dispatch_event(self, event: str, payload: Dict[str, Any]) -> int:
"""Queue *event* without blocking; return the subscriber count scheduled. Pending work is
@@ -342,8 +335,7 @@ class PluginDispatchMixin:
if depth >= _EVENT_EMIT_DEPTH_CAP:
logger.warning(
"Event bus recursion cap (%d) exceeded while dispatching '%s' "
- "— dropping this emit to prevent an infinite loop", _EVENT_EMIT_DEPTH_CAP, event,
- )
+ "— dropping this emit to prevent an infinite loop", _EVENT_EMIT_DEPTH_CAP, event)
return 0
budget_msg = "Event bus pending budget (%d) exhausted while dispatching '%s' — dropping this emit"
with self._event_lock:
@@ -357,8 +349,7 @@ class PluginDispatchMixin:
return 0
item = _QueuedPluginEvent(
event=event, payload=dict(payload), subscriptions=subscriptions, depth=depth + 1,
- generation=generation,
- )
+ generation=generation)
try:
self._event_queue.put_nowait(item)
except queue.Full:
@@ -387,8 +378,7 @@ class PluginDispatchMixin:
if len(rendered) >= MAX_SYSTEM_PROMPT_SECTIONS:
logger.warning(
"Plugin system prompt section %s exceeded the section-count "
- "budget (%d) and was skipped", section.id, MAX_SYSTEM_PROMPT_SECTIONS,
- )
+ "budget (%d) and was skipped", section.id, MAX_SYSTEM_PROMPT_SECTIONS)
continue
text = self._render_prompt_section_text(section, frozen_info)
if text is None:
@@ -400,19 +390,15 @@ class PluginDispatchMixin:
logger.warning(
"Plugin system prompt section %s (%s) exceeded the aggregate "
"session budget (%d chars) and was skipped", section.id, section.plugin,
- MAX_SYSTEM_PROMPT_SECTIONS_TOTAL_CHARS,
- )
+ MAX_SYSTEM_PROMPT_SECTIONS_TOTAL_CHARS)
continue
rendered.append(
RenderedPluginSystemPromptSection(
- id=section.id, content=text, position=section.position, plugin=section.plugin,
- )
- )
+ id=section.id, content=text, position=section.position, plugin=section.plugin))
total_chars += rendered_chars
logger.info(
"Session plugin prompt section: id=%s plugin=%s position=%s chars=%d", section.id,
- section.plugin, section.position, len(text),
- )
+ section.plugin, section.position, len(text))
return rendered
@staticmethod
@@ -422,8 +408,7 @@ class PluginDispatchMixin:
"""Evaluate one section; return its stripped text or None (with a warning) when skipped."""
def _skip(detail: str, *args: Any) -> None:
logger.warning(
- "Plugin system prompt section %s (%s) " + detail, section.id, section.plugin, *args,
- )
+ "Plugin system prompt section %s (%s) " + detail, section.id, section.plugin, *args)
try:
value = section.content(frozen_info) if callable(section.content) else section.content
@@ -458,6 +443,5 @@ class PluginDispatchMixin:
results.append(ret)
except Exception as exc:
logger.warning(
- "Middleware '%s' callback %s raised: %s", kind, getattr(cb, "__name__", repr(cb)), exc,
- )
+ "Middleware '%s' callback %s raised: %s", kind, getattr(cb, "__name__", repr(cb)), exc)
return results