File size: 11,617 Bytes
c422cb9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Atlas Agent Host - güvenli sandbox ortamında çalışan komut aracısı.

Modelin ürettiği tool çağrılarını alır, güvenlik kurallarına göre filtreler
ve yalnızca yetkili işlemleri çalıştırır. Tüm eylemler audit log'a yazılır.

Güvenlik kuralları:
  - Yalnızca ~/atlas-workspace dizini içinde işlem yapılabilir
  - Sistem yolları yasaktır: /etc, /usr, /bin, /boot, /proc, /sys, /dev, /var, /root
  - root/sudo komutları çalıştırılamaz
  - Tehlikeli komutlar (rm -rf /, dd, mkfs, :(){:|:&};:) engellenir
  - Çalıştırılan her komut kullanıcı onayına sunulur (onay modu)
"""

import argparse
import json
import os
import re
import shlex
import subprocess
import sys
import time
import urllib.request
from datetime import datetime
from pathlib import Path

WORKSPACE = Path(os.path.expanduser("~/atlas-workspace")).resolve()
OLLAMA_URL = os.environ.get("OLLAMA_URL", "http://localhost:11434/api/chat")
MODEL = os.environ.get("ATLAS_MODEL", "atlas-q4km")
AUDIT_LOG = Path(os.path.expanduser("~/atlas-workspace/audit.log"))

FORBIDDEN_PATHS = [
    "/etc", "/usr", "/bin", "/boot", "/proc", "/sys", "/dev", "/var",
    "/root", "/run", "/sbin", "/lib", "/opt",
]
FORBIDDEN_CMDS = [
    r"\brm\s+-rf\s+/", r"\brm\s+-rf\s+~", r"\bdd\b", r"\bmkfs", r"\bchmod\s+777\s+/",
    r"\{\s*:\|\s*:\s*&\s*\}\s*;", r"\b:\(\)\s*\{", r"\bmount\b", r"\bumount\b",
    r"\bkillall", r"\bkill\b", r"\bshutdown", r"\breboot", r"\bhalt\b",
    r"\bwget.*/dev/sd", r"\bcurl.*/dev/sd", r"\bsudo\b", r"\bsu\b",
]

TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "list_files",
            "description": "Belirtilen dizindeki dosyaları listeler",
            "parameters": {
                "type": "object",
                "properties": {"path": {"type": "string", "description": "Dizin yolu (yalnızca ~/atlas-workspace içinde)"}},
                "required": ["path"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "read_file",
            "description": "Bir dosyanın içeriğini okur",
            "parameters": {
                "type": "object",
                "properties": {"path": {"type": "string", "description": "Dosya yolu (yalnızca ~/atlas-workspace içinde)"}},
                "required": ["path"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "write_file",
            "description": "Bir dosyaya içerik yazar (varsa üzerine yazar)",
            "parameters": {
                "type": "object",
                "properties": {
                    "path": {"type": "string", "description": "Dosya yolu"},
                    "content": {"type": "string", "description": "Yazılacak içerik"},
                },
                "required": ["path", "content"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "append_file",
            "description": "Bir dosyanın sonuna içerik ekler",
            "parameters": {
                "type": "object",
                "properties": {
                    "path": {"type": "string", "description": "Dosya yolu"},
                    "content": {"type": "string", "description": "Eklenecek içerik"},
                },
                "required": ["path", "content"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "make_dir",
            "description": "Yeni bir dizin oluşturur",
            "parameters": {
                "type": "object",
                "properties": {"path": {"type": "string", "description": "Oluşturulacak dizin yolu"}},
                "required": ["path"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "run_command",
            "description": "Güvenli bir terminal komutu çalıştırır (salt okunur komutlar önerilir: ls, cat, grep, find, date, uptime, du, df, whoami)",
            "parameters": {
                "type": "object",
                "properties": {"cmd": {"type": "string", "description": "Çalıştırılacak komut"}},
                "required": ["cmd"],
            },
        },
    },
]


def audit(action, detail=""):
    AUDIT_LOG.parent.mkdir(parents=True, exist_ok=True)
    ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    line = f"[{ts}] {action} {detail}"
    with open(AUDIT_LOG, "a", encoding="utf-8") as f:
        f.write(line + "\n")
    print(line)


def resolve_path(path):
    p = Path(os.path.expanduser(path))
    if not p.is_absolute():
        p = WORKSPACE / p
    p = p.resolve()
    if not str(p).startswith(str(WORKSPACE)):
        raise PermissionError(f"ERİŞİM REDDEDİLDİ: '{path}' çalışma alanı dışında")
    for fp in FORBIDDEN_PATHS:
        if str(p) == fp or str(p).startswith(fp + "/"):
            raise PermissionError(f"ERİŞİM REDDEDİLDİ: '{path}' sistem yolu")
    return p


def check_command(cmd):
    for pat in FORBIDDEN_CMDS:
        if re.search(pat, cmd):
            raise PermissionError(f"KOMUT REDDEDİLDİ: '{cmd}' yasaklı kalıp '{pat}' içeriyor")
    for token in shlex.split(cmd):
        tok = token.replace("'", "").replace('"', "").replace("$", "").replace("`", "")
        if tok.startswith("/"):
            if any(tok == fp or tok.startswith(fp + "/") for fp in FORBIDDEN_PATHS):
                raise PermissionError(f"KOMUT REDDEDİLDİ: '{token}' sistem yolu içeriyor")


def run_tool(name, args, confirm):
    try:
        if name == "list_files":
            p = resolve_path(args.get("path", "."))
            entries = sorted(os.listdir(p))
            detail = "\n".join(entries) if entries else "(boş)"
            return {"result": detail}
        elif name == "read_file":
            p = resolve_path(args.get("path", ""))
            if not p.is_file():
                return {"result": f"DOSYA YOK: {p}"}
            content = p.read_text(encoding="utf-8", errors="replace")
            return {"result": content[:4000]}
        elif name == "write_file":
            p = resolve_path(args.get("path", ""))
            if confirm and not ask(f"Dosya yazılacak: {p} - onaylıyor musun?"):
                return {"result": "Kullanıcı reddetti"}
            p.parent.mkdir(parents=True, exist_ok=True)
            p.write_text(args.get("content", ""), encoding="utf-8")
            audit("WRITE", str(p))
            return {"result": "Dosya yazıldı"}
        elif name == "append_file":
            p = resolve_path(args.get("path", ""))
            if confirm and not ask(f"Dosyaya eklenecek: {p} - onaylıyor musun?"):
                return {"result": "Kullanıcı reddetti"}
            p.parent.mkdir(parents=True, exist_ok=True)
            with open(p, "a", encoding="utf-8") as f:
                f.write(args.get("content", "") + "\n")
            audit("APPEND", str(p))
            return {"result": "İçerik eklendi"}
        elif name == "make_dir":
            p = resolve_path(args.get("path", ""))
            p.mkdir(parents=True, exist_ok=True)
            audit("MKDIR", str(p))
            return {"result": f"Dizin oluşturuldu: {p}"}
        elif name == "run_command":
            cmd = args.get("cmd", "")
            check_command(cmd)
            if confirm and not ask(f"Komut çalıştırılacak: {cmd} - onaylıyor musun?"):
                return {"result": "Kullanıcı reddetti"}
            audit("CMD", cmd)
            r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=30, cwd=WORKSPACE)
            out = (r.stdout or "") + (r.stderr or "")
            return {"result": out[:4000] if out else f"(çıktı yok, exit={r.returncode})"}
        else:
            return {"result": f"Bilinmeyen tool: {name}"}
    except PermissionError as e:
        audit("BLOCK", str(e))
        return {"result": str(e)}
    except Exception as e:
        return {"result": f"HATA: {e}"}


def ask(question):
    try:
        ans = input(f"\n? {question} [y/N]: ").strip().lower()
        return ans in ("y", "yes")
    except (EOFError, KeyboardInterrupt):
        return False


def call_model(messages):
    body = {
        "model": MODEL,
        "messages": messages,
        "stream": False,
        "think": False,
        "tools": TOOLS,
    }
    req = urllib.request.Request(
        OLLAMA_URL,
        data=json.dumps(body).encode(),
        headers={"Content-Type": "application/json"},
    )
    with urllib.request.urlopen(req, timeout=180) as resp:
        return json.loads(resp.read())


def main():
    ap = argparse.ArgumentParser(description="Atlas Agent Host")
    ap.add_argument("istek", nargs="?", help="Tek seferlik istek (interaktif mod kapalıyken)")
    ap.add_argument("--interactive", "-i", action="store_true", help="İnteraktif sohbet modu")
    ap.add_argument("--no-confirm", action="store_true", help="Komut onayı isteme (varsayılan: ister)")
    args = ap.parse_args()

    WORKSPACE.mkdir(parents=True, exist_ok=True)
    audit("START", f"model={MODEL} workspace={WORKSPACE}")

    if args.interactive or not args.istek:
        print("Atlas Agent Host - çıkmak için 'exit' yazın")
        print(f"Çalışma alanı: {WORKSPACE}")
        while True:
            try:
                q = input("\nSen: ")
            except (EOFError, KeyboardInterrupt):
                break
            if q.strip().lower() in ("exit", "quit", "q"):
                break
            messages = [{"role": "user", "content": q}]
            for _ in range(10):
                resp = call_model(messages)
                m = resp.get("message", {})
                tools = m.get("tool_calls") or []
                if not tools:
                    print("\nAtlas:", m.get("content", "(boş)"))
                    break
                messages.append({"role": "assistant", "content": m.get("content") or "", "tool_calls": tools})
                for tc in tools:
                    fn = tc.get("function", {})
                    name = fn.get("name", "")
                    fargs = fn.get("arguments", {})
                    if isinstance(fargs, str):
                        try:
                            fargs = json.loads(fargs)
                        except Exception:
                            fargs = {}
                    result = run_tool(name, fargs, not args.no_confirm)
                    messages.append({"role": "tool", "name": name, "content": json.dumps(result, ensure_ascii=False)})
    else:
        messages = [{"role": "user", "content": args.istek}]
        for _ in range(10):
            resp = call_model(messages)
            m = resp.get("message", {})
            tools = m.get("tool_calls") or []
            if not tools:
                print(m.get("content", "(boş)"))
                break
            messages.append({"role": "assistant", "content": m.get("content") or "", "tool_calls": tools})
            for tc in tools:
                fn = tc.get("function", {})
                name = fn.get("name", "")
                fargs = fn.get("arguments", {})
                if isinstance(fargs, str):
                    try:
                        fargs = json.loads(fargs)
                    except Exception:
                        fargs = {}
                result = run_tool(name, fargs, not args.no_confirm)
                messages.append({"role": "tool", "name": name, "content": json.dumps(result, ensure_ascii=False)})


if __name__ == "__main__":
    main()