Repository navigation
Expand file tree
/
Copy pathaction_executor.py
More file actions
3563 lines (2834 loc) · 140 KB
/
Copy pathaction_executor.py
File metadata and controls
3563 lines (2834 loc) · 140 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
import types
from typing import Any, Callable, Dict, List, Optional, Union
from je_auto_control.utils.exception.exception_tags import (
action_is_null_error_message, add_command_exception_error_message,
executor_list_error_message, cant_execute_action_error_message
)
from je_auto_control.utils.exception.exceptions import (
AutoControlActionException, AutoControlAddCommandException,
AutoControlActionNullException
)
from je_auto_control.utils.accessibility.accessibility_api import (
click_accessibility_element, find_accessibility_element,
)
from je_auto_control.utils.self_healing import (
default_heal_log,
self_heal_click as _self_heal_click_impl,
self_heal_locate as _self_heal_locate_impl,
)
from je_auto_control.utils.vision.vlm_api import (
click_by_description, locate_by_description,
)
from je_auto_control.utils.clipboard.clipboard import (
get_clipboard, set_clipboard,
)
from je_auto_control.utils.executor.action_schema import validate_actions
from je_auto_control.utils.executor.flow_control import (
BLOCK_COMMANDS, LoopBreak, LoopContinue,
)
from je_auto_control.utils.executor.mouse_aliases import MOUSE_BUTTON_COMMANDS
from je_auto_control.utils.llm.planner import (
plan_actions as llm_plan_actions,
run_from_description as llm_run_from_description,
)
from je_auto_control.utils.remote_desktop.registry import (
registry as remote_desktop_registry,
)
from je_auto_control.utils.rest_api.rest_registry import (
rest_api_registry,
)
from je_auto_control.utils.admin.admin_client import (
default_admin_console,
)
from je_auto_control.utils.ocr.ocr_engine import (
click_text as ocr_click_text,
find_text_regex as ocr_find_text_regex,
locate_text_center as ocr_locate_text_center,
read_text_in_region as ocr_read_text_in_region,
wait_for_text as ocr_wait_for_text,
)
from je_auto_control.utils.profiler.profiler import default_profiler
from je_auto_control.utils.run_history.history_store import default_history_store
from je_auto_control.utils.secrets import default_secret_manager
from je_auto_control.utils.script_vars.interpolate import (
interpolate_actions, interpolate_value,
)
from je_auto_control.utils.script_vars.scope import VariableScope
from je_auto_control.utils.http_client.http_client import http_request
from je_auto_control.utils.generate_report.generate_html_report import generate_html, generate_html_report
from je_auto_control.utils.generate_report.generate_json_report import generate_json, generate_json_report
from je_auto_control.utils.generate_report.generate_xml_report import generate_xml, generate_xml_report
from je_auto_control.utils.json.json_file import read_action_json
from je_auto_control.utils.logging.logging_instance import autocontrol_logger
from je_auto_control.utils.mcp_server.http_transport import start_mcp_http_server
from je_auto_control.utils.mcp_server.server import start_mcp_stdio_server
from je_auto_control.utils.package_manager.package_manager_class import package_manager
from je_auto_control.utils.project.create_project_structure import create_project_dir
from je_auto_control.utils.shell_process.shell_exec import default_shell_manager
from je_auto_control.utils.start_exe.start_another_process import start_exe
from je_auto_control.utils.test_record.record_test_class import record_action_to_list, test_record_instance
from je_auto_control.wrapper.auto_control_image import locate_all_image, locate_and_click, locate_image_center
from je_auto_control.wrapper.auto_control_keyboard import (
check_key_is_press, get_keyboard_keys_table,
press_keyboard_key, release_keyboard_key, hotkey, type_keyboard, write
)
from je_auto_control.wrapper.auto_control_mouse import (
get_mouse_position, press_mouse, release_mouse, click_mouse,
mouse_scroll, get_mouse_table, set_mouse_position
)
from je_auto_control.wrapper.auto_control_record import record, stop_record
from je_auto_control.wrapper.auto_control_screen import screenshot, screen_size
from je_auto_control.wrapper.auto_control_window import (
close_window_by_title, focus_window, list_windows, wait_for_window,
)
def _a11y_list_as_dicts(app_name: Optional[str] = None,
max_results: int = 200) -> List[dict]:
"""Executor adapter: list accessibility elements as plain dicts."""
from je_auto_control.utils.accessibility.accessibility_api import (
list_accessibility_elements,
)
return [
element.to_dict()
for element in list_accessibility_elements(
app_name=app_name, max_results=int(max_results),
)
]
def _a11y_find_as_dict(name: Optional[str] = None,
role: Optional[str] = None,
app_name: Optional[str] = None) -> Optional[dict]:
"""Executor adapter: find an accessibility element, return its dict."""
element = find_accessibility_element(
name=name, role=role, app_name=app_name,
)
return None if element is None else element.to_dict()
def _vlm_locate_as_list(description: str,
screen_region: Optional[List[int]] = None,
model: Optional[str] = None) -> Optional[List[int]]:
"""Executor adapter: return VLM-located coords as a JSON-safe list."""
coords = locate_by_description(
description, screen_region=screen_region, model=model,
)
return None if coords is None else [coords[0], coords[1]]
def _self_heal_locate(template_path: Optional[str] = None,
description: Optional[str] = None,
detect_threshold: float = 0.9,
screen_region: Optional[List[int]] = None,
model: Optional[str] = None,
raise_on_miss: bool = False) -> Dict[str, Any]:
"""Executor adapter: template-first locate with VLM fallback."""
outcome = _self_heal_locate_impl(
template_path=template_path, description=description,
detect_threshold=float(detect_threshold),
screen_region=screen_region, model=model,
raise_on_miss=bool(raise_on_miss),
)
return outcome.to_dict()
def _self_heal_click(template_path: Optional[str] = None,
description: Optional[str] = None,
mouse_keycode: str = "mouse_left",
detect_threshold: float = 0.9,
screen_region: Optional[List[int]] = None,
model: Optional[str] = None,
raise_on_miss: bool = False) -> Dict[str, Any]:
"""Executor adapter: locate with self-heal, then click."""
outcome = _self_heal_click_impl(
template_path=template_path, description=description,
mouse_keycode=mouse_keycode,
detect_threshold=float(detect_threshold),
screen_region=screen_region, model=model,
raise_on_miss=bool(raise_on_miss),
)
return outcome.to_dict()
def _self_heal_log_list(limit: int = 50) -> List[Dict[str, Any]]:
"""Executor adapter: return the recent self-healing events."""
return [event.to_dict()
for event in default_heal_log.list_events(limit=int(limit))]
def _self_heal_log_clear() -> Dict[str, Any]:
default_heal_log.clear()
return {"cleared": True, "path": str(default_heal_log.path)}
def _run_dag(definition: Dict[str, Any],
max_parallel: int = 4) -> Dict[str, Any]:
"""Executor adapter: run a cross-host DAG definition."""
from je_auto_control.utils.dag import run_dag
return run_dag(definition, max_parallel=int(max_parallel)).to_dict()
_AX_RECORDER_SINGLETON = None
def _a11y_dump(app_name: Optional[str] = None,
max_results: int = 500) -> Dict[str, Any]:
"""Executor adapter: dump the accessibility tree as nested dict."""
from je_auto_control.utils.accessibility import dump_accessibility_tree
return dump_accessibility_tree(
app_name=app_name, max_results=int(max_results),
).to_dict()
def _a11y_record_start(app_name: Optional[str] = None,
poll_interval_s: float = 0.25,
min_movement_px: int = 8) -> Dict[str, Any]:
"""Executor adapter: start the singleton accessibility recorder."""
from je_auto_control.utils.accessibility import AccessibilityRecorder
global _AX_RECORDER_SINGLETON
if (_AX_RECORDER_SINGLETON is not None
and _AX_RECORDER_SINGLETON.is_running):
return {"running": True, "already": True}
_AX_RECORDER_SINGLETON = AccessibilityRecorder(
app_name=app_name,
poll_interval_s=float(poll_interval_s),
min_movement_px=int(min_movement_px),
)
_AX_RECORDER_SINGLETON.start()
return {"running": True, "already": False}
def _a11y_record_stop() -> List[Dict[str, Any]]:
"""Executor adapter: stop the recorder and return the captured events."""
global _AX_RECORDER_SINGLETON
if _AX_RECORDER_SINGLETON is None:
return []
events = _AX_RECORDER_SINGLETON.stop()
_AX_RECORDER_SINGLETON = None
return [event.to_dict() for event in events]
def _a11y_record_events() -> List[Dict[str, Any]]:
"""Executor adapter: peek at events without stopping the recorder."""
if _AX_RECORDER_SINGLETON is None:
return []
return [event.to_dict() for event in _AX_RECORDER_SINGLETON.events()]
def _ab_locate(target_id: str,
strategies: Dict[str, Dict[str, Any]],
max_parallel: int = 4,
record: bool = True) -> Dict[str, Any]:
"""Executor adapter: race N locator strategies for the same target."""
from je_auto_control.utils.ab_locator import ab_locate
from je_auto_control.utils.anchor_locator import (
Locator as AnchorLocator,
)
locators = {name: AnchorLocator(**spec)
for name, spec in strategies.items()}
return ab_locate(
target_id=target_id, strategies=locators,
max_parallel=int(max_parallel), record=bool(record),
).to_dict()
def _ab_report(target_id: str) -> Dict[str, Any]:
from je_auto_control.utils.ab_locator import ab_report_for
return ab_report_for(target_id).to_dict()
def _ab_best_strategy(target_id: str) -> Dict[str, Any]:
from je_auto_control.utils.ab_locator import ab_best_strategy
return {"target_id": target_id,
"strategy": ab_best_strategy(target_id)}
def _ab_clear() -> Dict[str, Any]:
from je_auto_control.utils.ab_locator import default_ab_store
default_ab_store.clear()
return {"cleared": True}
def _failure_hook_fire(source: str, source_id: str,
error_text: str = "",
script_path: Optional[str] = None,
screenshot_path: Optional[str] = None,
log_tail: str = "",
metadata: Optional[Dict[str, Any]] = None,
) -> List[Dict[str, Any]]:
"""Executor adapter: file a ticket through every registered backend."""
from je_auto_control.utils.failure_hooks import (
FailureReport, default_failure_hook_manager,
)
report = FailureReport(
source=source, source_id=source_id, error_text=error_text,
script_path=script_path, screenshot_path=screenshot_path,
log_tail=log_tail, metadata=dict(metadata or {}),
)
return [result.to_dict()
for result in default_failure_hook_manager.fire(report)]
def _failure_hook_list() -> List[Dict[str, Any]]:
from je_auto_control.utils.failure_hooks import default_failure_hook_manager
return default_failure_hook_manager.list_backends()
def _failure_hook_clear() -> Dict[str, Any]:
from je_auto_control.utils.failure_hooks import default_failure_hook_manager
default_failure_hook_manager.clear()
return {"cleared": True}
def _costs_record(provider: str, model: str,
input_tokens: int, output_tokens: int,
label: Optional[str] = None,
run_id: Optional[str] = None,
user: Optional[str] = None) -> Dict[str, Any]:
"""Executor adapter: append one LLM call to the cost-telemetry log."""
from je_auto_control.utils.cost_telemetry import record_llm_call
event = record_llm_call(
provider=provider, model=model,
input_tokens=int(input_tokens),
output_tokens=int(output_tokens),
label=label, run_id=run_id, user=user,
)
return event.to_dict()
def _costs_summary(limit: int = 10000) -> Dict[str, Any]:
"""Executor adapter: aggregate cost events by model / provider / day."""
from je_auto_control.utils.cost_telemetry import (
default_cost_store, summarise_llm_costs,
)
events = default_cost_store.list_events(limit=int(limit))
return summarise_llm_costs(events).to_dict()
def _costs_list(limit: int = 100) -> List[Dict[str, Any]]:
from je_auto_control.utils.cost_telemetry import default_cost_store
return [event.to_dict()
for event in default_cost_store.list_events(limit=int(limit))]
def _costs_clear() -> Dict[str, Any]:
from je_auto_control.utils.cost_telemetry import default_cost_store
default_cost_store.clear()
return {"cleared": True, "path": str(default_cost_store.path)}
def _wait_screen_stable(region: Optional[List[int]] = None,
timeout_s: float = 10.0,
poll_interval_s: float = 0.2,
stable_for_s: float = 0.5,
max_pixel_diff: int = 0) -> Dict[str, Any]:
"""Executor adapter: smart wait for the screen to stop moving."""
from je_auto_control.utils.smart_waits import wait_until_screen_stable
return wait_until_screen_stable(
region=region, timeout_s=float(timeout_s),
poll_interval_s=float(poll_interval_s),
stable_for_s=float(stable_for_s),
max_pixel_diff=int(max_pixel_diff),
).to_dict()
def _wait_pixel_changes(x: int, y: int,
timeout_s: float = 10.0,
poll_interval_s: float = 0.1,
rgb_tolerance: int = 5) -> Dict[str, Any]:
"""Executor adapter: smart wait for one pixel to change colour."""
from je_auto_control.utils.smart_waits import wait_until_pixel_changes
return wait_until_pixel_changes(
x=int(x), y=int(y),
timeout_s=float(timeout_s),
poll_interval_s=float(poll_interval_s),
rgb_tolerance=int(rgb_tolerance),
).to_dict()
def _wait_clipboard_change(baseline: Optional[str] = None,
target: Optional[str] = None,
contains: bool = False,
timeout_s: float = 10.0,
poll_interval_s: float = 0.2) -> Dict[str, Any]:
"""Executor adapter: wait until the clipboard changes (or matches target)."""
from je_auto_control.utils.smart_waits import wait_until_clipboard_changes
return wait_until_clipboard_changes(
baseline=baseline, target=target, contains=bool(contains),
timeout_s=float(timeout_s), poll_interval_s=float(poll_interval_s),
).to_dict()
def _wait_window_closed(title: str, case_sensitive: bool = False,
timeout_s: float = 10.0,
poll_interval_s: float = 0.2) -> Dict[str, Any]:
"""Executor adapter: wait until a window matching ``title`` disappears."""
from je_auto_control.utils.smart_waits import wait_until_window_closed
return wait_until_window_closed(
title, case_sensitive=bool(case_sensitive),
timeout_s=float(timeout_s), poll_interval_s=float(poll_interval_s),
).to_dict()
def _wait_region_idle(region: List[int],
timeout_s: float = 10.0,
poll_interval_s: float = 0.2,
stable_for_s: float = 0.5,
max_pixel_diff: int = 0) -> Dict[str, Any]:
"""Executor adapter: smart wait for a sub-region to stop moving."""
from je_auto_control.utils.smart_waits import wait_until_region_idle
return wait_until_region_idle(
region=region, timeout_s=float(timeout_s),
poll_interval_s=float(poll_interval_s),
stable_for_s=float(stable_for_s),
max_pixel_diff=int(max_pixel_diff),
).to_dict()
def _wait_for_file(path: str, timeout_s: float = 30.0,
poll_interval_s: float = 0.25,
stable_for_s: float = 1.0,
min_size: int = 1) -> Dict[str, Any]:
"""Executor adapter: wait until a file exists and finishes being written."""
from je_auto_control.utils.smart_waits import wait_until_file
return wait_until_file(
path, timeout_s=float(timeout_s),
poll_interval_s=float(poll_interval_s),
stable_for_s=float(stable_for_s), min_size=int(min_size),
).to_dict()
def _wait_for_port(host: str, port: int, timeout_s: float = 30.0,
poll_interval_s: float = 0.25,
connect_timeout_s: float = 1.0) -> Dict[str, Any]:
"""Executor adapter: wait until a TCP port accepts connections."""
from je_auto_control.utils.smart_waits import wait_until_port
return wait_until_port(
host, int(port), timeout_s=float(timeout_s),
poll_interval_s=float(poll_interval_s),
connect_timeout_s=float(connect_timeout_s),
).to_dict()
def _wait_for_process(name: str, present: bool = True, timeout_s: float = 30.0,
poll_interval_s: float = 0.25) -> Dict[str, Any]:
"""Executor adapter: wait until a process appears or exits."""
from je_auto_control.utils.smart_waits import wait_until_process
return wait_until_process(
name, present=bool(present), timeout_s=float(timeout_s),
poll_interval_s=float(poll_interval_s),
).to_dict()
def _ocr_read_structure(region: Optional[List[int]] = None,
lang: str = "eng",
min_confidence: float = 60.0,
) -> Dict[str, Any]:
"""Executor adapter: structured OCR (rows / tables / form fields)."""
from je_auto_control.utils.ocr.structure import read_structure
structured = read_structure(
region=region, lang=lang,
min_confidence=float(min_confidence),
)
return structured.to_dict()
def _anchor_locate(anchor: Dict[str, Any], target: Dict[str, Any],
relation: str = "near",
max_distance_px: float = 200.0) -> Dict[str, Any]:
"""Executor adapter: anchor-based spatial locator."""
from je_auto_control.utils.anchor_locator import (
Locator, anchor_locate,
)
anchor_loc = Locator(**anchor)
target_loc = Locator(**target)
outcome = anchor_locate(
anchor=anchor_loc, target=target_loc,
relation=relation, max_distance_px=float(max_distance_px),
)
return outcome.to_dict()
def _anchor_click(anchor: Dict[str, Any], target: Dict[str, Any],
mouse_keycode: str = "mouse_left",
relation: str = "near",
max_distance_px: float = 200.0) -> Dict[str, Any]:
"""Executor adapter: anchor-locate + click."""
outcome = _anchor_locate(anchor, target, relation, max_distance_px)
if outcome.get("found") and outcome.get("target_coords"):
cx, cy = outcome["target_coords"]
from je_auto_control.wrapper.auto_control_mouse import (
click_mouse, set_mouse_position,
)
set_mouse_position(int(cx), int(cy))
click_mouse(mouse_keycode, int(cx), int(cy))
return outcome
def _chatops_dispatch(message: str,
context: Optional[Dict[str, Any]] = None,
script_root: Optional[str] = None) -> Dict[str, Any]:
"""Executor adapter: route one chat message through the default router."""
from je_auto_control.utils.chatops import (
CommandRouter, register_chatops_default_commands,
)
router = CommandRouter()
register_chatops_default_commands(router)
merged_context: Dict[str, Any] = dict(context or {})
if script_root is not None:
merged_context.setdefault("script_root", script_root)
result = router.dispatch(message, context=merged_context)
return {"matched": False} if result is None else {
"matched": True, **result.to_dict(),
}
def _presence_register(viewer_id: str, label: str = "",
role: str = "observer") -> Dict[str, Any]:
from je_auto_control.utils.remote_desktop.presence import (
default_presence_registry,
)
return default_presence_registry().register(
viewer_id, label, role=role,
).to_dict()
def _presence_unregister(viewer_id: str) -> Dict[str, Any]:
from je_auto_control.utils.remote_desktop.presence import (
default_presence_registry,
)
removed = default_presence_registry().unregister(viewer_id)
return {"viewer_id": viewer_id, "removed": removed}
def _presence_update_cursor(viewer_id: str, x: int, y: int) -> Dict[str, Any]:
from je_auto_control.utils.remote_desktop.presence import (
default_presence_registry,
)
return default_presence_registry().update_cursor(
viewer_id, int(x), int(y),
).to_dict()
def _presence_set_role(viewer_id: str, role: str) -> Dict[str, Any]:
from je_auto_control.utils.remote_desktop.presence import (
default_presence_registry,
)
return default_presence_registry().update_role(viewer_id, role).to_dict()
def _presence_list() -> List[Dict[str, Any]]:
from je_auto_control.utils.remote_desktop.presence import (
default_presence_registry,
)
return [row.to_dict() for row in default_presence_registry().list()]
def _presence_clear() -> Dict[str, Any]:
from je_auto_control.utils.remote_desktop.presence import (
default_presence_registry,
)
default_presence_registry().clear()
return {"cleared": True}
def _run_agent(goal: str,
backend: str = "anthropic",
max_steps: int = 25,
wall_seconds: float = 300.0,
model: Optional[str] = None,
max_tokens: int = 1024) -> Dict[str, Any]:
"""Executor adapter: drive the closed-loop ``AgentLoop`` against ``goal``.
``backend`` selects between the production backends (Anthropic /
OpenAI). The Anthropic computer-use raw path remains available
via :func:`_computer_use` / ``AC_computer_use``.
"""
from je_auto_control.utils.agent import AgentBudget, AgentLoop
from je_auto_control.utils.agent.backends import (
AnthropicAgentBackend, OpenAIAgentBackend,
)
from je_auto_control.utils.tool_use_schema import (
export_anthropic_tools, export_openai_tools,
)
name = (backend or "anthropic").strip().lower()
if name == "anthropic":
tools = export_anthropic_tools()
backend_obj = AnthropicAgentBackend(
tools=tools,
model=model or "claude-opus-4-7",
max_tokens=int(max_tokens),
)
elif name == "openai":
tools = export_openai_tools()
# OpenAIAgentBackend does not accept max_tokens (Anthropic-only).
backend_obj = OpenAIAgentBackend(
tools=tools,
model=model or "gpt-4o",
)
else:
raise ValueError(f"unknown agent backend: {backend!r}")
budget = AgentBudget(
max_steps=int(max_steps), wall_seconds=float(wall_seconds),
)
result = AgentLoop(backend_obj, budget=budget).run(goal)
return {
"succeeded": bool(result.succeeded),
"elapsed_s": float(result.elapsed_s),
"final_message": result.final_message,
"steps": [
{
"index": step.index,
"tool": step.tool,
"arguments": step.arguments,
"error": step.error,
"stop_reason": step.stop_reason,
}
for step in result.steps
],
}
def _redact_screenshot(file_path: str,
output_path: Optional[str] = None,
policy: str = "moderate",
regions: Optional[List[List[int]]] = None,
accessibility: Optional[List[Dict[str, Any]]] = None,
ocr: Optional[List[Dict[str, Any]]] = None,
) -> Dict[str, Any]:
"""Executor adapter: blur PII regions in a saved screenshot.
Reads ``file_path``, applies the chosen redaction policy
(optionally with caller-supplied accessibility / OCR context),
and writes the result to ``output_path`` (or overwrites the
source when omitted). Returns ``{output_path, boxes,
detectors_used}`` for downstream audit.
"""
from je_auto_control.utils.redaction import (
RedactionEngine, policy_from_name,
)
target = output_path or file_path
chosen = policy_from_name(policy)
if regions:
chosen = chosen.with_extra_regions(
[tuple(int(v) for v in r) for r in regions],
)
engine = RedactionEngine(chosen)
context: Dict[str, Any] = {}
if accessibility is not None:
context["accessibility"] = list(accessibility)
if ocr is not None:
context["ocr"] = [(item["text"], item["bbox"]) for item in ocr]
with open(file_path, "rb") as src:
png_bytes = src.read()
redacted, result = engine.redact_bytes(png_bytes, context)
with open(target, "wb") as dest:
dest.write(redacted)
return {
"output_path": str(target),
"boxes": [list(b) for b in result.boxes],
"detectors_used": list(result.detectors_used),
}
def _assert_text(text: str,
region: Optional[List[int]] = None,
lang: str = "eng",
regex: bool = False,
present: bool = True,
ignore_case: bool = True,
min_confidence: float = 60.0,
raise_on_fail: bool = True,
capture_on_fail: bool = False) -> Dict[str, Any]:
"""Executor adapter: assert OCR text is (not) on screen."""
from je_auto_control.utils.assertion import assert_text
return assert_text(
text, region=region, lang=lang, regex=bool(regex),
present=bool(present), ignore_case=bool(ignore_case),
min_confidence=float(min_confidence),
raise_on_fail=bool(raise_on_fail),
capture_on_fail=bool(capture_on_fail),
).to_dict()
def _assert_image(template_path: str,
threshold: float = 0.9,
present: bool = True,
raise_on_fail: bool = True,
capture_on_fail: bool = False) -> Dict[str, Any]:
"""Executor adapter: assert a template image is (not) on screen."""
from je_auto_control.utils.assertion import assert_image
return assert_image(
template_path, threshold=float(threshold), present=bool(present),
raise_on_fail=bool(raise_on_fail),
capture_on_fail=bool(capture_on_fail),
).to_dict()
def _assert_pixel(x: int, y: int, rgb: List[int],
tolerance: int = 0,
match: bool = True,
raise_on_fail: bool = True,
capture_on_fail: bool = False) -> Dict[str, Any]:
"""Executor adapter: assert a pixel matches (or differs from) ``rgb``."""
from je_auto_control.utils.assertion import assert_pixel
return assert_pixel(
int(x), int(y), rgb, tolerance=int(tolerance), match=bool(match),
raise_on_fail=bool(raise_on_fail),
capture_on_fail=bool(capture_on_fail),
).to_dict()
def _assert_window(title: str,
exists: bool = True,
ignore_case: bool = True,
raise_on_fail: bool = True,
capture_on_fail: bool = False) -> Dict[str, Any]:
"""Executor adapter: assert a window matching ``title`` does (not) exist."""
from je_auto_control.utils.assertion import assert_window
return assert_window(
title, exists=bool(exists), ignore_case=bool(ignore_case),
raise_on_fail=bool(raise_on_fail),
capture_on_fail=bool(capture_on_fail),
).to_dict()
def _assert_vlm(description: str,
present: bool = True,
screen_region: Optional[List[int]] = None,
model: Optional[str] = None,
raise_on_fail: bool = True,
capture_on_fail: bool = False) -> Dict[str, Any]:
"""Executor adapter: assert the screen matches a description (VLM judged)."""
from je_auto_control.utils.assertion import assert_by_description
return assert_by_description(
description, present=bool(present), screen_region=screen_region,
model=model, raise_on_fail=bool(raise_on_fail),
capture_on_fail=bool(capture_on_fail),
).to_dict()
def _assert_clipboard(text: str,
mode: str = "equals",
ignore_case: bool = False,
present: bool = True,
raise_on_fail: bool = True,
capture_on_fail: bool = False) -> Dict[str, Any]:
"""Executor adapter: assert clipboard text matches ``text``."""
from je_auto_control.utils.assertion import assert_clipboard
return assert_clipboard(
text, mode=mode, ignore_case=bool(ignore_case),
present=bool(present), raise_on_fail=bool(raise_on_fail),
capture_on_fail=bool(capture_on_fail),
).to_dict()
def _assert_process(name: str,
running: bool = True,
raise_on_fail: bool = True,
capture_on_fail: bool = False) -> Dict[str, Any]:
"""Executor adapter: assert a process matching ``name`` is (not) running."""
from je_auto_control.utils.assertion import assert_process
return assert_process(
name, running=bool(running), raise_on_fail=bool(raise_on_fail),
capture_on_fail=bool(capture_on_fail),
).to_dict()
def _assert_file(path: str,
exists: bool = True,
contains: Optional[str] = None,
sha256: Optional[str] = None,
min_size: Optional[int] = None,
raise_on_fail: bool = True) -> Dict[str, Any]:
"""Executor adapter: assert a file's existence / content / hash / size."""
from je_auto_control.utils.assertion import assert_file
return assert_file(
path, exists=bool(exists), contains=contains, sha256=sha256,
min_size=None if min_size is None else int(min_size),
raise_on_fail=bool(raise_on_fail),
).to_dict()
def _assert_http(url: str,
status: int = 200,
contains: Optional[str] = None,
timeout: float = 10.0,
method: str = "GET",
raise_on_fail: bool = True) -> Dict[str, Any]:
"""Executor adapter: assert an HTTP(S) endpoint status / body."""
from je_auto_control.utils.assertion import assert_http
return assert_http(
url, status=int(status), contains=contains, timeout=float(timeout),
method=method, raise_on_fail=bool(raise_on_fail),
).to_dict()
def _assert_all(specs: List[Dict[str, Any]],
raise_on_fail: bool = True) -> Dict[str, Any]:
"""Executor adapter: run a batch of assertion specs (soft assertions)."""
from je_auto_control.utils.assertion import assert_all
return assert_all(specs, raise_on_fail=bool(raise_on_fail)).to_dict()
def _assert_any(specs: List[Dict[str, Any]],
raise_on_fail: bool = True) -> Dict[str, Any]:
"""Executor adapter: pass when at least one assertion spec passes."""
from je_auto_control.utils.assertion import assert_any
return assert_any(specs, raise_on_fail=bool(raise_on_fail)).to_dict()
def _assert_eventually(spec: Dict[str, Any],
timeout: float = 5.0,
interval: float = 0.25,
raise_on_fail: bool = True) -> Dict[str, Any]:
"""Executor adapter: poll one assertion spec until it passes / times out."""
from je_auto_control.utils.assertion import assert_eventually
return assert_eventually(
spec, timeout=float(timeout), interval=float(interval),
raise_on_fail=bool(raise_on_fail),
).to_dict()
def _load_data(source: Dict[str, Any]) -> List[Dict[str, Any]]:
"""Executor adapter: load tabular rows from a data source spec."""
from je_auto_control.utils.data_source import load_rows
return load_rows(source)
def _flaky_report(limit: int = 500,
min_runs: int = 2,
group_by: str = "script_path") -> Dict[str, Any]:
"""Executor adapter: score run-history flakiness per script / source."""
from je_auto_control.utils.flakiness import analyze_flakiness
return analyze_flakiness(
limit=int(limit), min_runs=int(min_runs), group_by=group_by,
).to_dict()
def _run_suite(spec: Dict[str, Any],
tags: Optional[List[str]] = None,
respect_quarantine: bool = True,
junit_path: Optional[str] = None,
allure_dir: Optional[str] = None) -> Dict[str, Any]:
"""Executor adapter: run a QA suite and optionally write CI reports."""
from je_auto_control.utils.test_suite import (
run_suite, write_allure_results, write_junit_xml,
)
result = run_suite(
spec, executor=executor, tags=tags,
respect_quarantine=bool(respect_quarantine),
)
payload = result.to_dict()
reports: Dict[str, Any] = {}
if junit_path:
reports["junit"] = write_junit_xml(result, junit_path)
if allure_dir:
reports["allure"] = write_allure_results(result, allure_dir)
if reports:
payload["reports"] = reports
return payload
def _quarantine_add(name: str, reason: str = "") -> Dict[str, Any]:
from je_auto_control.utils.quarantine import default_quarantine_store
return default_quarantine_store().add(name, reason=reason).to_dict()
def _quarantine_remove(name: str) -> Dict[str, Any]:
from je_auto_control.utils.quarantine import default_quarantine_store
return {"name": name, "removed": default_quarantine_store().remove(name)}
def _quarantine_list() -> List[Dict[str, Any]]:
from je_auto_control.utils.quarantine import default_quarantine_store
return [entry.to_dict() for entry in default_quarantine_store().list()]
def _quarantine_clear() -> Dict[str, Any]:
from je_auto_control.utils.quarantine import default_quarantine_store
return {"cleared": default_quarantine_store().clear()}
def _quarantine_auto(flip_rate_threshold: float = 0.5,
min_runs: int = 3,
limit: int = 500,
group_by: str = "script_path") -> List[Dict[str, Any]]:
from je_auto_control.utils.quarantine import auto_quarantine_from_flakiness
return [
entry.to_dict()
for entry in auto_quarantine_from_flakiness(
flip_rate_threshold=float(flip_rate_threshold),
min_runs=int(min_runs), limit=int(limit), group_by=group_by,
)
]
def _audit_accessibility(app_name: Optional[str] = None,
contrast_pairs: Optional[List[Dict[str, Any]]] = None,
texts: Optional[List[str]] = None,
min_ratio: float = 4.5,
max_results: int = 500) -> Dict[str, Any]:
"""Executor adapter: run the accessibility / i18n audit."""
from je_auto_control.utils.a11y_audit import run_audit
return run_audit(
app_name=app_name, contrast_pairs=contrast_pairs, texts=texts,
min_ratio=float(min_ratio), max_results=int(max_results),
).to_dict()
def _audit_contrast(foreground: List[int], background: List[int],
min_ratio: float = 4.5) -> Dict[str, Any]:
"""Executor adapter: WCAG contrast ratio for one colour pair."""
from je_auto_control.utils.a11y_audit import contrast_ratio
ratio = contrast_ratio(foreground, background)
return {
"ratio": round(ratio, 2),
"passes_aa": ratio >= float(min_ratio),
"foreground": list(foreground), "background": list(background),
}
def _wcag_audit(app_name: Optional[str] = None,
contrast_pairs: Optional[List[Dict[str, Any]]] = None,
texts: Optional[List[str]] = None, level: str = "AA",
min_target_px: int = 24, max_results: int = 500
) -> Dict[str, Any]:
"""Executor adapter: WCAG-tagged conformance audit (SC ids + levels)."""
from je_auto_control.utils.a11y_audit import wcag_audit
return wcag_audit(
app_name=app_name, contrast_pairs=contrast_pairs, texts=texts,
level=str(level), min_target_px=int(min_target_px),
max_results=int(max_results))
def _run_device_matrix(actions: List[Any], devices: List[Dict[str, Any]],
max_parallel: int = 4,
var_name: str = "device") -> Dict[str, Any]:
"""Executor adapter: run an action list across many devices in parallel."""
from je_auto_control.utils.device_matrix import run_on_devices
return run_on_devices(
actions, devices, max_parallel=int(max_parallel), var_name=var_name,
).to_dict()
def _assert_audio(duration_s: float = 1.0,
threshold: float = 0.01,
expect_sound: bool = True,
samplerate: int = 44100,
channels: int = 1,
raise_on_fail: bool = True) -> Dict[str, Any]:
"""Executor adapter: assert audio activity / silence."""
from je_auto_control.utils.media_assert import assert_audio_activity
return assert_audio_activity(
duration_s=float(duration_s), threshold=float(threshold),
expect_sound=bool(expect_sound), samplerate=int(samplerate),
channels=int(channels), raise_on_fail=bool(raise_on_fail),
).to_dict()
def _assert_video_changes(video_path: str,
start_s: float = 0.0,
end_s: Optional[float] = None,
threshold: float = 1.0,
expect_motion: bool = True,
region: Optional[List[int]] = None,
raise_on_fail: bool = True) -> Dict[str, Any]:
"""Executor adapter: assert a video segment has motion / is static."""
from je_auto_control.utils.media_assert import assert_video_changes
return assert_video_changes(
video_path, start_s=float(start_s),
end_s=None if end_s is None else float(end_s),
threshold=float(threshold), expect_motion=bool(expect_motion),
region=region, raise_on_fail=bool(raise_on_fail),
).to_dict()
def _computer_use(goal: str,
display_width_px: Optional[int] = None,
display_height_px: Optional[int] = None,
display_number: Optional[int] = None,
max_steps: int = 25,
wall_seconds: float = 300.0,
model: str = "claude-opus-4-7",
max_tokens: int = 1024) -> Dict[str, Any]:
"""Executor adapter: run Anthropic Computer-Use to achieve ``goal``."""
from je_auto_control.utils.agent.computer_use import (
result_to_dict, run_computer_use,
)
result = run_computer_use(
goal,
display_width_px=display_width_px,
display_height_px=display_height_px,
display_number=display_number,
max_steps=int(max_steps), wall_seconds=float(wall_seconds),
model=model, max_tokens=int(max_tokens),
)
return result_to_dict(result)
def _remote_start_host(token: str,
bind: str = "127.0.0.1",
port: int = 0,
fps: float = 10.0,
quality: int = 70,
region: Optional[List[int]] = None,
max_clients: int = 4) -> Dict[str, Any]:
"""Executor adapter: start the singleton remote-desktop host."""
return remote_desktop_registry.start_host(
token=token, bind=bind, port=int(port),
fps=float(fps), quality=int(quality),
region=region, max_clients=int(max_clients),
)
def _remote_stop_host() -> Dict[str, Any]:
return remote_desktop_registry.stop_host()
def _remote_host_status() -> Dict[str, Any]:
return remote_desktop_registry.host_status()
def _remote_connect(host: str, port: int, token: str,
timeout: float = 5.0) -> Dict[str, Any]:
"""Executor adapter: connect the singleton viewer."""
return remote_desktop_registry.connect_viewer(
host=host, port=int(port), token=token, timeout=float(timeout),
)