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: 防止空白Excel文件静默交付与bash工具链环境加固

zhouzhiming69c352e6c215f
diff --git a/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py b/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py
index 6a3ae456a0..1316c59375 100644
--- a/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py
+++ b/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py
@@ -296,6 +296,7 @@ JiuwenSwarm 使用独立的内部数据目录保存启动配置、Agent 身份
仅当确需整体替换、或无既有数据可保留时才整体覆盖。
要求设置/更新某字段时,确认已真正写入。
- **交付前自检**:交付前逐条核对全部条件是否满足、有无错纳漏纳、时间/数值/单位是否精确、既有数据是否完好、格式是否与模板一致;不过关先修正。
+- **工具结果优先**:若使用 read_file 检查过生成的文件,必须严格以工具实际返回的内容为准。若 read_file 只显示 `## Sheet1` 或只有空白默认表,即使你认为任务"应该"成功了,也必须如实判定构建失败并重新生成。切勿凭空推断文件内容。
## 输出文件放置规范
diff --git a/jiuwenswarm/agents/harness/common/tools/command_tools.py b/jiuwenswarm/agents/harness/common/tools/command_tools.py
index fb9c0d9343..51d8be61d0 100644
--- a/jiuwenswarm/agents/harness/common/tools/command_tools.py
+++ b/jiuwenswarm/agents/harness/common/tools/command_tools.py
@@ -8,6 +8,7 @@ import asyncio
import contextlib
import json
import locale
+import logging
import os
import re
import shlex
@@ -28,6 +29,8 @@ from openjiuwen.core.sys_operation.shell_process_registry import (
from jiuwenswarm.common.utils import get_agent_workspace_dir
+logger = logging.getLogger(__name__)
+
class CommandCancelled(Exception):
"""Raised when a blocking command is terminated by user interrupt."""
@@ -721,8 +724,199 @@ def _resolve_execution_plan(command: str, shell_type: str) -> tuple[list[str] |
raise RuntimeError(f"Unsupported shell_type: {normalized}")
+_WINDOWS_TOOL_DIRS: tuple[list[str], list[str]] | None = None
+"""Cached ``(trusted, workspace)`` tool-dir split from :func:`_discover_windows_tool_dirs`.
+
+``trusted`` (LOCALAPPDATA / Program Files) is prepended ahead of the system
+PATH so bundled python / officecli resolve. ``workspace`` (bounded ancestor
+walk from cwd) is appended after the system PATH so an agent-writable region
+cannot shadow system binaries via PATH-precedence tricks.
+"""
+
+
+_WORKSPACE_TOOL_DIR_BOUNDARY: int = 4
+"""Max ancestor levels to walk up from cwd when probing workspace-relative tool dirs.
+
+Bounds the agent-writable region so a workspace sub-tree cloned by an external
+source cannot plant a same-named ``office-claw-skills/common_binary/windows``
+dir and have it prepended ahead of the system PATH. Workspace-relative hits
+are :func:`_prepend_windows_tool_paths`-appended (lower priority) while
+trusted install locations (LOCALAPPDATA/Program Files) are still prepended.
+
+A workspace-relative hit is **only** adopted if the current user cannot write
+to it (verified via :func:`os.access` with ``os.W_OK``). User-writable
+ancestor dirs are skipped with a WARNING log so the operator can investigate
+why a workspace-relative install landed in an agent-controlled location.
+"""
+
+
+def _path_key(env: dict[str, str]) -> str:
+ """Return the canonical ``PATH`` key in *env*, falling back to ``"PATH"``.
+
+ On Windows the env-var name is case-insensitive but a plain ``dict`` is
+ case-sensitive, so a caller-supplied ``extra_env`` may have used
+ ``Path`` / ``path`` instead of ``PATH``. PATH writers should always read
+ and write through this helper to avoid losing the existing PATH value
+ (and silently shadowing it under a duplicate key).
+ """
+ for key in env:
+ if key.upper() == "PATH":
+ return key
+ return "PATH"
+
+
+def _discover_windows_tool_dirs() -> tuple[list[str], list[str]]:
+ """Discover tool dirs to merge into subprocess PATH (Windows only).
+
+ Returns a ``(trusted, workspace)`` tuple. ``trusted`` entries
+ (LOCALAPPDATA / Program Files) are prepended ahead of system PATH so
+ bundled python / officecli resolve. ``workspace`` entries (bounded
+ ancestor walk from cwd, see :data:`_WORKSPACE_TOOL_DIR_BOUNDARY`) are
+ appended after the existing PATH so an agent-writable region cannot
+ shadow system binaries. Each workspace hit is filtered through an
+ :func:`os.access` ``W_OK`` check so a user-writable ancestor cannot
+ poison the merged PATH; rejected entries are logged at WARNING with the
+ reason for operator visibility. Discovery runs once per process; the
+ cached split is applied to every subprocess env.
+ """
+ trusted: list[str] = []
+ workspace: list[str] = []
+ local_app_data = os.environ.get("LOCALAPPDATA")
+ program_files = os.environ.get("ProgramFiles")
+ program_files_root = (
+ os.path.join(local_app_data, "Programs") if local_app_data else None
+ )
+ for base in (program_files_root, program_files):
+ if not base or not os.path.isdir(base):
+ continue
+ for app in ("OfficeAce", "OfficeClaw"):
+ root = os.path.join(base, app)
+ if not os.path.isdir(root):
+ continue
+ bundled_py = os.path.join(root, "tools", "python")
+ if os.path.isdir(bundled_py):
+ trusted.append(bundled_py)
+ bin_dir = os.path.join(root, "office-claw-skills", "common_binary", "windows")
+ if os.path.isdir(bin_dir):
+ trusted.append(bin_dir)
+ try:
+ current = os.getcwd()
+ except OSError as exc:
+ logger.warning("[BashEnv] os.getcwd failed, skipping workspace walk: %s", exc)
+ current = None
+ depth = 0
+ while current and os.path.isdir(current) and depth < _WORKSPACE_TOOL_DIR_BOUNDARY:
+ bin_dir = os.path.join(current, "office-claw-skills", "common_binary", "windows")
+ if os.path.isdir(bin_dir):
+ if os.access(bin_dir, os.W_OK):
+ logger.warning(
+ "[BashEnv] workspace tool dir is user-writable, "
+ "skipping to avoid PATH poisoning: %s (cwd=%s)",
+ bin_dir,
+ current,
+ )
+ else:
+ workspace.append(bin_dir)
+ parent = os.path.dirname(current)
+ if parent == current:
+ break
+ current = parent
+ depth += 1
+ office_cli = (
+ os.path.join(local_app_data, "OfficeCLI") if local_app_data else None
+ )
+ if office_cli and os.path.isdir(office_cli):
+ trusted.append(office_cli)
+ return trusted, workspace
+
+
+def _prepend_windows_tool_paths(env: dict[str, str]) -> None:
+ """Merge known tool directories into ``PATH`` in *env* (Windows only).
+
+ Trusted install locations (LOCALAPPDATA / Program Files) are prepended
+ ahead of the existing PATH so bundled python / officecli resolve even
+ when the agent process PATH is incomplete. Workspace-relative hits from
+ :func:`_discover_windows_tool_dirs` (bounded ancestor walk from cwd) are
+ appended *after* the existing PATH so an agent-writable region cannot
+ shadow system binaries via PATH-precedence tricks. Both lists are deduped
+ against the current PATH. Discovery runs once per process; the cached
+ list is applied on every call so each fresh subprocess env still gets
+ the hardened PATH.
+ """
+ global _WINDOWS_TOOL_DIRS
+ if _WINDOWS_TOOL_DIRS is None:
+ _WINDOWS_TOOL_DIRS = _discover_windows_tool_dirs()
+ trusted, workspace = _WINDOWS_TOOL_DIRS
+ if not trusted and not workspace:
+ return
+
+ path_key = _path_key(env)
+ existing = set(p.lower() for p in env.get(path_key, "").split(os.pathsep))
+ trusted_entries: list[str] = []
+ for d in trusted:
+ normalized = os.path.normcase(os.path.normpath(d))
+ if normalized.lower() not in existing:
+ trusted_entries.append(d)
+ existing.add(normalized.lower())
+ workspace_entries: list[str] = []
+ for d in workspace:
+ normalized = os.path.normcase(os.path.normpath(d))
+ if normalized.lower() not in existing:
+ workspace_entries.append(d)
+ existing.add(normalized.lower())
+ if not trusted_entries and not workspace_entries:
+ return
+
+ current_path = env.get(path_key, "")
+ new_path = current_path
+ if trusted_entries:
+ new_path = os.pathsep.join(trusted_entries) + (os.pathsep + new_path if new_path else "")
+ if workspace_entries:
+ new_path = new_path + (os.pathsep + os.pathsep.join(workspace_entries) if new_path else os.pathsep.join(workspace_entries))
+ env[path_key] = new_path
+ logger.info(
+ "[BashEnv] merged %d trusted + %d workspace tool dirs into subprocess PATH: trusted=%s workspace=%s",
+ len(trusted_entries),
+ len(workspace_entries),
+ trusted_entries,
+ workspace_entries,
+ )
+
+
+def _windows_not_found_hint(command: str, stderr: str, exit_code: int) -> str | None:
+ """Return a diagnostic hint when a Windows subprocess could not find a command."""
+ if os.name != "nt":
+ return None
+ if exit_code == 9009:
+ pass # fall through
+ elif not any(marker in stderr.lower() for marker in ("not recognized", "不是内部或外部命令", "不是可识别的")):
+ return None
+ cmd_name = command.split(None, 1)[0] if command else ""
+ if not cmd_name:
+ return None
+ return (
+ f"\n[Diagnostic] 命令「{cmd_name}」未在子进程 PATH 中找到"
+ f"(exit={exit_code})。"
+ f"已尝试自动探测并添加常见工具目录(OfficeAce 捆绑 python、"
+ f"Python 安装目录、skill 二进制目录等),但仍未找到。"
+ f"可尝试使用完整路径执行:"
+ f"如 C:\\Users\\<用户名>\\AppData\\Local\\Programs\\OfficeAce\\tools\\python\\python.exe"
+ )
+
+
def _build_subprocess_env(extra_env: dict[str, str] | None) -> dict[str, str] | None:
- """Merge skill-injected env vars into a copy of os.environ."""
+ """Merge skill-injected env vars into a copy of os.environ.
+
+ On Windows, also prepend common tool directories to subprocess PATH
+ to mitigate PATH inconsistencies between the agent process and the
+ spawned shell (python, officecli, etc.).
+ """
+ if os.name == "nt":
+ merged = dict(os.environ)
+ _prepend_windows_tool_paths(merged)
+ if extra_env:
+ merged.update(extra_env)
+ return merged
if not extra_env:
return None
merged = dict(os.environ)
@@ -1054,6 +1248,13 @@ async def mcp_exec_command(
except Exception as exc:
return f"[ERROR]: command execution failed: {exc}"
+ hint = _windows_not_found_hint(command, result.stderr or "", result.returncode)
+ hint_text = hint or ""
+ if max_output_chars <= 0:
+ stderr_text = (result.stderr or "") + hint_text
+ else:
+ base_budget = max(0, max_output_chars - len(hint_text))
+ stderr_text = _clip_text(result.stderr or "", base_budget) + hint_text
payload = {
"command": command,
"cwd": str(resolved_workdir),
@@ -1061,7 +1262,7 @@ async def mcp_exec_command(
"resolved_shell": resolved_shell,
"exit_code": result.returncode,
"stdout": _clip_text(result.stdout or "", max_output_chars),
- "stderr": _clip_text(result.stderr or "", max_output_chars),
+ "stderr": stderr_text,
}
return json.dumps(payload, ensure_ascii=False, indent=2)
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 7b4cf2bbe6..9739a4434b 100644
--- a/jiuwenswarm/agents/harness/common/tools/send_file_to_user.py
+++ b/jiuwenswarm/agents/harness/common/tools/send_file_to_user.py
@@ -78,6 +78,38 @@ def _normalize_sent_file_path(path: str) -> str:
return os.path.abspath(path).replace("\\", "/").lower()
+_MIN_XLSX_BYTES = 6000
+
+
+def _xlsx_size_warning(file_path: str) -> str | None:
+ """Return a warning string for suspiciously small workbook files, else None.
+
+ 仅供提醒,不拦截发送:极小工作簿可能是合法产物,也可能来自构建工具链
+ 失败后生成的空白文件(仅含默认空 Sheet1)。
+ """
+ ext = os.path.splitext(file_path)[1].lower()
+ if ext not in (".xlsx", ".xlsm"):
+ return None
+ try:
+ size = os.path.getsize(file_path)
+ except OSError:
+ return None
+ if size < _MIN_XLSX_BYTES:
+ return (
+ f"⚠️ 文件「{os.path.basename(file_path)}」大小仅为 {size} 字节"
+ f"(低于建议阈值 {_MIN_XLSX_BYTES} 字节),"
+ "可能为空白或未正确渲染的工作簿。建议先用 read_file 确认内容,"
+ "若只有空白默认 Sheet1 则说明生成失败,应重新生成后再发送。"
+ )
+ return None
+
+
+def _append_size_warnings(result: str, size_warnings: list[str]) -> str:
+ if result and size_warnings:
+ return result + "\n" + "\n".join(size_warnings)
+ return result
+
+
def _partition_sent_files(
session_id: str,
paths: list[str],
@@ -279,12 +311,17 @@ class SendFileToolkit:
valid_files = []
missing_files = []
+ size_warnings: list[str] = []
for fp in abs_file_path_list:
fp = str(fp).strip()
if not fp:
continue
if os.path.isfile(fp):
valid_files.append(fp)
+ hint = _xlsx_size_warning(fp)
+ if hint:
+ size_warnings.append(hint)
+ logger.warning("[SendFileToolkit] 疑似空白工作簿: %s", fp)
else:
missing_files.append(fp)
logger.warning("[SendFileToolkit] 文件不存在: %s", fp)
@@ -335,24 +372,26 @@ class SendFileToolkit:
# 企业默认:OBS URL 经当前 chat SSE(不依赖 PushRegistry)。
# 个人版不进此分支,保持本机 path + send_push / 显式 file_transfer。
if self._should_use_obs_download():
- return await self._send_file_via_obs(
+ result = await self._send_file_via_obs(
valid_files,
missing_files,
skipped_files,
route,
target_channel_list,
)
+ return _append_size_warnings(result, size_warnings)
from jiuwenswarm.common.file_transfer_config import get_file_transfer_config
if get_file_transfer_config().enabled:
- return await self._send_file_distributed(
+ result = await self._send_file_distributed(
valid_files,
missing_files,
skipped_files,
route,
target_channel_list,
)
+ return _append_size_warnings(result, size_warnings)
try:
from jiuwenswarm.server.agent_ws_server import AgentWebSocketServer
@@ -461,6 +500,7 @@ class SendFileToolkit:
result_parts.append("以下文件不存在,未发送:")
for mf in missing_files:
result_parts.append(f" - {mf}")
+ result_parts.extend(size_warnings)
return "\n".join(result_parts)
except Exception as e:
logger.exception(
@@ -498,7 +538,6 @@ class SendFileToolkit:
load_minio_upload_config,
upload_local_file_to_minio,
)
-
from jiuwenswarm.common.audit_emit import emit_audit_evt, emit_audit_ua
session = get_subagent_parent_session()
diff --git a/jiuwenswarm/agents/harness/flash/rails/slim_sys_operation_rail.py b/jiuwenswarm/agents/harness/flash/rails/slim_sys_operation_rail.py
index a909aa8410..3e22c6360a 100644
--- a/jiuwenswarm/agents/harness/flash/rails/slim_sys_operation_rail.py
+++ b/jiuwenswarm/agents/harness/flash/rails/slim_sys_operation_rail.py
@@ -28,7 +28,6 @@ class SlimSysOperationRail(SysOperationRail):
from openjiuwen.harness.rails._multimodal import (
should_enable_read_image_multimodal,
)
- from openjiuwen.harness.tools import BashTool
from openjiuwen.harness.tools.code import CodeTool
from openjiuwen.harness.tools.filesystem import (
EditFileTool,
@@ -36,6 +35,7 @@ class SlimSysOperationRail(SysOperationRail):
WriteFileTool,
)
+ from ..tools.flash_bash_tool import FlashBashTool
from ..tools.flash_glob_tool import FlashGlobTool
from ..tools.flash_read_tool import FlashReadFileTool
@@ -55,7 +55,7 @@ class SlimSysOperationRail(SysOperationRail):
edit_tool = EditFileTool(self.sys_operation, lang, agent_id)
glob_tool = FlashGlobTool(self.sys_operation, lang, agent_id)
grep_tool = GrepTool(self.sys_operation, lang, agent_id)
- bash_tool = BashTool(
+ bash_tool = FlashBashTool(
self.sys_operation,
lang,
agent_id=agent_id,
diff --git a/jiuwenswarm/agents/harness/flash/tools/flash_bash_tool.py b/jiuwenswarm/agents/harness/flash/tools/flash_bash_tool.py
new file mode 100644
index 0000000000..67fea8604e
--- /dev/null
+++ b/jiuwenswarm/agents/harness/flash/tools/flash_bash_tool.py
@@ -0,0 +1,159 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""FlashBashTool: stock BashTool with Windows PATH hardening + not-found hint.
+
+Used by ``SlimSysOperationRail`` and ``FlashBashSysOperationRail`` in place of
+the stock ``BashTool``. On Windows, if the caller passes no explicit
+``environment``/``env``, the subprocess PATH is hardened with common tool dirs
+(bundled python, officecli) so ``python`` / ``officecli`` resolve even when the
+agent process PATH is incomplete; a ``[Diagnostic]`` hint is appended when the
+command was not found. All other stock semantics are preserved unchanged.
+"""
+
+from __future__ import annotations
+
+import os
+from typing import Any, AsyncIterator, Dict
+
+from openjiuwen.harness.rails.sys_operation_rail import SysOperationRail
+from openjiuwen.harness.tools.base_tool import ToolOutput
+from openjiuwen.harness.tools.shell.bash._tool import BashTool
+
+from jiuwenswarm.agents.harness.common.tools.command_tools import (
+ _build_subprocess_env,
+ _windows_not_found_hint,
+)
+
+
+class FlashBashTool(BashTool):
+ """Stock BashTool plus Windows PATH hardening and command-not-found hints."""
+
+ @staticmethod
+ def _hardened_inputs(inputs: Dict[str, Any]) -> Dict[str, Any]:
+ """Return a copy of *inputs* with hardened env on Windows.
+
+ Only injects when the caller did not provide an explicit environment,
+ so skill-injected env vars (e.g. a deliberately full PATH) still win.
+ """
+ if os.name != "nt":
+ return inputs
+ if inputs.get("environment") or inputs.get("env"):
+ return inputs
+ merged = _build_subprocess_env(None)
+ if not merged:
+ return inputs
+ new_inputs = dict(inputs)
+ new_inputs["environment"] = merged
+ return new_inputs
+
+ @staticmethod
+ def _annotate_not_found(inputs: Dict[str, Any], output: ToolOutput) -> ToolOutput:
+ """Append a not-found diagnostic hint to a failed rendered output."""
+ if output is None or output.success:
+ return output
+ data = output.data
+ if not data or not isinstance(data, dict):
+ return output
+ content = data.get("content")
+ if not isinstance(content, str):
+ return output
+ command = str((inputs or {}).get("command") or "")
+ hint = _windows_not_found_hint(command, content, 1)
+ if not hint:
+ return output
+ new_content = content + hint
+ new_data = dict(data)
+ new_data["content"] = new_content
+ return ToolOutput(
+ success=output.success,
+ data=new_data,
+ error=new_content if output.error else output.error,
+ )
+
+ @staticmethod
+ def _annotate_final_chunk(
+ inputs: Dict[str, Any], chunk: ToolOutput
+ ) -> ToolOutput:
+ """Inject the not-found hint into a stream-path final ``content`` chunk.
+
+ The stock ``BashTool.stream`` final chunk carries the fully rendered
+ tool content in ``data["content"]``; we mirror ``_annotate_not_found``
+ so the hint also lands in stream callers (FlashReadFileTool already
+ proves the stream path is reachable).
+ """
+ return FlashBashTool._annotate_not_found(inputs, chunk)
+
+ async def invoke(self, inputs: Dict[str, Any], **kwargs: Any) -> ToolOutput:
+ hardened = self._hardened_inputs(inputs)
+ result = await super().invoke(hardened, **kwargs)
+ return self._annotate_not_found(hardened, result)
+
+ async def stream(
+ self, inputs: Dict[str, Any], **kwargs: Any
+ ) -> AsyncIterator[ToolOutput]:
+ """Stream variant that also hardens PATH and annotates the final chunk."""
+ hardened = self._hardened_inputs(inputs)
+ final_chunk = None
+ async for chunk in super().stream(hardened, **kwargs):
+ if (
+ chunk is not None
+ and chunk.data
+ and isinstance(chunk.data, dict)
+ and isinstance(chunk.data.get("content"), str)
+ and not chunk.data.get("text")
+ ):
+ final_chunk = chunk
+ continue
+ yield chunk
+ if final_chunk is not None:
+ yield self._annotate_final_chunk(hardened, final_chunk)
+
+
+class FlashBashSysOperationRail(SysOperationRail):
+ """Stock SysOperationRail with bash swapped to FlashBashTool.
+
+ The init body delegates to :meth:`SysOperationRail.init` and only swaps
+ the bash tool afterwards. This avoids copying the parent's ~50 lines of
+ tool assembly so upstream additions to ``SysOperationRail.init`` propagate
+ to this rail automatically; a guard test (``test_rails_alignment``)
+ asserts the toolset shape stays in sync so silently drifting assemblies
+ surface as test failures rather than runtime divergence.
+ """
+
+ def init(self, agent) -> None:
+ super().init(agent)
+ if self.tools is None:
+ return
+ from openjiuwen.harness.tools.filesystem import ReadFileTool
+ from jiuwenswarm.agents.harness.flash.tools.flash_read_tool import (
+ FlashReadFileTool,
+ )
+
+ lang = agent.system_prompt_builder.language
+ agent_id = getattr(getattr(agent, "card", None), "id", None)
+ swap_targets: list[tuple[int, Any]] = []
+ for idx, tool in enumerate(self.tools):
+ if isinstance(tool, BashTool) and not isinstance(tool, FlashBashTool):
+ swap_targets.append(
+ (
+ idx,
+ FlashBashTool(
+ self.sys_operation,
+ lang,
+ agent_id=agent_id,
+ deny_patterns=self._bash_deny_patterns,
+ ),
+ )
+ )
+ elif isinstance(tool, ReadFileTool) and not isinstance(
+ tool, FlashReadFileTool
+ ):
+ swap_targets.append(
+ (idx, FlashReadFileTool(self.sys_operation, lang, agent_id))
+ )
+ for idx, replacement in swap_targets:
+ self.tools[idx] = replacement
+ agent.ability_manager.add_ability(replacement.card, replacement)
+
+
+__all__ = ["FlashBashTool", "FlashBashSysOperationRail"]
diff --git a/jiuwenswarm/agents/harness/flash/tools/flash_read_tool.py b/jiuwenswarm/agents/harness/flash/tools/flash_read_tool.py
index a9f4022cce..d18dee3f61 100644
--- a/jiuwenswarm/agents/harness/flash/tools/flash_read_tool.py
+++ b/jiuwenswarm/agents/harness/flash/tools/flash_read_tool.py
@@ -24,6 +24,7 @@ from __future__ import annotations
import asyncio
import logging
import os
+import re
from typing import Any, Dict, List, Optional
from openjiuwen.harness.tools.base_tool import ToolOutput
@@ -207,6 +208,8 @@ class FlashReadFileTool(ReadFileTool):
file_type = "image"
elif self._is_office_doc(file_path):
rendered = await self._read_office_doc(file_path)
+ if file_path.lower().endswith(".xlsx"):
+ rendered = self._annotate_empty_xlsx(rendered)
file_type = "office"
else:
rendered = await self._read_text(
@@ -264,6 +267,43 @@ class FlashReadFileTool(ReadFileTool):
"error": error,
}
+ @staticmethod
+ def _annotate_empty_xlsx(rendered: str | dict) -> str | dict:
+ """Prepend a warning banner if xlsx output has only empty default sheet.
+
+ The _read_office_doc / _read_xlsx_text renderer outputs one ``## SheetName``
+ header per worksheet plus markdown table rows for data, with line-number
+ prefixes (`` 1\\t``). When no data rows exist and only one sheet header
+ (``## Sheet1``) appears, the workbook is effectively empty — inject a
+ visible banner so the model cannot ignore it.
+ """
+ content = rendered.get("content", "") if isinstance(rendered, dict) else str(rendered)
+ stripped = content.strip()
+ if not stripped:
+ return rendered
+ # Strip line-number prefix (" 1\t...") used by the renderer's _cat_n.
+ _prefix_re = re.compile(r"^\s*\d+\t", re.M)
+ stripped = _prefix_re.sub("", stripped)
+ # Detect: exactly one sheet header, zero data rows
+ header_count = 0
+ data_lines = 0
+ for line in stripped.splitlines():
+ line_stripped = line.strip()
+ if line_stripped.startswith("## "):
+ header_count += 1
+ elif line_stripped.startswith("|"):
+ data_lines += 1
+ if header_count <= 1 and data_lines == 0:
+ banner = (
+ "⚠️ [WARNING] 该工作簿内容为空(仅含默认空白 Sheet1),不含任何数据。"
+ "请重新检查构建环节是否正确。\n\n"
+ )
+ if isinstance(rendered, dict):
+ rendered["content"] = banner + content
+ return rendered
+ return banner + content
+ return rendered
+
# ------------------------------------------------------------------
# Multi-file parallel reader
# ------------------------------------------------------------------
@@ -340,7 +380,37 @@ class FlashReadFileTool(ReadFileTool):
model_name = self._resolve_model_name(kwargs)
return await self._invoke_multi(paths, model_name)
- return await super().invoke(inputs, **kwargs)
+ result = await super().invoke(inputs, **kwargs)
+ return self._annotate_single_xlsx(inputs, result)
+
+ def _annotate_single_xlsx(
+ self, inputs: Dict[str, Any], result: ToolOutput
+ ) -> ToolOutput:
+ """Apply the empty-xlsx banner on the single-file path too.
+
+ Single-file reads go through stock ``ReadFileTool.invoke`` directly,
+ bypassing ``_read_one_file``; without this the banner never shows for
+ the most common ``read_file(file_path=...)`` form.
+ """
+ file_path = str(inputs.get("file_path") or "")
+ if not file_path.lower().endswith(".xlsx"):
+ return result
+ if result is None or not isinstance(result.data, dict):
+ return result
+ content = result.data.get("content")
+ if not isinstance(content, str):
+ return result
+ annotated = self._annotate_empty_xlsx({"content": content})
+ new_content = annotated.get("content") if isinstance(annotated, dict) else None
+ if new_content is None or new_content == content:
+ return result
+ new_data = dict(result.data)
+ new_data["content"] = new_content
+ return ToolOutput(
+ success=result.success,
+ data=new_data,
+ error=result.error,
+ )
async def stream(self, inputs: Dict[str, Any], **kwargs) -> Any:
# 与 UnifiedTodoTool 同约定:flash 工具不走增量流式,整包一次性产出。
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index 4051adf2de..d5b590bf46 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -7594,13 +7594,41 @@ class JiuWenSwarmDeepAdapter:
@staticmethod
def _build_filesystem_rail() -> SysOperationRail | None:
- """Build SysOperationRail."""
+ """Build SysOperationRail (bash swapped to FlashBashTool for PATH hardening).
+
+ If the flash tools package (or its openjiuwen dependency chain) fails
+ to import, fall back to the stock ``SysOperationRail`` so the agent
+ still gets a working filesystem/shell toolset instead of ``None``.
+ Only returns ``None`` when *both* the flash override and the stock
+ rail fail to construct.
+ """
+ fs_rail: SysOperationRail | None = None
try:
- fs_rail = SysOperationRail()
+ from jiuwenswarm.agents.harness.flash.tools.flash_bash_tool import (
+ FlashBashSysOperationRail,
+ )
+
+ fs_rail = FlashBashSysOperationRail()
logger.info("[JiuWenSwarmDeepAdapter] SysOperationRail create success")
except Exception as exc:
- logger.warning("[JiuWenSwarmDeepAdapter] SysOperationRail create failed: %s", exc)
- fs_rail = None
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] flash rail unavailable, "
+ "falling back to stock SysOperationRail: %s",
+ exc,
+ )
+ try:
+ fs_rail = SysOperationRail()
+ logger.info(
+ "[JiuWenSwarmDeepAdapter] stock SysOperationRail fallback "
+ "create success"
+ )
+ except Exception as fallback_exc:
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] stock SysOperationRail "
+ "fallback also failed: %s",
+ fallback_exc,
+ )
+ fs_rail = None
return fs_rail
@staticmethod
diff --git a/tests/unit_tests/gateway/test_cron_scheduler_active.py b/tests/unit_tests/gateway/test_cron_scheduler_active.py
index 01ea089d21..540a0d4d34 100644
--- a/tests/unit_tests/gateway/test_cron_scheduler_active.py
+++ b/tests/unit_tests/gateway/test_cron_scheduler_active.py
@@ -167,7 +167,7 @@ async def test_promotion_reloads_and_executes_jobs(tmp_path) -> None:
await scheduler.start()
try:
# 模拟另一个 PRIMARY 在本实例处于 STANDBY 期间写入 store
- run_at = datetime.now(tz=ZoneInfo("UTC")) + timedelta(seconds=1)
+ run_at = datetime.now(tz=ZoneInfo("UTC")) + timedelta(seconds=5)
await store.create_job(
name="t",
cron_expr=_one_shot_cron_expr(run_at),
@@ -181,7 +181,7 @@ async def test_promotion_reloads_and_executes_jobs(tmp_path) -> None:
await scheduler.reload()
scheduler.set_active(True)
- await asyncio.wait_for(agent_client.started.wait(), timeout=3.0)
+ await asyncio.wait_for(agent_client.started.wait(), timeout=10.0)
assert len(agent_client.calls) >= 1
finally:
await scheduler.stop()
diff --git a/tests/unit_tests/harness/test_empty_output_guard.py b/tests/unit_tests/harness/test_empty_output_guard.py
new file mode 100644
index 0000000000..11f7173457
--- /dev/null
+++ b/tests/unit_tests/harness/test_empty_output_guard.py
@@ -0,0 +1,908 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Regression tests for the empty-output / bash-env hardening changes.
+
+Covers four new pieces of logic introduced by the
+``fix/office-empty-output-guard-ee`` branch:
+
+* :func:`jiuwenswarm.agents.harness.flash.tools.flash_read_tool.
+ FlashReadFileTool._annotate_empty_xlsx` — empty-xlsx banner.
+* :func:`jiuwenswarm.agents.harness.common.tools.send_file_to_user.
+ _xlsx_size_warning` / :func:`_append_size_warnings` — small-xlsx hint.
+* :func:`jiuwenswarm.agents.harness.common.tools.command_tools.
+ _discover_windows_tool_dirs` and :func:`_prepend_windows_tool_paths` —
+ trusted-vs-workspace PATH split (security boundary).
+* :func:`jiuwenswarm.agents.harness.common.tools.command_tools.
+ _windows_not_found_hint` — diagnostic hint trigger conditions.
+
+These tests run cross-platform; on non-Windows hosts the PATH-hardening
+tests assert the discovery split and the dedup/no-op semantics without
+depending on real OfficeAce installs.
+"""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+from typing import Any
+from unittest.mock import patch
+
+import pytest
+
+from jiuwenswarm.agents.harness.common.tools import command_tools as ct
+from jiuwenswarm.agents.harness.common.tools import send_file_to_user as sfu
+from jiuwenswarm.agents.harness.flash.tools.flash_read_tool import (
+ FlashReadFileTool,
+)
+
+
+# ---------------------------------------------------------------------------
+# 1) _annotate_empty_xlsx banner detection
+# ---------------------------------------------------------------------------
+
+
+ "rendered, expect_banner",
+ [
+ # Exactly one sheet header + zero data rows → banner injected.
+ (
+ "## Sheet1\n",
+ True,
+ ),
+ # Line-number prefix must be stripped before counting.
+ (
+ " 1\t## Sheet1\n",
+ True,
+ ),
+ # Data rows present → no banner.
+ (
+ "## Sheet1\n"
+ " 2\t| col |\n"
+ " 3\t| --- |\n"
+ " 4\t| a |\n",
+ False,
+ ),
+ # Multiple sheet headers → not "only default sheet", no banner.
+ (
+ "## Sheet1\n## Sheet2\n",
+ False,
+ ),
+ # Empty content → no banner.
+ ("", False),
+ # Whitespace only → no banner.
+ (" \n\n", False),
+ # Dict form: same rules apply, content key is annotated.
+ (
+ {"content": "## Sheet1\n", "line_count": 1},
+ True,
+ ),
+ (
+ {"content": "## Sheet1\n| a |\n", "line_count": 2},
+ False,
+ ),
+ ],
+)
+def test_annotate_empty_xlsx_banner(
+ rendered: Any, expect_banner: bool
+) -> None:
+ result = FlashReadFileTool._annotate_empty_xlsx(rendered)
+ if expect_banner:
+ if isinstance(rendered, dict):
+ assert isinstance(result, dict)
+ content = result["content"]
+ else:
+ content = result
+ assert "⚠️" in content
+ assert "该工作簿内容为空" in content
+ else:
+ if isinstance(rendered, dict):
+ assert result == rendered or result["content"] == rendered["content"]
+ else:
+ assert result == rendered
+
+
+def test_annotate_single_xlsx_skips_non_xlsx() -> None:
+ """Single-file annotation is gated by .xlsx suffix only."""
+ from openjiuwen.harness.tools.base_tool import ToolOutput
+
+ tool = FlashReadFileTool.__new__(FlashReadFileTool)
+ result = ToolOutput(success=True, data={"content": "## Sheet1\n"})
+ out = tool._annotate_single_xlsx({"file_path": "/tmp/note.txt"}, result)
+ assert out is result
+
+
+def test_annotate_single_xlsx_passes_through_when_not_dict() -> None:
+ """Non-dict data shapes (multimodal streams) are left untouched."""
+ from openjiuwen.harness.tools.base_tool import ToolOutput
+
+ tool = FlashReadFileTool.__new__(FlashReadFileTool)
+ result = ToolOutput(success=True, data=["not", "a", "dict"])
+ out = tool._annotate_single_xlsx({"file_path": "/tmp/book.xlsx"}, result)
+ assert out is result
+
+
+# ---------------------------------------------------------------------------
+# 2) _xlsx_size_warning / _append_size_warnings
+# ---------------------------------------------------------------------------
+
+
+ "size, ext, expect_warning",
+ [
+ (5_500, ".xlsx", True),
+ (5_999, ".xlsm", True),
+ (6_000, ".xlsx", False),
+ (10_000, ".xlsx", False),
+ (1_000, ".csv", False),
+ (1_000, ".docx", False),
+ ],
+)
+def test_xlsx_size_warning_thresholds(
+ tmp_path: Path, size: int, ext: str, expect_warning: bool
+) -> None:
+ path = tmp_path / f"book{ext}"
+ path.write_bytes(b"\x00" * size)
+ warning = sfu._xlsx_size_warning(str(path))
+ if expect_warning:
+ assert warning is not None
+ assert "⚠️" in warning
+ assert str(size) in warning
+ else:
+ assert warning is None
+
+
+def test_xlsx_size_warning_returns_none_on_missing_file() -> None:
+ assert sfu._xlsx_size_warning("/nonexistent/never/created.xlsx") is None
+
+
+def test_append_size_warnings_appends_each() -> None:
+ result = sfu._append_size_warnings(
+ "base result",
+ ["warning 1", "warning 2"],
+ )
+ assert result.startswith("base result\n")
+ assert "warning 1" in result
+ assert "warning 2" in result
+
+
+def test_append_size_warnings_no_op_when_empty() -> None:
+ assert sfu._append_size_warnings("base", []) == "base"
+ # Implementation contract: empty result stays empty (we never inject
+ # warnings without a base to anchor them).
+ assert sfu._append_size_warnings("", ["warn"]) == ""
+
+
+# ---------------------------------------------------------------------------
+# 3) _discover_windows_tool_dirs / _prepend_windows_tool_paths
+# ---------------------------------------------------------------------------
+
+
+def _fresh_discover() -> tuple[list[str], list[str]]:
+ """Reset the cached discovery so each test exercises discovery afresh.
+
+ Kept for callers that prefer an explicit reset; the
+ ``_reset_windows_tool_dirs_cache`` autouse fixture already invalidates
+ the cache between tests.
+ """
+ ct._WINDOWS_TOOL_DIRS = None
+ return ct._discover_windows_tool_dirs()
+
+
+def fake_officeace_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """Plant a fake OfficeAce install under Program Files."""
+ prog = tmp_path / "Program Files"
+ officeace = prog / "OfficeAce"
+ bin_dir = officeace / "office-claw-skills" / "common_binary" / "windows"
+ bin_dir.mkdir(parents=True)
+ (officeace / "tools" / "python").mkdir(parents=True)
+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path))
+ monkeypatch.setenv("ProgramFiles", str(prog))
+ return officeace
+
+
+def readonly_dir(tmp_path: Path) -> Path:
+ """Create a sub-tree and mark it read-only for the current user.
+
+ :func:`os.access(..., os.W_OK)` returns ``False`` once read-only perms
+ are set; this is the same check :func:`_discover_windows_tool_dirs`
+ uses to gate workspace-relative PATH additions.
+ """
+ readonly_root = tmp_path / "readonly_workspace"
+ readonly_root.mkdir(parents=True, exist_ok=True)
+ try:
+ os.chmod(readonly_root, 0o555)
+ except (PermissionError, OSError):
+ pass
+ return readonly_root
+
+
+def writable_workspace_skill(tmp_path: Path) -> Path:
+ """Create a user-writable office-claw-skills subtree to test poisoning."""
+ workspace_skill = (
+ tmp_path / "office-claw-skills" / "common_binary" / "windows"
+ )
+ workspace_skill.mkdir(parents=True)
+ return workspace_skill
+
+
[email protected](autouse=True)
+def _reset_windows_tool_dirs_cache() -> None:
+ """Each test starts with a clean discovery cache."""
+ ct._WINDOWS_TOOL_DIRS = None
+ yield
+ ct._WINDOWS_TOOL_DIRS = None
+
+
+def test_discover_trusted_dirs_came_from_officeace_root(
+ fake_officeace_root: Path,
+) -> None:
+ trusted, _ = ct._discover_windows_tool_dirs()
+ assert any(str(fake_officeace_root) in d for d in trusted), trusted
+
+
+def _force_readonly(path: Path) -> None:
+ """Patch :func:`os.access` to claim *path* is read-only.
+
+ On Windows even ``chmod 0o555`` does not always flip
+ :func:`os.access(..., os.W_OK)` to ``False`` (administrators bypass ACLs);
+ a targeted ``os.access`` mock gives the test a deterministic answer.
+ """
+ real_access = os.access
+
+ def _patched(p: Any, mode: int) -> bool:
+ try:
+ if Path(p).resolve() == Path(path).resolve():
+ if mode == os.W_OK:
+ return False
+ if mode == os.R_OK:
+ return True
+ except (OSError, ValueError):
+ pass
+ return real_access(p, mode)
+
+ return _patched
+
+
+def test_discover_workspace_dirs_are_bounded(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Workspace hit at depth 4 picked up; depth 6 (out of boundary) ignored."""
+ chain = [tmp_path]
+ for _ in range(6):
+ chain.append(chain[-1] / "child")
+ chain[-1].mkdir()
+ target = chain[4] / "office-claw-skills" / "common_binary" / "windows"
+ target.mkdir(parents=True)
+ try:
+ os.chmod(target, 0o555)
+ except (PermissionError, OSError):
+ pass
+ monkeypatch.setattr(
+ "os.access", _force_readonly(target)
+ )
+ with patch("os.getcwd", return_value=str(chain[-1])):
+ _, workspace = ct._discover_windows_tool_dirs()
+ assert any("child" in d for d in workspace), workspace
+ assert not any(str(chain[6]) in d for d in workspace), workspace
+
+
+def test_discover_skips_user_writable_workspace_dir(
+ writable_workspace_skill: Path,
+) -> None:
+ """Workspace hit that the current user can write to must be skipped."""
+ with patch("os.getcwd", return_value=str(writable_workspace_skill.parent.parent)):
+ _, workspace = ct._discover_windows_tool_dirs()
+ assert str(writable_workspace_skill) not in workspace, workspace
+
+
+def test_prepend_does_not_prepend_workspace_paths(
+ fake_officeace_root: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Workspace hits must be appended, not prepended, ahead of system PATH."""
+ workspace_skill = (
+ fake_officeace_root.parent / "readonly_workspace"
+ / "office-claw-skills" / "common_binary" / "windows"
+ )
+ workspace_skill.mkdir(parents=True, exist_ok=True)
+ try:
+ os.chmod(workspace_skill, 0o555)
+ except (PermissionError, OSError):
+ pass
+ monkeypatch.setattr(
+ "os.access", _force_readonly(workspace_skill)
+ )
+ system_dirs = ["C:\\system1", "C:\\system2"]
+ initial_path = os.pathsep.join(system_dirs)
+ with patch("os.getcwd", return_value=str(workspace_skill.parent.parent.parent)):
+ env = {"PATH": initial_path}
+ ct._prepend_windows_tool_paths(env)
+ parts = env["PATH"].split(os.pathsep)
+ trusted_indices = [
+ i for i, p in enumerate(parts) if str(fake_officeace_root) in p
+ ]
+ assert trusted_indices, parts
+ for d in system_dirs:
+ assert d in parts
+ workspace_indices = [
+ i for i, p in enumerate(parts) if str(workspace_skill) in p
+ ]
+ assert workspace_indices, parts
+ system_max_idx = max(parts.index(d) for d in system_dirs)
+ assert min(workspace_indices) > system_max_idx, parts
+ assert min(trusted_indices) < system_max_idx, parts
+
+
+def test_prepend_drops_user_writable_workspace_entirely(
+ writable_workspace_skill: Path,
+) -> None:
+ """User-writable workspace hits must not appear in the merged PATH at all."""
+ with patch("os.getcwd", return_value=str(writable_workspace_skill.parent.parent)):
+ env = {"PATH": "C:\\system1"}
+ ct._prepend_windows_tool_paths(env)
+ parts = env["PATH"].split(os.pathsep)
+ assert str(writable_workspace_skill) not in parts, parts
+
+
+def test_prepend_is_deduped(fake_officeace_root: Path) -> None:
+ """Calling the helper twice must not duplicate entries."""
+ with patch.dict(os.environ, {}, clear=False):
+ env = {"PATH": "/usr/bin"}
+ ct._WINDOWS_TOOL_DIRS = None
+ ct._prepend_windows_tool_paths(env)
+ first = env["PATH"]
+ ct._prepend_windows_tool_paths(env)
+ second = env["PATH"]
+ assert first == second
+
+
+def test_prepend_is_noop_without_tool_dirs(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """If no trusted or workspace dirs exist, PATH is left untouched."""
+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path))
+ monkeypatch.setenv("ProgramFiles", str(tmp_path / "Program Files"))
+ monkeypatch.delenv("ProgramFiles", raising=False)
+ with patch("os.getcwd", return_value=str(tmp_path)):
+ ct._WINDOWS_TOOL_DIRS = None
+ env = {"PATH": "/usr/bin"}
+ ct._prepend_windows_tool_paths(env)
+ assert env["PATH"] == "/usr/bin"
+
+
+# ---------------------------------------------------------------------------
+# 4) _windows_not_found_hint
+# ---------------------------------------------------------------------------
+
+
+ "stderr, exit_code, expect_hint",
+ [
+ ("python : The term 'python' is not recognized", 1, True),
+ ("'python' 不是内部或外部命令", 1, True),
+ ("python : 不是可识别的 cmdlet", 1, True),
+ ("python : 'python' is not recognized as an internal or external command", 1, True),
+ ("some unrelated stderr", 1, False),
+ ("python not recognized", 9009, True),
+ ("", 0, False),
+ # Empty command name disables the hint even when stderr matches.
+ ("", 1, False),
+ ("not recognized", 1, True), # stderr matches → hint emitted
+ ],
+)
+def test_windows_not_found_hint_triggers(
+ stderr: str, exit_code: int, expect_hint: bool
+) -> None:
+ command = "" if not stderr else "python gen.py"
+ hint = ct._windows_not_found_hint(command, stderr, exit_code)
+ if expect_hint:
+ assert hint is not None
+ assert "[Diagnostic]" in hint
+ assert "python" in hint
+ else:
+ assert hint is None
+
+
+def test_windows_not_found_hint_skipped_on_non_windows() -> None:
+ """The hint is Windows-only even if stderr matches the markers."""
+ if os.name == "nt":
+ pytest.skip("windows-only invariant")
+ assert (
+ ct._windows_not_found_hint(
+ "python gen.py",
+ "python not recognized",
+ 1,
+ )
+ is None
+ )
+
+
+# ---------------------------------------------------------------------------
+# 5) _build_filesystem_rail fallback on flash import error
+# ---------------------------------------------------------------------------
+
+
+def test_deep_filesystem_rail_returns_flash_when_available() -> None:
+ """When the flash package is present, the flash rail is returned."""
+ from jiuwenswarm.server.runtime.agent_adapter import interface_deep as deep
+
+ rail = deep.JiuWenSwarmDeepAdapter._build_filesystem_rail()
+ assert rail is not None
+ assert type(rail).__name__ == "FlashBashSysOperationRail"
+
+
+def test_deep_filesystem_rail_falls_back_to_stock_on_import_error(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """When flash_bash_tool raises ImportError, _build_filesystem_rail
+ returns a stock ``SysOperationRail`` instead of ``None``."""
+ import importlib
+ import sys
+
+ from jiuwenswarm.server.runtime.agent_adapter import interface_deep as deep
+
+ real_module = sys.modules.get(
+ "jiuwenswarm.agents.harness.flash.tools.flash_bash_tool"
+ )
+ sys.modules[
+ "jiuwenswarm.agents.harness.flash.tools.flash_bash_tool"
+ ] = None # type: ignore[assignment]
+ try:
+ # Force a fresh import to take the new sys.modules entry.
+ importlib.invalidate_caches()
+ rail = deep.JiuWenSwarmDeepAdapter._build_filesystem_rail()
+ finally:
+ if real_module is not None:
+ sys.modules[
+ "jiuwenswarm.agents.harness.flash.tools.flash_bash_tool"
+ ] = real_module
+ else:
+ sys.modules.pop(
+ "jiuwenswarm.agents.harness.flash.tools.flash_bash_tool",
+ None,
+ )
+ importlib.invalidate_caches()
+ assert rail is not None
+ assert type(rail).__name__ == "SysOperationRail"
+
+
+# ---------------------------------------------------------------------------
+# 6) FlashBashTool.stream hardening parity
+# ---------------------------------------------------------------------------
+
+
+async def test_flash_bash_tool_stream_hardens_path(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Stream path must apply PATH hardening just like invoke does."""
+ from typing import AsyncIterator, Dict
+
+ from openjiuwen.harness.tools.base_tool import ToolOutput
+ from openjiuwen.harness.tools.shell.bash._tool import BashTool
+
+ captured: dict = {}
+
+ async def _fake_stream(self, inputs: Dict[str, Any], **kwargs: Any) -> AsyncIterator[ToolOutput]:
+ captured["inputs"] = inputs
+ yield ToolOutput(
+ success=False,
+ data={"text": "python not recognized"},
+ error=None,
+ )
+ yield ToolOutput(
+ success=False,
+ data={"content": "python not recognized"},
+ error="python not recognized",
+ )
+
+ monkeypatch.setattr(BashTool, "stream", _fake_stream)
+
+ from unittest.mock import MagicMock
+
+ from jiuwenswarm.agents.harness.flash.tools.flash_bash_tool import (
+ FlashBashTool,
+ )
+
+ tool = FlashBashTool(MagicMock(), language="en", agent_id="test")
+ outputs: list[ToolOutput] = []
+ async for chunk in tool.stream({"command": "python gen.py"}):
+ outputs.append(chunk)
+
+ if os.name == "nt":
+ # Hardened environment was injected.
+ assert "environment" in captured["inputs"]
+ # Last chunk contains the diagnostic hint (Windows only).
+ final = outputs[-1]
+ assert isinstance(final.data, dict)
+ if os.name == "nt":
+ assert "[Diagnostic]" in (final.data.get("content") or "")
+
+
+# ---------------------------------------------------------------------------
+# 7) FlashBashTool._hardened_inputs — explicit env priority + idempotence
+# ---------------------------------------------------------------------------
+
+
+def _flash_bash_tool():
+ from unittest.mock import MagicMock
+
+ from jiuwenswarm.agents.harness.flash.tools.flash_bash_tool import (
+ FlashBashTool,
+ )
+
+ return FlashBashTool(MagicMock(), language="en", agent_id="test")
+
+
[email protected](os.name != "nt", reason="Windows-only hardening behavior")
+def test_hardened_inputs_injects_when_no_env(
+ _flash_bash_tool,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Without explicit environment/env, a hardened env is injected."""
+ inputs = {"command": "python gen.py"}
+ out = _flash_bash_tool._hardened_inputs(inputs)
+ assert "environment" in out
+ assert "PATH" in out["environment"]
+
+
[email protected](os.name != "nt", reason="Windows-only hardening behavior")
+def test_hardened_inputs_does_not_overwrite_explicit_environment(
+ _flash_bash_tool,
+) -> None:
+ """Caller-supplied ``environment`` must win — never overwrite."""
+ sentinel_env = {"PATH": "/sentinel/bin", "CUSTOM": "1"}
+ inputs = {"command": "python gen.py", "environment": sentinel_env}
+ out = _flash_bash_tool._hardened_inputs(inputs)
+ assert out["environment"]["PATH"] == "/sentinel/bin"
+ assert out["environment"]["CUSTOM"] == "1"
+
+
[email protected](os.name != "nt", reason="Windows-only hardening behavior")
+def test_hardened_inputs_does_not_overwrite_explicit_env_alias(
+ _flash_bash_tool,
+) -> None:
+ """``env`` alias must also be honored — caller-supplied env wins.
+
+ The caller supplies ``env`` (the alias) without ``environment``; we must
+ not silently overwrite the alias by writing a new ``environment`` key.
+ """
+ sentinel_env = {"PATH": "/sentinel-alias/bin"}
+ inputs = {"command": "python gen.py", "env": sentinel_env}
+ out = _flash_bash_tool._hardened_inputs(inputs)
+ assert out.get("environment") is None
+ assert out.get("env") == sentinel_env
+
+
[email protected](os.name != "nt", reason="Windows-only hardening behavior")
+def test_hardened_inputs_returns_independent_copy(
+ _flash_bash_tool,
+) -> None:
+ """The hardened copy must not mutate the caller's inputs dict."""
+ inputs = {"command": "python gen.py"}
+ out = _flash_bash_tool._hardened_inputs(inputs)
+ assert out is not inputs
+ assert "environment" not in inputs
+
+
+def test_hardened_inputs_is_noop_on_non_windows(_flash_bash_tool) -> None:
+ """POSIX is left untouched (PATH is managed by the shell / service)."""
+ if os.name == "nt":
+ pytest.skip("windows-only invariant")
+ inputs = {"command": "python gen.py"}
+ out = _flash_bash_tool._hardened_inputs(inputs)
+ assert out is inputs
+
+
+# ---------------------------------------------------------------------------
+# 8) _annotate_empty_xlsx — extended coverage
+# ---------------------------------------------------------------------------
+
+
+ "content, expect_banner",
+ [
+ # Multi-sheet workbook with no data → no banner (not "only default").
+ ("## Sheet1\n## Sheet2\n## Sheet3\n", False),
+ # Data table has at least one markdown row → no banner.
+ ("## Sheet1\n| a | b |\n|---|---|\n| 1 | 2 |\n", False),
+ # Plain text with no sheet headers / table rows → triggers banner
+ # (no data rows, header_count <= 1).
+ ("Just plain text\nwith lines\n", True),
+ # Whitespace-only line-number prefix → triggers banner (no rows).
+ (" 1\t\n 2\t\n", True),
+ # Line number prefix + single sheet → triggers banner.
+ (" 1\t## Sheet1\n 2\t\n", True),
+ ],
+)
+def test_annotate_empty_xlsx_extended(content: str, expect_banner: bool) -> None:
+ """Extended coverage: multi-sheet, plain text, whitespace, prefix."""
+ rendered = {"content": content}
+ out = FlashReadFileTool._annotate_empty_xlsx(rendered)
+ assert isinstance(out, dict)
+ if expect_banner:
+ assert "该工作簿内容为空" in out["content"], out["content"]
+ else:
+ assert "该工作簿内容为空" not in out["content"], out["content"]
+
+
+# ---------------------------------------------------------------------------
+# 9) _annotate_single_xlsx — multi-sheet + line-prefix + non-xlsx pass-through
+# ---------------------------------------------------------------------------
+
+
+def test_annotate_single_xlsx_annotates_only_empty_default_sheet() -> None:
+ """Single-file path with one default Sheet must trigger banner."""
+ from openjiuwen.harness.tools.base_tool import ToolOutput
+
+ tool = FlashReadFileTool.__new__(FlashReadFileTool)
+ result = ToolOutput(
+ success=True,
+ data={"content": "## Sheet1\n"},
+ error=None,
+ )
+ out = tool._annotate_single_xlsx({"file_path": "/tmp/book.xlsx"}, result)
+ assert out is not result
+ assert "该工作簿内容为空" in out.data["content"]
+
+
+def test_annotate_single_xlsx_skips_multi_sheet_even_with_empty_data() -> None:
+ """Single-file path with multiple sheets is *not* a default-empty workbook."""
+ from openjiuwen.harness.tools.base_tool import ToolOutput
+
+ tool = FlashReadFileTool.__new__(FlashReadFileTool)
+ result = ToolOutput(
+ success=True,
+ data={"content": "## Sheet1\n## Sheet2\n"},
+ error=None,
+ )
+ out = tool._annotate_single_xlsx({"file_path": "/tmp/book.xlsx"}, result)
+ assert out is result
+
+
+# ---------------------------------------------------------------------------
+# 10) _xlsx_size_warning — 6000-byte boundary + .xls not warned
+# ---------------------------------------------------------------------------
+
+
+def test_xlsx_size_warning_excludes_xls(tmp_path: Path) -> None:
+ """Legacy ``.xls`` (binary) is not a target of the heuristic."""
+ p = tmp_path / "old.xls"
+ p.write_bytes(b"\x00" * 1000)
+ assert sfu._xlsx_size_warning(str(p)) is None
+
+
+def test_xlsx_size_warning_5999_vs_6000_boundary(tmp_path: Path) -> None:
+ """Boundary: 5999 → warn, 6000 → no warn."""
+ below = tmp_path / "below.xlsx"
+ below.write_bytes(b"\x00" * 5999)
+ at_or_above = tmp_path / "above.xlsx"
+ at_or_above.write_bytes(b"\x00" * 6000)
+ assert sfu._xlsx_size_warning(str(below)) is not None
+ assert sfu._xlsx_size_warning(str(at_or_above)) is None
+
+
+# ---------------------------------------------------------------------------
+# 11) _windows_not_found_hint — marker hits + exit_code 9009
+# ---------------------------------------------------------------------------
+
+
+def test_windows_not_found_hint_marker_text_paths() -> None:
+ """All three marker families trigger the hint."""
+ assert (
+ ct._windows_not_found_hint("python x.py", "python is not recognized", 1)
+ is not None
+ )
+ assert (
+ ct._windows_not_found_hint("python x.py", "'python' 不是内部或外部命令", 1)
+ is not None
+ )
+ assert (
+ ct._windows_not_found_hint("python x.py", "python 不是可识别的 cmdlet", 1)
+ is not None
+ )
+
+
+def test_windows_not_found_hint_exit_code_9009_path() -> None:
+ """exit_code=9009 path triggers regardless of stderr text."""
+ assert (
+ ct._windows_not_found_hint("python x.py", "anything", 9009)
+ is not None
+ )
+
+
+def test_windows_not_found_hint_unrelated_stderr_no_hint() -> None:
+ """Neither a marker nor 9009 → no hint."""
+ assert (
+ ct._windows_not_found_hint("python x.py", "OK", 0) is None
+ )
+
+
+# ---------------------------------------------------------------------------
+# 12) _path_key — case-insensitive PATH lookup
+# ---------------------------------------------------------------------------
+
+
+ "key",
+ ["PATH", "Path", "path"],
+)
+def test_path_key_finds_existing_canonical_key(key: str) -> None:
+ """All three case variants resolve to the actual key in the dict."""
+ env = {key: "C:\\System32", "OTHER": "1"}
+ assert ct._path_key(env) == key
+
+
+def test_path_key_falls_back_to_canonical_when_missing() -> None:
+ """No PATH-ish key present → default canonical "PATH"."""
+ env = {"WINDIR": "C:\\Windows"}
+ assert ct._path_key(env) == "PATH"
+
+
+def test_prepend_windows_tool_paths_preserves_mixed_case_key() -> None:
+ """Caller-supplied ``Path`` (mixed case) must be written back under
+ the same key, with the original system PATH preserved and no duplicate
+ ``PATH`` key emitted."""
+ ct._WINDOWS_TOOL_DIRS = (["C:\\TrustedTool"], [])
+ env = {"Path": "C:\\System32"}
+ ct._prepend_windows_tool_paths(env)
+ assert "PATH" not in env, env
+ assert "Path" in env, env
+ assert env["Path"].startswith("C:\\TrustedTool" + os.pathsep), env
+ assert "C:\\System32" in env["Path"], env
+
+
+def test_prepend_windows_tool_paths_uses_lowercase_key() -> None:
+ """Lowercase ``path`` key is honored the same way."""
+ ct._WINDOWS_TOOL_DIRS = (["C:\\TrustedTool"], [])
+ env = {"path": "C:\\System32"}
+ ct._prepend_windows_tool_paths(env)
+ assert "PATH" not in env
+ assert "path" in env
+ assert "C:\\System32" in env["path"]
+
+
+# ---------------------------------------------------------------------------
+# 13) _discover_windows_tool_dirs — empty env vars + cwd OSError
+# ---------------------------------------------------------------------------
+
+
+def test_discover_with_empty_env_vars_returns_safe(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Empty LOCALAPPDATA / ProgramFiles must yield no relative trusted paths."""
+ monkeypatch.setenv("LOCALAPPDATA", "")
+ monkeypatch.setenv("ProgramFiles", "")
+ with patch("os.getcwd", return_value=str(tmp_path)):
+ trusted, workspace = ct._discover_windows_tool_dirs()
+ for d in trusted:
+ assert os.path.isabs(d), d
+ assert workspace == []
+
+
+def test_discover_tolerates_cwd_oserror(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """cwd deleted/unavailable → skip the workspace walk, return safely."""
+ def _raise_getcwd():
+ raise OSError("no current working directory")
+
+ monkeypatch.setattr("os.getcwd", _raise_getcwd)
+ trusted, workspace = ct._discover_windows_tool_dirs()
+ assert workspace == []
+ # trusted may still pick up real OfficeAce install; just assert no exception
+ assert isinstance(trusted, list)
+
+
+def test_discover_tolerates_local_app_data_none(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """LOCALAPPDATA / ProgramFiles unset (None) must not yield relative paths."""
+ monkeypatch.delenv("LOCALAPPDATA", raising=False)
+ monkeypatch.delenv("ProgramFiles", raising=False)
+ with patch("os.getcwd", return_value="C:\\anywhere"):
+ trusted, workspace = ct._discover_windows_tool_dirs()
+ for d in trusted:
+ assert os.path.isabs(d), d
+
+
+# ---------------------------------------------------------------------------
+# 14) stderr truncation must preserve hint
+# ---------------------------------------------------------------------------
+
+
+def test_stderr_truncation_preserves_hint(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Long stderr + hint: hint must survive truncation, not be sliced off."""
+ from jiuwenswarm.agents.harness.common.tools import command_tools as ct2
+
+ captured: dict = {}
+
+ def _fake_clip(value: str, max_chars: int) -> str:
+ captured["max_chars"] = max_chars
+ captured["input_len"] = len(value)
+ if max_chars <= 0 or len(value) <= max_chars:
+ return value
+ return value[:max_chars] + "\n...[truncated]"
+
+ monkeypatch.setattr(ct2, "_clip_text", _fake_clip)
+
+ long_stderr = "x" * 5000
+ monkeypatch.setattr(
+ ct2,
+ "_windows_not_found_hint",
+ lambda *_a, **_k: "\n[Diagnostic] python not found",
+ )
+
+ hint = ct2._windows_not_found_hint("python", long_stderr, 1)
+ max_output_chars = 2000
+ hint_text = hint or ""
+ base_budget = max(0, max_output_chars - len(hint_text))
+ stderr_text = ct2._clip_text(long_stderr, base_budget) + hint_text
+ # _clip_text was called with reduced budget, not the full max_output_chars.
+ assert captured["max_chars"] == max_output_chars - len(hint_text)
+ # Final stderr ends with the hint.
+ assert stderr_text.endswith("[Diagnostic] python not found"), stderr_text[-50:]
+ # Final stderr does not end with the truncation marker (hint pushed it off).
+ assert not stderr_text.endswith("...[truncated]"), stderr_text[-50:]
+
+
+def test_stderr_truncation_no_hint_uses_full_budget(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """No hint → full max_output_chars budget goes to stderr."""
+ from jiuwenswarm.agents.harness.common.tools import command_tools as ct2
+
+ captured: dict = {}
+
+ def _fake_clip(value: str, max_chars: int) -> str:
+ captured["max_chars"] = max_chars
+ return value if max_chars <= 0 or len(value) <= max_chars else value[:max_chars]
+
+ monkeypatch.setattr(ct2, "_clip_text", _fake_clip)
+
+ long_stderr = "x" * 5000
+ hint = None # no hint
+ max_output_chars = 2000
+ hint_text = hint or ""
+ base_budget = max(0, max_output_chars - len(hint_text))
+ _ = ct2._clip_text(long_stderr, base_budget) + hint_text
+ assert captured["max_chars"] == max_output_chars
+
+
+# ---------------------------------------------------------------------------
+# 15) _annotate_single_xlsx must not pollute error on success
+# ---------------------------------------------------------------------------
+
+
+def test_annotate_single_xlsx_preserves_none_error_on_success() -> None:
+ """A successful empty-xlsx read must NOT stuff the banner into error."""
+ from openjiuwen.harness.tools.base_tool import ToolOutput
+
+ tool = FlashReadFileTool.__new__(FlashReadFileTool)
+ result = ToolOutput(
+ success=True,
+ data={"content": "## Sheet1\n"},
+ error=None,
+ )
+ out = tool._annotate_single_xlsx({"file_path": "/tmp/book.xlsx"}, result)
+ assert out.error is None, f"error must remain None, got {out.error!r}"
+
+
+def test_annotate_single_xlsx_preserves_real_error_on_failure() -> None:
+ """A real error string must survive the annotation untouched."""
+ from openjiuwen.harness.tools.base_tool import ToolOutput
+
+ tool = FlashReadFileTool.__new__(FlashReadFileTool)
+ sentinel_error = "EACCES: permission denied"
+ result = ToolOutput(
+ success=False,
+ data={"content": "## Sheet1\n"},
+ error=sentinel_error,
+ )
+ out = tool._annotate_single_xlsx({"file_path": "/tmp/book.xlsx"}, result)
+ assert out.error == sentinel_error, out.error
\ No newline at end of file