The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: decode config and state files as UTF-8 on non-UTF-8 locales
CoreyNoDream9f6b2a64e003
diff --git a/agent/copilot_acp_client.py b/agent/copilot_acp_client.pyindex e4990fdf5e7..572e10758ad 100644--- a/agent/copilot_acp_client.py+++ b/agent/copilot_acp_client.py@@ -736,7 +736,7 @@ class CopilotACPClient:if denied:raise PermissionError(denied)path.parent.mkdir(parents=True, exist_ok=True)- path.write_text(str(params.get("content") or ""))+ path.write_text(str(params.get("content") or ""), encoding="utf-8")response = {"jsonrpc": "2.0","id": message_id,diff --git a/agent/nous_rate_guard.py b/agent/nous_rate_guard.pyindex 415d367ca17..0234eef2ea2 100644--- a/agent/nous_rate_guard.py+++ b/agent/nous_rate_guard.py@@ -117,7 +117,7 @@ def record_nous_rate_limit(# Atomic write: write to temp file + renamefd, tmp_path = tempfile.mkstemp(dir=state_dir, suffix=".tmp")try:- with os.fdopen(fd, "w") as f:+ with os.fdopen(fd, "w", encoding="utf-8") as f:json.dump(state, f)atomic_replace(tmp_path, path)except Exception:diff --git a/tests/agent/test_copilot_acp_client.py b/tests/agent/test_copilot_acp_client.pyindex 1d1d28cc542..cfe6c78c7df 100644--- a/tests/agent/test_copilot_acp_client.py+++ b/tests/agent/test_copilot_acp_client.py@@ -203,6 +203,84 @@ class CopilotACPClientSafetyTests(unittest.TestCase):self.assertNotIn("abc123def456", content)self.assertIn("OPENAI_API_KEY=", content)+ def test_fs_read_text_file_decodes_as_utf8_under_non_utf8_locale(self) -> None:+ """Regression for #18637 (bug 2): fs/read_text_file used+ ``path.read_text()`` with no explicit encoding, so on Windows+ GBK/CP932/CP949 locales the Copilot read_file tool crashed on any+ source file with non-ASCII content (e.g. a CJK comment, an em dash,+ or UTF-8 BOM)."""+ with tempfile.TemporaryDirectory() as tmpdir:+ root = Path(tmpdir)+ target = root / "note.md"+ target.write_text("# 中文标题\nem dash — here\n", encoding="utf-8")++ original_read_text = Path.read_text++ def strict_read_text(self, encoding=None, errors=None, **kwargs):+ if self == target and encoding != "utf-8":+ raise UnicodeDecodeError(+ "gbk", b"\x94", 0, 1, "illegal multibyte sequence"+ )+ return original_read_text(+ self, encoding=encoding, errors=errors, **kwargs+ )++ with patch.object(Path, "read_text", strict_read_text):+ response = self._dispatch(+ {+ "jsonrpc": "2.0",+ "id": 10,+ "method": "fs/read_text_file",+ "params": {"path": str(target)},+ },+ cwd=str(root),+ )++ self.assertNotIn("error", response)+ content = ((response.get("result") or {}).get("content") or "")+ self.assertIn("中文标题", content)+ self.assertIn("em dash —", content)++ def test_fs_write_text_file_encodes_as_utf8(self) -> None:+ """Regression for #18637 (bug 2): fs/write_text_file used+ ``path.write_text()`` with no explicit encoding, so on non-UTF-8+ locales the Copilot write tool could not emit code/config files+ containing any char outside the platform codec."""+ with tempfile.TemporaryDirectory() as tmpdir:+ root = Path(tmpdir)+ target = root / "out.md"+ payload = "# 中文标题\nem dash — here\n"++ original_write_text = Path.write_text++ def strict_write_text(+ self, data, encoding=None, errors=None, **kwargs+ ):+ if self == target and encoding != "utf-8":+ raise UnicodeEncodeError(+ "gbk", data, 0, 1, "illegal multibyte sequence"+ )+ return original_write_text(+ self, data, encoding=encoding, errors=errors, **kwargs+ )++ with patch.object(Path, "write_text", strict_write_text):+ response = self._dispatch(+ {+ "jsonrpc": "2.0",+ "id": 11,+ "method": "fs/write_text_file",+ "params": {+ "path": str(target),+ "content": payload,+ },+ },+ cwd=str(root),+ )++ self.assertNotIn("error", response)+ self.assertEqual(target.read_text(encoding="utf-8"), payload)+def test_write_text_file_reuses_write_denylist(self) -> None:with tempfile.TemporaryDirectory() as tmpdir:home = Path(tmpdir) / "home"diff --git a/tests/agent/test_nous_rate_guard.py b/tests/agent/test_nous_rate_guard.pyindex 4441aa6e447..18920efb947 100644--- a/tests/agent/test_nous_rate_guard.py+++ b/tests/agent/test_nous_rate_guard.py@@ -389,3 +389,48 @@ class TestIsGenuineNousRateLimit:assert is_genuine_nous_rate_limit(headers=None, last_known_state=None) is False+++class TestRateGuardStateEncoding:+ """Regression for #18637: the cross-session rate-limit state file was+ opened without ``encoding="utf-8"`` on both the atomic write (os.fdopen)+ and the read. On Windows Chinese locales the platform default decoder+ raises on UTF-8 bytes written by a peer process, silently losing the+ rate-limit guard and re-enabling the retry amplification the module was+ built to prevent.+ """++ def test_read_uses_utf8_under_non_utf8_locale(self, rate_guard_env, monkeypatch):+ import builtins++ from agent.nous_rate_guard import nous_rate_limit_remaining, _state_path++ path = _state_path()+ os.makedirs(os.path.dirname(path), exist_ok=True)+ # State JSON written with a UTF-8 provider label. Python's json+ # module itself escapes non-ASCII by default, but a peer writer+ # (or human) using ensure_ascii=False produces raw UTF-8 bytes,+ # which is what this guards against.+ with open(path, "w", encoding="utf-8") as f:+ f.write(+ '{"reset_at": %d, "provider": "中文", "recorded_at": 0}'+ % (int(time.time()) + 3600)+ )++ real_open = builtins.open++ def guarded_open(file, mode="r", *args, **kwargs):+ try:+ is_target = str(file) == str(path)+ except Exception:+ is_target = False+ if is_target and "b" not in mode and kwargs.get("encoding") != "utf-8":+ raise UnicodeDecodeError(+ "gbk", b"\x94", 0, 1, "illegal multibyte sequence"+ )+ return real_open(file, mode, *args, **kwargs)++ monkeypatch.setattr(builtins, "open", guarded_open)++ remaining = nous_rate_limit_remaining()+ assert remaining is not None and remaining > 0