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(rails): 读取类工具路径仅空白不同时自动纠正并告知模型

zhangfuzhi2e1c25df7561
diff --git a/jiuwenswarm/agents/harness/common/rails/path_whitespace_fix.py b/jiuwenswarm/agents/harness/common/rails/path_whitespace_fix.py
new file mode 100644
index 0000000000..10cbda327c
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/rails/path_whitespace_fix.py
@@ -0,0 +1,136 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Repair file-tool paths that differ from a real path only by whitespace."""
+
+from __future__ import annotations
+
+import json
+import os
+import pathlib
+from typing import Any
+
+# Built-in read-side tools that work on the local filesystem. Write/edit tools
+# are left out on purpose: a missing path there may be a file to create.
+# ACP's read_text_file is left out too: it is served by the client (fs/read_text_file
+# JSON-RPC), so the path lives on the client's filesystem and os.path.exists on the
+# host cannot tell whether it is missing.
+WHITESPACE_FIX_TOOL_NAMES = frozenset({"read_file", "list_files", "glob", "grep"})
+
+_SINGLE_PATH_KEYS = ("file_path", "path")
+_MULTI_PATH_KEYS = ("file_paths",)
+
+
+def _squash(name: str) -> str:
+ """Drop every whitespace character (``str.split`` covers full-width spaces)."""
+ return "".join(name.split())
+
+
+def _is_unc_path(path: str) -> bool:
+ return path.startswith(("\\\\", "//"))
+
+
+def resolve_whitespace_variant(path: str, base_dir: str | None = None) -> str | None:
+ if not isinstance(path, str) or not path.strip():
+ return None
+ expanded = os.path.expanduser(path.strip())
+ if _is_unc_path(expanded):
+ return None
+ if not os.path.isabs(expanded):
+ if not base_dir:
+ return None
+ expanded = os.path.join(base_dir, expanded)
+ if os.path.exists(expanded):
+ return None
+
+ parts = pathlib.PurePath(expanded).parts
+ if len(parts) < 2 or not os.path.isdir(parts[0]):
+ return None
+
+ current = parts[0]
+ changed = False
+ for part in parts[1:]:
+ candidate = os.path.join(current, part)
+ if os.path.exists(candidate):
+ current = candidate
+ continue
+ key = _squash(part)
+ if not key:
+ return None
+ try:
+ names = os.listdir(current)
+ except OSError:
+ return None
+ matches = [name for name in names if _squash(name) == key]
+ if len(matches) != 1:
+ return None
+ current = os.path.join(current, matches[0])
+ changed = True
+ return current if changed else None
+
+
+def fix_whitespace_path_arguments(
+ arguments: Any,
+ base_dir: str | None = None,
+) -> tuple[dict[str, Any], list[tuple[str, str]]] | None:
+ if isinstance(arguments, str):
+ try:
+ arguments = json.loads(arguments)
+ except (json.JSONDecodeError, TypeError):
+ return None
+ if not isinstance(arguments, dict):
+ return None
+
+ new_args = dict(arguments)
+ fixes: list[tuple[str, str]] = []
+
+ for key in _SINGLE_PATH_KEYS:
+ value = arguments.get(key)
+ if not isinstance(value, str):
+ continue
+ corrected = resolve_whitespace_variant(value, base_dir)
+ if corrected:
+ new_args[key] = corrected
+ fixes.append((value, corrected))
+
+ for key in _MULTI_PATH_KEYS:
+ values = arguments.get(key)
+ if not isinstance(values, list):
+ continue
+ new_values = list(values)
+ for index, value in enumerate(values):
+ if not isinstance(value, str):
+ continue
+ corrected = resolve_whitespace_variant(value, base_dir)
+ if corrected:
+ new_values[index] = corrected
+ fixes.append((value, corrected))
+ new_args[key] = new_values
+
+ if not fixes:
+ return None
+ return new_args, fixes
+
+
+def build_whitespace_fix_notice(fixes: list[tuple[str, str]], language: str = "cn") -> str:
+ lines = []
+ for requested, corrected in fixes:
+ if language == "en":
+ lines.append(
+ f"[Path corrected] '{requested}' does not exist. Used the only entry that differs "
+ f"by whitespace alone: '{corrected}'. The result below is for the corrected path; "
+ "keep using it and do not retry the original path."
+ )
+ else:
+ lines.append(
+ f"[路径已自动纠正] 请求的路径不存在:'{requested}'。已改用同目录下仅空白字符不同的唯一匹配:"
+ f"'{corrected}'。下面是纠正后路径的结果,后续请直接使用该路径,不要重试原路径。"
+ )
+ return "\n".join(lines)
+
+
+__all__ = [
+ "WHITESPACE_FIX_TOOL_NAMES",
+ "build_whitespace_fix_notice",
+ "fix_whitespace_path_arguments",
+ "resolve_whitespace_variant",
+]
diff --git a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
index 4688489a57..4ac028c1d7 100644
--- a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
@@ -47,6 +47,11 @@ from jiuwenswarm.agents.harness.common.tools.todo_resume import (
from jiuwenswarm.agents.harness.common.rails.symphony import (
SymphonyToolStreamHandler,
)
+from jiuwenswarm.agents.harness.common.rails.path_whitespace_fix import (
+ WHITESPACE_FIX_TOOL_NAMES,
+ build_whitespace_fix_notice,
+ fix_whitespace_path_arguments,
+)
from jiuwenswarm.agents.harness.common.rails.read_file_validation import (
extract_path_from_arguments,
handle_read_file_before_tool_call,
@@ -70,6 +75,7 @@ from jiuwenswarm.common.utils import fix_json_arguments, logger
# "todo":flash 统一工具(单卡 action 分发,覆盖同一组引擎操作)
_TODO_TOOL_NAMES = frozenset(["todo_create", "todo_get", "todo_list", "todo_modify", "todo"])
_EARLY_CHECKPOINT_EXTRA_KEY = "_jiuwenswarm_early_checkpoint_done"
+_WHITESPACE_PATH_FIXES_EXTRA_KEY = "_jiuwenswarm_whitespace_path_fixes"
_EARLY_CHECKPOINT_ENV = "JIUWENCLAW_EARLY_CHECKPOINT"
@@ -533,6 +539,55 @@ class JiuSwarmStreamEventRail(DeepAgentRail):
return None
return rebased
+ @staticmethod
+ def _fix_whitespace_path_args(tool_call: Any, tool_name: str) -> list[tuple[str, str]]:
+ try:
+ from openjiuwen.core.sys_operation.cwd import get_cwd
+
+ base_dir = get_cwd()
+ except Exception: # noqa: BLE001 - cwd is optional, absolute paths still work
+ base_dir = None
+ try:
+ raw_args = getattr(tool_call, "arguments", None)
+ fixed = fix_whitespace_path_arguments(raw_args, str(base_dir) if base_dir else None)
+ if fixed is None:
+ return []
+ new_args, fixes = fixed
+ # ToolCall.arguments is a JSON string; keep the type it arrived with.
+ tool_call.arguments = (
+ json.dumps(new_args, ensure_ascii=False) if isinstance(raw_args, str) else new_args
+ )
+ for original, corrected in fixes:
+ logger.info(
+ "[StreamEventRail] fixed whitespace in %s path: %s -> %s",
+ tool_name,
+ original,
+ corrected,
+ )
+ return fixes
+ except (AttributeError, TypeError, OSError) as exc:
+ logger.warning(
+ "[StreamEventRail] failed to fix whitespace in %s path: %s",
+ tool_name,
+ exc,
+ )
+ return []
+
+ def _annotate_whitespace_path_fix(self, ctx: AgentCallbackContext) -> None:
+ extra = getattr(ctx, "extra", None)
+ fixes_by_call = extra.get(_WHITESPACE_PATH_FIXES_EXTRA_KEY) if isinstance(extra, dict) else None
+ if not isinstance(fixes_by_call, dict):
+ return
+ tool_call_id = str(getattr(getattr(ctx.inputs, "tool_call", None), "id", "") or "")
+ fixes = fixes_by_call.pop(tool_call_id, None)
+ if not fixes:
+ return
+ tool_msg = getattr(ctx.inputs, "tool_msg", None)
+ content = getattr(tool_msg, "content", None)
+ if not isinstance(content, str):
+ return
+ tool_msg.content = build_whitespace_fix_notice(fixes, self._get_prompt_language()) + "\n" + content
+
def _rebase_user_artifact_path_args(self, tool_call: Any, tool_name: str) -> None:
"""Rewrite write/edit file_path when model hardcodes agent workspace."""
args = getattr(tool_call, "arguments", None)
@@ -1139,6 +1194,13 @@ class JiuSwarmStreamEventRail(DeepAgentRail):
)
if tool_name in ("write_file", "edit_file"):
self._rebase_user_artifact_path_args(tc, tool_name)
+ if tool_name in WHITESPACE_FIX_TOOL_NAMES:
+ fixes = self._fix_whitespace_path_args(tc, tool_name)
+ tool_call_id = str(getattr(tc, "id", "") or "")
+ if fixes and tool_call_id and isinstance(getattr(ctx, "extra", None), dict):
+ # ctx.extra is shared across all tool calls of the whole invoke;
+ # entries are popped in after_tool_call keyed by tool_call_id.
+ ctx.extra.setdefault(_WHITESPACE_PATH_FIXES_EXTRA_KEY, {})[tool_call_id] = fixes
if is_read_file_tool(tool_name):
path = extract_path_from_arguments(getattr(tc, "arguments", {}))
if path:
@@ -1348,6 +1410,7 @@ class JiuSwarmStreamEventRail(DeepAgentRail):
return
normalize_read_file_tool_outcome(ctx)
+ self._annotate_whitespace_path_fix(ctx)
# A call suspended for user input (approval card, ask_user) has no
# result yet: ToolCallResilienceRail only left a failure placeholder
# on ctx.inputs.tool_result. Emitting it would show the tool as
diff --git a/tests/unit_tests/agents/harness/common/rails/test_path_whitespace_fix.py b/tests/unit_tests/agents/harness/common/rails/test_path_whitespace_fix.py
new file mode 100644
index 0000000000..f48318bade
--- /dev/null
+++ b/tests/unit_tests/agents/harness/common/rails/test_path_whitespace_fix.py
@@ -0,0 +1,251 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace
+
+import pytest
+from openjiuwen.core.foundation.llm import ToolMessage
+from openjiuwen.core.single_agent.rail.base import ToolCallInputs
+from openjiuwen.harness.tools.base_tool import ToolOutput
+
+from jiuwenswarm.agents.harness.common.rails.path_whitespace_fix import (
+ build_whitespace_fix_notice,
+ fix_whitespace_path_arguments,
+ resolve_whitespace_variant,
+)
+from jiuwenswarm.agents.harness.common.rails.stream_event_rail import (
+ JiuSwarmStreamEventRail,
+)
+
+
+def test_file_name_with_inserted_spaces_is_resolved(tmp_path):
+ real = tmp_path / "交委港航收支报告8.26冉.docx"
+ real.write_bytes(b"x")
+ wrong = tmp_path / "交委港航收支报告 8.26 冉.docx"
+ assert resolve_whitespace_variant(str(wrong)) == str(real)
+
+
+def test_directory_segments_are_resolved_too(tmp_path):
+ real_dir = tmp_path / "复核2026" / "港航收支8.26"
+ real_dir.mkdir(parents=True)
+ real = real_dir / "审查8.26 (2).xlsx"
+ real.write_bytes(b"x")
+ wrong = tmp_path / "复核 2026" / "港航收支 8.26" / "审查 8.26 (2).xlsx"
+ assert resolve_whitespace_variant(str(wrong)) == str(real)
+
+
+def test_existing_path_is_left_alone(tmp_path):
+ real = tmp_path / "报告 8.26.docx"
+ real.write_bytes(b"x")
+ (tmp_path / "报告8.26.docx").write_bytes(b"x")
+ assert resolve_whitespace_variant(str(real)) is None
+
+
+def test_ambiguous_match_is_not_resolved(tmp_path):
+ (tmp_path / "报告8.26 冉.docx").write_bytes(b"x")
+ (tmp_path / "报告 8.26冉.docx").write_bytes(b"x")
+ assert resolve_whitespace_variant(str(tmp_path / "报告 8.26 冉.docx")) is None
+
+
+def test_non_whitespace_difference_is_not_resolved(tmp_path):
+ (tmp_path / "报告8.26冉.docx").write_bytes(b"x")
+ assert resolve_whitespace_variant(str(tmp_path / "报告 8.27 冉.docx")) is None
+ assert resolve_whitespace_variant(str(tmp_path / "报告 8.26 冉.doc")) is None
+
+
+def test_relative_path_uses_base_dir(tmp_path):
+ real = tmp_path / "报告8.26冉.docx"
+ real.write_bytes(b"x")
+ assert resolve_whitespace_variant("报告 8.26 冉.docx") is None
+ assert resolve_whitespace_variant("报告 8.26 冉.docx", str(tmp_path)) == str(real)
+
+
+def test_arguments_dict_and_json_string_are_fixed_without_mutation(tmp_path):
+ real = tmp_path / "报告8.26冉.docx"
+ real.write_bytes(b"x")
+ wrong = str(tmp_path / "报告 8.26 冉.docx")
+ args = {"file_path": wrong, "call_goal": "读取报告"}
+ new_args, fixes = fix_whitespace_path_arguments(args)
+ assert new_args == {"file_path": str(real), "call_goal": "读取报告"}
+ assert fixes == [(wrong, str(real))]
+ assert args["file_path"] == wrong
+ new_args, _ = fix_whitespace_path_arguments(json.dumps(args, ensure_ascii=False))
+ assert new_args["file_path"] == str(real)
+
+
+def test_file_paths_list_is_fixed_per_entry(tmp_path):
+ real = tmp_path / "报告8.26冉.docx"
+ real.write_bytes(b"x")
+ other = tmp_path / "plain.txt"
+ other.write_text("x", encoding="utf-8")
+ wrong = str(tmp_path / "报告 8.26 冉.docx")
+ new_args, fixes = fix_whitespace_path_arguments({"file_paths": [wrong, str(other)]})
+ assert new_args["file_paths"] == [str(real), str(other)]
+ assert fixes == [(wrong, str(real))]
+
+
+def test_nothing_to_fix_returns_none(tmp_path):
+ missing = str(tmp_path / "不存在.docx")
+ assert fix_whitespace_path_arguments({"file_path": missing}) is None
+ assert fix_whitespace_path_arguments("not json") is None
+ assert fix_whitespace_path_arguments(None) is None
+
+
+def test_stream_event_rail_rewrites_tool_call_arguments(tmp_path):
+ real = tmp_path / "报告8.26冉.docx"
+ real.write_bytes(b"x")
+ tool_call = SimpleNamespace(arguments={"file_path": str(tmp_path / "报告 8.26 冉.docx")})
+ wrong = tool_call.arguments["file_path"]
+ fixes = JiuSwarmStreamEventRail._fix_whitespace_path_args(tool_call, "read_file")
+ assert tool_call.arguments == {"file_path": str(real)}
+ assert fixes == [(wrong, str(real))]
+
+
+def test_json_string_arguments_stay_a_json_string(tmp_path):
+ real = tmp_path / "报告8.26冉.docx"
+ real.write_bytes(b"x")
+ wrong = str(tmp_path / "报告 8.26 冉.docx")
+ tool_call = SimpleNamespace(arguments=json.dumps({"file_path": wrong}, ensure_ascii=False))
+ fixes = JiuSwarmStreamEventRail._fix_whitespace_path_args(tool_call, "read_file")
+ assert isinstance(tool_call.arguments, str)
+ assert json.loads(tool_call.arguments) == {"file_path": str(real)}
+ assert "报告8.26冉" in tool_call.arguments
+ assert fixes == [(wrong, str(real))]
+
+
+async def test_hooks_keep_json_string_arguments_as_string(tmp_path):
+ real = tmp_path / "报告8.26冉.txt"
+ real.write_text("hello", encoding="utf-8")
+ wrong = str(tmp_path / "报告 8.26 冉.txt")
+ arguments = json.dumps({"file_path": wrong, "call_goal": "读取文件"}, ensure_ascii=False)
+ ctx = SimpleNamespace(
+ session=_FakeSession(),
+ agent=None,
+ context=None,
+ extra={},
+ exception=None,
+ inputs=ToolCallInputs(
+ tool_call=SimpleNamespace(id="call_a", name="read_file", arguments=arguments),
+ tool_name="read_file",
+ tool_args=arguments,
+ ),
+ )
+ await JiuSwarmStreamEventRail().before_tool_call(ctx)
+ assert isinstance(ctx.inputs.tool_call.arguments, str)
+ assert json.loads(ctx.inputs.tool_call.arguments) == {"file_path": str(real)}
+ assert json.loads(ctx.inputs.tool_args) == {"file_path": str(real)}
+
+
+_FIXES_KEY = "_jiuwenswarm_whitespace_path_fixes"
+
+
+def _after_ctx(extra: dict, tool_call_id: str, content: object) -> SimpleNamespace:
+ return SimpleNamespace(
+ extra=extra,
+ inputs=SimpleNamespace(
+ tool_call=SimpleNamespace(id=tool_call_id),
+ tool_msg=SimpleNamespace(content=content),
+ ),
+ )
+
+
+def test_stream_event_rail_tells_model_about_the_correction():
+ fixes = [("D:\\工作\\报告 8.26 冉.docx", "D:\\工作\\报告8.26冉.docx")]
+ extra = {_FIXES_KEY: {"call_a": fixes}}
+ ctx = _after_ctx(extra, "call_a", "1\thello")
+ rail = SimpleNamespace(_get_prompt_language=lambda: "cn")
+ JiuSwarmStreamEventRail._annotate_whitespace_path_fix(rail, ctx)
+ content = ctx.inputs.tool_msg.content
+ assert content == build_whitespace_fix_notice(fixes, "cn") + "\n1\thello"
+ assert "报告 8.26 冉.docx" in content
+ assert "报告8.26冉.docx" in content
+ assert extra[_FIXES_KEY] == {}
+
+
+def test_parallel_tool_calls_only_annotate_their_own_result():
+ fixes = [("D:\\工作\\报告 8.26 冉.docx", "D:\\工作\\报告8.26冉.docx")]
+ # ctx.extra is one dict shared by every tool call of the same model turn.
+ extra = {_FIXES_KEY: {"call_a": fixes}}
+ untouched = _after_ctx(extra, "call_b", "1\tother file")
+ corrected = _after_ctx(extra, "call_a", "1\thello")
+ rail = SimpleNamespace(_get_prompt_language=lambda: "cn")
+ JiuSwarmStreamEventRail._annotate_whitespace_path_fix(rail, untouched)
+ JiuSwarmStreamEventRail._annotate_whitespace_path_fix(rail, corrected)
+ assert untouched.inputs.tool_msg.content == "1\tother file"
+ assert corrected.inputs.tool_msg.content.startswith("[路径已自动纠正]")
+
+
+def test_stream_event_rail_leaves_result_alone_without_correction():
+ rail = SimpleNamespace(_get_prompt_language=lambda: "cn")
+ plain = _after_ctx({}, "call_a", "1\thello")
+ JiuSwarmStreamEventRail._annotate_whitespace_path_fix(rail, plain)
+ assert plain.inputs.tool_msg.content == "1\thello"
+ non_text = [{"type": "text", "text": "hello"}]
+ multimodal = _after_ctx({_FIXES_KEY: {"call_a": [("a", "b")]}}, "call_a", non_text)
+ JiuSwarmStreamEventRail._annotate_whitespace_path_fix(rail, multimodal)
+ assert multimodal.inputs.tool_msg.content is non_text
+
+
+class _FakeSession:
+ def __init__(self):
+ self.outputs = []
+
+ async def write_stream(self, output):
+ self.outputs.append(output)
+
+ @staticmethod
+ def get_session_id() -> str:
+ return "sess-1"
+
+
+def _read_file_ctx(session: _FakeSession, extra: dict, call_id: str, path: str) -> SimpleNamespace:
+ arguments = {"file_path": path, "call_goal": "读取文件"}
+ return SimpleNamespace(
+ session=session,
+ agent=None,
+ context=None,
+ extra=extra,
+ exception=None,
+ inputs=ToolCallInputs(
+ tool_call=SimpleNamespace(id=call_id, name="read_file", arguments=arguments),
+ tool_name="read_file",
+ tool_args=arguments,
+ ),
+ )
+
+
+async def test_hooks_fix_the_path_and_annotate_only_the_corrected_call(tmp_path):
+ real = tmp_path / "报告8.26冉.txt"
+ real.write_text("hello", encoding="utf-8")
+ other = tmp_path / "其他.txt"
+ other.write_text("other", encoding="utf-8")
+ wrong = str(tmp_path / "报告 8.26 冉.txt")
+ rail = JiuSwarmStreamEventRail()
+ session = _FakeSession()
+ shared_extra: dict = {}
+ corrected = _read_file_ctx(session, shared_extra, "call_a", wrong)
+ untouched = _read_file_ctx(session, shared_extra, "call_b", str(other))
+ await rail.before_tool_call(corrected)
+ await rail.before_tool_call(untouched)
+ # The tool runs with the corrected path; call_goal is stripped as before.
+ assert corrected.inputs.tool_args == {"file_path": str(real)}
+ assert untouched.inputs.tool_args == {"file_path": str(other)}
+ for ctx, text in ((untouched, "1\tother"), (corrected, "1\thello")):
+ ctx.inputs.tool_result = ToolOutput(success=True, data={"content": text})
+ ctx.inputs.tool_msg = ToolMessage(content=text, tool_call_id=ctx.inputs.tool_call.id)
+ await rail.after_tool_call(ctx)
+ assert untouched.inputs.tool_msg.content == "1\tother"
+ assert corrected.inputs.tool_msg.content.startswith("[路径已自动纠正]")
+ assert corrected.inputs.tool_msg.content.endswith("1\thello")
+ assert wrong in corrected.inputs.tool_msg.content
+ assert str(real) in corrected.inputs.tool_msg.content
+
+
+def test_english_notice_names_both_paths():
+ notice = build_whitespace_fix_notice([("a b.txt", "ab.txt")], "en")
+ assert notice.startswith("[Path corrected]")
+ assert "'a b.txt'" in notice and "'ab.txt'" in notice