-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathfs.py
More file actions
387 lines (331 loc) · 12.3 KB
/
Copy pathfs.py
File metadata and controls
387 lines (331 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
import logging
from dataclasses import dataclass
from pydantic import BaseModel, Field
from pydantic_ai import FunctionToolset, ModelRetry, RunContext, Tool
from surrealdb import RecordID
from tools.deps import Deps
from kaig.definitions import OriginalDocument
logger = logging.getLogger(__name__)
@dataclass
class FileEntry:
id: RecordID
path: str
content_type: str
content: str | None = None
class CatArgs(BaseModel):
path: str = Field(..., description="File to read")
async def cat(
context: RunContext[Deps],
args: CatArgs,
) -> str:
"""
Read the full contents of a file and return it as text.
Usage: provide an absolute path or one relative to the current working directory.
Errors: returns an error when the path does not exist or targets a directory.
"""
if not args.path.startswith("/"):
args.path = "/" + args.path
result = context.deps.db.query_one(
"SELECT * FROM ONLY file WHERE path = $path LIMIT 1",
{"path": args.path},
OriginalDocument,
)
if result is None:
return f"File not found: {args.path}"
return (
result.content
or f"Error: content type is not text/plain {result.content_type}"
)
async def ls(
context: RunContext[Deps],
*,
path: str = "/",
all: bool = False,
long: bool = False,
recursive: bool = False,
dir_only: bool = False,
human: bool = False,
) -> str:
"""
List files with optional recursion and size details.
Usage: set `path` absolute or relative; `all` shows dotfiles; `long` adds byte sizes; `recursive` descends directories; `dir_only` filters to directories; `human` reports base-1024 sizes.
"""
# Normalize prefix: must start and end with "/"
if not path.startswith("/"):
path = "/" + path
if not path.endswith("/"):
path = path + "/"
entries = context.deps.db.query(
"SELECT id, path, content_type, content FROM file WHERE string::starts_with(path OR '', $prefix)",
{"prefix": path},
FileEntry,
)
if not entries:
return "(empty)"
def _fmt_size(n: int) -> str:
if not human:
return str(n)
for unit in ("B", "K", "M", "G", "T"):
if n < 1024:
return f"{n}{unit}"
n //= 1024
return f"{n}P"
if recursive:
lines: list[str] = []
for e in entries:
rel = e.path[len(path) :]
if not all and any(seg.startswith(".") for seg in rel.split("/")):
continue
if dir_only:
continue # no directories in flat file store
if long:
size = len(e.content) if e.content else 0
lines.append(f"{_fmt_size(size):>8} {e.path}")
else:
lines.append(e.path)
return "\n".join(lines) if lines else "(empty)"
# Non-recursive: show only immediate children (files and "directories")
seen_dirs: set[str] = set()
file_lines: list[str] = []
dir_lines: list[str] = []
for e in entries:
rel = e.path[len(path) :] # relative path under prefix
if not rel:
continue
slash_pos = rel.find("/")
if slash_pos == -1:
# Direct child file
name = rel
if not all and name.startswith("."):
continue
if dir_only:
continue
if long:
size = len(e.content) if e.content else 0
file_lines.append(f"{_fmt_size(size):>8} {name}")
else:
file_lines.append(name)
else:
# Child in a subdirectory
dirname = rel[:slash_pos] + "/"
if not all and dirname.startswith("."):
continue
if dirname in seen_dirs:
continue
seen_dirs.add(dirname)
if long:
dir_lines.append(f"{'':>8} {dirname}")
else:
dir_lines.append(dirname)
result = sorted(dir_lines) + sorted(file_lines)
return "\n".join(result) if result else "(empty)"
class WriteFileArgs(BaseModel):
path: str = Field(..., description="Destination path")
content: str = Field(..., description="File contents to write")
async def write_file(context: RunContext[Deps], args: WriteFileArgs) -> str:
"""
Write markdown content to the given path, creating or replacing the file.
Usage: provide `path` absolute or relative; `content` is written exactly as supplied. Missing parent directories are created automatically.
Notes: overwrites existing files.
"""
path = args.path
if not path.startswith("/"):
path = "/" + path
filename = path.rsplit("/", 1)[-1]
parent_path = path.rsplit("/", 1)[0] or "/"
parent_rec_id: RecordID | None = None
# Ensure all ancestor directories exist, creating them if necessary
if parent_path != "/":
segments = [s for s in parent_path.split("/") if s]
current_parent_id: RecordID | None = None
for i, segment in enumerate(segments):
partial_path = "/" + "/".join(segments[: i + 1])
existing_dir = context.deps.db.query(
"SELECT id, path, content_type FROM file WHERE path = $path",
{"path": partial_path},
FileEntry,
)
if existing_dir:
if existing_dir[0].content_type != "folder":
return (
f"ERROR: Path already exists as a file: {partial_path}"
)
current_parent_id = existing_dir[0].id
else:
_ = context.deps.db.sync_conn.query(
"CREATE file CONTENT $content",
{
"content": {
"filename": segment,
"content_type": "folder",
"parent": current_parent_id,
}
},
)
new_dir = context.deps.db.query(
"SELECT id, path, content_type FROM file WHERE path = $path",
{"path": partial_path},
FileEntry,
)
current_parent_id = new_dir[0].id
parent_rec_id = current_parent_id
# Check if path already exists
existing = context.deps.db.query(
"SELECT id, path, content_type FROM file WHERE path = $path",
{"path": path},
FileEntry,
)
content_type = "text/markdown"
if (
args.content[:50]
.strip()
.lower()
.startswith(("<html", "<!doctype html"))
):
content_type = "text/html"
if existing:
if existing[0].content_type == "folder":
return f"ERROR: Path is a directory: {path}"
_ = context.deps.db.sync_conn.query(
"UPDATE file SET content = $content, content_type = $content_type, flow_chunked = NONE, flow_keywords = NONE, updated_at = time::now() WHERE path = $path",
{
"path": path,
"content": args.content,
"content_type": content_type,
},
)
_ = context.deps.db.sync_conn.query(
"DELETE chunk WHERE doc = $doc",
{"doc": existing[0].id},
)
return f"Updated: {path}"
else:
res = context.deps.db.sync_conn.query(
"CREATE file CONTENT $content",
{
"content": {
"filename": filename,
"parent": parent_rec_id,
"content_type": content_type,
"content": args.content,
}
},
)
logger.debug(f"Created file: {res}")
return f"Created: {path}"
class EditArgs(BaseModel):
path: str = Field(..., description="File to edit")
old: str = Field(..., description="Substring or pattern to replace")
new: str = Field(..., description="Replacement text")
replace_all: bool = Field(
False,
description="Replace all occurrences (default replaces first only)",
)
async def edit(ctx: RunContext[Deps], *, args: EditArgs) -> str:
"""
Replace text inside a SurrealFs file. Provide the target path, the text to find, and the replacement text. Set `replace_all` to true to replace every occurrence; otherwise only the first match is replaced.
Usage:
- `path`: absolute or relative to the current working directory inside SurrealFs.
- `old`: substring or pattern to replace.
- `new`: replacement text.
- `replace_all`: boolean, default false.
Common errors:
- Path does not exist or points to a directory.
- No occurrence of `old` found (operation may return unchanged content).
"""
path = args.path
if not path.startswith("/"):
path = "/" + path
existing = ctx.deps.db.query(
"SELECT id, path, content_type, content FROM file WHERE path = $path",
{"path": path},
FileEntry,
)
if not existing:
raise ModelRetry(f"ERROR: File not found: {path}")
if existing[0].content_type == "folder":
raise ModelRetry(f"ERROR: Path is a directory: {path}")
current = existing[0].content or ""
if args.old not in current:
raise ModelRetry(f"ERROR: Text not found in {path}: {args.old!r}")
if args.replace_all:
updated = current.replace(args.old, args.new)
else:
updated = current.replace(args.old, args.new, 1)
file_id = existing[0].id
_ = ctx.deps.db.sync_conn.query(
"UPDATE file SET content = $content, flow_chunked = NONE, flow_keywords = NONE, updated_at = time::now() WHERE path = $path",
{"path": path, "content": updated},
)
_ = ctx.deps.db.sync_conn.query(
"DELETE chunk WHERE doc = $doc",
{"doc": file_id},
)
return f"Edited: {path}"
class MkdirArgs(BaseModel):
path: str = Field(
..., description="Directory path to create (parents included)"
)
parents: bool = Field(
False, description="Create parent directories as needed"
)
async def mkdir(ctx: RunContext[Deps], *, args: MkdirArgs) -> str:
"""
Create a directory and any missing parent directories.
Usage: pass the desired path, absolute or relative to the current working directory.
Errors: fails if the path already exists as a file.
"""
path = args.path
if not path.startswith("/"):
path = "/" + path
path = path.rstrip("/") or "/"
if path == "/":
return "/"
segments = [s for s in path.split("/") if s]
created: list[str] = []
current_parent_id: RecordID | None = None
select_file_query = (
"SELECT id, path, content_type FROM file WHERE path = $path"
)
for i, segment in enumerate(segments):
partial_path = "/" + "/".join(segments[: i + 1])
is_last = i == len(segments) - 1
existing = ctx.deps.db.query(
select_file_query, {"path": partial_path}, FileEntry
)
if existing:
if existing[0].content_type != "folder":
return f"ERROR: Path already exists as a file: {partial_path}"
current_parent_id = existing[0].id
else:
if not is_last and not args.parents:
raise ModelRetry(
f"ERROR: Parent directory does not exist: {partial_path}. Pass parents=true to create it."
)
_ = ctx.deps.db.sync_conn.query(
"CREATE file CONTENT $content",
{
"content": {
"filename": segment,
"content_type": "folder",
"parent": current_parent_id,
}
},
)
created.append(partial_path)
new_dir = ctx.deps.db.query(
select_file_query, {"path": partial_path}, FileEntry
)
current_parent_id = new_dir[0].id
if created:
return "Created: " + ", ".join(created)
return f"Directory already exists: {path}"
def build_fs_toolset() -> FunctionToolset[Deps]:
tools = [
Tool(cat, takes_ctx=True),
Tool(ls, takes_ctx=True),
Tool(write_file, takes_ctx=True),
Tool(edit, takes_ctx=True),
Tool(mkdir, takes_ctx=True),
]
return FunctionToolset(tools)