-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
1400 lines (1235 loc) · 52.2 KB
/
Copy pathserver.py
File metadata and controls
1400 lines (1235 loc) · 52.2 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
"""
GBOX Local API Server
Implements gbox.ai UI Action, Command, and File System APIs locally using pyautogui.
Listens on 0.0.0.0:5789
"""
import base64
import io
import json
import logging
import os
import platform
import re
import shutil
import subprocess
import time
import uuid
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional
import traceback
import pyautogui
import pyperclip
from flask import Flask, jsonify, make_response, request
from PIL import Image
from PIL import PngImagePlugin # noqa: force-load PNG plugin at import time so PyInstaller bundles it eagerly
try:
import mss
except ImportError:
mss = None
app = Flask(__name__)
app.config["PROPAGATE_EXCEPTIONS"] = True
try:
import _version
GIT_COMMIT = _version.GIT_COMMIT
except Exception:
GIT_COMMIT = "unknown"
pyautogui.PAUSE = 0.05
pyautogui.FAILSAFE = False
platform_name = platform.system() # noqa
def _json_500(msg: str, tb: str = None):
"""Return a 500 response with JSON body; always used for errors."""
body = {"error": msg}
if tb:
body["traceback"] = tb
resp = make_response(json.dumps(body, ensure_ascii=False), 500)
resp.headers["Content-Type"] = "application/json; charset=utf-8"
return resp
@app.errorhandler(500)
def handle_500(e):
"""Ensure 500 responses are always JSON."""
traceback.print_exc()
logging.exception("Unhandled error")
try:
msg = str(e) if e else "Internal server error"
except Exception:
msg = "Internal server error"
return _json_500(msg, traceback.format_exc())
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _new_action_id() -> str:
return str(uuid.uuid4())
def _parse_duration_ms(s, default_ms: int = 500) -> float:
"""Parse a duration string like '500ms', '1s', '2m', '1h' into seconds."""
if s is None:
return default_ms / 1000.0
s = str(s).strip()
m = re.fullmatch(r"(\d+(?:\.\d+)?)\s*(ms|s|m|h)", s, re.IGNORECASE)
if not m:
return default_ms / 1000.0
value, unit = float(m.group(1)), m.group(2).lower()
if unit == "ms":
return value / 1000.0
elif unit == "s":
return value
elif unit == "m":
return value * 60
else:
return value * 3600
def _take_screenshot_b64(clip=None) -> str:
"""Take a screenshot and return as base64-encoded PNG data URI. (legacy wrapper)"""
png_bytes = _take_screenshot_buf(clip)
b64 = base64.b64encode(png_bytes).decode()
return f"data:image/png;base64,{b64}"
def _get_screenshot_phases(options: dict) -> list:
if not options:
return []
sc = options.get("screenshot")
if sc is None or sc is False:
return []
if sc is True:
return ["before", "after"]
if isinstance(sc, dict):
return sc.get("phases", ["before", "after"])
return []
def _get_screenshot_delay(options: dict) -> float:
if not options:
return 0.5
sc = options.get("screenshot")
if isinstance(sc, dict):
return _parse_duration_ms(sc.get("delay", "500ms"), 500)
return 0.5
def _action_result(action_id: str, options=None,
before_uri: Optional[str] = None,
after_uri: Optional[str] = None) -> dict:
result = {
"message": "Action executed successfully",
"actionId": action_id,
}
if before_uri or after_uri:
sc = {}
if before_uri:
sc["before"] = {"uri": before_uri}
if after_uri:
sc["after"] = {"uri": after_uri}
result["screenshot"] = sc
return result
KEY_MAP = {
"arrowUp": "up", "arrowDown": "down", "arrowLeft": "left", "arrowRight": "right",
"escape": "esc", "backspace": "backspace", "delete": "delete",
"enter": "enter", "space": "space", "tab": "tab",
"home": "home", "end": "end", "pageUp": "pageup", "pageDown": "pagedown",
"insert": "insert", "capsLock": "capslock", "numLock": "numlock",
"scrollLock": "scrolllock", "pause": "pause", "printScreen": "printscreen",
"meta": "win", "win": "win", "cmd": "win", "option": "alt",
"control": "ctrl", "shift": "shift", "alt": "alt",
"numpad0": "num0", "numpad1": "num1", "numpad2": "num2", "numpad3": "num3",
"numpad4": "num4", "numpad5": "num5", "numpad6": "num6", "numpad7": "num7",
"numpad8": "num8", "numpad9": "num9",
"numpadAdd": "add", "numpadSubtract": "subtract",
"numpadMultiply": "multiply", "numpadDivide": "divide",
"numpadDecimal": "decimal", "numpadEnter": "enter", "numpadEqual": "=",
"volumeUp": "volumeup", "volumeDown": "volumedown", "volumeMute": "volumemute",
"mediaPlayPause": "playpause", "mediaStop": "stop",
"mediaNextTrack": "nexttrack", "mediaPreviousTrack": "prevtrack",
}
def _map_key(k: str) -> str:
return KEY_MAP.get(k, k)
def _file_info(path: str) -> dict:
p = Path(path)
stat = p.stat()
modified = datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc).isoformat()
try:
mode = oct(stat.st_mode)[-3:]
except Exception:
mode = "644"
if p.is_dir():
return {
"type": "directory",
"name": p.name,
"path": str(p).replace("\\", "/") + "/",
"mode": mode,
"modified": modified,
}
size_bytes = stat.st_size
if size_bytes < 1024:
size_str = f"{size_bytes}B"
elif size_bytes < 1024 * 1024:
size_str = f"{size_bytes / 1024:.1f}KB"
elif size_bytes < 1024 * 1024 * 1024:
size_str = f"{size_bytes / (1024 * 1024):.1f}MB"
else:
size_str = f"{size_bytes / (1024 * 1024 * 1024):.1f}GB"
return {
"type": "file",
"name": p.name,
"path": str(p).replace("\\", "/"),
"size": size_str,
"mode": mode,
"modified": modified,
}
def _resolve_path(path: str, working_dir: Optional[str] = None) -> str:
if os.path.isabs(path):
return path
base = working_dir or os.getcwd()
return os.path.join(base, path)
def _parse_timeout(timeout_str, default_s: float = 30.0) -> float:
if timeout_str is None:
return default_s
# Plain integer string (e.g. "30000") is treated as milliseconds
try:
return float(timeout_str) / 1000.0
except (ValueError, TypeError):
pass
return _parse_duration_ms(timeout_str, int(default_s * 1000))
# ---------------------------------------------------------------------------
# UI Action Routes /api/v1/actions/*
# ---------------------------------------------------------------------------
def _take_screenshot_buf(clip=None) -> bytes:
"""Take a screenshot and return raw PNG bytes.
Prefer mss when available: it writes PNG natively via its own zlib path,
avoiding the lazy PIL plugin import that can fail in PyInstaller bundles
with a zlib decompression error (corrupted archive entry).
"""
if mss is not None:
with mss.mss() as sct:
monitor = sct.monitors[0]
if clip:
region = {
"left": int(clip.get("x", 0)),
"top": int(clip.get("y", 0)),
"width": int(clip.get("width", monitor["width"])),
"height": int(clip.get("height", monitor["height"])),
}
shot = sct.grab(region)
else:
shot = sct.grab(monitor)
return mss.tools.to_png(shot.rgb, shot.size)
# Fallback: use pyautogui + PIL (requires PngImagePlugin to be importable)
img = pyautogui.screenshot()
if clip:
x = int(clip.get("x", 0))
y = int(clip.get("y", 0))
w = int(clip.get("width", img.width))
h = int(clip.get("height", img.height))
img = img.crop((x, y, x + w, y + h))
buf = io.BytesIO()
img.save(buf, format="PNG")
return buf.getvalue()
def _put_to_presigned_url(png_bytes: bytes, presigned_put_url: str) -> None:
"""Upload PNG bytes to a presigned S3 PUT URL."""
import urllib.request
req = urllib.request.Request(
presigned_put_url,
data=png_bytes,
method="PUT",
headers={"Content-Type": "image/png", "Content-Length": str(len(png_bytes))},
)
with urllib.request.urlopen(req, timeout=30) as resp:
if resp.status not in (200, 204):
raise RuntimeError(f"Presigned PUT failed with HTTP {resp.status}")
@app.route("/api/v1/actions/screenshot", methods=["POST"])
def action_screenshot():
import sys; print('[screenshot] request received', flush=True); sys.stdout.flush(); sys.stderr.flush()
try:
data = request.get_json(silent=True) or {}
# transferFormat: "base64" (default) or "storageKey"
transfer_format = data.get("transferFormat", "base64")
presigned_put_url = data.get("presignedPutUrl")
storage_key = data.get("storageKey")
clip = data.get("clip")
png_bytes = _take_screenshot_buf(clip)
if transfer_format == "storageKey" and presigned_put_url:
# Upload directly to S3 via presigned PUT URL
_put_to_presigned_url(png_bytes, presigned_put_url)
return jsonify({
"storageKey": storage_key,
"outputFormat": "storageKey",
})
else:
# Return as base64 (raw, no data URI prefix so caller can build it)
image_b64 = base64.b64encode(png_bytes).decode()
return jsonify({
"uri": f"data:image/png;base64,{image_b64}",
"outputFormat": "base64",
})
except Exception as e:
traceback.print_exc()
logging.exception("screenshot failed")
try:
msg = str(e)
except Exception:
msg = "Screenshot failed"
return _json_500(msg, traceback.format_exc())
@app.route("/api/v1/actions/click", methods=["POST"])
def action_click():
data = request.get_json(silent=True) or {}
action_id = _new_action_id()
options = data.get("options")
phases = _get_screenshot_phases(options)
delay = _get_screenshot_delay(options)
before_uri = _take_screenshot_b64() if "before" in phases else None
x = data.get("x")
y = data.get("y")
if x is None or y is None:
return jsonify({"error": "x and y coordinates are required"}), 400
button = data.get("button", "left")
# Support both 'clicks' (click count, from remote service) and 'double' (legacy boolean)
clicks_param = data.get("clicks")
double = data.get("double", False)
if clicks_param is not None:
click_count = int(clicks_param)
elif double:
click_count = 2
else:
click_count = 1
modifier_keys = data.get("modifierKeys", [])
pyautogui_button = "left" if button == "left" else ("right" if button == "right" else "middle")
mapped_modifiers = [_map_key(k) for k in modifier_keys]
for mod in mapped_modifiers:
pyautogui.keyDown(mod)
try:
if click_count == 2:
pyautogui.doubleClick(x=int(x), y=int(y), button=pyautogui_button)
elif click_count > 2:
pyautogui.click(x=int(x), y=int(y), button=pyautogui_button, clicks=click_count)
else:
pyautogui.click(x=int(x), y=int(y), button=pyautogui_button)
finally:
for mod in reversed(mapped_modifiers):
pyautogui.keyUp(mod)
if "after" in phases:
time.sleep(delay)
after_uri = _take_screenshot_b64()
else:
after_uri = None
result = _action_result(action_id, options, before_uri, after_uri)
result["actual"] = {"x": int(x), "y": int(y)}
return jsonify(result)
@app.route("/api/v1/actions/move", methods=["POST"])
def action_move():
data = request.get_json(silent=True) or {}
action_id = _new_action_id()
x = data.get("x")
y = data.get("y")
if x is None or y is None:
return jsonify({"error": "x and y are required"}), 400
options = data.get("options")
phases = _get_screenshot_phases(options)
delay = _get_screenshot_delay(options)
before_uri = _take_screenshot_b64() if "before" in phases else None
pyautogui.moveTo(int(x), int(y))
after_uri = None
if "after" in phases:
time.sleep(delay)
after_uri = _take_screenshot_b64()
return jsonify(_action_result(action_id, options, before_uri, after_uri))
@app.route("/api/v1/actions/type", methods=["POST"])
def action_type():
data = request.get_json(silent=True) or {}
action_id = _new_action_id()
text = data.get("text")
if text is None:
return jsonify({"error": "text is required"}), 400
mode = data.get("mode", "append")
press_enter = data.get("pressEnter", False)
options = data.get("options")
phases = _get_screenshot_phases(options)
delay = _get_screenshot_delay(options)
before_uri = _take_screenshot_b64() if "before" in phases else None
if mode == "replace":
pyautogui.hotkey("ctrl", "a")
time.sleep(0.05)
pyautogui.write(text, interval=0.01)
if press_enter:
pyautogui.press("enter")
after_uri = None
if "after" in phases:
time.sleep(delay)
after_uri = _take_screenshot_b64()
return jsonify(_action_result(action_id, options, before_uri, after_uri))
@app.route("/api/v1/actions/press-key", methods=["POST"])
def action_press_key():
data = request.get_json(silent=True) or {}
action_id = _new_action_id()
keys = data.get("keys", [])
if not keys:
return jsonify({"error": "keys is required"}), 400
combination = data.get("combination", True)
options = data.get("options")
phases = _get_screenshot_phases(options)
delay = _get_screenshot_delay(options)
before_uri = _take_screenshot_b64() if "before" in phases else None
mapped = [_map_key(k) for k in keys]
if combination and len(mapped) > 1:
pyautogui.hotkey(*mapped)
else:
for k in mapped:
pyautogui.press(k)
after_uri = None
if "after" in phases:
time.sleep(delay)
after_uri = _take_screenshot_b64()
return jsonify(_action_result(action_id, options, before_uri, after_uri))
@app.route("/api/v1/actions/scroll", methods=["POST"])
def action_scroll():
data = request.get_json(silent=True) or {}
action_id = _new_action_id()
options = data.get("options")
phases = _get_screenshot_phases(options)
delay = _get_screenshot_delay(options)
before_uri = _take_screenshot_b64() if "before" in phases else None
screen_w, screen_h = pyautogui.size()
if "scrollX" in data or "scrollY" in data:
# Absolute pixel delta mode: {x, y, scrollX, scrollY}
x = int(data.get("x", screen_w // 2))
y = int(data.get("y", screen_h // 2))
scroll_x = data.get("scrollX", 0)
scroll_y = data.get("scrollY", 0)
pyautogui.moveTo(x, y)
if scroll_y != 0:
clicks = int(scroll_y / 100 * 3)
if clicks == 0:
clicks = 1 if scroll_y > 0 else -1
pyautogui.scroll(clicks, x=x, y=y)
if scroll_x != 0:
clicks = int(scroll_x / 100 * 3)
if clicks == 0:
clicks = 1 if scroll_x > 0 else -1
pyautogui.hscroll(clicks, x=x, y=y)
actual = {"x": x, "y": y, "scrollX": scroll_x, "scrollY": scroll_y}
elif "direction" in data:
# Direction + click-count mode: {x, y, direction, clicks}
direction = data.get("direction", "up")
x = int(data.get("x", screen_w // 2))
y = int(data.get("y", screen_h // 2))
clicks_count = int(data.get("clicks", 3))
sx, sy = 0, 0
if direction == "up":
pyautogui.scroll(clicks_count, x=x, y=y)
sy = clicks_count * 100 // 3
elif direction == "down":
pyautogui.scroll(-clicks_count, x=x, y=y)
sy = -(clicks_count * 100 // 3)
elif direction == "left":
pyautogui.hscroll(-clicks_count, x=x, y=y)
sx = -(clicks_count * 100 // 3)
else: # right
pyautogui.hscroll(clicks_count, x=x, y=y)
sx = clicks_count * 100 // 3
actual = {"x": x, "y": y, "scrollX": sx, "scrollY": sy}
else:
# Legacy direction + distance mode
direction = data.get("direction", "up")
distance_raw = data.get("distance")
x = screen_w // 2
y = screen_h // 2
distance_map = {"tiny": 50, "short": 150, "medium": 300, "long": 600}
if distance_raw is None:
pixels = screen_h // 2
elif isinstance(distance_raw, str):
pixels = distance_map.get(distance_raw, 300)
else:
pixels = int(distance_raw)
clicks = max(1, pixels // 100 * 3)
sx, sy = 0, 0
if direction == "up":
pyautogui.scroll(clicks, x=x, y=y)
sy = pixels
elif direction == "down":
pyautogui.scroll(-clicks, x=x, y=y)
sy = -pixels
elif direction == "left":
pyautogui.hscroll(-clicks, x=x, y=y)
sx = -pixels
else:
pyautogui.hscroll(clicks, x=x, y=y)
sx = pixels
actual = {"x": x, "y": y, "scrollX": sx, "scrollY": sy}
after_uri = None
if "after" in phases:
time.sleep(delay)
after_uri = _take_screenshot_b64()
result = _action_result(action_id, options, before_uri, after_uri)
result["actual"] = actual
return jsonify(result)
@app.route("/api/v1/actions/drag", methods=["POST"])
def action_drag():
data = request.get_json(silent=True) or {}
action_id = _new_action_id()
options = data.get("options")
phases = _get_screenshot_phases(options)
delay_sec = _get_screenshot_delay(options)
before_uri = _take_screenshot_b64() if "before" in phases else None
if "path" in data:
path_points = data["path"]
if not path_points:
return jsonify({"error": "path must not be empty"}), 400
duration_str = data.get("duration", "50ms")
interval = _parse_duration_ms(duration_str, 50)
start = path_points[0]
pyautogui.mouseDown(x=int(start["x"]), y=int(start["y"]))
for pt in path_points[1:]:
pyautogui.moveTo(int(pt["x"]), int(pt["y"]), duration=interval)
end = path_points[-1]
pyautogui.mouseUp(x=int(end["x"]), y=int(end["y"]))
actual = {
"start": {"x": int(start["x"]), "y": int(start["y"])},
"end": {"x": int(end["x"]), "y": int(end["y"])},
"duration": duration_str,
}
elif "startX" in data or "startY" in data:
# Flat coordinate mode: {startX, startY, endX, endY, duration?}
sx = int(data.get("startX", 0))
sy = int(data.get("startY", 0))
ex = int(data.get("endX", 0))
ey = int(data.get("endY", 0))
duration_val = data.get("duration")
dur = (duration_val / 1000.0) if isinstance(duration_val, (int, float)) else _parse_duration_ms(duration_val, 500)
pyautogui.mouseDown(x=sx, y=sy)
pyautogui.moveTo(ex, ey, duration=dur)
pyautogui.mouseUp(x=ex, y=ey)
actual = {
"start": {"x": sx, "y": sy},
"end": {"x": ex, "y": ey},
"duration": str(duration_val or "500ms"),
}
else:
start = data.get("start")
end = data.get("end")
if not start or not end:
return jsonify({"error": "start and end are required"}), 400
if not isinstance(start, dict) or not isinstance(end, dict):
return jsonify({"error": "Natural language targets are not supported in local mode"}), 422
duration_str = data.get("duration", "500ms")
dur = _parse_duration_ms(duration_str, 500)
sx, sy = int(start["x"]), int(start["y"])
ex, ey = int(end["x"]), int(end["y"])
pyautogui.mouseDown(x=sx, y=sy)
pyautogui.moveTo(ex, ey, duration=dur)
pyautogui.mouseUp(x=ex, y=ey)
actual = {
"start": {"x": sx, "y": sy},
"end": {"x": ex, "y": ey},
"duration": duration_str,
}
after_uri = None
if "after" in phases:
time.sleep(delay_sec)
after_uri = _take_screenshot_b64()
result = _action_result(action_id, options, before_uri, after_uri)
result["actual"] = actual
return jsonify(result)
@app.route("/api/v1/actions/long-press", methods=["POST"])
def action_long_press():
data = request.get_json(silent=True) or {}
action_id = _new_action_id()
x = data.get("x")
y = data.get("y")
if x is None or y is None:
return jsonify({"error": "x and y are required"}), 400
duration_str = data.get("duration", "500ms")
dur = _parse_duration_ms(duration_str, 500)
options = data.get("options")
phases = _get_screenshot_phases(options)
delay = _get_screenshot_delay(options)
before_uri = _take_screenshot_b64() if "before" in phases else None
pyautogui.mouseDown(x=int(x), y=int(y))
time.sleep(dur)
pyautogui.mouseUp(x=int(x), y=int(y))
after_uri = None
if "after" in phases:
time.sleep(delay)
after_uri = _take_screenshot_b64()
result = _action_result(action_id, options, before_uri, after_uri)
result["actual"] = {"x": int(x), "y": int(y), "duration": duration_str}
return jsonify(result)
@app.route("/api/v1/actions/swipe", methods=["POST"])
def action_swipe():
data = request.get_json(silent=True) or {}
action_id = _new_action_id()
start = data.get("start")
end = data.get("end")
if not start or not end:
return jsonify({"error": "start and end are required"}), 400
if not isinstance(start, dict) or not isinstance(end, dict):
return jsonify({"error": "start and end must be coordinate objects"}), 400
duration_str = data.get("duration", "300ms")
dur = _parse_duration_ms(duration_str, 300)
options = data.get("options")
phases = _get_screenshot_phases(options)
delay = _get_screenshot_delay(options)
before_uri = _take_screenshot_b64() if "before" in phases else None
sx, sy = int(start["x"]), int(start["y"])
ex, ey = int(end["x"]), int(end["y"])
pyautogui.mouseDown(x=sx, y=sy)
pyautogui.moveTo(ex, ey, duration=dur)
pyautogui.mouseUp(x=ex, y=ey)
after_uri = None
if "after" in phases:
time.sleep(delay)
after_uri = _take_screenshot_b64()
result = _action_result(action_id, options, before_uri, after_uri)
result["actual"] = {"start": {"x": sx, "y": sy}, "end": {"x": ex, "y": ey}, "duration": duration_str}
return jsonify(result)
@app.route("/api/v1/actions/touch", methods=["POST"])
def action_touch():
"""Multi-touch simulation. Each point has a start position and a list of actions."""
data = request.get_json(silent=True) or {}
action_id = _new_action_id()
points = data.get("points", [])
if not points:
return jsonify({"error": "points is required"}), 400
options = data.get("options")
phases = _get_screenshot_phases(options)
delay = _get_screenshot_delay(options)
before_uri = _take_screenshot_b64() if "before" in phases else None
for point in points:
start = point.get("start", {})
cur_x = int(start.get("x", 0))
cur_y = int(start.get("y", 0))
pyautogui.moveTo(cur_x, cur_y)
for action in point.get("actions", []):
action_type = action.get("type", "")
if action_type == "move":
to_x = int(action.get("x", cur_x))
to_y = int(action.get("y", cur_y))
pyautogui.dragTo(to_x, to_y, duration=0.1, button="left")
cur_x, cur_y = to_x, to_y
elif action_type == "wait":
dur = _parse_duration_ms(action.get("duration", "100ms"), 100)
time.sleep(dur)
elif action_type == "click":
pyautogui.click(x=cur_x, y=cur_y)
after_uri = None
if "after" in phases:
time.sleep(delay)
after_uri = _take_screenshot_b64()
return jsonify(_action_result(action_id, options, before_uri, after_uri))
@app.route("/api/v1/actions/press-button", methods=["POST"])
def action_press_button():
"""Press device hardware buttons (volume up/down, etc.)."""
data = request.get_json(silent=True) or {}
action_id = _new_action_id()
buttons = data.get("buttons", data.get("button", []))
if not buttons:
return jsonify({"error": "buttons is required"}), 400
options = data.get("options")
phases = _get_screenshot_phases(options)
delay = _get_screenshot_delay(options)
before_uri = _take_screenshot_b64() if "before" in phases else None
BUTTON_KEY_MAP = {
"volumeUp": "volumeup",
"volumeDown": "volumedown",
"volumeMute": "volumemute",
"home": "win",
"back": "alt+left",
"menu": "apps",
}
for btn in buttons:
key = BUTTON_KEY_MAP.get(btn)
if key is None:
return jsonify({"error": f"Unsupported button: {btn}"}), 400
if "+" in key:
parts = key.split("+")
pyautogui.hotkey(*parts)
else:
pyautogui.press(key)
after_uri = None
if "after" in phases:
time.sleep(delay)
after_uri = _take_screenshot_b64()
return jsonify(_action_result(action_id, options, before_uri, after_uri))
@app.route("/api/v1/actions/screen-size", methods=["GET"])
def action_get_screen_size():
"""Return current screen resolution."""
w, h = pyautogui.size()
return jsonify({"width": w, "height": h})
@app.route("/api/v1/actions/screen-resolution", methods=["POST"])
def action_set_screen_resolution():
"""Set screen resolution via OS command (Windows only)."""
data = request.get_json(silent=True) or {}
width = data.get("width")
height = data.get("height")
if width is None or height is None:
return jsonify({"error": "width and height are required"}), 400
width, height = int(width), int(height)
if platform_name == "Windows":
# Use PowerShell to change display resolution
ps_script = (
f"Add-Type -AssemblyName System.Windows.Forms; "
f"$mode = [System.Windows.Forms.Screen]::PrimaryScreen; "
f"$dm = New-Object System.Management.ManagementObject('Win32_VideoController.DeviceID=\"VideoController1\"'); "
f"& {{ "
f" $signature = @'`n"
f"[DllImport(\"user32.dll\")] public static extern bool EnumDisplaySettings(string deviceName, int modeNum, ref DEVMODE devMode);`n"
f"[DllImport(\"user32.dll\")] public static extern int ChangeDisplaySettings(ref DEVMODE devMode, int flags);`n"
f"[StructLayout(LayoutKind.Sequential)] public struct DEVMODE {{ [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string dmDeviceName; public short dmSpecVersion; public short dmDriverVersion; public short dmSize; public short dmDriverExtra; public int dmFields; public int dmPositionX; public int dmPositionY; public int dmDisplayOrientation; public int dmDisplayFixedOutput; public short dmColor; public short dmDuplex; public short dmYResolution; public short dmTTOption; public short dmCollate; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string dmFormName; public short dmLogPixels; public int dmBitsPerPel; public int dmPelsWidth; public int dmPelsHeight; public int dmDisplayFlags; public int dmDisplayFrequency; }}`n"
f"'@`n"
f" Add-Type -MemberDefinition $signature -Name NativeMethods -Namespace Win32`n"
f" $dm = New-Object Win32.NativeMethods+DEVMODE`n"
f" $dm.dmSize = [System.Runtime.InteropServices.Marshal]::SizeOf($dm)`n"
f" [Win32.NativeMethods]::EnumDisplaySettings($null, -1, [ref]$dm) | Out-Null`n"
f" $dm.dmPelsWidth = {width}`n"
f" $dm.dmPelsHeight = {height}`n"
f" $dm.dmFields = 0x180000`n"
f" $result = [Win32.NativeMethods]::ChangeDisplaySettings([ref]$dm, 0)`n"
f" exit $result`n"
f"}}"
)
try:
result = subprocess.run(
["powershell", "-NoProfile", "-NonInteractive", "-Command", ps_script],
capture_output=True, text=True, timeout=15,
creationflags=subprocess.CREATE_NO_WINDOW if platform_name == "Windows" else 0
)
if result.returncode != 0:
return jsonify({"error": f"ChangeDisplaySettings returned {result.returncode}", "stderr": result.stderr}), 500
return jsonify({"message": f"Resolution set to {width}x{height}"})
except Exception as e:
return jsonify({"error": str(e)}), 500
else:
# Linux/macOS: try xrandr
try:
result = subprocess.run(
["xrandr", "--fb", f"{width}x{height}"],
capture_output=True, text=True, timeout=10
)
if result.returncode != 0:
return jsonify({"error": result.stderr or "xrandr failed"}), 500
return jsonify({"message": f"Resolution set to {width}x{height}"})
except FileNotFoundError:
return jsonify({"error": "xrandr not available"}), 501
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/v1/actions/clipboard", methods=["GET"])
def action_get_clipboard():
try:
text = pyperclip.paste()
return jsonify({"text": text})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/v1/actions/clipboard", methods=["POST"])
def action_set_clipboard():
data = request.get_json(silent=True) or {}
# Accept both "text" (preferred) and "content" (legacy) fields
text = data.get("text") if data.get("text") is not None else data.get("content")
if text is None:
return jsonify({"error": "text is required"}), 400
try:
pyperclip.copy(text)
return jsonify({"message": "Clipboard set successfully"})
except Exception as e:
return jsonify({"error": str(e)}), 500
# ---------------------------------------------------------------------------
# Command Routes /api/v1/commands
# ---------------------------------------------------------------------------
@app.route("/api/v1/commands", methods=["POST"])
def exec_command():
data = request.get_json(silent=True) or {}
command = data.get("command")
if not command:
return jsonify({"error": "command is required"}), 400
envs = data.get("envs")
working_dir = data.get("workingDir")
timeout_str = data.get("timeout", "30s")
timeout_sec = _parse_timeout(timeout_str, 30.0)
env = os.environ.copy()
if envs and isinstance(envs, dict):
env.update(envs)
kwargs = dict(
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
text=True,
timeout=timeout_sec,
env=env,
cwd=working_dir or None,
)
if platform_name == "Windows":
kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW
try:
result = subprocess.run(command, **kwargs)
return jsonify({
"exitCode": result.returncode,
"returncode": result.returncode,
"stdout": result.stdout,
"stderr": result.stderr,
})
except subprocess.TimeoutExpired:
return jsonify({"exitCode": 124, "returncode": 124, "stdout": "", "stderr": f"Command timed out after {timeout_sec}s"})
except Exception as e:
return jsonify({"error": str(e)}), 500
# ---------------------------------------------------------------------------
# File System Routes /api/v1/fs/*
# ---------------------------------------------------------------------------
@app.route("/api/v1/fs/list", methods=["GET"])
def fs_list():
path = request.args.get("path")
working_dir = request.args.get("workingDir")
depth = int(request.args.get("depth", 1))
if not path:
return jsonify({"error": "path is required"}), 400
resolved = _resolve_path(path, working_dir)
if not os.path.exists(resolved):
return jsonify({"error": "Directory not found"}), 404
if not os.path.isdir(resolved):
return jsonify({"error": "Path is not a directory"}), 400
def _list_dir(dir_path: str, current_depth: int) -> list:
entries = []
try:
for name in sorted(os.listdir(dir_path)):
full = os.path.join(dir_path, name)
info = _file_info(full)
if os.path.isdir(full) and current_depth < depth:
info["children"] = _list_dir(full, current_depth + 1)
entries.append(info)
except PermissionError:
pass
return entries
return jsonify(_list_dir(resolved, 1))
@app.route("/api/v1/fs/read", methods=["GET"])
def fs_read():
path = request.args.get("path")
working_dir = request.args.get("workingDir")
if not path:
return jsonify({"error": "path is required"}), 400
resolved = _resolve_path(path, working_dir)
if not os.path.exists(resolved):
return jsonify({"error": "File not found"}), 404
if os.path.isdir(resolved):
return jsonify({"error": "Path is a directory"}), 405
try:
with open(resolved, "r", encoding="utf-8", errors="replace") as f:
content = f.read()
return jsonify({"content": content})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/v1/fs/write", methods=["POST"])
def fs_write():
if request.content_type and "multipart/form-data" in request.content_type:
path = request.form.get("path")
working_dir = request.form.get("workingDir")
file_obj = request.files.get("content")
text_content = request.form.get("content") if file_obj is None else None
is_binary = file_obj is not None
else:
data = request.get_json(silent=True) or {}
path = data.get("path")
working_dir = data.get("workingDir")
text_content = data.get("content")
is_binary = False
file_obj = None
if not path:
return jsonify({"error": "path is required"}), 400
if text_content is None and file_obj is None:
return jsonify({"error": "content is required"}), 400
resolved = _resolve_path(path, working_dir)
if os.path.isdir(resolved):
return jsonify({"error": "Path is already a directory"}), 409
parent = os.path.dirname(resolved)
if parent:
os.makedirs(parent, exist_ok=True)
try:
if is_binary and file_obj:
file_obj.save(resolved)
else:
with open(resolved, "w", encoding="utf-8") as f:
f.write(text_content)
return jsonify(_file_info(resolved))
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/v1/fs", methods=["DELETE"])
def fs_delete():
# Accept path from query params (preferred) or JSON body
path = request.args.get("path")
working_dir = request.args.get("workingDir")
if path is None:
data = request.get_json(silent=True) or {}
path = data.get("path")
working_dir = data.get("workingDir") or working_dir
if not path:
return jsonify({"error": "path is required"}), 400
resolved = _resolve_path(path, working_dir)
if not os.path.exists(resolved):
return jsonify({"error": "File/dir not found"}), 404
try:
if os.path.isdir(resolved):
shutil.rmtree(resolved)
else:
os.remove(resolved)
return jsonify({"message": "File/Directory deleted successfully"})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/v1/fs/exists", methods=["POST"])
def fs_exists():
data = request.get_json(silent=True) or {}
path = data.get("path")
working_dir = data.get("workingDir")
if not path:
return jsonify({"error": "path is required"}), 400
resolved = _resolve_path(path, working_dir)
if not os.path.exists(resolved):
return jsonify({"exists": False})
fs_type = "directory" if os.path.isdir(resolved) else "file"
return jsonify({"exists": True, "type": fs_type})
@app.route("/api/v1/fs/rename", methods=["POST"])
def fs_rename():
data = request.get_json(silent=True) or {}
old_path = data.get("oldPath")
new_path = data.get("newPath")
working_dir = data.get("workingDir")