-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcli.py
More file actions
2887 lines (2525 loc) · 111 KB
/
Copy pathcli.py
File metadata and controls
2887 lines (2525 loc) · 111 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
"""CLI for Windows Agent Arena benchmark evaluation.
This module provides command-line tools for running WAA evaluations:
- Mock evaluation (no Windows VM required)
- Live evaluation against a WAA server
- Azure-based parallel evaluation
Usage:
# Run mock evaluation
python -m openadapt_evals.benchmarks.cli mock --tasks 10
# Run live evaluation
python -m openadapt_evals.benchmarks.cli live --server http://vm-ip:5000
# Check server status
python -m openadapt_evals.benchmarks.cli probe --server http://vm-ip:5000
# Generate benchmark viewer
python -m openadapt_evals.benchmarks.cli view --run-name my_eval_run
"""
from __future__ import annotations
import argparse
import json
import logging
import os
import subprocess
import sys
from pathlib import Path
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
datefmt="%H:%M:%S",
)
logger = logging.getLogger(__name__)
def _resolve_vm_context(args: argparse.Namespace) -> tuple[str, str] | None:
"""Resolve VM name/resource group from args, env, or Azure CLI tags.
Resolution order:
1) CLI args
2) Environment variables
3) Azure CLI: running VM tagged openadapt-role=waa
"""
vm_name = (
getattr(args, "vm_name", None)
or os.getenv("AZURE_WAA_VM_NAME")
or os.getenv("AZURE_VM_NAME")
)
resource_group = (
getattr(args, "resource_group", None)
or os.getenv("AZURE_ML_RESOURCE_GROUP")
or os.getenv("AZURE_RESOURCE_GROUP")
)
if vm_name and resource_group:
return vm_name, resource_group
# If only vm name is provided, try to resolve resource group.
if vm_name and not resource_group:
try:
result = subprocess.run(
[
"az",
"vm",
"list",
"--query",
f"[?name=='{vm_name}'].resourceGroup | [0]",
"-o",
"tsv",
],
capture_output=True,
text=True,
timeout=30,
)
if result.returncode == 0 and result.stdout.strip():
return vm_name, result.stdout.strip()
except (FileNotFoundError, subprocess.TimeoutExpired):
return None
# Prefer tagged running VM, but fall back to any tagged VM.
queries = [
(
"[?tags.\"openadapt-role\"=='waa' && powerState=='VM running']."
"{name:name, rg:resourceGroup, tags:tags, status:powerState}"
),
(
"[?tags.\"openadapt-role\"=='waa']."
"{name:name, rg:resourceGroup, tags:tags, status:powerState}"
),
]
vms = []
for query in queries:
try:
result = subprocess.run(
[
"az",
"vm",
"list",
"--show-details",
"--query",
query,
"-o",
"json",
],
capture_output=True,
text=True,
timeout=30,
)
except (FileNotFoundError, subprocess.TimeoutExpired):
return None
if result.returncode != 0:
continue
try:
vms = json.loads(result.stdout)
except json.JSONDecodeError:
continue
if vms:
break
if not vms:
return None
if len(vms) > 1:
print("WARNING: Multiple tagged WAA VMs found. Using the first:")
for vm in vms:
status = vm.get("status") or "unknown"
print(f" - {vm.get('name')} ({vm.get('rg')}) [{status}]")
vm = vms[0]
name = vm.get("name")
rg = vm.get("rg")
if not name or not rg:
return None
return name, rg
def _requested_environment_flags(args: argparse.Namespace) -> dict[str, str | bool | None]:
"""Collect requested desktop-parity flags from CLI args."""
return {
"clean_desktop": bool(getattr(args, "clean_desktop", False)),
"force_tray_icons": bool(getattr(args, "force_tray_icons", False)),
"waa_image_version": getattr(args, "waa_image_version", None),
}
def _write_run_environment_metadata(
benchmark_dir: Path,
*,
requested: dict[str, str | bool | None],
adapter,
server_url: str,
evaluate_url: str | None,
) -> None:
"""Persist run environment flags/profile into benchmark metadata.json."""
metadata_path = benchmark_dir / "metadata.json"
metadata: dict = {}
if metadata_path.exists():
try:
metadata = json.loads(metadata_path.read_text())
except Exception as e:
logger.warning("Could not parse metadata.json for environment patch: %s", e)
metadata = {}
observed = {}
if hasattr(adapter, "get_environment_profile"):
try:
observed = adapter.get_environment_profile() or {}
except Exception as e:
logger.debug("Could not read adapter environment profile: %s", e)
metadata["environment"] = {
"requested": requested,
"observed": observed,
"server_url": server_url,
"evaluate_url": evaluate_url,
}
benchmark_dir.mkdir(parents=True, exist_ok=True)
metadata_path.write_text(json.dumps(metadata, indent=2))
def cmd_mock(args: argparse.Namespace) -> int:
"""Run mock evaluation (no Windows VM required)."""
from openadapt_evals.benchmarks import (
WAAMockAdapter,
SmartMockAgent,
EvaluationConfig,
evaluate_agent_on_benchmark,
compute_metrics,
)
from openadapt_evals.agents import ApiAgent
print(f"Running mock WAA evaluation with {args.tasks} tasks...")
# Create mock adapter
adapter = WAAMockAdapter(num_tasks=args.tasks)
# Create agent based on --agent option
agent_type = getattr(args, "agent", "mock") or "mock"
# Load demo from file if provided
demo_text = None
if hasattr(args, "demo") and args.demo:
demo_path = Path(args.demo)
if demo_path.exists():
demo_text = demo_path.read_text()
print(f"Loaded demo from {demo_path} ({len(demo_text)} chars)")
else:
# Treat as direct demo text
demo_text = args.demo
if agent_type == "mock":
agent = SmartMockAgent()
print("Using SmartMockAgent (deterministic mock)")
elif agent_type in ("api-claude", "claude", "anthropic"):
try:
agent = ApiAgent(provider="anthropic", demo=demo_text)
print(f"Using ApiAgent with Claude (demo={'yes' if agent.demo else 'no'})")
except RuntimeError as e:
print(f"ERROR: {e}")
return 1
elif agent_type in ("api-openai", "openai", "gpt"):
try:
agent = ApiAgent(provider="openai", demo=demo_text)
print(f"Using ApiAgent with GPT-5.1 (demo={'yes' if agent.demo else 'no'})")
except RuntimeError as e:
print(f"ERROR: {e}")
return 1
elif agent_type in ("api-claude-cu", "claude-cu"):
try:
from openadapt_evals.agents import ClaudeComputerUseAgent
agent = ClaudeComputerUseAgent(demo=demo_text)
print(f"Using ClaudeComputerUseAgent (demo={'yes' if agent.demo else 'no'})")
except RuntimeError as e:
print(f"ERROR: {e}")
return 1
elif agent_type == "qwen3vl":
try:
from openadapt_evals.agents import Qwen3VLAgent
model_path = getattr(args, "model_path", None)
model_endpoint = getattr(args, "model_endpoint", None)
use_thinking = getattr(args, "use_thinking", False)
use_a11y_tree = getattr(args, "use_a11y_tree", False)
agent = Qwen3VLAgent(
model_path=model_path, model_endpoint=model_endpoint,
demo=demo_text, use_thinking=use_thinking,
use_accessibility_tree=use_a11y_tree,
)
print(f"Using Qwen3VLAgent (model={agent.model_path}, endpoint={agent.model_endpoint}, demo={'yes' if agent.demo else 'no'})")
except RuntimeError as e:
print(f"ERROR: {e}")
return 1
elif agent_type == "smol":
try:
from openadapt_evals.agents import SmolOperatorAgent
agent = SmolOperatorAgent(demo=demo_text)
print(f"Using SmolOperatorAgent (model={agent.model_path}, demo={'yes' if agent.demo else 'no'})")
except RuntimeError as e:
print(f"ERROR: {e}")
return 1
elif agent_type == "http":
agent_endpoint = getattr(args, "agent_endpoint", None)
if not agent_endpoint:
print("ERROR: --agent-endpoint required for http agent")
return 1
from openadapt_evals.agents import HttpAgent
agent = HttpAgent(endpoint_url=agent_endpoint)
print(f"Using HttpAgent (endpoint={agent_endpoint})")
else:
print(f"ERROR: Unknown agent type: {agent_type}")
print("Available for mock: mock, api-claude, api-openai, api-claude-cu, qwen3vl, smol, http")
return 1
# Create config for trace collection
done_gate = getattr(args, "done_gate", False)
done_gate_max_overrides = getattr(args, "done_gate_max_overrides", 3)
done_gate_threshold = getattr(args, "done_gate_threshold", 1.0)
config = None
if args.output or done_gate:
config = EvaluationConfig(
save_execution_traces=bool(args.output),
output_dir=args.output or "benchmark_results",
run_name=args.run_name or "mock_eval",
done_gate=done_gate,
done_gate_max_overrides=done_gate_max_overrides,
done_gate_threshold=done_gate_threshold,
)
# Run evaluation
results = evaluate_agent_on_benchmark(
agent=agent,
adapter=adapter,
max_steps=args.max_steps,
config=config,
)
# Compute and display metrics
metrics = compute_metrics(results)
print("\n" + "=" * 50)
print("Evaluation Results")
print("=" * 50)
print(f"Tasks: {metrics['num_tasks']}")
print(f"Success rate: {metrics['success_rate']:.1%}")
print(f"Avg score: {metrics['avg_score']:.3f}")
print(f"Avg steps: {metrics['avg_steps']:.1f}")
if metrics.get("num_infrastructure_failures", 0):
print(f"Infra fails: {metrics['num_infrastructure_failures']}")
print(f"Adj success: {metrics.get('success_rate_excluding_infra', 0.0):.1%}")
if config:
print(f"\nResults saved to: {config.output_dir}/{config.run_name}")
return 0
def cmd_run(args: argparse.Namespace) -> int:
"""Simplified live evaluation with good defaults.
This is a convenience wrapper around 'live' that:
- Uses localhost:5001 by default (matches openadapt-ml SSH tunnel)
- Accepts --task (singular) or --tasks (comma-separated)
- Sets sensible defaults for output and run name
"""
from openadapt_evals.adapters import WAALiveAdapter, WAALiveConfig
from openadapt_evals.agents import SmartMockAgent, ApiAgent, RetrievalAugmentedAgent
from openadapt_evals.agents.scripted_agent import ScriptedAgent
from openadapt_evals.adapters.base import BenchmarkAction
from openadapt_evals.benchmarks import (
EvaluationConfig,
evaluate_agent_on_benchmark,
compute_metrics,
)
server_url = args.server
evaluate_url = getattr(args, "evaluate_url", None)
waa_examples_path = getattr(args, "waa_examples_path", None)
print(f"Connecting to WAA server at {server_url}...")
# Create live adapter
config = WAALiveConfig(
server_url=server_url,
evaluate_url=evaluate_url,
max_steps=args.max_steps,
waa_examples_path=waa_examples_path,
clean_desktop=getattr(args, "clean_desktop", False),
force_tray_icons=getattr(args, "force_tray_icons", False),
waa_image_version=getattr(args, "waa_image_version", None),
focus_check_method=getattr(args, "focus_check_method", "win32"),
)
adapter = WAALiveAdapter(config)
# Check connection
if not adapter.check_connection():
print(f"ERROR: Cannot connect to WAA server at {server_url}")
print()
print("Make sure:")
print(" 1. Azure VM is running (openadapt-ml: vm status)")
print(" 2. SSH tunnels are active (openadapt-ml: vm monitor)")
print(" 3. WAA server is ready (openadapt-ml: vm probe)")
return 1
print("Connected!")
# Parse task IDs from --task or --tasks
task_ids = []
if args.task:
task_ids = [args.task]
elif args.tasks:
task_ids = [t.strip() for t in args.tasks.split(",")]
else:
print("ERROR: Specify --task or --tasks")
print("Example: --task notepad_1")
print("Example: --tasks notepad_1,notepad_2,browser_1")
return 1
# Create agent
agent_type = args.agent
# Load demo from file if provided
demo_text = None
if hasattr(args, "demo") and args.demo:
demo_path = Path(args.demo)
if demo_path.exists():
demo_text = demo_path.read_text()
print(f"Loaded demo from {demo_path} ({len(demo_text)} chars)")
else:
demo_text = args.demo
if agent_type in ("noop", "done"):
agent = ScriptedAgent([BenchmarkAction(type="done")])
print("Using ScriptedAgent (noop): immediate DONE")
elif agent_type == "mock":
agent = SmartMockAgent()
print("Using SmartMockAgent")
elif agent_type in ("api-claude", "claude", "anthropic"):
try:
agent = ApiAgent(provider="anthropic", demo=demo_text)
print(f"Using ApiAgent with Claude (demo={'yes' if agent.demo else 'no'})")
except RuntimeError as e:
print(f"ERROR: {e}")
return 1
elif agent_type in ("api-openai", "openai", "gpt"):
try:
agent = ApiAgent(provider="openai", demo=demo_text)
print(f"Using ApiAgent with GPT-5.1 (demo={'yes' if agent.demo else 'no'})")
except RuntimeError as e:
print(f"ERROR: {e}")
return 1
elif agent_type in ("api-claude-cu", "claude-cu"):
try:
from openadapt_evals.agents import ClaudeComputerUseAgent
agent = ClaudeComputerUseAgent(demo=demo_text)
print(f"Using ClaudeComputerUseAgent (demo={'yes' if agent.demo else 'no'})")
except RuntimeError as e:
print(f"ERROR: {e}")
return 1
elif agent_type == "qwen3vl":
try:
from openadapt_evals.agents import Qwen3VLAgent
model_path = getattr(args, "model_path", None)
model_endpoint = getattr(args, "model_endpoint", None)
use_thinking = getattr(args, "use_thinking", False)
use_a11y_tree = getattr(args, "use_a11y_tree", False)
agent = Qwen3VLAgent(
model_path=model_path, model_endpoint=model_endpoint,
demo=demo_text, use_thinking=use_thinking,
use_accessibility_tree=use_a11y_tree,
)
print(f"Using Qwen3VLAgent (model={agent.model_path}, endpoint={agent.model_endpoint}, demo={'yes' if agent.demo else 'no'})")
except RuntimeError as e:
print(f"ERROR: {e}")
return 1
elif agent_type == "smol":
try:
from openadapt_evals.agents import SmolOperatorAgent
agent = SmolOperatorAgent(demo=demo_text)
print(f"Using SmolOperatorAgent (model={agent.model_path}, demo={'yes' if agent.demo else 'no'})")
except RuntimeError as e:
print(f"ERROR: {e}")
return 1
elif agent_type == "http":
agent_endpoint = getattr(args, "agent_endpoint", None)
if not agent_endpoint:
print("ERROR: --agent-endpoint required for http agent")
return 1
from openadapt_evals.agents import HttpAgent
agent = HttpAgent(endpoint_url=agent_endpoint)
print(f"Using HttpAgent (endpoint={agent_endpoint})")
else:
print(f"ERROR: Unknown agent type: {agent_type}")
print("Available: noop, mock, api-claude, api-openai, api-claude-cu, qwen3vl, smol, http")
return 1
# Create config for trace collection
eval_config = EvaluationConfig(
save_execution_traces=True,
output_dir=args.output,
run_name=args.run_name,
done_gate=getattr(args, "done_gate", False),
done_gate_max_overrides=getattr(args, "done_gate_max_overrides", 3),
done_gate_threshold=getattr(args, "done_gate_threshold", 1.0),
)
print(f"Running {len(task_ids)} task(s): {', '.join(task_ids)}")
# Check if controller mode is requested
use_controller = getattr(args, "controller", False) and demo_text is not None
if use_controller:
print(f"Using DemoController (max_retries={args.max_retries}, max_replans={args.max_replans})")
# Set up correction store if requested
correction_store = None
enable_correction_capture = getattr(args, "enable_correction_capture", False)
correction_library_path = getattr(args, "correction_library", None)
if correction_library_path:
from openadapt_evals.correction_store import CorrectionStore
correction_store = CorrectionStore(correction_library_path)
print(f"Correction library: {correction_library_path}")
if enable_correction_capture:
print("Correction capture: ENABLED (will prompt for human corrections on failure)")
# Run evaluation
if use_controller:
from openadapt_evals.demo_controller import run_with_controller
results = []
for tid in task_ids:
task = adapter.load_task(tid)
result = run_with_controller(
agent=agent,
adapter=adapter,
task=task,
demo_text=demo_text,
max_steps=args.max_steps,
max_retries=args.max_retries,
max_replans=args.max_replans,
correction_store=correction_store,
enable_correction_capture=enable_correction_capture,
)
results.append(result)
else:
results = evaluate_agent_on_benchmark(
agent=agent,
adapter=adapter,
max_steps=args.max_steps,
task_ids=task_ids,
config=eval_config,
)
# Compute and display metrics
metrics = compute_metrics(results)
print("\n" + "=" * 50)
print("Evaluation Results")
print("=" * 50)
print(f"Tasks: {metrics['num_tasks']}")
print(f"Success rate: {metrics['success_rate']:.1%}")
print(f"Avg score: {metrics['avg_score']:.3f}")
print(f"Avg steps: {metrics['avg_steps']:.1f}")
if metrics.get("num_infrastructure_failures", 0):
print(f"Infra fails: {metrics['num_infrastructure_failures']}")
print(f"Adj success: {metrics.get('success_rate_excluding_infra', 0.0):.1%}")
benchmark_dir = Path(eval_config.output_dir) / eval_config.run_name
_write_run_environment_metadata(
benchmark_dir,
requested=_requested_environment_flags(args),
adapter=adapter,
server_url=server_url,
evaluate_url=evaluate_url,
)
print(f"\nResults saved to: {benchmark_dir}")
no_open = getattr(args, "no_open", False)
if sys.stdout.isatty() and not no_open:
try:
from openadapt_evals.benchmarks import generate_benchmark_viewer
import webbrowser
viewer_path = benchmark_dir / "viewer.html"
generate_benchmark_viewer(benchmark_dir=benchmark_dir, output_path=viewer_path)
print(f"Viewer generated: {viewer_path}")
webbrowser.open(f"file://{viewer_path.absolute()}")
except Exception as e:
logger.warning(f"Could not auto-open viewer: {e}")
print(f"\nView results: openadapt-evals view --run-name {eval_config.run_name}")
else:
print(f"\nView results: openadapt-evals view --run-name {eval_config.run_name}")
return 0
def cmd_live(args: argparse.Namespace) -> int:
"""Run live evaluation against a WAA server."""
from openadapt_evals.adapters import WAALiveAdapter, WAALiveConfig
from openadapt_evals.agents import SmartMockAgent, ApiAgent, RetrievalAugmentedAgent
from openadapt_evals.agents.scripted_agent import ScriptedAgent
from openadapt_evals.adapters.base import BenchmarkAction
from openadapt_evals.benchmarks import (
EvaluationConfig,
evaluate_agent_on_benchmark,
compute_metrics,
)
evaluate_url = getattr(args, "evaluate_url", None)
waa_examples_path = getattr(args, "waa_examples_path", None)
print(f"Connecting to WAA server at {args.server}...")
# Create live adapter
config = WAALiveConfig(
server_url=args.server,
evaluate_url=evaluate_url,
max_steps=args.max_steps,
waa_examples_path=waa_examples_path,
clean_desktop=getattr(args, "clean_desktop", False),
force_tray_icons=getattr(args, "force_tray_icons", False),
waa_image_version=getattr(args, "waa_image_version", None),
focus_check_method=getattr(args, "focus_check_method", "win32"),
)
adapter = WAALiveAdapter(config)
# Check connection
if not adapter.check_connection():
print(f"ERROR: Cannot connect to WAA server at {args.server}")
print("Ensure Windows VM is running and WAA server is started.")
return 1
print("Connected!")
# Create agent based on --agent option
agent_type = getattr(args, "agent", "mock") or "mock"
# Load demo from file if provided
demo_text = None
if hasattr(args, "demo") and args.demo:
demo_path = Path(args.demo)
if demo_path.exists():
demo_text = demo_path.read_text()
print(f"Loaded demo from {demo_path} ({len(demo_text)} chars)")
else:
# Treat as direct demo text
demo_text = args.demo
# Check for demo library (for retrieval agents)
demo_library_path = getattr(args, "demo_library", None)
if agent_type == "mock":
agent = SmartMockAgent()
elif agent_type in ("noop", "done"):
# Minimal smoke-test agent: immediately returns DONE.
# This is useful for validating end-to-end connectivity + /evaluate plumbing
# without requiring API keys.
agent = ScriptedAgent([BenchmarkAction(type="done")])
print("Using ScriptedAgent (noop): immediate DONE")
elif agent_type in ("api-claude", "claude", "anthropic"):
try:
agent = ApiAgent(provider="anthropic", demo=demo_text)
print(f"Using ApiAgent with Claude (demo={'yes' if agent.demo else 'no'})")
except RuntimeError as e:
print(f"ERROR: {e}")
return 1
elif agent_type in ("api-openai", "openai", "gpt"):
try:
agent = ApiAgent(provider="openai", demo=demo_text)
print(f"Using ApiAgent with GPT-5.1 (demo={'yes' if agent.demo else 'no'})")
except RuntimeError as e:
print(f"ERROR: {e}")
return 1
elif agent_type in ("retrieval-claude", "retrieval-anthropic"):
if not demo_library_path:
print("ERROR: --demo-library required for retrieval agent")
return 1
try:
agent = RetrievalAugmentedAgent(
demo_library_path=demo_library_path,
provider="anthropic",
)
print(f"Using RetrievalAugmentedAgent with Claude (library={demo_library_path})")
except Exception as e:
print(f"ERROR: {e}")
return 1
elif agent_type in ("retrieval-openai", "retrieval-gpt"):
if not demo_library_path:
print("ERROR: --demo-library required for retrieval agent")
return 1
try:
agent = RetrievalAugmentedAgent(
demo_library_path=demo_library_path,
provider="openai",
)
print(f"Using RetrievalAugmentedAgent with GPT-5.1 (library={demo_library_path})")
except Exception as e:
print(f"ERROR: {e}")
return 1
elif agent_type in ("api-claude-cu", "claude-cu"):
try:
from openadapt_evals.agents import ClaudeComputerUseAgent
agent = ClaudeComputerUseAgent(demo=demo_text)
print(f"Using ClaudeComputerUseAgent (demo={'yes' if agent.demo else 'no'})")
except RuntimeError as e:
print(f"ERROR: {e}")
return 1
elif agent_type == "qwen3vl":
try:
from openadapt_evals.agents import Qwen3VLAgent
model_path = getattr(args, "model_path", None)
model_endpoint = getattr(args, "model_endpoint", None)
use_thinking = getattr(args, "use_thinking", False)
use_a11y_tree = getattr(args, "use_a11y_tree", False)
agent = Qwen3VLAgent(
model_path=model_path, model_endpoint=model_endpoint,
demo=demo_text, use_thinking=use_thinking,
use_accessibility_tree=use_a11y_tree,
)
print(f"Using Qwen3VLAgent (model={agent.model_path}, endpoint={agent.model_endpoint}, demo={'yes' if agent.demo else 'no'})")
except RuntimeError as e:
print(f"ERROR: {e}")
return 1
elif agent_type == "smol":
try:
from openadapt_evals.agents import SmolOperatorAgent
agent = SmolOperatorAgent(demo=demo_text)
print(f"Using SmolOperatorAgent (model={agent.model_path}, demo={'yes' if agent.demo else 'no'})")
except RuntimeError as e:
print(f"ERROR: {e}")
return 1
elif agent_type == "http":
agent_endpoint = getattr(args, "agent_endpoint", None)
if not agent_endpoint:
print("ERROR: --agent-endpoint required for http agent")
return 1
from openadapt_evals.agents import HttpAgent
agent = HttpAgent(endpoint_url=agent_endpoint)
print(f"Using HttpAgent (endpoint={agent_endpoint})")
else:
print(f"ERROR: Unknown agent type: {agent_type}")
print(
"Available: mock, noop, api-claude, api-openai, api-claude-cu, qwen3vl, smol, http, retrieval-claude, retrieval-openai"
)
return 1
# Create config for trace collection
done_gate = getattr(args, "done_gate", False)
done_gate_max_overrides = getattr(args, "done_gate_max_overrides", 3)
done_gate_threshold = getattr(args, "done_gate_threshold", 1.0)
eval_config = None
if args.output or done_gate:
eval_config = EvaluationConfig(
save_execution_traces=bool(args.output),
output_dir=args.output or "benchmark_results",
run_name=args.run_name or "live_eval",
done_gate=done_gate,
done_gate_max_overrides=done_gate_max_overrides,
done_gate_threshold=done_gate_threshold,
)
# Load tasks
if args.task_ids:
task_ids = args.task_ids.split(",")
else:
# For live evaluation, we need explicit task IDs
print("ERROR: --task-ids required for live evaluation")
print("Example: --task-ids notepad_1,notepad_2,browser_1")
return 1
# Run evaluation
results = evaluate_agent_on_benchmark(
agent=agent,
adapter=adapter,
max_steps=args.max_steps,
task_ids=task_ids,
config=eval_config,
)
# Compute and display metrics
metrics = compute_metrics(results)
print("\n" + "=" * 50)
print("Evaluation Results")
print("=" * 50)
print(f"Tasks: {metrics['num_tasks']}")
print(f"Success rate: {metrics['success_rate']:.1%}")
print(f"Avg score: {metrics['avg_score']:.3f}")
print(f"Avg steps: {metrics['avg_steps']:.1f}")
if metrics.get("num_infrastructure_failures", 0):
print(f"Infra fails: {metrics['num_infrastructure_failures']}")
print(f"Adj success: {metrics.get('success_rate_excluding_infra', 0.0):.1%}")
if eval_config:
benchmark_dir = Path(eval_config.output_dir) / eval_config.run_name
_write_run_environment_metadata(
benchmark_dir,
requested=_requested_environment_flags(args),
adapter=adapter,
server_url=args.server,
evaluate_url=evaluate_url,
)
print(f"\nResults saved to: {eval_config.output_dir}/{eval_config.run_name}")
return 0
def cmd_smoke_live(args: argparse.Namespace) -> int:
"""One-command live smoke test.
Starts the tagged WAA VM (or specified vm-name/resource-group), starts the
existing 'winarena' container, patches /evaluate, probes until ready, runs a
single live task, then deallocates the VM by default.
This is intended to validate "end-to-end" wiring (VM -> server -> adapter ->
runner -> /evaluate) without requiring any API keys.
"""
import base64
import time
from pathlib import Path
from openadapt_evals.adapters import WAALiveAdapter, WAALiveConfig
from openadapt_evals.adapters.base import BenchmarkAction
from openadapt_evals.agents.scripted_agent import ScriptedAgent
from openadapt_evals.benchmarks import EvaluationConfig, compute_metrics, evaluate_agent_on_benchmark
vm_context = _resolve_vm_context(args)
if not vm_context:
print("ERROR: Unable to resolve VM name/resource group.")
print("Set --vm-name/--resource-group or tag VM with openadapt-role=waa.")
print("Example: az vm update -g <rg> -n <vm> --set tags.openadapt-role=waa")
return 1
vm_name, resource_group = vm_context
def _run(cmd: list[str], *, timeout: int | None = None) -> subprocess.CompletedProcess:
return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
def patch_evaluate_endpoint() -> bool:
eval_path = Path(__file__).resolve().parents[1] / "server" / "evaluate_endpoint.py"
if not eval_path.exists():
print(f"WARNING: evaluate_endpoint.py not found at {eval_path}")
return False
payload = base64.b64encode(eval_path.read_bytes()).decode("ascii")
patch_script = f'''
set -e
CONTAINER_ID=$(docker ps -aq -f name=winarena)
if [ -z "$CONTAINER_ID" ]; then
echo "ERROR: No winarena container found"
exit 1
fi
TMPFILE=$(mktemp)
echo "{payload}" | base64 -d > "$TMPFILE"
docker cp "$TMPFILE" winarena:/home/azureuser/WindowsAgentArena/src/win-arena-container/vm/setup/server/evaluate_endpoint.py
rm -f "$TMPFILE"
docker exec winarena python - <<'PY'
from pathlib import Path
main_path = Path("/home/azureuser/WindowsAgentArena/src/win-arena-container/vm/setup/server/main.py")
marker = "# openadapt-evals: /evaluate endpoint"
content = main_path.read_text()
if marker not in content:
patch_block = (
"\n\n"
"# openadapt-evals: /evaluate endpoint\n"
"try:\n"
" from evaluate_endpoint import create_evaluate_blueprint\n"
" evaluate_bp = create_evaluate_blueprint()\n"
" app.register_blueprint(evaluate_bp)\n"
"except Exception as exc:\n"
" print(f\"WAA /evaluate endpoint disabled: {{exc}}\")\n"
)
if "if __name__ == \"__main__\":" in content:
parts = content.split("if __name__ == \"__main__\":", 1)
content = parts[0] + patch_block + "\nif __name__ == \"__main__\":" + parts[1]
else:
content += patch_block
main_path.write_text(content)
print("/evaluate endpoint patched")
PY
'''
try:
result = _run(
[
"az",
"vm",
"run-command",
"invoke",
"--resource-group",
resource_group,
"--name",
vm_name,
"--command-id",
"RunShellScript",
"--scripts",
patch_script,
],
timeout=900,
)
except subprocess.TimeoutExpired:
print("WARNING: /evaluate patch timed out (az vm run-command).")
return False
if result.returncode != 0:
print(f"WARNING: /evaluate patch failed: {result.stderr.strip()}")
return False
return True
server_url: str | None = None
try:
print(f"[1/6] Starting VM '{vm_name}'...")
result = _run(["az", "vm", "start", "--name", vm_name, "--resource-group", resource_group])
if result.returncode != 0:
print(f"ERROR: Failed to start VM: {result.stderr.strip()}")
return 1
print("[2/6] Getting public IP...")
result = _run(
[
"az",
"vm",
"show",
"--name",
vm_name,
"--resource-group",
resource_group,
"--show-details",
"--query",
"publicIps",
"-o",
"tsv",
]
)
if result.returncode != 0 or not result.stdout.strip():
print("ERROR: Could not get public IP")
return 1
public_ip = result.stdout.strip()
server_url = f"http://{public_ip}:5000"
print(f" Server URL: {server_url}")
print(f"[3/6] Waiting {args.boot_wait}s then starting winarena container...")
time.sleep(args.boot_wait)
start_script = '''
set -e
CONTAINER_ID=$(docker ps -aq -f name=winarena)
if [ -z "$CONTAINER_ID" ]; then
echo "ERROR: No winarena container found"
exit 1
fi
RUNNING=$(docker ps -q -f name=winarena)
if [ -z "$RUNNING" ]; then
echo "Starting winarena container (async)..."
nohup docker start winarena >/tmp/winarena_start.log 2>&1 &
disown || true
echo "Started docker start in background; see /tmp/winarena_start.log"
fi
sleep 3
docker ps -f name=winarena --format "Container: {{.Names}}, Status: {{.Status}}"
'''
try:
result = _run(
[
"az",
"vm",
"run-command",
"invoke",
"--resource-group",
resource_group,
"--name",
vm_name,
"--command-id",
"RunShellScript",
"--scripts",
start_script,
],
timeout=900,
)
except subprocess.TimeoutExpired:
print("ERROR: Timed out while starting winarena container (az vm run-command).")
return 1
if result.returncode != 0:
print(f"ERROR: Failed to start container: {result.stderr.strip()}")
return 1
print("[4/6] Patching /evaluate endpoint...")
patch_evaluate_endpoint()
print(f"[5/6] Probing server at {server_url}...")
try:
import requests
except ImportError:
print("ERROR: requests package required")
return 1
ready = False
for attempt in range(args.probe_attempts):
try:
resp = requests.get(f"{server_url}/probe", timeout=5.0)
if resp.status_code == 200:
ready = True
break
except Exception:
pass
time.sleep(args.probe_interval)
print(f" Attempt {attempt + 1}/{args.probe_attempts}: waiting...")
if not ready:
print("ERROR: WAA server not reachable after probing")
return 1
# Optional /evaluate health check
try:
eval_resp = requests.get(f"{server_url}/evaluate/health", timeout=5.0)
if eval_resp.status_code == 200:
print(" /evaluate endpoint: ready")
else:
print(f" WARNING: /evaluate endpoint health returned {eval_resp.status_code}")
except Exception:
print(" WARNING: /evaluate endpoint health check failed")
print("[6/6] Running single-task live evaluation...")
agent = ScriptedAgent([BenchmarkAction(type="done")])
adapter = WAALiveAdapter(
WAALiveConfig(
server_url=server_url,
max_steps=args.max_steps,