refactor(sessions): discover target handles through search (#6315)
Co-authored-by: chengyongru <chengyongru.ai@gmail.com>
This commit is contained in:
1 parent
acc3750c28
commit
b6d9009bb4
6 files changed
+93
-116
No files matched your search
@@ -5,7 +5,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
from collections import OrderedDict, deque
|
||||
from collections.abc import Callable
|
||||
@@ -59,46 +58,6 @@ class _PendingReply:
|
||||
timer: _CancelHandle | None = None
|
||||
|
||||
|
||||
@tool_parameters(tool_parameters_schema())
|
||||
class ListSessionsTool(Tool):
|
||||
"""List the handles of other persisted sessions."""
|
||||
|
||||
def __init__(self, sessions: SessionManager) -> None:
|
||||
self._handles = SessionHandleResolver(sessions)
|
||||
|
||||
@classmethod
|
||||
def create(cls, ctx: ToolContext) -> Tool:
|
||||
if ctx.sessions is None:
|
||||
raise RuntimeError("list_sessions requires a session manager")
|
||||
return cls(ctx.sessions)
|
||||
|
||||
@classmethod
|
||||
def enabled(cls, ctx: ToolContext) -> bool:
|
||||
return ctx.sessions is not None
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return "list_sessions"
|
||||
|
||||
@property
|
||||
def description(self) -> str:
|
||||
return "List other persisted sessions by @handle."
|
||||
|
||||
async def execute(self, **kwargs: Any) -> str:
|
||||
request = current_request_context()
|
||||
if request is None or not request.session_key:
|
||||
return ToolResult.error("Error: session context is unavailable")
|
||||
handles = await self._handles.alist_all()
|
||||
return json.dumps(
|
||||
[
|
||||
f"@{handle.name}"
|
||||
for handle in handles
|
||||
if handle.session_key != request.session_key
|
||||
],
|
||||
ensure_ascii=True,
|
||||
)
|
||||
|
||||
|
||||
@tool_parameters(
|
||||
tool_parameters_schema(
|
||||
to=StringSchema("Target @handle."),
|
||||
|
||||
@@ -54,6 +54,7 @@ def _session_ref(session_key: str) -> str:
|
||||
class _SessionTool(Tool):
|
||||
def __init__(self, sessions: SessionManager) -> None:
|
||||
self._access = SessionHistoryReader(sessions)
|
||||
self._handles = SessionHandleResolver(sessions)
|
||||
|
||||
@classmethod
|
||||
def create(cls, ctx: ToolContext) -> Tool:
|
||||
@@ -81,7 +82,7 @@ class _SessionTool(Tool):
|
||||
)
|
||||
)
|
||||
class SearchSessionsTool(_SessionTool):
|
||||
"""Find persisted sessions without changing them."""
|
||||
"""Find persisted conversations and their public handles."""
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
@@ -90,10 +91,10 @@ class SearchSessionsTool(_SessionTool):
|
||||
@property
|
||||
def description(self) -> str:
|
||||
return (
|
||||
"Search other persisted conversation sessions by title or recent visible message "
|
||||
"text. Use this only when the user asks about a past conversation or when prior "
|
||||
"discussion is needed to answer. Results contain bounded excerpts; use "
|
||||
"read_session for more context. When citing a result, link its title to the exact "
|
||||
"Search other persisted conversations by title or visible message text. Use when "
|
||||
"past discussion is relevant or to find the target of a user-requested session "
|
||||
"message. Results include @handles for read_session and send_session_message "
|
||||
"when available, plus bounded excerpts. When citing a result, link its title to the exact "
|
||||
"session_ref using Markdown. The current session is excluded."
|
||||
)
|
||||
|
||||
@@ -111,6 +112,7 @@ class SearchSessionsTool(_SessionTool):
|
||||
_SEARCH_LIMIT,
|
||||
exclude_session_key=current_request_session_key(),
|
||||
)
|
||||
handles = await self._handles.alist_all_by_key() if matches else {}
|
||||
needle = query.casefold()
|
||||
result = {
|
||||
"notice": _UNTRUSTED_NOTICE,
|
||||
@@ -119,6 +121,10 @@ class SearchSessionsTool(_SessionTool):
|
||||
{
|
||||
"session_key": match["session_key"],
|
||||
"session_ref": _session_ref(match["session_key"]),
|
||||
"handle": (
|
||||
f"@{handles[match['session_key']].name}"
|
||||
if match["session_key"] in handles else None
|
||||
),
|
||||
"title": match["title"],
|
||||
"updated_at": match["updated_at"],
|
||||
"excerpts": [
|
||||
@@ -156,10 +162,6 @@ class SearchSessionsTool(_SessionTool):
|
||||
class ReadSessionTool(_SessionTool):
|
||||
"""Read bounded visible history from one persisted session."""
|
||||
|
||||
def __init__(self, sessions: SessionManager) -> None:
|
||||
super().__init__(sessions)
|
||||
self._handles = SessionHandleResolver(sessions)
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return "read_session"
|
||||
|
||||
@@ -31,24 +31,27 @@ async def test_session_tools_find_old_matches_in_full_session(
|
||||
manager.save(session)
|
||||
manager = SessionManager(tmp_path)
|
||||
|
||||
with request_context(RequestContext(
|
||||
channel="sdk", chat_id="current", session_key="sdk:current",
|
||||
)):
|
||||
if tool_name == "search":
|
||||
output = json.loads(await SearchSessionsTool(manager).execute(query="launch decision"))
|
||||
assert [item["session_key"] for item in output["results"]] == [key]
|
||||
matches = output["results"][0]["excerpts"]
|
||||
expected = range(8, 10)
|
||||
else:
|
||||
output = json.loads(await ReadSessionTool(manager).execute(
|
||||
session_key=key, query="launch decision",
|
||||
))
|
||||
matches = output["messages"]
|
||||
expected = range(2, 10)
|
||||
latest = json.loads(await ReadSessionTool(manager).execute(session_key=key))
|
||||
assert len(latest["messages"]) == 8
|
||||
assert [item["message_index"] for item in latest["messages"]] == list(range(352, 360))
|
||||
assert latest["messages"][-1]["content"] == "acknowledged 179"
|
||||
try:
|
||||
with request_context(RequestContext(
|
||||
channel="sdk", chat_id="current", session_key="sdk:current",
|
||||
)):
|
||||
if tool_name == "search":
|
||||
output = json.loads(await SearchSessionsTool(manager).execute(query="launch decision"))
|
||||
assert [item["session_key"] for item in output["results"]] == [key]
|
||||
matches = output["results"][0]["excerpts"]
|
||||
expected = range(8, 10)
|
||||
else:
|
||||
output = json.loads(await ReadSessionTool(manager).execute(
|
||||
session_key=key, query="launch decision",
|
||||
))
|
||||
matches = output["messages"]
|
||||
expected = range(2, 10)
|
||||
latest = json.loads(await ReadSessionTool(manager).execute(session_key=key))
|
||||
assert len(latest["messages"]) == 8
|
||||
assert [item["message_index"] for item in latest["messages"]] == list(range(352, 360))
|
||||
assert latest["messages"][-1]["content"] == "acknowledged 179"
|
||||
finally:
|
||||
await manager.state.aclose()
|
||||
|
||||
assert [item["content"] for item in matches] == [f"launch decision {i}" for i in expected]
|
||||
assert [item["message_index"] for item in matches] == [i * 2 for i in expected]
|
||||
|
||||
@@ -11,12 +11,23 @@ import pytest
|
||||
from nanobot.agent.tools.context import RequestContext, request_context
|
||||
from nanobot.agent.tools.loader import ToolLoader
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
from nanobot.agent.tools.session_messages import SendSessionMessageTool
|
||||
from nanobot.agent.tools.sessions import ReadSessionTool, SearchSessionsTool
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.runtime_context import RuntimeContextBlock, append_runtime_context
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.session_handles import SessionHandleResolver
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def manager(tmp_path):
|
||||
sessions = SessionManager(tmp_path)
|
||||
try:
|
||||
yield sessions
|
||||
finally:
|
||||
await sessions.state.aclose()
|
||||
|
||||
|
||||
def _save_session(
|
||||
manager: SessionManager,
|
||||
key: str,
|
||||
@@ -78,8 +89,7 @@ def test_session_tools_do_not_own_runtime_context(tmp_path) -> None:
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_sessions_has_no_hidden_content_scan_cutoff(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
async def test_search_sessions_has_no_hidden_content_scan_cutoff(manager):
|
||||
# Seed offline on this thread; nested saves share the existing store transaction.
|
||||
with manager._store.transaction():
|
||||
for index in range(200):
|
||||
@@ -108,8 +118,7 @@ async def test_search_sessions_has_no_hidden_content_scan_cutoff(tmp_path):
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_sessions_ranks_titles_before_message_matches(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
async def test_search_sessions_ranks_titles_before_message_matches(manager):
|
||||
_save_session(
|
||||
manager,
|
||||
"websocket:current",
|
||||
@@ -131,19 +140,41 @@ async def test_search_sessions_ranks_titles_before_message_matches(tmp_path):
|
||||
updated_at=datetime(2025, 1, 1),
|
||||
)
|
||||
|
||||
handles = SessionHandleResolver(manager).list_all_by_key()
|
||||
with _webui_request():
|
||||
result = _decode(await SearchSessionsTool(manager).execute(query="pricing"))
|
||||
|
||||
rows = result["results"]
|
||||
assert isinstance(rows, list)
|
||||
assert [row["session_key"] for row in rows] == ["websocket:title", "websocket:body"]
|
||||
assert [row["handle"] for row in rows] == [
|
||||
f"@{handles[key].name}" for key in ("websocket:title", "websocket:body")
|
||||
]
|
||||
assert rows[0]["session_ref"] == "#session/websocket%3Atitle"
|
||||
assert rows[1]["excerpts"][0]["content"] == "The pricing model is BYOK."
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_session_tools_hide_private_and_non_conversation_messages(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
async def test_search_keeps_match_if_session_is_deleted_before_handle_lookup(manager, monkeypatch):
|
||||
key = "slack:history"
|
||||
_save_session(manager, key, title="Database notes", messages=[])
|
||||
tool = SearchSessionsTool(manager)
|
||||
lookup = tool._handles.alist_all_by_key
|
||||
|
||||
async def delete_before_lookup():
|
||||
assert await manager.state.delete(key)
|
||||
return await lookup()
|
||||
|
||||
monkeypatch.setattr(tool._handles, "alist_all_by_key", delete_before_lookup)
|
||||
with _webui_request():
|
||||
result = _decode(await tool.execute(query="Database"))
|
||||
|
||||
assert [row["session_key"] for row in result["results"]] == [key]
|
||||
assert result["results"][0]["handle"] is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_session_tools_hide_private_and_non_conversation_messages(manager):
|
||||
content, marker = append_runtime_context(
|
||||
"visible question",
|
||||
[RuntimeContextBlock(source="private", content="secret runtime context")],
|
||||
@@ -257,8 +288,7 @@ async def test_read_session_reports_invalid_requests(tmp_path):
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_session_tools_read_persisted_sessions_from_any_channel(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
async def test_search_handles_support_reading_and_sending_across_channels(manager):
|
||||
_save_session(
|
||||
manager,
|
||||
"websocket:visible",
|
||||
@@ -278,6 +308,8 @@ async def test_session_tools_read_persisted_sessions_from_any_channel(tmp_path):
|
||||
messages=[{"role": "user", "content": "needle"}],
|
||||
)
|
||||
tools = SearchSessionsTool(manager), ReadSessionTool(manager)
|
||||
bus = MessageBus()
|
||||
sender = SendSessionMessageTool(sessions=manager, bus=bus)
|
||||
|
||||
with request_context(RequestContext(
|
||||
channel="telegram",
|
||||
@@ -285,22 +317,30 @@ async def test_session_tools_read_persisted_sessions_from_any_channel(tmp_path):
|
||||
session_key="telegram:external",
|
||||
)):
|
||||
search = _decode(await tools[0].execute(query="needle"))
|
||||
websocket_read = _decode(await tools[1].execute(session_key="websocket:visible"))
|
||||
slack_read = _decode(await tools[1].execute(session_key="slack:history"))
|
||||
matches = {row["session_key"]: row for row in search["results"]}
|
||||
assert set(matches) == {"websocket:visible", "slack:history"}
|
||||
websocket_handle = matches["websocket:visible"]["handle"]
|
||||
slack_handle = matches["slack:history"]["handle"]
|
||||
websocket_read = _decode(await tools[1].execute(session_key=websocket_handle))
|
||||
slack_read = _decode(await tools[1].execute(session_key=slack_handle))
|
||||
current_read = await tools[1].execute(session_key="telegram:external")
|
||||
sent = await sender.execute(
|
||||
to=slack_handle, content="Please follow up on the needle.", expect_reply=False,
|
||||
)
|
||||
|
||||
assert {row["session_key"] for row in search["results"]} == {
|
||||
"websocket:visible",
|
||||
"slack:history",
|
||||
}
|
||||
assert websocket_read["session_key"] == "websocket:visible"
|
||||
assert slack_read["session_key"] == "slack:history"
|
||||
assert websocket_read["handle"] == websocket_handle
|
||||
assert slack_read["handle"] == slack_handle
|
||||
assert [message["content"] for message in slack_read["messages"]] == ["needle"]
|
||||
assert current_read.is_error and "session not found" in str(current_read)
|
||||
assert sent == f"Sent to {slack_handle}."
|
||||
assert bus.inbound_size == 1
|
||||
inbound = await bus.consume_inbound()
|
||||
assert inbound.session_key_override == "slack:history"
|
||||
assert inbound.content == "Please follow up on the needle."
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_read_session_accepts_a_persisted_session_handle(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
async def test_read_session_accepts_a_persisted_session_handle(manager):
|
||||
_save_session(
|
||||
manager,
|
||||
"slack:history",
|
||||
@@ -321,8 +361,7 @@ async def test_read_session_accepts_a_persisted_session_handle(tmp_path):
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_session_tools_work_without_request_context(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
async def test_session_tools_work_without_request_context(manager):
|
||||
_save_session(
|
||||
manager,
|
||||
"custom:history",
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import asyncio
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
from unittest.mock import patch
|
||||
@@ -8,7 +7,6 @@ import pytest
|
||||
|
||||
from nanobot.agent.tools.context import RequestContext, request_context
|
||||
from nanobot.agent.tools.session_messages import (
|
||||
ListSessionsTool,
|
||||
SendSessionMessageTool,
|
||||
SessionMessageError,
|
||||
)
|
||||
@@ -70,28 +68,6 @@ def test_config_and_tool_schema_keep_only_the_basic_reply_contract(
|
||||
assert (timeout["minimum"], timeout["maximum"]) == (5, 60)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_sessions_includes_all_persisted_channels_except_current(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
sessions = SessionManager(tmp_path)
|
||||
_persist(sessions, "websocket:current", "telegram:other", "slack:team")
|
||||
tool = ListSessionsTool(sessions)
|
||||
expected = {
|
||||
f"@{_handle(sessions, 'telegram:other').name}",
|
||||
f"@{_handle(sessions, 'slack:team').name}",
|
||||
}
|
||||
|
||||
with request_context(RequestContext(
|
||||
channel="websocket",
|
||||
chat_id="current",
|
||||
session_key="websocket:current",
|
||||
)):
|
||||
result = json.loads(await tool.execute())
|
||||
|
||||
assert set(result) == expected
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_publishes_user_input_to_the_existing_target(
|
||||
tmp_path: Path,
|
||||
|
||||
@@ -20,7 +20,7 @@ from nanobot.agent.runner import AgentRunResult
|
||||
from nanobot.agent.subagent import SubagentControlError, SubagentManager
|
||||
from nanobot.agent.subagent_sessions import SUBAGENT, TASK_METADATA_KEY, SubagentSessions
|
||||
from nanobot.agent.tools.context import RequestContext, current_request_context, request_context
|
||||
from nanobot.agent.tools.session_messages import ListSessionsTool, SendSessionMessageTool
|
||||
from nanobot.agent.tools.session_messages import SendSessionMessageTool
|
||||
from nanobot.agent.tools.sessions import ReadSessionTool, SearchSessionsTool
|
||||
from nanobot.agent.tools.subagent import SubagentTool
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -548,7 +548,7 @@ async def test_child_preserves_transcript_provider_state_and_summary_in_common_s
|
||||
assert request.session_key == spec.session_key
|
||||
assert spec.session_key.startswith("subagent:")
|
||||
assert spec.initial_messages[-1] == {"role": "user", "content": "Inspect the config"}
|
||||
assert {"subagent", "send_session_message", "list_sessions"}.isdisjoint(
|
||||
assert {"subagent", "send_session_message"}.isdisjoint(
|
||||
definition["function"]["name"] for definition in spec.tools.get_definitions()
|
||||
)
|
||||
return AgentRunResult(
|
||||
@@ -594,8 +594,6 @@ async def test_child_is_unavailable_to_public_session_tools(tmp_path):
|
||||
with request_context(RequestContext(channel="websocket", chat_id="other", session_key="websocket:other")):
|
||||
assert json.loads(await SearchSessionsTool(sessions).execute(query="Private investigation"))["results"] == []
|
||||
assert "not found" in await ReadSessionTool(sessions).execute(session_key=child_key)
|
||||
handles = json.loads(await ListSessionsTool(sessions).execute())
|
||||
assert len(handles) == 1
|
||||
assert "Error:" in await sender.execute(to=child_key, content="bypass parent", expect_reply=False)
|
||||
with request_context(RequestContext(channel="websocket", chat_id="parent", session_key=child_key)):
|
||||
assert "Error:" in await sender.execute(to=public_handle.name, content="bypass parent", expect_reply=False)
|
||||
|
||||
Reference in new issue
Block a user