The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
chore(relay): scope 0.9 upgrade to compatibility changes
Alex Fournierc70630732f0c
diff --git a/agent/relay_llm.py b/agent/relay_llm.pyindex 06fbeaf4449..71586844b1b 100644--- a/agent/relay_llm.py+++ b/agent/relay_llm.py@@ -695,13 +695,24 @@ def _complete_logical(output.update({"model": model_name, "provider": provider_name})if response_model_name is not None:output["response_model"] = response_model_name- relay_runtime.SESSION_COORDINATOR.complete_logical_call(- turn,- request_id=request_id,- handle=handle,- output=output,- operation_lease=operation_lease,- )+ with turn.finalize_lock:+ with turn.logical_llm_lock:+ if turn.logical_llm_calls.get(request_id) is not handle:+ return+ if lease.session is None:+ return+ try:+ (operation_lease or lease.host).run_in_session(+ lease.session, relay_runtime.pop_relay_scope, lease.host.relay, handle,+ output=output, metadata=relay_runtime.runtime_metadata(lease.host.runtime_id),+ )+ except Exception:+ # Provider result is authoritative; retain the handle so turn finalization can retry.+ logger.warning("Hermes Relay logical LLM finalization failed", exc_info=True)+ return+ with turn.logical_llm_lock:+ if turn.logical_llm_calls.get(request_id) is handle:+ del turn.logical_llm_calls[request_id]def _is_cancellation(error: BaseException) -> bool:diff --git a/agent/relay_runtime.py b/agent/relay_runtime.pyindex df2f3252c23..580ecb8f647 100644--- a/agent/relay_runtime.py+++ b/agent/relay_runtime.py@@ -815,7 +815,6 @@ class RelayTurnContext:task_id: strhandle: Any = Nonelogical_llm_calls: dict[str, Any] = field(default_factory=dict, repr=False)- logical_llm_outputs: dict[str, dict[str, Any]] = field(default_factory=dict, repr=False)logical_llm_lock: threading.RLock = field(default_factory=threading.RLock, repr=False)finalize_lock: threading.RLock = field(default_factory=threading.RLock, repr=False)_previous_turn: RelayTurnContext | None = field(default=None, repr=False)@@ -1071,86 +1070,30 @@ class RelaySessionCoordinator:if not turn.closed:self._finish_logical_calls(turn, outcome=outcome)- def complete_logical_call(- self,- turn: RelayTurnContext,- *,- request_id: str,- handle: Any,- output: dict[str, Any],- operation_lease: RelayOperationLease | None = None,- ) -> None:- """Close completed logical calls once they reach the Relay stack top."""- with turn.finalize_lock:- with turn.logical_llm_lock:- if turn.logical_llm_calls.get(request_id) is not handle:- return- turn.logical_llm_outputs[request_id] = dict(output)- self._drain_completed_logical_calls(- turn,- operation_lease=operation_lease,- )-- def _finish_logical_calls(self, turn: RelayTurnContext, *, outcome: str) -> None:- with turn.logical_llm_lock:- for request_id in turn.logical_llm_calls:- turn.logical_llm_outputs.setdefault(- request_id,- {"outcome": outcome},- )- self._drain_completed_logical_calls(turn, allow_orphan_drain=True)-@staticmethod- def _drain_completed_logical_calls(- turn: RelayTurnContext,- *,- operation_lease: RelayOperationLease | None = None,- allow_orphan_drain: bool = False,- ) -> None:+ def _finish_logical_calls(turn: RelayTurnContext, *, outcome: str) -> None:lease = turn.leasehost = lease.live_runtime()- session = lease.session- if host is None or session is None:+ if host is None:return- while True:- with turn.logical_llm_lock:- if not turn.logical_llm_calls:- turn.logical_llm_outputs.clear()- return- request_id = next(reversed(turn.logical_llm_calls))- output = turn.logical_llm_outputs.get(request_id)- if output is None:- return- logical_handle = turn.logical_llm_calls[request_id]- if allow_orphan_drain:- failure = host._close_scope_handle(- session,- logical_handle,- output=output,- failure_label="logical LLM scope close failed",- )- if failure is not None:- logger.warning("Hermes Relay logical LLM finalization failed: %s", failure)- return- else:- try:- (operation_lease or host).run_in_session(- session,- pop_relay_scope,- host.relay,- logical_handle,- output=output,- metadata=runtime_metadata(host.runtime_id),- )- except Exception:- # Provider results are authoritative. Retain the completion- # so turn finalization can retry without changing the result.- logger.warning("Hermes Relay logical LLM finalization failed", exc_info=True)- return+ with turn.logical_llm_lock:+ logical_calls = list(turn.logical_llm_calls.items())+ turn.logical_llm_calls.clear()+ while logical_calls:+ _request_id, logical_handle = logical_calls[-1]+ failure = host._close_scope_handle(+ lease.session, logical_handle, output={"outcome": outcome},+ failure_label="logical LLM scope close failed",+ )+ if failure is None:+ logical_calls.pop()+ continuewith turn.logical_llm_lock:- if turn.logical_llm_calls.get(request_id) is logical_handle:- del turn.logical_llm_calls[request_id]- turn.logical_llm_outputs.pop(request_id, None)+ # Stack-owned: if the newest handle cannot close even after drain, older ones cannot either.+ for pending_request_id, pending_handle in logical_calls:+ turn.logical_llm_calls.setdefault(pending_request_id, pending_handle)+ logger.warning("Hermes Relay logical LLM finalization failed: %s", failure)+ break@staticmethoddef _reset_turn_context(turn: RelayTurnContext) -> None:diff --git a/hermes_cli/relay_plugin_migrate.py b/hermes_cli/relay_plugin_migrate.pyindex 33a5b28411c..f50834ac474 100644--- a/hermes_cli/relay_plugin_migrate.py+++ b/hermes_cli/relay_plugin_migrate.py@@ -14,7 +14,6 @@ from __future__ import annotationsimport loggingfrom dataclasses import dataclass, fieldfrom pathlib import Path-from tempfile import TemporaryDirectoryfrom typing import Any, Mapping, Optionalfrom hermes_cli.relay_plugin_cutover import (@@ -126,33 +125,15 @@ def dumps_toml(document: Mapping[str, Any]) -> str:def validate_relay_plugin_payload(payload: Mapping[str, Any]) -> list:- """Validate the serialized payload through the same file layering the runtime uses.-- Returns warnings (empty = clean) and raises when Relay rejects the document,- including by error-level diagnostics or a failed dynamic plugin that Relay- did not select for activation.- """+ """Run the payload through Relay's own validator; returns the warnings (empty = clean).+ Raises when Relay rejects the document, including by error-level diagnostics."""from nemo_relay import plugin- with TemporaryDirectory(prefix="hermes-relay-validation-") as directory:- config_path = Path(directory) / RELAY_PLUGINS_TOML_NAME- config_path.write_text(dumps_toml(payload), encoding="utf-8")- report = plugin.validate({}, additional_plugins_toml=config_path)- diagnostics = list(report["config"]["diagnostics"])+ # validate() would layer the payload over the ambient user config; the runtime never does.+ diagnostics = list(plugin.validate_exact(dict(payload))["config"]["diagnostics"])# Relay 0.8's initialize() raised on these; 0.9's validator only reports them.- errors = [str(d.get("message") or d.get("code") or d) for d in diagnostics if d.get("level") == "error"]- for dynamic in report["dynamic_plugins"]:- failure = dynamic.get("failure")- # Optional trust failures remain selected in Relay 0.9. Required failures are deselected- # and initialize() rejects them; any failed, unselected requested plugin is unsafe to migrate.- if failure is None or dynamic.get("selected") is not False:- continue- plugin_id = str(dynamic.get("plugin_id") or dynamic.get("manifest_ref") or "unknown")- code = str(failure.get("code") or "validation_failed")- message = str(failure.get("message") or code)- errors.append(f"dynamic plugin {plugin_id!r} ({code}): {message}")- if errors:- raise ValueError("; ".join(errors))+ if errors := [d for d in diagnostics if d.get("level") == "error"]:+ raise ValueError("; ".join(str(d.get("message") or d.get("code") or d) for d in errors))return diagnosticsdiff --git a/pyproject.toml b/pyproject.tomlindex 2eb56a84982..8b6e9e13dd9 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -175,7 +175,7 @@ dependencies = [# Hence the ``sys_platform == 'win32'`` marker: the dep (and its portalocker# / pywin32 tree) ships only where it's actually used."concurrent-log-handler==0.9.29; sys_platform == 'win32'",- # First-party lifecycle and shared-metrics runtime. Relay 0.8 is the supported+ # First-party lifecycle and shared-metrics runtime. Relay 0.9 is the supported# native runtime and provider-codec baseline. Managed calls pass request and# response data through this native module in-process; shared metrics installs# no network exporter and consumes only its bounded projection. This markerdiff --git a/tests/hermes_cli/test_relay_plugin_migrate.py b/tests/hermes_cli/test_relay_plugin_migrate.pyindex 8ec682d693d..7ed96bf937e 100644--- a/tests/hermes_cli/test_relay_plugin_migrate.py+++ b/tests/hermes_cli/test_relay_plugin_migrate.py@@ -57,8 +57,8 @@ def test_legacy_env_becomes_validated_toml_selected_from_env(profile_env):sink = document["components"][0]["config"]["atof"]["sinks"][0]assert sink["type"] == "file" and sink["filename"] == "hermes-atof.jsonl"assert document["components"][0]["config"]["atif"]["filename_template"] == "trajectory-{session_id}.json"- # Relay itself accepts the file Hermes will load at runtime.- report = nemo_relay.plugin.validate({}, additional_plugins_toml=toml_path)+ # Relay accepts the complete document generated from the legacy settings.+ report = nemo_relay.plugin.validate_exact(document)assert report["config"]["diagnostics"] == []# .env now selects the file; the legacy lines survive as comments (not deleted), so the# runtime warning + doctor finding go quiet and a second run is a no-op.@@ -89,19 +89,15 @@ def test_update_migrates_every_profile_home_separately(profile_env):assert (idle / ".env").read_text(encoding="utf-8") == "SLACK_BOT_TOKEN=y\n"-def _relay_report(*diagnostics, dynamic_plugins=None):- return {- "config": {"diagnostics": list(diagnostics)},- "config_paths": [],- "dynamic_plugins": list(dynamic_plugins or []),- }+def _relay_report(*diagnostics):+ return {"config": {"diagnostics": list(diagnostics)}, "config_paths": [], "dynamic_plugins": []}def test_error_diagnostics_reject_the_payload_like_relay_0_8_did(monkeypatch):monkeypatch.setattr(nemo_relay.plugin,- "validate",- lambda _payload, additional_plugins_toml=None: _relay_report(+ "validate_exact",+ lambda _payload: _relay_report({"level": "warning", "code": "unknown_field", "message": "unknown field 'x'"},{"level": "error", "code": "unsupported_value", "message": "atof.mode 'nope' is unsupported"},),@@ -113,95 +109,9 @@ def test_error_diagnostics_reject_the_payload_like_relay_0_8_did(monkeypatch):def test_warning_diagnostics_are_returned_not_raised(monkeypatch):warning = {"level": "warning", "code": "unknown_field", "message": "unknown field 'x'"}- observed = {}-- def validate(payload, additional_plugins_toml=None):- observed["payload"] = payload- observed["document"] = tomllib.loads(- Path(additional_plugins_toml).read_text(encoding="utf-8")- )- return _relay_report(warning)-- monkeypatch.setattr(nemo_relay.plugin, "validate", validate)+ monkeypatch.setattr(nemo_relay.plugin, "validate_exact", lambda _payload: _relay_report(warning))assert validate_relay_plugin_payload({"version": 1}) == [warning]- assert observed == {"payload": {}, "document": {"version": 1}}---def test_selected_optional_dynamic_plugin_failure_is_not_rejected(monkeypatch):- monkeypatch.setattr(- nemo_relay.plugin,- "validate",- lambda _payload, additional_plugins_toml=None: _relay_report(- dynamic_plugins=[{- "plugin_id": "fixture.optional",- "selected": True,- "failure": {- "phase": "validation",- "code": "integrity_failed",- "message": "failed optional integrity verification",- },- }]- ),- )-- assert validate_relay_plugin_payload({"version": 1}) == []---def test_real_relay_dynamic_plugin_failure_leaves_env_untouched(profile_env, monkeypatch):- (profile_env / ".env").write_text(LEGACY_ENV.format(home=profile_env), encoding="utf-8")- before = (profile_env / ".env").read_text(encoding="utf-8")- artifact = profile_env / "artifact.bin"- artifact.write_bytes(b"dynamic plugin trust fixture")- manifest = profile_env / "relay-plugin-manifest.toml"- manifest.write_text(- f'''manifest_version = 1--[plugin]-id = "fixture.required"-kind = "worker"--[compat]-relay = ">=0.9.0,<0.10"-worker_protocol = "grpc-v1"--[defaults]-enabled = false--[capabilities]-items = ["plugin_worker"]--[source]-artifact = "{artifact}"--[integrity]-sha256 = "sha256:{'0' * 64}"--[load]-runtime = "command"-entrypoint = "fixture-worker"-''',- encoding="utf-8",- )- payload = {- "version": 1,- "plugins": {- "policy": {"defaults": {"startup": "required", "attestation": "integrity_only"}},- "dynamic": [{"manifest": str(manifest)}],- },- }- monkeypatch.setattr(- "hermes_cli.relay_plugin_migrate.relay_plugin_payload_from_legacy_env",- lambda _env: payload,- )-- result = migrate_profile_relay_env(profile_env)-- assert not result.migrated- assert "dynamic plugin 'fixture.required' (integrity_failed)" in result.validation_error- assert "failed integrity verification" in result.validation_error- assert (profile_env / ".env").read_text(encoding="utf-8") == before- assert not (profile_env / RELAY_PLUGINS_TOML_NAME).exists()def test_error_diagnostics_leave_env_untouched(profile_env, monkeypatch):@@ -209,10 +119,8 @@ def test_error_diagnostics_leave_env_untouched(profile_env, monkeypatch):before = (profile_env / ".env").read_text(encoding="utf-8")monkeypatch.setattr(nemo_relay.plugin,- "validate",- lambda _payload, additional_plugins_toml=None: _relay_report(- {"level": "error", "code": "bad", "message": "rejected"}- ),+ "validate_exact",+ lambda _payload: _relay_report({"level": "error", "code": "bad", "message": "rejected"}),)result = migrate_profile_relay_env(profile_env)diff --git a/tests/hermes_cli/test_relay_shared_metrics_runtime.py b/tests/hermes_cli/test_relay_shared_metrics_runtime.pyindex ee46ae3f3be..1af1455bf34 100644--- a/tests/hermes_cli/test_relay_shared_metrics_runtime.py+++ b/tests/hermes_cli/test_relay_shared_metrics_runtime.py@@ -1317,71 +1317,6 @@ def test_direct_runtime_fake_enforces_lifo_scope_contract(direct_runtime):runtime.run_in_session(session, direct_runtime.scope.pop, first)-def test_completed_logical_calls_close_in_stack_order(direct_runtime):- coordinator = relay_runtime.SESSION_COORDINATOR- profile_key = relay_runtime.current_profile_key()- lease = coordinator.acquire_conversation(- profile_key=profile_key,- session_id="logical-completion-order",- platform="cli",- )- turn = coordinator.begin_turn(- lease,- turn_id="turn",- task_id="task",- )- runtime = lease.live_runtime()- assert runtime is not None-- handles = []- for request_id in ("request-1", "request-2"):- handle = runtime.run_in_session(- lease.session,- direct_runtime.scope.push,- relay_runtime.LOGICAL_LLM_SCOPE,- direct_runtime.ScopeType.Function,- handle=turn.handle,- input={},- )- turn.logical_llm_calls[request_id] = handle- handles.append(handle)-- coordinator.complete_logical_call(- turn,- request_id="request-1",- handle=handles[0],- output={"outcome": "success", "model": "auxiliary"},- )- assert list(turn.logical_llm_calls) == ["request-1", "request-2"]- assert not [event for event in direct_runtime.events if event[0] == "scope.pop.rejected"]-- coordinator.complete_logical_call(- turn,- request_id="request-2",- handle=handles[1],- output={"outcome": "failed", "model": "primary"},- )- assert turn.logical_llm_calls == {}- assert turn.logical_llm_outputs == {}- logical_pops = [- event- for event in direct_runtime.events- if event[0] == "scope.pop" and event[1] in handles- ]- assert [event[1] for event in logical_pops] == list(reversed(handles))- assert [event[2]["output"] for event in logical_pops] == [- {"outcome": "failed", "model": "primary"},- {"outcome": "success", "model": "auxiliary"},- ]-- coordinator.end_turn(turn, outcome="success")- coordinator.release_conversation(lease)- coordinator.finalize_conversation(- profile_key=profile_key,- session_id="logical-completion-order",- )--def test_close_session_drains_orphaned_scopes_before_session_pop(direct_runtime):"""Orphaned physical scopes must not permanently wedge session close (#81521)."""runtime = relay_runtime.get_runtime()diff --git a/uv.lock b/uv.lockindex 1af3581e5db..8598fc0afbe 100644--- a/uv.lock+++ b/uv.lock@@ -8,7 +8,7 @@ resolution-markers = [][options]-exclude-newer = "2026-09-04T17:51:26.683963Z"+exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values.exclude-newer-span = "P14D"[options.exclude-newer-package]@@ -4283,7 +4283,7 @@ resolution-markers = ["python_full_version < '3.12'",]dependencies = [- { name = "numpy", marker = "python_full_version < '3.12'" },+ { name = "numpy" },]sdist = { url = "https://files.pythonhosted.org/packages/7a/97/5a3609c4f8d58b039179648e62dd220f89864f56f7357f5d4f45c29eb2cc/scipy-1.17.1.tar.gz", hash = "sha256:95d8e012d8cb8816c226aef832200b1d45109ed4464303e997c5b13122b297c0", size = 30573822, upload-time = "2026-02-23T00:26:24.851Z" }wheels = [@@ -4338,7 +4338,7 @@ resolution-markers = ["python_full_version == '3.12.*'",]dependencies = [- { name = "numpy", marker = "python_full_version >= '3.12'" },+ { name = "numpy" },]sdist = { url = "https://files.pythonhosted.org/packages/a7/25/c2700dfaf6442b4effaa91af24ebce5dc9d31bb4a69706313aae70d72cd0/scipy-1.18.0.tar.gz", hash = "sha256:67b2ad2ad54c72ca6d04975a9b2df8c3638c34ddd5b28738e94fc2b57929d378", size = 30774447, upload-time = "2026-06-19T15:01:43.456Z" }wheels = [@@ -4975,11 +4975,11 @@ name = "vercel-workers"version = "0.0.25"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "anyio", marker = "python_full_version >= '3.12'" },- { name = "httpx", marker = "python_full_version >= '3.12'" },- { name = "pydantic", marker = "python_full_version >= '3.12'" },- { name = "python-dotenv", marker = "python_full_version >= '3.12'" },- { name = "vercel", marker = "python_full_version >= '3.12'" },+ { name = "anyio" },+ { name = "httpx" },+ { name = "pydantic" },+ { name = "python-dotenv" },+ { name = "vercel" },]sdist = { url = "https://files.pythonhosted.org/packages/30/df/04d37021ad7ca53b7599c313e411d91623c7a005c741f491d1eefb7a9f0c/vercel_workers-0.0.25.tar.gz", hash = "sha256:212ded01400b524be51d251df49f801caf115ad7d48cca7eb168cbeceda3def3", size = 64149, upload-time = "2026-06-20T19:26:27.177Z" }wheels = [