fix(agent): remove local context tail truncation (#5820)
* fix(agent): remove local context tail truncation * fix(agent): defer subagent type annotations * fix(agent): require context consolidator for runner * refactor(agent): minimize consolidator contract diff
This commit is contained in:
1 parent
8d0430c761
commit
29ba4c7f2d
18 files changed
+483
-855
No files matched your search
@@ -10,6 +10,13 @@ from nanobot.providers.base import GenerationSettings, LLMProvider
|
||||
from nanobot.utils.llm_runtime import LLMRuntime
|
||||
|
||||
|
||||
async def failed_test_consolidator(
|
||||
_messages: list[dict[str, Any]],
|
||||
_previous_summary: str | None,
|
||||
) -> None:
|
||||
"""Model a failed summary and raw fallback in tests not exercising compaction."""
|
||||
|
||||
|
||||
def make_run_spec(provider: LLMProvider, **kwargs: Any) -> AgentRunSpec:
|
||||
"""Build a run spec from the pre-runtime test arguments.
|
||||
|
||||
@@ -51,4 +58,5 @@ def make_run_spec(provider: LLMProvider, **kwargs: Any) -> AgentRunSpec:
|
||||
),
|
||||
context_window_tokens=context_window_tokens,
|
||||
)
|
||||
kwargs.setdefault("consolidate_history", failed_test_consolidator)
|
||||
return AgentRunSpec(runtime=runtime, **kwargs)
|
||||
@@ -160,6 +160,34 @@ class TestTurnTranscriptSummary:
|
||||
assert "SNIP" in call["messages"][-1]["content"]
|
||||
assert call["tools"] == tools
|
||||
|
||||
async def test_nonpersistent_failure_returns_raw_checkpoint_without_journaling(
|
||||
self,
|
||||
consolidator,
|
||||
mock_provider,
|
||||
runtime,
|
||||
store,
|
||||
):
|
||||
accepted = [
|
||||
{"role": "system", "content": "stable system"},
|
||||
{"role": "user", "content": "accepted history"},
|
||||
]
|
||||
mock_provider.chat_stream_with_retry.return_value = LLMResponse(content="")
|
||||
consolidator._SAFETY_BUFFER = 0
|
||||
|
||||
result = await consolidator.summarize_transcript(
|
||||
accepted,
|
||||
None,
|
||||
runtime=runtime,
|
||||
session_key="test:ephemeral-turn",
|
||||
tools=[],
|
||||
persist=False,
|
||||
)
|
||||
|
||||
assert result is not None
|
||||
assert "[RAW]" in result
|
||||
assert "accepted history" in result
|
||||
assert store.read_unprocessed_history(since_cursor=0) == []
|
||||
|
||||
async def test_native_compaction_appends_only_archive_prompt(
|
||||
self,
|
||||
consolidator,
|
||||
|
||||
@@ -8,6 +8,7 @@ from nanobot.providers.base import (
|
||||
GenerationSettings,
|
||||
LLMResponse,
|
||||
ProviderConversationState,
|
||||
ToolCallRequest,
|
||||
)
|
||||
from nanobot.session.summary import SUMMARY_CONTINUATION_TEXT
|
||||
|
||||
@@ -89,6 +90,114 @@ async def test_runner_pressure_commits_summary_and_current_delta(tmp_path) -> No
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ephemeral_runner_pressure_summarizes_without_persisting(tmp_path) -> None:
|
||||
loop = _make_loop(
|
||||
tmp_path, estimated_tokens=100, context_window_tokens=1_624, max_tokens=100,
|
||||
)
|
||||
loop.provider.can_resume_conversation_state.return_value = False
|
||||
loop.schedule_background = lambda coro: coro.close() # type: ignore[method-assign]
|
||||
|
||||
session = loop.sessions.get_or_create("cli:ephemeral")
|
||||
session.messages = [
|
||||
{"role": role, "content": f"old-{role}-{turn}"}
|
||||
for turn in range(6)
|
||||
for role in ("user", "assistant")
|
||||
]
|
||||
original_messages = [dict(message) for message in session.messages]
|
||||
loop.sessions.save(session)
|
||||
|
||||
def estimate(messages, _tools, _model):
|
||||
contents = [str(message.get("content")) for message in messages]
|
||||
if contents and "SNIP" in contents[-1]:
|
||||
return 300, "test-counter"
|
||||
if any(content.startswith("old-") for content in contents):
|
||||
return 600, "test-counter"
|
||||
return 100, "test-counter"
|
||||
|
||||
loop.provider.estimate_prompt_tokens.side_effect = estimate
|
||||
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=[
|
||||
LLMResponse(content="Transient checkpoint.", tool_calls=[]),
|
||||
LLMResponse(content="done", tool_calls=[]),
|
||||
])
|
||||
|
||||
result = await loop.process_direct(
|
||||
"continue the task",
|
||||
session_key="cli:ephemeral",
|
||||
ephemeral=True,
|
||||
)
|
||||
|
||||
assert result.content == "done"
|
||||
assert loop.provider.chat_stream_with_retry.await_count == 2
|
||||
model_request = loop.provider.chat_stream_with_retry.await_args_list[1].kwargs["messages"]
|
||||
assert "Transient checkpoint." in model_request[0]["content"]
|
||||
assert model_request[1]["content"] == "continue the task"
|
||||
|
||||
reloaded = loop.sessions.get_or_create("cli:ephemeral")
|
||||
assert reloaded.messages[: len(original_messages)] == original_messages
|
||||
assert all(
|
||||
"Transient checkpoint." not in str(message.get("content"))
|
||||
for message in reloaded.messages
|
||||
)
|
||||
assert "_last_summary" not in reloaded.metadata
|
||||
assert loop.context.memory.read_unprocessed_history(since_cursor=0) == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ephemeral_tool_loop_pressure_summarizes_before_next_model_call(
|
||||
tmp_path,
|
||||
) -> None:
|
||||
loop = _make_loop(
|
||||
tmp_path, estimated_tokens=100, context_window_tokens=1_624, max_tokens=100,
|
||||
)
|
||||
loop.provider.can_resume_conversation_state.return_value = False
|
||||
loop.schedule_background = lambda coro: coro.close() # type: ignore[method-assign]
|
||||
loop.tools.execute = AsyncMock(return_value="large-result")
|
||||
|
||||
def estimate(messages, _tools, _model):
|
||||
contents = [str(message.get("content")) for message in messages]
|
||||
if contents and "SNIP" in contents[-1]:
|
||||
return 300, "test-counter"
|
||||
if sum(message.get("role") == "tool" for message in messages) >= 2:
|
||||
return 600, "test-counter"
|
||||
return 100, "test-counter"
|
||||
|
||||
normal_calls = 0
|
||||
|
||||
async def respond(*, messages, **_kwargs):
|
||||
nonlocal normal_calls
|
||||
contents = [str(message.get("content")) for message in messages]
|
||||
if contents and "SNIP" in contents[-1]:
|
||||
return LLMResponse(content="Tool-loop checkpoint.", tool_calls=[])
|
||||
normal_calls += 1
|
||||
if normal_calls <= 2:
|
||||
return LLMResponse(
|
||||
content="checking",
|
||||
tool_calls=[ToolCallRequest(
|
||||
id=f"call-{normal_calls}",
|
||||
name="list_dir",
|
||||
arguments={"path": "."},
|
||||
)],
|
||||
)
|
||||
return LLMResponse(content="done", tool_calls=[])
|
||||
|
||||
loop.provider.estimate_prompt_tokens.side_effect = estimate
|
||||
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
|
||||
|
||||
result = await loop.process_direct(
|
||||
"inspect the workspace",
|
||||
session_key="cli:ephemeral-tool-loop",
|
||||
ephemeral=True,
|
||||
)
|
||||
|
||||
assert result.content == "done"
|
||||
assert loop.provider.chat_stream_with_retry.await_count == 4
|
||||
model_request = loop.provider.chat_stream_with_retry.await_args_list[3].kwargs["messages"]
|
||||
assert "Tool-loop checkpoint." in model_request[0]["content"]
|
||||
assert sum(message.get("role") == "tool" for message in model_request) == 1
|
||||
assert loop.context.memory.read_unprocessed_history(since_cursor=0) == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_native_provider_compaction_commits_portable_terminal_checkpoint(
|
||||
tmp_path,
|
||||
|
||||
@@ -688,6 +688,7 @@ async def test_subagent_max_iterations_announces_existing_fallback(tmp_path, mon
|
||||
workspace=tmp_path,
|
||||
bus=bus,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
consolidator=MagicMock(),
|
||||
max_iterations=2,
|
||||
)
|
||||
mgr._announce_result = AsyncMock()
|
||||
|
||||
@@ -62,7 +62,8 @@ def test_initial_transcript_is_built_from_structured_turn_input() -> None:
|
||||
messages, compaction = AgentRunner._initial_transcript_and_compaction(spec)
|
||||
|
||||
assert messages == expected
|
||||
assert compaction is None
|
||||
assert compaction is not None
|
||||
assert compaction.raw_messages == expected
|
||||
transcript_builder.assert_called_once_with(transcript_input)
|
||||
|
||||
|
||||
|
||||
@@ -77,8 +77,7 @@ async def test_repeat_requires_original_read_result_in_current_context(tmp_path,
|
||||
assert repeated == (stub if retained == "original" else contents)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rewrite", ["compact", "snip"])
|
||||
async def test_dedup_uses_governed_request_instead_of_raw_transcript(tmp_path, monkeypatch, rewrite):
|
||||
async def test_dedup_uses_compacted_request_instead_of_raw_transcript(tmp_path, monkeypatch):
|
||||
tools = _tools(tmp_path)
|
||||
first, contents, _ = await _read(tools, "read-1")
|
||||
|
||||
@@ -87,7 +86,6 @@ async def test_dedup_uses_governed_request_instead_of_raw_transcript(tmp_path, m
|
||||
return (600 if contains_original else 100), "test-counter"
|
||||
|
||||
monkeypatch.setattr("nanobot.agent.context_governance.estimate_prompt_tokens_chain", estimate)
|
||||
monkeypatch.setattr("nanobot.agent.context_governance.estimate_message_tokens", lambda _: 300)
|
||||
consolidate = AsyncMock(return_value="The file was inspected; its original text was omitted.")
|
||||
|
||||
def build(transcript):
|
||||
@@ -97,25 +95,24 @@ async def test_dedup_uses_governed_request_instead_of_raw_transcript(tmp_path, m
|
||||
messages.append({"role": "user", "content": transcript.current_message})
|
||||
return messages
|
||||
|
||||
options = {}
|
||||
if rewrite == "compact":
|
||||
options = {
|
||||
"transcript_input": TranscriptInput(
|
||||
history=first.messages, current_message="Read data.txt again.",
|
||||
),
|
||||
"transcript_builder": build,
|
||||
"consolidate_history": consolidate,
|
||||
}
|
||||
result, repeated, requests = await _read(
|
||||
tools, "read-2", first.messages, context_window_tokens=1_624, max_tokens=100, **options,
|
||||
tools,
|
||||
"read-2",
|
||||
first.messages,
|
||||
context_window_tokens=1_624,
|
||||
max_tokens=100,
|
||||
transcript_input=TranscriptInput(
|
||||
history=first.messages, current_message="Read data.txt again.",
|
||||
),
|
||||
transcript_builder=build,
|
||||
consolidate_history=consolidate,
|
||||
)
|
||||
|
||||
assert any(message.get("tool_call_id") == "read-1" for message in result.messages)
|
||||
assert not any(message.get("tool_call_id") == "read-1" for message in requests[0])
|
||||
assert repeated == contents
|
||||
if rewrite == "compact":
|
||||
consolidate.assert_awaited_once()
|
||||
assert result.summary_checkpoint is not None
|
||||
consolidate.assert_awaited_once()
|
||||
assert result.summary_checkpoint is not None
|
||||
|
||||
|
||||
async def test_direct_read_without_model_context_never_omits_contents(tmp_path):
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Tests for AgentRunner context governance: repair and request fitting."""
|
||||
"""Tests for AgentRunner context governance, repair, and compaction."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -10,6 +10,7 @@ from agent.runner_helpers import make_run_spec
|
||||
from nanobot.agent.context import TranscriptInput
|
||||
from nanobot.agent.context_governance import (
|
||||
BACKFILL_CONTENT,
|
||||
ContextCompactionState,
|
||||
ContextGovernanceConfig,
|
||||
ContextGovernor,
|
||||
ContextWindowExceededError,
|
||||
@@ -60,6 +61,15 @@ def _governance_config(
|
||||
)
|
||||
|
||||
|
||||
def _compaction_state(spec: AgentRunSpec) -> ContextCompactionState:
|
||||
assert spec.initial_messages is not None
|
||||
return ContextCompactionState.from_messages(
|
||||
spec.initial_messages,
|
||||
spec.consolidate_history,
|
||||
spec.consolidate_provider_compaction,
|
||||
)
|
||||
|
||||
|
||||
def _make_loop(tmp_path):
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -130,56 +140,6 @@ async def test_runner_propagates_context_governance_failure():
|
||||
provider.chat_stream_with_retry.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_runner_locally_fits_oversized_initial_transcript(monkeypatch):
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="done"))
|
||||
tools = MagicMock()
|
||||
tools.get_definitions.return_value = []
|
||||
old_content = "x" * 20_000
|
||||
estimate = MagicMock(
|
||||
side_effect=lambda _provider, _model, messages, _tools: (
|
||||
(600, "test-counter")
|
||||
if any(message.get("content") == old_content for message in messages)
|
||||
else (100, "test-counter")
|
||||
)
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.agent.context_governance.estimate_prompt_tokens_chain",
|
||||
estimate,
|
||||
)
|
||||
|
||||
result = await AgentRunner().run(make_run_spec(
|
||||
provider,
|
||||
initial_messages=[
|
||||
{"role": "system", "content": "system"},
|
||||
{"role": "user", "content": "old question"},
|
||||
{"role": "assistant", "content": old_content},
|
||||
{"role": "user", "content": "continue"},
|
||||
],
|
||||
tools=tools,
|
||||
model="local-model",
|
||||
context_window_tokens=1_624,
|
||||
max_tokens=100,
|
||||
max_iterations=1,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
))
|
||||
|
||||
assert provider.chat_stream_with_retry.await_args.kwargs["messages"] == [
|
||||
{"role": "system", "content": "system"},
|
||||
{"role": "user", "content": "continue"},
|
||||
]
|
||||
estimated_messages = [call.args[2] for call in estimate.call_args_list]
|
||||
assert sum(
|
||||
any(message.get("content") == old_content for message in messages)
|
||||
for messages in estimated_messages
|
||||
) == 1
|
||||
assert len(estimated_messages) == 3
|
||||
assert any(message.get("content") == old_content for message in result.messages)
|
||||
|
||||
|
||||
async def test_runner_summarizes_history_and_preserves_current_input(monkeypatch):
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
provider.can_resume_conversation_state.return_value = True
|
||||
@@ -664,265 +624,14 @@ async def test_runner_governs_messages_added_by_before_iteration_hook(monkeypatc
|
||||
provider.chat_stream_with_retry.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_runner_drops_resumable_provider_state_when_request_is_fitted(monkeypatch):
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
provider.can_resume_conversation_state.return_value = True
|
||||
captured_contexts = []
|
||||
old_content = "old-oversized-history"
|
||||
candidate = ProviderConversationState(
|
||||
kind="openai_responses",
|
||||
provider="openai:test",
|
||||
model="local-model",
|
||||
version=1,
|
||||
payload={"items": [{"type": "message", "content": "fresh state"}]},
|
||||
)
|
||||
|
||||
async def chat_stream_with_retry(*, provider_context=None, **_kwargs):
|
||||
captured_contexts.append(provider_context)
|
||||
return LLMResponse(
|
||||
content="done",
|
||||
usage=LLMUsage.reported(input_tokens=100, output_tokens=10),
|
||||
provider_state=candidate,
|
||||
)
|
||||
|
||||
provider.chat_stream_with_retry = chat_stream_with_retry
|
||||
tools = MagicMock()
|
||||
tools.get_definitions.return_value = []
|
||||
monkeypatch.setattr(
|
||||
"nanobot.agent.context_governance.estimate_prompt_tokens_chain",
|
||||
lambda _provider, _model, messages, _tools: (
|
||||
(600, "test-counter")
|
||||
if any(message.get("content") == old_content for message in messages)
|
||||
else (100, "test-counter")
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.agent.context_governance.estimate_message_tokens",
|
||||
lambda message: 450 if message.get("content") == old_content else 50,
|
||||
)
|
||||
saved_state = ProviderConversationState(
|
||||
kind="openai_responses",
|
||||
provider="openai:test",
|
||||
model="local-model",
|
||||
version=1,
|
||||
payload={"items": [{"type": "message", "content": "stale state"}]},
|
||||
)
|
||||
|
||||
result = await AgentRunner().run(make_run_spec(
|
||||
provider,
|
||||
initial_messages=[
|
||||
{"role": "assistant", "content": old_content},
|
||||
{"role": "user", "content": "continue"},
|
||||
],
|
||||
tools=tools,
|
||||
model="local-model",
|
||||
context_window_tokens=1_624,
|
||||
max_tokens=100,
|
||||
max_iterations=1,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
provider_state=saved_state,
|
||||
))
|
||||
|
||||
assert captured_contexts[0].conversation_state is None
|
||||
assert result.provider_state is not None
|
||||
assert result.provider_state.payload == candidate.payload
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_runner_fits_each_malformed_retry_with_its_actual_tools(monkeypatch):
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
calls: list[dict] = []
|
||||
estimated_tools: list[object] = []
|
||||
definitions = [{"type": "function", "function": {"name": "read_file"}}]
|
||||
|
||||
async def chat_stream_with_retry(*, messages, tools=None, **_kwargs):
|
||||
calls.append({"messages": [dict(message) for message in messages], "tools": tools})
|
||||
if len(calls) < 3:
|
||||
return LLMResponse(
|
||||
content="bad tool request",
|
||||
tool_calls=[ToolCallRequest(id=f"bad_{len(calls)}", name=None, arguments={})],
|
||||
finish_reason="tool_calls",
|
||||
usage=LLMUsage.reported(input_tokens=100, output_tokens=10),
|
||||
)
|
||||
return LLMResponse(
|
||||
content="recovered",
|
||||
usage=LLMUsage.reported(input_tokens=100, output_tokens=10),
|
||||
)
|
||||
|
||||
def estimate(_provider, _model, messages, _tools):
|
||||
estimated_tools.append(_tools)
|
||||
user_count = sum(message.get("role") == "user" for message in messages)
|
||||
return (600 if user_count > 1 else 100), "test-counter"
|
||||
|
||||
provider.chat_stream_with_retry = chat_stream_with_retry
|
||||
tools = MagicMock()
|
||||
tools.get_definitions.return_value = definitions
|
||||
monkeypatch.setattr(
|
||||
"nanobot.agent.context_governance.estimate_prompt_tokens_chain",
|
||||
estimate,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.agent.context_governance.estimate_message_tokens",
|
||||
lambda _message: 300,
|
||||
)
|
||||
|
||||
result = await AgentRunner().run(make_run_spec(
|
||||
provider,
|
||||
initial_messages=[{"role": "user", "content": "use a tool"}],
|
||||
tools=tools,
|
||||
model="local-model",
|
||||
context_window_tokens=1_624,
|
||||
max_tokens=100,
|
||||
max_iterations=1,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
))
|
||||
|
||||
assert [call["tools"] for call in calls] == [definitions, definitions, None]
|
||||
assert definitions in estimated_tools
|
||||
assert None in estimated_tools
|
||||
assert [len(call["messages"]) for call in calls] == [1, 1, 1]
|
||||
assert result.final_content == "recovered"
|
||||
assert result.usage is not None
|
||||
assert result.usage.input_tokens == 300
|
||||
assert result.usage.output_tokens == 30
|
||||
assert result.usage.request_count == 3
|
||||
# Recovery dispatches contribute to the total without becoming extra chart bars.
|
||||
assert result.round_usages == [result.usage]
|
||||
assert result.messages == [
|
||||
{"role": "user", "content": "use a tool"},
|
||||
{"role": "assistant", "content": "recovered"},
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_runner_fits_empty_response_finalization_before_dispatch(monkeypatch):
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
calls: list[dict] = []
|
||||
|
||||
async def chat_stream_with_retry(*, messages, tools=None, **_kwargs):
|
||||
calls.append({"messages": [dict(message) for message in messages], "tools": tools})
|
||||
if len(calls) < 3:
|
||||
return LLMResponse(
|
||||
content=None,
|
||||
usage=LLMUsage.reported(input_tokens=100, output_tokens=1),
|
||||
)
|
||||
return LLMResponse(
|
||||
content="finalized",
|
||||
usage=LLMUsage.reported(input_tokens=100, output_tokens=10),
|
||||
)
|
||||
|
||||
def estimate(_provider, _model, messages, _tools):
|
||||
contents = [str(message.get("content") or "") for message in messages]
|
||||
has_original = "do task" in contents
|
||||
has_finalization = any("conversation above" in content for content in contents)
|
||||
return (600 if has_original and has_finalization else 100), "test-counter"
|
||||
|
||||
provider.chat_stream_with_retry = chat_stream_with_retry
|
||||
tools = MagicMock()
|
||||
tools.get_definitions.return_value = []
|
||||
monkeypatch.setattr(
|
||||
"nanobot.agent.context_governance.estimate_prompt_tokens_chain",
|
||||
estimate,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.agent.context_governance.estimate_message_tokens",
|
||||
lambda _message: 300,
|
||||
)
|
||||
|
||||
result = await AgentRunner().run(make_run_spec(
|
||||
provider,
|
||||
initial_messages=[{"role": "user", "content": "do task"}],
|
||||
tools=tools,
|
||||
model="local-model",
|
||||
context_window_tokens=1_624,
|
||||
max_tokens=100,
|
||||
max_iterations=3,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
))
|
||||
|
||||
assert len(calls) == 3
|
||||
assert calls[-1]["tools"] is None
|
||||
assert all(message.get("content") != "do task" for message in calls[-1]["messages"])
|
||||
assert result.final_content == "finalized"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_runner_fits_max_iteration_finalization_before_dispatch(monkeypatch):
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
calls: list[dict] = []
|
||||
oversized_result = "oversized-current-tool-result"
|
||||
|
||||
async def chat_stream_with_retry(*, messages, tools=None, **_kwargs):
|
||||
calls.append({"messages": [dict(message) for message in messages], "tools": tools})
|
||||
if len(calls) == 1:
|
||||
return LLMResponse(
|
||||
content="working",
|
||||
tool_calls=[ToolCallRequest(id="call_1", name="read_file", arguments={})],
|
||||
finish_reason="tool_calls",
|
||||
usage=LLMUsage.reported(input_tokens=100, output_tokens=10),
|
||||
)
|
||||
return LLMResponse(
|
||||
content="safe summary",
|
||||
usage=LLMUsage.reported(input_tokens=100, output_tokens=10),
|
||||
)
|
||||
|
||||
def estimate(_provider, _model, messages, _tools):
|
||||
has_oversized = any(
|
||||
message.get("content") == oversized_result for message in messages
|
||||
)
|
||||
return (600 if has_oversized else 100), "test-counter"
|
||||
|
||||
provider.chat_stream_with_retry = chat_stream_with_retry
|
||||
tools = MagicMock()
|
||||
tools.get_definitions.return_value = []
|
||||
tools.execute = AsyncMock(return_value=oversized_result)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.agent.context_governance.estimate_prompt_tokens_chain",
|
||||
estimate,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.agent.context_governance.estimate_message_tokens",
|
||||
lambda message: 600 if message.get("content") == oversized_result else 50,
|
||||
)
|
||||
|
||||
result = await AgentRunner().run(make_run_spec(
|
||||
provider,
|
||||
initial_messages=[{"role": "user", "content": "inspect"}],
|
||||
tools=tools,
|
||||
model="local-model",
|
||||
context_window_tokens=1_624,
|
||||
max_tokens=100,
|
||||
max_iterations=1,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
))
|
||||
|
||||
assert len(calls) == 2
|
||||
assert calls[-1]["tools"] is None
|
||||
assert all(
|
||||
message.get("content") != oversized_result
|
||||
for message in calls[-1]["messages"]
|
||||
)
|
||||
assert any(message.get("content") == oversized_result for message in result.messages)
|
||||
assert result.final_content == "safe summary"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("input_tokens", "expected_fitted"),
|
||||
("input_tokens", "expected_pressure"),
|
||||
[(500, True), (100, False)],
|
||||
)
|
||||
async def test_matching_reported_provider_usage_avoids_local_estimate(
|
||||
monkeypatch,
|
||||
input_tokens,
|
||||
expected_fitted,
|
||||
expected_pressure,
|
||||
):
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
tools = MagicMock()
|
||||
@@ -945,23 +654,30 @@ async def test_matching_reported_provider_usage_avoids_local_estimate(
|
||||
)
|
||||
|
||||
governor = ContextGovernor()
|
||||
monkeypatch.setattr(governor, "fit_to_budget", lambda *_args, **_kwargs: [])
|
||||
state = ModelRequestState(
|
||||
config=_governance_config(provider, tools, spec),
|
||||
conversation=ProviderConversationStateController(
|
||||
provider=provider, model=spec.runtime.model, messages=spec.initial_messages,
|
||||
),
|
||||
compaction=_compaction_state(spec),
|
||||
usage=LLMUsage.reported(input_tokens=input_tokens, output_tokens=10),
|
||||
messages=spec.initial_messages,
|
||||
tool_definitions=[],
|
||||
)
|
||||
messages, _context = await governor.prepare_request(
|
||||
state,
|
||||
spec.initial_messages,
|
||||
tool_definitions=tools.get_definitions(),
|
||||
)
|
||||
|
||||
assert messages == ([] if expected_fitted else spec.initial_messages)
|
||||
if expected_pressure:
|
||||
with pytest.raises(ContextWindowExceededError):
|
||||
await governor.prepare_request(
|
||||
state,
|
||||
spec.initial_messages,
|
||||
tool_definitions=tools.get_definitions(),
|
||||
)
|
||||
else:
|
||||
messages, _context = await governor.prepare_request(
|
||||
state,
|
||||
spec.initial_messages,
|
||||
tool_definitions=tools.get_definitions(),
|
||||
)
|
||||
assert messages == spec.initial_messages
|
||||
|
||||
|
||||
async def test_changed_messages_use_local_estimate_after_reported_usage(monkeypatch):
|
||||
@@ -985,23 +701,22 @@ async def test_changed_messages_use_local_estimate_after_reported_usage(monkeypa
|
||||
)
|
||||
|
||||
governor = ContextGovernor()
|
||||
monkeypatch.setattr(governor, "fit_to_budget", lambda *_args, **_kwargs: [])
|
||||
state = ModelRequestState(
|
||||
config=_governance_config(provider, tools, spec),
|
||||
conversation=ProviderConversationStateController(
|
||||
provider=provider, model=spec.runtime.model, messages=spec.initial_messages,
|
||||
),
|
||||
compaction=_compaction_state(spec),
|
||||
usage=LLMUsage.reported(input_tokens=900, output_tokens=10),
|
||||
messages=[{"role": "user", "content": "previous request"}],
|
||||
tool_definitions=[],
|
||||
)
|
||||
messages, _context = await governor.prepare_request(
|
||||
state,
|
||||
spec.initial_messages,
|
||||
tool_definitions=tools.get_definitions(),
|
||||
)
|
||||
|
||||
assert messages == []
|
||||
with pytest.raises(ContextWindowExceededError):
|
||||
await governor.prepare_request(
|
||||
state,
|
||||
spec.initial_messages,
|
||||
tool_definitions=tools.get_definitions(),
|
||||
)
|
||||
estimate.assert_called_once()
|
||||
|
||||
|
||||
@@ -1039,7 +754,7 @@ def test_resumed_provider_context_avoids_full_transcript_estimate(monkeypatch):
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_runner_counts_resumed_provider_state_before_dispatch(monkeypatch):
|
||||
async def test_runner_refuses_oversized_resumed_state_without_compactor(monkeypatch):
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
@@ -1077,23 +792,22 @@ async def test_runner_counts_resumed_provider_state_before_dispatch(monkeypatch)
|
||||
lambda *_args, **_kwargs: (100, "test-counter"),
|
||||
)
|
||||
|
||||
result = await AgentRunner().run(make_run_spec(
|
||||
provider,
|
||||
initial_messages=[current_message],
|
||||
tools=tools,
|
||||
model="local-model",
|
||||
context_window_tokens=1_624,
|
||||
max_tokens=100,
|
||||
max_iterations=1,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
provider_state=saved_state,
|
||||
))
|
||||
with pytest.raises(ContextWindowExceededError) as exc_info:
|
||||
await AgentRunner().run(make_run_spec(
|
||||
provider,
|
||||
initial_messages=[current_message],
|
||||
tools=tools,
|
||||
model="local-model",
|
||||
context_window_tokens=1_624,
|
||||
max_tokens=100,
|
||||
max_iterations=1,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
provider_state=saved_state,
|
||||
))
|
||||
|
||||
assert captured_contexts[0].conversation_state is None
|
||||
assert result.messages == [
|
||||
current_message,
|
||||
{"role": "assistant", "content": "done"},
|
||||
]
|
||||
assert exc_info.value.estimated_tokens == 550
|
||||
assert exc_info.value.source == "resumed provider state plus pending messages"
|
||||
assert captured_contexts == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -1101,7 +815,7 @@ async def test_runner_counts_resumed_provider_state_before_dispatch(monkeypatch)
|
||||
("context_window_tokens", "expected_budget"),
|
||||
[(1_624, 500), (1_000, 0)],
|
||||
)
|
||||
async def test_runner_refuses_locally_fitted_request_that_still_cannot_fit(
|
||||
async def test_runner_refuses_oversized_request_without_compactor(
|
||||
monkeypatch,
|
||||
context_window_tokens,
|
||||
expected_budget,
|
||||
@@ -1137,113 +851,6 @@ async def test_runner_refuses_locally_fitted_request_that_still_cannot_fit(
|
||||
provider.chat_stream_with_retry.assert_not_awaited()
|
||||
|
||||
|
||||
def test_snip_history_drops_orphaned_tool_results_from_trimmed_slice(monkeypatch):
|
||||
provider = MagicMock()
|
||||
tools = MagicMock()
|
||||
tools.get_definitions.return_value = []
|
||||
messages = [
|
||||
{"role": "system", "content": "system"},
|
||||
{"role": "user", "content": "old user"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "tool call",
|
||||
"tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "ls", "arguments": "{}"}}],
|
||||
},
|
||||
{"role": "tool", "tool_call_id": "call_1", "content": "tool output"},
|
||||
{"role": "assistant", "content": "after tool"},
|
||||
]
|
||||
spec = make_run_spec(provider,
|
||||
initial_messages=messages,
|
||||
tools=tools,
|
||||
model="test-model",
|
||||
max_iterations=1,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
context_window_tokens=1_224,
|
||||
max_tokens=100,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
"nanobot.agent.context_governance.estimate_prompt_tokens_chain",
|
||||
lambda *_args, **_kwargs: (500, None),
|
||||
)
|
||||
token_sizes = {
|
||||
"old user": 120,
|
||||
"tool call": 120,
|
||||
"tool output": 40,
|
||||
"after tool": 40,
|
||||
"system": 0,
|
||||
}
|
||||
monkeypatch.setattr(
|
||||
"nanobot.agent.context_governance.estimate_message_tokens",
|
||||
lambda msg: token_sizes.get(str(msg.get("content")), 40),
|
||||
)
|
||||
|
||||
trimmed = ContextGovernor().snip_history(
|
||||
_governance_config(provider, tools, spec),
|
||||
messages,
|
||||
tool_definitions=tools.get_definitions(),
|
||||
)
|
||||
|
||||
# After the fix, the user message is recovered so the sequence is valid
|
||||
# for providers that require system → user (e.g. GLM error 1214).
|
||||
assert trimmed[0]["role"] == "system"
|
||||
non_system = [m for m in trimmed if m["role"] != "system"]
|
||||
assert non_system[0]["role"] == "user", f"Expected user after system, got {non_system[0]['role']}"
|
||||
|
||||
|
||||
def test_snip_history_reserves_budget_for_tool_definitions(monkeypatch):
|
||||
provider = MagicMock()
|
||||
tools = MagicMock()
|
||||
tools.get_definitions.return_value = [{"type": "function", "function": {"name": "large_tool"}}]
|
||||
messages = [
|
||||
{"role": "system", "content": "system"},
|
||||
{"role": "user", "content": "old user"},
|
||||
{"role": "assistant", "content": "old assistant"},
|
||||
{"role": "user", "content": "recent one"},
|
||||
{"role": "assistant", "content": "recent answer"},
|
||||
{"role": "user", "content": "recent two"},
|
||||
]
|
||||
spec = make_run_spec(provider,
|
||||
initial_messages=messages,
|
||||
tools=tools,
|
||||
model="test-model",
|
||||
max_iterations=1,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
context_window_tokens=1_624,
|
||||
max_tokens=100,
|
||||
)
|
||||
|
||||
def _estimate(_provider, _model, estimate_messages, estimate_tools):
|
||||
if estimate_messages == messages:
|
||||
return 1000, None
|
||||
assert estimate_messages == [{"role": "system", "content": "system"}]
|
||||
assert estimate_tools == tools.get_definitions.return_value
|
||||
return 350, None
|
||||
|
||||
monkeypatch.setattr("nanobot.agent.context_governance.estimate_prompt_tokens_chain", _estimate)
|
||||
token_sizes = {
|
||||
"system": 50,
|
||||
"old user": 200,
|
||||
"old assistant": 200,
|
||||
"recent one": 200,
|
||||
"recent answer": 200,
|
||||
"recent two": 200,
|
||||
}
|
||||
monkeypatch.setattr(
|
||||
"nanobot.agent.context_governance.estimate_message_tokens",
|
||||
lambda msg: token_sizes.get(str(msg.get("content")), 40),
|
||||
)
|
||||
|
||||
trimmed = ContextGovernor().snip_history(
|
||||
_governance_config(provider, tools, spec),
|
||||
messages,
|
||||
tool_definitions=tools.get_definitions(),
|
||||
)
|
||||
|
||||
contents = [message.get("content") for message in trimmed]
|
||||
assert contents == ["system", "recent two"]
|
||||
|
||||
|
||||
async def test_backfill_missing_tool_results_inserts_error():
|
||||
"""Orphaned tool_use (no matching tool_result) should get a synthetic error."""
|
||||
|
||||
@@ -1519,11 +1126,9 @@ async def test_runner_backfill_only_mutates_model_context_not_returned_messages(
|
||||
]
|
||||
|
||||
|
||||
def test_governance_repairs_orphans_after_snip():
|
||||
"""After snipping clips an assistant+tool_calls, orphan repair cleans up the tail."""
|
||||
# Simulate snipping that keeps only the tail: drop the assistant with
|
||||
# tool_calls but keep its tool result (orphan).
|
||||
snipped = [
|
||||
def test_governance_repairs_orphans_after_history_rewrite():
|
||||
"""A rewritten history drops tool results whose calls are no longer present."""
|
||||
rewritten = [
|
||||
{"role": "system", "content": "system"},
|
||||
{"role": "tool", "tool_call_id": "tc_old", "name": "search",
|
||||
"content": "old result"},
|
||||
@@ -1531,7 +1136,7 @@ def test_governance_repairs_orphans_after_snip():
|
||||
{"role": "user", "content": "new msg"},
|
||||
]
|
||||
|
||||
cleaned = ContextGovernor.drop_orphan_tool_results(snipped)
|
||||
cleaned = ContextGovernor.drop_orphan_tool_results(rewritten)
|
||||
# The orphan tool result should be removed.
|
||||
assert not any(
|
||||
m.get("role") == "tool" and m.get("tool_call_id") == "tc_old"
|
||||
@@ -1555,138 +1160,6 @@ def test_governance_fallback_still_repairs_orphans():
|
||||
assert not any(m.get("tool_call_id") == "orphan_tc" for m in repaired)
|
||||
|
||||
|
||||
def test_snip_history_preserves_user_message_after_truncation(monkeypatch):
|
||||
"""When _snip_history truncates messages and the only user message ends up
|
||||
outside the kept window, the method must recover the nearest user message
|
||||
so the resulting sequence is valid for providers like GLM (which reject
|
||||
system→assistant with error 1214).
|
||||
|
||||
This reproduces the exact scenario from the bug report:
|
||||
- Normal interaction: user asks, assistant calls tool, tool returns,
|
||||
assistant replies.
|
||||
- Injection adds a phantom user message, triggering more tool calls.
|
||||
- _snip_history activates, keeping only recent assistant/tool pairs.
|
||||
- The injected user message is in the truncated prefix and gets lost.
|
||||
"""
|
||||
provider = MagicMock()
|
||||
tools = MagicMock()
|
||||
tools.get_definitions.return_value = []
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": "system"},
|
||||
{"role": "assistant", "content": "previous reply"},
|
||||
{"role": "user", "content": ".nanobot的同目录"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": None,
|
||||
"tool_calls": [{"id": "tc_1", "type": "function", "function": {"name": "exec", "arguments": "{}"}}],
|
||||
},
|
||||
{"role": "tool", "tool_call_id": "tc_1", "content": "tool output 1"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": None,
|
||||
"tool_calls": [{"id": "tc_2", "type": "function", "function": {"name": "exec", "arguments": "{}"}}],
|
||||
},
|
||||
{"role": "tool", "tool_call_id": "tc_2", "content": "tool output 2"},
|
||||
]
|
||||
|
||||
spec = make_run_spec(provider,
|
||||
initial_messages=messages,
|
||||
tools=tools,
|
||||
model="test-model",
|
||||
max_iterations=1,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
context_window_tokens=1_224,
|
||||
max_tokens=100,
|
||||
)
|
||||
|
||||
# Make estimate_prompt_tokens_chain report above budget so _snip_history activates.
|
||||
monkeypatch.setattr(
|
||||
"nanobot.agent.context_governance.estimate_prompt_tokens_chain",
|
||||
lambda *_a, **_kw: (500, None),
|
||||
)
|
||||
# Make kept window small: only the last 2 messages fit the budget.
|
||||
token_sizes = {
|
||||
"system": 0,
|
||||
"previous reply": 200,
|
||||
".nanobot的同目录": 80,
|
||||
"tool output 1": 80,
|
||||
"tool output 2": 80,
|
||||
}
|
||||
monkeypatch.setattr(
|
||||
"nanobot.agent.context_governance.estimate_message_tokens",
|
||||
lambda msg: token_sizes.get(str(msg.get("content")), 100),
|
||||
)
|
||||
|
||||
trimmed = ContextGovernor().snip_history(
|
||||
_governance_config(provider, tools, spec),
|
||||
messages,
|
||||
tool_definitions=tools.get_definitions(),
|
||||
)
|
||||
|
||||
# The first non-system message MUST be user (not assistant).
|
||||
non_system = [m for m in trimmed if m.get("role") != "system"]
|
||||
assert non_system, "trimmed should contain at least one non-system message"
|
||||
assert non_system[0]["role"] == "user", (
|
||||
f"First non-system message must be 'user', got '{non_system[0]['role']}'. "
|
||||
f"Roles: {[m['role'] for m in trimmed]}"
|
||||
)
|
||||
|
||||
|
||||
def test_snip_history_no_user_at_all_falls_back_gracefully(monkeypatch):
|
||||
"""Edge case: if non_system has zero user messages, _snip_history should
|
||||
still return a valid sequence (not crash or produce system→assistant)."""
|
||||
provider = MagicMock()
|
||||
tools = MagicMock()
|
||||
tools.get_definitions.return_value = []
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": "system"},
|
||||
{"role": "assistant", "content": "reply"},
|
||||
{"role": "tool", "tool_call_id": "tc_1", "content": "result"},
|
||||
{"role": "assistant", "content": "reply 2"},
|
||||
{"role": "tool", "tool_call_id": "tc_2", "content": "result 2"},
|
||||
]
|
||||
|
||||
spec = make_run_spec(provider,
|
||||
initial_messages=messages,
|
||||
tools=tools,
|
||||
model="test-model",
|
||||
max_iterations=1,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
context_window_tokens=1_224,
|
||||
max_tokens=100,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
"nanobot.agent.context_governance.estimate_prompt_tokens_chain",
|
||||
lambda *_a, **_kw: (500, None),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.agent.context_governance.estimate_message_tokens",
|
||||
lambda msg: 100,
|
||||
)
|
||||
|
||||
trimmed = ContextGovernor().snip_history(
|
||||
_governance_config(provider, tools, spec),
|
||||
messages,
|
||||
tool_definitions=tools.get_definitions(),
|
||||
)
|
||||
|
||||
# Should not crash. The result should still be a valid list.
|
||||
assert isinstance(trimmed, list)
|
||||
# Must have at least system.
|
||||
assert any(m.get("role") == "system" for m in trimmed)
|
||||
# The _enforce_role_alternation safety net must be able to fix whatever
|
||||
# _snip_history returns here — verify it produces a valid sequence.
|
||||
fixed = LLMProvider._enforce_role_alternation(trimmed)
|
||||
non_system = [m for m in fixed if m["role"] != "system"]
|
||||
if non_system:
|
||||
assert non_system[0]["role"] in ("user", "tool"), (
|
||||
f"Safety net should ensure first non-system is user/tool, got {non_system[0]['role']}"
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Malformed tool_call name guard (missing/non-string name wedges the session
|
||||
# upstream: messages.content.N.tool_use.name: Input should be a valid string)
|
||||
|
||||
@@ -2,6 +2,7 @@ from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from agent.runner_helpers import failed_test_consolidator
|
||||
from nanobot.agent.runner import AgentRunner, AgentRunSpec
|
||||
from nanobot.config.schema import AgentDefaults
|
||||
from nanobot.providers.base import (
|
||||
@@ -68,6 +69,7 @@ async def test_active_run_keeps_provider_captured_at_admission() -> None:
|
||||
runtime=selected_runtime,
|
||||
max_iterations=2,
|
||||
max_tool_result_chars=AgentDefaults().max_tool_result_chars,
|
||||
consolidate_history=failed_test_consolidator,
|
||||
session_key="webui:cache-test",
|
||||
))
|
||||
|
||||
|
||||
@@ -188,6 +188,7 @@ async def test_subagent_recovers_from_tool_error_in_same_run(tmp_path):
|
||||
workspace=tmp_path,
|
||||
bus=MessageBus(),
|
||||
max_tool_result_chars=16_000,
|
||||
consolidator=MagicMock(),
|
||||
)
|
||||
|
||||
result = await sm.run_inline(
|
||||
@@ -200,6 +201,67 @@ async def test_subagent_recovers_from_tool_error_in_same_run(tmp_path):
|
||||
assert provider.chat_stream_with_retry.await_count == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_subagent_pressure_uses_transient_summary(tmp_path):
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
provider.get_default_model.return_value = "test"
|
||||
provider.can_resume_conversation_state.return_value = False
|
||||
provider.generation = GenerationSettings(max_tokens=100)
|
||||
|
||||
def estimate(messages, _tools, _model):
|
||||
if sum(message.get("role") == "tool" for message in messages) >= 2:
|
||||
return 600, "test-counter"
|
||||
return 100, "test-counter"
|
||||
|
||||
provider.estimate_prompt_tokens = MagicMock(side_effect=estimate)
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=[
|
||||
LLMResponse(
|
||||
content="checking",
|
||||
tool_calls=[ToolCallRequest(
|
||||
id="call-1",
|
||||
name="list_dir",
|
||||
arguments={"path": "."},
|
||||
)],
|
||||
),
|
||||
LLMResponse(
|
||||
content="checking again",
|
||||
tool_calls=[ToolCallRequest(
|
||||
id="call-2",
|
||||
name="list_dir",
|
||||
arguments={"path": "."},
|
||||
)],
|
||||
),
|
||||
LLMResponse(content="done", tool_calls=[]),
|
||||
])
|
||||
consolidator = MagicMock()
|
||||
consolidator.summarize_transcript = AsyncMock(return_value="Subagent checkpoint.")
|
||||
consolidator.summarize_provider_compaction = AsyncMock(return_value=None)
|
||||
manager = SubagentManager(
|
||||
workspace=tmp_path,
|
||||
bus=MessageBus(),
|
||||
max_tool_result_chars=16_000,
|
||||
consolidator=consolidator,
|
||||
)
|
||||
runtime = LLMRuntime.capture(
|
||||
provider,
|
||||
"test",
|
||||
context_window_tokens=1_624,
|
||||
)
|
||||
|
||||
result = await manager.run_inline(
|
||||
task="inspect the workspace",
|
||||
session_key="test:direct",
|
||||
runtime=runtime,
|
||||
)
|
||||
|
||||
assert result == "done"
|
||||
consolidator.summarize_transcript.assert_awaited_once()
|
||||
assert consolidator.summarize_transcript.await_args.kwargs["persist"] is False
|
||||
model_request = provider.chat_stream_with_retry.await_args_list[2].kwargs["messages"]
|
||||
assert "Subagent checkpoint." in model_request[0]["content"]
|
||||
assert sum(message.get("role") == "tool" for message in model_request) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_spawned_subagent_inherits_llm_usage_source(tmp_path):
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
|
||||
@@ -439,6 +439,7 @@ class TestSubagentCancellation:
|
||||
workspace=tmp_path,
|
||||
bus=bus,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
consolidator=MagicMock(),
|
||||
)
|
||||
|
||||
async def fake_execute(self, **kwargs):
|
||||
@@ -538,6 +539,7 @@ class TestSubagentCancellation:
|
||||
workspace=tmp_path,
|
||||
bus=bus,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
consolidator=MagicMock(),
|
||||
)
|
||||
mgr._announce_result = AsyncMock()
|
||||
|
||||
@@ -586,6 +588,7 @@ class TestSubagentCancellation:
|
||||
workspace=tmp_path,
|
||||
bus=bus,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
consolidator=MagicMock(),
|
||||
)
|
||||
mgr._announce_result = AsyncMock()
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ from collections.abc import AsyncIterator
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from agent.runner_helpers import failed_test_consolidator
|
||||
from openai import AsyncOpenAI
|
||||
|
||||
from nanobot.agent.hook import AgentHook
|
||||
@@ -196,6 +197,7 @@ async def test_runner_streams_past_old_wall_limit_with_optional_ui(
|
||||
tools=ToolRegistry(),
|
||||
runtime=LLMRuntime.capture(provider, "gpt-5.2", context_window_tokens=128_000),
|
||||
max_iterations=1, max_tool_result_chars=1_000, hook=Hook(),
|
||||
consolidate_history=failed_test_consolidator,
|
||||
))
|
||||
assert result.stop_reason == "completed"
|
||||
assert result.final_content == "done"
|
||||
@@ -231,6 +233,7 @@ async def test_chat_only_provider_still_has_a_timeout(monkeypatch, finalize):
|
||||
tools=ToolRegistry(),
|
||||
runtime=LLMRuntime.capture(provider, "test", context_window_tokens=128_000),
|
||||
max_iterations=1, max_tool_result_chars=1_000,
|
||||
consolidate_history=failed_test_consolidator,
|
||||
max_iterations_message="Tool budget exhausted.",
|
||||
)), timeout=1)
|
||||
assert provider.calls == (2 if finalize else 1)
|
||||
|
||||
Reference in new issue
Block a user