Skip to content

feat(core): session secrets, cookie names and MCP endpoint options for servers that sandboxed code calls - #6161

Merged
athitten merged 6 commits into
mainfrom
dmolinari/session-secret-and-mcp-endpoint-options
Nov 24, 2026
Merged

athitten merged 6 commits into
mainfrom
dmolinari/session-secret-and-mcp-endpoint-options

Conversation

@d-molinari

@d-molinari d-molinari commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Lets a server that code in a sandbox calls keep its sessions and its MCP endpoint to itself. It is the first of three pieces that #5010's review split out: this one, then single_agent_turn's step loop (#6162, built on this branch), then OfficeEnv's sandboxed server (#5010, built on that one). Every option is off by default, and the defaults are today's behavior.

  • Session cookies and MCP session tokens can be signed with a secret made for the run. run_session_secret(name) makes one per server and keeps it in the environment, so the workers uvicorn starts after the main process built the server inherit it, as episode_token_secret() does for episode tokens. SimpleServer.get_session_secret() returns it when the server sets signs_sessions_with_run_secret or its config sets mcp_bearer_token, and today's key, get_session_middleware_key(), otherwise. The session_secret property resolves it once per server, and the session middleware, session routing and the MCP endpoint all read it there.
  • SimpleServer.get_session_cookie_name() is the session cookie's name (default: the same key).
  • mcp_server_name on BaseResourcesServerConfig is the name the MCP endpoint lists itself under in the seed's MCP metadata. Harnesses name its tools after it, each in its own way (Pi mcp__<name>__<tool>, OpenCode <name>_<tool>), and verify-time normalization strips the mcp__<name>__ namespace.
  • mcp_bearer_token hands out the session token as Authorization: Bearer. tools/list then needs a token and lists only the session's tools, a tool outside the grant is answered as an unknown tool, and errors name no framework.
  • Both options are refused without expose_tools_over_mcp. mcp_server_name must be a name an MCP grant takes (MCP_TOOL_ACCESS_NAME_PATTERN, which starts with a letter or digit) and fit MCP's tool-name alphabet. A single_agent_turn pairing that grants two MCP endpoints listed under one name does not start, since their tools would collide; the check is per pairing, so two servers in one run may share a name when no episode is granted both.
  • With mcp_bearer_token the server signs with its run secret, from YAML alone and with any num_workers: the default key is public (the default cookie name shows it), so code that reads one token could otherwise sign another session's. An override of get_session_secret() that returns that key keeps the endpoint from starting.
  • opencode_agent refuses at seed two MCP grants whose tools OpenCode could name alike. OpenCode keys a tool <grant>_<tool>, writing any character other than a letter, digit, _ or - as _, and a later key replaces an earlier one, so company beside company_files is refused (their files_list and list would both be company_files_list), as are names that differ only where OpenCode writes _.

Validation

On main fa845c0e70:

  • Gym's core suite, as CI runs it (four shards, then -m sandbox): all four shards and the 1,870 sandbox tests pass; combined core coverage 95.04%.
  • gym env test: environment_servers/single_agent_turn 299 passed, responses_api_agents/opencode_agent 1,033 passed, responses_api_agents/pi_agent 382 passed.
  • tests/e2e/session_routing with NEMO_GYM_MULTIWORKER_E2E=1: 3 of 3 runs pass. In CI its test_every_mcp_request_runs_on_the_worker_that_runs_its_episode can fail its check that the episodes spread over workers (assert 1 > 1), as it did on build(deps): bump mlflow, GitPython and transitive deps for security fixes #6268, which changes no session code.
  • The new tests fail on the code they guard: tokens read with the public key, run_webserver handing session routing Gym's own header or key, the options without the endpoint, two endpoints under one name, a name no grant takes, and a bearer token signed with the default key. The OpenCode tests refuse the pair above and keep pairs that cannot collide (company-files, companyfiles). The run secret's tests cover one secret per server name, the same secret in a new process started with the environment, the defaults with and without the flag or bearer tokens, and one resolution per server however it was built.
  • pre-commit passes on the changed files, detect-secrets flags only test values and placeholders in them, and every commit is signed off.

Checklist

  • I have read the contributing guidelines.
  • The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs.
  • Tests added or updated and pass locally, or N/A for docs-only / non-code changes (so CI unit/server checks pass when applicable).
  • Documentation added or updated, or N/A with justification (the MCP resources-server tutorial; single_agent_turn's and opencode_agent's READMEs).
  • Pre-commit checks pass locally, on the changed files (so CI lint/format checks pass).
  • New source files include the required Apache-2.0 SPDX header.
  • All commits have DCO sign-off (git commit -s) (so the DCO check passes).

🤖 Generated with Claude Code

@copy-pr-bot

copy-pr-bot Bot commented Nov 13, 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.

@d-molinari

Copy link
Copy Markdown
Contributor Author

/ok to test d60160b

@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 13, 2026 19:30
@github-actions

github-actions Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

@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

Two RISK findings affect the new mcp_server_name option: some accepted names fail during agent seeding, and the shared legacy sandbox seeder ignores the advertised name.

I reviewed all 13 changed files and traced the affected signing, routing, checkpoint, grant, and agent-consumer paths. One delegated report wasn't available, so I completed that topic's source inspection directly. This was a static review; I didn't execute tests or model rollouts, and the PR's validation results remain author-reported.


Inline comments (escaped v1):

  • nemo_gym/server_runtime/tool_access.py line 47: RISK — Accept the new endpoint names in the MCP grant contract

    With expose_tools_over_mcp: true and mcp_server_name: _company, the new configuration field validates, but a single_agent_turn episode granting those tools fails before agent seeding. _mcp_tool_access copies the advertised name into this field, whose pattern rejects a leading _ or -. Every episode using either newly accepted leading character fails instead of carrying the advertised name unchanged.

    Could you align this consumer with the endpoint's supported alphabet? At this field, the small correction is:

        name: str = Field(min_length=1, pattern=r"^[A-Za-z0-9_-][A-Za-z0-9._-]*$")
    

    This preserves existing alphanumeric names and interior dots while accepting the new leading characters. Keep DirectHTTPToolAccess unchanged, and retain rejection of empty names and leading dots. The inspected OpenCode consumer uses the name unchanged as its configuration key; Codex's name predicate also permits these characters.

    Proposed checks, not executed: parameterize the metadata-to-grant test with _company, -company, and company; each episode should reach agent seeding with that exact name and unchanged Authorization header. Add contract assertions that company.tools remains accepted while '' and .company remain rejected. Retain the collision cases: equal names on two granted MCP endpoints fail, but direct-HTTP-only Resources access causes no MCP-name collision. Verify the suggested code before adopting it.

  • nemo_gym/agents/agent_tools.py line 67: RISK — Honor the advertised name in the shared sandbox seeder

    The new option changes seed metadata's server_name, but seed_mcp_servers still keys each client configuration entry by the deployment reference. For example, a tool server referenced as store with mcp_server_name: company produces an entry named store, not company. PiSandboxedAgent passes these entries into its MCP configuration, and the adapter constructs tool names from those keys, so the model still sees store_append rather than company_append. The legacy OpenCode path uses the same helper. These sandbox callers therefore ignore the new identity option.

    Could you use the metadata name for the client entry while retaining the deployment reference for HTTP routing? Immediately before constructing the entry here, a suggested correction is:

    listed_as = metadata.get("server_name") or server.name
    if listed_as in entries:
        raise ValueError(f"Tool servers advertise the same MCP name {listed_as!r}")
    entries[listed_as] = {
        # Keep the existing URL, headers, enabled, and timeout fields.
    }

    The dependent OpenCode change is required: its required-server environment variable must use the same effective entry keys, or the required-server check will reject the renamed connection. Before building that command, derive them as:

    rollout_mcp = getattr(request.state, "_ng_opencode_mcp", None)
    required_mcp_names = (
        list(rollout_mcp)
        if isinstance(rollout_mcp, dict)
        else [s.name for s in self.config.tool_servers]
    )

    Then serialize required_mcp_names in the environment variable. Keep sandbox_server_url(server.name, ...), deployment lookups, and network routing on the real server reference. Preserve the old name when metadata omits server_name, unchanged headers/timeouts, and existing static-config precedence. Reject duplicate advertised names within one seeded set rather than silently overwriting an endpoint; separate episodes may still reuse a name.

    Proposed checks, not executed: stub a seed reply with server_name='company', URL path /mcp, and Authorization: Bearer scoped. Seeding reference store should return only key company, with the URL still resolved through store and the header unchanged. Without server_name, expect key store. Two references advertising company should fail explicitly. Check that Pi's generated configuration uses company, and OpenCode's configuration and required-server list both use company. Retain the per-run configuration test's assertions that credentials stay out of the receipt and the static configuration remains unchanged. Verify these suggestions before adopting them.

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

@cmunley1 cmunley1 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.

Looks good overall. With every option off the behavior matches today (same header, key and cookie name, same error text), and the new tests fail when the guarded lines are broken.

RISK: mcp_bearer_token with the default session secret (base_resources_server.py:186, base_server.py:348)
The default get_session_secret() is the public Class___name string, which is also the default cookie name, so it shows up in every Set-Cookie header. With mcp_bearer_token: true and no override, sandboxed code can sign {"sid": <another session>, "tools": null} and get every tool on another session, which is the per-session grant this option exists to enforce.
Suggest refusing the config at startup when mcp_bearer_token is on and get_session_secret() == get_session_middleware_key().

NOTE: tokens never expire (base_resources_server.py:104)
URLSafeSerializer has no timestamp, so only the session fence ends a token. This was already true on main, but this PR is the one that hands tokens to code the model can read. URLSafeTimedSerializer with max_age on load would close it.

@yaoyu-33
yaoyu-33 requested review from gchlebus and removed request for sephmard November 16, 2026 00:16
@svcnvidia-nemo-ci svcnvidia-nemo-ci added feature New capabilities, enhancements, or enablement work area:core Shared APIs, servers, telemetry, health, and registries needs-review PR is ready for code review and waiting on a reviewer labels Nov 16, 2026
@github-actions github-actions Bot added the sla:review-overdue Review response is over the one-business-day SLA label Nov 16, 2026
@d-molinari
d-molinari force-pushed the dmolinari/session-secret-and-mcp-endpoint-options branch from 40a158b to 2efe9fd Compare November 17, 2026 01:40
@d-molinari

Copy link
Copy Markdown
Contributor Author

Thanks, both. Fixed in 2efe9fd, and the branch is now rebased onto main (4e3f503):

  • Bot, grant names: fixed on the producer side. mcp_server_name must now match MCP_TOOL_ACCESS_NAME_PATTERN, the MCP grant's own pattern (one constant), on top of MCP's tool-name alphabet. _company, -company and .company are refused at config, and the grant contract is unchanged. A dot stays refused in mcp_server_name, because Pi's MCP adapter and Codex reject it in a server name.
  • Bot, legacy seeder: seed_mcp_servers keys each entry by the advertised server_name (else the reference) and refuses two servers that advertise one name. URL resolution and headers still follow the reference. OpenCode's required-server list uses the same keys; Pi needed no change. The tests cover each case you listed.
  • cmunley1, bearer tokens with the default secret: good catch. Exposure now refuses mcp_bearer_token while get_session_secret() returns the public session middleware key, and the error names the override. OfficeEnv's sandboxed server (feat(officeenv): run OfficeEnv episodes in a sandbox, for Gym's sandboxed harnesses #5010) already overrides it.
  • cmunley1, token expiry: this is true on main too. Today a closed session's fence ends its tokens. A timed token needs a max age longer than the longest episode, so I'd rather do it in its own PR than here.
  • Rebase: main's Environment Server tools now serve MCP through mount_mcp_endpoint (feat(environment): serve BaseEnvironmentServerWithTools episode tools over MCP #5349), and resources servers' auto-exposure mounts through it too, under the advertised mcp_server_name. Main's header sessions (feat(environment): route BaseEnvironmentServerWithTools tool calls to the worker that runs the episode #5350) and this PR's bearer-token reader both stay in session routing.

@d-molinari

Copy link
Copy Markdown
Contributor Author

/ok to test 2efe9fd

@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team November 17, 2026 01:55
@yaoyu-33
yaoyu-33 requested a review from lafrancef November 17, 2026 02:05
@d-molinari
d-molinari force-pushed the dmolinari/session-secret-and-mcp-endpoint-options branch from 2efe9fd to 6341cc9 Compare November 18, 2026 23:39
@d-molinari

Copy link
Copy Markdown
Contributor Author

/ok to test 6341cc9

@svcnvidia-nemo-ci svcnvidia-nemo-ci added the risk:high Autobot PR risk: high label Nov 18, 2026
# To sign sessions with a secret, override get_session_secret instead.
return f"{self.__class__.__name__}___{self.config.name}"

def get_session_secret(self) -> str:

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.

Can we handle per-run secret generation in server_runtime using the same env-handoff pattern as episode_token_secret() in nemo_gym/server_runtime/episode_tokens.py:25-35 (#5346), rather than requiring subclasses to override get_session_secret()?

As wired today, pushing secret generation onto subclass overrides has a few sharp edges:

  1. mcp_bearer_token: true cannot be used from YAML alone: expose_tools_over_mcp and mcp_server_name work on any existing Resources Server purely via YAML config, whereas enabling mcp_bearer_token: true fails at startup (mcp_auto_exposure.py:902-908) unless the server also adds a Python subclass overriding get_session_secret().
  2. Multi-worker divergence: Generating secrets.token_urlsafe(32) in model_post_init (as OfficeEnvSandboxResourcesServer does in feat(officeenv): run OfficeEnv episodes in a sandbox, for Gym's sandboxed harnesses #5010) only works for num_workers=1; with num_workers > 1, each Uvicorn worker re-imports the entrypoint and mints a different secret unless every subclass re-implements cross-worker propagation.
  3. Uncached multi-call hazard: server.get_session_secret() is called 5 separate times per process (setup_session_middleware, install_auto_exposure's check and serializer, run_webserver's mcp_token_routing and install_session_routing, plus lazily in _mcp_token_claims). A naive override return secrets.token_urlsafe(32) passes single-worker /mcp unit tests (since install_auto_exposure reuses one serializer) while handing SessionMiddleware, SessionRoutingMiddleware, and ResourcesCheckpointMiddleware different keys.

In #5346, episode_token_secret() solved this in server_runtime by minting secrets.token_urlsafe(32) on first call in the main process and storing it in os.environ before Uvicorn spawns workers, so all workers of that server inherit the same per-run secret automatically.

Concretely, we could:

  • Provide a per-server-run secret helper on that same os.environ pattern (keyed by server name so multiple servers in one test process stay isolated, and initialized before Uvicorn spawns workers).
  • Use it automatically when mcp_bearer_token: true (and let servers whose non-MCP HTTP routes also face a sandbox, like feat(officeenv): run OfficeEnv episodes in a sandbox, for Gym's sandboxed harnesses #5010, opt in via config/class flag or call the same helper) so mcp_bearer_token: true works out of the box from YAML across num_workers >= 1 without a startup refusal or custom secret plumbing.
  • Resolve/cache the server's session secret once per server instance if get_session_secret() is kept as an extension point, so repeated calls within a process can never return different keys.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed, and done in 8fac8b1 on the episode_token_secret() pattern:

  • run_session_secret(name) makes one secret per server for the run, keyed by the server's name, and keeps it in os.environ. The main process reads it in setup_webserver, before uvicorn starts the workers, so every worker of the server inherits it.
  • get_session_secret() returns it when the server sets signs_sessions_with_run_secret (a class flag) or its config sets mcp_bearer_token, and the public key otherwise. So mcp_bearer_token: true works from YAML alone with any num_workers, and the startup refusal now fires only for an override that returns the public key.
  • The session_secret property resolves it once per server instance (a cached_property, so it also holds for servers that tests build without model_post_init), and SessionMiddleware, session routing, the MCP serializer and _mcp_token_claims all read it there, so an override that answers differently per call can no longer split them.

#5010's sandboxed server sets the flag and drops its own token_urlsafe secret and override (c549c9b). Tests cover one secret per server name, a new process with the environment reading the same secret, the defaults with and without the flag or bearer tokens, the resolved-once property, and bearer tokens from config alone.

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.

Checked at 1508f1a337. Every reader takes the key from session_secret: SessionMiddleware, session routing, the MCP serializer and _mcp_token_claims. The main process resolves it in setup_webserver before uvicorn starts the workers, and mcp_bearer_token: true alone selects the run secret (get_session_secret). Looks resolved to me.

@d-molinari

Copy link
Copy Markdown
Contributor Author

/ok to test 8fac8b1

…ret-and-mcp-endpoint-options

Keep both constants main and this branch add to tool_access.py:
END_ACTIVATION_HEADER (#5465) and MCP_TOOL_ACCESS_NAME_PATTERN.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
@yaoyu-33

Copy link
Copy Markdown
Contributor

/ok to test 1508f1a

@yaoyu-33 yaoyu-33 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.

I merged current main into the branch (1508f1a337; the only conflict was nemo_gym/server_runtime/tool_access.py, where main's END_ACTIVATION_HEADER and this PR's MCP_TOOL_ACCESS_NAME_PATTERN both stay) and started CI.

With every option off, the behavior matches main: the same signing key, cookie name, token header, listed name and error text. The earlier threads hold at this head:

  • The run secret follows the episode_token_secret() hand-off. The main process resolves it once, before uvicorn starts the workers.
  • The legacy seeder and both sandboxed agents match main again.
  • The OpenCode collision rule is exact for both pinned versions. OpenCode 1.17.11 (catalog.ts#L116-L118) and 2.2.7 (runtime.ts#L288-L293) key MCP tools the same way.

The new tests are real: reverting their guards one at a time, 36 of 37 reverts fail a test. The one gap is inline.

Validation on the merged head (Linux workstation):

  • tests/unit_tests/server_runtime: 2194 passed.
  • environment_servers/single_agent_turn: 220 passed.
  • responses_api_agents/opencode_agent: 1164 passed.
  • The only failures (5 supervisor/uv tests and one test_pinned shell exit-code test) fail the same way on main.
  • Not run: a real checkpoint restore across a server restart, or an Apptainer sandbox.

No blockers. The notes are inline.

f"{NEMO_GYM_MCP_SESSION_TOKEN_HEADER}, and require one for tools/list too, which then lists only the "
"session's tools; a tool outside the session's grant is answered as an unknown tool, and errors name no "
"framework. For clients that pass the seed's MCP headers as given, as the environment server's MCP grants "
"do. Needs expose_tools_over_mcp. The server then signs its sessions with a secret made for the run, which "

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.

base_resources_server.py:173

A server with a run secret can't read the cookies or MCP tokens it signed before a restart, as get_session_secret says. Partial-rollout checkpointing still assumes they decode:

  • participant_workers.py#L20-L21 says a cookie from before the crash reaches the session.
  • After a restore, single_agent_turn sends its stored resources_cookies to /verify and close. It re-seeds only when the agent borrowed a sandbox and has not closed yet (app.py#L485-L493).

Starlette then hands out an empty session, so the continued episode verifies on a fresh one. Nothing in the repo turns this on yet, and OfficeEnv stays restart_only. But mcp_bearer_token: true set from YAML on an exported or stateless server reaches it, and nothing refuses that combination.

Could the server refuse a run secret when checkpointing is on and checkpoint_mode_in_effect() isn't restart_only, or report such a server as restart_only? Could this description and participant_workers.py also say so?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in #6746, as the second option: a server that signs with the run's secret (signs_sessions_with_run_secret or mcp_bearer_token) takes part as restart_only whatever checkpoint_mode_in_effect() returns, with one warning. setup_resources_checkpoint decides it, so a subclass override that returns exported is covered too, and setup_agent_checkpoint does the same for an agent with the class flag. The mcp_bearer_token description, get_session_secret, both checkpoint_mode_in_effect docstrings and participant_workers.py say so.

variable = RUN_SESSION_SECRET_ENV_PREFIX + hashlib.sha256(server_name.encode()).hexdigest()[:16].upper()
secret = environ.get(variable)
if not secret:
secret = environ[variable] = secrets.token_urlsafe(32)

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.

base_server.py:290

The run secret stays in os.environ for the server's whole life, so every process the server starts inherits it. Whether sandboxed code can read it depends on the provider:

  • Docker, OpenSandbox, OpenShell, bwrap and Enroot keep the server's environment out of the sandbox.
  • The Apptainer provider runs apptainer exec with os.environ.copy() and no --cleanenv by default (provider.py#L97-L101). Apptainer passes host variables into the container by default (docs).
  • LocalProvider passes its environment too, though it has no isolation by design.

On Apptainer, code in the sandbox can read NEMO_GYM_RUN_SESSION_SECRET_* and sign another session's token, which the docstring says it cannot.

This follows the episode_token_secret() hand-off that was asked for, so I'm not asking for a redesign. Could the docstring and the tutorial say the guarantee holds only on providers that keep the server's environment out of the sandbox? Optional ways to close the gap:

  • drop NEMO_GYM_RUN_SESSION_SECRET_* from the Apptainer and Local exec environment; or
  • have a worker pop the variable once session_secret has cached it. The multi-worker main process keeps it for respawns.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in #6746. The docstring and the tutorial say the guarantee holds only where code in the sandbox cannot read the server's environment, and name the exception. The Apptainer and local providers also leave NEMO_GYM_RUN_SESSION_SECRET_* out of the environment they pass (nemo_gym.core.run_session_secrets). I didn't pop the variable in the workers: /proc/<pid>/environ keeps a process's initial environment, so a worker that inherited the secret still shows it to code that runs as the same user in the host's process table (the local provider, Apptainer without --containall), which the docstring now says.


When the MCP client runs where the model can read its configuration, such as a harness in a sandbox the resources server lends, two config options make the endpoint an ordinary one:

- `mcp_server_name` is the name the `mcp` metadata gives the endpoint, which clients name its tools by (default: the server's name). It takes letters, digits, `_` and `-`, and starts with a letter or a digit. The Environment Server's MCP grants carry this name, and so do the MCP entries that a sandboxed agent's `tool_servers` seed. Verify-time normalization strips `mcp__<mcp_server_name>__`.

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.

mcp-resources-server.mdx:291

Since 19ab60f, seed_mcp_servers keys tool_servers entries by the server's reference again (agent_tools.py#L67), so this clause no longer holds. The deprecated sandboxed agents' tool names then aren't stripped by the mcp__<mcp_server_name>__ normalization either.

Suggested change
- `mcp_server_name` is the name the `mcp` metadata gives the endpoint, which clients name its tools by (default: the server's name). It takes letters, digits, `_` and `-`, and starts with a letter or a digit. The Environment Server's MCP grants carry this name, and so do the MCP entries that a sandboxed agent's `tool_servers` seed. Verify-time normalization strips `mcp__<mcp_server_name>__`.
- `mcp_server_name` is the name the `mcp` metadata gives the endpoint, which clients name its tools by (default: the server's name). It takes letters, digits, `_` and `-`, and starts with a letter or a digit. The Environment Server's MCP grants carry this name; the deprecated sandboxed agents' `tool_servers` entries keep the server's reference name. Verify-time normalization strips `mcp__<mcp_server_name>__`.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Applied in #6746.

name: tavily
```

When the tools served to an episode come from several MCP endpoints, each endpoint lists itself under its server's `mcp_server_name`, or else its server's name, and the harness names the endpoint's tools after that name in its own way: Pi and mini-SWE as `mcp__<name>__<tool>`, OpenCode as `<name>_<tool>` (each agent's README says how). The Environment Server does not start when two granted endpoints list themselves under one name, since their tools would collide in every harness. Distinct names can still collide in a harness's own naming, which that harness's agent refuses: the OpenCode agent refuses `company` beside `company_files`, whose tools `files_list` and `list` would both be `company_files_list`.

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.

README.md:52

Two corrections to this paragraph:

  • Pi's naming. Pi shows the model <name>_<tool> (gym_mcp.mjs#L165). mcp__<name>__<tool> is only the name Gym records. Pi already refuses the company / company_files pair (_mcp_grant_problems).
  • "which that harness's agent refuses" doesn't hold for every agent. kilocode_agent takes these grants and keys tools like OpenCode 1, but it refuses only names that are equal after sanitizing (kilocode_agent/app.py#L531-L537). So company beside company_files silently loses a tool there. Hermes skips the second owner with only a log line.

That code predates this PR, so a follow-up for Kilo and Hermes is fine. The README should name only the agents that refuse. app.py#L166-L169 and base_resources_server.py#L159 repeat the Pi naming.

Suggested change
When the tools served to an episode come from several MCP endpoints, each endpoint lists itself under its server's `mcp_server_name`, or else its server's name, and the harness names the endpoint's tools after that name in its own way: Pi and mini-SWE as `mcp__<name>__<tool>`, OpenCode as `<name>_<tool>` (each agent's README says how). The Environment Server does not start when two granted endpoints list themselves under one name, since their tools would collide in every harness. Distinct names can still collide in a harness's own naming, which that harness's agent refuses: the OpenCode agent refuses `company` beside `company_files`, whose tools `files_list` and `list` would both be `company_files_list`.
When the tools served to an episode come from several MCP endpoints, each endpoint lists itself under its server's `mcp_server_name`, or else its server's name, and the harness names the endpoint's tools after that name in its own way: Pi and OpenCode show the model `<name>_<tool>` (Gym records Pi's calls as `mcp__<name>__<tool>`), mini-SWE `mcp__<name>__<tool>` (each agent's README says how). The Environment Server does not start when two granted endpoints list themselves under one name, since their tools would collide in every harness. Distinct names can still collide in a harness's own naming: the OpenCode and Pi agents refuse `company` beside `company_files`, whose tools `files_list` and `list` would both be `company_files_list`, but not every agent checks this yet.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Applied in #6746. _check_mcp_server_names and the mcp_server_name comment no longer repeat Pi's naming. Kilo and Hermes are left for their own PR.

assert mcp["server_name"] == "company" and list(mcp["headers"]) == ["Authorization"]
scheme, _, token = mcp["headers"]["Authorization"].partition(" ")
assert scheme == "Bearer"
_handshake(client)

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.

test_mcp_auto_exposure.py:607

Nothing checks the serverInfo.name that initialize returns (mcp_auto_exposure.py#L952). Reverting that line to the config name passes every test, and the endpoint then names its internal server (store) to code in the sandbox. Could this test check it before the handshake? For example:

        init = {"jsonrpc": "2.0", "id": 0, "method": "initialize",
                "params": {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "t", "version": "0"}}}
        assert client.post("/mcp", headers=RPC_HEADERS, json=init).json()["result"]["serverInfo"]["name"] == "company"

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added in #6746: _handshake returns the initialize reply, and the test checks serverInfo.name == "company". Against mcp_auto_exposure naming the config name, it fails.

@yaoyu-33 yaoyu-33 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.

Approving at 1508f1a. No blockers; the five inline notes from the earlier review (run secret vs. checkpoint restore, run secret inheritance in Apptainer/Local sandboxes, two doc fixes, the serverInfo.name test) can land here or in a follow-up. The failing check is the non-blocking miniswe_sandboxed harness conformance probe, which fails the same way on main.

@yaoyu-33 yaoyu-33 added ready-to-merge PR is approved, current, and waiting for final CI or merge and removed needs-review PR is ready for code review and waiting on a reviewer labels Nov 24, 2026
@athitten
athitten added this pull request to the merge queue Nov 24, 2026
@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/45430453931

@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/45434651193

@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 24, 2026
@athitten
athitten added this pull request to the merge queue Nov 24, 2026
@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/45443968482

Merged via the queue into main with commit d1391e9 Nov 24, 2026
81 of 84 checks passed
@athitten
athitten deleted the dmolinari/session-secret-and-mcp-endpoint-options branch November 24, 2026 17:51
d-molinari added a commit that referenced this pull request Nov 24, 2026
#6161 now makes a secret per server and run in server_runtime, which every worker of the
server shares (signs_sessions_with_run_secret). The sandboxed server sets that flag instead
of minting its own secret in model_post_init and overriding get_session_secret(): its
cookies and MCP tokens are signed, as before, with a secret code in a sandbox cannot
derive from the server's name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>
yfw added a commit that referenced this pull request Nov 25, 2026
#5010 was rebased onto main after #6161 merged, so this branch no longer shared its base. The merge takes
#5010's new head for every file outside this layer, and this layer's diff (the Stirrup changes since
c549c9b) applied cleanly on top. The PR's diff against its base is again only the Stirrup layer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>
ko3n1g pushed a commit to ko3n1g/Gym that referenced this pull request Nov 30, 2026
…oxed harnesses (NVIDIA-NeMo#5010)

* feat(single_agent_turn): drive the agent one step at a time and end the episode on the task state

A resources server whose task ends through its state, rather than through one tool's call, can now have its
episode end right after the step that ended the task. OfficeEnv's task ends when its user app's task row leaves
pending, which several operations reach, depending on how a row exposes its apps.

- single_agent_turn: max_episode_steps drives the agent one step per activation, up to that many steps, and
  end_on_task_state reads the resources session's task state between steps (GET /task_state, ResourcesTaskState
  in nemo_gym.server_runtime). Each step's failure report is kept. The server checks at startup that its agent keeps
  a session, runs the tools it calls and stops after one step. Driven episodes take part in checkpoints as restarts
  (BaseEnvironmentServer.checkpoint_mode_in_effect).
- simple_agent: with x-ng-agent-episode-step-limit, a step stopped by its own one-step limit counts as completed
  unless it is the episode's last, and the session keeps one invocation for the episode, as the agent's own loop
  does, instead of one per step that repeats the whole history.
- OfficeEnv: GET /task_state answers ResourcesTaskState; close_tools_on_task_end refuses the calls a step makes after
  the one that ended its task; its rows route by taskset to single_agent_turn with the step loop on, and the config
  allows only the simple agent. A retired attempt no longer keeps its episode, so its replacement can seed the same
  session ID. The server runs OfficeEnv 1.14.0 (1.13.0 at least), with its example rows emitted again.

Signed-off-by: Daniele Molinari <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(single_agent_turn): run the step loop's tests in the core suite, and keep a simple_agent subclass in step

CI on the step loop found two things:
- agentic_turn_simulation_agent overrides simple_agent's _create_episode, which now takes
  step_limit_owned_by_caller. The override accepts it; only an agent session sets it, and this agent
  refuses those.
- The core coverage gate counts single_agent_turn's and simple_agent's app.py, but the step loop's tests
  ran in the server suite only. They move to the core suite unchanged, and simple_agent's step limit and
  invocation folding get core tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(single_agent_turn): import each name in the moved step-loop tests from the module that defines it

Tests under tests/ import from the defining module, not a package's public API, and
test_the_librarys_tests_import_from_the_module_that_defines_each_name failed on the two files this PR moved
into the core suite.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(simple_agent): one step per activation that names the episode's step limit, counted by its index

With x-ng-agent-episode-step-limit, the agent takes one step (one model call and the tool calls it makes) whatever
its max_steps says, so a pairing no longer needs max_steps: 1, which composition drops when --agent-type
simple_agent replaces the environment's agent. Requests without the header run as before.

- The step is the activation's index (x-ng-agent-activation), which such a caller sends with every step, not the
  count of requests, so a step resent after a dropped connection is not counted as the next one.
- The session keeps the model server's cookies from step to step, so the episode keeps one model server session.
- A step that raises ends the episode's folded invocation as failed (or incomplete when cancelled), not with the
  completed status of the step before.
- The step keywords go to _create_episode only with the header, so an override that predates them keeps working;
  agentic_turn_simulation_agent's override no longer needs to accept one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(single_agent_turn): drive only agents that take one step per activation, and keep what the steps did

- STEP_DRIVEN_AGENT_TYPES (nemo_gym.config, beside AGENT_SESSION_AGENT_TYPES) lists the agent types that take one
  step per activation that names the episode's step limit: simple_agent. The startup check refuses any other type,
  such as hermes_agent or browsecomp_agent, which keep a session but run their own loop in an activation; a unit
  test keeps the list in step with the agent apps. The check no longer reads max_steps, and reads execute_tools as
  the agent's config does, so a string "false" is false.
- A failure after a step completed keeps the completed steps, their output and summed usage, as its partial
  response, unless it already carries one; a failure before the first reply has none.
- An episode that runs out of steps with every step calling a tool says so in its reply's metadata
  (ng_termination_reason: max_episode_steps). Its status stays the last step's: incomplete_details names only the
  model's own cutoffs, and an incomplete reply would read as malformed to rollout recovery.
- The task state is not read after the last step, which ends the episode either way.
- GET /task_state answering 404 with failure_kind session_lost ends the episode, which goes on to /verify and its
  masked lost-session result, as when a tool call finds the session gone. Other failed reads fail the episode as
  before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(server_runtime): an environment server's checkpoint mode in effect sets its participant and its episodes

A server whose class declares exported but whose instance runs as restart_only installs a restart_only participant,
and its episodes begin as restarts; an unknown mode in effect stops the server at setup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(officeenv): run on single_agent_turn_legacy, so flat rows and session-less agents run too

single_agent_turn's /run takes only episode requests, so flat rows (training corpora, rows routed by their agent)
failed. single_agent_turn_legacy takes flat rows and taskset episodes, and runs the same step loop: OfficeEnv keeps
max_episode_steps 50, end_on_task_state, direct HTTP tools and the example taskset's route, and the simple agent no
longer sets max_steps: 1. Composition's fallback relays an agent without agent sessions through legacy_agent to its
own /run, so allowed_agents also admits simple_agent_with_compaction; the relay takes flat rows, not the taskset's
episodes.

The test that restated the YAML (skipped in CI with OfficeEnv absent) gives way to core tests that resolve the
config with a model and build its environment server: as shipped, with simple_agent.yaml added as --agent-type
simple_agent does, and with the compaction agent's config, where the server becomes a legacy_agent relay. The config
comment and README say what --agent-type and allowed_agents do, and that rollout_recovery.target_level: sibling
applies to the whole training run.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* docs: GET /task_state and the episode step-limit header

The Seed/Verify Protocol Extensions table lists GET /task_state, its reply, and what a 404 or 5xx does to the
episode. The agent integration page describes x-ng-agent-episode-step-limit beside x-ng-agent-activation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(core): LentSandboxes lends a sandbox with its own image, environment and setup, and releases all within a deadline

What the OfficeEnv sandboxed server needs from core's lent sandboxes, so it builds on them instead of a copy:

- lend() takes a per-sandbox image, more environment variables and a setup that runs against the started sandbox,
  its files delivered, before it is lent (start_with_setup); a setup that fails stops the sandbox.
- The start runs to its end once begun, within start_timeout_s (30 minutes by default), even while the request that
  asked for it is cancelled: a create cut in flight leaves a sandbox whose id the provider never returned. A lend
  cancelled meanwhile lends nothing and stops what it started, and says so in the log.
- release_all(timeout_s=...) refuses new lends (503) from its start, waits for those still starting, stops everything
  within the deadline, and returns and logs the sessions whose sandbox may still run, for a reaper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(officeenv): run OfficeEnv episodes in a sandbox, for Gym's sandboxed harnesses

resources_servers/officeenv_sandbox's OfficeEnvSandboxResourcesServer subclasses the OfficeEnv server and lends each
episode session a sandbox through LentSandboxes (an operate descriptor: the harness uses it, only the server stops
it), stopped before the episode is graded.

- The harness reaches the apps as the row's exposure says: MCP tools, a command per app (cli), or endpoints it finds
  over MCP and calls with curl (api_search).
- File content stays out of the conversation through OfficeEnv's workspace mode: downloads land in the workspace,
  uploads and attachments name a workspace file, and a file API moves bytes directly.
- The sandbox sees an ordinary company API. Only Gym's servers on this node (any of the node's own addresses) and
  trusted_networks reach seeding, closing, verification, metrics, the reverify mode, the app catalog, the task state
  and the tool routes, which answer others 404 before reading a body; sessions are signed with a per-process secret.
- Seeds take turns, and a seed is admitted again before it lends; a close or a retire stops the sandbox, a failed
  seed's stop is tried again at its session's close, and shutdown stops everything within the run's grace.
- A sandbox provider failure fails the call (502) and masks the episode's reward.
- Configs for Pi (Docker and OpenSandbox), Codex CLI, mini-SWE, OpenCode, OpenClaw and Terminus 2; nine sandbox tasks
  (OfficeEnv 1.14.0), the first five as example rows with Pi's rollouts of them; images and a README.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(core): LentSandboxes logs a start its limit cut before the provider returned the sandbox's id

When start_timeout_s cuts a provider's create in flight, the sandbox's id is unknown, so the lend's stop cannot reach
what the create left. The lend now logs that cut at ERROR with the resources session, the task (id and taskset), the
provider, the image and the labels, so a reaper can find the sandbox. A start cut after the create returned stops its
sandbox as before and asks for no reaper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* refactor(officeenv_sandbox): name each harness's instances after it, so harness configs compose in one run

Every harness config defined `oe` and `single_agent_turn_legacy`, so two of them could not run together. Now:

- the episodes' resources server is officeenv_sandbox_resources_server;
- each config adds officeenv_sandbox_<harness>_agent (`_inherit_from` Gym's instance of the harness, as benchmarks do)
  and officeenv_sandbox_<harness>_environment_server (`_inherit_from: single_agent_turn_legacy`);
- Pi, Codex and OpenCode, which name MCP tools their own way, run on their own copy of the episodes' server
  (officeenv_sandbox_<harness>_resources_server, `_copy` with its mcp_tool_prefix); the other harnesses run on the
  shared one. A copy takes the shared server's settings from the merged config, so one override reaches every harness.

The interpolations, the documented overrides, the probe script and the README follow (a table of the names; the
OpenSandbox config is listed after the other harness configs, since a later one pulls the episodes' config in again).
A core test resolves each config alone and all six together with a model config, and replaces the server test that
restated their YAML; it needs no OfficeEnv, so it runs in CI. The OpenCode and OpenClaw configs and the README no
longer say those harnesses refuse MCP tool grants.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(officeenv_sandbox): sandbox_config.start_timeout_s bounds a sandbox's start; host_relay needs trusted_workstation

- sandbox_config.start_timeout_s (1800 s by default, a finite number above 0) is passed to LentSandboxes, which fails
  the seed at that limit and logs a create it cut for a reaper. The README says when to raise it: creates on a busy
  OpenSandbox cell have taken up to 2,430 s.
- host_relay forwards sandbox connections from the host's loopback, which the caller check takes for Gym's own
  servers, so code in a sandbox could call the routes kept for Gym for any session. Config validation now refuses
  host_relay unless sandbox_config.trusted_workstation is true, which a config sets only on a single-user workstation;
  its description and the README state the risk.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(officeenv_sandbox): officeenv_sandboxless.yaml runs the OfficeEnv server's instances under names of their own

It composes resources_servers/officeenv/configs/officeenv.yaml and copies (`_copy`) its three instances as
officeenv_sandboxless_resources_server, officeenv_sandbox_simple_agent and officeenv_sandbox_environment_server, each
copy pointing at the other copies, while the OfficeEnv server's instances keep their names. The copied agent declares
no dataset, so the example rows and their taskset stay with the OfficeEnv server's instances, and rows that name
officeenv_sandbox_simple_agent (flat rows, agent_ref) route to the copied environment server.

A `_copy` takes its source as written, before the source's own `_inherit_from` applies, so the environment server is
copied as the instance of the server type officeenv_environment_server inherits, with that server's own settings for
it on top. The core test checks each copy against its source, references aside, alone and beside the Pi and Codex
configs, so a change to the source's server type fails it rather than leaving the copy behind.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(officeenv_sandbox): the sandboxless arm copies single_agent_turn_legacy, which the OfficeEnv server now runs

officeenv_environment_server inherits single_agent_turn_legacy now, so the copy takes that instance, then the server's
own settings for it under that type, with its references still pointing at the other copies.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* refactor(officeenv_sandbox): every harness runs the episodes' server under its own name, so none is left idle

Each harness config now adds officeenv_sandbox_<harness>_resources_server with `_inherit_from:
officeenv_sandbox_resources_server`, OpenClaw, mini-SWE and Terminus 2 included, and no harness names the episodes'
server. `_inherit_from` reads it from the merged config and takes it out of the run, so a run of one or several
harness configs starts no idle episodes' server, while the episodes config alone still runs it under its own name.
Settings on the episodes' server, the OpenSandbox config's included, reach every harness's server. The OpenSandbox
config still goes after the other harness configs (the first harness config listed pulls the episodes' config in),
and the README now says why. The core test checks that no episodes' server starts or is named beside the harnesses',
alone and with all six, and that the episodes config runs on its own.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(core): the cut-start log says OpenSandbox deletes what an abandoned create left

Main's OpenSandbox provider now deletes the sandbox of a create its caller gave up on (NVIDIA-NeMo#4799), so
a start that LentSandboxes' start_timeout_s cuts before the provider returned the sandbox's id no
longer needs a reaper there. The ERROR log, LentSandboxes' docstring and the officeenv_sandbox
README now say so, and keep the reaper for providers without that cleanup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(officeenv_sandbox): Pi's run ends once its task has ended, on every exposure

- The sandboxed server holds the call that ends a watched episode's task, on
  every way in (tools, commands, endpoints, the file API), until the
  environment server releases it; the episode's lock is let go first. Only
  Gym's node reaches GET /task_state and POST /task_state/release.
- Pi supports POST /rollouts/{rollout_id}/stop (_rollout_sandbox_session): a
  run stopped as completed answers so, marked in ng_rollout_stop, and is not
  reported as a wall-time timeout.
- The Pi config sets end_on_task_state on its environment server and drops
  finish_tool_names (now []): the stop ends the run on cli and api_search rows
  too, which offer no finish tool. Its comment no longer asks cli rows to drop
  the MCP transport, which they run with as it is.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* docs(officeenv): the servers run OfficeEnv 1.14.2

1.14.2 is the OfficeEnv release N4's training runs grade with. 1.14.1 and
1.14.2 are patch releases; neither changes the API these servers use. The
READMEs' install lines name it, and the example rows are emitted again by it
(officeenv emit for resources_servers/officeenv, sandbox/prepare_rows.py for
officeenv_sandbox), which changed only their version stamp. The example
rollouts stay the ones collected against 1.14.0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(officeenv_sandbox): refuse calls after the task ended with ResourcesSessionConflictError

Main's session contract (NVIDIA-NeMo#5691) has every 409 a resources server answers raise
ResourcesSessionConflictError, and tests/unit_tests/test_session_contract_repo.py
checks it. The sandboxed server refused a tool call once verification began, and a
file API call once the episode's files closed, with plain HTTPException(409)s; both
now raise the named error. The status and the detail are the same, so callers see no
change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(core): LentSandboxes shields a start only with start_timeout_s

Main's opencode_search (NVIDIA-NeMo#6211) lends through LentSandboxes and expects a seed cancelled
while its sandbox starts to stop that sandbox at once, as LentSandboxes did before this
branch; the shielded start made it wait for the start's end. The shield is now opt-in.
Without start_timeout_s a cancel cuts the start as it cuts any await, as on main, and the
lend stops the sandbox it began. With it, the start runs to its end within that limit,
which the OfficeEnv sandbox server sets (sandbox_config.start_timeout_s, 1,800 s by
default). START_TIMEOUT_S goes, since no default limit remains.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* build(officeenv_sandbox): lock against main's upgraded dependency locks

Main's lock upgrade (NVIDIA-NeMo#6528) moved the root lock, and `uv sync --locked` refused the
sandboxed server's older lock, so neither its suite nor a run could start it. `uv lock`
with uv 0.13.4 takes the root lock's versions (e2b 2.50.0, protobuf-py 0.1.1, pyqwest
0.10.0), keeps the tzdata OfficeEnv pins (2026.6), and passes scripts/component_locks.py.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(core): a cut start's test counts the closes the provider made

Main's NVIDIA-NeMo#6410 changed the stopped fixture from AsyncSandbox.stop calls to the closes the
provider made. A start cut before the provider returned its sandbox's id leaves nothing
to close, so the hung-start test now expects none, as the ERROR line it checks says.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(single_agent_turn): stop an agent's own loop once its task has ended

With end_on_task_state and no max_episode_steps, single_agent_turn now ends an
agent that runs its own loop (a sandboxed harness) at its task's end, as the
step loop ends a step-driven one:

- Before the agent runs it reads GET /task_state?watch=true; while the agent
  runs it reads again, each read waiting up to 30 s (wait_s).
- Once the task has ended it stops the run with POST /rollouts/{id}/stop
  {"reason": "task_ended", "completed": true}, waits for the activation to
  answer (at most 120 s), then posts /task_state/release.
- The resources server holds its answer to the call that ended the task until
  that release, so the harness never reads it while its run could go on, and
  no model call follows the call that ended the task.
- The server refuses at startup an agent type outside ROLLOUT_STOP_AGENT_TYPES
  (the agents whose runs the stop route can end; a unit test keeps the list in
  step with the apps).

Core: RolloutStopRequest.completed; such a stop answers as completed
(report_rollout_stop) and says so in ng_rollout_stop. Docker uploads take a
bound of their own, so a stop's marker never waits for the exec slot a running
harness holds (uploads_independent_of_execs).

OfficeEnv: GET /task_state takes watch and wait_s (at most 60 s); POST
/task_state/release; task_end_hold_seconds (180) bounds the hold.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(officeenv_sandbox): the stand-in sandbox stops as main's AsyncSandbox.stop does

Main's NVIDIA-NeMo#6410 moved the shielded, bounded stop into AsyncSandbox.stop(timeout_s=...),
which LentSandboxes now calls. The tests' FakeSandbox.stop took no timeout_s and had no
shield, so a seed or close cancelled during a stop failed or hung. FakeSandbox.stop now
takes timeout_s and shields its provider-side _stop, as AsyncSandbox.stop does, and the
tests that slow down, refuse or hang a stop patch _stop.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(cline_agent): the fake sandbox session carries expire_completed

report_rollout_stop now reads SandboxSession.expire_completed (a run stopped once
its task has ended answers as completed), so the stand-in that Cline's session
tests use carries it too, as the real session does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* refactor(officeenv_sandbox): sign sessions with Gym's run secret

NVIDIA-NeMo#6161 now makes a secret per server and run in server_runtime, which every worker of the
server shares (signs_sessions_with_run_secret). The sandboxed server sets that flag instead
of minting its own secret in model_post_init and overriding get_session_secret(): its
cookies and MCP tokens are signed, as before, with a secret code in a sandbox cannot
derive from the server's name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(officeenv): refuse a tool call after the task ended with ResourcesSessionConflictError

Main's session contract (NVIDIA-NeMo#5691) has every 409 a resources server answers raise
ResourcesSessionConflictError, and tests/unit_tests/test_session_contract_repo.py
checks it. With close_tools_on_task_end, the OfficeEnv server refused a call after the
task ended with a plain HTTPException(409); it now raises the named error. The status
and the detail are the same, so callers see no change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(core): release_all stops the lent sandboxes while a lend is still starting

release_all waited for every start in flight before it stopped any lent
sandbox, all inside one time limit. One slow start at shutdown then left
every lent sandbox running until its TTL. Now the lent sandboxes stop at
once, and each starting sandbox is stopped when its start ends.

The new test fails before this change (no sandbox stopped) and passes
after it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(officeenv_sandbox): keep the agent and environment servers on 127.0.0.1

NeMo RL sets default_host to the node's address, and an explicit
default_host applies to every server, not only to the types in
absolute_ip_server_types. A sandbox's network rule opens every port of an
allowed host. So code in a sandbox could call the agent and environment
servers: run Pi on Gym's host (/v1/responses without a session), start
episodes (/run) and stop another episode's run
(/rollouts/{rollout_id}/stop).

Each harness config now sets host: 127.0.0.1 on its agent and its
environment server. No sandbox calls them: each harness in a sandbox calls
only the model server and the resources server, and NeMo RL calls /run from
the same node. Without default_host, Gym already binds them to 127.0.0.1.
The comment in officeenv_opensandbox.yaml and the README now say this.

The new config test resolves every harness config under
default_host: 10.0.0.5, on Docker and on OpenSandbox. It fails before this
change (the agent server gets 10.0.0.5) and passes after it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(officeenv_sandbox): refuse calls after the task ends for every harness

No sandboxed config set close_tools_on_task_end, though the README said
that it refuses a harness's later calls. Only Pi's environment server
stops the run at the task's end. So under Codex, OpenCode, OpenClaw,
mini-SWE and Terminus 2, a tool or file API call after complete_task could
still change what /verify grades: a late upload made a task pass.

The episodes' config, which every harness's resources server inherits, now
sets close_tools_on_task_end: true. The config test asserts the resolved
value for each harness in every composition. It fails before this change
and passes after it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* refactor(officeenv_sandbox): leave the mini-SWE pairing to a follow-up PR

The mini-SWE config ran on miniswe_sandboxed_agent, which is deprecated
for new configs in favor of mini_swe_agent's agent sessions. A follow-up
PR will add the pairing on mini_swe_agent/mini_swe_agent_sandboxed, with
one real `cli` row. This removes configs/officeenv_sandbox_miniswe.yaml,
its rows in both config tests and its mentions in the README. The other
five harness configs are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(single_agent_turn): make the task-end stop reach the agent and fail for good on 501

The stop that ends an agent's own loop at the task end now:
- goes over the reserved control connection pool, with the release, so it never waits for a connection that the
  running activation holds;
- counts its 120 s bound from the time the stop is sent, and waits for the activation also when the stop answers
  stopped: false;
- logs a warning and marks the reply (ng_task_end_stop: unconfirmed) when the activation still runs at that bound;
- fails the episode for good when the agent answers 501 (the sandbox provider cannot stop a running harness), since
  every attempt would fail the same way. 500 and 502 stay retryable.

A task that has already ended, or a lost resources session, at the first watch starts no run: the episode goes on to
verification with a reply that has no output (ng_termination_reason: task_ended_before_run).

The step loop logs a warning at startup when the driven agent sets max_steps, which it does not use.

The single_agent_turn README names bwrap among the providers that can stop a running harness, and the providers whose
stop answers 501.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(officeenv): report tool_drift for episode seeds, and document close_tools_on_task_end

An episode seed (ResourcesSeedSessionRequest) now passes the task's responses_create_params to OfficeEnv with the row,
as a seed of the whole row did through legacy_agent, so tool_drift is reported again for rows whose tools are stale.

The README no longer says that checks read every message sent after complete_task: with close_tools_on_task_end, which
this configuration turns on, such a call gets 409 and changes nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* docs(agent-server): describe completed rollout stops and the providers that can stop a running harness

The harness guide now names RolloutStopRequest.completed and the completed status it gives a stopped run, and lists
Local, bwrap, Docker and OpenSandbox with background_exec as the providers that can stop a running harness. The others
answer HTTP 501.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(officeenv_sandbox): report tool_drift for episode seeds

NVIDIA-NeMo#6162 makes the OfficeEnv server's episode seed keep the task's
responses_create_params, so tool_drift compares the row's tools with the
ones the server serves. This server overrides _new_episode with the same
task_data-only seed, so it reported no drift for an episode seed. It now
passes responses_create_params the same way.

The new test seeds a row whose first tool has a stale description. It
fails before this change (tool_drift 0.0) and passes after it (1.0).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(simple_agent): run a caller-driven step once when it is sent again

Without checkpointing, the environment server's client sends a step again after a dropped connection, and the step ran
its model call and tool calls a second time: a second email, say, while the environment recorded one reply.

A step of a session that a caller drives one step per activation (x-ng-agent-episode-step-limit) is now keyed by its
session and its activation index. A step sent again while it runs shares its run, and one sent after it answered gets
the same reply and cookies; neither calls the model or runs a tool again. The step runs apart from the request that
sent it, so a disconnect that cancels that request does not cut it short, and closing the session cancels a step that
still runs. A step older than the session's latest is refused with 409.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(agents): a run stopped as completed closes with its invocation completed

A stop with completed: true, for a run whose task ended, makes the run's response completed (report_rollout_stop), but
the harness agents record their invocation before that, as incomplete. So the same run had two statuses: completed in
its response and incomplete in its agent observations (for Prime, and for every agent in ROLLOUT_STOP_AGENT_TYPES).

The base agent's session close now applies report_completed_rollout_stop when the rollout's sandbox session ended with
a completed stop: each top-level invocation the stop left incomplete says completed, with no error type. The sandbox
observation keeps the supervisor's raw timeout, and a child invocation keeps its own status.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* docs(agent-server): a step sent again runs once, and a completed stop closes completed

The integration guide says that simple_agent runs a caller-driven step once without checkpointing, and that the
session close of a run stopped as completed reports its top-level invocation as completed. The harness guide says the
same of the close.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(simple_agent): drop a session's saved step when it closes

The close now clears the step the session kept for a step sent again, so a session never keeps it after it ends. The
docstring says why only caller-driven steps without checkpointing need it: with checkpointing, the activation tracking
already gives a repeated activation its saved reply, and any other activation is the episode's only one or a
continuation session's turn on new input.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* test(goose_agent): a stop for an ended task closes with the invocation completed

A second agent from ROLLOUT_STOP_AGENT_TYPES, besides Prime, whose close after a completed stop has the shape the base
close fixes: a top-level invocation left incomplete, which report_completed_rollout_stop marks completed, and a sandbox
observation that keeps the supervisor's timeout.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* build(officeenv_sandbox): lock against main's bumped root dependencies

CI tests this branch merged onto NVIDIA-NeMo#6162's merge ref with main. Main's NVIDIA-NeMo#6268
bumped hydra-core (>=1.4.0rc3), omegaconf (>=2.4.1rc2), mlflow and
gitpython in the root pyproject, which this server's lock includes through
nemo-gym. So `uv sync --locked` and the lock check refused this lock in CI.

This lock was made with `uv lock` on a tree shaped like CI's: this branch
merged onto NVIDIA-NeMo#6162's merge ref 5c7691f (942c31a on main 6aa1fd6).
There, `uv lock --check` and `uv sync --locked` pass, and the server's
tests pass. On this branch alone, `uv lock --check` fails until NVIDIA-NeMo#6162
contains main, because the branch still has the older root pyproject. The
lock is the one that is right once NVIDIA-NeMo#6162 has main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(single_agent_turn): keep task-end watches and stops progressing

Signed-off-by: yaoyu-33 <[email protected]>

* fix(officeenv_sandbox): bind sandboxless services to loopback

Signed-off-by: yaoyu-33 <[email protected]>

* fix(pi): report task-end stops after classifying the invocation

Signed-off-by: yaoyu-33 <[email protected]>

* chore(officeenv_sandbox): add the test package license header

Signed-off-by: yaoyu-33 <[email protected]>

---------

Signed-off-by: Daniele Molinari <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Yi-Fu Wu <[email protected]>
Co-authored-by: yaoyu-33 <[email protected]>
d-molinari added a commit that referenced this pull request Nov 30, 2026
…eep the secret from sandboxes

A restart replaces the run's secret, so the cookies and MCP tokens a server signed before it no
longer decode. A resources server or agent that signs with it (signs_sessions_with_run_secret, or
mcp_bearer_token) now takes part in partial-rollout checkpoints as restart_only whatever it
declares, with one warning: a restored session could not be reached, so its episodes start over
after a crash instead of verifying on an empty session. The mcp_bearer_token description,
get_session_secret, checkpoint_mode_in_effect and participant_workers.py say so.

The secret lives in the server's environment, which every process it starts inherits. The
Apptainer and local providers now leave the run-secret variables out of the environment they pass
to sandboxed code (nemo_gym.core.run_session_secrets, which both packages may import). The
get_session_secret docstring and the MCP tutorial state the guarantee's limit: code that shares
the server's user and the host's process table (the local provider's, or Apptainer's without
--containall) can still read a multi-worker server's secret from its workers' environment.

Addresses the review notes on #6161 about the run secret and checkpoint restore, and about its
inheritance in Apptainer and local sandboxes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>
d-molinari added a commit that referenced this pull request Nov 30, 2026
…ialize reports

Pi shows the model <name>_<tool>, as OpenCode does (gym_mcp.mjs); mcp__<name>__<tool> is what Gym
records for Pi's calls, and what mini-SWE uses. The single_agent_turn README, the
_check_mcp_server_names docstring and the mcp_server_name comment now say so, and the README names
only the agents that refuse names that collide in their own naming (OpenCode and Pi). The MCP
tutorial no longer says the deprecated sandboxed agents' tool_servers entries carry
mcp_server_name: since 19ab60f they keep the server's reference name.

test_bearer_token_and_advertised_name_present_an_ordinary_endpoint now checks that initialize
introduces the endpoint under mcp_server_name, so reverting mcp_auto_exposure to the config name
fails it.

Addresses the review notes on #6161 about the naming docs and the serverInfo.name test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>
yaoyu-33 added a commit to yaoyu-33/Gym that referenced this pull request Dec 1, 2026
…ion to keep the recorded history (NVIDIA-NeMo#6672)

* feat(core): session secrets, cookie names and MCP endpoint options for servers that sandboxed code calls

A resources server that lends a sandbox is reached by code the model controls, so the session key that every
caller can compute from the server's class and name must not sign its cookies and MCP tokens, and its endpoint
should look like an ordinary one.

- SimpleServer.get_session_secret() signs session cookies and MCP session tokens (default: the session middleware
  key, so nothing changes). Session routing reads cookies and tokens with it. Its docstring states what an
  override must keep: one secret in every worker, and a secret that changes ends every open session.
- SimpleServer.get_session_cookie_name() names the session cookie (default: the same key).
- mcp_server_name: the name the MCP endpoint lists itself under; verify-time normalization strips its namespace.
- mcp_bearer_token: tokens ride as Authorization: Bearer, tools/list needs one and lists only the session's tools,
  a tool outside the grant is an unknown tool, and errors name no framework.
- Both options are refused without expose_tools_over_mcp, and a name outside MCP's tool-name alphabet is refused.
  A single_agent_turn pairing refuses to grant two MCP endpoints listed under one name.

Signed-off-by: Daniele Molinari <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(server_runtime): honor mcp_server_name end to end and refuse bearer tokens without a secret

Review fixes for the MCP endpoint options.

- mcp_server_name is also checked against the name pattern of an MCP grant (MCP_TOOL_ACCESS_NAME_PATTERN in
  tool_access, which MCPToolAccess uses), so a name that an Environment Server cannot grant, one that starts with
  '_' or '-', is refused at config instead of failing every episode before the agent seed. The grant contract is
  unchanged. A dot stays refused: Pi's MCP adapter and Codex refuse server names outside [A-Za-z0-9_-].
- seed_mcp_servers keys each entry by the seed metadata's server_name, else the server's name, and refuses two
  servers listed under one name. URLs, headers and routing still use the server's reference. The sandboxed
  OpenCode agent's required-server list uses the same keys; the sandboxed Pi agent reads them as given.
- An MCP endpoint with mcp_bearer_token refuses to start while get_session_secret() is the public session
  middleware key, since code that reads one bearer token could sign another session's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* revert(agents): keep MCP endpoint names off the legacy seeder

Review asked to keep the MCP changes on the agent-session path. The only callers of
seed_mcp_servers, the sandboxed Pi and OpenCode agents, run on the agent-owned /run path
that #5222 deprecates, and OfficeEnv's Pi preset gets the advertised name and headers
through its MCPToolAccess grant. The seeder keys its entries by server name again, and
the aliasing's tests go with it. It no longer refuses two servers under one name, a
refusal that came after the primary server may have started a task sandbox and before
OpenCode's cleanup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(opencode_agent): refuse MCP grants whose tools OpenCode could name alike

Review found that distinct endpoint names can still hide a tool in opencode_agent.
OpenCode keys each MCP tool <grant>_<tool>, writing characters outside [a-zA-Z0-9_-]
as '_', and a later tool under a key already taken replaces the earlier one without a
word: `company` serving `files_list` and `company_files` serving `list` both register
`company_files_list`. The agent's seed now refuses two MCP grants whose tools could
share a key, which the grant names decide: equal once written as OpenCode writes them,
or one the other followed by '_'. single_agent_turn's README and check, and the
mcp_server_name field, describe tool naming as each harness's own.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(server_runtime): sign sessions with a secret made for the run

Review asked for per-run session secrets in server_runtime, as episode_token_secret()
does (#5346), instead of each server overriding get_session_secret().
run_session_secret(name) makes one secret per server for the run and keeps it in the
environment, so the workers uvicorn starts after the main process built the server
inherit it. get_session_secret() returns it when the server sets
signs_sessions_with_run_secret or its config sets mcp_bearer_token, so bearer tokens work
from YAML alone and with any number of workers; otherwise it is the public key, as before.
The session_secret property resolves it once per server (a cached_property, so it holds
for a server built without its model_post_init too), and the session middleware, session
routing and the MCP endpoint all read it there, so an override that answers differently
from call to call cannot split them. Exposure still refuses bearer tokens signed with the
public key, which only an override can now produce.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(single_agent_turn): drive the agent one step at a time and end the episode on the task state

A resources server whose task ends through its state, rather than through one tool's call, can now have its
episode end right after the step that ended the task. OfficeEnv's task ends when its user app's task row leaves
pending, which several operations reach, depending on how a row exposes its apps.

- single_agent_turn: max_episode_steps drives the agent one step per activation, up to that many steps, and
  end_on_task_state reads the resources session's task state between steps (GET /task_state, ResourcesTaskState
  in nemo_gym.server_runtime). Each step's failure report is kept. The server checks at startup that its agent keeps
  a session, runs the tools it calls and stops after one step. Driven episodes take part in checkpoints as restarts
  (BaseEnvironmentServer.checkpoint_mode_in_effect).
- simple_agent: with x-ng-agent-episode-step-limit, a step stopped by its own one-step limit counts as completed
  unless it is the episode's last, and the session keeps one invocation for the episode, as the agent's own loop
  does, instead of one per step that repeats the whole history.
- OfficeEnv: GET /task_state answers ResourcesTaskState; close_tools_on_task_end refuses the calls a step makes after
  the one that ended its task; its rows route by taskset to single_agent_turn with the step loop on, and the config
  allows only the simple agent. A retired attempt no longer keeps its episode, so its replacement can seed the same
  session ID. The server runs OfficeEnv 1.14.0 (1.13.0 at least), with its example rows emitted again.

Signed-off-by: Daniele Molinari <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(single_agent_turn): run the step loop's tests in the core suite, and keep a simple_agent subclass in step

CI on the step loop found two things:
- agentic_turn_simulation_agent overrides simple_agent's _create_episode, which now takes
  step_limit_owned_by_caller. The override accepts it; only an agent session sets it, and this agent
  refuses those.
- The core coverage gate counts single_agent_turn's and simple_agent's app.py, but the step loop's tests
  ran in the server suite only. They move to the core suite unchanged, and simple_agent's step limit and
  invocation folding get core tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(single_agent_turn): import each name in the moved step-loop tests from the module that defines it

Tests under tests/ import from the defining module, not a package's public API, and
test_the_librarys_tests_import_from_the_module_that_defines_each_name failed on the two files this PR moved
into the core suite.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(simple_agent): one step per activation that names the episode's step limit, counted by its index

With x-ng-agent-episode-step-limit, the agent takes one step (one model call and the tool calls it makes) whatever
its max_steps says, so a pairing no longer needs max_steps: 1, which composition drops when --agent-type
simple_agent replaces the environment's agent. Requests without the header run as before.

- The step is the activation's index (x-ng-agent-activation), which such a caller sends with every step, not the
  count of requests, so a step resent after a dropped connection is not counted as the next one.
- The session keeps the model server's cookies from step to step, so the episode keeps one model server session.
- A step that raises ends the episode's folded invocation as failed (or incomplete when cancelled), not with the
  completed status of the step before.
- The step keywords go to _create_episode only with the header, so an override that predates them keeps working;
  agentic_turn_simulation_agent's override no longer needs to accept one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(single_agent_turn): drive only agents that take one step per activation, and keep what the steps did

- STEP_DRIVEN_AGENT_TYPES (nemo_gym.config, beside AGENT_SESSION_AGENT_TYPES) lists the agent types that take one
  step per activation that names the episode's step limit: simple_agent. The startup check refuses any other type,
  such as hermes_agent or browsecomp_agent, which keep a session but run their own loop in an activation; a unit
  test keeps the list in step with the agent apps. The check no longer reads max_steps, and reads execute_tools as
  the agent's config does, so a string "false" is false.
- A failure after a step completed keeps the completed steps, their output and summed usage, as its partial
  response, unless it already carries one; a failure before the first reply has none.
- An episode that runs out of steps with every step calling a tool says so in its reply's metadata
  (ng_termination_reason: max_episode_steps). Its status stays the last step's: incomplete_details names only the
  model's own cutoffs, and an incomplete reply would read as malformed to rollout recovery.
- The task state is not read after the last step, which ends the episode either way.
- GET /task_state answering 404 with failure_kind session_lost ends the episode, which goes on to /verify and its
  masked lost-session result, as when a tool call finds the session gone. Other failed reads fail the episode as
  before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(server_runtime): an environment server's checkpoint mode in effect sets its participant and its episodes

A server whose class declares exported but whose instance runs as restart_only installs a restart_only participant,
and its episodes begin as restarts; an unknown mode in effect stops the server at setup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(officeenv): run on single_agent_turn_legacy, so flat rows and session-less agents run too

single_agent_turn's /run takes only episode requests, so flat rows (training corpora, rows routed by their agent)
failed. single_agent_turn_legacy takes flat rows and taskset episodes, and runs the same step loop: OfficeEnv keeps
max_episode_steps 50, end_on_task_state, direct HTTP tools and the example taskset's route, and the simple agent no
longer sets max_steps: 1. Composition's fallback relays an agent without agent sessions through legacy_agent to its
own /run, so allowed_agents also admits simple_agent_with_compaction; the relay takes flat rows, not the taskset's
episodes.

The test that restated the YAML (skipped in CI with OfficeEnv absent) gives way to core tests that resolve the
config with a model and build its environment server: as shipped, with simple_agent.yaml added as --agent-type
simple_agent does, and with the compaction agent's config, where the server becomes a legacy_agent relay. The config
comment and README say what --agent-type and allowed_agents do, and that rollout_recovery.target_level: sibling
applies to the whole training run.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* docs: GET /task_state and the episode step-limit header

The Seed/Verify Protocol Extensions table lists GET /task_state, its reply, and what a 404 or 5xx does to the
episode. The agent integration page describes x-ng-agent-episode-step-limit beside x-ng-agent-activation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(single_agent_turn): stop an agent's own loop once its task has ended

With end_on_task_state and no max_episode_steps, single_agent_turn now ends an
agent that runs its own loop (a sandboxed harness) at its task's end, as the
step loop ends a step-driven one:

- Before the agent runs it reads GET /task_state?watch=true; while the agent
  runs it reads again, each read waiting up to 30 s (wait_s).
- Once the task has ended it stops the run with POST /rollouts/{id}/stop
  {"reason": "task_ended", "completed": true}, waits for the activation to
  answer (at most 120 s), then posts /task_state/release.
- The resources server holds its answer to the call that ended the task until
  that release, so the harness never reads it while its run could go on, and
  no model call follows the call that ended the task.
- The server refuses at startup an agent type outside ROLLOUT_STOP_AGENT_TYPES
  (the agents whose runs the stop route can end; a unit test keeps the list in
  step with the apps).

Core: RolloutStopRequest.completed; such a stop answers as completed
(report_rollout_stop) and says so in ng_rollout_stop. Docker uploads take a
bound of their own, so a stop's marker never waits for the exec slot a running
harness holds (uploads_independent_of_execs).

OfficeEnv: GET /task_state takes watch and wait_s (at most 60 s); POST
/task_state/release; task_end_hold_seconds (180) bounds the hold.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(cline_agent): the fake sandbox session carries expire_completed

report_rollout_stop now reads SandboxSession.expire_completed (a run stopped once
its task has ended answers as completed), so the stand-in that Cline's session
tests use carries it too, as the real session does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(officeenv): refuse a tool call after the task ended with ResourcesSessionConflictError

Main's session contract (#5691) has every 409 a resources server answers raise
ResourcesSessionConflictError, and tests/unit_tests/test_session_contract_repo.py
checks it. With close_tools_on_task_end, the OfficeEnv server refused a call after the
task ended with a plain HTTPException(409); it now raises the named error. The status
and the detail are the same, so callers see no change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(core): LentSandboxes lends a sandbox with its own image, environment and setup, and releases all within a deadline

What the OfficeEnv sandboxed server needs from core's lent sandboxes, so it builds on them instead of a copy:

- lend() takes a per-sandbox image, more environment variables and a setup that runs against the started sandbox,
  its files delivered, before it is lent (start_with_setup); a setup that fails stops the sandbox.
- The start runs to its end once begun, within start_timeout_s (30 minutes by default), even while the request that
  asked for it is cancelled: a create cut in flight leaves a sandbox whose id the provider never returned. A lend
  cancelled meanwhile lends nothing and stops what it started, and says so in the log.
- release_all(timeout_s=...) refuses new lends (503) from its start, waits for those still starting, stops everything
  within the deadline, and returns and logs the sessions whose sandbox may still run, for a reaper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(officeenv): run OfficeEnv episodes in a sandbox, for Gym's sandboxed harnesses

resources_servers/officeenv_sandbox's OfficeEnvSandboxResourcesServer subclasses the OfficeEnv server and lends each
episode session a sandbox through LentSandboxes (an operate descriptor: the harness uses it, only the server stops
it), stopped before the episode is graded.

- The harness reaches the apps as the row's exposure says: MCP tools, a command per app (cli), or endpoints it finds
  over MCP and calls with curl (api_search).
- File content stays out of the conversation through OfficeEnv's workspace mode: downloads land in the workspace,
  uploads and attachments name a workspace file, and a file API moves bytes directly.
- The sandbox sees an ordinary company API. Only Gym's servers on this node (any of the node's own addresses) and
  trusted_networks reach seeding, closing, verification, metrics, the reverify mode, the app catalog, the task state
  and the tool routes, which answer others 404 before reading a body; sessions are signed with a per-process secret.
- Seeds take turns, and a seed is admitted again before it lends; a close or a retire stops the sandbox, a failed
  seed's stop is tried again at its session's close, and shutdown stops everything within the run's grace.
- A sandbox provider failure fails the call (502) and masks the episode's reward.
- Configs for Pi (Docker and OpenSandbox), Codex CLI, mini-SWE, OpenCode, OpenClaw and Terminus 2; nine sandbox tasks
  (OfficeEnv 1.14.0), the first five as example rows with Pi's rollouts of them; images and a README.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(core): LentSandboxes logs a start its limit cut before the provider returned the sandbox's id

When start_timeout_s cuts a provider's create in flight, the sandbox's id is unknown, so the lend's stop cannot reach
what the create left. The lend now logs that cut at ERROR with the resources session, the task (id and taskset), the
provider, the image and the labels, so a reaper can find the sandbox. A start cut after the create returned stops its
sandbox as before and asks for no reaper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* refactor(officeenv_sandbox): name each harness's instances after it, so harness configs compose in one run

Every harness config defined `oe` and `single_agent_turn_legacy`, so two of them could not run together. Now:

- the episodes' resources server is officeenv_sandbox_resources_server;
- each config adds officeenv_sandbox_<harness>_agent (`_inherit_from` Gym's instance of the harness, as benchmarks do)
  and officeenv_sandbox_<harness>_environment_server (`_inherit_from: single_agent_turn_legacy`);
- Pi, Codex and OpenCode, which name MCP tools their own way, run on their own copy of the episodes' server
  (officeenv_sandbox_<harness>_resources_server, `_copy` with its mcp_tool_prefix); the other harnesses run on the
  shared one. A copy takes the shared server's settings from the merged config, so one override reaches every harness.

The interpolations, the documented overrides, the probe script and the README follow (a table of the names; the
OpenSandbox config is listed after the other harness configs, since a later one pulls the episodes' config in again).
A core test resolves each config alone and all six together with a model config, and replaces the server test that
restated their YAML; it needs no OfficeEnv, so it runs in CI. The OpenCode and OpenClaw configs and the README no
longer say those harnesses refuse MCP tool grants.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(officeenv_sandbox): sandbox_config.start_timeout_s bounds a sandbox's start; host_relay needs trusted_workstation

- sandbox_config.start_timeout_s (1800 s by default, a finite number above 0) is passed to LentSandboxes, which fails
  the seed at that limit and logs a create it cut for a reaper. The README says when to raise it: creates on a busy
  OpenSandbox cell have taken up to 2,430 s.
- host_relay forwards sandbox connections from the host's loopback, which the caller check takes for Gym's own
  servers, so code in a sandbox could call the routes kept for Gym for any session. Config validation now refuses
  host_relay unless sandbox_config.trusted_workstation is true, which a config sets only on a single-user workstation;
  its description and the README state the risk.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(officeenv_sandbox): officeenv_sandboxless.yaml runs the OfficeEnv server's instances under names of their own

It composes resources_servers/officeenv/configs/officeenv.yaml and copies (`_copy`) its three instances as
officeenv_sandboxless_resources_server, officeenv_sandbox_simple_agent and officeenv_sandbox_environment_server, each
copy pointing at the other copies, while the OfficeEnv server's instances keep their names. The copied agent declares
no dataset, so the example rows and their taskset stay with the OfficeEnv server's instances, and rows that name
officeenv_sandbox_simple_agent (flat rows, agent_ref) route to the copied environment server.

A `_copy` takes its source as written, before the source's own `_inherit_from` applies, so the environment server is
copied as the instance of the server type officeenv_environment_server inherits, with that server's own settings for
it on top. The core test checks each copy against its source, references aside, alone and beside the Pi and Codex
configs, so a change to the source's server type fails it rather than leaving the copy behind.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(officeenv_sandbox): the sandboxless arm copies single_agent_turn_legacy, which the OfficeEnv server now runs

officeenv_environment_server inherits single_agent_turn_legacy now, so the copy takes that instance, then the server's
own settings for it under that type, with its references still pointing at the other copies.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* refactor(officeenv_sandbox): every harness runs the episodes' server under its own name, so none is left idle

Each harness config now adds officeenv_sandbox_<harness>_resources_server with `_inherit_from:
officeenv_sandbox_resources_server`, OpenClaw, mini-SWE and Terminus 2 included, and no harness names the episodes'
server. `_inherit_from` reads it from the merged config and takes it out of the run, so a run of one or several
harness configs starts no idle episodes' server, while the episodes config alone still runs it under its own name.
Settings on the episodes' server, the OpenSandbox config's included, reach every harness's server. The OpenSandbox
config still goes after the other harness configs (the first harness config listed pulls the episodes' config in),
and the README now says why. The core test checks that no episodes' server starts or is named beside the harnesses',
alone and with all six, and that the episodes config runs on its own.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(core): the cut-start log says OpenSandbox deletes what an abandoned create left

Main's OpenSandbox provider now deletes the sandbox of a create its caller gave up on (#4799), so
a start that LentSandboxes' start_timeout_s cuts before the provider returned the sandbox's id no
longer needs a reaper there. The ERROR log, LentSandboxes' docstring and the officeenv_sandbox
README now say so, and keep the reaper for providers without that cleanup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(officeenv_sandbox): Pi's run ends once its task has ended, on every exposure

- The sandboxed server holds the call that ends a watched episode's task, on
  every way in (tools, commands, endpoints, the file API), until the
  environment server releases it; the episode's lock is let go first. Only
  Gym's node reaches GET /task_state and POST /task_state/release.
- Pi supports POST /rollouts/{rollout_id}/stop (_rollout_sandbox_session): a
  run stopped as completed answers so, marked in ng_rollout_stop, and is not
  reported as a wall-time timeout.
- The Pi config sets end_on_task_state on its environment server and drops
  finish_tool_names (now []): the stop ends the run on cli and api_search rows
  too, which offer no finish tool. Its comment no longer asks cli rows to drop
  the MCP transport, which they run with as it is.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* docs(officeenv): the servers run OfficeEnv 1.14.2

1.14.2 is the OfficeEnv release N4's training runs grade with. 1.14.1 and
1.14.2 are patch releases; neither changes the API these servers use. The
READMEs' install lines name it, and the example rows are emitted again by it
(officeenv emit for resources_servers/officeenv, sandbox/prepare_rows.py for
officeenv_sandbox), which changed only their version stamp. The example
rollouts stay the ones collected against 1.14.0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(officeenv_sandbox): refuse calls after the task ended with ResourcesSessionConflictError

Main's session contract (#5691) has every 409 a resources server answers raise
ResourcesSessionConflictError, and tests/unit_tests/test_session_contract_repo.py
checks it. The sandboxed server refused a tool call once verification began, and a
file API call once the episode's files closed, with plain HTTPException(409)s; both
now raise the named error. The status and the detail are the same, so callers see no
change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(core): LentSandboxes shields a start only with start_timeout_s

Main's opencode_search (#6211) lends through LentSandboxes and expects a seed cancelled
while its sandbox starts to stop that sandbox at once, as LentSandboxes did before this
branch; the shielded start made it wait for the start's end. The shield is now opt-in.
Without start_timeout_s a cancel cuts the start as it cuts any await, as on main, and the
lend stops the sandbox it began. With it, the start runs to its end within that limit,
which the OfficeEnv sandbox server sets (sandbox_config.start_timeout_s, 1,800 s by
default). START_TIMEOUT_S goes, since no default limit remains.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* build(officeenv_sandbox): lock against main's upgraded dependency locks

Main's lock upgrade (#6528) moved the root lock, and `uv sync --locked` refused the
sandboxed server's older lock, so neither its suite nor a run could start it. `uv lock`
with uv 0.13.4 takes the root lock's versions (e2b 2.50.0, protobuf-py 0.1.1, pyqwest
0.10.0), keeps the tzdata OfficeEnv pins (2026.6), and passes scripts/component_locks.py.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(core): a cut start's test counts the closes the provider made

Main's #6410 changed the stopped fixture from AsyncSandbox.stop calls to the closes the
provider made. A start cut before the provider returned its sandbox's id leaves nothing
to close, so the hung-start test now expects none, as the ERROR line it checks says.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(officeenv_sandbox): the stand-in sandbox stops as main's AsyncSandbox.stop does

Main's #6410 moved the shielded, bounded stop into AsyncSandbox.stop(timeout_s=...),
which LentSandboxes now calls. The tests' FakeSandbox.stop took no timeout_s and had no
shield, so a seed or close cancelled during a stop failed or hung. FakeSandbox.stop now
takes timeout_s and shields its provider-side _stop, as AsyncSandbox.stop does, and the
tests that slow down, refuse or hang a stop patch _stop.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* refactor(officeenv_sandbox): sign sessions with Gym's run secret

#6161 now makes a secret per server and run in server_runtime, which every worker of the
server shares (signs_sessions_with_run_secret). The sandboxed server sets that flag instead
of minting its own secret in model_post_init and overriding get_session_secret(): its
cookies and MCP tokens are signed, as before, with a secret code in a sandbox cannot
derive from the server's name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(stirrup_agent): stop a run once its task has ended, and run Stirrup on OfficeEnv's sandboxed episodes

Stirrup could not be stopped in flight, so single_agent_turn's end_on_task_state refused it and OfficeEnv's
sandboxed episodes had no Stirrup harness:

- stirrup_agent returns its sandbox session for a rollout stop (_rollout_sandbox_session) and marks the run a
  stop ended (report_rollout_stop): a stop once the task has ended answers as completed, with ng_rollout_stop and
  without the deadline's stop_reason. stirrup_agent joins ROLLOUT_STOP_AGENT_TYPES.
- The runner, ended by its supervisor while a turn's tool calls run, reports that turn's reply too (its calls
  without answers) rather than the history as of the turn's start. A stop once the task has ended lands so: the
  call that ended the task waits for its answer until the run is over, and it stays the run's last item, as Pi's
  does.
- resources_servers/officeenv_sandbox/configs/officeenv_sandbox_stirrup.yaml: Stirrup on `cli` rows, under the
  harness configs' names (officeenv_sandbox_stirrup_agent, _environment_server, _resources_server), no MCP
  transports, end_on_task_state, admitted episodes capped at Stirrup's concurrency.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* feat(stirrup_agent): options to keep the run's history as it was recorded

Training on recorded tokens needs one unbroken history per episode, and Stirrup's defaults rewrite it: past 0.7 of
the context window it replaces the history with a summary, and on a context overflow it unwinds completed turns.
Two options keep those defaults and let a training config turn them off:

- context_summarization_cutoff (default 0.7, Stirrup's): None never summarizes, so an episode at the context limit
  ends there;
- recover_from_context_overflow (default true, Stirrup's): false raises instead of unwinding.

The runner passes them to Stirrup's agent; a payload without them keeps Stirrup's defaults.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* test(officeenv_sandbox): cover the Stirrup harness config in the core config tests

The server's own config tests skip without OfficeEnv, and CI does not install OfficeEnv. The core config tests
resolve each harness config without it, so they now include officeenv_sandbox_stirrup.yaml. The tests make sure
that its instances carry Stirrup's name, that it composes beside the other harness configs with its own cap of 32,
and that its environment server stops the run once the task has ended.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* docs(stirrup_agent): describe rollout stops and the history options

The README now says how a rollout stop ends a Stirrup run and what the response carries. A run that ends while a
turn's tool calls run ends with that turn's reply. The options table lists context_summarization_cutoff and
recover_from_context_overflow, and a new section names the settings that keep the recorded history for training.

With context_overflow_recovery off, its default, the client never reports an overflow to Stirrup. So
recover_from_context_overflow changes a run only when a config also turns context_overflow_recovery on.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(stirrup_agent): keep a compaction summary out of a stopped run's output

The runner kept the last reply of every model call, a compaction summary's included. A summary can carry tool
calls, since its first attempts offer the tools. If the run then ended while the next policy call waited for the
model, the runner added the summary and its calls to the output as the running turn, although those calls never ran.

The runner now keeps only the reply of the policy turn that is running. Each model call clears the reply first, and
a reply made during a compaction is never kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(stirrup_agent): answer a stop that arrives before the runner starts

A rollout stop accepted during the seed or before the activation keeps the supervisor from launching the runner.
The runner then writes no output.json, so the activation failed with "Stirrup sandbox runner exited without
output", although the agent server had answered the stop as stopped.

When the session reports an expiry before launch, the runner's report is now an empty run that ended at its time
limit, with the session's cookies. The agent server then marks the stop and gives the status the stop asked for, as
for a run that a stop ended. Missing output from a runner that did launch still fails the activation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(stirrup_agent): report the live turn of a run stopped around a compaction

The previous commit kept no summary reply, but a run cut during a compaction still lost its last turn. Stirrup takes
its history snapshot at the start of each turn and summarizes after the turn has answered. So during a summary
request, the snapshot does not hold the turn that just ran, and the output was empty or ended with that turn's call
without its answer.

The runner now watches Stirrup's step, as it watches summarize_messages. It keeps the message list that step gets,
which Stirrup extends with the answered turn, and keeps a reply only when its request is that list and only while
step runs. On a cut, it reports that live list and the running turn's reply. A summary request sends a new list, so
its reply is never kept. The test covers a cut after a summary, in the second summary attempt and in the first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(stirrup_agent): answer a stop that ends the runner while it starts

The runner installs its SIGTERM handler only after its imports. A rollout stop in that window ends the runner
before it writes its report, and the activation still failed with "Stirrup sandbox runner exited without output".

collect now also returns the empty stopped report when the session expired (a stop that the supervisor acted on)
and the runner left no output file. A runner that crashed, or a deadline that ended it with no stop, still fails
the activation. The report helper is now _stopped_without_output, since it covers both windows.

Tests: a stop after the seed and before the run answers as an empty stopped run with no observation gaps. A runner
that never gets past its start answers as an empty stopped run when a stop ended it, and fails when its deadline
did.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* refactor(stirrup_agent): drop recover_from_context_overflow

Stirrup reads this option only when the client raises ContextOverflowError, and the client raises it only with
context_overflow_recovery on. With that option off, its default, Stirrup drops no turn whatever this option says.
With it on and this option false, the episode ends at the first overflow, as it does with context_overflow_recovery
off. So the option added no behavior, and a training config needs only context_summarization_cutoff: null.

This removes the field, its payload key, the runner argument, its README row and paragraph, and its test cases.
Draft #5835 adds the same option. No release has it, so no removed-option entry is needed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(stirrup_agent): bound context_summarization_cutoff at 1

Stirrup compares the cutoff with the last call's tokens divided by the context window, and it does not reject a
value above 1. Such a value fires only when one call uses more tokens than the window. So a percent such as 70
turned compaction off with no error. The field now accepts values above 0 and at most 1, and null still never
summarizes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* docs(stirrup_agent): name the other history rewrites, and fix the Stirrup config's network note

The Stirrup README section on keeping the recorded history now also names truncation_recovery, which sends one call
with an instruction that the history never records. It also names the two rewrites that stay: an assistant turn
with no parsed tool call loses its tool-call text, and reasoning that comes back in its own field is not sent back.

The header of officeenv_sandbox_stirrup.yaml said that Stirrup's sandboxes need the package index. The agent server
builds Stirrup's Python runtime on its own host and uploads it, so the sandboxes need no internet. Only the host
needs the package index.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* feat(single_agent_turn): drive the agent one step at a time and end the episode on the task state

A resources server whose task ends through its state, rather than through one tool's call, can now have its
episode end right after the step that ended the task. OfficeEnv's task ends when its user app's task row leaves
pending, which several operations reach, depending on how a row exposes its apps.

- single_agent_turn: max_episode_steps drives the agent one step per activation, up to that many steps, and
  end_on_task_state reads the resources session's task state between steps (GET /task_state, ResourcesTaskState
  in nemo_gym.server_runtime). Each step's failure report is kept. The server checks at startup that its agent keeps
  a session, runs the tools it calls and stops after one step. Driven episodes take part in checkpoints as restarts
  (BaseEnvironmentServer.checkpoint_mode_in_effect).
- simple_agent: with x-ng-agent-episode-step-limit, a step stopped by its own one-step limit counts as completed
  unless it is the episode's last, and the session keeps one invocation for the episode, as the agent's own loop
  does, instead of one per step that repeats the whole history.
- OfficeEnv: GET /task_state answers ResourcesTaskState; close_tools_on_task_end refuses the calls a step makes after
  the one that ended its task; its rows route by taskset to single_agent_turn with the step loop on, and the config
  allows only the simple agent. A retired attempt no longer keeps its episode, so its replacement can seed the same
  session ID. The server runs OfficeEnv 1.14.0 (1.13.0 at least), with its example rows emitted again.

Signed-off-by: Daniele Molinari <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(single_agent_turn): run the step loop's tests in the core suite, and keep a simple_agent subclass in step

CI on the step loop found two things:
- agentic_turn_simulation_agent overrides simple_agent's _create_episode, which now takes
  step_limit_owned_by_caller. The override accepts it; only an agent session sets it, and this agent
  refuses those.
- The core coverage gate counts single_agent_turn's and simple_agent's app.py, but the step loop's tests
  ran in the server suite only. They move to the core suite unchanged, and simple_agent's step limit and
  invocation folding get core tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(single_agent_turn): import each name in the moved step-loop tests from the module that defines it

Tests under tests/ import from the defining module, not a package's public API, and
test_the_librarys_tests_import_from_the_module_that_defines_each_name failed on the two files this PR moved
into the core suite.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(simple_agent): one step per activation that names the episode's step limit, counted by its index

With x-ng-agent-episode-step-limit, the agent takes one step (one model call and the tool calls it makes) whatever
its max_steps says, so a pairing no longer needs max_steps: 1, which composition drops when --agent-type
simple_agent replaces the environment's agent. Requests without the header run as before.

- The step is the activation's index (x-ng-agent-activation), which such a caller sends with every step, not the
  count of requests, so a step resent after a dropped connection is not counted as the next one.
- The session keeps the model server's cookies from step to step, so the episode keeps one model server session.
- A step that raises ends the episode's folded invocation as failed (or incomplete when cancelled), not with the
  completed status of the step before.
- The step keywords go to _create_episode only with the header, so an override that predates them keeps working;
  agentic_turn_simulation_agent's override no longer needs to accept one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(single_agent_turn): drive only agents that take one step per activation, and keep what the steps did

- STEP_DRIVEN_AGENT_TYPES (nemo_gym.config, beside AGENT_SESSION_AGENT_TYPES) lists the agent types that take one
  step per activation that names the episode's step limit: simple_agent. The startup check refuses any other type,
  such as hermes_agent or browsecomp_agent, which keep a session but run their own loop in an activation; a unit
  test keeps the list in step with the agent apps. The check no longer reads max_steps, and reads execute_tools as
  the agent's config does, so a string "false" is false.
- A failure after a step completed keeps the completed steps, their output and summed usage, as its partial
  response, unless it already carries one; a failure before the first reply has none.
- An episode that runs out of steps with every step calling a tool says so in its reply's metadata
  (ng_termination_reason: max_episode_steps). Its status stays the last step's: incomplete_details names only the
  model's own cutoffs, and an incomplete reply would read as malformed to rollout recovery.
- The task state is not read after the last step, which ends the episode either way.
- GET /task_state answering 404 with failure_kind session_lost ends the episode, which goes on to /verify and its
  masked lost-session result, as when a tool call finds the session gone. Other failed reads fail the episode as
  before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(server_runtime): an environment server's checkpoint mode in effect sets its participant and its episodes

A server whose class declares exported but whose instance runs as restart_only installs a restart_only participant,
and its episodes begin as restarts; an unknown mode in effect stops the server at setup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(officeenv): run on single_agent_turn_legacy, so flat rows and session-less agents run too

single_agent_turn's /run takes only episode requests, so flat rows (training corpora, rows routed by their agent)
failed. single_agent_turn_legacy takes flat rows and taskset episodes, and runs the same step loop: OfficeEnv keeps
max_episode_steps 50, end_on_task_state, direct HTTP tools and the example taskset's route, and the simple agent no
longer sets max_steps: 1. Composition's fallback relays an agent without agent sessions through legacy_agent to its
own /run, so allowed_agents also admits simple_agent_with_compaction; the relay takes flat rows, not the taskset's
episodes.

The test that restated the YAML (skipped in CI with OfficeEnv absent) gives way to core tests that resolve the
config with a model and build its environment server: as shipped, with simple_agent.yaml added as --agent-type
simple_agent does, and with the compaction agent's config, where the server becomes a legacy_agent relay. The config
comment and README say what --agent-type and allowed_agents do, and that rollout_recovery.target_level: sibling
applies to the whole training run.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* docs: GET /task_state and the episode step-limit header

The Seed/Verify Protocol Extensions table lists GET /task_state, its reply, and what a 404 or 5xx does to the
episode. The agent integration page describes x-ng-agent-episode-step-limit beside x-ng-agent-activation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(core): LentSandboxes lends a sandbox with its own image, environment and setup, and releases all within a deadline

What the OfficeEnv sandboxed server needs from core's lent sandboxes, so it builds on them instead of a copy:

- lend() takes a per-sandbox image, more environment variables and a setup that runs against the started sandbox,
  its files delivered, before it is lent (start_with_setup); a setup that fails stops the sandbox.
- The start runs to its end once begun, within start_timeout_s (30 minutes by default), even while the request that
  asked for it is cancelled: a create cut in flight leaves a sandbox whose id the provider never returned. A lend
  cancelled meanwhile lends nothing and stops what it started, and says so in the log.
- release_all(timeout_s=...) refuses new lends (503) from its start, waits for those still starting, stops everything
  within the deadline, and returns and logs the sessions whose sandbox may still run, for a reaper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(officeenv): run OfficeEnv episodes in a sandbox, for Gym's sandboxed harnesses

resources_servers/officeenv_sandbox's OfficeEnvSandboxResourcesServer subclasses the OfficeEnv server and lends each
episode session a sandbox through LentSandboxes (an operate descriptor: the harness uses it, only the server stops
it), stopped before the episode is graded.

- The harness reaches the apps as the row's exposure says: MCP tools, a command per app (cli), or endpoints it finds
  over MCP and calls with curl (api_search).
- File content stays out of the conversation through OfficeEnv's workspace mode: downloads land in the workspace,
  uploads and attachments name a workspace file, and a file API moves bytes directly.
- The sandbox sees an ordinary company API. Only Gym's servers on this node (any of the node's own addresses) and
  trusted_networks reach seeding, closing, verification, metrics, the reverify mode, the app catalog, the task state
  and the tool routes, which answer others 404 before reading a body; sessions are signed with a per-process secret.
- Seeds take turns, and a seed is admitted again before it lends; a close or a retire stops the sandbox, a failed
  seed's stop is tried again at its session's close, and shutdown stops everything within the run's grace.
- A sandbox provider failure fails the call (502) and masks the episode's reward.
- Configs for Pi (Docker and OpenSandbox), Codex CLI, mini-SWE, OpenCode, OpenClaw and Terminus 2; nine sandbox tasks
  (OfficeEnv 1.14.0), the first five as example rows with Pi's rollouts of them; images and a README.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(core): LentSandboxes logs a start its limit cut before the provider returned the sandbox's id

When start_timeout_s cuts a provider's create in flight, the sandbox's id is unknown, so the lend's stop cannot reach
what the create left. The lend now logs that cut at ERROR with the resources session, the task (id and taskset), the
provider, the image and the labels, so a reaper can find the sandbox. A start cut after the create returned stops its
sandbox as before and asks for no reaper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* refactor(officeenv_sandbox): name each harness's instances after it, so harness configs compose in one run

Every harness config defined `oe` and `single_agent_turn_legacy`, so two of them could not run together. Now:

- the episodes' resources server is officeenv_sandbox_resources_server;
- each config adds officeenv_sandbox_<harness>_agent (`_inherit_from` Gym's instance of the harness, as benchmarks do)
  and officeenv_sandbox_<harness>_environment_server (`_inherit_from: single_agent_turn_legacy`);
- Pi, Codex and OpenCode, which name MCP tools their own way, run on their own copy of the episodes' server
  (officeenv_sandbox_<harness>_resources_server, `_copy` with its mcp_tool_prefix); the other harnesses run on the
  shared one. A copy takes the shared server's settings from the merged config, so one override reaches every harness.

The interpolations, the documented overrides, the probe script and the README follow (a table of the names; the
OpenSandbox config is listed after the other harness configs, since a later one pulls the episodes' config in again).
A core test resolves each config alone and all six together with a model config, and replaces the server test that
restated their YAML; it needs no OfficeEnv, so it runs in CI. The OpenCode and OpenClaw configs and the README no
longer say those harnesses refuse MCP tool grants.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(officeenv_sandbox): sandbox_config.start_timeout_s bounds a sandbox's start; host_relay needs trusted_workstation

- sandbox_config.start_timeout_s (1800 s by default, a finite number above 0) is passed to LentSandboxes, which fails
  the seed at that limit and logs a create it cut for a reaper. The README says when to raise it: creates on a busy
  OpenSandbox cell have taken up to 2,430 s.
- host_relay forwards sandbox connections from the host's loopback, which the caller check takes for Gym's own
  servers, so code in a sandbox could call the routes kept for Gym for any session. Config validation now refuses
  host_relay unless sandbox_config.trusted_workstation is true, which a config sets only on a single-user workstation;
  its description and the README state the risk.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(officeenv_sandbox): officeenv_sandboxless.yaml runs the OfficeEnv server's instances under names of their own

It composes resources_servers/officeenv/configs/officeenv.yaml and copies (`_copy`) its three instances as
officeenv_sandboxless_resources_server, officeenv_sandbox_simple_agent and officeenv_sandbox_environment_server, each
copy pointing at the other copies, while the OfficeEnv server's instances keep their names. The copied agent declares
no dataset, so the example rows and their taskset stay with the OfficeEnv server's instances, and rows that name
officeenv_sandbox_simple_agent (flat rows, agent_ref) route to the copied environment server.

A `_copy` takes its source as written, before the source's own `_inherit_from` applies, so the environment server is
copied as the instance of the server type officeenv_environment_server inherits, with that server's own settings for
it on top. The core test checks each copy against its source, references aside, alone and beside the Pi and Codex
configs, so a change to the source's server type fails it rather than leaving the copy behind.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(officeenv_sandbox): the sandboxless arm copies single_agent_turn_legacy, which the OfficeEnv server now runs

officeenv_environment_server inherits single_agent_turn_legacy now, so the copy takes that instance, then the server's
own settings for it under that type, with its references still pointing at the other copies.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* refactor(officeenv_sandbox): every harness runs the episodes' server under its own name, so none is left idle

Each harness config now adds officeenv_sandbox_<harness>_resources_server with `_inherit_from:
officeenv_sandbox_resources_server`, OpenClaw, mini-SWE and Terminus 2 included, and no harness names the episodes'
server. `_inherit_from` reads it from the merged config and takes it out of the run, so a run of one or several
harness configs starts no idle episodes' server, while the episodes config alone still runs it under its own name.
Settings on the episodes' server, the OpenSandbox config's included, reach every harness's server. The OpenSandbox
config still goes after the other harness configs (the first harness config listed pulls the episodes' config in),
and the README now says why. The core test checks that no episodes' server starts or is named beside the harnesses',
alone and with all six, and that the episodes config runs on its own.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(core): the cut-start log says OpenSandbox deletes what an abandoned create left

Main's OpenSandbox provider now deletes the sandbox of a create its caller gave up on (#4799), so
a start that LentSandboxes' start_timeout_s cuts before the provider returned the sandbox's id no
longer needs a reaper there. The ERROR log, LentSandboxes' docstring and the officeenv_sandbox
README now say so, and keep the reaper for providers without that cleanup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(officeenv_sandbox): Pi's run ends once its task has ended, on every exposure

- The sandboxed server holds the call that ends a watched episode's task, on
  every way in (tools, commands, endpoints, the file API), until the
  environment server releases it; the episode's lock is let go first. Only
  Gym's node reaches GET /task_state and POST /task_state/release.
- Pi supports POST /rollouts/{rollout_id}/stop (_rollout_sandbox_session): a
  run stopped as completed answers so, marked in ng_rollout_stop, and is not
  reported as a wall-time timeout.
- The Pi config sets end_on_task_state on its environment server and drops
  finish_tool_names (now []): the stop ends the run on cli and api_search rows
  too, which offer no finish tool. Its comment no longer asks cli rows to drop
  the MCP transport, which they run with as it is.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* docs(officeenv): the servers run OfficeEnv 1.14.2

1.14.2 is the OfficeEnv release N4's training runs grade with. 1.14.1 and
1.14.2 are patch releases; neither changes the API these servers use. The
READMEs' install lines name it, and the example rows are emitted again by it
(officeenv emit for resources_servers/officeenv, sandbox/prepare_rows.py for
officeenv_sandbox), which changed only their version stamp. The example
rollouts stay the ones collected against 1.14.0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(officeenv_sandbox): refuse calls after the task ended with ResourcesSessionConflictError

Main's session contract (#5691) has every 409 a resources server answers raise
ResourcesSessionConflictError, and tests/unit_tests/test_session_contract_repo.py
checks it. The sandboxed server refused a tool call once verification began, and a
file API call once the episode's files closed, with plain HTTPException(409)s; both
now raise the named error. The status and the detail are the same, so callers see no
change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(core): LentSandboxes shields a start only with start_timeout_s

Main's opencode_search (#6211) lends through LentSandboxes and expects a seed cancelled
while its sandbox starts to stop that sandbox at once, as LentSandboxes did before this
branch; the shielded start made it wait for the start's end. The shield is now opt-in.
Without start_timeout_s a cancel cuts the start as it cuts any await, as on main, and the
lend stops the sandbox it began. With it, the start runs to its end within that limit,
which the OfficeEnv sandbox server sets (sandbox_config.start_timeout_s, 1,800 s by
default). START_TIMEOUT_S goes, since no default limit remains.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* build(officeenv_sandbox): lock against main's upgraded dependency locks

Main's lock upgrade (#6528) moved the root lock, and `uv sync --locked` refused the
sandboxed server's older lock, so neither its suite nor a run could start it. `uv lock`
with uv 0.13.4 takes the root lock's versions (e2b 2.50.0, protobuf-py 0.1.1, pyqwest
0.10.0), keeps the tzdata OfficeEnv pins (2026.6), and passes scripts/component_locks.py.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(core): a cut start's test counts the closes the provider made

Main's #6410 changed the stopped fixture from AsyncSandbox.stop calls to the closes the
provider made. A start cut before the provider returned its sandbox's id leaves nothing
to close, so the hung-start test now expects none, as the ERROR line it checks says.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(single_agent_turn): stop an agent's own loop once its task has ended

With end_on_task_state and no max_episode_steps, single_agent_turn now ends an
agent that runs its own loop (a sandboxed harness) at its task's end, as the
step loop ends a step-driven one:

- Before the agent runs it reads GET /task_state?watch=true; while the agent
  runs it reads again, each read waiting up to 30 s (wait_s).
- Once the task has ended it stops the run with POST /rollouts/{id}/stop
  {"reason": "task_ended", "completed": true}, waits for the activation to
  answer (at most 120 s), then posts /task_state/release.
- The resources server holds its answer to the call that ended the task until
  that release, so the harness never reads it while its run could go on, and
  no model call follows the call that ended the task.
- The server refuses at startup an agent type outside ROLLOUT_STOP_AGENT_TYPES
  (the agents whose runs the stop route can end; a unit test keeps the list in
  step with the apps).

Core: RolloutStopRequest.completed; such a stop answers as completed
(report_rollout_stop) and says so in ng_rollout_stop. Docker uploads take a
bound of their own, so a stop's marker never waits for the exec slot a running
harness holds (uploads_independent_of_execs).

OfficeEnv: GET /task_state takes watch and wait_s (at most 60 s); POST
/task_state/release; task_end_hold_seconds (180) bounds the hold.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(officeenv_sandbox): the stand-in sandbox stops as main's AsyncSandbox.stop does

Main's #6410 moved the shielded, bounded stop into AsyncSandbox.stop(timeout_s=...),
which LentSandboxes now calls. The tests' FakeSandbox.stop took no timeout_s and had no
shield, so a seed or close cancelled during a stop failed or hung. FakeSandbox.stop now
takes timeout_s and shields its provider-side _stop, as AsyncSandbox.stop does, and the
tests that slow down, refuse or hang a stop patch _stop.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(cline_agent): the fake sandbox session carries expire_completed

report_rollout_stop now reads SandboxSession.expire_completed (a run stopped once
its task has ended answers as completed), so the stand-in that Cline's session
tests use carries it too, as the real session does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* refactor(officeenv_sandbox): sign sessions with Gym's run secret

#6161 now makes a secret per server and run in server_runtime, which every worker of the
server shares (signs_sessions_with_run_secret). The sandboxed server sets that flag instead
of minting its own secret in model_post_init and overriding get_session_secret(): its
cookies and MCP tokens are signed, as before, with a secret code in a sandbox cannot
derive from the server's name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(officeenv): refuse a tool call after the task ended with ResourcesSessionConflictError

Main's session contract (#5691) has every 409 a resources server answers raise
ResourcesSessionConflictError, and tests/unit_tests/test_session_contract_repo.py
checks it. With close_tools_on_task_end, the OfficeEnv server refused a call after the
task ended with a plain HTTPException(409); it now raises the named error. The status
and the detail are the same, so callers see no change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* docs(officeenv_sandbox): say when the task-end stop ends a Stirrup run

Stirrup cannot run without a finish tool, so with its default finish tool most runs end when the model calls
finish. The environment server's task-end stop ends a run that calls `user complete-task`, before its next model
call. Pi's config sets finish_tool_names: [], so for Pi the stop is the normal end. The README now says so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(core): release_all stops the lent sandboxes while a lend is still starting

release_all waited for every start in flight before it stopped any lent
sandbox, all inside one time limit. One slow start at shutdown then left
every lent sandbox running until its TTL. Now the lent sandboxes stop at
once, and each starting sandbox is stopped when its start ends.

The new test fails before this change (no sandbox stopped) and passes
after it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(officeenv_sandbox): keep the agent and environment servers on 127.0.0.1

NeMo RL sets default_host to the node's address, and an explicit
default_host applies to every server, not only to the types in
absolute_ip_server_types. A sandbox's network rule opens every port of an
allowed host. So code in a sandbox could call the agent and environment
servers: run Pi on Gym's host (/v1/responses without a session), start
episodes (/run) and stop another episode's run
(/rollouts/{rollout_id}/stop).

Each harness config now sets host: 127.0.0.1 on its agent and its
environment server. No sandbox calls them: each harness in a sandbox calls
only the model server and the resources server, and NeMo RL calls /run from
the same node. Without default_host, Gym already binds them to 127.0.0.1.
The comment in officeenv_opensandbox.yaml and the README now say this.

The new config test resolves every harness config under
default_host: 10.0.0…
d-molinari added a commit that referenced this pull request Dec 2, 2026
…eep the secret from sandboxes

A restart replaces the run's secret, so the cookies and MCP tokens a server signed before it no
longer decode. A resources server or agent that signs with it (signs_sessions_with_run_secret, or
mcp_bearer_token) now takes part in partial-rollout checkpoints as restart_only whatever it
declares, with one warning: a restored session could not be reached, so its episodes start over
after a crash instead of verifying on an empty session. The mcp_bearer_token description,
get_session_secret, checkpoint_mode_in_effect and participant_workers.py say so.

The secret lives in the server's environment, which every process it starts inherits. The
Apptainer and local providers now leave the run-secret variables out of the environment they pass
to sandboxed code (nemo_gym.core.run_session_secrets, which both packages may import). The
get_session_secret docstring and the MCP tutorial state the guarantee's limit: code that shares
the server's user and the host's process table (the local provider's, or Apptainer's without
--containall) can still read a multi-worker server's secret from its workers' environment.

Addresses the review notes on #6161 about the run secret and checkpoint restore, and about its
inheritance in Apptainer and local sandboxes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>
d-molinari added a commit that referenced this pull request Dec 2, 2026
…ialize reports

Pi shows the model <name>_<tool>, as OpenCode does (gym_mcp.mjs); mcp__<name>__<tool> is what Gym
records for Pi's calls, and what mini-SWE uses. The single_agent_turn README, the
_check_mcp_server_names docstring and the mcp_server_name comment now say so, and the README names
only the agents that refuse names that collide in their own naming (OpenCode and Pi). The MCP
tutorial no longer says the deprecated sandboxed agents' tool_servers entries carry
mcp_server_name: since 19ab60f they keep the server's reference name.

test_bearer_token_and_advertised_name_present_an_ordinary_endpoint now checks that initialize
introduces the endpoint under mcp_server_name, so reverting mcp_auto_exposure to the config name
fails it.

Addresses the review notes on #6161 about the naming docs and the serverInfo.name test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>
d-molinari added a commit that referenced this pull request Dec 4, 2026
…eep the secret from sandboxes

A restart replaces the run's secret, so the cookies and MCP tokens a server signed before it no
longer decode. A resources server or agent that signs with it (signs_sessions_with_run_secret, or
mcp_bearer_token) now takes part in partial-rollout checkpoints as restart_only whatever it
declares, with one warning: a restored session could not be reached, so its episodes start over
after a crash instead of verifying on an empty session. The mcp_bearer_token description,
get_session_secret, checkpoint_mode_in_effect and participant_workers.py say so.

The secret lives in the server's environment, which every process it starts inherits. The
Apptainer and local providers now leave the run-secret variables out of the environment they pass
to sandboxed code (nemo_gym.core.run_session_secrets, which both packages may import). The
get_session_secret docstring and the MCP tutorial state the guarantee's limit: code that shares
the server's user and the host's process table (the local provider's, or Apptainer's without
--containall) can still read a multi-worker server's secret from its workers' environment.

Addresses the review notes on #6161 about the run secret and checkpoint restore, and about its
inheritance in Apptainer and local sandboxes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>
d-molinari added a commit that referenced this pull request Dec 4, 2026
…ialize reports

Pi shows the model <name>_<tool>, as OpenCode does (gym_mcp.mjs); mcp__<name>__<tool> is what Gym
records for Pi's calls, and what mini-SWE uses. The single_agent_turn README, the
_check_mcp_server_names docstring and the mcp_server_name comment now say so, and the README names
only the agents that refuse names that collide in their own naming (OpenCode and Pi). The MCP
tutorial no longer says the deprecated sandboxed agents' tool_servers entries carry
mcp_server_name: since 19ab60f they keep the server's reference name.

test_bearer_token_and_advertised_name_present_an_ordinary_endpoint now checks that initialize
introduces the endpoint under mcp_server_name, so reverting mcp_auto_exposure to the config name
fails it.

Addresses the review notes on #6161 about the naming docs and the serverInfo.name test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core Shared APIs, servers, telemetry, health, and registries feature New capabilities, enhancements, or enablement work ready-to-merge PR is approved, current, and waiting for final CI or merge risk:high Autobot PR risk: high sla:review-overdue Review response is over the one-business-day SLA

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants