-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathrun_agent.py
More file actions
2490 lines (2252 loc) · 122 KB
/
Copy pathrun_agent.py
File metadata and controls
2490 lines (2252 loc) · 122 KB
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import argparse
import json
import os
import re
import shutil
import sys
import time
import uuid
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
import subprocess
import platform
from dotenv import load_dotenv
from typing import Dict, List, Optional
# Load environment variables from .env file
load_dotenv()
# Ensure package import works when running this file directly
CURRENT_FILE = Path(__file__).resolve()
PKG_ROOT = CURRENT_FILE.parent
REPO_ROOT = PKG_ROOT.parent
if str(REPO_ROOT) not in sys.path:
sys.path.insert(0, str(REPO_ROOT))
from ResearchGym.environment import AgenticEnv
from ResearchGym.utils.logging import setup_file_logger
from ResearchGym.agents.ml_master_adapter import MLMasterAdapter, MLMasterConfig
from ResearchGym.agents.ai_scientist_adapter import AIScientistAdapter, AIScientistConfig
from ResearchGym.environment.runtime.docker_runner import plan_docker_command
from ResearchGym.environment.runtime.uv_runner import detect_task_overlay, plan_uv_commands
from ResearchGym.agents.rg_agent_adapter import RGAgentAdapter, RGAgentConfig
from ResearchGym.agents.rg_agent_evolution_adapter import RGAgentEvolutionAdapter, RGAgentEvolutionConfig
from ResearchGym.agents.ClaudeCode.adapter import ClaudeCodeAdapter
from ResearchGym.agents.ClaudeCode.config import ClaudeCodeConfig
from ResearchGym.agents.Codex.adapter import CodexAdapter
from ResearchGym.agents.Codex.config import CodexConfig, PROVIDER_SUBSCRIPTION
def _gen_ids() -> tuple[str, str]:
run_group = time.strftime("%Y-%m-%d")
run_id = uuid.uuid4().hex[:8]
return run_group, run_id
def _ensure_git_bash_in_path() -> None:
"""On Windows, ensure RG_BASH_PATH points to Git Bash and PATH includes it."""
if os.name != "nt":
return
def _is_stub(path: str) -> bool:
lowered = path.lower()
return (
"windowsapps\\bash.exe" in lowered
or "system32\\bash.exe" in lowered
or "sysnative\\bash.exe" in lowered
)
if os.environ.get("RG_BASH_PATH"):
return
candidates = [
shutil.which("bash"),
r"C:\Program Files\Git\bin\bash.exe",
r"C:\Program Files\Git\usr\bin\bash.exe",
r"C:\Program Files\Git\bin",
r"C:\Program Files\Git\usr\bin",
]
for cand in candidates:
if not cand:
continue
path_obj = Path(cand)
if path_obj.is_dir():
path_obj = path_obj / "bash.exe"
if path_obj.exists() and not _is_stub(str(path_obj)):
os.environ["RG_BASH_PATH"] = str(path_obj)
parent = str(path_obj.parent)
current_path = os.environ.get("PATH", "")
os.environ["PATH"] = f"{parent}{os.pathsep}{current_path}"
return
def _ensure_git_initialized(repo_dir: Path, logger=None) -> None:
"""Ensure a git repository exists at repo_dir.
This initializes git for each run's task workspace so that agents can make
commits during the run. Safe to call repeatedly.
"""
try:
repo_dir.mkdir(parents=True, exist_ok=True)
if (repo_dir / ".git").exists():
return
# Initialize repository quietly
subprocess.run(["git", "init"], cwd=str(repo_dir), check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# Ensure user identity is set locally to avoid commit failures
email_probe = subprocess.run(["git", "config", "user.email"], cwd=str(repo_dir), stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, encoding='utf-8')
if email_probe.returncode != 0 or not email_probe.stdout.strip():
subprocess.run(["git", "config", "user.email", "agent@researchgym.local"], cwd=str(repo_dir), check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
name_probe = subprocess.run(["git", "config", "user.name"], cwd=str(repo_dir), stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, encoding='utf-8')
if name_probe.returncode != 0 or not name_probe.stdout.strip():
subprocess.run(["git", "config", "user.name", "ResearchGym Agent"], cwd=str(repo_dir), check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if logger:
try:
logger.info(f"Initialized git repository at {repo_dir}")
except Exception:
pass
except Exception as e:
# Do not fail the run if git is not available; just warn.
msg = f"Warning: failed to initialize git repo at {repo_dir}: {e}"
print(msg)
if logger:
try:
logger.warning(msg)
except Exception:
pass
@dataclass
class ResumeUsage:
hours_spent: float
budget_spent: float
log_files: List[str]
def _parse_iso_timestamp(raw: str) -> datetime:
if not raw:
raise ValueError("missing timestamp")
if raw.endswith("Z"):
raw = raw[:-1] + "+00:00"
return datetime.fromisoformat(raw)
def _list_inspect_logs(log_dir: Path) -> List[Path]:
if not log_dir.exists():
return []
candidates = sorted(log_dir.glob("*.json"), key=lambda p: p.stat().st_mtime, reverse=False)
if candidates:
return candidates
return sorted(log_dir.glob("*.eval"), key=lambda p: p.stat().st_mtime, reverse=False)
def _collect_resume_usage(run_dir: Path) -> ResumeUsage:
log_dir = run_dir / "logs"
stdout_log = log_dir / "exec.stdout.log"
if not stdout_log.exists():
raise FileNotFoundError(f"Missing exec stdout log for resume: {stdout_log}")
inspect_logs = []
for candidate in _list_inspect_logs(log_dir):
try:
data = json.loads(candidate.read_text(encoding="utf-8"))
except Exception:
continue
stats = data.get("stats") or {}
started = stats.get("started_at")
completed = stats.get("completed_at")
if not started or not completed:
continue
inspect_logs.append((candidate, started, completed))
if not inspect_logs:
raise FileNotFoundError(f"No inspect logs (.json/.eval) with timing metadata found in {log_dir}")
total_hours = 0.0
for _, start_raw, end_raw in inspect_logs:
start_dt = _parse_iso_timestamp(start_raw)
end_dt = _parse_iso_timestamp(end_raw)
delta = (end_dt - start_dt).total_seconds()
if delta > 0:
total_hours += delta / 3600.0
last_cost = None
cost_pattern = re.compile(r"Session total cost:\s*\$([0-9]+(?:\.[0-9]+)?)")
with stdout_log.open("r", encoding="utf-8", errors="ignore") as fh:
for line in fh:
match = cost_pattern.search(line)
if match:
try:
last_cost = float(match.group(1))
except ValueError:
continue
if last_cost is None:
raise RuntimeError(f"Could not parse session cost from {stdout_log}")
return ResumeUsage(
hours_spent=total_hours,
budget_spent=last_cost,
log_files=[path.name for path, _, _ in inspect_logs],
)
def _collect_claude_code_resume_usage(run_dir: Path, original_hours: float | None = None) -> ResumeUsage:
"""Collect resume usage from ClaudeCode's cost_summary.json.
Unlike RGAgent which uses inspect logs, ClaudeCode stores usage
in cost_summary.json created by its CostTracker.
Args:
run_dir: Path to the run directory to collect usage from
original_hours: Original time budget in hours (e.g., 24). If provided,
calculates cumulative time spent using remaining_seconds for accurate
multi-generation resume tracking.
"""
log_dir = run_dir / "logs"
cost_summary_path = log_dir / "cost_summary.json"
if not cost_summary_path.exists():
raise FileNotFoundError(f"Missing cost_summary.json for resume: {cost_summary_path}")
try:
data = json.loads(cost_summary_path.read_text(encoding="utf-8"))
except json.JSONDecodeError as e:
raise RuntimeError(f"Invalid JSON in cost_summary.json: {e}")
# Extract time spent (in hours)
# For multi-generation resumes, use remaining_seconds to get cumulative time
time_info = data.get("time", {})
remaining_seconds = time_info.get("remaining_seconds")
if original_hours is not None and remaining_seconds is not None and remaining_seconds >= 0:
# Calculate cumulative time spent: original_budget - remaining
# This correctly accounts for ALL previous sessions, not just the immediate one
original_seconds = original_hours * 3600
hours_spent = (original_seconds - remaining_seconds) / 3600.0
else:
# Fallback to active_seconds (first-generation resume or missing data)
active_seconds = time_info.get("active_seconds", 0.0)
hours_spent = active_seconds / 3600.0
# Extract cost spent
budget_spent = data.get("total_cost_usd", 0.0)
return ResumeUsage(
hours_spent=hours_spent,
budget_spent=budget_spent,
log_files=["cost_summary.json"],
)
def _collect_codex_resume_usage(run_dir: Path, original_hours: float | None = None) -> ResumeUsage:
"""Collect resume usage from Codex cost_summary.json.
Args:
run_dir: Path to the run directory to collect usage from
original_hours: Original time budget in hours (e.g., 24). If provided,
calculates cumulative time spent using remaining_seconds for accurate
multi-generation resume tracking.
"""
log_dir = run_dir / "logs"
cost_summary_path = log_dir / "cost_summary.json"
if not cost_summary_path.exists():
raise FileNotFoundError(f"Missing cost_summary.json for resume: {cost_summary_path}")
try:
data = json.loads(cost_summary_path.read_text(encoding="utf-8"))
except json.JSONDecodeError as e:
raise RuntimeError(f"Invalid JSON in cost_summary.json: {e}")
# Extract time spent (in hours)
# For multi-generation resumes, use remaining_seconds to get cumulative time
time_info = data.get("time", {})
remaining_seconds = time_info.get("remaining_seconds")
if original_hours is not None and remaining_seconds is not None and remaining_seconds >= 0:
# Calculate cumulative time spent: original_budget - remaining
original_seconds = original_hours * 3600
hours_spent = (original_seconds - remaining_seconds) / 3600.0
else:
# Fallback to active_seconds (first-generation resume or missing data)
active_seconds = time_info.get("active_seconds", 0.0)
hours_spent = active_seconds / 3600.0
budget_spent = data.get("total_cost_usd", 0.0)
return ResumeUsage(
hours_spent=hours_spent,
budget_spent=budget_spent,
log_files=["cost_summary.json"],
)
def _get_claude_code_session_id(run_dir: Path) -> str | None:
"""Get session ID from ClaudeCode's session.json for resume."""
session_path = run_dir / "logs" / "session.json"
if not session_path.exists():
return None
try:
data = json.loads(session_path.read_text(encoding="utf-8"))
return data.get("session_id")
except (json.JSONDecodeError, OSError):
return None
def _get_codex_session_id(run_dir: Path) -> str | None:
"""Get session ID from Codex JSONL output for resume."""
output_path = run_dir / "logs" / "codex_output.jsonl"
if not output_path.exists():
return None
try:
with output_path.open("r", encoding="utf-8", errors="ignore") as f:
for line in f:
try:
data = json.loads(line.strip())
except json.JSONDecodeError:
continue
session_id = data.get("session_id")
if session_id:
return session_id
except Exception:
return None
return None
def _encode_claude_project_path(workspace_path: Path) -> str:
"""Encode a workspace path the way Claude stores it in ~/.claude/projects/."""
path_str = str(workspace_path.resolve())
# Replace \ / : with - (Claude does NOT collapse multiple dashes)
return path_str.replace('\\', '-').replace('/', '-').replace(':', '-')
def _copy_claude_session_file(
old_workspace: Path,
new_workspace: Path,
session_id: str,
) -> bool:
"""Copy Claude session file from old workspace to new workspace.
Claude stores sessions in ~/.claude/projects/<encoded-cwd>/<session_id>.jsonl
To resume a session in a new workspace, we need to copy the session file.
Args:
old_workspace: Original workspace directory (as used by Claude cwd)
new_workspace: New workspace directory
session_id: Session ID to copy
Returns:
True if copy succeeded, False otherwise
"""
claude_projects = Path.home() / ".claude" / "projects"
if not claude_projects.exists():
print(f"Warning: ~/.claude/projects/ not found")
return False
old_encoded = _encode_claude_project_path(old_workspace)
new_encoded = _encode_claude_project_path(new_workspace)
old_session_dir = claude_projects / old_encoded
new_session_dir = claude_projects / new_encoded
if not old_session_dir.exists():
print(f"Warning: Original session directory not found: {old_session_dir}")
return False
session_file = old_session_dir / f"{session_id}.jsonl"
if not session_file.exists():
print(f"Warning: Session file not found: {session_file}")
return False
# Create new session directory and copy the file
new_session_dir.mkdir(parents=True, exist_ok=True)
new_session_file = new_session_dir / f"{session_id}.jsonl"
try:
shutil.copy2(session_file, new_session_file)
print(f" Copied session file to new workspace")
return True
except Exception as e:
print(f"Warning: Failed to copy session file: {e}")
return False
def _derive_resume_run_id(run_group_dir: Path, parent_run_id: str) -> str:
# Extract base ID if parent is already a resume (e.g., "abc123_resume-01" -> "abc123")
resume_match = re.match(r"^(.+?)_resume-\d+$", parent_run_id)
base_id = resume_match.group(1) if resume_match else parent_run_id
base = f"{base_id}_resume"
suffix = 1
while True:
candidate = f"{base}-{suffix:02d}"
candidate_path = run_group_dir / candidate
if not candidate_path.exists():
return candidate
suffix += 1
def _replicate_run_state(src: Path, dst: Path, symlink_workspace: bool = False) -> None:
"""Copy run state from src to dst for resume.
Args:
src: Source run directory
dst: Destination run directory
symlink_workspace: If True, symlink workspace/input instead of copying.
Useful when workspace has many files (models, datasets).
"""
# Directories to skip during resume (regenerated automatically or too large)
skip_dirs = {".uv_cache", "__pycache__", ".venv", "venv"}
for item in src.iterdir():
if item.name in skip_dirs:
continue
target = dst / item.name
# Handle workspace specially - can symlink to avoid copying large dirs
if item.name == "workspace" and symlink_workspace:
# Symlink workspace/input to original (Windows needs special handling)
src_input = item / "input"
dst_input = target / "input"
if src_input.exists():
target.mkdir(parents=True, exist_ok=True)
# Remove dst_input if it exists (created by env.reset)
if dst_input.exists():
shutil.rmtree(dst_input)
try:
# Try symlink first (requires admin or dev mode on Windows)
dst_input.symlink_to(src_input, target_is_directory=True)
except OSError:
# Fallback: use junction on Windows
import subprocess
subprocess.run(
["cmd", "/c", "mklink", "/J", str(dst_input), str(src_input)],
capture_output=True
)
continue
if item.is_dir():
shutil.copytree(item, target, dirs_exist_ok=True)
else:
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(item, target)
def _write_usage_summary(run_dir: Path, agent_type: str = "rg-agent") -> None:
"""Write usage summary, trying agent-specific format first."""
try:
if agent_type == "claude-code":
# Try claude-code format (cost_summary.json)
usage = _collect_claude_code_resume_usage(run_dir)
elif agent_type == "codex":
usage = _collect_codex_resume_usage(run_dir)
else:
# Try inspect log format (rg-agent)
usage = _collect_resume_usage(run_dir)
except Exception as exc:
print(f"Warning: unable to write usage summary for {run_dir}: {exc}")
return
summary_path = run_dir / "usage_summary.json"
payload = {
"hours_spent": usage.hours_spent,
"budget_spent": usage.budget_spent,
"log_files": usage.log_files,
"computed_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
}
summary_path.write_text(json.dumps(payload, indent=2))
IDEA_HINT_HEADER = "## Idea Hint"
def _load_idea_hint_text(task_dir: Path) -> str:
hint_path = task_dir / "idea_hint.txt"
if not hint_path.exists():
raise FileNotFoundError(f"--idea_hint enabled but idea_hint.txt not found at {hint_path}")
idea_text = hint_path.read_text(encoding="utf-8").strip()
if not idea_text:
raise ValueError(f"--idea_hint enabled but {hint_path} is empty.")
return idea_text
def _inject_idea_hint_section(target_file: Path, idea_hint: str) -> Path:
"""Append or replace the idea hint section in the given file."""
existing = target_file.read_text(encoding="utf-8")
section = f"{IDEA_HINT_HEADER}\n\n{idea_hint.strip()}\n"
pattern = re.compile(r"^## Idea Hint\b.*?(?=^#|\Z)", re.MULTILINE | re.DOTALL)
if pattern.search(existing):
updated = pattern.sub(section + "\n", existing)
else:
base = existing.rstrip()
updated = f"{base}\n\n{section}" if base else section
target_file.write_text(updated.rstrip() + "\n", encoding="utf-8")
return target_file
def _apply_idea_hint(input_dir: Path, idea_hint: Optional[str]) -> Optional[Path]:
"""Apply idea_hint to task_description.md under input_dir."""
if not idea_hint:
return None
target = input_dir / "task_description.md"
if not target.exists():
raise FileNotFoundError(f"--idea_hint enabled but task_description.md not found under {input_dir}")
_inject_idea_hint_section(target, idea_hint)
return target
def _apply_idea_hint_or_exit(input_dir: Path, idea_hint: Optional[str]) -> Optional[Path]:
"""Wrapper that exits cleanly on idea-hint failures."""
if not idea_hint:
return None
try:
return _apply_idea_hint(input_dir, idea_hint)
except Exception as exc:
print(f"Failed to apply idea hint: {exc}")
sys.exit(2)
def main() -> None:
parser = argparse.ArgumentParser(description="Run an agent against a ResearchGym task")
parser.add_argument("task_dir", type=Path, help="Path to task directory (e.g., tasks/continual-learning)")
parser.add_argument(
"agent",
choices=["ml-master", "ai-scientist", "rg-agent", "rg-agent-evolution", "openevolve", "claude-code", "codex"],
help="Agent to run",
)
parser.add_argument("--runs_dir", type=Path, default=PKG_ROOT / "runs", dest="runs_dir")
parser.add_argument("--dry_run", action="store_true", help="Do not execute, only plan")
# Resume options
parser.add_argument("--resume", type=Path, default=None, help="Absolute path to existing run_dir to resume (e.g., .../runs/2025-09-11/<run_id>)")
parser.add_argument("--resume_with_instruction", action="store_true", help="When resuming, start a fresh conversation with a minimal resume note prepended to the original instructions")
parser.add_argument("--idea_hint", action="store_true", help="Append tasks/<task>/idea_hint.txt to the task description used for prompting")
# ML-Master minimal args
# Model selection argument
parser.add_argument("--model", type=str,
help="Model name to use (e.g., 'gemini-2.5-pro', 'gpt-5')")
# Generic agent config (model/backends)
parser.add_argument("--code_model", type=str, default="")
parser.add_argument("--code_temp", type=float, default=0.5)
parser.add_argument("--code_base_url", type=str, default="")
parser.add_argument("--code_api_key", type=str, default="")
parser.add_argument("--feedback_model", type=str, default="")
parser.add_argument("--feedback_temp", type=float, default=0.5)
parser.add_argument("--feedback_base_url", type=str, default="")
parser.add_argument("--feedback_api_key", type=str, default="")
parser.add_argument("--ml_master_root", type=Path, default=None)
parser.add_argument("--desc_file", type=Path, default=None)
parser.add_argument("--runtime", choices=["docker", "uv"], default="uv")
parser.add_argument("--image", type=str, default="researchgym-base:latest")
parser.add_argument("--gpus", action="store_true")
# AI-Scientist args
parser.add_argument("--ai_scientist_root", type=Path, default=None)
parser.add_argument("--ai_desc_file", type=Path, default=None)
parser.add_argument("--ai_steps", type=int, default=5)
parser.add_argument("--ai_workers", type=int, default=3)
parser.add_argument("--ai_code_model", type=str, default="openai/gpt-5")
parser.add_argument("--ai_feedback_model", type=str, default="openai/gpt-5")
parser.add_argument("--ai_vlm_model", type=str, default="openai/gpt-5")
parser.add_argument("--ai_code_temp", type=float, default=1.0)
parser.add_argument("--ai_feedback_temp", type=float, default=0.5)
parser.add_argument("--ai_vlm_temp", type=float, default=0.5)
parser.add_argument("--ai_report_model", type=str, default="openai/gpt-5")
parser.add_argument("--ai_report_temp", type=float, default=1.0)
parser.add_argument("--ai_hours", type=float, default=3.0, help="Max wall-clock hours for AI-Scientist runs")
# LiteLLM configuration
parser.add_argument("--litellm_base_url", type=str, default="", help="LiteLLM base URL for proxying API calls")
parser.add_argument("--litellm_prelude", type=str, default="", help="LiteLLM prelude commands")
# RGAgent args
parser.add_argument("--basic_agent_root", type=Path, default=None)
parser.add_argument("--basic_agent_evolution_root", type=Path, default=None)
# OpenEvolve args (initially minimal)
parser.add_argument("--openevolve_root", type=Path, default=None)
parser.add_argument("--openevolve_iterations", type=int, default=100)
parser.add_argument("--basic_hours", type=float, default=0.25, help="Max wall-clock hours for RGAgent")
parser.add_argument("--basic_iterative", action="store_true", help="Use iterative RGAgent loop")
parser.add_argument("--basic_disallow_submit", action="store_true", help="Hide end_task tool")
parser.add_argument("--basic_code_only", action="store_true", help="Code-only system message variant")
parser.add_argument("--budget_limit", type=float, default=10.0, help="Maximum budget in USD for LLM API calls (0 for no limit)")
# ClaudeCode args
parser.add_argument("--claude_hours", type=float, default=0.25, help="Max wall-clock hours for ClaudeCode agent")
# Codex args
parser.add_argument("--codex_hours", type=float, default=0.25, help="Max wall-clock hours for Codex agent")
parser.add_argument("--codex_model", type=str, default="", help="Codex model override (e.g., gpt-5-codex)")
parser.add_argument(
"--codex_reasoning_effort",
type=str,
default="xhigh",
choices=["minimal", "low", "medium", "high", "xhigh"],
help="Reasoning effort level for Codex (minimal, low, medium, high, xhigh). Default: xhigh"
)
parser.add_argument(
"--codex_subscription",
action="store_true",
help="Use ChatGPT subscription instead of API (requires prior 'codex login')"
)
args = parser.parse_args()
_ensure_git_bash_in_path()
# Determine default models based on --model argument and Azure configuration
def get_default_models():
if args.model:
# Use the exact model name provided by the user
return args.model, args.model
else:
# Default based on Azure availability
azure_endpoint = os.getenv('AZURE_OPENAI_ENDPOINT')
azure_api_key = os.getenv('AZURE_OPENAI_API_KEY')
azure_available = azure_endpoint and azure_api_key
if azure_available:
return "gpt-5", "gpt-5"
else:
return "gemini/gemini-2.5-flash-lite", "gemini/gemini-2.5-flash-lite"
default_code_model, default_feedback_model = get_default_models()
# Set default models if not provided
if not args.code_model:
args.code_model = default_code_model
if not args.feedback_model:
args.feedback_model = default_feedback_model
runs_dir_abs = args.runs_dir.resolve()
env = AgenticEnv(base_runs_dir=args.runs_dir)
task_dir_resolved = args.task_dir.resolve()
# Allow enabling idea hints via CLI flag or env var (useful in Docker where envs are easier to pass)
idea_hint_enabled = args.idea_hint or os.environ.get("RG_IDEA_HINT", "false").strip().lower() == "true"
idea_hint_text: Optional[str] = None
if idea_hint_enabled:
try:
idea_hint_text = _load_idea_hint_text(task_dir_resolved)
except Exception as exc:
print(f"Failed to load idea hint: {exc}")
sys.exit(2)
# Plan run identifiers and environment initialization (supports resume)
is_resuming = args.resume is not None
resume_dir = None
resume_usage = None
resumed_into_new_dir = False
if is_resuming:
resume_dir = args.resume.resolve()
if not resume_dir.exists() or not resume_dir.is_dir():
print(f"--resume path does not exist or is not a directory: {resume_dir}")
sys.exit(2)
resume_run_group = resume_dir.parent.name
resume_run_id = resume_dir.name
try:
resume_dir.relative_to(runs_dir_abs)
except Exception:
print(f"--resume path {resume_dir} is not under --runs_dir {runs_dir_abs}. Set --runs_dir appropriately or pass a path under it.")
sys.exit(2)
meta_path = resume_dir / "metadata.json"
parent_meta = {}
if meta_path.exists():
try:
parent_meta = json.loads(meta_path.read_text())
prior_task_dir = Path(parent_meta.get("task_dir", "")).resolve() if parent_meta.get("task_dir") else None
if prior_task_dir and prior_task_dir != task_dir_resolved:
print(f"Task dir mismatch. metadata.json has {prior_task_dir}, CLI provided {task_dir_resolved}.")
sys.exit(2)
except Exception:
parent_meta = {}
if args.agent == "rg-agent":
transcript_path = resume_dir / "transcript.json"
if not transcript_path.exists():
print(f"Transcript file not found at {transcript_path}. Cannot resume without conversation history.")
sys.exit(2)
log_dir = resume_dir / "logs"
has_json_logs = any(log_dir.glob("*.json"))
has_eval_logs = any(log_dir.glob("*.eval"))
if not has_json_logs or not has_eval_logs:
missing = []
if not has_json_logs:
missing.append(".json")
if not has_eval_logs:
missing.append(".eval")
print(f"Required log files {', '.join(missing)} missing under {log_dir}. Restore the logs before resuming.")
sys.exit(2)
try:
resume_usage = _collect_resume_usage(resume_dir)
except Exception as exc:
print(f"Unable to resume: {exc}")
sys.exit(2)
requested_total_hours = args.basic_hours
if requested_total_hours <= 0:
print(f"--basic_hours must represent the TOTAL desired hours when resuming. Received {requested_total_hours}.")
sys.exit(2)
hours_remaining = requested_total_hours - resume_usage.hours_spent
if hours_remaining <= 0:
print(
f"No time remaining: already used {resume_usage.hours_spent:.2f}h, "
f"requested total {requested_total_hours:.2f}h."
)
sys.exit(2)
total_budget = args.budget_limit
if total_budget > 0:
budget_remaining = total_budget - resume_usage.budget_spent
if budget_remaining <= 0:
print(
f"No budget remaining: already used ${resume_usage.budget_spent:.2f}, "
f"requested total ${total_budget:.2f}."
)
sys.exit(2)
else:
budget_remaining = 0.0
args.basic_hours = hours_remaining
if total_budget > 0:
args.budget_limit = budget_remaining
run_group = resume_run_group
run_id = _derive_resume_run_id(runs_dir_abs / run_group, resume_run_id)
obs = env.reset(task_dir=args.task_dir, run_group=run_group, run_id=run_id)
new_run_dir = env.run_dir
_replicate_run_state(resume_dir, new_run_dir)
resumed_into_new_dir = True
resume_generation = parent_meta.get("resume_generation", 0) + 1
meta = {
"task_dir": str(task_dir_resolved),
"run_group": run_group,
"run_id": run_id,
"resumed_from": str(resume_dir),
"resumed_from_run_group": resume_run_group,
"resumed_from_run_id": resume_run_id,
"resume_generation": resume_generation,
"resume_total_hours": requested_total_hours,
"resume_hours_consumed": resume_usage.hours_spent,
"resume_hours_remaining": hours_remaining,
"resume_total_budget": total_budget,
"resume_budget_consumed": resume_usage.budget_spent,
"resume_budget_remaining": budget_remaining if total_budget > 0 else None,
}
(new_run_dir / "metadata.json").write_text(json.dumps(meta, indent=2))
(new_run_dir / "status.json").write_text(
json.dumps(
{
"status": "resuming",
"resumed_from": str(resume_dir),
"remaining_hours": hours_remaining,
"remaining_budget": budget_remaining if total_budget > 0 else "unlimited",
},
indent=2,
)
)
print(
f"Created resumed run {run_group}/{run_id} from {resume_dir} "
f"(used {resume_usage.hours_spent:.2f}h / ${resume_usage.budget_spent:.2f})."
)
if total_budget > 0:
print(
f"Total targets -> {requested_total_hours:.2f}h & ${total_budget:.2f}; "
f"remaining allocation -> {hours_remaining:.2f}h & ${budget_remaining:.2f}."
)
else:
print(
f"Total target -> {requested_total_hours:.2f}h; remaining allocation -> {hours_remaining:.2f}h (budget unlimited)."
)
elif args.agent == "claude-code":
# ClaudeCode uses session.json + cost_summary.json for resume
# Can also resume with just transcript.json (transcript seeding fallback)
session_id = _get_claude_code_session_id(resume_dir)
cost_summary_path = resume_dir / "logs" / "cost_summary.json"
transcript_path = resume_dir / "logs" / "transcript.json"
if not cost_summary_path.exists():
print(f"cost_summary.json not found at {cost_summary_path}. Cannot resume without usage data.")
sys.exit(2)
if not session_id and not transcript_path.exists():
print(f"Neither session.json nor transcript.json found in {resume_dir / 'logs'}. Cannot resume.")
sys.exit(2)
if not session_id:
print(f" Note: No session_id found, will use transcript seeding for resume.")
requested_total_hours = args.claude_hours
try:
# Pass original_hours for accurate cumulative time tracking across multi-gen resumes
resume_usage = _collect_claude_code_resume_usage(resume_dir, original_hours=requested_total_hours)
except Exception as exc:
print(f"Unable to resume: {exc}")
sys.exit(2)
if requested_total_hours <= 0:
print(f"--claude_hours must represent the TOTAL desired hours when resuming. Received {requested_total_hours}.")
sys.exit(2)
hours_remaining = requested_total_hours - resume_usage.hours_spent
if hours_remaining <= 0:
print(
f"No time remaining: already used {resume_usage.hours_spent:.2f}h, "
f"requested total {requested_total_hours:.2f}h."
)
sys.exit(2)
total_budget = args.budget_limit
if total_budget > 0:
budget_remaining = total_budget - resume_usage.budget_spent
if budget_remaining <= 0:
print(
f"No budget remaining: already used ${resume_usage.budget_spent:.2f}, "
f"requested total ${total_budget:.2f}."
)
sys.exit(2)
else:
budget_remaining = 0.0
# Update args with remaining time
# NOTE: budget_limit stays as TOTAL budget (not remaining)
# CostTracker inherits previous costs and compares against total
args.claude_hours = hours_remaining
# args.budget_limit stays as total_budget (not budget_remaining)
run_group = resume_run_group
run_id = _derive_resume_run_id(runs_dir_abs / run_group, resume_run_id)
obs = env.reset(task_dir=args.task_dir, run_group=run_group, run_id=run_id)
new_run_dir = env.run_dir
# Use symlink for workspace to avoid copying large dirs (models, datasets)
_replicate_run_state(resume_dir, new_run_dir, symlink_workspace=True)
resumed_into_new_dir = True
# Store session_id for later use in dispatch
# Use placeholder if no session_id but transcript exists (for transcript seeding)
args._claude_resume_session_id = session_id or "transcript-seeding"
resume_generation = parent_meta.get("resume_generation", 0) + 1
meta = {
"task_dir": str(task_dir_resolved),
"run_group": run_group,
"run_id": run_id,
"resumed_from": str(resume_dir),
"resumed_from_run_group": resume_run_group,
"resumed_from_run_id": resume_run_id,
"resume_generation": resume_generation,
"resume_total_hours": requested_total_hours,
"resume_hours_consumed": resume_usage.hours_spent,
"resume_hours_remaining": hours_remaining,
"resume_total_budget": total_budget,
"resume_budget_consumed": resume_usage.budget_spent,
"resume_budget_remaining": budget_remaining if total_budget > 0 else None,
"resume_session_id": session_id,
}
(new_run_dir / "metadata.json").write_text(json.dumps(meta, indent=2))
(new_run_dir / "status.json").write_text(
json.dumps(
{
"status": "resuming",
"resumed_from": str(resume_dir),
"remaining_hours": hours_remaining,
"remaining_budget": budget_remaining if total_budget > 0 else "unlimited",
"session_id": session_id,
},
indent=2,
)
)
print(
f"Created resumed run {run_group}/{run_id} from {resume_dir} "
f"(used {resume_usage.hours_spent:.2f}h / ${resume_usage.budget_spent:.2f})."
)
print(f"Resuming session: {session_id}")
if total_budget > 0:
print(
f"Total targets -> {requested_total_hours:.2f}h & ${total_budget:.2f}; "
f"remaining allocation -> {hours_remaining:.2f}h & ${budget_remaining:.2f}."
)
else:
print(
f"Total target -> {requested_total_hours:.2f}h; remaining allocation -> {hours_remaining:.2f}h (budget unlimited)."
)
elif args.agent == "codex":
session_id = _get_codex_session_id(resume_dir)
cost_summary_path = resume_dir / "logs" / "cost_summary.json"
transcript_path = resume_dir / "logs" / "codex_output.jsonl"
if not cost_summary_path.exists():
print(f"cost_summary.json not found at {cost_summary_path}. Cannot resume without usage data.")
sys.exit(2)
if not transcript_path.exists() and not session_id:
print(f"No codex_output.jsonl or session_id found in {resume_dir / 'logs'}. Cannot resume.")
sys.exit(2)
requested_total_hours = args.codex_hours
try:
# Pass original_hours for accurate cumulative time tracking across multi-gen resumes
resume_usage = _collect_codex_resume_usage(resume_dir, original_hours=requested_total_hours)
except Exception as exc:
print(f"Unable to resume: {exc}")
sys.exit(2)
if requested_total_hours <= 0:
print(f"--codex_hours must represent the TOTAL desired hours when resuming. Received {requested_total_hours}.")
sys.exit(2)
hours_remaining = requested_total_hours - resume_usage.hours_spent
if hours_remaining <= 0:
print(
f"No time remaining: already used {resume_usage.hours_spent:.2f}h, "
f"requested total {requested_total_hours:.2f}h."
)
sys.exit(2)
total_budget = args.budget_limit
if total_budget > 0:
budget_remaining = total_budget - resume_usage.budget_spent
if budget_remaining <= 0:
print(
f"No budget remaining: already used ${resume_usage.budget_spent:.2f}, "
f"requested total ${total_budget:.2f}."
)
sys.exit(2)
else:
budget_remaining = 0.0
args.codex_hours = hours_remaining
run_group = resume_run_group
run_id = _derive_resume_run_id(runs_dir_abs / run_group, resume_run_id)
obs = env.reset(task_dir=args.task_dir, run_group=run_group, run_id=run_id)
new_run_dir = env.run_dir
_replicate_run_state(resume_dir, new_run_dir, symlink_workspace=True)
resumed_into_new_dir = True
# For Codex, prefer transcript seeding over native resume
# Native resume only if no transcript exists
use_native_resume = bool(session_id and not transcript_path.exists())
args._codex_resume_session_id = session_id if use_native_resume else None
# Always pass inherited cost path for cost tracking continuity
args._codex_inherited_cost_path = cost_summary_path
resume_generation = parent_meta.get("resume_generation", 0) + 1
meta = {
"task_dir": str(task_dir_resolved),
"run_group": run_group,
"run_id": run_id,
"resumed_from": str(resume_dir),
"resumed_from_run_group": resume_run_group,
"resumed_from_run_id": resume_run_id,
"resume_generation": resume_generation,
"resume_total_hours": requested_total_hours,
"resume_hours_consumed": resume_usage.hours_spent,
"resume_hours_remaining": hours_remaining,
"resume_total_budget": total_budget,
"resume_budget_consumed": resume_usage.budget_spent,
"resume_budget_remaining": budget_remaining if total_budget > 0 else None,
"resume_session_id": session_id,
}
(new_run_dir / "metadata.json").write_text(json.dumps(meta, indent=2))
(new_run_dir / "status.json").write_text(
json.dumps(
{
"status": "resuming",
"resumed_from": str(resume_dir),
"remaining_hours": hours_remaining,
"remaining_budget": budget_remaining if total_budget > 0 else "unlimited",
"session_id": session_id,
},
indent=2,
)
)
if transcript_path.exists():
prev_transcript = new_run_dir / "logs" / "previous_transcript.jsonl"
prev_transcript.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(transcript_path, prev_transcript)
print(f" Copied transcript for seeding: {prev_transcript}")
# Also copy cost summary for inheritance detection
if cost_summary_path.exists():
prev_cost = new_run_dir / "logs" / "previous_cost_summary.json"
shutil.copy2(cost_summary_path, prev_cost)
print(f" Copied cost summary for inheritance: {prev_cost}")
elif use_native_resume:
print(f" Using native resume session: {session_id}")
print(
f"Created resumed run {run_group}/{run_id} from {resume_dir} "
f"(used {resume_usage.hours_spent:.2f}h / ${resume_usage.budget_spent:.2f})."
)
if total_budget > 0:
print(
f"Total targets -> {requested_total_hours:.2f}h & ${total_budget:.2f}; "
f"remaining allocation -> {hours_remaining:.2f}h & ${budget_remaining:.2f}."
)
else:
print(
f"Total target -> {requested_total_hours:.2f}h; remaining allocation -> {hours_remaining:.2f}h (budget unlimited)."
)
else:
run_group, run_id = resume_run_group, resume_run_id
obs = env.reset(task_dir=args.task_dir, run_group=run_group, run_id=run_id)
if env.run_dir.resolve() != resume_dir:
print(f"Resolved env.run_dir {env.run_dir} differs from --resume path {resume_dir}. Check --runs_dir.")
sys.exit(2)
(env.run_dir / "status.json").write_text(json.dumps({"status": "resuming"}, indent=2))
print(f"Resuming run: group={run_group} id={run_id}")
else:
run_group, run_id = _gen_ids()
obs = env.reset(task_dir=args.task_dir, run_group=run_group, run_id=run_id)
logger = setup_file_logger("runner", env.logs_dir / "runner.log")