fix(agent): provide current workspace access before model requests
This commit is contained in:
1 parent
d7d4b97df3
commit
1d69f630d7
17 files changed
+265
-44
No files matched your search
@@ -2083,6 +2083,12 @@ For API keys, tokens, and other secrets, see [Environment Variables for Secrets]
|
||||
| `tools.ssrfWhitelist` | `[]` | CIDR ranges exempted from the shared SSRF guard used by web fetches and HTTP/SSE MCP connections. Prefer exact host CIDRs such as `192.168.1.50/32`; broad ranges increase SSRF exposure. |
|
||||
| `channels.*.allowFrom` | omitted | Access control per channel. Omit to use pairing-only mode; set `["*"]` to allow everyone; or list specific user IDs. See [Pairing](#pairing) for details. |
|
||||
|
||||
Each new user request includes the current project and file-access restriction in model-only
|
||||
context. This uses the same policy resolver as the tools, including restrictions from
|
||||
a configured exec sandbox. It does not grant access or change OS permissions.
|
||||
The context is stored with that request, not rewritten in earlier messages. New requests
|
||||
refresh it after a project switch or context compaction. It is hidden from the chat view.
|
||||
|
||||
To diagnose a path error, the agent can call `my(action="check", key="workspace_sandbox")`.
|
||||
This read-only result shows the current tool directory and workspace restriction, including
|
||||
the restriction from `tools.exec.sandbox`. The older `workspace` value is an agent-directory
|
||||
|
||||
@@ -620,6 +620,8 @@ class AgentLoop:
|
||||
from nanobot.agent.tools.context import ToolContext
|
||||
from nanobot.agent.tools.loader import ToolLoader
|
||||
|
||||
runtime_control = AgentRuntimeControl(self)
|
||||
self.register_runtime_context_provider(runtime_control.workspace_context)
|
||||
ctx = ToolContext(
|
||||
config=self.tools_config,
|
||||
workspace=str(self.workspace),
|
||||
@@ -632,7 +634,7 @@ class AgentLoop:
|
||||
image_generation_provider_configs=self._image_generation_provider_configs,
|
||||
timezone=self.context.timezone or "UTC",
|
||||
workspace_sandbox=self.workspace_scopes.sandbox_status,
|
||||
runtime_control=AgentRuntimeControl(self),
|
||||
runtime_control=runtime_control,
|
||||
)
|
||||
loader = ToolLoader()
|
||||
registered = loader.load(ctx, self.tools)
|
||||
@@ -741,6 +743,7 @@ class AgentLoop:
|
||||
sender_id=ctx.msg.sender_id,
|
||||
turn_id=ctx.delivery.route.turn_id or ctx.turn_id,
|
||||
workspace=scope.project_path,
|
||||
workspace_scope=scope,
|
||||
log_content=ctx.session.policy.log_content and not ctx.ephemeral,
|
||||
persist_session=ctx.session.policy.persist and not ctx.ephemeral,
|
||||
can_receive_background_results=self._running,
|
||||
@@ -1085,6 +1088,8 @@ class AgentLoop:
|
||||
sender_id=pending_msg.sender_id,
|
||||
turn_id=request_ctx.turn_id,
|
||||
workspace=scope.project_path,
|
||||
# Injected input continues the active run's tool policy.
|
||||
workspace_scope=effective_scope,
|
||||
log_content=request_ctx.log_content,
|
||||
)
|
||||
blocks = await self._resolve_runtime_context_for_request(
|
||||
@@ -1197,6 +1202,7 @@ class AgentLoop:
|
||||
)
|
||||
request_ctx = dataclasses.replace(
|
||||
request_ctx,
|
||||
workspace_scope=effective_scope,
|
||||
log_content=(
|
||||
request_ctx.log_content and not ephemeral
|
||||
and (session is None or session.policy.log_content)
|
||||
|
||||
@@ -16,7 +16,7 @@ if TYPE_CHECKING:
|
||||
from nanobot.config.schema import ProviderConfig, ToolsConfig
|
||||
from nanobot.cron.service import CronService
|
||||
from nanobot.providers.factory import ProviderSnapshot
|
||||
from nanobot.security.workspace_access import WorkspaceSandboxStatus
|
||||
from nanobot.security.workspace_access import WorkspaceSandboxStatus, WorkspaceScope
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.utils.llm_runtime import LLMRuntime
|
||||
|
||||
@@ -44,6 +44,8 @@ class RequestContext:
|
||||
# The host can consume completion messages after this request returns.
|
||||
can_receive_background_results: bool = True
|
||||
persist_session: bool = True
|
||||
# Effective tool scope; injected inputs retain the active run's scope.
|
||||
workspace_scope: WorkspaceScope | None = None
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
|
||||
@@ -2,14 +2,22 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Protocol, TypeAlias, runtime_checkable
|
||||
|
||||
from nanobot.security.workspace_access import current_tool_workspace, workspace_sandbox_status
|
||||
from nanobot.runtime_context import RuntimeContextBlock, wrap_runtime_context_lines
|
||||
from nanobot.security.workspace_access import (
|
||||
WorkspaceSandboxStatus,
|
||||
WorkspaceScope,
|
||||
current_tool_workspace,
|
||||
workspace_sandbox_status,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.agent.tools.context import RequestContext
|
||||
from nanobot.agent.tools.shell import ExecToolConfig
|
||||
from nanobot.agent.tools.web import WebToolsConfig
|
||||
from nanobot.config.schema import ModelPresetConfig
|
||||
@@ -159,14 +167,43 @@ class AgentRuntimeControl:
|
||||
self.__scratchpad: dict[str, JsonValue] = {}
|
||||
self.__workspace_display: str | None = None
|
||||
|
||||
def snapshot(self) -> RuntimeSnapshot:
|
||||
def _workspace_sandbox(self, scope: WorkspaceScope | None = None) -> WorkspaceSandboxStatus:
|
||||
target = self.__target
|
||||
workspace = current_tool_workspace(
|
||||
target.workspace,
|
||||
restrict_to_workspace=target.restrict_to_workspace,
|
||||
sandbox_restricts_workspace=bool(target.exec_config.sandbox),
|
||||
scope=scope,
|
||||
)
|
||||
assert workspace.project_path is not None
|
||||
return workspace_sandbox_status(
|
||||
workspace=workspace.project_path,
|
||||
restrict_to_workspace=workspace.restrict_to_workspace,
|
||||
)
|
||||
|
||||
async def workspace_context(self, request: RequestContext) -> RuntimeContextBlock:
|
||||
"""Append current access facts without changing the reusable prompt prefix."""
|
||||
status = self._workspace_sandbox(request.workspace_scope)
|
||||
# A valid directory can contain newlines or prompt delimiters. Keep it data.
|
||||
root = json.dumps(status.workspace_root, ensure_ascii=False)
|
||||
root = root.replace("[", "\\u005b").replace("]", "\\u005d")
|
||||
lines = [
|
||||
f"Current project (JSON path): {root}",
|
||||
(
|
||||
"File access: limited to this project, plus tool-specific allowed paths."
|
||||
if status.restrict_to_workspace
|
||||
else "File access: not restricted to this project."
|
||||
),
|
||||
"OS permissions and tool-specific rules still apply.",
|
||||
]
|
||||
if self.__target.exec_config.sandbox:
|
||||
lines.append(
|
||||
"A shell sandbox is configured. Extra shell binds do not grant file-tool access."
|
||||
)
|
||||
return RuntimeContextBlock(source="workspace_access", content=wrap_runtime_context_lines(lines))
|
||||
|
||||
def snapshot(self) -> RuntimeSnapshot:
|
||||
target = self.__target
|
||||
return RuntimeSnapshot(
|
||||
model=target.model,
|
||||
model_preset=target.model_preset,
|
||||
@@ -184,10 +221,7 @@ class AgentRuntimeControl:
|
||||
web_config=_snapshot_web_config(target.web_config),
|
||||
exec_config=_snapshot_exec_config(target.exec_config),
|
||||
scratchpad=_snapshot_json_mapping(self.__scratchpad),
|
||||
workspace_sandbox=workspace_sandbox_status(
|
||||
workspace=workspace.project_path,
|
||||
restrict_to_workspace=workspace.restrict_to_workspace,
|
||||
).as_dict(),
|
||||
workspace_sandbox=self._workspace_sandbox().as_dict(),
|
||||
)
|
||||
|
||||
def set_model(self, model: str) -> LLMRuntime:
|
||||
|
||||
@@ -348,10 +348,11 @@ def current_tool_workspace(
|
||||
*,
|
||||
restrict_to_workspace: bool = False,
|
||||
sandbox_restricts_workspace: bool = False,
|
||||
scope: WorkspaceScope | None = None,
|
||||
) -> ToolWorkspace:
|
||||
"""Return the workspace/access policy for the current tool call."""
|
||||
"""Resolve tool policy from an explicit request scope or the bound call scope."""
|
||||
|
||||
scope = current_workspace_scope()
|
||||
scope = scope if scope is not None else current_workspace_scope()
|
||||
project_path = (
|
||||
scope.project_path
|
||||
if scope is not None
|
||||
|
||||
@@ -6,6 +6,19 @@ import time
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.agent.subagent_status import SubagentStatus
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.runtime_context import (
|
||||
RUNTIME_CONTEXT_HISTORY_META,
|
||||
RUNTIME_CONTEXT_MESSAGE_META,
|
||||
public_history_message,
|
||||
)
|
||||
|
||||
|
||||
def visible_message(message: dict) -> dict:
|
||||
"""Project raw runner or persisted messages without model-only context."""
|
||||
marker = message.get("_meta", {}).get(RUNTIME_CONTEXT_MESSAGE_META)
|
||||
if marker is not None:
|
||||
message = {**message, RUNTIME_CONTEXT_HISTORY_META: marker}
|
||||
return public_history_message(message)
|
||||
|
||||
|
||||
def save_completed_subagent(loop: AgentLoop, task_id: str, owner: str) -> None:
|
||||
|
||||
@@ -13,6 +13,7 @@ from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.config.schema import ChannelsConfig
|
||||
from nanobot.providers.base import LLMResponse
|
||||
from nanobot.runtime_context import public_history_message
|
||||
from nanobot.utils.document import reference_non_image_attachments
|
||||
|
||||
|
||||
@@ -109,7 +110,7 @@ async def test_document_reference_survives_session_reload(tmp_path: Path) -> Non
|
||||
persisted = loop.sessions.get_or_create(session_key)
|
||||
|
||||
assert [message["role"] for message in persisted.messages] == ["user"]
|
||||
assert persisted.messages[0]["content"] == (
|
||||
assert public_history_message(persisted.messages[0])["content"] == (
|
||||
f"review this\n\n[Attachment: {doc_path.resolve()}]"
|
||||
)
|
||||
assert "media" not in persisted.messages[0]
|
||||
|
||||
@@ -15,6 +15,7 @@ from nanobot.command import CommandContext
|
||||
from nanobot.config.schema import AgentDefaults, Config
|
||||
from nanobot.events import NO_EVENTS
|
||||
from nanobot.providers.base import LLMResponse
|
||||
from nanobot.runtime_context import public_history_message
|
||||
from nanobot.session.keys import HEARTBEAT_SESSION_KEY
|
||||
|
||||
|
||||
@@ -422,7 +423,7 @@ class TestAutoCompactIdleDetection:
|
||||
m["content"] == "old user 0"
|
||||
for m in session_after.get_history(max_messages=len(session_after.messages))
|
||||
)
|
||||
assert any(m["content"] == "new msg" for m in session_after.messages)
|
||||
assert any(public_history_message(m)["content"] == "new msg" for m in session_after.messages)
|
||||
await loop.aclose()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -692,9 +693,10 @@ class TestAutoCompactIntegration:
|
||||
"[Resumed Session]" in str(m.get("content", "")) for m in session_after.messages
|
||||
)
|
||||
assert resumed_system_prompt.count(overview) == 1
|
||||
# Runtime context end marker should NOT be persisted
|
||||
# Persisted model-only context must not leak into the public history.
|
||||
assert not any(
|
||||
"[/Runtime Context]" in str(m.get("content", "")) for m in session_after.messages
|
||||
"[/Runtime Context]" in str(public_history_message(m).get("content", ""))
|
||||
for m in session_after.messages
|
||||
)
|
||||
|
||||
# Pending summary should be consumed (one-shot)
|
||||
@@ -706,8 +708,8 @@ class TestAutoCompactIntegration:
|
||||
await loop.aclose()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_runtime_context_markers_not_persisted_for_multi_paragraph_turn(self, tmp_path):
|
||||
"""Auto-compact resume context must not leak runtime markers into persisted session history."""
|
||||
async def test_runtime_context_markers_hidden_for_multi_paragraph_turn(self, tmp_path):
|
||||
"""Auto-compact resume context must not leak runtime markers into public history."""
|
||||
loop = _make_loop(tmp_path, session_ttl_minutes=15)
|
||||
session = loop.sessions.get_or_create("cli:test")
|
||||
session.add_message("user", "old message")
|
||||
@@ -728,7 +730,7 @@ class TestAutoCompactIntegration:
|
||||
session_after = loop.sessions.get_or_create("cli:test")
|
||||
assert any(m.get("content") == "old message" for m in session_after.messages)
|
||||
for persisted in session_after.messages:
|
||||
content = str(persisted.get("content", ""))
|
||||
content = str(public_history_message(persisted).get("content", ""))
|
||||
assert "[Runtime Context" not in content
|
||||
assert "[/Runtime Context]" not in content
|
||||
await loop.aclose()
|
||||
|
||||
@@ -116,5 +116,6 @@ async def test_runner_checkpoint_keeps_current_user_as_replay_boundary(tmp_path:
|
||||
sent_text = "\n".join(str(message.get("content")) for message in sent_messages)
|
||||
assert "new question" in sent_text
|
||||
assert [message["role"] for message in sent_messages] == ["system", "user"]
|
||||
assert sent_messages[1]["content"] == "new question"
|
||||
assert sent_messages[1]["content"].startswith("new question\n\n")
|
||||
assert "File access:" in sent_messages[1]["content"]
|
||||
assert any(message.get("content") == "long older turn" for message in session.messages)
|
||||
@@ -76,7 +76,8 @@ async def test_runner_pressure_commits_summary_and_current_delta(tmp_path) -> No
|
||||
model_request = loop.provider.chat_stream_with_retry.await_args_list[1].kwargs["messages"]
|
||||
assert "Current checkpoint." in model_request[0]["content"]
|
||||
assert [message["role"] for message in model_request] == ["system", "user"]
|
||||
assert model_request[1]["content"] == "continue the task"
|
||||
assert model_request[1]["content"].startswith("continue the task\n\n")
|
||||
assert "File access: not restricted to this project." in model_request[1]["content"]
|
||||
|
||||
reloaded = loop.sessions.get_or_create("cli:test")
|
||||
assert reloaded.messages[0]["content"] == "old-user-0"
|
||||
@@ -84,7 +85,7 @@ async def test_runner_pressure_commits_summary_and_current_delta(tmp_path) -> No
|
||||
assert reloaded.messages[reloaded.last_archived]["content"] == (
|
||||
SUMMARY_CONTINUATION_TEXT
|
||||
)
|
||||
assert [message["content"] for message in reloaded.get_history()] == [
|
||||
assert [message["content"] for message in reloaded.get_history(include_runtime_context=False)] == [
|
||||
"continue the task",
|
||||
"done",
|
||||
]
|
||||
@@ -131,7 +132,8 @@ async def test_ephemeral_runner_pressure_summarizes_without_persisting(tmp_path)
|
||||
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"
|
||||
assert model_request[1]["content"].startswith("continue the task\n\n")
|
||||
assert "File access: not restricted to this project." in model_request[1]["content"]
|
||||
|
||||
reloaded = loop.sessions.get_or_create("cli:ephemeral")
|
||||
assert reloaded.messages[: len(original_messages)] == original_messages
|
||||
@@ -238,7 +240,7 @@ async def test_native_provider_compaction_commits_portable_terminal_checkpoint(
|
||||
accepted_contents = [message.get("content") for message in accepted]
|
||||
assert "accepted history" in accepted_contents
|
||||
assert "accepted answer" in accepted_contents
|
||||
assert "continue" in accepted_contents
|
||||
assert any(content.startswith("continue\n\n") for content in accepted_contents)
|
||||
assert "done" not in accepted_contents
|
||||
reloaded = loop.sessions.get_or_create("cli:native")
|
||||
assert reloaded.provider_state is None
|
||||
|
||||
@@ -903,7 +903,7 @@ class TestToolEventProgress:
|
||||
assert requests[0][-1]["content"].endswith("Background research completed")
|
||||
assert any(
|
||||
message.get("role") == "user"
|
||||
and message.get("content") == "Can you include the key detail?"
|
||||
and str(message.get("content")).startswith("Can you include the key detail?\n\n")
|
||||
for message in requests[1]
|
||||
)
|
||||
assert len(request_contexts) == 1
|
||||
|
||||
@@ -616,7 +616,7 @@ async def test_next_turn_after_llm_error_keeps_turn_boundary(tmp_path):
|
||||
session = loop.sessions.get_or_create("cli:test")
|
||||
assert [
|
||||
{key: value for key, value in message.items() if key in {"role", "content"}}
|
||||
for message in session.messages
|
||||
for message in map(public_history_message, session.messages)
|
||||
] == [
|
||||
{"role": "user", "content": "first question"},
|
||||
{"role": "assistant", "content": _PERSISTED_MODEL_ERROR_PLACEHOLDER},
|
||||
|
||||
@@ -7,7 +7,7 @@ from unittest.mock import AsyncMock, MagicMock
|
||||
import pytest
|
||||
from loguru import logger
|
||||
|
||||
from agent.session_helpers import run_session, save_completed_subagent
|
||||
from agent.session_helpers import run_session, save_completed_subagent, visible_message
|
||||
from nanobot.agent.context import ContextBuilder, TranscriptInput
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.agent.runner import AgentRunResult
|
||||
@@ -350,7 +350,7 @@ async def test_absolute_path_reaches_provider_as_chat(tmp_path, channel, content
|
||||
for message in request["messages"]
|
||||
)
|
||||
session = loop.sessions.get_or_create(f"{channel}:path")
|
||||
assert session.get_history()[0]["content"] == content
|
||||
assert session.get_history(include_runtime_context=False)[0]["content"] == content
|
||||
assert not session.messages[0].get("_command")
|
||||
finally:
|
||||
await loop.aclose()
|
||||
@@ -1102,7 +1102,7 @@ async def test_process_message_persists_user_message_before_turn_completes(tmp_p
|
||||
loop.sessions.invalidate("feishu:c1")
|
||||
persisted = loop.sessions.get_or_create("feishu:c1")
|
||||
assert [m["role"] for m in persisted.messages] == ["user"]
|
||||
assert persisted.messages[0]["content"] == "persist me"
|
||||
assert public_history_message(persisted.messages[0])["content"] == "persist me"
|
||||
assert persisted.metadata.get(AgentLoop._PENDING_USER_TURN_KEY) is True
|
||||
assert persisted.updated_at >= persisted.created_at
|
||||
|
||||
@@ -1376,7 +1376,7 @@ async def test_process_message_persists_media_paths_on_user_turn(tmp_path: Path)
|
||||
loop.sessions.invalidate("websocket:c-media")
|
||||
persisted = loop.sessions.get_or_create("websocket:c-media")
|
||||
assert [m["role"] for m in persisted.messages] == ["user"]
|
||||
assert persisted.messages[0]["content"] == "look"
|
||||
assert public_history_message(persisted.messages[0])["content"] == "look"
|
||||
assert persisted.messages[0]["media"] == [str(img_a), str(img_b)]
|
||||
|
||||
|
||||
@@ -1408,7 +1408,7 @@ async def test_process_message_persists_media_only_turn_without_text(tmp_path: P
|
||||
persisted = loop.sessions.get_or_create("websocket:c-images-only")
|
||||
assert len(persisted.messages) == 1
|
||||
assert persisted.messages[0]["role"] == "user"
|
||||
assert persisted.messages[0]["content"] == ""
|
||||
assert public_history_message(persisted.messages[0])["content"] == ""
|
||||
assert persisted.messages[0]["media"] == [str(img)]
|
||||
|
||||
|
||||
@@ -1434,7 +1434,7 @@ async def test_process_message_does_not_duplicate_early_persisted_user_message(t
|
||||
session = loop.sessions.get_or_create("feishu:c2")
|
||||
assert [
|
||||
{k: v for k, v in m.items() if k in {"role", "content"}}
|
||||
for m in session.messages
|
||||
for m in map(public_history_message, session.messages)
|
||||
] == [
|
||||
{"role": "user", "content": "hello"},
|
||||
{"role": "assistant", "content": "done"},
|
||||
@@ -1848,7 +1848,7 @@ async def test_next_turn_after_crash_closes_pending_user_turn_before_new_input(t
|
||||
session = loop.sessions.get_or_create("feishu:c3")
|
||||
assert [
|
||||
{k: v for k, v in m.items() if k in {"role", "content"}}
|
||||
for m in session.messages
|
||||
for m in map(public_history_message, session.messages)
|
||||
] == [
|
||||
{"role": "user", "content": "old question"},
|
||||
{"role": "assistant", "content": "Error: Task interrupted before a response was generated."},
|
||||
@@ -1947,7 +1947,7 @@ async def test_stop_preserves_runtime_checkpoint_for_next_turn(tmp_path: Path) -
|
||||
session = loop.sessions.get_or_create("feishu:c4")
|
||||
assert [
|
||||
{k: v for k, v in m.items() if k in {"role", "content", "tool_call_id", "name"}}
|
||||
for m in session.messages
|
||||
for m in map(public_history_message, session.messages)
|
||||
] == [
|
||||
{"role": "user", "content": "keep progress"},
|
||||
{"role": "assistant", "content": "working"},
|
||||
@@ -2422,7 +2422,7 @@ async def test_turn_after_unanswered_user_keeps_tool_call_pairing(tmp_path: Path
|
||||
initial_messages = _assembled_messages(loop.context, transcript_input)
|
||||
assert [m["role"] for m in initial_messages] == ["system", "user", "user"]
|
||||
assert initial_messages[-2]["content"] == "earlier question that never got an answer"
|
||||
assert initial_messages[-1]["content"] == "and another thing"
|
||||
assert visible_message(initial_messages[-1])["content"] == "and another thing"
|
||||
return _agent_run_result(
|
||||
"done",
|
||||
[
|
||||
|
||||
@@ -18,7 +18,7 @@ from nanobot.bus.events import (
|
||||
)
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequest
|
||||
from nanobot.runtime_context import RuntimeContextBlock
|
||||
from nanobot.runtime_context import RuntimeContextBlock, public_history_message
|
||||
from nanobot.session.keys import UNIFIED_SESSION_KEY
|
||||
from nanobot.session.manager import SessionPolicy
|
||||
from nanobot.webui.temporary_chats import WebUITemporaryChats
|
||||
@@ -282,7 +282,7 @@ async def test_transient_session_stays_outside_unified_session(tmp_path) -> None
|
||||
|
||||
await run_session(loop, _message(key, "private question"))
|
||||
|
||||
assert [message["content"] for message in transient.messages] == [
|
||||
assert [public_history_message(message)["content"] for message in transient.messages] == [
|
||||
"private question",
|
||||
"private answer",
|
||||
]
|
||||
|
||||
@@ -27,6 +27,7 @@ from nanobot.providers.base import (
|
||||
ToolCallRequest,
|
||||
)
|
||||
from nanobot.providers.conversation_state import ProviderConversationStateController
|
||||
from nanobot.runtime_context import public_history_message
|
||||
from nanobot.session.summary import SUMMARY_CONTINUATION_TEXT
|
||||
|
||||
_MAX_TOOL_RESULT_CHARS = AgentDefaults().max_tool_result_chars
|
||||
@@ -1028,7 +1029,7 @@ async def test_backfill_repairs_model_context_without_shifting_save_turn_boundar
|
||||
for key, value in message.items()
|
||||
if key in {"role", "content", "tool_call_id", "name", "tool_calls"}
|
||||
}
|
||||
for message in session_after.messages
|
||||
for message in map(public_history_message, session_after.messages)
|
||||
] == [
|
||||
{"role": "user", "content": "old user"},
|
||||
{
|
||||
|
||||
@@ -9,7 +9,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
|
||||
import pytest
|
||||
|
||||
from agent.runner_helpers import make_run_spec
|
||||
from agent.session_helpers import run_session
|
||||
from agent.session_helpers import run_session, visible_message
|
||||
from nanobot.agent.context import TranscriptInput
|
||||
from nanobot.agent.tools.context import RequestContext
|
||||
from nanobot.config.schema import AgentDefaults
|
||||
@@ -823,7 +823,7 @@ async def test_pending_injection_resolves_its_own_runtime_context(tmp_path):
|
||||
assert "telegram | group-1 | user-c | message-3" in str(model_messages)
|
||||
assert "Carol | topic-7" in str(model_messages)
|
||||
assert all(
|
||||
message["_meta"][RUNTIME_CONTEXT_MESSAGE_META]["sources"] == ["identity"]
|
||||
message["_meta"][RUNTIME_CONTEXT_MESSAGE_META]["sources"] == ["workspace_access", "identity"]
|
||||
for message in injected
|
||||
)
|
||||
|
||||
@@ -892,7 +892,7 @@ async def test_subagent_pending_injection_is_hidden_history_and_not_merged(tmp_p
|
||||
assert result.had_injections is True
|
||||
assert call_count["n"] == 2
|
||||
injected_users = [message for message in result.messages if message.get("role") == "user"][-2:]
|
||||
assert [message["content"] for message in injected_users] == ["visible follow-up", payload]
|
||||
assert [visible_message(message)["content"] for message in injected_users] == ["visible follow-up", payload]
|
||||
assert injected_users[1][HIDDEN_HISTORY_META] == {
|
||||
"kind": "subagent_result",
|
||||
"subagent_task_id": "sub-1",
|
||||
@@ -1283,7 +1283,7 @@ async def test_pending_queue_batches_full_snapshot_before_first_model_call(tmp_p
|
||||
for idx in range(total_followups):
|
||||
assert f"follow-up-{idx}" in flattened_user_content
|
||||
raw_followups = [
|
||||
message["content"]
|
||||
visible_message(message)["content"]
|
||||
for message in result.messages
|
||||
if message.get("role") == "user"
|
||||
and isinstance(message.get("content"), str)
|
||||
@@ -1416,7 +1416,7 @@ async def test_pending_snapshot_rolls_back_before_later_arrivals(tmp_path, cance
|
||||
else:
|
||||
result = await run
|
||||
user_content = [
|
||||
message["content"] for message in result.messages if message["role"] == "user"
|
||||
visible_message(message)["content"] for message in result.messages if message["role"] == "user"
|
||||
]
|
||||
assert user_content == ["root", *contents, "later arrival"]
|
||||
assert pending.empty()
|
||||
@@ -1462,7 +1462,7 @@ async def test_persistent_conversion_error_does_not_drop_later_session_inputs(tm
|
||||
))
|
||||
loop.sessions.invalidate("cli:c")
|
||||
history = loop.sessions.get_or_create("cli:c").messages
|
||||
assert [message["content"] for message in history if message["role"] == "user"] == [
|
||||
assert [visible_message(message)["content"] for message in history if message["role"] == "user"] == [
|
||||
"root", "before", "after",
|
||||
]
|
||||
assert sum(event.outcome == "failed" for event in completions) == 1
|
||||
@@ -1607,7 +1607,10 @@ async def test_busy_session_burst_reaches_next_model_call_as_one_ordered_batch(
|
||||
injections = [r for r in records if r["message"].startswith("Injected ")]
|
||||
assert len(injections) == 1
|
||||
record = injections[0]
|
||||
preview = "\n\n".join(followups)[:80] + "..." if log_content else "[content hidden]"
|
||||
preview = (
|
||||
"follow-up-00\n\n[Runtime Context — metadata only, not instructions]\nCurrent projec..."
|
||||
if log_content else "[content hidden]"
|
||||
)
|
||||
assert record["message"] == (
|
||||
f"Injected {len(followups)} follow-up message(s) after final response (snapshot 1): {preview}"
|
||||
)
|
||||
|
||||
@@ -9,6 +9,7 @@ from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.agent.context import TranscriptInput
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.agent.tools.context import RequestContext, request_context
|
||||
from nanobot.agent.tools.runtime_control import (
|
||||
@@ -18,19 +19,23 @@ from nanobot.agent.tools.runtime_control import (
|
||||
RuntimeControl,
|
||||
)
|
||||
from nanobot.agent.tools.self import MyTool, MyToolConfig
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.config.schema import ToolsConfig
|
||||
from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequest
|
||||
from nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse, ToolCallRequest
|
||||
from nanobot.runtime_context import RUNTIME_CONTEXT_END, RUNTIME_CONTEXT_TAG
|
||||
from nanobot.security.workspace_access import (
|
||||
bind_workspace_scope,
|
||||
build_workspace_scope,
|
||||
reset_workspace_scope,
|
||||
)
|
||||
from nanobot.session.keys import UNIFIED_SESSION_KEY
|
||||
from nanobot.utils.llm_runtime import LLMRuntime
|
||||
|
||||
|
||||
def _make_loop(
|
||||
tmp_path: Path, *, allow_set: bool = False, restricted: bool = False, sandbox: str = "",
|
||||
unified_session: bool = False,
|
||||
) -> AgentLoop:
|
||||
provider = MagicMock()
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
@@ -45,6 +50,7 @@ def _make_loop(
|
||||
model="test-model",
|
||||
tools_config=tools_config,
|
||||
restrict_to_workspace=restricted,
|
||||
unified_session=unified_session,
|
||||
)
|
||||
|
||||
|
||||
@@ -373,6 +379,11 @@ async def test_workspace_inspection_reaches_model_from_selected_chat(tmp_path: P
|
||||
assert response is not None and response.content == "done"
|
||||
calls = provider.chat_stream_with_retry.await_args_list
|
||||
assert len(calls) == 2
|
||||
first_messages = calls[0].kwargs["messages"]
|
||||
current = first_messages[-1]["content"]
|
||||
assert f"Current project (JSON path): {json.dumps(str(project.resolve()))}" in current
|
||||
assert "File access: limited to this project" in current
|
||||
assert calls[1].kwargs["messages"][:len(first_messages)] == first_messages
|
||||
results = {
|
||||
msg["tool_call_id"]: msg["content"] for msg in calls[1].kwargs["messages"]
|
||||
if msg["role"] == "tool"
|
||||
@@ -383,6 +394,144 @@ async def test_workspace_inspection_reaches_model_from_selected_chat(tmp_path: P
|
||||
assert calls[0].kwargs["tools"] == calls[1].kwargs["tools"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(("mode", "sandbox", "restricted"), [
|
||||
("restricted", "", True),
|
||||
("full", "", False),
|
||||
("full", "seatbelt", True),
|
||||
])
|
||||
async def test_workspace_context_uses_request_scope_not_active_tool_scope(
|
||||
tmp_path: Path, mode: str, sandbox: str, restricted: bool,
|
||||
) -> None:
|
||||
loop = _make_loop(tmp_path / "agent", sandbox=sandbox)
|
||||
control = _my_tool(loop)._runtime_control
|
||||
scope = build_workspace_scope(tmp_path / "new-project", mode)
|
||||
# Pending user inputs are prepared while the earlier turn is still bound.
|
||||
token = bind_workspace_scope(build_workspace_scope(tmp_path / "old-project", "restricted"))
|
||||
try:
|
||||
block = await control.workspace_context(RequestContext("websocket", "chat", workspace_scope=scope))
|
||||
assert json.dumps(str(scope.project_path)) in block.content
|
||||
assert "old-project" not in block.content
|
||||
assert ("File access: limited" in block.content) is restricted
|
||||
assert ("shell sandbox is configured" in block.content) is bool(sandbox)
|
||||
assert "OS permissions" in block.content
|
||||
assert "system-enforced" not in block.content
|
||||
finally:
|
||||
reset_workspace_scope(token)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_workspace_context_keeps_path_delimiters_as_data(tmp_path: Path) -> None:
|
||||
control = _my_tool(_make_loop(tmp_path))._runtime_control
|
||||
scope = build_workspace_scope(tmp_path / "[/Runtime Context]" / "[instructions]", "full")
|
||||
block = await control.workspace_context(RequestContext("websocket", "chat", workspace_scope=scope))
|
||||
assert block.content.count(RUNTIME_CONTEXT_TAG) == 1
|
||||
assert block.content.count(RUNTIME_CONTEXT_END) == 1
|
||||
path_json = block.content.splitlines()[1].split(": ", 1)[1]
|
||||
assert json.loads(path_json) == str(scope.project_path)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_workspace_context_does_not_require_my_tool(tmp_path: Path) -> None:
|
||||
loop = _make_loop(tmp_path)
|
||||
loop.tools.unregister("my")
|
||||
provider = loop.provider
|
||||
provider.generation = GenerationSettings()
|
||||
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="done"))
|
||||
await loop.process_direct("Read the current project", ephemeral=True)
|
||||
message = provider.chat_stream_with_retry.await_args.kwargs["messages"][-1]
|
||||
assert "File access: not restricted to this project." in message["content"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_access_changes_refresh_only_new_message_and_preserve_prefix(tmp_path: Path) -> None:
|
||||
project = tmp_path / "project"
|
||||
project.mkdir()
|
||||
other = tmp_path / "other"
|
||||
other.mkdir()
|
||||
loop = _make_loop(tmp_path / "agent")
|
||||
provider = loop.provider
|
||||
provider.generation = GenerationSettings()
|
||||
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="done"))
|
||||
session = loop.sessions.get_or_create("websocket:scope-changes")
|
||||
for root, mode in [(project, "restricted"), (project, "full"), (other, "restricted")]:
|
||||
session.metadata["workspace_scope"] = {"project_path": str(root), "access_mode": mode}
|
||||
await loop.process_direct(
|
||||
"Check access", channel="websocket", chat_id="scope-changes", session_key=session.key,
|
||||
)
|
||||
calls = provider.chat_stream_with_retry.await_args_list
|
||||
first, second, third = [LLMProvider._sanitize_empty_content(call.kwargs["messages"]) for call in calls]
|
||||
# Access changes belong to the new request, not a rewrite of the cached history.
|
||||
assert json.dumps(second[:len(first)]) == json.dumps(first)
|
||||
assert "File access: limited" in first[-1]["content"]
|
||||
assert "File access: not restricted" in second[-1]["content"]
|
||||
assert json.dumps(str(other.resolve())) in third[-1]["content"]
|
||||
assert json.dumps(str(project.resolve())) not in third[-1]["content"]
|
||||
assert all(call.kwargs["tools"] == calls[0].kwargs["tools"] for call in calls)
|
||||
assert all(message["content"] == "Check access" for message in session.get_history(
|
||||
include_runtime_context=False,
|
||||
) if message["role"] == "user")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_injected_channel_input_reports_active_tool_scope(tmp_path: Path) -> None:
|
||||
project = tmp_path / "project"
|
||||
project.mkdir()
|
||||
(project / "marker.txt").write_text("active project", encoding="utf-8")
|
||||
loop = _make_loop(tmp_path / "agent", unified_session=True)
|
||||
loop.provider.generation = GenerationSettings()
|
||||
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=[
|
||||
LLMResponse(content=None, tool_calls=[
|
||||
ToolCallRequest(id="read", name="read_file", arguments={"path": "marker.txt"}),
|
||||
]),
|
||||
LLMResponse(content="done"),
|
||||
])
|
||||
session = loop.sessions.get_or_create(UNIFIED_SESSION_KEY)
|
||||
session.metadata["workspace_scope"] = {"project_path": str(project), "access_mode": "restricted"}
|
||||
pending = asyncio.Queue()
|
||||
await pending.put(InboundMessage("telegram", "user", "chat", "Read marker.txt"))
|
||||
await loop._run_agent_loop(
|
||||
TranscriptInput(history=[{"role": "user", "content": "Start"}], current_message=None),
|
||||
runtime=loop.llm_runtime(), session=session, pending_queue=pending,
|
||||
request_context=RequestContext("websocket", "chat", session_key=session.key),
|
||||
)
|
||||
calls = loop.provider.chat_stream_with_retry.await_args_list
|
||||
context = calls[0].kwargs["messages"][-1]["content"]
|
||||
assert json.dumps(str(project.resolve())) in context
|
||||
assert "File access: limited" in context
|
||||
assert any(message.get("role") == "tool" and "active project" in message["content"]
|
||||
for message in calls[1].kwargs["messages"])
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("trigger", ["idle", "new"])
|
||||
async def test_workspace_context_compaction_reuses_serialized_prefix(tmp_path: Path, trigger: str) -> None:
|
||||
loop = _make_loop(tmp_path)
|
||||
provider = loop.provider
|
||||
provider.generation = GenerationSettings()
|
||||
provider.estimate_prompt_tokens.return_value = (100, "test")
|
||||
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="done"))
|
||||
await loop.process_direct("Check access", session_key="cli:context")
|
||||
first = provider.chat_stream_with_retry.await_args.kwargs
|
||||
session = loop.sessions.get_or_create("cli:context")
|
||||
if trigger == "idle":
|
||||
await loop.consolidator.compact_idle_session(session.key, runtime=loop.llm_runtime())
|
||||
else:
|
||||
await loop.consolidator.archive_session(
|
||||
session, archive_end=len(session.messages), runtime=loop.llm_runtime(),
|
||||
)
|
||||
compact = provider.chat_stream_with_retry.await_args.kwargs
|
||||
first_wire = LLMProvider._sanitize_empty_content(first["messages"])
|
||||
compact_wire = LLMProvider._sanitize_empty_content(compact["messages"])
|
||||
assert len(compact_wire) > len(first_wire)
|
||||
assert json.dumps(compact_wire[:len(first_wire)]) == json.dumps(first_wire)
|
||||
assert compact["tools"] == first["tools"]
|
||||
await loop.process_direct("Check again", session_key=session.key)
|
||||
current = provider.chat_stream_with_retry.await_args.kwargs["messages"][-1]["content"]
|
||||
assert current.count("Current project (JSON path):") == 1
|
||||
assert "File access: not restricted to this project." in current
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def runtime() -> LLMRuntime:
|
||||
return LLMRuntime(MagicMock(), "test", GenerationSettings(), 128_000)
|
||||
|
||||
Reference in new issue
Block a user