feat(subagent): add session-owned task messaging and cancellation (#5985)
let's go!
This commit is contained in:
1 parent
f75470e72f
commit
6ff96f2a8f
93 files changed
+5632
-1156
No files matched your search
@@ -1,7 +1,6 @@
|
||||
"""Tests for subagent tool registration and wiring."""
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
@@ -9,7 +8,9 @@ import pytest
|
||||
|
||||
from nanobot.agent.context import TranscriptInput
|
||||
from nanobot.agent.memory import Consolidator
|
||||
from nanobot.agent.runner import AgentRunResult
|
||||
from nanobot.agent.tools.context import RequestContext
|
||||
from nanobot.agent.tools.registry import is_tool_error_result
|
||||
from nanobot.config.schema import AgentDefaults
|
||||
from nanobot.providers.base import GenerationSettings
|
||||
from nanobot.utils.llm_runtime import LLMRuntime
|
||||
@@ -35,7 +36,8 @@ async def test_run_inline_returns_result_without_announcement(tmp_path):
|
||||
bus=MessageBus(),
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
)
|
||||
manager.runner.run = AsyncMock(return_value=SimpleNamespace(
|
||||
manager.runner.run = AsyncMock(return_value=AgentRunResult(
|
||||
messages=[],
|
||||
stop_reason="done",
|
||||
final_content="review result",
|
||||
error=None,
|
||||
@@ -52,8 +54,7 @@ async def test_run_inline_returns_result_without_announcement(tmp_path):
|
||||
assert result == "review result"
|
||||
manager._announce_result.assert_not_awaited()
|
||||
assert manager._running_tasks == {}
|
||||
assert manager._task_statuses == {}
|
||||
assert manager._session_tasks == {}
|
||||
assert [s.state for s in manager.statuses_for_session("test:c1").values()] == ["done"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -69,7 +70,8 @@ async def test_run_inline_returns_structured_error(tmp_path):
|
||||
bus=MessageBus(),
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
)
|
||||
manager.runner.run = AsyncMock(return_value=SimpleNamespace(
|
||||
manager.runner.run = AsyncMock(return_value=AgentRunResult(
|
||||
messages=[],
|
||||
stop_reason="error",
|
||||
final_content=None,
|
||||
error="subagent failed",
|
||||
@@ -85,13 +87,13 @@ async def test_run_inline_returns_structured_error(tmp_path):
|
||||
assert result == "subagent failed"
|
||||
assert is_tool_error_result(result)
|
||||
assert manager._running_tasks == {}
|
||||
assert manager._session_tasks == {}
|
||||
assert [s.state for s in manager.statuses_for_session("test:c1").values()] == ["error"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_subagent_exec_tool_receives_allowed_env_keys(tmp_path):
|
||||
"""allowed_env_keys from ExecToolConfig must be forwarded to the subagent's ExecTool."""
|
||||
from nanobot.agent.subagent import SubagentManager, SubagentStatus
|
||||
from nanobot.agent.subagent import SubagentManager
|
||||
from nanobot.agent.tools.shell import ExecToolConfig
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.config.schema import ToolsConfig
|
||||
@@ -112,7 +114,8 @@ async def test_subagent_exec_tool_receives_allowed_env_keys(tmp_path):
|
||||
exec_tool = spec.tools.get("exec")
|
||||
assert exec_tool is not None
|
||||
assert exec_tool.allowed_env_keys == ["GOPATH", "JAVA_HOME"]
|
||||
return SimpleNamespace(
|
||||
return AgentRunResult(
|
||||
messages=[],
|
||||
stop_reason="done",
|
||||
final_content="done",
|
||||
error=None,
|
||||
@@ -121,17 +124,14 @@ async def test_subagent_exec_tool_receives_allowed_env_keys(tmp_path):
|
||||
|
||||
mgr.runner.run = AsyncMock(side_effect=fake_run)
|
||||
|
||||
status = SubagentStatus(
|
||||
task_id="sub-1", label="label", task_description="do task", started_at=time.monotonic()
|
||||
)
|
||||
await mgr._run_subagent(
|
||||
"sub-1",
|
||||
"do task",
|
||||
"label",
|
||||
{"channel": "test", "chat_id": "c1"},
|
||||
status,
|
||||
_runtime(provider),
|
||||
await mgr.spawn(
|
||||
task="do task",
|
||||
label="label",
|
||||
origin_channel="test",
|
||||
origin_chat_id="c1",
|
||||
runtime=_runtime(provider),
|
||||
)
|
||||
await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
|
||||
|
||||
mgr.runner.run.assert_awaited_once()
|
||||
|
||||
@@ -139,7 +139,7 @@ async def test_subagent_exec_tool_receives_allowed_env_keys(tmp_path):
|
||||
@pytest.mark.asyncio
|
||||
async def test_subagent_uses_configured_max_iterations(tmp_path):
|
||||
"""Subagents should honor the configured tool-iteration limit."""
|
||||
from nanobot.agent.subagent import SubagentManager, SubagentStatus
|
||||
from nanobot.agent.subagent import SubagentManager
|
||||
from nanobot.bus.queue import MessageBus
|
||||
|
||||
bus = MessageBus()
|
||||
@@ -156,7 +156,8 @@ async def test_subagent_uses_configured_max_iterations(tmp_path):
|
||||
|
||||
async def fake_run(spec):
|
||||
assert spec.max_iterations == 37
|
||||
return SimpleNamespace(
|
||||
return AgentRunResult(
|
||||
messages=[],
|
||||
stop_reason="done",
|
||||
final_content="done",
|
||||
error=None,
|
||||
@@ -165,17 +166,14 @@ async def test_subagent_uses_configured_max_iterations(tmp_path):
|
||||
|
||||
mgr.runner.run = AsyncMock(side_effect=fake_run)
|
||||
|
||||
status = SubagentStatus(
|
||||
task_id="sub-1", label="label", task_description="do task", started_at=time.monotonic()
|
||||
)
|
||||
await mgr._run_subagent(
|
||||
"sub-1",
|
||||
"do task",
|
||||
"label",
|
||||
{"channel": "test", "chat_id": "c1"},
|
||||
status,
|
||||
_runtime(provider),
|
||||
await mgr.spawn(
|
||||
task="do task",
|
||||
label="label",
|
||||
origin_channel="test",
|
||||
origin_chat_id="c1",
|
||||
runtime=_runtime(provider),
|
||||
)
|
||||
await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
|
||||
|
||||
mgr.runner.run.assert_awaited_once()
|
||||
|
||||
@@ -203,7 +201,8 @@ async def test_spawn_forwards_temperature_to_run_spec(tmp_path):
|
||||
async def fake_run(spec):
|
||||
seen["temperature"] = spec.runtime.generation.temperature
|
||||
seen["runtime"] = spec.runtime
|
||||
return SimpleNamespace(
|
||||
return AgentRunResult(
|
||||
messages=[],
|
||||
stop_reason="done", final_content="done", error=None, tool_events=[],
|
||||
)
|
||||
|
||||
@@ -221,7 +220,7 @@ async def test_spawn_forwards_temperature_to_run_spec(tmp_path):
|
||||
async def test_background_spawn_waits_for_concurrency_capacity(tmp_path):
|
||||
"""Background tasks should be accepted and start when capacity becomes available."""
|
||||
from nanobot.agent.subagent import SubagentManager
|
||||
from nanobot.agent.tools.spawn import SpawnTool
|
||||
from nanobot.agent.tools.subagent import SubagentTool
|
||||
from nanobot.bus.queue import MessageBus
|
||||
|
||||
bus = MessageBus()
|
||||
@@ -249,7 +248,8 @@ async def test_background_spawn_waits_for_concurrency_capacity(tmp_path):
|
||||
else:
|
||||
second_entered.set()
|
||||
await release_second.wait()
|
||||
return SimpleNamespace(
|
||||
return AgentRunResult(
|
||||
messages=[],
|
||||
stop_reason="done",
|
||||
final_content="done",
|
||||
error=None,
|
||||
@@ -260,23 +260,23 @@ async def test_background_spawn_waits_for_concurrency_capacity(tmp_path):
|
||||
|
||||
from nanobot.agent.tools.context import RequestContext, request_context
|
||||
|
||||
tool = SpawnTool(mgr)
|
||||
tool = SubagentTool(mgr)
|
||||
with request_context(RequestContext(
|
||||
channel="test",
|
||||
chat_id="c1",
|
||||
session_key="test:c1",
|
||||
runtime=_runtime(provider),
|
||||
)):
|
||||
first_result = await tool.execute(task="first task")
|
||||
first_result = await tool.execute(action="create", task="first task")
|
||||
assert "started" in first_result
|
||||
await asyncio.wait_for(first_entered.wait(), timeout=1.0)
|
||||
|
||||
second_result = await tool.execute(task="second task")
|
||||
second_result = await tool.execute(action="create", task="second task")
|
||||
assert "started" in second_result
|
||||
tasks = list(mgr._running_tasks.values())
|
||||
await asyncio.sleep(0)
|
||||
assert not second_entered.is_set()
|
||||
phases = {status.task_description: status.phase for status in mgr._task_statuses.values()}
|
||||
phases = {status.task_description: status.phase for status in mgr.runtime_statuses().values()}
|
||||
assert phases == {"first task": "initializing", "second task": "queued"}
|
||||
|
||||
release_first.set()
|
||||
@@ -288,9 +288,9 @@ async def test_background_spawn_waits_for_concurrency_capacity(tmp_path):
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_spawn_tool_waits_for_inline_result():
|
||||
async def test_subagent_tool_waits_for_inline_result():
|
||||
from nanobot.agent.tools.context import RequestContext, request_context
|
||||
from nanobot.agent.tools.spawn import SpawnTool
|
||||
from nanobot.agent.tools.subagent import SubagentTool
|
||||
|
||||
class Manager:
|
||||
max_concurrent_subagents = 1
|
||||
@@ -306,7 +306,7 @@ async def test_spawn_tool_waits_for_inline_result():
|
||||
return await self.inline(**kwargs)
|
||||
|
||||
manager = Manager()
|
||||
tool = SpawnTool(manager)
|
||||
tool = SubagentTool(manager)
|
||||
runtime = _runtime(MagicMock())
|
||||
with request_context(RequestContext(
|
||||
channel="test",
|
||||
@@ -314,7 +314,7 @@ async def test_spawn_tool_waits_for_inline_result():
|
||||
session_key="test:c1",
|
||||
runtime=runtime,
|
||||
)):
|
||||
result = await tool.execute(task="review this", wait=True)
|
||||
result = await tool.execute(action="create", task="review this", wait=True)
|
||||
|
||||
assert result == "review result"
|
||||
manager.inline.assert_awaited_once()
|
||||
@@ -325,7 +325,7 @@ async def test_spawn_tool_waits_for_inline_result():
|
||||
async def test_inline_spawn_waits_for_concurrency_capacity(tmp_path):
|
||||
from nanobot.agent.subagent import SubagentManager
|
||||
from nanobot.agent.tools.context import RequestContext, request_context
|
||||
from nanobot.agent.tools.spawn import SpawnTool
|
||||
from nanobot.agent.tools.subagent import SubagentTool
|
||||
from nanobot.bus.queue import MessageBus
|
||||
|
||||
manager = SubagentManager(
|
||||
@@ -348,7 +348,8 @@ async def test_inline_spawn_waits_for_concurrency_capacity(tmp_path):
|
||||
else:
|
||||
second_entered.set()
|
||||
await release_second.wait()
|
||||
return SimpleNamespace(
|
||||
return AgentRunResult(
|
||||
messages=[],
|
||||
stop_reason="done",
|
||||
final_content="done",
|
||||
error=None,
|
||||
@@ -356,17 +357,17 @@ async def test_inline_spawn_waits_for_concurrency_capacity(tmp_path):
|
||||
)
|
||||
|
||||
manager.runner.run = AsyncMock(side_effect=fake_run)
|
||||
tool = SpawnTool(manager)
|
||||
tool = SubagentTool(manager)
|
||||
with request_context(RequestContext(
|
||||
channel="test",
|
||||
chat_id="c1",
|
||||
session_key="test:c1",
|
||||
runtime=_runtime(MagicMock()),
|
||||
)):
|
||||
first = asyncio.create_task(tool.execute(task="first", wait=True))
|
||||
first = asyncio.create_task(tool.execute(action="create", task="first", wait=True))
|
||||
await asyncio.wait_for(first_entered.wait(), timeout=1.0)
|
||||
|
||||
second = asyncio.create_task(tool.execute(task="second", wait=True))
|
||||
second = asyncio.create_task(tool.execute(action="create", task="second", wait=True))
|
||||
await asyncio.sleep(0)
|
||||
|
||||
assert not second.done()
|
||||
@@ -379,7 +380,7 @@ async def test_inline_spawn_waits_for_concurrency_capacity(tmp_path):
|
||||
assert await second == "done"
|
||||
|
||||
assert manager.get_running_count() == 0
|
||||
assert manager._session_tasks == {}
|
||||
assert [s.state for s in manager.statuses_for_session("test:c1").values()] == ["done", "done"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -390,7 +391,7 @@ async def test_runner_executes_inline_spawn_batch_concurrently(tmp_path):
|
||||
from nanobot.agent.tools.context import RequestContext, request_context
|
||||
from nanobot.agent.tools.execution import execute_tool_calls
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
from nanobot.agent.tools.spawn import SpawnTool
|
||||
from nanobot.agent.tools.subagent import SubagentTool
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.providers.base import ToolCallRequest
|
||||
|
||||
@@ -410,7 +411,8 @@ async def test_runner_executes_inline_spawn_batch_concurrently(tmp_path):
|
||||
if len(entered) == 2:
|
||||
both_entered.set()
|
||||
await release.wait()
|
||||
return SimpleNamespace(
|
||||
return AgentRunResult(
|
||||
messages=[],
|
||||
stop_reason="done",
|
||||
final_content=spec.initial_messages[-1]["content"],
|
||||
error=None,
|
||||
@@ -419,18 +421,18 @@ async def test_runner_executes_inline_spawn_batch_concurrently(tmp_path):
|
||||
|
||||
manager.runner.run = AsyncMock(side_effect=fake_run)
|
||||
tools = ToolRegistry()
|
||||
tools.register(SpawnTool(manager))
|
||||
tools.register(SubagentTool(manager))
|
||||
runtime = _runtime(MagicMock())
|
||||
calls = [
|
||||
ToolCallRequest(
|
||||
id="spawn-1",
|
||||
name="spawn",
|
||||
arguments={"task": "first", "wait": True},
|
||||
id="create-1",
|
||||
name="subagent",
|
||||
arguments={"action": "create", "task": "first", "wait": True},
|
||||
),
|
||||
ToolCallRequest(
|
||||
id="spawn-2",
|
||||
name="spawn",
|
||||
arguments={"task": "second", "wait": True},
|
||||
id="create-2",
|
||||
name="subagent",
|
||||
arguments={"action": "create", "task": "second", "wait": True},
|
||||
),
|
||||
]
|
||||
|
||||
@@ -485,11 +487,11 @@ async def test_cancel_by_session_cancels_inline_subagent(tmp_path):
|
||||
await asyncio.wait_for(entered.wait(), timeout=1.0)
|
||||
|
||||
assert await manager.cancel_by_session("test:c1") == 1
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await inline
|
||||
result = await inline
|
||||
assert is_tool_error_result(result)
|
||||
assert result == "Task cancelled."
|
||||
assert manager._running_tasks == {}
|
||||
assert manager._task_statuses == {}
|
||||
assert manager._session_tasks == {}
|
||||
assert [s.state for s in manager.statuses_for_session("test:c1").values()] == ["cancelled"]
|
||||
|
||||
|
||||
def test_subagent_default_max_concurrent_matches_agent_defaults(tmp_path):
|
||||
@@ -567,13 +569,12 @@ async def test_agent_loop_syncs_updated_max_iterations_before_run(tmp_path):
|
||||
async def fake_run(spec):
|
||||
assert spec.max_iterations == 55
|
||||
assert loop.subagents.max_iterations == 55
|
||||
return SimpleNamespace(
|
||||
return AgentRunResult(
|
||||
messages=[],
|
||||
stop_reason="done",
|
||||
final_content="done",
|
||||
error=None,
|
||||
tool_events=[],
|
||||
messages=[],
|
||||
usage=None,
|
||||
had_injections=False,
|
||||
tools_used=[],
|
||||
)
|
||||
@@ -609,13 +610,12 @@ async def test_drain_pending_no_block_when_no_subagents(tmp_path):
|
||||
nonlocal injection_callback, terminal_injection_callback
|
||||
injection_callback = spec.injection_callback
|
||||
terminal_injection_callback = spec.terminal_injection_callback
|
||||
return SimpleNamespace(
|
||||
return AgentRunResult(
|
||||
messages=[],
|
||||
stop_reason="done",
|
||||
final_content="done",
|
||||
error=None,
|
||||
tool_events=[],
|
||||
messages=[],
|
||||
usage=None,
|
||||
had_injections=False,
|
||||
tools_used=[],
|
||||
provider_state=None,
|
||||
@@ -660,13 +660,12 @@ async def test_terminal_drain_timeout(tmp_path):
|
||||
async def fake_runner_run(spec):
|
||||
nonlocal terminal_injection_callback
|
||||
terminal_injection_callback = spec.terminal_injection_callback
|
||||
return SimpleNamespace(
|
||||
return AgentRunResult(
|
||||
messages=[],
|
||||
stop_reason="done",
|
||||
final_content="done",
|
||||
error=None,
|
||||
tool_events=[],
|
||||
messages=[],
|
||||
usage=None,
|
||||
had_injections=False,
|
||||
tools_used=[],
|
||||
provider_state=None,
|
||||
@@ -674,13 +673,11 @@ async def test_terminal_drain_timeout(tmp_path):
|
||||
|
||||
loop.runner.run = AsyncMock(side_effect=fake_runner_run)
|
||||
|
||||
# Register a "running" sub-agent that will never complete
|
||||
async def _hang_forever():
|
||||
async def _hang_forever(spec):
|
||||
await asyncio.Event().wait()
|
||||
|
||||
hang_task = asyncio.create_task(_hang_forever())
|
||||
loop.subagents._session_tasks.setdefault(session.key, set()).add("sub-timeout-1")
|
||||
loop.subagents._running_tasks["sub-timeout-1"] = hang_task
|
||||
loop.subagents.runner.run = _hang_forever
|
||||
await loop.subagents.spawn("pending", runtime=loop.llm_runtime(), session_key=session.key)
|
||||
|
||||
runtime = loop.llm_runtime()
|
||||
await loop._run_agent_loop(
|
||||
@@ -707,12 +704,7 @@ async def test_terminal_drain_timeout(tmp_path):
|
||||
results = await terminal_injection_callback()
|
||||
assert results == []
|
||||
|
||||
# Cleanup
|
||||
hang_task.cancel()
|
||||
try:
|
||||
await hang_task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
await loop.subagents.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -736,13 +728,12 @@ async def test_terminal_drain_reuses_one_timeout_budget(tmp_path):
|
||||
async def fake_runner_run(spec):
|
||||
nonlocal terminal_injection_callback
|
||||
terminal_injection_callback = spec.terminal_injection_callback
|
||||
return SimpleNamespace(
|
||||
return AgentRunResult(
|
||||
messages=[],
|
||||
stop_reason="done",
|
||||
final_content="done",
|
||||
error=None,
|
||||
tool_events=[],
|
||||
messages=[],
|
||||
usage=None,
|
||||
had_injections=False,
|
||||
tools_used=[],
|
||||
provider_state=None,
|
||||
@@ -750,12 +741,11 @@ async def test_terminal_drain_reuses_one_timeout_budget(tmp_path):
|
||||
|
||||
loop.runner.run = AsyncMock(side_effect=fake_runner_run)
|
||||
|
||||
async def _hang_forever():
|
||||
async def _hang_forever(spec):
|
||||
await asyncio.Event().wait()
|
||||
|
||||
hang_task = asyncio.create_task(_hang_forever())
|
||||
loop.subagents._session_tasks.setdefault(session.key, set()).add("sub-deadline-1")
|
||||
loop.subagents._running_tasks["sub-deadline-1"] = hang_task
|
||||
loop.subagents.runner.run = _hang_forever
|
||||
await loop.subagents.spawn("pending", runtime=loop.llm_runtime(), session_key=session.key)
|
||||
|
||||
await loop._run_agent_loop(
|
||||
TranscriptInput(history=[{"role": "user", "content": "test"}], current_message=None),
|
||||
@@ -788,6 +778,4 @@ async def test_terminal_drain_reuses_one_timeout_budget(tmp_path):
|
||||
|
||||
assert timeouts == [300.0, 200.0]
|
||||
|
||||
hang_task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await hang_task
|
||||
await loop.subagents.close()
|
||||
Reference in new issue
Block a user