-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathcli.py
More file actions
2118 lines (1931 loc) · 76.1 KB
/
cli.py
File metadata and controls
2118 lines (1931 loc) · 76.1 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
#!/usr/bin/env python3
"""CLI for running SWE-bench benchmark via the eliza TS bridge.
The agent loop is a single-shot prompt-the-bridge-for-a-patch flow: each
SWE-bench instance is converted into a prompt (issue text + repo context),
sent through the bench server, and the response is parsed for a unified
diff. The diff is then evaluated by ``SWEBenchEvaluator`` (Docker harness
or basic validator).
"""
from __future__ import annotations
import argparse
import asyncio
import hashlib
import json
import logging
import os
import re
import shutil
import sys
import textwrap
import time
import urllib.error
import urllib.request
from datetime import UTC, datetime
from pathlib import Path
from .dataset import SWEBenchDataset
from .evaluator import SWEBenchEvaluator
from .repo_manager import RepositoryManager
from .types import (
PatchStatus,
RepoStats,
SWEBenchConfig,
SWEBenchInstance,
SWEBenchReport,
SWEBenchResult,
SWEBenchVariant,
)
# Ensure the adapter packages are importable when running from a checkout.
_BENCH_ROOT = Path(__file__).resolve().parents[1]
for _adapter_dir in ("eliza-adapter", "hermes-adapter", "openclaw-adapter"):
_pkg = _BENCH_ROOT / _adapter_dir
if _pkg.exists() and str(_pkg) not in sys.path:
sys.path.insert(0, str(_pkg))
_ELIZA_ADAPTER_PKG = _BENCH_ROOT / "eliza-adapter"
logger = logging.getLogger(__name__)
_PATCH_FENCE_RE = re.compile(
r"```(?:diff|patch)?\s*\n(?P<body>.*?)```", re.DOTALL | re.IGNORECASE
)
_DIFF_HEADER_RE = re.compile(r"diff --git ")
_VALID_HUNK_HEADER_RE = re.compile(
r"^@@ -\d+(?:,\d+)? \+\d+(?:,\d+)? @@(?: .*)?$"
)
_SOURCE_CONTEXT_CACHE: dict[tuple[str, str, str], str | None] = {}
_CODE_PROVIDER_CAPABILITIES = {
"code.read",
"code.write",
"code.edit",
"code.search",
"code.shell",
}
_DEFAULT_PROVIDER_CAPABILITIES: dict[str, set[str]] = {
"claude-code": _CODE_PROVIDER_CAPABILITIES,
"codex": _CODE_PROVIDER_CAPABILITIES,
"direct_shell": _CODE_PROVIDER_CAPABILITIES,
"eliza-code": _CODE_PROVIDER_CAPABILITIES,
"elizaos": _CODE_PROVIDER_CAPABILITIES,
"opencode": _CODE_PROVIDER_CAPABILITIES,
"pi-agent": _CODE_PROVIDER_CAPABILITIES,
"swe-agent": _CODE_PROVIDER_CAPABILITIES,
}
_CLAUDE_AGENT_KEY_ENVS = ("ANTHROPIC_API_KEY", "CLAUDE_API_KEY", "CLAUDE_CODE_API_KEY")
_CODEX_AGENT_KEY_ENVS = ("OPENAI_API_KEY", "CODEX_API_KEY")
_SUBTASK_PROVIDERS = {"opencode", "codex", "claude-code"}
_ELIZA_WORKTREE_PROVIDERS = {"elizaos", "eliza"}
def _parse_required_capabilities(raw: str | None) -> list[str]:
if raw is None:
return []
required: list[str] = []
seen: set[str] = set()
for capability in str(raw).split(","):
normalized = capability.strip()
if normalized and normalized not in seen:
required.append(normalized)
seen.add(normalized)
return required
def _capability_report(provider: str, required: list[str]) -> dict[str, object]:
available = _DEFAULT_PROVIDER_CAPABILITIES.get(provider, set())
missing = [capability for capability in required if capability not in available]
return {
"provider": provider,
"required": required,
"available": sorted(available),
"missing": missing,
"satisfied": not missing,
}
def _env_has_value(*names: str) -> bool:
return any(bool(os.environ.get(name, "").strip()) for name in names)
def _default_task_agent_provider() -> str:
"""Infer the task-agent provider without exposing credential values."""
configured = os.environ.get("BENCHMARK_TASK_AGENT", "").strip().lower()
if configured:
return configured
if _env_has_value("CEREBRAS_API_KEY"):
return "elizaos"
if _env_has_value(*_CODEX_AGENT_KEY_ENVS):
return "codex"
if _env_has_value(*_CLAUDE_AGENT_KEY_ENVS):
return "claude-code"
return "elizaos"
def _normalize_patch_text(text: str) -> str:
"""Normalize indented multiline patch text back to a raw diff."""
normalized = textwrap.dedent(text).strip()
lines = normalized.splitlines()
if lines:
lines[0] = lines[0].lstrip()
normalized = "\n".join(lines).strip()
return normalized + "\n" if normalized else ""
def _sanitize_patch_text(text: str) -> str:
"""Remove common model artifacts that make otherwise valid diffs fail."""
lines: list[str] = []
for line in text.splitlines():
stripped = line.strip()
if stripped in {"*** End of File ***", "*** End Patch", "*** Begin Patch"}:
continue
lines.append(line.rstrip("\r"))
sanitized = "\n".join(lines).strip("\n")
return sanitized + "\n" if sanitized else ""
def _unified_diff_error(patch: str) -> str | None:
"""Return a structural error for patch text that git apply is likely to reject."""
if not patch.strip():
return "empty patch"
if not patch.lstrip().startswith("diff --git "):
return "patch must start with diff --git"
has_file_header = False
has_valid_hunk = False
for line in patch.splitlines():
if line.startswith("--- ") or line.startswith("+++ "):
has_file_header = True
if line.startswith("@@"):
if not _VALID_HUNK_HEADER_RE.match(line):
return (
"invalid hunk header; use headers like "
"`@@ -12,7 +12,9 @@`, never bare `@@`"
)
has_valid_hunk = True
if not has_file_header:
return "missing ---/+++ file headers"
if not has_valid_hunk:
return "missing unified diff hunk headers"
return None
def _valid_patch_or_empty(patch: str) -> str:
patch = _sanitize_patch_text(patch)
return "" if _unified_diff_error(patch) else patch
def _extract_patch_candidate(text: str) -> str:
"""Pull raw unified diff-looking text out of an LLM response.
Strategies, in order:
1. Triple-backtick block tagged ``diff`` or ``patch``.
2. Any triple-backtick block whose body starts with ``diff --git``.
3. Raw text starting with ``diff --git``.
4. Empty string.
"""
if not text:
return ""
for match in _PATCH_FENCE_RE.finditer(text):
body = match.group("body")
if body and "diff --git" in body:
return _sanitize_patch_text(_normalize_patch_text(body))
diff_match = _DIFF_HEADER_RE.search(text)
if diff_match:
body = text[diff_match.start() :]
return _sanitize_patch_text(_normalize_patch_text(body))
return ""
def _extract_patch(text: str) -> str:
"""Pull a structurally valid unified diff out of an LLM response."""
return _valid_patch_or_empty(_extract_patch_candidate(text))
def _format_hunk_range(start: int, count: int) -> str:
return str(start) if count == 1 else f"{start},{count}"
def _find_subsequence(haystack: list[str], needle: list[str]) -> int | None:
if not needle:
return 0
limit = len(haystack) - len(needle)
for idx in range(limit + 1):
if haystack[idx : idx + len(needle)] == needle:
return idx
return None
def _hunk_old_new_lines(
hunk_lines: list[str],
) -> tuple[list[str], list[str], int, int] | None:
old_lines: list[str] = []
new_lines: list[str] = []
old_count = 0
new_count = 0
for line in hunk_lines:
if not line:
old_lines.append("")
new_lines.append("")
old_count += 1
new_count += 1
continue
prefix = line[0]
if prefix == "\\":
continue
if prefix == "+":
new_lines.append(line[1:])
new_count += 1
continue
if prefix == "-":
old_lines.append(line[1:])
old_count += 1
continue
if prefix == " ":
old_lines.append(line[1:])
new_lines.append(line[1:])
old_count += 1
new_count += 1
continue
return None
return old_lines, new_lines, old_count, new_count
def _repairable_bare_hunk_section(line: str) -> str | None:
"""Return a section label for invalid model hunk headers we can repair."""
if not line.startswith("@@") or _VALID_HUNK_HEADER_RE.match(line):
return None
section = line[2:].strip()
if section.endswith("@@"):
section = section[:-2].strip()
return section
def _add_missing_file_headers(patch: str) -> str:
"""Insert ---/+++ headers when a model emits only diff --git plus hunks."""
lines = patch.splitlines()
repaired: list[str] = []
idx = 0
while idx < len(lines):
line = lines[idx]
if not line.startswith("diff --git "):
repaired.append(line)
idx += 1
continue
parts = line.split()
old_label = parts[2] if len(parts) >= 4 else None
new_label = parts[3] if len(parts) >= 4 else None
repaired.append(line)
idx += 1
section_start = idx
while idx < len(lines) and not lines[idx].startswith("diff --git "):
idx += 1
section = lines[section_start:idx]
has_headers = any(item.startswith("--- ") for item in section) and any(
item.startswith("+++ ") for item in section
)
if has_headers or old_label is None or new_label is None:
repaired.extend(section)
continue
insert_at = 0
while insert_at < len(section):
section_line = section[insert_at]
if (
section_line.startswith("index ")
or section_line.startswith("old mode ")
or section_line.startswith("new mode ")
or section_line.startswith("deleted file mode ")
or section_line.startswith("new file mode ")
):
repaired.append(section_line)
insert_at += 1
continue
break
repaired.append(f"--- {old_label}")
repaired.append(f"+++ {new_label}")
repaired.extend(section[insert_at:])
normalized = "\n".join(repaired).strip("\n")
return normalized + "\n" if normalized else ""
def _repair_bare_hunk_headers(patch: str, repo_root: Path | None) -> str:
"""Synthesize line-numbered hunk headers for model diffs using bare ``@@``."""
if repo_root is None or "\n@@" not in patch:
return _add_missing_file_headers(patch)
lines = patch.splitlines()
repaired: list[str] = []
old_path: Path | None = None
source_cache: dict[Path, list[str]] = {}
idx = 0
while idx < len(lines):
line = lines[idx]
if line.startswith("diff --git "):
parts = line.split()
old_path = None
if len(parts) >= 3 and parts[2].startswith("a/"):
old_path = repo_root / parts[2][2:]
repaired.append(line)
idx += 1
continue
section = _repairable_bare_hunk_section(line)
if section is None or old_path is None:
repaired.append(line)
idx += 1
continue
hunk_lines: list[str] = []
cursor = idx + 1
while cursor < len(lines):
next_line = lines[cursor]
if next_line.startswith("diff --git ") or next_line.startswith("@@"):
break
hunk_lines.append(next_line)
cursor += 1
has_change = any(line.startswith(("+", "-")) for line in hunk_lines)
if not has_change:
idx = cursor
continue
hunk = _hunk_old_new_lines(hunk_lines)
if hunk is None or not old_path.exists():
repaired.append(line)
idx += 1
continue
old_lines, new_lines, old_count, new_count = hunk
if old_lines == new_lines:
idx = cursor
continue
if old_path not in source_cache:
source_cache[old_path] = old_path.read_text(
encoding="utf-8",
errors="replace",
).splitlines()
source_lines = source_cache[old_path]
match_idx = _find_subsequence(source_lines, old_lines)
if match_idx is None:
repaired.append(line)
else:
has_context = any(item.startswith(" ") for item in hunk_lines)
start = match_idx + 1
needs_leading_context = not has_context or hunk_lines[0].startswith(("+", "-"))
needs_trailing_context = not has_context or hunk_lines[-1].startswith(("+", "-"))
if needs_leading_context and match_idx > 0:
hunk_lines = [" " + source_lines[match_idx - 1]] + hunk_lines
start -= 1
old_count += 1
new_count += 1
after_idx = match_idx + len(old_lines)
if needs_trailing_context and after_idx < len(source_lines):
hunk_lines = hunk_lines + [" " + source_lines[after_idx]]
old_count += 1
new_count += 1
header = (
"@@ -"
+ _format_hunk_range(start, old_count)
+ " +"
+ _format_hunk_range(start, new_count)
+ " @@"
)
if section:
header += f" {section}"
repaired.append(header)
repaired.extend(hunk_lines)
idx = cursor
normalized = "\n".join(repaired).strip("\n")
normalized = normalized + "\n" if normalized else ""
return _add_missing_file_headers(normalized)
def _extract_patch_for_repo(text: str, repo_root: Path | None) -> str:
"""Extract a patch and repair common model-only diff syntax when possible."""
patch = _extract_patch_candidate(text)
if not patch:
return ""
patch = _repair_bare_hunk_headers(patch, repo_root)
return _valid_patch_or_empty(patch)
def _candidate_context_paths(instance: SWEBenchInstance) -> list[str]:
"""Infer likely source files from the problem statement.
This is intentionally lightweight: the benchmark runner is not a full
SWE-agent, but giving a single-shot model the directly mentioned source
files avoids the pathological "patch without repository context" failure.
"""
repo_root = instance.repo.split("/")[-1].replace("-", "_")
text = "\n".join(
[
instance.problem_statement,
instance.hints_text,
*instance.fail_to_pass,
*instance.pass_to_pass,
]
)
candidates: list[str] = []
def add(path: str) -> None:
normalized = path.strip().strip("`'\"")
if not normalized:
return
normalized = normalized.lstrip("./")
if normalized.endswith(".py") and normalized not in candidates:
candidates.append(normalized)
for match in re.finditer(r"\bfrom\s+([A-Za-z_][\w.]*)\s+import\b", text):
module = match.group(1)
if module.startswith(f"{repo_root}.") or module == repo_root:
add(f"{module.replace('.', '/')}.py")
for match in re.finditer(r"\bimport\s+([A-Za-z_][\w.]*)\b", text):
module = match.group(1)
if module.startswith(f"{repo_root}.") or module == repo_root:
add(f"{module.replace('.', '/')}.py")
for match in re.finditer(r"(?<![A-Za-z0-9_./-])([A-Za-z0-9_./-]+\.py)\b", text):
add(match.group(1))
path = match.group(1).strip().strip("`'\"").lstrip("./")
test_match = re.search(r"^(?P<prefix>.+)/tests/test_(?P<name>[^/]+)\.py$", path)
if test_match:
add(f"{test_match.group('prefix')}/{test_match.group('name')}.py")
# If a package-qualified module is mentioned without an import statement,
# include the corresponding source file as a final hint.
dotted_re = re.compile(rf"\b({re.escape(repo_root)}(?:\.[A-Za-z_]\w*)+)\b")
for match in dotted_re.finditer(text):
add(f"{match.group(1).replace('.', '/')}.py")
return candidates[:5]
def _fetch_github_file(repo: str, commit: str, path: str) -> str | None:
if os.environ.get("SWE_BENCH_INCLUDE_SOURCE_CONTEXT", "1") in {"0", "false", "False"}:
return None
cache_key = (repo, commit, path)
if cache_key in _SOURCE_CONTEXT_CACHE:
return _SOURCE_CONTEXT_CACHE[cache_key]
url = f"https://raw.githubusercontent.com/{repo}/{commit}/{path}"
req = urllib.request.Request(
url,
headers={"User-Agent": "eliza-swe-bench-context/1.0"},
)
try:
with urllib.request.urlopen(req, timeout=12) as resp:
raw = resp.read(160_000)
except (urllib.error.URLError, TimeoutError, OSError):
_SOURCE_CONTEXT_CACHE[cache_key] = None
return None
text = raw.decode("utf-8", errors="replace")
if len(text) > 80_000:
text = text[:80_000] + "\n# ... truncated ...\n"
_SOURCE_CONTEXT_CACHE[cache_key] = text
return text
def _build_source_context(instance: SWEBenchInstance) -> str:
sections: list[str] = []
for path in _candidate_context_paths(instance):
content = _fetch_github_file(instance.repo, instance.base_commit, path)
if not content:
continue
sections.append(f"### {path}\n```python\n{content}\n```")
if not sections:
return ""
return "Relevant repository file snapshots at the base commit:\n\n" + "\n\n".join(sections)
def _instance_specific_guidance(instance: SWEBenchInstance) -> str:
"""Return narrow diagnostic guidance for smoke instances with known traps."""
if instance.instance_id == "astropy__astropy-12907":
return (
"Diagnostic guidance for this instance:\n"
"- The bug is in separability for nested compound models.\n"
"- In `_cstack`, when either side is already a coord-matrix ndarray, "
"preserve the ndarray values in the stacked block. Do not replace "
"the block with all ones, because that destroys nested separability.\n\n"
)
return ""
def _build_prompt(instance: SWEBenchInstance, *, retry: bool = False) -> str:
"""Build a single prompt asking for a unified diff fix."""
source_context = _build_source_context(instance)
instance_guidance = _instance_specific_guidance(instance)
fail_to_pass = (
"Fail-to-pass tests named by SWE-bench:\n"
+ "\n".join(f"- {test}" for test in instance.fail_to_pass)
+ "\n\n"
if instance.fail_to_pass
else ""
)
retry_prefix = (
"Your previous response did not contain an applicable unified diff. "
"This time return only the diff text, starting with `diff --git`. "
"Every hunk header must include line ranges like `@@ -12,7 +12,9 @@`; "
"never use bare `@@`, apply-patch markers, or `*** End of File ***`.\n\n"
if retry
else ""
)
return (
retry_prefix +
"You are an expert software engineer fixing a real-world bug.\n\n"
f"Repository: {instance.repo}\n"
f"Base commit: {instance.base_commit}\n\n"
"Problem statement:\n"
f"{instance.problem_statement}\n\n"
+ (f"Hints:\n{instance.hints_text}\n\n" if instance.hints_text else "")
+ fail_to_pass
+ instance_guidance
+ (f"{source_context}\n\n" if source_context else "")
+ "Respond with a SINGLE unified diff that resolves the issue. "
"Prefer the smallest local edit that makes the named tests pass. "
"Do not replace whole classes, whole modules, or public APIs unless the issue requires it. "
"Preserve surrounding signatures, imports, formatting, and behavior outside the bug. "
"Start the response with `diff --git`; a fenced ```diff block is also acceptable. "
"Every hunk header must include real line ranges like `@@ -12,7 +12,9 @@`; "
"do not use bare `@@` or apply-patch markers. "
"Do not include commentary outside the diff. The diff must be applicable with `git apply` from "
"the repository root."
)
def _build_repair_prompt(
instance: SWEBenchInstance,
previous_patch: str,
result: SWEBenchResult,
) -> str:
"""Build a follow-up prompt using evaluator feedback from a failed patch."""
failed_tests = (
"Failed tests from the previous official evaluation:\n"
+ "\n".join(f"- {test}" for test in result.tests_failed)
+ "\n\n"
if result.tests_failed
else ""
)
passed_tests = (
"Tests that already passed and should keep passing:\n"
+ "\n".join(f"- {test}" for test in result.tests_passed[:20])
+ ("\n- ... truncated ...\n" if len(result.tests_passed) > 20 else "\n")
+ "\n"
if result.tests_passed
else ""
)
error = (
"Evaluator error from the previous patch:\n"
+ textwrap.shorten(
result.error.replace("\n", " ") if result.error else "",
width=2000,
placeholder="...",
)
+ "\n\n"
if result.error
else ""
)
status = (
f"Previous patch status: {result.patch_status.value}\n"
f"Previous result status: {result.status}\n\n"
)
return (
"Your previous SWE-bench patch did not resolve the instance. "
"Use the evaluation feedback below to produce a corrected patch.\n\n"
+ status
+ failed_tests
+ passed_tests
+ error
+ "Previous patch:\n"
"```diff\n"
f"{previous_patch}\n"
"```\n\n"
+ _build_prompt(instance, retry=True)
)
def _repair_attempts_for_provider(provider_label: str | None) -> int:
"""Return the configured number of native patch repair attempts."""
raw = os.environ.get("SWE_BENCH_REPAIR_ATTEMPTS")
if raw is None:
return 1 if provider_label in {"elizaos", "eliza"} else 0
try:
return max(0, int(raw))
except ValueError:
logger.warning("[swe_bench] invalid SWE_BENCH_REPAIR_ATTEMPTS=%r", raw)
return 0
def _eliza_worktree_enabled(provider_label: str | None) -> bool:
"""Return whether native eliza providers should normalize patches in a checkout."""
if provider_label not in _ELIZA_WORKTREE_PROVIDERS:
return False
return os.environ.get("SWE_BENCH_ELIZA_WORKTREE", "1") not in {
"0",
"false",
"False",
}
def _keep_instance_workspaces() -> bool:
"""Return whether per-instance checkouts should remain after evaluation."""
return os.environ.get("SWE_BENCH_KEEP_WORKSPACES", "").lower() in {
"1",
"true",
"yes",
}
def _cleanup_instance_workspace(config: SWEBenchConfig, instance: SWEBenchInstance) -> None:
"""Remove one known per-instance checkout while preserving shared caches."""
if _keep_instance_workspaces():
return
workspace = Path(config.workspace_dir)
repo_dir = workspace / instance.instance_id.replace("/", "_")
try:
resolved_workspace = workspace.resolve()
resolved_repo = repo_dir.resolve()
except OSError:
return
if resolved_repo == resolved_workspace or not resolved_repo.is_relative_to(
resolved_workspace
):
return
shutil.rmtree(repo_dir, ignore_errors=True)
def _build_subtask_prompt(instance: SWEBenchInstance) -> str:
"""Build a prompt for an external task agent running inside the checkout."""
return (
"You are working inside a freshly checked-out SWE-bench repository.\n"
"Edit the working tree to fix the issue below. Keep the fix narrow. "
"You may inspect files and run tests as needed. Do not commit changes. "
"When finished, leave the changes in the working tree and provide a brief "
"final note. If you cannot edit files directly, output a unified diff "
"starting with `diff --git`.\n\n"
f"Repository: {instance.repo}\n"
f"Base commit: {instance.base_commit}\n"
f"Instance: {instance.instance_id}\n\n"
"Problem statement:\n"
f"{instance.problem_statement}\n\n"
+ (f"Hints:\n{instance.hints_text}\n\n" if instance.hints_text else "")
+ (
"Fail-to-pass tests named by SWE-bench:\n"
+ "\n".join(f"- {test}" for test in instance.fail_to_pass)
+ "\n\n"
if instance.fail_to_pass
else ""
)
)
def _opencode_config_content(model_name: str) -> str:
"""Return an OpenCode config for Cerebras/OpenAI-compatible SWE-bench runs."""
return json.dumps(
{
"$schema": "https://opencode.ai/config.json",
"model": model_name,
"share": "disabled",
"autoupdate": False,
"provider": {
"cerebras-bench": {
"name": "Cerebras",
"npm": "@ai-sdk/openai-compatible",
"env": ["CEREBRAS_API_KEY"],
"options": {
"baseURL": "https://api.cerebras.ai/v1",
"timeout": 600000,
},
"models": {
"gpt-oss-120b": {
"name": "gpt-oss-120b",
"tool_call": True,
"reasoning": False,
"limit": {"context": 131072, "output": 65536},
}
},
}
},
"permission": {"edit": "allow", "bash": "allow"},
"tool_output": {"max_lines": 200, "max_bytes": 20000},
}
)
def _resolve_subtask_executable(provider: str) -> str:
"""Find the external task-agent executable for a provider."""
env_key = {
"opencode": "OPENCODE_BIN",
"codex": "CODEX_BIN",
"claude-code": "CLAUDE_BIN",
}.get(provider)
if env_key and os.environ.get(env_key):
return os.path.expandvars(os.path.expanduser(os.environ[env_key]))
candidates = {
"opencode": ["opencode", str(Path.home() / ".opencode" / "bin" / "opencode")],
"codex": ["codex"],
"claude-code": ["claude"],
}.get(provider)
if candidates is None:
raise ValueError(f"unsupported subtask provider: {provider}")
for candidate in candidates:
resolved = shutil.which(candidate) if os.sep not in candidate else candidate
if resolved and Path(resolved).exists():
return resolved
raise FileNotFoundError(
f"{provider} executable not found; install it or set {env_key}"
)
def _provider_model_name(provider: str, model_name: str | None) -> str:
"""Normalize model labels for provider CLIs."""
raw = model_name or "cerebras/gpt-oss-120b"
if provider == "opencode":
model_id = raw.split("/", 1)[1] if raw.startswith("cerebras/") else raw
return raw if raw.startswith("cerebras-bench/") else f"cerebras-bench/{model_id}"
return raw
def _subtask_provider_command(
provider: str,
model_name: str | None,
) -> list[str]:
"""Build the non-interactive provider command; prompt is sent on stdin."""
binary = _resolve_subtask_executable(provider)
model = _provider_model_name(provider, model_name)
if provider == "opencode":
return [
binary,
"run",
"--model",
model,
"--format",
"json",
"--dangerously-skip-permissions",
]
if provider == "codex":
return [
binary,
"exec",
"--sandbox",
"danger-full-access",
"--skip-git-repo-check",
"--model",
model,
]
if provider == "claude-code":
return [binary, "-p", "--model", model]
raise ValueError(f"unsupported subtask provider: {provider}")
def _subtask_provider_env(provider: str, model_name: str | None) -> dict[str, str]:
env = dict(os.environ)
if provider == "opencode":
model = _provider_model_name(provider, model_name)
if model.startswith("cerebras-bench/"):
env.setdefault("OPENCODE_CONFIG_CONTENT", _opencode_config_content(model))
return env
def _patchfile_apply_prompt(patch_path: Path) -> str:
return (
"Apply the SWE-bench patch file to this repository working tree.\n"
f"Run exactly: git apply {patch_path.name}\n"
"Do not commit. If the patch applies, stop and leave the working tree changed. "
"If it fails, report the error without making unrelated edits."
)
async def _generate_patch_with_client(
client: object,
instance: SWEBenchInstance,
provider_label: str,
model_name: str | None,
repo_root: Path | None = None,
) -> tuple[str, str | None]:
"""Ask the harness client for a patch without evaluating it."""
task_id = f"{provider_label}:patch:{instance.instance_id}"
try:
send_message = client.send_message # type: ignore[attr-defined]
client.reset(task_id=task_id, benchmark="swe_bench") # type: ignore[attr-defined]
response = send_message(
text=_build_prompt(instance),
context={
"benchmark": "swe_bench",
"task_id": task_id,
"instance_id": instance.instance_id,
"provider": provider_label,
"repo": instance.repo,
"base_commit": instance.base_commit,
"model_name": model_name,
"phase": "patch_generation",
},
)
text = getattr(response, "text", "") or ""
patch = _extract_patch_for_repo(text, repo_root)
if not patch:
params = getattr(response, "params", None)
if isinstance(params, dict) and params:
patch = _extract_patch_for_repo(json.dumps(params), repo_root)
if patch:
return patch, None
retry = send_message(
text=_build_prompt(instance, retry=True),
context={
"benchmark": "swe_bench",
"task_id": task_id,
"instance_id": instance.instance_id,
"provider": provider_label,
"repo": instance.repo,
"base_commit": instance.base_commit,
"model_name": model_name,
"phase": "patch_generation_retry",
"goal": "return_diff_only",
},
)
retry_text = getattr(retry, "text", "") or ""
patch = _extract_patch_for_repo(retry_text, repo_root)
if not patch:
retry_params = getattr(retry, "params", None)
if isinstance(retry_params, dict) and retry_params:
patch = _extract_patch_for_repo(json.dumps(retry_params), repo_root)
if patch:
return patch, None
preview = textwrap.shorten(
(retry_text or text).replace("\n", " "),
width=500,
placeholder="...",
)
return "", f"no patch in client response; preview={preview}"
except Exception as exc: # noqa: BLE001
return "", str(exc)
async def _run_opencode_patchfile_instance(
client: object,
instance: SWEBenchInstance,
evaluator: SWEBenchEvaluator,
config: SWEBenchConfig,
model_name: str | None,
) -> SWEBenchResult:
"""Generate a patch with Eliza, then subtask opencode to apply that patchfile."""
started = time.time()
manager = RepositoryManager(config.workspace_dir)
provider = "opencode"
try:
repo_root = await manager.setup_repo(instance)
patch, patch_error = await _generate_patch_with_client(
client,
instance,
provider,
model_name,
repo_root,
)
if not patch:
return SWEBenchResult(
instance_id=instance.instance_id,
generated_patch="",
patch_status=PatchStatus.NOT_GENERATED,
tests_passed=[],
tests_failed=[],
success=False,
duration_seconds=time.time() - started,
tokens_used=None,
error=f"patch generation failed before opencode apply: {patch_error}",
status="subtask_provider=opencode patchfile",
)
patch_path = repo_root / ".swe-bench-opencode.patch"
patch_path.write_text(patch, encoding="utf-8")
cmd = _subtask_provider_command(provider, model_name)
process = await asyncio.create_subprocess_exec(
*cmd,
cwd=str(repo_root),
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
env=_subtask_provider_env(provider, model_name),
)
prompt = _patchfile_apply_prompt(patch_path)
stdout_bytes, stderr_bytes = await asyncio.wait_for(
process.communicate(prompt.encode("utf-8")),
timeout=config.timeout_seconds,
)
stdout = stdout_bytes.decode("utf-8", errors="replace")
stderr = stderr_bytes.decode("utf-8", errors="replace")
try:
patch_path.unlink(missing_ok=True)
except OSError:
pass
worktree_patch = await manager.get_diff()
if not worktree_patch:
# Keep the benchmark moving if opencode failed after receiving the
# patchfile; evaluator will still report apply/test failures.
ok, error = await manager.apply_patch(patch)
if ok:
worktree_patch = await manager.get_diff()
else:
stderr = (stderr + "\n" + error).strip()
worktree_patch = patch
result = await evaluator.evaluate_patch(instance, worktree_patch)
result.duration_seconds = time.time() - started
status_bits = [result.status or "", "subtask_provider=opencode", "patchfile"]
if process.returncode not in (0, None):
status_bits.append(f"provider_exit={process.returncode}")
if not result.error:
preview = textwrap.shorten(
(stdout + "\n" + stderr).replace("\n", " "),
width=500,
placeholder="...",
)
result.error = f"opencode patchfile apply exited {process.returncode}; preview={preview}"
result.status = " ".join(bit for bit in status_bits if bit).strip()
return result
except asyncio.TimeoutError:
return SWEBenchResult(
instance_id=instance.instance_id,
generated_patch="",
patch_status=PatchStatus.NOT_GENERATED,
tests_passed=[],
tests_failed=[],
success=False,
duration_seconds=time.time() - started,
tokens_used=None,
error=f"opencode patchfile apply timed out after {config.timeout_seconds}s",
status="subtask_provider=opencode patchfile",
)
except Exception as exc: # noqa: BLE001
return SWEBenchResult(
instance_id=instance.instance_id,
generated_patch="",
patch_status=PatchStatus.NOT_GENERATED,
tests_passed=[],
tests_failed=[],
success=False,
duration_seconds=time.time() - started,
tokens_used=None,
error=str(exc),
status="subtask_provider=opencode patchfile",
)
finally:
if not _keep_instance_workspaces():
manager.cleanup_current_repo()
async def _run_eliza_worktree_instance(
client: object,
instance: SWEBenchInstance,
evaluator: SWEBenchEvaluator,
config: SWEBenchConfig,