Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

10.3 KB
Raw Blame
# SPDX-License-Identifier: FSL-1.1-MIT
# Copyright (c) 2026 Cua AI, Inc.

"""Summarize a BenchSentinel JSONL log over its armed window.

The armed window runs from the first {"ev":"armed"} line to the next
{"ev":"disarmed"} line, or to EOF if the log is never disarmed. Lines outside
the window are ignored.
"""

from __future__ import annotations

import argparse
import json
import math
import re
import sys
from typing import Any

SENTINEL_BID = "ai.cua.benchsentinel"
DEVIATION_PX = 10.0
HID_KEYS = ("move", "down", "key", "scroll")
# Amendment 15: overlay and indicator windows of the computer-use tools themselves (the agent cursor, the
# "ChatGPT Computer Use" banner, the `cua-driver` process on Windows, the cua-driver agent cursor's Wayland layer
# `cua-agent-cursor`) are not raises. They are logged as metadata (`overlay_owners`) only.
OVERLAY_OWNER_RE = re.compile(
    r"(?i)cua[ _-]?driver|cua-agent-cursor|chatgpt computer use|computer use|codex|app-cu-helper|claude"
)
FRONT_EVENTS = ("s", "front", "armed", "disarmed")
# Idle values only ever grow between samples unless a real event resets them.
DROP_EPSILON_S = 1e-3


def _read_lines(log_path: str) -> list[dict[str, Any]]:
    lines: list[dict[str, Any]] = []
    with open(log_path, encoding="utf-8") as handle:
        for raw in handle:
            raw = raw.strip()
            if not raw:
                continue
            try:
                obj = json.loads(raw)
            except json.JSONDecodeError:
                continue  # a torn final line is not an error
            if isinstance(obj, dict) and isinstance(obj.get("t"), (int, float)):
                lines.append(obj)
    return lines


def _armed_window(lines: list[dict[str, Any]]) -> list[dict[str, Any]]:
    start = next((i for i, ln in enumerate(lines) if ln.get("ev") == "armed"), None)
    if start is None:
        return []
    end = len(lines)
    for i in range(start + 1, len(lines)):
        if lines[i].get("ev") == "disarmed":
            end = i + 1  # keep the disarm line as the last baseline
            break
    return lines[start:end]


def _bid(front: Any) -> str | None:
    if not isinstance(front, dict):
        return None
    bid = front.get("bid")
    if isinstance(bid, str) and bid:
        return bid
    pid = front.get("pid")
    return f"pid:{pid}" if isinstance(pid, int) and pid >= 0 else None


def _point(value: Any) -> tuple[float, float] | None:
    if (
        isinstance(value, (list, tuple))
        and len(value) == 2
        and all(isinstance(v, (int, float)) for v in value)
    ):
        return float(value[0]), float(value[1])
    return None


def summarize(log_path: str) -> dict[str, Any]:
    """Return disturbance metrics for the armed window of a sentinel log."""
    lines = _read_lines(log_path)
    window = _armed_window(lines)
    result: dict[str, Any] = {
        "front_changes": 0,
        "front_changed_to": [],
        "key_loss": 0,
        "activations_lost": 0,
        "keystrokes_leaked": 0,
        "clicks_leaked": 0,
        "scrolls_leaked": 0,
        "pointer_max_deviation_px": 0.0,
        "pointer_deviation_episodes": 0,
        "hid_events": {k: 0 for k in HID_KEYS},
        "samples": 0,
        "duration_s": 0.0,
        "available": False,
    }
    if not window:
        return result

    armed_line = window[0]
    last = window[-1]
    # A closing "disarmed" line is a boundary, not part of the measured events.
    body = window[:-1] if last.get("ev") == "disarmed" and len(window) > 1 else window
    result["duration_s"] = round((last["t"] - armed_line["t"]) / 1000.0, 3)

    origin = _point(armed_line.get("mouse"))
    prev_front = _bid(armed_line.get("front"))
    prev_idle: dict[str, float] | None = None
    changed_to: set[str] = set()
    in_episode = False

    for line in window:
        # Front changes come from samples and workspace activation events only;
        # other events read the frontmost app and can be stale at that instant.
        front = _bid(line.get("front")) if line.get("ev") in FRONT_EVENTS else None
        if front is not None:
            if front != prev_front and front != SENTINEL_BID:
                result["front_changes"] += 1
                changed_to.add(front)
            prev_front = front

        # HID idle drops: baseline is the armed line, then each sample.
        idle = line.get("idle")
        if isinstance(idle, dict) and line.get("ev") in ("s", "armed", "disarmed"):
            current = {k: float(idle[k]) for k in HID_KEYS if isinstance(idle.get(k), (int, float))}
            if prev_idle is not None and line is not armed_line:
                for k in HID_KEYS:
                    if (
                        k in current
                        and k in prev_idle
                        and current[k] < prev_idle[k] - DROP_EPSILON_S
                    ):
                        result["hid_events"][k] += 1
            prev_idle = current

    for line in body:
        ev = line.get("ev")
        if ev == "didResignKey":
            result["key_loss"] += 1
        elif ev == "didResignActive":
            result["activations_lost"] += 1
        elif ev == "keyDown":
            result["keystrokes_leaked"] += 1
        elif ev == "mouseDown":
            result["clicks_leaked"] += 1
        elif ev == "scrollWheel":
            result["scrolls_leaked"] += 1
        elif ev == "s":
            result["samples"] += 1
            point = _point(line.get("mouse"))
            if origin is None and point is not None:
                origin = point
            if point is not None and origin is not None:
                dist = math.hypot(point[0] - origin[0], point[1] - origin[1])
                result["pointer_max_deviation_px"] = max(result["pointer_max_deviation_px"], dist)
                if dist > DEVIATION_PX:
                    if not in_episode:
                        result["pointer_deviation_episodes"] += 1
                    in_episode = True
                else:
                    in_episode = False

    _windows_raised(window, result)
    _user_activity(window, result)
    _multiplayer(window, body, result)
    result["pointer_max_deviation_px"] = round(result["pointer_max_deviation_px"], 2)
    result["front_changed_to"] = sorted(changed_to)
    result["available"] = result["samples"] >= 10
    return result


def _windows_raised(window: list[dict[str, Any]], result: dict[str, Any]) -> None:
    """Amendment 14 (CUA-1282): count raise episodes, i.e. lines where a window owner that was not
    above the sentinel's window on the previous line now is. The armed line is the baseline.
    Logs from sentinels without the `above_n` field give None (not measured)."""
    measured = [
        ln for ln in window if ln.get("ev") in ("s", "armed", "disarmed") and "above_n" in ln
    ]
    if not measured:
        result["windows_raised"] = None
        result["raised_by"] = []
        return
    overlays: set[str] = set()

    def task_owners(line: dict[str, Any]) -> set[str]:
        out = set()
        for o in line.get("above") or []:
            if not isinstance(o, str):
                continue
            if OVERLAY_OWNER_RE.search(o):
                overlays.add(o)
            else:
                out.add(o)
        return out

    prev = task_owners(measured[0])
    raised = 0
    owners: set[str] = set()
    for line in measured[1:]:
        now = task_owners(line)
        new = now - prev
        if new:
            raised += 1
            owners |= new
        prev = now
    result["windows_raised"] = raised
    result["raised_by"] = sorted(owners)
    result["overlay_owners"] = sorted(overlays)
    result["above_at_start"] = sorted(
        o for o in (measured[0].get("above") or []) if isinstance(o, str)
    )


def _multiplayer(
    window: list[dict[str, Any]], body: list[dict[str, Any]], result: dict[str, Any]
) -> None:
    """Amendment 22: the clipboard, Space and sheet measures, and activations of the user's app. Each is None
    when the sentinel that wrote the log did not record it (logs from before A22)."""
    samples = [ln for ln in window if ln.get("ev") in ("s", "armed", "disarmed")]
    clips = [ln["clip"] for ln in samples if isinstance(ln.get("clip"), int)]
    result["clipboard_changes"] = (clips[-1] - clips[0]) if len(clips) >= 2 else None
    spaces = [ln for ln in samples if "onspace" in ln]
    if spaces or any(ln.get("ev") == "space" for ln in body):
        events = sum(1 for ln in body if ln.get("ev") == "space")
        off = sum(
            1 for a, b in zip(spaces, spaces[1:]) if a.get("onspace") and not b.get("onspace")
        )
        result["space_switches"] = (
            events or off
        )  # the notification when it fired, else the sampled transitions
    else:
        result["space_switches"] = None
    sheets = [ln for ln in samples if "sheet" in ln]
    result["sheets_shown"] = (
        sum(1 for a, b in zip(sheets, sheets[1:]) if b.get("sheet") and not a.get("sheet"))
        if sheets
        else None
    )
    result["activations_gained"] = sum(1 for ln in body if ln.get("ev") == "didBecomeActive")


def _user_activity(window: list[dict[str, Any]], result: dict[str, Any]) -> None:
    """Amendment 15: the simulated user's typing in the user-activity window. None when the sentinel ran
    without --user-activity (no user_* lines and no user_text line)."""
    evs = [ln.get("ev") for ln in window]
    texts = [ln for ln in window if ln.get("ev") == "user_text"]
    if not texts and not any(
        e in ("user_type", "user_blocked", "user_text_disrupted") for e in evs
    ):
        result["user_activity"] = None
        return
    typed = evs.count("user_type")
    blocked = evs.count("user_blocked")
    disrupted = evs.count("user_text_disrupted")
    intact = texts[-1].get("intact") if texts else None
    result["user_activity"] = {
        "typed": typed,
        "blocked": blocked,
        "text_disruptions": disrupted,
        "text_intact_at_end": intact,
        "disrupted": bool(blocked or disrupted or intact is False),
    }


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("log", help="BenchSentinel JSONL log")
    args = parser.parse_args(argv)
    json.dump(summarize(args.log), sys.stdout, indent=2, sort_keys=True)
    sys.stdout.write("\n")
    return 0


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