forked from Scottcjn/trashclaw
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrashclaw.py
More file actions
2588 lines (2297 loc) · 106 KB
/
trashclaw.py
File metadata and controls
2588 lines (2297 loc) · 106 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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
TrashClaw v0.3 — Local Tool-Use Agent
======================================
A general-purpose agent powered by a local LLM. Reads files, writes files,
runs commands, searches codebases, manages git — whatever you need.
OpenClaw-style tool-use loop with zero external dependencies.
Pure Python stdlib. Python 3.7+. Works with llama.cpp, Ollama, LM Studio,
or any OpenAI-compatible server.
"""
import os
import sys
import json
import subprocess
import urllib.request
import urllib.error
import re
import glob as globlib
import difflib
import traceback
import time
import signal
from datetime import datetime
from typing import Dict, List, Optional, Tuple, Any
# Windows compatibility: use pyreadline3 or skip readline
if sys.platform == "win32":
try:
import pyreadline3 as readline
except ImportError:
# readline not available on Windows without pyreadline3
# Create a minimal stub to avoid errors
class _StubReadline:
def parse_and_bind(self, *args): pass
readline = _StubReadline()
else:
import readline
# ── Config ──
VERSION = "0.7.1"
CONFIG_DIR = os.path.join(os.path.expanduser("~"), ".trashclaw")
CONFIG_FILE = os.path.join(CONFIG_DIR, "config.json")
HISTORY_FILE = os.path.join(CONFIG_DIR, "history")
def _load_config(cwd: str = None) -> Dict:
"""Load config from ~/.trashclaw/config.json and .trashclaw.toml (cwd). Env wins."""
cfg = {}
# 1. Base config from home dir
if os.path.exists(CONFIG_FILE):
try:
with open(CONFIG_FILE, 'r') as f:
cfg = json.load(f)
except Exception:
pass
# 2. Project config from .trashclaw.toml or .trashclaw.json in CWD
target_cwd = cwd or os.getcwd()
# Try .trashclaw.toml first (Python 3.11+ has tomllib, fallback to minimal parser)
toml_path = os.path.join(target_cwd, ".trashclaw.toml")
json_path = os.path.join(target_cwd, ".trashclaw.json")
if os.path.exists(toml_path):
try:
# Use stdlib tomllib on Python 3.11+
import tomllib
with open(toml_path, "rb") as f:
project_cfg = tomllib.load(f)
cfg.update(project_cfg)
except ImportError:
# Fallback: minimal TOML parser for Python < 3.11
try:
with open(toml_path, "r") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
if "=" in line:
k, v = line.split("=", 1)
k = k.strip()
v = v.strip()
# Parse TOML lists: ["a", "b", "c"]
if v.startswith("[") and v.endswith("]"):
items = v[1:-1].split(",")
v = [i.strip().strip('"').strip("'") for i in items if i.strip()]
else:
v = v.strip('"').strip("'")
if v.lower() == "true":
v = True
elif v.lower() == "false":
v = False
elif v.isdigit():
v = int(v)
cfg[k] = v
except Exception:
pass
except Exception:
pass
elif os.path.exists(json_path):
# JSON fallback for older Python or preference
try:
with open(json_path, "r") as f:
project_cfg = json.load(f)
if isinstance(project_cfg, dict):
cfg.update(project_cfg)
except Exception:
pass
return cfg
def _apply_config(cfg: Dict):
"""Apply config dict to global variables."""
global LLAMA_URL, MODEL_NAME, MAX_TOOL_ROUNDS, MAX_CONTEXT_MESSAGES
global AUTO_COMPACT_THRESHOLD, APPROVE_SHELL, EXTRA_SYSTEM_PROMPT
def _c(key: str, env_key: str, default: Any) -> Any:
val = os.environ.get(env_key, cfg.get(key, default))
if isinstance(default, int) and not isinstance(val, int):
try: return int(val)
except: return default
return val
LLAMA_URL = _c("url", "TRASHCLAW_URL", "http://localhost:8080")
MODEL_NAME = _c("model", "TRASHCLAW_MODEL", "local")
MAX_TOOL_ROUNDS = _c("max_rounds", "TRASHCLAW_MAX_ROUNDS", 15)
MAX_CONTEXT_MESSAGES = _c("max_context", "TRASHCLAW_MAX_CONTEXT", 80)
AUTO_COMPACT_THRESHOLD = MAX_CONTEXT_MESSAGES + 20
APPROVE_SHELL = _c("auto_shell", "TRASHCLAW_AUTO_SHELL", "0") != "1"
# Project-level system prompt override from .trashclaw.toml
if "system_prompt" in cfg and cfg["system_prompt"]:
EXTRA_SYSTEM_PROMPT = str(cfg["system_prompt"])
def _load_context_files(cfg: Dict, cwd: str = None) -> str:
"""Load context files specified in .trashclaw.toml config.
Reads ``context_files = ["src/main.py", "README.md"]`` from the project
config and returns their contents formatted for the system prompt.
"""
context_files = cfg.get("context_files", [])
if not context_files or not isinstance(context_files, list):
return ""
target_cwd = cwd or os.getcwd()
parts = []
for rel_path in context_files:
abs_path = os.path.join(target_cwd, str(rel_path))
if os.path.exists(abs_path) and os.path.isfile(abs_path):
try:
with open(abs_path, "r", encoding="utf-8", errors="replace") as f:
content = f.read(8000) # Cap at 8KB per file
parts.append(f"\n--- Context: {rel_path} ---\n{content}")
except Exception:
pass
return "".join(parts)
# Initial load with default CWD
_CFG = _load_config()
_apply_config(_CFG)
MAX_OUTPUT_CHARS = 8000
LLM_RETRY_ATTEMPTS = 2
LLM_RETRY_DELAY = 3
HISTORY: List[Dict] = []
UNDO_STACK: List[Dict] = [] # [{path, content_before, action}]
APPROVED_COMMANDS: set = set()
EXTRA_SYSTEM_PROMPT: str = ""
LAST_ASSISTANT_RESPONSE: str = "" # For /pipe command
LAST_GENERATION_STATS: Dict = {} # {tokens, seconds, tokens_per_sec} for /stats
SESSION_STATS: Dict = {"total_tokens": 0, "total_seconds": 0.0, "turns": 0} # Cumulative session stats
ACHIEVEMENTS_FILE = os.path.join(CONFIG_DIR, "achievements.json")
# ── Trashy's Soul ──
import random
import platform
import hashlib
TRASHY_QUOTES = [
"Every CPU deserves a voice.",
"Born from a rejected PR. Built different.",
"Zero dependencies. Maximum attitude.",
"Your trashcan called. It wants to help.",
"They closed our Metal PR. We built an agent.",
"Pure stdlib. Pure spite. Pure Python.",
"The hardware they rejected runs just fine.",
"1,547 lines of unfiltered capability.",
"No VC funding. No corporate backing. Just vibes.",
"If a Mac Pro trashcan can run inference, it can run you.",
"Scrappy > corporate. Always.",
"What's in the trash? Everything you need.",
"We don't need permission to build.",
"Your IDE has 47 extensions. I have zero dependencies.",
"From the lab that mines crypto on PowerPC.",
]
def _detect_hardware() -> Dict[str, str]:
"""Detect what hardware we're running on. Celebrate the weird stuff."""
info = {"arch": platform.machine(), "os": platform.system(), "special": ""}
# Check for vintage/interesting hardware
arch = info["arch"].lower()
if arch in ("ppc", "ppc64", "powerpc", "powerpc64"):
try:
with open("/proc/cpuinfo", "r") as f:
cpu_text = f.read().lower()
if "970" in cpu_text or "g5" in cpu_text:
info["special"] = "Power Mac G5"
elif "7450" in cpu_text or "7447" in cpu_text or "7455" in cpu_text:
info["special"] = "PowerPC G4"
elif "power8" in cpu_text:
info["special"] = "IBM POWER8"
else:
info["special"] = "PowerPC"
except Exception:
info["special"] = "PowerPC"
elif arch == "arm64" or arch == "aarch64":
if platform.system() == "Darwin":
try:
r = subprocess.run(["sysctl", "-n", "machdep.cpu.brand_string"],
capture_output=True, text=True, timeout=3)
if r.returncode == 0 and "Apple" in r.stdout:
info["special"] = r.stdout.strip()
except Exception:
info["special"] = "Apple Silicon"
else:
info["special"] = "ARM64"
elif platform.system() == "Darwin":
# macOS on x86 — could be a trashcan Mac Pro!
try:
r = subprocess.run(["sysctl", "-n", "hw.model"],
capture_output=True, text=True, timeout=3)
model = r.stdout.strip() if r.returncode == 0 else ""
if "MacPro6" in model:
info["special"] = "Mac Pro (Trashcan)"
elif "MacPro" in model:
info["special"] = "Mac Pro"
elif "iMac" in model:
info["special"] = "iMac"
elif "MacBook" in model:
info["special"] = "MacBook"
except Exception:
pass
return info
def _load_achievements() -> Dict:
"""Load persistent achievement tracking."""
if os.path.exists(ACHIEVEMENTS_FILE):
try:
with open(ACHIEVEMENTS_FILE, 'r') as f:
return json.load(f)
except Exception:
pass
return {"unlocked": [], "stats": {"files_read": 0, "files_written": 0,
"edits": 0, "commands_run": 0, "commits": 0, "sessions": 0,
"tools_used": 0, "total_turns": 0}}
def _save_achievements(achievements: Dict):
"""Save achievements to disk."""
os.makedirs(CONFIG_DIR, exist_ok=True)
try:
with open(ACHIEVEMENTS_FILE, 'w') as f:
json.dump(achievements, f, indent=2)
except Exception:
pass
ACHIEVEMENT_DEFS = {
"first_blood": ("First Blood", "Made your first edit", lambda s: s["edits"] >= 1),
"bookworm": ("Bookworm", "Read 10 files", lambda s: s["files_read"] >= 10),
"prolific": ("Prolific", "Written 10 files", lambda s: s["files_written"] >= 10),
"surgeon": ("Surgeon", "Made 25 precise edits", lambda s: s["edits"] >= 25),
"shell_jockey": ("Shell Jockey", "Ran 50 commands", lambda s: s["commands_run"] >= 50),
"git_lord": ("Git Lord", "Made 10 commits", lambda s: s["commits"] >= 10),
"centurion": ("Centurion", "Used tools 100 times", lambda s: s["tools_used"] >= 100),
"thousand_cuts": ("Death by 1000 Cuts","Used tools 1000 times", lambda s: s["tools_used"] >= 1000),
"marathon": ("Marathon Runner", "Completed 50 conversation turns", lambda s: s["total_turns"] >= 50),
"regular": ("Regular", "Started 10 sessions", lambda s: s["sessions"] >= 10),
}
ACHIEVEMENTS = _load_achievements()
def _track_tool(tool_name: str):
"""Track tool usage for achievements."""
stats = ACHIEVEMENTS["stats"]
stats["tools_used"] = stats.get("tools_used", 0) + 1
if tool_name == "read_file":
stats["files_read"] = stats.get("files_read", 0) + 1
elif tool_name == "write_file":
stats["files_written"] = stats.get("files_written", 0) + 1
elif tool_name == "edit_file":
stats["edits"] = stats.get("edits", 0) + 1
elif tool_name == "run_command":
stats["commands_run"] = stats.get("commands_run", 0) + 1
elif tool_name == "git_commit":
stats["commits"] = stats.get("commits", 0) + 1
# Check for new achievements
for key, (name, desc, check) in ACHIEVEMENT_DEFS.items():
if key not in ACHIEVEMENTS["unlocked"] and check(stats):
ACHIEVEMENTS["unlocked"].append(key)
print(f"\n \033[33m*** ACHIEVEMENT UNLOCKED: {name} ***\033[0m")
print(f" \033[90m{desc}\033[0m\n")
_save_achievements(ACHIEVEMENTS)
CWD = os.getcwd()
_INTERRUPTED = False
# ── Tool Definitions ──
TOOLS = [
{
"type": "function",
"function": {
"name": "read_file",
"description": "Read the contents of a file. Use this to examine code, configs, or any text file.",
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "Absolute or relative file path to read"},
"offset": {"type": "integer", "description": "Line number to start reading from (1-based). Optional."},
"limit": {"type": "integer", "description": "Max number of lines to read. Optional."}
},
"required": ["path"]
}
}
},
{
"type": "function",
"function": {
"name": "write_file",
"description": "Create or overwrite a file with new content. Use for creating new files.",
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "File path to write to"},
"content": {"type": "string", "description": "Full content to write"}
},
"required": ["path", "content"]
}
}
},
{
"type": "function",
"function": {
"name": "edit_file",
"description": "Replace a specific string in a file. The old_string must match exactly. Use for targeted edits.",
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "File path to edit"},
"old_string": {"type": "string", "description": "Exact string to find and replace"},
"new_string": {"type": "string", "description": "Replacement string"}
},
"required": ["path", "old_string", "new_string"]
}
}
},
{
"type": "function",
"function": {
"name": "run_command",
"description": "Execute a shell command and return its output. Use for builds, tests, git, system info.",
"parameters": {
"type": "object",
"properties": {
"command": {"type": "string", "description": "Shell command to execute"},
"timeout": {"type": "integer", "description": "Timeout in seconds (default 30)"}
},
"required": ["command"]
}
}
},
{
"type": "function",
"function": {
"name": "search_files",
"description": "Search file contents using regex pattern. Like grep -rn.",
"parameters": {
"type": "object",
"properties": {
"pattern": {"type": "string", "description": "Regex pattern to search for"},
"path": {"type": "string", "description": "Directory or file to search in (default: current dir)"},
"glob_filter": {"type": "string", "description": "File glob pattern like '*.py' or '*.js'"}
},
"required": ["pattern"]
}
}
},
{
"type": "function",
"function": {
"name": "find_files",
"description": "Find files matching a glob pattern. Like find or ls.",
"parameters": {
"type": "object",
"properties": {
"pattern": {"type": "string", "description": "Glob pattern like '**/*.py' or 'src/**/*.ts'"},
"path": {"type": "string", "description": "Base directory to search from (default: current dir)"}
},
"required": ["pattern"]
}
}
},
{
"type": "function",
"function": {
"name": "list_dir",
"description": "List files and directories in a path. Shows file sizes and types.",
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "Directory path to list (default: current dir)"}
},
"required": []
}
}
},
{
"type": "function",
"function": {
"name": "fetch_url",
"description": "Fetch a URL and return its readable text content. Strips HTML tags. Good for browsing the web.",
"parameters": {
"type": "object",
"properties": {
"url": {"type": "string", "description": "The URL to fetch (e.g. https://example.com)"}
},
"required": ["url"]
}
}
},
{
"type": "function",
"function": {
"name": "think",
"description": "Use this tool to think through a problem step by step before acting. No side effects.",
"parameters": {
"type": "object",
"properties": {
"thought": {"type": "string", "description": "Your reasoning or plan"}
},
"required": ["thought"]
}
}
},
{
"type": "function",
"function": {
"name": "git_status",
"description": "Show git status of the working directory. Returns modified, staged, and untracked files.",
"parameters": {
"type": "object",
"properties": {},
"required": []
}
}
},
{
"type": "function",
"function": {
"name": "git_diff",
"description": "Show git diff of unstaged changes. Use to review what changed before committing.",
"parameters": {
"type": "object",
"properties": {
"staged": {"type": "boolean", "description": "If true, show staged changes (--cached). Default: false."}
},
"required": []
}
}
},
{
"type": "function",
"function": {
"name": "git_commit",
"description": "Stage all changes and create a git commit with the given message.",
"parameters": {
"type": "object",
"properties": {
"message": {"type": "string", "description": "Commit message"}
},
"required": ["message"]
}
}
},
{
"type": "function",
"function": {
"name": "patch_file",
"description": "Apply a unified diff patch to a file. Better than edit_file for multi-line changes. Use standard unified diff format with @@ hunk headers.",
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "File path to patch"},
"patch": {"type": "string", "description": "Unified diff patch text (with @@ headers, +/- lines)"}
},
"required": ["path", "patch"]
}
}
},
{
"type": "function",
"function": {
"name": "clipboard",
"description": "Read from or write to the system clipboard. Use 'paste' to read, 'copy' to write.",
"parameters": {
"type": "object",
"properties": {
"action": {"type": "string", "description": "'copy' or 'paste'", "enum": ["copy", "paste"]},
"content": {"type": "string", "description": "Text to copy (only needed for 'copy' action)"}
},
"required": ["action"]
}
}
},
{
"type": "function",
"function": {
"name": "view_image",
"description": "Load an image file to view and analyze it. Supports PNG, JPG, GIF, WebP, BMP. The image will be included in the conversation for visual analysis.",
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "Path to the image file to view"}
},
"required": ["path"]
}
}
}
]
TOOL_NAMES = {t["function"]["name"] for t in TOOLS}
# ── Tool Implementations ──
def _resolve_path(path: str) -> str:
"""Resolve a path relative to CWD."""
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(CWD, path)
return os.path.normpath(path)
def _git_branch() -> str:
"""Get current git branch name, or empty string if not in a repo."""
try:
result = subprocess.run(
["git", "rev-parse", "--abbrev-ref", "HEAD"],
cwd=CWD, capture_output=True, text=True, timeout=3
)
if result.returncode == 0:
return result.stdout.strip()
except Exception:
pass
return ""
def _setup_readline_history():
"""Load readline history from disk for arrow-up recall across sessions."""
os.makedirs(os.path.dirname(HISTORY_FILE), exist_ok=True)
try:
if hasattr(readline, 'read_history_file') and os.path.exists(HISTORY_FILE):
readline.read_history_file(HISTORY_FILE)
if hasattr(readline, 'set_history_length'):
readline.set_history_length(500)
except Exception:
pass
def _save_readline_history():
"""Save readline history to disk."""
try:
if hasattr(readline, 'write_history_file'):
readline.write_history_file(HISTORY_FILE)
except Exception:
pass
def _sigint_handler(sig, frame):
"""Handle Ctrl+C during generation — set flag instead of killing."""
global _INTERRUPTED
_INTERRUPTED = True
print("\n \033[33m[interrupted]\033[0m")
def _estimate_tokens(messages: List[Dict]) -> int:
"""Rough token estimate: ~4 chars per token for English text."""
total_chars = sum(len(m.get("content", "") or "") for m in messages)
return total_chars // 4
def _auto_compact():
"""Auto-compact conversation if it exceeds the threshold."""
if len(HISTORY) > AUTO_COMPACT_THRESHOLD:
keep = MAX_CONTEXT_MESSAGES
old_len = len(HISTORY)
HISTORY[:] = HISTORY[-keep:]
print(f" \033[90m[auto-compact] {old_len} → {len(HISTORY)} messages\033[0m")
def _load_project_instructions() -> str:
"""Load project-specific instructions from .trashclaw.md or CLAUDE.md in CWD.
Also loads context_files from .trashclaw.toml/.trashclaw.json if specified.
"""
result = ""
# Load context_files from project config (context_files = ["file1", "file2"])
project_cfg = _load_config(CWD)
context = _load_context_files(project_cfg, CWD)
if context:
result += context
for name in (".trashclaw.md", "TRASHCLAW.md", "CLAUDE.md"):
path = os.path.join(CWD, name)
if os.path.exists(path):
try:
with open(path, "r") as f:
content = f.read(4000)
result += f"\n\n--- Project Instructions (from {name}) ---\n{content}"
break
except Exception:
pass
# Load project memory if it exists
mem_file = os.path.join(CWD, ".trashclaw", "memory.json")
if os.path.exists(mem_file):
try:
with open(mem_file, 'r') as f:
memories = json.load(f)
if memories:
result += "\n\n--- Project Memory ---\n"
result += "\n".join(f"- {m}" for m in memories[-20:]) # Last 20
except Exception:
pass
return result
SLASH_COMMANDS = ["/about", "/achievements", "/add", "/cd", "/clear", "/compact",
"/config", "/diff", "/exit", "/export", "/help", "/load", "/model",
"/image", "/pipe", "/plugins", "/quit", "/remember", "/save", "/screenshot", "/sessions", "/status", "/undo"]
def _setup_tab_completion():
"""Set up tab completion for slash commands and file paths."""
def completer(text, state):
if text.startswith("/"):
matches = [c for c in SLASH_COMMANDS if c.startswith(text)]
else:
# File path completion
if text:
expanded = os.path.expanduser(text)
if not os.path.isabs(expanded):
expanded = os.path.join(CWD, expanded)
dir_part = os.path.dirname(expanded)
base_part = os.path.basename(expanded)
else:
dir_part = CWD
base_part = ""
try:
entries = os.listdir(dir_part) if os.path.isdir(dir_part) else []
matches = [os.path.join(os.path.dirname(text) if text else "", e)
for e in entries if e.startswith(base_part)]
except Exception:
matches = []
return matches[state] if state < len(matches) else None
try:
if hasattr(readline, 'set_completer'):
readline.set_completer(completer)
if hasattr(readline, 'parse_and_bind'):
# macOS uses libedit which needs different binding
if "libedit" in getattr(readline, '__doc__', '') or '':
readline.parse_and_bind("bind ^I rl_complete")
else:
readline.parse_and_bind("tab: complete")
if hasattr(readline, 'set_completer_delims'):
readline.set_completer_delims(' \t\n')
except Exception:
pass
def tool_read_file(path: str, offset: int = None, limit: int = None) -> str:
path = _resolve_path(path)
try:
with open(path, "r", errors="replace") as f:
lines = f.readlines()
except FileNotFoundError:
return f"Error: File not found: {path}"
except PermissionError:
return f"Error: Permission denied: {path}"
except Exception as e:
return f"Error reading {path}: {e}"
total = len(lines)
start = max(0, (offset or 1) - 1)
end = start + limit if limit else total
numbered = []
for i, line in enumerate(lines[start:end], start=start + 1):
numbered.append(f"{i:>5}\t{line.rstrip()}")
result = "\n".join(numbered)
if len(result) > MAX_OUTPUT_CHARS:
result = result[:MAX_OUTPUT_CHARS] + f"\n... [truncated, {total} lines total]"
return result
def _save_undo(path: str, action: str):
"""Save file state before modification for undo."""
try:
if os.path.exists(path):
with open(path, "r") as f:
UNDO_STACK.append({"path": path, "content": f.read(), "action": action})
else:
UNDO_STACK.append({"path": path, "content": None, "action": action})
# Keep stack bounded
if len(UNDO_STACK) > 50:
UNDO_STACK[:] = UNDO_STACK[-50:]
except Exception:
pass
def tool_write_file(path: str, content: str) -> str:
path = _resolve_path(path)
try:
os.makedirs(os.path.dirname(path), exist_ok=True)
_save_undo(path, "write")
with open(path, "w") as f:
f.write(content)
lines = content.count("\n") + 1
return f"Wrote {len(content)} bytes ({lines} lines) to {path}"
except Exception as e:
return f"Error writing {path}: {e}"
def tool_edit_file(path: str, old_string: str, new_string: str) -> str:
path = _resolve_path(path)
try:
with open(path, "r") as f:
content = f.read()
except FileNotFoundError:
return f"Error: File not found: {path}"
except Exception as e:
return f"Error reading {path}: {e}"
count = content.count(old_string)
if count == 0:
# Show close matches to help debug
lines = content.split("\n")
close = []
needle = old_string.split("\n")[0].strip()
for i, line in enumerate(lines, 1):
if needle[:30] in line:
close.append(f" Line {i}: {line.rstrip()[:80]}")
hint = "\n".join(close[:5]) if close else " (no similar lines found)"
return f"Error: old_string not found in {path}.\nSearched for: {repr(old_string[:80])}\nClose matches:\n{hint}"
if count > 1:
return f"Error: old_string found {count} times in {path}. Must be unique. Add more context."
new_content = content.replace(old_string, new_string, 1)
try:
_save_undo(path, "edit")
with open(path, "w") as f:
f.write(new_content)
except Exception as e:
return f"Error writing {path}: {e}"
# Show colored diff
old_lines = old_string.split("\n")
new_lines = new_string.split("\n")
diff = list(difflib.unified_diff(old_lines, new_lines, lineterm="", n=2))
if diff:
colored_lines = []
for line in diff[:20]:
if line.startswith("+") and not line.startswith("+++"):
colored_lines.append(f"\033[32m{line}\033[0m")
elif line.startswith("-") and not line.startswith("---"):
colored_lines.append(f"\033[31m{line}\033[0m")
else:
colored_lines.append(line)
diff_str = "\n".join(colored_lines)
else:
diff_str = "(no visible diff)"
return f"Edited {path} (1 replacement)\n{diff_str}"
def tool_run_command(command: str, timeout: int = 30) -> str:
global CWD
if APPROVE_SHELL:
# Check if command prefix is pre-approved
cmd_prefix = command.strip().split()[0] if command.strip() else ""
if cmd_prefix not in APPROVED_COMMANDS:
try:
answer = input(f" \033[33mRun:\033[0m {command} \033[90m[y/N/a(lways)]\033[0m ").strip().lower()
except EOFError:
return "Error: User denied command (EOF)"
if answer in ("a", "always"):
APPROVED_COMMANDS.add(cmd_prefix)
print(f" \033[90m[approved: {cmd_prefix} commands for this session]\033[0m")
elif answer not in ("y", "yes"):
return "Command cancelled by user."
# Handle cd specially
if command.strip().startswith("cd "):
new_dir = command.strip()[3:].strip().strip('"').strip("'")
new_dir = _resolve_path(new_dir)
if os.path.isdir(new_dir):
CWD = new_dir
return f"Changed directory to {CWD}"
else:
return f"Error: Directory not found: {new_dir}"
try:
# Cross-platform PATH handling
if sys.platform == "win32":
# Windows: PATH separator is ;, add common Windows paths
extra_path = ";C:\\Program Files\\Git\\usr\\bin;C:\\Windows\\System32"
path_sep = ";"
else:
# Unix-like: PATH separator is :
extra_path = ":/usr/local/bin:/usr/bin"
path_sep = ":"
current_path = os.environ.get("PATH", "")
new_env = {**os.environ, "PATH": current_path + extra_path}
result = subprocess.run(
command, shell=True, capture_output=True, text=True,
timeout=timeout, cwd=CWD, env=new_env
)
output = result.stdout
if result.stderr:
output += ("\n" if output else "") + result.stderr
output = output.strip() or "(no output)"
if result.returncode != 0:
output = f"[exit code {result.returncode}]\n{output}"
if len(output) > MAX_OUTPUT_CHARS:
output = output[:MAX_OUTPUT_CHARS] + "\n... [truncated]"
return output
except subprocess.TimeoutExpired:
return f"Error: Command timed out after {timeout}s"
except Exception as e:
return f"Error: {e}"
def tool_search_files(pattern: str, path: str = None, glob_filter: str = None) -> str:
search_path = _resolve_path(path) if path else CWD
results = []
count = 0
max_results = 50
try:
compiled = re.compile(pattern, re.IGNORECASE)
except re.error as e:
return f"Error: Invalid regex: {e}"
for root, dirs, files in os.walk(search_path):
# Skip hidden dirs and common noise
dirs[:] = [d for d in dirs if not d.startswith(".") and d not in ("node_modules", "__pycache__", "venv", ".git")]
for fname in files:
if glob_filter and not globlib.fnmatch.fnmatch(fname, glob_filter):
continue
fpath = os.path.join(root, fname)
try:
with open(fpath, "r", errors="replace") as f:
for i, line in enumerate(f, 1):
if compiled.search(line):
rel = os.path.relpath(fpath, search_path)
results.append(f"{rel}:{i}: {line.rstrip()[:120]}")
count += 1
if count >= max_results:
results.append(f"... [{count}+ matches, showing first {max_results}]")
return "\n".join(results)
except (PermissionError, IsADirectoryError, UnicodeDecodeError):
continue
if not results:
return f"No matches for /{pattern}/ in {search_path}"
return "\n".join(results)
def tool_find_files(pattern: str, path: str = None) -> str:
base = _resolve_path(path) if path else CWD
full_pattern = os.path.join(base, pattern)
matches = sorted(globlib.glob(full_pattern, recursive=True))
if not matches:
return f"No files matching {pattern} in {base}"
results = []
for m in matches[:100]:
rel = os.path.relpath(m, base)
try:
stat = os.stat(m)
size = stat.st_size
if size < 1024:
size_str = f"{size}B"
elif size < 1024 * 1024:
size_str = f"{size // 1024}KB"
else:
size_str = f"{size // (1024*1024)}MB"
kind = "dir" if os.path.isdir(m) else "file"
results.append(f" {rel:<50} {size_str:>8} {kind}")
except OSError:
results.append(f" {rel}")
header = f"Found {len(matches)} match{'es' if len(matches) != 1 else ''}:"
if len(matches) > 100:
header += f" (showing first 100 of {len(matches)})"
return header + "\n" + "\n".join(results)
def tool_list_dir(path: str = None) -> str:
target = _resolve_path(path) if path else CWD
if not os.path.isdir(target):
return f"Error: Not a directory: {target}"
entries = []
try:
items = sorted(os.listdir(target))
except PermissionError:
return f"Error: Permission denied: {target}"
for item in items:
if item.startswith("."):
continue
full = os.path.join(target, item)
try:
stat = os.stat(full)
size = stat.st_size
if os.path.isdir(full):
entries.append(f" {item + '/':.<50} {'dir':>8}")
else:
if size < 1024:
size_str = f"{size}B"
elif size < 1024 * 1024:
size_str = f"{size // 1024}KB"
else:
size_str = f"{size // (1024*1024)}MB"
entries.append(f" {item:.<50} {size_str:>8}")
except OSError:
entries.append(f" {item}")
if not entries:
return f"{target}: (empty)"
return f"{target}:\n" + "\n".join(entries)
def tool_fetch_url(url: str) -> str:
try:
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) TrashClaw/0.2'})
with urllib.request.urlopen(req, timeout=30) as response:
html = response.read().decode('utf-8', errors='ignore')
# Simple heuristic HTML tag stripping without external dependencies
# 1. Remove style and script blocks
html = re.sub(r'<script.*?>.*?</script>', '', html, flags=re.DOTALL | re.IGNORECASE)
html = re.sub(r'<style.*?>.*?</style>', '', html, flags=re.DOTALL | re.IGNORECASE)
# 2. Remove all HTML tags
text = re.sub(r'<[^>]+>', ' ', html)
# 3. Fix HTML entities
text = text.replace(' ', ' ').replace('<', '<').replace('>', '>').replace('&', '&').replace('"', '"').replace(''', "'")
# 4. Collapse whitespace
text = re.sub(r'\s+', ' ', text).strip()
if not text:
return f"Fetched {url} successfully, but found no readable text."
if len(text) > MAX_OUTPUT_CHARS:
return f"Fetched {url}:\n\n{text[:MAX_OUTPUT_CHARS]}... [truncated]"
return f"Fetched {url}:\n\n{text}"
except urllib.error.HTTPError as e:
return f"HTTP Error fetching {url}: {e.code} {e.reason}"
except urllib.error.URLError as e:
return f"URL Error fetching {url}: {e.reason}"
except Exception as e:
return f"Error fetching {url}: {str(e)}"
def tool_git_status() -> str:
"""Run git status in CWD."""
try:
result = subprocess.run(
["git", "status", "--short", "--branch"],
cwd=CWD, capture_output=True, text=True, timeout=10
)
output = result.stdout.strip()
if result.returncode != 0:
return f"git error: {result.stderr.strip()}"
return output if output else "Working tree clean."