"""Direct-execution limits and tool-confirmation grant language policy."""
from __future__ import annotations
import re
from app.models.chat import ChatCompletionRequest
from app.services.direct_command_sessions import is_continuation_request
_NON_EXECUTION_TOOL_NAMES = frozenset({
"verify_run_benchmark", "verify_check_npu_status",
"quantify_run_msmodelslim", "quantify_sensitivity_analysis",
"adapt_review_repo", "adapt_generate_compat_layer",
"optimizer_torch_npu_optimize", "optimizer_npu_profiling",
"optimizer_triton_op_optimize",
"deploy_model_deployment", "deploy_esm2_demo",
"invoke_claude_skill",
"generate_word_document", "write_workspace_text_file",
"write_workspace_word_document",
"doc_agent_one_click_generate", "doc_agent_generate_local",
"doc_agent_example_qwen35_flow", "doc_agent_example_qwen3_8b",
})
_NON_EXECUTION_COMMAND_NAMES = frozenset({
"claude", "verify", "adapt", "optimize", "quantify", "deploy",
"workflow", "commit", "torch",
})
_DIRECT_EXECUTION_EXCLUSION_RE = re.compile(
r"(?:不要|禁止|请勿|暂不|不需要|无需|不)(?:实际)?执行"
r"|明确排除[\s\S]{0,40}实际执行"
r"|实际执行[\s\S]{0,20}(?:明确排除|不要|禁止|请勿|暂不|不执行)",
re.IGNORECASE,
)
_ANALYSIS_ONLY_RE = re.compile(
r"(?:只|仅)(?:做|进行)?(?:分析|说明|评估|给出方案)",
re.IGNORECASE,
)
_NEGATED_ANALYSIS_ONLY_PREFIX_RE = re.compile(
r"(?:不|并非|并不是|不是|不要|不能|别)(?:仅|只)?$",
re.IGNORECASE,
)
_EXECUTION_AFTER_ANALYSIS_RE = re.compile(
r"^[\s,,、;;]*(?:(?:但|而且|并且|同时|还|也|而是)[\s,,、;;]*)?"
r"(?:(?:需(?:要)?|要|必须|请|直接|实际)[\s]*)*"
r"(?:执行|运行|部署|验证|测试|跑)",
re.IGNORECASE,
)
def has_explicit_execution_exclusion(text: str) -> bool:
"""Recognize an explicit no-execution constraint without matching auth text."""
value = str(text or "")
if _DIRECT_EXECUTION_EXCLUSION_RE.search(value):
return True
for match in _ANALYSIS_ONLY_RE.finditer(value):
prefix = value[max(0, match.start() - 4):match.start()]
if _NEGATED_ANALYSIS_ONLY_PREFIX_RE.search(prefix):
continue
if _EXECUTION_AFTER_ANALYSIS_RE.search(value[match.end():match.end() + 40]):
continue
return True
return False
_SHELL_TASK_COMMAND_RE = re.compile(
r"\b(?:git\s+(?:clone|fetch|pull|push)|bash\s+[^\s;]+)\b",
re.IGNORECASE,
)
_SHELL_TASK_REQUEST_RE = re.compile(
r"\b(?:run\s+(?:these|the\s+following)\s+steps|do\s+the\s+following|"
r"execute\s+(?:these|the\s+following)\s+steps)\b|"
r"(?:请|帮我|直接)(?:在.{0,20})?(?:执行|运行)(?:以下|这些|这条)?(?:命令|步骤)",
re.IGNORECASE,
)
_BARE_SHELL_COMMAND_RE = re.compile(
r"^\s*(?:git\s+(?:clone|fetch|pull|push)|bash\s+[^\s;]+)(?:\s|$)",
re.IGNORECASE,
)
def is_explicit_shell_task(text: str) -> bool:
"""Route only concrete, affirmative shell requests to the local executor."""
value = str(text or "").strip()
if not value or has_explicit_execution_exclusion(value):
return False
return bool(
_SHELL_TASK_COMMAND_RE.search(value)
and (_BARE_SHELL_COMMAND_RE.match(value) or _SHELL_TASK_REQUEST_RE.search(value))
)
def _request_excludes_execution(request: ChatCompletionRequest) -> bool:
"""Carry an original restriction into an explicit continuation only."""
messages = list(request.messages or [])
latest = str(messages[-1].content or "") if messages else ""
if has_explicit_execution_exclusion(latest):
return True
if not is_continuation_request(latest):
return False
return any(
has_explicit_execution_exclusion(str(message.content or ""))
for message in messages[:-1]
if getattr(message, "role", "") == "user"
)
_GRANT_TOOL_CONFIRM_RE = re.compile(
r"直接(完成|执行|干|搞|来|办|选|进入|动手|推进|开始|按)|"
r"无需(再)?(确认|询问)|不用(再)?(确认|问|等)|不需要(再)?(确认|问|等)|"
r"已获授权|授权直接|"
r"别(再)?(问|确认)|不要(再)?(问|确认)|"
r"不要(?:再)?(?:停在|一直|反复|总是|不断|老是|继续|每次|每步)?确认|"
r"(?<![等在盼想起叫])你(来(办|处理|负责|安排|搞定|弄|做|执行|干|决定|定|管|操作|协调|落实|吧|$)|定|决定|看着办)|"
r"(?<![等在盼])交给你(办|处理|负责|安排|搞定|去做|管|操作|了|吧|$)|"
r"听你的|按你说的|"
r"自动(完成|执行|继续|跑)|随便(执行|跑|弄)|"
r"just\s+do\s+it|auto\s+proceed",
re.IGNORECASE,
)
_AUTO_CONFIRM_QUESTION_RE = re.compile(r"[??]\s*$|吗\s*$|呢\s*$")
_AUTO_CONFIRM_REVOKE_RE = re.compile(
r"(?:不要(?!再?(?:问|确认))(?!再?停在(?:确认|原地|那))(?!再?(?:一直|反复|总是|不断|老是|继续|每次|每步)确认(?=\s*[。,,!!??]|请|$))|别(?!再?(?:问|确认))|不想|不希望|禁止|请勿|暂不|先别).{0,12}"
r"(?:直接|自动|执行|完成|处理|部署|运行|操作)|"
r"(?:等等|等一下|稍等|先别|不要了|算了|取消|不同意|反对|拒绝|reject|再看看|再考虑)|"
r"(?<!不需要再)(?<!不用再)(?<!无需再)(?<!不需要)(?<!不用)(?<!无需)"
r"(?:等|等待|正在等|我在等|盼|期盼).{0,8}"
r"(?:你来|你决定|你处理|结果|完成|执行)|"
r"(?:我在|正在|目前|还在).{0,8}等待",
re.IGNORECASE,
)
_GRANT_NEGATION_PREFIX_CHARS = "不别勿莫难没未休"
_GRANT_NEGATION_SUFFIXES = ("不了", "不成", "不行", "不是", "不得")
def _grant_match(msg: str) -> re.Match[str] | None:
"""首个非否定语境的授权匹配;逐匹配检查,只跳过被否定的那个。"""
for m in _GRANT_TOOL_CONFIRM_RE.finditer(msg):
before = msg[:m.start()].rstrip(",,。!!??、 \t")
if before and before[-1] in _GRANT_NEGATION_PREFIX_CHARS:
continue
if msg[m.end():].startswith(_GRANT_NEGATION_SUFFIXES):
continue
return m
return None
def _next_auto_confirm_state(current: bool, msg: str) -> bool:
"""按单条用户消息计算会话授权新状态(纯函数,便于测试)。
优先级:撤回授权 > 问句征询(不改状态) > 显式授权。
问句("可以直接完成吗?")是征询许可而非放行,不得据此豁免确认。
撤销判定仅使用 _AUTO_CONFIRM_REVOKE_RE,不复用 brainstorm 的负向词表。
"""
if not msg:
return current
msg = msg.strip()
if _AUTO_CONFIRM_REVOKE_RE.search(msg):
return False
if _AUTO_CONFIRM_QUESTION_RE.search(msg):
return current
if _grant_match(msg):
return True
return current
_READ_ONLY_AUTO_TOOLS = frozenset({
"list_claude_skills", "search_ascend_models", "verify_check_npu_status",
})
_TOOL_CONFIRM_ALWAYS = frozenset({"deploy_model_deployment", "deploy_esm2_demo"})
_ADAPT_TASK_REQUEST_RE = re.compile(
r"(?:帮我|请|开始|实际|直接).{0,24}适配|"
r"\b(?:please|can you|could you)\s+adapt\b",
re.IGNORECASE,
)
_READ_ONLY_REQUEST_RE = re.compile(
r"(?:只读|仅读|不修改|不安装).{0,20}(?:检查|探测|查询)|"
r"(?:检查|探测|查询).{0,20}(?:只读|仅读)|"
r"\b(?:read[ -]?only|inspect|check)\b.{0,30}\b(?:environment|npu|status)\b",
re.IGNORECASE,
)
def tool_confirmation_bypass_kind(
tool_calls: list[dict], user_text: str, *, session_authorized: bool,
execution_excluded: bool,
) -> str | None:
"""Return the single-turn reason a tool batch can run without another prompt."""
names = {str(call.get("name") or "") for call in tool_calls}
if not names or names & _TOOL_CONFIRM_ALWAYS:
return None
if execution_excluded and not names <= _READ_ONLY_AUTO_TOOLS:
return None
if session_authorized:
return "session"
if names <= _READ_ONLY_AUTO_TOOLS and (
_ADAPT_TASK_REQUEST_RE.search(user_text)
or _READ_ONLY_REQUEST_RE.search(user_text)
):
return "read_only"
if names - (_READ_ONLY_AUTO_TOOLS | {"invoke_claude_skill"}):
return None
if "invoke_claude_skill" not in names:
return None
if re.search(r"(?:请调用|调用|call|invoke|please)\s*[`'\"]?invoke_claude_skill\b", user_text, re.IGNORECASE):
return "explicit_skill"
if not _ADAPT_TASK_REQUEST_RE.search(user_text):
return None
skills = [
args.get("skill_name") if isinstance(args := call.get("args"), dict) else None
for call in tool_calls if call.get("name") == "invoke_claude_skill"
]
if skills and all(skill in {"adapt-agent", "npu-basic-migrate"} for skill in skills):
return "requested_adaptation"
return None