Skip to content

feat(environment): add BaseEnvironmentServerWithTools, which serves an episode's tools - #5347

Merged
ffrujeri merged 6 commits into
ffrujeri/episode-tokensfrom
ffrujeri/self-contained-environment-server
Nov 16, 2026
Merged

ffrujeri merged 6 commits into
ffrujeri/episode-tokensfrom
ffrujeri/self-contained-environment-server

Conversation

@ffrujeri

@ffrujeri ffrujeri commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #5346 (episode tokens). Review that one first; this PR's diff against it is the base class and the toolset.

What changed

BaseEnvironmentServerWithTools (nemo_gym/server_runtime/base_environment_server.py, next to BaseEnvironmentServer) is a base class for an Environment Server that serves each episode's tools itself, so it needs no Resources Server. Other Environment Servers grant the agent a Resources Server's tools; this one owns the tools, the episode's state and verification. It does not impose turns: a subclass runs its episodes as it likes, and the user-simulation layer adds the turn loop on top. BaseEnvironmentServer does not change.

class MyEnvironment(BaseEnvironmentServerWithTools[MyRequest, MyResponse]):
    async def run(self, request, cleanup):
        state = MyEpisodeState(request.task)                       # the episode's state lives here
        served = await self.serve_tools(request, TypedToolset(state), cleanup)
        ...                                                        # seed the agent with served.tool_accesses
        return grade(state, served.calls)                          # every call, in order
  • EpisodeToolset (nemo_gym/server_runtime/episode_tools.py): the tools of one episode, as specs() and call(name, arguments). TypedToolset builds one from @episode_tool methods that take a Pydantic model of arguments; the docstring is the description and the model's JSON schema the parameters. A toolset can also come from the task, as nemo_user_sim's probe tools will.
  • serve_tools(request, toolset, cleanup) grants the toolset until the episode's cleanup runs. It returns a DirectHTTPToolAccess that points at this server, with a signed episode token (feat(environment): sign episode tokens for Environment Server tool grants #5346) in its headers, and the list that records each call.
  • Tool calls go to POST /<tool name> at the server's root, as on a Resources Server, so simple_agent calls them unchanged, also under a /ng-rollout/<id>/ prefix. A tool cannot take the name of one of the server's routes, such as run.
  • BaseEnvironmentServerWithToolsConfig (exported from nemo_gym.server_runtime), with an optional tool_call_timeout_seconds. A call that runs longer is cancelled, recorded as an error and answered 504, and the episode's next call runs. A TimeoutError that the tool raises itself is still a failure of the tool (500). Calls to one episode run one at a time, so without a timeout a hung call makes the episode's next calls wait until the episode ends. A client that disconnects cancels its call, which is recorded: run_webserver installs Gym's disconnect middleware.
  • Call IDs. An agent may send the model's call_id in X-NeMo-Gym-Tool-Call-Id (TOOL_CALL_ID_HEADER), and ToolCallRecord.call_id stores it, so the record joins the agent's trajectory; simple_agent sends it. Every call runs, as on a Resources Server: a model can give two calls the same ID, tool and arguments, so the server cannot tell a resend from a new call. A client that resends a call after a dropped connection runs it again, as it does against a Resources Server.
  • Tool errors over direct HTTP. A reply to a call the server records as an error, including a tool's own ToolResult(is_error=True) on a 200, carries X-NeMo-Gym-Tool-Error: true (TOOL_ERROR_HEADER, next to DirectHTTPToolAccess). It is the direct HTTP form of MCP's isError. simple_agent records such a call as failed with error_type="tool_error", as codex_agent does, so tool-error counts do not depend on the transport.
  • Public API. nemo_gym.server_runtime exports BaseEnvironmentServerWithTools, ServedTools and the toolset names (EpisodeToolset, TypedToolset, episode_tool, ToolSpec, ToolResult, ToolCallRecord, ToolArgumentsError), next to BaseEnvironmentServer, because a server outside nemo_gym/ imports from the package, not from its submodules.
  • Calls to one episode run one at a time, in arrival order, and each is recorded (ToolCallRecord: name, arguments, output, error flag, duration).
Call Answer
Ran (a tool can return ToolResult(is_error=True) for an error the agent should handle) 200 with the tool's output, and X-NeMo-Gym-Tool-Error: true for an error result
No token, or one this server did not sign 401
Signed for this episode, but not the nonce of its grant 403
The episode is not running here (it ended, or another episode's token) 410
A tool the episode does not have 404
Arguments the tool rejects, or a body that is not a JSON object 422, recorded
The tool raised 500, recorded and logged
Ran longer than tool_call_timeout_seconds 504, recorded

Why

This is the core abstraction for environments that drop their Resources Server: BIRD-Interact first, then nemo_user_sim (Linear GYMINT-640; the user-simulation RFC's layer 1, BaseEnvironmentServerWithTools). Per review, it is a new base class rather than a change to BaseEnvironmentServer, so existing Environment Servers are untouched. It was briefly named BaseSelfContainedEnvironmentServer, then BaseTurnBasedEnvironmentServer; it is now named for what it adds, since it does not impose turns.

Interim limit: until session routing covers these servers (the next PR in the stack), a BaseEnvironmentServerWithTools refuses num_workers > 1. With several workers, a tool call can reach a worker that does not hold the episode. Single-worker is not the target; the routing PR removes the limit.

Validation

Command Result
pytest tests/unit_tests/server_runtime/test_base_environment_server_with_tools.py tests/unit_tests/server_runtime/test_episode_tools.py tests/unit_tests/server_runtime/test_environment_server.py tests/unit_tests/test_public_api.py tests/unit_tests/test_import_linter_coverage.py (after the rebase onto main at dda609f86) 169 passed
pytest tests/unit_tests/server_runtime/test_base_environment_server_with_tools.py tests/unit_tests/server_runtime/test_episode_tools.py 29 passed. The server tests run real HTTP tool calls against the app (httpx.ASGITransport) while run() is in progress: calls change the episode's state and are recorded in order; a call after the episode ends gets 410; five token cases (missing, garbage, another server's, a guessed nonce, another episode's); unknown tool, rejected arguments, a non-object body and a raising tool; a rollout-prefixed call; two concurrent episodes with separate tokens; conflicting toolsets fail the episode; one grant per episode; num_workers=2 refused.
Same test with the per-episode lock removed test_calls_to_one_episode_run_one_at_a_time fails (three calls ran at once), so the test checks the lock
pytest tests/unit_tests/server_runtime/test_environment_server.py tests/unit_tests/server_runtime/test_episode_tokens.py 57 passed
pytest tests/unit_tests/server_runtime/test_base_environment_server_with_tools.py tests/unit_tests/test_public_api.py (tool-error header) 140 passed. test_a_reply_says_whether_the_call_was_an_error: a result has no header; an error result and a rejected call have it
pytest responses_api_agents/simple_agent/tests/test_app.py, in the server's venv (tool-error header) 126 passed. test_agent_session_uses_seeded_direct_http_tool_access[error-result] records a 200 with the header as failed, tool_error
Same tests, with the server not setting the header, then simple_agent not reading it 2 of the 3 server cases fail; the simple_agent error-result case fails
pytest tests/unit_tests/server_runtime/ tests/unit_tests/agents/ tests/unit_tests/test_public_api.py tests/unit_tests/test_import_linter_coverage.py tests/unit_tests/test_moved_paths.py (tool-call timeout) 2,193 passed. test_a_call_that_runs_too_long_is_cancelled_and_frees_the_episode (504, recorded, the next call runs) and test_a_timeout_the_tool_raises_itself_is_a_failure_of_the_tool (500)
Same tests, without the timeout, then without the check that the deadline expired the first fails after 10 s instead of hanging; the second fails
A real uvicorn server with Gym's ClientDisconnectCancellationMiddleware: a client starts a slow call, then drops the connection The handler is cancelled. Without the middleware it runs to the end. (An earlier check served the app without the middleware, and wrongly found that a dropped call keeps running.)
pytest tests/unit_tests/server_runtime/ tests/unit_tests/agents/ ... and simple_agent's tests (call IDs) 2,198 and 126 passed. test_a_call_records_the_id_the_agent_sent; test_a_call_that_repeats_the_last_one_runs_again (two calls with the same ID, tool and arguments: totals 2 then 4, two records)
Same tests, with the ID not recorded, or with the earlier resend check put back; then simple_agent not sending the header Each fails at least one test
pre-commit run on the changed files passed

Rollout evidence

N/A: a base class that no environment uses yet. BIRD-Interact's move onto it (Linear GYMINT-646) will run rollouts with simple_agent and Codex.

Compatibility

BaseEnvironmentServer and every existing server are unchanged. BaseEnvironmentServerWithTools subclasses take the new BaseEnvironmentServerWithToolsConfig. simple_agent now records a direct HTTP tool call whose reply has X-NeMo-Gym-Tool-Error: true as failed; no server set that header before, so existing runs record the same.

Next in the stack

MCP exposure of an episode's toolset, multi-worker session routing on the episode token, and running open episodes' cleanups at shutdown.

@copy-pr-bot

copy-pr-bot Bot commented Oct 30, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 7db0586

@ffrujeri
ffrujeri added this pull request to stack #5352 October 30, 2026 06:21
@svcnvidia-nemo-ci svcnvidia-nemo-ci added area:env-infra Shared environment framework, lifecycle, registry, scaffolding, and validation feature New capabilities, enhancements, or enablement work labels Oct 30, 2026
@ffrujeri
ffrujeri force-pushed the ffrujeri/self-contained-environment-server branch from 7db0586 to fb8001f Compare October 30, 2026 16:21
@ffrujeri ffrujeri changed the title feat(environment): add BaseSelfContainedEnvironmentServer, which serves an episode's tools feat(environment): add BaseTurnBasedEnvironmentServer, which serves an episode's tools Oct 30, 2026
@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test fb8001f

@ffrujeri
ffrujeri force-pushed the ffrujeri/self-contained-environment-server branch from fb8001f to cabd187 Compare October 31, 2026 13:16
@ffrujeri ffrujeri changed the title feat(environment): add BaseTurnBasedEnvironmentServer, which serves an episode's tools feat(environment): add BaseEnvironmentServerWithTools, which serves an episode's tools Oct 31, 2026
@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test cabd187

@ffrujeri

ffrujeri commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 24cd72d

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 474c002

@adil-a

adil-a commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

/review reset=True

@ffrujeri
ffrujeri marked this pull request as ready for review November 11, 2026 03:43

@svcnvidia-nemo-ci svcnvidia-nemo-ci left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SHIP WITH CARE

I found four RISK correctness issues in failure propagation and resend handling, plus a required rollout-evidence gap. The earlier fixes for stale grants, cancellation records, rollout context and keyword-only methods are present in the current source.

RISK — Provide representative rollout evidence for the changed agent path

The PR reports unit tests and transport experiments but marks real rollouts N/A. The changed Simple Agent execution path now sends call IDs and changes tool-failure accounting. The trusted quality bar requires representative real model smoke rollouts for behavior-changing agent work; unit tests alone don't satisfy it.

Could you run a minimal environment subclass with Simple Agent and a real model, inspect tool execution and the final episode result, and record the command/config and artifact evidence? Acceptance should demonstrate a state-changing tool call and final answer, plus a tool-supplied error result recorded as failed/tool_error while its output still reaches the model. Preserve the Resources-backed and legacy paths. This is missing validation evidence, not a claim that a rollout failed.

NOTE — Document the self-contained Environment Server path

The previous bot review's documentation finding remains unresolved. The architecture guide still says Environment Servers don't implement tools or scoring and that environment-specific tools belong to Resources Servers. That contradicts the new public base class.

Could you describe this additional authoring path and add a minimal example showing TypedToolset, serve_tools, the returned agent-session grant, and ToolSpec.function_tool() declarations supplied during activation? Preserve the existing Resources-backed and legacy workflows. State the current single-worker, restart-only and direct-HTTP limits. Static acceptance: the example advertises the tool's schema, uses the returned grant for execution, registers cleanup, and doesn't imply MCP support in this PR. This is an authoring-documentation suggestion, not a runtime failure.

I inspected all nine changed files and traced their directly affected callers, contracts, tests and failure paths. All three delegated inspections reached terminal status; one report wasn't delivered, so I inspected its typed-tool, export, layering and documentation topic directly. This was a source-only review: I didn't execute tests or independently verify the reported validation results. All acceptance checks below are proposed, not executed.

Review generated by codex. This was a full review. Request a full review with /review reset=true.

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 33e4afd

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 1010c87

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 3caf30c

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 7fcdd65

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test ea50d56

ffrujeri and others added 6 commits November 16, 2026 17:56
…n episode's tools

BaseEnvironmentServerWithTools is the base class for an Environment
Server that serves each episode's tools itself and owns the episode's
state and verification, with no Resources Server: run() holds the
episode's state, and serve_tools() grants the agent the episode's tools
until the episode's cleanup runs.

- EpisodeToolset: the tools of one episode, as specs plus a call
  method. TypedToolset builds one from @episode_tool methods with a
  Pydantic model of arguments; a toolset can also come from the task.
- Tool calls go to POST /<tool name> at the server's root, as on a
  Resources Server, with a signed episode token (EpisodeTokens) in a
  header, and under a rollout prefix as well.
- Calls to one episode run one at a time and are recorded in order.
- A call after the episode ends gets 410; a missing or foreign token
  401, another grant's nonce 403, an unknown tool 404, arguments the
  tool rejects 422, and a tool that raises 500.
- Until session routing covers these servers, a server refuses
  num_workers > 1, because a tool call can reach a worker that does not
  hold the episode.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Felipe Vieira Frujeri <[email protected]>
Review of #5347:

- A request with an episode token reaches only the episode's tools. A
  model's call named run (or ../run, which the HTTP client resolves to
  /run) got the server's /run and could start another episode.
- A call that waited for its body or for the calls before it rechecks
  that its grant is still live, so it cannot run after the episode ends.
- When the episode ends, a call still running is cancelled and gets
  410, so a late call cannot act on a stopped sandbox.
- A call cancelled by its client is recorded, because the tool may
  already have changed state.
- Each call runs under the episode's rollout, whatever its path, so a
  tool's own model or Resources Server calls carry the episode's
  capture key.
- A call to a tool the episode does not have, and an output that is not
  JSON (NaN, Infinity), are recorded as errors.
- Tokens are signed with the per-run secret (episode_token_secret).
- A subclass that sets checkpoint_mode = "exported" is refused: the
  agent's grant names the attempt that a restore replaces.
- @episode_tool refuses a method that is not async, and TypedToolset
  one whose arguments model is keyword-only. TypedToolset builds the
  specs of each class once.
- ToolSpec requires an object schema, and function_tool() declares the
  tool to the model with its full schema, $defs included.
- The docstring says that a subclass route needs more than one path
  segment, because the tool route takes every one-segment POST path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Felipe Vieira Frujeri <[email protected]>
Over MCP, a tool's error result carries `isError`. Over direct HTTP, the
same result was a plain 200, so simple_agent recorded the call as
completed, and tool-error counts in the trajectory depended on the
transport.

- A direct HTTP tool route answers a call whose result is an error with
  `X-NeMo-Gym-Tool-Error: true` (TOOL_ERROR_HEADER, next to
  DirectHTTPToolAccess). BaseEnvironmentServerWithTools sets it on every
  call it records as an error.
- simple_agent records a call whose reply has the header as failed, with
  error_type "tool_error", as codex_agent does. A non-2xx status still
  gives http_<status>.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Felipe Vieira Frujeri <[email protected]>
…tool call runs

Calls to one episode run one at a time, so a hung call made the
episode's next calls wait until the episode ended. A client that
disconnects does not end its call either: uvicorn does not cancel the
request, on direct HTTP or on MCP, with mcp 1.29, 1.30 or 2.3.

- BaseEnvironmentServerWithToolsConfig, with an optional
  tool_call_timeout_seconds. A call that runs longer is cancelled,
  recorded as an error and answered 504, and the episode's next call
  runs. A TimeoutError that the tool raises itself is still a failure
  of the tool (500).
- The test of a cancelled call is renamed: it cancels the request, which
  a disconnecting client does not do.

No separate cap on concurrent tool calls: an episode runs one call at a
time, so max_concurrent_episodes already bounds them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Felipe Vieira Frujeri <[email protected]>
…l without running it again

A ToolCallRecord had no call ID, so the server's record could not be
joined to the agent's trajectory. And simple_agent's HTTP client resends
a POST whose connection dropped (_resend_after_disconnect defaults to
true), while the server, which uvicorn does not cancel, may already have
run it: a tool such as BIRD's submit could charge twice.

- An agent may send the model's call_id in X-NeMo-Gym-Tool-Call-Id
  (TOOL_CALL_ID_HEADER, next to DirectHTTPToolAccess); ToolCallRecord
  stores it as call_id. simple_agent sends it on direct HTTP tool calls.
- Calls to one episode run one at a time, so a resend waits behind the
  call it repeats. A call with the same ID, tool and arguments as the
  episode's last recorded call gets that call's reply, and the tool does
  not run again. A reused ID with other arguments, or not on the last
  call, runs, because a model can reuse IDs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Felipe Vieira Frujeri <[email protected]>
A resend check keyed on the call ID could not tell a resent request from
a new model decision with the same ID, tool and arguments, and so could
skip a real call. A Resources Server runs every call, so this class does
too. The call ID stays on each record, to join it to the agent's
trajectory. The docstring now says that a disconnect cancels the call,
as Gym's disconnect middleware does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Felipe Vieira Frujeri <[email protected]>
@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test b1ae342

@github-actions

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/43936967937

@github-actions

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/43943700912

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:env-infra Shared environment framework, lifecycle, registry, scaffolding, and validation feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants