diff --git a/openshell/__init__.py b/openshell/__init__.py index c00a8b8..f4c97d3 100644 --- a/openshell/__init__.py +++ b/openshell/__init__.py @@ -11,9 +11,10 @@ def register(ctx): - from . import busybox_env, launcher_cli, loopback_env, sandbox_hook + from . import busybox_env, launcher_cli, loopback_env, relay_receipts, sandbox_hook loopback_env.apply() ctx.register_terminal_environment_provider(busybox_env.BusyboxProvider()) launcher_cli.register(ctx) sandbox_hook.register(ctx) + relay_receipts.register(ctx) diff --git a/openshell/docs/development.md b/openshell/docs/development.md index d8bfecf..2b6a70f 100644 --- a/openshell/docs/development.md +++ b/openshell/docs/development.md @@ -11,6 +11,7 @@ the pinned OpenShell builds are changed. | `launcher_cli.py` | The `hermes sandbox` commands | | `launcher/` | The host launcher: the switch, the proxy, the drivers, the gateway, cards, keys and sign-ins, the review at switch-off, the activity log | | `sandbox_hook.py`, `inside/` | What runs inside the sandbox: the tool-result hook and the start-up step | +| `relay_receipts.py` | Optional model-response receipts in Relay traces | | `busybox_env.py`, `loopback_env.py` | Windows only: the busybox terminal backend and the loopback names | | `desktop/plugin.js` | The desktop half: the Sandbox page | | `dashboard/` | The routes the host backend answers for a profile whose sandbox is off | @@ -105,6 +106,7 @@ The plugin needs Hermes core and desktop support for a profile that runs elsewhe | The per-profile backend override (`host.setProfileBackend` and `host.clearProfileBackend`) | The desktop app | | The `access` and `network` kinds on approval cards | The desktop app | | On Linux: `security.fake_ip_ranges` and `terminal.env_passthrough` read from the managed scope | Hermes core. See [Programs inside the sandbox](inside-the-sandbox.md#linux-web-tools-and-execute_code). | +| Optional Relay receipts: the `llm_http_response` observer hook | Hermes core; in-process plugins only | How to get a Hermes build that has them is in [Install](install.md#get-a-hermes-build-with-sandbox-support). diff --git a/openshell/docs/security.md b/openshell/docs/security.md index 9cd5829..d9f20a9 100644 --- a/openshell/docs/security.md +++ b/openshell/docs/security.md @@ -103,6 +103,32 @@ See [Set up Windows](setup-windows.md#use-a-copy-of-your-own). ## Telemetry +### Relay response receipts + +To link native model calls to OpenShell's HTTP records, enable receipts in the profile's +`config.yaml`: + +```yaml +plugins: + enabled: [openshell] + entries: + openshell: + settings: + relay_receipts: true +``` + +Requires Hermes's `llm_http_response` hook and a compatible Relay build. The version bundled +with Hermes may not yet have the required APIs; the plugin warns and skips capture if they +are missing. This works inside the sandbox with in-process plugins, not plugin-host isolation. + +Receipts contain only the request ID and HTTP status, not other headers, bodies, prompts or +credentials. Use Relay's `full` or `openinference` export mode to retain them. The plugin does +not configure exporters or open network destinations. + +A receipt means response headers arrived, not that a stream completed or a policy allowed +the request. It is not an authorization token. Tool-subprocess requests are not covered. +Capture is off by default; a recording failure does not change the model request's result. + ### OpenShell's usage telemetry is off OpenShell sends anonymous usage counts to NVIDIA unless it is told not to. diff --git a/openshell/relay_receipts.py b/openshell/relay_receipts.py new file mode 100644 index 0000000..d315b39 --- /dev/null +++ b/openshell/relay_receipts.py @@ -0,0 +1,45 @@ +"""Optional OpenShell receipts under the active Relay model call.""" + +from __future__ import annotations + +from functools import partial +import logging +from uuid import UUID + +from .sandbox_hook import active + +log = logging.getLogger("openshell.relay_receipts") + + +def register(ctx) -> None: + if not active() or ctx.get_config("relay_receipts", False) is not True: + return + try: + import nemo_relay + except ImportError: + log.warning("OpenShell Relay receipts require NeMo Relay with active-scope and mark APIs") + return + required = ("scope_stack_active", "capture_propagation_context", "fork_scope_stack", "use_scope_stack") + if not all(callable(getattr(nemo_relay, name, None)) for name in required) or not callable( + getattr(getattr(nemo_relay, "scope", None), "event", None) + ): + log.warning("OpenShell Relay receipts require NeMo Relay with active-scope and mark APIs") + return + ctx.register_hook("llm_http_response", partial(_record_receipt, nemo_relay)) + + +def _record_receipt(relay, *, status_code: int, get_header, **_) -> None: + try: + request_id = get_header("x-openshell-request-id") + if type(status_code) is not int or not 100 <= status_code <= 599: + return + if not isinstance(request_id, str) or len(request_id) != 36 or str(UUID(request_id)) != request_id: + return + if not relay.scope_stack_active() or not relay.capture_propagation_context().traceparent: + return + # Managed calls carry an active event outside the lexical scope stack. + with relay.use_scope_stack(relay.fork_scope_stack()): + relay.scope.event("openshell.request.receipt", data={"request_id": request_id, "http_status": status_code}) + except Exception: + # Observability must not change the model request's outcome. + return diff --git a/openshell/tests/test_relay_receipts.py b/openshell/tests/test_relay_receipts.py new file mode 100644 index 0000000..965d4e9 --- /dev/null +++ b/openshell/tests/test_relay_receipts.py @@ -0,0 +1,132 @@ +"""The plugin selects receipt metadata without owning a model HTTP client.""" + +from __future__ import annotations + +import asyncio +import builtins +import sys +from types import SimpleNamespace + +import pytest + +from openshell import relay_receipts + +RECEIPT = "7d2ef4cb-fcae-45fd-9880-deef74880df5" + + +class Context: + def __init__(self, enabled=True): + self.enabled = enabled + self.hooks = {} + + def get_config(self, key, default=None): + return self.enabled if key == "relay_receipts" else default + + def register_hook(self, name, callback): + self.hooks[name] = callback + + +@pytest.mark.parametrize("inside,enabled", [(False, True), (True, False), (True, "true")]) +def test_disabled_receipts_do_not_import_relay(monkeypatch, inside, enabled): + monkeypatch.setattr(relay_receipts, "active", lambda: inside) + original = builtins.__import__ + + def importing(name, *args, **kwargs): + assert name != "nemo_relay", "disabled receipts must not import Relay" + return original(name, *args, **kwargs) + + monkeypatch.setattr(builtins, "__import__", importing) + ctx = Context(enabled) + relay_receipts.register(ctx) + assert not ctx.hooks + + +@pytest.mark.parametrize("module", [None, SimpleNamespace(scope=SimpleNamespace(event=lambda: None))]) +def test_missing_or_incompatible_relay_warns_without_registering(monkeypatch, caplog, module): + monkeypatch.setattr(relay_receipts, "active", lambda: True) + monkeypatch.setitem(sys.modules, "nemo_relay", module) + ctx = Context() + relay_receipts.register(ctx) + assert not ctx.hooks + assert "require NeMo Relay with active-scope and mark APIs" in caplog.text + + +@pytest.fixture +def observer(monkeypatch, tmp_path): + monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "config")) + import nemo_relay + + monkeypatch.setitem(sys.modules, "nemo_relay.integrations.openshell", None) + monkeypatch.setattr(relay_receipts, "active", lambda: True) + ctx, events = Context(), [] + relay_receipts.register(ctx) + nemo_relay.subscribers.register("openshell.receipt-test", events.append) + try: + yield nemo_relay, ctx.hooks["llm_http_response"], events + finally: + nemo_relay.subscribers.flush() + nemo_relay.subscribers.deregister("openshell.receipt-test") + + +def run_model(relay, callback): + def provider(request): + callback() + return {"ok": True} + + async def execute(): + return await relay.llm.execute("model", relay.LLMRequest({}, {}), provider) + + with relay.use_scope_stack(relay.create_scope_stack()): + with relay.scope.scope("agent", relay.ScopeType.Agent): + return asyncio.run(execute()) + + +def test_receipt_uses_real_model_parent_and_only_requests_one_header(observer): + relay, observe, events = observer + requested = [] + + def header(name): + requested.append(name) + return RECEIPT + + run_model(relay, lambda: observe(status_code=403, get_header=header)) + relay.subscribers.flush() + mark, = [event for event in events if event.name == "openshell.request.receipt"] + model = next(event for event in events if event.name == "model" and event.scope_category == "start") + assert mark.parent_uuid == model.uuid + assert mark.data == {"request_id": RECEIPT, "http_status": 403} + assert requested == ["x-openshell-request-id"] + + +def test_invalid_receipts_do_not_change_model_result(observer): + relay, observe, events = observer + + def report_invalid_receipts(): + for value, status in [(None, 200), ("bad-id", 200), (RECEIPT.upper(), 200), + (RECEIPT, 99), (RECEIPT, True)]: + observe(status_code=status, get_header=lambda name: value) + + assert run_model(relay, report_invalid_receipts) == {"ok": True} + relay.subscribers.flush() + assert not [event for event in events if event.name == "openshell.request.receipt"] + assert any(event.name == "model" and event.scope_category == "end" for event in events) + + +def test_recording_failure_does_not_change_model_result(observer, monkeypatch): + relay, observe, events = observer + + def unavailable(*args, **kwargs): + raise RuntimeError("observer unavailable") + + monkeypatch.setattr(relay.scope, "event", unavailable) + assert run_model(relay, lambda: observe(status_code=200, get_header=lambda name: RECEIPT)) == {"ok": True} + relay.subscribers.flush() + assert not [event for event in events if event.name == "openshell.request.receipt"] + + +def test_no_active_context_does_not_create_a_relay_trace(observer): + relay, observe, events = observer + assert not relay.scope_stack_active() + observe(status_code=200, get_header=lambda name: RECEIPT) + relay.subscribers.flush() + assert not events