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: 修复文件重发被去重拦截并新增不可重试工具结果契约

openJiuwen-bot636baa1c76fd
diff --git a/deploy/yuanrong/conf/gateway-config-yuanrong.template.yaml b/deploy/yuanrong/conf/gateway-config-yuanrong.template.yaml
index 158ef36e65..8af41c382e 100644
--- a/deploy/yuanrong/conf/gateway-config-yuanrong.template.yaml
+++ b/deploy/yuanrong/conf/gateway-config-yuanrong.template.yaml
@@ -529,6 +529,10 @@ execution_guard:
global_breaker_threshold: 30
# 未知/错误工具连续调用达到该次数时停止重试并中断
unknown_tool_threshold: 10
+ # 同一工具+参数连续返回不可重试契约时中断。
+ # 仅在 circuit_breaker.enabled=true 时生效;默认部署由 agent_ras 负责循环检测,
+ # 不消费 tool_result_contract。
+ non_retryable_threshold: 3
channels:
web:
diff --git a/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py b/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py
index 8ce4dd7ab0..842e89eaff 100644
--- a/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py
+++ b/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py
@@ -389,6 +389,13 @@ JiuwenSwarm 使用独立的内部数据目录保存启动配置、Agent 身份
**调用方式**:使用文件的绝对路径作为参数调用 `send_file_to_user` 工具。
+**用户说没收到文件时**:如果用户明确表示没有收到文件、要求“再发一次/重新发送/文件呢”,
+调用 `send_file_to_user` 时设置 `force=true`,绕过本会话的重复发送保护。
+`force` 只用于用户明确要求重发的场景,普通首次发送不要设置。
+
+**不要用 PPT 翻译工具发送普通文件**:`invoke_pptx_translation` 只用于翻译已打开的 PPT;
+发送/找回已生成的 md、html、docx、xlsx 等文件必须使用 `send_file_to_user`。
+
**跨 channel 投递**:`send_file_to_user` 接受可选参数 `target_channels`(字符串数组),
用于指定文件投递的目标 channel(如 `["feishu", "xiaoyi", "web"]`)。
- 用户在某个 channel(如飞书)请求发送文件、或要求把文件发给指定 channel 时,传入 `target_channels`。
@@ -544,6 +551,14 @@ When the `send_file_to_user` tool is available in your tool list, you **must** p
**How to call**: Use the absolute file path(s) as the parameter to invoke the `send_file_to_user` tool.
+**When the user says they did not receive the file**: if the user explicitly reports a missing
+file or asks to resend it, call `send_file_to_user` with `force=true` to bypass the session-level
+duplicate guard. Do not set `force` for an ordinary first delivery.
+
+**Do not use the PPT translation tool to send ordinary files**: `invoke_pptx_translation` is only
+for translating an already-open PPT. Use `send_file_to_user` for md, html, docx, xlsx, and other
+deliverables.
+
**Cross-channel delivery**: `send_file_to_user` accepts an optional `target_channels` parameter
to specify delivery targets by channel id (e.g. `["feishu", "xiaoyi", "web"]`).
- When a user on a given channel requests a file, or asks to send it to a specific channel,
diff --git a/jiuwenswarm/agents/harness/common/rails/execution_guard/circuit_breaker_rail.py b/jiuwenswarm/agents/harness/common/rails/execution_guard/circuit_breaker_rail.py
index 8420a65b87..b9fd8c8f60 100644
--- a/jiuwenswarm/agents/harness/common/rails/execution_guard/circuit_breaker_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/execution_guard/circuit_breaker_rail.py
@@ -7,6 +7,12 @@
- unknown_tool_repeat: 错误工具连续调用 (CRITICAL≥10)
- global_breaker: 工具无进展兜底中断 (CRITICAL≥30)
- ping_pong: 两工具交替循环,尾部无进展轮次 (WARNING≥10, CRITICAL≥20)
+ - non_retryable_tool: 同一工具+参数连续返回非重试契约 (CRITICAL≥3)
+
+部署边界:
+ 本 rail 仅在 ``execution_guard.circuit_breaker.enabled: true`` 时挂载;
+ 默认部署使用 agent_ras 的 repeat_tool 检测链,不消费
+ ``tool_result_contract``,因此默认不会触发 non_retryable_tool。
"""
from __future__ import annotations
@@ -23,6 +29,9 @@ from typing import Any
from openjiuwen.core.single_agent.rail.base import AgentCallbackContext, InvokeInputs
from openjiuwen.harness.rails.base import DeepAgentRail
+from jiuwenswarm.agents.harness.common.tools.tool_result_contract import (
+ is_non_retryable_tool_result,
+)
from jiuwenswarm.common.utils import logger
@@ -32,6 +41,7 @@ class CircuitBreakerConfig:
critical_threshold: int = 20
global_breaker_threshold: int = 30
unknown_tool_threshold: int = 10
+ non_retryable_threshold: int = 3
@property
def history_size(self) -> int:
@@ -39,6 +49,7 @@ class CircuitBreakerConfig:
4 * self.critical_threshold,
2 * self.global_breaker_threshold,
2 * self.unknown_tool_threshold,
+ 2 * self.non_retryable_threshold,
)
_invoke_sid: contextvars.ContextVar[str | None] = contextvars.ContextVar(
@@ -55,6 +66,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"ping_pong_critical": "Ping-Pong 循环: {count} 轮交替无进展,阻断",
"ping_pong_warning": "Ping-Pong 警告: {count} 轮交替无进展",
"generic_repeat": "工具 {tool_name} 已重复调用 {count} 次,请检查是否有效",
+ "non_retryable_tool": "工具 {tool_name} 的前置条件不满足且已被要求停止重试,现已终止本轮",
},
"en": {
"global_circuit_breaker": (
@@ -70,6 +82,10 @@ _MESSAGES: dict[str, dict[str, str]] = {
"generic_repeat": (
"Tool {tool_name} has been repeated {count} times, please verify it is effective"
),
+ "non_retryable_tool": (
+ "Tool {tool_name} reported a non-retryable precondition failure {count} times; "
+ "the current turn is being stopped"
+ ),
},
}
@@ -281,6 +297,7 @@ class ToolCallRecord:
result_hash: str | None
timestamp: float
has_error: bool = False
+ non_retryable: bool = False
@dataclass
@@ -410,6 +427,7 @@ class CircuitBreakerRail(DeepAgentRail):
has_error = ToolResultErrorDetector.infer_record_has_error(
tool_result, ctx,
)
+ non_retryable = self._is_non_retryable_result(tool_result)
async with self._get_lock(sid):
history = self._get_history(sid)
@@ -419,6 +437,7 @@ class CircuitBreakerRail(DeepAgentRail):
result_hash=result_hash,
timestamp=time.time(),
has_error=has_error,
+ non_retryable=non_retryable,
))
if len(history) > self._config.history_size:
self._histories[sid] = history[-self._config.history_size:]
@@ -437,7 +456,7 @@ class CircuitBreakerRail(DeepAgentRail):
logger.warning("[CircuitBreaker] %s", self._format_message(result))
# ------------------------------------------------------------------
- # _detect: 四种检测器按优先级依次检查
+ # _detect: 五种检测器按优先级依次检查
# ------------------------------------------------------------------
def _detect(
@@ -460,6 +479,14 @@ class CircuitBreakerRail(DeepAgentRail):
detector="unknown_tool_repeat", count=unknown_streak,
msg_key="unknown_tool_repeat", tool_name=tool_name)
+ non_retryable_streak = self._get_non_retryable_streak(
+ history, tool_name, args_hash,
+ )
+ if non_retryable_streak >= cfg.non_retryable_threshold:
+ return DetectionResult(stuck=True, level="critical",
+ detector="non_retryable_tool", count=non_retryable_streak,
+ msg_key="non_retryable_tool", tool_name=tool_name)
+
ping_pong = self._get_ping_pong_streak(history, args_hash)
if (
ping_pong.no_progress
@@ -522,6 +549,11 @@ class CircuitBreakerRail(DeepAgentRail):
}
return {"raw": str(result)}
+ @staticmethod
+ def _is_non_retryable_result(result: Any) -> bool:
+ """Detect a structured tool result that explicitly asks not to be retried."""
+ return is_non_retryable_tool_result(result)
+
# ------------------------------------------------------------------
# 计数方法
# ------------------------------------------------------------------
@@ -651,4 +683,21 @@ class CircuitBreakerRail(DeepAgentRail):
if not record.has_error:
break
streak += 1
+ return streak
+
+ def _get_non_retryable_streak(
+ self,
+ history: list[ToolCallRecord],
+ tool_name: str,
+ args_hash: str,
+ ) -> int:
+ streak = 0
+ for record in reversed(history):
+ if record.tool_name != tool_name:
+ break
+ if record.args_hash != args_hash:
+ break
+ if not record.non_retryable:
+ break
+ streak += 1
return streak
\ No newline at end of file
diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py
index d930766232..81c5add97d 100644
--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py
+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py
@@ -944,6 +944,16 @@ def _bounded_diagnostic(
return bounded or fallback
+_ABS_PATH_SEGMENT_RE = re.compile(
+ r"(?:(?:[A-Za-z]:\\|/)[^:\n\r]*[\\/])([^\\/\s'\"<>|]+)"
+)
+
+
+def _basename_paths(text: str) -> str:
+ """Keep only the final path segment so host directories are not exposed."""
+ return _ABS_PATH_SEGMENT_RE.sub(r"\1", text)
+
+
def _redact_json_value(value: Any, secrets: tuple[str, ...]) -> Any:
"""Iteratively copy and redact a bounded JSON key/value tree."""
if isinstance(value, str):
@@ -4172,6 +4182,12 @@ async def _consume_stream(
"conversation_id": chunk.get("conversation_id", outcome_cid),
"error_code": "report_file_write_failed",
"error": type(exc).__name__,
+ "detail": _bounded_diagnostic(
+ _basename_paths(str(exc)),
+ secrets=(),
+ limit=500,
+ fallback=type(exc).__name__,
+ ),
}, chunk)
artifact_mime_types = {
"md": "text/markdown",
@@ -5100,9 +5116,16 @@ async def _write_report_artifacts_stream(
fallback_markdown = report_path_md.read_text(encoding="utf-8")
except (OSError, UnicodeError):
fallback_markdown = None
- generated_html = await _generate_report_html(
- final_result, report_path_md, fallback_markdown
- )
+ try:
+ generated_html = await _generate_report_html(
+ final_result, report_path_md, fallback_markdown
+ )
+ except Exception as exc: # noqa: BLE001 - markdown remains the deliverable
+ logger.warning(
+ "[deepresearch_stream] html generation failed; delivering markdown only: %r",
+ exc,
+ )
+ generated_html = None
html_style_status = None
html_style_phase = None
html_style_reason_code = None
diff --git a/jiuwenswarm/agents/harness/common/tools/send_file_to_user.py b/jiuwenswarm/agents/harness/common/tools/send_file_to_user.py
index 0cc177615c..f0c78ec06d 100644
--- a/jiuwenswarm/agents/harness/common/tools/send_file_to_user.py
+++ b/jiuwenswarm/agents/harness/common/tools/send_file_to_user.py
@@ -21,6 +21,9 @@ from typing import Any, List, Optional, Union
from openjiuwen.core.foundation.tool import LocalFunction, Tool, ToolCard
+from jiuwenswarm.agents.harness.common.tools.tool_result_contract import (
+ build_non_retryable_tool_result,
+)
from jiuwenswarm.edition import is_enterprise
@@ -166,6 +169,29 @@ def _partition_sent_files(
return new_paths, skipped
+def _format_skipped_file_links(skipped_files: list[str], session_id: str) -> list[str]:
+ """Best-effort download links for files already delivered in this session.
+
+ A user who reports "I did not receive the file" must still get something
+ clickable even when the duplicate guard blocks a second push.
+ """
+ lines: list[str] = []
+ for path in skipped_files:
+ name = os.path.basename(path)
+ url = ""
+ try:
+ from jiuwenswarm.agents.harness.common.tools.web_file_download import (
+ build_file_download_info,
+ )
+
+ info = build_file_download_info(path, name, session_id)
+ url = str(info.get("download_url") or "").strip()
+ except Exception as exc: # noqa: BLE001 - a missing link must not fail the tool
+ logger.warning("[SendFileToolkit] build download link failed: %s (%s)", path, exc)
+ lines.append(f" - {name}: {url}" if url else f" - {path}")
+ return lines
+
+
def _mark_files_sent(session_id: str, paths: list[str]) -> None:
sid = (session_id or "").strip() or "default"
sent = _SENT_FILE_PATHS_BY_SESSION.setdefault(sid, set())
@@ -309,6 +335,7 @@ class SendFileToolkit:
self,
abs_file_path_list: Union[List[str], str],
target_channels: Union[List[str], str, None] = None,
+ force: bool = False,
**_ignored: Any,
) -> str:
"""Send files to user.
@@ -321,6 +348,9 @@ class SendFileToolkit:
Gateway auto-routes the file to all channels joined to the
session (team mode). When provided, the file is delivered
only to the specified targets.
+ force: Bypass the session-level duplicate guard. Set this only
+ when the user explicitly says they did not receive the file
+ and asks to resend it.
Returns:
Success message or error description.
@@ -365,20 +395,28 @@ class SendFileToolkit:
logger.warning("[SendFileToolkit] 文件不存在: %s", fp)
if not valid_files:
- msg_parts = ["发送文件失败:所有文件均不存在"]
- for mf in missing_files:
- msg_parts.append(f" - {mf}")
+ error = "发送文件失败:所有文件均不存在;请先确认路径。缺失文件: " + ", ".join(
+ missing_files
+ )
_safe_emit_audit_evt(
SUBMDL="file",
PROC="send_file_to_user",
- MSG=msg_parts[0],
+ MSG="发送文件失败:所有文件均不存在",
EVT="send_file_failed",
session_id=route.session_id,
request_id=route.request_id,
)
- return "\n".join(msg_parts)
+ return build_non_retryable_tool_result(error, "read_file")
- valid_files, skipped_files = _partition_sent_files(route.session_id, valid_files)
+ if force:
+ skipped_files: list[str] = []
+ logger.info(
+ "[SendFileToolkit] force resend requested session_id=%s files=%d",
+ route.session_id,
+ len(valid_files),
+ )
+ else:
+ valid_files, skipped_files = _partition_sent_files(route.session_id, valid_files)
if not valid_files:
logger.info(
"[SendFileToolkit] skip duplicate send session_id=%s skipped=%s missing=%s",
@@ -388,9 +426,8 @@ class SendFileToolkit:
)
msg_parts: list[str] = []
if skipped_files:
- msg_parts.append("文件已在本次会话发送过,跳过重复投递:")
- for sf in skipped_files:
- msg_parts.append(f" - {sf}")
+ msg_parts.append("文件已在本次会话发送过,跳过重复投递。可直接使用以下链接下载:")
+ msg_parts.extend(_format_skipped_file_links(skipped_files, route.session_id))
if missing_files:
msg_parts.append("以下文件不存在,未发送:")
for mf in missing_files:
@@ -850,6 +887,7 @@ class SendFileToolkit:
"省略时默认投给最近发起请求的人类成员(按 session 记录的发起者);web 发起或无人类成员时投 web。"
"多 app 场景定向到指定 feishu 用户时,传入该用户的 member_name(不会误投其它 app);"
"跨端投递(如把文件发给飞书用户、或发给 web)时传入对应 member_name 或 'web'。"
+ "force 可选:用户明确说没有收到文件、要求重新发送时传 true;普通首次发送不要传。"
"【文件命名与「AI生成」合规标记】用户指定文件名时,交付文件名必须与其要求逐字一致,"
"禁止自行追加「-AI生成」等任何后缀或额外标记;用户说「文件名不要带 AI生成 后缀 / 命名保持完全一致」"
"时仅指文件命名本身,按用户要求(重)命名后重新交付即可。"
@@ -881,6 +919,13 @@ class SendFileToolkit:
"定向到指定 feishu 用户传其 member_name;跨端投递传对应 member_name 或 'web'。"
),
},
+ "force": {
+ "type": "boolean",
+ "description": (
+ "可选:用户明确表示没有收到文件并要求重新发送时设为 true,"
+ "跳过本会话的重复发送保护。普通首次发送不要设置。"
+ ),
+ },
},
"required": ["abs_file_path_list"],
},
diff --git a/jiuwenswarm/agents/harness/common/tools/tool_result_contract.py b/jiuwenswarm/agents/harness/common/tools/tool_result_contract.py
new file mode 100644
index 0000000000..9906f3980c
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/tools/tool_result_contract.py
@@ -0,0 +1,74 @@
+"""Structured contract for tool results that must not be retried."""
+
+from __future__ import annotations
+
+import json
+from collections.abc import Iterator
+from typing import Any
+
+NON_RETRYABLE_CONTRACT_ID = "jiuwenswarm.non_retryable.v1"
+
+
+def build_non_retryable_tool_result(error: str, suggested_tool: str) -> str:
+ """Build the canonical non-retryable tool result payload."""
+ return json.dumps(
+ {
+ "contract": NON_RETRYABLE_CONTRACT_ID,
+ "success": False,
+ "error": error,
+ "retryable": False,
+ "suggested_tool": suggested_tool,
+ },
+ ensure_ascii=False,
+ )
+
+
+def is_non_retryable_tool_result(result: Any) -> bool:
+ """Return True only for a structured non-retryable tool result.
+
+ The check accepts structured payloads only, and requires the explicit
+ ``contract`` marker emitted by :func:`build_non_retryable_tool_result`.
+ The marker keeps a normal tool result (for example ``read_file`` returning
+ a JSON file whose content happens to contain ``retryable: false``) from
+ being misclassified as a tool failure contract.
+ """
+ for payload in _iter_structured_payloads(result):
+ if _matches_contract(payload):
+ return True
+ return False
+
+
+def _matches_contract(payload: dict[str, Any]) -> bool:
+ if payload.get("contract") != NON_RETRYABLE_CONTRACT_ID:
+ return False
+ return payload.get("retryable") is False
+
+
+def _iter_structured_payloads(value: Any) -> Iterator[dict[str, Any]]:
+ if isinstance(value, dict):
+ yield value
+ for attr in ("content", "output", "result", "data"):
+ nested = value.get(attr)
+ if nested is not None:
+ yield from _iter_structured_payloads(nested)
+ return
+ if isinstance(value, str):
+ parsed = _parse_json(value)
+ if isinstance(parsed, dict):
+ yield parsed
+ return
+ if isinstance(value, (list, tuple)):
+ for item in value:
+ yield from _iter_structured_payloads(item)
+ return
+ for attr in ("content", "output", "result", "data"):
+ nested = getattr(value, attr, None)
+ if nested is not None:
+ yield from _iter_structured_payloads(nested)
+
+
+def _parse_json(text: str) -> Any:
+ try:
+ return json.loads(text)
+ except (TypeError, ValueError):
+ return None
diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yaml
index 195c4ba580..8ffa15ce23 100644
--- a/jiuwenswarm/resources/config.yaml
+++ b/jiuwenswarm/resources/config.yaml
@@ -1016,12 +1016,15 @@ execution_guard:
# develop 防死循环 rail:重复调用 / ping-pong / 未知工具打断(force-finish)。
# 默认关闭,避免和 dest-stable 已开启的 agent_ras.repeat_tool 双挂。
# 不是 issue 的 OPEN/HALF_OPEN 恢复型熔断。
+ # non_retryable_tool 检测器也在此开关下;默认部署使用 agent_ras,
+ # 不消费 tool_result_contract,因此默认不会触发该检测器。
circuit_breaker:
enabled: false
warning_threshold: 10
critical_threshold: 20
global_breaker_threshold: 30
unknown_tool_threshold: 10
+ non_retryable_threshold: 3
# Agent RAS 整体配置
agent_ras:
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index 033d40e616..36d008b3aa 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -10261,6 +10261,10 @@ class JiuWenSwarmDeepAdapter:
cb_cfg.get("unknown_tool_threshold", defaults.unknown_tool_threshold),
defaults.unknown_tool_threshold,
)
+ non_retryable = JiuWenSwarmDeepAdapter._coerce_circuit_breaker_threshold(
+ cb_cfg.get("non_retryable_threshold", defaults.non_retryable_threshold),
+ defaults.non_retryable_threshold,
+ )
if warning > critical:
return None
if critical > global_breaker:
@@ -10270,17 +10274,28 @@ class JiuWenSwarmDeepAdapter:
critical_threshold=critical,
global_breaker_threshold=global_breaker,
unknown_tool_threshold=unknown,
+ non_retryable_threshold=non_retryable,
)
def _build_circuit_breaker_rail(self) -> CircuitBreakerRail | None:
- """Build develop's loop-detection rail. Default off; dest-stable RAS stays on."""
+ """Build develop's loop-detection rail. Default off; dest-stable RAS stays on.
+
+ The non_retryable_tool detector is only mounted when
+ ``execution_guard.circuit_breaker.enabled`` is true. Default deployments
+ keep agent_ras as the loop-detection chain, which does not consume
+ ``tool_result_contract``.
+ """
try:
guard_cfg = (get_config() or {}).get("execution_guard") or {}
cb_cfg = guard_cfg.get("circuit_breaker") if isinstance(guard_cfg, dict) else {}
if not isinstance(cb_cfg, dict):
cb_cfg = {}
if cb_cfg.get("enabled", False) is not True:
- logger.info("[JiuWenSwarmDeepAdapter] CircuitBreakerRail disabled by config")
+ logger.info(
+ "[JiuWenSwarmDeepAdapter] CircuitBreakerRail disabled by config; "
+ "agent_ras is the active loop-detection chain and does not consume "
+ "tool_result_contract (non_retryable_tool inactive)"
+ )
return None
defaults = CircuitBreakerConfig()
config = self._circuit_breaker_config_from_mapping(cb_cfg, defaults)
diff --git a/tests/unit_tests/agentserver/rails/test_circuit_breaker_rail.py b/tests/unit_tests/agentserver/rails/test_circuit_breaker_rail.py
index ce7b840129..939c91836e 100644
--- a/tests/unit_tests/agentserver/rails/test_circuit_breaker_rail.py
+++ b/tests/unit_tests/agentserver/rails/test_circuit_breaker_rail.py
@@ -50,6 +50,7 @@ def _rail(**overrides: int) -> CircuitBreakerRail:
critical_threshold=overrides.get("critical_threshold", 4),
global_breaker_threshold=overrides.get("global_breaker_threshold", 5),
unknown_tool_threshold=overrides.get("unknown_tool_threshold", 3),
+ non_retryable_threshold=overrides.get("non_retryable_threshold", 3),
)
)
@@ -114,6 +115,112 @@ def test_unknown_tool_repeat_interrupts_error_streak() -> None:
assert result.detector == "unknown_tool_repeat"
+def test_non_retryable_tool_streak_stops_on_threshold_failure() -> None:
+ rail = _rail(
+ warning_threshold=10,
+ critical_threshold=10,
+ global_breaker_threshold=10,
+ unknown_tool_threshold=10,
+ )
+ history = [
+ _record("invoke_pptx_translation", "a", "err", has_error=True),
+ _record("invoke_pptx_translation", "a", "err", has_error=True),
+ _record("invoke_pptx_translation", "a", "err", has_error=True),
+ ]
+ for record in history:
+ record.non_retryable = True
+ result = rail._detect(history, "invoke_pptx_translation", "a")
+ assert result.stuck is True
+ assert result.level == "critical"
+ assert result.detector == "non_retryable_tool"
+
+
+def test_non_retryable_streak_requires_same_args() -> None:
+ rail = _rail(
+ warning_threshold=10,
+ critical_threshold=10,
+ global_breaker_threshold=10,
+ unknown_tool_threshold=10,
+ )
+ history = [
+ _record("send_file_to_user", "missing-a", "err", has_error=True),
+ _record("send_file_to_user", "missing-b", "err", has_error=True),
+ _record("send_file_to_user", "missing-c", "err", has_error=True),
+ ]
+ for record in history:
+ record.non_retryable = True
+ result = rail._detect(history, "send_file_to_user", "missing-c")
+ assert result.detector != "non_retryable_tool"
+ assert result.stuck is False
+
+
+def test_non_retryable_result_marker_is_detected() -> None:
+ rail = _rail()
+ contract = '"contract": "jiuwenswarm.non_retryable.v1"'
+ assert rail._is_non_retryable_result(
+ f'{{{contract}, "success": false, "retryable": false, '
+ '"suggested_tool": "send_file_to_user"}'
+ )
+ assert rail._is_non_retryable_result(
+ {"contract": "jiuwenswarm.non_retryable.v1", "retryable": False}
+ )
+ assert rail._is_non_retryable_result(
+ {"content": f'{{{contract}, "retryable": false}}'}
+ )
+ assert not rail._is_non_retryable_result('{"success": true}')
+
+
+def test_contract_shaped_json_file_is_not_a_tool_failure() -> None:
+ rail = _rail()
+ assert not rail._is_non_retryable_result(
+ '{"success": false, "retryable": false, "suggested_tool": "read_file"}'
+ )
+
+
+def test_free_text_retryable_field_does_not_trigger() -> None:
+ rail = _rail(
+ warning_threshold=10,
+ critical_threshold=10,
+ global_breaker_threshold=10,
+ unknown_tool_threshold=10,
+ )
+ history = [
+ _record(
+ "read_file",
+ "a",
+ 'config example: {"retryable": false, "note": "not a tool contract"}',
+ ),
+ _record(
+ "read_file",
+ "a",
+ 'doc example: {"retryable": false, "note": "not a tool contract"}',
+ ),
+ ]
+ for record in history:
+ record.non_retryable = rail._is_non_retryable_result(record.result_hash)
+ result = rail._detect(history, "read_file", "a")
+ assert result.detector != "non_retryable_tool"
+ assert result.stuck is False
+
+
+def test_bare_retryable_false_without_contract_marker_is_ignored() -> None:
+ rail = _rail()
+ assert not rail._is_non_retryable_result({"retryable": False})
+ assert not rail._is_non_retryable_result('{"retryable": false}')
+
+
+def test_build_non_retryable_tool_result_roundtrips() -> None:
+ from jiuwenswarm.agents.harness.common.tools.tool_result_contract import (
+ build_non_retryable_tool_result,
+ is_non_retryable_tool_result,
+ )
+
+ payload = build_non_retryable_tool_result(
+ "PPT_TOOLS_NOT_ACTIVE", "send_file_to_user"
+ )
+ assert is_non_retryable_tool_result(payload)
+
+
def test_ping_pong_critical_when_both_sides_stall() -> None:
rail = _rail(critical_threshold=3, warning_threshold=2, global_breaker_threshold=20)
history: list[ToolCallRecord] = []
@@ -160,6 +267,45 @@ async def test_after_tool_call_force_finishes_unknown_tool() -> None:
assert ctx.has_force_finish_request is True
+async def test_real_non_retryable_tool_result_stops_on_threshold_call(tmp_path) -> None:
+ from jiuwenswarm.agents.harness.common.tools.send_file_to_user import (
+ SendFileToolkit,
+ )
+
+ rail = _rail(
+ warning_threshold=10,
+ critical_threshold=10,
+ global_breaker_threshold=10,
+ unknown_tool_threshold=10,
+ )
+ missing = tmp_path / "ai_chip_report.md"
+ result = await SendFileToolkit(
+ request_id="r-missing",
+ session_id="s1",
+ channel_id="web",
+ ).send_file(str(missing))
+
+ contexts = []
+ for _ in range(3):
+ ctx = AgentCallbackContext(
+ agent=object(),
+ inputs=ToolCallInputs(
+ tool_call=SimpleNamespace(
+ name="send_file_to_user",
+ arguments={"abs_file_path_list": [str(missing)]},
+ ),
+ tool_result=result,
+ ),
+ extra={"__jiuwenswarm_cb_session_id__": "s1"},
+ )
+ contexts.append(ctx)
+ await rail.after_tool_call(ctx)
+
+ assert contexts[0].has_force_finish_request is False
+ assert contexts[1].has_force_finish_request is False
+ assert contexts[2].has_force_finish_request is True
+
+
def test_circuit_breaker_builder_stays_disabled_by_default(monkeypatch) -> None:
from jiuwenswarm.server.runtime.agent_adapter import interface_deep as deep_mod
@@ -202,6 +348,7 @@ def test_circuit_breaker_builder_coerces_string_thresholds(monkeypatch) -> None:
"critical_threshold": "20",
"global_breaker_threshold": "30",
"unknown_tool_threshold": "10",
+ "non_retryable_threshold": "3",
}
}
},
@@ -211,6 +358,7 @@ def test_circuit_breaker_builder_coerces_string_thresholds(monkeypatch) -> None:
assert rail is not None
assert rail._config.warning_threshold == 10
assert rail._config.critical_threshold == 20
+ assert rail._config.non_retryable_threshold == 3
def test_dest_agent_ras_passthrough_is_not_disabled() -> None:
diff --git a/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py b/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py
index 7acfed5053..1989dffe09 100644
--- a/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py
+++ b/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py
@@ -3242,6 +3242,46 @@ async def test_html_failure_keeps_published_markdown(tmp_path: Path):
assert Path(artifacts["md"]).is_file()
+async def test_html_exception_still_publishes_markdown(tmp_path: Path):
+ final_result = {
+ "response_content": "# Report",
+ "infer_messages": [],
+ "chart_messages": [],
+ }
+ with patch.object(dt, "get_cwd", return_value=str(tmp_path)), patch.object(
+ dt,
+ "_generate_report_html",
+ new=AsyncMock(side_effect=ValueError("html render failed")),
+ ):
+ (
+ artifacts,
+ html_style_status,
+ html_style_phase,
+ html_style_reason_code,
+ ) = await dt._write_report_artifacts_stream(
+ final_result, "Research", "C1"
+ )
+
+ assert set(artifacts) == {"md"}
+ assert html_style_status is None
+ assert html_style_phase is None
+ assert html_style_reason_code is None
+ assert Path(artifacts["md"]).is_file()
+
+
+def test_error_detail_keeps_only_path_basename():
+ assert dt._basename_paths(
+ r"failed to write D:\zzm\relay-claw\workspace\report.md"
+ ) == "failed to write report.md"
+ assert dt._basename_paths(
+ "failed to write /home/user/workspace/report.md"
+ ) == "failed to write report.md"
+ assert dt._basename_paths(
+ r"failed to write C:\Users\A B\report.md"
+ ) == "failed to write report.md"
+
+
@pytest.mark.asyncio
async def test_progress_file_is_precreated_in_private_owned_directory():
proc = _Proc([json.dumps({"__deepsearch_status__": "error", "error": "done"})])
diff --git a/tests/unit_tests/test_send_file_session_dedup.py b/tests/unit_tests/test_send_file_session_dedup.py
index aa95a0fdfc..aac98bc93d 100644
--- a/tests/unit_tests/test_send_file_session_dedup.py
+++ b/tests/unit_tests/test_send_file_session_dedup.py
@@ -1,4 +1,5 @@
import asyncio
+import json
import sys
import types
from unittest.mock import AsyncMock, MagicMock, patch
@@ -74,6 +75,117 @@ def test_send_file_skips_duplicate_after_success(tmp_path, monkeypatch):
assert mock_server.send_push.await_count == 1
+def test_send_file_force_resends_after_duplicate(tmp_path, monkeypatch):
+ file_path = tmp_path / "ai_chip_report.md"
+ file_path.write_text("hello", encoding="utf-8")
+
+ toolkit = SendFileToolkit(
+ request_id="r-resend",
+ session_id="sess-resend",
+ channel_id="officeclaw",
+ )
+ mock_server = MagicMock()
+ mock_server.send_push = AsyncMock(return_value=1)
+
+ class _FakeAgentWebSocketServer:
+ @staticmethod
+ def get_instance():
+ return mock_server
+
+ monkeypatch.setitem(
+ sys.modules,
+ "jiuwenswarm.server.agent_ws_server",
+ types.SimpleNamespace(AgentWebSocketServer=_FakeAgentWebSocketServer),
+ )
+
+ with patch(
+ "jiuwenswarm.server.runtime.session.session_history.append_history_record",
+ ):
+ first = asyncio.run(toolkit.send_file(str(file_path)))
+ second = asyncio.run(toolkit.send_file(str(file_path)))
+ third = asyncio.run(toolkit.send_file(str(file_path), force=True))
+
+ assert "成功发送" in first
+ assert "跳过重复投递" in second
+ assert "成功发送" in third
+ assert mock_server.send_push.await_count == 2
+
+
+def test_duplicate_skip_returns_a_usable_file_reference(tmp_path, monkeypatch):
+ file_path = tmp_path / "ai_chip_report.html"
+ file_path.write_text("<html></html>", encoding="utf-8")
+
+ toolkit = SendFileToolkit(
+ request_id="r-skip",
+ session_id="sess-skip",
+ channel_id="officeclaw",
+ )
+ mock_server = MagicMock()
+ mock_server.send_push = AsyncMock(return_value=1)
+
+ class _FakeAgentWebSocketServer:
+ @staticmethod
+ def get_instance():
+ return mock_server
+
+ monkeypatch.setitem(
+ sys.modules,
+ "jiuwenswarm.server.agent_ws_server",
+ types.SimpleNamespace(AgentWebSocketServer=_FakeAgentWebSocketServer),
+ )
+
+ with patch(
+ "jiuwenswarm.server.runtime.session.session_history.append_history_record",
+ ), patch(
+ "jiuwenswarm.agents.harness.common.tools.web_file_download.build_file_download_info",
+ return_value={"download_url": "https://example.test/file", "size": 5},
+ ) as build_info:
+ asyncio.run(toolkit.send_file(str(file_path)))
+ build_info.reset_mock()
+ skipped = asyncio.run(toolkit.send_file(str(file_path)))
+
+ assert "跳过重复投递" in skipped
+ assert "https://example.test/file" in skipped
+ assert build_info.call_count == 1
+
+
+def test_duplicate_skip_falls_back_to_path_when_link_generation_fails(tmp_path, monkeypatch):
+ file_path = tmp_path / "ai_chip_report.md"
+ file_path.write_text("hello", encoding="utf-8")
+
+ toolkit = SendFileToolkit(
+ request_id="r-skip-fallback",
+ session_id="sess-skip-fallback",
+ channel_id="officeclaw",
+ )
+ mock_server = MagicMock()
+ mock_server.send_push = AsyncMock(return_value=1)
+
+ class _FakeAgentWebSocketServer:
+ @staticmethod
+ def get_instance():
+ return mock_server
+
+ monkeypatch.setitem(
+ sys.modules,
+ "jiuwenswarm.server.agent_ws_server",
+ types.SimpleNamespace(AgentWebSocketServer=_FakeAgentWebSocketServer),
+ )
+
+ with patch(
+ "jiuwenswarm.server.runtime.session.session_history.append_history_record",
+ ), patch(
+ "jiuwenswarm.agents.harness.common.tools.web_file_download.build_file_download_info",
+ side_effect=RuntimeError("download token unavailable"),
+ ):
+ asyncio.run(toolkit.send_file(str(file_path)))
+ skipped = asyncio.run(toolkit.send_file(str(file_path)))
+
+ assert "跳过重复投递" in skipped
+ assert str(file_path) in skipped
+ assert "https://" not in skipped
+
+
def test_send_file_fails_when_send_push_delivers_zero(tmp_path, monkeypatch):
file_path = tmp_path / "report.pptx"
file_path.write_bytes(b"fake-pptx")
@@ -151,3 +263,21 @@ def test_send_file_succeeds_when_append_history_raises(tmp_path, monkeypatch):
assert new_paths == []
assert skipped == [str(file_path)]
assert mock_server.send_push.await_count == 1
+
+
+def test_all_missing_files_return_non_retryable_contract(tmp_path):
+ toolkit = SendFileToolkit(
+ request_id="r-missing",
+ session_id="sess-missing",
+ channel_id="web",
+ )
+ missing = tmp_path / "ai_chip_report.md"
+
+ result = asyncio.run(toolkit.send_file(str(missing)))
+
+ payload = json.loads(result)
+ assert payload["contract"] == "jiuwenswarm.non_retryable.v1"
+ assert payload["success"] is False
+ assert payload["retryable"] is False
+ assert payload["suggested_tool"] == "read_file"
+ assert "ai_chip_report.md" in payload["error"]