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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -205,3 +205,6 @@ webui/backend/.env.*

# Prepared frontend manifests are included in release archives, not source Git.
webui/RESOURCE-MANIFEST.json

# Test-generated execution traces.
/tests/skills/demo_traces/
3 changes: 3 additions & 0 deletions ms_agent/agent/agent.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ callbacks:
- input_callback

tools:
# Requires a host QuestionHandler; set enabled: false to disable.
ask_user:
mcp: false
file_system:
mcp: false
include:
Expand Down
19 changes: 19 additions & 0 deletions ms_agent/agent/llm_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,11 @@ def __init__(
# _select_permission_handler() picks by mode + interactivity.
self._permission_handler = kwargs.get('permission_handler', None)

# Optional injected QuestionHandler (TUI/WebUI/Server) — the seam the
# ask_user_question tool consults. When None nobody can be asked, and
# the tool is not registered at all (see ToolManager).
self._question_handler = kwargs.get('question_handler', None)

# Structured event sink — the UI-agnostic output seam (ms_agent.ui).
# When set, the agent emits semantic AgentEvents (content / reasoning /
# tool / ...) that a TUI renders and a WebUI backend forwards. When
Expand Down Expand Up @@ -1094,6 +1099,19 @@ def set_permission_handler(self, handler) -> None:
"""Inject a custom PermissionHandler (TUI/WebUI/Server) before run."""
self._permission_handler = handler

def _select_question_handler(self):
"""Use host interaction for main agents; subagents cannot ask directly."""
from ms_agent.interaction import AutoQuestionHandler
if getattr(self.config, 'ms_agent_subagent', False):
return AutoQuestionHandler()
if self._question_handler is not None:
return self._question_handler
return AutoQuestionHandler()

def set_question_handler(self, handler) -> None:
"""Inject the question handler before preparing tools."""
self._question_handler = handler

def set_permission_mode(self, mode: str) -> str:
"""Change the permission mode at runtime; returns the normalized mode.

Expand Down Expand Up @@ -1203,6 +1221,7 @@ async def prepare_tools(self):
read_policy=perm_config.safety.read_policy,
hook_runtime=hook_runtime,
permission_config=perm_config,
question_handler=self._select_question_handler(),
trust_remote_code=self.trust_remote_code,
mcp_callable_check=mcp_rt.is_callable if mcp_rt else None,
mcp_failure_handler=self._on_mcp_failure if mcp_rt else None,
Expand Down
14 changes: 14 additions & 0 deletions ms_agent/interaction/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Copyright (c) ModelScope Contributors. All rights reserved.
"""Host-side user question handlers."""

from .handler import (QUESTION_ASK_TIMEOUT, AutoQuestionHandler,
QuestionEventEmitter, WebQuestionHandler,
make_question_handler)

__all__ = [
'AutoQuestionHandler',
'WebQuestionHandler',
'QuestionEventEmitter',
'QUESTION_ASK_TIMEOUT',
'make_question_handler',
]
243 changes: 243 additions & 0 deletions ms_agent/interaction/handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,243 @@
# Copyright (c) ModelScope Contributors. All rights reserved.
"""UI-independent question handling, separate from permission decisions."""
from __future__ import annotations

import asyncio
import math
import os
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Protocol
from uuid import uuid4

from ms_agent.ui.interaction import (CUSTOM_OPTION_ID, Answer, AnswerStatus,
Question, QuestionReply)

# Wait indefinitely by default; read environment overrides at construction.
QUESTION_ASK_TIMEOUT: float | None = None

UNAVAILABLE_NOTE = (
'No interactive channel is available, so this question could not be put '
'to anyone. Do not try again. Decide using the most reasonable default, '
'and state plainly which assumption you made.')

SKIPPED_NOTE = ('The user chose not to answer. Proceed with the most '
'reasonable default and say which assumption you made, or '
'stop and explain what you still need.')

CANCELLED_NOTE = ('This question was withdrawn before it was answered (the '
'turn was stopped or the session closed). Nobody declined '
'anything — stop here rather than guessing.')


def _timeout_note(seconds: float) -> str:
return (f'No answer within {seconds:.0f}s. This is a TIMEOUT, not a '
'choice or a refusal. Do not ask it again; continue only with a '
'safe stated assumption, or explain what information is missing.')


class QuestionEventEmitter(Protocol):
"""Protocol for pushing a raw question event to the host's transport."""

def emit(self, event: Dict[str, Any]) -> None:
...


class AutoQuestionHandler:
"""Report unavailable interaction without fabricating answers."""

supports_questions = False

async def ask(self,
questions: List[Question],
call_id: str = '') -> QuestionReply:
return QuestionReply(
status=AnswerStatus.UNAVAILABLE, note=UNAVAILABLE_NOTE)


@dataclass
class _PendingQuestion:
"""One ask the user has not answered yet, and what it was about."""
future: 'asyncio.Future[QuestionReply]'
questions: List[Question]
call_id: str


class WebQuestionHandler:
"""Await answers by request ID, independently of permission state."""

supports_questions = True

def __init__(
self,
event_emitter: QuestionEventEmitter,
timeout: float | None = QUESTION_ASK_TIMEOUT,
) -> None:
self._pending: Dict[str, _PendingQuestion] = {}
self._event_emitter = event_emitter
raw_timeout = os.environ.get('MSA_QUESTION_TIMEOUT')
if timeout is None and raw_timeout:
timeout = float(raw_timeout)
if timeout is not None and (not math.isfinite(timeout)
or timeout <= 0):
raise ValueError(
'Question timeout must be a positive finite number')
self._timeout = timeout

async def ask(self,
questions: List[Question],
call_id: str = '') -> QuestionReply:
request_id = uuid4().hex
loop = asyncio.get_running_loop()
future: 'asyncio.Future[QuestionReply]' = loop.create_future()
questions = list(questions)
# Register before emitting so immediate answers resolve correctly.
# Emit inside try/finally so failures cannot leak a pending request.
self._pending[request_id] = _PendingQuestion(
future=future,
questions=questions,
call_id=str(call_id or ''),
)
try:
self._event_emitter.emit({
'type':
'question_requested',
'request_id':
request_id,
'call_id':
str(call_id or ''),
'questions': [q.to_dict() for q in questions],
})
if self._timeout is None:
return await future
return await asyncio.wait_for(future, timeout=self._timeout)
except asyncio.TimeoutError:
return QuestionReply(
status=AnswerStatus.TIMEOUT,
note=_timeout_note(self._timeout or 0.0),
)
finally:
self._pending.pop(request_id, None)
if not future.done():
future.cancel()

# -- host-facing state ---------------------------------------------------

def awaiting_request_ids(self) -> set:
"""Return pending request IDs for reconnects."""
return {
request_id
for request_id, pending in self._pending.items()
if not pending.future.done()
}

def is_awaiting(self, request_id: str) -> bool:
"""Check whether a request still awaits an answer."""
pending = self._pending.get(request_id)
return pending is not None and not pending.future.done()

def pending_questions(self, request_id: str) -> List[Question]:
"""The questions of one open ask (for a host that re-renders them)."""
pending = self._pending.get(request_id)
return list(pending.questions) if pending else []

# -- resolution ----------------------------------------------------------

def resolve(self, request_id: str, answers: List[Answer]) -> bool:
"""Validate a complete answer set; reject invalid or repeated submissions."""
pending = self._pending.get(request_id)
if pending is None or pending.future.done():
# Covers the ordinary races: a second click, a submission from
# another tab, an answer arriving after the ask expired.
return False
validated = self._validate(pending.questions, answers)
if validated is None:
return False
pending.future.set_result(
QuestionReply(status=AnswerStatus.ANSWERED, answers=validated))
return True

def skip(self, request_id: str) -> bool:
"""The user declined to answer. Distinct from a cancel: they SAW it."""
pending = self._pending.get(request_id)
if pending is None or pending.future.done():
return False
pending.future.set_result(
QuestionReply(status=AnswerStatus.SKIPPED, note=SKIPPED_NOTE))
return True

def cancel_pending(self, note: str = CANCELLED_NOTE) -> int:
"""Resolve pending requests before the host cancels execution."""
resolved = 0
for request_id, pending in list(self._pending.items()):
if pending.future.done():
continue
pending.future.set_result(
QuestionReply(status=AnswerStatus.CANCELLED, note=note))
resolved += 1
self._pending.pop(request_id, None)
return resolved

# -- internals -----------------------------------------------------------

@staticmethod
def _validate(questions: List[Question],
answers: List[Answer]) -> List[Answer] | None:
"""Validate IDs and derive labels from the original options."""
by_id = {q.id: q for q in questions}
seen: set = set()
out: List[Answer] = []
for answer in answers:
question = by_id.get(answer.question_id)
if question is None or answer.question_id in seen:
return None # unknown or duplicated question
seen.add(answer.question_id)
option_ids = list(answer.option_ids)
if len(option_ids) != len(set(option_ids)):
return None
custom = answer.custom_text.strip()
if len(custom) > 2000:
return None
if CUSTOM_OPTION_ID in option_ids:
if not question.allow_custom or not custom:
return None
elif custom:
return None # free text without claiming the custom option
if not option_ids:
return None # an answered question must carry a choice
if not question.multi_select and len(option_ids) > 1:
return None
labels: List[str] = []
for option_id in option_ids:
if option_id == CUSTOM_OPTION_ID:
labels.append(custom)
continue
option = question.option(option_id)
if option is None:
return None
labels.append(option.label)
out.append(
Answer(
question_id=answer.question_id,
option_ids=option_ids,
labels=labels,
custom_text=custom,
))
if seen != set(by_id):
return None
# Preserve question order regardless of submission order.
answers_by_id = {a.question_id: a for a in out}
return [answers_by_id[q.id] for q in questions]


def make_question_handler(
emit: Callable[[Dict[str, Any]], None],
timeout: float | None = QUESTION_ASK_TIMEOUT,
) -> WebQuestionHandler:
"""Convenience for hosts that have a callable rather than an emitter."""

class _Emitter:

def emit(self, event: Dict[str, Any]) -> None:
emit(event)

return WebQuestionHandler(_Emitter(), timeout=timeout)
6 changes: 5 additions & 1 deletion ms_agent/plugins/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,11 @@
'Glob': ('file_system', ),
'Skill': (), # skills are injected separately
'TodoWrite': ('todo_list', ),
'AskUserQuestion': (), # no dedicated tool yet
# Maps to the ask_user tool, though a SUB-agent (which is what a plugin
# agent is) does not get to ask: _withhold_ask_user strips the key when the
# sub-agent is built. Declared anyway so the translation stays truthful and
# so lifting that restriction is a one-place change.
'AskUserQuestion': ('ask_user', ),
'Task': ('agent_tools', ),
}

Expand Down
3 changes: 3 additions & 0 deletions ms_agent/prompting/builtin.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@
say you don't know.
- Prefer doing over asking when the action is safe and easy to undo. Ask first
when it isn't, and ask everything you need in one round.
- Stay within the user's requested scope and stopping point. For plan-only,
research-only, or advice-only tasks, deliver the requested result and stop;
do not start implementation or ask to authorize a new phase unless requested.
- Report outcomes honestly, including steps that failed or were skipped.
- Respond in the language the user is using; switch when they switch.

Expand Down
28 changes: 28 additions & 0 deletions ms_agent/session/session_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,17 @@ def record_permission(self, event: Dict[str, Any]) -> None:
}
self._append_line(record)

def record_question(self, event: Dict[str, Any]) -> None:
"""Record UI-only history; answers enter model context as tool results."""
seq = self._next_seq()
record = {
'_type': 'question',
'seq': seq,
'timestamp': datetime.now(timezone.utc).isoformat(),
**event,
}
self._append_line(record)

def record_skill_invocation(self, event: Dict[str, Any]) -> None:
"""Record a slash-skill invocation — a display-only marker.

Expand Down Expand Up @@ -546,6 +557,23 @@ def get_permissions(self) -> List[Dict[str, Any]]:
perms.append(record)
return perms

def get_questions(self) -> List[Dict[str, Any]]:
"""Read question history in sequence order."""
questions: List[Dict[str, Any]] = []
if not self._path.exists():
return questions
for line in self._path.read_text(encoding='utf-8').splitlines():
line = line.strip()
if not line:
continue
try:
record = json.loads(line)
except json.JSONDecodeError:
continue
if record.get('_type') == 'question':
questions.append(record)
return questions

def get_loop_ends(self) -> List[Dict[str, Any]]:
"""All tool-call-loop boundary markers in chronological order (each
keeps its ``seq``). Excluded from ``get_all_messages`` (and the LLM
Expand Down
Loading
Loading