forked from openai/openai-agents-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_shell_tool.py
More file actions
813 lines (691 loc) · 26.3 KB
/
Copy pathtest_shell_tool.py
File metadata and controls
813 lines (691 loc) · 26.3 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
from __future__ import annotations
import json
from typing import Any, cast
import pytest
from agents import (
Agent,
RunConfig,
RunContextWrapper,
RunHooks,
ShellCallOutcome,
ShellCommandOutput,
ShellResult,
ShellTool,
UserError,
set_tracing_disabled,
trace,
)
from agents.items import ToolApprovalItem, ToolCallOutputItem
from agents.run_internal.run_loop import ShellAction, ToolRunShellCall, execute_shell_calls
from agents.tool import ShellOnApprovalFunctionResult
from .testing_processor import SPAN_PROCESSOR_TESTING
from .utils.hitl import (
HITL_REJECTION_MSG,
make_context_wrapper,
make_model_and_agent,
make_on_approval_callback,
make_shell_call,
reject_tool_call,
require_approval,
)
def _get_function_span(tool_name: str) -> dict[str, Any]:
for span in SPAN_PROCESSOR_TESTING.get_ordered_spans(including_empty=True):
exported = span.export()
if not exported:
continue
span_data = exported.get("span_data")
if not isinstance(span_data, dict):
continue
if span_data.get("type") == "function" and span_data.get("name") == tool_name:
return exported
raise AssertionError(f"Function span for tool '{tool_name}' not found")
def _shell_call(call_id: str = "call_shell") -> dict[str, Any]:
return cast(
dict[str, Any],
make_shell_call(
call_id,
id_value="shell_call",
commands=["echo hi"],
status="completed",
),
)
def test_shell_tool_defaults_to_local_environment() -> None:
shell_tool = ShellTool(executor=lambda request: "ok")
assert shell_tool.environment == {"type": "local"}
assert shell_tool.executor is not None
def test_shell_tool_supports_hosted_environment_without_executor() -> None:
shell_tool = ShellTool(
environment={
"type": "container_reference",
"container_id": "cntr_123",
}
)
assert shell_tool.environment == {"type": "container_reference", "container_id": "cntr_123"}
assert shell_tool.executor is None
def test_shell_tool_normalizes_container_auto_environment() -> None:
shell_tool = ShellTool(
environment={
"type": "container_auto",
"file_ids": ["file_123"],
"memory_limit": "4g",
"network_policy": {
"type": "allowlist",
"allowed_domains": ["example.com"],
"domain_secrets": [
{
"domain": "example.com",
"name": "API_TOKEN",
"value": "secret",
}
],
},
"skills": [
{"type": "skill_reference", "skill_id": "skill_123", "version": "latest"},
{
"type": "inline",
"name": "csv-workbench",
"description": "Analyze CSV files.",
"source": {
"type": "base64",
"media_type": "application/zip",
"data": "ZmFrZS16aXA=",
},
},
],
}
)
assert shell_tool.environment == {
"type": "container_auto",
"file_ids": ["file_123"],
"memory_limit": "4g",
"network_policy": {
"type": "allowlist",
"allowed_domains": ["example.com"],
"domain_secrets": [
{
"domain": "example.com",
"name": "API_TOKEN",
"value": "secret",
}
],
},
"skills": [
{"type": "skill_reference", "skill_id": "skill_123", "version": "latest"},
{
"type": "inline",
"name": "csv-workbench",
"description": "Analyze CSV files.",
"source": {
"type": "base64",
"media_type": "application/zip",
"data": "ZmFrZS16aXA=",
},
},
],
}
def test_shell_tool_rejects_local_mode_without_executor() -> None:
with pytest.raises(UserError, match="requires an executor"):
ShellTool()
with pytest.raises(UserError, match="requires an executor"):
ShellTool(environment={"type": "local"})
def test_shell_tool_allows_unvalidated_hosted_environment_shapes() -> None:
shell_tool = ShellTool(environment=cast(Any, {"type": "container_reference"}))
assert shell_tool.environment == {"type": "container_reference"}
shell_tool = ShellTool(
environment=cast(
Any,
{
"type": "container_auto",
"network_policy": {
"type": "future_mode",
"allowed_domains": ["example.com"],
"some_new_field": True,
},
"skills": [{"type": "skill_reference"}],
},
)
)
assert isinstance(shell_tool.environment, dict)
assert shell_tool.environment["type"] == "container_auto"
def test_shell_tool_rejects_local_executor_and_approval_for_hosted_environment() -> None:
with pytest.raises(UserError, match="does not accept an executor"):
ShellTool(
executor=lambda request: "ok",
environment={"type": "container_reference", "container_id": "cntr_123"},
)
with pytest.raises(UserError, match="does not support needs_approval or on_approval"):
ShellTool(
environment={"type": "container_reference", "container_id": "cntr_123"},
needs_approval=True,
)
with pytest.raises(UserError, match="does not support needs_approval or on_approval"):
ShellTool(
environment={"type": "container_reference", "container_id": "cntr_123"},
on_approval=lambda _context, _item: {"approve": True},
)
@pytest.mark.asyncio
async def test_execute_shell_calls_surfaces_missing_local_executor() -> None:
shell_tool = ShellTool(
environment={
"type": "container_reference",
"container_id": "cntr_123",
}
)
tool_run = ToolRunShellCall(tool_call=_shell_call(), shell_tool=shell_tool)
agent = Agent(name="shell-agent", tools=[shell_tool])
context_wrapper: RunContextWrapper[Any] = RunContextWrapper(context=None)
result = await execute_shell_calls(
public_agent=agent,
calls=[tool_run],
context_wrapper=context_wrapper,
hooks=RunHooks[Any](),
config=RunConfig(),
)
assert len(result) == 1
output_item = result[0]
assert isinstance(output_item, ToolCallOutputItem)
assert output_item.output == "Shell tool has no local executor configured."
raw_item = cast(dict[str, Any], output_item.raw_item)
assert raw_item["type"] == "shell_call_output"
assert raw_item["call_id"] == "call_shell"
assert raw_item["status"] == "failed"
@pytest.mark.asyncio
async def test_shell_tool_structured_output_is_rendered() -> None:
shell_tool = ShellTool(
executor=lambda request: ShellResult(
output=[
ShellCommandOutput(
command="echo hi",
stdout="hi\n",
outcome=ShellCallOutcome(type="exit", exit_code=0),
),
ShellCommandOutput(
command="ls",
stdout="README.md\nsrc\n",
stderr="warning",
outcome=ShellCallOutcome(type="exit", exit_code=1),
),
],
provider_data={"runner": "demo"},
max_output_length=4096,
)
)
tool_call = _shell_call()
tool_call["action"]["commands"] = ["echo hi", "ls"]
tool_call["action"]["max_output_length"] = 4096
tool_run = ToolRunShellCall(tool_call=tool_call, shell_tool=shell_tool)
agent = Agent(name="shell-agent", tools=[shell_tool])
context_wrapper: RunContextWrapper[Any] = RunContextWrapper(context=None)
result = await ShellAction.execute(
agent=agent,
call=tool_run,
hooks=RunHooks[Any](),
context_wrapper=context_wrapper,
config=RunConfig(),
)
assert isinstance(result, ToolCallOutputItem)
assert "$ echo hi" in result.output
assert "stderr:\nwarning" in result.output
raw_item = cast(dict[str, Any], result.raw_item)
assert raw_item["type"] == "shell_call_output"
assert raw_item["status"] == "completed"
assert raw_item["provider_data"]["runner"] == "demo"
assert raw_item["max_output_length"] == 4096
shell_output = raw_item["shell_output"]
assert shell_output[1]["exit_code"] == 1
assert isinstance(raw_item["output"], list)
first_output = raw_item["output"][0]
assert first_output["stdout"].startswith("hi")
assert first_output["outcome"]["type"] == "exit"
assert first_output["outcome"]["exit_code"] == 0
assert "command" not in first_output
input_payload = result.to_input_item()
assert isinstance(input_payload, dict)
payload_dict = cast(dict[str, Any], input_payload)
assert payload_dict["type"] == "shell_call_output"
assert "status" not in payload_dict
assert "shell_output" not in payload_dict
assert "provider_data" not in payload_dict
@pytest.mark.asyncio
async def test_shell_tool_emits_function_span() -> None:
shell_tool = ShellTool(executor=lambda request: "shell span output")
tool_run = ToolRunShellCall(tool_call=_shell_call("call_shell_trace"), shell_tool=shell_tool)
agent = Agent(name="shell-agent", tools=[shell_tool])
context_wrapper: RunContextWrapper[Any] = RunContextWrapper(context=None)
set_tracing_disabled(False)
with trace("shell-span-test"):
result = await ShellAction.execute(
agent=agent,
call=tool_run,
hooks=RunHooks[Any](),
context_wrapper=context_wrapper,
config=RunConfig(),
)
assert isinstance(result, ToolCallOutputItem)
function_span = _get_function_span(shell_tool.name)
span_data = cast(dict[str, Any], function_span["span_data"])
assert "echo hi" in cast(str, span_data.get("input", ""))
assert span_data.get("output") == "shell span output"
@pytest.mark.asyncio
async def test_shell_tool_redacts_span_error_when_sensitive_data_disabled() -> None:
secret_error = "shell secret output"
class ExplodingExecutor:
def __call__(self, request):
raise RuntimeError(secret_error)
shell_tool = ShellTool(executor=ExplodingExecutor())
tool_run = ToolRunShellCall(
tool_call=_shell_call("call_shell_trace_redacted"),
shell_tool=shell_tool,
)
agent = Agent(name="shell-agent", tools=[shell_tool])
context_wrapper: RunContextWrapper[Any] = RunContextWrapper(context=None)
set_tracing_disabled(False)
with trace("shell-span-redaction-test"):
result = await ShellAction.execute(
agent=agent,
call=tool_run,
hooks=RunHooks[Any](),
context_wrapper=context_wrapper,
config=RunConfig(trace_include_sensitive_data=False),
)
assert isinstance(result, ToolCallOutputItem)
function_span = _get_function_span(shell_tool.name)
assert function_span.get("error") == {
"message": "Error running tool",
"data": {
"tool_name": shell_tool.name,
"error": "Tool execution failed. Error details are redacted.",
},
}
assert secret_error not in json.dumps(function_span)
span_data = cast(dict[str, Any], function_span["span_data"])
assert span_data.get("input") is None
assert span_data.get("output") is None
@pytest.mark.asyncio
async def test_shell_tool_executor_failure_returns_error() -> None:
class ExplodingExecutor:
def __call__(self, request):
raise RuntimeError("boom" * 10)
shell_tool = ShellTool(executor=ExplodingExecutor())
tool_call = {
"type": "shell_call",
"id": "shell_call_fail",
"call_id": "call_shell_fail",
"status": "completed",
"action": {
"commands": ["echo boom"],
"timeout_ms": 1000,
"max_output_length": 6,
},
}
tool_run = ToolRunShellCall(tool_call=tool_call, shell_tool=shell_tool)
agent = Agent(name="shell-agent", tools=[shell_tool])
context_wrapper: RunContextWrapper[Any] = RunContextWrapper(context=None)
result = await ShellAction.execute(
agent=agent,
call=tool_run,
hooks=RunHooks[Any](),
context_wrapper=context_wrapper,
config=RunConfig(),
)
assert isinstance(result, ToolCallOutputItem)
assert result.output == "boombo"
raw_item = cast(dict[str, Any], result.raw_item)
assert raw_item["type"] == "shell_call_output"
assert raw_item["status"] == "failed"
assert raw_item["max_output_length"] == 6
assert isinstance(raw_item["output"], list)
assert raw_item["output"][0]["stdout"] == "boombo"
first_output = raw_item["output"][0]
assert first_output["outcome"]["type"] == "exit"
assert first_output["outcome"]["exit_code"] == 1
assert "command" not in first_output
assert isinstance(raw_item["output"], list)
input_payload = result.to_input_item()
assert isinstance(input_payload, dict)
payload_dict = cast(dict[str, Any], input_payload)
assert payload_dict["type"] == "shell_call_output"
assert "status" not in payload_dict
assert "shell_output" not in payload_dict
assert "provider_data" not in payload_dict
@pytest.mark.asyncio
async def test_shell_tool_output_respects_max_output_length() -> None:
shell_tool = ShellTool(
executor=lambda request: ShellResult(
output=[
ShellCommandOutput(
stdout="0123456789",
stderr="abcdef",
outcome=ShellCallOutcome(type="exit", exit_code=0),
)
],
)
)
tool_call = {
"type": "shell_call",
"id": "shell_call",
"call_id": "call_shell",
"status": "completed",
"action": {
"commands": ["echo hi"],
"timeout_ms": 1000,
"max_output_length": 6,
},
}
tool_run = ToolRunShellCall(tool_call=tool_call, shell_tool=shell_tool)
agent = Agent(name="shell-agent", tools=[shell_tool])
context_wrapper: RunContextWrapper[Any] = RunContextWrapper(context=None)
result = await ShellAction.execute(
agent=agent,
call=tool_run,
hooks=RunHooks[Any](),
context_wrapper=context_wrapper,
config=RunConfig(),
)
assert isinstance(result, ToolCallOutputItem)
assert result.output == "012345"
raw_item = cast(dict[str, Any], result.raw_item)
assert raw_item["max_output_length"] == 6
assert raw_item["output"][0]["stdout"] == "012345"
assert raw_item["output"][0]["stderr"] == ""
@pytest.mark.asyncio
async def test_shell_tool_uses_smaller_max_output_length() -> None:
shell_tool = ShellTool(
executor=lambda request: ShellResult(
output=[
ShellCommandOutput(
stdout="0123456789",
stderr="abcdef",
outcome=ShellCallOutcome(type="exit", exit_code=0),
)
],
max_output_length=8,
)
)
tool_call = {
"type": "shell_call",
"id": "shell_call",
"call_id": "call_shell",
"status": "completed",
"action": {
"commands": ["echo hi"],
"timeout_ms": 1000,
"max_output_length": 6,
},
}
tool_run = ToolRunShellCall(tool_call=tool_call, shell_tool=shell_tool)
agent = Agent(name="shell-agent", tools=[shell_tool])
context_wrapper: RunContextWrapper[Any] = RunContextWrapper(context=None)
result = await ShellAction.execute(
agent=agent,
call=tool_run,
hooks=RunHooks[Any](),
context_wrapper=context_wrapper,
config=RunConfig(),
)
assert isinstance(result, ToolCallOutputItem)
assert result.output == "012345"
raw_item = cast(dict[str, Any], result.raw_item)
assert raw_item["max_output_length"] == 6
assert raw_item["output"][0]["stdout"] == "012345"
assert raw_item["output"][0]["stderr"] == ""
@pytest.mark.asyncio
async def test_shell_tool_executor_can_override_max_output_length_to_zero() -> None:
shell_tool = ShellTool(
executor=lambda request: ShellResult(
output=[
ShellCommandOutput(
stdout="0123456789",
stderr="abcdef",
outcome=ShellCallOutcome(type="exit", exit_code=0),
)
],
max_output_length=0,
)
)
tool_call = {
"type": "shell_call",
"id": "shell_call",
"call_id": "call_shell",
"status": "completed",
"action": {
"commands": ["echo hi"],
"timeout_ms": 1000,
"max_output_length": 6,
},
}
tool_run = ToolRunShellCall(tool_call=tool_call, shell_tool=shell_tool)
agent = Agent(name="shell-agent", tools=[shell_tool])
context_wrapper: RunContextWrapper[Any] = RunContextWrapper(context=None)
result = await ShellAction.execute(
agent=agent,
call=tool_run,
hooks=RunHooks[Any](),
context_wrapper=context_wrapper,
config=RunConfig(),
)
assert isinstance(result, ToolCallOutputItem)
assert result.output == ""
raw_item = cast(dict[str, Any], result.raw_item)
assert raw_item["max_output_length"] == 0
assert raw_item["output"][0]["stdout"] == ""
assert raw_item["output"][0]["stderr"] == ""
@pytest.mark.asyncio
async def test_shell_tool_action_can_request_zero_max_output_length() -> None:
shell_tool = ShellTool(
executor=lambda request: ShellResult(
output=[
ShellCommandOutput(
stdout="0123456789",
stderr="abcdef",
outcome=ShellCallOutcome(type="exit", exit_code=0),
)
],
)
)
tool_call = {
"type": "shell_call",
"id": "shell_call",
"call_id": "call_shell",
"status": "completed",
"action": {
"commands": ["echo hi"],
"timeout_ms": 1000,
"max_output_length": 0,
},
}
tool_run = ToolRunShellCall(tool_call=tool_call, shell_tool=shell_tool)
agent = Agent(name="shell-agent", tools=[shell_tool])
context_wrapper: RunContextWrapper[Any] = RunContextWrapper(context=None)
result = await ShellAction.execute(
agent=agent,
call=tool_run,
hooks=RunHooks[Any](),
context_wrapper=context_wrapper,
config=RunConfig(),
)
assert isinstance(result, ToolCallOutputItem)
assert result.output == ""
raw_item = cast(dict[str, Any], result.raw_item)
assert raw_item["max_output_length"] == 0
assert raw_item["output"][0]["stdout"] == ""
assert raw_item["output"][0]["stderr"] == ""
@pytest.mark.asyncio
async def test_shell_tool_action_negative_max_output_length_clamps_to_zero() -> None:
shell_tool = ShellTool(
executor=lambda request: ShellResult(
output=[
ShellCommandOutput(
stdout="0123456789",
stderr="abcdef",
outcome=ShellCallOutcome(type="exit", exit_code=0),
)
],
)
)
tool_call = {
"type": "shell_call",
"id": "shell_call",
"call_id": "call_shell",
"status": "completed",
"action": {
"commands": ["echo hi"],
"timeout_ms": 1000,
"max_output_length": -5,
},
}
tool_run = ToolRunShellCall(tool_call=tool_call, shell_tool=shell_tool)
agent = Agent(name="shell-agent", tools=[shell_tool])
context_wrapper: RunContextWrapper[Any] = RunContextWrapper(context=None)
result = await ShellAction.execute(
agent=agent,
call=tool_run,
hooks=RunHooks[Any](),
context_wrapper=context_wrapper,
config=RunConfig(),
)
assert isinstance(result, ToolCallOutputItem)
assert result.output == ""
raw_item = cast(dict[str, Any], result.raw_item)
assert raw_item["max_output_length"] == 0
assert raw_item["output"][0]["stdout"] == ""
assert raw_item["output"][0]["stderr"] == ""
@pytest.mark.asyncio
async def test_shell_tool_needs_approval_returns_approval_item() -> None:
"""Test that shell tool with needs_approval=True returns ToolApprovalItem."""
shell_tool = ShellTool(
executor=lambda request: "output",
needs_approval=require_approval,
)
tool_run = ToolRunShellCall(tool_call=_shell_call(), shell_tool=shell_tool)
_, agent = make_model_and_agent(tools=[shell_tool], name="shell-agent")
context_wrapper = make_context_wrapper()
result = await ShellAction.execute(
agent=agent,
call=tool_run,
hooks=RunHooks[Any](),
context_wrapper=context_wrapper,
config=RunConfig(),
)
assert isinstance(result, ToolApprovalItem)
assert result.tool_name == "shell"
assert result.name == "shell"
@pytest.mark.asyncio
async def test_shell_tool_needs_approval_rejected_returns_rejection() -> None:
"""Test that shell tool with needs_approval that is rejected returns rejection output."""
shell_tool = ShellTool(
executor=lambda request: "output",
needs_approval=require_approval,
)
tool_call = _shell_call()
tool_run = ToolRunShellCall(tool_call=tool_call, shell_tool=shell_tool)
_, agent = make_model_and_agent(tools=[shell_tool], name="shell-agent")
context_wrapper = make_context_wrapper()
# Pre-reject the tool call
reject_tool_call(context_wrapper, agent, tool_call, "shell")
result = await ShellAction.execute(
agent=agent,
call=tool_run,
hooks=RunHooks[Any](),
context_wrapper=context_wrapper,
config=RunConfig(),
)
assert isinstance(result, ToolCallOutputItem)
assert HITL_REJECTION_MSG in result.output
raw_item = cast(dict[str, Any], result.raw_item)
assert raw_item["type"] == "shell_call_output"
assert len(raw_item["output"]) == 1
assert raw_item["output"][0]["stderr"] == HITL_REJECTION_MSG
@pytest.mark.asyncio
async def test_shell_tool_rejection_uses_run_level_formatter() -> None:
"""Shell approval rejection should use the run-level formatter message."""
shell_tool = ShellTool(
executor=lambda request: "output",
needs_approval=require_approval,
)
tool_call = _shell_call()
tool_run = ToolRunShellCall(tool_call=tool_call, shell_tool=shell_tool)
_, agent = make_model_and_agent(tools=[shell_tool], name="shell-agent")
context_wrapper = make_context_wrapper()
reject_tool_call(context_wrapper, agent, tool_call, "shell")
result = await ShellAction.execute(
agent=agent,
call=tool_run,
hooks=RunHooks[Any](),
context_wrapper=context_wrapper,
config=RunConfig(
tool_error_formatter=lambda args: f"{args.tool_name} denied ({args.call_id})"
),
)
assert isinstance(result, ToolCallOutputItem)
assert result.output == "shell denied (call_shell)"
raw_item = cast(dict[str, Any], result.raw_item)
assert raw_item["output"][0]["stderr"] == "shell denied (call_shell)"
@pytest.mark.asyncio
async def test_shell_tool_on_approval_callback_auto_approves() -> None:
"""Test that shell tool on_approval callback can auto-approve."""
shell_tool = ShellTool(
executor=lambda request: "output",
needs_approval=require_approval,
on_approval=make_on_approval_callback(approve=True),
)
tool_run = ToolRunShellCall(tool_call=_shell_call(), shell_tool=shell_tool)
_, agent = make_model_and_agent(tools=[shell_tool], name="shell-agent")
context_wrapper = make_context_wrapper()
result = await ShellAction.execute(
agent=agent,
call=tool_run,
hooks=RunHooks[Any](),
context_wrapper=context_wrapper,
config=RunConfig(),
)
# Should execute normally since on_approval auto-approved
assert isinstance(result, ToolCallOutputItem)
assert result.output == "output"
@pytest.mark.asyncio
async def test_shell_tool_on_approval_callback_auto_rejects() -> None:
"""Test that shell tool on_approval callback can auto-reject."""
shell_tool = ShellTool(
executor=lambda request: "output",
needs_approval=require_approval,
on_approval=make_on_approval_callback(approve=False, reason="Not allowed"),
)
tool_run = ToolRunShellCall(tool_call=_shell_call(), shell_tool=shell_tool)
agent = Agent(name="shell-agent", tools=[shell_tool])
context_wrapper: RunContextWrapper[Any] = make_context_wrapper()
result = await ShellAction.execute(
agent=agent,
call=tool_run,
hooks=RunHooks[Any](),
context_wrapper=context_wrapper,
config=RunConfig(),
)
# Should return rejection output
assert isinstance(result, ToolCallOutputItem)
assert result.output == "Not allowed"
raw_item = cast(dict[str, Any], result.raw_item)
assert raw_item["output"][0]["stderr"] == "Not allowed"
@pytest.mark.asyncio
async def test_shell_tool_on_approval_empty_reason_uses_default_rejection() -> None:
"""Test that empty rejection reasons do not suppress the default message."""
async def on_approval(
_context: RunContextWrapper[Any], _approval_item: ToolApprovalItem
) -> ShellOnApprovalFunctionResult:
return {"approve": False, "reason": ""}
shell_tool = ShellTool(
executor=lambda request: "output",
needs_approval=require_approval,
on_approval=on_approval,
)
tool_run = ToolRunShellCall(tool_call=_shell_call(), shell_tool=shell_tool)
agent = Agent(name="shell-agent", tools=[shell_tool])
context_wrapper: RunContextWrapper[Any] = make_context_wrapper()
result = await ShellAction.execute(
agent=agent,
call=tool_run,
hooks=RunHooks[Any](),
context_wrapper=context_wrapper,
config=RunConfig(),
)
assert isinstance(result, ToolCallOutputItem)
assert result.output == HITL_REJECTION_MSG