test_subagent_recursion.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. import asyncio
  2. import tempfile
  3. import unittest
  4. from unittest.mock import AsyncMock, patch
  5. from cyber_agent.core.agent_mode import RECURSIVE_CAPABILITY_TOOLS_CONTEXT_KEY
  6. from cyber_agent.tools.builtin.subagent import agent, evaluate
  7. from cyber_agent.trace.goal_models import Goal, GoalTree
  8. from cyber_agent.trace.models import Trace
  9. from cyber_agent.trace.store import FileSystemTraceStore
  10. class FakeToolRegistry:
  11. TOOL_NAMES = [
  12. "agent",
  13. "evaluate",
  14. "bash_command",
  15. "read_file",
  16. "grep_content",
  17. "glob_files",
  18. "goal",
  19. ]
  20. def get_tool_names(self):
  21. return list(self.TOOL_NAMES)
  22. class FakeRunner:
  23. def __init__(self, store):
  24. self.store = store
  25. self.tools = FakeToolRegistry()
  26. self.debug = False
  27. self.stdin_check = None
  28. self._cancel_events = {}
  29. self.configs = []
  30. async def run_result(self, messages, config, on_event=None):
  31. self.configs.append(config)
  32. await self.store.update_trace(config.trace_id, status="completed")
  33. return {
  34. "status": "completed",
  35. "summary": f"completed: {config.trace_id}",
  36. "saved_knowledge_ids": [],
  37. "stats": {
  38. "total_messages": 1,
  39. "total_tokens": 1,
  40. "total_cost": 0.0,
  41. },
  42. }
  43. class SubAgentModeTest(unittest.IsolatedAsyncioTestCase):
  44. async def asyncSetUp(self):
  45. self.temp_dir = tempfile.TemporaryDirectory()
  46. self.store = FileSystemTraceStore(self.temp_dir.name)
  47. self.runner = FakeRunner(self.store)
  48. self.root_id = await self._create_root("root")
  49. async def asyncTearDown(self):
  50. self.temp_dir.cleanup()
  51. async def _create_root(
  52. self,
  53. trace_id,
  54. uid="user-1",
  55. *,
  56. agent_mode="recursive",
  57. include_mode=True,
  58. ):
  59. context = {
  60. "agent_depth": 0,
  61. "root_trace_id": trace_id,
  62. }
  63. if include_mode:
  64. context.update({
  65. "agent_mode": agent_mode,
  66. "agent_mode_revision": 1,
  67. })
  68. trace = Trace(
  69. trace_id=trace_id,
  70. mode="agent",
  71. task=f"task-{trace_id}",
  72. uid=uid,
  73. model="fake-model",
  74. context=context,
  75. )
  76. await self.store.create_trace(trace)
  77. await self.store.update_goal_tree(trace_id, GoalTree(mission=trace.task))
  78. return trace_id
  79. def _context(self, trace_id, goal_id=None):
  80. return {
  81. "store": self.store,
  82. "trace_id": trace_id,
  83. "goal_id": goal_id,
  84. "runner": self.runner,
  85. "knowledge_config": None,
  86. RECURSIVE_CAPABILITY_TOOLS_CONTEXT_KEY: self.runner.tools.get_tool_names(),
  87. }
  88. async def _spawn_one(self, parent_id, task="child"):
  89. return await agent(task=task, context=self._context(parent_id))
  90. async def _local_children(self, parent_id):
  91. return await self.store.list_traces(
  92. parent_trace_id=parent_id,
  93. created_by_tool="agent",
  94. limit=20,
  95. )
  96. async def test_legacy_preserves_single_level_behavior(self):
  97. legacy_root = await self._create_root("legacy-root", agent_mode="legacy")
  98. first = await self._spawn_one(legacy_root)
  99. self.assertEqual("completed", first["status"])
  100. child_id = first["sub_trace_id"]
  101. child_config = self.runner.configs[-1]
  102. self.assertNotIn("agent", child_config.tools)
  103. blocked = await self._spawn_one(child_id, "grandchild")
  104. self.assertEqual("failed", blocked["status"])
  105. self.assertIn("depth limit reached", blocked["error"])
  106. self.assertIn("mode=legacy", blocked["error"])
  107. async def test_legacy_has_no_direct_child_quota(self):
  108. legacy_root = await self._create_root("legacy-unlimited", agent_mode="legacy")
  109. result = await agent(
  110. task=[f"legacy-child-{index}" for index in range(8)],
  111. context=self._context(legacy_root),
  112. )
  113. self.assertEqual("completed", result["status"])
  114. self.assertEqual(8, len(await self._local_children(legacy_root)))
  115. async def test_five_subagent_levels_and_sixth_level_rejected(self):
  116. parent_id = self.root_id
  117. for expected_depth in range(1, 6):
  118. result = await self._spawn_one(parent_id, f"depth-{expected_depth}")
  119. self.assertEqual("completed", result["status"])
  120. child_id = result["sub_trace_id"]
  121. child = await self.store.get_trace(child_id)
  122. self.assertEqual(parent_id, child.parent_trace_id)
  123. self.assertEqual(expected_depth, child.context["agent_depth"])
  124. self.assertEqual(self.root_id, child.context["root_trace_id"])
  125. tools = self.runner.configs[-1].tools
  126. if expected_depth < 5:
  127. self.assertIn("agent", tools)
  128. else:
  129. self.assertNotIn("agent", tools)
  130. self.assertNotIn("evaluate", tools)
  131. self.assertNotIn("bash_command", tools)
  132. parent_id = child_id
  133. blocked = await self._spawn_one(parent_id, "depth-6")
  134. self.assertEqual("failed", blocked["status"])
  135. self.assertIn("depth limit reached", blocked["error"])
  136. self.assertEqual([], await self._local_children(parent_id))
  137. async def test_six_children_allowed_and_seventh_rejected(self):
  138. tasks = [f"child-{index}" for index in range(6)]
  139. result = await agent(task=tasks, context=self._context(self.root_id))
  140. self.assertEqual("completed", result["status"])
  141. self.assertEqual(6, len(await self._local_children(self.root_id)))
  142. blocked = await self._spawn_one(self.root_id, "child-7")
  143. self.assertEqual("failed", blocked["status"])
  144. self.assertIn("child Agent limit exceeded", blocked["error"])
  145. self.assertEqual(6, len(await self._local_children(self.root_id)))
  146. async def test_child_batch_is_rejected_without_partial_creation(self):
  147. initial = [f"child-{index}" for index in range(5)]
  148. await agent(task=initial, context=self._context(self.root_id))
  149. blocked = await agent(
  150. task=["overflow-1", "overflow-2"],
  151. context=self._context(self.root_id),
  152. )
  153. self.assertEqual("failed", blocked["status"])
  154. self.assertEqual(5, len(await self._local_children(self.root_id)))
  155. async def test_mismatched_per_agent_messages_are_rejected_before_spawn(self):
  156. result = await agent(
  157. task=["first", "second"],
  158. messages=[[{"role": "user", "content": "only one message list"}]],
  159. context=self._context(self.root_id),
  160. )
  161. self.assertEqual("failed", result["status"])
  162. self.assertIn("exactly one message list per task", result["error"])
  163. self.assertEqual([], await self._local_children(self.root_id))
  164. async def test_goal_keeps_children_created_across_multiple_calls(self):
  165. tree = await self.store.get_goal_tree(self.root_id)
  166. tree.goals = [Goal(id="1", description="delegate twice")]
  167. await self.store.update_goal_tree(self.root_id, tree)
  168. context = self._context(self.root_id, goal_id="1")
  169. await agent(task="first", context=context)
  170. await agent(task="second", context=context)
  171. updated_tree = await self.store.get_goal_tree(self.root_id)
  172. sub_trace_ids = updated_tree.find("1").sub_trace_ids
  173. self.assertEqual(2, len(sub_trace_ids))
  174. self.assertEqual(2, len({entry["trace_id"] for entry in sub_trace_ids}))
  175. async def test_legacy_goal_overwrites_sub_traces_with_latest_call(self):
  176. legacy_root = await self._create_root("legacy-goal", agent_mode="legacy")
  177. tree = await self.store.get_goal_tree(legacy_root)
  178. tree.goals = [Goal(id="1", description="delegate twice")]
  179. await self.store.update_goal_tree(legacy_root, tree)
  180. context = self._context(legacy_root, goal_id="1")
  181. first = await agent(task="first", context=context)
  182. second = await agent(task="second", context=context)
  183. updated_tree = await self.store.get_goal_tree(legacy_root)
  184. sub_trace_ids = updated_tree.find("1").sub_trace_ids
  185. self.assertEqual(
  186. [{"trace_id": second["sub_trace_id"], "mission": "second"}],
  187. sub_trace_ids,
  188. )
  189. self.assertNotEqual(first["sub_trace_id"], second["sub_trace_id"])
  190. async def test_concurrent_batches_never_exceed_limit(self):
  191. results = await asyncio.gather(
  192. agent(
  193. task=[f"left-{index}" for index in range(4)],
  194. context=self._context(self.root_id),
  195. ),
  196. agent(
  197. task=[f"right-{index}" for index in range(4)],
  198. context=self._context(self.root_id),
  199. ),
  200. )
  201. self.assertEqual({"completed", "failed"}, {item["status"] for item in results})
  202. self.assertLessEqual(len(await self._local_children(self.root_id)), 6)
  203. async def test_continue_from_does_not_consume_child_slot(self):
  204. tasks = [f"child-{index}" for index in range(6)]
  205. created = await agent(task=tasks, context=self._context(self.root_id))
  206. child_id = created["sub_trace_ids"][0]["trace_id"]
  207. continued = await agent(
  208. task="continue existing child",
  209. continue_from=child_id,
  210. context=self._context(self.root_id),
  211. )
  212. self.assertEqual("completed", continued["status"])
  213. self.assertTrue(continued["continue_from"])
  214. self.assertEqual(6, len(await self._local_children(self.root_id)))
  215. async def test_continue_from_requires_direct_child_and_matching_owner(self):
  216. created = await self._spawn_one(self.root_id)
  217. child_id = created["sub_trace_id"]
  218. other_root = await self._create_root("other-root")
  219. wrong_parent = await agent(
  220. task="continue",
  221. continue_from=child_id,
  222. context=self._context(other_root),
  223. )
  224. self.assertEqual("failed", wrong_parent["status"])
  225. self.assertIn("direct child", wrong_parent["error"])
  226. await self.store.update_trace(child_id, uid="other-user")
  227. wrong_owner = await agent(
  228. task="continue",
  229. continue_from=child_id,
  230. context=self._context(self.root_id),
  231. )
  232. self.assertEqual("failed", wrong_owner["status"])
  233. self.assertIn("owner", wrong_owner["error"])
  234. async def test_continue_from_requires_matching_persisted_mode(self):
  235. created = await self._spawn_one(self.root_id)
  236. child_id = created["sub_trace_id"]
  237. child = await self.store.get_trace(child_id)
  238. child.context["agent_mode"] = "legacy"
  239. await self.store.update_trace(child_id, context=child.context)
  240. result = await agent(
  241. task="continue",
  242. continue_from=child_id,
  243. context=self._context(self.root_id),
  244. )
  245. self.assertEqual("failed", result["status"])
  246. self.assertIn("mode does not match", result["error"])
  247. async def test_continue_from_rejects_cross_tool_traces(self):
  248. evaluated = await evaluate(messages=[], context=self._context(self.root_id))
  249. rejected_agent = await agent(
  250. task="wrong tool",
  251. continue_from=evaluated["sub_trace_id"],
  252. context=self._context(self.root_id),
  253. )
  254. self.assertEqual("failed", rejected_agent["status"])
  255. self.assertIn("created by the agent tool", rejected_agent["error"])
  256. created = await self._spawn_one(self.root_id)
  257. rejected_evaluator = await evaluate(
  258. messages=[],
  259. continue_from=created["sub_trace_id"],
  260. context=self._context(self.root_id),
  261. )
  262. self.assertEqual("failed", rejected_evaluator["status"])
  263. self.assertIn("created by evaluate", rejected_evaluator["error"])
  264. async def test_continue_from_rejects_forged_depth_or_root_lineage(self):
  265. created = await self._spawn_one(self.root_id)
  266. child_id = created["sub_trace_id"]
  267. child = await self.store.get_trace(child_id)
  268. child.context["agent_depth"] = 0
  269. child.context["root_trace_id"] = "wrong-root"
  270. await self.store.update_trace(child_id, context=child.context)
  271. result = await agent(
  272. task="continue forged child",
  273. continue_from=child_id,
  274. context=self._context(self.root_id),
  275. )
  276. self.assertEqual("failed", result["status"])
  277. self.assertIn("lineage does not match", result["error"])
  278. async def test_evaluator_never_receives_recursive_or_shell_tools(self):
  279. await evaluate(messages=[], context=self._context(self.root_id))
  280. config = self.runner.configs[-1]
  281. self.assertEqual([], config.tool_groups)
  282. self.assertEqual(
  283. ["agent", "evaluate", "bash_command"],
  284. config.exclude_tools,
  285. )
  286. async def test_evaluator_traces_do_not_consume_local_child_slots(self):
  287. for _ in range(2):
  288. result = await evaluate(messages=[], context=self._context(self.root_id))
  289. self.assertEqual("completed", result["status"])
  290. result = await agent(
  291. task=[f"child-{index}" for index in range(6)],
  292. context=self._context(self.root_id),
  293. )
  294. self.assertEqual("completed", result["status"])
  295. self.assertEqual(6, len(await self._local_children(self.root_id)))
  296. async def test_trace_without_mode_is_treated_as_legacy(self):
  297. historical_root = await self._create_root(
  298. "historical-root",
  299. include_mode=False,
  300. )
  301. child = await self._spawn_one(historical_root, "legacy child")
  302. self.assertEqual("completed", child["status"])
  303. child_trace = await self.store.get_trace(child["sub_trace_id"])
  304. self.assertEqual("legacy", child_trace.context["agent_mode"])
  305. self.assertNotIn("agent", self.runner.configs[-1].tools)
  306. async def test_remote_agent_is_not_counted_as_local_child(self):
  307. child = await self._spawn_one(self.root_id)
  308. before = len(await self._local_children(child["sub_trace_id"]))
  309. remote_result = {
  310. "mode": "remote",
  311. "agent_type": "remote_research",
  312. "status": "completed",
  313. "summary": "remote completed",
  314. "stats": {},
  315. }
  316. with patch(
  317. "cyber_agent.tools.builtin.subagent._run_remote_agent",
  318. new=AsyncMock(return_value=remote_result),
  319. ):
  320. result = await agent(
  321. task="remote task",
  322. agent_type="remote_research",
  323. context=self._context(child["sub_trace_id"]),
  324. )
  325. self.assertEqual("completed", result["status"])
  326. self.assertEqual(before, len(await self._local_children(child["sub_trace_id"])))
  327. if __name__ == "__main__":
  328. unittest.main()