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.

fix lint errors (#1345)

r33drichards6b12a70434fd
diff --git a/libs/cua-bench/cua_bench/agents/opencua_agent.py b/libs/cua-bench/cua_bench/agents/opencua_agent.py
index f03a99b57a..95843e8502 100644
--- a/libs/cua-bench/cua_bench/agents/opencua_agent.py
+++ b/libs/cua-bench/cua_bench/agents/opencua_agent.py
@@ -151,7 +151,7 @@ class OpenCUAAgent(BaseAgent):
) from e
instruction = self._render_instruction(task_description)
-
+
print(f"Instruction: {instruction}")
trajectory_dir = None
@@ -188,7 +188,7 @@ class OpenCUAAgent(BaseAgent):
),
**extra_kwargs,
)
-
+
print(f"OpenCUA Agent initialized with model: {composed_model}")
total_usage = {
@@ -197,13 +197,11 @@ class OpenCUAAgent(BaseAgent):
"total_tokens": 0,
"response_cost": 0.0,
}
-
- last_exc: BaseException | None = None
-
+
try:
step = 0
task_completed = False
-
+
async for result in agent.run(instruction):
sys.stdout.flush()
step += 1
diff --git a/libs/cua-bench/cua_bench/agents/qwen35_agent.py b/libs/cua-bench/cua_bench/agents/qwen35_agent.py
index c9a14c9708..4930b76797 100644
--- a/libs/cua-bench/cua_bench/agents/qwen35_agent.py
+++ b/libs/cua-bench/cua_bench/agents/qwen35_agent.py
@@ -40,7 +40,7 @@ if TYPE_CHECKING:
@register_agent("qwen35")
class Qwen35Agent(BaseAgent):
"""Agent implementation using a Qwen3.5 model via the CUA Computer Agent SDK."""
-
+
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.model = kwargs.get("model", "openai/qwen35-4b")
@@ -131,7 +131,7 @@ class Qwen35Agent(BaseAgent):
"move": move,
"scroll": scroll,
"drag": drag,
- "wait": wait
+ "wait": wait,
}
async def perform_task(
diff --git a/libs/cua-bench/cua_bench/agents/qwen3vl_agent.py b/libs/cua-bench/cua_bench/agents/qwen3vl_agent.py
index 0eb26ec31a..de8337abfe 100644
--- a/libs/cua-bench/cua_bench/agents/qwen3vl_agent.py
+++ b/libs/cua-bench/cua_bench/agents/qwen3vl_agent.py
@@ -206,14 +206,20 @@ class Qwen3VLAgent(BaseAgent):
action = out_item.get("action", {})
print(f" [{idx}] computer_call: action={action}")
elif item_type == "function_call":
- print(f" [{idx}] function_call: name={out_item.get('name')}, args={out_item.get('arguments')}")
+ print(
+ f" [{idx}] function_call: name={out_item.get('name')}, args={out_item.get('arguments')}"
+ )
elif item_type == "computer_call_output":
output = out_item.get("output", {})
has_img = "image_url" in output if isinstance(output, dict) else False
print(f" [{idx}] computer_call_output: has_screenshot={has_img}")
elif item_type == "message":
content = out_item.get("content", [])
- texts = [c.get("text", "") for c in content if isinstance(c, dict) and c.get("text")]
+ texts = [
+ c.get("text", "")
+ for c in content
+ if isinstance(c, dict) and c.get("text")
+ ]
print(f" [{idx}] message: {' '.join(texts)[:200]}")
else:
print(f" [{idx}] {item_type}: {str(out_item)[:200]}")
diff --git a/libs/cua-bench/cua_bench/cli/commands/interact.py b/libs/cua-bench/cua_bench/cli/commands/interact.py
index d59ecaa991..6baf797c33 100644
--- a/libs/cua-bench/cua_bench/cli/commands/interact.py
+++ b/libs/cua-bench/cua_bench/cli/commands/interact.py
@@ -172,13 +172,13 @@ async def _execute_simulated_interactive(args, env_path: Path) -> int:
# Set headless to False for interactive mode (fall back if no display available)
import os
import sys
- has_display = (
- sys.platform == "darwin"
- or bool(os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"))
+
+ has_display = sys.platform == "darwin" or bool(
+ os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")
)
if not has_display:
print(f"{GREY}No graphical display detected. Running in headless mode.{RESET}")
-
+
env.headless = not has_display
env.print_actions = True
# Apply max steps if provided
diff --git a/libs/cua-bench/cua_bench/runner/task_runner.py b/libs/cua-bench/cua_bench/runner/task_runner.py
index dc51f58b0e..6ca704343e 100644
--- a/libs/cua-bench/cua_bench/runner/task_runner.py
+++ b/libs/cua-bench/cua_bench/runner/task_runner.py
@@ -888,7 +888,10 @@ class TaskRunner:
raise FileNotFoundError(
f"--with path does not exist: {dev_path} (resolved to {abs_path})"
)
- if not (abs_path / "pyproject.toml").exists() and not (abs_path / "setup.py").exists():
+ if (
+ not (abs_path / "pyproject.toml").exists()
+ and not (abs_path / "setup.py").exists()
+ ):
raise FileNotFoundError(
f"--with path is not an installable package (no pyproject.toml or setup.py): {abs_path}"
)
diff --git a/libs/cua-bench/cua_bench/trainer/off_policy/tinker/__init__.py b/libs/cua-bench/cua_bench/trainer/off_policy/tinker/__init__.py
index e436ebbfaa..7aac05b088 100644
--- a/libs/cua-bench/cua_bench/trainer/off_policy/tinker/__init__.py
+++ b/libs/cua-bench/cua_bench/trainer/off_policy/tinker/__init__.py
@@ -1,5 +1,5 @@
+from .checkpoints import CheckpointInfo, get_last_checkpoint, save_checkpoint
from .grpo import GRPOConfig
-from .checkpoints import CheckpointInfo, save_checkpoint, get_last_checkpoint
__all__ = [
"TrainingConfig",
@@ -14,5 +14,6 @@ __all__ = [
def __getattr__(name: str):
if name in ("TrainingConfig", "run"):
from .rl_loop import TrainingConfig, run
+
return {"TrainingConfig": TrainingConfig, "run": run}[name]
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
diff --git a/libs/cua-bench/cua_bench/trainer/off_policy/tinker/grpo.py b/libs/cua-bench/cua_bench/trainer/off_policy/tinker/grpo.py
index 1447ec9a21..2c3ac40336 100644
--- a/libs/cua-bench/cua_bench/trainer/off_policy/tinker/grpo.py
+++ b/libs/cua-bench/cua_bench/trainer/off_policy/tinker/grpo.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from dataclasses import dataclass, field
+from dataclasses import dataclass
from typing import TYPE_CHECKING, Optional
if TYPE_CHECKING:
@@ -106,8 +106,8 @@ def _build_datum(
All four arrays must have the same length (``model_input.length``).
"""
- import torch
import tinker.types as tt
+ import torch
from tinker.types.tensor_data import TensorData
if not any(a != 0.0 for a in advantages):
@@ -126,7 +126,7 @@ def _build_datum(
"target_tokens": TensorData.from_torch(torch.tensor(target_tokens)),
"logprobs": TensorData.from_torch(torch.tensor(ref_logprobs)),
"advantages": TensorData.from_torch(torch.tensor(advantages)),
- }
+ },
)
@@ -153,7 +153,6 @@ def build_batch(
Observation / system-prompt tokens are masked (advantage = 0).
One datum is produced per trajectory.
"""
- import tinker.types as tt
task_groups = _group_episodes_by_task(episodes)
@@ -165,7 +164,7 @@ def build_batch(
for task_desc, task_episodes in task_groups.items():
for ep in task_episodes:
advantage = _trajectory_advantage(ep, task_episodes)
-
+
steps = _retained_steps(ep, max_images=max_images)
if not steps:
continue
@@ -177,9 +176,7 @@ def build_batch(
for k, step in enumerate(steps):
obs_msgs = _build_messages_up_to_obs(ep, steps, k)
obs_prompt = renderer.build_generation_prompt(obs_msgs)
- action_ids_k = tokenizer.encode(
- step.action_text, add_special_tokens=False
- )
+ action_ids_k = tokenizer.encode(step.action_text, add_special_tokens=False)
if action_ids_k:
# In the target array, position i predicts token i+1.
# The model at position (obs_len - 1) predicts the first
@@ -188,7 +185,7 @@ def build_batch(
if not action_spans:
continue
-
+
# Build model_input: TODO: check whether we need to render everything up to the last observation
# (which includes all prior obs+actions), then append the last
# step's action tokens (minus the final one for next-token shift).
@@ -247,9 +244,7 @@ def build_batch(
per_token_advantages[pos] = advantage
lp_offset += len(action_ids_k)
- datum = _build_datum(
- model_input, target_tokens, per_token_logprobs, per_token_advantages
- )
+ datum = _build_datum(model_input, target_tokens, per_token_logprobs, per_token_advantages)
if datum is not None:
datums.append(datum)
@@ -283,16 +278,11 @@ def train_step(
return {"loss": 0.0, "n_datums": 0}
adam_params = tt.AdamParams(
- learning_rate=config.learning_rate,
- beta1=config.beta1,
- beta2=config.beta2,
- eps=config.eps
+ learning_rate=config.learning_rate, beta1=config.beta1, beta2=config.beta2, eps=config.eps
)
# Submit both futures before blocking — lands in same Tinker cycle
- fwd_bwd_future = training_client.forward_backward(
- datums, loss_fn="importance_sampling"
- )
+ fwd_bwd_future = training_client.forward_backward(datums, loss_fn="importance_sampling")
optim_step_future = training_client.optim_step(adam_params)
# Block and collect results
diff --git a/libs/cua-bench/cua_bench/trainer/off_policy/tinker/rl_loop.py b/libs/cua-bench/cua_bench/trainer/off_policy/tinker/rl_loop.py
index 3d76a2af87..32b60edcfa 100644
--- a/libs/cua-bench/cua_bench/trainer/off_policy/tinker/rl_loop.py
+++ b/libs/cua-bench/cua_bench/trainer/off_policy/tinker/rl_loop.py
@@ -6,10 +6,11 @@ import time
from dataclasses import dataclass, field
from typing import Optional
-from .grpo import GRPOConfig
-from tinker_cookbook import checkpoint_utils, model_info, renderers
+from tinker_cookbook import model_info, renderers
from tinker_cookbook.image_processing_utils import get_image_processor
+from .grpo import GRPOConfig
+
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
@@ -72,11 +73,11 @@ def run(config: TrainingConfig) -> None:
All Tinker imports are deferred so the module can be imported in
environments where ``tinker`` is not installed.
"""
- from tinker import ServiceClient
import tinker.types as tt
- from transformers import AutoTokenizer, AutoProcessor
+ from tinker import ServiceClient
+ from transformers import AutoTokenizer
- from . import traces, rollout, grpo, checkpoints
+ from . import checkpoints, grpo, rollout, traces
from .rollout import _get_run_output_dir
if config.mode not in ("online", "offline"):
@@ -96,9 +97,11 @@ def run(config: TrainingConfig) -> None:
# --- Resume or fresh start ---
resume_info = checkpoints.get_last_checkpoint(config.log_path)
-
+
if resume_info:
- print(f"[loop] Resuming from checkpoint: {resume_info.state_path} (epoch {resume_info.epoch})")
+ print(
+ f"[loop] Resuming from checkpoint: {resume_info.state_path} (epoch {resume_info.epoch})"
+ )
training_client = service_client.create_training_client_from_state_with_optimizer(
resume_info.state_path
)
@@ -113,14 +116,14 @@ def run(config: TrainingConfig) -> None:
start_epoch = 0
# --- Tokenizer ---
- tokenizer = AutoTokenizer.from_pretrained(
- config.base_model, trust_remote_code=True
- )
-
+ tokenizer = AutoTokenizer.from_pretrained(config.base_model, trust_remote_code=True)
+
image_processor = get_image_processor(config.base_model)
-
+
renderer_name = model_info.get_recommended_renderer_name(config.base_model)
- renderer = renderers.get_renderer(renderer_name, tokenizer=tokenizer, image_processor=image_processor)
+ renderer = renderers.get_renderer(
+ renderer_name, tokenizer=tokenizer, image_processor=image_processor
+ )
# --- Sampling params for reference logprobs ---
sampling_params = tt.SamplingParams(max_tokens=1)
@@ -146,7 +149,7 @@ def run(config: TrainingConfig) -> None:
log_path=config.log_path,
kind="state",
loop_state={"epoch": epoch - 1},
- ttl_seconds=config.ttl_seconds
+ ttl_seconds=config.ttl_seconds,
)
# 2. Snapshot current weights for reference logprobs
@@ -179,9 +182,7 @@ def run(config: TrainingConfig) -> None:
# 4. Load traces from all rollout runs
episodes = traces.load_runs(run_dirs)
-
- breakpoint()
-
+
if not episodes:
print(f"[loop] No valid episodes across {len(run_dirs)} runs. Skipping epoch.")
continue
@@ -207,7 +208,7 @@ def run(config: TrainingConfig) -> None:
# 5. Build datums
print("[loop] Building training batch...")
-
+
datums_D = grpo.build_batch(
renderer=renderer,
episodes=episodes,
@@ -215,7 +216,7 @@ def run(config: TrainingConfig) -> None:
sampling_params=sampling_params,
tokenizer=tokenizer,
gamma=config.grpo.gamma,
- max_images=config.grpo.max_images
+ max_images=config.grpo.max_images,
)
# 6. Training step
@@ -243,7 +244,7 @@ def run(config: TrainingConfig) -> None:
loop_state={"epoch": config.epochs},
ttl_seconds=None,
)
- print(f"\n[loop] Training complete.")
+ print("\n[loop] Training complete.")
# ---------------------------------------------------------------------------
@@ -256,33 +257,47 @@ def _build_parser() -> argparse.ArgumentParser:
description="Off-policy RL training loop using Tinker (GRPO-style).",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
- p.add_argument("--mode", choices=["online", "offline"], default="online",
- help="'online' collects rollouts via cb run; 'offline' uses pre-collected run IDs")
+ p.add_argument(
+ "--mode",
+ choices=["online", "offline"],
+ default="online",
+ help="'online' collects rollouts via cb run; 'offline' uses pre-collected run IDs",
+ )
p.add_argument("--base-model", default="Qwen/Qwen3-8B")
p.add_argument("--lora-rank", type=int, default=16)
p.add_argument("--tasks-path", default="tasks/")
p.add_argument("--agent", default="opencua")
- p.add_argument("--model", default="openai/opencua",
- help="litellm model string forwarded to cb run")
+ p.add_argument(
+ "--model", default="openai/opencua", help="litellm model string forwarded to cb run"
+ )
p.add_argument("--max-steps", type=int, default=50)
p.add_argument("--vllm-url", default="http://localhost:30000/v1")
p.add_argument("--epochs", type=int, default=20)
p.add_argument("--save-every", type=int, default=5)
p.add_argument("--log-path", default="/tmp/tinker-cua-rl")
- p.add_argument("--num-rollouts", type=int, default=2,
- help="Number of rollouts per task per epoch (>= 2 for GRPO)")
- p.add_argument("--offline-run-ids", nargs="*", default=[],
- help="Run IDs for offline mode (reused every epoch)")
+ p.add_argument(
+ "--num-rollouts",
+ type=int,
+ default=2,
+ help="Number of rollouts per task per epoch (>= 2 for GRPO)",
+ )
+ p.add_argument(
+ "--offline-run-ids",
+ nargs="*",
+ default=[],
+ help="Run IDs for offline mode (reused every epoch)",
+ )
p.add_argument("--gamma", type=float, default=0.99)
p.add_argument("--lr", type=float, default=1e-5)
- p.add_argument("--beta1", type=float, default=0.9,
- help="AdamW beta1")
- p.add_argument("--beta2", type=float, default=0.95,
- help="AdamW beta2")
- p.add_argument("--max-images", type=int, default=3,
- help="Maximum number of recent screenshots to keep per trajectory")
- p.add_argument("--resume-from", default=None,
- help="tinker:// checkpoint path to resume from")
+ p.add_argument("--beta1", type=float, default=0.9, help="AdamW beta1")
+ p.add_argument("--beta2", type=float, default=0.95, help="AdamW beta2")
+ p.add_argument(
+ "--max-images",
+ type=int,
+ default=3,
+ help="Maximum number of recent screenshots to keep per trajectory",
+ )
+ p.add_argument("--resume-from", default=None, help="tinker:// checkpoint path to resume from")
return p
diff --git a/libs/cua-bench/cua_bench/trainer/off_policy/tinker/rollout.py b/libs/cua-bench/cua_bench/trainer/off_policy/tinker/rollout.py
index 2e7e6a56d4..ae2da3429b 100644
--- a/libs/cua-bench/cua_bench/trainer/off_policy/tinker/rollout.py
+++ b/libs/cua-bench/cua_bench/trainer/off_policy/tinker/rollout.py
@@ -6,7 +6,6 @@ import subprocess
import time
from pathlib import Path
-
# ---------------------------------------------------------------------------
# Internal helpers
# ---------------------------------------------------------------------------
@@ -54,11 +53,18 @@ def _run_single_rollout(
env = {**os.environ, **(extra_env or {})}
cmd = [
- "cb", "run", "dataset", str(tasks_path),
- "--agent", agent,
- "--model", model,
- "--max-steps", str(max_steps),
- "--with", "libs/python/agent/agent"
+ "cb",
+ "run",
+ "dataset",
+ str(tasks_path),
+ "--agent",
+ agent,
+ "--model",
+ model,
+ "--max-steps",
+ str(max_steps),
+ "--with",
+ "libs/python/agent/agent",
]
print(f"[rollout] Launching: {' '.join(cmd)}")
@@ -115,8 +121,7 @@ def run_rollouts(
poll_interval: int = 10,
extra_env: dict[str, str] | None = None,
) -> list[tuple[str, Path]]:
- """Run cua-bench rollouts and block until all sessions finish.
- """
+ """Run cua-bench rollouts and block until all sessions finish."""
results: list[tuple[str, Path]] = []
for i in range(num_rollouts):
if num_rollouts > 1:
diff --git a/libs/cua-bench/cua_bench/trainer/off_policy/tinker/traces.py b/libs/cua-bench/cua_bench/trainer/off_policy/tinker/traces.py
index 7132adbbb8..64fa8dfcef 100644
--- a/libs/cua-bench/cua_bench/trainer/off_policy/tinker/traces.py
+++ b/libs/cua-bench/cua_bench/trainer/off_policy/tinker/traces.py
@@ -54,9 +54,7 @@ def _extract_action_text(output_items: list[dict]) -> str:
elif kind == "computer_call":
parts.append(json.dumps({"action": item.get("action")}))
elif kind == "tool_use":
- parts.append(
- json.dumps({"tool": item.get("name"), "input": item.get("input")})
- )
+ parts.append(json.dumps({"tool": item.get("name"), "input": item.get("input")}))
# Fallback: if nothing matched, serialise the raw list so we always have
# *something* to tokenise.
return "\n".join(parts) if parts else json.dumps(output_items)
@@ -72,6 +70,7 @@ def _as_pil(img) -> Optional[Image.Image]:
# as a raw buffer rather than a decoded PIL image.
if isinstance(img, dict) and "bytes" in img:
import io
+
return Image.open(io.BytesIO(img["bytes"])).convert("RGB")
return None
@@ -143,7 +142,9 @@ def load_episode(trace_dir: str | Path) -> Optional[Episode]:
if post_screenshot is not None:
prev_screenshot = post_screenshot
- trajectory_id = ds[0]["trajectory_id"] if len(ds) > 0 and ds[0]["trajectory_id"] is not None else ""
+ trajectory_id = (
+ ds[0]["trajectory_id"] if len(ds) > 0 and ds[0]["trajectory_id"] is not None else ""
+ )
assert isinstance(trajectory_id, str), f"trajectory_id is not a string: {trajectory_id}"
return Episode(
diff --git a/libs/python/agent/cua_agent/agent.py b/libs/python/agent/cua_agent/agent.py
index a2ea6e762c..40aa747bb4 100644
--- a/libs/python/agent/cua_agent/agent.py
+++ b/libs/python/agent/cua_agent/agent.py
@@ -639,7 +639,7 @@ class ComputerAgent:
for callback in self.callbacks:
if hasattr(callback, "on_run_continue"):
should_continue = await callback.on_run_continue(kwargs, old_items, new_items)
- if not should_continue:
+ if not should_continue:
return False
return True
@@ -1030,7 +1030,7 @@ class ComputerAgent:
# Add agent response to new_items
new_items += result.get("output")
-
+
# Get output call ids
output_call_ids = get_output_call_ids(result.get("output", []))
@@ -1046,7 +1046,6 @@ class ComputerAgent:
if pi_type == "computer_call_output":
output = pi.get("output", {})
has_image = "image_url" in output if isinstance(output, dict) else False
-
new_items += partial_items
diff --git a/libs/python/agent/cua_agent/cli.py b/libs/python/agent/cua_agent/cli.py
index 9bdc25d5a4..cb0b85c84e 100644
--- a/libs/python/agent/cua_agent/cli.py
+++ b/libs/python/agent/cua_agent/cli.py
@@ -358,8 +358,8 @@ Examples:
# Import here to avoid import errors if dependencies are missing
try:
- from cua_agent import ComputerAgent
from computer import Computer
+ from cua_agent import ComputerAgent
except ImportError as e:
print_colored(f"❌ Import error: {e}", Colors.RED, bold=True)
print_colored("Make sure agent and computer libraries are installed.", Colors.YELLOW)
diff --git a/libs/python/agent/cua_agent/loops/anthropic.py b/libs/python/agent/cua_agent/loops/anthropic.py
index 194a1524e7..4ee015b08b 100644
--- a/libs/python/agent/cua_agent/loops/anthropic.py
+++ b/libs/python/agent/cua_agent/loops/anthropic.py
@@ -1816,7 +1816,7 @@ class AnthropicHostedToolsConfig(AsyncAgentConfig):
# Use liteLLM acompletion
response = await litellm.acompletion(**api_kwargs)
-
+
# print(f"[DEBUG][Anthropic Response] response: {response}")
# Call API end hook
diff --git a/libs/python/agent/cua_agent/loops/opencua.py b/libs/python/agent/cua_agent/loops/opencua.py
index b35d059af2..2f2f572b87 100644
--- a/libs/python/agent/cua_agent/loops/opencua.py
+++ b/libs/python/agent/cua_agent/loops/opencua.py
@@ -348,9 +348,7 @@ class OpenCUAConfig(ComposedGroundedConfig):
# Rescale coordinates if present
coord = args.get("coordinate")
if coord and isinstance(coord, (list, tuple)) and len(coord) >= 2:
- rx, ry = _rescale(
- int(round(float(coord[0]))), int(round(float(coord[1])))
- )
+ rx, ry = _rescale(int(round(float(coord[0]))), int(round(float(coord[1]))))
args = {**args, "coordinate": [rx, ry]}
# Convert Qwen format to Computer Calls format
diff --git a/libs/python/agent/cua_agent/loops/qwen35.py b/libs/python/agent/cua_agent/loops/qwen35.py
index 55b0ff636e..61ad7f42c0 100644
--- a/libs/python/agent/cua_agent/loops/qwen35.py
+++ b/libs/python/agent/cua_agent/loops/qwen35.py
@@ -31,15 +31,15 @@ QWEN3_5_COMPUTER_TOOL: Dict[str, Any] = {
"name": "computer",
"description": (
"* `key`: Performs key down presses on the arguments passed in order, then performs key releases in reverse order.\n"
- "* `type`: Type a string of text on the keyboard.\n"
+ "* `type`: Type a string of text on the keyboard.\n"
"* `mouse_move`: Move the cursor to a specified (x, y) pixel coordinate on the screen.\n"
- "* `left_click`: Click the left mouse button at a specified (x, y) pixel coordinate on the screen. Optional `text` parameter can specify modifier keys (e.g., \"ctrl\", \"shift\", \"ctrl+shift\") that will be held during the click.\n"
+ '* `left_click`: Click the left mouse button at a specified (x, y) pixel coordinate on the screen. Optional `text` parameter can specify modifier keys (e.g., "ctrl", "shift", "ctrl+shift") that will be held during the click.\n'
"* `left_click_drag`: Click and drag the cursor to a specified (x, y) pixel coordinate on the screen.\n"
"* `right_click`: Click the right mouse button at a specified (x, y) pixel coordinate on the screen. Optional `text` parameter can specify modifier keys that will be held during the click.\n"
"* `middle_click`: Click the middle mouse button at a specified (x, y) pixel coordinate on the screen. Optional `text` parameter can specify modifier keys that will be held during the click.\n"
"* `double_click`: Double-click the left mouse button at a specified (x, y) pixel coordinate on the screen. Optional `text` parameter can specify modifier keys that will be held during the click.\n"
"* `triple_click`: Triple-click the left mouse button at a specified (x, y) pixel coordinate on the screen (simulated as double-click since it's the closest action). Optional `text` parameter can specify modifier keys that will be held during the click.\n"
- "* `scroll`: Performs a scroll of the mouse scroll wheel. Optional `text` parameter can specify a modifier key (e.g., \"shift\", \"ctrl\") that will be held during scrolling.\n"
+ '* `scroll`: Performs a scroll of the mouse scroll wheel. Optional `text` parameter can specify a modifier key (e.g., "shift", "ctrl") that will be held during scrolling.\n'
"* `hscroll`: Performs a horizontal scroll (mapped to regular scroll). Optional `text` parameter can specify a modifier key that will be held during scrolling.\n"
"* `wait`: Wait specified seconds for the change to happen.\n"
# "* `terminate`: Terminate the current task and report its completion status.\n"
@@ -160,16 +160,14 @@ def _parse_tool_call_from_text(text: str) -> Optional[Dict[str, Any]]:
params_block = fn_match.group(2)
# Extract all <parameter=key>value</parameter> pairs
params: Dict[str, Any] = {}
- for pm in re.finditer(
- r"<parameter=(\w+)>\s*([\s\S]*?)\s*</parameter>", params_block
- ):
+ for pm in re.finditer(r"<parameter=(\w+)>\s*([\s\S]*?)\s*</parameter>", params_block):
key = pm.group(1)
val = pm.group(2).strip()
# Try to parse as JSON (for arrays/numbers), fall back to string
try:
params[key] = json.loads(val)
except (json.JSONDecodeError, ValueError):
- params[key] = val
+ params[key] = val
# The XML format uses <parameter=type> for the action field name,
# but the Qwen tool schema calls it "action". Remap if we got
# "type" that looks like an action name rather than a literal type.
@@ -297,7 +295,7 @@ class Qwen35Config(AsyncAgentConfig):
messages,
allow_images_in_tool_results=False,
)
-
+
# print(f"The number of items in the converted_msgs: {len(converted_msgs)}")
# Build function schemas from tools array
@@ -322,7 +320,7 @@ class Qwen35Config(AsyncAgentConfig):
# If no tools provided or no computer tool found, use default QWEN3_COMPUTER_TOOL
if not function_schemas:
function_schemas = [QWEN3_5_COMPUTER_TOOL["function"]]
-
+
# print(f"[qwen35] function_schemas: {function_schemas}")
# Prepend Nous-generated system if available
@@ -428,7 +426,7 @@ class Qwen35Config(AsyncAgentConfig):
part["min_pixels"] = MIN_PIXELS
part["max_pixels"] = MAX_PIXELS
last_rw, last_rh = rw, rh
-
+
for i, msg in enumerate(completion_messages):
role = msg.get("role")
content = msg.get("content")
@@ -437,17 +435,17 @@ class Qwen35Config(AsyncAgentConfig):
for item in content:
item_type = item.get("type")
if item_type == "text":
- step_content.append(item.get('text'))
+ step_content.append(item.get("text"))
elif item_type == "image_url":
- step_content.append("Image URL: " + item.get('image_url').get('url')[:100])
+ step_content.append("Image URL: " + item.get("image_url").get("url")[:100])
else:
item = content
step_content = ""
if isinstance(item, dict) and item.get("type") == "image_url":
- step_content = "Image URL: " + item.get('image_url').get('url')[:100]
+ step_content = "Image URL: " + item.get("image_url").get("url")[:100]
else:
step_content = content
-
+
print(f"Step {i}: Role: {role}, Content: {step_content}")
api_kwargs: Dict[str, Any] = {
@@ -497,12 +495,14 @@ class Qwen35Config(AsyncAgentConfig):
if tool_call and isinstance(tool_call, dict):
fn_name = tool_call.get("name") or "computer"
raw_args = tool_call.get("arguments") or {}
-
- output_items.append({
- "type": "message",
- "role": "assistant",
- "content": [{"type": "output_text", "text": content_text}],
- })
+
+ output_items.append(
+ {
+ "type": "message",
+ "role": "assistant",
+ "content": [{"type": "output_text", "text": content_text}],
+ }
+ )
# Unnormalize coordinates to actual screen size using last resized dims
if last_rw is None or last_rh is None:
@@ -529,17 +529,19 @@ class Qwen35Config(AsyncAgentConfig):
"arguments": json.dumps(args),
},
}
- ]
+ ],
}
output_items.extend(convert_completion_messages_to_responses_items([fake_cm]))
-
+
elif tool_calls_array:
-
- output_items.append({
- "type": "message",
- "role": "assistant",
- "content": [{"type": "output_text", "text": content_text}],
- })
+
+ output_items.append(
+ {
+ "type": "message",
+ "role": "assistant",
+ "content": [{"type": "output_text", "text": content_text}],
+ }
+ )
processed_tool_calls = []
for tc in tool_calls_array:
@@ -579,7 +581,7 @@ class Qwen35Config(AsyncAgentConfig):
"tool_calls": processed_tool_calls,
}
output_items.extend(convert_completion_messages_to_responses_items([fake_cm]))
-
+
else:
# No tool calls found in either format, return text response
fake_cm = {"role": "assistant", "content": content_text}
@@ -605,7 +607,8 @@ class Qwen35Config(AsyncAgentConfig):
"type": "function",
"function": {
**QWEN3_5_COMPUTER_TOOL["function"],
- "parameters": {**QWEN3_5_COMPUTER_TOOL["function"]["parameters"],
+ "parameters": {
+ **QWEN3_5_COMPUTER_TOOL["function"]["parameters"],
"type": "object",
"properties": {
"action": {"type": "string", "enum": ["left_click"]},
diff --git a/libs/python/agent/cua_agent/loops/qwen3vl.py b/libs/python/agent/cua_agent/loops/qwen3vl.py
index 507c4a9c32..2e12404e77 100644
--- a/libs/python/agent/cua_agent/loops/qwen3vl.py
+++ b/libs/python/agent/cua_agent/loops/qwen3vl.py
@@ -14,4 +14,5 @@ from .generic_vlm import GenericVlmConfig
@register_agent(models=r"(?i).*qwen.*")
class Qwen3VlConfig(GenericVlmConfig):
"""Qwen3-VL agent loop using litellm with function/tool calling."""
+
pass
diff --git a/libs/python/agent/example.py b/libs/python/agent/example.py
index 7d8f20a7a9..0d466c063d 100644
--- a/libs/python/agent/example.py
+++ b/libs/python/agent/example.py
@@ -5,9 +5,9 @@ Example usage of the agent library with docstring-based tool definitions.
import asyncio
import logging
-from cua_agent import ComputerAgent
from computer import Computer
from computer.helpers import sandboxed
+from cua_agent import ComputerAgent
@sandboxed()
diff --git a/libs/python/computer-server/computer_server/handlers/android.py b/libs/python/computer-server/computer_server/handlers/android.py
index 0a310720e8..e5a8cc8387 100644
--- a/libs/python/computer-server/computer_server/handlers/android.py
+++ b/libs/python/computer-server/computer_server/handlers/android.py
@@ -687,9 +687,7 @@ class AndroidAutomationHandler(BaseAutomationHandler):
success, output = await adb_exec.run("shell", script, decode=True)
return {"success": success, "output": output}
- async def run_command(
- self, command: str, timeout: Optional[float] = None
- ) -> Dict[str, Any]:
+ async def run_command(self, command: str, timeout: Optional[float] = None) -> Dict[str, Any]:
"""Run a shell command inside the Android emulator via adb shell.
Args:
@@ -715,9 +713,7 @@ class AndroidAutomationHandler(BaseAutomationHandler):
if timeout is None:
stdout, stderr = await process.communicate()
else:
- stdout, stderr = await asyncio.wait_for(
- process.communicate(), timeout=timeout
- )
+ stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)
except asyncio.TimeoutError:
process.kill()
return {
diff --git a/libs/python/computer-server/computer_server/handlers/base.py b/libs/python/computer-server/computer_server/handlers/base.py
index f9880e3112..907dcdb12b 100644
--- a/libs/python/computer-server/computer_server/handlers/base.py
+++ b/libs/python/computer-server/computer_server/handlers/base.py
@@ -377,9 +377,7 @@ class BaseAutomationHandler(ABC):
return {"success": False, "error": str(e)}
# Command Execution
- async def run_command(
- self, command: str, timeout: Optional[float] = None
- ) -> Dict[str, Any]:
+ async def run_command(self, command: str, timeout: Optional[float] = None) -> Dict[str, Any]:
"""Run a shell command locally and return its output.
When IS_CUA_ANDROID env var is set, routes the command through
@@ -414,9 +412,7 @@ class BaseAutomationHandler(ABC):
if timeout is None:
stdout, stderr = await process.communicate()
else:
- stdout, stderr = await asyncio.wait_for(
- process.communicate(), timeout=timeout
- )
+ stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)
except asyncio.TimeoutError:
process.kill()
return {
diff --git a/libs/python/computer-server/computer_server/handlers/windows.py b/libs/python/computer-server/computer_server/handlers/windows.py
index e8e77e4603..c218cc813d 100644
--- a/libs/python/computer-server/computer_server/handlers/windows.py
+++ b/libs/python/computer-server/computer_server/handlers/windows.py
@@ -709,9 +709,7 @@ class WindowsAutomationHandler(BaseAutomationHandler):
# Clipboard inherited from BaseAutomationHandler
# Command Execution (Windows override for multi-encoding support)
- async def run_command(
- self, command: str, timeout: Optional[float] = None
- ) -> Dict[str, Any]:
+ async def run_command(self, command: str, timeout: Optional[float] = None) -> Dict[str, Any]:
"""Execute a shell command asynchronously.
Args:
@@ -755,9 +753,7 @@ class WindowsAutomationHandler(BaseAutomationHandler):
if timeout is None:
stdout, stderr = await process.communicate()
else:
- stdout, stderr = await asyncio.wait_for(
- process.communicate(), timeout=timeout
- )
+ stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)
except asyncio.TimeoutError:
process.kill()
return {
diff --git a/libs/python/computer-server/computer_server/main.py b/libs/python/computer-server/computer_server/main.py
index d71d810730..3715c8b10f 100644
--- a/libs/python/computer-server/computer_server/main.py
+++ b/libs/python/computer-server/computer_server/main.py
@@ -69,6 +69,7 @@ def _unavailable_status_code() -> Optional[int]:
except ValueError:
return DEFAULT_UNAVAILABLE_STATUS_CODE
+
try:
from cua_agent import ComputerAgent
@@ -105,6 +106,7 @@ app = FastAPI(
redirect_slashes=False,
)
+
class UnavailableWithoutContainerMiddleware:
"""ASGI middleware that rejects all requests when CONTAINER_NAME is required but unset.
@@ -328,9 +330,7 @@ if hasattr(automation_handler, "multitouch_gesture"):
class AuthenticationManager:
def __init__(self):
self.container_name = os.environ.get("CONTAINER_NAME")
- self.api_base_url = os.environ.get(
- "CUA_BASE_URL_AUTH", "https://www.cua.ai"
- ).rstrip("/")
+ self.api_base_url = os.environ.get("CUA_BASE_URL_AUTH", "https://www.cua.ai").rstrip("/")
async def auth(self, container_name: str, api_key: str) -> bool:
"""Authenticate container name and API key against the TryCUA API.
diff --git a/libs/python/computer-server/tests/test_auth_availability.py b/libs/python/computer-server/tests/test_auth_availability.py
index e9c81326dc..5b93d90e4b 100644
--- a/libs/python/computer-server/tests/test_auth_availability.py
+++ b/libs/python/computer-server/tests/test_auth_availability.py
@@ -16,10 +16,9 @@ These tests verify two things:
from __future__ import annotations
import pytest
+from fastapi.testclient import TestClient
try:
- from fastapi.testclient import TestClient
-
from computer_server.main import _unavailable_status_code, app
except Exception as import_error: # pragma: no cover - environment-dependent
pytest.skip(
diff --git a/libs/python/cua-cli/cua_cli/api/client.py b/libs/python/cua-cli/cua_cli/api/client.py
index b1faf4d014..772e357255 100644
--- a/libs/python/cua-cli/cua_cli/api/client.py
+++ b/libs/python/cua-cli/cua_cli/api/client.py
@@ -7,8 +7,8 @@ from typing import Any, Optional
from urllib.parse import quote
import aiohttp
-from cua_core.http import cua_version_headers
from cua_cli.auth.store import require_api_key
+from cua_core.http import cua_version_headers
DEFAULT_API_BASE = "https://api.cua.ai"
diff --git a/libs/python/cua-cli/cua_cli/commands/auth.py b/libs/python/cua-cli/cua_cli/commands/auth.py
index b234f3fc89..4589ca7892 100644
--- a/libs/python/cua-cli/cua_cli/commands/auth.py
+++ b/libs/python/cua-cli/cua_cli/commands/auth.py
@@ -5,7 +5,6 @@ import os
from pathlib import Path
import aiohttp
-from cua_core.http import cua_version_headers
from cua_cli.auth.browser import authenticate_via_browser
from cua_cli.auth.store import (
ACTIVE_WORKSPACE_KEY,
@@ -22,6 +21,7 @@ from cua_cli.auth.store import (
)
from cua_cli.utils.async_utils import run_async
from cua_cli.utils.output import print_error, print_info, print_success
+from cua_core.http import cua_version_headers
DEFAULT_API_BASE = "https://api.cua.ai"
diff --git a/libs/python/cua-cli/cua_cli/commands/workspace.py b/libs/python/cua-cli/cua_cli/commands/workspace.py
index 73b76b1194..82d66b4840 100644
--- a/libs/python/cua-cli/cua_cli/commands/workspace.py
+++ b/libs/python/cua-cli/cua_cli/commands/workspace.py
@@ -5,7 +5,6 @@ import asyncio
import os
import aiohttp
-from cua_core.http import cua_version_headers
from cua_cli.auth.browser import authenticate_via_browser
from cua_cli.auth.store import (
_get_store,
@@ -17,6 +16,7 @@ from cua_cli.auth.store import (
)
from cua_cli.utils.async_utils import run_async
from cua_cli.utils.output import print_error, print_info, print_success
+from cua_core.http import cua_version_headers
DEFAULT_API_BASE = "https://api.cua.ai"
diff --git a/libs/python/cua-sandbox-apps/cua_sandbox_apps/apps/emacs/linux/launch.sh b/libs/python/cua-sandbox-apps/cua_sandbox_apps/apps/emacs/linux/launch.sh
index 737deaab25..d9c86752e5 100644
--- a/libs/python/cua-sandbox-apps/cua_sandbox_apps/apps/emacs/linux/launch.sh
+++ b/libs/python/cua-sandbox-apps/cua_sandbox_apps/apps/emacs/linux/launch.sh
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
-import subprocess
import os
+import subprocess
import time
os.environ['DISPLAY'] = ':1'
diff --git a/libs/python/cua-sandbox-apps/cua_sandbox_apps/cli.py b/libs/python/cua-sandbox-apps/cua_sandbox_apps/cli.py
index 2800afa1bf..aa0573903e 100644
--- a/libs/python/cua-sandbox-apps/cua_sandbox_apps/cli.py
+++ b/libs/python/cua-sandbox-apps/cua_sandbox_apps/cli.py
@@ -66,15 +66,22 @@ def discover_onet(output: str | None) -> None:
@click.option("--model", type=str, default="haiku", help="Claude model (haiku, sonnet, opus)")
@click.option("--max-parallel", type=int, default=22, help="Max parallel agents")
@click.option("--start-angle", type=int, default=0, help="Search angle index to start from (0-7)")
-def discover_software(input_path: str | None, output: str | None, target: int, model: str, max_parallel: int, start_angle: int) -> None:
+def discover_software(
+ input_path: str | None,
+ output: str | None,
+ target: int,
+ model: str,
+ max_parallel: int,
+ start_angle: int,
+) -> None:
"""Discover software per occupation group using Claude agents with WebSearch.
All 22 occupation groups run fully in parallel. Each agent gets WebSearch
and a submit_apps tool to ingest entries. Outer loop re-prompts until target.
Fully resumable — deduplicates on ingress.
"""
- from .discovery.onet import read_jsonl
from .discovery.discover import run_discovery
+ from .discovery.onet import read_jsonl
inp = Path(input_path) if input_path else DEFAULT_DATA_DIR / "occupations.jsonl"
out = Path(output) if output else DEFAULT_DATA_DIR / "raw_software.jsonl"
@@ -84,8 +91,19 @@ def discover_software(input_path: str | None, output: str | None, target: int, m
raise SystemExit(1)
occupations = read_jsonl(inp)
- click.echo(f"Discovery: {len(occupations)} groups, target={target}, model={model}, max_parallel={max_parallel}, start_angle={start_angle}")
- asyncio.run(run_discovery(occupations, out, target=target, model=model, max_parallel=max_parallel, start_angle=start_angle))
+ click.echo(
+ f"Discovery: {len(occupations)} groups, target={target}, model={model}, max_parallel={max_parallel}, start_angle={start_angle}"
+ )
+ asyncio.run(
+ run_discovery(
+ occupations,
+ out,
+ target=target,
+ model=model,
+ max_parallel=max_parallel,
+ start_angle=start_angle,
+ )
+ )
click.echo(f"Results in {out}")
@@ -94,7 +112,9 @@ def discover_software(input_path: str | None, output: str | None, target: int, m
@click.option("--output", type=click.Path(), default=None)
@click.option("--concurrency", type=int, default=5)
@click.option("--model", type=str, default="haiku", help="Claude model (haiku, sonnet, opus)")
-def discover_enrich(input_path: str | None, output: str | None, concurrency: int, model: str) -> None:
+def discover_enrich(
+ input_path: str | None, output: str | None, concurrency: int, model: str
+) -> None:
"""Enrich raw software entries with detailed metadata."""
from .discovery.enrich import run_enrichment
@@ -115,8 +135,15 @@ def discover_enrich(input_path: str | None, output: str | None, concurrency: int
@click.option("--output", type=click.Path(), default=None)
@click.option("--n", type=int, default=3, help="Number of searches per app")
@click.option("--concurrency", type=int, default=50, help="Concurrent searches")
[email protected]("--searxng-url", default="http://localhost:8080", show_default=True, help="SearXNG base URL (set empty string to use DuckDuckGo fallback)")
-def discover_search(input_path: str | None, output: str | None, n: int, concurrency: int, searxng_url: str) -> None:
+ "--searxng-url",
+ default="http://localhost:8080",
+ show_default=True,
+ help="SearXNG base URL (set empty string to use DuckDuckGo fallback)",
+)
+def discover_search(
+ input_path: str | None, output: str | None, n: int, concurrency: int, searxng_url: str
+) -> None:
"""Phase 1 of batch enrichment: gather N web searches per app via SearXNG."""
from .discovery.batch_enrich import run_search
@@ -130,20 +157,37 @@ def discover_search(input_path: str | None, output: str | None, n: int, concurre
enriched = DEFAULT_DATA_DIR / "enriched_software.jsonl"
brave_key = os.environ.get("BRAVE_API_KEY")
provider = (searxng_url or "duckduckgo") + (" + brave api" if brave_key else "")
- click.echo(f"Gathering {n} searches per app from {inp} (concurrency={concurrency}, provider={provider})")
- asyncio.run(run_search(inp, out, n=n, concurrency=concurrency, enriched_path=enriched,
- searxng_url=searxng_url or None, brave_api_key=brave_key))
+ click.echo(
+ f"Gathering {n} searches per app from {inp} (concurrency={concurrency}, provider={provider})"
+ )
+ asyncio.run(
+ run_search(
+ inp,
+ out,
+ n=n,
+ concurrency=concurrency,
+ enriched_path=enriched,
+ searxng_url=searxng_url or None,
+ brave_api_key=brave_key,
+ )
+ )
click.echo(f"Search results written to {out}")
@discover.command("batch-submit")
[email protected]("--input", "input_path", type=click.Path(exists=True), default=None, help="search_results.jsonl")
+ "--input", "input_path", type=click.Path(exists=True), default=None, help="search_results.jsonl"
+)
@click.option("--bucket", required=True, help="S3 bucket for input/output")
@click.option("--prefix", default="cua-sandbox-apps/enrich", help="S3 key prefix")
[email protected]("--model", default="us.anthropic.claude-haiku-4-5-20251001-v1:0", help="Bedrock model ID")
+ "--model", default="us.anthropic.claude-haiku-4-5-20251001-v1:0", help="Bedrock model ID"
+)
@click.option("--region", default="us-east-1")
@click.option("--role-arn", default=None, help="IAM role ARN for Bedrock (if needed)")
-def discover_batch_submit(input_path: str | None, bucket: str, prefix: str, model: str, region: str, role_arn: str | None) -> None:
+def discover_batch_submit(
+ input_path: str | None, bucket: str, prefix: str, model: str, region: str, role_arn: str | None
+) -> None:
"""Phase 2: upload search results to S3 and create Bedrock batch inference job."""
from .discovery.batch_enrich import submit_batch
@@ -154,7 +198,15 @@ def discover_batch_submit(input_path: str | None, bucket: str, prefix: str, mode
raise SystemExit(1)
enriched = DEFAULT_DATA_DIR / "enriched_software.jsonl"
- job_arn = submit_batch(inp, s3_bucket=bucket, s3_prefix=prefix, model_id=model, region=region, role_arn=role_arn, enriched_path=enriched)
+ job_arn = submit_batch(
+ inp,
+ s3_bucket=bucket,
+ s3_prefix=prefix,
+ model_id=model,
+ region=region,
+ role_arn=role_arn,
+ enriched_path=enriched,
+ )
click.echo(f"Job ARN: {job_arn}")
click.echo(f"Run 'discover batch-fetch --job-arn {job_arn}' when complete.")
@@ -163,16 +215,22 @@ def discover_batch_submit(input_path: str | None, bucket: str, prefix: str, mode
@click.option("--job-arn", required=True, help="Bedrock batch job ARN")
@click.option("--output", type=click.Path(), default=None)
@click.option("--region", default="us-east-1")
[email protected]("--no-poll", is_flag=True, help="Don't wait — fetch immediately (job must already be complete)")
+ "--no-poll", is_flag=True, help="Don't wait — fetch immediately (job must already be complete)"
+)
@click.option("--poll-interval", type=int, default=60, help="Seconds between status checks")
-def discover_batch_fetch(job_arn: str, output: str | None, region: str, no_poll: bool, poll_interval: int) -> None:
+def discover_batch_fetch(
+ job_arn: str, output: str | None, region: str, no_poll: bool, poll_interval: int
+) -> None:
"""Phase 3: download Bedrock batch results from S3, write enriched JSONL."""
from .discovery.batch_enrich import fetch_results
out = Path(output) if output else DEFAULT_DATA_DIR / "enriched_software.jsonl"
click.echo(f"Fetching results for job {job_arn} → {out}")
- count = fetch_results(job_arn, out, region=region, poll=not no_poll, poll_interval=poll_interval)
+ count = fetch_results(
+ job_arn, out, region=region, poll=not no_poll, poll_interval=poll_interval
+ )
click.echo(f"Done: {count} entries written to {out}")
@@ -201,8 +259,11 @@ def discover_dedup(input_path: str | None, output: str | None, threshold: int) -
@click.option("--os", "os_filter", multiple=True, help="Only these OS types (repeatable)")
@click.option("--concurrency", type=int, default=4, help="Max concurrent agents")
@click.option("--limit", type=int, default=None, help="Max app/os pairs to process")
[email protected]("--strict-install-verify/--no-strict-install-verify", default=True,
- help="Pre-submit: bash -n parse + re-run install.sh end-to-end in a fresh sandbox")
+ "--strict-install-verify/--no-strict-install-verify",
+ default=True,
+ help="Pre-submit: bash -n parse + re-run install.sh end-to-end in a fresh sandbox",
+)
def generate(
catalog: str | None,
apps_dir: str | None,
@@ -225,22 +286,44 @@ def generate(
raise SystemExit(1)
os_list = list(os_filter) if os_filter else None
- click.echo(f"Generating installers: catalog={cat}, apps_dir={apps}, os={os_list or 'auto-detect'}, concurrency={concurrency}")
- asyncio.run(run_orchestrator(
- cat, apps, os_filter=os_list, concurrency=concurrency, limit=limit,
- strict_install_verify=strict_install_verify,
- ))
+ click.echo(
+ f"Generating installers: catalog={cat}, apps_dir={apps}, os={os_list or 'auto-detect'}, concurrency={concurrency}"
+ )
+ asyncio.run(
+ run_orchestrator(
+ cat,
+ apps,
+ os_filter=os_list,
+ concurrency=concurrency,
+ limit=limit,
+ strict_install_verify=strict_install_verify,
+ )
+ )
@cli.command("create-tasks")
[email protected]("--apps-dir", type=click.Path(), default=None, help="Apps directory (default: package apps/)")
+ "--apps-dir", type=click.Path(), default=None, help="Apps directory (default: package apps/)"
+)
@click.option("--concurrency", type=int, default=4, help="Max concurrent task-creator agents")
@click.option("--limit", type=int, default=None, help="Max (app, os) pairs to process")
[email protected]("--seeds", "target_seed_count", type=int, default=100, help="Target high-quality seed tasks per app")
+ "--seeds",
+ "target_seed_count",
+ type=int,
+ default=100,
+ help="Target high-quality seed tasks per app",
+)
@click.option("--model", type=str, default="sonnet", help="Claude model for the task creator")
@click.option("--app", "only_apps", multiple=True, help="Only run on these app ids (repeatable)")
-def create_tasks(apps_dir: str | None, concurrency: int, limit: int | None,
- target_seed_count: int, model: str, only_apps: tuple[str, ...]) -> None:
+def create_tasks(
+ apps_dir: str | None,
+ concurrency: int,
+ limit: int | None,
+ target_seed_count: int,
+ model: str,
+ only_apps: tuple[str, ...],
+) -> None:
"""Phase 3: Generate open-ended deterministic tasks per app (resumable).
Runs after `generate`. For each (app, os) pair with a working install,
@@ -249,16 +332,24 @@ def create_tasks(apps_dir: str | None, concurrency: int, limit: int | None,
and writes a small set of seed tasks audited by an independent verifier.
"""
from .pipeline.tasks.orchestrator import run_task_orchestrator
+
apps = Path(apps_dir) if apps_dir else Path(__file__).parent / "apps"
if not apps.exists():
click.echo(f"Apps dir not found: {apps}. Run 'generate' first.", err=True)
raise SystemExit(1)
- click.echo(f"Creating tasks: apps_dir={apps}, concurrency={concurrency}, seeds={target_seed_count}, model={model}")
- asyncio.run(run_task_orchestrator(
- apps, concurrency=concurrency, limit=limit,
- target_seed_count=target_seed_count, model=model,
- only_apps=list(only_apps) if only_apps else None,
- ))
+ click.echo(
+ f"Creating tasks: apps_dir={apps}, concurrency={concurrency}, seeds={target_seed_count}, model={model}"
+ )
+ asyncio.run(
+ run_task_orchestrator(
+ apps,
+ concurrency=concurrency,
+ limit=limit,
+ target_seed_count=target_seed_count,
+ model=model,
+ only_apps=list(only_apps) if only_apps else None,
+ )
+ )
@cli.command("extract-tools")
@@ -271,12 +362,15 @@ def create_tasks(apps_dir: str | None, concurrency: int, limit: int | None,
def extract_tools(apps_dir, tasks_dir, only_apps, concurrency, tools_per_app, model):
"""Stage 1: Extract MCP tool primitives per app."""
from .pipeline.tasks.mcp.tool_extractor import extract_tools_for_app
+
apps = Path(apps_dir) if apps_dir else Path(__file__).parent / "apps"
tasks = Path(tasks_dir) if tasks_dir else Path(__file__).parent / "tasks"
async def _run():
import asyncio
+
sem = asyncio.Semaphore(concurrency)
+
async def _one(app_id):
async with sem:
app_dir = apps / app_id
@@ -286,8 +380,9 @@ def extract_tools(apps_dir, tasks_dir, only_apps, concurrency, tools_per_app, mo
app_dir.mkdir(parents=True, exist_ok=True)
click.echo(f"No install dir for {app_id} — running research-only")
await extract_tools_for_app(
- app_dir, "linux", target_tool_count=tools_per_app,
- model=model, tasks_root=tasks)
+ app_dir, "linux", target_tool_count=tools_per_app, model=model, tasks_root=tasks
+ )
+
await asyncio.gather(*[_one(a) for a in only_apps])
asyncio.run(_run())
@@ -296,23 +391,33 @@ def extract_tools(apps_dir, tasks_dir, only_apps, concurrency, tools_per_app, mo
@cli.command("verify-replica")
@click.argument("app_id")
@click.option("--tasks-dir", type=click.Path(), default=None)
[email protected]("--replica-source", type=click.Path(), default=None, help="Local path to replica source code")
+ "--replica-source", type=click.Path(), default=None, help="Local path to replica source code"
+)
@click.option("--os", "os_type", default="linux")
@click.option("--model", type=str, default="sonnet")
-def verify_replica(app_id: str, tasks_dir: str | None, replica_source: str | None,
- os_type: str, model: str) -> None:
+def verify_replica(
+ app_id: str, tasks_dir: str | None, replica_source: str | None, os_type: str, model: str
+) -> None:
"""Verify a replica environment: boot sandbox, install, screenshot, check /gym.
The agent can debug failures and edit source code — patches are saved for review.
Reads config from tasks/{app_id}/{os}/replica/app.json.
"""
from .pipeline.replica.creator import create_replica_installer
+
tasks = Path(tasks_dir) if tasks_dir else Path(__file__).parent / "tasks"
source = Path(replica_source) if replica_source else None
click.echo(f"Verifying replica: {app_id}/{os_type}, tasks_dir={tasks}")
- result = asyncio.run(create_replica_installer(
- app_id, os_type, tasks_root=tasks, replica_source_dir=source, model=model,
- ))
+ result = asyncio.run(
+ create_replica_installer(
+ app_id,
+ os_type,
+ tasks_root=tasks,
+ replica_source_dir=source,
+ model=model,
+ )
+ )
if result and result.get("verification_passed"):
click.echo(f"PASSED: {app_id} replica verified")
if result.get("patch_file"):
@@ -327,12 +432,15 @@ def verify_replica(app_id: str, tasks_dir: str | None, replica_source: str | Non
@cli.command("compose-workflows")
@click.option("--tasks-dir", type=click.Path(), default=None)
[email protected]("--app", "app_ids", multiple=True, required=True, help="App ids whose tools to compose")
+ "--app", "app_ids", multiple=True, required=True, help="App ids whose tools to compose"
+)
@click.option("--target", type=int, default=50)
@click.option("--model", type=str, default="sonnet")
def compose_workflows(tasks_dir, app_ids, target, model):
"""Stage 2: Compose multi-app workflows from extracted MCP tools."""
from .pipeline.tasks.mcp.workflow_composer import compose_workflows as _compose
+
tasks = Path(tasks_dir) if tasks_dir else Path(__file__).parent / "tasks"
asyncio.run(_compose(list(app_ids), tasks, target_count=target, model=model))
@@ -343,12 +451,15 @@ def compose_workflows(tasks_dir, app_ids, target, model):
@click.option("--os", "os_type", default="linux")
@click.option("--target", type=int, default=75, help="Target amplified task count")
@click.option("--model", type=str, default="us.anthropic.claude-haiku-4-5-20251001-v1:0")
-def amplify_tasks_cmd(app_id: str, tasks_dir: str | None, os_type: str, target: int, model: str) -> None:
+def amplify_tasks_cmd(
+ app_id: str, tasks_dir: str | None, os_type: str, target: int, model: str
+) -> None:
"""Amplify seed tasks using a cheap non-agentic LLM (Gym-Anything §4).
Reads seeds from tasks/{app}/{os}/tasks.jsonl, outputs to tasks_amplified.jsonl.
"""
from .pipeline.tasks.amplifier import amplify_tasks
+
tasks = Path(tasks_dir) if tasks_dir else Path(__file__).parent / "tasks"
result = amplify_tasks(app_id, os_type, tasks_root=tasks, target_count=target, model_id=model)
click.echo(f"Amplified {len(result)} tasks for {app_id}")
@@ -360,11 +471,16 @@ def amplify_tasks_cmd(app_id: str, tasks_dir: str | None, os_type: str, target:
@click.option("--os", "os_type", default="linux")
@click.option("--target", type=int, default=75)
@click.option("--model", type=str, default="sonnet")
-def amplify_tasks_agent_cmd(app_id: str, tasks_dir: str | None, os_type: str, target: int, model: str) -> None:
+def amplify_tasks_agent_cmd(
+ app_id: str, tasks_dir: str | None, os_type: str, target: int, model: str
+) -> None:
"""Agent-driven task amplification with sandbox validation (no reviser needed)."""
from .pipeline.tasks.amplifier_agent import amplify_tasks_agent
+
tasks = Path(tasks_dir) if tasks_dir else Path(__file__).parent / "tasks"
- result = asyncio.run(amplify_tasks_agent(app_id, os_type, tasks_root=tasks, target_count=target, model=model))
+ result = asyncio.run(
+ amplify_tasks_agent(app_id, os_type, tasks_root=tasks, target_count=target, model=model)
+ )
click.echo(f"Amplified {len(result)} validated tasks for {app_id}")
@@ -375,6 +491,7 @@ def amplify_tasks_agent_cmd(app_id: str, tasks_dir: str | None, os_type: str, ta
def amplify_workflows_cmd(tasks_dir: str | None, target: int, model: str) -> None:
"""Amplify seed workflows using a cheap non-agentic LLM (Gym-Anything §4)."""
from .pipeline.tasks.amplifier import amplify_workflows
+
tasks = Path(tasks_dir) if tasks_dir else Path(__file__).parent / "tasks"
result = amplify_workflows(tasks_root=tasks, target_count=target, model_id=model)
click.echo(f"Amplified {len(result)} workflows")
@@ -386,11 +503,16 @@ def amplify_workflows_cmd(tasks_dir: str | None, target: int, model: str) -> Non
@click.option("--os", "os_type", default="linux")
@click.option("--type", "file_type", type=click.Choice(["seed", "amplified"]), default="seed")
@click.option("--max-retries", type=int, default=3)
-def revise_tasks_cmd(app_id: str, tasks_dir: str | None, os_type: str, file_type: str, max_retries: int) -> None:
+def revise_tasks_cmd(
+ app_id: str, tasks_dir: str | None, os_type: str, file_type: str, max_retries: int
+) -> None:
"""Revise tasks to fix quality gaps (missing fields, read-only, bad scripts)."""
from .pipeline.tasks.reviser import revise_tasks
+
tasks = Path(tasks_dir) if tasks_dir else Path(__file__).parent / "tasks"
- result = revise_tasks(app_id, os_type, tasks_root=tasks, file_type=file_type, max_retries=max_retries)
+ result = revise_tasks(
+ app_id, os_type, tasks_root=tasks, file_type=file_type, max_retries=max_retries
+ )
click.echo(f"Revised: {result['revised']}, OK: {result['skipped']}, Failed: {result['failed']}")
@@ -400,11 +522,16 @@ def revise_tasks_cmd(app_id: str, tasks_dir: str | None, os_type: str, file_type
@click.option("--os", "os_type", default="linux")
@click.option("--type", "file_type", type=click.Choice(["seed", "amplified"]), default="seed")
@click.option("--model", type=str, default="sonnet")
-def revise_tasks_agent_cmd(app_id: str, tasks_dir: str | None, os_type: str, file_type: str, model: str) -> None:
+def revise_tasks_agent_cmd(
+ app_id: str, tasks_dir: str | None, os_type: str, file_type: str, model: str
+) -> None:
"""Agent-driven task revision: boots sandbox, validates start+end state, fixes issues, produces patches."""
from .pipeline.tasks.reviser_agent import revise_tasks_agent
+
tasks = Path(tasks_dir) if tasks_dir else Path(__file__).parent / "tasks"
- result = asyncio.run(revise_tasks_agent(app_id, os_type, tasks_root=tasks, file_type=file_type, model=model))
+ result = asyncio.run(
+ revise_tasks_agent(app_id, os_type, tasks_root=tasks, file_type=file_type, model=model)
+ )
if "error" in result:
click.echo(f"Error: {result['error']}", err=True)
raise SystemExit(1)
@@ -418,13 +545,16 @@ def revise_tasks_agent_cmd(app_id: str, tasks_dir: str | None, os_type: str, fil
def revise_workflows_agent_cmd(tasks_dir: str | None, file_type: str, model: str) -> None:
"""Agent-driven workflow revision. Safe to run N instances in parallel — uses file locks."""
from .pipeline.tasks.reviser_agent import revise_workflows_agent
+
tasks = Path(tasks_dir) if tasks_dir else Path(__file__).parent / "tasks"
result = asyncio.run(revise_workflows_agent(tasks_root=tasks, file_type=file_type, model=model))
if "error" in result:
click.echo(f"Error: {result['error']}", err=True)
raise SystemExit(1)
- click.echo(f"This agent: {result['total']} processed, {result['passed']} passed. "
- f"Global: {result.get('global_done', '?')}/{result.get('global_total', '?')} done.")
+ click.echo(
+ f"This agent: {result['total']} processed, {result['passed']} passed. "
+ f"Global: {result.get('global_done', '?')}/{result.get('global_total', '?')} done."
+ )
@cli.command("revise-workflows")
@@ -434,6 +564,7 @@ def revise_workflows_agent_cmd(tasks_dir: str | None, file_type: str, model: str
def revise_workflows_cmd(tasks_dir: str | None, file_type: str, max_retries: int) -> None:
"""Revise workflows to fix quality gaps (descriptive oracles, missing fields)."""
from .pipeline.tasks.reviser import revise_workflows
+
tasks = Path(tasks_dir) if tasks_dir else Path(__file__).parent / "tasks"
result = revise_workflows(tasks_root=tasks, file_type=file_type, max_retries=max_retries)
click.echo(f"Revised: {result['revised']}, OK: {result['skipped']}, Failed: {result['failed']}")
@@ -447,12 +578,17 @@ def revise_workflows_cmd(tasks_dir: str | None, file_type: str, max_retries: int
def validate_tasks_cmd(app_id: str, tasks_dir: str | None, os_type: str, file_type: str) -> None:
"""E2E validate tasks: boot sandbox, run setup, execute golden path, verify extract."""
from .pipeline.tasks.validator import validate_tasks_batch
+
tasks = Path(tasks_dir) if tasks_dir else Path(__file__).parent / "tasks"
- result = asyncio.run(validate_tasks_batch(app_id, os_type, tasks_root=tasks, file_type=file_type))
+ result = asyncio.run(
+ validate_tasks_batch(app_id, os_type, tasks_root=tasks, file_type=file_type)
+ )
if "error" in result:
click.echo(f"Error: {result['error']}", err=True)
raise SystemExit(1)
- click.echo(f"Total: {result['total']}, Start OK: {result['start_ok']}, End OK: {result['end_ok']}, Failed: {result['failed']}")
+ click.echo(
+ f"Total: {result['total']}, Start OK: {result['start_ok']}, End OK: {result['end_ok']}, Failed: {result['failed']}"
+ )
for r in result.get("results", []):
if r.get("issues"):
click.echo(f" {r['task_id']}: {r['issues']}")
@@ -465,10 +601,12 @@ def validate_tasks_cmd(app_id: str, tasks_dir: str | None, os_type: str, file_ty
@click.option("--apps-dir", type=click.Path(), default=None)
@click.option("--tasks-dir", type=click.Path(), default=None)
@click.option("--port", type=int, default=8787)
-def review_task(app_id: str, task_id: str, os_type: str, apps_dir: str | None,
- tasks_dir: str | None, port: int) -> None:
+def review_task(
+ app_id: str, task_id: str, os_type: str, apps_dir: str | None, tasks_dir: str | None, port: int
+) -> None:
"""Boot a task in a sandbox with VNC for human review."""
from .pipeline.tasks.review.server import review_task as _review
+
apps = Path(apps_dir) if apps_dir else Path(__file__).parent / "apps"
tasks = Path(tasks_dir) if tasks_dir else Path(__file__).parent / "tasks"
asyncio.run(_review(app_id, task_id, apps, tasks, target_os=os_type, port=port))
diff --git a/libs/python/cua-sandbox-apps/cua_sandbox_apps/discovery/batch_enrich.py b/libs/python/cua-sandbox-apps/cua_sandbox_apps/discovery/batch_enrich.py
index 2a3da3e699..499b480c48 100644
--- a/libs/python/cua-sandbox-apps/cua_sandbox_apps/discovery/batch_enrich.py
+++ b/libs/python/cua-sandbox-apps/cua_sandbox_apps/discovery/batch_enrich.py
@@ -98,7 +98,7 @@ def _search_queries(name: str, website: str, n: int) -> list[str]:
f"{q} pricing open source github",
f"{q} install linux windows macos apt brew choco winget",
f"{q} {website} features review",
- f'site:github.com {q}',
+ f"site:github.com {q}",
]
return base[:n]
@@ -107,6 +107,7 @@ def _search_queries(name: str, website: str, n: int) -> list[str]:
# Phase 1: Search
# ---------------------------------------------------------------------------
+
async def _searxng_search(
query: str,
searxng_url: str,
@@ -121,7 +122,14 @@ async def _searxng_search(
return []
data = await resp.json(content_type=None)
results = data.get("results", [])[:max_results]
- return [{"title": r.get("title", ""), "body": r.get("content", ""), "href": r.get("url", "")} for r in results]
+ return [
+ {
+ "title": r.get("title", ""),
+ "body": r.get("content", ""),
+ "href": r.get("url", ""),
+ }
+ for r in results
+ ]
except Exception as e:
logger.debug("SearXNG search failed for %r: %s", query, e)
return []
@@ -129,6 +137,7 @@ async def _searxng_search(
class _TokenBucket:
"""Simple async token bucket — refills at `rate` tokens/sec."""
+
def __init__(self, rate: float):
self._rate = rate
self._tokens = rate
@@ -158,10 +167,15 @@ async def _brave_search(
if bucket:
await bucket.acquire()
try:
- headers = {"Accept": "application/json", "Accept-Encoding": "gzip", "X-Subscription-Token": api_key}
+ headers = {
+ "Accept": "application/json",
+ "Accept-Encoding": "gzip",
+ "X-Subscription-Token": api_key,
+ }
params = {"q": query, "count": max_results}
- async with session.get("https://api.search.brave.com/res/v1/web/search",
- headers=headers, params=params) as resp:
+ async with session.get(
+ "https://api.search.brave.com/res/v1/web/search", headers=headers, params=params
+ ) as resp:
if resp.status == 429:
logger.warning("Brave API rate limit hit for %r", query)
return []
@@ -170,7 +184,14 @@ async def _brave_search(
return []
data = await resp.json(content_type=None)
results = data.get("web", {}).get("results", [])[:max_results]
- return [{"title": r.get("title", ""), "body": r.get("description", ""), "href": r.get("url", "")} for r in results]
+ return [
+ {
+ "title": r.get("title", ""),
+ "body": r.get("description", ""),
+ "href": r.get("url", ""),
+ }
+ for r in results
+ ]
except Exception as e:
logger.debug("Brave API search failed for %r: %s", query, e)
return []
@@ -197,7 +218,9 @@ async def _search_one(
# Sequential queries per app — keeps total req/s = concurrency (not concurrency*n)
results_list = []
for q in queries:
- results_list.append(await _brave_search(q, brave_api_key, session, bucket=brave_bucket))
+ results_list.append(
+ await _brave_search(q, brave_api_key, session, bucket=brave_bucket)
+ )
for q, results in zip(queries, results_list):
search_results[q] = results
elif searxng_url and session is not None:
@@ -208,6 +231,7 @@ async def _search_one(
else:
try:
from duckduckgo_search import AsyncDDGS
+
async with AsyncDDGS() as ddgs:
for q in queries:
try:
@@ -258,8 +282,13 @@ async def run_search(
done |= _already_enriched(enriched_path)
remaining = [e for e in raw_entries if e.get("name", "").lower().strip() not in done]
- logger.info("Searching %d entries (%d already done/enriched, n=%d, concurrency=%d)",
- len(remaining), len(done), n, concurrency)
+ logger.info(
+ "Searching %d entries (%d already done/enriched, n=%d, concurrency=%d)",
+ len(remaining),
+ len(done),
+ n,
+ concurrency,
+ )
sem = asyncio.Semaphore(concurrency)
output_path.parent.mkdir(parents=True, exist_ok=True)
@@ -274,24 +303,37 @@ async def run_search(
if brave_api_key or searxng_url:
import aiohttp
- connector = aiohttp.TCPConnector(limit=concurrency * 3) # N queries fired in parallel per app
+
+ connector = aiohttp.TCPConnector(
+ limit=concurrency * 3
+ ) # N queries fired in parallel per app
headers = {"X-Forwarded-For": "127.0.0.1"}
brave_bucket = _TokenBucket(45) if brave_api_key else None # 45 req/s < 50/s limit
async with aiohttp.ClientSession(connector=connector, headers=headers) as session:
+
async def _run_one(entry: dict) -> None:
- result = await _search_one(entry, n, sem, searxng_url=searxng_url,
- brave_api_key=brave_api_key,
- brave_bucket=brave_bucket, session=session)
+ result = await _search_one(
+ entry,
+ n,
+ sem,
+ searxng_url=searxng_url,
+ brave_api_key=brave_api_key,
+ brave_bucket=brave_bucket,
+ session=session,
+ )
with open(output_path, "a", encoding="utf-8") as f:
f.write(json.dumps(result, default=str) + "\n")
logger.info("Searched: %s", entry.get("name"))
+
await asyncio.gather(*[_run_one(e) for e in remaining])
else:
+
async def _run_one(entry: dict) -> None: # type: ignore[no-redef]
result = await _search_one(entry, n, sem)
with open(output_path, "a", encoding="utf-8") as f:
f.write(json.dumps(result, default=str) + "\n")
logger.info("Searched: %s", entry.get("name"))
+
await asyncio.gather(*[_run_one(e) for e in remaining])
logger.info("Search complete. Results in %s", output_path)
@@ -301,6 +343,7 @@ async def run_search(
# Phase 2: Bedrock Batch Submit
# ---------------------------------------------------------------------------
+
def _make_batch_record(entry: dict, model_id: str) -> dict:
name = entry.get("name", "unknown")
website = entry.get("website", "")
@@ -350,14 +393,18 @@ def submit_batch(
import boto3
with open(input_path, encoding="utf-8") as f:
- entries = [json.loads(l) for l in f if l.strip()]
+ entries = [json.loads(line) for line in f if line.strip()]
# Skip already enriched entries
already_done = _already_enriched(enriched_path)
if already_done:
before = len(entries)
entries = [e for e in entries if e.get("name", "").lower().strip() not in already_done]
- logger.info("Skipping %d already-enriched entries (%d remaining)", before - len(entries), len(entries))
+ logger.info(
+ "Skipping %d already-enriched entries (%d remaining)",
+ before - len(entries),
+ len(entries),
+ )
logger.info("Preparing %d batch records for %s", len(entries), model_id)
records = [_make_batch_record(e, model_id) for e in entries]
@@ -401,6 +448,7 @@ def submit_batch(
def get_batch_status(job_arn: str, region: str = "us-east-1") -> dict:
import boto3
+
bedrock = boto3.client("bedrock", region_name=region)
resp = bedrock.get_model_invocation_job(jobIdentifier=job_arn)
return {
@@ -417,6 +465,7 @@ def get_batch_status(job_arn: str, region: str = "us-east-1") -> dict:
# Phase 3: Fetch from S3
# ---------------------------------------------------------------------------
+
def fetch_results(
job_arn: str,
output_path: Path,
diff --git a/libs/python/cua-sandbox-apps/cua_sandbox_apps/discovery/dedup.py b/libs/python/cua-sandbox-apps/cua_sandbox_apps/discovery/dedup.py
index 851fb20aa5..c0fa7eaa29 100644
--- a/libs/python/cua-sandbox-apps/cua_sandbox_apps/discovery/dedup.py
+++ b/libs/python/cua-sandbox-apps/cua_sandbox_apps/discovery/dedup.py
@@ -79,6 +79,7 @@ def deduplicate(
logger.info(
"Dedup complete: %d unique entries (%d duplicates removed)",
- len(seen), duplicates,
+ len(seen),
+ duplicates,
)
return len(seen)
diff --git a/libs/python/cua-sandbox-apps/cua_sandbox_apps/discovery/discover.py b/libs/python/cua-sandbox-apps/cua_sandbox_apps/discovery/discover.py
index bf15e52a9f..d17a4bf0ff 100644
--- a/libs/python/cua-sandbox-apps/cua_sandbox_apps/discovery/discover.py
+++ b/libs/python/cua-sandbox-apps/cua_sandbox_apps/discovery/discover.py
@@ -227,7 +227,7 @@ async def discover_software_for_group(
If the agent submits fewer than min_new_entries new items, it is re-prompted
up to 2 extra times to search from a different sub-angle.
"""
- from claude_agent_sdk import query, ClaudeAgentOptions, create_sdk_mcp_server
+ from claude_agent_sdk import ClaudeAgentOptions, create_sdk_mcp_server, query
submit_tool = _make_ingress_tool(catalog_path)
ingress_server = create_sdk_mcp_server(
@@ -267,7 +267,8 @@ async def discover_software_for_group(
model=model,
mcp_servers={"ingress": ingress_server},
allowed_tools=[
- "WebSearch", "WebFetch",
+ "WebSearch",
+ "WebFetch",
"mcp__ingress__submit_apps",
],
permission_mode="dontAsk",
@@ -285,13 +286,18 @@ async def discover_software_for_group(
session_id = msg.session_id
except Exception as e:
- logger.error("Discovery agent failed for %s (attempt %d): %s", occupation_group, attempt, e)
+ logger.error(
+ "Discovery agent failed for %s (attempt %d): %s", occupation_group, attempt, e
+ )
added_this_attempt = _count_catalog(catalog_path) - attempt_before
total_added += added_this_attempt
logger.info(
"%s attempt %d: +%d new entries (total this call: %d)",
- occupation_group, attempt, added_this_attempt, total_added,
+ occupation_group,
+ attempt,
+ added_this_attempt,
+ total_added,
)
if total_added >= min_new_entries:
@@ -299,7 +305,10 @@ async def discover_software_for_group(
if attempt < 2:
logger.info(
"%s: only %d new entries (< %d), resuming session %s...",
- occupation_group, total_added, min_new_entries, session_id,
+ occupation_group,
+ total_added,
+ min_new_entries,
+ session_id,
)
return total_added
@@ -323,7 +332,9 @@ async def run_discovery(
output_path.parent.mkdir(parents=True, exist_ok=True)
current = _count_catalog(output_path)
- logger.info("Starting discovery. Current catalog: %d, target: %d, model: %s", current, target, model)
+ logger.info(
+ "Starting discovery. Current catalog: %d, target: %d, model: %s", current, target, model
+ )
if current >= target:
logger.info("Already at target (%d >= %d)", current, target)
@@ -344,13 +355,14 @@ async def run_discovery(
angle = SEARCH_ANGLES[angle_idx % len(SEARCH_ANGLES)]
logger.info(
"=== DISCOVERY ROUND %d (catalog: %d / %d, concurrency: %d, angle: %s) ===",
- round_num, current, target, concurrency, angle[:40],
+ round_num,
+ current,
+ target,
+ concurrency,
+ angle[:40],
)
- tasks_to_run = [
- (occ["soc_code"], occ["occupation_title"])
- for occ in occupations
- ]
+ tasks_to_run = [(occ["soc_code"], occ["occupation_title"]) for occ in occupations]
sem = asyncio.Semaphore(concurrency)
@@ -360,7 +372,11 @@ async def run_discovery(
logger.info("[Round %d] Starting: %s", round_num, title)
try:
n = await discover_software_for_group(
- soc_code, title, output_path, model=model, search_angle=_angle,
+ soc_code,
+ title,
+ output_path,
+ model=model,
+ search_angle=_angle,
)
logger.info("[Round %d] +%d entries for %s", round_num, n, title)
return (n, True)
@@ -378,7 +394,12 @@ async def run_discovery(
current = _count_catalog(output_path)
logger.info(
"Round %d done: +%d entries, %d/%d agents succeeded. TOTAL: %d / %d",
- round_num, added, successes, len(results), current, target,
+ round_num,
+ added,
+ successes,
+ len(results),
+ current,
+ target,
)
# Advance to next search angle each round
@@ -388,7 +409,9 @@ async def run_discovery(
consecutive_zero_rounds += 1
logger.warning(
"No new entries in round %d (angle: %s). Zero streak: %d",
- round_num, angle[:40], consecutive_zero_rounds,
+ round_num,
+ angle[:40],
+ consecutive_zero_rounds,
)
# Give up only after exhausting all angles twice
if consecutive_zero_rounds >= len(SEARCH_ANGLES) * 2:
diff --git a/libs/python/cua-sandbox-apps/cua_sandbox_apps/discovery/enrich.py b/libs/python/cua-sandbox-apps/cua_sandbox_apps/discovery/enrich.py
index fba740b247..b7fe2b628e 100644
--- a/libs/python/cua-sandbox-apps/cua_sandbox_apps/discovery/enrich.py
+++ b/libs/python/cua-sandbox-apps/cua_sandbox_apps/discovery/enrich.py
@@ -110,7 +110,10 @@ def _make_submit_tool(output_path: Path, result_holder: list):
"categories": {"type": "array", "items": {"type": "string"}},
"tags": {"type": "array", "items": {"type": "string"}},
"os_support": {"type": "array", "items": {"type": "string"}},
- "app_type": {"type": "string", "enum": ["standalone", "cli", "library", "webapp", "both"]},
+ "app_type": {
+ "type": "string",
+ "enum": ["standalone", "cli", "library", "webapp", "both"],
+ },
"requires_payment": {"type": "boolean"},
"foss": {"type": "boolean"},
"gh_repo": {"type": "string"},
@@ -141,14 +144,16 @@ def _make_submit_tool(output_path: Path, result_holder: list):
_release_lock(output_path)
result_holder.append(entry)
- return {"content": [{"type": "text", "text": f"OK: enriched entry saved for {entry['name']}"}]}
+ return {
+ "content": [{"type": "text", "text": f"OK: enriched entry saved for {entry['name']}"}]
+ }
return submit_enriched
async def enrich_app(raw_entry: dict, output_path: Path, model: str = "haiku") -> dict | None:
"""Enrich a single app entry via a Claude agent with submit_enriched tool."""
- from claude_agent_sdk import query, ClaudeAgentOptions, create_sdk_mcp_server
+ from claude_agent_sdk import ClaudeAgentOptions, create_sdk_mcp_server, query
name = raw_entry.get("name", "unknown")
website = raw_entry.get("website", "")
@@ -198,10 +203,7 @@ async def run_enrichment(
raw_entries = read_jsonl(input_path)
already_done = _already_enriched(output_path)
- remaining = [
- e for e in raw_entries
- if e.get("name", "").lower().strip() not in already_done
- ]
+ remaining = [e for e in raw_entries if e.get("name", "").lower().strip() not in already_done]
random.shuffle(remaining)
if not remaining:
@@ -210,7 +212,9 @@ async def run_enrichment(
logger.info(
"Enriching %d entries (%d already done, concurrency=%d)",
- len(remaining), len(already_done), concurrency,
+ len(remaining),
+ len(already_done),
+ concurrency,
)
sem = asyncio.Semaphore(concurrency)
diff --git a/libs/python/cua-sandbox-apps/cua_sandbox_apps/discovery/onet.py b/libs/python/cua-sandbox-apps/cua_sandbox_apps/discovery/onet.py
index ebf3fb249b..72e50c951a 100644
--- a/libs/python/cua-sandbox-apps/cua_sandbox_apps/discovery/onet.py
+++ b/libs/python/cua-sandbox-apps/cua_sandbox_apps/discovery/onet.py
@@ -21,7 +21,9 @@ BLS_OEWS_URL = "https://www.bls.gov/oes/special-requests/oesm24nat.zip"
# O*NET occupation data (SOC crosswalk)
ONET_SOC_URL = "https://www.onetcenter.org/dl_files/database/db_29_1_text/Occupation%20Data.txt"
# O*NET computer use importance/level
-ONET_WORK_ACTIVITIES_URL = "https://www.onetcenter.org/dl_files/database/db_29_1_text/Work%20Activities.txt"
+ONET_WORK_ACTIVITIES_URL = (
+ "https://www.onetcenter.org/dl_files/database/db_29_1_text/Work%20Activities.txt"
+)
async def download_if_missing(url: str, dest: Path, client: httpx.AsyncClient) -> Path:
@@ -56,13 +58,15 @@ def parse_oews_national(csv_path: Path) -> list[dict]:
except ValueError:
mean_wage = 0.0
if employment > 0 and mean_wage > 0:
- records.append({
- "soc_code": row.get("OCC_CODE", ""),
- "occupation_title": row.get("OCC_TITLE", ""),
- "employment": employment,
- "mean_wage": mean_wage,
- "wage_bill": employment * mean_wage,
- })
+ records.append(
+ {
+ "soc_code": row.get("OCC_CODE", ""),
+ "occupation_title": row.get("OCC_TITLE", ""),
+ "employment": employment,
+ "mean_wage": mean_wage,
+ "wage_bill": employment * mean_wage,
+ }
+ )
return records
diff --git a/libs/python/cua-sandbox-apps/cua_sandbox_apps/pipeline/creator_agent.py b/libs/python/cua-sandbox-apps/cua_sandbox_apps/pipeline/creator_agent.py
index 1350feb982..c8604a8ba8 100644
--- a/libs/python/cua-sandbox-apps/cua_sandbox_apps/pipeline/creator_agent.py
+++ b/libs/python/cua-sandbox-apps/cua_sandbox_apps/pipeline/creator_agent.py
@@ -15,7 +15,7 @@ import os
from pathlib import Path
from typing import Any
-from claude_agent_sdk import query, ClaudeAgentOptions, create_sdk_mcp_server
+from claude_agent_sdk import ClaudeAgentOptions, create_sdk_mcp_server, query
from .sandbox_tools import make_sandbox_tools
@@ -61,6 +61,7 @@ def _lint_fail_fast(script: str) -> list[str]:
missing.append("`set -o pipefail` (surface errors in pipelines)")
return missing
+
CREATOR_SYSTEM_PROMPT = """\
You are an app installer agent. Your job is to create working install and launch
scripts for a specific application on a specific OS.
@@ -191,15 +192,25 @@ def _save_transcript(session_id: str | None, logs_dir: Path, app_id: str, target
# Convert to HTML
try:
subprocess.run(
- ["claude-code-transcripts", "json", str(dst), "-o", str(logs_dir / "install-transcript")],
- capture_output=True, text=True, timeout=60,
+ [
+ "claude-code-transcripts",
+ "json",
+ str(dst),
+ "-o",
+ str(logs_dir / "install-transcript"),
+ ],
+ capture_output=True,
+ text=True,
+ timeout=60,
)
logger.info("Generated HTML transcript for %s/%s", app_id, target_os)
except (subprocess.SubprocessError, FileNotFoundError) as e:
logger.warning("Failed to generate HTML transcript: %s", e)
-async def _verify_screenshot(screenshot_path: Path, app_name: str, is_cli: bool = False) -> tuple[bool, str]:
+async def _verify_screenshot(
+ screenshot_path: Path, app_name: str, is_cli: bool = False
+) -> tuple[bool, str]:
"""Use Bedrock haiku vision to check if the app is visible in the screenshot.
Returns (passed, reason).
@@ -240,13 +251,18 @@ async def _verify_screenshot(screenshot_path: Path, app_name: str, is_cli: bool
body = {
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 256,
- "messages": [{
- "role": "user",
- "content": [
- {"type": "image", "source": {"type": "base64", "media_type": media_type, "data": img_b64}},
- {"type": "text", "text": verification_text},
- ],
- }],
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "image",
+ "source": {"type": "base64", "media_type": media_type, "data": img_b64},
+ },
+ {"type": "text", "text": verification_text},
+ ],
+ }
+ ],
}
try:
@@ -282,23 +298,25 @@ async def _verify_metadata_script(script: str, app_name: str) -> tuple[bool, str
body = {
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 256,
- "messages": [{
- "role": "user",
- "content": (
- f"Review this metadata extraction script for the app \"{app_name}\". "
- f"The script is supposed to dynamically discover the binary path, display name, "
- f"version, icons, and desktop entries by inspecting the actual installed artifacts "
- f"(e.g. using `which`, `dpkg -L`, `rpm -ql`, reading .desktop files, parsing "
- f"package manager output, checking /usr/share/applications, etc.).\n\n"
- f"Does the script ACTUALLY inspect installed artifacts to extract metadata, "
- f"or does it just hardcode/echo static values?\n\n"
- f"Script:\n```\n{script}\n```\n\n"
- f"Reply with exactly one line:\n"
- f"PASS: <brief description of how it inspects artifacts>\n"
- f"or\n"
- f"FAIL: <what is hardcoded and how it should dynamically discover it instead>"
- ),
- }],
+ "messages": [
+ {
+ "role": "user",
+ "content": (
+ f'Review this metadata extraction script for the app "{app_name}". '
+ f"The script is supposed to dynamically discover the binary path, display name, "
+ f"version, icons, and desktop entries by inspecting the actual installed artifacts "
+ f"(e.g. using `which`, `dpkg -L`, `rpm -ql`, reading .desktop files, parsing "
+ f"package manager output, checking /usr/share/applications, etc.).\n\n"
+ f"Does the script ACTUALLY inspect installed artifacts to extract metadata, "
+ f"or does it just hardcode/echo static values?\n\n"
+ f"Script:\n```\n{script}\n```\n\n"
+ f"Reply with exactly one line:\n"
+ f"PASS: <brief description of how it inspects artifacts>\n"
+ f"or\n"
+ f"FAIL: <what is hardcoded and how it should dynamically discover it instead>"
+ ),
+ }
+ ],
}
try:
@@ -320,7 +338,14 @@ async def _verify_metadata_script(script: str, app_name: str) -> tuple[bool, str
return False, f"Verification error: {e}"
-def _make_submit_tool(result_holder: list, output_dir: Path | None, app_name: str, sandbox_registry: dict[str, Any] | None = None, target_os: str = "linux", strict_install_verify: bool = True):
+def _make_submit_tool(
+ result_holder: list,
+ output_dir: Path | None,
+ app_name: str,
+ sandbox_registry: dict[str, Any] | None = None,
+ target_os: str = "linux",
+ strict_install_verify: bool = True,
+):
"""MCP tool that verifies the screenshot before accepting the submission."""
from claude_agent_sdk import tool
@@ -337,17 +362,41 @@ def _make_submit_tool(result_holder: list, output_dir: Path | None, app_name: st
"properties": {
"app_id": {"type": "string"},
"os": {"type": "string"},
- "sandbox_name": {"type": "string", "description": "Name of the sandbox to verify screenshot from"},
- "install_script": {"type": "string", "description": "Contents of the install script"},
- "launch_script": {"type": "string", "description": "Contents of the launch script"},
- "extract_metadata_script": {"type": "string", "description": "Contents of the extract_metadata.sh/.ps1 script"},
- "metadata": {"type": "object", "description": "JSON output from extract_metadata script with binary_path, display_name, icon_paths, version"},
+ "sandbox_name": {
+ "type": "string",
+ "description": "Name of the sandbox to verify screenshot from",
+ },
+ "install_script": {
+ "type": "string",
+ "description": "Contents of the install script",
+ },
+ "launch_script": {
+ "type": "string",
+ "description": "Contents of the launch script",
+ },
+ "extract_metadata_script": {
+ "type": "string",
+ "description": "Contents of the extract_metadata.sh/.ps1 script",
+ },
+ "metadata": {
+ "type": "object",
+ "description": "JSON output from extract_metadata script with binary_path, display_name, icon_paths, version",
+ },
"install_exit_code": {"type": "integer"},
"install_stdout": {"type": "string"},
"verification_command": {"type": "string"},
- "download_available": {"type": "boolean", "description": "False if no public download exists (quote/sales required)"},
- "app_type_detected": {"type": "string", "description": "Set to 'library' or 'webapp' for early exit"},
- "is_cli": {"type": "boolean", "description": "True if this is a CLI/TUI tool (terminal screenshot accepted)"},
+ "download_available": {
+ "type": "boolean",
+ "description": "False if no public download exists (quote/sales required)",
+ },
+ "app_type_detected": {
+ "type": "string",
+ "description": "Set to 'library' or 'webapp' for early exit",
+ },
+ "is_cli": {
+ "type": "boolean",
+ "description": "True if this is a CLI/TUI tool (terminal screenshot accepted)",
+ },
"notes": {"type": "string"},
},
"required": ["app_id", "os", "install_exit_code"],
@@ -370,12 +419,24 @@ def _make_submit_tool(result_holder: list, output_dir: Path | None, app_name: st
else:
result["download_available"] = False
result_holder.append(result)
- logger.info("Early exit for %s/%s: %s — %s",
- result.get("app_id"), result.get("os"), detected_type or "no-download", reason)
- return {"content": [{"type": "text", "text": (
- f"OK: recorded for {result.get('app_id')} on {result.get('os')}. "
- f"Type: {detected_type or 'no-download'}. Reason: {reason}"
- )}]}
+ logger.info(
+ "Early exit for %s/%s: %s — %s",
+ result.get("app_id"),
+ result.get("os"),
+ detected_type or "no-download",
+ reason,
+ )
+ return {
+ "content": [
+ {
+ "type": "text",
+ "text": (
+ f"OK: recorded for {result.get('app_id')} on {result.get('os')}. "
+ f"Type: {detected_type or 'no-download'}. Reason: {reason}"
+ ),
+ }
+ ]
+ }
if not sandbox_name:
return {"content": [{"type": "text", "text": "ERROR: sandbox_name is required."}]}
@@ -403,12 +464,18 @@ def _make_submit_tool(result_holder: list, output_dir: Path | None, app_name: st
# ── Check 2: metadata extraction produced valid results ──
metadata = result.get("metadata")
if not metadata or not isinstance(metadata, dict):
- failures.append("metadata is missing. Run your extract_metadata script and include its JSON output.")
+ failures.append(
+ "metadata is missing. Run your extract_metadata script and include its JSON output."
+ )
else:
if not metadata.get("binary_path"):
- failures.append("metadata.binary_path is missing — the script must find the installed binary path.")
+ failures.append(
+ "metadata.binary_path is missing — the script must find the installed binary path."
+ )
if not metadata.get("display_name"):
- failures.append("metadata.display_name is missing — the script must extract the app's display name.")
+ failures.append(
+ "metadata.display_name is missing — the script must extract the app's display name."
+ )
# ── Check 3: install_script must parse (bash -n) and run end-to-end in
# a clean sandbox. Catches cases where the agent debugged interactively
@@ -422,7 +489,7 @@ def _make_submit_tool(result_holder: list, output_dir: Path | None, app_name: st
rendered = "; ".join(f"line {ln}: {txt.strip()}" for ln, txt in masks[:5])
failures.append(
f"install_script ERROR-MASKING: the install must FAIL FAST on any "
- f"error — strip all `|| true`, `|| :`, `|| echo \"\"` etc. "
+ f'error — strip all `|| true`, `|| :`, `|| echo ""` etc. '
f"If a command is genuinely optional, use a real `if` guard and "
f"log the decision. Violations: {rendered}"
)
@@ -430,10 +497,16 @@ def _make_submit_tool(result_holder: list, output_dir: Path | None, app_name: st
if missing_ff:
failures.append(
"install_script missing fail-fast pragmas near the top: "
- + ", ".join(missing_ff) + ". Add `set -euo pipefail` to the "
+ + ", ".join(missing_ff)
+ + ". Add `set -euo pipefail` to the "
"header so unchecked failures and undefined vars abort the script."
)
- if strict_install_verify and install_script and target_os != "windows" and sandbox_registry is not None:
+ if (
+ strict_install_verify
+ and install_script
+ and target_os != "windows"
+ and sandbox_registry is not None
+ ):
sb = sandbox_registry.get(sandbox_name)
if sb is not None:
await sb.files.write_text("/tmp/_verify_install.sh", install_script)
@@ -445,10 +518,18 @@ def _make_submit_tool(result_holder: list, output_dir: Path | None, app_name: st
else:
# Full end-to-end re-run in a fresh sandbox to catch idempotency
# regressions that the agent's iterative debugging masked.
- from cua_sandbox import Image as _Image, Sandbox as _Sandbox
- img_map = {"linux": _Image.linux, "macos": _Image.macos, "android": _Image.android}
+ from cua_sandbox import Image as _Image
+ from cua_sandbox import Sandbox as _Sandbox
+
+ img_map = {
+ "linux": _Image.linux,
+ "macos": _Image.macos,
+ "android": _Image.android,
+ }
img = img_map[target_os]()
- verify_sb = await _Sandbox.create(img, local=True, name=f"verify-{sandbox_name}")
+ verify_sb = await _Sandbox.create(
+ img, local=True, name=f"verify-{sandbox_name}"
+ )
try:
await verify_sb.files.write_text("/tmp/install.sh", install_script)
await verify_sb.shell.run("chmod +x /tmp/install.sh")
@@ -458,6 +539,7 @@ def _make_submit_tool(result_holder: list, output_dir: Path | None, app_name: st
background=True,
)
import asyncio as _aio
+
done = False
for _ in range(180): # up to 30 min
await _aio.sleep(10)
@@ -476,7 +558,9 @@ def _make_submit_tool(result_holder: list, output_dir: Path | None, app_name: st
done = True
break
if not done:
- failures.append("install_script timed out in fresh-sandbox verify (30 min)")
+ failures.append(
+ "install_script timed out in fresh-sandbox verify (30 min)"
+ )
finally:
try:
await verify_sb.destroy()
@@ -486,7 +570,9 @@ def _make_submit_tool(result_holder: list, output_dir: Path | None, app_name: st
# ── Check 4: extract_metadata_script was provided and actually inspects artifacts ──
extract_script = result.get("extract_metadata_script", "")
if not extract_script:
- failures.append("extract_metadata_script is missing. Write and include the metadata extraction script.")
+ failures.append(
+ "extract_metadata_script is missing. Write and include the metadata extraction script."
+ )
else:
# Verify the script actually inspects artifacts rather than hardcoding values
script_ok, script_reason = await _verify_metadata_script(extract_script, app_name)
@@ -495,10 +581,17 @@ def _make_submit_tool(result_holder: list, output_dir: Path | None, app_name: st
if failures:
checklist = "\n".join(f" - {f}" for f in failures)
- return {"content": [{"type": "text", "text": (
- f"CRITERIA NOT MET:\n{checklist}\n\n"
- f"Fix the issues above, then call submit_result again."
- )}]}
+ return {
+ "content": [
+ {
+ "type": "text",
+ "text": (
+ f"CRITERIA NOT MET:\n{checklist}\n\n"
+ f"Fix the issues above, then call submit_result again."
+ ),
+ }
+ ]
+ }
# All checks passed — extract icons from sandbox before it gets deleted
icon_paths = metadata.get("icon_paths", []) if metadata else []
@@ -508,7 +601,9 @@ def _make_submit_tool(result_holder: list, output_dir: Path | None, app_name: st
for icon_path in icon_paths:
try:
# Get icon dimensions and read file from sandbox
- r = await sb.shell.run(f"file {icon_path} 2>/dev/null | grep -oP '\\d+ x \\d+' | head -1")
+ r = await sb.shell.run(
+ f"file {icon_path} 2>/dev/null | grep -oP '\\d+ x \\d+' | head -1"
+ )
size = "unknown"
if r.returncode == 0 and r.stdout.strip():
dims = r.stdout.strip().split(" x ")
@@ -517,7 +612,8 @@ def _make_submit_tool(result_holder: list, output_dir: Path | None, app_name: st
# Fallback: try to get size from path (e.g. /usr/share/icons/hicolor/256x256/...)
if size == "unknown":
import re
- m = re.search(r'(\d+)x\d+', icon_path)
+
+ m = re.search(r"(\d+)x\d+", icon_path)
if m:
size = m.group(1)
r = await sb.shell.run(f"base64 {icon_path} 2>/dev/null")
@@ -534,12 +630,19 @@ def _make_submit_tool(result_holder: list, output_dir: Path | None, app_name: st
result["verification_passed"] = True
result["extracted_icons"] = extracted_icons
result_holder.append(result)
- return {"content": [{"type": "text", "text": (
- f"OK: result accepted for {result.get('app_id')} on {result.get('os')}.\n"
- f"Screenshot: {result.get('screenshot_verification', 'verified')}\n"
- f"Metadata: binary={metadata.get('binary_path')}, name={metadata.get('display_name')}, "
- f"version={metadata.get('version')}, icons={len(extracted_icons)} extracted"
- )}]}
+ return {
+ "content": [
+ {
+ "type": "text",
+ "text": (
+ f"OK: result accepted for {result.get('app_id')} on {result.get('os')}.\n"
+ f"Screenshot: {result.get('screenshot_verification', 'verified')}\n"
+ f"Metadata: binary={metadata.get('binary_path')}, name={metadata.get('display_name')}, "
+ f"version={metadata.get('version')}, icons={len(extracted_icons)} extracted"
+ ),
+ }
+ ]
+ }
return submit_result
@@ -570,7 +673,9 @@ async def create_app_installer(
agent_logger.setLevel(logging.INFO)
agent_log_path = logs_dir / "install-agent.log"
file_handler = logging.FileHandler(str(agent_log_path), mode="w", encoding="utf-8")
- file_handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s"))
+ file_handler.setFormatter(
+ logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s")
+ )
agent_logger.addHandler(file_handler)
# Per-agent sandbox registry — no cross-agent interference
@@ -580,7 +685,9 @@ async def create_app_installer(
sandbox_tools = make_sandbox_tools(evidence_dir=logs_dir, sandbox_registry=my_sandboxes)
result_holder: list = []
submit_tool = _make_submit_tool(
- result_holder, logs_dir, app_name,
+ result_holder,
+ logs_dir,
+ app_name,
sandbox_registry=my_sandboxes,
target_os=target_os,
strict_install_verify=strict_install_verify,
@@ -591,7 +698,8 @@ async def create_app_installer(
# Tool names for allowed_tools — NO Bash
tool_names = [
- "WebSearch", "WebFetch",
+ "WebSearch",
+ "WebFetch",
"mcp__sandbox__create_sandbox",
"mcp__sandbox__sandbox_run",
"mcp__sandbox__sandbox_write",
@@ -656,11 +764,14 @@ async def create_app_installer(
if result.get("download_available") is False:
app_os_dir.mkdir(parents=True, exist_ok=True)
(app_os_dir / "result.json").write_text(
- json.dumps(result, indent=2, default=str, ensure_ascii=True), encoding="utf-8")
+ json.dumps(result, indent=2, default=str, ensure_ascii=True), encoding="utf-8"
+ )
app_json = apps_dir / app_id / "app.json"
if not app_json.exists():
app_json.write_text(json.dumps(app_entry, indent=2, default=str), encoding="utf-8")
- logger.info("Recorded %s/%s as not downloadable: %s", app_id, target_os, result.get("notes"))
+ logger.info(
+ "Recorded %s/%s as not downloadable: %s", app_id, target_os, result.get("notes")
+ )
return result
# Write scripts to disk
@@ -682,20 +793,26 @@ async def create_app_installer(
metadata = result.get("metadata")
if metadata:
(app_os_dir / "metadata.json").write_text(
- json.dumps(metadata, indent=2, default=str, ensure_ascii=True), encoding="utf-8")
+ json.dumps(metadata, indent=2, default=str, ensure_ascii=True), encoding="utf-8"
+ )
# Write full result to logs
(logs_dir / "install-result.json").write_text(
- json.dumps(result, indent=2, default=str, ensure_ascii=True), encoding="utf-8")
+ json.dumps(result, indent=2, default=str, ensure_ascii=True), encoding="utf-8"
+ )
# Write app.json at the app level (shared across OS targets)
app_json = apps_dir / app_id / "app.json"
if not app_json.exists():
app_json.write_text(json.dumps(app_entry, indent=2, default=str), encoding="utf-8")
- logger.info("Created installer for %s/%s (verified=%s, screenshot=%s)",
- app_id, target_os, result.get("verification_passed"),
- result.get("screenshot_verification", "n/a"))
+ logger.info(
+ "Created installer for %s/%s (verified=%s, screenshot=%s)",
+ app_id,
+ target_os,
+ result.get("verification_passed"),
+ result.get("screenshot_verification", "n/a"),
+ )
return result
logger.warning("No result from creator agent for %s/%s", app_id, target_os)
@@ -712,6 +829,9 @@ async def create_installer_from_entry(
) -> dict | None:
"""Convenience wrapper — create installer from a catalog entry dict."""
return await create_app_installer(
- entry, target_os, apps_dir, model=model,
+ entry,
+ target_os,
+ apps_dir,
+ model=model,
strict_install_verify=strict_install_verify,
)
diff --git a/libs/python/cua-sandbox-apps/cua_sandbox_apps/pipeline/orchestrator.py b/libs/python/cua-sandbox-apps/cua_sandbox_apps/pipeline/orchestrator.py
index e836ffa70a..52b05e64b0 100644
--- a/libs/python/cua-sandbox-apps/cua_sandbox_apps/pipeline/orchestrator.py
+++ b/libs/python/cua-sandbox-apps/cua_sandbox_apps/pipeline/orchestrator.py
@@ -11,7 +11,7 @@ import json
import logging
from pathlib import Path
-from .shared_memory import init_memory, read_memory, append_learning
+from .shared_memory import append_learning, init_memory, read_memory
logger = logging.getLogger(__name__)
@@ -84,9 +84,11 @@ def _already_created(apps_dir: Path) -> set[str]:
continue
ext = "ps1" if os_dir.name == "windows" else "sh"
has_install = (os_dir / f"install.{ext}").exists()
- has_result = ((os_dir / "result.json").exists()
- or (os_dir / "logs" / "install-result.json").exists()
- or (os_dir / "logs" / "result.json").exists()) # legacy name
+ has_result = (
+ (os_dir / "result.json").exists()
+ or (os_dir / "logs" / "install-result.json").exists()
+ or (os_dir / "logs" / "result.json").exists()
+ ) # legacy name
if has_install or has_result:
done.add(f"{app_dir.name}/{os_dir.name}")
return done
@@ -177,7 +179,9 @@ async def run_orchestrator(
app_name = entry.get("name", "unknown")
logger.info("Creating: %s / %s", app_name, os_type)
ok = await create_installer_from_entry(
- entry, os_type, apps_dir,
+ entry,
+ os_type,
+ apps_dir,
strict_install_verify=strict_install_verify,
)
if ok:
@@ -200,5 +204,7 @@ async def run_orchestrator(
logger.info(
"Orchestrator complete: %d success, %d failed out of %d",
- success, fail, len(work),
+ success,
+ fail,
+ len(work),
)
diff --git a/libs/python/cua-sandbox-apps/cua_sandbox_apps/pipeline/sandbox_tools.py b/libs/python/cua-sandbox-apps/cua_sandbox_apps/pipeline/sandbox_tools.py
index f9e8d5f792..4c050dc801 100644
--- a/libs/python/cua-sandbox-apps/cua_sandbox_apps/pipeline/sandbox_tools.py
+++ b/libs/python/cua-sandbox-apps/cua_sandbox_apps/pipeline/sandbox_tools.py
@@ -18,7 +18,9 @@ logger = logging.getLogger(__name__)
_all_sandboxes: dict[str, Any] = {}
-def make_sandbox_tools(evidence_dir: Path | None = None, sandbox_registry: dict[str, Any] | None = None):
+def make_sandbox_tools(
+ evidence_dir: Path | None = None, sandbox_registry: dict[str, Any] | None = None
+):
"""Create MCP tools for sandbox lifecycle + file/exec operations.
Args:
@@ -71,7 +73,14 @@ def make_sandbox_tools(evidence_dir: Path | None = None, sandbox_registry: dict[
_all_sandboxes[name] = sb
logger.info("Created sandbox %s (os=%s)", name, os_type)
- return {"content": [{"type": "text", "text": f"OK: sandbox '{name}' created (os={os_type}). Use this name with other sandbox tools."}]}
+ return {
+ "content": [
+ {
+ "type": "text",
+ "text": f"OK: sandbox '{name}' created (os={os_type}). Use this name with other sandbox tools.",
+ }
+ ]
+ }
except Exception as e:
logger.error("Failed to create sandbox %s: %s", name, e)
@@ -85,7 +94,11 @@ def make_sandbox_tools(evidence_dir: Path | None = None, sandbox_registry: dict[
"properties": {
"name": {"type": "string", "description": "Sandbox name from create_sandbox"},
"command": {"type": "string", "description": "Shell command to run"},
- "timeout": {"type": "integer", "description": "Timeout in seconds (default 120)", "default": 120},
+ "timeout": {
+ "type": "integer",
+ "description": "Timeout in seconds (default 120)",
+ "default": 120,
+ },
},
"required": ["name", "command"],
},
@@ -97,7 +110,14 @@ def make_sandbox_tools(evidence_dir: Path | None = None, sandbox_registry: dict[
sb = sandboxes.get(name)
if not sb:
- return {"content": [{"type": "text", "text": f"ERROR: sandbox '{name}' not found. Create one first."}]}
+ return {
+ "content": [
+ {
+ "type": "text",
+ "text": f"ERROR: sandbox '{name}' not found. Create one first.",
+ }
+ ]
+ }
logger.info("[%s] $ %s", name, command[:120])
try:
@@ -110,7 +130,9 @@ def make_sandbox_tools(evidence_dir: Path | None = None, sandbox_registry: dict[
output = f"EXIT CODE: {result.returncode}\n\nSTDOUT:\n{result.stdout[:10000]}\n\nSTDERR:\n{result.stderr[:5000]}"
return {"content": [{"type": "text", "text": output}]}
except asyncio.TimeoutError:
- return {"content": [{"type": "text", "text": f"ERROR: command timed out after {timeout}s"}]}
+ return {
+ "content": [{"type": "text", "text": f"ERROR: command timed out after {timeout}s"}]
+ }
except Exception as e:
return {"content": [{"type": "text", "text": f"ERROR: {e}"}]}
@@ -121,9 +143,16 @@ def make_sandbox_tools(evidence_dir: Path | None = None, sandbox_registry: dict[
"type": "object",
"properties": {
"name": {"type": "string", "description": "Sandbox name"},
- "path": {"type": "string", "description": "Absolute path inside the sandbox (e.g. /tmp/install.sh)"},
+ "path": {
+ "type": "string",
+ "description": "Absolute path inside the sandbox (e.g. /tmp/install.sh)",
+ },
"content": {"type": "string", "description": "File content to write"},
- "executable": {"type": "boolean", "description": "Make the file executable (default false)", "default": False},
+ "executable": {
+ "type": "boolean",
+ "description": "Make the file executable (default false)",
+ "default": False,
+ },
},
"required": ["name", "path", "content"],
},
@@ -145,7 +174,9 @@ def make_sandbox_tools(evidence_dir: Path | None = None, sandbox_registry: dict[
await sb.shell.run(f"cat > {path} << 'SANDBOX_EOF'\n{content}\nSANDBOX_EOF")
if executable:
await sb.shell.run(f"chmod +x {path}")
- return {"content": [{"type": "text", "text": f"OK: wrote {len(content)} bytes to {path}"}]}
+ return {
+ "content": [{"type": "text", "text": f"OK: wrote {len(content)} bytes to {path}"}]
+ }
except Exception as e:
return {"content": [{"type": "text", "text": f"ERROR: {e}"}]}
@@ -157,7 +188,11 @@ def make_sandbox_tools(evidence_dir: Path | None = None, sandbox_registry: dict[
"properties": {
"name": {"type": "string", "description": "Sandbox name"},
"path": {"type": "string", "description": "Absolute path inside the sandbox"},
- "max_lines": {"type": "integer", "description": "Max lines to return (default 200)", "default": 200},
+ "max_lines": {
+ "type": "integer",
+ "description": "Max lines to return (default 200)",
+ "default": 200,
+ },
},
"required": ["name", "path"],
},
@@ -202,23 +237,31 @@ def make_sandbox_tools(evidence_dir: Path | None = None, sandbox_registry: dict[
if evidence_dir:
evidence_dir.mkdir(parents=True, exist_ok=True)
out_path = evidence_dir / f"{name}.jpg"
- if hasattr(screenshot, 'save'):
+ if hasattr(screenshot, "save"):
# PIL Image — save as JPEG
screenshot = screenshot.convert("RGB")
screenshot.save(str(out_path), "JPEG", quality=85)
elif isinstance(screenshot, bytes):
# Raw PNG bytes — convert to JPEG
try:
- from PIL import Image as PILImage
import io
+
+ from PIL import Image as PILImage
+
img = PILImage.open(io.BytesIO(screenshot)).convert("RGB")
img.save(str(out_path), "JPEG", quality=85)
except ImportError:
# No PIL — save as PNG with .jpg extension (fallback)
out_path = evidence_dir / f"{name}.png"
out_path.write_bytes(screenshot)
- return {"content": [{"type": "text", "text": f"OK: screenshot saved to {out_path}"}]}
- return {"content": [{"type": "text", "text": "OK: screenshot taken (no evidence_dir configured)"}]}
+ return {
+ "content": [{"type": "text", "text": f"OK: screenshot saved to {out_path}"}]
+ }
+ return {
+ "content": [
+ {"type": "text", "text": "OK: screenshot taken (no evidence_dir configured)"}
+ ]
+ }
except Exception as e:
return {"content": [{"type": "text", "text": f"ERROR: {e}"}]}
@@ -239,7 +282,11 @@ def make_sandbox_tools(evidence_dir: Path | None = None, sandbox_registry: dict[
sb = sandboxes.pop(name, None)
_all_sandboxes.pop(name, None)
if not sb:
- return {"content": [{"type": "text", "text": f"OK: sandbox '{name}' already deleted or not found."}]}
+ return {
+ "content": [
+ {"type": "text", "text": f"OK: sandbox '{name}' already deleted or not found."}
+ ]
+ }
try:
await sb.destroy()
@@ -249,7 +296,14 @@ def make_sandbox_tools(evidence_dir: Path | None = None, sandbox_registry: dict[
logger.warning("Error deleting sandbox %s: %s", name, e)
return {"content": [{"type": "text", "text": f"WARN: sandbox deleted with error: {e}"}]}
- return [create_sandbox, sandbox_run, sandbox_write, sandbox_read, sandbox_screenshot, delete_sandbox]
+ return [
+ create_sandbox,
+ sandbox_run,
+ sandbox_write,
+ sandbox_read,
+ sandbox_screenshot,
+ delete_sandbox,
+ ]
async def cleanup_all_sandboxes() -> None:
diff --git a/libs/python/cua-sandbox-apps/cua_sandbox_apps/schema.py b/libs/python/cua-sandbox-apps/cua_sandbox_apps/schema.py
index 5771bdacd6..669080b70e 100644
--- a/libs/python/cua-sandbox-apps/cua_sandbox_apps/schema.py
+++ b/libs/python/cua-sandbox-apps/cua_sandbox_apps/schema.py
@@ -44,9 +44,7 @@ class AppEntry(BaseModel):
soc_groups: list[str] = Field(default_factory=list)
# Availability
- os_support: list[Literal["linux", "windows", "macos", "android"]] = Field(
- default_factory=list
- )
+ os_support: list[Literal["linux", "windows", "macos", "android"]] = Field(default_factory=list)
# True if a CUA agent would need to pay (credit card / subscription) to
# fully exercise the app's core UI. Free tiers, trials, OSS = False.
requires_payment: bool = False
diff --git a/libs/python/cua-sandbox/cua_sandbox/builder/executor.py b/libs/python/cua-sandbox/cua_sandbox/builder/executor.py
index cd68aac4d9..db908d825e 100644
--- a/libs/python/cua-sandbox/cua_sandbox/builder/executor.py
+++ b/libs/python/cua-sandbox/cua_sandbox/builder/executor.py
@@ -27,10 +27,10 @@ def _find_app_install_script(app_id: str, os_type: str) -> str | None:
ext = _OS_EXT.get(os_type, "sh")
# Try cua_sandbox_apps package path first
try:
- import importlib.resources
from pathlib import Path
import cua_sandbox_apps
+
apps_dir = Path(cua_sandbox_apps.__file__).parent / "apps"
script_path = apps_dir / app_id / os_type / f"install.{ext}"
if script_path.exists():
@@ -47,6 +47,7 @@ def _find_app_launch_script(app_id: str, os_type: str) -> str | None:
from pathlib import Path
import cua_sandbox_apps
+
apps_dir = Path(cua_sandbox_apps.__file__).parent / "apps"
script_path = apps_dir / app_id / os_type / f"launch.{ext}"
if script_path.exists():
@@ -271,17 +272,15 @@ class LayerExecutor:
async def _exec_app_install(self, layer: dict) -> dict:
"""Install an app from cua-sandbox-apps. Reads its install.sh and runs it."""
app_id = layer["app_id"]
- try:
- from cua_sandbox_apps.pipeline.task_creator_agent import _resolve_app_scripts
- except ImportError:
- # cua-sandbox-apps not installed — try to locate the script file directly
- pass
# Locate the install script from the apps catalog
script = _find_app_install_script(app_id, self.os_type)
if script is None:
- return {"success": False, "return_code": 1,
- "stderr": f"No install script found for app '{app_id}' on {self.os_type}. "
- f"Install cua-sandbox-apps or run 'cua-sandbox-apps generate' first."}
+ return {
+ "success": False,
+ "return_code": 1,
+ "stderr": f"No install script found for app '{app_id}' on {self.os_type}. "
+ f"Install cua-sandbox-apps or run 'cua-sandbox-apps generate' first.",
+ }
return await self.run_command(f"bash -c {_sh_quote(script)}", timeout=900)
async def _exec_expose(self, layer: dict) -> dict:
diff --git a/libs/python/cua-sandbox/cua_sandbox/builder/windows_unattend.py b/libs/python/cua-sandbox/cua_sandbox/builder/windows_unattend.py
index 1485bcdb84..bb0352ae2c 100644
--- a/libs/python/cua-sandbox/cua_sandbox/builder/windows_unattend.py
+++ b/libs/python/cua-sandbox/cua_sandbox/builder/windows_unattend.py
@@ -31,7 +31,9 @@ def download_file(url: str, dest: Path, description: str = "") -> Path:
return dest
-def _resolve_server_eval_url(server_version: str, culture: str = "en-us", country: str = "US") -> str:
+def _resolve_server_eval_url(
+ server_version: str, culture: str = "en-us", country: str = "US"
+) -> str:
"""Resolve Windows Server evaluation ISO download URL from Microsoft's eval center.
Adapted from quickemu/quickget's download_windows_server() which is itself
@@ -200,7 +202,10 @@ def generate_autounattend_xml(
image_name = _server_image_names.get(version)
# Use /IMAGE/NAME for server (more reliable than index)
image_select_key = "/IMAGE/NAME"
- image_select_value = image_name or f"Windows Server {version.split('-')[1]} Standard Evaluation (Desktop Experience)"
+ image_select_value = (
+ image_name
+ or f"Windows Server {version.split('-')[1]} Standard Evaluation (Desktop Experience)"
+ )
else:
image_select_key = "/IMAGE/INDEX"
image_select_value = "1"
diff --git a/libs/python/cua-sandbox/cua_sandbox/image.py b/libs/python/cua-sandbox/cua_sandbox/image.py
index 727cc4ac8f..22d8cc76dc 100644
--- a/libs/python/cua-sandbox/cua_sandbox/image.py
+++ b/libs/python/cua-sandbox/cua_sandbox/image.py
@@ -125,9 +125,7 @@ class Image:
# ── Constructors ─────────────────────────────────────────────────────
@classmethod
- def linux(
- cls, distro: str = "ubuntu", version: str = "24.04", kind: str = "vm"
- ) -> Image:
+ def linux(cls, distro: str = "ubuntu", version: str = "24.04", kind: str = "vm") -> Image:
"""Linux image. Defaults to 'vm' (QEMU). Use kind='container' for Docker/XFCE."""
return cls(os_type="linux", distro=distro, version=version, kind=kind)
diff --git a/libs/python/cua-sandbox/cua_sandbox/interfaces/apps.py b/libs/python/cua-sandbox/cua_sandbox/interfaces/apps.py
index 4257a41f5e..9eb981eca9 100644
--- a/libs/python/cua-sandbox/cua_sandbox/interfaces/apps.py
+++ b/libs/python/cua-sandbox/cua_sandbox/interfaces/apps.py
@@ -20,11 +20,14 @@ class Apps:
script = _find_app_install_script(app_id, self._os_type)
if script is None:
return CommandResult(
- stdout="", returncode=1,
+ stdout="",
+ returncode=1,
stderr=f"No install script for '{app_id}' on {self._os_type}. "
- f"Install cua-sandbox-apps or run 'cua-sandbox-apps generate'.",
+ f"Install cua-sandbox-apps or run 'cua-sandbox-apps generate'.",
)
- result = await self._t.send("run_command", command=f"bash -c {_sh_quote(script)}", timeout=900)
+ result = await self._t.send(
+ "run_command", command=f"bash -c {_sh_quote(script)}", timeout=900
+ )
if isinstance(result, dict):
return CommandResult(
stdout=result.get("stdout", ""),
@@ -44,7 +47,8 @@ class Apps:
script = _find_app_launch_script(app_id, self._os_type)
if script is None:
return CommandResult(
- stdout="", returncode=1,
+ stdout="",
+ returncode=1,
stderr=f"No launch script for '{app_id}' on {self._os_type}.",
)
result = await self._t.pty_create(command=f"bash -c {_sh_quote(script)}")
diff --git a/libs/python/cua-sandbox/cua_sandbox/interfaces/files.py b/libs/python/cua-sandbox/cua_sandbox/interfaces/files.py
index a15cf0664d..467637b0ed 100644
--- a/libs/python/cua-sandbox/cua_sandbox/interfaces/files.py
+++ b/libs/python/cua-sandbox/cua_sandbox/interfaces/files.py
@@ -65,12 +65,14 @@ class Files:
if isinstance(item, str):
out.append(FileEntry(name=item, path=f"{path.rstrip('/')}/{item}", is_dir=False))
elif isinstance(item, dict):
- out.append(FileEntry(
- name=item.get("name", ""),
- path=item.get("path", f"{path.rstrip('/')}/{item.get('name', '')}"),
- is_dir=bool(item.get("is_dir", False)),
- size=item.get("size"),
- ))
+ out.append(
+ FileEntry(
+ name=item.get("name", ""),
+ path=item.get("path", f"{path.rstrip('/')}/{item.get('name', '')}"),
+ is_dir=bool(item.get("is_dir", False)),
+ size=item.get("size"),
+ )
+ )
return out
async def make_dir(self, path: str) -> None:
diff --git a/libs/python/cua-sandbox/cua_sandbox/registry/qemu_builder.py b/libs/python/cua-sandbox/cua_sandbox/registry/qemu_builder.py
index 9015038f6e..b454133bfd 100644
--- a/libs/python/cua-sandbox/cua_sandbox/registry/qemu_builder.py
+++ b/libs/python/cua-sandbox/cua_sandbox/registry/qemu_builder.py
@@ -58,7 +58,9 @@ class QEMUImageConfig:
disk_format: str = "qcow2"
tpm: bool = True
architecture: str = "x86_64"
- qemu_bin: Optional[str] = None # Custom QEMU binary path (e.g. /opt/incus/bin/qemu-system-x86_64)
+ qemu_bin: Optional[str] = (
+ None # Custom QEMU binary path (e.g. /opt/incus/bin/qemu-system-x86_64)
+ )
display: dict = field(default_factory=lambda: {"width": 1920, "height": 1080})
@@ -286,7 +288,6 @@ def _build_image_wsl2(
# ── Full build ──────────────────────────────────────────────────────────────
-
def build_image(
config: Optional[QEMUImageConfig] = None,
*,
@@ -331,6 +332,7 @@ def build_image(
qemu = config.qemu_bin
else:
from cua_sandbox.runtime.qemu_installer import qemu_bin
+
qemu = qemu_bin(config.architecture)
qemu_dir = Path(qemu).parent
@@ -778,7 +780,9 @@ def main():
# build
build_p = sub.add_parser("build", help="Build a Windows VM image")
- build_p.add_argument("--windows-version", default="11", help="Windows version (10, 11, server-2022, server-2025)")
+ build_p.add_argument(
+ "--windows-version", default="11", help="Windows version (10, 11, server-2022, server-2025)"
+ )
build_p.add_argument("--iso-path", help="Path to Windows ISO (skip download)")
build_p.add_argument("--disk-size", type=int, default=64, help="Disk size in GB")
build_p.add_argument("--ram", type=int, default=8192, help="RAM in MB")
@@ -789,7 +793,9 @@ def main():
build_p.add_argument(
"--wsl2", action="store_true", help="Run QEMU inside WSL2 with KVM acceleration"
)
- build_p.add_argument("--qemu-bin", help="Custom QEMU binary path (e.g. /opt/incus/bin/qemu-system-x86_64)")
+ build_p.add_argument(
+ "--qemu-bin", help="Custom QEMU binary path (e.g. /opt/incus/bin/qemu-system-x86_64)"
+ )
# push
push_p = sub.add_parser("push", help="Push a qcow2 disk as OCI image")
diff --git a/libs/python/cua-sandbox/cua_sandbox/runtime/android_emulator.py b/libs/python/cua-sandbox/cua_sandbox/runtime/android_emulator.py
index 1d4638bf44..58943126e2 100644
--- a/libs/python/cua-sandbox/cua_sandbox/runtime/android_emulator.py
+++ b/libs/python/cua-sandbox/cua_sandbox/runtime/android_emulator.py
@@ -453,7 +453,7 @@ class AndroidEmulatorRuntime(Runtime):
"mkdir -p /data/local/tmp && "
"echo 'chrome --no-first-run --disable-fre "
"--no-default-browser-check "
- f"--disable-digital-asset-link-verification-for-url=\"{origin}\"' "
+ f'--disable-digital-asset-link-verification-for-url="{origin}"\' '
"> /data/local/tmp/chrome-command-line",
]:
subprocess.run(
diff --git a/libs/python/cua-sandbox/cua_sandbox/sandbox.py b/libs/python/cua-sandbox/cua_sandbox/sandbox.py
index b43f4142bd..32031f8e1b 100644
--- a/libs/python/cua-sandbox/cua_sandbox/sandbox.py
+++ b/libs/python/cua-sandbox/cua_sandbox/sandbox.py
@@ -266,7 +266,7 @@ class Sandbox:
self.terminal = Terminal(transport)
self.mobile = Mobile(transport)
self.tunnel = Tunnel(transport)
- _os = (_runtime_info.environment if _runtime_info and _runtime_info.environment else "linux")
+ _os = _runtime_info.environment if _runtime_info and _runtime_info.environment else "linux"
self.apps = Apps(transport, os_type=_os)
async def _connect(self) -> None:
diff --git a/libs/python/cua-sandbox/cua_sandbox/transport/cloud.py b/libs/python/cua-sandbox/cua_sandbox/transport/cloud.py
index 9bb9209cf4..a776067755 100644
--- a/libs/python/cua-sandbox/cua_sandbox/transport/cloud.py
+++ b/libs/python/cua-sandbox/cua_sandbox/transport/cloud.py
@@ -144,7 +144,6 @@ class CloudTransport(Transport):
# server. This overlaps the kopf handler's credential injection
# and DNS setup with the CUA server boot.
- server_ready: asyncio.Event = asyncio.Event()
probe_task: Optional[asyncio.Task] = None
resolved_url: Optional[str] = None
@@ -162,10 +161,10 @@ class CloudTransport(Transport):
# Got a direct IP — start probing if not already
if probe_task is None:
resolved_url = url
- logger.debug("[cloud] early endpoint: %s at %.1fs — starting probe", url, elapsed)
- probe_task = asyncio.create_task(
- _connect_and_wait_ready(url, api_key)
+ logger.debug(
+ "[cloud] early endpoint: %s at %.1fs — starting probe", url, elapsed
)
+ probe_task = asyncio.create_task(_connect_and_wait_ready(url, api_key))
except (ValueError, KeyError):
pass
@@ -407,7 +406,9 @@ class CloudTransport(Transport):
try:
resp = await self._inner._client.get("/", timeout=2.0)
# Any response means the server is up
- logger.debug("[cloud] server HTTP up (status=%d) at %.1fs", resp.status_code, elapsed)
+ logger.debug(
+ "[cloud] server HTTP up (status=%d) at %.1fs", resp.status_code, elapsed
+ )
break
except Exception as e:
last_err = e
diff --git a/libs/python/cua-sandbox/tests/test_parse_sse.py b/libs/python/cua-sandbox/tests/test_parse_sse.py
index c6be2c27fc..7696052e29 100644
--- a/libs/python/cua-sandbox/tests/test_parse_sse.py
+++ b/libs/python/cua-sandbox/tests/test_parse_sse.py
@@ -16,7 +16,6 @@ These tests pin the new behavior:
"""
import pytest
-
from cua_sandbox.transport.http import HTTPTransport
@@ -32,9 +31,7 @@ class TestParseSSESurfacesFailures:
def test_explicit_error_field_preserved_verbatim(self):
with pytest.raises(RuntimeError, match=r"Remote error: boom"):
- HTTPTransport._parse_sse(
- _sse('{"success": false, "error": "boom"}')
- )
+ HTTPTransport._parse_sse(_sse('{"success": false, "error": "boom"}'))
def test_shell_failure_surfaces_return_code_and_stderr(self):
with pytest.raises(RuntimeError) as exc:
diff --git a/libs/python/cua-sandbox/tests/test_windows_cloud.py b/libs/python/cua-sandbox/tests/test_windows_cloud.py
index 2f8e397816..58d9b6f68b 100644
--- a/libs/python/cua-sandbox/tests/test_windows_cloud.py
+++ b/libs/python/cua-sandbox/tests/test_windows_cloud.py
@@ -7,14 +7,15 @@ Run:
import os
import time
-import sys
import pytest
-
from cua_sandbox import Image, Sandbox
pytestmark = pytest.mark.asyncio
-P = lambda *a, **kw: print(*a, **kw, flush=True)
+
+
+def P(*a, **kw):
+ print(*a, **kw, flush=True)
def _has_env() -> bool:
@@ -27,7 +28,7 @@ async def test_windows_create_and_snapshot():
t0 = time.monotonic()
- P(f"\n Creating Sandbox with Image.windows('server-2025')...")
+ P("\n Creating Sandbox with Image.windows('server-2025')...")
async with Sandbox.ephemeral(Image.windows("server-2025"), local=False) as sb:
t_create = time.monotonic() - t0
P(f" Sandbox ready: {t_create:.1f}s name={sb.name}")
@@ -42,14 +43,14 @@ async def test_windows_create_and_snapshot():
# Snapshot
t1 = time.monotonic()
- P(f" Taking snapshot...")
+ P(" Taking snapshot...")
snapshot_img = await sb.snapshot()
t_snap = time.monotonic() - t1
P(f" Snapshot: {t_snap:.2f}s")
# Fork from snapshot
t2 = time.monotonic()
- P(f" Forking from snapshot...")
+ P(" Forking from snapshot...")
async with Sandbox.ephemeral(snapshot_img, local=False) as fork:
t_fork = time.monotonic() - t2
P(f" Fork ready: {t_fork:.1f}s name={fork.name}")
@@ -62,7 +63,7 @@ async def test_windows_create_and_snapshot():
fork_screen = None
t_total = time.monotonic() - t0
- P(f"\n === TIMINGS ===")
+ P("\n === TIMINGS ===")
P(f" Create+ready: {t_create:.1f}s")
P(f" Snapshot: {t_snap:.2f}s")
P(f" Fork+ready: {t_fork:.1f}s")
@@ -75,7 +76,7 @@ async def test_windows_stateful_snapshot_fork():
t0 = time.monotonic()
- P(f"\n Creating Sandbox with Image.windows('server-2025')...")
+ P("\n Creating Sandbox with Image.windows('server-2025')...")
async with Sandbox.ephemeral(Image.windows("server-2025"), local=False) as sb:
t_create = time.monotonic() - t0
P(f" Sandbox ready: {t_create:.1f}s name={sb.name}")
@@ -86,14 +87,14 @@ async def test_windows_stateful_snapshot_fork():
# Stateful snapshot — captures memory state
t1 = time.monotonic()
- P(f" Taking stateful snapshot...")
+ P(" Taking stateful snapshot...")
snapshot_img = await sb.snapshot(stateful=True)
t_snap = time.monotonic() - t1
P(f" Stateful snapshot: {t_snap:.2f}s")
# Fork from stateful snapshot — should resume instantly
t2 = time.monotonic()
- P(f" Forking from stateful snapshot...")
+ P(" Forking from stateful snapshot...")
async with Sandbox.ephemeral(snapshot_img, local=False) as fork:
t_fork = time.monotonic() - t2
P(f" Fork ready: {t_fork:.1f}s name={fork.name}")
@@ -104,7 +105,7 @@ async def test_windows_stateful_snapshot_fork():
assert len(fork_screen) > 1000, "Fork screenshot should be non-trivial"
t_total = time.monotonic() - t0
- P(f"\n === STATEFUL TIMINGS ===")
+ P("\n === STATEFUL TIMINGS ===")
P(f" Create+ready: {t_create:.1f}s")
P(f" Stateful snapshot: {t_snap:.2f}s")
P(f" Fork+ready: {t_fork:.1f}s (should be <10s with stateful)")
diff --git a/libs/python/cua-sandbox/tests/test_windows_timing.py b/libs/python/cua-sandbox/tests/test_windows_timing.py
index bea11dd5f3..b371aabde8 100644
--- a/libs/python/cua-sandbox/tests/test_windows_timing.py
+++ b/libs/python/cua-sandbox/tests/test_windows_timing.py
@@ -9,11 +9,13 @@ import os
import time
import pytest
-
from cua_sandbox import Image, Sandbox
pytestmark = pytest.mark.asyncio
-P = lambda *a, **kw: print(*a, **kw, flush=True)
+
+
+def P(*a, **kw):
+ print(*a, **kw, flush=True)
def _has_env() -> bool:
@@ -74,7 +76,7 @@ async def test_windows_all_restore_modes():
P(f" Screenshot: {len(fork2_screen)} bytes")
P(f"\n {'='*50}")
- P(f" TIMING COMPARISON")
+ P(" TIMING COMPARISON")
P(f" {'='*50}")
P(f" Image.windows() create: {results['create']:6.1f}s")
P(f" snapshot(stateful=False): {results['snapshot']:6.2f}s")
diff --git a/libs/python/mcp-server/mcp_server/server.py b/libs/python/mcp-server/mcp_server/server.py
index b909c42f0b..7258022397 100644
--- a/libs/python/mcp-server/mcp_server/server.py
+++ b/libs/python/mcp-server/mcp_server/server.py
@@ -35,8 +35,8 @@ except ImportError as e:
sys.exit(1)
try:
- from cua_agent import ComputerAgent
from computer import Computer
+ from cua_agent import ComputerAgent
logger.debug("Successfully imported Computer and Agent modules")
except ImportError as e:
diff --git a/tests/test_image_builder.py b/tests/test_image_builder.py
index 89963419aa..534c8b5b56 100644
--- a/tests/test_image_builder.py
+++ b/tests/test_image_builder.py
@@ -12,6 +12,7 @@ Run with:
from __future__ import annotations
import pytest
+
from cua import Image, Sandbox, skip_if_unsupported
# ── helpers ──────────────────────────────────────────────────────────────────
diff --git a/tests/test_image_builder_cloud.py b/tests/test_image_builder_cloud.py
index 685c4aae05..7a003a79f8 100644
--- a/tests/test_image_builder_cloud.py
+++ b/tests/test_image_builder_cloud.py
@@ -13,6 +13,7 @@ from __future__ import annotations
import os
import pytest
+
from cua import Image, Sandbox
pytestmark = pytest.mark.asyncio
diff --git a/tests/test_interfaces.py b/tests/test_interfaces.py
index cc56fbaa74..4afcd86f59 100644
--- a/tests/test_interfaces.py
+++ b/tests/test_interfaces.py
@@ -38,6 +38,7 @@ import base64
import httpx
import pytest
+
from cua import Image, Sandbox, skip_if_unsupported
# ── helpers ──────────────────────────────────────────────────────────────────
diff --git a/tests/test_telemetry.py b/tests/test_telemetry.py
index 6e6097b1ca..98295fe612 100644
--- a/tests/test_telemetry.py
+++ b/tests/test_telemetry.py
@@ -24,7 +24,11 @@ for path in pythonpath.split(":"):
sys.path.insert(0, path) # Insert at beginning to prioritize
print(f"Added to sys.path: {path}")
-from cua_core.telemetry import destroy_telemetry_client, is_telemetry_enabled, record_event
+from cua_core.telemetry import (
+ destroy_telemetry_client,
+ is_telemetry_enabled,
+ record_event,
+)
class TestTelemetry: