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
@@ -2,6 +2,8 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
@@ -71,7 +73,6 @@ def test_runtime_snapshot_has_exact_allowlist_and_redacts_secrets(tmp_path: Path
|
||||
"tool_names",
|
||||
"web_config",
|
||||
"exec_config",
|
||||
"subagents",
|
||||
})
|
||||
assert RUNTIME_SNAPSHOT_KEYS == expected_snapshot_keys
|
||||
assert frozenset(values) == expected_snapshot_keys
|
||||
@@ -247,64 +248,117 @@ def runtime() -> LLMRuntime:
|
||||
return LLMRuntime(MagicMock(), "test", GenerationSettings(), 128_000)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", [None, "subagents", "subagents._task_statuses"])
|
||||
async def test_my_subagent_snapshot_is_session_scoped(tmp_path, key, runtime):
|
||||
@pytest.mark.parametrize("params", [
|
||||
{"action": "create"},
|
||||
{"action": "create", "task": " "},
|
||||
{"action": "send", "message": "update"},
|
||||
{"action": "cancel"},
|
||||
])
|
||||
async def test_subagent_rejects_missing_action_inputs(tmp_path, runtime, params):
|
||||
loop = _make_loop(tmp_path)
|
||||
with request_context(RequestContext("test", "route", session_key="owner", runtime=runtime)):
|
||||
result = await loop.tools.execute("subagent", params)
|
||||
assert result.startswith("Error:")
|
||||
assert loop.subagents.get_running_count() == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("single_task", [False, True])
|
||||
async def test_subagent_check_is_session_scoped(tmp_path, single_task, runtime):
|
||||
loop = _make_loop(tmp_path)
|
||||
manager = loop.subagents
|
||||
# Spawn without yielding to the child runner: queued tasks must be scoped too.
|
||||
# Queued tasks must be scoped before their runner starts.
|
||||
await manager.spawn("ALPHA_PRIVATE_TASK", label="ALPHA_LABEL", session_key="owner:a", runtime=runtime)
|
||||
await manager.spawn("BETA_PRIVATE_TASK", label="BETA_LABEL", session_key="owner:b", runtime=runtime)
|
||||
try:
|
||||
tool = _my_tool(loop)
|
||||
with request_context(RequestContext("test", "same-chat", session_key="owner:a")):
|
||||
snapshot = tool._runtime_control.snapshot()
|
||||
assert len(snapshot.subagent_statuses) == 1
|
||||
assert "BETA" not in repr(snapshot.as_mapping())
|
||||
result = await tool.execute(action="check", key=key)
|
||||
assert "ALPHA_LABEL" in result
|
||||
assert "BETA" not in result
|
||||
with request_context(RequestContext("test", "same-chat", session_key="owner:b")):
|
||||
result = await tool.execute(action="check", key=key)
|
||||
assert "BETA_LABEL" in result
|
||||
assert "ALPHA" not in result
|
||||
for owner, visible, hidden in [("owner:a", "ALPHA", "BETA"), ("owner:b", "BETA", "ALPHA")]:
|
||||
with request_context(RequestContext("test", "same-chat", session_key=owner)):
|
||||
params = {"action": "check"}
|
||||
if single_task:
|
||||
params["task_id"] = next(iter(manager.statuses_for_session(owner)))
|
||||
result = await loop.tools.execute("subagent", params)
|
||||
assert visible + "_LABEL" in result
|
||||
assert visible + "_PRIVATE_TASK" in result
|
||||
assert hidden not in result
|
||||
assert "queued" in result
|
||||
overview = await loop.tools.execute("my", {"action": "check"})
|
||||
assert "ALPHA" not in overview and "BETA" not in overview
|
||||
assert "not accessible" in await loop.tools.execute("my", {
|
||||
"action": "check", "key": "subagents",
|
||||
})
|
||||
finally:
|
||||
await manager.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ["", ".task_description", ".tool_events", ".usage"])
|
||||
async def test_my_rejects_other_sessions_task_paths(tmp_path, field, runtime):
|
||||
async def test_subagent_check_rejects_foreign_task(tmp_path, runtime):
|
||||
loop = _make_loop(tmp_path)
|
||||
manager = loop.subagents
|
||||
await manager.spawn("PRIVATE_TASK", session_key="owner:a", runtime=runtime)
|
||||
try:
|
||||
task_id = next(iter(manager.statuses_for_session("owner:a")))
|
||||
tool = _my_tool(loop)
|
||||
with request_context(RequestContext("test", "same-chat", session_key="owner:a")):
|
||||
detail = await tool.execute(action="check", key=f"subagents._task_statuses.{task_id}")
|
||||
assert "PRIVATE_TASK" in detail
|
||||
with request_context(RequestContext("test", "same-chat", session_key="owner:b")):
|
||||
result = await tool.execute(
|
||||
action="check", key=f"subagents._task_statuses.{task_id}{field}",
|
||||
)
|
||||
assert result.startswith("Error:")
|
||||
assert "PRIVATE_TASK" not in result
|
||||
result = await loop.tools.execute("subagent", {"action": "check", "task_id": task_id})
|
||||
unknown = await loop.tools.execute("subagent", {"action": "check", "task_id": "unknown"})
|
||||
assert result == unknown
|
||||
assert result.startswith("Error: task unavailable")
|
||||
finally:
|
||||
await manager.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("session_key", [None, ""])
|
||||
async def test_my_without_session_cannot_enumerate_tasks(tmp_path, session_key, runtime):
|
||||
async def test_subagent_check_without_session_cannot_enumerate_tasks(tmp_path, session_key, runtime):
|
||||
loop = _make_loop(tmp_path)
|
||||
manager = loop.subagents
|
||||
await manager.spawn("PRIVATE_TASK", session_key="owner:a", runtime=runtime)
|
||||
try:
|
||||
tool = _my_tool(loop)
|
||||
assert tool._runtime_control.snapshot().subagent_statuses == {}
|
||||
assert "PRIVATE_TASK" not in await tool.execute(action="check")
|
||||
assert "unavailable" in await tool.execute(action="check", key="subagents")
|
||||
task_id = next(iter(manager.statuses_for_session("owner:a")))
|
||||
assert "unavailable" in await loop.tools.execute("subagent", {"action": "check"})
|
||||
with request_context(RequestContext("test", "same-chat", session_key=session_key)):
|
||||
assert tool._runtime_control.snapshot().subagent_statuses == {}
|
||||
assert "PRIVATE_TASK" not in await tool.execute(action="check")
|
||||
assert "unavailable" in await tool.execute(action="check", key="subagents._task_statuses")
|
||||
assert "unavailable" in await loop.tools.execute("subagent", {"action": "check"})
|
||||
assert "unavailable" in await loop.tools.execute("subagent", {
|
||||
"action": "check", "task_id": task_id,
|
||||
})
|
||||
finally:
|
||||
await manager.close()
|
||||
|
||||
|
||||
async def test_subagent_check_retained_results_and_receipts_are_scoped_and_detached(tmp_path, runtime):
|
||||
from nanobot.agent.runner import AgentRunResult
|
||||
|
||||
loop = _make_loop(tmp_path)
|
||||
manager = loop.subagents
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
|
||||
async def run(spec):
|
||||
entered.set()
|
||||
await release.wait()
|
||||
return AgentRunResult(messages=[], final_content="PRIVATE_RESULT")
|
||||
|
||||
manager.runner.run = run
|
||||
owner = RequestContext("test", "route", session_key="owner:a", runtime=runtime)
|
||||
try:
|
||||
with request_context(owner):
|
||||
await loop.tools.execute("subagent", {"action": "create", "task": "private"})
|
||||
await entered.wait()
|
||||
task_id = next(iter(manager.statuses_for_session("owner:a")))
|
||||
sent = json.loads(await loop.tools.execute("subagent", {
|
||||
"action": "send", "task_id": task_id, "message": "pending",
|
||||
}))
|
||||
release.set()
|
||||
await asyncio.gather(*manager._running_tasks.values())
|
||||
params = {"action": "check", "task_id": task_id}
|
||||
result = json.loads(await loop.tools.execute("subagent", params))
|
||||
assert result["state"] == "done"
|
||||
assert result["result"] == "PRIVATE_RESULT"
|
||||
assert result["receipts"] == {sent["message_id"]: "undelivered"}
|
||||
snapshot = manager.check(task_id, "owner:a")
|
||||
snapshot.receipts.clear()
|
||||
snapshot.result = "tampered"
|
||||
assert json.loads(await loop.tools.execute("subagent", params)) == result
|
||||
listed = json.loads(await loop.tools.execute("subagent", {"action": "check"}))
|
||||
assert listed == {"tasks": [result]}
|
||||
with request_context(RequestContext("test", "route", session_key="owner:b")):
|
||||
assert "unavailable" in await loop.tools.execute("subagent", params)
|
||||
assert json.loads(await loop.tools.execute("subagent", {"action": "check"})) == {"tasks": []}
|
||||
finally:
|
||||
release.set()
|
||||
await manager.close()
|
||||
@@ -40,6 +40,7 @@ def _make_mock_loop(**overrides):
|
||||
loop._unified_session = False
|
||||
loop._extra_hooks = []
|
||||
loop.set_runtime_model.side_effect = lambda value: setattr(loop, "model", value)
|
||||
loop.set_runtime_max_iterations.side_effect = lambda value: setattr(loop, "max_iterations", value)
|
||||
loop.set_runtime_context_window.side_effect = lambda value: setattr(
|
||||
loop,
|
||||
"context_window_tokens",
|
||||
@@ -59,12 +60,6 @@ def _make_mock_loop(**overrides):
|
||||
|
||||
# SubagentManager mock
|
||||
loop.subagents = MagicMock()
|
||||
loop.subagents._running_tasks = {"abc123": MagicMock(done=MagicMock(return_value=False))}
|
||||
loop.subagents._task_statuses = {}
|
||||
loop.subagents.statuses_for_session.side_effect = (
|
||||
lambda key: loop.subagents._task_statuses if key == "test:owner" else {}
|
||||
)
|
||||
loop.subagents.get_running_count = MagicMock(return_value=1)
|
||||
|
||||
for k, v in overrides.items():
|
||||
setattr(loop, k, v)
|
||||
@@ -412,11 +407,11 @@ class TestModifyOpen:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_modify_subagents_blocked(self):
|
||||
"""subagents is READ_ONLY — cannot be replaced."""
|
||||
"""Subagent control is outside the self-inspection capability."""
|
||||
tool = _make_tool()
|
||||
new_subagents = MagicMock()
|
||||
result = await tool.execute(action="set", key="subagents", value=new_subagents)
|
||||
assert "read-only" in result
|
||||
assert "protected" in result
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_modify_runner_blocked(self):
|
||||
@@ -584,78 +579,6 @@ class TestDeniedAttrs:
|
||||
assert "protected" in result, f"{attr} should be blocked"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# SubagentStatus formatting
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestSubagentStatusFormatting:
|
||||
|
||||
def test_format_single_status(self):
|
||||
"""_format_value should produce a rich multi-line display for a SubagentStatus."""
|
||||
from nanobot.agent.subagent import SubagentStatus
|
||||
|
||||
status = SubagentStatus(
|
||||
task_id="abc12345",
|
||||
label="read logs and summarize",
|
||||
task_description="Read the log files and produce a summary",
|
||||
started_at=time.monotonic() - 12.4,
|
||||
phase="awaiting_tools",
|
||||
iteration=3,
|
||||
tool_events=[
|
||||
{"name": "read_file", "status": "ok", "detail": "read app.log"},
|
||||
{"name": "grep", "status": "ok", "detail": "searched ERROR"},
|
||||
{"name": "exec", "status": "error", "detail": "timeout"},
|
||||
],
|
||||
usage=LLMUsage.reported(input_tokens=4500, output_tokens=1200),
|
||||
)
|
||||
result = MyTool._format_value(status)
|
||||
assert "abc12345" in result
|
||||
assert "read logs and summarize" in result
|
||||
assert "awaiting_tools" in result
|
||||
assert "iteration: 3" in result
|
||||
assert "read_file(ok)" in result
|
||||
assert "exec(error)" in result
|
||||
assert "4500" in result
|
||||
|
||||
def test_format_status_dict(self):
|
||||
"""_format_value should handle dict[str, SubagentStatus] with rich display."""
|
||||
from nanobot.agent.subagent import SubagentStatus
|
||||
|
||||
statuses = {
|
||||
"abc12345": SubagentStatus(
|
||||
task_id="abc12345",
|
||||
label="task A",
|
||||
task_description="Do task A",
|
||||
started_at=time.monotonic() - 5.0,
|
||||
phase="awaiting_tools",
|
||||
iteration=1,
|
||||
),
|
||||
}
|
||||
result = MyTool._format_value(statuses)
|
||||
assert "1 subagent(s)" in result
|
||||
assert "abc12345" in result
|
||||
assert "task A" in result
|
||||
|
||||
def test_format_empty_status_dict(self):
|
||||
"""Empty dict[str, SubagentStatus] should show 'no running subagents'."""
|
||||
result = MyTool._format_value({})
|
||||
assert "{}" in result
|
||||
|
||||
def test_format_status_with_error(self):
|
||||
"""Status with error should include the error message."""
|
||||
from nanobot.agent.subagent import SubagentStatus
|
||||
|
||||
status = SubagentStatus(
|
||||
task_id="err00001",
|
||||
label="failing task",
|
||||
task_description="A task that fails",
|
||||
started_at=time.monotonic() - 1.0,
|
||||
phase="error",
|
||||
error="Connection refused",
|
||||
)
|
||||
result = MyTool._format_value(status)
|
||||
assert "error: Connection refused" in result
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _SubagentHook after_iteration updates status
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -674,7 +597,7 @@ class TestSubagentHookStatus:
|
||||
task_description="test",
|
||||
started_at=time.monotonic(),
|
||||
)
|
||||
hook = _SubagentHook("test", status)
|
||||
hook = _SubagentHook(status)
|
||||
|
||||
context = AgentHookContext(
|
||||
iteration=5,
|
||||
@@ -701,7 +624,7 @@ class TestSubagentHookStatus:
|
||||
task_description="test",
|
||||
started_at=time.monotonic(),
|
||||
)
|
||||
hook = _SubagentHook("test", status)
|
||||
hook = _SubagentHook(status)
|
||||
|
||||
context = AgentHookContext(
|
||||
iteration=1,
|
||||
@@ -718,7 +641,7 @@ class TestSubagentHookStatus:
|
||||
from nanobot.agent.hook import AgentHookContext
|
||||
from nanobot.agent.subagent import _SubagentHook
|
||||
|
||||
hook = _SubagentHook("test")
|
||||
hook = _SubagentHook()
|
||||
context = AgentHookContext(iteration=1, messages=[])
|
||||
result = await hook.after_iteration(context)
|
||||
|
||||
@@ -780,60 +703,6 @@ class TestCheckpointCallback:
|
||||
assert status.iteration == 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# check subagents._task_statuses via dot-path
|
||||
# Task status inspection requires the owning session context.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestInspectTaskStatuses:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_inspect_task_statuses_accessible(self):
|
||||
"""subagents is READ_ONLY — check should show subagent statuses."""
|
||||
from nanobot.agent.subagent import SubagentStatus
|
||||
|
||||
loop = _make_mock_loop()
|
||||
loop.subagents._task_statuses = {
|
||||
"abc12345": SubagentStatus(
|
||||
task_id="abc12345",
|
||||
label="read logs",
|
||||
task_description="Read the log files",
|
||||
started_at=time.monotonic() - 8.0,
|
||||
phase="awaiting_tools",
|
||||
iteration=2,
|
||||
tool_events=[{"name": "read_file", "status": "ok", "detail": "ok"}],
|
||||
usage=LLMUsage.reported(input_tokens=500, output_tokens=100),
|
||||
),
|
||||
}
|
||||
tool = _make_tool(loop=loop)
|
||||
with request_context(RequestContext("test", "owner", session_key="test:owner")):
|
||||
result = await tool.execute(action="check", key="subagents._task_statuses")
|
||||
assert "abc12345" in result
|
||||
assert "read logs" in result
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_inspect_single_subagent_status_accessible(self):
|
||||
"""subagents._task_statuses.<id> should return individual SubagentStatus."""
|
||||
from nanobot.agent.subagent import SubagentStatus
|
||||
|
||||
loop = _make_mock_loop()
|
||||
status = SubagentStatus(
|
||||
task_id="xyz",
|
||||
label="search code",
|
||||
task_description="Search the codebase",
|
||||
started_at=time.monotonic() - 3.0,
|
||||
phase="done",
|
||||
iteration=4,
|
||||
stop_reason="completed",
|
||||
)
|
||||
loop.subagents._task_statuses = {"xyz": status}
|
||||
tool = _make_tool(loop=loop)
|
||||
with request_context(RequestContext("test", "owner", session_key="test:owner")):
|
||||
result = await tool.execute(action="check", key="subagents._task_statuses.xyz")
|
||||
assert "search code" in result
|
||||
assert "completed" in result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# read-only mode (tools.my.allow_set=False)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -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