diff --git a/docs/getting_started/quickstart.md b/docs/getting_started/quickstart.md index 1cd8d7f..e962787 100644 --- a/docs/getting_started/quickstart.md +++ b/docs/getting_started/quickstart.md @@ -94,6 +94,14 @@ ROLLOUT_NNODES=32 MODEL= EVAL_STEP= RUN=$WORK_DIR/runs/eval bas The records and the summary land in `$RUN/val_dumps/eval_.jsonl` and `$RUN/val_dumps/eval__summary.json`. +## Model-controlled completion in LIBERO + +Set `policy_finish: true` in the LIBERO entry of the recipe's tool config +(`actor_rollout_ref.rollout.multi_turn.tool_config_path`). The model can submit its usual action or a fenced JSON block +containing `{"finish": true}`. Reaching the goal still returns an observation while there is budget for another turn. When the model emits `finish`, LIBERO checks the +current state and the rollout receives 1 for success or 0 for failure. A rollout that exhausts the native step or token +budget without finishing receives 0. The episode records `finish` and `budget` as distinct end reasons. + ## Next Steps - [Robot-Use RL with Qwen3.8-27B](../../examples/models/qwen3_8_27b_pear/train/README.md): stages 2 and 3 diff --git a/examples/models/qwen3_8_27b_pear/train/libero_robodojo_tool_config.yaml b/examples/models/qwen3_8_27b_pear/train/libero_robodojo_tool_config.yaml index 805b882..c0a4e11 100644 --- a/examples/models/qwen3_8_27b_pear/train/libero_robodojo_tool_config.yaml +++ b/examples/models/qwen3_8_27b_pear/train/libero_robodojo_tool_config.yaml @@ -5,6 +5,7 @@ tools: config: type: native env_class: pear.envs.libero.env.LiberoEnv # the family: its facts and its simulator + policy_finish: false # true lets the model finish the episode # its servers: one per slot the rollout machines offer as libero (scripts/start_ray_node.sh) log_dir: ${oc.env:PEAR_LOG_DIR} # the servers' logs and the tool's call log (the recipe: $RUN/sim) - class_name: pear.envs.tool.EnvironmentTool diff --git a/pear/agent_loop/agent_loop.py b/pear/agent_loop/agent_loop.py index eef623b..fd35f05 100644 --- a/pear/agent_loop/agent_loop.py +++ b/pear/agent_loop/agent_loop.py @@ -76,6 +76,8 @@ async def run(self, sampling_params: dict[str, Any], **kwargs) -> AgentLoopOutpu # the episode's record for the val dumps and the evaluation's records, as a dict (verl ships extra_fields as # JSON); written only now: verl takes an empty extra_fields as the mark of the first generation output.extra_fields["episode"] = self.episode.record() + if getattr(self.tool, "policy_finish", False): + output.extra_fields["episode"]["end_reason"] = self.end_reason.value # uid is the prompt's id, shared by the n trajectories of a group; global_steps is the training step (both from # verl's batch) @@ -167,6 +169,11 @@ async def _handle_processing_tools_state(self, agent_data: AgentData) -> AgentSt if self.episode.done: self.end_reason = EndReason.ENV + if getattr(self.tool, "policy_finish", False): + if result["outcome"] == "finish": + self.end_reason = EndReason.FINISH + elif result["outcome"] == "budget": + self.end_reason = EndReason.BUDGET return AgentState.TERMINATED return await self._resume_generating(agent_data, {"role": "user", "content": content}) diff --git a/pear/agent_loop/episode.py b/pear/agent_loop/episode.py index 02e187b..3d6639e 100644 --- a/pear/agent_loop/episode.py +++ b/pear/agent_loop/episode.py @@ -10,8 +10,9 @@ class EndReason(str, Enum): """How an episode ends, each by the text its EPISODE_END record names it with.""" ENV = "env" # the environment finished it + FINISH = "finish" # the model declared the task complete PARSE = "parse" # an answer without a usable action - BUDGET = "budget" # its response tokens ran out + BUDGET = "budget" # its response tokens or native steps ran out @dataclass(eq=False) # each episode is a run of its own: two are never the same by their contents @@ -52,5 +53,7 @@ def record(self) -> dict[str, Any]: @staticmethod def is_success(result: dict[str, Any]) -> bool: - """Returns whether ``result`` ends its episode with the task done: its action earned a reward.""" + """Returns whether the result ends the episode with the task complete.""" + if "task_success" in result: + return bool(result["done"]) and result["task_success"] return bool(result["done"]) and sum(float(reward) for reward in result["rewards"]) > 0.0 diff --git a/pear/agent_loop/protocol.py b/pear/agent_loop/protocol.py index 774867e..12ee8a9 100644 --- a/pear/agent_loop/protocol.py +++ b/pear/agent_loop/protocol.py @@ -12,6 +12,11 @@ class JsonBlockProtocol: JSON_BLOCK_PATTERN = re.compile(r"```json\s*(\{.*?\})\s*```", re.DOTALL) # a fenced json block and its object + @staticmethod + def is_finish(action: Any) -> bool: + """Whether the output is the explicit finish action.""" + return isinstance(action, dict) and action.keys() == {"finish"} and action["finish"] is True + @staticmethod def system_prompt(template: str, environment: str, instruction: str) -> str: """Returns ``template`` with the family's facts as its ENVIRONMENT section (no section without facts) and the diff --git a/pear/envs/libero/configs/tool_config.yaml b/pear/envs/libero/configs/tool_config.yaml index 3814e78..d74ce66 100644 --- a/pear/envs/libero/configs/tool_config.yaml +++ b/pear/envs/libero/configs/tool_config.yaml @@ -6,5 +6,6 @@ tools: config: type: native env_class: pear.envs.libero.env.LiberoEnv # the family: its facts and its simulator + policy_finish: false # true lets the model finish the episode # its servers: one per slot the rollout machines offer as libero (scripts/start_ray_node.sh) log_dir: ${oc.env:PEAR_LOG_DIR} # the servers' logs and the tool's call log (the recipe: $RUN/sim) diff --git a/pear/envs/libero/controller.py b/pear/envs/libero/controller.py index 11d1cd6..8f3749a 100644 --- a/pear/envs/libero/controller.py +++ b/pear/envs/libero/controller.py @@ -85,7 +85,9 @@ def __init__(self, scene: Any, observation: dict[str, np.ndarray], action: dict[ self.stall_step_n = self.slow_stall_step_n = 0 self.is_stopping = False - def move(self, budget: int) -> tuple[dict[str, np.ndarray], list[list[float]], list[float], bool, str]: + def move( + self, budget: int, *, stop_on_success: bool = True + ) -> tuple[dict[str, np.ndarray], list[list[float]], list[float], bool, str]: """Native actions toward the targets until they are reached at rest, the robot stops short of them, the task ends, or the episode's ``budget`` or the action's cap runs out: the last observation, the actions, their rewards, whether the episode ended and the outcome (reached | stopped | done | budget | timeout).""" @@ -97,7 +99,8 @@ def move(self, budget: int) -> tuple[dict[str, np.ndarray], list[list[float]], l self.observation, reward, done, _ = self.scene.step(native_action) actions.append(native_action.tolist()) rewards.append(float(reward)) - if done: + # The pinned LIBERO sets done to its task success predicate. + if done and stop_on_success: return self.observation, actions, rewards, True, "done" outcome = self._step_outcome() if outcome is not None: diff --git a/pear/envs/libero/env.py b/pear/envs/libero/env.py index e344188..c99f06c 100644 --- a/pear/envs/libero/env.py +++ b/pear/envs/libero/env.py @@ -18,6 +18,7 @@ import torch from PIL import Image +from pear.agent_loop.protocol import JsonBlockProtocol from pear.envs.libero.controller import MotionController from pear.sim.env import StatelessEnv from pear.sim.process import SimulatorProcess @@ -62,14 +63,18 @@ class LiberoEnv(StatelessEnv): # the family's conversation (EnvironmentTool) SCHEMA = MotionController.SCHEMA CAMERAS = ("agentview", "wrist") # the frames of an observation, in this order - ENVIRONMENT_PROMPT = Path(__file__).with_name("environment_prompt.md").read_text().strip() + POLICY_FINISH_ENVIRONMENT_PROMPT = Path(__file__).with_name("environment_prompt.md").read_text().strip() + ENVIRONMENT_PROMPT = ( + POLICY_FINISH_ENVIRONMENT_PROMPT + + "\n- the episode ends by itself as soon as the task is done: while observations keep coming, the task is not done yet." + ) # beyond this the simulator process is hung, even in a replay of the longest episode (520 steps) ROLLOUT_TIMEOUT_S = 180.0 # LIBERO benchmark object per suite (instruction, bddl file, init states), process-wide _benchmark_by_suite: dict[str, Any] = {} - def __init__(self, suite: str, task_id: int, trial_id: int) -> None: + def __init__(self, suite: str, task_id: int, trial_id: int, policy_finish: bool = False) -> None: if suite not in self.MAX_STEP_N_BY_SUITE: raise ValueError(f"unknown suite {suite!r}; known: {sorted(self.MAX_STEP_N_BY_SUITE)}") assert 0 <= int(trial_id) < self.TRIALS_PER_TASK, ( @@ -79,6 +84,7 @@ def __init__(self, suite: str, task_id: int, trial_id: int) -> None: self.suite = suite self.task_id = int(task_id) self.trial_id = int(trial_id) + self.policy_finish = policy_finish self.scene: Any = None # the OffScreenRenderEnv of the current call self._render_cache: dict[tuple, Any] = {} @@ -147,10 +153,16 @@ def rollout(self, history: list[list[float]], action: dict[str, Any] | None) -> outcome = None done = len(history) >= max_step_n # nothing left to execute: the budget is already spent if action is not None and not done: - with self._no_render(): # the controller steps the scene and reads only proprioception - observation, actions, rewards, done, outcome = MotionController( - self.scene, observation, action - ).move(max_step_n - len(history)) + if self.policy_finish and JsonBlockProtocol.is_finish(action): + done, outcome = True, "finish" + else: + with self._no_render(): # the controller steps the scene and reads only proprioception + observation, actions, rewards, done, outcome = MotionController( + self.scene, observation, action + ).move(max_step_n - len(history), stop_on_success=not self.policy_finish) + + if self.policy_finish and len(history) + len(actions) >= max_step_n: + done, outcome = True, "budget" result: EnvResult = { "images": None, # the frames come below, while the episode goes on @@ -159,13 +171,15 @@ def rollout(self, history: list[list[float]], action: dict[str, Any] | None) -> "rewards": rewards, "done": done, "executed": len(actions), - "outcome": outcome, # reached | stopped | done | budget | timeout + "outcome": outcome, # reached | stopped | done | budget | timeout | finish "instruction": re.sub( r"\b(left|right)\b", lambda match: self.MIRRORED_SIDE_BY_SIDE[match.group(1)], str(self._benchmark().get_task(self.task_id).language), ), } + if self.policy_finish and done: + result["task_success"] = outcome == "finish" and bool(self.scene.check_success()) if not done: if len(history) or actions: # the reset rendered its last step, the replay and the action nothing observation = self.scene.env._get_observations(force_update=True) diff --git a/pear/envs/libero/environment_prompt.md b/pear/envs/libero/environment_prompt.md index 66b635c..1068998 100644 --- a/pear/envs/libero/environment_prompt.md +++ b/pear/envs/libero/environment_prompt.md @@ -1,3 +1,2 @@ - agentview: a fixed camera; the robot's base is at the top of its image, +x points toward the bottom of the image and +y toward its left. - wrist: a camera on the gripper; with the gripper pointing straight down at yaw 0, +x points toward the top of its image and +y toward its right. -- the episode ends by itself as soon as the task is done: while observations keep coming, the task is not done yet. diff --git a/pear/envs/tool.py b/pear/envs/tool.py index 9ec2691..4bc7daa 100644 --- a/pear/envs/tool.py +++ b/pear/envs/tool.py @@ -29,11 +29,18 @@ class EnvironmentTool(BaseTool): SYSTEM_PROMPT_TEMPLATE = Path(__file__).with_name("system_prompt.md").read_text() # repeated every turn: without it the model drops the json block REMINDER = "The current camera frames follow. End your response with one json block containing the next action." + FINISH_INSTRUCTION = ( + 'End your response with one fenced json block containing the next action or {"finish": true} ' + "if you have completed the task." + ) def __init__(self, config: dict, tool_schema: OpenAIFunctionToolSchema | None = None) -> None: # one instance per agent-loop process (PEAR's trainer config keeps verl's dataset from building the tools on # the driver); the loop's episodes run on its client self.env_class: type[BaseEnv] = pkgutil.resolve_name(config["env_class"]) # the family's facts and simulator + self.policy_finish = config.get("policy_finish", False) + if self.policy_finish and self.env_class.POLICY_FINISH_ENVIRONMENT_PROMPT is None: + raise ValueError(f"policy_finish is not supported by {config['env_class']}") self.client = pkgutil.resolve_name(self.env_class.CLIENT_CLASS_PATH)(self.env_class) # its kind's client self.log_path = Path(str(config["log_dir"])) / f"actions_{os.getpid()}.jsonl" self.log_path.parent.mkdir(parents=True, exist_ok=True) @@ -63,22 +70,25 @@ def get_openai_tool_schema(self) -> OpenAIFunctionToolSchema: async def open(self, episode: Episode) -> tuple[list[dict[str, Any]] | None, EnvResult]: """Opens ``episode`` and returns the first user turn's content with the result of its initial observation.""" steps_before, start_time = len(episode.actions), time.monotonic() - result = await self.client.open(episode.uid, episode.env_args) + env_args = {**episode.env_args, "policy_finish": True} if self.policy_finish else episode.env_args + result = await self.client.open(episode.uid, env_args) self._log_call(episode, steps_before, None, result, time.monotonic() - start_time) return self._observation(result), result def system_prompt(self, result: EnvResult) -> str: """Returns the episode's system prompt, from the result of its initial observation.""" - return JsonBlockProtocol.system_prompt( - self.SYSTEM_PROMPT_TEMPLATE, self.env_class.environment_prompt(result), result["instruction"] - ) + environment = self.env_class.environment_prompt(result) + if self.policy_finish: + environment = f"{self.env_class.POLICY_FINISH_ENVIRONMENT_PROMPT}\n- {self.FINISH_INSTRUCTION}" + return JsonBlockProtocol.system_prompt(self.SYSTEM_PROMPT_TEMPLATE, environment, result["instruction"]) async def step(self, episode: Episode, action: Any) -> tuple[list[dict[str, Any]] | None, EnvResult]: """Carries out the answer's ``action`` in ``episode`` and returns the next user turn's content (None once the episode ended) with the result; raises InvalidAction for a json block that is no action.""" steps_before, start_time = len(episode.actions), time.monotonic() - JsonBlockProtocol.check_action(action, self.env_class.SCHEMA) + if not (self.policy_finish and JsonBlockProtocol.is_finish(action)): + JsonBlockProtocol.check_action(action, self.env_class.SCHEMA) result = await self.client.step(episode.uid, action) self._log_call(episode, steps_before, action, result, time.monotonic() - start_time) @@ -117,7 +127,10 @@ def _observation(self, result: EnvResult) -> list[dict[str, Any]] | None: if result["images"] is None: return None - text = JsonBlockProtocol.turn_text(result["state"], self.REMINDER) + reminder = ( + f"The current camera frames follow. {self.FINISH_INSTRUCTION}" if self.policy_finish else self.REMINDER + ) + text = JsonBlockProtocol.turn_text(result["state"], reminder) blocks: list[dict[str, Any]] = [{"type": "text", "text": text}] for name, image in zip(self.env_class.CAMERAS, result["images"]): diff --git a/pear/sim/env.py b/pear/sim/env.py index 5017874..412e027 100644 --- a/pear/sim/env.py +++ b/pear/sim/env.py @@ -30,6 +30,7 @@ class BaseEnv(ABC): CAMERAS: tuple[str, ...] # the frames' names, in the order of a result's images ENVIRONMENT_PROMPT: str # the facts the protocol leaves out, in the family's words; empty: no ENVIRONMENT section LOG_KEYS: tuple[str, ...] = () # the keys of its results the call log records besides the protocol's + POLICY_FINISH_ENVIRONMENT_PROMPT: str | None = None @classmethod def server_n(cls, config: dict[str, Any], cluster_resources: dict[str, float]) -> int: diff --git a/pear/sim/schemas.py b/pear/sim/schemas.py index 7edf3cb..cbbeacb 100644 --- a/pear/sim/schemas.py +++ b/pear/sim/schemas.py @@ -14,7 +14,11 @@ class ServerContext: log: Callable[[str], None] # appends a message to the server's log -class EnvResult(TypedDict): +class _TerminalResult(TypedDict, total=False): + task_success: bool # explicit verdict for a terminal result in policy finish mode + + +class EnvResult(_TerminalResult): """What one call of an env returns: the protocol's keys, in this order, before the keys of the family's own.""" images: list[Any] | None # the cameras' frames in CAMERAS order; None once the episode ended diff --git a/tests/agent_loop/test_agent_loop_invalid_action_on_cpu.py b/tests/agent_loop/test_agent_loop_invalid_action_on_cpu.py index efc023b..4e9d1a9 100644 --- a/tests/agent_loop/test_agent_loop_invalid_action_on_cpu.py +++ b/tests/agent_loop/test_agent_loop_invalid_action_on_cpu.py @@ -15,6 +15,7 @@ ZERO = {"arm": {"x": 0.0, "y": 0.0, "z": 0.0, "roll": 0.0, "pitch": 0.0, "yaw": 0.0}, "gripper": {"width": 0.0}} # json blocks that are no action of LIBERO's schema, each with the tool's reason INVALID_ACTIONS = [ + ({"finish": True}, "the json block must map exactly the parts arm, gripper to their quantities"), ([ZERO], "the json block must map exactly the parts arm, gripper to their quantities"), ({"arm": ZERO["arm"]}, "the json block must map exactly the parts arm, gripper to their quantities"), ({**ZERO, "gripper": {}}, "'gripper' must give exactly its quantities width"), diff --git a/tests/agent_loop/test_policy_finish_on_cpu.py b/tests/agent_loop/test_policy_finish_on_cpu.py new file mode 100644 index 0000000..407e7dc --- /dev/null +++ b/tests/agent_loop/test_policy_finish_on_cpu.py @@ -0,0 +1,77 @@ +import asyncio +import json +from types import SimpleNamespace + +import pytest +from PIL import Image + +from pear.agent_loop.agent_loop import PearAgentLoop +from pear.agent_loop.episode import EndReason, Episode +from pear.agent_loop.protocol import InvalidAction +from pear.envs.libero.env import LiberoEnv +from pear.envs.tool import EnvironmentTool +from verl.experimental.agent_loop.tool_agent_loop import AgentState + + +class Client: + def __init__(self, env_class): + pass + + async def open(self, uid, env_args): + assert env_args["policy_finish"] is True + return { + "images": [Image.new("RGB", (1, 1)) for _ in LiberoEnv.CAMERAS], + "state": {}, + "actions": [], + "rewards": [], + "done": False, + "executed": 0, + "outcome": None, + "instruction": "Place the bowl on the plate.", + } + + async def step(self, uid, action): + assert action == {"finish": True} + return { + "images": None, + "state": {}, + "actions": [], + "rewards": [], + "done": True, + "executed": 0, + "outcome": "finish", + "instruction": "Place the bowl on the plate.", + "task_success": True, + } + + +def test_a_policy_finish_reaches_libero_and_terminates_the_agent_loop(tmp_path, monkeypatch): + monkeypatch.setattr(LiberoEnv, "CLIENT_CLASS_PATH", f"{__name__}.{Client.__qualname__}") + loop = object.__new__(PearAgentLoop) + loop.tool = EnvironmentTool( + {"env_class": "pear.envs.libero.env.LiberoEnv", "log_dir": str(tmp_path), "policy_finish": True} + ) + loop.episode = Episode({"suite": "libero_goal", "task_id": 3, "trial_id": 0}) + loop.end_reason = None + agent_data = SimpleNamespace(metrics={}, tool_calls=[SimpleNamespace(arguments=json.dumps({"finish": True}))]) + observation, initial = asyncio.run(loop.tool.open(loop.episode)) + prompt = loop.tool.system_prompt(initial) + assert '{"finish": true}' in prompt + assert '{"finish": true}' in observation[0]["text"] + assert "the episode ends by itself" not in prompt + + state = asyncio.run(loop._handle_processing_tools_state(agent_data)) + + assert (state, loop.end_reason) == (AgentState.TERMINATED, EndReason.FINISH) + assert (loop.episode.done, loop.episode.success, loop.episode.actions) == (True, True, []) + + +@pytest.mark.parametrize("action", [{"finish": 1}, {"finish": True, "arm": {}}]) +def test_malformed_finish_stays_an_invalid_action(tmp_path, monkeypatch, action): + monkeypatch.setattr(LiberoEnv, "CLIENT_CLASS_PATH", f"{__name__}.{Client.__qualname__}") + tool = EnvironmentTool( + {"env_class": "pear.envs.libero.env.LiberoEnv", "log_dir": str(tmp_path), "policy_finish": True} + ) + + with pytest.raises(InvalidAction): + asyncio.run(tool.step(Episode({}), action)) diff --git a/tests/envs/test_libero_policy_finish_on_cpu.py b/tests/envs/test_libero_policy_finish_on_cpu.py new file mode 100644 index 0000000..1e8cdcf --- /dev/null +++ b/tests/envs/test_libero_policy_finish_on_cpu.py @@ -0,0 +1,112 @@ +from contextlib import nullcontext +from types import SimpleNamespace + +import numpy as np +import pytest + +from pear.agent_loop.episode import Episode +from pear.envs.libero.controller import MotionController +from pear.envs.libero.env import LiberoEnv + +ENV_ARGS = {"suite": "libero_goal", "task_id": 3, "trial_id": 0} +FINISH = {"finish": True} + + +def move_to(position): + action = {part: dict.fromkeys(quantities, 0) for part, quantities in MotionController.SCHEMA.items()} + action["arm"]["x"] = position + return action + + +class Scene: + """A LIBERO-shaped scene whose goal is satisfied at position 1.""" + + def __init__(self): + self.env = self + self.position = 0 + self.steps = 0 + + def check_success(self): + return self.position == 1 + + def _get_observations(self, *, force_update=False): + frame = np.full((2, 2, 3), self.position, dtype=np.uint8) + return {"agentview_image": frame, "robot0_eye_in_hand_image": frame} + + def step(self, action): + self.steps += 1 + self.position = int(action[0]) + success = self.check_success() + return self._get_observations(), float(success), success, {} + + +@pytest.fixture +def make_env(monkeypatch): + def open_scene(env): + env.scene = Scene() + return env.scene._get_observations() + + def init_motion(controller, scene, observation, action): + controller.scene = scene + controller.observation = observation + controller.position = action["arm"]["x"] + controller.start_step = scene.steps + + benchmark = SimpleNamespace(get_task=lambda _: SimpleNamespace(language="Place the bowl on the plate.")) + monkeypatch.setattr(LiberoEnv, "_bind_rendering", lambda _: None) + monkeypatch.setattr(LiberoEnv, "_open_scene", open_scene) + monkeypatch.setattr(LiberoEnv, "_close_scene", lambda _: None) + monkeypatch.setattr(LiberoEnv, "_no_render", lambda _: nullcontext()) + monkeypatch.setattr(LiberoEnv, "_benchmark", lambda _: benchmark) + monkeypatch.setattr(MotionController, "__init__", init_motion) + monkeypatch.setattr(MotionController, "_arm_offsets", lambda self: [self.position, 0, 0, 0, 0, 0]) + monkeypatch.setattr(MotionController, "_grip_direction", lambda _: 0) + monkeypatch.setattr( + MotionController, "_step_outcome", lambda self: "reached" if self.scene.steps - self.start_step == 2 else None + ) + monkeypatch.setattr(MotionController, "state", staticmethod(lambda scene, _: {"position": {"x": scene.position}})) + return lambda **kwargs: LiberoEnv(**ENV_ARGS, **kwargs) + + +@pytest.mark.parametrize(("positions", "success"), [([], False), ([1], True), ([1, 0], False)]) +def test_finish_scores_only_the_final_state(make_env, positions, success): + env = make_env(policy_finish=True) + episode = Episode(ENV_ARGS) + for position in positions: + result = env.rollout(episode.actions, move_to(position)) + episode.update(result) + assert not episode.done + assert not episode.success + assert result["executed"] == 2 + assert all(image.getpixel((0, 0)) == (position,) * 3 for image in result["images"]) + + result = env.rollout(episode.actions, FINISH) + episode.update(result) + + assert episode.done + assert episode.success is success + assert (result["outcome"], result["images"], result["executed"]) == ("finish", None, 0) + assert len(episode.actions) == 2 * len(positions) + + +def test_policy_finish_at_step_budget_is_a_truncation(make_env, monkeypatch): + env = make_env(policy_finish=True) + monkeypatch.setattr(env, "MAX_STEP_N_BY_SUITE", {"libero_goal": 2}) + episode = Episode(ENV_ARGS) + + result = env.rollout([], move_to(1)) + episode.update(result) + + assert (episode.done, episode.success) == (True, False) + assert (result["outcome"], result["rewards"], result["images"]) == ("budget", [1.0, 1.0], None) + + +def test_default_mode_stops_at_first_successful_native_step(make_env): + env = make_env() + episode = Episode(ENV_ARGS) + + result = env.rollout([], move_to(1)) + episode.update(result) + + assert (episode.done, episode.success) == (True, True) + assert (result["outcome"], result["executed"], result["images"]) == ("done", 1, None)