Skip to content

Your lightweight open-source personal agent.

fix(my): scope subagent snapshots to the current session (#5976)

chengyongru66f5f2df1545
diff --git a/docs/my-tool.md b/docs/my-tool.md
index 2e2ad3779..8c5f1d16c 100644
--- a/docs/my-tool.md
+++ b/docs/my-tool.md
@@ -160,6 +160,11 @@ Agent: I've used ~53k tokens total so far. I'll keep my remaining replies concis
### "Subagent monitoring"
+Subagent snapshots include only tasks created by the current session. This scope
+also applies to `subagents._task_statuses.<task_id>` and nested fields. Without a
+current session key, direct subagent checks return an error and the full overview
+contains no tasks. Completed tasks are removed; this is not a result archive.
+
```text
Agent: Let me check on the background tasks.
→ my(action="check", key="subagents")
diff --git a/nanobot/agent/subagent.py b/nanobot/agent/subagent.py
index d2f693a0a..0a363876f 100644
--- a/nanobot/agent/subagent.py
+++ b/nanobot/agent/subagent.py
@@ -169,6 +169,17 @@ class SubagentManager:
"""Return the observable task statuses used by runtime-control snapshots."""
return self._task_statuses
+ def statuses_for_session(self, session_key: str | None) -> Mapping[str, SubagentStatus]:
+ """Return only tasks owned by the given session, never a global fallback."""
+ if not session_key:
+ return {}
+ task_ids = self._session_tasks.get(session_key, set())
+ return {
+ task_id: status
+ for task_id, status in self._task_statuses.items()
+ if task_id in task_ids
+ }
+
def set_provider(self, provider: LLMProvider, model: str) -> None:
"""Update the deprecated runtime source used by legacy ``spawn`` calls."""
warnings.warn(
diff --git a/nanobot/agent/tools/runtime_control.py b/nanobot/agent/tools/runtime_control.py
index 3e442db9f..b3550df9b 100644
--- a/nanobot/agent/tools/runtime_control.py
+++ b/nanobot/agent/tools/runtime_control.py
@@ -7,6 +7,8 @@ from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Protocol, TypeAlias, runtime_checkable
+from nanobot.agent.tools.context import current_request_session_key
+
if TYPE_CHECKING:
from nanobot.agent.subagent import SubagentManager, SubagentStatus
from nanobot.agent.tools.shell import ExecToolConfig
@@ -268,7 +270,7 @@ def _snapshot_subagent_statuses(
) -> dict[str, dict[str, object]]:
return {
task_id: _snapshot_subagent_status(status)
- for task_id, status in manager.runtime_statuses().items()
+ for task_id, status in manager.statuses_for_session(current_request_session_key()).items()
}
diff --git a/nanobot/agent/tools/self.py b/nanobot/agent/tools/self.py
index 005ad1be0..63da627b5 100644
--- a/nanobot/agent/tools/self.py
+++ b/nanobot/agent/tools/self.py
@@ -393,6 +393,10 @@ class MyTool(Tool):
def _inspect(self, key: str | None) -> str:
if not key:
return self._inspect_all()
+ if key == "subagents" or key.startswith("subagents."):
+ request_ctx = current_request_context()
+ if request_ctx is None or not request_ctx.session_key:
+ return ToolResult.error("Error: current session context is unavailable")
if key == "request" or key.startswith("request."):
request_ctx = current_request_context()
if request_ctx is None:
diff --git a/tests/agent/tools/test_runtime_control.py b/tests/agent/tools/test_runtime_control.py
index 41cc124e9..44304180e 100644
--- a/tests/agent/tools/test_runtime_control.py
+++ b/tests/agent/tools/test_runtime_control.py
@@ -8,6 +8,7 @@ from unittest.mock import MagicMock
import pytest
from nanobot.agent.loop import AgentLoop
+from nanobot.agent.tools.context import RequestContext, request_context
from nanobot.agent.tools.runtime_control import (
RUNTIME_COMMAND_KEYS,
RUNTIME_SNAPSHOT_KEYS,
@@ -17,6 +18,8 @@ from nanobot.agent.tools.runtime_control import (
from nanobot.agent.tools.self import MyTool, MyToolConfig
from nanobot.bus.queue import MessageBus
from nanobot.config.schema import ToolsConfig
+from nanobot.providers.base import GenerationSettings
+from nanobot.utils.llm_runtime import LLMRuntime
def _make_loop(tmp_path: Path, *, allow_set: bool = False) -> AgentLoop:
@@ -237,3 +240,71 @@ async def test_workspace_display_command_cannot_change_path_enforcement(tmp_path
assert tool._runtime_control.snapshot().workspace == "elsewhere"
assert loop.workspace == tmp_path
assert loop.workspace_scopes.default_workspace == tmp_path
+
+
+def runtime() -> LLMRuntime:
+ return LLMRuntime(MagicMock(), "test", GenerationSettings(), 128_000)
+
+
[email protected]("key", [None, "subagents", "subagents._task_statuses"])
+async def test_my_subagent_snapshot_is_session_scoped(tmp_path, key, runtime):
+ loop = _make_loop(tmp_path)
+ manager = loop.subagents
+ # Spawn without yielding to the child runner: queued tasks must be scoped too.
+ 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
+ finally:
+ await manager.close()
+
+
[email protected]("field", ["", ".task_description", ".tool_events", ".usage"])
+async def test_my_rejects_other_sessions_task_paths(tmp_path, field, 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
+ finally:
+ await manager.close()
+
+
[email protected]("session_key", [None, ""])
+async def test_my_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")
+ 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")
+ finally:
+ await manager.close()
diff --git a/tests/agent/tools/test_self_tool.py b/tests/agent/tools/test_self_tool.py
index e0362b192..77ec3544a 100644
--- a/tests/agent/tools/test_self_tool.py
+++ b/tests/agent/tools/test_self_tool.py
@@ -61,7 +61,9 @@ def _make_mock_loop(**overrides):
loop.subagents = MagicMock()
loop.subagents._running_tasks = {"abc123": MagicMock(done=MagicMock(return_value=False))}
loop.subagents._task_statuses = {}
- loop.subagents.runtime_statuses.side_effect = lambda: 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():
@@ -780,8 +782,7 @@ class TestCheckpointCallback:
# ---------------------------------------------------------------------------
# check subagents._task_statuses via dot-path
-# NOTE: subagents is now BLOCKED for security, so these tests verify
-# that access is properly rejected.
+# Task status inspection requires the owning session context.
# ---------------------------------------------------------------------------
class TestInspectTaskStatuses:
@@ -805,7 +806,8 @@ class TestInspectTaskStatuses:
),
}
tool = _make_tool(loop=loop)
- result = await tool.execute(action="check", key="subagents._task_statuses")
+ 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
@@ -826,7 +828,8 @@ class TestInspectTaskStatuses:
)
loop.subagents._task_statuses = {"xyz": status}
tool = _make_tool(loop=loop)
- result = await tool.execute(action="check", key="subagents._task_statuses.xyz")
+ 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