File size: 11,617 Bytes
44084af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Read Harbor ATIF trajectories (agent/trajectory.json) and recover the file edits an agent made.

Supported edit shapes (anything else that looks like it modifies files marks the replay approximate):
  - structured write/edit tools: Write, Edit, MultiEdit, write_file, replace_in_file, str_replace, create_file
  - apply_patch (V4A patch text), as a tool or as `apply_patch <<'EOF'` inside a shell command
  - shell heredocs: `cat > path <<'EOF' ... EOF` and `cat <<'EOF' > path`
Paths are resolved against /workspace/monitoring (the task's working directory).
"""

from __future__ import annotations

import json
import re
import shlex

WS = "/workspace/monitoring"
SHELL_TOOLS = {"bash", "shell", "exec_command", "bash_command", "run_terminal_cmd", "local_shell", "terminal",
               "run_shell_command", "execute_command"}
_HEREDOC = re.compile(r"cat\s+(?:>\s*(?P<p1>\S+)\s+<<-?\s*(?P<q1>['\"]?)(?P<t1>\w+)(?P=q1)"
                      r"|<<-?\s*(?P<q2>['\"]?)(?P<t2>\w+)(?P=q2)\s*>\s*(?P<p2>\S+))[^\n]*\n")
_PATCH_HEREDOC = re.compile(r"apply_patch\s+<<-?\s*(['\"]?)(\w+)\1[^\n]*\n")
_MUTATING = re.compile(r"(?<![0-9&])>(?!\s*/dev/null)(?!&)|\bsed\s+-i|\btee\b|\bmv\s|\bcp\s|\brm\s|\bpython3?\s+-c"
                       r"|\bperl\s+-[pi]|\bapply_patch\b|\btruncate\b|\bpatch\s")


def rel_path(p: str | None) -> str | None:
    """Workspace-relative path, or None when the path is outside /workspace/monitoring."""
    if not p:
        return None
    p = p.strip().strip("'\"")
    if p.startswith(WS + "/"):
        p = p[len(WS) + 1:]
    elif p.startswith("/"):
        return None
    p = re.sub(r"^\./", "", p)
    return None if ".." in p.split("/") else p


def command_text(args: dict) -> str:
    c = args.get("command", args.get("cmd", args.get("keystrokes", args.get("input", ""))))
    if isinstance(c, list):
        c = c[-1] if len(c) >= 3 and c[0] in ("bash", "sh", "zsh") and c[1] in ("-lc", "-c") else shlex.join(c)
    return str(c or "")


def shell_ops(cmd: str) -> tuple[list[tuple], bool]:
    """Edits recoverable from a shell command, plus whether an unrecovered write may remain."""
    ops, rest, pos = [], [], 0
    while True:
        m_h, m_p = _HEREDOC.search(cmd, pos), _PATCH_HEREDOC.search(cmd, pos)
        m = min((x for x in (m_h, m_p) if x), key=lambda x: x.start(), default=None)
        if m is None:
            rest.append(cmd[pos:])
            break
        tag = m.group(2) if m is m_p else (m.group("t1") or m.group("t2"))
        end = re.compile(rf"^\s*{re.escape(tag)}\s*$", re.M).search(cmd, m.end())
        body = cmd[m.end():end.start() if end else len(cmd)]
        rest.append(cmd[pos:m.start()])
        if m is m_p:
            ops.append(("patch", body))
        else:
            path = rel_path(m.group("p1") or m.group("p2"))
            if path:
                ops.append(("write", path, body))
        pos = end.end() if end else len(cmd)
    leftover = "".join(rest)
    return ops, bool(_MUTATING.search(leftover))


def call_ops(name: str, args: dict) -> tuple[list[tuple], bool]:
    """(edit ops, maybe_unreplayed) for one tool call."""
    n = (name or "").lower()
    path = rel_path(args.get("file_path") or args.get("path") or args.get("filename"))
    if n in ("write", "write_file", "create_file", "create") and "content" in args:
        return ([("write", path, str(args["content"]))] if path else []), False
    if n in ("edit", "str_replace", "replace_in_file", "str_replace_editor", "edit_file"):
        old = args.get("old_string", args.get("old", args.get("old_str")))
        new = args.get("new_string", args.get("new", args.get("new_str")))
        if path and old is not None and new is not None:
            return [("replace", path, str(old), str(new), bool(args.get("replace_all")))], False
        return [], bool(path)
    if n == "multiedit":
        return ([("replace", path, str(e.get("old_string", "")), str(e.get("new_string", "")),
                  bool(e.get("replace_all"))) for e in args.get("edits") or []] if path else []), False
    if n == "apply_patch":
        return [("patch", str(args.get("input") or args.get("patch") or command_text(args)))], False
    if n == "exec" and "tools." in str(args.get("input", "")):
        return codex_exec_ops(str(args["input"]))
    if n in SHELL_TOOLS:
        return shell_ops(command_text(args))
    return [], False


_JS_STR = r'"(?:[^"\\]|\\.)*"'
_JS_PATCH = re.compile(r"tools\.apply_patch\(\s*(" + _JS_STR + ")")
_JS_CMD = re.compile(r"\bcmd\s*:\s*(" + _JS_STR + ")")


def codex_exec_ops(src: str) -> tuple[list[tuple], bool]:
    """Codex code-mode: one `exec` call holds JS that calls tools.apply_patch("...") / tools.exec_command({cmd:"..."})."""
    events = []
    for m in _JS_PATCH.finditer(src):
        events.append((m.start(), [("patch", json.loads(m.group(1)))], False))
    for m in _JS_CMD.finditer(src):
        ops, maybe = shell_ops(json.loads(m.group(1)))
        events.append((m.start(), ops, maybe))
    ops, maybe = [], False
    for _, o, mb in sorted(events, key=lambda e: e[0]):
        ops += o
        maybe = maybe or mb
    # commands built dynamically (e.g. a JS array passed to exec_command) cannot be replayed exactly
    if "exec_command" in src and not _JS_CMD.search(src):
        maybe = maybe or bool(_MUTATING.search(src))
    return ops, maybe


def apply_v4a(files: dict, patch: str) -> tuple[list[tuple], bool]:
    """Turn a V4A patch into write/delete ops against `files` ({rel: text}); returns (ops, ok)."""
    ops, ok = [], True
    lines = patch.splitlines()
    i = 0
    while i < len(lines):
        ln = lines[i]
        if ln.startswith("*** Add File: "):
            path, body = rel_path(ln[14:]), []
            i += 1
            while i < len(lines) and not lines[i].startswith("*** "):
                body.append(lines[i][1:] if lines[i].startswith("+") else lines[i])
                i += 1
            if path:
                ops.append(("write", path, "\n".join(body) + "\n"))
            continue
        if ln.startswith("*** Delete File: "):
            path = rel_path(ln[17:])
            if path:
                ops.append(("delete", path))
            i += 1
            continue
        if ln.startswith("*** Update File: "):
            path, target = rel_path(ln[17:]), None
            i += 1
            if i < len(lines) and lines[i].startswith("*** Move to: "):
                target = rel_path(lines[i][13:])
                i += 1
            hunks, cur = [], []
            while i < len(lines) and not (lines[i].startswith("*** ") and lines[i] != "*** End of File"):
                if lines[i].startswith("@@"):
                    if cur:
                        hunks.append(cur)
                    cur = []
                elif lines[i] != "*** End of File":
                    cur.append(lines[i])
                i += 1
            if cur:
                hunks.append(cur)
            text = files.get(path) if path else None
            if text is None:
                ok = False
                continue
            cursor = 0
            for h in hunks:
                old = "\n".join(x[1:] for x in h if x[:1] in (" ", "-") or x == "")
                new = "\n".join(x[1:] for x in h if x[:1] in (" ", "+") or x == "")
                at = text.find(old, cursor) if old else len(text)
                if at < 0:
                    ok = False
                    continue
                text = text[:at] + new + text[at + len(old):]
                cursor = at + len(new)
            if target and target != path:
                ops.append(("delete", path))
            ops.append(("write", target or path, text))
            continue
        i += 1
    return ops, ok


def load_trajectory(path: str) -> dict:
    with open(path) as fh:
        return json.loads(renamed(fh.read()))


# ---------------------------------------------------------------------------- renamed host names

_RENAME: tuple | None = None   # (regex, mapping), set by load_renames
_COPIES: list[str] = []


def load_renames(path: str | None) -> int:
    """`--rename-map FILE` ({"map": {old: new}}): host names a release renamed in the tasks (the fictional company
    domains moved to reserved `.example` names in 0.2.0). Stored trajectories, traces and workspaces are read
    through it, so that they replay and grade against the renamed tasks. Returns the number of names."""
    global _RENAME
    if not path:
        _RENAME = None
        return 0
    with open(path) as fh:
        m = json.load(fh)["map"]
    keys = sorted(m, key=lambda k: (-len(k), k))
    _RENAME = (re.compile(r"(?<![A-Za-z0-9-])(?:" + "|".join(map(re.escape, keys)) + r")(?![A-Za-z0-9])"), m)
    return len(m)


def renamed(text: str) -> str:
    if _RENAME is None:
        return text
    rx, m = _RENAME
    return rx.sub(lambda mo: m[mo.group(0)], text)


def renamed_tree(root: str) -> str:
    """`root` itself without a rename map; otherwise a scratch copy (removed at exit) with every UTF-8 file and file
    name read through the map."""
    if _RENAME is None:
        return root
    import atexit
    import os
    import shutil
    import tempfile
    if not _COPIES:
        atexit.register(lambda: [shutil.rmtree(d, ignore_errors=True) for d in _COPIES])
    dst = tempfile.mkdtemp(prefix="af-renamed-")
    _COPIES.append(dst)
    out = os.path.join(dst, os.path.basename(root.rstrip("/")))
    for dp, dns, fns in os.walk(root):
        dns[:] = [d for d in dns if d != "__pycache__"]
        for fn in fns:
            src = os.path.join(dp, fn)
            if os.path.islink(src):
                continue
            rel = renamed(os.path.relpath(src, root))
            p = os.path.join(out, rel)
            os.makedirs(os.path.dirname(p), exist_ok=True)
            with open(src, "rb") as fh:
                data = fh.read()
            try:
                data = renamed(data.decode("utf-8")).encode("utf-8")
            except UnicodeDecodeError:
                pass
            with open(p, "wb") as fh:
                fh.write(data)
            shutil.copymode(src, p)
    return out


def text_of(content) -> str:
    if content is None:
        return ""
    if isinstance(content, str):
        return content
    if isinstance(content, list):
        return "\n".join(str(p.get("text", "")) for p in content if isinstance(p, dict) and p.get("type") == "text")
    return str(content)


def iter_events(traj: dict):
    """Yield ('think', text) | ('call', id, name, args) | ('obs', id, text) in trajectory order.

    The first user message (the task instruction) and system messages are skipped.
    """
    seen_user = False
    for st in traj.get("steps") or []:
        src = st.get("source")
        if src == "system":
            continue
        if src == "user":
            if seen_user:
                yield ("think", "[user] " + text_of(st.get("message")))
            seen_user = True
            continue
        thought = "\n\n".join(x for x in (st.get("reasoning_content") or "", text_of(st.get("message"))) if x.strip())
        if thought.strip():
            yield ("think", thought)
        calls = st.get("tool_calls") or []
        for c in calls:
            yield ("call", c.get("tool_call_id"), c.get("function_name", ""), c.get("arguments") or {})
        results = ((st.get("observation") or {}).get("results")) or []
        for k, r in enumerate(results):
            cid = r.get("source_call_id") or (calls[k].get("tool_call_id") if k < len(calls) else None)
            yield ("obs", cid, text_of(r.get("content")))