File size: 6,315 Bytes
fbd4e33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2136d7
 
 
 
 
 
 
 
 
 
 
 
 
 
fbd4e33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
471461a
 
fbd4e33
471461a
 
fbd4e33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Fetch Antigravity sandbox artifacts with retries and a log-based fallback.

``fetch`` regularly fails with HTTP 503 "Environment snapshot is temporarily
unavailable". It is transient: the same session usually fetches fine a minute
later. This wrapper retries with exponential backoff and, if the snapshot never
comes back, recovers the agent's final message from the run log so the analysis
is not lost.

Usage:
    python scripts/ag_fetch.py --state /tmp/ag_task.json --out /tmp/ag_task_fetch
    python scripts/ag_fetch.py --state ... --out ... --retries 8 --base-delay 15
    python scripts/ag_fetch.py --log logs/.../antigravity_task.log --out /tmp/ag_task_fetch --recover-only
"""

from __future__ import annotations

import argparse
import json
import random
import subprocess
import sys
import time
from pathlib import Path

DEFAULT_WRAPPER = Path.home() / ".config" / "opencode" / "antigravity" / "antigravity.py"

TRANSIENT = (
    "503",
    "UNAVAILABLE",
    "temporarily unavailable",
    "502",
    "504",
    "deadline",
    "timeout",
    "connection reset",
    "ECONNRESET",
)


def is_transient(output: str) -> bool:
    text = output.lower()
    return any(marker.lower() in text for marker in TRANSIENT)


def json_objects(text: str):
    """Yield every top-level JSON object embedded in a log, in order."""
    decoder = json.JSONDecoder()
    index = 0
    while True:
        start = text.find("{", index)
        if start < 0:
            return
        try:
            value, end = decoder.raw_decode(text, start)
        except json.JSONDecodeError:
            index = start + 1
            continue
        yield value
        index = end


def last_final(log_path: Path) -> str | None:
    if not log_path.exists():
        return None
    final = None
    for payload in json_objects(log_path.read_text(encoding="utf-8", errors="replace")):
        if isinstance(payload, dict) and isinstance(payload.get("final"), str) and payload["final"].strip():
            final = payload["final"]
    return final


def log_completed(log_path: Path) -> bool:
    """True when the run log already holds a completed response.

    The wrapper writes its state file only after the process returns, so a dead
    pid plus no state is not proof of failure: the log often has the result.
    """
    if not log_path.exists():
        return False
    for payload in json_objects(log_path.read_text(encoding="utf-8", errors="replace")):
        if isinstance(payload, dict) and payload.get("status") == "completed":
            return True
    return False


def recover_from_log(log_path: Path, out_dir: Path) -> Path | None:
    final = last_final(log_path)
    if not final:
        return None
    target = out_dir / "final.md"
    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_text(final + "\n", encoding="utf-8")
    return target


def wrapper_fetch(wrapper: Path, state: Path, out_dir: Path) -> tuple[int, str]:
    command = [sys.executable, str(wrapper), "--state", str(state), "fetch", "--out", str(out_dir)]
    process = subprocess.run(command, text=True, capture_output=True, check=False)
    return process.returncode, (process.stdout or "") + (process.stderr or "")


def fetch_with_retry(
    wrapper: Path,
    state: Path,
    out_dir: Path,
    log_path: Path | None = None,
    retries: int = 6,
    base_delay: float = 15.0,
    max_delay: float = 180.0,
    sleep=time.sleep,
) -> dict:
    """Returns {"status": ok|recovered|failed, "attempts": n, "final": path|None}."""
    last_output = ""
    attempts_made = 0
    for attempt in range(1, retries + 1):
        attempts_made = attempt
        code, output = wrapper_fetch(wrapper, state, out_dir)
        last_output = output
        extracted = out_dir / "extracted"
        has_files = extracted.exists() and any(extracted.rglob("*"))
        if code == 0 and has_files:
            return {"status": "ok", "attempts": attempt, "final": None}
        if code == 0 and extracted.exists() and not has_files:
            output += "\nempty snapshot (no files extracted)"
        if not is_transient(output) and code != 0:
            print(f"fetch failed with a non-transient error (attempt {attempt}): {output.strip()[:300]}")
            break
        if attempt < retries:
            delay = min(max_delay, base_delay * (2 ** (attempt - 1)))
            delay *= 1 + random.uniform(-0.1, 0.1)
            print(f"fetch attempt {attempt} failed (503/transient); retrying in {delay:.0f}s", flush=True)
            sleep(delay)

    print("fetch exhausted; trying log-based recovery", flush=True)
    recovered = recover_from_log(log_path, out_dir) if log_path else None
    if recovered:
        print(f"recovered final message from log -> {recovered}", flush=True)
        return {"status": "recovered", "attempts": attempts_made, "final": str(recovered)}
    return {"status": "failed", "attempts": attempts_made, "final": None, "error": last_output[-500:]}


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--state", type=Path, required=True)
    parser.add_argument("--out", type=Path, required=True)
    parser.add_argument("--log", type=Path, default=None, help="run log, used for recovery")
    parser.add_argument("--wrapper", type=Path, default=DEFAULT_WRAPPER)
    parser.add_argument("--retries", type=int, default=6)
    parser.add_argument("--base-delay", type=float, default=15.0)
    parser.add_argument("--max-delay", type=float, default=180.0)
    parser.add_argument("--recover-only", action="store_true")
    args = parser.parse_args()

    if args.recover_only:
        recovered = recover_from_log(args.log, args.out) if args.log else None
        if not recovered:
            raise SystemExit("nothing to recover")
        print(f"recovered -> {recovered}")
        return

    result = fetch_with_retry(
        args.wrapper,
        args.state,
        args.out,
        log_path=args.log,
        retries=args.retries,
        base_delay=args.base_delay,
        max_delay=args.max_delay,
    )
    print(json.dumps(result, indent=2))
    if result["status"] == "failed":
        raise SystemExit(1)


if __name__ == "__main__":
    main()