fix(my): scope subagent snapshots to the current session (#5976)
* fix(my): scope subagent snapshots to the current session * test(my): reuse runtime fixture in session isolation checks
This commit is contained in:
1 parent
f18423800e
commit
66f5f2df15
6 files changed
+102
-6
No files matched your search
@@ -160,6 +160,11 @@ Agent: I've used ~53k tokens total so far. I'll keep my remaining replies concis
|
|||||||
|
|
||||||
### "Subagent monitoring"
|
### "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
|
```text
|
||||||
Agent: Let me check on the background tasks.
|
Agent: Let me check on the background tasks.
|
||||||
→ my(action="check", key="subagents")
|
→ my(action="check", key="subagents")
|
||||||
|
|||||||
@@ -169,6 +169,17 @@ class SubagentManager:
|
|||||||
"""Return the observable task statuses used by runtime-control snapshots."""
|
"""Return the observable task statuses used by runtime-control snapshots."""
|
||||||
return self._task_statuses
|
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:
|
def set_provider(self, provider: LLMProvider, model: str) -> None:
|
||||||
"""Update the deprecated runtime source used by legacy ``spawn`` calls."""
|
"""Update the deprecated runtime source used by legacy ``spawn`` calls."""
|
||||||
warnings.warn(
|
warnings.warn(
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ from dataclasses import dataclass
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import TYPE_CHECKING, Protocol, TypeAlias, runtime_checkable
|
from typing import TYPE_CHECKING, Protocol, TypeAlias, runtime_checkable
|
||||||
|
|
||||||
|
from nanobot.agent.tools.context import current_request_session_key
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from nanobot.agent.subagent import SubagentManager, SubagentStatus
|
from nanobot.agent.subagent import SubagentManager, SubagentStatus
|
||||||
from nanobot.agent.tools.shell import ExecToolConfig
|
from nanobot.agent.tools.shell import ExecToolConfig
|
||||||
@@ -268,7 +270,7 @@ def _snapshot_subagent_statuses(
|
|||||||
) -> dict[str, dict[str, object]]:
|
) -> dict[str, dict[str, object]]:
|
||||||
return {
|
return {
|
||||||
task_id: _snapshot_subagent_status(status)
|
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()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -393,6 +393,10 @@ class MyTool(Tool):
|
|||||||
def _inspect(self, key: str | None) -> str:
|
def _inspect(self, key: str | None) -> str:
|
||||||
if not key:
|
if not key:
|
||||||
return self._inspect_all()
|
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."):
|
if key == "request" or key.startswith("request."):
|
||||||
request_ctx = current_request_context()
|
request_ctx = current_request_context()
|
||||||
if request_ctx is None:
|
if request_ctx is None:
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ from unittest.mock import MagicMock
|
|||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from nanobot.agent.loop import AgentLoop
|
from nanobot.agent.loop import AgentLoop
|
||||||
|
from nanobot.agent.tools.context import RequestContext, request_context
|
||||||
from nanobot.agent.tools.runtime_control import (
|
from nanobot.agent.tools.runtime_control import (
|
||||||
RUNTIME_COMMAND_KEYS,
|
RUNTIME_COMMAND_KEYS,
|
||||||
RUNTIME_SNAPSHOT_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.agent.tools.self import MyTool, MyToolConfig
|
||||||
from nanobot.bus.queue import MessageBus
|
from nanobot.bus.queue import MessageBus
|
||||||
from nanobot.config.schema import ToolsConfig
|
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:
|
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 tool._runtime_control.snapshot().workspace == "elsewhere"
|
||||||
assert loop.workspace == tmp_path
|
assert loop.workspace == tmp_path
|
||||||
assert loop.workspace_scopes.default_workspace == tmp_path
|
assert loop.workspace_scopes.default_workspace == tmp_path
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
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):
|
||||||
|
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()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("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()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("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()
|
||||||
@@ -61,7 +61,9 @@ def _make_mock_loop(**overrides):
|
|||||||
loop.subagents = MagicMock()
|
loop.subagents = MagicMock()
|
||||||
loop.subagents._running_tasks = {"abc123": MagicMock(done=MagicMock(return_value=False))}
|
loop.subagents._running_tasks = {"abc123": MagicMock(done=MagicMock(return_value=False))}
|
||||||
loop.subagents._task_statuses = {}
|
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)
|
loop.subagents.get_running_count = MagicMock(return_value=1)
|
||||||
|
|
||||||
for k, v in overrides.items():
|
for k, v in overrides.items():
|
||||||
@@ -780,8 +782,7 @@ class TestCheckpointCallback:
|
|||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# check subagents._task_statuses via dot-path
|
# check subagents._task_statuses via dot-path
|
||||||
# NOTE: subagents is now BLOCKED for security, so these tests verify
|
# Task status inspection requires the owning session context.
|
||||||
# that access is properly rejected.
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
class TestInspectTaskStatuses:
|
class TestInspectTaskStatuses:
|
||||||
@@ -805,7 +806,8 @@ class TestInspectTaskStatuses:
|
|||||||
),
|
),
|
||||||
}
|
}
|
||||||
tool = _make_tool(loop=loop)
|
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 "abc12345" in result
|
||||||
assert "read logs" in result
|
assert "read logs" in result
|
||||||
|
|
||||||
@@ -826,7 +828,8 @@ class TestInspectTaskStatuses:
|
|||||||
)
|
)
|
||||||
loop.subagents._task_statuses = {"xyz": status}
|
loop.subagents._task_statuses = {"xyz": status}
|
||||||
tool = _make_tool(loop=loop)
|
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 "search code" in result
|
||||||
assert "completed" in result
|
assert "completed" in result
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user