-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtest_agents.py
More file actions
2137 lines (1712 loc) · 79.4 KB
/
Copy pathtest_agents.py
File metadata and controls
2137 lines (1712 loc) · 79.4 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 json
import re
from pathlib import Path
import pytest
from brigade import agents
def test_build_argv_for_known_clis():
# A claude write run with no explicit sandbox must fail safely rather than
# silently grant full access (or stall on a permission prompt).
with pytest.raises(ValueError, match="explicit sandbox"):
agents.build_argv("claude", "hi")
assert agents.build_argv("codex", "hi") == ["codex", "exec", "-"]
assert agents.build_argv("opencode", "hi") == ["opencode", "run", "hi"]
assert agents.build_argv("antigravity", "hi") == [
"agy",
"--add-dir",
str(Path.cwd().resolve()),
"--dangerously-skip-permissions",
"--print",
"hi",
]
assert agents.build_argv("pi", "hi") == ["pi", "-p", "hi"]
assert agents.build_argv("cursor", "hi") == [
"cursor-agent",
"-p",
"--output-format",
"text",
"-f",
"hi",
]
assert agents.build_argv("aider", "hi") == ["aider", "--yes", "--no-auto-commits", "--message", "hi"]
assert agents.build_argv("goose", "hi") == ["goose", "run", "--no-session", "-t", "hi"]
assert agents.build_argv("continue", "hi") == ["cn", "-p", "hi"]
assert agents.build_argv("copilot", "hi") == ["copilot", "-p", "hi"]
assert agents.build_argv("qwen", "hi") == ["qwen", "-p", "hi", "--approval-mode", "yolo"]
assert agents.build_argv("kimi", "hi") == ["kimi", "-p", "hi"]
assert agents.build_argv("adal", "hi") == ["adal", "-q", "hi"]
assert agents.build_argv("openhands", "hi") == ["openhands", "--headless", "-t", "hi"]
assert agents.build_argv("grok", "hi") == ["grok", "-p", "hi", "--always-approve"]
assert agents.build_argv("amp", "hi") == ["amp", "-x", "hi"]
assert agents.build_argv("crush", "hi") == ["crush", "run", "hi"]
assert agents.build_argv("ollama:llama3.3", "hi") == ["ollama", "run", "llama3.3", "hi"]
def test_build_argv_for_read_only_codex():
assert agents.build_argv("codex", "hi", read_only=True) == [
"codex",
"exec",
"--sandbox",
"read-only",
"-",
]
assert agents.build_argv("claude", "hi", read_only=True) == [
"claude",
"-p",
"--permission-mode",
"plan",
"--disallowedTools",
"Task,Agent,Bash,Edit,Write,NotebookEdit,WebSearch,WebFetch,mcp__*",
"--",
"hi",
]
assert agents.build_argv("opencode", "hi", read_only=True) == ["opencode", "run", "hi"]
assert agents.build_argv("antigravity", "hi", read_only=True) == ["agy", "--sandbox", "--print", "hi"]
assert agents.build_argv("pi", "hi", read_only=True) == ["pi", "--tools", "read,grep,find,ls", "-p", "hi"]
assert agents.build_argv("cursor", "hi", read_only=True) == [
"cursor-agent",
"-p",
"--mode",
"plan",
"--output-format",
"text",
"--trust",
"hi",
]
assert agents.build_argv("aider", "hi", read_only=True) == [
"aider",
"--no-auto-commits",
"--dry-run",
"--message",
"hi",
]
assert agents.build_argv("continue", "hi", read_only=True) == ["cn", "-p", "hi", "--readonly"]
assert agents.build_argv("qwen", "hi", read_only=True) == ["qwen", "-p", "hi", "--approval-mode", "plan"]
kimi_read_only = agents.build_argv("kimi", "hi", read_only=True)
assert kimi_read_only[:2] == ["kimi", "-p"]
assert kimi_read_only[-1].startswith("Read-only planning run.")
assert agents.build_argv("goose", "hi", read_only=True)[-1].startswith("Read-only planning run.")
assert agents.build_argv("copilot", "hi", read_only=True)[-1].startswith("Read-only planning run.")
assert agents.build_argv("adal", "hi", read_only=True)[-1].startswith("Read-only planning run.")
assert agents.build_argv("openhands", "hi", read_only=True)[-1].startswith("Read-only planning run.")
assert agents.build_argv("grok", "hi", read_only=True) == [
"grok",
"-p",
"hi",
"--permission-mode",
"plan",
]
assert agents.build_argv("amp", "hi", read_only=True)[-1].startswith("Read-only planning run.")
assert agents.build_argv("crush", "hi", read_only=True)[-1].startswith("Read-only planning run.")
assert agents.build_argv("ollama:llama3.3", "hi", read_only=True) == [
"ollama",
"run",
"llama3.3",
"hi",
]
def test_claude_read_only_disallows_mutating_tools_and_subagents():
# Contract: read-only must be enforced by the CLI (a hard deny), not just
# the prompt. Subagents (Task, Agent) and every filesystem-mutating tool
# are removed from the model's context, and every MCP/plugin tool is
# removed via `mcp__*` so configured extension write tools cannot bypass
# read-only. Read-only is also enforced by `--permission-mode plan`,
# Claude's actual permission/sandbox mechanism, so a buggy `--disallowedTools`
# for MCP tools (anthropics/claude-code#12863) cannot let a write through.
argv = agents.build_argv("claude", "inspect it", read_only=True)
assert argv == [
"claude",
"-p",
"--permission-mode",
"plan",
"--disallowedTools",
"Task,Agent,Bash,Edit,Write,NotebookEdit,WebSearch,WebFetch,mcp__*",
"--",
"inspect it",
]
def test_claude_read_only_sandbox_variant_matches_read_only_flag():
assert agents.build_argv("claude", "inspect it", sandbox="read-only") == [
"claude",
"-p",
"--permission-mode",
"plan",
"--disallowedTools",
"Task,Agent,Bash,Edit,Write,NotebookEdit,WebSearch,WebFetch,mcp__*",
"--",
"inspect it",
]
def test_hides_write_tools_reports_plan_mode_seats():
# #518: plan-mode seats hide every write tool, so a prompt that leads the
# model toward a plan-file write produces a failed write, not a file.
assert agents.hides_write_tools("claude", read_only=True) is True
assert agents.hides_write_tools("claude", sandbox="read-only") is True
assert agents.hides_write_tools("grok", read_only=True) is True
assert agents.hides_write_tools("cursor", read_only=True) is True
assert agents.hides_write_tools("claude", sandbox="danger-full-access") is False
assert agents.hides_write_tools("codex", read_only=True) is False
assert agents.hides_write_tools("ollama:llama3.3", read_only=True) is False
def test_claude_write_run_uses_skip_permissions_and_disallows_subagents():
# Contract: only an explicit --sandbox danger-full-access request may add
# --dangerously-skip-permissions. A write run with no explicit sandbox must
# fail safely with actionable guidance instead of silently granting full
# access (or stalling on a permission prompt). The deny list always removes
# subagent spawning so the worker cannot delegate out of the seat.
expected = [
"claude",
"-p",
"--dangerously-skip-permissions",
"--disallowedTools",
"Task,Agent",
"--",
"implement it",
]
assert agents.build_argv("claude", "implement it", sandbox="danger-full-access") == expected
with pytest.raises(ValueError, match="explicit sandbox"):
agents.build_argv("claude", "implement it")
def test_claude_read_only_prompt_is_not_consumed_by_disallowed_tools():
# Regression for #446: `--disallowedTools` is variadic and greedily consumes
# every following non-flag argv element, splitting each on whitespace, so a
# multi-word prompt placed right after the deny list was shredded into deny
# rules ("##", "Code", "graph", ...). The `--` end-of-options separator must
# sit between the deny list and the prompt so the prompt survives intact.
prompt = "## Code graph of src/brigade/router.py"
argv = agents.build_argv("claude", prompt, read_only=True)
# The prompt survives intact as the final positional.
assert argv[-1] == prompt
# The deny list is a single unsplit argument equal to the constant.
disallowed_index = argv.index("--disallowedTools")
assert argv[disallowed_index + 1] == agents._CLAUDE_DISALLOWED_READ_ONLY
# Ordering invariant: `--` separates the variadic deny list from the prompt,
# so nothing else (including any prompt word) can leak into deny values.
assert argv[disallowed_index + 2] == "--"
assert argv[disallowed_index + 1 : argv.index("--")] == [agents._CLAUDE_DISALLOWED_READ_ONLY]
# Read-only enforcement stays intact.
assert argv[argv.index("--permission-mode") + 1] == "plan"
def test_claude_danger_full_access_prompt_is_not_consumed_by_disallowed_tools():
# Regression for #446, danger-full-access branch: same variadic
# `--disallowedTools` pitfall, same `--` separator guarantee.
prompt = "## Code graph of src/brigade/router.py"
argv = agents.build_argv("claude", prompt, sandbox="danger-full-access")
assert argv[-1] == prompt
disallowed_index = argv.index("--disallowedTools")
assert argv[disallowed_index + 1] == agents._CLAUDE_DISALLOWED_ALWAYS
assert argv[disallowed_index + 2] == "--"
assert argv[disallowed_index + 1 : argv.index("--")] == [agents._CLAUDE_DISALLOWED_ALWAYS]
assert "--dangerously-skip-permissions" in argv
def test_claude_read_only_denies_web_tools_that_prompt_for_approval():
# Regression for #456: under `--permission-mode plan`, Claude Code's built-in
# WebSearch/WebFetch tools route to an interactive approval prompt that a
# non-interactive Brigade worker cannot answer, so a read-only worker blocked
# with no final output. Both must be hidden from the read-only tool surface
# via the deny list, exactly like Bash/Edit/Write.
prompt = "summarize this module"
argv = agents.build_argv("claude", prompt, read_only=True)
disallowed_index = argv.index("--disallowedTools")
denied = argv[disallowed_index + 1].split(",")
assert "WebSearch" in denied
assert "WebFetch" in denied
# The deny list is still a single comma-joined argv element and the prompt
# is still separated by the end-of-options marker (#446/#451 must not
# regress): the web tool names must not leak into the prompt position.
assert argv[disallowed_index + 2] == "--"
assert argv[-1] == prompt
# The danger-full-access branch skips permissions entirely, so no prompt
# can block there; its deny list stays scoped to subagent spawning only.
full_access = agents.build_argv("claude", prompt, sandbox="danger-full-access")
full_denied = full_access[full_access.index("--disallowedTools") + 1]
assert full_denied == agents._CLAUDE_DISALLOWED_ALWAYS
assert "WebSearch" not in full_denied
assert "WebFetch" not in full_denied
def test_claude_workspace_write_rejected_before_launch():
# Contract: workspace-write cannot be truthfully enforced by this CLI
# version, so it is rejected before launch with an actionable error.
with pytest.raises(ValueError, match="workspace-write"):
agents.build_argv("claude", "implement it", sandbox="workspace-write")
def test_run_agent_claude_workspace_write_fails_without_spawn(monkeypatch):
spawned = []
def fake_run(argv, **kw):
spawned.append(argv)
return agents.proc.Result(0, "answer", "")
monkeypatch.setattr(agents.proc, "which", lambda c: "/x/" + c)
monkeypatch.setattr(agents.proc, "run", fake_run)
res = agents.run_agent("claude", "implement it", sandbox="workspace-write")
assert res.ok is False
assert res.failure_phase == "dispatch"
assert res.failure_kind == "unsupported-sandbox"
assert "workspace-write" in res.detail
assert "danger-full-access" in res.detail
assert spawned == [] # never launched the claude process
def test_run_agent_claude_write_without_sandbox_fails_safely(monkeypatch):
# Regression for finding 4: a claude write run with no explicit sandbox
# must fail safely with actionable guidance instead of silently adding
# --dangerously-skip-permissions (or stalling on a permission prompt). Only
# an explicit danger-full-access request may add the skip-permissions flag.
spawned = []
def fake_run(argv, **kw):
spawned.append(argv)
return agents.proc.Result(0, "answer", "")
monkeypatch.setattr(agents.proc, "which", lambda c: "/x/" + c)
monkeypatch.setattr(agents.proc, "run", fake_run)
res = agents.run_agent("claude", "implement it") # sandbox=None
assert res.ok is False
assert res.failure_phase == "dispatch"
assert res.failure_kind == "unsupported-sandbox"
assert "explicit sandbox" in res.detail
assert "danger-full-access" in res.detail
assert spawned == [] # never launched the claude process
# And the dangerous flag is not present anywhere it could have been added.
assert not any("--dangerously-skip-permissions" in argv for argv in spawned)
def test_read_only_enforcement_claude_is_hard():
# Contract: claude now hard-enforces read-only via --disallowedTools, so the
# advisory table must report 'hard' (not 'none') so --read-only stops warning
# that claude cannot be constrained.
assert agents.READ_ONLY_ENFORCEMENT["claude"] == "hard"
assert agents.read_only_enforcement("claude") == "hard"
assert agents.read_only_enforcement("claude", sandbox="read-only") == "hard"
def test_run_agent_non_sandbox_value_error_is_not_unsupported_sandbox(monkeypatch):
# Regression for finding 1 (CodeRabbit r3632410930): a ValueError from
# build_argv that is NOT a sandbox rejection (here, an unsupported model pin
# on goose) must not be mislabeled unsupported-sandbox. Only the dedicated
# UnsupportedSandboxError maps to unsupported-sandbox; other ValueErrors map
# to invalid-dispatch-args.
spawned = []
monkeypatch.setattr(agents.proc, "which", lambda c: "/x/" + c)
monkeypatch.setattr(agents.proc, "run", lambda argv, **kw: spawned.append(argv))
result = agents.run_agent("goose", "hi", model="anything")
assert result.ok is False
assert result.failure_phase == "dispatch"
assert result.failure_kind == "invalid-dispatch-args"
assert "does not support model pinning" in result.detail
assert spawned == []
def test_run_agent_unknown_cli_value_error_is_not_unsupported_sandbox(monkeypatch):
# A second non-sandbox ValueError class: an unknown cli must be
# invalid-dispatch-args, not unsupported-sandbox.
monkeypatch.setattr(agents.proc, "which", lambda c: "/x/" + c)
monkeypatch.setattr(agents.proc, "run", lambda argv, **kw: agents.proc.Result(0, "answer", ""))
result = agents.run_agent("nope", "hi")
assert result.ok is False
assert result.failure_phase == "dispatch"
assert result.failure_kind == "invalid-dispatch-args"
assert "unknown agent cli" in result.detail
def test_unsupported_sandbox_error_is_value_error_subclass():
# Contract: direct build_argv callers historically caught ValueError; the
# dedicated sandbox error stays a ValueError subclass so they keep working.
assert issubclass(agents.UnsupportedSandboxError, ValueError)
with pytest.raises(ValueError, match="workspace-write"):
agents.build_argv("claude", "implement it", sandbox="workspace-write")
with pytest.raises(ValueError, match="explicit sandbox"):
agents.build_argv("claude", "implement it")
def test_claude_read_only_enforces_permission_mode_plan_not_prompt_only():
# Regression for finding 5 (Greptile security r3632423694): Claude read-only
# must be enforced by Claude's actual permission/sandbox mechanism
# (`--permission-mode plan`), not a prompt-only claim. Plan mode routes file
# edits and shell-write tools to the permission callback and never
# auto-approves them, so configured MCP/plugin write tools -- which
# `--disallowedTools` cannot reach (anthropics/claude-code#12863) -- cannot
# bypass read-only. The deny list also strips every MCP/plugin tool via
# `mcp__*` as defense in depth.
argv = agents.build_argv("claude", "Write the secret to disk.", read_only=True)
# The actual permission/sandbox mechanism is present in the argv.
assert "--permission-mode" in argv
assert argv[argv.index("--permission-mode") + 1] == "plan"
# Every MCP/plugin tool is removed from context so extension write tools
# cannot bypass the built-in-only deny list.
disallowed = argv[argv.index("--disallowedTools") + 1].split(",")
assert "mcp__*" in disallowed
assert {"Task", "Agent", "Bash", "Edit", "Write", "NotebookEdit"}.issubset(disallowed)
# Read-only is NOT a prompt-only claim: the user prompt is passed through
# verbatim with no "do not modify" instruction injected by the adapter.
assert argv[-1] == "Write the secret to disk."
assert "Read-only planning run." not in argv[-1]
def test_build_argv_antigravity_writable_uses_cwd_write_approval(tmp_path):
assert agents.build_argv("antigravity", "hi", cwd=tmp_path) == [
"agy",
"--add-dir",
str(tmp_path),
"--dangerously-skip-permissions",
"--print",
"hi",
]
def test_build_argv_antigravity_writable_preserves_explicit_cwd():
cwd = Path("workspace")
assert agents.build_argv("antigravity", "hi", cwd=cwd) == [
"agy",
"--add-dir",
"workspace",
"--dangerously-skip-permissions",
"--print",
"hi",
]
def test_build_argv_antigravity_writable_uses_current_cwd_when_cwd_omitted(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
assert agents.build_argv("antigravity", "hi") == [
"agy",
"--add-dir",
str(tmp_path.resolve()),
"--dangerously-skip-permissions",
"--print",
"hi",
]
def test_research_antigravity_cli_uses_current_cwd_when_cwd_omitted(tmp_path, monkeypatch):
from brigade.research import llm
captured = {}
def fake_run(argv, **kw):
captured["argv"] = argv
captured["cwd"] = kw["cwd"]
return agents.proc.Result(0, "answer", "")
monkeypatch.chdir(tmp_path)
monkeypatch.setattr(agents.proc, "which", lambda c: "/x/" + c)
monkeypatch.setattr(agents.proc, "run", fake_run)
assert llm._run_cli("antigravity", "hi", 10) == "answer"
assert captured["cwd"] is None
assert captured["argv"] == [
"/x/agy",
"--add-dir",
str(tmp_path.resolve()),
"--dangerously-skip-permissions",
"--print",
"hi",
]
def test_build_argv_antigravity_read_only_keeps_sandbox_without_write_flags(tmp_path):
assert agents.build_argv("antigravity", "hi", read_only=True, cwd=tmp_path) == [
"agy",
"--sandbox",
"--print",
"hi",
]
argv = agents.build_argv("antigravity", "hi", sandbox="read-only", cwd=tmp_path)
assert argv == ["agy", "--sandbox", "--print", "hi"]
assert "--add-dir" not in argv
assert "--dangerously-skip-permissions" not in argv
def test_build_argv_cursor_sandbox_read_only_uses_plan_mode():
assert agents.build_argv("cursor", "hi", sandbox="read-only") == [
"cursor-agent",
"-p",
"--mode",
"plan",
"--output-format",
"text",
"--trust",
"hi",
]
def test_build_argv_kimi_prompt_mode_uses_soft_read_only_instruction():
assert agents.build_argv("kimi", "hi") == ["kimi", "-p", "hi"]
read_only = agents.build_argv("kimi", "hi", read_only=True)
assert read_only[:2] == ["kimi", "-p"]
assert read_only[-1].startswith("Read-only planning run.")
assert "--yolo" not in read_only
def test_build_argv_can_set_codex_sandbox():
assert agents.build_argv("codex", "hi", sandbox="danger-full-access") == [
"codex",
"exec",
"--sandbox",
"danger-full-access",
"-",
]
assert agents.build_argv("codex", "hi", read_only=True, sandbox="workspace-write") == [
"codex",
"exec",
"--sandbox",
"workspace-write",
"-",
]
def test_build_argv_unknown_raises():
with pytest.raises(ValueError):
agents.build_argv("nope", "hi")
def test_build_argv_pins_model_for_claude_and_codex():
assert agents.build_argv("claude", "hi", sandbox="danger-full-access", model="claude-fable-5") == [
"claude",
"--model",
"claude-fable-5",
"-p",
"--dangerously-skip-permissions",
"--disallowedTools",
"Task,Agent",
"--",
"hi",
]
assert agents.build_argv("codex", "hi", model="gpt-5.5-codex") == [
"codex",
"exec",
"-m",
"gpt-5.5-codex",
"-",
]
assert agents.build_argv("codex", "hi", read_only=True, model="gpt-5.5-codex") == [
"codex",
"exec",
"--sandbox",
"read-only",
"-m",
"gpt-5.5-codex",
"-",
]
assert agents.build_argv("codex", "hi", sandbox="workspace-write", model="gpt-5.5-codex") == [
"codex",
"exec",
"--sandbox",
"workspace-write",
"-m",
"gpt-5.5-codex",
"-",
]
def test_build_argv_without_model_is_unchanged():
assert agents.build_argv("claude", "hi", sandbox="danger-full-access", model=None) == [
"claude",
"-p",
"--dangerously-skip-permissions",
"--disallowedTools",
"Task,Agent",
"--",
"hi",
]
assert agents.build_argv("codex", "hi", model=None) == ["codex", "exec", "-"]
def test_build_argv_model_on_unsupported_cli_raises():
with pytest.raises(ValueError, match="model"):
agents.build_argv("goose", "hi", model="anything")
def test_build_argv_model_on_ollama_ref_raises():
with pytest.raises(ValueError, match="model"):
agents.build_argv("ollama:llama3.3", "hi", model="mistral")
def test_command_for_returns_binary():
assert agents.command_for("claude") == "claude"
assert agents.command_for("codex") == "codex"
assert agents.command_for("opencode") == "opencode"
assert agents.command_for("antigravity") == "agy"
assert agents.command_for("pi") == "pi"
assert agents.command_for("cursor") == "cursor-agent"
assert agents.command_for("aider") == "aider"
assert agents.command_for("goose") == "goose"
assert agents.command_for("continue") == "cn"
assert agents.command_for("copilot") == "copilot"
assert agents.command_for("qwen") == "qwen"
assert agents.command_for("kimi") == "kimi"
assert agents.command_for("adal") == "adal"
assert agents.command_for("openhands") == "openhands"
assert agents.command_for("grok") == "grok"
assert agents.command_for("amp") == "amp"
assert agents.command_for("crush") == "crush"
assert agents.command_for("ollama:llama3.3") == "ollama"
def test_is_known():
assert agents.is_known("claude")
assert agents.is_known("codex")
assert agents.is_known("opencode")
assert agents.is_known("antigravity")
assert agents.is_known("pi")
assert agents.is_known("cursor")
assert agents.is_known("aider")
assert agents.is_known("goose")
assert agents.is_known("continue")
assert agents.is_known("copilot")
assert agents.is_known("qwen")
assert agents.is_known("kimi")
assert agents.is_known("adal")
assert agents.is_known("openhands")
assert agents.is_known("grok")
assert agents.is_known("amp")
assert agents.is_known("crush")
assert agents.is_known("ollama:anything")
assert not agents.is_known("bogus")
def test_run_agent_reports_missing(monkeypatch):
monkeypatch.setattr(agents.proc, "which", lambda c: None)
res = agents.run_agent("claude", "hi")
assert res.ok is False
assert "not installed" in res.detail
_OLLAMA_LIST_HEADER = "NAME ID SIZE MODIFIED\n"
def _fake_ollama_env(monkeypatch, list_result, run_result=None):
"""Route proc.run so `ollama list` returns list_result and record any other argv."""
calls = []
def fake_run(argv, **kw):
calls.append(argv)
if len(argv) >= 2 and Path(argv[0]).name == "ollama" and argv[1] == "list":
return list_result
return run_result if run_result is not None else agents.proc.Result(0, "answer", "")
monkeypatch.setattr(agents.proc, "which", lambda c: "/x/" + c)
monkeypatch.setattr(agents.proc, "run", fake_run)
return calls
def test_run_agent_ollama_refuses_model_not_pulled(monkeypatch):
# `ollama run` on a missing model silently auto-pulls it (43GB for
# llama3.3, once enough to fill a root disk); dispatch must refuse instead.
listing = agents.proc.Result(0, _OLLAMA_LIST_HEADER + "other:latest abc 2.0 GB 2 days ago\n", "")
calls = _fake_ollama_env(monkeypatch, listing)
res = agents.run_agent("ollama:llama3.3", "hi")
assert res.ok is False
assert "not pulled locally" in res.detail
assert "never auto-pulls" in res.detail
assert calls == [["/x/ollama", "list"]]
def test_run_agent_ollama_runs_when_model_pulled(monkeypatch):
listing = agents.proc.Result(0, _OLLAMA_LIST_HEADER + "llama3.3:latest abc 43 GB 2 days ago\n", "")
calls = _fake_ollama_env(monkeypatch, listing)
res = agents.run_agent("ollama:llama3.3", "hi")
assert res.ok is True
assert res.text == "answer"
assert calls[-1] == ["/x/ollama", "run", "llama3.3", "hi"]
def test_run_agent_ollama_matches_exact_tag(monkeypatch):
listing = agents.proc.Result(0, _OLLAMA_LIST_HEADER + "llama3.2:3b abc 2.0 GB 2 days ago\n", "")
calls = _fake_ollama_env(monkeypatch, listing)
res = agents.run_agent("ollama:llama3.2:3b", "hi")
assert res.ok is True
assert calls[-1] == ["/x/ollama", "run", "llama3.2:3b", "hi"]
def test_run_agent_ollama_fails_seat_when_list_fails(monkeypatch):
listing = agents.proc.Result(1, "", "could not connect to ollama server")
calls = _fake_ollama_env(monkeypatch, listing)
res = agents.run_agent("ollama:llama3.2:3b", "hi")
assert res.ok is False
assert "could not list local ollama models" in res.detail
assert calls == [["/x/ollama", "list"]]
def test_run_agent_captures_output(monkeypatch):
monkeypatch.setattr(agents.proc, "which", lambda c: "/x/" + c)
monkeypatch.setattr(agents.proc, "run", lambda argv, **kw: agents.proc.Result(0, " answer ", ""))
res = agents.run_agent("codex", "do it")
assert res.ok is True
assert res.text == "answer"
assert res.stdout == " answer "
assert res.stderr == ""
assert res.exit_code == 0
assert res.timed_out is False
def test_run_agent_rejects_decode_failure_even_when_exit_zero(monkeypatch):
decode_error = "child stderr is not valid UTF-8 (utf-8): 'utf-8' codec can't decode byte 0x9d in position 0"
monkeypatch.setattr(agents.proc, "which", lambda c: "/x/" + c)
monkeypatch.setattr(
agents.proc,
"run",
lambda argv, **kwargs: agents.proc.Result(
0,
"final answer\n",
decode_error,
stderr_decode_error=decode_error,
),
)
result = agents.run_agent("codex", "do it")
assert result.ok is False
assert result.text == "final answer"
assert result.exit_code == 0
assert result.failure_phase == "harness"
assert result.failure_kind == "decode-failure"
assert decode_error in result.detail
def test_run_agent_rejects_structured_grok_decode_failure_before_parsing(monkeypatch):
decode_error = "child stdout is not valid UTF-8 (utf-8): 'utf-8' codec can't decode byte 0x9d in position 7"
partial_stdout = "prefix\n\ufffd"
monkeypatch.setattr(agents.proc, "which", lambda c: "/x/" + c)
monkeypatch.setattr(
agents.proc,
"run",
lambda argv, **kwargs: agents.proc.Result(
0,
partial_stdout,
decode_error,
stdout_decode_error=decode_error,
),
)
def fail_if_called(*args, **kwargs):
raise AssertionError("_parse_grok_final_output must not run when decode_failed")
monkeypatch.setattr(agents, "_parse_grok_final_output", fail_if_called)
result = agents.run_agent("grok", "review it", read_only=True, model="grok-4.5")
assert result.ok is False
assert result.text == partial_stdout.strip()
assert result.exit_code == 0
assert result.failure_phase == "harness"
assert result.failure_kind == "decode-failure"
assert decode_error in result.detail
def test_run_agent_rejects_intent_only_antigravity_output(monkeypatch):
output = "\n".join(
[
"I will locate the relevant files in the repository.",
"I will list the repository contents to understand its structure.",
"I will run a search for the provider dispatch path.",
"I will inspect the matching source files next.",
]
)
monkeypatch.setattr(agents.proc, "which", lambda command: "/x/" + command)
monkeypatch.setattr(agents.proc, "run", lambda argv, **kwargs: agents.proc.Result(0, output + "\n", ""))
result = agents.run_agent("antigravity", "trace it", model="Gemini 3.5 Flash (High)")
assert result.ok is False
assert result.text == output
assert result.exit_code == 0
assert result.failure_phase == "output-validation"
assert result.failure_kind == "non-final-output"
assert result.detail == "provider returned progress or intent without a final result"
@pytest.mark.parametrize(
"output",
[
"Reviewing repository files.",
"First, I will inspect the repo.",
"Now I will run the tests.",
"I'm going to inspect the files first.",
"I am inspecting the files first.",
],
)
def test_run_agent_rejects_bare_progress_only_output(monkeypatch, output):
monkeypatch.setattr(agents.proc, "which", lambda command: "/x/" + command)
monkeypatch.setattr(
agents.proc,
"run",
lambda argv, **kwargs: agents.proc.Result(0, output + "\n", ""),
)
result = agents.run_agent("antigravity", "review it")
assert result.ok is False
assert result.failure_kind == "non-final-output"
def test_run_agent_rejects_progress_over_changed_files(monkeypatch):
monkeypatch.setattr(agents.proc, "which", lambda command: "/x/" + command)
monkeypatch.setattr(
agents.proc,
"run",
lambda argv, **kwargs: agents.proc.Result(0, "Reviewing changed files.\n", ""),
)
result = agents.run_agent("antigravity", "review it")
assert result.ok is False
assert result.failure_kind == "non-final-output"
@pytest.mark.parametrize(
"payload",
[
{"tool_calls": [{"name": "read_file", "arguments": {"path": "README.md"}}]},
{"tool_calls": [{"name": "write_file", "arguments": {"text": "content"}}]},
{"type": "tool_call", "name": "read_file", "arguments": {"path": "README.md"}},
{"type": "tool_call", "name": "write_file", "arguments": {"text": "content"}},
{"name": "read_file", "arguments": {"path": "README.md"}},
{"name": "write_file", "arguments": {"text": "content"}},
{"type": "function_call_output", "call_id": "call-1", "output": "file contents"},
{"type": "tool_result", "content": "file contents"},
{"call_id": "call-1", "output": "file contents"},
],
)
def test_run_agent_rejects_tool_call_only_output(monkeypatch, payload):
output = json.dumps(payload)
monkeypatch.setattr(agents.proc, "which", lambda command: "/x/" + command)
monkeypatch.setattr(agents.proc, "run", lambda argv, **kwargs: agents.proc.Result(0, output, ""))
result = agents.run_agent("antigravity", "inspect it")
assert result.ok is False
assert result.failure_phase == "output-validation"
assert result.failure_kind == "tool-only-output"
assert result.detail == "provider returned tool-call data without a final result"
@pytest.mark.parametrize(
"output",
[
'<tool_use>{"name":"read_file","path":"README.md"}</tool_use>',
'<tool_use name="read_file">{"path":"README.md"}</tool_use>',
'<tool_call name="read_file"/><function_call>{"name":"inspect"}</function_call>',
],
)
def test_run_agent_rejects_tool_use_markup_without_final_text(monkeypatch, output):
monkeypatch.setattr(agents.proc, "which", lambda command: "/x/" + command)
monkeypatch.setattr(agents.proc, "run", lambda argv, **kwargs: agents.proc.Result(0, output, ""))
result = agents.run_agent("antigravity", "inspect it")
assert result.ok is False
assert result.failure_kind == "tool-only-output"
def test_run_agent_rejects_tool_call_and_tool_result_transcript(monkeypatch):
output = json.dumps(
{
"messages": [
{
"role": "assistant",
"content": "I will inspect the repository first.",
"tool_calls": [{"name": "read_file", "arguments": {"path": "README.md"}}],
},
{"role": "tool", "type": "tool_result", "content": "file contents"},
]
}
)
monkeypatch.setattr(agents.proc, "which", lambda command: "/x/" + command)
monkeypatch.setattr(agents.proc, "run", lambda argv, **kwargs: agents.proc.Result(0, output, ""))
result = agents.run_agent("antigravity", "inspect it")
assert result.ok is False
assert result.failure_kind == "tool-only-output"
@pytest.mark.parametrize("result_type", ["function_call_output", "tool_call_output"])
def test_run_agent_rejects_call_output_without_final_text(monkeypatch, result_type):
output = json.dumps(
{
"items": [
{"type": "function_call", "name": "read_file", "arguments": "{}"},
{"type": result_type, "call_id": "call-1", "output": "file contents"},
]
}
)
monkeypatch.setattr(agents.proc, "which", lambda command: "/x/" + command)
monkeypatch.setattr(agents.proc, "run", lambda argv, **kwargs: agents.proc.Result(0, output, ""))
result = agents.run_agent("antigravity", "inspect it")
assert result.ok is False
assert result.failure_kind == "tool-only-output"
@pytest.mark.parametrize(
("output", "failure_kind"),
[
("Error: authentication required. Run provider login.", "authentication-error"),
("Error: failed to connect to the model provider.", "network-error"),
("Error: model gemini-example is not available.", "provider-setting-error"),
("Error: rate limit exceeded for this provider.", "rate-limit-error"),
],
)
def test_run_agent_rejects_in_band_operational_diagnostics(monkeypatch, output, failure_kind):
monkeypatch.setattr(agents.proc, "which", lambda command: "/x/" + command)
monkeypatch.setattr(agents.proc, "run", lambda argv, **kwargs: agents.proc.Result(0, output, ""))
result = agents.run_agent("antigravity", "answer directly")
assert result.ok is False
assert result.failure_phase == "output-validation"
assert result.failure_kind == failure_kind
assert result.detail.startswith("provider returned an operational error instead of a final result:")
@pytest.mark.parametrize(
"output",
[
"No findings.",
"OK",
"I will inspect the repository first. No findings.",
"Running the targeted tests passed.",
"Checking the implementation, I do not see any regressions.",
"```text\nError: NonRetriableError: Provider Error\n```\nThis is the requested fixture.",
],
)
def test_run_agent_accepts_short_or_quoted_substantive_output(monkeypatch, output):
monkeypatch.setattr(agents.proc, "which", lambda command: "/x/" + command)
monkeypatch.setattr(agents.proc, "run", lambda argv, **kwargs: agents.proc.Result(0, output, ""))
result = agents.run_agent("antigravity", "answer directly")
assert result.ok is True
assert result.text == output
def test_run_agent_forwards_model_to_argv(monkeypatch):
captured = {}
def fake_run(argv, **kw):
captured["argv"] = argv
return agents.proc.Result(0, "answer", "")
monkeypatch.setattr(agents.proc, "which", lambda c: "/x/" + c)
monkeypatch.setattr(agents.proc, "run", fake_run)
res = agents.run_agent("claude", "hi", sandbox="danger-full-access", model="claude-fable-5")
assert res.ok is True
assert captured["argv"] == [
"/x/claude",
"--model",
"claude-fable-5",
"-p",
"--dangerously-skip-permissions",
"--disallowedTools",
"Task,Agent",
"--",
"hi",
]
def test_run_agent_codex_feeds_prompt_on_stdin(monkeypatch):
"""codex exec must take the prompt on stdin (`-`), not as a trailing argv token.
Codex 0.144+ treats a non-TTY open stdin as optional append input and can
hang on 'Reading additional input from stdin...' when the prompt is only
passed as an argument.
"""
captured = {}
def fake_run(argv, **kw):
captured["argv"] = argv
captured["stdin"] = kw.get("stdin")
return agents.proc.Result(0, "answer", "")
monkeypatch.setattr(agents.proc, "which", lambda c: "/x/" + c)
monkeypatch.setattr(agents.proc, "run", fake_run)
res = agents.run_agent("codex", "plan this task", model="gpt-5.5", read_only=True)
assert res.ok is True
assert captured["argv"] == [
"/x/codex",
"exec",
"--sandbox",
"read-only",
"-m",
"gpt-5.5",
"-",
]
assert captured["stdin"] == b"plan this task"
def test_run_agent_maps_codex_stdin_hang_banner(monkeypatch):
def fake_run(argv, **kw):
return agents.proc.Result(
124,
"",
"Reading additional input from stdin...\nOpenAI Codex v0.144.5\n--------\n",
)
monkeypatch.setattr(agents.proc, "which", lambda c: "/x/" + c)
monkeypatch.setattr(agents.proc, "run", fake_run)
res = agents.run_agent("codex", "hi")
assert res.ok is False
assert "Reading additional input from stdin" not in res.detail
assert "stdin" in res.detail.lower()
assert "codex" in res.detail.lower()
@pytest.mark.parametrize(
("cli_ref", "expected"),
[
("codex", ["codex", "exec", "-c", 'model_reasoning_effort="xhigh"', "-"]),
("opencode", ["opencode", "run", "--variant", "xhigh", "hi"]),
("pi", ["pi", "--thinking", "xhigh", "-p", "hi"]),
("grok", ["grok", "--reasoning-effort", "xhigh", "-p", "hi", "--always-approve"]),
],
)
def test_build_argv_applies_reasoning(cli_ref, expected):
assert agents.build_argv(cli_ref, "hi", reasoning="xhigh") == expected
def test_build_argv_rejects_reasoning_for_unsupported_adapter():
with pytest.raises(ValueError, match="does not support reasoning"):
agents.build_argv("claude", "hi", sandbox="danger-full-access", reasoning="high")