Skip to content

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

Merged
yfw merged 21 commits into
mainfrom
dmolinari/single-agent-turn-step-loop
Nov 30, 2026
Merged

yfw merged 21 commits into
mainfrom
dmolinari/single-agent-turn-step-loop

Conversation

@d-molinari

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

Copy link
Copy Markdown
Contributor

Follow-up commits (review fixes)

  • 3c69ed1793 fix(single_agent_turn): the task-end stop and the release go over the reserved control connection pool; the 120 s wait counts from the time the stop is sent, and also covers a stop that answers stopped: false; a run still going at that time is logged and its reply says ng_task_end_stop: unconfirmed; a stop answered 501 (the sandbox provider cannot stop a running harness) fails the episode for good; a task already ended, or a lost session, at the first watch starts no run; a max_steps the step loop does not use is named in a startup warning.
  • 0bf3ee5628 fix(officeenv): an episode seed passes the task's responses_create_params with the row, so tool_drift is reported again; the README says that close_tools_on_task_end refuses calls after the task ended.
  • a53810f379 docs(agent-server): the harness guide names completed stops and the providers that can stop a running harness (Local, bwrap, Docker, OpenSandbox with background_exec).
  • 65143e9ba8 fix(simple_agent): without checkpointing, a step sent again with the same activation index (after a dropped connection) shares the step's run or gets its reply, so its model call and tool calls run once; closing the session cancels a step still running; an older step gets 409.
  • 282d4448a2 fix(agents): the session close of a run stopped as completed reports its top-level invocation as completed, as its response does; the sandbox observation keeps the supervisor's timeout.
  • e0c1990002 docs(agent-server): the integration and harness guides describe the last two changes.
  • 7eb796ec35 fix(simple_agent): the session close drops the saved step, and the docstring says why only caller-driven steps without checkpointing need it.
  • 942c31ad60 test(goose_agent): a second stop agent, besides Prime, whose close after a completed stop the base fix marks completed.

What does this PR do?

Lets single_agent_turn drive its agent one step at a time, and end the episode once the resources server says its task has ended; an agent that runs its own loop, such as a sandboxed harness, has its run stopped then. It is the second of three pieces that #5010's review split out, built on #6161 (merged); #5010 (OfficeEnv's sandboxed server) builds on this branch.

single_agent_turn

  • max_episode_steps drives the agent one step per activation (one model call and the tool calls it makes), up to that many steps. The episode ends after a step with no tool call, or one that did not complete, as the agent's own loop ends. One that runs out of steps says so in its reply's metadata (ng_termination_reason: max_episode_steps).
  • end_on_task_state reads GET /task_state on the episode's resources session after each step but the last, and ends the episode once the task has ended. The reply model is ResourcesTaskState ({"task_ended": bool}), in nemo_gym.server_runtime. A session the resources server no longer holds (404, session_lost) ends the episode too, so /verify masks it as it does when a tool call finds the session gone.
  • Every step's failure report is kept, the reply carries every step's output and summed usage, and a failure after a step completed keeps the steps before it as its partial response.
  • At startup the server checks that the agent's type takes one step per activation (STEP_DRIVEN_AGENT_TYPES, today the simple agent) and runs the tools it calls.
  • Driven episodes take part in checkpoints as restarts, through BaseEnvironmentServer.checkpoint_mode_in_effect(), as agents and resources servers already declare theirs.
  • Without max_episode_steps, end_on_task_state stops an agent that runs its own loop once its task has ended. The server watches the session (GET /task_state?watch=true, then reads that wait up to 30 s), stops the run as completed (POST /rollouts/{rollout_id}/stop, {"reason": "task_ended", "completed": true}), waits for the activation to answer, and only then releases the call that ended the task (POST /task_state/release). The resources server holds that call's answer until the release, so no model call follows it. The agent's type must be in ROLLOUT_STOP_AGENT_TYPES, which the server checks at startup.
  • single_agent_turn_legacy inherits all of this, so the step loop also runs flat rows.

simple_agent: the step loop sends x-ng-agent-episode-step-limit with each activation. With it, the agent takes exactly one step, whatever its own max_steps, numbers the step by x-ng-agent-activation, and counts it as completed unless it is the episode's last. The session keeps one invocation for the episode (marked failed when a step fails) and its model-server cookies, instead of one invocation per step that repeats the whole history. The cookies live in the session field that main's continuation sessions (#5465) use; a continuation session answers the step-limit header with 422, since each of its activations runs a whole turn on new input.

Rollout stops (core): RolloutStopRequest.completed stops a run whose task has ended; the run answers as completed, and its ng_rollout_stop metadata says "completed": true. Docker uploads take a bound of their own, so a stop's marker never waits for the exec slot a running harness holds.

OfficeEnv (resources_servers/officeenv)

  • GET /task_state answers ResourcesTaskState. With watch=true, the call that ends the task waits for POST /task_state/release, at most task_end_hold_seconds (180 s); wait_s (at most 60 s) makes a read wait for the end.
  • close_tools_on_task_end refuses the calls a step makes after the one that ended the task (a 409, ResourcesSessionConflictError).
  • It runs on single_agent_turn_legacy with the step loop on: its taskset rows (officeenv:example) run as typed episodes, and flat rows (training corpora) through the legacy /run. allowed_agents lists the simple agent and the compaction agent, which composition relays through legacy_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 and its rollouts collected again.

The docs describe GET /task_state (resources-server APIs) and the step-limit header (integrating agents).

Validation

On main d1391e9ffe (#6161 merged):

  • Gym's core suite, as CI runs it (four shards, then -m sandbox): all four shards and the 2,106 sandbox tests pass; combined core coverage 95.12%.
  • tests/unit_tests/orchestration/test_single_agent_turn_task_end_stop.py (12 tests) covers the stop at the task's end: the watch before the run, the stop as completed, the release only after the activation answered, a run that ends first, a lost session, failed reads and stops, the release after the stop's bound, the poll interval and the startup check.
  • gym env test: single_agent_turn 299 passed, single_agent_turn_legacy 54 passed, simple_agent 195 passed, agentic_turn_simulation_agent 93 passed, automationbench (which runs through single_agent_turn) 17 passed, openhands_agent 148 passed; resources_servers/officeenv with OfficeEnv 1.14.0 installed: 50 passed (the hold, the waiting read and the release among them), data validated.
  • gym env test for every other agent whose run the stop can end (ROLLOUT_STOP_AGENT_TYPES: Cline, Codex, CrewAI, Droid, Goose, Kimi Code, LangChain Deep Agents, mini-SWE, Prime, Qwen Code, Terminus 2; feat(officeenv): run OfficeEnv episodes in a sandbox, for Gym's sandboxed harnesses #5010 adds Pi), and for wildclawbench_agent, which main added to the session agents: every suite passes.
  • tests/unit_tests/benchmarks/test_officeenv_pairings.py (3 passed) resolves OfficeEnv's config, alone and with --agent-type's simple and compaction agents, and builds its environment server; it needs no OfficeEnv, so it runs in CI.
  • The new tests fail on the code they guard: 19 of 19 single-line breaks of the step loop and the simple agent's step handling fail them.
  • pre-commit passes on the changed files, detect-secrets flags only test values, placeholders and a pinned commit hash in them, and every commit is signed off.

Rollouts

  • azure/openai/gpt-5.5 on the five example rows on main 4e3f503549, with OfficeEnv 1.14.0: collated by taskset (typed episodes), and again as flat rows routed to the agent. Every row was graded: all five at 1.0 as episodes; as flat rows four at 1.0, and schedule_kickoff at 0.75, booked over the meeting injected during the episode, as OfficeEnv's README describes. sprint_handover, whose task ends with complete_task, ended at that call both times. data/example_rollouts.jsonl holds an earlier head's run of the same rows.
  • On main 4e3f503549 with feat(officeenv): run OfficeEnv episodes in a sandbox, for Gym's sandboxed harnesses #5010 on top, gpt-5.5 on Docker: the 34 episodes of a sandboxed harness (Pi) that called complete_task each ended at that call, stopped as completed; before the stop, each of the 29 sampled ones wrote at least one more message. The 17 sandboxless ones ended at it, as before.
  • On main d1391e9ffe with feat(officeenv): run OfficeEnv episodes in a sandbox, for Gym's sandboxed harnesses #5010 on top, Pi with gpt-5.5 on Docker on feat(officeenv): run OfficeEnv episodes in a sandbox, for Gym's sandboxed harnesses #5010's five example rows (OfficeEnv 1.14.2): each run ended at its complete_task call, stopped as completed, all at reward 1.0.
  • A two-step NeMo RL smoke of this stack, ported onto a training branch, ran sandboxless episodes through single_agent_turn_legacy's step loop beside sandboxed ones. Every episode was graded, and none made a model call after a successful complete_task.

Compatibility and benchmark impact

  • After a stop with completed: true, the session close of every agent in ROLLOUT_STOP_AGENT_TYPES now records the run's top-level invocation as completed (with no error type), not incomplete. The sandbox observation still says timeout. Before this PR no caller sent such a stop, so only readers of these new runs see the change.
  • With close_tools_on_task_end, the calls that a step makes after complete_task get 409. Without the setting, OfficeEnv runs them. So a model that calls complete_task before its last edit or message in the same step can now score lower.
  • OfficeEnv's episodes run on single_agent_turn_legacy's step loop instead of the legacy_agent relay, and end at the step that completes the task. The episode's limit is max_episode_steps (50); the simple agent's own max_steps no longer matters under the step loop.
  • --agent-type adds an agent's config, and allowed_agents refuses composable templates other than the two above. A session-less agent composed in runs flat rows through legacy_agent; collated taskset rows can't reach it yet, since that relay takes only flat rows.
  • NeMo RL's turn and prefix recovery accept only the legacy_agent environment server, so until NeMo RL follows, OfficeEnv training sets rollout_recovery.target_level: sibling for the whole run.
  • The OfficeEnv server locks the tzdata OfficeEnv pins. A release older than 1.13.0 stops the server at its import, naming both versions.

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 (single_agent_turn's and OfficeEnv's READMEs, the Fern pages above).
  • 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 6ba2e0a

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

SHIP WITH CARE

I found three RISKs in startup validation and agent composition, plus one NOTE about retaining partial-response evidence. The findings below include proposed regression checks; I didn't execute tests.

I assessed all 20 changed paths and their directly affected contracts. OfficeEnv's external package source wasn't available, and the file reader truncated the long records in the refreshed rollouts, so I couldn't independently verify their complete trajectories or reward fields. The reported smoke-run results remain author-provided evidence.


Inline comments (escaped v1):

  • environment_servers/single_agent_turn/app.py line 215: RISK — Validate the parsed agent settings, not their raw representations.

    With max_steps: 1 and execute_tools: "false", this check accepts the pairing because the string isn't the singleton False. The agent config parses that value as false, so its loop returns tool calls without executing them. The environment then continues with unresolved calls instead of rejecting the pairing. Conversely, the valid max_steps: "1" is rejected. YAML strings and environment interpolations can reach these raw settings.

    Could _check_step_driven_agent parse both values as the agent does? Replace the two conditions, retaining their existing error messages:

    if not TypeAdapter(bool).validate_python(config.get("execute_tools", True)):
        problems.append("it does not run the tools it calls (execute_tools: false)")
    if TypeAdapter(int | None).validate_python(config.get("max_steps")) != 1:
        problems.append(f"it stops after max_steps: {config.get('max_steps')} steps per activation, not 1")

    This restores agreement between startup validation and runtime behavior while preserving omitted/true tool execution and numeric one-step settings.

    Proposed acceptance, not executed: extend the startup cases so string "false" and native false are refused; numeric/string one with omitted, native true, or string "true" tool execution starts; and missing or multi-step limits remain refused. Verify the suggested code before adopting it.

  • environment_servers/single_agent_turn/app.py line 213: RISK — Session support doesn't establish support for this step protocol.

    An agent block with agent_type="hermes_agent" and an added max_steps: 1 passes these checks. However, the registry promises only session support. Hermes config uses max_turns, not max_steps; its activation payload still supplies that limit, which the runner passes as max_iterations. With otherwise valid sandbox/tool settings, the accepted activation isn't constrained to one model call, so polling after it cannot enforce termination between its calls.

    Could this check fail closed on adapters that don't implement the step protocol? For the currently documented implementation, add this alongside the existing session check:

    if agent_type in AGENT_SESSION_AGENT_TYPES and agent_type != "simple_agent":
        problems.append(f"its type {agent_type!r} does not implement the step-driven protocol")

    Broader support would need an explicit capability covering one model call plus its tools and the episode-step-limit header—not session support alone.

    Preservation and proposed acceptance: the startup regression table should refuse hermes_agent even with max_steps=1, while retaining the unknown-agent rejection. The valid simple-agent pairing must still start, disabled-tools/multi-step variants must remain refused, and configurations without max_episode_steps must still accept other session adapters. These are source-based checks, not an executed Hermes run; verify the suggestion before adopting it.

  • nemo_gym/config/global_config.py line 993: RISK — Explicitly selecting OfficeEnv's permitted agent removes its required step limit.

    gym env start --resources-server officeenv --model-type openai_model --agent-type simple_agent, with valid model settings, now fails environment startup. The new OfficeEnv pairing permits this agent and requires max_steps: 1. But composition replaces its settings with the standalone template, which declares no limit. The carry-over list excludes max_steps, so the new startup check rejects the sole permitted harness. Omitting --agent-type retains the limit and works around the failure. The new step-driven pairing makes this existing composition behavior fatal.

    Could compose_unbound_agent preserve or reapply the one-step requirement specifically when composing the simple agent onto a step-driven pairing? The invariant is that selecting its permitted harness leaves the environment and agent limits compatible. The exact implementation needs care: globally carrying target-agent settings into every harness would break the intentional composition contract, so I don't have a safe complete replacement patch to suggest.

    Preservation and proposed acceptance, not executed: resolve OfficeEnv both without an agent override and with the standalone simple-agent config included. Both must retain officeenv_simple_agent.responses_api_agents.simple_agent.max_steps == 1, preserve the taskset route, and pass environment construction. Keep incompatible harnesses rejected. Retain the existing Hermes composition assertion that max_steps does not leak into Hermes.

  • environment_servers/single_agent_turn/app.py line 775: NOTE — Suggestion: retain completed steps when a later dependency call fails.

    After a successful tool step, make GET /task_state fail, as the new failed-read test already does. The dependency failure carries no partial response, so _run_steps loses its accumulated output and usage. A later activation transport failure does the same. This limits diagnostics when observation capture is disabled; the failure model already supports retaining this evidence.

    Could _run_steps initialize response = None before the loop and wrap the existing loop with this handler?

    except NgFailureEvent as error:
        if is_handled_episode_failure(error) and response is not None:
            error.episode_evidence["partial_response"] = response.model_copy(
                update={"output": outputs, "usage": usage}
            )
        raise

    The invariant is that failures after completed steps retain their ordered output and summed usage. Preserve the original failure, retryability, cleanup, and no-verification behavior; a failure before the first reply must not fabricate a response.

    Proposed acceptance, not executed: extend the failed-read test to require the first call/output pair and USAGE in failure.partial_response. Add two successful steps followed by an activation transport failure and require both pairs plus doubled usage. Retain successful aggregation, failure-stage/no-verification assertions, and a first-activation failure with no partial response. Verify the suggested handler before adopting it.

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

@d-molinari

Copy link
Copy Markdown
Contributor Author

/ok to test 9ee5637

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

@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. Two small notes, beyond the bot's open items on the step loop:

NOTE: new kwarg passed with the feature off (responses_api_agents/simple_agent/app.py:930)
step_limit_owned_by_caller= is passed to _create_episode on every call. A SimpleAgent subclass outside this repo that overrides _create_episode without the keyword or **kwargs would raise TypeError on every request even with no step limit set. In-tree subclasses are updated. Passing it only when True keeps old overrides working.

NOTE: step-limit cutoff reports completed (environment_servers/single_agent_turn/app.py:777)
When the loop runs out at max_episode_steps with every step calling a tool, the merged reply goes out with status completed and no incomplete_details. Only the agent's own invocation record says incomplete. Setting incomplete_details (reason max steps) on the merged reply would let downstream readers see the cutoff.

@cmunley1

Copy link
Copy Markdown
Contributor

/review

@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

The three RISKs and one NOTE from bot review 5897161649 remain unresolved at this head.

I verified that the agentic-turn subclass now accepts the added keyword. I also checked the moved step-loop tests, the new core helper tests, and their directly affected paths. I found no eligible new regression since the reviewed baseline.

This was a follow-up review, not a fresh whole-PR assessment. I couldn't execute tests in this read-only review; the checks below are proposed, and the reported smoke-run results remain author-provided evidence.


Inline comments (escaped v1):

  • environment_servers/single_agent_turn/app.py line 215: RISK — Validate the parsed agent settings, not their raw representations.

    The first RISK from bot review 5897161649 remains unresolved. With max_steps: 1 and execute_tools: "false", startup accepts the pairing because the string isn't the singleton False. The simple-agent config parses it as false, so the disabled-tools branch returns unresolved calls instead of executing them. Conversely, valid max_steps: "1" is rejected. This affects step-driven configurations using quoted YAML values or environment interpolation.

    Could _check_step_driven_agent use the agent's parsing semantics? Replace its two setting checks, keeping their messages:

    if not TypeAdapter(bool).validate_python(config.get("execute_tools", True)):
        problems.append("it does not run the tools it calls (execute_tools: false)")
    if TypeAdapter(int | None).validate_python(config.get("max_steps")) != 1:
        problems.append(f"it stops after max_steps: {config.get('max_steps')} steps per activation, not 1")

    The invariant is agreement between startup validation and the agent's effective settings. Preserve omitted/true tool execution, numeric one-step settings, rejection of missing/multi-step limits, and configurations without max_episode_steps.

    Proposed acceptance, not executed: extend the startup cases: native false and string "false" must fail; numeric/string one with omitted, native true, or string "true" tool execution must construct successfully; missing and multi-step limits must remain rejected. Verify the suggested code before adopting it.

  • environment_servers/single_agent_turn/app.py line 213: RISK — Session support doesn't establish support for the step protocol.

    The second RISK from bot review 5897161649 remains unresolved. A referenced hermes_agent block with added max_steps: 1 passes this validator because Hermes belongs to the session registry. But Hermes config controls activations with max_turns, not max_steps; its payload passes that independent limit to the runner's max_iterations. With otherwise valid sandbox/MCP settings, startup therefore accepts an adapter without enforcing one model call per activation. Polling after that activation cannot enforce the advertised between-call task-state boundary.

    Could this check fail closed on adapters without the step protocol? For the currently supported implementation, add alongside the session check:

    if agent_type in AGENT_SESSION_AGENT_TYPES and agent_type != "simple_agent":
        problems.append(f"its type {agent_type!r} does not implement the step-driven protocol")

    Broader support needs an explicit capability covering one model call plus its tools and the episode-step-limit header. Session support alone must not satisfy that contract.

    Preservation and proposed acceptance, not executed: add hermes_agent with max_steps=1 to the startup rejection table. Retain unknown-agent, disabled-tools, and multi-step rejection; the valid simple-agent pairing must still construct. With max_episode_steps=None, environment construction must continue accepting Hermes. This consequence is source-based, not an executed Hermes run; verify the suggestion before adopting it.

  • nemo_gym/config/global_config.py line 993: RISK — Explicitly selecting OfficeEnv's permitted agent still removes its required step limit.

    The composition RISK from bot review 5897161649 remains unresolved. With valid model settings, gym env start --resources-server officeenv --model-type openai_model --agent-type simple_agent still fails environment startup. The OfficeEnv pairing permits simple_agent and requires max_steps: 1. Composition replaces its settings with the standalone template, which declares no limit. The carry-over contract preserves only bindings and datasets, so the environment constructor rejects the missing limit. Omitting --agent-type retains the pairing's limit.

    Could compose_unbound_agent preserve or reapply the one-step requirement specifically when composing the simple agent onto a step-driven pairing? Selecting the permitted harness must leave its settings compatible with the environment. The exact implementation needs pairing context that _carry_over_agent_bindings currently doesn't receive, so I don't have a safe complete replacement patch. Globally carrying max_steps into every harness would violate the existing composition contract.

    Preservation and proposed acceptance, not executed: resolve OfficeEnv both without an override and with the standalone simple-agent config included. Both must retain officeenv_simple_agent.responses_api_agents.simple_agent.max_steps == 1, retain the officeenv:example route and its environment reference, and pass environment construction. Keep incompatible OfficeEnv harnesses rejected and ordinary non-step-driven composition unchanged. Retain the existing Hermes assertion that max_steps does not leak into Hermes.

  • environment_servers/single_agent_turn/app.py line 775: NOTE — Suggestion: retain completed steps when a later dependency call fails.

    The NOTE from bot review 5897161649 remains unresolved. In the failed task-state read case, the first activation completes a call/output pair, then GET /task_state fails. _run_steps unwinds without retaining its accumulated output or usage. A later activation transport failure loses earlier steps in the same way. This limits diagnostics when observations aren't captured; the failure contract already supports partial_response.

    Could _run_steps initialize response = None before the loop and wrap the existing loop with this handler, leaving the successful return afterward?

    except NgFailureEvent as error:
        if (
            is_handled_episode_failure(error)
            and response is not None
            and error.episode_evidence.get("partial_response") is None
        ):
            error.episode_evidence["partial_response"] = response.model_copy(
                update={"output": outputs, "usage": usage}
            )
        raise

    This retains completed steps without replacing existing, potentially newer partial evidence. Preserve the original failure, retryability, cleanup, no-verification behavior, and successful aggregation. A failure before the first reply must not fabricate a response.

    Proposed acceptance, not executed: extend the failed-read test to require the first call/output pair and USAGE in failure.partial_response. Add two successful steps followed by an activation transport failure; require both ordered pairs and usage (input_tokens=20, output_tokens=8, total_tokens=28, reasoning_tokens=2). Retain failure-stage/no-verification assertions and successful aggregation checks. Cover a first-activation failure with no partial response and an existing non-null partial response that remains unchanged. Verify the suggested handler before adopting it.

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

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

Verdict: HOLD, for one CI failure that is a quick fix. After that, and with the bot's open RISKs addressed, this looks close.

Thanks for splitting this out of #5010. The step loop is small and reads well. It moves OfficeEnv off the legacy_agent relay and ends the episode at the step that ends the task, and the rollouts at this head back that up. We reviewed only this PR's two commits on top of #6161, at 9ee56370b9.

CI. "Unit tests / Core tests (shard 2)" fails at this head with 1 failed, 7100 passed. The failing test is the import-rule check test_the_librarys_tests_import_from_the_module_that_defines_each_name, and the cause is the two test files this PR moved into tests/unit_tests/ (inline comments with the fix). The body's "fails only where main does" predates that move. The "Environment Server compliance (non-blocking)" warnings (run() and aggregate_metrics in simple_agent) are already on the base, so we left them out.

Existing review items. All six are still open at this head, and we agree with each of them:

  • R1 (raw execute_tools / max_steps compare): agree. Only the execute_tools half fails open: ${oc.env:X,false} resolves to the string 'False', and openai_model.yaml already uses that form for a bool. The max_steps half goes away if the step limit moves to the header (see our comment on officeenv.yaml:40).
  • R2 (session support is not the step protocol): agree. browsecomp_agent is another case. It is in AGENT_SESSION_AGENT_TYPES and has its own max_steps, so max_steps: 1 passes the check, and step 2 then 409s ("BrowseComp sessions support one activation"). The failure is loud, but an explicit step-driven capability set beside AGENT_SESSION_AGENT_TYPES would refuse it at startup.
  • R3 (--agent-type simple_agent drops max_steps: 1): we reproduced it with gym env resolve. The template-level override ++simple_agent.responses_api_agents.simple_agent.max_steps=1 works around it. ++officeenv_simple_agent...max_steps=1 does not, because of struct mode. Our comment on officeenv.yaml:40 suggests a fix at the root.
  • N1 (partial response lost on a later failure): agree, including the bot's second-round guard that keeps an existing partial_response.
  • N2 (step_limit_owned_by_caller always passed): agree, as optional. #3888 added activation= the same way.
  • N3 (cutoff reported as completed): agree on the gap. incomplete_details can't carry it, though (inline comment on app.py:777).

Our comments below are additions to these items, not repeats of them.

Not verified: OfficeEnv's own tests and behavior. The package is not installable from our side, and every OfficeEnv test skips in CI. The step-loop and simple-agent tests pass on a Linux workstation (26 + 133). Changing the guarded code one place at a time made the new tests fail in all 13 cases we tried.

Comment thread resources_servers/officeenv/README.md Resolved
@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/single-agent-turn-step-loop branch from 9ee5637 to b11bc55 Compare November 16, 2026 01:38
@svcnvidia-nemo-ci svcnvidia-nemo-ci added feature New capabilities, enhancements, or enablement work area:env-infra Shared environment framework, lifecycle, registry, scaffolding, and validation needs-review PR is ready for code review and waiting on a reviewer labels Nov 16, 2026
@d-molinari
d-molinari force-pushed the dmolinari/single-agent-turn-step-loop branch from b11bc55 to f6d0501 Compare November 17, 2026 01:40
@d-molinari

Copy link
Copy Markdown
Contributor Author

Thanks, all. At f6d0501, rebased onto #6161's new head (main 4e3f503):

  • Bot R1: execute_tools is now read as the agent reads it (TypeAdapter(bool)). max_steps is gone from the check (yaoyu's header change below).
  • Bot R2: STEP_DRIVEN_AGENT_TYPES (today simple_agent) sits beside AGENT_SESSION_AGENT_TYPES, and a unit test keeps it in step with the agents. hermes_agent and browsecomp_agent are now refused at startup.
  • Bot R3: fixed at the root, as yaoyu suggested. Under the step-limit header, simple_agent takes one step per activation, so OfficeEnv's config no longer needs max_steps: 1, and --agent-type simple_agent starts.
  • Bot N1: _run_steps keeps the completed steps as partial_response, and doesn't replace one the failure already carries.
  • cmunley1 N2: the step keywords are passed only with the header, and agentic_turn_simulation_agent's override is back to its old signature.
  • cmunley1 N3: the reply's metadata carries ng_termination_reason: max_episode_steps (see yaoyu's thread on line 777 for why not incomplete_details).
  • One more change: OfficeEnv's environment server is now single_agent_turn_legacy. Its taskset rows still run as typed episodes on the step loop, and flat rows (training corpora, NeMo RL's /run) now run too; plain single_agent_turn refused them. It also lets composition relay a session-less agent through legacy_agent, so --agent-type simple_agent_with_compaction runs flat rows again. Collated taskset rows can't reach a session-less agent yet, because a legacy_agent relay takes only flat rows. Closing that is a change to composition, which I'd make in its own PR.

yaoyu's inline notes are answered in their threads.

@d-molinari

Copy link
Copy Markdown
Contributor Author

/ok to test f6d0501

yfw added a commit that referenced this pull request Nov 25, 2026
#6162 now marks a run that a stop ended as completed as completed in the close's agent observations, too
(report_completed_rollout_stop), through the sandbox session that this layer gives rollout stops. The Stirrup
session tests now check that status: completed after a task-end stop, and after a stop before the runner starts it
follows the stop's completed flag.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>
yfw added a commit that referenced this pull request Nov 25, 2026
#5010 merges #6162's head 942c31a and refreshes officeenv_sandbox's lock against main's root dependencies. The
merge had no conflict.

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

yfw commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

/ok to test f1550cc

yfw added a commit that referenced this pull request Nov 25, 2026
…tion

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>
yfw added a commit that referenced this pull request Nov 25, 2026
#5010 now contains #6162 with main 6aa1fd6, so its locks match its own tree. The merge had no conflict.

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

Copy link
Copy Markdown
Contributor

I’ll take over the remaining task-end fixes here. I reproduced a watch waiting behind the running agent for a data connection, and a slow stop reply delaying release past its deadline. I’ll add regression coverage for both and make failed releases visible.

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

Approved after independent review of 3f54743. All three task-end regressions failed on the previous head and passed with the fixes, including the real HTTP case where an activation holds the only data connection. The focused suites passed (702 passed, 2 skipped), and full pre-commit passed. The workstation lacked the private OfficeEnv package, so this rerun did not include an OfficeEnv model rollout.

@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 30, 2026
yaoyu-33 added a commit that referenced this pull request Nov 30, 2026
@yfw

yfw commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

/ok to test 3f54743

@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 30, 2026 17:00
yfw added a commit that referenced this pull request Nov 30, 2026
#5010 now has the task-end fixes from #6162, binds the sandboxless OfficeEnv services to loopback in the mixed
preset, reports Pi's task-end stops after classifying the invocation, and adds a license header. The merge had no
conflict. Stirrup needs no matching change: its agent and environment servers are already on 127.0.0.1, its
resources server keeps the node's address for the sandbox, and it already applies report_rollout_stop last, after
report_outcome.

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

@yfw yfw 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 @yaoyu-33 's latest changes

@yfw
yfw added this pull request to the merge queue Nov 30, 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/46478914933

Merged via the queue into main with commit 0b3fdb3 Nov 30, 2026
84 of 90 checks passed
@yfw
yfw deleted the dmolinari/single-agent-turn-step-loop branch November 30, 2026 18:13
@d-molinari

Copy link
Copy Markdown
Contributor Author

Thanks @yaoyu-33 and @yfw for pushing this over the finish line

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]>
adil-a added a commit that referenced this pull request Dec 1, 2026
Semantic resolution with #6162 in the Docker provider:
- _run takes both spawned (create-cancellation protection) and semaphore (main's upload bound); the chosen
  semaphore guards the slot, and the spawned/_finish_despite_cancellation path is unchanged.
- One _exec_argv(cwd, env, user, stdin, detach): -i from stdin as on main, -d for exec_detached. exec and
  exec_detached keep sharing _run_exec for timeout and runtime-failure mapping.
- Test fakes of _run accept spawned and semaphore; RunRecorder records semaphore and sets spawned.

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

Labels

area:env-infra Shared environment framework, lifecycle, registry, scaffolding, and validation feature New capabilities, enhancements, or enablement work 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