refactor(sessions): discover target handles through search (#6315)

Co-authored-by: chengyongru <chengyongru.ai@gmail.com>
This commit is contained in:
davidandchengyongru authored and GitHub committed 2026-10-29 10:38:06 +08:00
1 parent acc3750c28
commit b6d9009bb4
6 files changed
+93 -116

No files matched your search

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