From 0e9815f91110c7dea7b5b0406016a35631307b03 Mon Sep 17 00:00:00 2001 From: Turino Date: Thu, 26 Nov 2026 15:09:14 +1000 Subject: [PATCH 1/4] feat: approve listed tools before they run, with per-conversation permission modes Tools listed in agent.config.misc.tool_approval.tools wait for the requester's approval before FunctionToolExecutor runs them, so sub-agents are covered too. Only the requester (or a scheduled task's creator) can answer; wakeups never do. Approving a future_task create/edit also grants its listed tools when it runs on schedule. ChatUI requests gain one path for per-conversation options: WEBCHAT_CHAT_OPTIONS and resolve_webchat_chat_options() validate them, the ChatOptions request model carries them for send, regenerate, thread and WebSocket requests, and the WebChat adapter puts them on the event. The first option is the permission mode (workspace, workspace_no_ask, ask, full): modes only narrow the role's local policy, follow changes live through PUT /api/v1/chat/sessions/{id}/permission-mode, and never pass full access or a waiver to scheduled tasks. ActionRow gains optional single_use, title, detail and tool_call_id fields for WebChat, and an approval_result chunk records the applied outcome. --- .../agent/runners/tool_loop_agent_runner.py | 4 +- astrbot/core/agent/tool_executor.py | 7 + astrbot/core/agent_wakeup.py | 5 + .../computer/booters/local.py | 10 + .../astr_agent_runtime/permission_mode.py | 73 +++ .../core/astr_agent_runtime/tool_approval.py | 419 ++++++++++++++++++ .../core/astr_agent_runtime/tool_executor.py | 8 + .../tools/computer_tools/shell.py | 7 +- .../tools/computer_tools/util.py | 14 + .../astr_agent_runtime/tools/cron_tools.py | 31 ++ astrbot/core/config/agent_runner.py | 1 + astrbot/core/config/default.py | 16 + astrbot/core/cron/manager.py | 4 + astrbot/core/i18n.py | 20 + astrbot/core/message/components.py | 17 + .../sources/webchat/message_parts_helper.py | 2 + .../platform/sources/webchat/request_flags.py | 29 ++ .../sources/webchat/webchat_adapter.py | 23 +- .../platform/sources/webchat/webchat_event.py | 11 +- astrbot/dashboard/api/chat.py | 39 ++ astrbot/dashboard/schemas.py | 16 +- astrbot/dashboard/services/chat_service.py | 45 +- .../dashboard/services/live_chat_service.py | 2 + .../src/api/generated/openapi-v1/sdk.gen.ts | 13 +- .../src/api/generated/openapi-v1/types.gen.ts | 23 + .../en-US/features/config-metadata.json | 9 + .../ja-JP/features/config-metadata.json | 9 + .../ru-RU/features/config-metadata.json | 9 + .../zh-CN/features/config-metadata.json | 9 + docs/en/dev/openapi-scopes.md | 1 + docs/public/openapi.json | 65 +++ docs/zh/dev/openapi-scopes.md | 1 + openspec/openapi-v1.yaml | 40 ++ 33 files changed, 973 insertions(+), 9 deletions(-) create mode 100644 astrbot/core/astr_agent_runtime/permission_mode.py create mode 100644 astrbot/core/astr_agent_runtime/tool_approval.py diff --git a/astrbot/core/agent/runners/tool_loop_agent_runner.py b/astrbot/core/agent/runners/tool_loop_agent_runner.py index d62befcf3e..0a59df541e 100644 --- a/astrbot/core/agent/runners/tool_loop_agent_runner.py +++ b/astrbot/core/agent/runners/tool_loop_agent_runner.py @@ -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): @@ -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( @@ -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: diff --git a/astrbot/core/agent/tool_executor.py b/astrbot/core/agent/tool_executor.py index 5061bf0662..cf39e9465c 100644 --- a/astrbot/core/agent/tool_executor.py +++ b/astrbot/core/agent/tool_executor.py @@ -1,5 +1,6 @@ import asyncio from collections.abc import AsyncGenerator +from contextvars import ContextVar from typing import Any, Generic import mcp @@ -7,6 +8,12 @@ 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 diff --git a/astrbot/core/agent_wakeup.py b/astrbot/core/agent_wakeup.py index 9458865803..34d65b7ef1 100644 --- a/astrbot/core/agent_wakeup.py +++ b/astrbot/core/agent_wakeup.py @@ -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. @@ -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, @@ -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) diff --git a/astrbot/core/astr_agent_runtime/computer/booters/local.py b/astrbot/core/astr_agent_runtime/computer/booters/local.py index 1f40451b23..0f01d90822 100644 --- a/astrbot/core/astr_agent_runtime/computer/booters/local.py +++ b/astrbot/core/astr_agent_runtime/computer/booters/local.py @@ -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. @@ -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. @@ -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 { diff --git a/astrbot/core/astr_agent_runtime/permission_mode.py b/astrbot/core/astr_agent_runtime/permission_mode.py new file mode 100644 index 0000000000..a5ae3ea762 --- /dev/null +++ b/astrbot/core/astr_agent_runtime/permission_mode.py @@ -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!!``) -> 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!!``. + """ + 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!!``. + 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 diff --git a/astrbot/core/astr_agent_runtime/tool_approval.py b/astrbot/core/astr_agent_runtime/tool_approval.py new file mode 100644 index 0000000000..8e5b26f12a --- /dev/null +++ b/astrbot/core/astr_agent_runtime/tool_approval.py @@ -0,0 +1,419 @@ +"""Ask a person to approve listed tools before they run. + +Tools listed in ``agent.config.misc.tool_approval.tools`` wait for the +requester's approval: a card with buttons in ChatUI, buttons where the +platform supports them, and a reply code everywhere. Approving the creation or +edit of a scheduled task (``future_task``) also approves the listed tools the +task uses when it later runs unattended. ChatUI's per-conversation permission +modes (see ``permission_mode.py``) can skip the prompt: "full" and +"workspace_no_ask" for everything except scheduled tasks, "workspace" for the +Local tools it actually confines. +""" + +import asyncio +import json +import secrets + +from astrbot import logger +from astrbot.core.agent.run_context import ContextWrapper +from astrbot.core.agent.tool_executor import CURRENT_TOOL_CALL_ID +from astrbot.core.astr_agent_runtime.context import AstrAgentContext +from astrbot.core.astr_agent_runtime.permission_mode import ( + NO_ASK_MODES, + WORKSPACE_MODES, + get_permission_mode, + set_conversation_permission_mode, +) +from astrbot.core.astr_agent_runtime.tools.computer_tools.util import ( + is_local_runtime, +) +from astrbot.core.astr_agent_runtime.tools.cron_tools import ( + TASK_APPROVAL_GRANTED, + TOOL_APPROVAL_GRANT_KEY, +) +from astrbot.core.i18n import translate +from astrbot.core.message.components import ActionRow, Button, Json, Plain +from astrbot.core.message.message_event_result import MessageChain +from astrbot.core.platform.agent_wakeup_event import AgentWakeupEvent +from astrbot.core.utils.config_number import coerce_int_config +from astrbot.core.utils.session_lock import session_lock_manager +from astrbot.core.utils.session_waiter import FILTERS, SessionFilter, SessionWaiter + +# Action ID of the approve and reject buttons; the "allow for this +# conversation" button (ChatUI only) has its own so the client can switch the +# conversation to full access. +TOOL_APPROVAL_ACTION_ID = "astrbot_tool_approval" +TOOL_APPROVAL_CONVERSATION_ACTION_ID = "astrbot_tool_approval_conversation" +SCHEDULED_TASK_TOOL = "future_task" +# Local tools that "workspace" mode confines to the conversation workspace. +WORKSPACE_CONFINED_TOOLS = frozenset( + { + "astrbot_file_read_tool", + "astrbot_file_write_tool", + "astrbot_file_edit_tool", + "astrbot_grep_tool", + "astrbot_execute_shell", + "astrbot_shell_session", + "astrbot_execute_python", + } +) +# The user must see everything they approve: text platforms show at most this +# many characters of arguments and say how many are hidden; a scheduled task +# (an unattended grant) is never asked about with hidden arguments, and +# arguments above the maximum are refused everywhere. +APPROVAL_TEXT_ARGS_CHARS = 1500 +APPROVAL_MAX_ARGS_CHARS = 100_000 +APPROVAL_TITLE_NAME_CHARS = 40 + + +class _ToolApprovalFilter(SessionFilter): + """Match approval replies by session and sender, not by the whole group.""" + + def filter(self, event) -> str: + # Wakeups (a scheduled task firing, a sub-agent result) share the + # session and sender of the conversation but are not the user's + # answer; they must not resolve a pending approval. + if isinstance(event, AgentWakeupEvent): + return "tool_approval:unattended" + return f"tool_approval:{event.unified_msg_origin}:{event.get_sender_id()}" + + +async def check_tool_approval( + tool, run_context: ContextWrapper[AstrAgentContext], tool_args: dict +) -> str | None: + """Ask the requester to approve a listed tool before it runs. + + Args: + tool: The tool the model wants to call. + run_context: The current agent run context. + tool_args: The arguments the tool would receive. + + Returns: + None if the tool may run, otherwise the reason (shown to the model) + why it was not executed. + """ + event = run_context.context.event + ctx = run_context.context.context + approval_config = ( + ctx.get_config(umo=event.unified_msg_origin if event else None) + .get("agent", {}) + .get("config", {}) + .get("misc", {}) + .get("tool_approval", {}) + ) + grants_task = tool.name == SCHEDULED_TASK_TOOL and tool_args.get("action") in ( + "create", + "edit", + ) + if tool.name == SCHEDULED_TASK_TOOL: + # Cleared on every call so a grant never outlives its own approval. + TASK_APPROVAL_GRANTED.set(False) + if tool.name not in (approval_config.get("tools") or []): + return None + if not event: + return f"error: Tool {tool.name} needs approval, but no user can be asked." + + # The conversation's current mode, which follows changes made after this + # run started (sub-agents keep the event of the turn that spawned them). + unattended = isinstance(event, AgentWakeupEvent) + mode = get_permission_mode(event) + if ( + mode in WORKSPACE_MODES + and tool.name in WORKSPACE_CONFINED_TOOLS + # Only the Local runtime is narrowed (get_local_permission_policy + # confines its files to the workspace in these modes). + and is_local_runtime(run_context) + ): + return None + # No-ask modes never grant a scheduled task's unattended runs by themselves + # (unattended runs never get these modes; see get_permission_mode). + if mode in NO_ASK_MODES and not unattended and not grants_task: + return None + + approver_id = event.get_sender_id() + if unattended: + # A scheduled task asks the user who created it, or runs freely if + # its creation was approved; a grant cannot spread to further tasks. + job = None + if event.source == "cron" and event.source_id: + job = await ctx.cron_manager.db.get_cron_job(event.source_id) + payload = job.payload if job and isinstance(job.payload, dict) else {} + if ( + payload.get(TOOL_APPROVAL_GRANT_KEY) is True + and tool.name != SCHEDULED_TASK_TOOL + ): + return None + approver_id = payload.get("sender_id") + if not approver_id: + return ( + f"error: Tool {tool.name} needs user approval, but this " + "unattended run has no user to ask, so it was not executed." + ) + + is_webchat = event.get_platform_name() == "webchat" + args_text = json.dumps(tool_args, ensure_ascii=False, default=str) + if len(args_text) > APPROVAL_MAX_ARGS_CHARS or ( + grants_task and not is_webchat and len(args_text) > APPROVAL_TEXT_ARGS_CHARS + ): + return ( + f"error: Tool {tool.name} was not executed because its arguments " + f"({len(args_text)} characters) are too long to show for approval. " + "Split the work into smaller calls or shorten the arguments." + ) + timeout = coerce_int_config( + approval_config.get("timeout", 120), + default=120, + min_value=1, + field_name="agent.config.misc.tool_approval.timeout", + ) + tool_call_id = CURRENT_TOOL_CALL_ID.get() + + async def deliver(message: MessageChain) -> None: + # A background sub-agent may ask after its turn's reply stream closed; + # ChatUI then gets the message as a proactive one. + delivered = await event.send(message) + if is_webchat and delivered is False: + if not await ctx.send_message(event.unified_msg_origin, message): + raise RuntimeError("Approval delivery failed") + + session_id = f"tool_approval:{event.unified_msg_origin}:{approver_id}" + # A session ID holds one waiter, so concurrent requests take turns. + async with session_lock_manager.acquire_lock(session_id): + # While this call waited, "Don't ask again" on another card or a mode + # change may already cover it. + if ( + not unattended + and not grants_task + and get_permission_mode(event) in NO_ASK_MODES + ): + return None + code = f"{secrets.randbelow(10000):04d}" + prompt = _approval_prompt( + event, + await ctx.get_locale(event.unified_msg_origin), + tool.name, + tool_args, + code, + timeout, + grants_task, + unattended, + ) + allow_conversation = False + try: + approved, allow_conversation = await _wait_for_answer( + session_id, code, timeout, deliver(prompt) + ) + except TimeoutError: + outcome = "expired" + reason = ( + f"error: Tool {tool.name} was not executed because the approval " + "request timed out. Do not retry unless the user asks." + ) + except Exception as exc: + logger.warning(f"Failed to deliver tool approval: {exc}") + return ( + f"error: Tool {tool.name} was not executed because we cannot ask " + f"the user for approval. Approval delivery failed: {exc}" + ) + else: + outcome = "approved" if approved else "rejected" + reason = ( + None + if approved + else f"error: The user rejected tool {tool.name}, so it was not " + "executed. Do not retry unless the user asks." + ) + + if is_webchat and tool_call_id: + # ChatUI marks the card with what was actually decided: a click can + # arrive after the request ended and change nothing. Only an open + # stream can update the card; a proactive save would store the + # result as a text message. + try: + await event.send( + MessageChain( + type="approval_result", + chain=[ + Json(data={"tool_call_id": tool_call_id, "outcome": outcome}) + ], + ) + ) + except Exception as exc: + logger.warning(f"Failed to report the approval outcome: {exc}") + if outcome == "approved": + if grants_task: + TASK_APPROVAL_GRANTED.set(True) + if allow_conversation: + # Everything in this conversation, including queued calls and + # running sub-agents, now runs without asking. It never widens + # access: a workspace conversation stays confined. + no_ask = ( + "workspace_no_ask" + if get_permission_mode(event) in WORKSPACE_MODES + else "full" + ) + event.set_extra("permission_mode", no_ask) + set_conversation_permission_mode(event.session_id, no_ask) + return reason + + +def _approval_prompt( + event, + locale: str, + tool_name: str, + tool_args: dict, + code: str, + timeout: int, + grants_task: bool, + unattended: bool, +) -> MessageChain: + """Build the approval prompt: a card in ChatUI, text and buttons elsewhere. + + Args: + event: The event the tool call runs with. + locale: Reply language of the session (``Context.get_locale``). + tool_name: The tool asking to run. + tool_args: Its arguments. + code: Reply code that approves this request. + timeout: Seconds the request stays valid. + grants_task: Whether approving grants a scheduled task's later runs. + unattended: Whether the request comes from an unattended run. + + Returns: + The message to send. + """ + + def text(key: str, **params) -> str: + return translate(f"tool_approval_{key}", locale, **params) + + if grants_task: + # The model chooses the name: keep the title one short line. + name = " ".join(str(tool_args.get("name") or "").split()) + if len(name) > APPROVAL_TITLE_NAME_CHARS: + name = name[:APPROVAL_TITLE_NAME_CHARS] + "…" + title = text("task_title", name=name) if name else text("task_title_unnamed") + notice = text("task_notice") + else: + title = text("tool_title", tool=tool_name) + notice = "" + args_text = json.dumps(tool_args, ensure_ascii=False, default=str) + if len(args_text) > APPROVAL_TEXT_ARGS_CHARS: + args_text = args_text[:APPROVAL_TEXT_ARGS_CHARS] + text( + "args_cut", + total=len(args_text), + hidden=len(args_text) - APPROVAL_TEXT_ARGS_CHARS, + ) + prompt_text = f"{title}\n{notice}{text('args')}{args_text}\n" + text( + "how_to", code=code, timeout=timeout + ) + buttons = [ + Button( + id=TOOL_APPROVAL_ACTION_ID, + label=text("allow"), + style=Button.Style.SUCCESS, + action=Button.CallbackAction(data={"code": code, "approve": True}), + ), + Button( + id=TOOL_APPROVAL_ACTION_ID, + label=text("deny"), + style=Button.Style.DANGER, + action=Button.CallbackAction(data={"code": code, "approve": False}), + ), + ] + if event.get_platform_name() != "webchat": + return MessageChain( + chain=[ + Plain(prompt_text), + ActionRow(buttons=buttons, action_timeout=timeout, single_use=True), + ] + ) + if not unattended: + # Only ChatUI keeps a per-conversation mode to switch to, and an + # unattended run must not widen its own permissions. + buttons.insert( + 1, + Button( + id=TOOL_APPROVAL_CONVERSATION_ACTION_ID, + label=text("allow_conversation"), + style=Button.Style.PRIMARY, + action=Button.CallbackAction(data={"code": code, "approve": True}), + ), + ) + # One card with the full arguments folded in a scrollable detail. + return MessageChain( + chain=[ + ActionRow( + buttons=buttons, + action_timeout=timeout, + single_use=True, + title=title, + detail=notice + + json.dumps(tool_args, ensure_ascii=False, default=str, indent=2), + tool_call_id=CURRENT_TOOL_CALL_ID.get(), + fallback_text=prompt_text, + ) + ] + ) + + +async def _wait_for_answer( + session_id: str, code: str, timeout: int, send_prompt +) -> tuple[bool, bool]: + """Send the prompt and wait for the approver's reply or click. + + The waiter is keyed by the approver rather than the waiting event (for + a scheduled task it is the task's creator), so the ``session_waiter`` + decorator, which derives the key from the event, does not fit. + + Args: + session_id: Waiter key, ``tool_approval::``. + code: Reply code that approves this request. + timeout: Seconds to wait. + send_prompt: Coroutine sending the prompt. + + Returns: + ``(approved, allow_conversation)``. + + Raises: + TimeoutError: If nobody answered in time. + Exception: If the prompt could not be delivered. + """ + session_filter = _ToolApprovalFilter() + FILTERS.append(session_filter) + waiter = SessionWaiter(session_filter, session_id, False) + allow_conversation = False + + async def on_reply(controller, reply) -> None: + nonlocal allow_conversation + interaction = reply.get_button_interaction() + if interaction is None: + approved = reply.message_str.strip() == code + else: + # The code ties a click to this request, so a button left over + # from an earlier request cannot approve this one. + data = interaction.data if isinstance(interaction.data, dict) else {} + approved = ( + interaction.action_id + in (TOOL_APPROVAL_ACTION_ID, TOOL_APPROVAL_CONVERSATION_ACTION_ID) + and data.get("code") == code + and data.get("approve") is True + ) + allow_conversation = ( + approved + and interaction.action_id == TOOL_APPROVAL_CONVERSATION_ACTION_ID + ) + controller.future.set_result(approved) + + def on_sent(task: asyncio.Task) -> None: + if not task.cancelled() and task.exception(): + waiter.session_controller.stop(task.exception()) + + # register_wait runs up to its first suspension before this task starts, + # so even an immediate reply finds the waiter registered. + send_task = asyncio.create_task(send_prompt) + send_task.add_done_callback(on_sent) + try: + approved = await waiter.register_wait(on_reply, timeout) + finally: + send_task.cancel() + return approved, allow_conversation diff --git a/astrbot/core/astr_agent_runtime/tool_executor.py b/astrbot/core/astr_agent_runtime/tool_executor.py index daf05e06d3..66139815b9 100644 --- a/astrbot/core/astr_agent_runtime/tool_executor.py +++ b/astrbot/core/astr_agent_runtime/tool_executor.py @@ -19,6 +19,7 @@ from astrbot.core.agent.tool_executor import BaseFunctionToolExecutor from astrbot.core.agent_wakeup import wake_main_agent from astrbot.core.astr_agent_runtime.context import AstrAgentContext +from astrbot.core.astr_agent_runtime.tool_approval import check_tool_approval from astrbot.core.astr_agent_runtime.tools.computer_tools import ( CuaKeyboardTypeTool, CuaMouseClickTool, @@ -247,6 +248,13 @@ async def execute(cls, tool, run_context, **tool_args): AsyncGenerator[None | mcp.types.CallToolResult, None] """ + denied = await check_tool_approval(tool, run_context, tool_args) + if denied: + yield mcp.types.CallToolResult( + content=[mcp.types.TextContent(type="text", text=denied)] + ) + return + if isinstance(tool, HandoffTool): is_bg = tool_args.pop("background_task", False) # Caller-owned outputs must settle before the turn's stream closes. diff --git a/astrbot/core/astr_agent_runtime/tools/computer_tools/shell.py b/astrbot/core/astr_agent_runtime/tools/computer_tools/shell.py index 4d3822ac78..7d3db7525f 100644 --- a/astrbot/core/astr_agent_runtime/tools/computer_tools/shell.py +++ b/astrbot/core/astr_agent_runtime/tools/computer_tools/shell.py @@ -373,7 +373,7 @@ async def call( Returns: JSON session operation result or a user-facing error. """ - _, permission_error = check_local_execution_permission( + local_policy, permission_error = check_local_execution_permission( context, "Shell session management", ) @@ -426,6 +426,11 @@ async def call( requester_is_admin=requester_is_admin, session_id=session_id, chars=f"{chars}\n" if action == "write_line" else chars, + # A permission mode change (e.g. ChatUI "workspace") + # also applies to sessions opened before it. + require_sandboxed=bool( + local_policy and local_policy.requires_sandbox + ), ) result = await sb.shell.poll_session( owner_id=owner_id, diff --git a/astrbot/core/astr_agent_runtime/tools/computer_tools/util.py b/astrbot/core/astr_agent_runtime/tools/computer_tools/util.py index 6ead8015bf..25ac945151 100644 --- a/astrbot/core/astr_agent_runtime/tools/computer_tools/util.py +++ b/astrbot/core/astr_agent_runtime/tools/computer_tools/util.py @@ -9,6 +9,10 @@ get_process_sandbox_status, ) from astrbot.core.astr_agent_runtime.context import AstrAgentContext +from astrbot.core.astr_agent_runtime.permission_mode import ( + WORKSPACE_MODES, + get_permission_mode, +) from astrbot.core.config.default import get_local_permission_defaults from astrbot.core.db import BaseDatabase from astrbot.core.utils.astrbot_path import get_astrbot_workspaces_path @@ -113,6 +117,7 @@ def get_local_permission_policy( umo=context.context.event.unified_msg_origin ) provider_settings = cfg.get("provider_settings", {}) + inspected_role = role role = ( "admin" if (role or get_agent_permissions(context).role) == "admin" @@ -133,6 +138,15 @@ def get_local_permission_policy( filesystem_scope = role_policy.get("filesystem_scope", defaults["filesystem_scope"]) if filesystem_scope not in {"none", "workspace", "host"}: filesystem_scope = defaults["filesystem_scope"] + # ChatUI "workspace" permission mode can only narrow the configured access: + # host files become workspace-only, which also puts execution under process + # isolation. Inspecting another role's policy is unaffected. + if ( + inspected_role is None + and filesystem_scope == "host" + and get_permission_mode(context.context.event) in WORKSPACE_MODES + ): + filesystem_scope = "workspace" allow_execution = ( filesystem_scope != "none" and role_policy.get("allow_execution", defaults["allow_execution"]) is True diff --git a/astrbot/core/astr_agent_runtime/tools/cron_tools.py b/astrbot/core/astr_agent_runtime/tools/cron_tools.py index 08c0cf30b0..e063ca9052 100644 --- a/astrbot/core/astr_agent_runtime/tools/cron_tools.py +++ b/astrbot/core/astr_agent_runtime/tools/cron_tools.py @@ -1,3 +1,4 @@ +from contextvars import ContextVar from datetime import datetime from datetime import timezone as dt_timezone from typing import Any @@ -11,9 +12,23 @@ from astrbot.core.agent.runtime import get_agent_permissions from astrbot.core.agent.tool import FunctionTool, ToolExecResult from astrbot.core.astr_agent_runtime.context import AstrAgentContext +from astrbot.core.astr_agent_runtime.permission_mode import ( + WORKSPACE_MODES, + get_permission_mode, +) from astrbot.core.cron.manager import CronJobSchedulingError from astrbot.core.platform.message_type import MessageType +# Set by the approval gate for the one future_task call it approved; the +# gate and the tool run in the same task, while concurrent calls (sub-agents +# share the event) have their own context. +# Job payload key recording that a scheduled task's creation or last edit was +# approved, so its unattended runs use listed tools without asking. +TOOL_APPROVAL_GRANT_KEY = "tool_approval_granted" +TASK_APPROVAL_GRANTED: ContextVar[bool] = ContextVar( + "task_approval_granted", default=False +) + def _extract_job_session(job: Any) -> str | None: payload = getattr(job, "payload", None) @@ -131,7 +146,13 @@ async def call( "note": note, "origin": "tool", "allow_admin_role": get_agent_permissions(context).is_admin, + # Set by the approval gate when the user approved this task. + TOOL_APPROVAL_GRANT_KEY: TASK_APPROVAL_GRANTED.get(), } + if get_permission_mode(context.context.event) in WORKSPACE_MODES: + # Runs later with the same narrowed access as the ChatUI + # conversation it was created in. + payload["permission_mode"] = "workspace" tz_name = str( context.context.context.get_config( @@ -243,6 +264,16 @@ async def call( return f"Deleted cron job {job_id}." payload = dict(job.payload) if isinstance(job.payload, dict) else {} + # An edit keeps unattended approval only if this edit was approved + # (by whoever edits it, e.g. a group admin); a missing key means + # no grant, so an unapproved edit leaves the payload as it was. + if TASK_APPROVAL_GRANTED.get(): + payload[TOOL_APPROVAL_GRANT_KEY] = True + else: + payload.pop(TOOL_APPROVAL_GRANT_KEY, None) + # An edit may narrow the task's access but never widens it. + if get_permission_mode(context.context.event) in WORKSPACE_MODES: + payload["permission_mode"] = "workspace" updates: dict[str, Any] = {} if "name" in kwargs: diff --git a/astrbot/core/config/agent_runner.py b/astrbot/core/config/agent_runner.py index b8c04894cc..eb6c96a392 100644 --- a/astrbot/core/config/agent_runner.py +++ b/astrbot/core/config/agent_runner.py @@ -32,6 +32,7 @@ "tool_schema_mode": "full", "tool_call_timeout": 120, "sanitize_context_by_modalities": False, + "tool_approval": {"tools": [], "timeout": 120}, }, }, "dify": { diff --git a/astrbot/core/config/default.py b/astrbot/core/config/default.py index 538a8b4e2d..8f6b6f0d24 100644 --- a/astrbot/core/config/default.py +++ b/astrbot/core/config/default.py @@ -4422,6 +4422,22 @@ def get_local_permission_defaults(system: str | None = None) -> dict: "agent.runtime": "astrbot", }, }, + "agent.config.misc.tool_approval.tools": { + "description": "需要审批的工具", + "type": "list", + "items": {"type": "string"}, + "hint": "名单内的工具执行前需要发起人点击「允许」或回复确认码。留空表示不审批。批准创建或修改定时任务时,也会批准该任务到点运行时用到的名单内工具。", + "condition": { + "agent.runtime": "astrbot", + }, + }, + "agent.config.misc.tool_approval.timeout": { + "description": "工具审批超时时间(秒)", + "type": "int", + "condition": { + "agent.runtime": "astrbot", + }, + }, "agent.config.misc.tool_schema_mode": { "description": "工具调用模式", "type": "string", diff --git a/astrbot/core/cron/manager.py b/astrbot/core/cron/manager.py index e89af67505..8f1ed3a05b 100644 --- a/astrbot/core/cron/manager.py +++ b/astrbot/core/cron/manager.py @@ -489,6 +489,10 @@ async def _run_active_agent_job(self, job: CronJob, start_time: datetime) -> Non cron_job=json.dumps(extras["cron_job"], ensure_ascii=False) ), role=role, + # Only the narrowing ChatUI mode is carried over to the run. + permission_mode=( + "workspace" if payload.get("permission_mode") == "workspace" else None + ), ) diff --git a/astrbot/core/i18n.py b/astrbot/core/i18n.py index 5e6c63b06d..e136c643c8 100644 --- a/astrbot/core/i18n.py +++ b/astrbot/core/i18n.py @@ -20,6 +20,16 @@ "invalid_param_type": "参数 {name} 类型错误。完整参数: {params}", "command_no_params": "无参数指令", "command_group_help": "参数不足。{group} 指令组下有如下指令,请参考:\n{tree}", + "tool_approval_task_title": "定时任务「{name}」请求批准", + "tool_approval_task_title_unnamed": "定时任务请求批准", + "tool_approval_task_notice": "批准后,任务到点会自动执行,审批名单内的工具不再逐项询问。\n", + "tool_approval_tool_title": "工具 {tool} 请求执行", + "tool_approval_how_to": "点击按钮或回复 {code} 批准,发送其他内容则取消({timeout} 秒内有效)", + "tool_approval_args": "参数:", + "tool_approval_args_cut": "\n……(参数共 {total} 字符,后面 {hidden} 字符未显示;看不到全部内容时请拒绝)", + "tool_approval_allow": "允许", + "tool_approval_allow_conversation": "本对话不再询问", + "tool_approval_deny": "拒绝", }, "en-US": { "tool_call": "🔨 Calling tool: {name}", @@ -37,6 +47,16 @@ "invalid_param_type": "Invalid type for parameter {name}. Full parameters: {params}", "command_no_params": "No parameters", "command_group_help": "Missing parameters. Available commands in group {group}:\n{tree}", + "tool_approval_task_title": 'Scheduled task "{name}" needs approval', + "tool_approval_task_title_unnamed": "Scheduled task needs approval", + "tool_approval_task_notice": "If approved, the task runs on schedule and approval-listed tools are not asked about again.\n", + "tool_approval_tool_title": "Tool {tool} wants to run", + "tool_approval_how_to": "Click a button or reply {code} to approve; anything else cancels (valid for {timeout} s)", + "tool_approval_args": "Arguments: ", + "tool_approval_args_cut": "\n... ({hidden} of {total} characters not shown; deny if you cannot see everything you are approving)", + "tool_approval_allow": "Allow", + "tool_approval_allow_conversation": "Don't ask again in this conversation", + "tool_approval_deny": "Deny", }, } diff --git a/astrbot/core/message/components.py b/astrbot/core/message/components.py index 5838baa3c9..8021c10d37 100644 --- a/astrbot/core/message/components.py +++ b/astrbot/core/message/components.py @@ -228,6 +228,15 @@ class ActionRow(BaseMessageComponent): buttons: list[Button] fallback_text: str | None = None action_timeout: float | None = Field(default=None, gt=0, allow_inf_nan=False) + # Hint that the row asks for one answer, so a client may lock it after a click. + single_use: bool = False + # Optional card text for clients that can render one: a heading and + # secondary text the client may keep collapsed. + title: str | None = None + detail: str | None = None + # Tool call this row asks about, so a client can mark that call as + # waiting for approval. + tool_call_id: str | None = None _action_expires_at: float | None = PrivateAttr(default=None) @property @@ -254,6 +263,14 @@ def toDict(self) -> dict: data["fallback_text"] = self.fallback_text if self.action_timeout is not None: data["action_timeout"] = self.action_timeout + if self.single_use: + data["single_use"] = True + if self.title is not None: + data["title"] = self.title + if self.detail is not None: + data["detail"] = self.detail + if self.tool_call_id is not None: + data["tool_call_id"] = self.tool_call_id return {"type": "actionrow", "data": data} diff --git a/astrbot/core/platform/sources/webchat/message_parts_helper.py b/astrbot/core/platform/sources/webchat/message_parts_helper.py index 285cbf2719..284c2399d6 100644 --- a/astrbot/core/platform/sources/webchat/message_parts_helper.py +++ b/astrbot/core/platform/sources/webchat/message_parts_helper.py @@ -572,6 +572,8 @@ async def message_chain_to_storage_message_parts( if isinstance(comp, ActionRow): row_data = comp.toDict()["data"] + if comp.action_expires_at is not None: + row_data["expires_at"] = comp.action_expires_at for button, serialized_button in zip( comp.buttons, row_data["buttons"], diff --git a/astrbot/core/platform/sources/webchat/request_flags.py b/astrbot/core/platform/sources/webchat/request_flags.py index 8248bce01a..0038b62c0c 100644 --- a/astrbot/core/platform/sources/webchat/request_flags.py +++ b/astrbot/core/platform/sources/webchat/request_flags.py @@ -1,5 +1,8 @@ +from collections.abc import Callable from typing import Any +from astrbot.core.astr_agent_runtime.permission_mode import PERMISSION_MODES + WEBCHAT_REQUEST_FLAG_DEFAULTS = { "enable_inline_genui": True, "enable_default_system_prompt": True, @@ -7,6 +10,16 @@ "enable_reasoning": True, } +# Per-conversation ChatUI options: the dashboard stores them per conversation +# and sends them with every request (send, regenerate, thread, WebSocket). The +# WebChat adapter puts each one on the event as an extra of the same name. +# To add an option, add its validator here and its field to ``ChatOptions`` in +# ``astrbot/dashboard/schemas.py`` (and the OpenAPI spec). +WEBCHAT_CHAT_OPTIONS: dict[str, Callable[[Any], bool]] = { + # Permission mode; see astrbot/core/astr_agent_runtime/permission_mode.py. + "permission_mode": lambda value: value in PERMISSION_MODES, +} + def resolve_webchat_request_flags(payload: dict[str, Any]) -> dict[str, bool]: """Resolve supported WebChat flags with legacy top-level fallbacks. @@ -29,3 +42,19 @@ def resolve_webchat_request_flags(payload: dict[str, Any]) -> dict[str, bool]: value = payload.get(key) resolved[key] = value if isinstance(value, bool) else default return resolved + + +def resolve_webchat_chat_options(payload: dict[str, Any]) -> dict[str, Any]: + """Resolve the per-conversation ChatUI options carried by a request. + + Args: + payload: Incoming WebChat request or queue payload. + + Returns: + Every supported option; missing or invalid values are None, so the + configured behavior applies. + """ + return { + key: value if is_valid(value := payload.get(key)) else None + for key, is_valid in WEBCHAT_CHAT_OPTIONS.items() + } diff --git a/astrbot/core/platform/sources/webchat/webchat_adapter.py b/astrbot/core/platform/sources/webchat/webchat_adapter.py index fc53d8f54b..3c270c42c2 100644 --- a/astrbot/core/platform/sources/webchat/webchat_adapter.py +++ b/astrbot/core/platform/sources/webchat/webchat_adapter.py @@ -7,6 +7,9 @@ from astrbot import logger from astrbot.core import db_helper +from astrbot.core.astr_agent_runtime.permission_mode import ( + set_conversation_permission_mode, +) from astrbot.core.db.po import PlatformMessageHistory from astrbot.core.message.components import InteractiveView from astrbot.core.message.interactive_ui import view_store @@ -26,7 +29,10 @@ message_chain_to_storage_message_parts, parse_webchat_message_parts, ) -from .request_flags import resolve_webchat_request_flags +from .request_flags import ( + resolve_webchat_chat_options, + resolve_webchat_request_flags, +) from .webchat_event import WebChatMessageEvent from .webchat_queue_mgr import WebChatQueueMgr, webchat_queue_mgr @@ -139,6 +145,9 @@ async def send_by_session( f"[WebChatAdapter] Failed to save proactive message: {e}", exc_info=True, ) + # Nobody would see an unsaved message: fail the send so callers + # (e.g. a tool approval request) do not wait for an answer. + raise await super().send_by_session(session, message_chain) return @@ -165,6 +174,7 @@ async def send_by_session( f"[WebChatAdapter] Failed to save proactive message: {e}", exc_info=True, ) + raise await super().send_by_session(session, message_chain) @@ -329,6 +339,17 @@ def create_event(self, message: AstrBotMessage) -> WebChatMessageEvent: "selected_provider", payload.get("selected_provider") ) message_event.set_extra("selected_model", payload.get("selected_model")) + for key, value in resolve_webchat_chat_options(payload).items(): + message_event.set_extra(key, value) + # Sub-agents and queued calls of this conversation follow the + # mode of its latest message (a thread keeps its own). Requests + # that do not state a mode (button clicks in threads, plugin + # view actions, other clients) must not reset it. + if "permission_mode" in payload: + set_conversation_permission_mode( + message_event.session_id, + message_event.get_extra("permission_mode"), + ) message_event.set_extra("action_type", payload.get("action_type")) message_event.set_extra("turn_id", payload.get("turn_id")) message_event.set_extra( diff --git a/astrbot/core/platform/sources/webchat/webchat_event.py b/astrbot/core/platform/sources/webchat/webchat_event.py index a7b4b6d9e5..8e98dee90e 100644 --- a/astrbot/core/platform/sources/webchat/webchat_event.py +++ b/astrbot/core/platform/sources/webchat/webchat_event.py @@ -3,6 +3,7 @@ import json import os import shutil +import time from pathlib import Path, PurePosixPath from astrbot.api import logger @@ -113,6 +114,11 @@ async def _send( return None elif isinstance(comp, ActionRow): row_data = comp.toDict()["data"] + if comp.action_expires_at is not None: + row_data["expires_at"] = comp.action_expires_at + row_data["expires_in"] = max( + 0, comp.action_expires_at - time.time() + ) for button, serialized_button in zip( comp.buttons, row_data["buttons"], @@ -225,7 +231,7 @@ async def _send( return data - async def send(self, message: MessageChain | None) -> None: + async def send(self, message: MessageChain | None) -> bool: message_id = self.message_obj.message_id follow_up_capture = self.get_extra("_follow_up_captured") if message is None and isinstance(follow_up_capture, dict): @@ -239,13 +245,14 @@ async def send(self, message: MessageChain | None) -> None: "message_id": message_id, }, ) - await WebChatMessageEvent._send( + delivered = await WebChatMessageEvent._send( message_id, message, session_id=self.get_extra("view_session_id", self.session_id), history_platform_id=self.get_extra("view_history_platform_id", "webchat"), ) await super().send(message if message is not None else MessageChain([])) + return delivered is not None async def send_typing(self) -> None: """Emit a run-start signal before an independent LLM request.""" diff --git a/astrbot/dashboard/api/chat.py b/astrbot/dashboard/api/chat.py index 97dd899719..d6554e54ee 100644 --- a/astrbot/dashboard/api/chat.py +++ b/astrbot/dashboard/api/chat.py @@ -8,6 +8,10 @@ from fastapi import APIRouter, Depends, File, Form, Query, Request, UploadFile from fastapi.responses import FileResponse, JSONResponse, StreamingResponse +from astrbot.core.astr_agent_runtime.permission_mode import ( + conversation_key, + set_conversation_permission_mode, +) from astrbot.core.message.components import UIInteraction, ViewContext from astrbot.core.message.interactive_ui import ViewActionRequest, ViewError, view_store from astrbot.dashboard.async_utils import run_maybe_async @@ -15,6 +19,7 @@ from astrbot.dashboard.schemas import ( ChatMessagePatchRequest, ChatMessageRegenerateRequest, + ChatPermissionModeRequest, ChatSessionBatchDeleteRequest, ChatSessionPatchRequest, ChatThreadCreateRequest, @@ -458,6 +463,40 @@ async def update_chat_session( ) +@router.put("/chat/sessions/{session_id}/permission-mode") +async def set_chat_permission_mode( + session_id: str, + payload: ChatPermissionModeRequest, + auth: AuthContext = Depends(require_chat_scope), + service: ChatService = Depends(get_service), +): + """Apply a ChatUI permission mode change to work already running. + + Sub-agents and later tool calls of a running turn read the mode at each + call, so the change takes effect from their next tool call. + + Args: + session_id: The caller's own WebChat conversation ID. + payload: The newly selected mode. + auth: Authenticated dashboard user. + service: Session storage used to verify ownership. + + Returns: + OK, or 403 if the conversation is not the caller's WebChat session. + """ + session = await service.db.get_platform_session_by_id(session_id) + if ( + session is None + or session.creator != auth.username + or session.platform_id != "webchat" + ): + return JSONResponse(error("Session unavailable"), status_code=403) + set_conversation_permission_mode( + conversation_key(auth.username, session_id), payload.mode + ) + return ok({"mode": payload.mode}) + + @router.delete("/chat/sessions/{session_id}") async def delete_chat_session( session_id: str, diff --git a/astrbot/dashboard/schemas.py b/astrbot/dashboard/schemas.py index 747dbb7c2a..b615826e04 100644 --- a/astrbot/dashboard/schemas.py +++ b/astrbot/dashboard/schemas.py @@ -153,7 +153,19 @@ class ChatFlags(BaseModel): enable_reasoning: bool = True -class ChatMessageRegenerateRequest(OpenModel): +class ChatOptions(OpenModel): + """Per-conversation ChatUI options; see ``resolve_webchat_chat_options``.""" + + permission_mode: Literal["workspace", "workspace_no_ask", "ask", "full"] | None = ( + None + ) + + +class ChatPermissionModeRequest(OpenModel): + mode: Literal["workspace", "workspace_no_ask", "ask", "full"] + + +class ChatMessageRegenerateRequest(ChatOptions): locale: str | None = None selected_provider: str | None = None selected_model: str | None = None @@ -167,7 +179,7 @@ class ChatThreadCreateRequest(OpenModel): selected_text: str -class ChatThreadMessageRequest(OpenModel): +class ChatThreadMessageRequest(ChatOptions): locale: str | None = None message: Any selected_provider: str | None = None diff --git a/astrbot/dashboard/services/chat_service.py b/astrbot/dashboard/services/chat_service.py index 75fd2e8bdd..3b6e66d18e 100644 --- a/astrbot/dashboard/services/chat_service.py +++ b/astrbot/dashboard/services/chat_service.py @@ -5,6 +5,7 @@ import os import re import sqlite3 +import time import uuid from collections.abc import AsyncIterator from copy import deepcopy @@ -14,6 +15,10 @@ from typing import Any from astrbot.core import logger, sp +from astrbot.core.astr_agent_runtime.permission_mode import ( + conversation_key, + set_conversation_permission_mode, +) from astrbot.core.core_lifecycle import AstrBotCoreLifecycle from astrbot.core.db import BaseDatabase from astrbot.core.db.conversation import ContextUnavailableError @@ -26,6 +31,7 @@ webchat_message_parts_have_content, ) from astrbot.core.platform.sources.webchat.request_flags import ( + resolve_webchat_chat_options, resolve_webchat_request_flags, ) from astrbot.core.platform.sources.webchat.webchat_queue_mgr import webchat_queue_mgr @@ -116,6 +122,12 @@ def normalize_reasoning_message_parts( if not isinstance(part, dict): continue copied = dict(part) + if copied.get("type") == "actionrow" and isinstance( + copied.get("expires_at"), (int, float) + ): + # The client anchors the deadline on its own clock (see + # webchat_event): send the time left, not only the server time. + copied["expires_in"] = max(0, copied["expires_at"] - time.time()) if copied.get("type") == "reasoning": copied = {"type": "think", "think": copied.get("text", "")} parts.append(copied) @@ -212,6 +224,18 @@ def add_plain( self._store_tool_call_result(result_text) return result_text + if chain_type == "approval_result": + # Record the backend's decision on the approval card it belongs to. + result = self._parse_json_object(result_text) or {} + for part in self.parts: + if ( + part.get("type") == "actionrow" + and part.get("tool_call_id") + and part.get("tool_call_id") == result.get("tool_call_id") + ): + part["outcome"] = result.get("outcome") + return result_text + if chain_type == "reasoning": self._flush_pending_text() self._append_think_part(result_text) @@ -447,8 +471,19 @@ def serialize_history_entry(history) -> dict: Dict with all model fields plus created_at/updated_at serialized as UTC-aware ISO strings (e.g. ``2026-07-06T04:00:00+00:00``). """ + serialized = history.model_dump() + content = serialized.get("content") + parts = content.get("message") if isinstance(content, dict) else None + for part in parts if isinstance(parts, list) else []: + # Time left on a button deadline, recomputed whenever history is served. + if ( + isinstance(part, dict) + and part.get("type") == "actionrow" + and isinstance(part.get("expires_at"), (int, float)) + ): + part["expires_in"] = max(0, part["expires_at"] - time.time()) return { - **history.model_dump(), + **serialized, "created_at": to_utc_isoformat(history.created_at), "updated_at": to_utc_isoformat(history.updated_at), } @@ -913,6 +948,7 @@ async def delete_threads_by_ids(self, thread_ids: list[str], creator: str) -> No ) webchat_queue_mgr.remove_queues(thread_id) self.running_convs.pop(thread_id, None) + set_conversation_permission_mode(conversation_key(creator, thread_id), None) async def save_bot_message( self, @@ -1366,6 +1402,7 @@ async def build_chat_stream( session_id = post_data.get("session_id", post_data.get("conversation_id")) selected_provider = post_data.get("selected_provider") selected_model = post_data.get("selected_model") + chat_options = resolve_webchat_chat_options(post_data) flags = resolve_webchat_request_flags(post_data) platform_history_id = post_data.get("_platform_history_id") or "webchat" thread_selected_text = post_data.get("_thread_selected_text") @@ -1475,6 +1512,7 @@ async def build_chat_stream( "message": message_parts, "selected_provider": selected_provider, "selected_model": selected_model, + **chat_options, "selected_stt_provider": post_data.get("selected_stt_provider"), "selected_tts_provider": post_data.get("selected_tts_provider"), "persona_prompt": post_data.get("persona_prompt"), @@ -1571,6 +1609,9 @@ async def delete_session_internal(self, session, username: str) -> None: if session.platform_id == "webchat": webchat_queue_mgr.remove_queues(session_id) + set_conversation_permission_mode( + conversation_key(username, session_id), None + ) await self.db.delete_platform_session(session_id) await asyncio.to_thread( @@ -2029,6 +2070,7 @@ async def prepare_thread_chat_payload(self, username: str, data: dict) -> dict: "locale": data.get("locale"), "selected_provider": data.get("selected_provider"), "selected_model": data.get("selected_model"), + **resolve_webchat_chat_options(data), "_platform_history_id": "webchat_thread", "_thread_selected_text": thread.selected_text, "_skip_user_history": is_button_interaction, @@ -2207,6 +2249,7 @@ async def prepare_regenerate_message_payload( "locale": data.get("locale"), "selected_provider": data.get("selected_provider"), "selected_model": data.get("selected_model"), + **resolve_webchat_chat_options(data), "_skip_user_history": True, "_turn_id": replacement.turn_id, } diff --git a/astrbot/dashboard/services/live_chat_service.py b/astrbot/dashboard/services/live_chat_service.py index 3c2a78305b..34839fd4e4 100644 --- a/astrbot/dashboard/services/live_chat_service.py +++ b/astrbot/dashboard/services/live_chat_service.py @@ -22,6 +22,7 @@ create_attachment_part_from_existing_file, ) from astrbot.core.platform.sources.webchat.request_flags import ( + resolve_webchat_chat_options, resolve_webchat_request_flags, ) from astrbot.core.platform.sources.webchat.webchat_queue_mgr import webchat_queue_mgr @@ -543,6 +544,7 @@ async def handle_chat_message( "session_id": session_id, "message": payload, "flags": resolve_webchat_request_flags(message), + **resolve_webchat_chat_options(message), **{ key: message.get(key) for key in ( diff --git a/dashboard/src/api/generated/openapi-v1/sdk.gen.ts b/dashboard/src/api/generated/openapi-v1/sdk.gen.ts index cb1110f275..9b0f7c0237 100644 --- a/dashboard/src/api/generated/openapi-v1/sdk.gen.ts +++ b/dashboard/src/api/generated/openapi-v1/sdk.gen.ts @@ -1,7 +1,7 @@ // This file is auto-generated by @hey-api/openapi-ts import { createClient, createConfig, type OptionsLegacyParser, formDataBodySerializer } from '@hey-api/client-axios'; -import type { LoginData, LoginError, LoginResponse, LogoutError, LogoutResponse, GetAuthSetupStatusError, GetAuthSetupStatusResponse, SetupAuthData, SetupAuthError, SetupAuthResponse, SetupTotpData, SetupTotpError, SetupTotpResponse, RecoverTotpError, RecoverTotpResponse, UpdateAuthAccountData, UpdateAuthAccountError, UpdateAuthAccountResponse, ListApiKeysError, ListApiKeysResponse, CreateApiKeyData, CreateApiKeyError, CreateApiKeyResponse, RevokeApiKeyData, RevokeApiKeyError, RevokeApiKeyResponse, DeleteApiKeyData, DeleteApiKeyError, DeleteApiKeyResponse, GetSystemConfigSchemaError, GetSystemConfigSchemaResponse, GetSystemConfigError, GetSystemConfigResponse, UpdateSystemConfigData, UpdateSystemConfigError, UpdateSystemConfigResponse, GetSystemConfigRuntimeError, GetSystemConfigRuntimeResponse, GetConfigProfileSchemaError, GetConfigProfileSchemaResponse, ListConfigProfilesError, ListConfigProfilesResponse, CreateConfigProfileData, CreateConfigProfileError, CreateConfigProfileResponse, GetConfigProfileData, GetConfigProfileError, GetConfigProfileResponse, UpdateConfigProfileContentData, UpdateConfigProfileContentError, UpdateConfigProfileContentResponse, RenameConfigProfileData, RenameConfigProfileError, RenameConfigProfileResponse, DeleteConfigProfileData, DeleteConfigProfileError, DeleteConfigProfileResponse, ListConfigRoutesError, ListConfigRoutesResponse, ReplaceConfigRoutesData, ReplaceConfigRoutesError, ReplaceConfigRoutesResponse, UpsertConfigRouteData, UpsertConfigRouteError, UpsertConfigRouteResponse, DeleteConfigRouteData, DeleteConfigRouteError, DeleteConfigRouteResponse, ListBotTypesError, ListBotTypesResponse, RegisterBotTypeData, RegisterBotTypeError, RegisterBotTypeResponse, ListBotsData, ListBotsError, ListBotsResponse, CreateBotData, CreateBotError, CreateBotResponse, ListBotStatsError, ListBotStatsResponse, GetBotByIdData, GetBotByIdError, GetBotByIdResponse, UpdateBotByIdData, UpdateBotByIdError, UpdateBotByIdResponse, DeleteBotByIdData, DeleteBotByIdError, DeleteBotByIdResponse, SetBotEnabledByIdData, SetBotEnabledByIdError, SetBotEnabledByIdResponse, TestBotByIdData, TestBotByIdError, TestBotByIdResponse, GetBotData, GetBotError, GetBotResponse, UpdateBotData, UpdateBotError, UpdateBotResponse, DeleteBotData, DeleteBotError, DeleteBotResponse, SetBotEnabledData, SetBotEnabledError, SetBotEnabledResponse, TestBotData, TestBotError, TestBotResponse, GetProviderSchemaError, GetProviderSchemaResponse, ListProviderSourcesError, ListProviderSourcesResponse, CreateProviderSourceData, CreateProviderSourceError, CreateProviderSourceResponse, GetProviderSourceByIdData, GetProviderSourceByIdError, GetProviderSourceByIdResponse, UpsertProviderSourceByIdData, UpsertProviderSourceByIdError, UpsertProviderSourceByIdResponse, DeleteProviderSourceByIdData, DeleteProviderSourceByIdError, DeleteProviderSourceByIdResponse, ListProviderSourceModelsByIdData, ListProviderSourceModelsByIdError, ListProviderSourceModelsByIdResponse, ListProvidersBySourceIdData, ListProvidersBySourceIdError, ListProvidersBySourceIdResponse, CreateProviderInSourceByIdData, CreateProviderInSourceByIdError, CreateProviderInSourceByIdResponse, GetProviderSourceData, GetProviderSourceError, GetProviderSourceResponse, UpsertProviderSourceData, UpsertProviderSourceError, UpsertProviderSourceResponse, DeleteProviderSourceData, DeleteProviderSourceError, DeleteProviderSourceResponse, ListProviderSourceModelsData, ListProviderSourceModelsError, ListProviderSourceModelsResponse, ListProvidersBySourceData, ListProvidersBySourceError, ListProvidersBySourceResponse, CreateProviderInSourceData, CreateProviderInSourceError, CreateProviderInSourceResponse, ListProvidersData, ListProvidersError, ListProvidersResponse, CreateProviderData, CreateProviderError, CreateProviderResponse, GetProviderByIdData, GetProviderByIdError, GetProviderByIdResponse, UpdateProviderByIdData, UpdateProviderByIdError, UpdateProviderByIdResponse, DeleteProviderByIdData, DeleteProviderByIdError, DeleteProviderByIdResponse, SetProviderEnabledByIdData, SetProviderEnabledByIdError, SetProviderEnabledByIdResponse, TestProviderByIdData, TestProviderByIdError, TestProviderByIdResponse, GetProviderEmbeddingDimensionByIdData, GetProviderEmbeddingDimensionByIdError, GetProviderEmbeddingDimensionByIdResponse, GetProviderData, GetProviderError, GetProviderResponse, UpdateProviderData, UpdateProviderError, UpdateProviderResponse, DeleteProviderData, DeleteProviderError, DeleteProviderResponse, SetProviderEnabledData, SetProviderEnabledError, SetProviderEnabledResponse, TestProviderData, TestProviderError, TestProviderResponse, GetProviderEmbeddingDimensionData, GetProviderEmbeddingDimensionError, GetProviderEmbeddingDimensionResponse, SendChatMessageData, SendChatMessageError, SendChatMessageResponse, TranscribeChatAudioData, TranscribeChatAudioError, TranscribeChatAudioResponse, OpenChatWebSocketData, OpenLiveChatWebSocketData, OpenUnifiedChatWebSocketData, ListChatSessionsData, ListChatSessionsError, ListChatSessionsResponse, CreateChatSessionData, CreateChatSessionError, CreateChatSessionResponse, BatchDeleteChatSessionsData, BatchDeleteChatSessionsError, BatchDeleteChatSessionsResponse, GetChatSessionData, GetChatSessionError, GetChatSessionResponse, UpdateChatSessionData, UpdateChatSessionError, UpdateChatSessionResponse, DeleteChatSessionData, DeleteChatSessionError, DeleteChatSessionResponse, StopChatSessionData, StopChatSessionError, StopChatSessionResponse, ResumeChatRunData, ResumeChatRunError, ResumeChatRunResponse, UpdateChatMessageData, UpdateChatMessageError, UpdateChatMessageResponse, RegenerateChatMessageData, RegenerateChatMessageError, RegenerateChatMessageResponse, ListChatConfigsError, ListChatConfigsResponse, CreateChatThreadData, CreateChatThreadError, CreateChatThreadResponse, GetChatThreadData, GetChatThreadError, GetChatThreadResponse, DeleteChatThreadData, DeleteChatThreadError, DeleteChatThreadResponse, SendChatThreadMessageData, SendChatThreadMessageError, SendChatThreadMessageResponse, ListChatProjectsError, ListChatProjectsResponse, CreateChatProjectData, CreateChatProjectError, CreateChatProjectResponse, GetChatProjectData, GetChatProjectError, GetChatProjectResponse, UpdateChatProjectData, UpdateChatProjectError, UpdateChatProjectResponse, DeleteChatProjectData, DeleteChatProjectError, DeleteChatProjectResponse, ListChatProjectSessionsData, ListChatProjectSessionsError, ListChatProjectSessionsResponse, ListChatProjectWorkspaceFilesData, ListChatProjectWorkspaceFilesError, ListChatProjectWorkspaceFilesResponse, GetChatProjectWorkspaceFileData, GetChatProjectWorkspaceFileError, GetChatProjectWorkspaceFileResponse, DownloadChatProjectWorkspaceFileData, DownloadChatProjectWorkspaceFileError, DownloadChatProjectWorkspaceFileResponse, AddChatProjectSessionData, AddChatProjectSessionError, AddChatProjectSessionResponse, RemoveChatProjectSessionData, RemoveChatProjectSessionError, RemoveChatProjectSessionResponse, SendImMessageData, SendImMessageError, SendImMessageResponse, ListImBotsError, ListImBotsResponse, UploadFileData, UploadFileError, UploadFileResponse, InitFileUploadData, InitFileUploadError, InitFileUploadResponse, UploadFileChunkData, UploadFileChunkError, UploadFileChunkResponse, CompleteFileUploadData, CompleteFileUploadError, CompleteFileUploadResponse, AbortFileUploadData, AbortFileUploadError, AbortFileUploadResponse, StatusFileUploadData, StatusFileUploadError, StatusFileUploadResponse, UploadOpenApiFileData, UploadOpenApiFileError, UploadOpenApiFileResponse, DownloadOpenApiFileData, DownloadOpenApiFileError, DownloadOpenApiFileResponse, GetFileByNameData, GetFileByNameError, GetFileByNameResponse, GetTokenFileData, GetTokenFileError, GetTokenFileResponse, GetAttachmentData, GetAttachmentError, GetAttachmentResponse, DeleteAttachmentData, DeleteAttachmentError, DeleteAttachmentResponse, DownloadAttachmentData, DownloadAttachmentError, DownloadAttachmentResponse, ListPluginsData, ListPluginsError, ListPluginsResponse, GetPluginByIdData, GetPluginByIdError, GetPluginByIdResponse, UninstallPluginByIdData, UninstallPluginByIdError, UninstallPluginByIdResponse, GetPluginConfigByIdData, GetPluginConfigByIdError, GetPluginConfigByIdResponse, UpdatePluginConfigByIdData, UpdatePluginConfigByIdError, UpdatePluginConfigByIdResponse, GetPluginConfigSchemaByIdData, GetPluginConfigSchemaByIdError, GetPluginConfigSchemaByIdResponse, ListPluginConfigFilesByIdData, ListPluginConfigFilesByIdError, ListPluginConfigFilesByIdResponse, UploadPluginConfigFilesByIdData, UploadPluginConfigFilesByIdError, UploadPluginConfigFilesByIdResponse, DeletePluginConfigFileByIdData, DeletePluginConfigFileByIdError, DeletePluginConfigFileByIdResponse, GetPluginReadmeByIdData, GetPluginReadmeByIdError, GetPluginReadmeByIdResponse, GetPluginChangelogByIdData, GetPluginChangelogByIdError, GetPluginChangelogByIdResponse, ReloadPluginByIdData, ReloadPluginByIdError, ReloadPluginByIdResponse, SetPluginEnabledByIdData, SetPluginEnabledByIdError, SetPluginEnabledByIdResponse, GetPluginData, GetPluginError, GetPluginResponse, UninstallPluginData, UninstallPluginError, UninstallPluginResponse, GetPluginConfigData, GetPluginConfigError, GetPluginConfigResponse, UpdatePluginConfigData, UpdatePluginConfigError, UpdatePluginConfigResponse, UpdatePluginLogLevelData, UpdatePluginLogLevelError, UpdatePluginLogLevelResponse, GetPluginConfigSchemaData, GetPluginConfigSchemaError, GetPluginConfigSchemaResponse, ListPluginConfigFilesData, ListPluginConfigFilesError, ListPluginConfigFilesResponse, UploadPluginConfigFilesData, UploadPluginConfigFilesError, UploadPluginConfigFilesResponse, DeletePluginConfigFileData, DeletePluginConfigFileError, DeletePluginConfigFileResponse, GetPluginReadmeData, GetPluginReadmeError, GetPluginReadmeResponse, GetPluginChangelogData, GetPluginChangelogError, GetPluginChangelogResponse, ReloadPluginData, ReloadPluginError, ReloadPluginResponse, BindPluginSourceData, BindPluginSourceError, BindPluginSourceResponse, SetPluginEnabledData, SetPluginEnabledError, SetPluginEnabledResponse, UpdatePluginData, UpdatePluginError, UpdatePluginResponse, UpdatePluginsData, UpdatePluginsError, UpdatePluginsResponse, CheckPluginVersionSupportData, CheckPluginVersionSupportError, CheckPluginVersionSupportResponse, ValidatePluginRepoData, ValidatePluginRepoError, ValidatePluginRepoResponse, ListFailedPluginsError, ListFailedPluginsResponse, UninstallFailedPluginData, UninstallFailedPluginError, UninstallFailedPluginResponse, ReloadFailedPluginData, ReloadFailedPluginError, ReloadFailedPluginResponse, InstallPluginFromGithubData, InstallPluginFromGithubError, InstallPluginFromGithubResponse, InstallPluginFromGitData, InstallPluginFromGitError, InstallPluginFromGitResponse, InstallPluginFromUrlData, InstallPluginFromUrlError, InstallPluginFromUrlResponse, InstallPluginFromUploadData, InstallPluginFromUploadError, InstallPluginFromUploadResponse, ListPluginMarketData, ListPluginMarketError, ListPluginMarketResponse, ListPluginMarketCategoriesError, ListPluginMarketCategoriesResponse, ListPluginSourcesError, ListPluginSourcesResponse, CreatePluginSourceData, CreatePluginSourceError, CreatePluginSourceResponse, ReplacePluginSourcesData, ReplacePluginSourcesError, ReplacePluginSourcesResponse, DeletePluginSourceData, DeletePluginSourceError, DeletePluginSourceResponse, DeletePluginSourceByIdData, DeletePluginSourceByIdError, DeletePluginSourceByIdResponse, ListPluginViewsByIdData, ListPluginViewsByIdError, ListPluginViewsByIdResponse, ListPluginPagesByIdData, ListPluginPagesByIdError, ListPluginPagesByIdResponse, GetPluginViewByIdData, GetPluginViewByIdError, GetPluginViewByIdResponse, GetPluginPageByIdData, GetPluginPageByIdError, GetPluginPageByIdResponse, ListPluginViewsData, ListPluginViewsError, ListPluginViewsResponse, ListPluginPagesData, ListPluginPagesError, ListPluginPagesResponse, GetPluginViewData, GetPluginViewError, GetPluginViewResponse, GetPluginPageData, GetPluginPageError, GetPluginPageResponse, GetPluginViewTokenAssetData, GetPluginViewTokenAssetError, GetPluginViewTokenAssetResponse, GetPluginPageBridgeSdkError, GetPluginPageBridgeSdkResponse, GetPluginExtensionRouteData, GetPluginExtensionRouteError, GetPluginExtensionRouteResponse, PostPluginExtensionRouteData, PostPluginExtensionRouteError, PostPluginExtensionRouteResponse, PutPluginExtensionRouteData, PutPluginExtensionRouteError, PutPluginExtensionRouteResponse, PatchPluginExtensionRouteData, PatchPluginExtensionRouteError, PatchPluginExtensionRouteResponse, DeletePluginExtensionRouteData, DeletePluginExtensionRouteError, DeletePluginExtensionRouteResponse, ListCommandsData, ListCommandsError, ListCommandsResponse, UpdateCommandData, UpdateCommandError, UpdateCommandResponse, ListCommandConflictsError, ListCommandConflictsResponse, ListToolsData, ListToolsError, ListToolsResponse, SetToolEnabledData, SetToolEnabledError, SetToolEnabledResponse, SetToolPermissionData, SetToolPermissionError, SetToolPermissionResponse, ListMcpServersError, ListMcpServersResponse, CreateMcpServerData, CreateMcpServerError, CreateMcpServerResponse, UpdateMcpServerByNameData, UpdateMcpServerByNameError, UpdateMcpServerByNameResponse, DeleteMcpServerByNameData, DeleteMcpServerByNameError, DeleteMcpServerByNameResponse, SetMcpServerEnabledByNameData, SetMcpServerEnabledByNameError, SetMcpServerEnabledByNameResponse, TestMcpServerByNameData, TestMcpServerByNameError, TestMcpServerByNameResponse, UpdateMcpServerData, UpdateMcpServerError, UpdateMcpServerResponse, DeleteMcpServerData, DeleteMcpServerError, DeleteMcpServerResponse, SetMcpServerEnabledData, SetMcpServerEnabledError, SetMcpServerEnabledResponse, TestMcpServerData, TestMcpServerError, TestMcpServerResponse, SyncModelScopeMcpServersData, SyncModelScopeMcpServersError, SyncModelScopeMcpServersResponse, ListSkillsData, ListSkillsError, ListSkillsResponse, UploadSkillData, UploadSkillError, UploadSkillResponse, UploadSkillsBatchData, UploadSkillsBatchError, UploadSkillsBatchResponse, UpdateSkillByNameData, UpdateSkillByNameError, UpdateSkillByNameResponse, DeleteSkillByNameData, DeleteSkillByNameError, DeleteSkillByNameResponse, DownloadSkillByNameData, DownloadSkillByNameError, DownloadSkillByNameResponse, ListSkillFilesByNameData, ListSkillFilesByNameError, ListSkillFilesByNameResponse, GetSkillFileByNameData, GetSkillFileByNameError, GetSkillFileByNameResponse, UpdateSkillFileByNameData, UpdateSkillFileByNameError, UpdateSkillFileByNameResponse, UpdateSkillData, UpdateSkillError, UpdateSkillResponse, DeleteSkillData, DeleteSkillError, DeleteSkillResponse, DownloadSkillData, DownloadSkillError, DownloadSkillResponse, ListSkillFilesData, ListSkillFilesError, ListSkillFilesResponse, GetSkillFileData, GetSkillFileError, GetSkillFileResponse, UpdateSkillFileData, UpdateSkillFileError, UpdateSkillFileResponse, ListNeoSkillCandidatesData, ListNeoSkillCandidatesError, ListNeoSkillCandidatesResponse, ListNeoSkillReleasesData, ListNeoSkillReleasesError, ListNeoSkillReleasesResponse, GetNeoSkillPayloadData, GetNeoSkillPayloadError, GetNeoSkillPayloadResponse, EvaluateNeoSkillCandidateData, EvaluateNeoSkillCandidateError, EvaluateNeoSkillCandidateResponse, PromoteNeoSkillCandidateData, PromoteNeoSkillCandidateError, PromoteNeoSkillCandidateResponse, RollbackNeoSkillReleaseData, RollbackNeoSkillReleaseError, RollbackNeoSkillReleaseResponse, SyncNeoSkillReleaseData, SyncNeoSkillReleaseError, SyncNeoSkillReleaseResponse, DeleteNeoSkillCandidateData, DeleteNeoSkillCandidateError, DeleteNeoSkillCandidateResponse, DeleteNeoSkillReleaseData, DeleteNeoSkillReleaseError, DeleteNeoSkillReleaseResponse, ListKnowledgeBasesData, ListKnowledgeBasesError, ListKnowledgeBasesResponse, CreateKnowledgeBaseData, CreateKnowledgeBaseError, CreateKnowledgeBaseResponse, GetKnowledgeBaseData, GetKnowledgeBaseError, GetKnowledgeBaseResponse, UpdateKnowledgeBaseData, UpdateKnowledgeBaseError, UpdateKnowledgeBaseResponse, DeleteKnowledgeBaseData, DeleteKnowledgeBaseError, DeleteKnowledgeBaseResponse, GetKnowledgeBaseStatsData, GetKnowledgeBaseStatsError, GetKnowledgeBaseStatsResponse, ListKnowledgeDocumentsData, ListKnowledgeDocumentsError, ListKnowledgeDocumentsResponse, UploadKnowledgeDocumentData, UploadKnowledgeDocumentError, UploadKnowledgeDocumentResponse, ImportKnowledgeDocumentsData, ImportKnowledgeDocumentsError, ImportKnowledgeDocumentsResponse, ImportKnowledgeDocumentFromUrlData, ImportKnowledgeDocumentFromUrlError, ImportKnowledgeDocumentFromUrlResponse, GetKnowledgeDocumentData, GetKnowledgeDocumentError, GetKnowledgeDocumentResponse, DeleteKnowledgeDocumentData, DeleteKnowledgeDocumentError, DeleteKnowledgeDocumentResponse, ListKnowledgeChunksData, ListKnowledgeChunksError, ListKnowledgeChunksResponse, DeleteKnowledgeChunkData, DeleteKnowledgeChunkError, DeleteKnowledgeChunkResponse, RetrieveKnowledgeBaseData, RetrieveKnowledgeBaseError, RetrieveKnowledgeBaseResponse, GetKnowledgeTaskData, GetKnowledgeTaskError, GetKnowledgeTaskResponse, GetPersonaTreeError, GetPersonaTreeResponse, ListPersonasData, ListPersonasError, ListPersonasResponse, CreatePersonaData, CreatePersonaError, CreatePersonaResponse, GetPersonaByIdData, GetPersonaByIdError, GetPersonaByIdResponse, UpdatePersonaByIdData, UpdatePersonaByIdError, UpdatePersonaByIdResponse, DeletePersonaByIdData, DeletePersonaByIdError, DeletePersonaByIdResponse, GetPersonaData, GetPersonaError, GetPersonaResponse, UpdatePersonaData, UpdatePersonaError, UpdatePersonaResponse, DeletePersonaData, DeletePersonaError, DeletePersonaResponse, ListPersonaFoldersData, ListPersonaFoldersError, ListPersonaFoldersResponse, CreatePersonaFolderData, CreatePersonaFolderError, CreatePersonaFolderResponse, UpdatePersonaFolderData, UpdatePersonaFolderError, UpdatePersonaFolderResponse, DeletePersonaFolderData, DeletePersonaFolderError, DeletePersonaFolderResponse, MovePersonaItemData, MovePersonaItemError, MovePersonaItemResponse, ReorderPersonaItemsData, ReorderPersonaItemsError, ReorderPersonaItemsResponse, ListActiveUmosData, ListActiveUmosError, ListActiveUmosResponse, ListSessionSendersData, ListSessionSendersError, ListSessionSendersResponse, GetSessionOverridesData, GetSessionOverridesError, GetSessionOverridesResponse, ListSessionRulesData, ListSessionRulesError, ListSessionRulesResponse, UpsertSessionRuleData, UpsertSessionRuleError, UpsertSessionRuleResponse, DeleteSessionRulesData, DeleteSessionRulesError, DeleteSessionRulesResponse, ListSessionGroupsError, ListSessionGroupsResponse, CreateSessionGroupData, CreateSessionGroupError, CreateSessionGroupResponse, UpdateSessionGroupData, UpdateSessionGroupError, UpdateSessionGroupResponse, DeleteSessionGroupData, DeleteSessionGroupError, DeleteSessionGroupResponse, ListConversationsData, ListConversationsError, ListConversationsResponse, GetConversationFilterOptionsError, GetConversationFilterOptionsResponse, BatchDeleteConversationsData, BatchDeleteConversationsError, BatchDeleteConversationsResponse, GetConversationData, GetConversationError, GetConversationResponse, UpdateConversationData, UpdateConversationError, UpdateConversationResponse, DeleteConversationData, DeleteConversationError, DeleteConversationResponse, ReplaceConversationMessagesData, ReplaceConversationMessagesError, ReplaceConversationMessagesResponse, ExportConversationsData, ExportConversationsError, ExportConversationsResponse, GetStatsData, GetStatsError, GetStatsResponse, GetProviderTokenStatsData, GetProviderTokenStatsError, GetProviderTokenStatsResponse, GetVersionError, GetVersionResponse, GetPublicVersionsError, GetPublicVersionsResponse, GetFirstNoticeData, GetFirstNoticeError, GetFirstNoticeResponse, TestGhproxyConnectionData, TestGhproxyConnectionError, TestGhproxyConnectionResponse, TestPypiIndexConnectionData, TestPypiIndexConnectionError, TestPypiIndexConnectionResponse, MeasurePypiIndexSpeedData, MeasurePypiIndexSpeedError, MeasurePypiIndexSpeedResponse, MeasureGhproxySpeedData, MeasureGhproxySpeedError, MeasureGhproxySpeedResponse, ListChangelogVersionsError, ListChangelogVersionsResponse, GetChangelogData, GetChangelogError, GetChangelogResponse, GetStartTimeError, GetStartTimeResponse, GetStorageStatusError, GetStorageStatusResponse, CleanupStorageData, CleanupStorageError, CleanupStorageResponse, RestartCoreError, RestartCoreResponse, ListBackupsData, ListBackupsError, ListBackupsResponse, CreateBackupData, CreateBackupError, CreateBackupResponse, UploadBackupData, UploadBackupError, UploadBackupResponse, InitBackupUploadData, InitBackupUploadError, InitBackupUploadResponse, UploadBackupChunkData, UploadBackupChunkError, UploadBackupChunkResponse, CompleteBackupUploadData, CompleteBackupUploadError, CompleteBackupUploadResponse, AbortBackupUploadData, AbortBackupUploadError, AbortBackupUploadResponse, StatusBackupUploadData, StatusBackupUploadError, StatusBackupUploadResponse, GetBackupProgressData, GetBackupProgressError, GetBackupProgressResponse, DownloadBackupData, DownloadBackupError, DownloadBackupResponse, RenameBackupData, RenameBackupError, RenameBackupResponse, DeleteBackupData, DeleteBackupError, DeleteBackupResponse, CheckBackupData, CheckBackupError, CheckBackupResponse, ImportBackupData, ImportBackupError, ImportBackupResponse, CheckUpdateError, CheckUpdateResponse, ListReleasesData, ListReleasesError, ListReleasesResponse, UpdateCoreData, UpdateCoreError, UpdateCoreResponse, UpdateDashboardData, UpdateDashboardError, UpdateDashboardResponse, GetUpdateProgressData, GetUpdateProgressError, GetUpdateProgressResponse, InstallPipPackageData, InstallPipPackageError, InstallPipPackageResponse, ListCronJobsData, ListCronJobsError, ListCronJobsResponse, CreateCronJobData, CreateCronJobError, CreateCronJobResponse, UpdateCronJobData, UpdateCronJobError, UpdateCronJobResponse, DeleteCronJobData, DeleteCronJobError, DeleteCronJobResponse, RunCronJobData, RunCronJobError, RunCronJobResponse, StreamLiveLogsError, StreamLiveLogsResponse, GetLogHistoryError, GetLogHistoryResponse, ExportLogsData, ExportLogsError, ExportLogsResponse, ListTracesData, ListTracesError, ListTracesResponse, GetTraceDetailData, GetTraceDetailError, GetTraceDetailResponse, GetTraceSettingsError, GetTraceSettingsResponse, UpdateTraceSettingsData, UpdateTraceSettingsError, UpdateTraceSettingsResponse, ListT2iTemplatesError, ListT2iTemplatesResponse, CreateT2iTemplateData, CreateT2iTemplateError, CreateT2iTemplateResponse, GetActiveT2iTemplateError, GetActiveT2iTemplateResponse, SetActiveT2iTemplateData, SetActiveT2iTemplateError, SetActiveT2iTemplateResponse, ResetDefaultT2iTemplateError, ResetDefaultT2iTemplateResponse, GetT2iTemplateData, GetT2iTemplateError, GetT2iTemplateResponse, UpdateT2iTemplateData, UpdateT2iTemplateError, UpdateT2iTemplateResponse, DeleteT2iTemplateData, DeleteT2iTemplateError, DeleteT2iTemplateResponse, ListAgentConfigsError, ListAgentConfigsResponse, CreateAgentConfigData, CreateAgentConfigError, CreateAgentConfigResponse, GetAgentConfigData, GetAgentConfigError, GetAgentConfigResponse, UpdateAgentConfigData, UpdateAgentConfigError, UpdateAgentConfigResponse, DeleteAgentConfigData, DeleteAgentConfigError, DeleteAgentConfigResponse, ListAgentRuntimesError, ListAgentRuntimesResponse, VerifyPlatformWebhookData, VerifyPlatformWebhookError, VerifyPlatformWebhookResponse, ReceivePlatformWebhookData, ReceivePlatformWebhookError, ReceivePlatformWebhookResponse, ListWorkbenchViewsError, ListWorkbenchViewsResponse, GetWorkbenchViewData, GetWorkbenchViewError, GetWorkbenchViewResponse, GetChatViewApiV1ChatViewsViewIdGetData, GetChatViewApiV1ChatViewsViewIdGetError, GetChatViewApiV1ChatViewsViewIdGetResponse, RunChatViewActionApiV1ChatViewsViewIdActionsPostData, RunChatViewActionApiV1ChatViewsViewIdActionsPostError, RunChatViewActionApiV1ChatViewsViewIdActionsPostResponse, GetChatViewActionApiV1ChatViewsViewIdActionsInteractionIdGetData, GetChatViewActionApiV1ChatViewsViewIdActionsInteractionIdGetError, GetChatViewActionApiV1ChatViewsViewIdActionsInteractionIdGetResponse } from './types.gen'; +import type { LoginData, LoginError, LoginResponse, LogoutError, LogoutResponse, GetAuthSetupStatusError, GetAuthSetupStatusResponse, SetupAuthData, SetupAuthError, SetupAuthResponse, SetupTotpData, SetupTotpError, SetupTotpResponse, RecoverTotpError, RecoverTotpResponse, UpdateAuthAccountData, UpdateAuthAccountError, UpdateAuthAccountResponse, ListApiKeysError, ListApiKeysResponse, CreateApiKeyData, CreateApiKeyError, CreateApiKeyResponse, RevokeApiKeyData, RevokeApiKeyError, RevokeApiKeyResponse, DeleteApiKeyData, DeleteApiKeyError, DeleteApiKeyResponse, GetSystemConfigSchemaError, GetSystemConfigSchemaResponse, GetSystemConfigError, GetSystemConfigResponse, UpdateSystemConfigData, UpdateSystemConfigError, UpdateSystemConfigResponse, GetSystemConfigRuntimeError, GetSystemConfigRuntimeResponse, GetConfigProfileSchemaError, GetConfigProfileSchemaResponse, ListConfigProfilesError, ListConfigProfilesResponse, CreateConfigProfileData, CreateConfigProfileError, CreateConfigProfileResponse, GetConfigProfileData, GetConfigProfileError, GetConfigProfileResponse, UpdateConfigProfileContentData, UpdateConfigProfileContentError, UpdateConfigProfileContentResponse, RenameConfigProfileData, RenameConfigProfileError, RenameConfigProfileResponse, DeleteConfigProfileData, DeleteConfigProfileError, DeleteConfigProfileResponse, ListConfigRoutesError, ListConfigRoutesResponse, ReplaceConfigRoutesData, ReplaceConfigRoutesError, ReplaceConfigRoutesResponse, UpsertConfigRouteData, UpsertConfigRouteError, UpsertConfigRouteResponse, DeleteConfigRouteData, DeleteConfigRouteError, DeleteConfigRouteResponse, ListBotTypesError, ListBotTypesResponse, RegisterBotTypeData, RegisterBotTypeError, RegisterBotTypeResponse, ListBotsData, ListBotsError, ListBotsResponse, CreateBotData, CreateBotError, CreateBotResponse, ListBotStatsError, ListBotStatsResponse, GetBotByIdData, GetBotByIdError, GetBotByIdResponse, UpdateBotByIdData, UpdateBotByIdError, UpdateBotByIdResponse, DeleteBotByIdData, DeleteBotByIdError, DeleteBotByIdResponse, SetBotEnabledByIdData, SetBotEnabledByIdError, SetBotEnabledByIdResponse, TestBotByIdData, TestBotByIdError, TestBotByIdResponse, GetBotData, GetBotError, GetBotResponse, UpdateBotData, UpdateBotError, UpdateBotResponse, DeleteBotData, DeleteBotError, DeleteBotResponse, SetBotEnabledData, SetBotEnabledError, SetBotEnabledResponse, TestBotData, TestBotError, TestBotResponse, GetProviderSchemaError, GetProviderSchemaResponse, ListProviderSourcesError, ListProviderSourcesResponse, CreateProviderSourceData, CreateProviderSourceError, CreateProviderSourceResponse, GetProviderSourceByIdData, GetProviderSourceByIdError, GetProviderSourceByIdResponse, UpsertProviderSourceByIdData, UpsertProviderSourceByIdError, UpsertProviderSourceByIdResponse, DeleteProviderSourceByIdData, DeleteProviderSourceByIdError, DeleteProviderSourceByIdResponse, ListProviderSourceModelsByIdData, ListProviderSourceModelsByIdError, ListProviderSourceModelsByIdResponse, ListProvidersBySourceIdData, ListProvidersBySourceIdError, ListProvidersBySourceIdResponse, CreateProviderInSourceByIdData, CreateProviderInSourceByIdError, CreateProviderInSourceByIdResponse, GetProviderSourceData, GetProviderSourceError, GetProviderSourceResponse, UpsertProviderSourceData, UpsertProviderSourceError, UpsertProviderSourceResponse, DeleteProviderSourceData, DeleteProviderSourceError, DeleteProviderSourceResponse, ListProviderSourceModelsData, ListProviderSourceModelsError, ListProviderSourceModelsResponse, ListProvidersBySourceData, ListProvidersBySourceError, ListProvidersBySourceResponse, CreateProviderInSourceData, CreateProviderInSourceError, CreateProviderInSourceResponse, ListProvidersData, ListProvidersError, ListProvidersResponse, CreateProviderData, CreateProviderError, CreateProviderResponse, GetProviderByIdData, GetProviderByIdError, GetProviderByIdResponse, UpdateProviderByIdData, UpdateProviderByIdError, UpdateProviderByIdResponse, DeleteProviderByIdData, DeleteProviderByIdError, DeleteProviderByIdResponse, SetProviderEnabledByIdData, SetProviderEnabledByIdError, SetProviderEnabledByIdResponse, TestProviderByIdData, TestProviderByIdError, TestProviderByIdResponse, GetProviderEmbeddingDimensionByIdData, GetProviderEmbeddingDimensionByIdError, GetProviderEmbeddingDimensionByIdResponse, GetProviderData, GetProviderError, GetProviderResponse, UpdateProviderData, UpdateProviderError, UpdateProviderResponse, DeleteProviderData, DeleteProviderError, DeleteProviderResponse, SetProviderEnabledData, SetProviderEnabledError, SetProviderEnabledResponse, TestProviderData, TestProviderError, TestProviderResponse, GetProviderEmbeddingDimensionData, GetProviderEmbeddingDimensionError, GetProviderEmbeddingDimensionResponse, SendChatMessageData, SendChatMessageError, SendChatMessageResponse, TranscribeChatAudioData, TranscribeChatAudioError, TranscribeChatAudioResponse, OpenChatWebSocketData, OpenLiveChatWebSocketData, OpenUnifiedChatWebSocketData, ListChatSessionsData, ListChatSessionsError, ListChatSessionsResponse, CreateChatSessionData, CreateChatSessionError, CreateChatSessionResponse, BatchDeleteChatSessionsData, BatchDeleteChatSessionsError, BatchDeleteChatSessionsResponse, GetChatSessionData, GetChatSessionError, GetChatSessionResponse, UpdateChatSessionData, UpdateChatSessionError, UpdateChatSessionResponse, DeleteChatSessionData, DeleteChatSessionError, DeleteChatSessionResponse, SetChatPermissionModeData, SetChatPermissionModeError, SetChatPermissionModeResponse, StopChatSessionData, StopChatSessionError, StopChatSessionResponse, ResumeChatRunData, ResumeChatRunError, ResumeChatRunResponse, UpdateChatMessageData, UpdateChatMessageError, UpdateChatMessageResponse, RegenerateChatMessageData, RegenerateChatMessageError, RegenerateChatMessageResponse, ListChatConfigsError, ListChatConfigsResponse, CreateChatThreadData, CreateChatThreadError, CreateChatThreadResponse, GetChatThreadData, GetChatThreadError, GetChatThreadResponse, DeleteChatThreadData, DeleteChatThreadError, DeleteChatThreadResponse, SendChatThreadMessageData, SendChatThreadMessageError, SendChatThreadMessageResponse, ListChatProjectsError, ListChatProjectsResponse, CreateChatProjectData, CreateChatProjectError, CreateChatProjectResponse, GetChatProjectData, GetChatProjectError, GetChatProjectResponse, UpdateChatProjectData, UpdateChatProjectError, UpdateChatProjectResponse, DeleteChatProjectData, DeleteChatProjectError, DeleteChatProjectResponse, ListChatProjectSessionsData, ListChatProjectSessionsError, ListChatProjectSessionsResponse, ListChatProjectWorkspaceFilesData, ListChatProjectWorkspaceFilesError, ListChatProjectWorkspaceFilesResponse, GetChatProjectWorkspaceFileData, GetChatProjectWorkspaceFileError, GetChatProjectWorkspaceFileResponse, DownloadChatProjectWorkspaceFileData, DownloadChatProjectWorkspaceFileError, DownloadChatProjectWorkspaceFileResponse, AddChatProjectSessionData, AddChatProjectSessionError, AddChatProjectSessionResponse, RemoveChatProjectSessionData, RemoveChatProjectSessionError, RemoveChatProjectSessionResponse, SendImMessageData, SendImMessageError, SendImMessageResponse, ListImBotsError, ListImBotsResponse, UploadFileData, UploadFileError, UploadFileResponse, InitFileUploadData, InitFileUploadError, InitFileUploadResponse, UploadFileChunkData, UploadFileChunkError, UploadFileChunkResponse, CompleteFileUploadData, CompleteFileUploadError, CompleteFileUploadResponse, AbortFileUploadData, AbortFileUploadError, AbortFileUploadResponse, StatusFileUploadData, StatusFileUploadError, StatusFileUploadResponse, UploadOpenApiFileData, UploadOpenApiFileError, UploadOpenApiFileResponse, DownloadOpenApiFileData, DownloadOpenApiFileError, DownloadOpenApiFileResponse, GetFileByNameData, GetFileByNameError, GetFileByNameResponse, GetTokenFileData, GetTokenFileError, GetTokenFileResponse, GetAttachmentData, GetAttachmentError, GetAttachmentResponse, DeleteAttachmentData, DeleteAttachmentError, DeleteAttachmentResponse, DownloadAttachmentData, DownloadAttachmentError, DownloadAttachmentResponse, ListPluginsData, ListPluginsError, ListPluginsResponse, GetPluginByIdData, GetPluginByIdError, GetPluginByIdResponse, UninstallPluginByIdData, UninstallPluginByIdError, UninstallPluginByIdResponse, GetPluginConfigByIdData, GetPluginConfigByIdError, GetPluginConfigByIdResponse, UpdatePluginConfigByIdData, UpdatePluginConfigByIdError, UpdatePluginConfigByIdResponse, GetPluginConfigSchemaByIdData, GetPluginConfigSchemaByIdError, GetPluginConfigSchemaByIdResponse, ListPluginConfigFilesByIdData, ListPluginConfigFilesByIdError, ListPluginConfigFilesByIdResponse, UploadPluginConfigFilesByIdData, UploadPluginConfigFilesByIdError, UploadPluginConfigFilesByIdResponse, DeletePluginConfigFileByIdData, DeletePluginConfigFileByIdError, DeletePluginConfigFileByIdResponse, GetPluginReadmeByIdData, GetPluginReadmeByIdError, GetPluginReadmeByIdResponse, GetPluginChangelogByIdData, GetPluginChangelogByIdError, GetPluginChangelogByIdResponse, ReloadPluginByIdData, ReloadPluginByIdError, ReloadPluginByIdResponse, SetPluginEnabledByIdData, SetPluginEnabledByIdError, SetPluginEnabledByIdResponse, GetPluginData, GetPluginError, GetPluginResponse, UninstallPluginData, UninstallPluginError, UninstallPluginResponse, GetPluginConfigData, GetPluginConfigError, GetPluginConfigResponse, UpdatePluginConfigData, UpdatePluginConfigError, UpdatePluginConfigResponse, UpdatePluginLogLevelData, UpdatePluginLogLevelError, UpdatePluginLogLevelResponse, GetPluginConfigSchemaData, GetPluginConfigSchemaError, GetPluginConfigSchemaResponse, ListPluginConfigFilesData, ListPluginConfigFilesError, ListPluginConfigFilesResponse, UploadPluginConfigFilesData, UploadPluginConfigFilesError, UploadPluginConfigFilesResponse, DeletePluginConfigFileData, DeletePluginConfigFileError, DeletePluginConfigFileResponse, GetPluginReadmeData, GetPluginReadmeError, GetPluginReadmeResponse, GetPluginChangelogData, GetPluginChangelogError, GetPluginChangelogResponse, ReloadPluginData, ReloadPluginError, ReloadPluginResponse, BindPluginSourceData, BindPluginSourceError, BindPluginSourceResponse, SetPluginEnabledData, SetPluginEnabledError, SetPluginEnabledResponse, UpdatePluginData, UpdatePluginError, UpdatePluginResponse, UpdatePluginsData, UpdatePluginsError, UpdatePluginsResponse, CheckPluginVersionSupportData, CheckPluginVersionSupportError, CheckPluginVersionSupportResponse, ValidatePluginRepoData, ValidatePluginRepoError, ValidatePluginRepoResponse, ListFailedPluginsError, ListFailedPluginsResponse, UninstallFailedPluginData, UninstallFailedPluginError, UninstallFailedPluginResponse, ReloadFailedPluginData, ReloadFailedPluginError, ReloadFailedPluginResponse, InstallPluginFromGithubData, InstallPluginFromGithubError, InstallPluginFromGithubResponse, InstallPluginFromGitData, InstallPluginFromGitError, InstallPluginFromGitResponse, InstallPluginFromUrlData, InstallPluginFromUrlError, InstallPluginFromUrlResponse, InstallPluginFromUploadData, InstallPluginFromUploadError, InstallPluginFromUploadResponse, ListPluginMarketData, ListPluginMarketError, ListPluginMarketResponse, ListPluginMarketCategoriesError, ListPluginMarketCategoriesResponse, ListPluginSourcesError, ListPluginSourcesResponse, CreatePluginSourceData, CreatePluginSourceError, CreatePluginSourceResponse, ReplacePluginSourcesData, ReplacePluginSourcesError, ReplacePluginSourcesResponse, DeletePluginSourceData, DeletePluginSourceError, DeletePluginSourceResponse, DeletePluginSourceByIdData, DeletePluginSourceByIdError, DeletePluginSourceByIdResponse, ListPluginViewsByIdData, ListPluginViewsByIdError, ListPluginViewsByIdResponse, ListPluginPagesByIdData, ListPluginPagesByIdError, ListPluginPagesByIdResponse, GetPluginViewByIdData, GetPluginViewByIdError, GetPluginViewByIdResponse, GetPluginPageByIdData, GetPluginPageByIdError, GetPluginPageByIdResponse, ListPluginViewsData, ListPluginViewsError, ListPluginViewsResponse, ListPluginPagesData, ListPluginPagesError, ListPluginPagesResponse, GetPluginViewData, GetPluginViewError, GetPluginViewResponse, GetPluginPageData, GetPluginPageError, GetPluginPageResponse, GetPluginViewTokenAssetData, GetPluginViewTokenAssetError, GetPluginViewTokenAssetResponse, GetPluginPageBridgeSdkError, GetPluginPageBridgeSdkResponse, GetPluginExtensionRouteData, GetPluginExtensionRouteError, GetPluginExtensionRouteResponse, PostPluginExtensionRouteData, PostPluginExtensionRouteError, PostPluginExtensionRouteResponse, PutPluginExtensionRouteData, PutPluginExtensionRouteError, PutPluginExtensionRouteResponse, PatchPluginExtensionRouteData, PatchPluginExtensionRouteError, PatchPluginExtensionRouteResponse, DeletePluginExtensionRouteData, DeletePluginExtensionRouteError, DeletePluginExtensionRouteResponse, ListCommandsData, ListCommandsError, ListCommandsResponse, UpdateCommandData, UpdateCommandError, UpdateCommandResponse, ListCommandConflictsError, ListCommandConflictsResponse, ListToolsData, ListToolsError, ListToolsResponse, SetToolEnabledData, SetToolEnabledError, SetToolEnabledResponse, SetToolPermissionData, SetToolPermissionError, SetToolPermissionResponse, ListMcpServersError, ListMcpServersResponse, CreateMcpServerData, CreateMcpServerError, CreateMcpServerResponse, UpdateMcpServerByNameData, UpdateMcpServerByNameError, UpdateMcpServerByNameResponse, DeleteMcpServerByNameData, DeleteMcpServerByNameError, DeleteMcpServerByNameResponse, SetMcpServerEnabledByNameData, SetMcpServerEnabledByNameError, SetMcpServerEnabledByNameResponse, TestMcpServerByNameData, TestMcpServerByNameError, TestMcpServerByNameResponse, UpdateMcpServerData, UpdateMcpServerError, UpdateMcpServerResponse, DeleteMcpServerData, DeleteMcpServerError, DeleteMcpServerResponse, SetMcpServerEnabledData, SetMcpServerEnabledError, SetMcpServerEnabledResponse, TestMcpServerData, TestMcpServerError, TestMcpServerResponse, SyncModelScopeMcpServersData, SyncModelScopeMcpServersError, SyncModelScopeMcpServersResponse, ListSkillsData, ListSkillsError, ListSkillsResponse, UploadSkillData, UploadSkillError, UploadSkillResponse, UploadSkillsBatchData, UploadSkillsBatchError, UploadSkillsBatchResponse, UpdateSkillByNameData, UpdateSkillByNameError, UpdateSkillByNameResponse, DeleteSkillByNameData, DeleteSkillByNameError, DeleteSkillByNameResponse, DownloadSkillByNameData, DownloadSkillByNameError, DownloadSkillByNameResponse, ListSkillFilesByNameData, ListSkillFilesByNameError, ListSkillFilesByNameResponse, GetSkillFileByNameData, GetSkillFileByNameError, GetSkillFileByNameResponse, UpdateSkillFileByNameData, UpdateSkillFileByNameError, UpdateSkillFileByNameResponse, UpdateSkillData, UpdateSkillError, UpdateSkillResponse, DeleteSkillData, DeleteSkillError, DeleteSkillResponse, DownloadSkillData, DownloadSkillError, DownloadSkillResponse, ListSkillFilesData, ListSkillFilesError, ListSkillFilesResponse, GetSkillFileData, GetSkillFileError, GetSkillFileResponse, UpdateSkillFileData, UpdateSkillFileError, UpdateSkillFileResponse, ListNeoSkillCandidatesData, ListNeoSkillCandidatesError, ListNeoSkillCandidatesResponse, ListNeoSkillReleasesData, ListNeoSkillReleasesError, ListNeoSkillReleasesResponse, GetNeoSkillPayloadData, GetNeoSkillPayloadError, GetNeoSkillPayloadResponse, EvaluateNeoSkillCandidateData, EvaluateNeoSkillCandidateError, EvaluateNeoSkillCandidateResponse, PromoteNeoSkillCandidateData, PromoteNeoSkillCandidateError, PromoteNeoSkillCandidateResponse, RollbackNeoSkillReleaseData, RollbackNeoSkillReleaseError, RollbackNeoSkillReleaseResponse, SyncNeoSkillReleaseData, SyncNeoSkillReleaseError, SyncNeoSkillReleaseResponse, DeleteNeoSkillCandidateData, DeleteNeoSkillCandidateError, DeleteNeoSkillCandidateResponse, DeleteNeoSkillReleaseData, DeleteNeoSkillReleaseError, DeleteNeoSkillReleaseResponse, ListKnowledgeBasesData, ListKnowledgeBasesError, ListKnowledgeBasesResponse, CreateKnowledgeBaseData, CreateKnowledgeBaseError, CreateKnowledgeBaseResponse, GetKnowledgeBaseData, GetKnowledgeBaseError, GetKnowledgeBaseResponse, UpdateKnowledgeBaseData, UpdateKnowledgeBaseError, UpdateKnowledgeBaseResponse, DeleteKnowledgeBaseData, DeleteKnowledgeBaseError, DeleteKnowledgeBaseResponse, GetKnowledgeBaseStatsData, GetKnowledgeBaseStatsError, GetKnowledgeBaseStatsResponse, ListKnowledgeDocumentsData, ListKnowledgeDocumentsError, ListKnowledgeDocumentsResponse, UploadKnowledgeDocumentData, UploadKnowledgeDocumentError, UploadKnowledgeDocumentResponse, ImportKnowledgeDocumentsData, ImportKnowledgeDocumentsError, ImportKnowledgeDocumentsResponse, ImportKnowledgeDocumentFromUrlData, ImportKnowledgeDocumentFromUrlError, ImportKnowledgeDocumentFromUrlResponse, GetKnowledgeDocumentData, GetKnowledgeDocumentError, GetKnowledgeDocumentResponse, DeleteKnowledgeDocumentData, DeleteKnowledgeDocumentError, DeleteKnowledgeDocumentResponse, ListKnowledgeChunksData, ListKnowledgeChunksError, ListKnowledgeChunksResponse, DeleteKnowledgeChunkData, DeleteKnowledgeChunkError, DeleteKnowledgeChunkResponse, RetrieveKnowledgeBaseData, RetrieveKnowledgeBaseError, RetrieveKnowledgeBaseResponse, GetKnowledgeTaskData, GetKnowledgeTaskError, GetKnowledgeTaskResponse, GetPersonaTreeError, GetPersonaTreeResponse, ListPersonasData, ListPersonasError, ListPersonasResponse, CreatePersonaData, CreatePersonaError, CreatePersonaResponse, GetPersonaByIdData, GetPersonaByIdError, GetPersonaByIdResponse, UpdatePersonaByIdData, UpdatePersonaByIdError, UpdatePersonaByIdResponse, DeletePersonaByIdData, DeletePersonaByIdError, DeletePersonaByIdResponse, GetPersonaData, GetPersonaError, GetPersonaResponse, UpdatePersonaData, UpdatePersonaError, UpdatePersonaResponse, DeletePersonaData, DeletePersonaError, DeletePersonaResponse, ListPersonaFoldersData, ListPersonaFoldersError, ListPersonaFoldersResponse, CreatePersonaFolderData, CreatePersonaFolderError, CreatePersonaFolderResponse, UpdatePersonaFolderData, UpdatePersonaFolderError, UpdatePersonaFolderResponse, DeletePersonaFolderData, DeletePersonaFolderError, DeletePersonaFolderResponse, MovePersonaItemData, MovePersonaItemError, MovePersonaItemResponse, ReorderPersonaItemsData, ReorderPersonaItemsError, ReorderPersonaItemsResponse, ListActiveUmosData, ListActiveUmosError, ListActiveUmosResponse, ListSessionSendersData, ListSessionSendersError, ListSessionSendersResponse, GetSessionOverridesData, GetSessionOverridesError, GetSessionOverridesResponse, ListSessionRulesData, ListSessionRulesError, ListSessionRulesResponse, UpsertSessionRuleData, UpsertSessionRuleError, UpsertSessionRuleResponse, DeleteSessionRulesData, DeleteSessionRulesError, DeleteSessionRulesResponse, ListSessionGroupsError, ListSessionGroupsResponse, CreateSessionGroupData, CreateSessionGroupError, CreateSessionGroupResponse, UpdateSessionGroupData, UpdateSessionGroupError, UpdateSessionGroupResponse, DeleteSessionGroupData, DeleteSessionGroupError, DeleteSessionGroupResponse, ListConversationsData, ListConversationsError, ListConversationsResponse, GetConversationFilterOptionsError, GetConversationFilterOptionsResponse, BatchDeleteConversationsData, BatchDeleteConversationsError, BatchDeleteConversationsResponse, GetConversationData, GetConversationError, GetConversationResponse, UpdateConversationData, UpdateConversationError, UpdateConversationResponse, DeleteConversationData, DeleteConversationError, DeleteConversationResponse, ReplaceConversationMessagesData, ReplaceConversationMessagesError, ReplaceConversationMessagesResponse, ExportConversationsData, ExportConversationsError, ExportConversationsResponse, GetStatsData, GetStatsError, GetStatsResponse, GetProviderTokenStatsData, GetProviderTokenStatsError, GetProviderTokenStatsResponse, GetVersionError, GetVersionResponse, GetPublicVersionsError, GetPublicVersionsResponse, GetFirstNoticeData, GetFirstNoticeError, GetFirstNoticeResponse, TestGhproxyConnectionData, TestGhproxyConnectionError, TestGhproxyConnectionResponse, TestPypiIndexConnectionData, TestPypiIndexConnectionError, TestPypiIndexConnectionResponse, MeasurePypiIndexSpeedData, MeasurePypiIndexSpeedError, MeasurePypiIndexSpeedResponse, MeasureGhproxySpeedData, MeasureGhproxySpeedError, MeasureGhproxySpeedResponse, ListChangelogVersionsError, ListChangelogVersionsResponse, GetChangelogData, GetChangelogError, GetChangelogResponse, GetStartTimeError, GetStartTimeResponse, GetStorageStatusError, GetStorageStatusResponse, CleanupStorageData, CleanupStorageError, CleanupStorageResponse, RestartCoreError, RestartCoreResponse, ListBackupsData, ListBackupsError, ListBackupsResponse, CreateBackupData, CreateBackupError, CreateBackupResponse, UploadBackupData, UploadBackupError, UploadBackupResponse, InitBackupUploadData, InitBackupUploadError, InitBackupUploadResponse, UploadBackupChunkData, UploadBackupChunkError, UploadBackupChunkResponse, CompleteBackupUploadData, CompleteBackupUploadError, CompleteBackupUploadResponse, AbortBackupUploadData, AbortBackupUploadError, AbortBackupUploadResponse, StatusBackupUploadData, StatusBackupUploadError, StatusBackupUploadResponse, GetBackupProgressData, GetBackupProgressError, GetBackupProgressResponse, DownloadBackupData, DownloadBackupError, DownloadBackupResponse, RenameBackupData, RenameBackupError, RenameBackupResponse, DeleteBackupData, DeleteBackupError, DeleteBackupResponse, CheckBackupData, CheckBackupError, CheckBackupResponse, ImportBackupData, ImportBackupError, ImportBackupResponse, CheckUpdateError, CheckUpdateResponse, ListReleasesData, ListReleasesError, ListReleasesResponse, UpdateCoreData, UpdateCoreError, UpdateCoreResponse, UpdateDashboardData, UpdateDashboardError, UpdateDashboardResponse, GetUpdateProgressData, GetUpdateProgressError, GetUpdateProgressResponse, InstallPipPackageData, InstallPipPackageError, InstallPipPackageResponse, ListCronJobsData, ListCronJobsError, ListCronJobsResponse, CreateCronJobData, CreateCronJobError, CreateCronJobResponse, UpdateCronJobData, UpdateCronJobError, UpdateCronJobResponse, DeleteCronJobData, DeleteCronJobError, DeleteCronJobResponse, RunCronJobData, RunCronJobError, RunCronJobResponse, StreamLiveLogsError, StreamLiveLogsResponse, GetLogHistoryError, GetLogHistoryResponse, ExportLogsData, ExportLogsError, ExportLogsResponse, ListTracesData, ListTracesError, ListTracesResponse, GetTraceDetailData, GetTraceDetailError, GetTraceDetailResponse, GetTraceSettingsError, GetTraceSettingsResponse, UpdateTraceSettingsData, UpdateTraceSettingsError, UpdateTraceSettingsResponse, ListT2iTemplatesError, ListT2iTemplatesResponse, CreateT2iTemplateData, CreateT2iTemplateError, CreateT2iTemplateResponse, GetActiveT2iTemplateError, GetActiveT2iTemplateResponse, SetActiveT2iTemplateData, SetActiveT2iTemplateError, SetActiveT2iTemplateResponse, ResetDefaultT2iTemplateError, ResetDefaultT2iTemplateResponse, GetT2iTemplateData, GetT2iTemplateError, GetT2iTemplateResponse, UpdateT2iTemplateData, UpdateT2iTemplateError, UpdateT2iTemplateResponse, DeleteT2iTemplateData, DeleteT2iTemplateError, DeleteT2iTemplateResponse, ListAgentConfigsError, ListAgentConfigsResponse, CreateAgentConfigData, CreateAgentConfigError, CreateAgentConfigResponse, GetAgentConfigData, GetAgentConfigError, GetAgentConfigResponse, UpdateAgentConfigData, UpdateAgentConfigError, UpdateAgentConfigResponse, DeleteAgentConfigData, DeleteAgentConfigError, DeleteAgentConfigResponse, ListAgentRuntimesError, ListAgentRuntimesResponse, VerifyPlatformWebhookData, VerifyPlatformWebhookError, VerifyPlatformWebhookResponse, ReceivePlatformWebhookData, ReceivePlatformWebhookError, ReceivePlatformWebhookResponse, ListWorkbenchViewsError, ListWorkbenchViewsResponse, GetWorkbenchViewData, GetWorkbenchViewError, GetWorkbenchViewResponse, GetChatViewApiV1ChatViewsViewIdGetData, GetChatViewApiV1ChatViewsViewIdGetError, GetChatViewApiV1ChatViewsViewIdGetResponse, RunChatViewActionApiV1ChatViewsViewIdActionsPostData, RunChatViewActionApiV1ChatViewsViewIdActionsPostError, RunChatViewActionApiV1ChatViewsViewIdActionsPostResponse, GetChatViewActionApiV1ChatViewsViewIdActionsInteractionIdGetData, GetChatViewActionApiV1ChatViewsViewIdActionsInteractionIdGetError, GetChatViewActionApiV1ChatViewsViewIdActionsInteractionIdGetResponse } from './types.gen'; export const client = createClient(createConfig()); @@ -822,6 +822,17 @@ export const deleteChatSession = (options: }); }; +/** + * Apply a ChatUI permission mode change to running work + * Sub-agents and later tool calls of a running turn in this conversation use the new mode from their next tool call. Only the caller's own WebChat conversations are accepted (403 otherwise). Scheduled runs are never given full access this way. + */ +export const setChatPermissionMode = (options: OptionsLegacyParser) => { + return (options?.client ?? client).put({ + ...options, + url: '/api/v1/chat/sessions/{session_id}/permission-mode' + }); +}; + /** * Stop active webchat work for a session */ diff --git a/dashboard/src/api/generated/openapi-v1/types.gen.ts b/dashboard/src/api/generated/openapi-v1/types.gen.ts index 2f6b53501a..2054f2a712 100644 --- a/dashboard/src/api/generated/openapi-v1/types.gen.ts +++ b/dashboard/src/api/generated/openapi-v1/types.gen.ts @@ -107,6 +107,7 @@ export type ChatMessageRegenerateRequest = { locale?: string; selected_provider?: string; selected_model?: string; + permission_mode?: ChatPermissionMode; /** * Deprecated compatibility field. It is used only when flags.enable_streaming is absent; otherwise flags.enable_streaming takes priority. * @deprecated @@ -115,6 +116,15 @@ export type ChatMessageRegenerateRequest = { flags?: ChatFlags; }; +/** + * ChatUI permission mode of the conversation for this request. It only narrows the role's configured access (workspace), skips approval prompts (full), or does both (workspace_no_ask); omit to ask for approval as configured. + */ +export type ChatPermissionMode = 'workspace' | 'workspace_no_ask' | 'ask' | 'full'; + +export type ChatPermissionModeRequest = { + mode: ChatPermissionMode; +}; + export type ChatProjectRequest = { title?: string; emoji?: string; @@ -153,6 +163,7 @@ export type ChatRequest = { config_name?: string; selected_provider?: string; selected_model?: string; + permission_mode?: ChatPermissionMode; /** * Deprecated compatibility field. It is used only when flags.enable_streaming is absent; otherwise flags.enable_streaming takes priority. * @deprecated @@ -199,6 +210,7 @@ export type ChatThreadMessageRequest = { message: (string | Array); selected_provider?: string; selected_model?: string; + permission_mode?: ChatPermissionMode; /** * Deprecated compatibility field. It is used only when flags.enable_streaming is absent; otherwise flags.enable_streaming takes priority. * @deprecated @@ -1579,6 +1591,17 @@ export type DeleteChatSessionResponse = (SuccessEnvelope); export type DeleteChatSessionError = unknown; +export type SetChatPermissionModeData = { + body: ChatPermissionModeRequest; + path: { + session_id: string; + }; +}; + +export type SetChatPermissionModeResponse = (SuccessEnvelope); + +export type SetChatPermissionModeError = (unknown); + export type StopChatSessionData = { path: { session_id: string; diff --git a/dashboard/src/i18n/locales/en-US/features/config-metadata.json b/dashboard/src/i18n/locales/en-US/features/config-metadata.json index f646698137..6ae30d3abe 100644 --- a/dashboard/src/i18n/locales/en-US/features/config-metadata.json +++ b/dashboard/src/i18n/locales/en-US/features/config-metadata.json @@ -492,6 +492,15 @@ "tool_call_timeout": { "description": "Tool Call Timeout (seconds)" }, + "tool_approval": { + "tools": { + "description": "Tools requiring approval", + "hint": "Listed tools wait for the requester to click Allow or reply with the confirmation code before running. Leave empty to disable. Approving the creation or edit of a scheduled task also approves the listed tools it uses when it runs." + }, + "timeout": { + "description": "Tool approval timeout (seconds)" + } + }, "sanitize_context_by_modalities": { "description": "Sanitize History by Modalities", "hint": "When enabled, sanitizes contexts before each LLM request by removing image blocks and tool-call structures that the current provider's modalities do not support (this changes what the model sees)." diff --git a/dashboard/src/i18n/locales/ja-JP/features/config-metadata.json b/dashboard/src/i18n/locales/ja-JP/features/config-metadata.json index 2cb5d0bfa8..487ed310f3 100644 --- a/dashboard/src/i18n/locales/ja-JP/features/config-metadata.json +++ b/dashboard/src/i18n/locales/ja-JP/features/config-metadata.json @@ -595,6 +595,15 @@ "tool_call_timeout": { "description": "ツール呼び出しタイムアウト(秒)" }, + "tool_approval": { + "tools": { + "description": "承認が必要なツール", + "hint": "リスト内のツールは、依頼者が「許可」を押すか確認コードを返信するまで実行されません。空欄で無効。予約タスクの作成・編集を承認すると、そのタスクの実行時に使うリスト内ツールも承認されます。" + }, + "timeout": { + "description": "ツール承認のタイムアウト(秒)" + } + }, "sanitize_context_by_modalities": { "description": "モデル機能に応じて履歴コンテキストをクリーンアップ", "hint": "有効にすると、LLM への各リクエスト前に、現在のモデルプロバイダーで選択したモデルの機能に応じて、未対応の画像やツール呼び出し構造を会話から削除します(モデルが参照する履歴が変わります)。" diff --git a/dashboard/src/i18n/locales/ru-RU/features/config-metadata.json b/dashboard/src/i18n/locales/ru-RU/features/config-metadata.json index 355864fbc8..b466bfdae9 100644 --- a/dashboard/src/i18n/locales/ru-RU/features/config-metadata.json +++ b/dashboard/src/i18n/locales/ru-RU/features/config-metadata.json @@ -595,6 +595,15 @@ "tool_call_timeout": { "description": "Таймаут вызова инструмента (сек)" }, + "tool_approval": { + "tools": { + "description": "Инструменты, требующие подтверждения", + "hint": "Перечисленные инструменты ждут, пока инициатор нажмёт «Разрешить» или ответит кодом подтверждения. Оставьте пустым, чтобы отключить. Подтверждение создания или изменения запланированной задачи также подтверждает перечисленные инструменты, которые она использует при запуске." + }, + "timeout": { + "description": "Тайм-аут подтверждения инструмента (секунды)" + } + }, "sanitize_context_by_modalities": { "description": "Очистка истории по модальностям", "hint": "Если включено, очищает контекст перед запросом, удаляя блоки (например, изображения), которые не поддерживаются выбранным провайдером." diff --git a/dashboard/src/i18n/locales/zh-CN/features/config-metadata.json b/dashboard/src/i18n/locales/zh-CN/features/config-metadata.json index 2552cb27c0..315db1102c 100644 --- a/dashboard/src/i18n/locales/zh-CN/features/config-metadata.json +++ b/dashboard/src/i18n/locales/zh-CN/features/config-metadata.json @@ -511,6 +511,15 @@ "tool_call_timeout": { "description": "工具调用超时时间(秒)" }, + "tool_approval": { + "tools": { + "description": "需要审批的工具", + "hint": "名单内的工具执行前需要发起人点击「允许」或回复确认码。留空表示不审批。批准创建或修改定时任务时,也会批准该任务到点运行时用到的名单内工具。" + }, + "timeout": { + "description": "工具审批超时时间(秒)" + } + }, "sanitize_context_by_modalities": { "description": "按模型能力清理历史上下文", "hint": "开启后,在每次请求 LLM 前会按当前模型提供商中所选择的模型能力删除对话中不支持的图片/工具调用结构(会改变模型看到的历史)" diff --git a/docs/en/dev/openapi-scopes.md b/docs/en/dev/openapi-scopes.md index b10abed353..51e1e11377 100644 --- a/docs/en/dev/openapi-scopes.md +++ b/docs/en/dev/openapi-scopes.md @@ -167,6 +167,7 @@ Use chat capabilities and manage ChatUI sessions and projects. | `DELETE` | `/api/v1/chat/sessions/{session_id}` | — | | `PATCH` | `/api/v1/chat/sessions/{session_id}/messages/{message_id}` | — | | `POST` | `/api/v1/chat/sessions/{session_id}/messages/{message_id}/regenerate` | — | +| `PUT` | `/api/v1/chat/sessions/{session_id}/permission-mode` | — | | `POST` | `/api/v1/chat/sessions/{session_id}/stop` | — | | `POST` | `/api/v1/chat/threads` | — | | `GET` | `/api/v1/chat/threads/{thread_id}` | — | diff --git a/docs/public/openapi.json b/docs/public/openapi.json index 0a77c3ac94..f059474257 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -1954,6 +1954,40 @@ "description": "**Required scope:** `chat`" } }, + "/api/v1/chat/sessions/{session_id}/permission-mode": { + "put": { + "tags": [ + "Chat" + ], + "summary": "Apply a ChatUI permission mode change to running work", + "description": "Sub-agents and later tool calls of a running turn in this conversation use the new mode from their next tool call. Only the caller's own WebChat conversations are accepted (403 otherwise). Scheduled runs are never given full access this way.\n\n**Required scope:** `chat`", + "operationId": "setChatPermissionMode", + "x-astrbot-scope": "chat", + "parameters": [ + { + "$ref": "#/components/parameters/SessionId" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ChatPermissionModeRequest" + } + } + } + }, + "responses": { + "200": { + "$ref": "#/components/responses/Ok" + }, + "403": { + "description": "The conversation is not the caller's WebChat session." + } + } + } + }, "/api/v1/chat/sessions/{session_id}/stop": { "post": { "tags": [ @@ -7782,6 +7816,9 @@ "selected_model": { "type": "string" }, + "permission_mode": { + "$ref": "#/components/schemas/ChatPermissionMode" + }, "enable_streaming": { "type": "boolean", "default": true, @@ -7847,6 +7884,28 @@ }, "additionalProperties": false }, + "ChatPermissionMode": { + "type": "string", + "enum": [ + "workspace", + "workspace_no_ask", + "ask", + "full" + ], + "description": "ChatUI permission mode of the conversation for this request. It only narrows the role's configured access (workspace), skips approval prompts (full), or does both (workspace_no_ask); omit to ask for approval as configured." + }, + "ChatPermissionModeRequest": { + "type": "object", + "required": [ + "mode" + ], + "properties": { + "mode": { + "$ref": "#/components/schemas/ChatPermissionMode" + } + }, + "additionalProperties": false + }, "ChatMessageRegenerateRequest": { "type": "object", "properties": { @@ -7860,6 +7919,9 @@ "selected_model": { "type": "string" }, + "permission_mode": { + "$ref": "#/components/schemas/ChatPermissionMode" + }, "enable_streaming": { "type": "boolean", "default": true, @@ -7928,6 +7990,9 @@ "selected_model": { "type": "string" }, + "permission_mode": { + "$ref": "#/components/schemas/ChatPermissionMode" + }, "enable_streaming": { "type": "boolean", "default": true, diff --git a/docs/zh/dev/openapi-scopes.md b/docs/zh/dev/openapi-scopes.md index 25e0515b1d..de46fb6d9f 100644 --- a/docs/zh/dev/openapi-scopes.md +++ b/docs/zh/dev/openapi-scopes.md @@ -167,6 +167,7 @@ outline: deep | `DELETE` | `/api/v1/chat/sessions/{session_id}` | — | | `PATCH` | `/api/v1/chat/sessions/{session_id}/messages/{message_id}` | — | | `POST` | `/api/v1/chat/sessions/{session_id}/messages/{message_id}/regenerate` | — | +| `PUT` | `/api/v1/chat/sessions/{session_id}/permission-mode` | — | | `POST` | `/api/v1/chat/sessions/{session_id}/stop` | — | | `POST` | `/api/v1/chat/threads` | — | | `GET` | `/api/v1/chat/threads/{thread_id}` | — | diff --git a/openspec/openapi-v1.yaml b/openspec/openapi-v1.yaml index 76a2203464..cf314b6b24 100644 --- a/openspec/openapi-v1.yaml +++ b/openspec/openapi-v1.yaml @@ -1373,6 +1373,27 @@ paths: "200": $ref: "#/components/responses/Ok" + /api/v1/chat/sessions/{session_id}/permission-mode: + put: + tags: [Chat] + summary: Apply a ChatUI permission mode change to running work + description: Sub-agents and later tool calls of a running turn in this conversation use the new mode from their next tool call. Only the caller's own WebChat conversations are accepted (403 otherwise). Scheduled runs are never given full access this way. + operationId: setChatPermissionMode + x-astrbot-scope: chat + parameters: + - $ref: "#/components/parameters/SessionId" + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/ChatPermissionModeRequest" + responses: + "200": + $ref: "#/components/responses/Ok" + "403": + description: The conversation is not the caller's WebChat session. + /api/v1/chat/sessions/{session_id}/stop: post: tags: [Chat] @@ -6363,6 +6384,8 @@ components: type: string selected_model: type: string + permission_mode: + $ref: "#/components/schemas/ChatPermissionMode" enable_streaming: type: boolean default: true @@ -6410,6 +6433,19 @@ components: additionalProperties: true additionalProperties: false + ChatPermissionMode: + type: string + enum: [workspace, workspace_no_ask, ask, full] + description: ChatUI permission mode of the conversation for this request. It only narrows the role's configured access (workspace), skips approval prompts (full), or does both (workspace_no_ask); omit to ask for approval as configured. + + ChatPermissionModeRequest: + type: object + required: [mode] + properties: + mode: + $ref: "#/components/schemas/ChatPermissionMode" + additionalProperties: false + ChatMessageRegenerateRequest: type: object properties: @@ -6420,6 +6456,8 @@ components: type: string selected_model: type: string + permission_mode: + $ref: "#/components/schemas/ChatPermissionMode" enable_streaming: type: boolean default: true @@ -6460,6 +6498,8 @@ components: type: string selected_model: type: string + permission_mode: + $ref: "#/components/schemas/ChatPermissionMode" enable_streaming: type: boolean default: true From d20896db1fcb556aba16f4da86e1ac7228a266dd Mon Sep 17 00:00:00 2001 From: Turino Date: Thu, 26 Nov 2026 15:09:14 +1000 Subject: [PATCH 2/4] feat(dashboard): dock approval cards and add a permission mode pill MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Per-conversation options are stored in one browser entry per conversation (chatSessionPrefs), spread into every chat request and cleared when the conversation is deleted or the user logs out. The newest open approval card is docked above the chat input; answered cards fold into the run details. Tool cards show a waiting state while their approval is pending. A pill next to + selects the conversation's permission mode; "Don't ask again" from workspace shows as "Workspace · not asking". --- dashboard/src/api/v1.ts | 11 + .../src/components/chat/ButtonActionRow.vue | 339 +++++++++++++++++- dashboard/src/components/chat/Chat.vue | 99 ++++- dashboard/src/components/chat/ChatInput.vue | 95 ++++- dashboard/src/components/chat/ThreadPanel.vue | 71 ++-- .../message_list_comps/ReasoningTimeline.vue | 4 + .../chat/message_list_comps/ToolCallCard.vue | 24 +- .../src/composables/useActionRowChoices.ts | 139 +++++++ dashboard/src/composables/useMessages.ts | 176 +++++++-- dashboard/src/composables/useSessions.ts | 11 +- .../src/i18n/locales/en-US/features/chat.json | 31 +- .../src/i18n/locales/ja-JP/features/chat.json | 31 +- .../src/i18n/locales/ru-RU/features/chat.json | 31 +- .../src/i18n/locales/zh-CN/features/chat.json | 31 +- dashboard/src/utils/chatPreferences.ts | 2 + dashboard/src/utils/chatSessionPrefs.mjs | 67 ++++ 16 files changed, 1101 insertions(+), 61 deletions(-) create mode 100644 dashboard/src/composables/useActionRowChoices.ts create mode 100644 dashboard/src/utils/chatSessionPrefs.mjs diff --git a/dashboard/src/api/v1.ts b/dashboard/src/api/v1.ts index e47220a926..18b44227d9 100644 --- a/dashboard/src/api/v1.ts +++ b/dashboard/src/api/v1.ts @@ -867,6 +867,17 @@ export const chatApi = { batchDeleteSessions(payload: ChatSessionBatchDeleteRequest) { return typed(openApiV1.batchDeleteChatSessions({ body: payload })); }, + setPermissionMode( + sessionId: string, + mode: "workspace" | "workspace_no_ask" | "ask" | "full", + ) { + return typed<{ mode: string }>( + openApiV1.setChatPermissionMode({ + path: { session_id: sessionId }, + body: { mode }, + }), + ); + }, stopSession(sessionId: string) { return typed( openApiV1.stopChatSession({ path: { session_id: sessionId } }), diff --git a/dashboard/src/components/chat/ButtonActionRow.vue b/dashboard/src/components/chat/ButtonActionRow.vue index 2b4c134656..b36ffc36e4 100644 --- a/dashboard/src/components/chat/ButtonActionRow.vue +++ b/dashboard/src/components/chat/ButtonActionRow.vue @@ -1,6 +1,64 @@