test_subagent_recursion.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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. agent_mode_revision=1,
  58. include_mode=True,
  59. ):
  60. context = {
  61. "agent_depth": 0,
  62. "root_trace_id": trace_id,
  63. }
  64. if include_mode:
  65. context.update({
  66. "agent_mode": agent_mode,
  67. "agent_mode_revision": agent_mode_revision,
  68. })
  69. trace = Trace(
  70. trace_id=trace_id,
  71. mode="agent",
  72. task=f"task-{trace_id}",
  73. uid=uid,
  74. model="fake-model",
  75. context=context,
  76. )
  77. await self.store.create_trace(trace)
  78. await self.store.update_goal_tree(trace_id, GoalTree(mission=trace.task))
  79. return trace_id
  80. def _context(self, trace_id, goal_id=None):
  81. return {
  82. "store": self.store,
  83. "trace_id": trace_id,
  84. "goal_id": goal_id,
  85. "runner": self.runner,
  86. "knowledge_config": None,
  87. RECURSIVE_CAPABILITY_TOOLS_CONTEXT_KEY: self.runner.tools.get_tool_names(),
  88. }
  89. async def _spawn_one(self, parent_id, task="child"):
  90. return await agent(task=task, context=self._context(parent_id))
  91. async def _local_children(self, parent_id):
  92. return await self.store.list_traces(
  93. parent_trace_id=parent_id,
  94. created_by_tool="agent",
  95. limit=20,
  96. )
  97. async def test_legacy_preserves_single_level_behavior(self):
  98. legacy_root = await self._create_root("legacy-root", agent_mode="legacy")
  99. first = await self._spawn_one(legacy_root)
  100. self.assertEqual("completed", first["status"])
  101. child_id = first["sub_trace_id"]
  102. child_config = self.runner.configs[-1]
  103. self.assertNotIn("agent", child_config.tools)
  104. blocked = await self._spawn_one(child_id, "grandchild")
  105. self.assertEqual("failed", blocked["status"])
  106. self.assertIn("depth limit reached", blocked["error"])
  107. self.assertIn("mode=legacy", blocked["error"])
  108. async def test_legacy_has_no_direct_child_quota(self):
  109. legacy_root = await self._create_root("legacy-unlimited", agent_mode="legacy")
  110. result = await agent(
  111. task=[f"legacy-child-{index}" for index in range(8)],
  112. context=self._context(legacy_root),
  113. )
  114. self.assertEqual("completed", result["status"])
  115. self.assertEqual(8, len(await self._local_children(legacy_root)))
  116. async def test_five_subagent_levels_and_sixth_level_rejected(self):
  117. parent_id = self.root_id
  118. for expected_depth in range(1, 6):
  119. result = await self._spawn_one(parent_id, f"depth-{expected_depth}")
  120. self.assertEqual("completed", result["status"])
  121. child_id = result["sub_trace_id"]
  122. child = await self.store.get_trace(child_id)
  123. self.assertEqual(parent_id, child.parent_trace_id)
  124. self.assertEqual(expected_depth, child.context["agent_depth"])
  125. self.assertEqual(self.root_id, child.context["root_trace_id"])
  126. tools = self.runner.configs[-1].tools
  127. if expected_depth < 5:
  128. self.assertIn("agent", tools)
  129. else:
  130. self.assertNotIn("agent", tools)
  131. self.assertNotIn("evaluate", tools)
  132. self.assertNotIn("bash_command", tools)
  133. parent_id = child_id
  134. blocked = await self._spawn_one(parent_id, "depth-6")
  135. self.assertEqual("failed", blocked["status"])
  136. self.assertIn("depth limit reached", blocked["error"])
  137. self.assertEqual([], await self._local_children(parent_id))
  138. async def test_six_children_allowed_and_seventh_rejected(self):
  139. tasks = [f"child-{index}" for index in range(6)]
  140. result = await agent(task=tasks, context=self._context(self.root_id))
  141. self.assertEqual("completed", result["status"])
  142. self.assertEqual(6, len(await self._local_children(self.root_id)))
  143. blocked = await self._spawn_one(self.root_id, "child-7")
  144. self.assertEqual("failed", blocked["status"])
  145. self.assertIn("child Agent limit exceeded", blocked["error"])
  146. self.assertEqual(6, len(await self._local_children(self.root_id)))
  147. async def test_child_batch_is_rejected_without_partial_creation(self):
  148. initial = [f"child-{index}" for index in range(5)]
  149. await agent(task=initial, context=self._context(self.root_id))
  150. blocked = await agent(
  151. task=["overflow-1", "overflow-2"],
  152. context=self._context(self.root_id),
  153. )
  154. self.assertEqual("failed", blocked["status"])
  155. self.assertEqual(5, len(await self._local_children(self.root_id)))
  156. async def test_mismatched_per_agent_messages_are_rejected_before_spawn(self):
  157. result = await agent(
  158. task=["first", "second"],
  159. messages=[[{"role": "user", "content": "only one message list"}]],
  160. context=self._context(self.root_id),
  161. )
  162. self.assertEqual("failed", result["status"])
  163. self.assertIn("exactly one message list per task", result["error"])
  164. self.assertEqual([], await self._local_children(self.root_id))
  165. async def test_goal_keeps_children_created_across_multiple_calls(self):
  166. tree = await self.store.get_goal_tree(self.root_id)
  167. tree.goals = [Goal(id="1", description="delegate twice")]
  168. await self.store.update_goal_tree(self.root_id, tree)
  169. context = self._context(self.root_id, goal_id="1")
  170. await agent(task="first", context=context)
  171. await agent(task="second", context=context)
  172. updated_tree = await self.store.get_goal_tree(self.root_id)
  173. sub_trace_ids = updated_tree.find("1").sub_trace_ids
  174. self.assertEqual(2, len(sub_trace_ids))
  175. self.assertEqual(2, len({entry["trace_id"] for entry in sub_trace_ids}))
  176. async def test_legacy_goal_overwrites_sub_traces_with_latest_call(self):
  177. legacy_root = await self._create_root("legacy-goal", agent_mode="legacy")
  178. tree = await self.store.get_goal_tree(legacy_root)
  179. tree.goals = [Goal(id="1", description="delegate twice")]
  180. await self.store.update_goal_tree(legacy_root, tree)
  181. context = self._context(legacy_root, goal_id="1")
  182. first = await agent(task="first", context=context)
  183. second = await agent(task="second", context=context)
  184. updated_tree = await self.store.get_goal_tree(legacy_root)
  185. sub_trace_ids = updated_tree.find("1").sub_trace_ids
  186. self.assertEqual(
  187. [{"trace_id": second["sub_trace_id"], "mission": "second"}],
  188. sub_trace_ids,
  189. )
  190. self.assertNotEqual(first["sub_trace_id"], second["sub_trace_id"])
  191. async def test_concurrent_batches_never_exceed_limit(self):
  192. results = await asyncio.gather(
  193. agent(
  194. task=[f"left-{index}" for index in range(4)],
  195. context=self._context(self.root_id),
  196. ),
  197. agent(
  198. task=[f"right-{index}" for index in range(4)],
  199. context=self._context(self.root_id),
  200. ),
  201. )
  202. self.assertEqual({"completed", "failed"}, {item["status"] for item in results})
  203. self.assertLessEqual(len(await self._local_children(self.root_id)), 6)
  204. async def test_continue_from_does_not_consume_child_slot(self):
  205. tasks = [f"child-{index}" for index in range(6)]
  206. created = await agent(task=tasks, context=self._context(self.root_id))
  207. child_id = created["sub_trace_ids"][0]["trace_id"]
  208. continued = await agent(
  209. task="continue existing child",
  210. continue_from=child_id,
  211. context=self._context(self.root_id),
  212. )
  213. self.assertEqual("completed", continued["status"])
  214. self.assertTrue(continued["continue_from"])
  215. self.assertEqual(6, len(await self._local_children(self.root_id)))
  216. async def test_continue_from_requires_direct_child_and_matching_owner(self):
  217. created = await self._spawn_one(self.root_id)
  218. child_id = created["sub_trace_id"]
  219. other_root = await self._create_root("other-root")
  220. wrong_parent = await agent(
  221. task="continue",
  222. continue_from=child_id,
  223. context=self._context(other_root),
  224. )
  225. self.assertEqual("failed", wrong_parent["status"])
  226. self.assertIn("direct child", wrong_parent["error"])
  227. await self.store.update_trace(child_id, uid="other-user")
  228. wrong_owner = await agent(
  229. task="continue",
  230. continue_from=child_id,
  231. context=self._context(self.root_id),
  232. )
  233. self.assertEqual("failed", wrong_owner["status"])
  234. self.assertIn("owner", wrong_owner["error"])
  235. async def test_continue_from_requires_matching_persisted_mode(self):
  236. created = await self._spawn_one(self.root_id)
  237. child_id = created["sub_trace_id"]
  238. child = await self.store.get_trace(child_id)
  239. child.context["agent_mode"] = "legacy"
  240. await self.store.update_trace(child_id, context=child.context)
  241. result = await agent(
  242. task="continue",
  243. continue_from=child_id,
  244. context=self._context(self.root_id),
  245. )
  246. self.assertEqual("failed", result["status"])
  247. self.assertIn("mode does not match", result["error"])
  248. async def test_continue_from_rejects_cross_tool_traces(self):
  249. evaluated = await evaluate(messages=[], context=self._context(self.root_id))
  250. rejected_agent = await agent(
  251. task="wrong tool",
  252. continue_from=evaluated["sub_trace_id"],
  253. context=self._context(self.root_id),
  254. )
  255. self.assertEqual("failed", rejected_agent["status"])
  256. self.assertIn("created by the agent tool", rejected_agent["error"])
  257. created = await self._spawn_one(self.root_id)
  258. rejected_evaluator = await evaluate(
  259. messages=[],
  260. continue_from=created["sub_trace_id"],
  261. context=self._context(self.root_id),
  262. )
  263. self.assertEqual("failed", rejected_evaluator["status"])
  264. self.assertIn("created by evaluate", rejected_evaluator["error"])
  265. async def test_continue_from_rejects_forged_depth_or_root_lineage(self):
  266. created = await self._spawn_one(self.root_id)
  267. child_id = created["sub_trace_id"]
  268. child = await self.store.get_trace(child_id)
  269. child.context["agent_depth"] = 0
  270. child.context["root_trace_id"] = "wrong-root"
  271. await self.store.update_trace(child_id, context=child.context)
  272. result = await agent(
  273. task="continue forged child",
  274. continue_from=child_id,
  275. context=self._context(self.root_id),
  276. )
  277. self.assertEqual("failed", result["status"])
  278. self.assertIn("lineage does not match", result["error"])
  279. async def test_evaluator_never_receives_recursive_or_shell_tools(self):
  280. await evaluate(messages=[], context=self._context(self.root_id))
  281. config = self.runner.configs[-1]
  282. self.assertEqual([], config.tool_groups)
  283. self.assertEqual(
  284. ["agent", "evaluate", "bash_command"],
  285. config.exclude_tools,
  286. )
  287. async def test_evaluator_traces_do_not_consume_local_child_slots(self):
  288. for _ in range(2):
  289. result = await evaluate(messages=[], context=self._context(self.root_id))
  290. self.assertEqual("completed", result["status"])
  291. result = await agent(
  292. task=[f"child-{index}" for index in range(6)],
  293. context=self._context(self.root_id),
  294. )
  295. self.assertEqual("completed", result["status"])
  296. self.assertEqual(6, len(await self._local_children(self.root_id)))
  297. async def test_trace_without_mode_is_treated_as_legacy(self):
  298. historical_root = await self._create_root(
  299. "historical-root",
  300. include_mode=False,
  301. )
  302. child = await self._spawn_one(historical_root, "legacy child")
  303. self.assertEqual("completed", child["status"])
  304. child_trace = await self.store.get_trace(child["sub_trace_id"])
  305. self.assertEqual("legacy", child_trace.context["agent_mode"])
  306. self.assertNotIn("agent", self.runner.configs[-1].tools)
  307. async def test_remote_agent_is_not_counted_as_local_child(self):
  308. child = await self._spawn_one(self.root_id)
  309. before = len(await self._local_children(child["sub_trace_id"]))
  310. remote_result = {
  311. "mode": "remote",
  312. "agent_type": "remote_research",
  313. "status": "completed",
  314. "summary": "remote completed",
  315. "stats": {},
  316. }
  317. with patch(
  318. "cyber_agent.tools.builtin.subagent._run_remote_agent",
  319. new=AsyncMock(return_value=remote_result),
  320. ):
  321. result = await agent(
  322. task="remote task",
  323. agent_type="remote_research",
  324. context=self._context(child["sub_trace_id"]),
  325. )
  326. self.assertEqual("completed", result["status"])
  327. self.assertEqual(before, len(await self._local_children(child["sub_trace_id"])))
  328. async def test_recursive_revision_2_remote_agent_fails_before_http(self):
  329. root_id = await self._create_root(
  330. "recursive-v2-remote",
  331. agent_mode_revision=2,
  332. )
  333. remote = AsyncMock(return_value={"status": "completed"})
  334. with patch(
  335. "cyber_agent.tools.builtin.subagent._run_remote_agent",
  336. new=remote,
  337. ):
  338. result = await agent(
  339. task="remote task",
  340. agent_type="remote_research",
  341. context=self._context(root_id),
  342. )
  343. self.assertEqual("failed", result["status"])
  344. self.assertEqual(
  345. "Writable Recursive protocol does not support remote agents; "
  346. "use a local task_brief delegation",
  347. result["error"],
  348. )
  349. remote.assert_not_awaited()
  350. self.assertEqual([], await self._local_children(root_id))
  351. if __name__ == "__main__":
  352. unittest.main()