Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
from nemo_fabric_adapters.common import instructions as common_instructions
from nemo_fabric_adapters.common import health as health_transport
from nemo_fabric_adapters.common import lifecycle
from nemo_fabric_adapters.common import relay_version
from nemo_fabric_adapters.common import mcp_availability
from nemo_fabric_adapters.common import relay_artifacts
from nemo_fabric_adapters.common import relay_gateway
Expand Down Expand Up @@ -595,12 +596,17 @@ def prepare_claude_relay(
"base_dir": base_dir,
"config": {"models": {"default": model.to_mapping()}},
"runtime_context": runtime_context.to_mapping(),
}
},
relay_release=contract.version,
)
config_path, plugin_config_path = common_utils.write_relay_configs(
relay_config={"agents": {"claude": {"command": "claude"}}, **http_config},
plugin_config=plugin_config,
)
except relay_version.RelayAtifOptionsUnsupported as error:
raise AdapterRelayError(
"claude_relay_atif_options_unsupported", str(error)
) from error
except RelayHttpModelError as error:
raise AdapterRelayError(
"claude_relay_invalid_http_model_hosts", str(error)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
from nemo_fabric_adapter_contract.models import McpServiceAccountConfig
from nemo_fabric_adapter_contract.models import RuntimeContext
from nemo_fabric_adapters.common import instructions as common_instructions
from nemo_fabric_adapters.common import relay_version
from nemo_fabric_adapters.common import mcp_availability
import nemo_fabric_adapters.common.relay_gateway as relay_gateway
from nemo_fabric_adapters.common.relay_http import (
Expand Down Expand Up @@ -1025,13 +1026,18 @@ def prepare_codex_relay(
"base_dir": base_dir,
"config": config.to_mapping(),
"runtime_context": context.to_mapping(),
}
},
relay_release=contract.version,
)
config_path, plugin_config_path = common_utils.write_relay_configs(
# Codex execution remains SDK-owned; Relay runs only as a gateway.
relay_config=http_config,
plugin_config=plugin_config,
)
except relay_version.RelayAtifOptionsUnsupported as error:
raise AdapterRelayError(
"codex_relay_atif_options_unsupported", str(error)
) from error
except RelayHttpModelError as error:
raise AdapterRelayError(
"codex_relay_invalid_http_model_hosts", str(error)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

from __future__ import annotations

from typing import Any

RELAY_MINIMUM_VERSION = (0, 11, 0)
RELAY_MAXIMUM_VERSION = (0, 12, 0)
RELAY_CLI_MINIMUM_VERSION = (0, 9, 0)
Expand All @@ -19,3 +21,39 @@ def is_supported_relay_version(version: tuple[int, int, int]) -> bool:
def is_supported_relay_cli_version(version: tuple[int, int, int]) -> bool:
"""Check the range of an already parsed stable Relay CLI release."""
return RELAY_CLI_MINIMUM_VERSION <= version < RELAY_CLI_MAXIMUM_VERSION


class RelayAtifOptionsUnsupported(ValueError):
"""The selected Relay release cannot apply ATIF field overrides."""


def validate_atif_options(
version: tuple[int, int, int], plugin_config: dict[str, Any]
) -> None:
"""Prevent older exporters from ignoring explicit ATIF field choices."""
if version >= RELAY_MINIMUM_VERSION:
return
for component in plugin_config.get("components") or []:
if (
not isinstance(component, dict)
or component.get("kind") != "observability"
or component.get("enabled") is False
):
continue
config = component.get("config")
if not isinstance(config, dict):
continue
atif = config.get("atif")
if (
isinstance(atif, dict)
and atif.get("enabled")
and any(
atif.get(field) is not None
for field in ("include_observed_events", "include_llm_requests")
)
):
installed = ".".join(map(str, version))
raise RelayAtifOptionsUnsupported(
"ATIF include_observed_events and include_llm_requests require "
f"NeMo Relay >=0.11.0; the selected release is {installed}"
)
16 changes: 14 additions & 2 deletions adapters/python/common/src/nemo_fabric_adapters/common/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

from nemo_fabric_adapter_contract.codec import JsonValue
from nemo_fabric_adapter_contract.models import RuntimeContext
from nemo_fabric_adapters.common.relay_version import validate_atif_options


_FIELD_NAME = re.compile(r"[!#$%&'*+\-.^_`|~0-9A-Za-z]+")
Expand Down Expand Up @@ -557,7 +558,19 @@ def validate_relay_observability(plugin_config: dict[str, Any]) -> None:
)


def load_relay_plugin_config(payload: dict[str, Any]) -> dict[str, Any]:
def load_relay_plugin_config(
payload: dict[str, Any], *, relay_release: tuple[int, int, int] | None = None
) -> dict[str, Any]:
plugin_config = read_relay_plugin_config()
if relay_release is not None:
validate_atif_options(relay_release, plugin_config)
normalize_relay_output_dirs(plugin_config, payload)
return plugin_config


def read_relay_plugin_config() -> dict[str, Any]:
"""Read the resolved Relay config without preparing output directories."""

config_path = os.environ.get("FABRIC_RELAY_CONFIG_PATH")
if not config_path:
raise RuntimeError("FABRIC_RELAY_CONFIG_PATH is required when Relay is enabled")
Expand All @@ -582,7 +595,6 @@ def load_relay_plugin_config(payload: dict[str, Any]) -> dict[str, Any]:
plugin_config = {"version": 1, "components": components}
plugin_config.setdefault("version", 1)
plugin_config.setdefault("components", [])
normalize_relay_output_dirs(plugin_config, payload)
return plugin_config


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
from nemo_fabric_adapter_contract.models import RuntimeContext
from nemo_fabric_adapters.common import instructions as common_instructions
from nemo_fabric_adapters.hermes import sessions
from nemo_fabric_adapters.common.relay_version import RelayAtifOptionsUnsupported
from nemo_fabric_adapters.common import lifecycle
from nemo_fabric_adapters.common import mcp_availability
from nemo_fabric_adapters.hermes import configuration
Expand Down Expand Up @@ -230,11 +231,22 @@ async def start(self, payload: dict[str, Any]) -> dict[str, Any] | None:
payload.get("runtime_context")
)
telemetry.validate_hermes_telemetry_provider(runtime_context)
relay_enabled = bool(
runtime_context.telemetry and runtime_context.telemetry.relay_enabled
)
if relay_enabled:
relay_release = (
telemetry.validate_hermes_relay_compatibility()
if runtime_context.telemetry and runtime_context.telemetry.relay_enabled
else None
)
relay_enabled = relay_release is not None
relay_plugin_config = None
if relay_release is not None:
try:
relay_plugin_config = telemetry.load_hermes_relay_plugin_config(
relay_release
)
except RelayAtifOptionsUnsupported as error:
raise lifecycle.LifecycleError(
"hermes_relay_atif_options_unsupported", str(error)
) from error
self._agent_config = agent_config
self._settings = configuration._settings(agent_config)
interface_ports = interfaces.interface_ports(self._settings)
Expand Down Expand Up @@ -330,12 +342,12 @@ async def start(self, payload: dict[str, Any]) -> dict[str, Any] | None:
self._mounted_plugin_links,
)

if relay_enabled:
if relay_plugin_config is not None:
relay_payload = {**payload, "config": agent_config.to_mapping()}
(
self._relay_plugin_config_path,
self._relay_plugin_config,
) = telemetry.write_hermes_relay_plugin_config(relay_payload)
self._relay_plugin_config_path = telemetry.write_hermes_relay_plugin_config(
relay_plugin_config, relay_payload
)
self._relay_plugin_config = relay_plugin_config
for name in telemetry.HERMES_RELAY_ENV_NAMES:
os.environ.pop(name, None)
os.environ["HERMES_NEMO_RELAY_PLUGINS_TOML"] = str(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from typing import Any

from nemo_fabric_adapter_contract.models import RuntimeContext
from nemo_fabric_adapters.common.relay_version import validate_atif_options
import nemo_fabric_adapters.common.utils as common_utils


Expand Down Expand Up @@ -66,7 +67,7 @@ def validate_hermes_telemetry_provider(runtime_context: RuntimeContext) -> None:
_STABLE_RELAY_VERSION = re.compile(r"(0|[1-9]\d*)\.(0|[1-9]\d*)\.(\d+)(?:\+\S+)?")


def validate_hermes_relay_compatibility() -> None:
def validate_hermes_relay_compatibility() -> tuple[int, int, int]:
"""Reject Hermes/Relay combinations that cannot activate Fabric telemetry."""
try:
relay_version = version("nemo-relay")
Expand All @@ -76,11 +77,8 @@ def validate_hermes_relay_compatibility() -> None:
"adapter's relay extra in the Hermes environment"
) from error
match = _STABLE_RELAY_VERSION.fullmatch(relay_version)
if match is None or not (0, 10, 0) <= (
int(match[1]),
int(match[2]),
int(match[3]),
) < (0, 12, 0):
installed = (int(match[1]), int(match[2]), int(match[3])) if match else None
if installed is None or not (0, 10, 0) <= installed < (0, 12, 0):
raise RuntimeError(
f"Hermes Relay telemetry requires nemo-relay 0.10 or 0.11; found {relay_version}"
)
Expand All @@ -99,14 +97,26 @@ def validate_hermes_relay_compatibility() -> None:
"compatible upstream release"
)

return installed


def load_hermes_relay_plugin_config(
relay_version: tuple[int, int, int],
) -> dict[str, Any]:
"""Read and validate Relay config before changing the Hermes home."""

hermes_plugin_config = common_utils.read_relay_plugin_config()
validate_atif_options(relay_version, hermes_plugin_config)
return hermes_plugin_config


def write_hermes_relay_plugin_config(
payload: dict[str, Any],
) -> tuple[Path, dict[str, Any]]:
"""Stage Fabric's resolved Relay config for Hermes' bundled integration."""
hermes_plugin_config: dict[str, Any], payload: dict[str, Any]
) -> Path:
"""Stage the prepared config using the selected Hermes home."""

common_utils.reject_ambient_relay_plugin_config()
hermes_plugin_config = common_utils.load_relay_plugin_config(payload)
common_utils.normalize_relay_output_dirs(hermes_plugin_config, payload)
for component in hermes_plugin_config.get("components", []):
if component.get("kind") != "observability":
continue
Expand All @@ -126,4 +136,4 @@ def write_hermes_relay_plugin_config(
)
if plugin_config_path is None:
raise RuntimeError("Hermes Relay plugin configuration was not generated")
return plugin_config_path, hermes_plugin_config
return plugin_config_path
18 changes: 16 additions & 2 deletions adapters/typescript/pi/src/relay-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,21 @@ function relayModelName(input: AdapterStartInput): string {
return selected?.model || "unknown";
}

export function hasRelayAtifOverrides(pluginConfig: RelayPluginConfig): boolean {
return components(pluginConfig).some((component) => {
if (!isRecord(component) || component.kind !== "observability" || component.enabled === false) {
return false;
}
const config = component.config;
const atif = isRecord(config) ? config.atif : undefined;
return (
isRecord(atif) &&
atif.enabled === true &&
(typeof atif.include_observed_events === "boolean" || typeof atif.include_llm_requests === "boolean")
);
});
}

export function validateRelayObservability(pluginConfig: RelayPluginConfig): void {
for (const component of components(pluginConfig)) {
if (!isRecord(component) || component.enabled === false) {
Expand Down Expand Up @@ -262,7 +277,7 @@ export async function normalizeRelayOutputDirs(
}
}

export async function loadRelayPluginConfig(input: AdapterStartInput): Promise<RelayPluginConfig> {
export async function readRelayPluginConfig(): Promise<RelayPluginConfig> {
const configPath = process.env.FABRIC_RELAY_CONFIG_PATH;
if (!configPath) {
throw new Error("FABRIC_RELAY_CONFIG_PATH is required when Relay is enabled");
Expand Down Expand Up @@ -296,7 +311,6 @@ export async function loadRelayPluginConfig(input: AdapterStartInput): Promise<R
}
pluginConfig.version ??= 1;
pluginConfig.components ??= [];
await normalizeRelayOutputDirs(pluginConfig, input);
return pluginConfig;
}

Expand Down
20 changes: 16 additions & 4 deletions adapters/typescript/pi/src/relay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ import type { JsonObject } from "nemo-fabric-adapter-contract";

import {
collectRelayArtifacts,
loadRelayPluginConfig,
hasRelayAtifOverrides,
readRelayPluginConfig,
normalizeRelayOutputDirs,
prepareRelayAtifMatchers,
type RelayArtifact,
type RelayAtifMatcher,
Expand Down Expand Up @@ -52,7 +54,7 @@ export interface PiRelayControllerFactory {
export interface PiRelayDependencies {
resolveCommand: typeof resolveRelayCommand;
checkContract: typeof relayCliContract;
loadPluginConfig: typeof loadRelayPluginConfig;
loadPluginConfig: typeof readRelayPluginConfig;
writeConfigs: typeof writeRelayConfigs;
findPort: typeof findAvailableTcpPort;
startGateway: typeof startRelayGateway;
Expand Down Expand Up @@ -228,7 +230,7 @@ export class PiRelayFactory implements PiRelayControllerFactory {
this.dependencies = {
resolveCommand: resolveRelayCommand,
checkContract: relayCliContract,
loadPluginConfig: loadRelayPluginConfig,
loadPluginConfig: readRelayPluginConfig,
writeConfigs: writeRelayConfigs,
findPort: findAvailableTcpPort,
startGateway: startRelayGateway,
Expand Down Expand Up @@ -280,13 +282,23 @@ export class PiRelayFactory implements PiRelayControllerFactory {
let configPath: string;
let pluginConfigPath: string;
try {
pluginConfig = await this.dependencies.loadPluginConfig(input);
pluginConfig = await this.dependencies.loadPluginConfig();
if (contract.version[0] === 0 && contract.version[1] < 11 && hasRelayAtifOverrides(pluginConfig)) {
throw new LifecycleError(
"pi_relay_atif_options_unsupported",
`ATIF include_observed_events and include_llm_requests require NeMo Relay CLI >=0.11.0; the selected CLI is ${contract.version.join(".")}`,
);
}
await normalizeRelayOutputDirs(pluginConfig, input);
({ configPath, pluginConfigPath } = await this.dependencies.writeConfigs(
pluginConfig,
gatewayConfig,
));
atifMatchers = await prepareRelayAtifMatchers(pluginConfig);
} catch (error) {
if (error instanceof LifecycleError && error.code === "pi_relay_atif_options_unsupported") {
throw error;
}
throw new LifecycleError(
"pi_relay_configuration_failed",
"NeMo Relay runtime configuration could not be prepared",
Expand Down
Loading
Loading