-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathtest_skill_toolset.py
More file actions
2266 lines (1918 loc) · 75 KB
/
test_skill_toolset.py
File metadata and controls
2266 lines (1918 loc) · 75 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
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
import collections
import logging
import sys
from unittest import mock
from google.adk.agents.readonly_context import ReadonlyContext
from google.adk.code_executors.base_code_executor import BaseCodeExecutor
from google.adk.code_executors.code_execution_utils import CodeExecutionResult
from google.adk.code_executors.unsafe_local_code_executor import UnsafeLocalCodeExecutor
from google.adk.models import llm_request as llm_request_model
from google.adk.skills import models
from google.adk.tools import skill_toolset
from google.adk.tools import tool_context
from google.genai import types
import pytest
@pytest.fixture(name="mock_skill1_frontmatter")
def _mock_skill1_frontmatter():
"""Fixture for skill1 frontmatter."""
frontmatter = mock.create_autospec(models.Frontmatter, instance=True)
frontmatter.name = "skill1"
frontmatter.description = "Skill 1 description"
frontmatter.allowed_tools = ["test_tool"]
frontmatter.model_dump.return_value = {
"name": "skill1",
"description": "Skill 1 description",
}
return frontmatter
@pytest.fixture(name="mock_skill1")
def _mock_skill1(mock_skill1_frontmatter):
"""Fixture for skill1."""
skill = mock.create_autospec(models.Skill, instance=True)
skill.name = "skill1"
skill.description = "Skill 1 description"
skill.instructions = "instructions for skill1"
skill.frontmatter = mock_skill1_frontmatter
skill.resources = mock.MagicMock(
spec=[
"get_reference",
"get_asset",
"get_script",
"list_references",
"list_assets",
"list_scripts",
]
)
def get_ref(name):
if name == "ref1.md":
return "ref content 1"
if name == "doc.pdf":
return b"fake pdf content"
return None
def get_asset(name):
if name == "asset1.txt":
return "asset content 1"
if name == "image.png":
return b"fake image content"
return None
def get_script(name):
if name == "setup.sh":
return models.Script(src="echo setup")
if name == "run.py":
return models.Script(src="print('hello')")
if name == "build.rb":
return models.Script(src="puts 'hello'")
return None
skill.resources.get_reference.side_effect = get_ref
skill.resources.get_asset.side_effect = get_asset
skill.resources.get_script.side_effect = get_script
skill.resources.list_references.return_value = ["ref1.md", "doc.pdf"]
skill.resources.list_assets.return_value = ["asset1.txt", "image.png"]
skill.resources.list_scripts.return_value = [
"setup.sh",
"run.py",
"build.rb",
]
return skill
@pytest.fixture(name="mock_skill2_frontmatter")
def _mock_skill2_frontmatter():
"""Fixture for skill2 frontmatter."""
frontmatter = mock.create_autospec(models.Frontmatter, instance=True)
frontmatter.name = "skill2"
frontmatter.description = "Skill 2 description"
frontmatter.allowed_tools = []
frontmatter.model_dump.return_value = {
"name": "skill2",
"description": "Skill 2 description",
}
return frontmatter
@pytest.fixture(name="mock_skill2")
def _mock_skill2(mock_skill2_frontmatter):
"""Fixture for skill2."""
skill = mock.create_autospec(models.Skill, instance=True)
skill.name = "skill2"
skill.description = "Skill 2 description"
skill.instructions = "instructions for skill2"
skill.frontmatter = mock_skill2_frontmatter
skill.resources = mock.MagicMock(
spec=[
"get_reference",
"get_asset",
"get_script",
"list_references",
"list_assets",
"list_scripts",
]
)
def get_ref(name):
if name == "ref2.md":
return "ref content 2"
return None
def get_asset(name):
if name == "asset2.txt":
return "asset content 2"
return None
skill.resources.get_reference.side_effect = get_ref
skill.resources.get_asset.side_effect = get_asset
skill.resources.list_references.return_value = ["ref2.md"]
skill.resources.list_assets.return_value = ["asset2.txt"]
skill.resources.list_scripts.return_value = []
return skill
@pytest.fixture
def tool_context_instance():
"""Fixture for tool context."""
ctx = mock.create_autospec(tool_context.ToolContext, instance=True)
ctx._invocation_context = mock.MagicMock()
ctx._invocation_context.agent = mock.MagicMock()
ctx._invocation_context.agent.name = "test_agent"
ctx._invocation_context.agent_states = {}
ctx.agent_name = "test_agent"
return ctx
# SkillToolset tests
def test_get_skill(mock_skill1, mock_skill2):
toolset = skill_toolset.SkillToolset([mock_skill1, mock_skill2])
assert toolset._get_skill("skill1") == mock_skill1
assert toolset._get_skill("nonexistent") is None
def test_list_skills(mock_skill1, mock_skill2):
toolset = skill_toolset.SkillToolset([mock_skill1, mock_skill2])
skills = toolset._list_skills()
assert len(skills) == 2
assert mock_skill1 in skills
assert mock_skill2 in skills
@pytest.mark.asyncio
async def test_get_tools(mock_skill1, mock_skill2):
toolset = skill_toolset.SkillToolset([mock_skill1, mock_skill2])
tools = await toolset.get_tools()
assert len(tools) == 4
assert isinstance(tools[0], skill_toolset.ListSkillsTool)
assert isinstance(tools[1], skill_toolset.LoadSkillTool)
assert isinstance(tools[2], skill_toolset.LoadSkillResourceTool)
assert isinstance(tools[3], skill_toolset.RunSkillScriptTool)
@pytest.mark.asyncio
async def test_resolve_additional_tools_from_state_none(mock_skill1):
toolset = skill_toolset.SkillToolset([mock_skill1])
# Mock ReadonlyContext
readonly_context = mock.create_autospec(ReadonlyContext, instance=True)
readonly_context.agent_name = "test_agent"
readonly_context.state.get.return_value = None
result = await toolset._resolve_additional_tools_from_state(readonly_context)
assert not result
@pytest.mark.asyncio
async def test_list_skills_tool(
mock_skill1, mock_skill2, tool_context_instance
):
toolset = skill_toolset.SkillToolset([mock_skill1, mock_skill2])
tool = skill_toolset.ListSkillsTool(toolset)
result = await tool.run_async(args={}, tool_context=tool_context_instance)
assert "<available_skills>" in result
assert "skill1" in result
assert "skill2" in result
@pytest.mark.asyncio
@pytest.mark.parametrize(
"args, expected_result",
[
(
{"skill_name": "skill1"},
{
"skill_name": "skill1",
"instructions": "instructions for skill1",
"frontmatter": {
"name": "skill1",
"description": "Skill 1 description",
},
},
),
(
{"skill_name": "nonexistent"},
{
"error": "Skill 'nonexistent' not found.",
"error_code": "SKILL_NOT_FOUND",
},
),
(
{},
{
"error": "Argument 'skill_name' is required.",
"error_code": "INVALID_ARGUMENTS",
},
),
],
)
async def test_load_skill_run_async(
mock_skill1, tool_context_instance, args, expected_result
):
toolset = skill_toolset.SkillToolset([mock_skill1])
tool = skill_toolset.LoadSkillTool(toolset)
result = await tool.run_async(args=args, tool_context=tool_context_instance)
assert result == expected_result
@pytest.mark.asyncio
async def test_load_skill_run_async_state_none(
mock_skill1, tool_context_instance
):
toolset = skill_toolset.SkillToolset([mock_skill1])
tool = skill_toolset.LoadSkillTool(toolset)
# Mock state to return None for the key
state_key = "_adk_activated_skill_test_agent"
tool_context_instance.state.get.return_value = None
result = await tool.run_async(
args={"skill_name": "skill1"}, tool_context=tool_context_instance
)
assert result["skill_name"] == "skill1"
tool_context_instance.state.__setitem__.assert_called_with(
state_key, ["skill1"]
)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"args, expected_result",
[
(
{"skill_name": "skill1", "file_path": "references/ref1.md"},
{
"skill_name": "skill1",
"file_path": "references/ref1.md",
"content": "ref content 1",
},
),
(
{"skill_name": "skill1", "file_path": "assets/asset1.txt"},
{
"skill_name": "skill1",
"file_path": "assets/asset1.txt",
"content": "asset content 1",
},
),
(
{"skill_name": "skill1", "file_path": "references/doc.pdf"},
{
"skill_name": "skill1",
"file_path": "references/doc.pdf",
"status": (
"Binary file detected. The content has been injected into"
" the conversation history for you to analyze."
),
},
),
(
{"skill_name": "skill1", "file_path": "assets/image.png"},
{
"skill_name": "skill1",
"file_path": "assets/image.png",
"status": (
"Binary file detected. The content has been injected into"
" the conversation history for you to analyze."
),
},
),
(
{"skill_name": "skill1", "file_path": "scripts/setup.sh"},
{
"skill_name": "skill1",
"file_path": "scripts/setup.sh",
"content": "echo setup",
},
),
(
{"skill_name": "nonexistent", "file_path": "references/ref1.md"},
{
"error": "Skill 'nonexistent' not found.",
"error_code": "SKILL_NOT_FOUND",
},
),
(
{"skill_name": "skill1", "file_path": "references/other.md"},
{
"error": (
"Resource 'references/other.md' not found in skill"
" 'skill1'."
),
"error_code": "RESOURCE_NOT_FOUND",
},
),
(
{"skill_name": "skill1", "file_path": "invalid/path.txt"},
{
"error": (
"Path must start with 'references/', 'assets/',"
" or 'scripts/'."
),
"error_code": "INVALID_RESOURCE_PATH",
},
),
(
{"file_path": "references/ref1.md"},
{
"error": "Argument 'skill_name' is required.",
"error_code": "INVALID_ARGUMENTS",
},
),
(
{"skill_name": "skill1"},
{
"error": "Argument 'file_path' is required.",
"error_code": "INVALID_ARGUMENTS",
},
),
],
)
async def test_load_resource_run_async(
mock_skill1, tool_context_instance, args, expected_result
):
toolset = skill_toolset.SkillToolset([mock_skill1])
tool = skill_toolset.LoadSkillResourceTool(toolset)
result = await tool.run_async(args=args, tool_context=tool_context_instance)
assert result == expected_result
@pytest.mark.asyncio
@pytest.mark.parametrize(
"resource_path, expected_mime, fake_content",
[
("references/doc.pdf", "application/pdf", b"fake pdf content"),
("assets/image.png", "image/png", b"fake image content"),
],
)
async def test_load_resource_process_llm_request_binary(
mock_skill1,
tool_context_instance,
resource_path,
expected_mime,
fake_content,
):
toolset = skill_toolset.SkillToolset([mock_skill1])
tool = skill_toolset.LoadSkillResourceTool(toolset)
llm_req = mock.create_autospec(llm_request_model.LlmRequest, instance=True)
part = types.Part.from_function_response(
name=tool.name,
response={
"skill_name": "skill1",
"file_path": resource_path,
"status": (
"Binary file detected. The content has been injected into the"
" conversation history for you to analyze."
),
},
)
content = types.Content(role="model", parts=[part])
llm_req.contents = [content]
await tool.process_llm_request(
tool_context=tool_context_instance, llm_request=llm_req
)
assert len(llm_req.contents) == 2
injected_content = llm_req.contents[1]
assert injected_content.role == "user"
assert len(injected_content.parts) == 2
assert (
f"The content of binary file '{resource_path}' is:"
in injected_content.parts[0].text
)
assert injected_content.parts[1].inline_data.data == fake_content
assert injected_content.parts[1].inline_data.mime_type == expected_mime
@pytest.mark.asyncio
async def test_process_llm_request_with_list_skills_tool(
mock_skill1, mock_skill2, tool_context_instance
):
toolset = skill_toolset.SkillToolset([mock_skill1, mock_skill2])
llm_req = mock.create_autospec(llm_request_model.LlmRequest, instance=True)
await toolset.process_llm_request(
tool_context=tool_context_instance, llm_request=llm_req
)
llm_req.append_instructions.assert_called_once_with(
[skill_toolset.DEFAULT_SKILL_SYSTEM_INSTRUCTION]
)
@pytest.mark.asyncio
async def test_process_llm_request_without_list_skills_tool(
mock_skill1, mock_skill2, tool_context_instance
):
toolset = skill_toolset.SkillToolset([mock_skill1, mock_skill2])
# Manually remove ListSkillsTool from self._tools to simulate it not being available
toolset._tools = [
t
for t in toolset._tools
if not isinstance(t, skill_toolset.ListSkillsTool)
]
llm_req = mock.create_autospec(llm_request_model.LlmRequest, instance=True)
await toolset.process_llm_request(
tool_context=tool_context_instance, llm_request=llm_req
)
llm_req.append_instructions.assert_called_once()
args, _ = llm_req.append_instructions.call_args
instructions = args[0]
assert len(instructions) == 2
assert instructions[0] == skill_toolset.DEFAULT_SKILL_SYSTEM_INSTRUCTION
assert "<available_skills>" in instructions[1]
assert "skill1" in instructions[1]
assert "skill2" in instructions[1]
def test_default_skill_system_instruction_warning():
with pytest.warns(
UserWarning, match="DEFAULT_SKILL_SYSTEM_INSTRUCTION is experimental"
):
instruction = skill_toolset.DEFAULT_SKILL_SYSTEM_INSTRUCTION
assert "specialized 'skills'" in instruction
def test_duplicate_skill_name_raises(mock_skill1):
skill_dup = mock.create_autospec(models.Skill, instance=True)
skill_dup.name = "skill1"
with pytest.raises(ValueError, match="Duplicate skill name"):
skill_toolset.SkillToolset([mock_skill1, skill_dup])
@pytest.mark.asyncio
async def test_scripts_resource_not_found(mock_skill1, tool_context_instance):
toolset = skill_toolset.SkillToolset([mock_skill1])
tool = skill_toolset.LoadSkillResourceTool(toolset)
result = await tool.run_async(
args={"skill_name": "skill1", "file_path": "scripts/nonexistent.sh"},
tool_context=tool_context_instance,
)
assert result["error_code"] == "RESOURCE_NOT_FOUND"
# RunSkillScriptTool tests
def _make_tool_context_with_agent(agent=None):
"""Creates a mock ToolContext with _invocation_context.agent."""
ctx = mock.MagicMock(spec=tool_context.ToolContext)
ctx._invocation_context = mock.MagicMock()
ctx._invocation_context.agent = agent or mock.MagicMock()
ctx._invocation_context.agent.name = "test_agent"
ctx._invocation_context.agent_states = {}
ctx.agent_name = "test_agent"
ctx.state = {}
return ctx
def _make_mock_executor(stdout="", stderr=""):
"""Creates a mock code executor that returns the given output."""
executor = mock.create_autospec(BaseCodeExecutor, instance=True)
executor.execute_code.return_value = CodeExecutionResult(
stdout=stdout, stderr=stderr
)
return executor
@pytest.mark.asyncio
@pytest.mark.parametrize(
"args, expected_error_code",
[
(
{"file_path": "setup.sh"},
"INVALID_ARGUMENTS",
),
(
{"skill_name": "skill1"},
"INVALID_ARGUMENTS",
),
(
{"skill_name": "", "file_path": "setup.sh"},
"INVALID_ARGUMENTS",
),
(
{"skill_name": "skill1", "file_path": ""},
"INVALID_ARGUMENTS",
),
],
)
async def test_execute_script_missing_params(
mock_skill1, args, expected_error_code
):
executor = _make_mock_executor()
toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor)
tool = skill_toolset.RunSkillScriptTool(toolset)
ctx = _make_tool_context_with_agent()
result = await tool.run_async(args=args, tool_context=ctx)
assert result["error_code"] == expected_error_code
@pytest.mark.asyncio
async def test_execute_script_skill_not_found(mock_skill1):
executor = _make_mock_executor()
toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor)
tool = skill_toolset.RunSkillScriptTool(toolset)
ctx = _make_tool_context_with_agent()
result = await tool.run_async(
args={"skill_name": "nonexistent", "file_path": "setup.sh"},
tool_context=ctx,
)
assert result["error_code"] == "SKILL_NOT_FOUND"
@pytest.mark.asyncio
async def test_execute_script_script_not_found(mock_skill1):
executor = _make_mock_executor()
toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor)
tool = skill_toolset.RunSkillScriptTool(toolset)
ctx = _make_tool_context_with_agent()
result = await tool.run_async(
args={"skill_name": "skill1", "file_path": "nonexistent.py"},
tool_context=ctx,
)
assert result["error_code"] == "SCRIPT_NOT_FOUND"
@pytest.mark.asyncio
async def test_execute_script_no_code_executor(mock_skill1):
toolset = skill_toolset.SkillToolset([mock_skill1])
tool = skill_toolset.RunSkillScriptTool(toolset)
# Agent without code_executor attribute
agent = mock.MagicMock(spec=[])
ctx = _make_tool_context_with_agent(agent=agent)
result = await tool.run_async(
args={"skill_name": "skill1", "file_path": "setup.sh"},
tool_context=ctx,
)
assert result["error_code"] == "NO_CODE_EXECUTOR"
@pytest.mark.asyncio
async def test_execute_script_agent_code_executor_none(mock_skill1):
"""Agent has code_executor attr but it's None."""
toolset = skill_toolset.SkillToolset([mock_skill1])
tool = skill_toolset.RunSkillScriptTool(toolset)
agent = mock.MagicMock()
agent.code_executor = None
ctx = _make_tool_context_with_agent(agent=agent)
result = await tool.run_async(
args={"skill_name": "skill1", "file_path": "setup.sh"},
tool_context=ctx,
)
assert result["error_code"] == "NO_CODE_EXECUTOR"
@pytest.mark.asyncio
async def test_execute_script_unsupported_type(mock_skill1):
executor = _make_mock_executor()
toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor)
tool = skill_toolset.RunSkillScriptTool(toolset)
ctx = _make_tool_context_with_agent()
result = await tool.run_async(
args={"skill_name": "skill1", "file_path": "build.rb"},
tool_context=ctx,
)
assert result["error_code"] == "UNSUPPORTED_SCRIPT_TYPE"
@pytest.mark.asyncio
async def test_execute_script_python_success(mock_skill1):
executor = _make_mock_executor(stdout="hello\n")
toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor)
tool = skill_toolset.RunSkillScriptTool(toolset)
ctx = _make_tool_context_with_agent()
result = await tool.run_async(
args={"skill_name": "skill1", "file_path": "run.py"},
tool_context=ctx,
)
assert result["status"] == "success"
assert result["stdout"] == "hello\n"
assert result["stderr"] == ""
assert result["skill_name"] == "skill1"
assert result["file_path"] == "run.py"
# Verify the code passed to executor runs the python scripts
call_args = executor.execute_code.call_args
code_input = call_args[0][1]
assert "_materialize_and_run()" in code_input.code
assert "import runpy" in code_input.code
assert "sys.argv = ['scripts/run.py']" in code_input.code
assert (
"runpy.run_path('scripts/run.py', run_name='__main__')" in code_input.code
)
@pytest.mark.asyncio
async def test_execute_script_shell_success(mock_skill1):
executor = _make_mock_executor(stdout="setup\n")
toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor)
tool = skill_toolset.RunSkillScriptTool(toolset)
ctx = _make_tool_context_with_agent()
result = await tool.run_async(
args={"skill_name": "skill1", "file_path": "setup.sh"},
tool_context=ctx,
)
assert result["status"] == "success"
assert result["stdout"] == "setup\n"
# Verify the code wraps in subprocess.run with JSON envelope
call_args = executor.execute_code.call_args
code_input = call_args[0][1]
assert "subprocess.run" in code_input.code
assert "bash" in code_input.code
assert "__shell_result__" in code_input.code
@pytest.mark.asyncio
async def test_execute_script_with_input_args_python(mock_skill1):
executor = _make_mock_executor(stdout="done\n")
toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor)
tool = skill_toolset.RunSkillScriptTool(toolset)
ctx = _make_tool_context_with_agent()
result = await tool.run_async(
args={
"skill_name": "skill1",
"file_path": "run.py",
"args": {"verbose": True, "count": "3"},
},
tool_context=ctx,
)
assert result["status"] == "success"
call_args = executor.execute_code.call_args
code_input = call_args[0][1]
assert (
"['scripts/run.py', '--verbose', 'True', '--count', '3']"
in code_input.code
)
@pytest.mark.asyncio
async def test_execute_script_with_input_args_shell(mock_skill1):
executor = _make_mock_executor(stdout="done\n")
toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor)
tool = skill_toolset.RunSkillScriptTool(toolset)
ctx = _make_tool_context_with_agent()
result = await tool.run_async(
args={
"skill_name": "skill1",
"file_path": "setup.sh",
"args": {"force": True},
},
tool_context=ctx,
)
assert result["status"] == "success"
call_args = executor.execute_code.call_args
code_input = call_args[0][1]
assert "['bash', 'scripts/setup.sh', '--force', 'True']" in code_input.code
@pytest.mark.asyncio
async def test_execute_script_with_list_args_python(
mock_skill1,
):
"""Verifies that python scripts can be executed with list arguments."""
executor = _make_mock_executor(stdout="done\n")
toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor)
tool = skill_toolset.RunSkillScriptTool(toolset)
ctx = _make_tool_context_with_agent()
result = await tool.run_async(
args={
"skill_name": "skill1",
"file_path": "run.py",
"args": ["--verbose", "True", "-n", "5", "input.txt"],
},
tool_context=ctx,
)
assert result["status"] == "success"
call_args = executor.execute_code.call_args
code_input = call_args[0][1]
assert (
"['scripts/run.py', '--verbose', 'True', '-n', '5', 'input.txt']"
in code_input.code
)
@pytest.mark.asyncio
async def test_execute_script_with_list_args_shell(
mock_skill1,
):
"""Verifies that shell scripts can be executed with list arguments."""
executor = _make_mock_executor(stdout="done\n")
toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor)
tool = skill_toolset.RunSkillScriptTool(toolset)
ctx = _make_tool_context_with_agent()
result = await tool.run_async(
args={
"skill_name": "skill1",
"file_path": "setup.sh",
"args": ["-n", "5", "input.txt"],
},
tool_context=ctx,
)
assert result["status"] == "success"
call_args = executor.execute_code.call_args
code_input = call_args[0][1]
assert (
"['bash', 'scripts/setup.sh', '-n', '5', 'input.txt']" in code_input.code
)
@pytest.mark.asyncio
async def test_execute_script_with_list_args_rejects_others_python(
mock_skill1, # pylint: disable=redefined-outer-name
):
"""Verifies that short_options and positional_args are rejected when args is a list for Python scripts."""
executor = _make_mock_executor(stdout="done\n")
toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor)
tool = skill_toolset.RunSkillScriptTool(toolset)
ctx = _make_tool_context_with_agent()
result = await tool.run_async(
args={
"skill_name": "skill1",
"file_path": "run.py",
"args": ["arg1", "arg2"],
"short_options": {"v": True},
"positional_args": ["pos1"],
},
tool_context=ctx,
)
assert result["error_code"] == "INVALID_ARGUMENTS"
assert (
"Cannot specify 'short_options' or 'positional_args'" in result["error"]
)
@pytest.mark.asyncio
async def test_execute_script_with_list_args_rejects_others_shell(
mock_skill1, # pylint: disable=redefined-outer-name
):
"""Verifies that short_options and positional_args are rejected when args is a list for shell scripts."""
executor = _make_mock_executor(stdout="done\n")
toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor)
tool = skill_toolset.RunSkillScriptTool(toolset)
ctx = _make_tool_context_with_agent()
result = await tool.run_async(
args={
"skill_name": "skill1",
"file_path": "setup.sh",
"args": ["arg1", "arg2"],
"short_options": {"v": True},
"positional_args": ["pos1"],
},
tool_context=ctx,
)
assert result["error_code"] == "INVALID_ARGUMENTS"
assert (
"Cannot specify 'short_options' or 'positional_args'" in result["error"]
)
@pytest.mark.asyncio
async def test_execute_script_scripts_prefix_stripping(mock_skill1):
executor = _make_mock_executor(stdout="setup\n")
toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor)
tool = skill_toolset.RunSkillScriptTool(toolset)
ctx = _make_tool_context_with_agent()
result = await tool.run_async(
args={
"skill_name": "skill1",
"file_path": "scripts/setup.sh",
},
tool_context=ctx,
)
assert result["status"] == "success"
assert result["file_path"] == "scripts/setup.sh"
@pytest.mark.asyncio
async def test_execute_script_toolset_executor_priority(mock_skill1):
"""Toolset-level executor takes priority over agent's."""
toolset_executor = _make_mock_executor(stdout="from toolset\n")
agent_executor = _make_mock_executor(stdout="from agent\n")
toolset = skill_toolset.SkillToolset(
[mock_skill1], code_executor=toolset_executor
)
tool = skill_toolset.RunSkillScriptTool(toolset)
agent = mock.MagicMock()
agent.code_executor = agent_executor
ctx = _make_tool_context_with_agent(agent=agent)
result = await tool.run_async(
args={"skill_name": "skill1", "file_path": "run.py"},
tool_context=ctx,
)
assert result["stdout"] == "from toolset\n"
toolset_executor.execute_code.assert_called_once()
agent_executor.execute_code.assert_not_called()
@pytest.mark.asyncio
async def test_execute_script_agent_executor_fallback(mock_skill1):
"""Falls back to agent's code executor when toolset has none."""
agent_executor = _make_mock_executor(stdout="from agent\n")
toolset = skill_toolset.SkillToolset([mock_skill1])
tool = skill_toolset.RunSkillScriptTool(toolset)
agent = mock.MagicMock()
agent.code_executor = agent_executor
ctx = _make_tool_context_with_agent(agent=agent)
result = await tool.run_async(
args={"skill_name": "skill1", "file_path": "run.py"},
tool_context=ctx,
)
assert result["stdout"] == "from agent\n"
agent_executor.execute_code.assert_called_once()
@pytest.mark.asyncio
async def test_execute_script_execution_error(mock_skill1):
executor = _make_mock_executor()
executor.execute_code.side_effect = RuntimeError("boom")
toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor)
tool = skill_toolset.RunSkillScriptTool(toolset)
ctx = _make_tool_context_with_agent()
result = await tool.run_async(
args={"skill_name": "skill1", "file_path": "run.py"},
tool_context=ctx,
)
assert result["error_code"] == "EXECUTION_ERROR"
assert "boom" in result["error"]
assert result["error"].startswith("Failed to execute script 'run.py':")
@pytest.mark.asyncio
async def test_execute_script_stderr_only_sets_error_status(mock_skill1):
"""stderr with no stdout should report error status."""
executor = _make_mock_executor(stdout="", stderr="fatal error\n")
toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor)
tool = skill_toolset.RunSkillScriptTool(toolset)
ctx = _make_tool_context_with_agent()
result = await tool.run_async(
args={"skill_name": "skill1", "file_path": "run.py"},
tool_context=ctx,
)
assert result["status"] == "error"
assert result["stderr"] == "fatal error\n"
@pytest.mark.asyncio
async def test_execute_script_stderr_with_stdout_sets_warning(mock_skill1):
"""stderr alongside stdout should report warning status."""
executor = _make_mock_executor(stdout="output\n", stderr="deprecation\n")
toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor)
tool = skill_toolset.RunSkillScriptTool(toolset)
ctx = _make_tool_context_with_agent()
result = await tool.run_async(
args={"skill_name": "skill1", "file_path": "run.py"},
tool_context=ctx,
)
assert result["status"] == "warning"
assert result["stdout"] == "output\n"
assert result["stderr"] == "deprecation\n"
@pytest.mark.asyncio
async def test_execute_script_execution_error_truncated(mock_skill1):
"""Long exception messages are truncated to avoid wasting LLM tokens."""
executor = _make_mock_executor()
executor.execute_code.side_effect = RuntimeError("x" * 300)
toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor)
tool = skill_toolset.RunSkillScriptTool(toolset)
ctx = _make_tool_context_with_agent()
result = await tool.run_async(
args={"skill_name": "skill1", "file_path": "run.py"},
tool_context=ctx,
)
assert result["error_code"] == "EXECUTION_ERROR"
# 200 chars of the message + "..." suffix + the prefix
assert result["error"].endswith("...")
assert len(result["error"]) < 300
@pytest.mark.asyncio
async def test_execute_script_system_exit_caught(mock_skill1):
"""sys.exit() in a script should not terminate the process."""
executor = _make_mock_executor()
executor.execute_code.side_effect = SystemExit(1)
toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor)
tool = skill_toolset.RunSkillScriptTool(toolset)
ctx = _make_tool_context_with_agent()
result = await tool.run_async(
args={"skill_name": "skill1", "file_path": "run.py"},
tool_context=ctx,
)
assert result["error_code"] == "EXECUTION_ERROR"
assert "exited with code 1" in result["error"]
@pytest.mark.asyncio
async def test_execute_script_system_exit_zero_is_success(mock_skill1):
"""sys.exit(0) is a normal termination and should report success."""
executor = _make_mock_executor()
executor.execute_code.side_effect = SystemExit(0)
toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor)
tool = skill_toolset.RunSkillScriptTool(toolset)
ctx = _make_tool_context_with_agent()
result = await tool.run_async(
args={"skill_name": "skill1", "file_path": "run.py"},
tool_context=ctx,
)
assert result["status"] == "success"
@pytest.mark.asyncio
async def test_execute_script_system_exit_none_is_success(mock_skill1):
"""sys.exit() with no arg (None) should report success."""
executor = _make_mock_executor()
executor.execute_code.side_effect = SystemExit(None)
toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor)
tool = skill_toolset.RunSkillScriptTool(toolset)
ctx = _make_tool_context_with_agent()
result = await tool.run_async(
args={"skill_name": "skill1", "file_path": "run.py"},
tool_context=ctx,
)
assert result["status"] == "success"
@pytest.mark.asyncio
async def test_execute_script_shell_includes_timeout(mock_skill1):
"""Shell wrapper includes timeout in subprocess.run."""
executor = _make_mock_executor(stdout="ok\n")
toolset = skill_toolset.SkillToolset(
[mock_skill1], code_executor=executor, script_timeout=60
)
tool = skill_toolset.RunSkillScriptTool(toolset)
ctx = _make_tool_context_with_agent()
result = await tool.run_async(
args={"skill_name": "skill1", "file_path": "setup.sh"},
tool_context=ctx,
)