codenaut 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agent/__init__.py +1 -0
- agent/agent.py +236 -0
- agent/events.py +145 -0
- agent/persistence.py +123 -0
- agent/session.py +99 -0
- client/__init__.py +1 -0
- client/llm_client.py +266 -0
- client/response.py +88 -0
- codenaut-0.1.0.dist-info/METADATA +199 -0
- codenaut-0.1.0.dist-info/RECORD +63 -0
- codenaut-0.1.0.dist-info/WHEEL +5 -0
- codenaut-0.1.0.dist-info/entry_points.txt +3 -0
- codenaut-0.1.0.dist-info/licenses/LICENSE +21 -0
- codenaut-0.1.0.dist-info/top_level.txt +12 -0
- config/__init__.py +1 -0
- config/config.py +173 -0
- config/loader.py +173 -0
- context/__init__.py +1 -0
- context/compaction.py +96 -0
- context/loop_detector.py +49 -0
- context/manager.py +257 -0
- hooks/__init__.py +1 -0
- hooks/hook_system.py +140 -0
- main.py +422 -0
- prompts/__init__.py +1 -0
- prompts/system.py +380 -0
- safety/__init__.py +1 -0
- safety/approval.py +157 -0
- skills/__init__.py +9 -0
- skills/discovery.py +97 -0
- skills/models.py +14 -0
- skills/registry.py +56 -0
- tools/__init__.py +1 -0
- tools/base.py +200 -0
- tools/builtin/__init__.py +67 -0
- tools/builtin/apply_patch.py +388 -0
- tools/builtin/edit_file.py +211 -0
- tools/builtin/glob.py +80 -0
- tools/builtin/grep.py +117 -0
- tools/builtin/list_dir.py +60 -0
- tools/builtin/memory.py +115 -0
- tools/builtin/read_file.py +133 -0
- tools/builtin/shell.py +160 -0
- tools/builtin/tasks.py +336 -0
- tools/builtin/web_fetch.py +55 -0
- tools/builtin/web_search.py +60 -0
- tools/builtin/write_file.py +111 -0
- tools/discovery.py +70 -0
- tools/mcp/__init__.py +1 -0
- tools/mcp/client.py +127 -0
- tools/mcp/mcp_manager.py +83 -0
- tools/mcp/mcp_tool.py +51 -0
- tools/registry.py +156 -0
- tools/subagents.py +148 -0
- ui/__init__.py +12 -0
- ui/completer.py +160 -0
- ui/prompt.py +65 -0
- ui/tui.py +669 -0
- utils/__init__.py +1 -0
- utils/errors.py +49 -0
- utils/file_tags.py +83 -0
- utils/paths.py +40 -0
- utils/text.py +79 -0
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from tools.base import (
|
|
3
|
+
FileDiff,
|
|
4
|
+
Tool,
|
|
5
|
+
ToolConfirmation,
|
|
6
|
+
ToolInvocation,
|
|
7
|
+
ToolKind,
|
|
8
|
+
ToolResult,
|
|
9
|
+
)
|
|
10
|
+
from pydantic import BaseModel, Field
|
|
11
|
+
|
|
12
|
+
from utils.paths import ensure_parent_directory, resolve_path
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class EditParams(BaseModel):
|
|
16
|
+
path: str = Field(
|
|
17
|
+
...,
|
|
18
|
+
description="Path to the file to edit (relative to working directory or absolute path)",
|
|
19
|
+
)
|
|
20
|
+
old_string: str = Field(
|
|
21
|
+
"",
|
|
22
|
+
description="The exact text to find and replace. Must match exactly including all whitespace and indentation. For new files, leave this empty.",
|
|
23
|
+
)
|
|
24
|
+
new_string: str = Field(
|
|
25
|
+
...,
|
|
26
|
+
description="The text to replace old_string with. Can be empty to delete text",
|
|
27
|
+
)
|
|
28
|
+
replace_all: bool = Field(
|
|
29
|
+
False, description="Replace all occurrences of old_string (default: false)"
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class EditTool(Tool):
|
|
34
|
+
name = "edit"
|
|
35
|
+
description = (
|
|
36
|
+
"Edit a file by replacing text. The old_string must match exactly "
|
|
37
|
+
"(including whitespace and indentation) and must be unique in the file "
|
|
38
|
+
"unless replace_all is true. Use this for precise, surgical edits. "
|
|
39
|
+
"For creating new files or complete rewrites, use write_file instead."
|
|
40
|
+
)
|
|
41
|
+
kind = ToolKind.WRITE
|
|
42
|
+
schema = EditParams
|
|
43
|
+
|
|
44
|
+
async def get_confirmation(
|
|
45
|
+
self,
|
|
46
|
+
invocation: ToolInvocation,
|
|
47
|
+
) -> ToolConfirmation | None:
|
|
48
|
+
params = EditParams(**invocation.params)
|
|
49
|
+
path = resolve_path(invocation.cwd, params.path)
|
|
50
|
+
|
|
51
|
+
is_new_file = not path.exists()
|
|
52
|
+
|
|
53
|
+
if is_new_file:
|
|
54
|
+
diff = FileDiff(
|
|
55
|
+
path=path,
|
|
56
|
+
old_content="",
|
|
57
|
+
new_content=params.new_string,
|
|
58
|
+
is_new_file=True,
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
return ToolConfirmation(
|
|
62
|
+
tool_name=self.name,
|
|
63
|
+
params=invocation.params,
|
|
64
|
+
description=f"Create new file: {path}",
|
|
65
|
+
diff=diff,
|
|
66
|
+
affected_paths=[path],
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
old_content = path.read_text(encoding="utf-8")
|
|
70
|
+
|
|
71
|
+
if params.replace_all:
|
|
72
|
+
new_content = old_content.replace(params.old_string, params.new_string)
|
|
73
|
+
else:
|
|
74
|
+
new_content = old_content.replace(params.old_string, params.new_string, 1)
|
|
75
|
+
|
|
76
|
+
diff = FileDiff(
|
|
77
|
+
path=path,
|
|
78
|
+
old_content=old_content,
|
|
79
|
+
new_content=new_content,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
return ToolConfirmation(
|
|
83
|
+
tool_name=self.name,
|
|
84
|
+
params=invocation.params,
|
|
85
|
+
description=f"Edit file: {path}",
|
|
86
|
+
diff=diff,
|
|
87
|
+
affected_paths=[path],
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
async def execute(self, invocation: ToolInvocation) -> ToolResult:
|
|
91
|
+
params = EditParams(**invocation.params)
|
|
92
|
+
path = resolve_path(invocation.cwd, params.path)
|
|
93
|
+
|
|
94
|
+
if not path.exists():
|
|
95
|
+
if params.old_string:
|
|
96
|
+
return ToolResult.error_result(
|
|
97
|
+
f"File does not exist: {path}. To create a new file, use an empty old_string."
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
ensure_parent_directory(path)
|
|
101
|
+
path.write_text(params.new_string, encoding="utf-8")
|
|
102
|
+
|
|
103
|
+
line_count = len(params.new_string.splitlines())
|
|
104
|
+
|
|
105
|
+
return ToolResult.success_result(
|
|
106
|
+
f"Created {path} {line_count} lines",
|
|
107
|
+
diff=FileDiff(
|
|
108
|
+
path=path,
|
|
109
|
+
old_content="",
|
|
110
|
+
new_content=params.new_string,
|
|
111
|
+
is_new_file=True,
|
|
112
|
+
),
|
|
113
|
+
metadata={
|
|
114
|
+
"path": str(path),
|
|
115
|
+
"is_new_file": True,
|
|
116
|
+
"lines": line_count,
|
|
117
|
+
},
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
old_content = path.read_text(encoding="utf-8")
|
|
121
|
+
|
|
122
|
+
if not params.old_string:
|
|
123
|
+
return ToolResult.error_result(
|
|
124
|
+
"old_string is empty but file exists. Provide old_string to edit, or use write_file to overwrite."
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
occurrence_count = old_content.count(params.old_string)
|
|
128
|
+
|
|
129
|
+
if occurrence_count == 0:
|
|
130
|
+
return self._no_match_error(params.old_string, old_content, path)
|
|
131
|
+
|
|
132
|
+
if occurrence_count > 1 and not params.replace_all:
|
|
133
|
+
return ToolResult.error_result(
|
|
134
|
+
f"old_string found {occurrence_count} times in {path}. "
|
|
135
|
+
f"Either: \n"
|
|
136
|
+
f"1. Provide more context to make the match unique or\n"
|
|
137
|
+
f"2. Set replace_all=true to replace all occurrences",
|
|
138
|
+
metadata={
|
|
139
|
+
"occurence_count": occurrence_count,
|
|
140
|
+
},
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
if params.replace_all:
|
|
144
|
+
new_content = old_content.replace(params.old_string, params.new_string)
|
|
145
|
+
replace_count = occurrence_count
|
|
146
|
+
else:
|
|
147
|
+
new_content = old_content.replace(params.old_string, params.new_string, 1)
|
|
148
|
+
replace_count = 1
|
|
149
|
+
|
|
150
|
+
if new_content == old_content:
|
|
151
|
+
return ToolResult.error_result(
|
|
152
|
+
"No change made - old_string equals new_string"
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
try:
|
|
156
|
+
path.write_text(new_content, encoding="utf-8")
|
|
157
|
+
except IOError as e:
|
|
158
|
+
return ToolResult.error_result(f"failed to write file: {e}")
|
|
159
|
+
|
|
160
|
+
old_lines = len(old_content.splitlines())
|
|
161
|
+
new_lines = len(new_content.splitlines())
|
|
162
|
+
line_diff = new_lines - old_lines
|
|
163
|
+
|
|
164
|
+
diff_msg = ""
|
|
165
|
+
|
|
166
|
+
if line_diff > 0:
|
|
167
|
+
diff_msg = f" (+{line_diff} lines)"
|
|
168
|
+
elif line_diff < 0:
|
|
169
|
+
diff_msg = f" ({line_diff} lines)"
|
|
170
|
+
|
|
171
|
+
return ToolResult.success_result(
|
|
172
|
+
f"Edited {path}: replaced {replace_count} occurrence(s){diff_msg}",
|
|
173
|
+
diff=FileDiff(path=path, old_content=old_content, new_content=new_content),
|
|
174
|
+
metadata={
|
|
175
|
+
"path": str(path),
|
|
176
|
+
"replaced_count": replace_count,
|
|
177
|
+
"line_diff": line_diff,
|
|
178
|
+
},
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
def _no_match_error(self, old_string: str, content: str, path: Path) -> ToolResult:
|
|
182
|
+
lines = content.splitlines()
|
|
183
|
+
|
|
184
|
+
partial_matches = []
|
|
185
|
+
search_terms = old_string.split()[:5]
|
|
186
|
+
|
|
187
|
+
if search_terms:
|
|
188
|
+
first_term = search_terms[0]
|
|
189
|
+
for i, line in enumerate(lines, 1):
|
|
190
|
+
if first_term in line:
|
|
191
|
+
partial_matches.append((i, line.strip()[:80]))
|
|
192
|
+
if len(partial_matches) >= 3:
|
|
193
|
+
break
|
|
194
|
+
|
|
195
|
+
error_msg = f"old_string not found in {path}."
|
|
196
|
+
|
|
197
|
+
if partial_matches:
|
|
198
|
+
error_msg += "\n\nPossible similar lines:"
|
|
199
|
+
for line_num, line_preview in partial_matches:
|
|
200
|
+
error_msg += f"\n Line {line_num}: {line_preview}"
|
|
201
|
+
error_msg += "\n\nMake sure old_string matches exactly (including whitespace and indentation)."
|
|
202
|
+
else:
|
|
203
|
+
error_msg += (
|
|
204
|
+
" Make sure the text matches exactly, including:\n"
|
|
205
|
+
"- All whitespace and indentation\n"
|
|
206
|
+
"- Line breaks\n"
|
|
207
|
+
"- Any invisible characters\n"
|
|
208
|
+
"Try re-reading the file using read_file tool and then editing."
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
return ToolResult.error_result(error_msg)
|
tools/builtin/glob.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
import re
|
|
4
|
+
from tools.base import Tool, ToolInvocation, ToolKind, ToolResult
|
|
5
|
+
from pydantic import BaseModel, Field
|
|
6
|
+
|
|
7
|
+
from utils.paths import is_binary_file, resolve_path
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class GlobParams(BaseModel):
|
|
11
|
+
pattern: str = Field(..., description="Glob pattern to match")
|
|
12
|
+
path: str = Field(
|
|
13
|
+
".", description="Directory to search in (default: current directory)"
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class GlobTool(Tool):
|
|
18
|
+
name = "glob"
|
|
19
|
+
description = (
|
|
20
|
+
"Find files matching a glob pattern. Supports ** for recursive matching."
|
|
21
|
+
)
|
|
22
|
+
kind = ToolKind.READ
|
|
23
|
+
schema = GlobParams
|
|
24
|
+
|
|
25
|
+
async def execute(self, invocation: ToolInvocation) -> ToolResult:
|
|
26
|
+
params = GlobParams(**invocation.params)
|
|
27
|
+
|
|
28
|
+
search_path = resolve_path(invocation.cwd, params.path)
|
|
29
|
+
|
|
30
|
+
if not search_path.exists() or not search_path.is_dir():
|
|
31
|
+
return ToolResult.error_result(f"Directory does not exist: {search_path}")
|
|
32
|
+
|
|
33
|
+
try:
|
|
34
|
+
matches = list(search_path.glob(params.pattern))
|
|
35
|
+
matches = [p for p in matches if p.is_file()]
|
|
36
|
+
except Exception as e:
|
|
37
|
+
return ToolResult.error_result(f"Error searching: {e}")
|
|
38
|
+
|
|
39
|
+
output_lines = []
|
|
40
|
+
|
|
41
|
+
for file_path in matches[:1000]:
|
|
42
|
+
try:
|
|
43
|
+
rel_path = file_path.relative_to(invocation.cwd)
|
|
44
|
+
except Exception:
|
|
45
|
+
rel_path = file_path
|
|
46
|
+
|
|
47
|
+
output_lines.append(str(rel_path))
|
|
48
|
+
|
|
49
|
+
if len(matches) > 1000:
|
|
50
|
+
output_lines.append(f"...(limited to 1000 results)")
|
|
51
|
+
|
|
52
|
+
return ToolResult.success_result(
|
|
53
|
+
"\n".join(output_lines),
|
|
54
|
+
metadata={
|
|
55
|
+
"path": str(search_path),
|
|
56
|
+
"matches": len(matches),
|
|
57
|
+
},
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
def _find_files(self, search_path: Path) -> list[Path]:
|
|
61
|
+
files = []
|
|
62
|
+
|
|
63
|
+
for root, dirs, filenames in os.walk(search_path):
|
|
64
|
+
dirs[:] = [
|
|
65
|
+
d
|
|
66
|
+
for d in dirs
|
|
67
|
+
if d not in {"node_modules", "__pycache__", ".git", ".venv", "venv"}
|
|
68
|
+
]
|
|
69
|
+
|
|
70
|
+
for filename in filenames:
|
|
71
|
+
if filename.startswith("."):
|
|
72
|
+
continue
|
|
73
|
+
|
|
74
|
+
file_path = Path(root) / filename
|
|
75
|
+
if not is_binary_file(file_path):
|
|
76
|
+
files.append(file_path)
|
|
77
|
+
if len(files) >= 500:
|
|
78
|
+
return files
|
|
79
|
+
|
|
80
|
+
return files
|
tools/builtin/grep.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
import re
|
|
4
|
+
from tools.base import Tool, ToolInvocation, ToolKind, ToolResult
|
|
5
|
+
from pydantic import BaseModel, Field
|
|
6
|
+
|
|
7
|
+
from utils.paths import is_binary_file, resolve_path
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class GrepParams(BaseModel):
|
|
11
|
+
pattern: str = Field(..., description="Regular expression pattern to search for")
|
|
12
|
+
path: str = Field(
|
|
13
|
+
".", description="File or directory to search in (default: current directory)"
|
|
14
|
+
)
|
|
15
|
+
case_insensitive: bool = Field(
|
|
16
|
+
False,
|
|
17
|
+
description="Case-insensitive search (default: false)",
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class GrepTool(Tool):
|
|
22
|
+
name = "grep"
|
|
23
|
+
description = "Search for a regex pattern in file contents. Returns matching lines with file paths and line numbers."
|
|
24
|
+
kind = ToolKind.READ
|
|
25
|
+
schema = GrepParams
|
|
26
|
+
|
|
27
|
+
async def execute(self, invocation: ToolInvocation) -> ToolResult:
|
|
28
|
+
params = GrepParams(**invocation.params)
|
|
29
|
+
|
|
30
|
+
search_path = resolve_path(invocation.cwd, params.path)
|
|
31
|
+
|
|
32
|
+
if not search_path.exists():
|
|
33
|
+
return ToolResult.error_result(f"Path does not exist: {search_path}")
|
|
34
|
+
|
|
35
|
+
try:
|
|
36
|
+
flags = re.IGNORECASE if params.case_insensitive else 0
|
|
37
|
+
pattern = re.compile(params.pattern, flags)
|
|
38
|
+
except re.error as e:
|
|
39
|
+
return ToolResult.error_result(f"Invalid regex pattern: {e}")
|
|
40
|
+
|
|
41
|
+
if search_path.is_dir():
|
|
42
|
+
files = self._find_files(search_path)
|
|
43
|
+
else:
|
|
44
|
+
files = [search_path]
|
|
45
|
+
|
|
46
|
+
output_lines = []
|
|
47
|
+
matches = 0
|
|
48
|
+
|
|
49
|
+
for file_path in files:
|
|
50
|
+
try:
|
|
51
|
+
content = file_path.read_text(encoding="utf-8")
|
|
52
|
+
except Exception:
|
|
53
|
+
continue
|
|
54
|
+
|
|
55
|
+
lines = content.splitlines()
|
|
56
|
+
file_matches = False
|
|
57
|
+
|
|
58
|
+
# === path.py ===
|
|
59
|
+
# 1: async def execute()
|
|
60
|
+
# 30: async def execute()
|
|
61
|
+
|
|
62
|
+
# === path2.py ===
|
|
63
|
+
# 1: async def execute()
|
|
64
|
+
# 30: async def execute()
|
|
65
|
+
for i, line in enumerate(lines, start=1):
|
|
66
|
+
if pattern.search(line):
|
|
67
|
+
matches += 1
|
|
68
|
+
if not file_matches:
|
|
69
|
+
rel_path = file_path.relative_to(invocation.cwd)
|
|
70
|
+
output_lines.append(f"=== {rel_path} ===")
|
|
71
|
+
file_matches = True
|
|
72
|
+
|
|
73
|
+
output_lines.append(f"{i}:{line}")
|
|
74
|
+
|
|
75
|
+
if file_matches:
|
|
76
|
+
output_lines.append("")
|
|
77
|
+
|
|
78
|
+
if not output_lines:
|
|
79
|
+
return ToolResult.success_result(
|
|
80
|
+
f"No matches found for pattern '{params.pattern}'",
|
|
81
|
+
metadata={
|
|
82
|
+
"path": str(search_path),
|
|
83
|
+
"matches": 0,
|
|
84
|
+
"files_searched": len(files),
|
|
85
|
+
},
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
return ToolResult.success_result(
|
|
89
|
+
"\n".join(output_lines),
|
|
90
|
+
metadata={
|
|
91
|
+
"path": str(search_path),
|
|
92
|
+
"matches": matches,
|
|
93
|
+
"files_searched": len(files),
|
|
94
|
+
},
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
def _find_files(self, search_path: Path) -> list[Path]:
|
|
98
|
+
files = []
|
|
99
|
+
|
|
100
|
+
for root, dirs, filenames in os.walk(search_path):
|
|
101
|
+
dirs[:] = [
|
|
102
|
+
d
|
|
103
|
+
for d in dirs
|
|
104
|
+
if d not in {"node_modules", "__pycache__", ".git", ".venv", "venv"}
|
|
105
|
+
]
|
|
106
|
+
|
|
107
|
+
for filename in filenames:
|
|
108
|
+
if filename.startswith("."):
|
|
109
|
+
continue
|
|
110
|
+
|
|
111
|
+
file_path = Path(root) / filename
|
|
112
|
+
if not is_binary_file(file_path):
|
|
113
|
+
files.append(file_path)
|
|
114
|
+
if len(files) >= 500:
|
|
115
|
+
return files
|
|
116
|
+
|
|
117
|
+
return files
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
from tools.base import Tool, ToolInvocation, ToolKind, ToolResult
|
|
2
|
+
from pydantic import BaseModel, Field
|
|
3
|
+
|
|
4
|
+
from utils.paths import resolve_path
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class ListDirParams(BaseModel):
|
|
8
|
+
path: str = Field(
|
|
9
|
+
".", description="Directory path to list (default: current directory)"
|
|
10
|
+
)
|
|
11
|
+
include_hidden: bool = Field(
|
|
12
|
+
False,
|
|
13
|
+
description="Whether to include hidden files and directories (default: false",
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ListDirTool(Tool):
|
|
18
|
+
name = "list_dir"
|
|
19
|
+
description = "List contents of a directory"
|
|
20
|
+
kind = ToolKind.READ
|
|
21
|
+
schema = ListDirParams
|
|
22
|
+
|
|
23
|
+
async def execute(self, invocation: ToolInvocation) -> ToolResult:
|
|
24
|
+
params = ListDirParams(**invocation.params)
|
|
25
|
+
|
|
26
|
+
dir_path = resolve_path(invocation.cwd, params.path)
|
|
27
|
+
|
|
28
|
+
if not dir_path.exists() or not dir_path.is_dir():
|
|
29
|
+
return ToolResult.error_result(f"Directory does not exist: {dir_path}")
|
|
30
|
+
|
|
31
|
+
try:
|
|
32
|
+
items = sorted(
|
|
33
|
+
dir_path.iterdir(), key=lambda p: (not p.is_dir(), p.name.lower())
|
|
34
|
+
)
|
|
35
|
+
except Exception as e:
|
|
36
|
+
return ToolResult.error_result(f"Error listing directory: {e}")
|
|
37
|
+
|
|
38
|
+
if not params.include_hidden:
|
|
39
|
+
items = [item for item in items if not item.name.startswith(".")]
|
|
40
|
+
|
|
41
|
+
if not items:
|
|
42
|
+
return ToolResult.success_result(
|
|
43
|
+
"Directory is empty", metadata={"path": str(dir_path), "entries": 0}
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
lines = []
|
|
47
|
+
|
|
48
|
+
for item in items:
|
|
49
|
+
if item.is_dir():
|
|
50
|
+
lines.append(f"{item.name}/")
|
|
51
|
+
else:
|
|
52
|
+
lines.append(item.name)
|
|
53
|
+
|
|
54
|
+
return ToolResult.success_result(
|
|
55
|
+
"\n".join(lines),
|
|
56
|
+
metadata={
|
|
57
|
+
"path": str(dir_path),
|
|
58
|
+
"entries": len(items),
|
|
59
|
+
},
|
|
60
|
+
)
|
tools/builtin/memory.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import uuid
|
|
3
|
+
from config.config import Config
|
|
4
|
+
from config.loader import get_data_dir
|
|
5
|
+
from tools.base import Tool, ToolInvocation, ToolKind, ToolResult
|
|
6
|
+
from pydantic import BaseModel, Field
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class MemoryParams(BaseModel):
|
|
10
|
+
action: str = Field(
|
|
11
|
+
..., description="Action: 'set', 'get', 'delete', 'list', 'clear'"
|
|
12
|
+
)
|
|
13
|
+
key: str | None = Field(
|
|
14
|
+
None, description="Memory key (required for `set`, `get`, `delete`)"
|
|
15
|
+
)
|
|
16
|
+
value: str | None = Field(None, description="Value to store (required for `set`)")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class MemoryTool(Tool):
|
|
20
|
+
name = "memory"
|
|
21
|
+
description = "Store and retrieve persistent memory. Use this to remember user preferences, important context or notes."
|
|
22
|
+
kind = ToolKind.MEMORY
|
|
23
|
+
schema = MemoryParams
|
|
24
|
+
|
|
25
|
+
def _load_memory(self) -> dict:
|
|
26
|
+
data_dir = get_data_dir()
|
|
27
|
+
data_dir.mkdir(parents=True, exist_ok=True)
|
|
28
|
+
path = data_dir / "user_memory.json"
|
|
29
|
+
|
|
30
|
+
if not path.exists():
|
|
31
|
+
return {"entries": {}}
|
|
32
|
+
|
|
33
|
+
try:
|
|
34
|
+
content = path.read_text(encoding="utf-8")
|
|
35
|
+
return json.loads(content)
|
|
36
|
+
except Exception:
|
|
37
|
+
return {"entries": {}}
|
|
38
|
+
|
|
39
|
+
def _save_memory(self, memory: dict) -> None:
|
|
40
|
+
data_dir = get_data_dir()
|
|
41
|
+
data_dir.mkdir(parents=True, exist_ok=True)
|
|
42
|
+
path = data_dir / "user_memory.json"
|
|
43
|
+
|
|
44
|
+
path.write_text(json.dumps(memory, indent=2, ensure_ascii=False))
|
|
45
|
+
|
|
46
|
+
async def execute(self, invocation: ToolInvocation) -> ToolResult:
|
|
47
|
+
params = MemoryParams(**invocation.params)
|
|
48
|
+
|
|
49
|
+
if params.action.lower() == "set":
|
|
50
|
+
if not params.key or not params.value:
|
|
51
|
+
return ToolResult.error_result(
|
|
52
|
+
"`key` and `value` are required for 'set' action"
|
|
53
|
+
)
|
|
54
|
+
memory = self._load_memory()
|
|
55
|
+
memory["entries"][params.key] = params.value
|
|
56
|
+
self._save_memory(memory)
|
|
57
|
+
|
|
58
|
+
return ToolResult.success_result(f"Set memory: {params.key}")
|
|
59
|
+
elif params.action.lower() == "get":
|
|
60
|
+
if not params.key:
|
|
61
|
+
return ToolResult.error_result("`key` required for 'get' action")
|
|
62
|
+
|
|
63
|
+
memory = self._load_memory()
|
|
64
|
+
if params.key not in memory.get("entries", {}):
|
|
65
|
+
return ToolResult.success_result(
|
|
66
|
+
f"Memory not found: {params.key}",
|
|
67
|
+
metadata={
|
|
68
|
+
"found": False,
|
|
69
|
+
},
|
|
70
|
+
)
|
|
71
|
+
return ToolResult.success_result(
|
|
72
|
+
f"Memory found: {params.key}: {memory['entries'][params.key]}",
|
|
73
|
+
metadata={
|
|
74
|
+
"found": True,
|
|
75
|
+
},
|
|
76
|
+
)
|
|
77
|
+
elif params.action == "delete":
|
|
78
|
+
if not params.key:
|
|
79
|
+
return ToolResult.error_result("`key` required for 'get' action")
|
|
80
|
+
memory = self._load_memory()
|
|
81
|
+
if params.key not in memory.get("entries", {}):
|
|
82
|
+
return ToolResult.success_result(f"Memory not found: {params.key}")
|
|
83
|
+
|
|
84
|
+
del memory["entries"][params.key]
|
|
85
|
+
self._save_memory(memory)
|
|
86
|
+
|
|
87
|
+
return ToolResult.success_result(f"Deleted memory: {params.key}")
|
|
88
|
+
elif params.action == "list":
|
|
89
|
+
memory = self._load_memory()
|
|
90
|
+
entries = memory.get("entries", {})
|
|
91
|
+
if not entries:
|
|
92
|
+
return ToolResult.success_result(
|
|
93
|
+
f"No memories stored",
|
|
94
|
+
metadata={
|
|
95
|
+
"found": False,
|
|
96
|
+
},
|
|
97
|
+
)
|
|
98
|
+
lines = [f"Stored memories:"]
|
|
99
|
+
for key, value in sorted(entries.items()):
|
|
100
|
+
lines.append(f" {key}: {value}")
|
|
101
|
+
|
|
102
|
+
return ToolResult.success_result(
|
|
103
|
+
"\n".join(lines),
|
|
104
|
+
metadata={
|
|
105
|
+
"found": True,
|
|
106
|
+
},
|
|
107
|
+
)
|
|
108
|
+
elif params.action == "clear":
|
|
109
|
+
memory = self._load_memory()
|
|
110
|
+
count = len(memory.get("entries", {}))
|
|
111
|
+
memory["entries"] = {}
|
|
112
|
+
self._save_memory(memory)
|
|
113
|
+
return ToolResult.success_result(f"Cleared {count} memory entries")
|
|
114
|
+
else:
|
|
115
|
+
return ToolResult.error_result(f"Unknown action: {params.action}")
|