Skip to content

feat(agent): add a pluggable sandbox session capture to SandboxSession - #4279

Draft
ananthsub wants to merge 6 commits into
mainfrom
ananthsub/session-capture-hook
Draft

ananthsub wants to merge 6 commits into
mainfrom
ananthsub/session-capture-hook

Conversation

@ananthsub

@ananthsub ananthsub commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

What changed and why

Some training setups record a harness's model calls, with their token ids, from a component that runs next to the harness inside the task sandbox, for example a proxy the harness calls instead of the model. The shared sandbox session lifecycle used by the Codex, Hermes and Pi agents can now run such a component when one is configured, so each agent does not implement its own start, collection and cleanup ordering. Gym ships only the interface, the lifecycle wiring, tests and a fake; real implementations live outside Gym and are selected by configuration.

Behavior:

  • An adapter starts the capture after its runtime is ready and before it builds the harness command, and points the harness at the endpoint the capture returns.
  • Close collects the capture after the harness has stopped and before the sandbox is released (an owned sandbox is stopped, a borrowed one is handed back). Collection happens at most once across concurrent and retried closes. A borrowed session whose harness cleanup is not confirmed defers collection to the retried close, because the harness may still be calling the component; an owned session collects before its forced stop.
  • Capture problems never fail the episode. A start that raises or is cancelled, a collection that raises or exceeds its timeout, or a session closed before the capture ran produce a masked TokenCapture that names the reason, and the component is aborted under a shield so a cancelled caller cannot interrupt the abort. A cancelled start still propagates the cancellation.
  • When the capture did not start, execute refuses to run the harness, and the adapter can answer the activation without the harness so the episode is still verified and closed while the masked capture keeps the sample out of training.
  • Without a configured capture the lifecycle is unchanged.

Names:

  • New module nemo_gym/agent_utils/sandbox_session_capture.py:
    • SandboxSessionCapture, an abstract base class with async start(sandbox) -> ModelEndpoint, async collect(sandbox) -> TokenCapture (reports an unusable capture as masked instead of raising) and async abort(sandbox) -> None (best effort, never raises). One instance is built per session.
    • SandboxSessionCaptureConfig, the type agents embed as an optional configuration field: implementation ("package.module:ClassName"), options (keyword arguments for the constructor) and collect_timeout_seconds (default 30). The class is imported and checked to be a complete SandboxSessionCapture subclass, and is constructed once with the options, when the configuration loads, so a bad import path, a class that does not implement the interface, or unknown options fail at agent startup with a validation error that names the path.
    • load_sandbox_session_capture_class, the loader behind that validation.
    • The name says where the capture runs: only inside a SandboxSession. The agents that adopt it refuse it on their other request paths. SandboxSession keeps its session_capture field and start_session_capture() method, which the class name already scopes.
  • SandboxSession in nemo_gym/agent_utils/sandbox_session.py:
    • session_capture: SandboxSessionCaptureConfig | None field.
    • start_session_capture() -> ModelEndpoint | None, which the adapter passes to model_endpoint(session_endpoint=...).
    • session_capture_failed, true when a configured capture cannot run.
    • token_capture() -> TokenCapture | None, for the agent's close response; None when no capture is configured.
  • harness_not_run_response(body, *, model, reason) and harness_not_run_observations(*, source, reason) in nemo_gym/agent_utils/sandbox_session.py let any agent answer an activation whose harness must not run (for example when session_capture_failed) the same way: a failed response with an empty assistant message, the request's tool fields and the reason as its error message, plus observations carrying one harness_not_run gap with the reason, so the episode is still verified and closed and its result shows why.

Timeout budget: the environment server bounds agent close with cleanup_timeout_seconds (180 seconds in environment_servers/single_agent_turn/configs/single_agent_turn.yaml). Collection and the abort after a failed collection are each bounded by collect_timeout_seconds. With Hermes' default session_close_timeout_seconds of 30, the existing close phases take at most 120 seconds, leaving room for the 30-second collect default; deployments that raise either value should keep their sum inside the environment server's cleanup timeout.

flowchart TD
    A["Adapter: runtime ready"] --> B["start_session_capture()"]
    B -->|"returns endpoint"| C["model_endpoint(session_endpoint=endpoint)"]
    B -->|"raises or is cancelled"| M1["Masked TokenCapture: capture did not start"]
    M1 --> AB1["abort (shielded)"]
    AB1 --> R1["execute refuses; adapter answers without the harness"]
    C --> D["execute: stage, launch, harness runs"]
    D --> E["Harness stops: cleanup confirmed, artifacts collected"]
    E --> F["close()"]
    R1 --> F
    F --> G{"Borrowed sandbox and cleanup not confirmed?"}
    G -->|"yes"| H["Raise; retried close collects later"]
    G -->|"no"| I{"Capture running?"}
    I -->|"no"| M2["Masked TokenCapture: not running when the session closed"]
    I -->|"yes"| J["collect, bounded by collect_timeout_seconds"]
    J -->|"returns"| K["token_capture() holds the result"]
    J -->|"raises or times out"| M3["Masked TokenCapture with the reason"]
    M3 --> AB2["abort (shielded)"]
    M2 --> L["Release sandbox: stop owned, hand back borrowed"]
    K --> L
    AB2 --> L
    L --> N["Agent close response carries token_capture"]
Loading

This depends on #4276 (SimpleResponsesAPIAgent.model_endpoint and ModelEndpoint) and #4278 (TokenCapture and AgentCloseSessionResponse.token_capture, carried into the episode result by the environment server). It will be rebased onto main once they merge; until then its diff on GitHub includes their commits.

No agent opts in here. The Codex, Hermes and Pi agents adopt SandboxSessionCaptureConfig in separate pull requests, and no environment server change is needed because #4278 already carries token_capture into the episode result.

Linked issue

None. This is the generic hook for capture components that run inside the task sandbox; it builds on #4276 and #4278.

Validation

  • NEMO_GYM_EXTRA_ROOTS=$PWD PYTHONPATH=$PWD python -m pytest tests/unit_tests/test_sandbox_session.py tests/unit_tests/test_agent_sessions.py tests/unit_tests/test_agent_session_retries.py tests/unit_tests/test_base_responses_api_agent.py -q
  • NEMO_GYM_EXTRA_ROOTS=$PWD PYTHONPATH=$PWD python -m pytest responses_api_agents/codex_agent/tests -q
  • NEMO_GYM_EXTRA_ROOTS=$PWD PYTHONPATH=$PWD python -m pytest responses_api_agents/hermes_agent/tests -q (with the Hermes agent's own environment)
  • NEMO_GYM_EXTRA_ROOTS=$PWD PYTHONPATH=$PWD python -m pytest responses_api_agents/pi_agent/tests -q; the three tests in test_outcome.py that need the Pi command line tool fail the same way without this change.
  • pre-commit run --files nemo_gym/agent_utils/sandbox_session_capture.py nemo_gym/agent_utils/sandbox_session.py tests/unit_tests/test_sandbox_session.py

The new tests in tests/unit_tests/test_sandbox_session.py use a fake capture selected through SandboxSessionCaptureConfig and a mocked sandbox, and record the order of capture and sandbox calls. They cover: start returning the endpoint; collection after the harness stops and before release, exactly once across concurrent and repeated closes, for owned and borrowed sandboxes; a failed start masking the capture, aborting the component and making execute refuse without staging; a cancelled start aborting the component and propagating; the abort surviving a second cancellation of its caller; collection that raises or exceeds its timeout masking the capture, aborting the component and still releasing; a timeout error raised by the component reported as a failure rather than a timeout; a masked capture from the component returned unchanged; harness failure and cancelled execution still collecting after cleanup; borrowed cleanup failure deferring collection to the retried close; owned cleanup failure collecting before the forced stop; closing without starting, and closing while the start is in progress; and the configuration rejecting a malformed path, an unimportable module, a missing attribute, a non-class, a class that is not a SandboxSessionCapture, an incomplete subclass and unknown options. Against the previous SandboxSession the new lifecycle tests fail, and removing the abort shield, the collect timeout, the execute refusal, or moving collection after release each fail the corresponding tests.

Rollouts

N/A. This adds an interface and lifecycle wiring that no agent enables yet; a session without a configured capture follows the unchanged lifecycle, which the existing session tests and the Codex, Hermes and Pi suites cover. Rollout evidence belongs to the agent changes that opt in.

Compatibility

Additive. SandboxSession gains an optional session_capture field that defaults to None, and existing callers are unaffected.

ananthsub and others added 4 commits October 8, 2026 22:58
An agent session can now hand back token-level training data that was captured outside Gym's model server, for example by a component that records the harness's model calls next to the task sandbox. `AgentCloseSessionResponse` gains an optional `token_capture` field holding a `TokenCapture`: the captured ATIF trajectories, capture metrics, and a masked flag with its reason.

After the agent session closes, the single_agent_turn environment server adds the capture to the episode result: `atif_trajectories` and `_ng_token_capture` at the top level, and `mask_sample` only when the capture is masked. The reward is unchanged and an unmasked capture never clears a mask the verifier set. The single_agent_turn_legacy flat-row wrapper keeps these fields at the top level of the row.

Signed-off-by: Ananth Subramaniam <[email protected]>
Rollout collection rejected every `_ng_*` key in an environment server's typed result, so any SingleAgentTurnRequest episode that carried `_ng_token_capture` from a capture outside Gym's model server failed. Allow exactly that key; identity, failure, and assembled observation keys remain reserved for rollout collection.

Co-authored-by: yaoyu-33 <[email protected]>
Signed-off-by: Ananth Subramaniam <[email protected]>
Agents that drive an external harness each decide on their own where the
harness sends model calls: a Gym model server with the rollout capture
prefix, or a directly configured OpenAI-compatible base URL. A later
session component that records model calls needs to substitute its own
endpoint, and agents should be able to run without a Gym model server
when another endpoint is supplied.

SimpleResponsesAPIAgent.model_endpoint now makes that choice in one
place. It returns a ModelEndpoint (base URL and an optional model name)
in this order: an endpoint the caller passes for the episode's session,
the model server through resolve_model_base_url (keeping the rollout
prefix and the training token capture route), then the agent's
configured base URL verbatim. It raises ValueError when none is set.
No agent is changed here; each adopts the helper in its own change.

Signed-off-by: Ananth Subramaniam <[email protected]>
…ifecycle

Some training setups record a harness's model calls, with their token ids, from a component that runs next to the harness inside the task sandbox, for example a proxy the harness calls instead of the model. SandboxSession, the execute, stop, collect and release lifecycle shared by the Codex, Hermes and Pi agents, now runs such a component when one is configured, so agents do not each implement its start, collection and cleanup ordering.

A capture implements the new SessionCapture interface: start returns the ModelEndpoint the harness must call, collect stops the component and returns a TokenCapture, and abort stops it without collecting. SessionCaptureConfig selects the implementation by import path with keyword options and a collect timeout; the class and its options are validated when the configuration loads, so a bad path, a class that is not a complete SessionCapture, or unknown options fail at agent startup.

The adapter awaits start_session_capture before it builds the harness command and passes the endpoint to model_endpoint. Close collects the capture after the harness has stopped and before the sandbox is released (an owned sandbox is stopped, a borrowed one is handed back), at most once, and token_capture returns it for the agent's close response. A borrowed session whose harness cleanup is not confirmed defers collection to the retried close, because the harness may still be calling the component. Capture problems never fail the episode: a start that fails or is cancelled, a collection that raises or exceeds its timeout, or a session closed before the capture ran produce a masked TokenCapture with the reason, and the component is aborted under a shield so a cancelled caller cannot interrupt it. When the capture did not start, execute refuses to run the harness and session_capture_failed tells the adapter to answer the activation without it.

Without a configured capture the lifecycle is unchanged. No agent opts in here; each does in its own change.

Signed-off-by: Ananth Subramaniam <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Oct 9, 2026

Copy link
Copy Markdown

Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

@ananthsub ananthsub changed the title # feat(agent): add a pluggable session capture to the sandbox session lifecycle feat(agent): add a pluggable session capture to the sandbox session lifecycle Oct 9, 2026
…ailing the episode

When a sandbox session's capture does not start, execute refuses to run the harness, but raising from the activation would fail the whole episode for a capture problem. harness_not_run_response gives every agent the same answer instead: a failed response with an empty assistant message, the request's model and tool fields, and the reason as its error message. harness_not_run_observations returns the matching observations, one harness_not_run gap whose detail is the reason, so the close response does not report an unrelated observation failure.

The environment server then still verifies and closes the episode, its result shows why the harness did not run, and the session's masked token capture keeps the sample out of training.

Signed-off-by: Ananth Subramaniam <[email protected]>
The capture runs only inside a SandboxSession, and agents refuse it on
every other path. Naming it after the sandbox session says so where it
is configured and in its error messages. The module moves to
nemo_gym/agent_utils/sandbox_session_capture.py. SandboxSession keeps
its session_capture field and start_session_capture method, which are
already scoped by the class.

Signed-off-by: Ananth Subramaniam <[email protected]>
@ananthsub ananthsub changed the title feat(agent): add a pluggable session capture to the sandbox session lifecycle feat(agent): add a pluggable sandbox session capture to SandboxSession Oct 9, 2026
@svcnvidia-nemo-ci svcnvidia-nemo-ci added area:agent Agent harnesses and Responses API agent behavior feature New capabilities, enhancements, or enablement work labels Oct 20, 2026

This branch has not been deployed

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

Labels

area:agent Agent harnesses and Responses API agent behavior feature New capabilities, enhancements, or enablement work

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants