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
24 changes: 24 additions & 0 deletions adapters/python/codex/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,30 @@ Codex state variables, the selected model's `api_key_env`, explicit
`environment.env` values, and variables named by `environment.env_names`
while clearing unrelated parent-process secrets.

### Explicit skill discovery

Set `harness.settings.skill_discovery: explicit` for a controlled skill
inventory. Pass the allowed directories via NeMo Fabric's `skills.paths` or the
Harbor task's skills directory. An explicit run without skill paths must have
an empty inventory.

Explicit runs require an API key via the selected model's `api_key_env` and
use a private Codex home. NeMo Fabric disables bundled and plugin discovery and
turns off the additional executor and orchestrator skill sources. It disables
ambient skills detected at startup through Codex's per-path configuration,
then verifies that exactly the requested skill files are enabled. NeMo Fabric
rejects `config_overrides` in this mode so the discovery check and the thread
cannot use different overrides.

NeMo Fabric checks the inventory again before each invocation. A mismatch stops
that invocation before calling the model. Read `output.skills.loaded` for the
verified names and origins. An empty array represents a verified empty
inventory. This is a discovery policy. Codex's sandbox controls filesystem
access separately.

For Harbor, pass `{"skill_discovery": "explicit"}` as
`fabric_harness_settings`. Use a fresh runtime per evaluation arm.

## Relay Integration

Relay requires a NeMo Relay CLI in the `>=0.9,<0.12` range on `PATH`. The
Expand Down
6 changes: 6 additions & 0 deletions adapters/python/codex/codex.fabric-adapter.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@
"uniqueItems": true,
"description": "Hosts trusted for credential-free HTTP model forwarding through NeMo Relay >=0.11.0; no schemes, ports, paths, wildcards, brackets, or zone identifiers."
},
"skill_discovery": {
"type": "string",
"enum": ["native", "explicit"],
"default": "native",
"description": "Explicit mode restricts enabled Codex skills to the configured skill paths, including an empty inventory."
},
"sandbox": {
"type": "string",
"enum": ["read-only", "workspace-write", "danger-full-access"],
Expand Down
191 changes: 176 additions & 15 deletions adapters/python/codex/src/nemo_fabric_adapters/codex/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
from collections.abc import Callable
from typing import Any

import tomli_w

from openai_codex import (
ApprovalMode,
AsyncCodex,
Expand All @@ -42,7 +44,10 @@
McpServerOauthLoginResponse,
McpServerStartupState,
McpServerStatusUpdatedNotification,
SkillMetadata,
SkillsConfigWriteResponse,
SkillsExtraRootsSetResponse,
SkillsListResponse,
ThreadReadResponse,
)
from openai_codex.types import Personality, ReasoningEffort, TurnStatus
Expand Down Expand Up @@ -356,6 +361,110 @@ async def _register_skill_roots(codex: AsyncCodex, skill_paths: list[Path]) -> N
)


def _explicit_skill_discovery(config: AgentConfig) -> bool:
mode = _settings(config).get("skill_discovery", "native")
if mode not in ("native", "explicit"):
raise AdapterConfigError(
"codex_invalid_configuration", "skill_discovery must be native or explicit"
)
if mode == "native":
return False
if _selected_model_config(config).api_key_env is None:
raise AdapterConfigError(
"codex_invalid_configuration",
"explicit skill discovery requires models.<name>.api_key_env for a private Codex home",
)
if _settings(config).get("config_overrides"):
raise AdapterConfigError(
"codex_invalid_configuration",
"explicit skill discovery does not support Codex config_overrides",
)
return True


# Both skills/list and the thread must use the same discovery controls.
_EXPLICIT_SKILL_CONFIG = {
"skills": {"bundled": {"enabled": False}, "include_instructions": True},
"features": {
"plugins": False,
"executor_capability_discovery": False,
"skip_host_skill_discovery": False,
"multi_agent": False,
"multi_agent_v2": {"enabled": False},
},
"orchestrator": {"skills": {"enabled": False}},
}


async def _skill_inventory(
codex: AsyncCodex, cwd: Path, allowed: frozenset[Path], *, configure: bool = False
) -> list[dict[str, str]]:
request = getattr(getattr(codex, "_client", None), "request", None)
if not callable(request):
raise AdapterConfigError(
"codex_skill_inventory_unverified",
"The pinned Codex app-server skill inventory requests are unavailable",
)

async def enabled() -> list[SkillMetadata]:
response = await request(
"skills/list",
{"cwds": [str(cwd)], "forceReload": True},
response_model=SkillsListResponse,
)
if (
len(response.data) != 1
or Path(response.data[0].cwd).resolve() != cwd.resolve()
or response.data[0].errors
):
raise AdapterConfigError(
"codex_skill_inventory_unverified",
"Codex could not resolve a complete skill inventory for the workspace",
)
return [skill for skill in response.data[0].skills if skill.enabled]

try:
skills = await enabled()
if configure:
rejected = [
skill
for skill in skills
if Path(skill.path.root).resolve() not in allowed
]
for skill in rejected:
await request(
"skills/config/write",
{"path": skill.path.root, "enabled": False},
response_model=SkillsConfigWriteResponse,
)
if rejected:
skills = await enabled()
paths = [Path(skill.path.root).resolve() for skill in skills]
except TimeoutError:
raise
except (CodexError, ValueError, OSError) as error:
raise AdapterConfigError(
"codex_skill_inventory_unverified",
"Codex could not configure or read the explicit skill inventory",
) from error
names = [skill.name for skill in skills]
if (
set(paths) != allowed
or len(paths) != len(allowed)
or len(set(names)) != len(names)
or any(skill.plugin_id is not None for skill in skills)
):
raise AdapterConfigError(
"codex_skill_inventory_mismatch",
"Codex enabled skills differ from the configured paths or have ambiguous names. "
"Check the skill paths or start a fresh runtime after changing the workspace inventory.",
)
return [
{"name": skill.name, "origin": "external"}
for skill in sorted(skills, key=lambda s: s.name)
]


def _mcp_oauth_servers(
config: AgentConfig,
) -> dict[str, McpOAuth2Config]:
Expand Down Expand Up @@ -977,6 +1086,13 @@ def thread_config(
name="harness.settings.config_overrides",
)
_apply_config_overrides(result, overrides)
if _explicit_skill_discovery(config):
result.update(
{
key: {**result.get(key, {}), **value}
for key, value in _EXPLICIT_SKILL_CONFIG.items()
}
)
if relay is not None:
provider = _selected_model_config(config).provider
transport_config = (
Expand Down Expand Up @@ -1075,6 +1191,7 @@ def validate_runtime_payload(

settings = _settings(config)
_native_skill_paths(config, base_dir)
_explicit_skill_discovery(config)
fabric_runtime_id = context.runtime_id
resolve_cwd(context, base_dir)
selected_model(config)
Expand Down Expand Up @@ -1461,7 +1578,9 @@ def __init__(self) -> None:
self._thread: Any = None
self._relay: CodexRelaySettings | None = None
self._gateway_process: subprocess.Popen[Any] | None = None
self._api_key_home: tempfile.TemporaryDirectory | None = None
self._private_home: tempfile.TemporaryDirectory | None = None
self._allowed_skill_files: frozenset[Path] | None = None
self._loaded_skills: list[dict[str, str]] | None = None
self._mcp_authentication_checked = False
self._mcp_statuses: CodexMcpStartupStatuses | None = None
self._unusable = False
Expand Down Expand Up @@ -1494,17 +1613,20 @@ async def start(self, payload: dict[str, Any]) -> None:
model_config = _selected_model_config(agent_config)
api_key_env = model_config.api_key_env
api_key = None
explicit_skills = _explicit_skill_discovery(agent_config)
skill_paths = _native_skill_paths(agent_config, base_dir)
if model_config.provider == "openai" and api_key_env is not None:
api_key = client_config.env.get(api_key_env)
if not api_key:
raise AdapterConfigError(
"codex_invalid_configuration",
f"{api_key_env} is required for Codex API-key authentication",
)
self._api_key_home = tempfile.TemporaryDirectory(
if api_key is not None or explicit_skills:
self._private_home = tempfile.TemporaryDirectory(
prefix="nemo-fabric-codex-"
)
private_home = Path(self._api_key_home.name).resolve()
private_home = Path(self._private_home.name).resolve()
if private_home.is_relative_to(
_artifact_root(context, base_dir).resolve()
):
Expand All @@ -1513,6 +1635,10 @@ async def start(self, payload: dict[str, Any]) -> None:
"Temporary Codex credential directory must be outside artifacts",
)
client_config.env["CODEX_HOME"] = str(private_home)
if explicit_skills:
client_config.env["CODEX_SQLITE_HOME"] = str(private_home)
with (private_home / "config.toml").open("wb") as file:
tomli_w.dump(_EXPLICIT_SKILL_CONFIG, file)
elif model_config.provider != "openai":
await asyncio.to_thread(
Path(client_config.env["CODEX_HOME"]).mkdir,
Expand All @@ -1523,9 +1649,22 @@ async def start(self, payload: dict[str, Any]) -> None:
self._client = client
if api_key is not None:
await client.login_api_key(api_key)
await _register_skill_roots(
client, _native_skill_paths(agent_config, base_dir)
await _register_skill_roots(client, skill_paths)
allowed_skill_files = (
frozenset((path / "SKILL.md").resolve() for path in skill_paths)
if explicit_skills
else None
)
if allowed_skill_files is not None:
# An explicit empty inventory still needs an initialized server.
if not skill_paths:
await client.models()
await _skill_inventory(
client,
resolve_cwd(context, base_dir),
allowed_skill_files,
configure=True,
)
thread = await _open_thread(
client,
agent_config,
Expand All @@ -1534,9 +1673,7 @@ async def start(self, payload: dict[str, Any]) -> None:
relay=relay,
)
mcp_servers = agent_config.mcp.servers if agent_config.mcp else {}
notifications = (
_codex_global_notifications(client) if mcp_servers else None
)
notifications = _codex_global_notifications(client) if mcp_servers else None
mcp_statuses = (
CodexMcpStartupStatuses(
str(thread.id),
Expand Down Expand Up @@ -1570,6 +1707,7 @@ async def start(self, payload: dict[str, Any]) -> None:
self._base_dir = base_dir
self._fabric_runtime_id = fabric_runtime_id
self._thread = thread
self._allowed_skill_files = allowed_skill_files
self._mcp_statuses = mcp_statuses
self._usage_totals = dict.fromkeys(USAGE_FIELDS, 0)

Expand Down Expand Up @@ -1720,6 +1858,7 @@ async def _invoke(
"codex_runtime_mismatch",
"Codex invocation does not match the connected runtime",
)
self._loaded_skills = None
if self._unusable:
return self._run_result(
_failure(
Expand All @@ -1745,6 +1884,25 @@ async def _invoke(
else None,
)
self._mcp_authentication_checked = True
if self._allowed_skill_files is not None:
deadline = asyncio.timeout_at(invocation_deadline)
try:
async with deadline:
self._loaded_skills = await _skill_inventory(
self._client,
resolve_cwd(context, base_dir),
self._allowed_skill_files,
)
except TimeoutError as error:
self._unusable = True
output = (
_failure("timeout", "Codex invocation timed out")
if deadline.expired()
else sdk_failure(error)
)
if self._relay is not None:
output = _relay_output(output, self._relay)
return self._run_result(output, self._usage_totals)
relay = self._relay
atif_before = (
relay_artifacts.snapshot_atif_files(relay.plugin_config)
Expand Down Expand Up @@ -1807,6 +1965,8 @@ def _run_result(
mcp := mcp_availability.output_block(self._mcp_statuses.unavailable())
):
output = {**output, "mcp": mcp}
if self._loaded_skills is not None:
output = {**output, "skills": {"loaded": self._loaded_skills}}
return _agent_run_result(output, cumulative_totals)

async def stop(self) -> None:
Expand All @@ -1818,6 +1978,8 @@ async def stop(self) -> None:
self._base_dir = None
self._thread = None
self._fabric_runtime_id = None
self._allowed_skill_files = None
self._loaded_skills = None
self._mcp_authentication_checked = False
self._mcp_statuses = None
self._unusable = True
Expand All @@ -1835,9 +1997,9 @@ async def stop(self) -> None:
cleanup_error = _cleanup_relay(self._relay, self._gateway_process)
self._relay = None
self._gateway_process = None
if self._api_key_home is not None:
self._api_key_home.cleanup()
self._api_key_home = None
if self._private_home is not None:
self._private_home.cleanup()
self._private_home = None

if isinstance(close_error, asyncio.CancelledError):
raise close_error
Expand Down Expand Up @@ -1865,9 +2027,9 @@ async def _cleanup_failed_start(self) -> None:
cleanup_error = _cleanup_relay(self._relay, self._gateway_process)
self._relay = None
self._gateway_process = None
if self._api_key_home is not None:
self._api_key_home.cleanup()
self._api_key_home = None
if self._private_home is not None:
self._private_home.cleanup()
self._private_home = None
if cleanup_error is not None:
LOGGER.error(
"Codex Relay cleanup after start failure also failed: %s",
Expand All @@ -1881,7 +2043,6 @@ def main() -> None:
lifecycle.serve(CodexRuntime, config_loader=AgentConfig.from_mapping)



# Selected software reported by the shared lifecycle host; no dependency scan.
PROVENANCE_PACKAGES = (
("adapter", "nemo-fabric-adapters-codex", "nemo_fabric_adapters.codex.adapter"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@
"uniqueItems": true,
"description": "Hosts trusted for credential-free HTTP model forwarding through NeMo Relay >=0.11.0; no schemes, ports, paths, wildcards, brackets, or zone identifiers."
},
"skill_discovery": {
"type": "string",
"enum": ["native", "explicit"],
"default": "native",
"description": "Explicit mode restricts enabled Codex skills to the configured skill paths, including an empty inventory."
},
"sandbox": {
"type": "string",
"enum": ["read-only", "workspace-write", "danger-full-access"],
Expand Down
Loading
Loading