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:解决code产物编码问题

Chenchong_RD4665c0210714
diff --git a/jiuwenswarm/agents/harness/code/prompt/code_prompt_builder.py b/jiuwenswarm/agents/harness/code/prompt/code_prompt_builder.py
index ed6deabc7e..d2d75ccbdd 100644
--- a/jiuwenswarm/agents/harness/code/prompt/code_prompt_builder.py
+++ b/jiuwenswarm/agents/harness/code/prompt/code_prompt_builder.py
@@ -339,6 +339,9 @@ def _code_using_your_tools_prompt() -> PromptSection:
"- To edit files use edit_file instead of sed or awk\n"
"- To create files use write_file instead of cat with heredoc "
"or echo redirection\n"
+ "- In generated Python source, use literal Unicode in string literals "
+ '(e.g. "文档标题"), not \\uXXXX / \\UXXXXXXXX / \\xXX for visible text; '
+ "save scripts as UTF-8\n"
"- To search for files use glob or list_files instead of find or ls\n"
"- To search the content of files, use grep instead of the bash grep command\n"
"- Reserve bash exclusively for system commands "
diff --git a/jiuwenswarm/agents/harness/common/rails/avatar_rail.py b/jiuwenswarm/agents/harness/common/rails/avatar_rail.py
index 3e10a36db1..dbfa36b75f 100644
--- a/jiuwenswarm/agents/harness/common/rails/avatar_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/avatar_rail.py
@@ -14,9 +14,11 @@ from openjiuwen.core.single_agent.rail.base import AgentCallbackContext
from openjiuwen.harness.prompts import PromptSection
from openjiuwen.harness.rails.base import DeepAgentRail
+from jiuwenswarm.agents.harness.common.memory.external_memory_config import is_builtin_memory_allowed
from jiuwenswarm.agents.harness.common.rails.permissions.owner_scopes import (
TOOL_PERMISSION_CONTEXT,
)
+from jiuwenswarm.common.config import get_config
from jiuwenswarm.common.utils import logger
_MEMORY_WRITE_TOOLS = frozenset({"write_memory", "edit_memory"})
@@ -53,21 +55,47 @@ class AvatarPromptRail(DeepAgentRail):
language = getattr(builder, "language", "cn") or "cn"
+ # forbidden_memory — engine=none 或自定义 forbidden 配置时注入,不依赖数字分身功能
+ engine_disabled = not is_builtin_memory_allowed(get_config())
try:
from jiuwenswarm.agents.harness.common.memory.forbidden import get_forbidden_memory_prompt
- forbidden = get_forbidden_memory_prompt(language)
- if forbidden:
- section = PromptSection(
- name="forbidden_memory",
- content={language: forbidden},
- priority=_AVATAR_PROMPT_PRIORITY + 3,
- )
- builder.add_section(section)
- self._injected_sections.add("forbidden_memory")
+ forbidden = get_forbidden_memory_prompt(language) or ""
except Exception as e:
logger.debug("[AvatarRail] 加载 forbidden_memory 失败: %s", e)
+ forbidden = ""
+
+ if engine_disabled or forbidden:
+ parts = []
+ if engine_disabled:
+ parts.append(_build_memory_fully_disabled_prompt(language))
+ if forbidden:
+ parts.append(forbidden)
+ content = "\n\n".join(parts)
+ section = PromptSection(
+ name="forbidden_memory",
+ content={language: content},
+ priority=_AVATAR_PROMPT_PRIORITY + 3,
+ )
+ builder.add_section(section)
+ self._injected_sections.add("forbidden_memory")
perm_ctx = TOOL_PERMISSION_CONTEXT.get()
+ should_disable_memory = (
+ perm_ctx is not None
+ and not perm_ctx.enable_memory
+ and perm_ctx.group_digital_avatar
+ and perm_ctx.avatar_mode
+ )
+
+ if not engine_disabled and not forbidden and not should_disable_memory:
+ section = PromptSection(
+ name="memory_runtime_enabled",
+ content={language: _build_memory_enabled_prompt(language)},
+ priority=_AVATAR_PROMPT_PRIORITY + 3,
+ )
+ builder.add_section(section)
+ self._injected_sections.add("memory_runtime_enabled")
+
if perm_ctx is None:
return
@@ -105,11 +133,6 @@ class AvatarPromptRail(DeepAgentRail):
self._injected_sections.add("group_chat_memory_notice")
# 记忆完全禁用(三个条件同时满足:enable_memory=False + group_digital_avatar=True + 群聊消息)
- should_disable_memory = (
- not perm_ctx.enable_memory
- and perm_ctx.group_digital_avatar
- and perm_ctx.avatar_mode
- )
if should_disable_memory:
disabled_content = _build_memory_fully_disabled_prompt(language)
section = PromptSection(
@@ -285,6 +308,19 @@ def _build_memory_fully_disabled_prompt(language: str) -> str:
"""
+def _build_memory_enabled_prompt(language: str) -> str:
+ """记忆已开启提示词。"""
+ if language == "cn":
+ return """## 记忆系统 - 已开启
+
+**记忆系统当前已启用。** 可按需使用记忆工具。对话历史中若出现「记忆已禁用」,以本段为准。
+"""
+ return """## Memory System - Enabled
+
+**The memory system is currently enabled.** Use memory tools as needed. If history says memory was disabled, this section prevails.
+"""
+
+
__all__ = [
"AvatarPromptRail",
]
diff --git a/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py b/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py
index 3ad8e6b49a..4788057e0e 100644
--- a/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py
@@ -44,8 +44,8 @@ _IMAGE_ARTIFACT_EXTENSIONS = frozenset({
".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg",
})
-# 文件路径检测的正则表达式模式(仿 PR#1440,配合图像扩展名白名单过滤)
-_IMAGE_FILE_PATH_PATTERNS = [
+# 文件路径检测的正则表达式模式(仿 PR#1440;调用方按扩展名白名单过滤)
+_FILE_PATH_PATTERNS = [
# Windows绝对路径 (D:\path, D:/path)
re.compile(r'[A-Za-z]:[/\\][^\s\]\}\)\,\'\"`<>,。;、:]+'),
# Unix绝对路径 (/path/to/file)
@@ -58,6 +58,7 @@ _IMAGE_FILE_PATH_PATTERNS = [
]
_PATH_TRAILING_CHARS = "'\"`\\]\\}\\),.;:,。;、:"
+_PYTHON_SCRIPT_EXTENSIONS = frozenset({".py", ".pyw"})
def _clean_path_candidate(path_str: str) -> str:
@@ -65,27 +66,41 @@ def _clean_path_candidate(path_str: str) -> str:
return path_str.strip().strip(_PATH_TRAILING_CHARS).strip()
-def _extract_image_paths_from_tool_result(tool_result: Any) -> list[str]:
- """从工具输出结果中提取图像产物路径。
+def _parse_tool_args_payload(tool_args: Any) -> dict[str, Any]:
+ if tool_args is None:
+ return {}
+ payload: Any = tool_args
+ if isinstance(tool_args, str):
+ try:
+ payload = json.loads(tool_args)
+ except (TypeError, ValueError):
+ return {}
+ if isinstance(payload, dict):
+ return payload
+ return {}
- 仿 PR#1440 的正则提取思路,范围限定为图像扩展名白名单。
- 处理字符串、字典、对象三类结果。
- """
- if tool_result is None:
- return []
+def _tool_result_to_text(tool_result: Any) -> str:
+ if tool_result is None:
+ return ""
if isinstance(tool_result, str):
- result_text = tool_result
- elif isinstance(tool_result, dict):
- result_text = json.dumps(tool_result, ensure_ascii=False)
- elif hasattr(tool_result, "__dict__"):
- result_text = str(tool_result)
- else:
- result_text = str(tool_result)
+ return tool_result
+ if isinstance(tool_result, dict):
+ return json.dumps(tool_result, ensure_ascii=False)
+ if hasattr(tool_result, "__dict__"):
+ return str(tool_result)
+ return str(tool_result)
+
+
+def _extract_raw_paths_from_result_text(tool_result: Any) -> list[str]:
+ """从工具输出结果中正则提取路径候选(不按扩展名过滤)。"""
+ result_text = _tool_result_to_text(tool_result)
+ if not result_text:
+ return []
seen: set[str] = set()
paths: list[str] = []
- for pattern in _IMAGE_FILE_PATH_PATTERNS:
+ for pattern in _FILE_PATH_PATTERNS:
for match in pattern.findall(result_text):
cleaned = _clean_path_candidate(match)
if not cleaned:
@@ -93,14 +108,47 @@ def _extract_image_paths_from_tool_result(tool_result: Any) -> list[str]:
identity = cleaned.replace("\\", "/").lower()
if identity in seen:
continue
- if Path(cleaned).suffix.lower() not in _IMAGE_ARTIFACT_EXTENSIONS:
- continue
seen.add(identity)
paths.append(cleaned)
-
return paths
+def _extract_file_paths_from_write_tool(
+ tool_name: str,
+ tool_args: Any,
+ tool_result: Any,
+) -> list[str]:
+ """从 write/edit 类工具参数或结果中提取产物路径。"""
+ paths: list[str] = []
+ payload = _parse_tool_args_payload(tool_args)
+ for key in ("path", "file_path", "target_file", "abs_file_path"):
+ value = str(payload.get(key) or "").strip()
+ if value:
+ paths.append(value)
+
+ if paths:
+ return list(dict.fromkeys(paths))
+
+ if tool_name in {"write_file", "edit_file", "write", "write_text_file"}:
+ for candidate in _extract_raw_paths_from_result_text(tool_result):
+ if Path(candidate).suffix.lower() in _PYTHON_SCRIPT_EXTENSIONS:
+ paths.append(candidate)
+ return list(dict.fromkeys(paths))
+
+
+def _extract_image_paths_from_tool_result(tool_result: Any) -> list[str]:
+ """从工具输出结果中提取图像产物路径。
+
+ 仿 PR#1440 的正则提取思路,范围限定为图像扩展名白名单。
+ 处理字符串、字典、对象三类结果。
+ """
+ return [
+ path
+ for path in _extract_raw_paths_from_result_text(tool_result)
+ if Path(path).suffix.lower() in _IMAGE_ARTIFACT_EXTENSIONS
+ ]
+
+
@dataclass
class TaskExecutionContext:
task_id: str
@@ -134,6 +182,12 @@ class TaskExecutionRail(DeepAgentRail):
# 触发图像产物后处理 hook 的工具
IMAGE_TOOLS = frozenset({"generate_image"})
+ FILE_ARTIFACT_TOOLS = frozenset({
+ "write_file",
+ "edit_file",
+ "write",
+ "write_text_file",
+ })
def __init__(self) -> None:
super().__init__()
@@ -251,6 +305,10 @@ class TaskExecutionRail(DeepAgentRail):
await self._trigger_image_artifact_hook(ctx)
return
+ if tool_name in self.FILE_ARTIFACT_TOOLS:
+ await self._trigger_artifact_post_process_hook(ctx)
+ return
+
async def _trigger_image_artifact_hook(
self, ctx: AgentCallbackContext
) -> None:
@@ -332,6 +390,87 @@ class TaskExecutionRail(DeepAgentRail):
len(image_paths),
)
+ async def _trigger_artifact_post_process_hook(
+ self, ctx: AgentCallbackContext
+ ) -> None:
+ """文件产物落盘后触发 ARTIFACT_POST_PROCESS 扩展 hook。"""
+ session = ctx.session
+ if session is None:
+ return
+ try:
+ session_id = session.get_session_id()
+ except Exception:
+ logger.debug(
+ "[TaskExecutionRail] artifact post-process hook: "
+ "failed to get session_id",
+ exc_info=True,
+ )
+ return
+
+ tool_args = getattr(ctx.inputs, "tool_args", None)
+ tool_result = getattr(ctx.inputs, "tool_result", None)
+ artifact_paths = _extract_file_paths_from_write_tool(
+ ctx.inputs.tool_name,
+ tool_args,
+ tool_result,
+ )
+ if not artifact_paths:
+ return
+
+ task_id = _ACTIVE_TASK_ID.get()
+ tool_name = ctx.inputs.tool_name
+
+ try:
+ from jiuwenswarm.extensions.registry import ExtensionRegistry
+ from jiuwenswarm.extensions.hook_event import (
+ AgentServerHookEvents,
+ )
+ from jiuwenswarm.extensions.hooks_context import (
+ ArtifactPostProcessHookContext,
+ )
+ except ImportError as exc:
+ logger.warning(
+ "[TaskExecutionRail] skip artifact post-process hook, "
+ "import failed: %s",
+ exc,
+ )
+ return
+
+ hook_ctx = ArtifactPostProcessHookContext(
+ session_id=session_id,
+ tool_name=tool_name,
+ task_id=task_id,
+ artifact_paths=artifact_paths,
+ )
+ try:
+ await ExtensionRegistry.get_instance().trigger(
+ AgentServerHookEvents.ARTIFACT_POST_PROCESS,
+ hook_ctx,
+ )
+ except RuntimeError:
+ logger.warning(
+ "[TaskExecutionRail] skip artifact post-process hook: "
+ "ExtensionRegistry not initialized",
+ )
+ return
+ except Exception as exc:
+ logger.warning(
+ "[TaskExecutionRail] artifact post-process hook failed "
+ "session_id=%s tool=%s error=%s",
+ session_id,
+ tool_name,
+ exc,
+ )
+ return
+
+ logger.info(
+ "[TaskExecutionRail] artifact post-process hook done "
+ "session_id=%s tool=%s count=%d",
+ session_id,
+ tool_name,
+ len(artifact_paths),
+ )
+
async def after_invoke(self, ctx: AgentCallbackContext) -> None:
self._todo_map_before_tool = {}
self._bind_context_to_in_progress_task()
diff --git a/jiuwenswarm/extensions/hook_event.py b/jiuwenswarm/extensions/hook_event.py
index e0818d472a..f036b69bcc 100644
--- a/jiuwenswarm/extensions/hook_event.py
+++ b/jiuwenswarm/extensions/hook_event.py
@@ -30,3 +30,4 @@ class AgentServerHookEvents(HookEventBase):
MEMORY_AFTER_CHAT = HookEventBase.get_event("memory_after_chat")
BEFORE_SYSTEM_PROMPT_BUILD = HookEventBase.get_event("before_system_prompt_build")
IMAGE_ARTIFACT_POST_PROCESS = HookEventBase.get_event("image_artifact_post_process")
+ ARTIFACT_POST_PROCESS = HookEventBase.get_event("artifact_post_process")
diff --git a/jiuwenswarm/extensions/hooks_context.py b/jiuwenswarm/extensions/hooks_context.py
index db7dd7a173..236eca937a 100644
--- a/jiuwenswarm/extensions/hooks_context.py
+++ b/jiuwenswarm/extensions/hooks_context.py
@@ -88,3 +88,21 @@ class ImageArtifactHookContext:
def to_dict(self) -> dict[str, Any]:
return asdict(self)
+
+
+@dataclass
+class ArtifactPostProcessHookContext:
+ """产物落盘检测后、向前端发送 ``artifact.generated`` 之前的扩展回调上下文。
+
+ 扩展可在 handler 中按 ``artifact_paths`` 对文件做原地后处理(如水印、源码可读性转换)。
+ """
+
+ session_id: str
+ tool_name: str
+ task_id: str | None = None
+ subagent_id: str | None = None
+ artifact_paths: list[str] = field(default_factory=list)
+ metadata: dict[str, Any] = field(default_factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yaml
index 4d7f78d5b8..4bf37fa3e6 100644
--- a/jiuwenswarm/resources/config.yaml
+++ b/jiuwenswarm/resources/config.yaml
@@ -367,6 +367,11 @@ perf:
# Parent+subagent breakdown in stats.by_agent (off by default).
include_by_agent: false
+# 生成代码可读性:Prompt 约束 + Python 源码 \uXXXX 兜底转换(仅 .py/.pyw)
+# 设为 false 可紧急关闭整套能力
+code_generation:
+ unicode_readable: true
+
telemetry:
# enabled=true 时统一 Runtime 独占 Provider 选择;下方旧
# agent_observability/team_observability 的 exporter/endpoint 不参与选择。
@@ -798,6 +803,8 @@ minio:
public_base_url:
channels:
+ officeclaw:
+ send_file_allowed: true
web:
send_file_allowed: true
feishu:
diff --git a/jiuwenswarm/server/app_agentserver.py b/jiuwenswarm/server/app_agentserver.py
index 42b6e50329..8f5f2c3b07 100644
--- a/jiuwenswarm/server/app_agentserver.py
+++ b/jiuwenswarm/server/app_agentserver.py
@@ -243,6 +243,13 @@ async def _run_with_telemetry(host: str, port: int, telemetry_lifecycle) -> None
extension_manager=extension_manager,
)
+ try:
+ from jiuwenswarm.server.runtime.code_source_unicode import register_code_source_unicode_hook
+
+ register_code_source_unicode_hook()
+ except Exception: # noqa: BLE001
+ logger.warning("[AgentServer] code_source_unicode hook registration skipped", exc_info=True)
+
try:
from jiuwenswarm.infrastructure.log_masking.engine import LogMaskingEngine
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index e75f773926..9accc29cc6 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -3601,18 +3601,18 @@ class JiuWenSwarmDeepAdapter:
mcc["model_name"] = (
react_mcc.get("model_name")
or react.get("model_name")
- or os.getenv("MODEL_NAME", "")
+ or read_env("MODEL_NAME", "")
or "gpt-4"
)
if not str(mcc.get("client_provider") or "").strip():
mcc["client_provider"] = (
react_mcc.get("client_provider")
- or os.getenv("MODEL_PROVIDER", "")
+ or read_env("MODEL_PROVIDER", "")
)
if not str(mcc.get("api_base") or "").strip():
- mcc["api_base"] = react_mcc.get("api_base") or os.getenv("API_BASE", "")
+ mcc["api_base"] = react_mcc.get("api_base") or read_env("API_BASE", "")
if not str(mcc.get("api_key") or "").strip():
- mcc["api_key"] = react_mcc.get("api_key") or os.getenv("API_KEY", "")
+ mcc["api_key"] = react_mcc.get("api_key") or read_env("API_KEY", "")
return mcc, meta
def _collect_default_model_log_fields(self) -> dict[str, str]:
diff --git a/jiuwenswarm/server/runtime/code_source_unicode.py b/jiuwenswarm/server/runtime/code_source_unicode.py
new file mode 100644
index 0000000000..534e1a27e7
--- /dev/null
+++ b/jiuwenswarm/server/runtime/code_source_unicode.py
@@ -0,0 +1,197 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Python script Unicode escape readability: normalize + artifact hook."""
+
+from __future__ import annotations
+
+import ast
+import io
+import logging
+import re
+import tokenize
+from pathlib import Path
+from tokenize import TokenInfo
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+_ESCAPE_MARKERS = re.compile(r"\\(?:u|U|x)")
+_PYTHON_SCRIPT_SUFFIXES = (".py", ".pyw")
+_FALSE_STRINGS = frozenset({"false", "0", "no", "off", ""})
+_SURROGATE_MIN = 0xD800
+_SURROGATE_MAX = 0xDFFF
+_HOOK_REGISTERED = False
+
+
+def is_code_unicode_readable_enabled(config: dict[str, Any] | None = None) -> bool:
+ if config is None:
+ try:
+ from jiuwenswarm.common.config import get_config
+
+ config = get_config()
+ except Exception:
+ return True
+ code_gen = config.get("code_generation") if isinstance(config, dict) else None
+ if not isinstance(code_gen, dict):
+ return True
+ value = code_gen.get("unicode_readable", True)
+ if value is None:
+ return True
+ if isinstance(value, str):
+ return value.strip().lower() not in _FALSE_STRINGS
+ return bool(value)
+
+
+def _string_prefix(token_str: str) -> str:
+ idx = 0
+ while idx < len(token_str) and token_str[idx] in "fFbBrRuU":
+ idx += 1
+ return token_str[:idx]
+
+
+def _should_skip_string_token(token_str: str) -> bool:
+ prefix = _string_prefix(token_str).lower()
+ return "f" in prefix or "b" in prefix or "r" in prefix
+
+
+def _contains_lone_surrogate(value: str) -> bool:
+ """Return True when *value* has UTF-16 surrogate code units (not valid in UTF-8)."""
+ return any(_SURROGATE_MIN <= ord(ch) <= _SURROGATE_MAX for ch in value)
+
+
+def _quote_python_string(value: str) -> str:
+ parts = ['"']
+ for ch in value:
+ code = ord(ch)
+ if ch == "\n":
+ parts.append("\\n")
+ elif ch == "\t":
+ parts.append("\\t")
+ elif ch == "\\":
+ parts.append("\\\\")
+ elif ch == '"':
+ parts.append('\\"')
+ elif ch == "\r":
+ parts.append("\\r")
+ elif code < 32 or (127 <= code <= 159):
+ parts.append(f"\\x{code:02x}")
+ else:
+ parts.append(ch)
+ parts.append('"')
+ return "".join(parts)
+
+
+def normalize_python_source_unicode_literals(source: str) -> tuple[str, int]:
+ """Decode \\u/\\U/\\x in Python string literals to readable Unicode text."""
+ if not source:
+ return source, 0
+ try:
+ tokens = list(tokenize.generate_tokens(io.StringIO(source).readline))
+ except (tokenize.TokenError, SyntaxError):
+ # IndentationError/TabError (SyntaxError subclasses) also escape generate_tokens
+ # on LLM-generated code with mixed tabs/spaces or inconsistent indent.
+ return source, 0
+
+ modified: list[TokenInfo] = []
+ replacements = 0
+ for tok in tokens:
+ if tok.type != tokenize.STRING or _should_skip_string_token(tok.string):
+ modified.append(tok)
+ continue
+ if not _ESCAPE_MARKERS.search(tok.string):
+ modified.append(tok)
+ continue
+ try:
+ value = ast.literal_eval(tok.string)
+ except (ValueError, SyntaxError):
+ modified.append(tok)
+ continue
+ if not isinstance(value, str) or not any(ord(ch) > 127 for ch in value):
+ modified.append(tok)
+ continue
+ if _contains_lone_surrogate(value):
+ modified.append(tok)
+ continue
+ new_token = _quote_python_string(value)
+ if new_token == tok.string:
+ modified.append(tok)
+ continue
+ replacements += 1
+ modified.append(TokenInfo(tok.type, new_token, tok.start, tok.end, tok.line))
+
+ if replacements == 0:
+ return source, 0
+ try:
+ return tokenize.untokenize(modified), replacements
+ except (tokenize.TokenError, TypeError) as exc:
+ logger.debug("[code_source_unicode] untokenize failed: %s", exc)
+ return source, 0
+
+
+def normalize_python_script_file(path: str | Path) -> int:
+ file_path = Path(path)
+ if file_path.suffix.lower() not in _PYTHON_SCRIPT_SUFFIXES:
+ return 0
+ try:
+ source = file_path.read_text(encoding="utf-8")
+ except (OSError, UnicodeDecodeError) as exc:
+ logger.debug("[code_source_unicode] skip read %s: %s", file_path, exc)
+ return 0
+ normalized, count = normalize_python_source_unicode_literals(source)
+ if count <= 0 or normalized == source:
+ return 0
+ try:
+ normalized.encode("utf-8")
+ except UnicodeEncodeError as exc:
+ logger.warning(
+ "[code_source_unicode] skip write (not utf-8 encodable) path=%s error=%s",
+ file_path,
+ exc,
+ )
+ return 0
+ try:
+ file_path.write_text(normalized, encoding="utf-8", newline="\n")
+ except (OSError, UnicodeEncodeError) as exc:
+ logger.warning("[code_source_unicode] write failed path=%s error=%s", file_path, exc)
+ return 0
+ return count
+
+
+async def _normalize_code_artifact_hook(ctx: Any) -> None:
+ if not is_code_unicode_readable_enabled():
+ return
+ for raw_path in getattr(ctx, "artifact_paths", []) or []:
+ path = str(raw_path or "").strip()
+ if not path:
+ continue
+ count = normalize_python_script_file(path)
+ if count > 0:
+ logger.info(
+ "[code_source_unicode] normalized path=%s count=%d",
+ path,
+ count,
+ )
+
+
+def register_code_source_unicode_hook() -> None:
+ global _HOOK_REGISTERED
+ if _HOOK_REGISTERED:
+ return
+ try:
+ from jiuwenswarm.extensions.hook_event import AgentServerHookEvents
+ from jiuwenswarm.extensions.registry import ExtensionRegistry
+ except ImportError as exc:
+ logger.warning("[code_source_unicode] skip hook registration: %s", exc)
+ return
+ try:
+ registry = ExtensionRegistry.get_instance()
+ except RuntimeError as exc:
+ logger.warning("[code_source_unicode] skip hook registration: %s", exc)
+ return
+ registry.register(
+ AgentServerHookEvents.ARTIFACT_POST_PROCESS,
+ _normalize_code_artifact_hook,
+ priority=50,
+ )
+ _HOOK_REGISTERED = True
+ logger.info("[code_source_unicode] registered ARTIFACT_POST_PROCESS hook")
diff --git a/tests/unit_tests/agentserver/rails/test_task_execution_artifact_paths.py b/tests/unit_tests/agentserver/rails/test_task_execution_artifact_paths.py
new file mode 100644
index 0000000000..94479b60ef
--- /dev/null
+++ b/tests/unit_tests/agentserver/rails/test_task_execution_artifact_paths.py
@@ -0,0 +1,49 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+from __future__ import annotations
+
+import warnings
+
+warnings.filterwarnings(
+ "ignore",
+ message=r"Protobuf gencode version.*",
+)
+
+from jiuwenswarm.agents.harness.common.rails.task_execution_rail import (
+ _extract_file_paths_from_write_tool,
+ _extract_image_paths_from_tool_result,
+)
+
+
+def test_write_tool_prefers_path_from_tool_args() -> None:
+ paths = _extract_file_paths_from_write_tool(
+ "write_file",
+ {"path": "/tmp/demo.py"},
+ "Wrote /tmp/other.py",
+ )
+ assert paths == ["/tmp/demo.py"]
+
+
+def test_write_tool_fallback_extracts_py_from_result_text() -> None:
+ paths = _extract_file_paths_from_write_tool(
+ "write_file",
+ {},
+ "Successfully wrote /workspace/out/demo.py",
+ )
+ assert paths == ["/workspace/out/demo.py"]
+
+
+def test_write_tool_fallback_ignores_non_python_paths() -> None:
+ paths = _extract_file_paths_from_write_tool(
+ "write_file",
+ {},
+ "Saved /workspace/out/chart.png and /workspace/out/notes.txt",
+ )
+ assert paths == []
+
+
+def test_image_path_extraction_keeps_image_whitelist() -> None:
+ paths = _extract_image_paths_from_tool_result(
+ "Generated /workspace/out/chart.png and /workspace/out/demo.py"
+ )
+ assert paths == ["/workspace/out/chart.png"]
diff --git a/tests/unit_tests/agentserver/test_code_source_unicode.py b/tests/unit_tests/agentserver/test_code_source_unicode.py
new file mode 100644
index 0000000000..0804325ecc
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_code_source_unicode.py
@@ -0,0 +1,113 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+from __future__ import annotations
+
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from jiuwenswarm.extensions.hooks_context import ArtifactPostProcessHookContext
+from jiuwenswarm.server.runtime.code_source_unicode import (
+ _normalize_code_artifact_hook,
+ is_code_unicode_readable_enabled,
+ normalize_python_script_file,
+ normalize_python_source_unicode_literals,
+ register_code_source_unicode_hook,
+)
+
+
+def test_normalize_unicode_escape_to_readable() -> None:
+ source = 'doc.add_paragraph("\\u6807\\u9898")\n'
+ normalized, count = normalize_python_source_unicode_literals(source)
+ assert count == 1
+ assert '"标题"' in normalized
+
+
+def test_raw_string_unchanged() -> None:
+ source = 'value = r"\\u6587"\n'
+ normalized, count = normalize_python_source_unicode_literals(source)
+ assert count == 0
+ assert normalized == source
+
+
+def test_inconsistent_indent_degrades_to_original() -> None:
+ """IndentationError from generate_tokens must not propagate."""
+ source = 'def f():\n if True:\n x = "\\u6807"\n y = 1\n'
+ normalized, count = normalize_python_source_unicode_literals(source)
+ assert count == 0
+ assert normalized == source
+
+
+def test_tab_error_degrades_to_original() -> None:
+ """TabError from generate_tokens must not propagate (3.11 tokenize may not raise it)."""
+ source = 'x = "\\u6807"\n'
+ with patch(
+ "jiuwenswarm.server.runtime.code_source_unicode.tokenize.generate_tokens",
+ side_effect=TabError("inconsistent use of tabs and spaces in indentation"),
+ ):
+ normalized, count = normalize_python_source_unicode_literals(source)
+ assert count == 0
+ assert normalized == source
+
+
+def test_incomplete_token_degrades_to_original() -> None:
+ source = 'x = "\\u6807'
+ normalized, count = normalize_python_source_unicode_literals(source)
+ assert count == 0
+ assert normalized == source
+
+
+def test_surrogate_escape_pair_unchanged() -> None:
+ source = 'x = "\\ud83d\\ude00"\n'
+ normalized, count = normalize_python_source_unicode_literals(source)
+ assert count == 0
+ assert normalized == source
+
+
+def test_normalize_python_script_file_surrogate_preserves_file(tmp_path: Path) -> None:
+ source = 'x = "\\ud83d\\ude00"\n'
+ script = tmp_path / "demo.py"
+ script.write_text(source, encoding="utf-8")
+ assert normalize_python_script_file(script) == 0
+ assert script.read_text(encoding="utf-8") == source
+
+
+def test_config_disabled() -> None:
+ assert is_code_unicode_readable_enabled({"code_generation": {"unicode_readable": False}}) is False
+
+
+async def test_artifact_hook_normalizes_file(tmp_path: Path) -> None:
+ script = tmp_path / "demo.py"
+ script.write_text('x = "\\u6807\\u9898"\n', encoding="utf-8")
+ ctx = ArtifactPostProcessHookContext(
+ session_id="s1",
+ tool_name="write_file",
+ artifact_paths=[str(script)],
+ )
+ await _normalize_code_artifact_hook(ctx)
+ assert script.read_text(encoding="utf-8") == 'x = "标题"\n'
+
+
+def test_normalize_python_script_file(tmp_path: Path) -> None:
+ script = tmp_path / "demo.py"
+ script.write_text('x = "\\u6807\\u9898"\n', encoding="utf-8")
+ assert normalize_python_script_file(script) == 1
+ assert script.read_text(encoding="utf-8") == 'x = "标题"\n'
+
+
+def test_register_hook_idempotent() -> None:
+ registry = MagicMock()
+ with pytest.MonkeyPatch.context() as mp:
+ mp.setattr(
+ "jiuwenswarm.extensions.registry.ExtensionRegistry.get_instance",
+ lambda: registry,
+ )
+ mp.setattr(
+ "jiuwenswarm.server.runtime.code_source_unicode._HOOK_REGISTERED",
+ False,
+ )
+ register_code_source_unicode_hook()
+ register_code_source_unicode_hook()
+ assert registry.register.call_count == 1