refactor(channels): move tool hint rendering out of core (#6498)
* refactor(channels): move tool hint rendering out of core * test: align progress privacy check with structured tool events
This commit is contained in:
1 parent
b1cc89e922
commit
acc3750c28
30 files changed
+530
-124
No files matched your search
@@ -623,7 +623,7 @@ Besides normal assistant text, nanobot can emit low-emphasis trace blocks. These
|
||||
|
||||
### Progress and Tool Hints
|
||||
|
||||
Progress and tool hints arrive through the normal `send(msg)` path. Check `msg.event` before rendering:
|
||||
Generic progress and tool activity arrive through `send(msg)`. Tool activity carries a `ProgressEvent` with structured `tool_events`; its core `content` is empty. Each item retains its call ID, tool name, arguments, lifecycle phase, and terminal result or error. Before queuing delivery, `prepare_tool_events(msg)` projects the activity for this channel. Its default implementation formats starts as concise text in a channel-local message copy, so text-only adapters can keep their normal formatting and thread handling:
|
||||
|
||||
```python
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
@@ -644,7 +644,9 @@ async def send(self, msg: OutboundMessage) -> None:
|
||||
await self._send_message(msg.chat_id, msg.content, media=msg.media)
|
||||
```
|
||||
|
||||
Tool hints are on by default. Users can disable them globally or per channel:
|
||||
Override `prepare_tool_events(msg)` to return the original message when the platform consumes structured activity directly, or return your own display projection. Keep this hook free of network sends: it runs once before delivery and its returned envelope is reused across retries. In `send(msg)`, consume `msg.event.tool_events` for native activity, grouping, buffering, or card updates; retain destination/thread metadata and handle start/end/error by call ID. Do not assume a preformatted hint is present or route a rendered copy back into the message bus. The default text formatter uses `self.tool_hint_max_length`, initialized from `agents.defaults.toolHintMaxLength`. Direct-call `on_progress` callbacks that display tools must accept the `tool_events` keyword and render those events themselves; `nanobot.utils.tool_hints.format_tool_event_hints()` is available for text consumers.
|
||||
|
||||
Tool starts are controlled by `sendToolHints`; terminal tool events retain the existing `sendProgress` policy. Tool hints are on by default. Users can disable them globally or per channel:
|
||||
|
||||
```json
|
||||
{
|
||||
|
||||
@@ -290,7 +290,6 @@ class AgentLoop:
|
||||
context_window_tokens: int | None = None,
|
||||
max_tool_result_chars: int | None = None,
|
||||
provider_retry_mode: str = "standard",
|
||||
tool_hint_max_length: int | None = None,
|
||||
cron_service: CronService | None = None,
|
||||
restrict_to_workspace: bool = False,
|
||||
session_manager: SessionManager | None = None,
|
||||
@@ -365,10 +364,6 @@ class AgentLoop:
|
||||
else defaults.max_tool_result_chars
|
||||
)
|
||||
self.provider_retry_mode = provider_retry_mode
|
||||
self.tool_hint_max_length = (
|
||||
tool_hint_max_length if tool_hint_max_length is not None
|
||||
else defaults.tool_hint_max_length
|
||||
)
|
||||
self.tools_config = _tc
|
||||
self.network_config = network_config or NetworkConfig()
|
||||
self.web_config = _tc.web
|
||||
@@ -515,7 +510,6 @@ class AgentLoop:
|
||||
context_window_tokens=context_window_tokens,
|
||||
max_tool_result_chars=defaults.max_tool_result_chars,
|
||||
provider_retry_mode=defaults.provider_retry_mode,
|
||||
tool_hint_max_length=defaults.tool_hint_max_length,
|
||||
restrict_to_workspace=config.tools.restrict_to_workspace,
|
||||
channels_config=config.channels,
|
||||
timezone=defaults.timezone,
|
||||
@@ -1320,7 +1314,6 @@ class AgentLoop:
|
||||
attributes=dict(request_ctx.attributes),
|
||||
session_key=active_session_key,
|
||||
workspace=effective_scope.project_path,
|
||||
tool_hint_max_length=self.tool_hint_max_length,
|
||||
registered_hook_factories=self._hook_factories,
|
||||
turn_hook_factories=list(hook_factories or []),
|
||||
registered_hooks=self._extra_hooks,
|
||||
|
||||
@@ -10,13 +10,11 @@ from loguru import logger
|
||||
from nanobot.agent.hook import AgentHook, AgentHookContext
|
||||
from nanobot.bus.outbound_events import ProgressEvent, StreamDeltaEvent, StreamEndEvent
|
||||
from nanobot.events import NO_EVENTS, EventSink
|
||||
from nanobot.providers.base import ToolCallRequest
|
||||
from nanobot.utils.helpers import IncrementalThinkExtractor, strip_think
|
||||
from nanobot.utils.progress_events import (
|
||||
build_tool_event_finish_payloads,
|
||||
build_tool_event_start_payload,
|
||||
)
|
||||
from nanobot.utils.tool_hints import format_tool_hints
|
||||
|
||||
|
||||
class AgentProgressHook(AgentHook):
|
||||
@@ -28,14 +26,12 @@ class AgentProgressHook(AgentHook):
|
||||
*,
|
||||
streaming: bool = False,
|
||||
session_key: str | None = None,
|
||||
tool_hint_max_length: int = 40,
|
||||
log_content: bool = True,
|
||||
) -> None:
|
||||
super().__init__(reraise=True)
|
||||
self._publish = events.publish
|
||||
self._streaming = streaming
|
||||
self._session_key = session_key
|
||||
self._tool_hint_max_length = tool_hint_max_length
|
||||
self._log_content = log_content
|
||||
self._stream_buf = ""
|
||||
self._think_extractor = IncrementalThinkExtractor()
|
||||
@@ -50,9 +46,6 @@ class AgentProgressHook(AgentHook):
|
||||
return None
|
||||
return strip_think(text) or None
|
||||
|
||||
def _tool_hint(self, tool_calls: list[Any]) -> str:
|
||||
return format_tool_hints(tool_calls, max_length=self._tool_hint_max_length)
|
||||
|
||||
async def on_stream(self, context: AgentHookContext, delta: str) -> None:
|
||||
prev_clean = strip_think(self._stream_buf)
|
||||
self._stream_buf += delta
|
||||
@@ -118,11 +111,7 @@ class AgentProgressHook(AgentHook):
|
||||
}
|
||||
if phase == "start":
|
||||
await self.on_stream_end(context, resuming=True)
|
||||
tool_call = ToolCallRequest(id=str(call_id), name=name, arguments=arguments)
|
||||
tool_hint = self._strip_think(self._tool_hint([tool_call])) or name
|
||||
await self._publish(ProgressEvent(
|
||||
content=tool_hint, tool_hint=True, tool_events=[payload],
|
||||
))
|
||||
await self._publish(ProgressEvent(tool_hint=True, tool_events=[payload]))
|
||||
logger.info(
|
||||
"Provider-hosted tool call: {}({})",
|
||||
name,
|
||||
@@ -138,11 +127,8 @@ class AgentProgressHook(AgentHook):
|
||||
thought = self._strip_think(context.response.content if context.response else None)
|
||||
if thought:
|
||||
await self._publish(ProgressEvent(content=thought))
|
||||
tool_hint = self._strip_think(self._tool_hint(context.tool_calls))
|
||||
tool_events = [build_tool_event_start_payload(tc) for tc in context.tool_calls]
|
||||
await self._publish(ProgressEvent(
|
||||
content=tool_hint or "", tool_hint=True, tool_events=tool_events,
|
||||
))
|
||||
await self._publish(ProgressEvent(tool_hint=True, tool_events=tool_events))
|
||||
for tc in context.tool_calls:
|
||||
args_str = (
|
||||
json.dumps(tc.arguments, ensure_ascii=False)[:200]
|
||||
|
||||
@@ -30,7 +30,6 @@ class AgentTurnHookSpec:
|
||||
metadata: dict[str, Any] | None = None
|
||||
session_key: str | None = None
|
||||
workspace: Path | None = None
|
||||
tool_hint_max_length: int = 40
|
||||
registered_hook_factories: list[AgentTurnHookFactory] = field(default_factory=list)
|
||||
turn_hook_factories: list[AgentTurnHookFactory] = field(default_factory=list)
|
||||
registered_hooks: list[AgentHook] = field(default_factory=list)
|
||||
@@ -48,7 +47,6 @@ def build_agent_turn_hook(spec: AgentTurnHookSpec) -> AgentHook:
|
||||
events=spec.events,
|
||||
streaming=spec.streaming,
|
||||
session_key=spec.session_key,
|
||||
tool_hint_max_length=spec.tool_hint_max_length,
|
||||
log_content=log_content,
|
||||
)
|
||||
if spec.ephemeral and not spec.run_extra_hooks_for_ephemeral:
|
||||
|
||||
@@ -3,12 +3,14 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.pairing import (
|
||||
@@ -19,6 +21,7 @@ from nanobot.pairing import (
|
||||
record_delivery,
|
||||
)
|
||||
from nanobot.pairing.events import PairingChanged
|
||||
from nanobot.utils.tool_hints import format_tool_event_hints
|
||||
|
||||
|
||||
class BaseChannel(ABC):
|
||||
@@ -35,6 +38,7 @@ class BaseChannel(ABC):
|
||||
uses_shared_proxy: bool = False
|
||||
send_progress: bool = True
|
||||
send_tool_hints: bool = True
|
||||
tool_hint_max_length: int = 40
|
||||
show_reasoning: bool = True
|
||||
show_compaction_notices: bool = False
|
||||
|
||||
@@ -115,6 +119,19 @@ class BaseChannel(ABC):
|
||||
"""
|
||||
pass
|
||||
|
||||
def prepare_tool_events(self, msg: OutboundMessage) -> OutboundMessage:
|
||||
"""Project tool activity once before delivery; override for native UI.
|
||||
|
||||
Keep the core event unchanged and reuse the returned envelope throughout
|
||||
retries, including adapters that track already-sent multipart messages.
|
||||
"""
|
||||
event = msg.event
|
||||
if isinstance(event, ProgressEvent) and event.tool_hint and event.tool_events:
|
||||
return replace(msg, content=format_tool_event_hints(
|
||||
event.tool_events, max_length=self.tool_hint_max_length,
|
||||
))
|
||||
return msg
|
||||
|
||||
@property
|
||||
def has_pending_delivery(self) -> bool:
|
||||
"""Whether delivery outlives an awaited ``send``/streaming call.
|
||||
|
||||
@@ -7,7 +7,7 @@ import pytest
|
||||
|
||||
from nanobot.bus.delivery import DeliveryRejectedError
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.outbound_events import ProgressEvent, outbound_message_for_event
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.channels.email.runtime import EmailChannel, EmailConfig
|
||||
@@ -814,7 +814,14 @@ async def test_send_uses_smtp_and_reply_subject(monkeypatch) -> None:
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_skips_progress_messages_before_smtp(monkeypatch) -> None:
|
||||
@pytest.mark.parametrize("event", [
|
||||
ProgressEvent(tool_hint=True, tool_events=[{
|
||||
"phase": "start", "call_id": "call-1", "name": "exec",
|
||||
"arguments": {"command": "git status"},
|
||||
}]),
|
||||
ProgressEvent(tool_events=[{"phase": "end", "call_id": "call-1", "name": "exec"}]),
|
||||
], ids=["tool-start", "tool-end"])
|
||||
async def test_send_skips_progress_messages_before_smtp(monkeypatch, event) -> None:
|
||||
called = {"smtp": False}
|
||||
|
||||
def _smtp_factory(*_args, **_kwargs):
|
||||
@@ -825,14 +832,12 @@ async def test_send_skips_progress_messages_before_smtp(monkeypatch) -> None:
|
||||
|
||||
channel = EmailChannel(_make_config(), MessageBus())
|
||||
|
||||
await channel.send(
|
||||
OutboundMessage(
|
||||
channel="email",
|
||||
chat_id="alice@example.com",
|
||||
content="",
|
||||
event=ProgressEvent(tool_events=[{"phase": "end", "name": "exec"}]),
|
||||
)
|
||||
msg = outbound_message_for_event(
|
||||
channel="email",
|
||||
chat_id="alice@example.com",
|
||||
event=event,
|
||||
)
|
||||
await ChannelManager._send_once(channel, channel.prepare_tool_events(msg))
|
||||
|
||||
assert called["smtp"] is False
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# ruff: noqa: E402
|
||||
|
||||
"""Tests for Feishu streaming (send_delta) via CardKit streaming API."""
|
||||
import json
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
@@ -10,9 +11,10 @@ import pytest
|
||||
pytest.importorskip("lark_oapi")
|
||||
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.outbound_events import ProgressEvent, outbound_message_for_event
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.feishu.runtime import FeishuChannel, FeishuConfig, _FeishuStreamBuf
|
||||
from nanobot.channels.manager import ChannelManager
|
||||
|
||||
|
||||
def _make_channel(streaming: bool = True, reply_to_message: bool = False) -> FeishuChannel:
|
||||
@@ -536,26 +538,35 @@ class TestToolHintInlineStreaming:
|
||||
@pytest.mark.asyncio
|
||||
async def test_tool_hint_keeps_existing_topic_when_reply_disabled(self):
|
||||
ch = _make_channel(reply_to_message=False)
|
||||
ch.tool_hint_max_length = 20
|
||||
reply_resp = MagicMock()
|
||||
reply_resp.success.return_value = True
|
||||
ch._client.im.v1.message.reply.return_value = reply_resp
|
||||
|
||||
msg = OutboundMessage(
|
||||
msg = outbound_message_for_event(
|
||||
channel="feishu", chat_id="oc_chat1",
|
||||
content='read_file("path")',
|
||||
event=ProgressEvent(content='read_file("path")', tool_hint=True),
|
||||
event=ProgressEvent(tool_hint=True, tool_events=[{
|
||||
"phase": "start", "call_id": "call-1", "name": "web_search",
|
||||
"arguments": {"query": "abcdefghijklmnopqrstuvwxyz"},
|
||||
}]),
|
||||
metadata={
|
||||
"message_id": "om_001",
|
||||
"chat_type": "group",
|
||||
"thread_id": "ot_001",
|
||||
},
|
||||
)
|
||||
await ch.send(msg)
|
||||
await ChannelManager._send_once(ch, ch.prepare_tool_events(msg))
|
||||
|
||||
ch._client.im.v1.message.reply.assert_called_once()
|
||||
ch._client.im.v1.message.create.assert_not_called()
|
||||
request = ch._client.im.v1.message.reply.call_args[0][0]
|
||||
assert request.message_id == "om_001"
|
||||
assert request.request_body.reply_in_thread is not True
|
||||
assert request.request_body.msg_type == "interactive"
|
||||
card = json.loads(request.request_body.content)
|
||||
assert card["elements"][0]["content"] == '🔧 search "abcdefghijklmnopqrs…"'
|
||||
assert msg.content == ""
|
||||
assert msg.event.content == ""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tool_hint_group_replies_when_reply_enabled(self):
|
||||
|
||||
@@ -197,6 +197,9 @@ class LinearChannel(BaseChannel):
|
||||
key="response",
|
||||
)
|
||||
|
||||
def prepare_tool_events(self, msg: OutboundMessage) -> OutboundMessage:
|
||||
return msg
|
||||
|
||||
async def _attachment_markdown(self, msg: OutboundMessage) -> list[str]:
|
||||
client = self._client
|
||||
if client is None:
|
||||
|
||||
@@ -36,6 +36,7 @@ from nanobot.channels.linear.oauth import OAUTH_FLOWS, authorization_url
|
||||
from nanobot.channels.linear.runtime import LinearChannel
|
||||
from nanobot.channels.linear.server import LinearServerLease, acquire_http_server
|
||||
from nanobot.channels.linear.state import LinearInstallation, LinearStateStore
|
||||
from nanobot.channels.manager import ChannelManager
|
||||
|
||||
|
||||
def _config(port: int = 3979) -> LinearConfig:
|
||||
@@ -1148,7 +1149,7 @@ async def test_outbound_response_and_tool_progress_use_native_activity_shapes(
|
||||
}]
|
||||
),
|
||||
)
|
||||
await channel.send(tool)
|
||||
await ChannelManager._send_once(channel, channel.prepare_tool_events(tool))
|
||||
|
||||
assert client.activities[0]["content"] == {"type": "response", "body": "Done"}
|
||||
assert client.activities[1]["activity_id"] == activity_id
|
||||
@@ -1220,19 +1221,22 @@ async def test_tool_activities_redact_credentials_and_make_start_ephemeral(
|
||||
metadata = {
|
||||
"linear": {"organization_id": "org-1", "agent_session_id": "session-1"}
|
||||
}
|
||||
await channel.send(OutboundMessage(
|
||||
send = AsyncMock(wraps=channel.send)
|
||||
channel.send = send
|
||||
msg = OutboundMessage(
|
||||
channel="linear",
|
||||
chat_id="session-1",
|
||||
content="",
|
||||
metadata=metadata,
|
||||
event=ProgressEvent(tool_events=[{
|
||||
event=ProgressEvent(tool_hint=True, tool_events=[{
|
||||
"phase": "start",
|
||||
"call_id": "call-secret",
|
||||
"name": "call_api",
|
||||
"arguments": {"api_key": "secret-value", "query": "safe"},
|
||||
}]),
|
||||
))
|
||||
await channel.send(OutboundMessage(
|
||||
)
|
||||
await ChannelManager._send_once(channel, channel.prepare_tool_events(msg))
|
||||
msg = OutboundMessage(
|
||||
channel="linear",
|
||||
chat_id="session-1",
|
||||
content="",
|
||||
@@ -1243,8 +1247,9 @@ async def test_tool_activities_redact_credentials_and_make_start_ephemeral(
|
||||
"name": "call_api",
|
||||
"error": "Authorization: Bearer plaintext-secret",
|
||||
}]),
|
||||
))
|
||||
await channel.send(OutboundMessage(
|
||||
)
|
||||
await ChannelManager._send_once(channel, channel.prepare_tool_events(msg))
|
||||
msg = OutboundMessage(
|
||||
channel="linear",
|
||||
chat_id="session-1",
|
||||
content="",
|
||||
@@ -1256,8 +1261,11 @@ async def test_tool_activities_redact_credentials_and_make_start_ephemeral(
|
||||
"arguments": {"api_key": "secret-value"},
|
||||
"result": {"token": "result-secret", "status": "ok"},
|
||||
}]),
|
||||
))
|
||||
)
|
||||
await ChannelManager._send_once(channel, channel.prepare_tool_events(msg))
|
||||
|
||||
assert send.await_count == 3
|
||||
assert all(call.args[0].content == "" for call in send.await_args_list)
|
||||
assert client.activities[0]["ephemeral"] is True
|
||||
assert client.activities[0]["content"]["action"] == "Call API"
|
||||
assert "secret-value" not in client.activities[0]["content"]["parameter"]
|
||||
|
||||
@@ -241,6 +241,7 @@ class ChannelManager:
|
||||
)
|
||||
kwargs["gateway"] = gateway
|
||||
channel = cls(section, self.bus, **kwargs)
|
||||
channel.tool_hint_max_length = self.config.agents.defaults.tool_hint_max_length
|
||||
if runtime_name and runtime_name != channel.name:
|
||||
channel.name = runtime_name
|
||||
progress_default, tool_hints_default = channel.progress_transport_defaults() or (
|
||||
@@ -801,6 +802,8 @@ class ChannelManager:
|
||||
"""
|
||||
if msg.delivery_id in self._scheduled_deliveries:
|
||||
return
|
||||
if isinstance(msg.event, ProgressEvent) and msg.event.tool_events:
|
||||
msg = channel.prepare_tool_events(msg)
|
||||
await self._outbound_slots.acquire()
|
||||
if msg.channel in self._stopping_channels or self.channels.get(msg.channel) is not channel:
|
||||
self._outbound_slots.release()
|
||||
|
||||
@@ -15,7 +15,9 @@ except ImportError:
|
||||
pytest.skip("Slack dependencies not installed (slack-sdk)", allow_module_level=True)
|
||||
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent, outbound_message_for_event
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.manager import ChannelManager
|
||||
from nanobot.channels.slack.runtime import SLACK_MAX_MESSAGE_LEN, SlackChannel, SlackConfig
|
||||
from nanobot.config.network import NetworkConfig
|
||||
|
||||
@@ -141,6 +143,33 @@ async def test_send_uses_thread_for_channel_messages() -> None:
|
||||
assert fake_web.file_upload_calls[0]["thread_ts"] == "1700000000.000100"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_structured_tool_start_sends_text_in_thread() -> None:
|
||||
channel = SlackChannel(SlackConfig(enabled=True), MessageBus())
|
||||
fake_web = _FakeAsyncWebClient()
|
||||
channel._web_client = fake_web
|
||||
channel.tool_hint_max_length = 20
|
||||
msg = outbound_message_for_event(
|
||||
channel="slack",
|
||||
chat_id="C123",
|
||||
event=ProgressEvent(tool_hint=True, tool_events=[{
|
||||
"phase": "start", "call_id": "call-1", "name": "web_search",
|
||||
"arguments": {"query": "abcdefghijklmnopqrstuvwxyz"},
|
||||
}]),
|
||||
metadata={"slack": {"thread_ts": "1700000000.000100", "channel_type": "channel"}},
|
||||
)
|
||||
|
||||
await ChannelManager._send_once(channel, channel.prepare_tool_events(msg))
|
||||
|
||||
assert fake_web.chat_post_calls == [{
|
||||
"channel": "C123",
|
||||
"text": 'search "abcdefghijklmnopqrs…"',
|
||||
"thread_ts": "1700000000.000100",
|
||||
}]
|
||||
assert msg.content == ""
|
||||
assert msg.event.content == ""
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_omits_thread_for_dm_root_messages() -> None:
|
||||
"""DM root replies should not be threaded; metadata carries thread_ts=None."""
|
||||
|
||||
@@ -14,8 +14,9 @@ except ImportError:
|
||||
|
||||
from nanobot.bus.delivery import ChannelNotReadyError
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.outbound_events import ProgressEvent, outbound_message_for_event
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.manager import ChannelManager
|
||||
from nanobot.channels.telegram.runtime import (
|
||||
TELEGRAM_MAX_MESSAGE_LEN,
|
||||
TELEGRAM_REPLY_CONTEXT_MAX_LEN,
|
||||
@@ -1909,6 +1910,37 @@ async def test_send_progress_keeps_message_in_topic() -> None:
|
||||
assert channel._app.bot.sent_messages[0]["message_thread_id"] == 42
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_structured_tool_start_sends_quote_in_topic() -> None:
|
||||
config = TelegramConfig(
|
||||
enabled=True, token="123:abc", allow_from=["*"], reply_to_message=True,
|
||||
)
|
||||
channel = TelegramChannel(config, MessageBus())
|
||||
app = _install_ready_app(channel)
|
||||
channel.tool_hint_max_length = 20
|
||||
msg = outbound_message_for_event(
|
||||
channel="telegram",
|
||||
chat_id="123",
|
||||
event=ProgressEvent(tool_hint=True, tool_events=[{
|
||||
"phase": "start", "call_id": "call-1", "name": "web_search",
|
||||
"arguments": {"query": "abcdefghijklmnopqrstuvwxyz"},
|
||||
}]),
|
||||
metadata={"message_id": 10, "message_thread_id": 42},
|
||||
)
|
||||
|
||||
await ChannelManager._send_once(channel, channel.prepare_tool_events(msg))
|
||||
|
||||
assert len(app.bot.sent_messages) == 1
|
||||
sent = app.bot.sent_messages[0]
|
||||
assert sent["chat_id"] == 123
|
||||
assert sent["text"] == '<blockquote expandable>search "abcdefghijklmnopqrs…"</blockquote>'
|
||||
assert sent["parse_mode"] == "HTML"
|
||||
assert sent["message_thread_id"] == 42
|
||||
assert sent["reply_parameters"].message_id == 10
|
||||
assert msg.content == ""
|
||||
assert msg.event.content == ""
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_reply_infers_topic_from_message_id_cache() -> None:
|
||||
config = TelegramConfig(enabled=True, token="123:abc", allow_from=["*"], reply_to_message=True)
|
||||
|
||||
@@ -1130,6 +1130,9 @@ class WebSocketChannel(BaseChannel):
|
||||
async def send(self, msg: OutboundMessage) -> None:
|
||||
await self._outbound.send(msg)
|
||||
|
||||
def prepare_tool_events(self, msg: OutboundMessage) -> OutboundMessage:
|
||||
return msg
|
||||
|
||||
async def send_reasoning_delta(
|
||||
self,
|
||||
chat_id: str,
|
||||
|
||||
@@ -40,6 +40,7 @@ from nanobot.bus.outbound_events import (
|
||||
UserInputEvent,
|
||||
)
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.manager import ChannelManager
|
||||
from nanobot.channels.websocket import runtime as websocket_runtime
|
||||
from nanobot.channels.websocket.runtime import (
|
||||
WebSocketChannel,
|
||||
@@ -2623,18 +2624,17 @@ async def test_send_removes_connection_on_connection_closed() -> None:
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_progress_includes_structured_tool_events() -> None:
|
||||
async def test_send_progress_includes_structured_tool_events(history) -> None:
|
||||
bus = MagicMock()
|
||||
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
||||
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus, session_manager=history.sessions))
|
||||
mock_ws = AsyncMock()
|
||||
channel._attach(mock_ws, "chat-1")
|
||||
|
||||
await channel.send(OutboundMessage(
|
||||
msg = await history.message(
|
||||
channel="websocket",
|
||||
chat_id="chat-1",
|
||||
content='search "hermes"',
|
||||
content="",
|
||||
event=ProgressEvent(
|
||||
content='search "hermes"',
|
||||
tool_hint=True,
|
||||
tool_events=[
|
||||
{
|
||||
@@ -2653,11 +2653,13 @@ async def test_send_progress_includes_structured_tool_events() -> None:
|
||||
metadata={
|
||||
"webui_turn_id": "turn-1",
|
||||
},
|
||||
))
|
||||
)
|
||||
await ChannelManager._send_once(channel, channel.prepare_tool_events(msg))
|
||||
|
||||
payload = json.loads(mock_ws.send.await_args.args[0])
|
||||
assert payload["event"] == "message"
|
||||
assert payload["kind"] == "tool_hint"
|
||||
assert payload["text"] == ""
|
||||
assert payload["turn_id"] == "turn-1"
|
||||
assert payload["turn_phase"] == "activity"
|
||||
assert payload["turn_seq"] == 1
|
||||
@@ -2674,6 +2676,15 @@ async def test_send_progress_includes_structured_tool_events() -> None:
|
||||
"embeds": [],
|
||||
}
|
||||
]
|
||||
[persisted] = history.read("websocket:chat-1")
|
||||
assert persisted["text"] == ""
|
||||
assert persisted["tool_events"] == payload["tool_events"]
|
||||
replay = history.build("websocket:chat-1")
|
||||
assert replay is not None
|
||||
[replayed] = replay["events"]
|
||||
assert replayed["kind"] == "tool_hint"
|
||||
assert replayed["text"] == ""
|
||||
assert replayed["tool_events"] == payload["tool_events"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -2704,14 +2715,17 @@ async def test_send_progress_omits_binary_tool_results_from_wire_and_transcript(
|
||||
}
|
||||
]
|
||||
|
||||
await channel.send(await history.message(
|
||||
msg = await history.message(
|
||||
channel="websocket",
|
||||
chat_id="chat-binary-tool-result",
|
||||
content="read_file completed",
|
||||
event=ProgressEvent(content="read_file completed", tool_events=tool_events),
|
||||
))
|
||||
content="",
|
||||
event=ProgressEvent(tool_events=tool_events),
|
||||
)
|
||||
await ChannelManager._send_once(channel, channel.prepare_tool_events(msg))
|
||||
|
||||
payload = json.loads(mock_ws.send.await_args.args[0])
|
||||
assert payload["kind"] == "progress"
|
||||
assert payload["text"] == ""
|
||||
[wire_event] = payload["tool_events"]
|
||||
assert wire_event["result"][0]["image_url"]["url"] == (
|
||||
"[binary content omitted from WebUI]"
|
||||
@@ -2719,8 +2733,14 @@ async def test_send_progress_omits_binary_tool_results_from_wire_and_transcript(
|
||||
assert len(mock_ws.send.await_args.args[0].encode("utf-8")) < 4096
|
||||
|
||||
[persisted] = history.read("websocket:chat-binary-tool-result")
|
||||
assert persisted["text"] == ""
|
||||
assert persisted["tool_events"] == payload["tool_events"]
|
||||
assert data_url not in json.dumps(persisted)
|
||||
replay = history.build("websocket:chat-binary-tool-result")
|
||||
assert replay is not None
|
||||
[replayed] = replay["events"]
|
||||
assert replayed["text"] == ""
|
||||
assert replayed["tool_events"] == payload["tool_events"]
|
||||
|
||||
# WebUI projection must not alter the result that the runner sends back to the model.
|
||||
assert tool_events[0]["result"][0]["image_url"]["url"] == data_url
|
||||
|
||||
@@ -16,6 +16,7 @@ import websockets
|
||||
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.channels.manager import ChannelManager
|
||||
from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
|
||||
@@ -220,14 +221,32 @@ async def test_server_send_tags_tool_hint_with_kind(bus: MagicMock) -> None:
|
||||
assert plain.raw.get("kind") is None
|
||||
|
||||
# Tool-hint breadcrumb: kind == "tool_hint".
|
||||
await ch.send(OutboundMessage(
|
||||
tool_start = {
|
||||
"phase": "start", "call_id": "call-weather", "name": "weather",
|
||||
"arguments": {"action": "get"},
|
||||
}
|
||||
msg = OutboundMessage(
|
||||
channel="websocket", chat_id=ready.chat_id,
|
||||
content='weather("get")',
|
||||
event=ProgressEvent(content='weather("get")', tool_hint=True),
|
||||
))
|
||||
content="",
|
||||
event=ProgressEvent(tool_hint=True, tool_events=[tool_start]),
|
||||
)
|
||||
await ChannelManager._send_once(ch, ch.prepare_tool_events(msg))
|
||||
hint = await c.recv_message()
|
||||
assert hint.raw.get("kind") == "tool_hint"
|
||||
assert hint.text == 'weather("get")'
|
||||
assert hint.text == ""
|
||||
assert hint.raw["tool_events"] == [tool_start]
|
||||
|
||||
tool_end = {**tool_start, "phase": "end", "result": "sunny"}
|
||||
msg = OutboundMessage(
|
||||
channel="websocket", chat_id=ready.chat_id,
|
||||
content="",
|
||||
event=ProgressEvent(tool_events=[tool_end]),
|
||||
)
|
||||
await ChannelManager._send_once(ch, ch.prepare_tool_events(msg))
|
||||
result = await c.recv_message()
|
||||
assert result.raw.get("kind") == "progress"
|
||||
assert result.text == ""
|
||||
assert result.raw["tool_events"] == [tool_end]
|
||||
|
||||
# Generic progress (non-tool-hint) gets the softer "progress" label.
|
||||
await ch.send(OutboundMessage(
|
||||
|
||||
@@ -1865,6 +1865,11 @@ class WeixinChannel(BaseChannel):
|
||||
self._raise_for_api_error("sendmessage", data)
|
||||
self._record_context_send(context_token)
|
||||
|
||||
def prepare_tool_events(self, msg: OutboundMessage) -> OutboundMessage:
|
||||
if self.config.reply_progress_messages:
|
||||
return msg
|
||||
return super().prepare_tool_events(msg)
|
||||
|
||||
async def send(self, msg: OutboundMessage) -> None:
|
||||
event = getattr(msg, "event", None)
|
||||
if isinstance(event, ContextCompactionEvent) and not (
|
||||
|
||||
@@ -10,8 +10,10 @@ import httpx
|
||||
import pytest
|
||||
|
||||
from nanobot.bus.delivery import ChannelNotReadyError
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.manager import ChannelManager
|
||||
from nanobot.channels.weixin import runtime as weixin_mod
|
||||
from nanobot.channels.weixin.runtime import (
|
||||
ITEM_IMAGE,
|
||||
@@ -1857,19 +1859,20 @@ async def test_buffer_multiple_tool_hints_flushed_on_final_answer() -> None:
|
||||
channel._send_text = AsyncMock()
|
||||
|
||||
for hint in ["tool1", "tool2"]:
|
||||
await channel.send(
|
||||
type(
|
||||
"Msg",
|
||||
(),
|
||||
{
|
||||
"chat_id": "wx-user",
|
||||
"content": hint,
|
||||
"media": [],
|
||||
"event": ProgressEvent(content=hint, tool_hint=True),
|
||||
"metadata": {},
|
||||
},
|
||||
)()
|
||||
msg = OutboundMessage(
|
||||
channel="weixin",
|
||||
chat_id="wx-user",
|
||||
content="",
|
||||
event=ProgressEvent(tool_hint=True, tool_events=[{
|
||||
"phase": "start", "call_id": f"call-{hint}", "name": hint, "arguments": {},
|
||||
}]),
|
||||
)
|
||||
await ChannelManager._send_once(channel, channel.prepare_tool_events(msg))
|
||||
assert msg.content == ""
|
||||
assert msg.event.content == ""
|
||||
|
||||
channel._send_text.assert_not_awaited()
|
||||
assert channel._pending_tool_hints["wx-user"] == ["tool1", "tool2"]
|
||||
|
||||
await channel.send(
|
||||
type(
|
||||
@@ -2050,19 +2053,16 @@ async def test_empty_progress_message_does_not_flush_tool_hints() -> None:
|
||||
)
|
||||
|
||||
# Send an empty progress message (no content, no media)
|
||||
await channel.send(
|
||||
type(
|
||||
"Msg",
|
||||
(),
|
||||
{
|
||||
"chat_id": "wx-user",
|
||||
"content": "",
|
||||
"media": [],
|
||||
"event": ProgressEvent(tool_events=[{"phase": "end"}]),
|
||||
"metadata": {},
|
||||
},
|
||||
)()
|
||||
msg = OutboundMessage(
|
||||
channel="weixin",
|
||||
chat_id="wx-user",
|
||||
content="",
|
||||
event=ProgressEvent(tool_events=[{
|
||||
"phase": "end", "call_id": "call-search", "name": "web_search",
|
||||
"arguments": {"query": "foo"}, "result": "found",
|
||||
}]),
|
||||
)
|
||||
await ChannelManager._send_once(channel, channel.prepare_tool_events(msg))
|
||||
|
||||
# Nothing should have been sent yet
|
||||
channel._send_text.assert_not_awaited()
|
||||
|
||||
@@ -443,18 +443,30 @@ async def test_structured_progress_is_capped_and_uses_one_run_id() -> None:
|
||||
{"phase": "start", "call_id": "call-2", "name": "exec"},
|
||||
]
|
||||
|
||||
await channel.send(
|
||||
OutboundMessage(
|
||||
channel="weixin",
|
||||
chat_id="wx-user",
|
||||
content="read_file",
|
||||
event=ProgressEvent(content="read_file", tool_hint=True, tool_events=events),
|
||||
)
|
||||
send = AsyncMock(wraps=channel.send)
|
||||
channel.send = send
|
||||
msg = OutboundMessage(
|
||||
channel="weixin",
|
||||
chat_id="wx-user",
|
||||
content="",
|
||||
event=ProgressEvent(tool_hint=True, tool_events=events),
|
||||
)
|
||||
await ChannelManager._send_once(channel, channel.prepare_tool_events(msg))
|
||||
|
||||
send.assert_awaited_once_with(msg)
|
||||
assert send.await_args.args[0] is msg
|
||||
assert msg.content == ""
|
||||
assert channel._send_message_item.await_count == 2
|
||||
first = channel._send_message_item.await_args_list[0]
|
||||
second = channel._send_message_item.await_args_list[1]
|
||||
assert first.args[1]["type"] == ITEM_TOOL_CALL_START
|
||||
assert second.args[1]["type"] == ITEM_TOOL_CALL_RESULT
|
||||
assert first.args[1]["tool_call_start_item"] == {
|
||||
"tool_name": "read_file", "tool_call_id": "call-1",
|
||||
}
|
||||
assert second.args[1]["tool_call_result_item"] == {
|
||||
"tool_name": "read_file", "tool_call_id": "call-1", "status": "completed",
|
||||
}
|
||||
assert first.args[2] == second.args[2] == "ctx-1"
|
||||
assert first.kwargs["run_id"] == second.kwargs["run_id"]
|
||||
assert first.kwargs["reserve_budget"] == second.kwargs["reserve_budget"] == 1
|
||||
@@ -21,11 +21,12 @@ from loguru import logger
|
||||
|
||||
from nanobot.bus.delivery import ChannelNotReadyError, DeliveryRequest
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.outbound_events import ProgressEvent, outbound_message_for_event
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.manager import ChannelManager
|
||||
from nanobot.channels.whatsapp_agent import runtime as runtime_module
|
||||
from nanobot.channels.whatsapp_agent.protocol import (
|
||||
TEXT_MAX_CHARS,
|
||||
APIError,
|
||||
WhatsAppAgentAPIError,
|
||||
WhatsAppAgentAuthError,
|
||||
@@ -35,6 +36,7 @@ from nanobot.channels.whatsapp_agent.runtime import (
|
||||
WhatsAppAgentChannel,
|
||||
WhatsAppAgentConfig,
|
||||
)
|
||||
from nanobot.utils.helpers import split_message
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
@@ -671,6 +673,69 @@ def test_manager_retry_resumes_after_acknowledged_parts(
|
||||
assert not channel._pending_sends
|
||||
|
||||
|
||||
async def test_manager_structured_tool_hint_retry_preserves_multipart_progress(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
|
||||
):
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
from nanobot.config.schema import Config
|
||||
|
||||
config = Config.model_validate({
|
||||
"agents": {"defaults": {"toolHintMaxLength": 500}},
|
||||
"channels": {
|
||||
"websocket": {"enabled": False},
|
||||
"whatsapp_agent": {
|
||||
"enabled": True, "token": "test-token", "sendToolHints": True,
|
||||
"stateDir": str(tmp_path),
|
||||
},
|
||||
},
|
||||
})
|
||||
manager = ChannelManager(config, MessageBus(), config_path=tmp_path / "config.json")
|
||||
channel = manager.channels["whatsapp_agent"]
|
||||
channel._state.note_creator("user:55")
|
||||
queries = [f"{index:02d}" + "x" * 498 for index in range(10)]
|
||||
msg = outbound_message_for_event(
|
||||
channel=channel.name,
|
||||
chat_id=CREATOR_CHAT_ID,
|
||||
event=ProgressEvent(tool_hint=True, tool_events=[{
|
||||
"phase": "start", "call_id": f"call-{index}", "name": "web_search",
|
||||
"arguments": {"query": query},
|
||||
} for index, query in enumerate(queries)]),
|
||||
)
|
||||
expected_hint = ", ".join(f'search "{query}"' for query in queries)
|
||||
chunks = split_message(expected_hint, TEXT_MAX_CHARS)
|
||||
assert len(chunks) == 2
|
||||
attempted: list[str] = []
|
||||
delivered: list[str] = []
|
||||
|
||||
def accept(request: httpx.Request) -> httpx.Response:
|
||||
body = json.loads(request.content)["text"]["body"]
|
||||
attempted.append(body)
|
||||
if len(attempted) == 2:
|
||||
raise httpx.ConnectError("not submitted", request=request)
|
||||
delivered.append(body)
|
||||
return httpx.Response(200, json={"messages": [{"id": str(len(attempted))}]})
|
||||
|
||||
send = AsyncMock(wraps=channel.send)
|
||||
monkeypatch.setattr(channel, "send", send)
|
||||
monkeypatch.setattr("nanobot.channels.manager._SEND_RETRY_DELAYS", (0,))
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(accept)) as client:
|
||||
channel._client = client
|
||||
await manager._queue_outbound(channel, msg)
|
||||
await asyncio.gather(*manager._outbound_tasks)
|
||||
|
||||
assert delivered == chunks
|
||||
assert attempted == [chunks[0], chunks[1], chunks[1]]
|
||||
assert send.await_count == 2
|
||||
first, retry = [call.args[0] for call in send.await_args_list]
|
||||
assert first is retry
|
||||
assert first is not msg
|
||||
assert first.content == expected_hint
|
||||
assert first.event is msg.event
|
||||
assert msg.content == msg.event.content == ""
|
||||
assert not channel._pending_sends
|
||||
|
||||
|
||||
@pytest.mark.parametrize("retry_ambiguous", [False, True])
|
||||
def test_media_failure_never_replays_accepted_text_or_attachments(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, retry_ambiguous: bool,
|
||||
|
||||
@@ -151,6 +151,7 @@ def _run_classic(runtime_config: Config, *, message: str | None, session_id: str
|
||||
format_restart_completed_message,
|
||||
should_show_cli_restart_notice,
|
||||
)
|
||||
from nanobot.utils.tool_hints import format_tool_event_hints
|
||||
|
||||
agent_loop_class = _classic_dependency("AgentLoop")
|
||||
stream_renderer_class = _classic_dependency("StreamRenderer")
|
||||
@@ -220,6 +221,7 @@ def _run_classic(runtime_config: Config, *, message: str | None, session_id: str
|
||||
content: str,
|
||||
*,
|
||||
tool_hint: bool = False,
|
||||
tool_events: list[dict[str, Any]] | None = None,
|
||||
reasoning: bool = False,
|
||||
**_kwargs: Any,
|
||||
) -> None:
|
||||
@@ -244,6 +246,10 @@ def _run_classic(runtime_config: Config, *, message: str | None, session_id: str
|
||||
return
|
||||
if ch and not tool_hint and not ch.send_progress:
|
||||
return
|
||||
if tool_hint and tool_events:
|
||||
content = format_tool_event_hints(
|
||||
tool_events, max_length=runtime_config.agents.defaults.tool_hint_max_length,
|
||||
)
|
||||
cli_terminal._print_cli_progress_line(content, _thinking, renderer)
|
||||
|
||||
return _cli_progress
|
||||
@@ -359,6 +365,7 @@ def _run_classic(runtime_config: Config, *, message: str | None, session_id: str
|
||||
agent_loop.channels_config,
|
||||
renderer,
|
||||
reasoning_buffer,
|
||||
tool_hint_max_length=runtime_config.agents.defaults.tool_hint_max_length,
|
||||
):
|
||||
continue
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ from nanobot.bus.outbound_events import (
|
||||
)
|
||||
from nanobot.cli.stream import StreamRenderer, ThinkingSpinner
|
||||
from nanobot.utils.helpers import sanitize_surrogates as _sanitize_surrogates
|
||||
from nanobot.utils.tool_hints import format_tool_event_hints
|
||||
|
||||
__all__ = [
|
||||
"_ReasoningBuffer",
|
||||
@@ -367,6 +368,8 @@ async def _maybe_print_interactive_progress(
|
||||
channels_config: Any,
|
||||
renderer: StreamRenderer | None = None,
|
||||
reasoning_buffer: _ReasoningBuffer | None = None,
|
||||
*,
|
||||
tool_hint_max_length: int = 40,
|
||||
) -> bool:
|
||||
event = msg.event
|
||||
if isinstance(event, ContextCompactionEvent):
|
||||
@@ -403,7 +406,10 @@ async def _maybe_print_interactive_progress(
|
||||
if channels_config and not is_tool_hint and not channels_config.send_progress:
|
||||
return True
|
||||
|
||||
await _print_interactive_progress_line(msg.content, thinking, renderer)
|
||||
content = msg.content
|
||||
if is_tool_hint and event.tool_events:
|
||||
content = format_tool_event_hints(event.tool_events, max_length=tool_hint_max_length)
|
||||
await _print_interactive_progress_line(content, thinking, renderer)
|
||||
return True
|
||||
|
||||
|
||||
|
||||
@@ -4,9 +4,10 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from typing import cast
|
||||
from typing import Any, cast
|
||||
|
||||
from nanobot.providers.base import ToolCallRequest
|
||||
from nanobot.utils.helpers import strip_think
|
||||
from nanobot.utils.path import abbreviate_path
|
||||
|
||||
# Registry: tool_name -> (key_args, template, is_path, is_command)
|
||||
@@ -36,6 +37,19 @@ _PATH_IN_CMD_RE = re.compile(
|
||||
ToolFormat = tuple[list[str], str, bool, bool]
|
||||
|
||||
|
||||
def format_tool_event_hints(events: list[dict[str, Any]], max_length: int = 40) -> str:
|
||||
"""Render structured tool starts for channels that choose plain-text hints."""
|
||||
calls = [
|
||||
ToolCallRequest(
|
||||
id=str(event.get("call_id") or ""),
|
||||
name=event.get("name", ""),
|
||||
arguments=event.get("arguments") or {},
|
||||
)
|
||||
for event in events if event.get("phase") == "start"
|
||||
]
|
||||
return strip_think(format_tool_hints(calls, max_length=max_length))
|
||||
|
||||
|
||||
def format_tool_hints(tool_calls: list[ToolCallRequest], max_length: int = 40) -> str:
|
||||
"""Format tool calls as concise hints with smart abbreviation."""
|
||||
if not tool_calls:
|
||||
|
||||
@@ -109,7 +109,7 @@ async def test_runner_routes_hosted_tool_events_to_structured_progress():
|
||||
"embeds": [],
|
||||
},
|
||||
]
|
||||
assert progress_text == ['search X "nanobot oauth"', ""]
|
||||
assert progress_text == ["", ""]
|
||||
assert timeline == [
|
||||
"delta:Before search.", "end:True", "tool:start", "tool:end", "delta:done", "end:False",
|
||||
]
|
||||
|
||||
@@ -53,7 +53,7 @@ async def test_start_and_finish_events_emitted() -> None:
|
||||
assert progress == [
|
||||
("Visible", False, None),
|
||||
(
|
||||
'custom_tool("foo.txt")',
|
||||
"",
|
||||
True,
|
||||
[{
|
||||
"version": 1,
|
||||
@@ -139,5 +139,51 @@ async def test_streamed_content_is_not_repeated_before_tool_execution() -> None:
|
||||
|
||||
assert result.final_content == "Done"
|
||||
assert streamed == ["I will", " inspect it."]
|
||||
assert progress[0][0] == 'custom_tool("foo.txt")'
|
||||
assert progress[0] == ("", True, [{
|
||||
"version": 1, "phase": "start", "call_id": "call1", "name": "custom_tool",
|
||||
"arguments": {"path": "foo.txt"}, "result": None, "error": None,
|
||||
"files": [], "embeds": [],
|
||||
}])
|
||||
assert all(item[0] != "I will inspect it." for item in progress)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_batched_file_reads_keep_each_call_and_complete_arguments() -> None:
|
||||
provider = MagicMock()
|
||||
calls = [
|
||||
ToolCallRequest(
|
||||
id=f"read-{offset}", name="read_file",
|
||||
arguments={"path": "src/" + "very-long-directory/" * 8 + "说明.md", "offset": offset},
|
||||
)
|
||||
for offset in (1, 200)
|
||||
]
|
||||
responses = iter([
|
||||
LLMResponse(content="", tool_calls=calls),
|
||||
LLMResponse(content="Done", tool_calls=[]),
|
||||
])
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=lambda *a, **kw: next(responses))
|
||||
tools = MagicMock()
|
||||
tools.get_definitions.return_value = []
|
||||
tools.prepare_call.side_effect = lambda _name, args: (None, args, None)
|
||||
tools.execute = AsyncMock(return_value="file contents")
|
||||
progress = []
|
||||
|
||||
async def on_progress(content, *, tool_hint=False, tool_events=None):
|
||||
progress.append((content, tool_hint, tool_events))
|
||||
|
||||
result = await AgentRunner().run(make_run_spec(
|
||||
provider, initial_messages=[], tools=tools, model="test-model",
|
||||
max_iterations=2, max_tool_result_chars=_DEFAULTS.max_tool_result_chars,
|
||||
concurrent_tools=True, hook=AgentProgressHook(output_events(on_progress=on_progress)),
|
||||
))
|
||||
|
||||
assert result.final_content == "Done"
|
||||
assert [(content, hint) for content, hint, _events in progress] == [("", True), ("", False)]
|
||||
for _content, _hint, events in progress:
|
||||
assert [(item["call_id"], item["name"], item["arguments"]) for item in events] == [
|
||||
(call.id, call.name, call.arguments) for call in calls
|
||||
]
|
||||
assert [item["phase"] for item in progress[0][2]] == ["start", "start"]
|
||||
assert [(item["phase"], item["result"]) for item in progress[1][2]] == [
|
||||
("end", "file contents"), ("end", "file contents"),
|
||||
]
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import asyncio
|
||||
from contextlib import suppress
|
||||
from copy import deepcopy
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
@@ -376,30 +377,101 @@ class TestProgressFiltering:
|
||||
assert send_mock.await_args_list[0].args[0].content == "final answer"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_channel_override_can_enable_tool_hints(self, manager, bus):
|
||||
manager.channels["mock"].send_tool_hints = True
|
||||
await bus.publish_outbound(outbound_message_for_event(
|
||||
channel="mock",
|
||||
chat_id="chat1",
|
||||
event=ProgressEvent(content="read_file(foo.py)", tool_hint=True),
|
||||
))
|
||||
@pytest.mark.parametrize(
|
||||
"send_progress, send_tool_hints, expected_indices, expected_contents",
|
||||
[
|
||||
(False, True, [1, 3], ["read foo.py", "read missing.py", "final answer"]),
|
||||
(True, False, [0, 2, 4], ["thinking", "", "", "final answer"]),
|
||||
],
|
||||
)
|
||||
async def test_tool_starts_and_terminals_follow_separate_visibility_settings(
|
||||
self, manager, bus, send_progress, send_tool_hints, expected_indices, expected_contents,
|
||||
):
|
||||
channel = manager._build_channel(
|
||||
MockChannel, {"sendProgress": send_progress, "sendToolHints": send_tool_hints},
|
||||
)
|
||||
manager.channels["mock"] = channel
|
||||
events = [
|
||||
ProgressEvent(content="thinking"),
|
||||
ProgressEvent(tool_hint=True, tool_events=[{
|
||||
"phase": "start", "call_id": "call-1", "name": "read_file",
|
||||
"arguments": {"path": "foo.py"},
|
||||
}]),
|
||||
ProgressEvent(tool_events=[{
|
||||
"phase": "end", "call_id": "call-1", "name": "read_file", "result": "contents",
|
||||
}]),
|
||||
ProgressEvent(tool_hint=True, tool_events=[{
|
||||
"phase": "start", "call_id": "call-2", "name": "read_file",
|
||||
"arguments": {"path": "missing.py"},
|
||||
}]),
|
||||
ProgressEvent(tool_events=[{
|
||||
"phase": "error", "call_id": "call-2", "name": "read_file", "error": "not found",
|
||||
}]),
|
||||
]
|
||||
messages = [
|
||||
outbound_message_for_event(channel="mock", chat_id="chat1", event=event)
|
||||
for event in events
|
||||
]
|
||||
final = OutboundMessage(channel="mock", chat_id="chat1", content="final answer")
|
||||
for msg in [*messages, final]:
|
||||
await bus.publish_outbound(msg)
|
||||
|
||||
delivered = asyncio.Event()
|
||||
|
||||
def record_send(msg):
|
||||
if msg is final:
|
||||
delivered.set()
|
||||
|
||||
channel._send_mock.side_effect = record_send
|
||||
task = asyncio.create_task(manager._dispatch_outbound())
|
||||
try:
|
||||
for _ in range(30):
|
||||
if manager.channels["mock"]._send_mock.await_count >= 1:
|
||||
break
|
||||
await asyncio.sleep(0.05)
|
||||
await asyncio.wait_for(delivered.wait(), timeout=2)
|
||||
finally:
|
||||
task.cancel()
|
||||
try:
|
||||
await task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
with suppress(asyncio.CancelledError):
|
||||
await asyncio.wait_for(task, timeout=2)
|
||||
|
||||
send_mock = manager.channels["mock"]._send_mock
|
||||
assert send_mock.await_count == 1
|
||||
assert send_mock.await_args_list[0].args[0].content == "read_file(foo.py)"
|
||||
sent = [call.args[0] for call in channel._send_mock.await_args_list]
|
||||
assert [msg.content for msg in sent] == expected_contents
|
||||
assert [msg.event for msg in sent] == [events[i] for i in expected_indices] + [None]
|
||||
if send_progress:
|
||||
assert sent[1] is messages[2]
|
||||
assert sent[2] is messages[4]
|
||||
assert messages[1].content == ""
|
||||
assert events[1].content == ""
|
||||
|
||||
|
||||
class TestToolEventDelivery:
|
||||
@pytest.mark.asyncio
|
||||
async def test_prepared_tool_hint_propagates_failure_without_mutating_core_message(self, manager):
|
||||
manager.config.agents.defaults.tool_hint_max_length = 20
|
||||
channel = manager._build_channel(MockChannel, {})
|
||||
msg = outbound_message_for_event(
|
||||
channel="mock",
|
||||
chat_id="chat1",
|
||||
event=ProgressEvent(tool_hint=True, stream_id="seg-1", tool_events=[{
|
||||
"phase": "start", "call_id": "call-1", "name": "web_search",
|
||||
"arguments": {"query": "abcdefghijklmnopqrstuvwxyz"},
|
||||
}]),
|
||||
metadata={"message_thread_id": 42},
|
||||
)
|
||||
original = deepcopy(msg)
|
||||
error = RuntimeError("send failed")
|
||||
channel._send_mock.side_effect = error
|
||||
prepared = channel.prepare_tool_events(msg)
|
||||
|
||||
with pytest.raises(RuntimeError, match="send failed") as raised:
|
||||
await manager._send_once(channel, prepared)
|
||||
|
||||
assert raised.value is error
|
||||
channel._send_mock.assert_awaited_once()
|
||||
sent = channel._send_mock.await_args.args[0]
|
||||
assert sent is prepared
|
||||
assert sent is not msg
|
||||
assert sent.content == 'search "abcdefghijklmnopqrs…"'
|
||||
assert sent.event is msg.event
|
||||
assert sent.metadata == original.metadata
|
||||
assert msg == original
|
||||
|
||||
|
||||
class TestRetryWaitFiltering:
|
||||
|
||||
@@ -1659,6 +1659,33 @@ def test_agent_uses_default_config_when_no_workspace_or_config_flags(mock_agent_
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("enabled", [True, False])
|
||||
def test_one_shot_agent_renders_structured_tool_hints(mock_agent_runtime, enabled):
|
||||
config = mock_agent_runtime["config"]
|
||||
config.channels.send_tool_hints = enabled
|
||||
config.channels.send_progress = False
|
||||
config.agents.defaults.tool_hint_max_length = 20
|
||||
mock_agent_runtime["agent_loop"].channels_config = config.channels
|
||||
events = [{
|
||||
"phase": "start", "call_id": "search-1", "name": "web_search",
|
||||
"arguments": {"query": "abcdefghijklmnopqrstuvwxyz"},
|
||||
}]
|
||||
|
||||
async def process_direct(*_args, on_progress, **_kwargs):
|
||||
await on_progress("", tool_hint=True, tool_events=events)
|
||||
return OutboundMessage(channel="cli", chat_id="direct", content="Done")
|
||||
|
||||
mock_agent_runtime["agent_loop"].process_direct.side_effect = process_direct
|
||||
with patch("nanobot.cli.terminal._print_cli_progress_line") as print_progress:
|
||||
result = runner.invoke(app, ["agent", "-m", "search"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
if enabled:
|
||||
assert print_progress.call_args.args[0] == 'search "abcdefghijklmnopqrs…"'
|
||||
else:
|
||||
print_progress.assert_not_called()
|
||||
|
||||
|
||||
def test_agent_uses_explicit_config_path(mock_agent_runtime, tmp_path: Path):
|
||||
config_path = tmp_path / "agent-config.json"
|
||||
config_path.write_text("{}")
|
||||
|
||||
@@ -189,3 +189,26 @@ async def test_non_reasoning_progress_not_affected_by_show_reasoning():
|
||||
|
||||
assert handled is True
|
||||
assert calls == ["working on it..."]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("enabled", [True, False])
|
||||
async def test_interactive_structured_tool_hint_uses_cli_length_and_switch(enabled):
|
||||
msg = SimpleNamespace(
|
||||
content="",
|
||||
event=ProgressEvent(tool_hint=True, tool_events=[{
|
||||
"phase": "start", "call_id": "search-1", "name": "web_search",
|
||||
"arguments": {"query": "abcdefghijklmnopqrstuvwxyz"},
|
||||
}]),
|
||||
metadata={},
|
||||
)
|
||||
config = SimpleNamespace(send_tool_hints=enabled, send_progress=False)
|
||||
with patch("nanobot.cli.terminal._print_interactive_progress_line") as print_progress:
|
||||
handled = await terminal._maybe_print_interactive_progress(
|
||||
msg, None, config, tool_hint_max_length=20,
|
||||
)
|
||||
assert handled is True
|
||||
if enabled:
|
||||
print_progress.assert_awaited_once_with('search "abcdefghijklmnopqrs…"', None, None)
|
||||
else:
|
||||
print_progress.assert_not_awaited()
|
||||
@@ -196,7 +196,7 @@ class TestMessageToolSuppressLogic:
|
||||
assert result.final_content == "Done"
|
||||
assert progress == [
|
||||
("Visible", False),
|
||||
('read foo.txt', True),
|
||||
("", True),
|
||||
]
|
||||
|
||||
class TestMessageToolSchema:
|
||||
|
||||
@@ -255,7 +255,7 @@ describe("NanobotTui transcript", () => {
|
||||
app.accept({
|
||||
event: "message",
|
||||
chat_id: "chat",
|
||||
text: "running shell",
|
||||
text: "",
|
||||
kind: "tool_hint",
|
||||
tool_events: [{ phase: "start", name: "exec", arguments: { cmd: "pwd" } }],
|
||||
})
|
||||
|
||||
@@ -22,7 +22,7 @@ test("restores canonical event history, media, tools, file edits and absolute fo
|
||||
{ event: "reasoning_delta", text: "private reasoning" },
|
||||
{ event: "reasoning_end", text: "private reasoning" },
|
||||
{ event: "message", kind: "reasoning", text: "private reasoning" },
|
||||
{ event: "message", kind: "tool_hint", text: "read_file", tool_events: tools },
|
||||
{ event: "message", kind: "tool_hint", text: "", tool_events: tools },
|
||||
{ event: "file_edit", edits },
|
||||
{ event: "delta", text: "partial" },
|
||||
{ event: "stream_end", text: "answer" },
|
||||
@@ -32,7 +32,7 @@ test("restores canonical event history, media, tools, file edits and absolute fo
|
||||
expect(await fetchHistory("http://fixture", "token", "chat")).toEqual({
|
||||
messages: [
|
||||
{ role: "user", content: "question", media, turnId: "turn" },
|
||||
{ role: "activity", content: "read_file", toolEvents: tools },
|
||||
{ role: "activity", content: "", toolEvents: tools },
|
||||
{ role: "activity", content: "", fileEdits: edits },
|
||||
{ role: "assistant", content: "answer", forkIndex: 8 },
|
||||
],
|
||||
|
||||
Reference in new issue
Block a user