|
| 1 | +from pathlib import Path |
| 2 | + |
| 3 | +from terminal_bench.handlers.trial_handler import TrialHandler |
| 4 | +from terminal_bench.parsers.base_parser import UnitTestStatus |
| 5 | +from terminal_bench.parsers.parser_factory import ParserFactory |
| 6 | +from terminal_bench.terminal.docker_compose_manager import DockerComposeManager |
| 7 | +from terminal_bench.terminal.terminal import Terminal |
| 8 | + |
| 9 | +from rllm.agents.agent import Episode |
| 10 | +from rllm.integrations.terminal_terminus_1 import RLLMModel |
| 11 | +from rllm.workflows.workflow import TerminationEvent, TerminationReason, Workflow |
| 12 | + |
| 13 | + |
| 14 | +class TerminalTerminusWorkflow(Workflow): |
| 15 | + """Run Terminus 1 with a generic rollout engine and return an Episode.""" |
| 16 | + |
| 17 | + def __init__( |
| 18 | + self, |
| 19 | + rollout_engine, |
| 20 | + model_name: str, |
| 21 | + env_args: dict | None = None, |
| 22 | + max_steps: int = 50, |
| 23 | + global_agent_timeout_sec: float | None = 600.0, |
| 24 | + **kwargs, |
| 25 | + ): |
| 26 | + super().__init__(rollout_engine=rollout_engine, **kwargs) |
| 27 | + self.model_name = model_name |
| 28 | + self.env_args = dict(env_args) if env_args is not None else {} |
| 29 | + self.max_steps = max_steps |
| 30 | + self.global_agent_timeout_sec = global_agent_timeout_sec |
| 31 | + |
| 32 | + self.trial_handler: TrialHandler | None = None |
| 33 | + self.terminal: Terminal | None = None |
| 34 | + self.session = None |
| 35 | + self.parser = None |
| 36 | + self.terminus: RLLMModel | None = None |
| 37 | + |
| 38 | + async def run(self, task: dict, uid: str, **kwargs) -> Episode: |
| 39 | + """Reset, run Terminus to completion, evaluate, and package an Episode.""" |
| 40 | + observation, info = await self.run_in_executor(self._reset_env, task=task, uid=uid) |
| 41 | + |
| 42 | + prompt = observation["prompt"] |
| 43 | + assert self.session is not None and self.terminus is not None |
| 44 | + |
| 45 | + trajectory, termination_reason = await self.terminus.run_agent_loop_with_engine( |
| 46 | + initial_prompt=prompt, |
| 47 | + session=self.session, |
| 48 | + ) |
| 49 | + |
| 50 | + try: |
| 51 | + reward = await self.run_in_executor(self._evaluate_completion_sync) |
| 52 | + finally: |
| 53 | + await self.run_in_executor(self._close_env) |
| 54 | + |
| 55 | + episode = Episode(id=uid, task=task, is_correct=bool(reward > 0), trajectories=[("terminus", trajectory)]) |
| 56 | + episode.termination_reason = termination_reason |
| 57 | + return episode |
| 58 | + |
| 59 | + async def _eval_and_terminate(self) -> None: |
| 60 | + try: |
| 61 | + await self.run_in_executor(self._evaluate_completion_sync) |
| 62 | + finally: |
| 63 | + await self.run_in_executor(self._close_env) |
| 64 | + raise TerminationEvent(TerminationReason.ENV_DONE) |
| 65 | + |
| 66 | + # ------------------------------ Sync helpers ------------------------------ |
| 67 | + def _reset_env(self, task: dict, uid: str): |
| 68 | + """Create trial, start containers and session, and build initial prompt.""" |
| 69 | + output_path = Path("/tmp/rllm_terminal_bench_output") |
| 70 | + output_path.mkdir(parents=True, exist_ok=True) |
| 71 | + |
| 72 | + task_path = Path(task.get("task_path")) |
| 73 | + instruction = task.get("instruction") |
| 74 | + task_id = task.get("task_id", "unknown") |
| 75 | + |
| 76 | + self.trial_handler = TrialHandler( |
| 77 | + trial_name=f"{task_id}.{uid}.rllm-run", |
| 78 | + input_path=task_path, |
| 79 | + output_path=output_path, |
| 80 | + ) |
| 81 | + |
| 82 | + task_config = self.trial_handler.task |
| 83 | + self.parser = ParserFactory.get_parser(task_config.parser_name) |
| 84 | + |
| 85 | + self.terminal = Terminal( |
| 86 | + client_container_name=self.trial_handler.client_container_name, |
| 87 | + client_image_name=self.trial_handler.client_image_name, |
| 88 | + docker_compose_path=self.trial_handler.task_paths.docker_compose_path, |
| 89 | + docker_image_name_prefix=self.trial_handler.docker_image_name_prefix, |
| 90 | + sessions_logs_path=self.trial_handler.trial_paths.sessions_path, |
| 91 | + agent_logs_path=self.trial_handler.trial_paths.agent_logging_dir, |
| 92 | + no_rebuild=self.env_args.get("no_rebuild", False), |
| 93 | + cleanup=self.env_args.get("cleanup", True), |
| 94 | + ) |
| 95 | + self.terminal.start() |
| 96 | + self.session = self.terminal.create_session("agent", is_active_stream=False, as_configured_user=True) |
| 97 | + |
| 98 | + self.terminus = RLLMModel( |
| 99 | + rollout_engine=self.rollout_engine, |
| 100 | + model_name=self.model_name, |
| 101 | + max_episodes=self.max_steps, |
| 102 | + global_agent_timeout_sec=self.global_agent_timeout_sec, |
| 103 | + api_base=self.env_args.get("api_base"), |
| 104 | + ) |
| 105 | + |
| 106 | + initial_prompt = self.terminus.build_initial_prompt(instruction=instruction, terminal_state=self.session.capture_pane()) |
| 107 | + |
| 108 | + observation = {"prompt": initial_prompt, "type": "initial"} |
| 109 | + info = { |
| 110 | + "task_id": task_id, |
| 111 | + "episode": 0, |
| 112 | + "max_steps": self.max_steps, |
| 113 | + "instruction": instruction, |
| 114 | + } |
| 115 | + return observation, info |
| 116 | + |
| 117 | + def _evaluate_completion_sync(self) -> float: |
| 118 | + """Copy tests, run them, parse output, and return a binary reward.""" |
| 119 | + assert self.trial_handler is not None and self.terminal is not None |
| 120 | + |
| 121 | + # Copy tests into the container |
| 122 | + paths = [self.trial_handler.task_paths.run_tests_path] |
| 123 | + if self.trial_handler.task_paths.test_dir.exists(): |
| 124 | + paths.append(self.trial_handler.task_paths.test_dir) |
| 125 | + self.terminal.copy_to_container( |
| 126 | + paths=paths, |
| 127 | + container_dir=str(DockerComposeManager.CONTAINER_TEST_DIR), |
| 128 | + ) |
| 129 | + |
| 130 | + # Choose session per config |
| 131 | + if self.trial_handler.task.run_tests_in_same_shell: |
| 132 | + print(1) |
| 133 | + test_session = self.session |
| 134 | + else: |
| 135 | + print(2) |
| 136 | + test_session = self.terminal.create_session("tests", is_active_stream=False, as_configured_user=False) |
| 137 | + |
| 138 | + # Execute tests |
| 139 | + test_script_path = str(DockerComposeManager.CONTAINER_TEST_DIR / "run-tests.sh") |
| 140 | + try: |
| 141 | + test_session.send_keys( |
| 142 | + [f"bash {test_script_path}", "Enter"], |
| 143 | + block=True, |
| 144 | + max_timeout_sec=self.trial_handler.task.max_test_timeout_sec, |
| 145 | + ) |
| 146 | + test_output = test_session.capture_pane(capture_entire=True) |
| 147 | + parser_results = self.parser.parse(test_output) |
| 148 | + |
| 149 | + all_passed = parser_results and all(status == UnitTestStatus.PASSED for status in parser_results.values()) |
| 150 | + except Exception: |
| 151 | + all_passed = False |
| 152 | + |
| 153 | + return 1.0 if all_passed else 0.0 |
| 154 | + |
| 155 | + def _close_env(self): |
| 156 | + """Stop/cleanup terminal containers if present.""" |
| 157 | + if self.terminal: |
| 158 | + self.terminal.stop() |
0 commit comments