File size: 3,125 Bytes
93be2a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import json
import os
from pathlib import Path
from typing import Any, Dict, List

from .registry import ToolRegistry


ALLOWED_ROOTS = [p for p in os.getenv("ALLOWED_ROOTS", "/data:/data/adaptai/projects/elizabeth").split(":") if p]


def _is_allowed(path: Path) -> bool:
    try:
        rp = path.resolve()
    except Exception:
        return False
    for root in ALLOWED_ROOTS:
        try:
            if str(rp).startswith(str(Path(root).resolve())):
                return True
        except Exception:
            continue
    return False


def t_file_read(args: Dict[str, Any]) -> str:
    p = Path(str(args.get("path", "")))
    if not _is_allowed(p):
        return json.dumps({"error": f"path not allowed: {p}"})
    try:
        text = p.read_text(encoding="utf-8")
        return json.dumps({"path": str(p), "content": text})
    except Exception as e:
        return json.dumps({"error": str(e)})


def t_file_write(args: Dict[str, Any]) -> str:
    p = Path(str(args.get("path", "")))
    content = args.get("content")
    if not isinstance(content, str):
        return json.dumps({"error": "content must be string"})
    if not _is_allowed(p):
        return json.dumps({"error": f"path not allowed: {p}"})
    try:
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_text(content, encoding="utf-8")
        return json.dumps({"path": str(p), "bytes": len(content.encode("utf-8"))})
    except Exception as e:
        return json.dumps({"error": str(e)})


def t_file_list(args: Dict[str, Any]) -> str:
    p = Path(str(args.get("path", "/data")))
    if not _is_allowed(p):
        return json.dumps({"error": f"path not allowed: {p}"})
    try:
        entries: List[Dict[str, Any]] = []
        for child in p.iterdir():
            try:
                st = child.stat()
                entries.append({
                    "path": str(child),
                    "is_dir": child.is_dir(),
                    "size": st.st_size,
                    "mtime": st.st_mtime,
                })
            except Exception:
                continue
        return json.dumps({"path": str(p), "entries": entries[:500]})
    except Exception as e:
        return json.dumps({"error": str(e)})


def register_tools(reg: ToolRegistry) -> None:
    reg.register(
        name="file_read",
        description="Read a text file within allowed roots (/data, project dir).",
        parameters={"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]},
        handler=t_file_read,
    )
    reg.register(
        name="file_write",
        description="Write a text file within allowed roots (/data, project dir).",
        parameters={"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}}, "required": ["path", "content"]},
        handler=t_file_write,
    )
    reg.register(
        name="file_list",
        description="List directory entries within allowed roots.",
        parameters={"type": "object", "properties": {"path": {"type": "string"}}},
        handler=t_file_list,
    )