-
-
Notifications
You must be signed in to change notification settings - Fork 949
Expand file tree
/
Copy pathdo.py
More file actions
1867 lines (1527 loc) · 65.5 KB
/
do.py
File metadata and controls
1867 lines (1527 loc) · 65.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""cua do — one-shot VM automation commands for agents.
Output is always a single line starting with ✅ (success) or ❌ (failure),
followed by a context line: 💻 vm-name\t🪟 Window Title (or Desktop).
Target VM is persisted in ~/.cua/do_target.json.
Zoom state (bbox + display scale) is also persisted there.
"""
from __future__ import annotations
import argparse
import base64
import io
import json
import os
import sys
import tempfile
from datetime import datetime
from pathlib import Path
# Ensure stdout/stderr can handle Unicode emojis on Windows
if sys.platform == "win32":
import io as _io
if hasattr(sys.stdout, "buffer"):
sys.stdout = _io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
if hasattr(sys.stderr, "buffer"):
sys.stderr = _io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8", errors="replace")
MAX_LENGTH = 1200 # max pixel dimension for screenshot output
# ── state ─────────────────────────────────────────────────────────────────────
_STATE_FILE = Path.home() / ".cua" / "do_target.json"
_HOST_CONSENT_FILE = Path.home() / ".cua" / "host_consented"
# Window titles that are internal OS/browser helper windows and should be hidden
_SKIP_WINDOW_TITLES = {
"Chrome Legacy Window",
}
PROVIDERS = ("cloud", "cloudv2", "local", "lume", "lumier", "docker", "winsandbox", "host")
_REMOTE_PROVIDERS = ("cloud", "cloudv2", "lume", "lumier", "docker", "winsandbox")
def _load_state() -> dict:
if _STATE_FILE.exists():
try:
return json.loads(_STATE_FILE.read_text())
except Exception:
pass
return {}
def _save_state(state: dict) -> None:
_STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
_STATE_FILE.write_text(json.dumps(state, indent=2))
def _update_state(**kwargs) -> dict:
state = _load_state()
state.update(kwargs)
_save_state(state)
return state
def _host_consented() -> bool:
return _HOST_CONSENT_FILE.exists()
# ── output helpers ────────────────────────────────────────────────────────────
def _ok(msg: str) -> int:
print(f"✅ {msg}")
return 0
def _fail(msg: str) -> int:
print(f"❌ {msg}", file=sys.stderr)
return 1
class _PtyUnavailable(Exception):
"""Raised when the remote PTY endpoint is unreachable; triggers run_command fallback."""
# ── provider / connection helpers ─────────────────────────────────────────────
async def _get_api_url(provider_type: str, name: str) -> str:
"""Resolve the computer-server API URL for the target sandbox."""
if provider_type == "host":
return "http://localhost:8000"
if provider_type == "local":
from cua_sandbox import sandbox_state
state = sandbox_state.load(name)
if not state:
raise ValueError(f"Local sandbox '{name}' not found. Check ~/.cua/sandboxes/")
return f"http://{state['host']}:{state['api_port']}"
if provider_type in ("cloud", "cloudv2"):
from cua_cli.auth.store import get_api_key
from cua_sandbox.transport.cloud import CloudTransport, cloud_get_vm
api_key = get_api_key()
if not api_key:
raise ValueError("Not authenticated. Run 'cua auth login' first")
vm = await cloud_get_vm(name, api_key=api_key)
if not vm:
raise ValueError(f"VM not found: {name}")
return CloudTransport._resolve_endpoint(vm)
# Legacy local provider types — map to sandbox state file lookup
if provider_type in ("lume", "lumier", "docker", "winsandbox"):
from cua_sandbox import sandbox_state
state = sandbox_state.load(name)
if state:
return f"http://{state['host']}:{state['api_port']}"
return "http://localhost:8000"
raise ValueError(f"Unknown provider: {provider_type}")
async def _host_dispatch(command: str, params: dict) -> dict:
"""Dispatch a computer-server command to the local host via cua_auto."""
try:
import cua_auto.keyboard as _kb
import cua_auto.mouse as _mouse
import cua_auto.screen as _screen
import cua_auto.shell as _shell
import cua_auto.window as _win
except ImportError as e:
return {
"success": False,
"error": f"cua-auto not installed: {e}. Run: pip install cua-auto",
}
try:
if command == "screenshot":
b64 = _screen.screenshot_b64()
return {"success": True, "image_data": b64}
elif command == "get_screen_size":
w, h = _screen.screen_size()
return {"success": True, "size": {"width": w, "height": h}}
elif command == "get_cursor_position":
x, y = _screen.cursor_position()
return {"success": True, "position": {"x": x, "y": y}}
elif command == "get_current_window_id":
handle = _win.get_active_window_handle()
if not handle:
return {"success": False, "error": "No active window"}
return {"success": True, "window_id": handle}
elif command == "get_window_name":
title = _win.get_window_name(params.get("window_id", ""))
if title is None:
return {"success": False, "error": "Window not found"}
return {"success": True, "name": title}
elif command == "get_application_windows":
handles = _win.get_windows_with_title(params.get("app", ""))
return {"success": True, "windows": handles}
elif command == "get_window_size":
result = _win.get_window_size(params.get("window_id", ""))
if result is None:
return {"success": False, "error": "Window not found"}
return {"success": True, "size": [result[0], result[1]]}
elif command == "get_window_position":
result = _win.get_window_position(params.get("window_id", ""))
if result is None:
return {"success": False, "error": "Window not found"}
return {"success": True, "position": [result[0], result[1]]}
elif command == "left_click":
_mouse.click(int(params["x"]), int(params["y"]))
return {"success": True}
elif command == "right_click":
_mouse.right_click(int(params["x"]), int(params["y"]))
return {"success": True}
elif command == "middle_click":
_mouse.click(int(params["x"]), int(params["y"]), "middle")
return {"success": True}
elif command == "double_click":
_mouse.double_click(int(params["x"]), int(params["y"]))
return {"success": True}
elif command == "move_cursor":
_mouse.move_to(int(params["x"]), int(params["y"]))
return {"success": True}
elif command == "mouse_down":
x = params.get("x")
y = params.get("y")
_mouse.mouse_down(
int(x) if x is not None else None,
int(y) if y is not None else None,
params.get("button", "left"),
)
return {"success": True}
elif command == "mouse_up":
x = params.get("x")
y = params.get("y")
_mouse.mouse_up(
int(x) if x is not None else None,
int(y) if y is not None else None,
params.get("button", "left"),
)
return {"success": True}
elif command == "scroll_direction":
direction = params.get("direction", "down")
clicks = int(params.get("clicks", 3))
if direction == "up":
_mouse.scroll_up(clicks)
elif direction == "down":
_mouse.scroll_down(clicks)
elif direction == "left":
_mouse.scroll_left(clicks)
elif direction == "right":
_mouse.scroll_right(clicks)
return {"success": True}
elif command == "drag_to":
_mouse.drag(
int(params["start_x"]),
int(params["start_y"]),
int(params["end_x"]),
int(params["end_y"]),
)
return {"success": True}
elif command == "type_text":
_kb.type_text(params.get("text", ""))
return {"success": True}
elif command == "press_key":
_kb.press_key(params.get("key", ""))
return {"success": True}
elif command == "key_down":
_kb.key_down(params.get("key", ""))
return {"success": True}
elif command == "key_up":
_kb.key_up(params.get("key", ""))
return {"success": True}
elif command == "hotkey":
keys = params.get("keys", [])
if isinstance(keys, str):
keys = [k.strip() for k in keys.replace("-", "+").split("+") if k.strip()]
_kb.hotkey(keys)
return {"success": True}
elif command == "run_command":
result = _shell.run(params.get("command", ""))
return {
"success": True,
"stdout": result.stdout,
"stderr": result.stderr,
"returncode": result.returncode,
}
elif command == "open":
_win.open(params.get("path") or params.get("target", ""))
return {"success": True}
elif command == "launch":
pid = _win.launch(params.get("app", ""), params.get("args"))
return {"success": True, "pid": pid}
elif command == "activate_window":
ok = _win.activate_window(params.get("window_id", ""))
return {"success": bool(ok)}
elif command == "minimize_window":
ok = _win.minimize_window(params.get("window_id", ""))
return {"success": bool(ok)}
elif command == "maximize_window":
ok = _win.maximize_window(params.get("window_id", ""))
return {"success": bool(ok)}
elif command == "close_window":
ok = _win.close_window(params.get("window_id", ""))
return {"success": bool(ok)}
elif command == "set_window_size":
ok = _win.set_window_size(
params["window_id"], int(params["width"]), int(params["height"])
)
return {"success": bool(ok)}
elif command == "set_window_position":
ok = _win.set_window_position(params["window_id"], int(params["x"]), int(params["y"]))
return {"success": bool(ok)}
elif command == "deactivate_window":
return {"success": False, "error": "deactivate_window not supported on host"}
else:
return {"success": False, "error": f"Unknown host command: {command}"}
except Exception as e:
return {"success": False, "error": str(e)}
async def _send(provider_type: str, name: str, command: str, params: dict) -> dict:
"""Send a command to the computer-server and return the parsed response."""
if provider_type == "host":
return await _host_dispatch(command, params)
import aiohttp
from core.http import cua_version_headers
api_url = await _get_api_url(provider_type, name)
headers = {"Content-Type": "application/json", **cua_version_headers()}
if provider_type in ("cloud", "cloudv2"):
from cua_cli.auth.store import get_api_key
api_key = get_api_key()
if api_key:
headers["X-API-Key"] = api_key
if name:
headers["X-Container-Name"] = name
async with aiohttp.ClientSession() as session:
async with session.post(
f"{api_url}/cmd",
json={"command": command, "params": params},
headers=headers,
timeout=aiohttp.ClientTimeout(total=30),
) as resp:
text = await resp.text()
for line in text.splitlines():
if line.startswith("data: "):
return json.loads(line[6:])
try:
return json.loads(text)
except Exception:
return {"success": False, "error": f"Unexpected response: {text[:200]}"}
# ── zoom / screenshot helpers ─────────────────────────────────────────────────
async def _resolve_zoom_bbox_by_id(provider_type: str, name: str, window_id: str) -> dict | None:
"""Get the bounding box of a window by its native handle/id."""
pos_r = await _send(provider_type, name, "get_window_position", {"window_id": window_id})
size_r = await _send(provider_type, name, "get_window_size", {"window_id": window_id})
pos = pos_r.get("position") or pos_r.get("data")
size = size_r.get("size") or size_r.get("data")
if not pos or not size:
return None
if isinstance(pos, (list, tuple)):
x, y = int(pos[0]), int(pos[1])
else:
x, y = int(pos.get("x", 0)), int(pos.get("y", 0))
if isinstance(size, (list, tuple)):
w, h = int(size[0]), int(size[1])
else:
w, h = int(size.get("width", 0)), int(size.get("height", 0))
return {"x": x, "y": y, "width": w, "height": h}
async def _resolve_zoom_bbox(provider_type: str, name: str, window_name: str) -> dict | None:
"""Get the bounding box of a window by app/window name.
Filters out internal helper windows (e.g. 'Chrome Legacy Window') so the
correct top-level window is always selected.
"""
wins_r = await _send(provider_type, name, "get_application_windows", {"app": window_name})
windows = wins_r.get("windows") or wins_r.get("data") or []
if not windows:
return None
# Pick the first window whose title is not an internal helper
window_id = None
for wid in windows:
try:
name_r = await _send(provider_type, name, "get_window_name", {"window_id": wid})
title = name_r.get("name") or ""
if title not in _SKIP_WINDOW_TITLES:
window_id = wid
break
except Exception:
pass
if window_id is None:
window_id = windows[0]
return await _resolve_zoom_bbox_by_id(provider_type, name, window_id)
async def _take_screenshot_data(
provider_type: str, name: str, state: dict
) -> tuple[bytes, float, dict | None]:
"""Take screenshot, apply zoom crop and max-length scaling.
Returns (image_bytes, display_scale, zoom_bbox).
display_scale < 1.0 means the image was shrunk; bbox is None if not zoomed.
"""
from PIL import Image
result = await _send(provider_type, name, "screenshot", {})
img_b64 = result.get("image_data") or result.get("data")
if not img_b64:
raise RuntimeError(result.get("error", "no image data returned"))
img = Image.open(io.BytesIO(base64.b64decode(img_b64)))
zoom_window = state.get("zoom_window")
zoom_window_id = state.get("zoom_window_id")
bbox: dict | None = None
if zoom_window:
try:
if zoom_window_id:
bbox = await _resolve_zoom_bbox_by_id(provider_type, name, str(zoom_window_id))
if not bbox:
bbox = await _resolve_zoom_bbox(provider_type, name, zoom_window)
if bbox:
img = img.crop(
(
bbox["x"],
bbox["y"],
bbox["x"] + bbox["width"],
bbox["y"] + bbox["height"],
)
)
except Exception:
bbox = None # fall back to full screen
w, h = img.size
scale = 1.0
if max(w, h) > MAX_LENGTH:
scale = MAX_LENGTH / max(w, h)
img = img.resize((int(w * scale), int(h * scale)), Image.LANCZOS)
buf = io.BytesIO()
img.save(buf, format="PNG")
return buf.getvalue(), scale, bbox
def _coords(x: int, y: int, state: dict) -> tuple[int, int]:
"""Translate image-space (x, y) to screen-space coordinates.
Accounts for:
- display_scale: image was scaled for output (divide to get original pixels)
- zoom_bbox: image was cropped, add offset to get screen coords
"""
zoom_scale: float = state.get("zoom_scale", 1.0) or 1.0
zoom_bbox: dict | None = state.get("zoom_bbox")
sx = round(x / zoom_scale)
sy = round(y / zoom_scale)
if zoom_bbox:
sx += zoom_bbox["x"]
sy += zoom_bbox["y"]
return sx, sy
async def _maybe_focus_zoom(provider_type: str, name: str, state: dict) -> None:
"""If a zoom window is tracked, bring it to focus before performing an action."""
window_id = state.get("zoom_window_id")
if window_id:
try:
await _send(provider_type, name, "activate_window", {"window_id": window_id})
except Exception:
pass
async def _print_context(provider_type: str, name: str, state: dict | None = None) -> None:
"""Print the VM + zoom context line after a command."""
vm_label = name if name else provider_type
if state is None:
state = _load_state()
zoom_window = state.get("zoom_window")
zoom_window_id = state.get("zoom_window_id")
if zoom_window:
zoom_info = (
f"zoom: {zoom_window} ({zoom_window_id})" if zoom_window_id else f"zoom: {zoom_window}"
)
else:
zoom_info = "zoom: off"
print(f"💻 {vm_label}\t🔍 {zoom_info}")
async def _take_screenshot_for_recording(
provider_type: str, name: str, state: dict
) -> bytes | None:
"""Silently take a screenshot for trajectory recording. Returns None on failure."""
try:
img_bytes, _, _ = await _take_screenshot_data(provider_type, name, state)
return img_bytes
except Exception:
return None
def _maybe_record_turn(
args: argparse.Namespace,
state: dict,
action_type: str,
action_params: dict,
screenshot_bytes: bytes | None = None,
) -> None:
"""Record a trajectory turn if recording is enabled. Never raises."""
if getattr(args, "no_record", False):
return
try:
from cua_cli.utils.trajectory_recorder import ensure_session, record_turn
session_dir = ensure_session(state)
record_turn(session_dir, action_type, action_params, screenshot_bytes)
except Exception:
pass # Never interfere with the primary command
def _require_target() -> dict | None:
state = _load_state()
if not state.get("provider"):
_fail("No VM selected. Run: cua do switch <provider> [name]")
return None
return state
# ── subcommand handlers ───────────────────────────────────────────────────────
def _cmd_switch(args: argparse.Namespace) -> int:
provider = args.provider.lower()
old_state = _load_state()
had_zoom = bool(old_state.get("zoom_window"))
if provider == "host":
if not _host_consented():
print(
"❌ Warning: you are about to allow an AI to control your host PC directly.\n"
" This grants full keyboard, mouse, and screen access to your local desktop.\n"
" To continue, please run: cua do-host-consent",
file=sys.stderr,
)
return 1
_save_state(
{
"provider": "host",
"name": "",
"zoom_window": None,
"zoom_window_id": None,
"zoom_bbox": None,
"zoom_scale": 1.0,
}
)
try:
from cua_cli.utils.trajectory_recorder import reset_session
reset_session(_load_state())
except Exception:
pass
msg = "Switched to host (local PC)"
if had_zoom:
msg += " — zoom reset"
return _ok(msg)
if provider not in PROVIDERS:
return _fail(f"Unknown provider '{provider}'. Choose from: {', '.join(PROVIDERS)}")
name = args.name or ""
_save_state(
{
"provider": provider,
"name": name,
"zoom_window": None,
"zoom_window_id": None,
"zoom_bbox": None,
"zoom_scale": 1.0,
}
)
try:
from cua_cli.utils.trajectory_recorder import reset_session
reset_session(_load_state())
except Exception:
pass
label = f"{provider}/{name}" if name else provider
msg = f"Switched to {label}"
if had_zoom:
msg += " — zoom reset"
return _ok(msg)
def _cmd_status(args: argparse.Namespace) -> int:
state = _load_state()
provider = state.get("provider")
if not provider:
return _fail("No VM selected. Run: cua do switch <provider> [name]")
name = state.get("name", "")
label = f"{provider}/{name}" if name else provider
zoom = state.get("zoom_window")
zoom_info = f" [zoomed to '{zoom}']" if zoom else ""
return _ok(f"Current target: {label}{zoom_info}")
def _cmd_ls(args: argparse.Namespace) -> int:
from cua_cli.utils.async_utils import run_async
explicit_provider = getattr(args, "provider", None)
async def _list_all() -> int:
from cua_cli.auth.store import get_api_key
from cua_sandbox import Sandbox
print(" host [local]")
try:
local_sandboxes = await Sandbox.list(local=True)
for s in local_sandboxes:
print(f" {s.name} [{s.status}] {s.source}")
except Exception:
pass
try:
api_key = get_api_key()
if api_key:
cloud_sandboxes = await Sandbox.list(local=False, api_key=api_key)
for s in cloud_sandboxes:
print(f" {s.name} [{s.status}] cloud")
except Exception:
pass
return 0
async def _list_one(ptype: str) -> int:
from cua_cli.auth.store import get_api_key
from cua_sandbox import Sandbox
if ptype == "host":
print(" host [local]")
return 0
local = ptype in ("local", "lume", "lumier", "docker", "winsandbox")
try:
api_key = None if local else get_api_key()
sandboxes = await Sandbox.list(local=local, api_key=api_key)
if not sandboxes:
print(f"No sandboxes found for provider '{ptype}'")
return 0
for s in sandboxes:
print(f" {s.name} [{s.status}]")
except Exception as e:
return _fail(str(e))
return 0
if explicit_provider:
return run_async(_list_one(explicit_provider.lower()))
else:
return run_async(_list_all())
def _cmd_zoom(args: argparse.Namespace) -> int:
from cua_cli.utils.async_utils import run_async
t = _require_target()
if not t:
return 1
window_name = args.window_name
async def _run() -> int:
state = _load_state()
p, n = state["provider"], state.get("name", "")
try:
wins_r = await _send(p, n, "get_application_windows", {"app": window_name})
windows = wins_r.get("windows") or wins_r.get("data") or []
if not windows:
return _fail(f"No windows found matching '{window_name}'")
# Fetch titles and filter out internal helper windows
candidates = []
for wid in windows:
name_r = await _send(p, n, "get_window_name", {"window_id": wid})
title = name_r.get("name") or str(wid)
if title not in _SKIP_WINDOW_TITLES:
candidates.append((wid, title))
if not candidates:
return _fail(f"No windows found matching '{window_name}'")
if len(candidates) > 1:
labels = [f"{wid} ({title})" for wid, title in candidates]
return _fail(
f"Multiple windows matched '{window_name}' — be more specific. "
f"Found: {', '.join(labels)}"
)
wid, matched_title = candidates[0]
except Exception:
wid, matched_title = None, window_name # resolution failed, still set zoom
_update_state(zoom_window=window_name, zoom_window_id=wid, zoom_bbox=None, zoom_scale=1.0)
id_suffix = f" ({wid})" if wid else ""
return _ok(f"Zoomed to '{matched_title}'{id_suffix}")
return run_async(_run())
def _cmd_unzoom(args: argparse.Namespace) -> int:
_update_state(zoom_window=None, zoom_window_id=None, zoom_bbox=None, zoom_scale=1.0)
return _ok("Unzoomed — full screen")
def _cmd_screenshot(args: argparse.Namespace) -> int:
from cua_cli.utils.async_utils import run_async
t = _require_target()
if not t:
return 1
async def _run() -> int:
state = _load_state()
try:
img_bytes, scale, bbox = await _take_screenshot_data(
state["provider"], state.get("name", ""), state
)
except Exception as e:
await _print_context(state["provider"], state.get("name", ""), state)
return _fail(str(e))
# Persist zoom state for coordinate translation
_update_state(zoom_scale=scale, zoom_bbox=bbox)
save_path = getattr(args, "save", None)
if not save_path:
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
save_path = f"{tempfile.gettempdir()}/cua_screenshot_{ts}.png"
with open(save_path, "wb") as f:
f.write(img_bytes)
_maybe_record_turn(args, state, "screenshot", {}, img_bytes)
rc = _ok(f"screenshot saved to {save_path}")
await _print_context(state["provider"], state.get("name", ""), state)
return rc
return run_async(_run())
def _cmd_snapshot(args: argparse.Namespace) -> int:
from cua_cli.utils.async_utils import run_async
t = _require_target()
if not t:
return 1
extra = " ".join(args.instructions) if args.instructions else ""
async def _run() -> int:
state = _load_state()
try:
img_bytes, scale, bbox = await _take_screenshot_data(
state["provider"], state.get("name", ""), state
)
except Exception as e:
await _print_context(state["provider"], state.get("name", ""), state)
return _fail(str(e))
_update_state(zoom_scale=scale, zoom_bbox=bbox)
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
save_path = f"{tempfile.gettempdir()}/cua_snapshot_{ts}.png"
with open(save_path, "wb") as f:
f.write(img_bytes)
api_key = os.environ.get("ANTHROPIC_API_KEY")
if not api_key:
await _print_context(state["provider"], state.get("name", ""), state)
return _fail("ANTHROPIC_API_KEY not set")
try:
import anthropic as _anthropic
client = _anthropic.Anthropic(api_key=api_key)
prompt = (
"You are analyzing a screenshot for an AI agent.\n"
"1. Write a 1-2 sentence summary of what is currently on screen.\n"
"2. List every interactive element visible (buttons, links, inputs, "
"menus, checkboxes, dropdowns, etc.) with its center coordinates "
"in image pixels (origin = top-left). Be precise."
)
if extra:
prompt += f"\nAdditional instructions: {extra}"
screenshot_analysis_tool = {
"name": "screenshot_analysis",
"description": "Report the analysis of the screenshot, including a summary and all interactive elements.",
"input_schema": {
"type": "object",
"properties": {
"summary": {
"type": "string",
"description": "1-2 sentence summary of what is currently on screen",
},
"elements": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {"type": "string", "description": "Element label or text"},
"type": {"type": "string", "description": "Element type (button, link, input, etc.)"},
"x": {"type": "integer", "description": "Center X coordinate in pixels"},
"y": {"type": "integer", "description": "Center Y coordinate in pixels"},
},
"required": ["name", "type", "x", "y"],
},
"description": "All interactive elements visible on screen",
},
},
"required": ["summary", "elements"],
},
}
img_b64 = base64.b64encode(img_bytes).decode()
response = client.messages.create(
model="claude-haiku-4-5-20251001",
max_tokens=1024,
tools=[screenshot_analysis_tool],
tool_choice={"type": "tool", "name": "screenshot_analysis"},
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/png",
"data": img_b64,
},
},
{"type": "text", "text": prompt},
],
}
],
)
# Extract the tool use result — guaranteed valid JSON matching the schema
tool_block = next(b for b in response.content if b.type == "tool_use")
parsed = tool_block.input
summary = parsed.get("summary", "")
elements = parsed.get("elements", [])
print(f"✅ snapshot — {save_path}")
print()
print(summary)
if elements:
print()
print("Interactive elements:")
for el in elements:
print(
f" • {el.get('name', '?')} [{el.get('type', '?')}] ({el.get('x', '?')}, {el.get('y', '?')})"
)
except ImportError:
await _print_context(state["provider"], state.get("name", ""), state)
return _fail("'anthropic' package not installed. Run: pip install anthropic")
except Exception as e:
await _print_context(state["provider"], state.get("name", ""), state)
return _fail(f"AI analysis failed: {e}")
await _print_context(state["provider"], state.get("name", ""), state)
return 0
return run_async(_run())
def _cmd_click(args: argparse.Namespace) -> int:
from cua_cli.utils.async_utils import run_async
t = _require_target()
if not t:
return 1
button = getattr(args, "button", "left") or "left"
cmd_map = {"left": "left_click", "right": "right_click", "middle": "middle_click"}
cmd = cmd_map.get(button, "left_click")
async def _run() -> int:
state = _load_state()
p, n = state["provider"], state.get("name", "")
await _maybe_focus_zoom(p, n, state)
sx, sy = _coords(args.x, args.y, state)
try:
result = await _send(p, n, cmd, {"x": sx, "y": sy})
except Exception as e:
await _print_context(p, n, state)
return _fail(str(e))
if not result.get("success", True):
await _print_context(p, n, state)
return _fail(result.get("error", "click failed"))
_scr = await _take_screenshot_for_recording(p, n, state)
_maybe_record_turn(args, state, "click", {"x": args.x, "y": args.y}, _scr)
rc = _ok(f"clicked ({args.x}, {args.y}) [{button}]")
await _print_context(p, n, state)
return rc
return run_async(_run())
def _cmd_dclick(args: argparse.Namespace) -> int:
from cua_cli.utils.async_utils import run_async
t = _require_target()
if not t:
return 1
async def _run() -> int:
state = _load_state()
p, n = state["provider"], state.get("name", "")
await _maybe_focus_zoom(p, n, state)
sx, sy = _coords(args.x, args.y, state)
try:
result = await _send(p, n, "double_click", {"x": sx, "y": sy})
except Exception as e:
await _print_context(p, n, state)
return _fail(str(e))
if not result.get("success", True):
await _print_context(p, n, state)
return _fail(result.get("error", "double-click failed"))
_scr = await _take_screenshot_for_recording(p, n, state)
_maybe_record_turn(args, state, "double_click", {"x": args.x, "y": args.y}, _scr)
rc = _ok(f"double-clicked ({args.x}, {args.y})")
await _print_context(p, n, state)
return rc
return run_async(_run())
def _cmd_move(args: argparse.Namespace) -> int:
from cua_cli.utils.async_utils import run_async
t = _require_target()
if not t:
return 1
async def _run() -> int:
state = _load_state()
p, n = state["provider"], state.get("name", "")
await _maybe_focus_zoom(p, n, state)
sx, sy = _coords(args.x, args.y, state)
try:
result = await _send(p, n, "move_cursor", {"x": sx, "y": sy})
except Exception as e:
await _print_context(p, n, state)
return _fail(str(e))
if not result.get("success", True):
await _print_context(p, n, state)
return _fail(result.get("error", "move failed"))
_maybe_record_turn(args, state, "move", {"x": args.x, "y": args.y})
rc = _ok(f"cursor moved to ({args.x}, {args.y})")
await _print_context(p, n, state)
return rc
return run_async(_run())
def _cmd_type(args: argparse.Namespace) -> int:
from cua_cli.utils.async_utils import run_async
t = _require_target()
if not t:
return 1
async def _run() -> int:
state = _load_state()
p, n = state["provider"], state.get("name", "")
await _maybe_focus_zoom(p, n, state)
try:
result = await _send(p, n, "type_text", {"text": args.text})
except Exception as e:
await _print_context(p, n, state)
return _fail(str(e))
if not result.get("success", True):
await _print_context(p, n, state)
return _fail(result.get("error", "type failed"))
_scr = await _take_screenshot_for_recording(p, n, state)
_maybe_record_turn(args, state, "type", {"text": args.text}, _scr)