Skip to content

Your lightweight open-source personal agent.

fix(tools): preserve supplied newlines when creating files

Shuhan Siae6801d3eba6
diff --git a/nanobot/agent/tools/filesystem.py b/nanobot/agent/tools/filesystem.py
index 1da8f23a2..77b3a926e 100644
--- a/nanobot/agent/tools/filesystem.py
+++ b/nanobot/agent/tools/filesystem.py
@@ -579,7 +579,7 @@ class WriteFileTool(_FsTool):
raise ValueError("Unknown content")
fp = self._resolve_write(path)
fp.parent.mkdir(parents=True, exist_ok=True)
- fp.write_text(content, encoding="utf-8")
+ fp.write_text(content, encoding="utf-8", newline="")
self._file_states.record_write(fp)
return f"Successfully wrote {len(content)} characters to {fp}"
except PermissionError as e:
@@ -948,7 +948,7 @@ class EditFileTool(_FsTool):
if not file_exists:
if old_text == "":
fp.parent.mkdir(parents=True, exist_ok=True)
- fp.write_text(new_text, encoding="utf-8")
+ fp.write_text(new_text, encoding="utf-8", newline="")
self._file_states.record_write(fp)
return self._format_summary(fp, "", fp.read_bytes().decode("utf-8"), created=True)
return self._file_not_found_msg(path, fp)
@@ -967,7 +967,7 @@ class EditFileTool(_FsTool):
content = raw.decode("utf-8")
if content.strip():
return ToolResult.error(f"Error: Cannot create file — {path} already exists and is not empty.")
- fp.write_text(new_text, encoding="utf-8")
+ fp.write_text(new_text, encoding="utf-8", newline="")
self._file_states.record_write(fp)
return self._format_summary(fp, content, fp.read_bytes().decode("utf-8"))
diff --git a/tests/tools/test_filesystem_tools.py b/tests/tools/test_filesystem_tools.py
index 210edf467..263d5e8f2 100644
--- a/tests/tools/test_filesystem_tools.py
+++ b/tests/tools/test_filesystem_tools.py
@@ -10,6 +10,28 @@ from nanobot.agent.tools.filesystem import (
WriteFileTool,
)
+
[email protected]("newline", ["\n", "\r\n", "\r"])
[email protected]("operation", ["write", "edit_new", "edit_empty"])
+async def test_file_creation_preserves_provided_newlines(tmp_path, newline, operation):
+ target = tmp_path / "nested" / "script.py"
+ content = f"first = 1{newline}second = 2{newline}"
+ if operation == "write":
+ result = await WriteFileTool(workspace=tmp_path).execute(
+ path=str(target), content=content,
+ )
+ else:
+ if operation == "edit_empty":
+ target.parent.mkdir()
+ target.touch()
+ result = await EditFileTool(workspace=tmp_path).execute(
+ path=str(target), old_text="", new_text=content,
+ )
+
+ assert "Error" not in result
+ assert target.read_bytes() == content.encode("utf-8")
+
# ---------------------------------------------------------------------------
# ReadFileTool
# ---------------------------------------------------------------------------