The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge branch 'simp/r3-33' into simp/integration3
Teknium0d336d055ac8
diff --cc tools/registry.pyindex dadd0deb4a7,1bca3621d9f..0d402d308ee--- a/tools/registry.py+++ b/tools/registry.py@@@ -1,11 -1,7 +1,9 @@@- """Central registry for all hermes-agent tools.-- Each tool file calls ``registry.register()`` at module level to declare its schema,- handler, toolset membership, and availability check; ``model_tools.py`` queries the- registry instead of keeping parallel data structures. Import chain (cycle-safe):- tools/registry.py imports nothing from model_tools or tool files; tools/*.py import- tools.registry at module level; model_tools.py imports both; run_agent/cli import that.- """+ """Central registry for all hermes-agent tools: each tool file calls ``registry.register()``-at import to declare schema, handler, toolset and availability check; ``model_tools.py``-queries it. Cycle-safe chain: this module imports nothing from model_tools or tool files;-tools/*.py import it; model_tools.py imports both; run_agent/cli import model_tools."""++at import to declare schema, handler, toolset membership and availability check;++``model_tools.py`` queries the registry instead of keeping parallel data structures.++Cycle-safe import chain: this module imports nothing from model_tools or tool files;++tools/*.py import it at module level; model_tools.py imports both; run_agent/cli import++model_tools."""import astimport functools@@@ -255,19 -240,14 +242,15 @@@ def _prune_check_fn_caches(now: float)def check_fn_cache_scope() -> Optional[str]:- """Return the active profile key when availability is profile-scoped.-- Browser-controller availability is request-bound (changes on every attach/detach), so a- fully bound browser-control request bypasses this cache AND model_tools' outer definition- cache (same sentinel) — one Browser session's live tools must not leak into another.- Single-profile processes keep the process-wide cache; a multiplex gateway installs a- Hermes-home override per profile turn, so the canonical profile key is the boundary.- """+ """Return the active profile key when availability is profile-scoped. Browser-controller+ availability is request-bound (changes on every attach/detach), so a fully bound+ browser-control request bypasses this cache AND model_tools' outer definition cache (same- sentinel) — one Browser session's live tools must not leak into another. A multiplex- gateway installs a Hermes-home override per profile turn, so that key is the boundary."""++ sentinel) — one Browser session's live tools must not leak into another. Single-profile++ processes keep the process-wide cache; a multiplex gateway installs a Hermes-home override++ per profile turn, so the canonical profile key is the boundary."""try:from gateway.session_context import get_session_env-- browser_identity = tuple(get_session_env(key, "") for key in _BROWSER_IDENTITY_KEYS)- if all(str(value or "").strip() for value in browser_identity):+ if all(str(get_session_env(k, "") or "").strip() for k in _BROWSER_IDENTITY_KEYS):return CHECK_FN_CACHE_BYPASSexcept Exception:pass@@@ -295,9 -271,8 +274,9 @@@ def _run_check_fn_uncached(fn: Callablereturn bool(fn())except UnscopedSecretError:if unresolved_scope:- # Expected fail-closed probe: with multiplexing on, boot-time check_fns run- # before any profile secret scope exists, so get_secret raises by design.- # No traceback so this cannot be mistaken for a crashed check_fn.- # Expected fail-closed probe: boot-time check_fns run before any multiplex profile- # secret scope exists. No traceback, so it isn't mistaken for a crashed check_fn.++ # Expected fail-closed probe: with multiplexing on, boot-time check_fns run before++ # any profile secret scope exists, so get_secret raises by design. No traceback,++ # so it isn't mistaken for a crashed check_fn.logger.debug("check_fn %s hit the multiplex fail-closed path with no ""profile secret scope active; dependent tools re-probe on the first scoped turn",@@@ -355,8 -324,7 +328,8 @@@ def _check_fn_cached(fn: Callable) -> b_fn_label(fn), outcome, _CHECK_FN_FAILURE_GRACE_SECONDS)return True- # No recent success (or grace expired) — honor the failure. Logged so silent- # tool loss in quiet mode (subagents) is diagnosable.- # No recent success — honor the failure; logged so silent tool loss is diagnosable.++ # No recent success (or grace expired) — honor the failure; logged so silent tool++ # loss in quiet mode (subagents) is diagnosable.logger.warning("check_fn %s %s; dependent tools will be unavailable this turn", _fn_label(fn), outcome)_check_fn_cache[cache_key] = (now, False)@@@ -413,9 -379,16 +384,16 @@@ class ToolRegistry@staticmethoddef current_scope_key() -> str:- """Return the active profile's canonical registry scope."""return hermes_home_key()+ @staticmethod- def _grouped(entries) -> Dict[str, List[ToolEntry]]:++ def _grouped(entries: List[ToolEntry]) -> Dict[str, List[ToolEntry]]:+ """``{toolset: entries}`` in first-appearance order."""+ groups: Dict[str, List[ToolEntry]] = {}+ for entry in entries:+ groups.setdefault(entry.toolset, []).append(entry)+ return groups+def _slot(self, scope: Optional[str], *, create: bool = False) -> Dict[str, ToolEntry]:"""The registration map for *scope*: global when None, else that profile's overlay."""if scope is None:@@@ -689,9 -645,8 +650,9 @@@description=description or schema.get("description", ""), emoji=emoji,max_result_size_chars=max_result_size_chars,dynamic_schema_overrides=dynamic_schema_overrides)- # Availability is derived per-tool (_toolset_has_exposable_tools), so this- # map no longer gates a toolset. It still feeds get_toolset_requirements ->- # Availability is derived per-tool, so this map no longer gates a toolset; it still- # feeds TOOLSET_REQUIREMENTS["check_fn"], which banner.py reads (presence only,++ # Availability is derived per-tool (_toolset_has_exposable_tools), so this map no++ # longer gates a toolset; it still feeds get_toolset_requirements ->+ # TOOLSET_REQUIREMENTS["check_fn"], which banner.py reads (presence only,# never called) to classify an unavailable toolset as lazy-init vs disabled.if scope is None and check_fn and toolset not in self._toolset_checks:self._toolset_checks[toolset] = check_fn@@@ -699,14 -654,11 +660,13 @@@def deregister(self, name: str, *, scope: Optional[str] = None) -> None:"""Remove a tool; drops the toolset check/aliases if it was the last in its toolset.- ``scope`` selects a profile overlay explicitly (multiplexed MCP tools live there);- plugin callers may not name another scope, non-plugin callers default to the global- map. Gated by the same opt-in as ``register(override=True)``, else a plugin could- deregister a tool it doesn't own and re-register over the empty slot (the override- check only runs when an entry exists). ``mcp-*`` is exempt — discovery repaves."""++ ``scope`` selects a profile overlay explicitly (multiplexed MCP tools live in the+ owning profile's overlay); plugin callers may not name another scope, non-plugin+ callers default to the process-global map. Gated by the same opt-in as+ ``register(override=True)``, else a plugin could deregister a tool it doesn't own+ and re-register over the empty slot (the override check only runs when an entry- exists). ``mcp-*`` toolsets are exempt — discovery repaves its own tools per refresh.- """++ exists). ``mcp-*`` toolsets are exempt — discovery repaves its own tools per refresh."""with self._lock:caller_mod = self._caller_module()caller_owner = self._plugin_namespace_of_module(caller_mod)@@@ -728,14 -679,11 +687,13 @@@returnif not entry.toolset.startswith("mcp-"):owner = self._plugin_owner_of(entry.handler)- # Ownership binds to the plugin package root (``hermes_plugins.{name}``),- # not the exact module string: a handler defined in a submodule is- # still owned by the package, so root-module cleanup may remove it.+ # Ownership binds to the plugin package root (``hermes_plugins.{name}``), not+ # the exact module: a submodule's handler is still the package's to remove.same_plugin = bool(owner and caller_owner == owner)- if caller_owner is not None and not same_plugin \- and not self._plugin_override_allowed(caller_scope, caller_owner):+ if (+ caller_owner is not None+ and not same_plugin+ and not self._plugin_override_allowed(caller_scope, caller_owner)):logger.error("Tool deregistration REJECTED: plugin %r attempted to ""remove tool %r (toolset %r) it does not own, without operator opt-in. Set "@@@ -837,12 -780,9 +790,11 @@@cannot slice or size."""if isinstance(result, str):return _bound_json_error_result(result)- if isinstance(result, dict) and result.get("_multimodal") is True \- and isinstance(result.get("content"), list):+ if (+ isinstance(result, dict)+ and result.get("_multimodal") is True+ and isinstance(result.get("content"), list)):return result-result_type = type(result).__name__logger.error("Tool %s handler returned unsupported result type: %s", name, result_type)return tool_error(@@@ -917,16 -851,7 +863,8 @@@"""True when a toolset has at least one exposable tool (never raises)."""return self._toolset_has_exposable_tools(toolset, self._snapshot_entries())- @staticmethod- def _grouped(entries: List[ToolEntry]) -> Dict[str, List[ToolEntry]]:- """``{toolset: entries}`` in first-appearance order."""- groups: Dict[str, List[ToolEntry]] = {}- for entry in entries:- groups.setdefault(entry.toolset, []).append(entry)- return groups+def check_toolset_requirements(self) -> Dict[str, bool]:- """Return ``{toolset: available_bool}`` for every toolset."""entries = self._snapshot_entries()return {toolset: self._toolset_has_exposable_tools(toolset, entries)diff --cc tools/schema_sanitizer.pyindex f263e1638e4,39a3d6c937b..b6962e43934--- a/tools/schema_sanitizer.py+++ b/tools/schema_sanitizer.py@@@ -225,46 -210,37 +210,39 @@@ def _const_branch_type(branch: Any) ->def collapse_const_unions(schema: Any) -> Any:- """Collapse ``anyOf``/``oneOf`` unions of same-typed consts to ``enum``.-- Ported from block/goose ``tool_schema_normalize.rs`` (Apache-2.0). Rust/TS-generated- MCP servers emit ``{"anyOf": [{"const": "red"}, {"const": "green"}]}``; strict- backends mishandle these while ``{"type": "string", "enum": [...]}`` is universal.+ """Collapse ``anyOf``/``oneOf`` unions of same-typed consts to ``enum`` (ported from+ block/goose ``tool_schema_normalize.rs``, Apache-2.0). Rust/TS MCP servers emit+ ``{"anyOf": [{"const": "red"}, {"const": "green"}]}``, which strict backends mishandle.Applies only when EVERY non-null branch is a pure ``const`` of one primitive type- (``bool`` never merges with ``integer``). One ``{"type": "null"}`` branch is- tolerated and recorded as ``nullable: true`` (null+multi-const unions land here,- not in ``strip_nullable_unions``). Enum order preserves branch order; outer- metadata is carried over; input is never mutated.- """- if isinstance(schema, list):- return [collapse_const_unions(item) for item in schema]- if not isinstance(schema, dict):- return schema-- out = {k: collapse_const_unions(v) for k, v in schema.items()}- for key in _UNION_KEYS:- variants = out.get(key)- if not isinstance(variants, list) or not variants:- continue- null_branches = [item for item in variants if _is_null_branch(item) and "const" not in item]- const_branches = [item for item in variants if item not in null_branches]- if len(null_branches) > 1 or not const_branches:- continue- branch_types = {_const_branch_type(item) for item in const_branches}- if len(branch_types) != 1 or None in branch_types:- continue- replacement: dict = {- "type": branch_types.pop(), "enum": [item["const"] for item in const_branches]}- if null_branches:- replacement["nullable"] = True- _carry_union_meta(out, replacement, skip_default_on_ref=False)- return replacement- return out+ (``bool`` never merges with ``integer``); one ``{"type": "null"}`` branch is tolerated- and recorded as ``nullable: true``. Branch order is kept; outer metadata carried over;- input never mutated."""++ and recorded as ``nullable: true`` (null+multi-const unions land here, not in++ ``strip_nullable_unions``). Branch order is kept; outer metadata carried over; input++ never mutated."""+ def collapse(out: dict) -> Any:+ for key in _UNION_KEYS:+ variants = out.get(key)+ if not isinstance(variants, list) or not variants:+ continue+ null_branches = [i for i in variants if _is_null_branch(i) and "const" not in i]+ const_branches = [item for item in variants if item not in null_branches]+ if len(null_branches) > 1 or not const_branches:+ continue+ branch_types = {_const_branch_type(item) for item in const_branches}+ if len(branch_types) != 1 or None in branch_types:+ continue+ replacement: dict = {+ "type": branch_types.pop(), "enum": [item["const"] for item in const_branches]}+ if null_branches:+ replacement["nullable"] = True+ _carry_union_meta(out, replacement, skip_default_on_ref=False)+ return replacement+ return out+ return _rewrite(schema, collapse)_BARE_TYPE_NAMES = frozenset({"object", "string", "number", "integer", "boolean", "array", "null"})- # Sibling keywords whose values are NOT schemas: recursing would mistake literal strings- # like "path" for bare-string schemas. Passed through (``required`` follows property renames).-# Keys whose values are NOT schemas (recursing would treat "path" as a bare-string schema).++# Keys whose values are NOT schemas (recursing would treat "path" as a bare-string schema);++# passed through (``required`` follows property renames)._NON_SCHEMA_LIST_KEYS = frozenset({"required", "enum", "examples", "dependentRequired"})