-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathtools.py
More file actions
2907 lines (2558 loc) · 113 KB
/
tools.py
File metadata and controls
2907 lines (2558 loc) · 113 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
"""Tool definitions and implementations for Dulus."""
import json
import os
import re
import glob as _glob
import difflib
import subprocess
import threading
from pathlib import Path
from typing import Callable, Optional
from tool_registry import ToolDef, register_tool
from tool_registry import execute_tool as _registry_execute
# Import input.py for slash command autocompletion
try:
from input import setup as input_setup, HAS_PROMPT_TOOLKIT, read_line
# Expose setup for backwards compatibility (Dulus uses input.setup())
except ImportError:
HAS_PROMPT_TOOLKIT = False
input_setup = None
read_line = None
# Import dulus's COMMANDS and _CMD_META for autocompletion
try:
from dulus import COMMANDS, _CMD_META
except ImportError:
COMMANDS = {}
_CMD_META = {}
try:
from config import load_config
except ImportError:
load_config = None
try:
from common import clr
except ImportError:
def clr(text, *keys):
return str(text)
# ── AskUserQuestion state ──────────────────────────────────────────────────────
# The main REPL loop drains _pending_questions and fills _question_answers.
_pending_questions: list[dict] = [] # [{id, question, options, allow_freetext, event, result_holder}]
_ask_lock = threading.Lock()
# ── Telegram turn detection (thread-local) ─────────────────────────────────
# Using thread-local storage instead of a shared config key prevents race
# conditions when slash commands run in their own daemon threads while the
# Telegram poll loop and the main REPL loop continue on other threads.
_tg_thread_local = threading.local()
def _is_in_tg_turn(config: dict) -> bool:
"""Return True if the *current thread* is handling a Telegram interaction.
Checks the thread-local flag first (set by the slash-command runner thread),
then falls back to the config key (set by the main REPL for _bg_runner turns).
"""
return getattr(_tg_thread_local, "active", False) or bool(config.get("_in_telegram_turn", False))
# ── Tool JSON schemas (sent to Claude API) ─────────────────────────────────
_LAUNCH_SANDBOX_SCHEMA = {
"name": "LaunchSandbox",
"description": "Start the Dulus Sandbox (mini-OS) web interface in the browser. "
"Provides a visual desktop experience with integrated Dulus Terminal.",
"input_schema": {
"type": "object",
"properties": {
"stop": {"type": "boolean", "description": "If true, stop the server instead of starting it."}
},
},
}
TOOL_SCHEMAS = [
_LAUNCH_SANDBOX_SCHEMA,
{
"name": "Read",
"description": (
"Read a file's contents. Returns content with line numbers "
"(format: 'N\\tline'). Use limit/offset to read large files in chunks."
),
"input_schema": {
"type": "object",
"properties": {
"file_path": {"type": "string", "description": "Absolute file path"},
"limit": {"type": "integer", "description": "Max lines to read"},
"offset": {"type": "integer", "description": "Start line (0-indexed)"},
},
"required": ["file_path"],
},
},
{
"name": "Write",
"description": "Write content to a file. DO NOT use this for temporary results or data that should simply be printed to the user - use PrintToConsole for that. Only use Write for persistent code or documentation.",
"input_schema": {
"type": "object",
"properties": {
"file_path": {"type": "string"},
"content": {"type": "string"},
},
"required": ["file_path", "content"],
},
},
{
"name": "Edit",
"description": (
"Replace exact text in a file. old_string must match exactly (including whitespace). "
"If old_string appears multiple times, use replace_all=true or add more context."
),
"input_schema": {
"type": "object",
"properties": {
"file_path": {"type": "string"},
"old_string": {"type": "string", "description": "Exact text to replace"},
"new_string": {"type": "string", "description": "Replacement text"},
"replace_all": {"type": "boolean", "description": "Replace all occurrences"},
},
"required": ["file_path", "old_string", "new_string"],
},
},
{
"name": "Bash",
"description": "Execute a shell command. Returns stdout+stderr. Stateless (no cd persistence).",
"input_schema": {
"type": "object",
"properties": {
"command": {"type": "string"},
"timeout": {"type": "integer", "description": "Seconds before timeout (default 30). Use 120-300 for package installs (npm, pip, npx), builds, and long-running commands."},
},
"required": ["command"],
},
},
{
"name": "Glob",
"description": "Find files matching a glob pattern. Returns sorted list of matching paths.",
"input_schema": {
"type": "object",
"properties": {
"pattern": {"type": "string", "description": "Glob pattern e.g. **/*.py"},
"path": {"type": "string", "description": "Base directory (default: cwd)"},
},
"required": ["pattern"],
},
},
{
"name": "Grep",
"description": "Search file contents with regex using ripgrep (falls back to grep).",
"input_schema": {
"type": "object",
"properties": {
"pattern": {"type": "string", "description": "Regex pattern"},
"path": {"type": "string", "description": "File or directory to search"},
"glob": {"type": "string", "description": "File filter e.g. *.py"},
"output_mode": {
"type": "string",
"enum": ["content", "files_with_matches", "count"],
"description": "content=matching lines, files_with_matches=file paths, count=match counts",
},
"case_insensitive": {"type": "boolean"},
"context": {"type": "integer", "description": "Lines of context around matches"},
},
"required": ["pattern"],
},
},
{
"name": "WebFetch",
"description": (
"Fetch a URL and return its TEXT content (HTML stripped, no JS). "
"Use for: reading docs, articles, READMEs, API responses, anything "
"where you only need the textual content of a static page.\n\n"
"⚠️ NOT for media playback or anything the user needs to SEE/HEAR. "
"If the user said 'play X on YouTube', 'reproduce / pon / ponme X', "
"'watch Y', 'open Z in the browser', or anything that implies "
"experiencing the page → use WebBridgeNavigate (or NewTab) instead. "
"WebFetch returns text; it does not open a browser window for the user."
),
"input_schema": {
"type": "object",
"properties": {
"url": {"type": "string", "description": "URL to fetch or file:// path"},
},
"required": ["url"],
},
},
{
"name": "WebSearch",
"description": (
"Search the web (Brave or DuckDuckGo) and return TEXT result snippets. "
"Use for: looking up info on behalf of the user — weather, news, prices, "
"definitions, finding the right URL before a WebFetch, anything where "
"the answer is text you'll relay back.\n\n"
"⚠️ NOT for 'play / open / watch / reproduce / pon X' — those are "
"experiential requests. If the user wants to SEE or HEAR something "
"(YouTube video, music, Spotify, a site they want to interact with), "
"go straight to WebBridgeNavigate. Returning a search-result link "
"when they asked you to play it is the wrong tool.\n\n"
"DO NOT save search results to files — process them inline or use "
"PrintToConsole to show them."
),
"input_schema": {
"type": "object",
"properties": {
"query": {"type": "string"},
},
"required": ["query"],
},
},
{
"name": "LineCount",
"description": "Rapidly count the number of lines in a file.",
"input_schema": {
"type": "object",
"properties": {
"file_path": {"type": "string", "description": "Absolute file path"},
},
"required": ["file_path"],
},
},
{
"name": "ExtractTextFromImage",
"description": (
"Extract text from an image LOCALLY via OCR — no vision model "
"tokens, no API calls, offline. Pass an absolute path to a .png "
"/ .jpg / .jpeg / .webp / .bmp / .tiff file (e.g. a screenshot "
"saved by WebBridgeScreenshot). Returns the extracted text.\n\n"
"✅ USE THIS for: screenshots of webpages, receipts, error stacks, "
"code in screenshots, tables, dense text inside images, anything "
"where the meaning lives in WRITTEN TEXT inside the picture.\n\n"
"⚠️ DO NOT use the Read tool on a .png / image file directly — "
"Read will dump several KB of binary garbage characters and burn "
"the user's context window. Image bytes are not text; OCR them "
"first.\n\n"
"⚠️ NOT for: charts, diagrams, faces, scenes, anything where the "
"meaning is VISUAL. For those, ask the user to /img the file or "
"use a vision-capable model.\n\n"
"Engines (auto-fallback): pytesseract (fast, accurate, needs "
"Tesseract binary) → easyocr (pure-Python, heavier, only if user "
"installed it). If neither is available the tool returns a "
"friendly install hint instead of erroring."
),
"input_schema": {
"type": "object",
"properties": {
"image_path": {
"type": "string",
"description": "Absolute path to the image file on disk.",
},
"languages": {
"type": "string",
"description": "Optional ISO-639 codes for OCR languages, comma-separated (e.g. 'en' or 'en,es'). Default: 'en,es'.",
},
},
"required": ["image_path"],
},
},
{
"name": "SearchLastOutput",
"description": (
"Search or summarize the tool outputs accumulated during this turn. "
"Use this to find specific data across one or more tool results that were truncated. "
"With no pattern: returns a summary of the whole accumulation. "
"With a pattern: returns only matching lines with context."
),
"input_schema": {
"type": "object",
"properties": {
"pattern": {
"type": "string",
"description": "Regex pattern to search for (case-insensitive). Omit to get a summary.",
},
"context": {
"type": "integer",
"description": "Lines of context around each match (default 2)",
},
},
"required": [],
},
},
{
"name": "PrintLastOutput",
"description": (
"Print the raw content of the last tool output file directly to terminal. "
"Use this for ASCII art, tables, or large outputs that shouldn't be rewritten by the model. "
"Returns the raw file content for direct display without processing."
),
"input_schema": {
"type": "object",
"properties": {},
"required": [],
},
},
# ── Task tools (schemas also listed here for Claude's tool list) ──────────
{
"name": "TaskCreate",
"description": (
"Create a new task in the task list. "
"Use this to track work items, to-dos, and multi-step plans."
),
"input_schema": {
"type": "object",
"properties": {
"subject": {"type": "string", "description": "Brief title"},
"description": {"type": "string", "description": "What needs to be done"},
"active_form": {"type": "string", "description": "Present-continuous label while in_progress"},
"metadata": {"type": "object", "description": "Arbitrary metadata"},
},
"required": ["subject", "description"],
},
},
{
"name": "TaskUpdate",
"description": (
"Update a task: change status, subject, description, owner, "
"dependency edges, or metadata. "
"Set status='deleted' to remove. "
"Statuses: pending, in_progress, completed, cancelled, deleted."
),
"input_schema": {
"type": "object",
"properties": {
"task_id": {"type": "string"},
"subject": {"type": "string"},
"description": {"type": "string"},
"status": {"type": "string", "enum": ["pending","in_progress","completed","cancelled","deleted"]},
"active_form": {"type": "string"},
"owner": {"type": "string"},
"add_blocks": {"type": "array", "items": {"type": "string"}},
"add_blocked_by":{"type": "array", "items": {"type": "string"}},
"metadata": {"type": "object"},
},
"required": ["task_id"],
},
},
{
"name": "TaskGet",
"description": "Retrieve full details of a single task by ID.",
"input_schema": {
"type": "object",
"properties": {
"task_id": {"type": "string", "description": "Task ID to retrieve"},
},
"required": ["task_id"],
},
},
{
"name": "TaskList",
"description": "List all tasks with their status, owner, and pending blockers.",
"input_schema": {
"type": "object",
"properties": {},
"required": [],
},
},
{
"name": "NotebookEdit",
"description": (
"Edit a Jupyter notebook (.ipynb) cell. "
"Supports replace (modify existing cell), insert (add new cell after cell_id), "
"and delete (remove cell) operations. "
"Read the notebook with the Read tool first to see cell IDs."
),
"input_schema": {
"type": "object",
"properties": {
"notebook_path": {
"type": "string",
"description": "Absolute path to the .ipynb notebook file",
},
"new_source": {
"type": "string",
"description": "New source code/text for the cell",
},
"cell_id": {
"type": "string",
"description": (
"ID of the cell to edit. For insert, the new cell is inserted after this cell "
"(or at the beginning if omitted). Use 'cell-N' (0-indexed) if no IDs are set."
),
},
"cell_type": {
"type": "string",
"enum": ["code", "markdown"],
"description": "Cell type. Required for insert; defaults to current type for replace.",
},
"edit_mode": {
"type": "string",
"enum": ["replace", "insert", "delete"],
"description": "replace (default) / insert / delete",
},
},
"required": ["notebook_path", "new_source"],
},
},
{
"name": "GetDiagnostics",
"description": (
"Get LSP-style diagnostics (errors, warnings, hints) for a source file. "
"Uses pyright/mypy/flake8 for Python, tsc for TypeScript/JavaScript, "
"and shellcheck for shell scripts. Returns structured diagnostic output."
),
"input_schema": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "Absolute or relative path to the file to diagnose",
},
"language": {
"type": "string",
"description": (
"Override auto-detected language: python, javascript, typescript, "
"shellscript. Omit to auto-detect from file extension."
),
},
},
"required": ["file_path"],
},
},
{
"name": "AskUserQuestion",
"description": (
"Pause execution and ask the user a clarifying question. "
"Use this when you need a decision from the user before proceeding. "
"Returns the user's answer as a string."
),
"input_schema": {
"type": "object",
"properties": {
"question": {
"type": "string",
"description": "The question to ask the user.",
},
"options": {
"type": "array",
"description": "Optional list of choices. Each item: {label, description}.",
"items": {
"type": "object",
"properties": {
"label": {"type": "string"},
"description": {"type": "string"},
},
"required": ["label"],
},
},
"allow_freetext": {
"type": "boolean",
"description": "If true (default), user may type a free-text answer instead of selecting an option.",
},
},
"required": ["question"],
},
},
{
"name": "Reminder",
"description": (
"Schedule a background reminder. When the duration elapses, a (System Automated Event) notification is injected "
"so you can wake up and execute deferred monitoring tasks or checks. "
"Use ONLY for genuine deferred wake-ups (e.g. 'remind me in 10 minutes to check the deploy'). "
"For pausing BETWEEN tool calls in the same turn, use `Bash('sleep N')` instead — "
"the Reminder countdown starts immediately and you should END the turn after calling it."
),
"input_schema": {
"type": "object",
"properties": {
"seconds": {"type": "integer", "description": "Number of seconds to sleep before waking up."}
},
"required": ["seconds"],
},
},
{
"name": "PrintToConsole",
"description": (
"Display text to the USER in the chat console WITHOUT using response tokens. "
"WARNING: This tool CANNOT save files. The 'file_path' parameter is for READING existing files only. "
"DO NOT try to use this to 'store' results. Use the 'content' parameter to show results to the user. "
"Perfect for: progress updates, step-by-step logs, lengthy explanations, debug info. "
"The content appears in the chat immediately as the tool result. "
"CRITICAL: After using PrintToConsole, DO NOT repeat the same content in your response."
),
"input_schema": {
"type": "object",
"properties": {
"content": {
"type": "string",
"description": "Text to display to the user. Supports newlines and formatting. This appears in the chat console.",
},
"style": {
"type": "string",
"enum": ["normal", "success", "info", "warning", "error"],
"description": "Visual style prefix: success=[OK], info=[i], warning=[!], error=[X], normal=none",
"default": "normal",
},
"prefix": {
"type": "string",
"description": "Optional source prefix like '[TOOL]' shown before the content",
"default": "",
},
"from_line": {
"type": "integer",
"description": "Extract content starting from this line number (1-indexed). Use with to_line to show specific range.",
"minimum": 1,
},
"to_line": {
"type": "integer",
"description": "Extract content up to this line number (inclusive). Use with from_line to show specific range.",
"minimum": 1,
},
"file_path": {
"type": "string",
"description": "Path to a file to read and display. If provided, reads this file instead of using content parameter. Useful for job files, logs, etc.",
},
},
"required": [],
},
},
]
# ── Safe bash commands (never ask permission) ───────────────────────────────
_SAFE_PREFIXES = (
"ls", "cat", "head", "tail", "wc", "pwd", "echo", "printf", "date",
"which", "type", "env", "printenv", "uname", "whoami", "id",
"git log", "git status", "git diff", "git show", "git branch",
"git remote", "git stash list", "git tag",
"find ", "grep ", "rg ", "ag ", "fd ",
"python ", "python3 ", "node ", "ruby ", "perl ",
"pip show", "pip list", "npm list", "cargo metadata",
"df ", "du ", "free ", "top -bn", "ps ",
"curl -I", "curl --head",
)
def _is_safe_bash(cmd: str) -> bool:
c = cmd.strip()
return any(c.startswith(p) for p in _SAFE_PREFIXES)
# ── Diff helpers ──────────────────────────────────────────────────────────
def generate_unified_diff(old, new, filename, context_lines=3):
old_lines = old.splitlines(keepends=True)
new_lines = new.splitlines(keepends=True)
diff = difflib.unified_diff(old_lines, new_lines,
fromfile=f"a/{filename}", tofile=f"b/{filename}", n=context_lines)
return "".join(diff)
def maybe_truncate_diff(diff_text, max_lines=80):
lines = diff_text.splitlines()
if len(lines) <= max_lines:
return diff_text
shown = lines[:max_lines]
remaining = len(lines) - max_lines
return "\n".join(shown) + f"\n\n[... {remaining} more lines ...]"
# ── Tool implementations ───────────────────────────────────────────────────
_DEFAULT_READ_LIMIT = 1000 # kimi-cli default
def _read(file_path: str, limit: int = None, offset: int = None) -> str:
p = Path(file_path).expanduser().resolve()
if not p.exists():
return f"Error: file not found: {p}"
if p.is_dir():
return f"Error: {p} is a directory"
try:
# Default limit so the model doesn't accidentally swallow multi-MB files.
effective_limit = limit if limit is not None else _DEFAULT_READ_LIMIT
# For small files, we can just read everything. For large files, we should iterate.
# Threshold for "large" file: 10MB
size = p.stat().st_size
if size < 10 * 1024 * 1024:
lines = p.read_text(encoding="utf-8", errors="replace", newline="").splitlines(keepends=True)
total = len(lines)
start = offset or 0
chunk = lines[start:start + effective_limit]
else:
# Memory efficient reading for large files
total = 0
chunk = []
start = offset or 0
end = start + effective_limit
with p.open("r", encoding="utf-8", errors="replace", newline="") as f:
for i, line in enumerate(f):
total += 1
if i >= start and i < end:
chunk.append(line)
if not chunk and total > 0:
return f"(offset {start} >= total lines {total})"
if not chunk:
return "(empty file)"
header = f"[File: {file_path} | Total lines: {total} | Reading: {start+1} to {start+len(chunk)}]\n"
if limit is None and total > effective_limit:
header += f"[TRUNCATED — default limit of {effective_limit} lines applied. Use offset + limit to read more.]\n"
content = "".join(f"{start + i + 1:6}\t{l}" for i, l in enumerate(chunk))
return header + content
except Exception as e:
return f"Error: {e}"
def _line_count(file_path: str) -> str:
p = Path(file_path)
if not p.exists():
return f"Error: file not found: {file_path}"
try:
count = 0
with p.open("rb") as f:
for line in f:
count += 1
return f"File: {file_path}\nTotal lines: {count}"
except Exception as e:
return f"Error: {e}"
def _ocr_extract(image_path: str, languages: str = "en,es") -> str:
"""Local OCR backend for the ExtractTextFromImage tool.
Mirrors the engine-order logic of cmd_ocr in dulus.py: try pytesseract
first (fast, accurate, needs Tesseract binary), fall back to easyocr
(pure-Python, heavier, only if user installed it). Returns the
extracted text as a plain string, or a friendly install hint when
neither engine is available — never raises so the model gets a
useful tool response instead of a tool-error stack.
"""
import os as _os, sys as _sys
p = Path(image_path)
if not p.exists():
return f"Error: file not found: {image_path}"
if not p.is_file():
return f"Error: not a file: {image_path}"
# ── Engine 1: pytesseract ────────────────────────────────────────
try:
import pytesseract # type: ignore
from PIL import Image
if _sys.platform == "win32":
for tp in (
r"C:\Program Files\Tesseract-OCR\tesseract.exe",
r"C:\Program Files (x86)\Tesseract-OCR\tesseract.exe",
):
if _os.path.exists(tp):
pytesseract.pytesseract.tesseract_cmd = tp # type: ignore[attr-defined]
break
try:
# pytesseract takes a single lang= string like "eng+spa". Map
# ISO-639 (en, es) → pytesseract codes (eng, spa).
iso_to_tess = {
"en": "eng", "es": "spa", "fr": "fra", "de": "deu",
"it": "ita", "pt": "por", "ja": "jpn", "ko": "kor",
"zh": "chi_sim", "ru": "rus", "ar": "ara",
}
lang_codes = [iso_to_tess.get(l.strip(), l.strip())
for l in (languages or "en").split(",") if l.strip()]
lang_arg = "+".join(lang_codes) or "eng"
text = pytesseract.image_to_string(Image.open(image_path), lang=lang_arg).rstrip()
if text:
return f"[engine: tesseract, languages: {lang_arg}]\n\n{text}"
except pytesseract.TesseractNotFoundError: # type: ignore[attr-defined]
pass
except Exception as e:
# tesseract data file missing for the requested language is the
# common subcase here; retry with English only before giving up.
try:
text = pytesseract.image_to_string(Image.open(image_path)).rstrip()
if text:
return f"[engine: tesseract, languages: eng (fallback after: {e})]\n\n{text}"
except Exception:
pass
except ImportError:
pass
# ── Engine 2: easyocr fallback ───────────────────────────────────
try:
import easyocr # type: ignore
langs = [l.strip() for l in (languages or "en").split(",") if l.strip()] or ["en"]
reader = easyocr.Reader(langs, gpu=False, verbose=False)
chunks = reader.readtext(image_path, detail=0)
text = "\n".join(chunks).rstrip()
if text:
return f"[engine: easyocr, languages: {','.join(langs)}]\n\n{text}"
return f"[engine: easyocr] ran but extracted no text — image may be too small/blurry or have no readable text."
except ImportError:
pass
# ── No engine available ──────────────────────────────────────────
return (
"Error: no OCR engine available. Install one:\n"
" pip install dulus[ocr] (uses pytesseract — needs Tesseract binary)\n"
" Windows: winget install -e --id UB-Mannheim.TesseractOCR\n"
" Linux: sudo apt-get install -y tesseract-ocr\n"
" macOS: brew install tesseract\n"
"Or as a pure-Python fallback (~1 GB):\n"
" pip install easyocr"
)
def _print_last_output() -> str:
"""Print the full content of the last tool output directly.
Use this to display large outputs (ASCII art, logs, etc.) without re-writing them.
"""
out_file = Path.home() / ".dulus" / "last_tool_output.txt"
if not out_file.exists():
return "No saved tool output available."
try:
content = out_file.read_text(encoding="utf-8", errors="replace")
if not content.strip():
return "Last tool output is empty."
return content
except Exception as e:
return f"Error reading saved output: {e}"
def _search_last_output(pattern: str = None, context: int = 2) -> str:
"""Search or summarize the tool outputs accumulated during this turn."""
out_file = Path.home() / ".dulus" / "last_tool_output.txt"
if not out_file.exists():
return "No saved tool output available. No tool has produced truncated output yet."
try:
lines = out_file.read_text(encoding="utf-8", errors="replace").splitlines()
except Exception as e:
return f"Error reading saved output: {e}"
total = len(lines)
if total == 0:
return "Saved tool output is empty."
# No pattern → summary mode
if not pattern:
preview_n = 30
head = lines[:preview_n]
tail = lines[-preview_n:] if total > preview_n * 2 else []
parts = [f"[Last tool output: {total} lines]"]
parts.append("── First {0} lines ──".format(min(preview_n, total)))
for i, l in enumerate(head):
parts.append(f"{i + 1:6}\t{l}")
if tail:
parts.append(f"\n── Last {preview_n} lines ──")
start = total - preview_n
for i, l in enumerate(tail):
parts.append(f"{start + i + 1:6}\t{l}")
return "\n".join(parts)
# Pattern mode → search with context
import re as _re
try:
rx = _re.compile(pattern, _re.IGNORECASE)
except _re.error as e:
return f"Invalid regex: {e}"
matches = []
for i, line in enumerate(lines):
if rx.search(line):
start = max(0, i - context)
end = min(total, i + context + 1)
block = []
for j in range(start, end):
marker = ">>>" if j == i else " "
block.append(f"{marker} {j + 1:6}\t{lines[j]}")
matches.append("\n".join(block))
if not matches:
return f"No matches for '{pattern}' in {total} lines of saved output."
header = f"[Found {len(matches)} match(es) in {total} lines]"
# Cap output to avoid blowing up context
result = header + "\n\n" + "\n---\n".join(matches)
if len(result) > 16000:
result = result[:16000] + f"\n\n... (output capped — {len(matches)} total matches, refine your pattern)"
# SAVE filtered result as new last_output so PrintLastOutput can display it
try:
out_file.write_text(result, encoding="utf-8")
except Exception:
pass # Silently fail if can't write
return result
def _write(file_path: str, content: str) -> str:
p = Path(file_path)
try:
is_new = not p.exists()
# Ensure utf-8 and newline="" for reading existing content to generate diff
old_content = "" if is_new else p.read_text(encoding="utf-8", errors="replace", newline="")
p.parent.mkdir(parents=True, exist_ok=True)
# Always write as utf-8 with newline="" to prevent double CRLF on Windows
p.write_text(content, encoding="utf-8", newline="")
if is_new:
lc = content.count("\n") + (1 if content and not content.endswith("\n") else 0)
return f"Created {file_path} ({lc} lines)"
filename = p.name
diff = generate_unified_diff(old_content, content, filename)
if not diff:
return f"No changes in {file_path}"
truncated = maybe_truncate_diff(diff)
return f"File updated — {file_path}:\n\n{truncated}"
except Exception as e:
return f"Error: {e}"
def _edit(file_path: str, old_string: str, new_string: str, replace_all: bool = False) -> str:
p = Path(file_path)
if not p.exists():
return f"Error: file not found: {file_path}"
try:
# Read with newline="" to get original line endings
content = p.read_text(encoding="utf-8", errors="replace", newline="")
# Detect original line endings: only treat as pure CRLF if every \n is part of \r\n
crlf_count = content.count("\r\n")
lf_count = content.count("\n")
is_pure_crlf = crlf_count > 0 and crlf_count == lf_count
# Normalize line endings to avoid \r\n vs \n mismatch during matching
content_norm = content.replace("\r\n", "\n")
old_norm = old_string.replace("\r\n", "\n")
new_norm = new_string.replace("\r\n", "\n")
count = content_norm.count(old_norm)
if count == 0:
return "Error: old_string not found in file. Please ensure EXACT match, including all exact leading spaces/indentation and trailing newlines."
if count > 1 and not replace_all:
return (f"Error: old_string appears {count} times. "
"Provide more context to make it unique, or use replace_all=true.")
old_content_norm = content_norm
new_content_norm = content_norm.replace(old_norm, new_norm) if replace_all else \
content_norm.replace(old_norm, new_norm, 1)
# Restore CRLF only for pure-CRLF files; mixed or LF-only files stay as LF
if is_pure_crlf:
final_content = new_content_norm.replace("\n", "\r\n")
old_content_final = content
else:
final_content = new_content_norm
old_content_final = content_norm
# Write with newline="" to prevent double CRLF translation on Windows
p.write_text(final_content, encoding="utf-8", newline="")
filename = p.name
diff = generate_unified_diff(old_content_final, final_content, filename)
return f"Changes applied to {filename}:\n\n{diff}"
except Exception as e:
return f"Error: {e}"
def _kill_proc_tree(pid: int):
"""Kill a process and all its children."""
import sys as _sys
if _sys.platform == "win32":
# taskkill /T kills the entire process tree on Windows
subprocess.run(["taskkill", "/F", "/T", "/PID", str(pid)],
capture_output=True)
else:
import signal
try:
os.killpg(os.getpgid(pid), signal.SIGKILL)
except (ProcessLookupError, PermissionError):
try:
os.kill(pid, signal.SIGKILL)
except (ProcessLookupError, PermissionError):
pass
def _find_windows_bash():
"""Return (kind, path) for the best bash available on Windows, or None."""
import shutil
if not hasattr(_find_windows_bash, "_cache"):
result = None
# 1. bash already in PATH (Git for Windows added to PATH, MSYS2, etc.)
bash_in_path = shutil.which("bash")
if bash_in_path:
# Skip WSL bash stub disguised as native bash
if "system32" not in bash_in_path.lower() and "sysnative" not in bash_in_path.lower() and "syswow64" not in bash_in_path.lower():
result = ("gitbash", bash_in_path)
# 2. Git Bash at default install locations
if result is None:
for candidate in [
r"C:\Program Files\Git\bin\bash.exe",
r"C:\Program Files (x86)\Git\bin\bash.exe",
]:
if Path(candidate).exists():
result = ("gitbash", candidate)
break
# 3. WSL
if result is None:
wsl = shutil.which("wsl")
if wsl:
try:
r = subprocess.run(["wsl", "echo", "ok"],
capture_output=True, text=True, timeout=5)
if r.returncode == 0:
result = ("wsl", wsl)
except Exception:
pass
_find_windows_bash._cache = result
return _find_windows_bash._cache
def _find_shell_by_type(shell_type: str, forced_path: str = ""):
"""Find a specific shell type on Windows. Returns (kind, path) or None."""
import shutil
# Handle custom shell with forced path
if shell_type == "custom" and forced_path and Path(forced_path).exists():
return ("custom", forced_path)
if shell_type == "gitbash":
# Try bash in PATH first (but not WSL stub)
bash_in_path = shutil.which("bash")
if bash_in_path:
if "system32" not in bash_in_path.lower() and "sysnative" not in bash_in_path.lower() and "syswow64" not in bash_in_path.lower():
return ("gitbash", bash_in_path)
# Try default Git locations
for candidate in [
r"C:\Program Files\Git\bin\bash.exe",
r"C:\Program Files (x86)\Git\bin\bash.exe",
]:
if Path(candidate).exists():
return ("gitbash", candidate)
elif shell_type == "wsl":
wsl = shutil.which("wsl")
if wsl:
try:
r = subprocess.run(["wsl", "echo", "ok"],
capture_output=True, text=True, timeout=5)
if r.returncode == 0:
return ("wsl", wsl)
except Exception:
pass
elif shell_type == "powershell":
# Try PowerShell Core first, then Windows PowerShell
candidates = [
shutil.which("pwsh"), # PowerShell Core
shutil.which("powershell"),
r"C:\Program Files\PowerShell\7\pwsh.exe",
r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe",
]
for candidate in candidates:
if candidate and Path(candidate).exists():
return ("powershell", candidate)
elif shell_type == "cmd":
cmd = shutil.which("cmd") or r"C:\Windows\System32\cmd.exe"
if Path(cmd).exists():
return ("cmd", cmd)
return None
def _win_to_posix(path_str: str, wsl: bool = False) -> str:
"""Convert a Windows path string to POSIX for bash/WSL.
C:\\Users\\foo → /c/Users/foo (gitbash)
C:\\Users\\foo → /mnt/c/Users/foo (wsl)
"""
import re
def _replace(m):
drive = m.group(1).lower()
rest = m.group(2).replace("\\", "/")
prefix = f"/mnt/{drive}" if wsl else f"/{drive}"
return prefix + "/" + rest
return re.sub(r"(?<![A-Za-z])([A-Za-z]):[\\/]([^'\";\n]*)", _replace, path_str)
# ── Bash sandbox: blocked dangerous command patterns ─────────────────────
_BASH_BLOCKED_PATTERNS: list[str] = [
# rm -rf targeting system / home
r"rm\s+-[a-zA-Z]*r[a-zA-Z]*f?\s+/(?:\s*;|\s*&&|\s*\|\||\s*$)",
r"rm\s+-[a-zA-Z]*r[a-zA-Z]*f?\s+/\*",
r"rm\s+-[a-zA-Z]*r[a-zA-Z]*f?\s+~",
# Disk destruction
r"dd\s+.*of=/dev/[sh]d[a-z]",
r"dd\s+.*of=/dev/nvme",
r"dd\s+.*of=/dev/mmcblk",
r">\s*/dev/[sh]d[a-z]",
r">\s*/dev/nvme",
# Formatters
r"mkfs\.\w+\s+/dev/",
r"mkfs\s+/dev/",
r"fdisk\s+/dev/",
r"parted\s+/dev/",
# Permission destruction
r"chmod\s+-[a-zA-Z]*R[a-zA-Z]*\s+777\s+/",
# Fork bomb
r":\s*\(\s*\)\s*\{\s*:\s*\|:\s*&\s*\}\s*;\s*:",
# Curl/wget pipe-to-shell
r"curl\s+.*\|\s*(?:bash|sh|zsh|fish)",
r"wget\s+.*\|\s*(?:bash|sh|zsh|fish)",
# Sensitive file reads
r"cat\s+.*(?:/etc/shadow|/etc/gshadow|/etc/master\.passwd)",
# Data exfiltration via curl
r"curl\s+.*(?:--data|@-|-d\s+@)",
r"curl\s+.*-T\s+\S+",