| 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 | """Die Werkzeuge des Modells: lesen, schreiben, aendern, Shell, suchen.
Beschreibungen fuer das Modell auf Englisch - die Modelle sind auf englische
Werkzeugbeschreibungen trainiert und rufen sie so verlaesslicher auf.
Jede Dateiaenderung wird vorher gesichert (~/.kode/sicherungen/<sitzung>/),
nie neben dem Original: eine .bak im Webroot wird als Klartext ausgeliefert.
"""
import difflib
import json
import os
import shutil
import subprocess
import time
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
from . import konfig
MAX_AUSGABE = 30000 # Zeichen je Werkzeugergebnis, wird an den Kontext angepasst
MAX_ZEILEN = 2000
SCHEMA: list[dict[str, Any]] = [
{"type": "function", "function": {
"name": "read_file",
"description": "Read a text file. Returns numbered lines (cat -n style). "
"Use offset/limit for large files.",
"parameters": {"type": "object", "properties": {
"path": {"type": "string", "description": "Absolute or relative file path"},
"offset": {"type": "integer", "description": "First line (1-based), optional"},
"limit": {"type": "integer", "description": "Number of lines, optional"}},
"required": ["path"]}}},
{"type": "function", "function": {
"name": "write_file",
"description": "Create a file or overwrite it completely with the given content. "
"Prefer edit_file for changes to existing files.",
"parameters": {"type": "object", "properties": {
"path": {"type": "string"},
"content": {"type": "string", "description": "The complete new file content"}},
"required": ["path", "content"]}}},
{"type": "function", "function": {
"name": "edit_file",
"description": "Replace an exact text snippet in a file. old_string must match the file "
"exactly (including indentation) and be unique unless replace_all is true. "
"Read the file first.",
"parameters": {"type": "object", "properties": {
"path": {"type": "string"},
"old_string": {"type": "string"},
"new_string": {"type": "string"},
"replace_all": {"type": "boolean"}},
"required": ["path", "old_string", "new_string"]}}},
{"type": "function", "function": {
"name": "bash",
"description": "Run a shell command (bash) on the server as root. The working directory "
"persists between calls (cd works). Default timeout 120 s, max 600 s. "
"For long-running servers use nohup ... & and redirect output to a file.",
"parameters": {"type": "object", "properties": {
"command": {"type": "string"},
"timeout": {"type": "integer", "description": "Seconds, optional"}},
"required": ["command"]}}},
{"type": "function", "function": {
"name": "glob",
"description": "Find files by glob pattern, e.g. '**/*.py'. Newest first, max 200.",
"parameters": {"type": "object", "properties": {
"pattern": {"type": "string"},
"path": {"type": "string", "description": "Directory to search in, optional"}},
"required": ["pattern"]}}},
{"type": "function", "function": {
"name": "grep",
"description": "Search file contents with a regular expression (ripgrep). "
"Returns file:line:text, max 200 matches.",
"parameters": {"type": "object", "properties": {
"pattern": {"type": "string"},
"path": {"type": "string", "description": "File or directory, optional"},
"glob": {"type": "string", "description": "Filter files, e.g. '*.js', optional"},
"ignore_case": {"type": "boolean"}},
"required": ["pattern"]}}},
{"type": "function", "function": {
"name": "list_dir",
"description": "List a directory (names, '/' marks directories, sizes).",
"parameters": {"type": "object", "properties": {
"path": {"type": "string"}}, "required": []}}},
]
NUR_LESEN = {"read_file", "glob", "grep", "list_dir"}
DATEI_AENDERN = {"write_file", "edit_file"}
@dataclass
class Umgebung:
"""Was eine Sitzung ueber Aufrufe hinweg behaelt."""
cwd: Path
sitzung: str
sicherungen: list[dict[str, Any]] = field(default_factory=list)
max_ausgabe: int = MAX_AUSGABE
def pfad(self, p: str | None) -> Path:
if not p:
return self.cwd
p = os.path.expanduser(p)
return Path(p) if os.path.isabs(p) else (self.cwd / p)
def sichern(self, ziel: Path) -> None:
ordner = konfig.SICHERUNGEN / self.sitzung
ordner.mkdir(parents=True, exist_ok=True)
eintrag: dict[str, Any] = {"pfad": str(ziel.resolve()), "zeit": time.time(), "kopie": None}
if ziel.exists():
kopie = ordner / f"{len(self.sicherungen):04d}_{ziel.name}"
shutil.copy2(ziel, kopie)
eintrag["kopie"] = str(kopie)
self.sicherungen.append(eintrag)
(ordner / "liste.json").write_text(json.dumps(self.sicherungen, indent=1), encoding="utf-8")
def rueckgaengig(self) -> str:
if not self.sicherungen:
return "Nichts rückgängig zu machen."
e = self.sicherungen.pop()
ziel = Path(e["pfad"])
if e["kopie"]:
shutil.copy2(e["kopie"], ziel)
return f"Wiederhergestellt: {ziel}"
ziel.unlink(missing_ok=True)
return f"Neu angelegte Datei entfernt: {ziel}"
def kuerzen(self, text: str) -> str:
if len(text) <= self.max_ausgabe:
return text
h = self.max_ausgabe // 2
return (text[:h] + f"\n\n[… {len(text) - 2*h} Zeichen ausgelassen …]\n\n" + text[-h:])
def diff(alt: str, neu: str, name: str) -> str:
return "".join(difflib.unified_diff(alt.splitlines(True), neu.splitlines(True),
f"a/{name}", f"b/{name}", n=3))
def _lesen(u: Umgebung, a: dict) -> str:
p = u.pfad(a.get("path"))
if not p.exists():
return f"Fehler: {p} existiert nicht."
if p.is_dir():
return f"Fehler: {p} ist ein Verzeichnis - list_dir benutzen."
roh = p.read_bytes()
if b"\0" in roh[:8000]:
return f"Fehler: {p} ist eine Binärdatei ({len(roh)} Bytes)."
zeilen = roh.decode("utf-8", errors="replace").splitlines()
start = max(1, int(a.get("offset") or 1))
anzahl = int(a.get("limit") or MAX_ZEILEN)
teil = zeilen[start - 1:start - 1 + anzahl]
text = "\n".join(f"{i:6}\t{z[:2000]}" for i, z in enumerate(teil, start))
rest = len(zeilen) - (start - 1 + len(teil))
if rest > 0:
text += f"\n[… noch {rest} Zeilen, offset={start + len(teil)} zum Weiterlesen]"
return text or "(leere Datei)"
def vorschau_schreiben(u: Umgebung, name: str, a: dict) -> tuple[str | None, str]:
"""Diff fuer die Freigabe. (diff, fehler) - fehler leer heisst: ausfuehrbar."""
p = u.pfad(a.get("path"))
alt = p.read_text(encoding="utf-8", errors="replace") if p.is_file() else ""
if name == "write_file":
return diff(alt, a.get("content") or "", str(p)), ""
if not p.is_file():
return None, f"Fehler: {p} existiert nicht."
alt_s, neu_s = a.get("old_string") or "", a.get("new_string") or ""
n = alt.count(alt_s) if alt_s else 0
if n == 0:
return None, "Fehler: old_string kommt in der Datei nicht vor. Datei erst lesen."
if n > 1 and not a.get("replace_all"):
return None, f"Fehler: old_string kommt {n}-mal vor. Mehr Kontext angeben oder replace_all."
neu = alt.replace(alt_s, neu_s) if a.get("replace_all") else alt.replace(alt_s, neu_s, 1)
return diff(alt, neu, str(p)), ""
def _schreiben(u: Umgebung, a: dict) -> str:
p = u.pfad(a.get("path"))
u.sichern(p)
p.parent.mkdir(parents=True, exist_ok=True)
inhalt = a.get("content") or ""
p.write_text(inhalt, encoding="utf-8")
return f"Geschrieben: {p} ({len(inhalt.splitlines())} Zeilen)"
def _aendern(u: Umgebung, a: dict) -> str:
d, fehler = vorschau_schreiben(u, "edit_file", a)
if fehler:
return fehler
p = u.pfad(a.get("path"))
alt = p.read_text(encoding="utf-8", errors="replace")
u.sichern(p)
if a.get("replace_all"):
neu = alt.replace(a["old_string"], a["new_string"])
else:
neu = alt.replace(a["old_string"], a["new_string"], 1)
p.write_text(neu, encoding="utf-8")
return f"Geändert: {p}"
MARKE = "__KODE_PWD__"
def _bash(u: Umgebung, a: dict, abbruch: Any = None) -> str:
befehl = a.get("command") or ""
frist = min(600, max(1, int(a.get("timeout") or 120)))
skript = f"{befehl}\n__kode_rc=$?\necho; echo {MARKE}$(pwd)\nexit $__kode_rc"
proc = None
try:
proc = subprocess.Popen(["bash", "-c", skript], cwd=u.cwd, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,
start_new_session=True)
try:
raus, _ = proc.communicate(timeout=frist)
zeitueber = False
except subprocess.TimeoutExpired:
os.killpg(proc.pid, 9)
raus, _ = proc.communicate()
zeitueber = True
except KeyboardInterrupt:
if proc:
try:
os.killpg(proc.pid, 9)
except OSError:
pass
raise
text = raus.decode("utf-8", errors="replace")
if MARKE in text:
text, _, neu = text.rpartition(MARKE)
neu = neu.strip()
if neu and Path(neu).is_dir():
u.cwd = Path(neu)
text = text.rstrip("\n")
kopf = f"[Zeitüberschreitung nach {frist} s, Prozess beendet]\n" if zeitueber else ""
rc = proc.returncode
fuss = f"\n[Exit-Code {rc}]" if rc not in (0, None) and not zeitueber else ""
return u.kuerzen(kopf + (text or "(keine Ausgabe)") + fuss)
def _glob(u: Umgebung, a: dict) -> str:
basis = u.pfad(a.get("path"))
muster = a.get("pattern") or "*"
try:
treffer = [p for p in basis.glob(muster)
if not any(t in p.parts for t in (".git", "node_modules", ".venv", "__pycache__"))]
except (ValueError, OSError) as f:
return f"Fehler: {f}"
treffer.sort(key=lambda p: p.stat().st_mtime if p.exists() else 0, reverse=True)
if not treffer:
return "Keine Treffer."
zeilen = [str(p) for p in treffer[:200]]
if len(treffer) > 200:
zeilen.append(f"[… {len(treffer) - 200} weitere]")
return "\n".join(zeilen)
def _grep(u: Umgebung, a: dict) -> str:
befehl = ["rg", "-n", "--no-heading", "--max-columns", "300", "-m", "50"]
if a.get("ignore_case"):
befehl.append("-i")
if a.get("glob"):
befehl += ["-g", a["glob"]]
befehl += ["-e", a.get("pattern") or "", str(u.pfad(a.get("path")))]
try:
r = subprocess.run(befehl, capture_output=True, text=True, timeout=60)
except subprocess.TimeoutExpired:
return "Fehler: Suche dauerte über 60 s - Pfad eingrenzen."
zeilen = r.stdout.splitlines()
if not zeilen:
return "Keine Treffer." + (f" ({r.stderr.strip()[:200]})" if r.stderr.strip() else "")
aus = "\n".join(zeilen[:200])
if len(zeilen) > 200:
aus += f"\n[… {len(zeilen) - 200} weitere Treffer]"
return u.kuerzen(aus)
def _liste(u: Umgebung, a: dict) -> str:
p = u.pfad(a.get("path"))
if not p.is_dir():
return f"Fehler: {p} ist kein Verzeichnis."
zeilen = []
for e in sorted(p.iterdir(), key=lambda e: (not e.is_dir(), e.name))[:500]:
try:
zeilen.append(f"{e.name}/" if e.is_dir() else f"{e.name} ({e.stat().st_size} B)")
except OSError:
zeilen.append(e.name)
return "\n".join(zeilen) or "(leer)"
def ausfuehren(u: Umgebung, name: str, a: dict) -> str:
try:
if name == "read_file":
return u.kuerzen(_lesen(u, a))
if name == "write_file":
return _schreiben(u, a)
if name == "edit_file":
return _aendern(u, a)
if name == "bash":
return _bash(u, a)
if name == "glob":
return _glob(u, a)
if name == "grep":
return _grep(u, a)
if name == "list_dir":
return _liste(u, a)
except KeyboardInterrupt:
raise
except Exception as f: # noqa: BLE001
return f"Fehler: {f.__class__.__name__}: {f}"
return f"Fehler: unbekanntes Werkzeug {name}" |