Debian Codegraph @

src/anthropic/lib/tools/_beta_builtin_memory_tool.py

raw
1 from __future__ import annotations
2
3 import os
4 import uuid
5 import shutil
6 from abc import abstractmethod
7 from typing import TYPE_CHECKING, Any, List, cast
8 from pathlib import Path
9 from typing_extensions import override, assert_never
10
11 from anyio import Path as AsyncPath
12 from anyio.to_thread import run_sync
13
14 from anthropic.types.beta import (
15 BetaMemoryTool20250818ViewCommand,
16 BetaMemoryTool20250818CreateCommand,
17 BetaMemoryTool20250818DeleteCommand,
18 BetaMemoryTool20250818InsertCommand,
19 BetaMemoryTool20250818RenameCommand,
20 BetaMemoryTool20250818StrReplaceCommand,
21 )
22
23 from ._files import read_text_exact
24 from ..._models import construct_type_unchecked
25 from ...types.beta import (
26 BetaMemoryTool20250818Param,
27 BetaMemoryTool20250818Command,
28 BetaCacheControlEphemeralParam,
29 BetaMemoryTool20250818ViewCommand,
30 BetaMemoryTool20250818CreateCommand,
31 BetaMemoryTool20250818DeleteCommand,
32 BetaMemoryTool20250818InsertCommand,
33 BetaMemoryTool20250818RenameCommand,
34 BetaMemoryTool20250818StrReplaceCommand,
35 )
36 from ._beta_functions import (
37 ToolError,
38 BetaBuiltinFunctionTool,
39 BetaFunctionToolResultType,
40 BetaAsyncBuiltinFunctionTool,
41 )
42
43 MAX_LINES = 999999
44 LINE_NUMBER_WIDTH = len(str(MAX_LINES))
45
46 # Owner read/write only. Avoids 0o666 which, in environments with a permissive
47 # umask (e.g. Docker where umask is often 0o000), would make memory files
48 # world-readable or even world-writable.
49 _FILE_CREATE_MODE = 0o600
50 # The default mkdir mode is 0o777, but we want to be more restrictive for memory
51 # directories to avoid them being world-accessible in environments with permissive umasks
52 # (eg Docker)
53 _DIR_CREATE_MODE = 0o700
54
55
56 class BetaAbstractMemoryTool(BetaBuiltinFunctionTool):
57 """Abstract base class for memory tool implementations.
58
59 This class provides the interface for implementing a custom memory backend for Claude.
60
61 Subclass this to create your own memory storage solution (e.g., database, cloud storage, encrypted files, etc.).
62
63 Example usage:
64
65 ```py
66 class MyMemoryTool(BetaAbstractMemoryTool):
67 def view(self, command: BetaMemoryTool20250818ViewCommand) -> BetaFunctionToolResultType:
68 ...
69 return "view result"
70
71 def create(self, command: BetaMemoryTool20250818CreateCommand) -> BetaFunctionToolResultType:
72 ...
73 return "created successfully"
74
75 # ... implement other abstract methods
76
77
78 client = Anthropic()
79 memory_tool = MyMemoryTool()
80 message = client.beta.messages.run_tools(
81 model="claude-sonnet-4-5",
82 messages=[{"role": "user", "content": "Remember that I like coffee"}],
83 tools=[memory_tool],
84 ).until_done()
85 ```
86 """
87
88 def __init__(self, *, cache_control: BetaCacheControlEphemeralParam | None = None) -> None:
89 super().__init__()
90 self._cache_control = cache_control
91
92 @override
93 def to_dict(self) -> BetaMemoryTool20250818Param:
94 param: BetaMemoryTool20250818Param = {"type": "memory_20250818", "name": "memory"}
95
96 if self._cache_control is not None:
97 param["cache_control"] = self._cache_control
98
99 return param
100
101 @override
102 def call(self, input: object) -> BetaFunctionToolResultType:
103 command = cast(
104 BetaMemoryTool20250818Command,
105 construct_type_unchecked(value=input, type_=cast(Any, BetaMemoryTool20250818Command)),
106 )
107 return self.execute(command)
108
109 def execute(self, command: BetaMemoryTool20250818Command) -> BetaFunctionToolResultType:
110 """Execute a memory command and return the result.
111
112 This method dispatches to the appropriate handler method based on the
113 command type (view, create, str_replace, insert, delete, rename).
114
115 You typically don't need to override this method.
116 """
117 if command.command == "view":
118 return self.view(command)
119 elif command.command == "create":
120 return self.create(command)
121 elif command.command == "str_replace":
122 return self.str_replace(command)
123 elif command.command == "insert":
124 return self.insert(command)
125 elif command.command == "delete":
126 return self.delete(command)
127 elif command.command == "rename":
128 return self.rename(command)
129 elif TYPE_CHECKING: # type: ignore[unreachable]
130 assert_never(command)
131 else:
132 raise NotImplementedError(f"Unknown command: {command.command}")
133
134 @abstractmethod
135 def view(self, command: BetaMemoryTool20250818ViewCommand) -> BetaFunctionToolResultType:
136 """View the contents of a memory path."""
137 pass
138
139 @abstractmethod
140 def create(self, command: BetaMemoryTool20250818CreateCommand) -> BetaFunctionToolResultType:
141 """Create a new memory file with the specified content."""
142 pass
143
144 @abstractmethod
145 def str_replace(self, command: BetaMemoryTool20250818StrReplaceCommand) -> BetaFunctionToolResultType:
146 """Replace text in a memory file."""
147 pass
148
149 @abstractmethod
150 def insert(self, command: BetaMemoryTool20250818InsertCommand) -> BetaFunctionToolResultType:
151 """Insert text at a specific line number in a memory file."""
152 pass
153
154 @abstractmethod
155 def delete(self, command: BetaMemoryTool20250818DeleteCommand) -> BetaFunctionToolResultType:
156 """Delete a memory file or directory."""
157 pass
158
159 @abstractmethod
160 def rename(self, command: BetaMemoryTool20250818RenameCommand) -> BetaFunctionToolResultType:
161 """Rename or move a memory file or directory."""
162 pass
163
164 def clear_all_memory(self) -> BetaFunctionToolResultType:
165 """Clear all memory data."""
166 raise NotImplementedError("clear_all_memory not implemented")
167
168
169 class BetaAsyncAbstractMemoryTool(BetaAsyncBuiltinFunctionTool):
170 """Abstract base class for memory tool implementations.
171
172 This class provides the interface for implementing a custom memory backend for Claude.
173
174 Subclass this to create your own memory storage solution (e.g., database, cloud storage, encrypted files, etc.).
175
176 Example usage:
177
178 ```py
179 class MyMemoryTool(BetaAbstractMemoryTool):
180 def view(self, command: BetaMemoryTool20250818ViewCommand) -> BetaFunctionToolResultType:
181 ...
182 return "view result"
183
184 def create(self, command: BetaMemoryTool20250818CreateCommand) -> BetaFunctionToolResultType:
185 ...
186 return "created successfully"
187
188 # ... implement other abstract methods
189
190
191 client = Anthropic()
192 memory_tool = MyMemoryTool()
193 message = client.beta.messages.run_tools(
194 model="claude-sonnet-4-5",
195 messages=[{"role": "user", "content": "Remember that I like coffee"}],
196 tools=[memory_tool],
197 ).until_done()
198 ```
199 """
200
201 def __init__(self, *, cache_control: BetaCacheControlEphemeralParam | None = None) -> None:
202 super().__init__()
203 self._cache_control = cache_control
204
205 @override
206 def to_dict(self) -> BetaMemoryTool20250818Param:
207 param: BetaMemoryTool20250818Param = {"type": "memory_20250818", "name": "memory"}
208
209 if self._cache_control is not None:
210 param["cache_control"] = self._cache_control
211
212 return param
213
214 @override
215 async def call(self, input: object) -> BetaFunctionToolResultType:
216 command = cast(
217 BetaMemoryTool20250818Command,
218 construct_type_unchecked(value=input, type_=cast(Any, BetaMemoryTool20250818Command)),
219 )
220 return await self.execute(command)
221
222 async def execute(self, command: BetaMemoryTool20250818Command) -> BetaFunctionToolResultType:
223 """Execute a memory command and return the result.
224
225 This method dispatches to the appropriate handler method based on the
226 command type (view, create, str_replace, insert, delete, rename).
227
228 You typically don't need to override this method.
229 """
230 if command.command == "view":
231 return await self.view(command)
232 elif command.command == "create":
233 return await self.create(command)
234 elif command.command == "str_replace":
235 return await self.str_replace(command)
236 elif command.command == "insert":
237 return await self.insert(command)
238 elif command.command == "delete":
239 return await self.delete(command)
240 elif command.command == "rename":
241 return await self.rename(command)
242 elif TYPE_CHECKING: # type: ignore[unreachable]
243 assert_never(command)
244 else:
245 raise NotImplementedError(f"Unknown command: {command.command}")
246
247 @abstractmethod
248 async def view(self, command: BetaMemoryTool20250818ViewCommand) -> BetaFunctionToolResultType:
249 """View the contents of a memory path."""
250 pass
251
252 @abstractmethod
253 async def create(self, command: BetaMemoryTool20250818CreateCommand) -> BetaFunctionToolResultType:
254 """Create a new memory file with the specified content."""
255 pass
256
257 @abstractmethod
258 async def str_replace(self, command: BetaMemoryTool20250818StrReplaceCommand) -> BetaFunctionToolResultType:
259 """Replace text in a memory file."""
260 pass
261
262 @abstractmethod
263 async def insert(self, command: BetaMemoryTool20250818InsertCommand) -> BetaFunctionToolResultType:
264 """Insert text at a specific line number in a memory file."""
265 pass
266
267 @abstractmethod
268 async def delete(self, command: BetaMemoryTool20250818DeleteCommand) -> BetaFunctionToolResultType:
269 """Delete a memory file or directory."""
270 pass
271
272 @abstractmethod
273 async def rename(self, command: BetaMemoryTool20250818RenameCommand) -> BetaFunctionToolResultType:
274 """Rename or move a memory file or directory."""
275 pass
276
277 async def clear_all_memory(self) -> BetaFunctionToolResultType:
278 """Clear all memory data."""
279 raise NotImplementedError("clear_all_memory not implemented")
280
281
282 def _atomic_write_file(target_path: Path, content: str) -> None:
283 dir_path = target_path.parent
284 temp_path = dir_path / f".tmp-{os.getpid()}-{uuid.uuid4()}"
285 data = content.encode("utf-8")
286
287 try:
288 fd = os.open(temp_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, _FILE_CREATE_MODE)
289 try:
290 offset = 0
291 while offset < len(data):
292 written = os.write(fd, data[offset:])
293 if written == 0:
294 raise OSError("os.write returned 0")
295 offset += written
296
297 os.fsync(fd)
298 finally:
299 os.close(fd)
300
301 os.replace(temp_path, target_path)
302 except Exception:
303 temp_path.unlink(missing_ok=True)
304 raise
305
306
307 def _secure_mkdir(path: Path, mode: int = _DIR_CREATE_MODE) -> None:
308 """Create `path` and any missing parents with `mode`, regardless of umask.
309
310 `Path.mkdir(parents=True, mode=...)` and `os.makedirs(mode=...)` apply the
311 requested mode only to the final (leaf) directory; intermediate parents are
312 created with the process umask default, which can be world-writable under a
313 permissive umask. We create each missing component explicitly so the entire
314 newly-created chain has restrictive permissions — closing a symlink-swap hole
315 where an attacker with write access to a world-writable parent could replace
316 the sandbox root and defeat path validation.
317 """
318 missing: list[Path] = []
319 current = path
320 while not current.exists():
321 missing.append(current)
322 parent = current.parent
323 if parent == current: # reached filesystem root
324 break
325 current = parent
326 for directory in reversed(missing):
327 try:
328 directory.mkdir(mode=mode)
329 except FileExistsError:
330 # Created concurrently between our exists() check and mkdir(); skip.
331 continue
332 # mkdir() is subject to umask; chmod is not. Enforce the exact mode so a
333 # restrictive umask can't strip owner bits. (We only chmod dirs we just
334 # created and therefore own — never pre-existing dirs.)
335 os.chmod(directory, mode)
336
337
338 def _validate_no_symlink_escape(target_path: Path, memory_root: Path) -> None:
339 resolved_root = memory_root.resolve()
340
341 current = target_path
342 while True:
343 try:
344 resolved = current.resolve()
345 if resolved != resolved_root and not str(resolved).startswith(str(resolved_root) + os.sep):
346 raise ToolError("Path would escape /memories directory via symlink")
347 return
348 except (FileNotFoundError, OSError):
349 parent = current.parent
350 if parent == current or current == memory_root:
351 return
352 current = parent
353
354
355 def _read_file_content(full_path: Path, memory_path: str) -> str:
356 try:
357 return read_text_exact(full_path)
358 except FileNotFoundError as err:
359 raise ToolError(
360 f"The file {memory_path} no longer exists (may have been deleted or renamed concurrently)."
361 ) from err
362
363
364 def _split_lines_keeping_cr(content: str) -> List[str]:
365 """Split on LF only (keeping any CR), without the empty tail a trailing newline leaves."""
366 lines = content.split("\n")
367 if lines[-1] == "":
368 lines.pop()
369 return lines
370
371
372 def _format_file_size(bytes_size: int) -> str:
373 if bytes_size == 0:
374 return "0B"
375 k = 1024
376 sizes = ["B", "K", "M", "G"]
377 i = int(bytes_size.bit_length() - 1) // 10
378 i = min(i, len(sizes) - 1)
379 size = bytes_size / (k**i)
380
381 if size == int(size):
382 return f"{int(size)}{sizes[i]}"
383 else:
384 return f"{size:.1f}{sizes[i]}"
385
386
387 class BetaLocalFilesystemMemoryTool(BetaAbstractMemoryTool):
388 """File-based memory storage implementation for Claude conversations"""
389
390 def __init__(self, base_path: str = "./memory"):
391 super().__init__()
392 self.base_path = Path(base_path)
393 self.memory_root = self.base_path / "memories"
394 _secure_mkdir(self.memory_root)
395
396 def _validate_path(self, path: str) -> Path:
397 """Validate and resolve memory paths"""
398 if not path.startswith("/memories"):
399 raise ToolError(f"Path must start with /memories, got: {path}")
400
401 relative_path = path[len("/memories") :].lstrip("/")
402 full_path = self.memory_root / relative_path if relative_path else self.memory_root
403
404 resolved_path = full_path.resolve()
405 resolved_root = self.memory_root.resolve()
406 if resolved_path != resolved_root and not str(resolved_path).startswith(str(resolved_root) + os.sep):
407 raise ToolError(f"Path {path} would escape /memories directory")
408
409 _validate_no_symlink_escape(resolved_path, self.memory_root)
410
411 return resolved_path
412
413 @override
414 def view(self, command: BetaMemoryTool20250818ViewCommand) -> str:
415 full_path = self._validate_path(command.path)
416
417 if not full_path.exists():
418 raise ToolError(f"The path {command.path} does not exist. Please provide a valid path.")
419
420 if full_path.is_dir():
421 items: List[tuple[str, str]] = []
422
423 def collect_items(dir_path: Path, relative_path: str, depth: int) -> None:
424 if depth > 2:
425 return
426
427 try:
428 dir_contents = sorted(dir_path.iterdir(), key=lambda x: x.name)
429 except Exception:
430 return
431
432 for item in dir_contents:
433 if item.name.startswith("."):
434 continue
435 item_relative_path = f"{relative_path}/{item.name}" if relative_path else item.name
436 try:
437 stat = item.stat()
438 except Exception:
439 continue
440
441 if item.is_dir():
442 items.append((_format_file_size(stat.st_size), f"{item_relative_path}/"))
443 if depth < 2:
444 collect_items(item, item_relative_path, depth + 1)
445 elif item.is_file():
446 items.append((_format_file_size(stat.st_size), item_relative_path))
447
448 collect_items(full_path, "", 1)
449
450 header = f"Here're the files and directories up to 2 levels deep in {command.path}, excluding hidden items:"
451 dir_stat = full_path.stat()
452 dir_size = _format_file_size(dir_stat.st_size)
453 lines = [f"{dir_size}\t{command.path}"]
454 lines.extend([f"{size}\t{command.path}/{path}" for size, path in items])
455
456 return f"{header}\n" + "\n".join(lines)
457
458 elif full_path.is_file():
459 content = _read_file_content(full_path, command.path)
460 lines = content.split("\n")
461
462 if len(lines) > MAX_LINES:
463 raise ToolError(f"File {command.path} exceeds maximum line limit of 999,999 lines.")
464
465 display_lines = lines
466 start_num = 1
467
468 if command.view_range and len(command.view_range) == 2:
469 start_line = max(1, command.view_range[0]) - 1
470 end_line = len(lines) if command.view_range[1] == -1 else command.view_range[1]
471 display_lines = lines[start_line:end_line]
472 start_num = start_line + 1
473
474 numbered_lines = [
475 f"{str(i + start_num).rjust(LINE_NUMBER_WIDTH)}\t{line}" for i, line in enumerate(display_lines)
476 ]
477
478 return f"Here's the content of {command.path} with line numbers:\n" + "\n".join(numbered_lines)
479 else:
480 raise ToolError(f"Unsupported file type for {command.path}")
481
482 @override
483 def create(self, command: BetaMemoryTool20250818CreateCommand) -> str:
484 full_path = self._validate_path(command.path)
485
486 _secure_mkdir(full_path.parent)
487
488 try:
489 fd = os.open(full_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, _FILE_CREATE_MODE)
490 try:
491 os.write(fd, command.file_text.encode("utf-8"))
492 os.fsync(fd)
493 finally:
494 os.close(fd)
495 except FileExistsError as err:
496 raise ToolError(f"File {command.path} already exists") from err
497
498 return f"File created successfully at: {command.path}"
499
500 @override
501 def str_replace(self, command: BetaMemoryTool20250818StrReplaceCommand) -> str:
502 full_path = self._validate_path(command.path)
503
504 if not full_path.exists():
505 raise ToolError(f"The path {command.path} does not exist. Please provide a valid path.")
506
507 if not full_path.is_file():
508 raise ToolError(f"The path {command.path} is not a file.")
509
510 content = _read_file_content(full_path, command.path)
511
512 count = content.count(command.old_str)
513 if count == 0:
514 raise ToolError(
515 f"No replacement was performed, old_str `{command.old_str}` did not appear verbatim in {command.path}."
516 )
517 elif count > 1:
518 matching_lines: List[int] = []
519 start = 0
520 while True:
521 pos = content.find(command.old_str, start)
522 if pos == -1:
523 break
524 matching_lines.append(content[:pos].count("\n") + 1)
525 start = pos + 1
526 raise ToolError(
527 f"No replacement was performed. Multiple occurrences of old_str `{command.old_str}` in lines: {', '.join(map(str, matching_lines))}. Please ensure it is unique"
528 )
529
530 pos = content.find(command.old_str)
531 changed_line_index = content[:pos].count("\n")
532 new_content = content.replace(command.old_str, command.new_str)
533 _atomic_write_file(full_path, new_content)
534
535 new_lines = new_content.split("\n")
536 context_start = max(0, changed_line_index - 2)
537 context_end = min(len(new_lines), changed_line_index + 3)
538 snippet = [
539 f"{str(line_num).rjust(LINE_NUMBER_WIDTH)}\t{new_lines[line_num - 1]}"
540 for line_num in range(context_start + 1, context_end + 1)
541 ]
542
543 return (
544 f"The memory file has been edited. Here is the snippet showing the change (with line numbers):\n"
545 + "\n".join(snippet)
546 )
547
548 @override
549 def insert(self, command: BetaMemoryTool20250818InsertCommand) -> str:
550 full_path = self._validate_path(command.path)
551
552 if not full_path.exists():
553 raise ToolError(f"The path {command.path} does not exist. Please provide a valid path.")
554
555 if not full_path.is_file():
556 raise ToolError(f"The path {command.path} is not a file.")
557
558 content = _read_file_content(full_path, command.path)
559 lines = _split_lines_keeping_cr(content)
560
561 if command.insert_line < 0 or command.insert_line > len(lines):
562 raise ToolError(
563 f"Invalid `insert_line` parameter: {command.insert_line}. "
564 f"It should be within the range [0, {len(lines)}]."
565 )
566
567 lines.insert(command.insert_line, command.insert_text.rstrip("\n"))
568 new_content = "\n".join(lines)
569 if not new_content.endswith("\n"):
570 new_content += "\n"
571 _atomic_write_file(full_path, content=new_content)
572 return f"The file {command.path} has been edited."
573
574 @override
575 def delete(self, command: BetaMemoryTool20250818DeleteCommand) -> str:
576 full_path = self._validate_path(command.path)
577
578 if command.path == "/memories":
579 raise ToolError("Cannot delete the /memories directory itself")
580
581 try:
582 if full_path.is_file():
583 full_path.unlink()
584 elif full_path.is_dir():
585 shutil.rmtree(full_path)
586 else:
587 raise ToolError(f"The path {command.path} does not exist")
588 except FileNotFoundError as err:
589 raise ToolError(f"The path {command.path} does not exist") from err
590
591 return f"Successfully deleted {command.path}"
592
593 @override
594 def rename(self, command: BetaMemoryTool20250818RenameCommand) -> str:
595 old_full_path = self._validate_path(command.old_path)
596 new_full_path = self._validate_path(command.new_path)
597
598 if new_full_path.exists():
599 raise ToolError(f"The destination {command.new_path} already exists")
600
601 _secure_mkdir(new_full_path.parent)
602
603 try:
604 old_full_path.rename(new_full_path)
605 except FileNotFoundError as err:
606 raise ToolError(f"The path {command.old_path} does not exist") from err
607
608 return f"Successfully renamed {command.old_path} to {command.new_path}"
609
610 @override
611 def clear_all_memory(self) -> str:
612 """Override the base implementation to provide file system clearing."""
613 if self.memory_root.exists():
614 shutil.rmtree(self.memory_root)
615 _secure_mkdir(self.memory_root)
616 return "All memory cleared"
617
618
619 async def _async_atomic_write_file(target_path: AsyncPath, content: str) -> None:
620 temp_path = target_path.parent / f".tmp-{os.getpid()}-{uuid.uuid4()}"
621 sync_target_path = Path(str(target_path))
622 sync_temp_path = Path(str(temp_path))
623 data = content.encode("utf-8")
624
625 try:
626
627 def write_replace_and_sync() -> None:
628 fd = os.open(sync_temp_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, _FILE_CREATE_MODE)
629 try:
630 offset = 0
631 while offset < len(data):
632 written = os.write(fd, data[offset:])
633 if written == 0:
634 raise OSError("os.write returned 0")
635 offset += written
636
637 os.fsync(fd)
638 finally:
639 os.close(fd)
640
641 os.replace(sync_temp_path, sync_target_path)
642
643 await run_sync(write_replace_and_sync)
644
645 except Exception:
646 await temp_path.unlink(missing_ok=True)
647 raise
648
649
650 async def _async_validate_no_symlink_escape(target_path: AsyncPath, memory_root: AsyncPath) -> None:
651 sync_target = Path(str(target_path))
652 sync_root = Path(str(memory_root))
653 await run_sync(_validate_no_symlink_escape, sync_target, sync_root)
654
655
656 async def _async_secure_mkdir(path: AsyncPath, mode: int = _DIR_CREATE_MODE) -> None:
657 await run_sync(_secure_mkdir, Path(str(path)), mode)
658
659
660 async def _async_read_file_content(full_path: AsyncPath, memory_path: str) -> str:
661 try:
662 return await run_sync(read_text_exact, Path(str(full_path)))
663 except FileNotFoundError as err:
664 raise ToolError(
665 f"The file {memory_path} no longer exists (may have been deleted or renamed concurrently)."
666 ) from err
667
668
669 class BetaAsyncLocalFilesystemMemoryTool(BetaAsyncAbstractMemoryTool):
670 """Async file-based memory storage implementation for Claude conversations"""
671
672 def __init__(self, base_path: str = "./memory"):
673 super().__init__()
674 self.base_path = AsyncPath(base_path)
675 self.memory_root = self.base_path / "memories"
676 # Note: Directory creation is deferred to async methods since __init__ can't be async
677
678 async def _ensure_memory_root(self) -> None:
679 """Ensure the memory root directory exists"""
680 await _async_secure_mkdir(self.memory_root)
681
682 async def _validate_path(self, path: str) -> AsyncPath:
683 """Validate and resolve memory paths"""
684 if not path.startswith("/memories"):
685 raise ToolError(f"Path must start with /memories, got: {path}")
686
687 relative_path = path[len("/memories") :].lstrip("/")
688 full_path = self.memory_root / relative_path if relative_path else self.memory_root
689
690 sync_memory_root = Path(str(self.memory_root))
691 sync_full_path = Path(str(full_path))
692
693 resolved_path = sync_full_path.resolve()
694 resolved_root = sync_memory_root.resolve()
695 if resolved_path != resolved_root and not str(resolved_path).startswith(str(resolved_root) + os.sep):
696 raise ToolError(f"Path {path} would escape /memories directory")
697
698 await _async_validate_no_symlink_escape(full_path, self.memory_root)
699
700 return AsyncPath(resolved_path)
701
702 @override
703 async def view(self, command: BetaMemoryTool20250818ViewCommand) -> str:
704 await self._ensure_memory_root()
705 full_path = await self._validate_path(command.path)
706
707 if not await full_path.exists():
708 raise ToolError(f"The path {command.path} does not exist. Please provide a valid path.")
709
710 if await full_path.is_dir():
711 items: List[tuple[str, str]] = []
712
713 async def collect_items(dir_path: AsyncPath, relative_path: str, depth: int) -> None:
714 if depth > 2:
715 return
716
717 try:
718 dir_items = [item async for item in dir_path.iterdir()]
719 dir_contents = sorted(dir_items, key=lambda x: x.name)
720 except Exception:
721 return
722
723 for item in dir_contents:
724 if item.name.startswith("."):
725 continue
726 item_relative_path = f"{relative_path}/{item.name}" if relative_path else item.name
727 try:
728 sync_item = Path(str(item))
729 stat = await run_sync(sync_item.stat)
730 except Exception:
731 continue
732
733 if await item.is_dir():
734 items.append((_format_file_size(stat.st_size), f"{item_relative_path}/"))
735 if depth < 2:
736 await collect_items(item, item_relative_path, depth + 1)
737 elif await item.is_file():
738 items.append((_format_file_size(stat.st_size), item_relative_path))
739
740 await collect_items(full_path, "", 1)
741
742 header = f"Here're the files and directories up to 2 levels deep in {command.path}, excluding hidden items:"
743 sync_full_path = Path(str(full_path))
744 dir_stat = await run_sync(sync_full_path.stat)
745 dir_size = _format_file_size(dir_stat.st_size)
746 lines = [f"{dir_size}\t{command.path}"]
747 lines.extend([f"{size}\t{command.path}/{path}" for size, path in items])
748
749 return f"{header}\n" + "\n".join(lines)
750
751 elif await full_path.is_file():
752 content = await _async_read_file_content(full_path, command.path)
753 lines = content.split("\n")
754
755 if len(lines) > MAX_LINES:
756 raise ToolError(f"File {command.path} exceeds maximum line limit of 999,999 lines.")
757
758 display_lines = lines
759 start_num = 1
760
761 if command.view_range and len(command.view_range) == 2:
762 start_line = max(1, command.view_range[0]) - 1
763 end_line = len(lines) if command.view_range[1] == -1 else command.view_range[1]
764 display_lines = lines[start_line:end_line]
765 start_num = start_line + 1
766
767 numbered_lines = [
768 f"{str(i + start_num).rjust(LINE_NUMBER_WIDTH)}\t{line}" for i, line in enumerate(display_lines)
769 ]
770
771 return f"Here's the content of {command.path} with line numbers:\n" + "\n".join(numbered_lines)
772 else:
773 raise ToolError(f"Unsupported file type for {command.path}")
774
775 @override
776 async def create(self, command: BetaMemoryTool20250818CreateCommand) -> str:
777 await self._ensure_memory_root()
778 full_path = await self._validate_path(command.path)
779
780 await _async_secure_mkdir(full_path.parent)
781
782 try:
783 sync_full_path = Path(str(full_path))
784
785 def create_exclusive() -> None:
786 fd = os.open(sync_full_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, _FILE_CREATE_MODE)
787 try:
788 os.write(fd, command.file_text.encode("utf-8"))
789 os.fsync(fd)
790 finally:
791 os.close(fd)
792
793 await run_sync(create_exclusive)
794 except FileExistsError as err:
795 raise ToolError(f"File {command.path} already exists") from err
796
797 return f"File created successfully at: {command.path}"
798
799 @override
800 async def str_replace(self, command: BetaMemoryTool20250818StrReplaceCommand) -> str:
801 await self._ensure_memory_root()
802 full_path = await self._validate_path(command.path)
803
804 if not await full_path.exists():
805 raise ToolError(f"The path {command.path} does not exist. Please provide a valid path.")
806
807 if not await full_path.is_file():
808 raise ToolError(f"The path {command.path} is not a file.")
809
810 content = await _async_read_file_content(full_path, command.path)
811
812 count = content.count(command.old_str)
813 if count == 0:
814 raise ToolError(
815 f"No replacement was performed, old_str `{command.old_str}` did not appear verbatim in {command.path}."
816 )
817 elif count > 1:
818 matching_lines: List[int] = []
819 start = 0
820 while True:
821 pos = content.find(command.old_str, start)
822 if pos == -1:
823 break
824 matching_lines.append(content[:pos].count("\n") + 1)
825 start = pos + 1
826 raise ToolError(
827 f"No replacement was performed. Multiple occurrences of old_str `{command.old_str}` in lines: {', '.join(map(str, matching_lines))}. Please ensure it is unique"
828 )
829
830 pos = content.find(command.old_str)
831 changed_line_index = content[:pos].count("\n")
832 new_content = content.replace(command.old_str, command.new_str)
833 await _async_atomic_write_file(full_path, new_content)
834
835 new_lines = new_content.split("\n")
836 context_start = max(0, changed_line_index - 2)
837 context_end = min(len(new_lines), changed_line_index + 3)
838 snippet = [
839 f"{str(line_num).rjust(LINE_NUMBER_WIDTH)}\t{new_lines[line_num - 1]}"
840 for line_num in range(context_start + 1, context_end + 1)
841 ]
842
843 return (
844 f"The memory file has been edited. Here is the snippet showing the change (with line numbers):\n"
845 + "\n".join(snippet)
846 )
847
848 @override
849 async def insert(self, command: BetaMemoryTool20250818InsertCommand) -> str:
850 await self._ensure_memory_root()
851 full_path = await self._validate_path(command.path)
852
853 if not await full_path.exists():
854 raise ToolError(f"The path {command.path} does not exist. Please provide a valid path.")
855
856 if not await full_path.is_file():
857 raise ToolError(f"The path {command.path} is not a file.")
858
859 content = await _async_read_file_content(full_path, command.path)
860 lines = _split_lines_keeping_cr(content)
861
862 if command.insert_line < 0 or command.insert_line > len(lines):
863 raise ToolError(
864 f"Invalid `insert_line` parameter: {command.insert_line}. "
865 f"It should be within the range [0, {len(lines)}]."
866 )
867
868 lines.insert(command.insert_line, command.insert_text.rstrip("\n"))
869 new_content = "\n".join(lines)
870 if not new_content.endswith("\n"):
871 new_content += "\n"
872 await _async_atomic_write_file(full_path, content=new_content)
873 return f"The file {command.path} has been edited."
874
875 @override
876 async def delete(self, command: BetaMemoryTool20250818DeleteCommand) -> str:
877 await self._ensure_memory_root()
878 full_path = await self._validate_path(command.path)
879
880 if command.path == "/memories":
881 raise ToolError("Cannot delete the /memories directory itself")
882
883 try:
884 if await full_path.is_file():
885 await full_path.unlink()
886 elif await full_path.is_dir():
887 await run_sync(shutil.rmtree, str(full_path))
888 else:
889 raise ToolError(f"The path {command.path} does not exist")
890 except FileNotFoundError as err:
891 raise ToolError(f"The path {command.path} does not exist") from err
892
893 return f"Successfully deleted {command.path}"
894
895 @override
896 async def rename(self, command: BetaMemoryTool20250818RenameCommand) -> str:
897 await self._ensure_memory_root()
898 old_full_path = await self._validate_path(command.old_path)
899 new_full_path = await self._validate_path(command.new_path)
900
901 if await new_full_path.exists():
902 raise ToolError(f"The destination {command.new_path} already exists")
903
904 await _async_secure_mkdir(new_full_path.parent)
905
906 try:
907 await old_full_path.rename(new_full_path)
908 except FileNotFoundError as err:
909 raise ToolError(f"The path {command.old_path} does not exist") from err
910
911 return f"Successfully renamed {command.old_path} to {command.new_path}"
912
913 @override
914 async def clear_all_memory(self) -> str:
915 """Override the base implementation to provide file system clearing."""
916 if await self.memory_root.exists():
917 await run_sync(shutil.rmtree, str(self.memory_root))
918 await _async_secure_mkdir(self.memory_root)
919 return "All memory cleared"