subagent.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. """Sub-agent manager — run tasks in background async tasks."""
  2. from __future__ import annotations
  3. import asyncio
  4. import json
  5. import uuid
  6. from pathlib import Path
  7. from typing import Any, Awaitable, Callable
  8. from toyclaw.provider import OpenAIProvider
  9. from toyclaw.tools.base import ToolRegistry
  10. from toyclaw.tools.builtin import (
  11. EditFileTool,
  12. ListDirTool,
  13. ReadFileTool,
  14. ShellTool,
  15. WebFetchTool,
  16. WebSearchTool,
  17. WriteFileTool,
  18. )
  19. class SubagentManager:
  20. """Spawns lightweight background sub-agents."""
  21. def __init__(
  22. self,
  23. provider: OpenAIProvider,
  24. workspace: Path,
  25. on_complete: Callable[[str], Awaitable[None]] | None = None,
  26. brave_api_key: str | None = None,
  27. max_iterations: int = 15,
  28. ):
  29. self.provider = provider
  30. self.workspace = workspace
  31. self.on_complete = on_complete
  32. self.brave_api_key = brave_api_key
  33. self.max_iterations = max_iterations
  34. self._tasks: dict[str, asyncio.Task[None]] = {}
  35. async def spawn(
  36. self,
  37. task: str,
  38. label: str | None = None,
  39. origin_channel: str = "cli",
  40. origin_chat_id: str = "direct",
  41. ) -> str:
  42. """Spawn a background sub-agent. Returns immediately."""
  43. task_id = uuid.uuid4().hex[:8]
  44. display = label or (task[:30] + "..." if len(task) > 30 else task)
  45. bg = asyncio.create_task(self._run(task_id, task, display))
  46. self._tasks[task_id] = bg
  47. bg.add_done_callback(lambda _t: self._tasks.pop(task_id, None))
  48. return f"Sub-agent [{display}] started (id: {task_id}). Will notify when done."
  49. # ------------------------------------------------------------------
  50. async def _run(self, task_id: str, task: str, label: str) -> None:
  51. """Execute a sub-agent loop and announce the result."""
  52. try:
  53. result = await self._agent_loop(task)
  54. except Exception as exc:
  55. result = f"Error: {exc}"
  56. announcement = f"🔔 Background task [{label}] finished:\n{result}"
  57. if self.on_complete:
  58. try:
  59. await self.on_complete(announcement)
  60. except Exception:
  61. pass # best-effort delivery
  62. async def _agent_loop(self, task: str) -> str:
  63. """Minimal agent loop (no spawn, no cron — prevent recursion)."""
  64. tools = self._build_tools()
  65. messages: list[dict[str, Any]] = [
  66. {"role": "system", "content": self._system_prompt()},
  67. {"role": "user", "content": task},
  68. ]
  69. for _ in range(self.max_iterations):
  70. resp = await self.provider.chat(messages=messages, tools=tools.get_definitions())
  71. if resp.has_tool_calls:
  72. tc_dicts = [
  73. {
  74. "id": tc.id,
  75. "type": "function",
  76. "function": {
  77. "name": tc.name,
  78. "arguments": json.dumps(tc.arguments, ensure_ascii=False),
  79. },
  80. }
  81. for tc in resp.tool_calls
  82. ]
  83. messages.append({"role": "assistant", "content": resp.content, "tool_calls": tc_dicts})
  84. for tc in resp.tool_calls:
  85. result = await tools.execute(tc.name, tc.arguments)
  86. messages.append({"role": "tool", "tool_call_id": tc.id, "name": tc.name, "content": result})
  87. else:
  88. return resp.content or "Task completed (no output)."
  89. return "Sub-agent reached iteration limit."
  90. def _build_tools(self) -> ToolRegistry:
  91. """Build a restricted tool set — NO spawn, NO cron."""
  92. reg = ToolRegistry()
  93. ws = self.workspace
  94. for cls in (ReadFileTool, WriteFileTool, EditFileTool, ListDirTool):
  95. reg.register(cls(workspace=ws))
  96. reg.register(ShellTool(workspace=ws))
  97. reg.register(WebSearchTool(api_key=self.brave_api_key))
  98. reg.register(WebFetchTool())
  99. return reg
  100. def _system_prompt(self) -> str:
  101. return (
  102. "# Sub-agent\n\n"
  103. "You are a background sub-agent spawned to complete a specific task.\n"
  104. "Stay focused. Your final text response will be reported back.\n\n"
  105. f"## Workspace\n{self.workspace}"
  106. )