Tasks and results

The task module contract (cb.Task, setup_config, the lifecycle decorators, the session API and actions) and the result.json and summary.json a run writes.

A task is a directory with a main.py. cb imports it, calls the @cb.tasks_config function to list the variants, then for each variant starts a sandbox from its computer and runs setup, the agent (or the @cb.solve_task oracle) and evaluation. Each lifecycle function receives the variant's cb.Task and the session on its sandbox.

cb.Task#

One task variant, as returned by the @cb.tasks_config function.

FieldTypeDefaultDescription
descriptionstrrequiredThe instruction the agent receives.
task_idstr | nullNoneA stable identifier for the variant (optional; the index is used otherwise).
metadatadict | nullNoneVariant-specific values your setup, solve and evaluate functions read.
computerdict | nullNoneThe sandbox: {"provider": "native", "setup_config": {...}} (see DesktopSetupConfig). native (the default) is the only provider.

setup_config#

A task's computer["setup_config"]: the sandbox the task runs in. Every key is optional. Command-line flags (--image, --kind, --cpu, --memory) override the task's values; --runtime (the engine) is a command-line choice only.

KeyTypeDescription
os_typestringGuest OS: linux (the default; ubuntu is an alias), windows (win11, win10 and older names are aliases), macos or android. macOS and Android run only with --on local.
widthintScreen width in pixels.
heightintScreen height in pixels.
imagestrRegistry image or OS alias (linux, windows, macos:tahoe). --image wins, then this, then CUA_BENCH_IMAGE, then the canonical image of os_type.
kindstrPreferred kind: container (Linux only) or vm.
kindslist[str]Kinds the task supports (a requirement, unlike kind): for example ["vm"] for a task that needs its own kernel.
requireslist[str]What the target must provide: kvm, env:<NAME> (a set environment variable), openai (env:OPENAI_API_KEY) or hf-gated (env:HF_TOKEN).
server_portintA port the image serves itself, used as the readiness probe.
memorystrVM memory, for example "8GB".
cpustrVM CPUs, for example "4".
backgroundstrIgnored (kept so older tasks still load).
wallpaperstrIgnored (kept so older tasks still load).
installed_appslist[str]Ignored (kept so older tasks still load).
storagestrDeprecated and ignored.
provider_typestrDeprecated: "cloud" named Cua Cloud, which has ended (it raises).

Lifecycle decorators#

DecoratorDescription
@cb.tasks_configMarks the function that lists the task's variants. The function takes no arguments and returns a list of cb.Task; the CLI indexes them from 0 (--variant-id). Use as @cb.tasks_config or with a split: @cb.tasks_config("train") (default train).
@cb.setup_taskMarks the function that prepares a variant's sandbox. async def setup(task_cfg: cb.Task, session: cb.DesktopSession) runs after the sandbox starts and before the agent or the oracle. Use as @cb.setup_task or with a split: @cb.setup_task("train").
@cb.solve_taskMarks the oracle: the function that solves a variant (optional). async def solve(task_cfg: cb.Task, session: cb.DesktopSession) runs instead of an agent with --oracle or when no agent is given. Use as @cb.solve_task or with a split: @cb.solve_task("train").
@cb.evaluate_taskMarks the function that scores a variant. async def evaluate(task_cfg: cb.Task, session: cb.DesktopSession) returns the evaluation, commonly list[float]; the reward is the mean of its numbers. Use as @cb.evaluate_task or with a split: @cb.evaluate_task("train").

Session#

Unified desktop session using the cua-sandbox SDK.

MethodReturnsDescription
computerAnyThe cua-computer style Computer of this session (0.2.x).
sandboxAnyThe connected cua_sandbox.Sandbox (None for computer-server sessions).
await step(action: Action)NoneExecute an action (alias for execute_action, for env.step() compatibility).
await start(config: Optional[DesktopSetupConfig]=None, headless: Optional[bool]=None)NoneStart the session and connect to the environment.
interfaceAnyThe cua-computer 0.5 interface surface of this session.
await serve_static(url_path: str, local_path: str)NoneServe static files - not applicable for remote environments.
await launch_window(url: Optional[str]=None, *, html: Optional[str]=None, folder: Optional[str]=None, title: str='Window', x: Optional[int]=None, y: Optional[int]=None, width: int=600, height: int=400, icon: Optional[str]=None, use_inner_size: bool=False, title_bar_style: str='default')int | strLaunch a window in the remote environment using bench_ui (pywebview).
await get_element_rect(pid: int | str, selector: str, *, space: Literal['window', 'screen']='window', timeout: float=0.5)dict[str, Any] | NoneGet element rect by CSS selector using bench_ui.
await execute_javascript(pid: int | str, javascript: str)AnyExecute JavaScript in a pywebview window using bench_ui.
await execute_action(action: Action)NoneExecute an action on the remote desktop using the SDK.
await screenshot()bytesCapture screenshot from remote environment.
await get_snapshot()SnapshotGet snapshot of desktop state with active window info.
await close()NoneClose the session and cleanup resources.
await close_all_windows()NoneClose all windows - best effort.
pageAnyReturn underlying page object - not applicable for remote.
vnc_urlstrReturn the VNC URL for accessing the environment.
appsAppsProxyAccess registered apps via session.apps.{app_name}.
await click_element(pid: int | str, selector: str)NoneFind element by CSS selector and click its center.
await right_click_element(pid: int | str, selector: str)NoneFind element by CSS selector and right-click its center.
await get_accessibility_tree()Dict[str, Any]Get the accessibility tree if supported ({} when not).
await shell_command(command: str, *, check: bool=True, timeout: Optional[float]=None)Dict[str, Any]Execute a shell command.
await read_file(path: str)strRead a text file from the environment.
await write_file(path: str, content: str)NoneWrite a text file to the environment.
await read_bytes(path: str)bytesRead a file as bytes from the environment.
await write_bytes(path: str, data: bytes)NoneWrite bytes to a file in the environment.
await file_exists(path: str)boolWhether path is an existing file (not a directory), as in 0.2.x.
await directory_exists(path: str)boolCheck if a directory exists in the environment.
await list_dir(path: str)list[str]List contents of a directory in the environment.
await run_command(command: str, *, check: bool=True, timeout: Optional[float]=None)Dict[str, Any]Execute a shell command (alias for shell_command).
await launch_application(app_name: str)NoneLaunch an application by name.
await check_status()boolCheck if the environment is responsive.
await wait_until_ready(timeout: int=60, poll_interval: float=2.0)boolWait until the environment is ready.
await click(x: int, y: int)NoneClick at coordinates.
await right_click(x: int, y: int)NoneRight-click at coordinates.
await double_click(x: int, y: int)NoneDouble-click at coordinates.
await type(text: str)NoneType text.
await key(key: str)NonePress a key.
await hotkey(keys: list[str])NonePress a key combination.
await scroll(direction: str='down', amount: int=300)NoneScroll the screen.
await move_to(x: int, y: int)NoneMove cursor to coordinates.
await drag(from_x: int, from_y: int, to_x: int, to_y: int)NoneDrag from one position to another.
os_typestrReturn the OS type for this session.
await install_app(app_name: str, *, with_shortcut: bool=True, **kwargs)NoneInstall a registered app on the native desktop environment.
await launch_app(app_name: str, **kwargs)NoneLaunch a registered app on the native desktop environment.

Actions#

Input actions for session.execute_action (from cua_bench).

ActionFields
ClickActionx: int, y: int
RightClickActionx: int, y: int
DoubleClickActionx: int, y: int
MiddleClickActionx: int, y: int
DragActionfrom_x: int, from_y: int, to_x: int, to_y: int, duration: float = 1.0
MoveToActionx: int, y: int, duration: float = 0.0
ScrollActiondirection: string = 'up', amount: int = 100
TypeActiontext: str
KeyActionkey: str
HotkeyActionkeys: list[str]
DoneActionnone
WaitActionseconds: float = 1.0

Example#

"""A tiny native task for smoke-testing a target: write a word to a file.
 
Runs on any Linux image with cua-spacesd (shell and files), for example:
 
    cb run example_tasks/hello_file_env                    # local gVisor container
    cb run example_tasks/hello_file_env --image <registry ref>
"""
 
import cua_bench as cb
 
WORDS = ["hello", "bench"]
 
@cb.tasks_config(split="train")
def load():
    return [
        cb.Task(
            description=f"Write the word '{word}' into /tmp/cb_answer.txt.",
            metadata={"word": word},
            computer={"provider": "native", "setup_config": {"os_type": "linux"}},
        )
        for word in WORDS
    ]
 
@cb.setup_task(split="train")
async def setup(task_cfg, session: cb.DesktopSession):
    await session.run_command("rm -f /tmp/cb_answer.txt", check=False)
    await session.write_file("/tmp/cb_goal.txt", task_cfg.metadata["word"])
 
@cb.solve_task(split="train")
async def solve(task_cfg, session: cb.DesktopSession):
    await session.run_command("cp /tmp/cb_goal.txt /tmp/cb_answer.txt")
 
@cb.evaluate_task(split="train")
async def evaluate(task_cfg, session: cb.DesktopSession) -> list[float]:
    if not await session.file_exists("/tmp/cb_answer.txt"):
        return [0.0]
    answer = (await session.read_file("/tmp/cb_answer.txt")).strip()
    return [1.0 if answer == task_cfg.metadata["word"] else 0.0]

Result files#

A run writes one directory per variant and a summary.json next to them:

<output-dir>/
  summary.json
  <task>_v<variant>/          (with _a<attempt> for --attempts repeats)
    result.json
    run.log
    trajectory.json           (ATIF-v1.8, screenshots under imgs/)
    task_<variant>_trace/     (a Hugging Face dataset of the trace events)

Both files carry schema_version; new keys are additive, and a rename or removal bumps the version.

result.json#

One variant's outcome: the cua-bench fields of its result.json.

KeyTypeDescription
schema_versionintLayout version; a rename or removal bumps it, new keys do not.
session_idstrThe session id (also the variant's log and trace key).
taskstrTask directory name.
variantintVariant index (--variant-id).
statusstrcompleted, failed or cancelled.
rewardfloat | nullThe mean of the evaluation's numbers (true counts as 1), or null when evaluation did not run.
evaluationanyWhat @cb.evaluate_task returned (commonly a list of floats).
errorstr | nullThe error message when the variant failed.
duration_sfloatWall time of the variant in seconds.
onstrWhere it ran: local, or the provider of --on.
backendstrWhat ran it, <location>-<engine> (local-gvisor, local-qemu, e2b-auto).
imagestr | nullThe image as the task or --image named it.
output_dirstrThe variant's output directory.
extradictExtra values the task or agent reported.
kindstr | nullcontainer or vm.
runtimestr | nullThe engine (gvisor, runc, qemu, lume) when one was chosen; None: the SDK picked.
image_refstr | nullThe resolved image reference.
image_variantstr | nullThe image variant that ran: rootfs, containerdisk or lume.
image_digeststr | nullThe pinned repo@sha256:... when the SDK reports it.
archstr | nullGuest architecture, when known.
attemptintThe --attempts repeat index (0 for the first).
retriesintHow many infrastructure retries (--retries) the variant took.
sandboxstr | nullThe sandbox's qualified ref (local:<name>), when known.
idstrA random id for this trial.
task_namestrThe task directory name.
trial_namestr<task>_v<variant>, with _a<attempt> for repeats.
trial_uristr | nullfile:// URI of the variant's output directory.
sourcestrAlways cua-bench.
agent_infodictThe agent label, version and model ({name, provider}).
verifier_resultdict | null{"rewards": {"reward": <float>, ...}} (numeric evaluation keys included), or null.
exception_infodict | nullException type, message, traceback and time when the variant raised, else null.
started_atstr | nullWhen the trial started.
finished_atstr | nullWhen the trial finished.
environment_setupSpan | nullSandbox start and task setup.
agent_setupnullAlways null (agents run in the cb process).
agent_executionSpan | nullThe agent's (or the oracle's) run.
verifierSpan | nullThe evaluation.

Phase spans (environment_setup, agent_execution, verifier) are started_at and finished_at timestamps (ISO 8601, UTC).

summary.json#

summary.json: the run's totals, written next to each variant's directory.

KeyTypeDescription
schema_versionintLayout version; a rename or removal bumps it, new keys do not.
totalintVariants run.
completedintVariants that completed.
failedintVariants that failed or were cancelled.
avg_rewardfloat | nullMean reward over variants with a reward, or null.
resultslist[SummaryResult]One row per variant (SummaryResult).
n_total_trialsintThe number of trials (Harbor), equal to total.
statsSummaryStatsHarbor-compatible statistics (SummaryStats).
pass_at_kdict | null{"<k>": <pass@k>} with --attempts above 1 (binary rewards, unbiased estimator), else null.
targetslist[SummaryTarget]Where the variants ran (SummaryTarget).

results[]#

One row of summary.json results: a variant's outcome.

KeyTypeDescription
results[].taskstrTask directory name.
results[].variantintVariant index (--variant-id).
results[].statusstrcompleted, failed or cancelled.
results[].rewardfloat | nullThe mean of the evaluation's numbers (true counts as 1), or null when evaluation did not run.
results[].duration_sfloatWall time of the variant in seconds.
results[].errorstr | nullThe error message when the variant failed.
results[].kindstr | nullcontainer or vm.
results[].runtimestr | nullThe engine (gvisor, runc, qemu, lume) when one was chosen, else null (the SDK picked).
results[].image_variantstr | nullThe image variant that ran: rootfs, containerdisk or lume.
results[].image_digeststr | nullThe pinned repo@sha256:... when the SDK reports it.
results[].attemptintThe --attempts repeat index (0 for the first).
results[].retriesintHow many infrastructure retries (--retries) the variant took.

stats#

KeyTypeDescription
stats.n_completedintVariants that completed.
stats.n_erroredintVariants with no reward that did not complete (the run broke).
stats.n_retriesintInfrastructure retries across the run.

targets[]#

Where variants ran: one row per (on, kind, runtime, image variant, image).

KeyTypeDescription
targets[].onstrWhere it ran: local, or the provider of --on.
targets[].kindstr | nullcontainer or vm.
targets[].runtimestr | nullThe engine (gvisor, runc, qemu, lume) when one was chosen; None: the SDK picked.
targets[].image_variantstr | nullThe image variant that ran: rootfs, containerdisk or lume.
targets[].imagestr | nullThe pinned digest when known, else the image reference.
targets[].countintVariants that ran there.