File size: 7,298 Bytes
bf80335
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94227eb
bf80335
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
#!/usr/bin/env python3
"""
Run OpenHands agent for a single branch coverage task.
"""
import os
import sys
import json
import shutil
import argparse
import traceback
import glob
from typing import Dict, Any, Optional

# Add exp directory to path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from prompt import build_prompt_openhands

# Default configuration
DEFAULT_API_BASE = "http://localhost:60101/v1"
DEFAULT_MODEL = "qwen-3.5-27b"
RESULTS_DIR = "/experiments/openhands/results"

# Suppress OpenHands banner
os.environ['OPENHANDS_SUPPRESS_BANNER'] = '1'


def find_generator_code(result_dir: str) -> str:
    """
    Find generator code in the result directory.

    Look for:
    1. generator.py directly in result_dir
    2. Any *.libpng_read_fuzzer.*.py pattern (agent-created files)
    """
    # First check for generator.py
    generator_path = os.path.join(result_dir, 'generator.py')
    if os.path.exists(generator_path):
        with open(generator_path, 'r') as f:
            content = f.read()
            if content.strip():  # Non-empty
                return content

    # Look for agent-created files with pattern: *.prog.src_site_id.to_take.try_id.py
    patterns = [
        os.path.join(result_dir, '*.py'),
        os.path.join(result_dir, '**', '*.py'),
    ]

    for pattern in patterns:
        for py_file in glob.glob(pattern, recursive=True):
            if py_file.endswith('generator.py'):
                continue
            try:
                with open(py_file, 'r') as f:
                    content = f.read()
                    if 'def generate_buf' in content:
                        return content
            except:
                continue

    return ""


def run_agent_single(
    question: Dict[str, Any],
    try_id: int,
    llm_name: str = DEFAULT_MODEL,
    api_base: str = DEFAULT_API_BASE,
    model: str = DEFAULT_MODEL,
    enable_thinking: bool = False,
    timeout: int = 1800,  # 30 minutes default timeout
) -> Dict[str, Any]:
    """
    Run OpenHands agent for a single branch coverage task.

    Args:
        question: Dict with keys 'prog', 'src_site_id', 'to_take', 'format'
        try_id: Attempt number (0-indexed)
        llm_name: Name for result directory
        api_base: OpenAI-compatible API base URL
        model: Model name to use
        enable_thinking: Whether to enable thinking/reasoning mode
        timeout: Maximum time for agent to run (seconds)

    Returns:
        Dict with result information
    """
    from openhands.sdk import LLM
    from openhands.tools.preset.default import get_default_agent
    from openhands.sdk import Conversation

    prog = question['prog']
    src_site_id = question['src_site_id']
    to_take = question['to_take']
    file_format = question.get('format', 'unknown')

    # Build result directory path
    result_dir_name = f"{llm_name}---{prog}---{src_site_id}---{to_take}---{try_id}"
    result_dir = os.path.join(RESULTS_DIR, result_dir_name)

    # Clean and create result directory
    if os.path.exists(result_dir):
        shutil.rmtree(result_dir)
    os.makedirs(result_dir)
    os.makedirs(os.path.join(result_dir, 'logs'))

    # Copy source code to workspace
    # Try to find the source directory
    original_src_dir = None
    possible_dirs = [
        f'/src/{prog.split("_")[0]}',  # e.g., /src/libpng for libpng_read_fuzzer
        f'/src/{prog}',
        f'/src/{prog.replace("_", "-")}',
    ]

    for possible_dir in possible_dirs:
        if os.path.exists(possible_dir):
            original_src_dir = possible_dir
            break

    workspace_src_dir = original_src_dir

    # Build prompt
    sys_prompt, user_prompt, _ = build_prompt_openhands(
        prog, file_format, src_site_id, to_take, result_dir, workspace_src_dir
    )

    # Initialize LLM with extra_body for thinking mode support
    llm_kwargs = {
        'model': f'hosted_vllm/{model}',
        'api_key': 'dummy',
        'base_url': api_base,
        'extra_body': {
            "chat_template_kwargs": {"enable_thinking": enable_thinking},
            "include_reasoning": enable_thinking,
        },
        'timeout': 3600,
    }

    llm = LLM(**llm_kwargs)

    # Get agent with CLI mode
    agent = get_default_agent(llm=llm, cli_mode=True)

    # Create conversation
    conversation = Conversation(
        agent=agent,
        workspace=result_dir,
        persistence_dir=os.path.join(result_dir, 'logs'),
        max_iteration_per_run=50,
    )

    error_msg = None
    generator_code = ""

    try:
        # Send initial message and run agent
        conversation.send_message(sys_prompt + user_prompt)
        conversation.run()

        # Find generator code in result directory
        generator_code = find_generator_code(result_dir)

    except Exception as e:
        error_msg = f"Agent failed: {str(e)}\n{traceback.format_exc()}"

        # Save error log
        error_path = os.path.join(result_dir, 'err.md')
        with open(error_path, 'w') as f:
            f.write("# Error Log\n\n")
            f.write(error_msg)

    # Save generator.py if found, otherwise create empty file
    generator_path = os.path.join(result_dir, 'generator.py')
    if generator_code:
        with open(generator_path, 'w') as f:
            f.write(generator_code)
    else:
        pass

    return {
        'success': bool(generator_code),
        'generator_code': generator_code,
        'error': error_msg,
        'result_dir': result_dir,
    }


def main():
    parser = argparse.ArgumentParser(description="Run OpenHands agent for a single task")

    # Task specification
    parser.add_argument("--prog", type=str, required=True, help="Program name")
    parser.add_argument("--src-site-id", type=int, required=True, help="Source site ID")
    parser.add_argument("--to-take", type=int, required=True, help="Branch direction (0 or 1)")
    parser.add_argument("--format", type=str, default="unknown", help="Input file format")
    parser.add_argument("--try-id", type=int, default=0, help="Try ID")

    # Model configuration
    parser.add_argument("--api-base", type=str, default=DEFAULT_API_BASE, help="API base URL")
    parser.add_argument("--model", type=str, default=DEFAULT_MODEL, help="Model name")
    parser.add_argument("--llm-name", type=str, default=None, help="LLM name for results")
    parser.add_argument("--enable-thinking", action="store_true", help="Enable thinking mode")

    args = parser.parse_args()

    llm_name = args.llm_name if args.llm_name else args.model

    question = {
        'prog': args.prog,
        'src_site_id': args.src_site_id,
        'to_take': args.to_take,
        'format': args.format,
    }

    print(f"Running OpenHands agent for: {question}")
    print(f"Try ID: {args.try_id}")
    print(f"Model: {args.model}")

    result = run_agent_single(
        question=question,
        try_id=args.try_id,
        llm_name=llm_name,
        api_base=args.api_base,
        model=args.model,
        enable_thinking=args.enable_thinking,
    )

    print(f"\nResult: {'Success' if result['success'] else 'Failed'}")
    if result['error']:
        print(f"Error: {result['error']}")
    print(f"Result directory: {result['result_dir']}")


if __name__ == '__main__':
    main()