From 85578a06b7460813ffce88eb5ca0fc9182eda0aa Mon Sep 17 00:00:00 2001 From: zhayujie Date: Sun, 1 Feb 2026 17:13:32 +0800 Subject: [PATCH] fix: memory edit bug --- agent/prompt/builder.py | 8 ++++++-- agent/tools/read/read.py | 18 ++++++++++++------ 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/agent/prompt/builder.py b/agent/prompt/builder.py index 9134e02..168018c 100644 --- a/agent/prompt/builder.py +++ b/agent/prompt/builder.py @@ -315,8 +315,12 @@ def _build_memory_section(memory_manager: Any, tools: Optional[List[Any]], langu "", "**使用原则**:", "- 自然使用记忆,就像你本来就知道; 不用刻意提起或列举记忆,除非用户提起相关内容", - "- 追加内容到现有记忆文件 → 必须用 `edit` 工具(先 read 读取,再 edit 追加)", - "- 创建新的记忆文件 → 可以用 `write` 工具(已有记忆文件不可直接write,会覆盖删除)", + "", + "**写入记忆的正确方式**:", + "- 追加到现有文件末尾 → 用 `read` 读取文件最后几行(offset=-10),然后用 `edit` 追加", + " 例: read(path=memory/2026-02-01.md, offset=-10) → 看到最后内容 → edit(oldText=最后几行完整文本, newText=最后几行+新内容)", + "- 创建新文件 → 用 `write`", + "- ⚠️ 不要用 `memory_get` 读取后再 `edit`,因为会截断长文本", "", ] diff --git a/agent/tools/read/read.py b/agent/tools/read/read.py index 4810890..6ecae07 100644 --- a/agent/tools/read/read.py +++ b/agent/tools/read/read.py @@ -26,7 +26,7 @@ class Read(BaseTool): }, "offset": { "type": "integer", - "description": "Line number to start reading from (1-indexed, optional)" + "description": "Line number to start reading from (1-indexed, optional). Use negative values to read from end (e.g. -20 for last 20 lines)" }, "limit": { "type": "integer", @@ -167,11 +167,17 @@ class Read(BaseTool): # Apply offset (if specified) start_line = 0 if offset is not None: - start_line = max(0, offset - 1) # Convert to 0-indexed - if start_line >= total_file_lines: - return ToolResult.fail( - f"Error: Offset {offset} is beyond end of file ({total_file_lines} lines total)" - ) + if offset < 0: + # Negative offset: read from end + # -20 means "last 20 lines" → start from (total - 20) + start_line = max(0, total_file_lines + offset) + else: + # Positive offset: read from start (1-indexed) + start_line = max(0, offset - 1) # Convert to 0-indexed + if start_line >= total_file_lines: + return ToolResult.fail( + f"Error: Offset {offset} is beyond end of file ({total_file_lines} lines total)" + ) start_line_display = start_line + 1 # For display (1-indexed)