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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
"""
Codex Agent Module - Agent implementation driving the Codex CLI.

This module provides an agent that:
- Generates a ~/.codex/config.toml for the Codex CLI targeting an
  OpenAI-compatible provider (e.g. DashScope) and injects the API key
- Runs `codex exec` inside the agent's Docker container with a timeout
- Parses Codex's JSONL event stream into a normalized trajectory
- Retries on recoverable errors (429 rate limits, 400 invalid parameter)
"""

import json
import logging
import os
import getpass
import subprocess
import time
from pathlib import Path
import sys

# Make the project root importable so `utils.config` can be resolved.
project_root = Path(__file__).resolve().parents[3]
sys.path.append(str(project_root))
from utils.config import OPENAI_API_BASE, OPENAI_API_KEY

from da_agent.envs.da_agent import DA_Agent_Env
from da_agent.agent.base import BaseAgent

logger = logging.getLogger("da_agent")

DEFAULT_TIME_OUT = 3600
MAX_OBS_LENGTH = 3000


class PromptAgent(BaseAgent):
    # Codex drives the `codex` CLI; only model is used from the shared config
    # (the timeout uses DEFAULT_TIME_OUT instead of max_steps). No cross-task
    # state, so __init__ is inherited from BaseAgent.

    def set_env_and_task(self, env: DA_Agent_Env):
        self.env = env
        self.work_dir = env.work_dir
        self.instruction = self.env.task_config['question']
        self._base_instruction = self.instruction
        self._native_context_retries = 0
        self.trajectory = []
        self.raw_output = ""
        self.event_timestamps = []

    def _build_task_prompt(self):
        task = self.instruction
        task += f"\n\nYou are working in the directory: {self.work_dir}."
        task += " All required data files are available in this directory."
        source_tree = getattr(self.env, "source_files_prompt", "")
        if source_tree:
            task += f"\n\nInput file tree (paths are relative to that directory):\n{source_tree}"
        task += " Complete the task and ensure all output files are saved in this directory."
        task += (
            " Do not print, cat, or grep entire datasets or large matching result sets."
            " Inspect schemas and small samples only, keep every tool output under 100 lines,"
            " and perform bulk processing in scripts to avoid exhausting the model context."
            " Use the installed pandas, geopandas, and rapidfuzz packages; do not manually parse"
            " binary DBF files. Do not enumerate full unique-value lists. You have a maximum of"
            f" {self.max_steps} shell calls for the whole task. HARD ORDERING RULE: your first shell command"
            " must create a Python processing script in the working directory. Before that"
            " script exists, directory listing, head/cat/grep, schema inspection, package"
            " installation, and all other exploratory commands are forbidden. Put concise"
            " schema inspection and the full solution inside that script, run it, then only"
            " debug the script until the requested outputs exist."
        )

        image_file_names = self._get_image_file_names()
        if image_file_names:
            task += self._build_plotting_instructions(image_file_names)

        return task

    def _get_image_file_names(self):
        image_file_names = []
        for post_process_f in self.env.post_process_func:
            def image_post_process(output_file_name):
                if output_file_name in self.env.task_config.get('output_file_name', []):
                    return output_file_name
                return None
            output_file_name = eval(post_process_f)
            if output_file_name:
                image_file_names.append(output_file_name)
        return image_file_names

    def _build_plotting_instructions(self, image_file_names):
        return f"""
### Plotting (REQUIRED)

If you create a matplotlib plot, you MUST call:

    from image import Plotprocess
    Plotprocess.plot_process(fig, "<image_file_name>")

Use ONLY these file names:
{", ".join(image_file_names)}

Rules:
- Call AFTER plotting is complete
- Call BEFORE saving the figure
- Use: fig = plt.gcf()
- Replace <image_file_name> with one from the list above

Example:
```python
from image import Plotprocess
import matplotlib.pyplot as plt

# plotting code ...

fig = plt.gcf()
Plotprocess.plot_process(fig, "{image_file_names[0]}")
```"""

    def _write_wrapper_script(self):
        # Read API config from utils.config (LLM settings live there).
        # Build TOML config for ~/.codex/config.toml
        # Codex CLI requires model_providers section with wire_api="chat"
        # for non-OpenAI providers (e.g., DashScope)
        config_toml = f'''model_provider = "DashScope"

[model_providers.DashScope]
name = "DashScope"
base_url = "{OPENAI_API_BASE}"
env_key = "OPENAI_API_KEY"
wire_api = "chat"
'''

        wrapper_code = f'''#!/usr/bin/env python3
import json
import os
import subprocess
import sys
import threading
import time

# Write config.toml before launching codex
config_dir = os.path.expanduser("~/.codex")
os.makedirs(config_dir, exist_ok=True)
with open(os.path.join(config_dir, "config.toml"), "w") as f:
    f.write("""{config_toml}""")

with open("{self.work_dir}/.task_prompt.txt") as f:
    prompt = f.read()

MAX_RETRIES = 3
RETRY_BACKOFF_429 = 30  # seconds to wait on rate limit
RETRY_BACKOFF_400 = 10   # seconds to wait on invalid parameter error

current_proc = None

def timeout_handler():
    global current_proc
    if current_proc:
        current_proc.terminate()
        kill_timer = threading.Timer(300, current_proc.kill)
        kill_timer.daemon = True
        kill_timer.start()

timer = threading.Timer({DEFAULT_TIME_OUT}, timeout_handler)
timer.daemon = True
timer.start()

def run_codex(cmd_args, is_resume=False):
    global current_proc
    cmd = ["stdbuf", "-oL"] + cmd_args
    current_proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    last_line = ""
    for line in iter(current_proc.stdout.readline, b""):
        decoded = line.decode("utf-8", errors="ignore")
        sys.stdout.write(decoded)
        sys.stdout.flush()
        last_line = decoded.strip()

    # Read remaining stderr after stdout is exhausted
    stderr = current_proc.stderr.read()
    if stderr:
        stderr_text = stderr.decode("utf-8", errors="ignore").strip()
        if stderr_text:
            last_line = stderr_text.split("\\n")[-1]
            sys.stderr.write(stderr_text + "\\n")
            sys.stderr.flush()

    current_proc.wait()
    return current_proc.returncode, last_line

def is_retryable_error(last_line):
    try:
        entry = json.loads(last_line)
        if entry.get("type") == "turn.failed":
            error_msg = json.dumps(entry.get("error", {{}}))
            if "429" in error_msg:
                return "429"
            if "400" in error_msg or "InvalidParameter" in error_msg:
                return "400"
    except (json.JSONDecodeError, TypeError):
        pass
    return None

# Initial run
cmd_args = ["codex", "exec", prompt,
            "--model", "{self.model}",
            "--sandbox", "danger-full-access",
            "--skip-git-repo-check",
            "--json"]

exit_code, last_line = run_codex(cmd_args)

# Retry on recoverable errors
for attempt in range(MAX_RETRIES):
    error_type = is_retryable_error(last_line)
    if not error_type:
        break

    backoff = RETRY_BACKOFF_429 if error_type == "429" else RETRY_BACKOFF_400
    print(f"[RETRY] turn.failed ({{error_type}}), waiting {{backoff}}s before retry {{attempt+1}}/{{MAX_RETRIES}}...", flush=True)
    time.sleep(backoff)

    exit_code, last_line = run_codex(cmd_args, is_resume=True)

sys.exit(exit_code)
'''
        wrapper_path = os.path.join(self.env.mnt_dir, ".run_codex.py")
        with open(wrapper_path, "w") as f:
            f.write(wrapper_code)

    def run(self):
        assert self.env is not None, "Environment is not set."

        if self.env.native:
            return self._run_native()

        task_prompt = self._build_task_prompt()
        container_name = self.env.container.name

        # Write task prompt and wrapper script to mounted directory
        task_path = os.path.join(self.env.mnt_dir, ".task_prompt.txt")
        with open(task_path, "w") as f:
            f.write(task_prompt)
        self._write_wrapper_script()

        # Execute wrapper script inside the container as the non-root user named
        # after the host user.
        process = subprocess.Popen(
            ["docker", "exec", "--user", getpass.getuser(), str(container_name),
             "python3", f"{self.work_dir}/.run_codex.py"],
            stdout=subprocess.PIPE, stderr=subprocess.STDOUT
        )

        output_lines = []
        self.event_timestamps = []
        try:
            while True:
                line = process.stdout.readline()
                if not line and process.poll() is not None:
                    break
                if line:
                    decoded = line.decode("utf-8", errors="ignore")
                    output_lines.append(decoded)
                    self.event_timestamps.append(time.time())
                    logger.debug("Codex: %s", decoded.strip())
        except Exception as e:
            process.kill()
            logger.error("Error running Codex: %s", e)
            self.raw_output = "".join(output_lines)
            self._parse_trajectory()
            return False, f"Error: {e}"

        self.raw_output = "".join(output_lines)
        exit_code = process.returncode

        self._parse_trajectory()

        # Codex exec --json exits 0 even when the turn is cut off (e.g. step
        # limit). Detect by trajectory tail: a normal turn ends with
        # turn.completed (normalized to "result"), an error event ("error"),
        # a turn.failed event, or unparsed stdout fragments ("raw"). Anything
        # else means the turn was interrupted mid-step.
        NORMAL_END_TYPES = {"result", "error", "raw", "turn.failed"}
        if exit_code == 0:
            last_type = self.trajectory[-1].get("type") if self.trajectory else None
            if last_type in NORMAL_END_TYPES:
                return True, "Task completed"
            else:
                return False, f"Agent stopped without turn completion (last_type={last_type})"
        else:
            return False, f"Agent exited with code {exit_code}"

    def _run_native(self):
        """Run Codex directly when the current host is already an isolated Pod."""
        task_prompt = self._build_task_prompt()
        runtime_env = getattr(self.env, "kwargs", {}).get("environment", {})
        provider_base = runtime_env.get("OPENAI_API_BASE", OPENAI_API_BASE)
        provider_key = runtime_env.get("OPENAI_API_KEY", OPENAI_API_KEY)
        extra_headers = json.loads(runtime_env.get("OPENAI_EXTRA_HEADERS_JSON", "{}"))
        context_window = int(
            getattr(self.env, "kwargs", {}).get("model_context_window", 16384)
        )
        compact_limit = max(6000, int(context_window * 0.75))
        header_config = ""
        if extra_headers:
            header_config = (
                "env_http_headers = { "
                + ", ".join(
                    f'{json.dumps(name)} = "ADBENCH_HTTP_HEADER_{index}"'
                    for index, name in enumerate(extra_headers)
                )
                + " }\n"
            )
        codex_home = Path(self.env.cache_dir).resolve() / "codex-home"
        codex_home.mkdir(parents=True, exist_ok=True)
        config_path = codex_home / "config.toml"
        config_path.write_text(
            'model_provider = "BenchmarkProxy"\n\n'
            f'model_context_window = {context_window}\n'
            f'model_auto_compact_token_limit = {compact_limit}\n'
            'tool_output_token_limit = 1000\n\n'
            'compact_prompt = "Preserve the exact user task, discovered schemas, and useful errors. Drop raw tool output. The next action must create or finish the processing script and requested output files, not perform more exploration."\n\n'
            '[model_providers.BenchmarkProxy]\n'
            'name = "Benchmark Proxy"\n'
            f'base_url = {json.dumps(provider_base)}\n'
            'env_key = "OPENAI_API_KEY"\n'
            + header_config
            + 'wire_api = "chat"\n',
            encoding="utf-8",
        )

        env = os.environ.copy()
        env["OPENAI_API_KEY"] = provider_key
        for index, value in enumerate(extra_headers.values()):
            env[f"ADBENCH_HTTP_HEADER_{index}"] = str(value)
        env["CODEX_HOME"] = str(codex_home)
        python_bin = str(Path(sys.executable).resolve().parent)
        env["PATH"] = python_bin + os.pathsep + env.get("PATH", "")
        command = [
            "codex", "exec", task_prompt,
            "--model", self.model,
            "--sandbox", "danger-full-access",
            "--skip-git-repo-check",
            "--json",
        ]

        process = subprocess.Popen(
            command,
            cwd=self.env.work_dir,
            env=env,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
        )
        output_lines = []
        self.event_timestamps = []
        deadline = time.monotonic() + DEFAULT_TIME_OUT
        command_steps = 0
        step_budget_reached = False
        while True:
            if time.monotonic() >= deadline:
                process.terminate()
                try:
                    process.wait(timeout=30)
                except subprocess.TimeoutExpired:
                    process.kill()
                self.raw_output = "".join(output_lines)
                self._parse_trajectory()
                return False, "Agent timed out"
            line = process.stdout.readline()
            if not line and process.poll() is not None:
                break
            if line:
                decoded = line.decode("utf-8", errors="ignore")
                output_lines.append(decoded)
                self.event_timestamps.append(time.time())
                logger.debug("Codex(native): %s", decoded.strip())
                try:
                    event = json.loads(decoded)
                except json.JSONDecodeError:
                    event = {}
                item = event.get("item", {})
                if (
                    event.get("type") == "item.completed"
                    and item.get("type") == "command_execution"
                ):
                    command_steps += 1
                    if command_steps >= self.max_steps:
                        step_budget_reached = True
                        process.terminate()
                        try:
                            process.wait(timeout=10)
                        except subprocess.TimeoutExpired:
                            process.kill()
                        break

        self.raw_output = "".join(output_lines)
        self._parse_trajectory()
        if step_budget_reached:
            output_names = self.env.task_config.get("output_file_name", [])
            output_names = output_names if isinstance(output_names, list) else [output_names]
            outputs_exist = all(
                (Path(self.env.work_dir) / output_name).exists()
                for output_name in output_names
            )
            return outputs_exist, (
                f"Codex reached the {self.max_steps}-command budget; "
                f"required outputs {'exist' if outputs_exist else 'are missing'}."
            )
        if process.returncode != 0:
            context_exhausted = (
                "context window" in self.raw_output.lower()
                or "longer than the model's context length" in self.raw_output.lower()
            )
            if context_exhausted and self._native_context_retries < 2:
                self._native_context_retries += 1
                logger.warning(
                    "Codex exhausted context; starting native recovery %d/2 in the same workspace",
                    self._native_context_retries,
                )
                self.instruction = self._base_instruction + (
                    "\n\nRECOVERY CONTEXT: A previous attempt already inspected the data and"
                    " created files in the working directory, especially process.py. Do not"
                    " repeat broad dataset exploration. Input datasets can be nested in"
                    " subdirectories: before declaring any task input missing, make process.py"
                    " discover files recursively with os.walk or Path.rglob. Your first command"
                    " must modify the existing processing script, then run it and finish"
                    " output.csv. Keep command output extremely short."
                )
                return self._run_native()
            return False, f"Agent exited with code {process.returncode}"
        last_type = self.trajectory[-1].get("type") if self.trajectory else None
        if last_type == "result":
            return True, "Task completed"
        return False, f"Agent stopped without turn completion (last_type={last_type})"

    def _parse_trajectory(self):
        self.trajectory = []

        # With --json, Codex outputs JSONL events line-by-line
        lines = self.raw_output.strip().split("\n")
        for i, line in enumerate(lines):
            line = line.strip()
            if not line:
                continue
            try:
                entry = json.loads(line)
                normalized = self._normalize_jsonl_entry(entry)
                if i < len(self.event_timestamps):
                    ts = self.event_timestamps[i]
                    prev_ts = self.event_timestamps[i - 1] if i > 0 else ts
                    normalized["timing"] = {
                        "start_time": prev_ts,
                        "end_time": ts,
                        "duration": ts - prev_ts,
                    }
                if normalized.get("type") not in ("thread_started", "turn_started"):
                    self.trajectory.append(normalized)
            except json.JSONDecodeError:
                step = {"type": "raw", "content": line}
                if i < len(self.event_timestamps):
                    ts = self.event_timestamps[i]
                    prev_ts = self.event_timestamps[i - 1] if i > 0 else ts
                    step["timing"] = {
                        "start_time": prev_ts,
                        "end_time": ts,
                        "duration": ts - prev_ts,
                    }
                self.trajectory.append(step)

    def _normalize_jsonl_entry(self, entry):
        if not isinstance(entry, dict):
            return {"type": "raw", "content": str(entry)}

        event_type = entry.get("type", "unknown")

        if event_type == "thread.started":
            return {"type": "thread_started"}

        elif event_type == "turn.started":
            return {"type": "turn_started"}

        elif event_type == "turn.completed":
            result = {"type": "result"}
            usage = entry.get("usage", {})
            if usage:
                result["usage"] = usage
            return result

        elif event_type == "item.completed":
            item = entry.get("item", {})
            item_type = item.get("type", "unknown")

            if item_type == "agent_message":
                text = item.get("text", "")
                return {"type": "assistant", "content": text}

            elif item_type == "command_execution":
                cmd = item.get("command", "")
                output = item.get("aggregated_output", "")
                exit_code = item.get("exit_code")
                if len(output) > MAX_OBS_LENGTH:
                    output = output[:MAX_OBS_LENGTH] + f"\n... (truncated, original {len(output)} chars)"
                result = {
                    "type": "assistant",
                    "code_action": cmd,
                    "observations": f"Execution logs:\n{output}",
                }
                if exit_code is not None:
                    result["exit_code"] = exit_code
                return result

            elif item_type == "todo_list":
                items = item.get("items", [])
                return {"type": "assistant", "content": f"Todo: {json.dumps(items)}"}

            return {"type": item_type, "content": json.dumps(item)}

        elif event_type == "item.started":
            item = entry.get("item", {})
            return {"type": "item_started", "content": json.dumps(item)}

        elif event_type == "error":
            return {"type": "error", "content": entry.get("message", "")}

        return {"type": event_type, "content": json.dumps(entry)}

    def get_trajectory(self):
        return {
            "task": self.instruction,
            "trajectory": self.trajectory
        }