File size: 5,076 Bytes
e1f5446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Run the native commit_runtime pipeline over one corpus repository, locally.

This is the launch path the proposal cites (Repo2RLEnv cli.py line 355):
    pipeline = pipeline_cls(gen_input, options, bootstrap=bootstrap_result)
with the prebaked BootstrapResult and the LocalSandbox adapter installed.

Usage:
    python -m r2e_local.driver --repo owner/name --sha <pinned> \
        --mirror assets/repos/owner__name --sandbox assets/sandboxes/owner__name \
        --bootstrap assets/bootstrap/owner__name/bootstrap.json \
        --out assets/heldout/owner__name \
        [--llm gemini/gemini-2.5-flash --llm-key-env GEMINI_API_KEY] [--opt key=value ...]
"""

from __future__ import annotations

import argparse
import json
import logging
import sys
import time
from pathlib import Path

from repo2rlenv.spec.input import (
    AuthSpec,
    BootstrapSpec,
    GenerationInput,
    LLMSpec,
    OutputSpec,
    PipelineName,
    PipelineSpec,
    RepoSpec,
)
from repo2rlenv.spec.options import CommitRuntimeOptions

from .pipeline import LocalCommitRuntimePipeline, install_hooks, load_bootstrap


def _parse_opts(items: list[str]) -> dict:
    out: dict = {}
    for item in items:
        k, _, v = item.partition("=")
        if v.lower() in ("true", "false"):
            out[k] = v.lower() == "true"
        elif v.isdigit():
            out[k] = int(v)
        else:
            try:
                out[k] = float(v)
            except ValueError:
                out[k] = v
    return out


def main(argv: list[str] | None = None) -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--repo", required=True, help="owner/name")
    ap.add_argument("--sha", required=True, help="pinned commit")
    ap.add_argument("--mirror", required=True, type=Path)
    ap.add_argument("--sandbox", required=True, type=Path)
    ap.add_argument("--bootstrap", required=True, type=Path)
    ap.add_argument("--out", required=True, type=Path)
    ap.add_argument("--llm", default=None, help="provider/model; omit to disable synthesis")
    ap.add_argument("--llm-key-env", default=None)
    ap.add_argument("--llm-endpoint", default=None)
    ap.add_argument("--opt", action="append", default=[], help="CommitRuntimeOptions field=value")
    ap.add_argument("-v", "--verbose", action="store_true")
    args = ap.parse_args(argv)

    logging.basicConfig(
        level=logging.DEBUG if args.verbose else logging.INFO,
        format="%(asctime)s %(levelname)s %(name)s: %(message)s",
        stream=sys.stderr,
    )

    github_url = f"https://github.com/{args.repo}"
    install_hooks({github_url: args.mirror.resolve()})

    llm = None
    if args.llm:
        provider, _, model = args.llm.partition("/")
        llm = LLMSpec(
            provider=provider,
            model=model,
            api_key_env=args.llm_key_env,
            endpoint=args.llm_endpoint,
        )

    opts = CommitRuntimeOptions(**_parse_opts(args.opt))
    if args.llm is None and opts.synthesize_with_llm:
        # Shipped default is synthesize_with_llm=True; with no LLM the pipeline
        # falls back to the commit message (commit_runtime.py _build_instruction).
        logging.getLogger(__name__).warning("no --llm given: instructions use commit text")

    gen_input = GenerationInput(
        repo=RepoSpec(url=github_url, ref=args.sha, access="public"),
        pipeline=PipelineSpec(name=PipelineName.COMMIT_RUNTIME, recipe="native"),
        llm=llm,
        output=OutputSpec(destination="local", org="commit-runtime", dataset_name="tasks"),
        bootstrap=BootstrapSpec(enabled=False),
        auth=AuthSpec(github_token_env="R2E_UNUSED_TOKEN", use_gh_cli=False, use_hf_cli=False),
    )
    bootstrap = load_bootstrap(args.bootstrap)

    pipeline = LocalCommitRuntimePipeline(
        gen_input, opts, bootstrap=bootstrap, sandbox_dir=args.sandbox.resolve()
    )
    events: list[dict] = []
    pipeline.set_progress_callback(
        lambda name, outcome, reason="": events.append(
            {"t": time.time(), "name": name, "outcome": outcome, "reason": reason}
        )
    )

    t0 = time.time()
    result = pipeline.run(args.out.resolve())
    elapsed = time.time() - t0

    summary = {
        "repo": args.repo,
        "sha": args.sha,
        "candidates": result.candidates,
        "emitted": result.emitted,
        "skipped": result.skipped,
        "skip_reasons": result.skip_reasons,
        "options": opts.model_dump() if hasattr(opts, "model_dump") else vars(opts),
        "llm": llm.qualified_name if llm else None,
        "llm_cost_usd": round(getattr(pipeline, "_llm_cost_usd", 0.0), 6),
        "elapsed_sec": round(elapsed, 1),
        "events": events,
    }
    args.out.mkdir(parents=True, exist_ok=True)
    (args.out / "result.json").write_text(json.dumps(summary, indent=2))
    print(
        json.dumps(
            {k: summary[k] for k in ("repo", "candidates", "emitted", "skipped", "skip_reasons", "elapsed_sec", "llm_cost_usd")}
        )
    )
    return 0


if __name__ == "__main__":
    raise SystemExit(main())