Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat(rails): 权限审批卡头部展示执行意图(动作短语 + call_goal)

yt2026de19d8c516c4
diff --git a/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py b/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py
index ca73619785..2de9382e43 100644
--- a/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py
+++ b/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py
@@ -277,6 +277,55 @@ def parse_hosted_permission_answer(answer: Any) -> Any:
return None
+def build_permission_intent_headline(tool_name: str, tool_args: Any) -> str:
+ """权限审批卡的意图标题:L1 规则动作短语 + L2 call_goal(模型自述目标)。
+
+ 组出形如 ``**是否允许「写入 report.md」?**\\n\\n目的:生成周报`` 的标题块;
+ 动作短语与 call_goal 均不可得时返回空串,调用方保持原文案不变。
+ 仅做展示增强:审批目标本身(工具声明行与参数区)始终保留,意图不可
+ 替代具体操作(模型自述可能被提示词注入包装,用户须能核对原始参数)。
+ """
+ name = (tool_name or "").strip()
+ if not name:
+ return ""
+ from jiuwenswarm.common.tool_display import (
+ build_tool_display_name,
+ extract_call_goal,
+ )
+
+ call_goal, cleaned_args = extract_call_goal(tool_args)
+ action = build_tool_display_name(name, cleaned_args).strip()
+ if action:
+ title = f"**是否允许「{action}」?**"
+ elif call_goal:
+ title = f"**是否允许执行 `{name}`?**"
+ else:
+ return ""
+ parts = [title]
+ if call_goal:
+ parts.append(f"目的:{call_goal}")
+ return "\n\n".join(parts)
+
+
+_PERMISSION_RULE_LINE_RE = re.compile(r"\n\n匹配规则:`[^`\n]*`")
+_PERMISSION_CONFIRM_SENTENCE = "请确认是否允许该操作。\n\n"
+
+
+def apply_permission_intent(message: str, tool_name: str, tool_args: Any) -> str:
+ """主 Agent 权限卡 question 头部加入意图标题,并移除内部「匹配规则」行。
+
+ 只做前置与删减:不改动「**工具 `X` 需要授权才能执行**」声明行与参数区
+ (TUI ``PERMISSION_TOOL_RE`` / 前端 ``approvalPresentation`` 的既有解析依赖
+ 它们)。无意图可展示时仅移除「匹配规则」行。
+ """
+ headline = build_permission_intent_headline(tool_name, tool_args)
+ cleaned = _PERMISSION_RULE_LINE_RE.sub("", message)
+ if headline:
+ cleaned = cleaned.replace(_PERMISSION_CONFIRM_SENTENCE, "", 1)
+ cleaned = f"{headline}\n\n{cleaned}"
+ return cleaned
+
+
def _format_hosted_permission_question(
*,
tool_name: str,
@@ -288,7 +337,11 @@ def _format_hosted_permission_question(
_format_tool_args_preview,
)
- parts = [
+ parts = []
+ headline = build_permission_intent_headline(tool_name, tool_args)
+ if headline:
+ parts += [headline, "\n\n"]
+ parts += [
f"**工具 `{tool_name}` 需要授权才能执行**\n\n",
f"> 发起方:子 Agent `{agent_scope_id}`",
"\n\n**关键参数或命令:**\n\n",
@@ -1406,6 +1459,8 @@ def extract_question_from_interaction(payload: Any) -> dict | None:
else:
header = f"权限审批: {tool_name}" if tool_name else "权限审批"
question = message
+ if source == "permission_interrupt":
+ question = apply_permission_intent(question, tool_name, tool_args)
if is_enterprise() and source == "permission_interrupt":
question = _strip_permanent_remember_hint(question)
diff --git a/jiuwenswarm/agents/harness/common/rails/subagent_permission_rail.py b/jiuwenswarm/agents/harness/common/rails/subagent_permission_rail.py
index ad3198d1f8..ff01694830 100644
--- a/jiuwenswarm/agents/harness/common/rails/subagent_permission_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/subagent_permission_rail.py
@@ -162,7 +162,15 @@ def build_tool_permission_approval_sender() -> ApprovalSender:
tool_args = payload.get("tool_args")
skill_name = str(payload.get("skill_name") or "").strip()
reason = str(payload.get("reason") or "").strip()
- question_parts = [
+ from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers import (
+ build_permission_intent_headline,
+ )
+
+ headline = build_permission_intent_headline(tool_name, tool_args)
+ question_parts = []
+ if headline:
+ question_parts += [headline, "\n\n"]
+ question_parts += [
f"**工具 `{tool_name}` 需要授权才能执行**\n\n",
f"> 发起方:子 Agent `{request.agent_scope_id}`"
f"(当前 Skill:`{skill_name}`)",
diff --git a/tests/unit_tests/agentserver/test_interrupt_helpers.py b/tests/unit_tests/agentserver/test_interrupt_helpers.py
index a31bb14c39..95ffccf6f4 100644
--- a/tests/unit_tests/agentserver/test_interrupt_helpers.py
+++ b/tests/unit_tests/agentserver/test_interrupt_helpers.py
@@ -1,4 +1,5 @@
import asyncio
+import json
from types import SimpleNamespace
import pytest
@@ -667,3 +668,177 @@ async def test_hosted_permission_rail_hook_registry_emit_resolve_roundtrip(
context_vars.reset_subagent_parent_session(token_parent)
SubagentApprovalRegistry.reset_instance_for_tests()
+
+# ---------------------------------------------------------------------------
+# 权限审批卡意图标题(build_permission_intent_headline / apply_permission_intent)
+# ---------------------------------------------------------------------------
+
+
+def _tool_permission_message(tool_name: str, tool_args: dict) -> str:
+ """Mirror agent-core PermissionInterruptRail._build_message output shape."""
+ args_preview = json.dumps(tool_args, ensure_ascii=False, indent=2)
+ return (
+ f"**工具 `{tool_name}` 需要授权才能执行**\n\n"
+ "请确认是否允许该操作。\n\n"
+ f"参数:\n```json\n{args_preview}\n```\n"
+ f"\n匹配规则:`permission_engine`"
+ )
+
+
+def test_intent_headline_combines_action_phrase_and_call_goal():
+ from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers import (
+ build_permission_intent_headline,
+ )
+
+ headline = build_permission_intent_headline(
+ "write_file",
+ {
+ "call_goal": "生成上周的数据分析周报",
+ "path": "/ws/report.md",
+ "content": "# 周报",
+ },
+ )
+
+ assert headline == "**是否允许「写入 report.md」?**\n\n目的:生成上周的数据分析周报"
+
+
+def test_intent_headline_action_phrase_without_call_goal():
+ from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers import (
+ build_permission_intent_headline,
+ )
+
+ headline = build_permission_intent_headline("bash", {"command": "ls -la /tmp"})
+
+ assert headline == "**是否允许「执行 ls -la /tmp」?**"
+
+
+def test_intent_headline_call_goal_only_for_unknown_tool():
+ from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers import (
+ build_permission_intent_headline,
+ )
+
+ headline = build_permission_intent_headline(
+ "mcp_custom_tool",
+ {"call_goal": "查询工单状态", "ticket": "T-1"},
+ )
+
+ assert headline == "**是否允许执行 `mcp_custom_tool`?**\n\n目的:查询工单状态"
+
+
+def test_intent_headline_empty_without_phrase_or_goal():
+ from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers import (
+ build_permission_intent_headline,
+ )
+
+ assert build_permission_intent_headline("mcp_custom_tool", {"command": "x"}) == ""
+ assert build_permission_intent_headline("", {"call_goal": "x"}) == ""
+
+
+def test_apply_permission_intent_prepends_headline_and_strips_rule_line():
+ from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers import (
+ apply_permission_intent,
+ )
+
+ tool_args = {
+ "call_goal": "生成上周的数据分析周报",
+ "path": "/ws/report.md",
+ "content": "# 周报",
+ }
+ message = _tool_permission_message("write_file", tool_args)
+
+ question = apply_permission_intent(message, "write_file", tool_args)
+
+ assert question.startswith("**是否允许「写入 report.md」?**")
+ assert "目的:生成上周的数据分析周报" in question
+ assert question.index("目的:") < question.index("**工具")
+ assert "匹配规则" not in question
+ assert "请确认是否允许该操作" not in question
+ # 安全不变量:工具声明行与原始参数保留,供用户核对实际操作。
+ assert "**工具 `write_file` 需要授权才能执行**" in question
+ assert '"/ws/report.md"' in question
+
+
+def test_apply_permission_intent_degrades_to_rule_line_removal_only():
+ from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers import (
+ apply_permission_intent,
+ )
+
+ tool_args = {"command": "ls -la /tmp"}
+ message = _tool_permission_message("mcp_custom_tool", tool_args)
+
+ question = apply_permission_intent(message, "mcp_custom_tool", tool_args)
+
+ # 词典外工具且无 call_goal:无标题,仅移除内部「匹配规则」行,其余不变。
+ assert question.startswith("**工具 `mcp_custom_tool` 需要授权才能执行**")
+ assert "匹配规则" not in question
+ assert "请确认是否允许该操作。" in question
+ assert "ls -la /tmp" in question
+
+
+def test_extract_question_adds_intent_to_permission_card(
+ monkeypatch: pytest.MonkeyPatch,
+):
+ from jiuwenswarm.agents.harness.common.rails.interrupt import interrupt_helpers as helpers
+
+ monkeypatch.setattr(helpers, "is_enterprise", lambda: False)
+ tool_args = {
+ "call_goal": "生成上周的数据分析周报",
+ "path": "/ws/report.md",
+ "content": "# 周报",
+ }
+ interaction = SimpleNamespace(
+ id="call_intent_1",
+ value={
+ "message": _tool_permission_message("write_file", tool_args),
+ "tool_name": "write_file",
+ "tool_args": tool_args,
+ },
+ )
+
+ result = helpers.extract_question_from_interaction(interaction)
+
+ assert result is not None
+ question = result["question"]
+ assert result["header"] == "权限审批: write_file"
+ assert question.startswith("**是否允许「写入 report.md」?**")
+ assert "目的:生成上周的数据分析周报" in question
+ assert "匹配规则" not in question
+ assert "**工具 `write_file` 需要授权才能执行**" in question
+ assert '"/ws/report.md"' in question
+ assert {"本次允许", "拒绝"} <= {opt["label"] for opt in result["options"]}
+
+
+def test_extract_question_keeps_non_permission_interrupt_untouched():
+ """确认类中断(confirm_interrupt)不经过意图改写。"""
+ from jiuwenswarm.agents.harness.common.rails.interrupt import interrupt_helpers as helpers
+
+ interaction = SimpleNamespace(
+ id="call_confirm_1",
+ value={"message": "确认执行该任务?", "tool_name": "switch_mode"},
+ )
+
+ result = helpers.extract_question_from_interaction(interaction)
+
+ assert result is not None
+ assert result["header"] == "操作确认: switch_mode"
+ assert result["question"] == "确认执行该任务?"
+
+
+def test_hosted_permission_question_leads_with_intent_headline():
+ from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers import (
+ _format_hosted_permission_question,
+ )
+
+ question = _format_hosted_permission_question(
+ tool_name="write_file",
+ tool_args={"call_goal": "生成周报", "path": "/ws/report.md"},
+ reason="file_guard",
+ agent_scope_id="child-sess",
+ )
+
+ assert question.startswith("**是否允许「写入 report.md」?**")
+ assert "目的:生成周报" in question
+ assert "**工具 `write_file` 需要授权才能执行**" in question
+ assert "> 发起方:子 Agent `child-sess`" in question
+ assert "**权限原因:** file_guard" in question
+
diff --git a/tests/unit_tests/agentserver/test_skill_authorization_permission_rail.py b/tests/unit_tests/agentserver/test_skill_authorization_permission_rail.py
index 0af1bd2c1a..1e3da7259e 100644
--- a/tests/unit_tests/agentserver/test_skill_authorization_permission_rail.py
+++ b/tests/unit_tests/agentserver/test_skill_authorization_permission_rail.py
@@ -421,3 +421,39 @@ async def test_disabled_policy_does_not_apply_persisted_grant(active_skill_permi
monkeypatch.setattr(type(rail).__mro__[1], '_get_permissions_snapshot', lambda self, context: disabled)
rail._refresh_permissions_for_tool_call(ctx)
assert (await rail._engine.check_permission('get_current_user', {})).permission.value == 'ask'
+
+
+async def test_subagent_tool_permission_card_leads_with_intent_headline(monkeypatch):
+ """Skill 窗口审批卡:意图标题置顶,声明/发起方/参数保留,options 不变。"""
+ from jiuwenswarm.agents.harness.common.rails import subagent_permission_rail as spr
+
+ captured: dict[str, Any] = {}
+
+ async def _fake_emit(session, request, *, header, question, options):
+ captured.update(header=header, question=question, options=options)
+
+ monkeypatch.setattr(spr, "_parent_stream_session", lambda: object())
+ monkeypatch.setattr(spr, "emit_subagent_approval", _fake_emit)
+
+ request = SimpleNamespace(
+ payload={
+ "tool_name": "write_file",
+ "tool_args": {"call_goal": "生成周报", "path": "/ws/report.md"},
+ "skill_name": "weekly-report",
+ "reason": "file_guard",
+ },
+ agent_scope_id="child-sess",
+ )
+
+ await spr.build_tool_permission_approval_sender()(request)
+
+ assert captured["header"] == "权限审批: write_file"
+ assert captured["question"].startswith("**是否允许「写入 report.md」?**")
+ assert "目的:生成周报" in captured["question"]
+ assert "**工具 `write_file` 需要授权才能执行**" in captured["question"]
+ assert (
+ "> 发起方:子 Agent `child-sess`(当前 Skill:`weekly-report`)"
+ in captured["question"]
+ )
+ assert [opt["label"] for opt in captured["options"]] == ["本次允许", "拒绝"]