Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion astrbot/core/agent/runners/tool_loop_agent_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@
from ..output import OutputComponent, PlainOutput, ReasoningOutput
from ..response import AgentResponse, AgentStats
from ..run_context import ContextWrapper, TContext
from ..tool_executor import BaseFunctionToolExecutor
from ..tool_executor import CURRENT_TOOL_CALL_ID, BaseFunctionToolExecutor
from .base import AgentState, BaseAgentRunner

if sys.version_info >= (3, 12):
Expand Down Expand Up @@ -2074,6 +2074,7 @@ async def _recorded_tool_results(
)
self._tool_execution_started = True
executor = None
call_token = CURRENT_TOOL_CALL_ID.set(call_id)
try:
detach = getattr(self.tool_executor, "detach", None)
executor = self._iter_tool_executor_results(
Expand Down Expand Up @@ -2141,6 +2142,7 @@ async def _recorded_tool_results(
error = RuntimeErrorInfo(code=type(exc).__name__, message=str(exc))
raise
finally:
CURRENT_TOOL_CALL_ID.reset(call_token)
if executor is not None:
await self._close_executor(executor)
if self._events.active:
Expand Down
7 changes: 7 additions & 0 deletions astrbot/core/agent/tool_executor.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
import asyncio
from collections.abc import AsyncGenerator
from contextvars import ContextVar
from typing import Any, Generic

import mcp

from .run_context import ContextWrapper, TContext
from .tool import FunctionTool

# ID of the tool call being executed, set by the runner around execute() so
# executors can refer to the call (e.g. an approval prompt for it).
CURRENT_TOOL_CALL_ID: ContextVar[str | None] = ContextVar(
"current_tool_call_id", default=None
)


class BaseFunctionToolExecutor(Generic[TContext]):
@classmethod
Expand Down
5 changes: 5 additions & 0 deletions astrbot/core/agent_wakeup.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ async def wake_main_agent(
agent_session: "AgentSessionRef | None" = None,
tool_result: "tuple[str, CallToolResult] | None" = None,
source_event: "AstrMessageEvent | None" = None,
permission_mode: str | None = None,
) -> None:
"""Queue a triggered user turn without waiting for agent execution.

Expand All @@ -40,6 +41,8 @@ async def wake_main_agent(
agent_session: Original runtime conversation when selection must not drift.
tool_result: Tool name and typed output, kept separate from trigger instructions.
source_event: Original caller identity and restrictions for background work.
permission_mode: ChatUI permission mode the run keeps from the
conversation that scheduled it ("workspace" narrows Local access).

Raises:
ValueError: If the source or target session is invalid,
Expand Down Expand Up @@ -67,4 +70,6 @@ async def wake_main_agent(
)
if stop_signal is not None:
event.set_extra("_background_stop_signal", stop_signal)
if permission_mode:
event.set_extra("permission_mode", permission_mode)
await ctx.get_event_queue().put(event)
10 changes: 10 additions & 0 deletions astrbot/core/astr_agent_runtime/computer/booters/local.py
Original file line number Diff line number Diff line change
Expand Up @@ -714,6 +714,7 @@ async def write_session(
requester_is_admin: bool,
session_id: str,
chars: str,
require_sandboxed: bool = False,
) -> dict[str, Any]:
"""Write text to the stdin pipe of a managed shell session.

Expand All @@ -723,6 +724,9 @@ async def write_session(
requester_is_admin: Whether the requester is an administrator.
session_id: Managed shell session identifier.
chars: Text to write verbatim.
require_sandboxed: The requester's current policy needs process
isolation, so a session started without it (e.g. before the
conversation was narrowed) must not take input.

Returns:
Current process status after the write.
Expand All @@ -742,6 +746,12 @@ async def write_session(
or session.process.stdin is None
):
raise ValueError(f"Shell session {session_id} is not accepting input.")
if require_sandboxed and not session.sandboxed:
raise ValueError(
f"Shell session {session_id} was started with wider access than "
"this conversation now allows, so it does not accept input. "
"Start a new shell session."
)
session.process.stdin.write(chars.encode("utf-8"))
await session.process.stdin.drain()
return {
Expand Down
73 changes: 73 additions & 0 deletions astrbot/core/astr_agent_runtime/permission_mode.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
"""Live ChatUI permission mode per conversation.

A ChatUI message carries the conversation's permission mode, but sub-agents
and later tool calls of a turn keep running with that message's event after
the user changes the mode (in the input bar or with "Allow for this
conversation"). The mode is therefore also kept here per WebChat
conversation, so every tool call reads the current choice. Unattended runs
(scheduled tasks, background wakeups) never take "full" or
"workspace_no_ask" from here: they may only be narrowed to "workspace".
"""

from astrbot.core.platform.agent_wakeup_event import AgentWakeupEvent

PERMISSION_MODES = ("workspace", "workspace_no_ask", "ask", "full")
# Modes that confine Local access to the conversation workspace.
WORKSPACE_MODES = ("workspace", "workspace_no_ask")
# Modes that skip approval prompts in attended ChatUI runs. "workspace_no_ask"
# is what "Don't ask again in this conversation" turns workspace into: no
# prompts, same confined access.
NO_ASK_MODES = ("full", "workspace_no_ask")

# WebChat session ID (``webchat!<user>!<conversation>``) -> current mode.
_conversation_modes: dict[str, str] = {}


def conversation_key(username: str, session_id: str) -> str:
"""Return the WebChat session ID of a user's conversation or thread.

Args:
username: Dashboard user who owns the conversation.
session_id: ChatUI conversation or thread ID.

Returns:
The event session ID, ``webchat!<user>!<conversation>``.
"""
return f"webchat!{username}!{session_id}"


def set_conversation_permission_mode(session_id: str, mode: str | None) -> None:
"""Record the mode the user chose for a ChatUI conversation.

Args:
session_id: WebChat session ID, ``webchat!<user>!<conversation>``.
mode: One of PERMISSION_MODES; anything else forgets the choice.
"""
if mode in PERMISSION_MODES:
_conversation_modes[session_id] = mode
else:
_conversation_modes.pop(session_id, None)


def get_permission_mode(event) -> str | None:
"""Return the permission mode that applies to a tool call now.

Args:
event: The event the tool call runs with.

Returns:
One of PERMISSION_MODES, or None (ask as configured). Unattended
runs only ever get "workspace" or None.
"""
# The local permission policy calls this for every tool context, and
# plugin-made or minimal events may lack these attributes.
get_extra = getattr(event, "get_extra", None)
mode = get_extra("permission_mode") if callable(get_extra) else None
get_platform_name = getattr(event, "get_platform_name", None)
live = None
if callable(get_platform_name) and get_platform_name() == "webchat":
live = _conversation_modes.get(getattr(event, "session_id", None) or "")
if isinstance(event, AgentWakeupEvent):
narrowed = mode in WORKSPACE_MODES or live in WORKSPACE_MODES
return "workspace" if narrowed else None
return live or mode
Loading
Loading