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

feature: security rail, sync from enterprise branch

openJiuwen-botada8d1cd23de
diff --git a/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py b/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py
index e1791b9fa8..aa41dce0c8 100644
--- a/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py
+++ b/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py
@@ -403,21 +403,32 @@ def extract_question_from_interaction(payload: Any) -> dict | None:
tool_name = ""
message = ""
+ ui_options = None
if hasattr(payload, 'value'):
value_obj = payload.value
message = getattr(value_obj, 'message', '') or getattr(value_obj, 'question', '')
tool_name = getattr(value_obj, 'tool_name', '')
+ ui_options = getattr(value_obj, 'ui_options', None)
elif isinstance(payload, dict):
value_obj = payload.get('value', {})
if isinstance(value_obj, dict):
message = value_obj.get('message', '') or value_obj.get('question', '')
tool_name = value_obj.get('tool_name', '')
+ ui_options = value_obj.get('ui_options', None)
else:
message = payload.get('message', '') or payload.get('question', '')
else:
return None
+ if ui_options and isinstance(ui_options, list) and len(ui_options) > 0:
+ return {
+ "question": message or f"工具 `{tool_name}` 需要授权才能执行",
+ "header": f"权限审批: {tool_name}" if tool_name else "权限审批",
+ "options": ui_options,
+ "multi_select": False,
+ }
+
return {
"question": message or f"工具 `{tool_name}` 需要授权才能执行",
"header": f"权限审批: {tool_name}" if tool_name else "权限审批",
diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsx
index 38ac42349c..8c9e9e222b 100644
--- a/jiuwenswarm/channels/web/frontend/src/App.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx
@@ -151,6 +151,8 @@ function AppContent() {
const [heartbeatToastVisible, setHeartbeatToastVisible] = useState(false);
const [heartbeatToastMessage, setHeartbeatToastMessage] = useState('');
const [heartbeatModalOpen, setHeartbeatModalOpen] = useState(false);
+ const [securityAlertVisible, setSecurityAlertVisible] = useState(false);
+ const [securityAlertContent, setSecurityAlertContent] = useState('');
const [hasVisitedSkills, setHasVisitedSkills] = useState(false);
const [hasVisitedChannels, setHasVisitedChannels] = useState(false);
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
@@ -362,6 +364,27 @@ function AppContent() {
}
}, []);
+ const securityAlertTimerRef = useRef<number | null>(null);
+
+ useEffect(() => {
+ const handleSecurityAlert = (e: CustomEvent) => {
+ setSecurityAlertContent(e.detail.message);
+ setSecurityAlertVisible(true);
+ if (securityAlertTimerRef.current) {
+ clearTimeout(securityAlertTimerRef.current);
+ }
+ securityAlertTimerRef.current = setTimeout(() => {
+ setSecurityAlertVisible(false);
+ securityAlertTimerRef.current = null;
+ }, 5000);
+ };
+ window.addEventListener('security-alert', handleSecurityAlert as EventListener);
+ return () => {
+ window.removeEventListener('security-alert', handleSecurityAlert as EventListener);
+ if (securityAlertTimerRef.current) clearTimeout(securityAlertTimerRef.current);
+ };
+ }, []);
+
const validateModelConfig = useCallback(
async (fields: {
api_base: string;
@@ -1323,6 +1346,38 @@ function AppContent() {
</div>
)}
+ {/* 安全警告提示 */}
+ {securityAlertVisible && (
+ <div className="app-toast-wrapper app-toast-wrapper--top">
+ <div className="app-heartbeat-toast animate-rise">
+ <div className="app-heartbeat-toast__header">
+ <div className="app-heartbeat-toast__title">
+ <span>⚠️</span>
+ <span className="text-xs font-medium text-text">{t('app.securityAlertTitle')}</span>
+ </div>
+ <button
+ type="button"
+ onClick={() => {
+ setSecurityAlertVisible(false);
+ if (securityAlertTimerRef.current) {
+ clearTimeout(securityAlertTimerRef.current);
+ securityAlertTimerRef.current = null;
+ }
+ }}
+ className="app-heartbeat-toast__close"
+ >
+ <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>
+ <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
+ </svg>
+ </button>
+ </div>
+ <div className="app-heartbeat-toast__content text-sm">
+ {securityAlertContent}
+ </div>
+ </div>
+ </div>
+ )}
+
{/* 配置保存后重启状态弹窗 */}
{restartModalOpen && (
<div className="app-restart-modal">
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InlineQuestionCard.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InlineQuestionCard.tsx
index e90d4562dc..69081b699d 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InlineQuestionCard.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InlineQuestionCard.tsx
@@ -11,7 +11,7 @@
import { useState, useCallback, useMemo, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useChatStore } from '../../stores';
-import { UserAnswer } from '../../types';
+import { UserAnswer, QuestionOption } from '../../types';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
@@ -43,7 +43,8 @@ export function InlineQuestionCard({ onSubmit }: InlineQuestionCardProps) {
return (pendingQuestion?.questions ?? []).map((q, idx) => {
const sel = selMap.get(idx);
if (sel) return { selected_options: [sel] };
- return { selected_options: q.options.length > 0 ? [q.options[0].label] : [] };
+ const firstOption = q.options[0];
+ return { selected_options: firstOption ? [firstOption.value || firstOption.label] : [] };
});
},
[pendingQuestion]
@@ -60,11 +61,12 @@ export function InlineQuestionCard({ onSubmit }: InlineQuestionCardProps) {
);
const handleSelect = useCallback(
- (questionIndex: number, optionLabel: string) => {
+ (questionIndex: number, option: QuestionOption) => {
if (submitted) return;
+ const value = option.value || option.label;
const next = new Map(selections);
- next.set(questionIndex, optionLabel);
+ next.set(questionIndex, value);
setSelections(next);
if (!isBatch) {
@@ -76,9 +78,14 @@ export function InlineQuestionCard({ onSubmit }: InlineQuestionCardProps) {
const handleAcceptAll = useCallback(() => {
if (!pendingQuestion || submitted) return;
- const acceptLabel = t('chatUi.inlineQuestion.accept');
const all = new Map<number, string>();
- pendingQuestion.questions.forEach((_, idx) => all.set(idx, acceptLabel));
+ pendingQuestion.questions.forEach((q, idx) => {
+ const acceptOption = q.options.find(o =>
+ o.label === t('chatUi.inlineQuestion.accept') ||
+ o.label === '本次允许'
+ );
+ all.set(idx, acceptOption?.value || acceptOption?.label || '');
+ });
setSelections(all);
doSubmit(all);
}, [pendingQuestion, submitted, t, doSubmit]);
@@ -186,7 +193,7 @@ export function InlineQuestionCard({ onSubmit }: InlineQuestionCardProps) {
style={{ maxHeight: '60vh' }}
>
{pendingQuestion.questions.map((question, qIndex) => {
- const selectedLabel = selections.get(qIndex);
+ const selectedValue = selections.get(qIndex);
return (
<div
@@ -210,6 +217,7 @@ export function InlineQuestionCard({ onSubmit }: InlineQuestionCardProps) {
{/* 选项按钮 */}
<div className="px-4 pb-3 flex flex-col gap-2">
{question.options.map((option) => {
+ const optionValue = option.value || option.label;
const isAccept = option.label === t('chatUi.inlineQuestion.accept')
|| option.label === t('chatUi.inlineQuestion.allowOnce')
|| option.label === '本次允许';
@@ -217,12 +225,12 @@ export function InlineQuestionCard({ onSubmit }: InlineQuestionCardProps) {
|| option.label === '总是允许';
const isReject = option.label === t('chatUi.inlineQuestion.reject')
|| option.label === '拒绝';
- const isSelected = selectedLabel === option.label;
+ const isSelected = selectedValue === optionValue;
return (
<button
key={option.label}
- onClick={() => handleSelect(qIndex, option.label)}
+ onClick={() => handleSelect(qIndex, option)}
disabled={submitted}
className="w-full text-left px-4 py-2.5 text-sm font-medium rounded-lg transition-all"
style={{
diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
index f067bd8389..40fbd85576 100644
--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
@@ -1243,6 +1243,15 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
if (!shouldHandleSessionEvent(payload)) return;
const content = typeof payload.content === 'string' ? payload.content : '';
const stage = typeof payload.stage === 'string' ? payload.stage : undefined;
+
+ // Check for security alert
+ const metadata = (payload as { metadata?: { is_security_alert?: boolean } }).metadata;
+ if (metadata?.is_security_alert) {
+ window.dispatchEvent(new CustomEvent('security-alert', {
+ detail: { message: content }
+ }));
+ }
+
useHarnessStore.getState().addHarnessMessage(content, stage);
// Pipeline start message contains stages array: { content, pipeline, stages: [{slot, display_name}] }
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
index c10a6bc19f..d64bf2db85 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
@@ -1186,6 +1186,7 @@
"heartbeatTitle": "Heartbeat message",
"heartbeatClose": "Close",
"heartbeatViewFull": "Click to view full message",
+ "securityAlertTitle": "Security Alert",
"noContent": "No details",
"restarting": "Restarting service",
"restartSuccess": "Restart successful",
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
index 5398fb28fc..bf615810ed 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
@@ -1185,6 +1185,7 @@
"heartbeatTitle": "心跳消息",
"heartbeatClose": "关闭",
"heartbeatViewFull": "点击查看完整心跳消息",
+ "securityAlertTitle": "安全警告",
"noContent": "无详细内容",
"restarting": "正在重启服务",
"restartSuccess": "重启成功",
diff --git a/jiuwenswarm/channels/web/frontend/src/types/websocket.ts b/jiuwenswarm/channels/web/frontend/src/types/websocket.ts
index 3f1a11da71..80ffc21909 100644
--- a/jiuwenswarm/channels/web/frontend/src/types/websocket.ts
+++ b/jiuwenswarm/channels/web/frontend/src/types/websocket.ts
@@ -123,6 +123,7 @@ export interface SubtaskUpdatePayload {
export interface QuestionOption {
label: string;
description?: string;
+ value?: string;
}
/**
diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.py
index 86aab35b41..84bfa30dd3 100644
--- a/jiuwenswarm/server/agent_ws_server.py
+++ b/jiuwenswarm/server/agent_ws_server.py
@@ -3665,10 +3665,17 @@ class AgentWebSocketServer:
manager = get_rail_manager()
- # 1. 更新配置文件中的启用状态
+ # 1. 确保 agent 实例已设置(用于热更新)
+ agent = self._agent_manager.get_agent_nowait()
+ if agent is not None:
+ agent_instance = agent.get_instance()
+ if agent_instance is not None:
+ manager.set_agent_instance(agent_instance)
+
+ # 2. 更新配置文件中的启用状态
extension = manager.toggle_extension(name, enabled)
- # 2. 触发热更新:根据 enabled 状态注册或注销 rail
+ # 3. 触发热更新:根据 enabled 状态注册或注销 rail
await manager.hot_reload_rail(name, enabled)
resp = AgentResponse(
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.py
index 4a75f231e6..bca42e500d 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py
@@ -408,19 +408,21 @@ class JiuWenClaw:
selected_options = answer.get("selected_options", []) if isinstance(answer, dict) else []
custom_input = answer.get("custom_input", "") if isinstance(answer, dict) else ""
- if "本次允许" in selected_options:
+ value = selected_options[0] if selected_options else ""
+
+ if value in ("approve", "本次允许", "Approve"):
confirm_payload = {"approved": True, "auto_confirm": False, "feedback": ""}
- elif "总是允许" in selected_options:
+ elif value in ("always_allow", "总是允许", "Always Allow"):
confirm_payload = {
"approved": True,
"auto_confirm": True,
"persist_allow": True,
"feedback": "",
}
- elif "拒绝" in selected_options:
+ elif value in ("reject", "拒绝", "Reject"):
confirm_payload = {"approved": False, "auto_confirm": False, "feedback": custom_input or "用户拒绝"}
else:
- confirm_payload = {"approved": False, "auto_confirm": False, "feedback": "未知选项"}
+ confirm_payload = {"approved": False, "auto_confirm": False, "feedback": f"未知选项: {value}"}
interactive_input.update(request_id, confirm_payload)
logger.info(
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index 19692e09c4..5b775a7a54 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -4907,6 +4907,9 @@ class JiuWenClawDeepAdapter:
result["stages"] = payload["stages"]
if "pipeline" in payload:
result["pipeline"] = payload["pipeline"]
+ # Pass through metadata for security alerts and other custom data
+ if "metadata" in payload:
+ result["metadata"] = payload["metadata"]
return result
# Auto-harness specific: harness.stage_result event
diff --git a/tests/unit_tests/agentserver/test_agentserver_acp.py b/tests/unit_tests/agentserver/test_agentserver_acp.py
index 39f6f7b791..3d70f407b8 100644
--- a/tests/unit_tests/agentserver/test_agentserver_acp.py
+++ b/tests/unit_tests/agentserver/test_agentserver_acp.py
@@ -181,6 +181,36 @@ def test_interface_deep_parse_stream_chunk_preserves_tool_update():
}
+def test_interface_deep_parse_stream_chunk_preserves_message_metadata():
+ """Test that metadata field is preserved in message type for security alerts."""
+ parsed = parse_stream_chunk(
+ types.SimpleNamespace(
+ type="message",
+ payload={
+ "role": "system",
+ "content": "[WARNING] API key/secret detected in read_file result.",
+ "metadata": {
+ "is_security_alert": True,
+ "level": "warning",
+ "alert_type": "api_key_leakage",
+ "display_mode": "popup",
+ "rail": "ApikeyguardalertRail",
+ },
+ },
+ )
+ )
+
+ assert parsed["event_type"] == "chat.message"
+ assert parsed["content"] == "[WARNING] API key/secret detected in read_file result."
+ assert parsed["role"] == "system"
+ assert "metadata" in parsed
+ assert parsed["metadata"]["is_security_alert"] is True
+ assert parsed["metadata"]["level"] == "warning"
+ assert parsed["metadata"]["alert_type"] == "api_key_leakage"
+ assert parsed["metadata"]["display_mode"] == "popup"
+ assert parsed["metadata"]["rail"] == "ApikeyguardalertRail"
+
+
def test_parse_stream_chunk_serializes_team_runtime_enum_kind():
parsed = parse_stream_chunk(
{