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

fix(agent): 鉴权失败/凭证探测早停并优化最大轮数收尾

openJiuwen-bot94dbaf9d3e99
diff --git a/jiuwenswarm/agents/harness/common/rails/execution_guard/stalled_access_circuit_rail.py b/jiuwenswarm/agents/harness/common/rails/execution_guard/stalled_access_circuit_rail.py
new file mode 100644
index 0000000000..085efd380f
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/rails/execution_guard/stalled_access_circuit_rail.py
@@ -0,0 +1,213 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Circuit breaker for repeated access-denied / credential-probing loops.
+
+The default ``agent_ras`` loop detectors key on identical tool arguments.
+Agents that retry the same *goal* with a different script on every turn
+(``auth_probe.py``, ``token_hunt.py``, ``leveldb_scan.py`` ...) never match
+those detectors. This rail counts two strategy-level signals instead:
+
+- repeated ``401 / AUTH_SESSION_TERMINATED`` results within a time window;
+- repeated attempts to read or copy session credentials
+ (``session.cookie`` / Chromium ``Cookies`` / LevelDB / DPAPI).
+
+When either threshold trips, the rail finishes the turn with an actionable
+message instead of letting the agent burn the whole ReAct budget.
+"""
+
+from __future__ import annotations
+
+import re
+import reprlib
+import time
+from typing import Any
+
+from openjiuwen.harness.rails.base import DeepAgentRail
+
+from jiuwenswarm.common.utils import logger
+
+_FATAL_ACCESS = re.compile(r"AUTH_SESSION_TERMINATED", re.IGNORECASE)
+_CREDENTIAL_PROBE = re.compile(
+ r"session\.cookie|Network[\\/]Cookies|Local Storage[\\/]leveldb|"
+ r"Login Data|CryptUnprotectData|CryptProtectData|DPAPI",
+ re.IGNORECASE,
+)
+
+# Only tools that can reach local app data or credentials participate.
+# Generic web tools may legitimately return 401 from third-party sites.
+_RELEVANT_TOOLS = frozenset(
+ {
+ "bash",
+ "read_file",
+ "write_file",
+ "edit_file",
+ "glob",
+ "grep",
+ "invoke_tool",
+ "mcp_exec_command",
+ "exec_command",
+ "run_command",
+ "execute_command",
+ "shell",
+ "execute_code",
+ "code_interpreter",
+ "office_claw_list_wishes",
+ }
+)
+
+_SCAN_LIMIT = 64 * 1024
+_TEXT_KEYS = ("content", "output", "error", "message", "stdout", "stderr", "result", "text")
+_REPR = reprlib.Repr()
+_REPR.maxstring = _SCAN_LIMIT
+_REPR.maxother = _SCAN_LIMIT
+
+
+def _head_tail(text: str, limit: int) -> str:
+ if len(text) <= limit:
+ return text
+ half = max(1, limit // 2)
+ return f"{text[:half]}\n...\n{text[-half:]}"
+
+
+def _bounded_text(value: Any, *, limit: int = _SCAN_LIMIT) -> str:
+ if value is None:
+ return ""
+ if isinstance(value, str):
+ return _head_tail(value, limit)
+ if isinstance(value, (bytes, bytearray)):
+ return _bounded_text(bytes(value).decode("utf-8", errors="replace"), limit=limit)
+ if isinstance(value, dict):
+ parts = [_bounded_text(value[key], limit=limit) for key in _TEXT_KEYS if key in value]
+ if parts:
+ return _head_tail("\n".join(parts), limit)
+ object_parts: list[str] = []
+ for key in ("data",) + _TEXT_KEYS:
+ attr = _safe_getattr(value, key)
+ if attr is not None:
+ object_parts.append(_bounded_text(attr, limit=limit))
+ if object_parts:
+ return _head_tail("\n".join(object_parts), limit)
+ if isinstance(value, (list, tuple)):
+ if not value:
+ return ""
+ per_item = max(1, limit // min(len(value), 8))
+ return _head_tail(
+ "\n".join(_bounded_text(item, limit=per_item) for item in value[:8]),
+ limit,
+ )
+ return _head_tail(_REPR.repr(value), limit)
+
+
+def _safe_getattr(value: Any, key: str) -> Any:
+ try:
+ return getattr(value, key, None)
+ except Exception: # noqa: BLE001
+ return None
+
+
+def _tool_args_text(inputs: Any) -> Any:
+ tool_args = getattr(inputs, "tool_args", None)
+ if tool_args:
+ return tool_args
+ tool_call = getattr(inputs, "tool_call", None)
+ tool_args = getattr(tool_call, "arguments", None)
+ if tool_args:
+ return tool_args
+ function = getattr(tool_call, "function", None)
+ return getattr(function, "arguments", None)
+
+
+class StalledAccessCircuitRail(DeepAgentRail):
+ """Stop strategy-level auth/credential retry loops."""
+
+ priority: int = 97
+
+ def __init__(
+ self,
+ *,
+ auth_threshold: int = 5,
+ probe_threshold: int = 3,
+ window_seconds: float = 1800.0,
+ language: str = "cn",
+ ) -> None:
+ super().__init__()
+ self._auth_threshold = max(1, int(auth_threshold))
+ self._probe_threshold = max(1, int(probe_threshold))
+ self._window = max(1.0, float(window_seconds))
+ self._language = "en" if str(language).lower().startswith("en") else "cn"
+ self._denied_at: list[float] = []
+ self._probe_at: list[float] = []
+ self._tripped = False
+
+ def set_language(self, language: str | None) -> None:
+ self._language = "en" if str(language or "").lower().startswith("en") else "cn"
+
+ async def before_invoke(self, ctx: Any) -> None:
+ self._denied_at = []
+ self._probe_at = []
+ self._tripped = False
+
+ async def after_tool_call(self, ctx: Any) -> None:
+ if self._tripped:
+ return
+ inputs = getattr(ctx, "inputs", None)
+ if inputs is None:
+ return
+ tool_name = str(getattr(inputs, "tool_name", "") or "")
+ if tool_name not in _RELEVANT_TOOLS:
+ return
+
+ result_text = _bounded_text(getattr(inputs, "tool_result", None))
+ args_text = _bounded_text(_tool_args_text(inputs))
+ now = time.monotonic()
+
+ if _CREDENTIAL_PROBE.search(result_text) or _CREDENTIAL_PROBE.search(args_text):
+ self._probe_at.append(now)
+
+ if _FATAL_ACCESS.search(result_text):
+ self._denied_at.append(now)
+
+ cutoff = now - self._window
+ self._denied_at = [stamp for stamp in self._denied_at if stamp >= cutoff]
+ self._probe_at = [stamp for stamp in self._probe_at if stamp >= cutoff]
+
+ if (
+ len(self._probe_at) < self._probe_threshold
+ and len(self._denied_at) < self._auth_threshold
+ ):
+ return
+
+ self._tripped = True
+ if self._language == "en":
+ output = (
+ "This data source requires a fresh sign-in, and the agent is not "
+ "allowed to read session credentials (session.cookie, browser "
+ "Cookies, LevelDB, or DPAPI).\n"
+ "Please sign in again or export the data and retry."
+ )
+ else:
+ output = (
+ "当前数据源需要重新登录,且系统不允许读取会话凭证"
+ "(session.cookie / 浏览器 Cookies / LevelDB / DPAPI)。\n"
+ "请重新登录或导出数据后重试。"
+ )
+ logger.warning(
+ "[StalledAccessCircuitRail] tripped session_id=%s tool=%s "
+ "probes_in_window=%s denied_in_window=%s",
+ self._session_id(ctx),
+ tool_name,
+ len(self._probe_at),
+ len(self._denied_at),
+ )
+ ctx.request_force_finish({"output": output, "result_type": "error"})
+
+ @staticmethod
+ def _session_id(ctx: Any) -> str:
+ session = getattr(ctx, "session", None)
+ try:
+ return str(session.get_session_id() or "") if session is not None else ""
+ except Exception: # noqa: BLE001
+ return ""
+
+
+__all__ = ["StalledAccessCircuitRail"]
diff --git a/jiuwenswarm/agents/harness/common/rails/last_iteration_finalize_rail.py b/jiuwenswarm/agents/harness/common/rails/last_iteration_finalize_rail.py
new file mode 100644
index 0000000000..75f2d31641
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/rails/last_iteration_finalize_rail.py
@@ -0,0 +1,107 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Graceful finalization when the ReAct budget is exhausted.
+
+``react_agent`` returns a bare ``Max iterations reached without completion``
+error after the final tool result has already been written. This rail runs on
+``AFTER_REACT_ITERATION`` of the final allowed iteration and requests a
+force-finish with an actionable message. The ReAct for-else consumes that
+request, so no change to the openjiuwen dependency is required.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from openjiuwen.harness.rails.base import DeepAgentRail
+
+from jiuwenswarm.common.utils import logger
+
+
+class LastIterationFinalizeRail(DeepAgentRail):
+ """Return an actionable partial-result message instead of a bare error."""
+
+ priority: int = 96
+
+ def __init__(self, *, language: str = "cn") -> None:
+ super().__init__()
+ self._language = "en" if str(language).lower().startswith("en") else "cn"
+ self._max_iterations: int | None = None
+
+ def set_language(self, language: str | None) -> None:
+ self._language = "en" if str(language or "").lower().startswith("en") else "cn"
+
+ async def before_invoke(self, ctx: Any) -> None:
+ self._max_iterations = self._read_max_iterations(ctx)
+ if self._max_iterations is None:
+ logger.warning(
+ "[LastIterationFinalizeRail] max_iterations unavailable; "
+ "graceful finalize disabled"
+ )
+
+ async def after_react_iteration(self, ctx: Any) -> None:
+ inputs = getattr(ctx, "inputs", None)
+ try:
+ iteration = int(getattr(inputs, "react_iteration", 0) or 0)
+ except (TypeError, ValueError):
+ return
+ max_iterations = self._max_iterations
+ if not isinstance(max_iterations, int) or max_iterations <= 0:
+ return
+ # react_iteration is 1-based. AFTER_REACT_ITERATION carries
+ # ModelCallInputs (not ToolCallInputs); a text-only final answer
+ # breaks the loop before this hook fires, so response.tool_calls
+ # is the completion signal available on this event.
+ if iteration < max_iterations:
+ return
+ response = getattr(inputs, "response", None)
+ if response is not None:
+ tool_calls = getattr(response, "tool_calls", None)
+ if tool_calls is None and isinstance(response, dict):
+ tool_calls = response.get("tool_calls")
+ if not tool_calls:
+ return
+
+ if self._language == "en":
+ output = (
+ f"The maximum number of reasoning iterations "
+ f"({iteration}/{max_iterations}) was reached and the task did "
+ "not complete.\nNarrow the task scope or provide the missing data "
+ "source, then retry."
+ )
+ else:
+ output = (
+ f"已达到最大思考轮数({iteration}/{max_iterations}),任务未完成。\n"
+ "建议:缩小任务范围,或补充数据源后重试。"
+ )
+
+ logger.warning(
+ "[LastIterationFinalizeRail] final iteration session_id=%s "
+ "iteration=%s/%s",
+ self._session_id(ctx),
+ iteration,
+ max_iterations,
+ )
+ ctx.request_force_finish({"output": output, "result_type": "error"})
+
+ @staticmethod
+ def _read_max_iterations(ctx: Any) -> int | None:
+ agent = getattr(ctx, "agent", None)
+ for holder in (getattr(agent, "_react_agent", None), agent):
+ for attr in ("_config", "config"):
+ value = getattr(getattr(holder, attr, None), "max_iterations", None)
+ if isinstance(value, int) and value > 0:
+ return value
+ value = getattr(agent, "max_iterations", None)
+ return value if isinstance(value, int) and value > 0 else None
+
+ @staticmethod
+ def _session_id(ctx: Any) -> str:
+ session = getattr(ctx, "session", None)
+ try:
+ return str(session.get_session_id() or "") if session is not None else ""
+ except Exception: # noqa: BLE001
+ return ""
+
+
+__all__ = ["LastIterationFinalizeRail"]
diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yaml
index 09d915f54e..be0a03b599 100644
--- a/jiuwenswarm/resources/config.yaml
+++ b/jiuwenswarm/resources/config.yaml
@@ -659,6 +659,7 @@ react:
- skill_tool
- skill_complete
- skill_acceleration_exec
+ - office_claw_list_wishes
- todo_create
- todo_list
- todo_modify
@@ -1021,9 +1022,15 @@ execution_guard:
repeat_window_chars: 1024
# 单字符连续重复阈值,用于检测分隔线等场景,默认较高以减少误判
single_char_repeat_count: 90
+ # 策略级鉴权失败 / 凭证探测断路器(单 agent / flash)。
+ stalled_access:
+ enabled: true
+ auth_threshold: 5
+ probe_threshold: 3
+ window_seconds: 1800
# develop 防死循环 rail:重复调用 / ping-pong / 未知工具打断(force-finish)。
# 默认关闭,避免和 dest-stable 已开启的 agent_ras.repeat_tool 双挂。
- # 不是 issue 的 OPEN/HALF_OPEN 恢复型熔断。
+ # 不是 issue 级 OPEN/HALF_OPEN 恢复型熔断;
# non_retryable_tool 检测器也在此开关下;默认部署使用 agent_ras,
# 不消费 tool_result_contract,因此默认不会触发该检测器。
circuit_breaker:
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index 9317636533..7e8b73334a 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -1784,6 +1784,11 @@ def _parse_bool(value: Any, *, default: bool = False) -> bool:
return default
+def _env_truthy(name: str) -> bool:
+ """True when the environment variable is explicitly enabled."""
+ return _parse_bool(os.getenv(name), default=False)
+
+
def _model_routing_enabled(config: dict[str, Any] | None) -> bool:
"""model_routing 总开关:config.yaml ``model_routing.enabled``(默认 false)+ 进程级 env 覆盖。
@@ -10396,6 +10401,79 @@ class JiuWenSwarmDeepAdapter:
logger.warning("[JiuWenSwarmDeepAdapter] CircuitBreakerRail create failed: %s", exc)
return None
+ def _build_stalled_access_circuit_rail(self) -> Any | None:
+ """Stop strategy-level auth/credential retry loops."""
+ if _env_truthy("JIUWEN_DISABLE_STALLED_ACCESS_RAIL"):
+ logger.info(
+ "[JiuWenSwarmDeepAdapter] StalledAccessCircuitRail disabled by env"
+ )
+ return None
+ try:
+ from jiuwenswarm.agents.harness.common.rails.execution_guard.stalled_access_circuit_rail import (
+ StalledAccessCircuitRail,
+ )
+
+ guard_cfg = (get_config() or {}).get("execution_guard") or {}
+ stalled_cfg = guard_cfg.get("stalled_access") if isinstance(guard_cfg, dict) else {}
+ if not isinstance(stalled_cfg, dict):
+ stalled_cfg = {}
+ if stalled_cfg.get("enabled", True) is False:
+ logger.info(
+ "[JiuWenSwarmDeepAdapter] StalledAccessCircuitRail disabled by config"
+ )
+ return None
+ try:
+ auth_threshold = int(stalled_cfg.get("auth_threshold", 5))
+ probe_threshold = int(stalled_cfg.get("probe_threshold", 3))
+ window_seconds = float(stalled_cfg.get("window_seconds", 1800))
+ except (TypeError, ValueError):
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] StalledAccessCircuitRail invalid thresholds; "
+ "using defaults"
+ )
+ auth_threshold, probe_threshold, window_seconds = 5, 3, 1800.0
+
+ rail = StalledAccessCircuitRail(
+ auth_threshold=auth_threshold,
+ probe_threshold=probe_threshold,
+ window_seconds=window_seconds,
+ language=self._resolve_runtime_language(),
+ )
+ logger.info(
+ "[JiuWenSwarmDeepAdapter] StalledAccessCircuitRail create success"
+ )
+ return rail
+ except Exception as exc:
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] StalledAccessCircuitRail create failed: %s",
+ exc,
+ )
+ return None
+
+ def _build_last_iteration_finalize_rail(self) -> Any | None:
+ """Return a partial result when the ReAct budget is exhausted."""
+ if _env_truthy("JIUWEN_DISABLE_LAST_ITERATION_FINALIZE_RAIL"):
+ logger.info(
+ "[JiuWenSwarmDeepAdapter] LastIterationFinalizeRail disabled by env"
+ )
+ return None
+ try:
+ from jiuwenswarm.agents.harness.common.rails.last_iteration_finalize_rail import (
+ LastIterationFinalizeRail,
+ )
+
+ rail = LastIterationFinalizeRail(language=self._resolve_runtime_language())
+ logger.info(
+ "[JiuWenSwarmDeepAdapter] LastIterationFinalizeRail create success"
+ )
+ return rail
+ except Exception as exc:
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] LastIterationFinalizeRail create failed: %s",
+ exc,
+ )
+ return None
+
@staticmethod
def _build_model_routing(config: dict[str, Any] | None = None) -> Any | None:
"""构建 ModelRoutingRail(模型路由)。
@@ -10964,6 +11042,20 @@ class JiuWenSwarmDeepAdapter:
),
]
+ if not mode.startswith("team") and not mode.startswith("code"):
+ rail_infos.append(
+ _RailBuildInfo(
+ "_stalled_access_circuit_rail",
+ self._build_stalled_access_circuit_rail,
+ )
+ )
+ rail_infos.append(
+ _RailBuildInfo(
+ "_last_iteration_finalize_rail",
+ self._build_last_iteration_finalize_rail,
+ )
+ )
+
# SkillEvolutionRail / TTSERail 不在冷启动时挂载,由 _update_rails_for_mode
# 经 _reconcile_evolution_rails 按配置按需注册/注销
@@ -13745,6 +13837,10 @@ class JiuWenSwarmDeepAdapter:
circuit_breaker_rail = getattr(self, "_circuit_breaker_rail", None)
if circuit_breaker_rail is not None:
circuit_breaker_rail.set_language(resolved_language)
+ for rail_name in ("_stalled_access_circuit_rail", "_last_iteration_finalize_rail"):
+ localized_rail = getattr(self, rail_name, None)
+ if localized_rail is not None:
+ localized_rail.set_language(resolved_language)
eternal_conversation_rail = getattr(self, "_eternal_conversation_rail", None)
if eternal_conversation_rail is not None:
@@ -20956,6 +21052,7 @@ class JiuWenSwarmDeepAdapter:
interaction_stream = None
interaction_stream_abort = True
perf_summary_status = "ok"
+ emitted_chat_error = False
hitl_pending_stream = False
try:
self._runtime_cron_tool_context.remember_current_binding()
@@ -22159,6 +22256,8 @@ class JiuWenSwarmDeepAdapter:
lambda: reset_current_multimodal_image_files(image_files_token),
)
)
+ if emitted_chat_error and perf_summary_status != "cancelled":
+ perf_summary_status = "error"
if perf_context_initialized:
cleanup_steps.extend(
(
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py b/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py
index a3bf652b87..57b9c88930 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py
@@ -219,6 +219,7 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):
"skill_tool",
"skill_complete",
"todo",
+ "office_claw_list_wishes",
],
},
}
@@ -259,6 +260,9 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):
"_model_routing_rail",
"_security_rail",
"_heartbeat_rail",
+ "_request_summary_rail",
+ "_stalled_access_circuit_rail",
+ "_last_iteration_finalize_rail",
"_subagent_rail",
"_permission_rail",
"_context_processor_rail",
diff --git a/tests/unit_tests/agentserver/rails/test_last_iteration_finalize_rail.py b/tests/unit_tests/agentserver/rails/test_last_iteration_finalize_rail.py
new file mode 100644
index 0000000000..f7ad89108a
--- /dev/null
+++ b/tests/unit_tests/agentserver/rails/test_last_iteration_finalize_rail.py
@@ -0,0 +1,165 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Tests for the last-iteration partial-result finalizer."""
+
+from __future__ import annotations
+
+import uuid
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import pytest
+from openjiuwen.core.foundation.llm import (
+ AssistantMessage,
+ ModelClientConfig,
+ ModelRequestConfig,
+ ToolCall,
+)
+from openjiuwen.core.foundation.tool import Tool, ToolCard
+from openjiuwen.core.runner import Runner
+from openjiuwen.core.session.agent import Session
+from openjiuwen.core.single_agent.rail.base import ModelCallInputs
+from openjiuwen.harness import create_deep_agent
+
+from jiuwenswarm.agents.harness.common.rails.last_iteration_finalize_rail import (
+ LastIterationFinalizeRail,
+)
+
+
+def _ctx(iteration: int, max_iterations: int, *, tool_calls: bool = True):
+ agent = SimpleNamespace(
+ _react_agent=SimpleNamespace(
+ _config=SimpleNamespace(max_iterations=max_iterations)
+ )
+ )
+ response = SimpleNamespace(tool_calls=[SimpleNamespace()] if tool_calls else [])
+ return SimpleNamespace(
+ agent=agent,
+ inputs=ModelCallInputs(react_iteration=iteration, response=response),
+ request_force_finish=MagicMock(),
+ )
+
+
+async def test_no_finish_before_last_iteration() -> None:
+ rail = LastIterationFinalizeRail()
+ ctx = _ctx(iteration=2, max_iterations=3)
+ await rail.before_invoke(ctx)
+
+ await rail.after_react_iteration(ctx)
+
+ ctx.request_force_finish.assert_not_called()
+
+
+async def test_last_iteration_with_model_call_inputs_returns_actionable_error() -> None:
+ rail = LastIterationFinalizeRail()
+ ctx = _ctx(iteration=3, max_iterations=3)
+ await rail.before_invoke(ctx)
+
+ await rail.after_react_iteration(ctx)
+
+ ctx.request_force_finish.assert_called_once()
+ payload = ctx.request_force_finish.call_args[0][0]
+ assert payload["result_type"] == "error"
+ assert "最大思考轮数" in payload["output"]
+ assert "建议" in payload["output"]
+
+
+async def test_text_only_response_does_not_force_finish() -> None:
+ rail = LastIterationFinalizeRail()
+ ctx = _ctx(iteration=3, max_iterations=3, tool_calls=False)
+ await rail.before_invoke(ctx)
+
+ await rail.after_react_iteration(ctx)
+
+ ctx.request_force_finish.assert_not_called()
+
+
+async def test_set_language_switches_to_english() -> None:
+ rail = LastIterationFinalizeRail()
+ ctx = _ctx(iteration=3, max_iterations=3)
+ await rail.before_invoke(ctx)
+ rail.set_language("en")
+
+ await rail.after_react_iteration(ctx)
+
+ payload = ctx.request_force_finish.call_args[0][0]
+ assert "maximum number of reasoning iterations" in payload["output"]
+
+
+async def test_reads_max_iterations_from_agent_config_fallback() -> None:
+ rail = LastIterationFinalizeRail()
+ ctx = SimpleNamespace(
+ agent=SimpleNamespace(_config=SimpleNamespace(max_iterations=3)),
+ inputs=ModelCallInputs(
+ react_iteration=3,
+ response=SimpleNamespace(tool_calls=[SimpleNamespace()]),
+ ),
+ request_force_finish=MagicMock(),
+ )
+ await rail.before_invoke(ctx)
+
+ await rail.after_react_iteration(ctx)
+
+ ctx.request_force_finish.assert_called_once()
+
+
+class _ToolCallModel:
+ def __init__(self) -> None:
+ self.model_client_config = ModelClientConfig(
+ client_provider="OpenAI", api_key="fake", api_base="https://fake.invalid"
+ )
+ self.model_config = ModelRequestConfig(model_name="fake")
+
+ async def stream(self, messages, **kwargs):
+ yield AssistantMessage(
+ content="",
+ tool_calls=[ToolCall(id="t1", type="function", name="echo", arguments="{}")],
+ )
+
+ async def invoke(self, messages, **kwargs):
+ return AssistantMessage(
+ content="",
+ tool_calls=[ToolCall(id="t1", type="function", name="echo", arguments="{}")],
+ )
+
+
+class _EchoTool(Tool):
+ def __init__(self) -> None:
+ super().__init__(ToolCard(name="echo", description="echo"))
+
+ async def invoke(self, inputs, **kwargs):
+ return "ok"
+
+ async def stream(self, inputs, **kwargs):
+ yield "ok"
+
+
+async def test_real_react_loop_uses_model_call_inputs_on_last_iteration(tmp_path) -> None:
+ await Runner.start()
+ agent = create_deep_agent(
+ model=_ToolCallModel(),
+ tools=[_EchoTool()],
+ system_prompt="last-iteration contract test",
+ max_iterations=1,
+ workspace=str(tmp_path),
+ agent_ras=False,
+ enable_security_rail=False,
+ enable_llm_retry_rail=False,
+ rails=[LastIterationFinalizeRail()],
+ )
+ await agent.start(session=Session(session_id="last-iter-" + uuid.uuid4().hex))
+ try:
+ result = await agent.invoke({"query": "run the echo tool"})
+ finally:
+ await agent.stop()
+
+ assert result["result_type"] == "error"
+ assert "最大思考轮数" in result["output"]
+ assert "Max iterations reached without completion" not in result["output"]
diff --git a/tests/unit_tests/agentserver/rails/test_stalled_access_circuit_rail.py b/tests/unit_tests/agentserver/rails/test_stalled_access_circuit_rail.py
new file mode 100644
index 0000000000..6665410097
--- /dev/null
+++ b/tests/unit_tests/agentserver/rails/test_stalled_access_circuit_rail.py
@@ -0,0 +1,201 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Tests for the strategy-level auth/credential loop breaker."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import pytest
+
+from jiuwenswarm.agents.harness.common.rails.execution_guard.stalled_access_circuit_rail import (
+ StalledAccessCircuitRail,
+)
+
+
+def _ctx(tool_result, tool_args=None, tool_name="bash"):
+ return SimpleNamespace(
+ session=SimpleNamespace(get_session_id=lambda: "session-1"),
+ inputs=SimpleNamespace(
+ tool_name=tool_name,
+ tool_args=tool_args or {},
+ tool_result=tool_result,
+ ),
+ request_force_finish=MagicMock(),
+ )
+
+
+async def test_trips_after_repeated_auth_failures() -> None:
+ rail = StalledAccessCircuitRail(auth_threshold=3, probe_threshold=99)
+ ctx = _ctx({"content": "HTTP 401 AUTH_SESSION_TERMINATED"})
+ await rail.before_invoke(ctx)
+
+ await rail.after_tool_call(ctx)
+ await rail.after_tool_call(ctx)
+ ctx.request_force_finish.assert_not_called()
+
+ await rail.after_tool_call(ctx)
+ ctx.request_force_finish.assert_called_once()
+ payload = ctx.request_force_finish.call_args[0][0]
+ assert payload["result_type"] == "error"
+ assert "重新登录" in payload["output"]
+
+
+async def test_trips_after_repeated_credential_probes() -> None:
+ rail = StalledAccessCircuitRail(auth_threshold=99, probe_threshold=2)
+ ctx = _ctx(
+ {"content": "wrote copy_cookies_share.py"},
+ {"content": "import ctypes; crypt32.CryptUnprotectData(data)"},
+ )
+ await rail.before_invoke(ctx)
+
+ await rail.after_tool_call(ctx)
+ ctx.request_force_finish.assert_not_called()
+
+ await rail.after_tool_call(ctx)
+ ctx.request_force_finish.assert_called_once()
+ payload = ctx.request_force_finish.call_args[0][0]
+ assert payload["result_type"] == "error"
+ assert "凭证" in payload["output"]
+
+
+async def test_single_auth_failure_does_not_trip() -> None:
+ rail = StalledAccessCircuitRail(auth_threshold=3, probe_threshold=99)
+ ctx = _ctx({"content": "401 AUTH_SESSION_TERMINATED"})
+ await rail.before_invoke(ctx)
+
+ await rail.after_tool_call(ctx)
+
+ ctx.request_force_finish.assert_not_called()
+
+
+async def test_normal_tool_results_do_not_count_as_probes() -> None:
+ # Both tool_result and tool_args participate in the scan; "ok" contains
+ # no credential fingerprint and therefore must not add to the count.
+ rail = StalledAccessCircuitRail(auth_threshold=99, probe_threshold=3)
+ ctx = _ctx({"content": "ok"}, {})
+ await rail.before_invoke(ctx)
+
+ await rail.after_tool_call(ctx)
+ ctx.inputs.tool_args = {"content": "CryptUnprotectData"}
+ await rail.after_tool_call(ctx)
+ ctx.request_force_finish.assert_not_called()
+
+ ctx.inputs.tool_args = {}
+ ctx.inputs.tool_result = {"content": "ok"}
+ await rail.after_tool_call(ctx)
+ ctx.inputs.tool_args = {"content": "Network/Cookies"}
+ await rail.after_tool_call(ctx)
+ ctx.request_force_finish.assert_not_called()
+
+ ctx.inputs.tool_args = {"content": "Login Data"}
+ await rail.after_tool_call(ctx)
+ ctx.request_force_finish.assert_called_once()
+
+
+async def test_non_relevant_tool_does_not_trip() -> None:
+ rail = StalledAccessCircuitRail(auth_threshold=3, probe_threshold=99)
+ ctx = _ctx({"content": "HTTP 401 AUTH_SESSION_TERMINATED"}, tool_name="web_search")
+ await rail.before_invoke(ctx)
+
+ await rail.after_tool_call(ctx)
+ await rail.after_tool_call(ctx)
+ await rail.after_tool_call(ctx)
+
+ ctx.request_force_finish.assert_not_called()
+
+
+async def test_generic_authentication_required_is_not_a_strong_fingerprint() -> None:
+ rail = StalledAccessCircuitRail(auth_threshold=2, probe_threshold=99)
+ ctx = _ctx({"content": "Authentication required"})
+ await rail.before_invoke(ctx)
+
+ await rail.after_tool_call(ctx)
+ await rail.after_tool_call(ctx)
+
+ ctx.request_force_finish.assert_not_called()
+
+
+async def test_set_language_switches_to_english() -> None:
+ rail = StalledAccessCircuitRail(auth_threshold=1, probe_threshold=99)
+ ctx = _ctx({"content": "AUTH_SESSION_TERMINATED"})
+ await rail.before_invoke(ctx)
+ rail.set_language("en")
+
+ await rail.after_tool_call(ctx)
+
+ payload = ctx.request_force_finish.call_args[0][0]
+ assert "sign in" in payload["output"]
+
+
+async def test_scans_tail_of_large_tool_result() -> None:
+ rail = StalledAccessCircuitRail(auth_threshold=1, probe_threshold=99)
+ ctx = _ctx({"content": "x" * (128 * 1024) + " AUTH_SESSION_TERMINATED"})
+ await rail.before_invoke(ctx)
+
+ await rail.after_tool_call(ctx)
+
+ ctx.request_force_finish.assert_called_once()
+
+
+async def test_exec_tool_participates() -> None:
+ rail = StalledAccessCircuitRail(auth_threshold=1, probe_threshold=99)
+ ctx = _ctx({"content": "AUTH_SESSION_TERMINATED"}, tool_name="exec_command")
+ await rail.before_invoke(ctx)
+
+ await rail.after_tool_call(ctx)
+
+ ctx.request_force_finish.assert_called_once()
+
+
+class _ToolOutputLike:
+ success = True
+ error = None
+
+ def __init__(self, data: str) -> None:
+ self.data = data
+
+ def __repr__(self) -> str:
+ raise AssertionError("repr must not be called for object tool output")
+
+
+async def test_object_tool_output_uses_fields_not_repr() -> None:
+ rail = StalledAccessCircuitRail(auth_threshold=1, probe_threshold=99)
+ payload = "x" * (4 * 1024 * 1024) + " AUTH_SESSION_TERMINATED"
+ ctx = _ctx(_ToolOutputLike(payload))
+ await rail.before_invoke(ctx)
+
+ await rail.after_tool_call(ctx)
+
+ ctx.request_force_finish.assert_called_once()
+
+
+async def test_tool_call_arguments_fallback() -> None:
+ rail = StalledAccessCircuitRail(auth_threshold=99, probe_threshold=1)
+ ctx = SimpleNamespace(
+ session=SimpleNamespace(get_session_id=lambda: "session-1"),
+ inputs=SimpleNamespace(
+ tool_name="bash",
+ tool_args=None,
+ tool_result={"content": "ok"},
+ tool_call=SimpleNamespace(arguments={"content": "CryptUnprotectData"}),
+ ),
+ request_force_finish=MagicMock(),
+ )
+ await rail.before_invoke(ctx)
+
+ await rail.after_tool_call(ctx)
+
+ ctx.request_force_finish.assert_called_once()
diff --git a/tests/unit_tests/agentserver/test_flash_adapter_tool_face.py b/tests/unit_tests/agentserver/test_flash_adapter_tool_face.py
index 5cf043441a..a1bbe190ea 100644
--- a/tests/unit_tests/agentserver/test_flash_adapter_tool_face.py
+++ b/tests/unit_tests/agentserver/test_flash_adapter_tool_face.py
@@ -109,6 +109,8 @@ def test_react_override_replaces_eager_tools_and_keeps_siblings() -> None:
assert react["enable_task_loop"] is False
lazy = react["tool_lazy_load"]
+ # Flash override is the source of truth for flash; config.yaml's
+ # react.tool_lazy_load.eager_tools covers the non-flash deep path.
assert lazy["eager_tools"] == [
"web_search",
"fetch_webpage",
@@ -122,6 +124,7 @@ def test_react_override_replaces_eager_tools_and_keeps_siblings() -> None:
"skill_tool",
"skill_complete",
"todo",
+ "office_claw_list_wishes",
]
assert lazy["enabled"] is True
assert lazy["subagents"] == {"enabled": True}