tass 0.1.10__py3-none-any.whl → 0.1.12__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
src/app.py CHANGED
@@ -1,11 +1,7 @@
1
1
  import json
2
- import os
3
- import subprocess
4
- from pathlib import Path
5
2
 
6
- import requests
7
3
  from prompt_toolkit import prompt
8
- from rich.console import Console, Group
4
+ from rich.console import Group
9
5
  from rich.live import Live
10
6
  from rich.markdown import Markdown
11
7
  from rich.panel import Panel
@@ -13,34 +9,39 @@ from rich.text import Text
13
9
 
14
10
  from src.constants import (
15
11
  SYSTEM_PROMPT,
16
- TOOLS,
12
+ console,
13
+ )
14
+ from src.llm_client import LLMClient
15
+ from src.tools import (
16
+ EDIT_FILE_TOOL,
17
+ EXECUTE_TOOL,
18
+ READ_FILE_TOOL,
19
+ edit_file,
20
+ execute,
21
+ read_file,
17
22
  )
18
23
  from src.utils import (
19
24
  FileCompleter,
20
25
  create_key_bindings,
21
- is_read_only_command,
22
26
  )
23
27
 
24
- console = Console()
25
-
26
28
 
27
29
  class TassApp:
28
30
 
29
31
  def __init__(self):
30
32
  self.messages: list[dict] = [{"role": "system", "content": SYSTEM_PROMPT}]
31
- self.host = os.environ.get("TASS_HOST", "http://localhost:8080")
33
+ self.llm_client = LLMClient()
32
34
  self.key_bindings = create_key_bindings()
33
35
  self.file_completer = FileCompleter()
34
36
  self.TOOLS_MAP = {
35
- "execute": self.execute,
36
- "read_file": self.read_file,
37
- "edit_file": self.edit_file,
37
+ "execute": execute,
38
+ "read_file": read_file,
39
+ "edit_file": edit_file,
38
40
  }
39
41
 
40
- def _check_llm_host(self):
41
- test_url = f"{self.host}/v1/models"
42
+ def check_llm_host(self):
42
43
  try:
43
- response = requests.get(test_url, timeout=2)
44
+ response = self.llm_client.get_models()
44
45
  console.print("Terminal Assistant [green](LLM connection ✓)[/green]")
45
46
  if response.status_code == 200:
46
47
  return
@@ -48,20 +49,20 @@ class TassApp:
48
49
  console.print("Terminal Assistant [red](LLM connection ✗)[/red]")
49
50
 
50
51
  console.print("\n[red]Could not connect to LLM[/red]")
51
- console.print(f"If your LLM isn't running on {self.host}, you can set the [bold]TASS_HOST[/] environment variable to a different URL.")
52
+ console.print(f"If your LLM isn't running on {self.llm_client.host}, you can set the [bold]TASS_HOST[/] environment variable to a different URL.")
52
53
  new_host = console.input(
53
54
  "Enter a different URL for this session (or press Enter to keep current): "
54
55
  ).strip()
55
56
 
56
57
  if new_host:
57
- self.host = new_host
58
+ self.llm_client.host = new_host
58
59
 
59
60
  try:
60
- response = requests.get(f"{self.host}/v1/models", timeout=2)
61
+ response = self.llm_client.get_models()
61
62
  if response.status_code == 200:
62
- console.print(f"[green]Connection established to {self.host}[/green]")
63
+ console.print(f"[green]Connection established to {self.llm_client.host}[/green]")
63
64
  except Exception:
64
- console.print(f"[red]Unable to verify new host {self.host}. Continuing with it anyway.[/red]")
65
+ console.print(f"[red]Unable to verify new host {self.llm_client.host}. Continuing with it anyway.[/red]")
65
66
 
66
67
  def summarize(self):
67
68
  max_messages = 20
@@ -78,15 +79,13 @@ class TassApp:
78
79
  )
79
80
 
80
81
  console.print("\n - Summarizing conversation...")
81
- response = requests.post(
82
- f"{self.host}/v1/chat/completions",
83
- json={
84
- "messages": self.messages + [{"role": "user", "content": prompt}],
85
- "tools": TOOLS, # For caching purposes
86
- "chat_template_kwargs": {
87
- "reasoning_effort": "medium",
88
- },
89
- },
82
+ response = self.llm_client.get_chat_completions(
83
+ messages=self.messages + [{"role": "user", "content": prompt}],
84
+ tools=[
85
+ EDIT_FILE_TOOL,
86
+ EXECUTE_TOOL,
87
+ READ_FILE_TOOL,
88
+ ], # For caching purposes
90
89
  )
91
90
  data = response.json()
92
91
  summary = data["choices"][0]["message"]["content"]
@@ -94,16 +93,13 @@ class TassApp:
94
93
  console.print(" [green]Summarization completed[/green]")
95
94
 
96
95
  def call_llm(self) -> bool:
97
- response = requests.post(
98
- f"{self.host}/v1/chat/completions",
99
- json={
100
- "messages": self.messages,
101
- "tools": TOOLS,
102
- "chat_template_kwargs": {
103
- "reasoning_effort": "medium",
104
- },
105
- "stream": True,
106
- },
96
+ response = self.llm_client.get_chat_completions(
97
+ messages=self.messages,
98
+ tools=[
99
+ EDIT_FILE_TOOL,
100
+ EXECUTE_TOOL,
101
+ READ_FILE_TOOL,
102
+ ],
107
103
  stream=True,
108
104
  )
109
105
 
@@ -223,178 +219,13 @@ class TassApp:
223
219
  )
224
220
  return False
225
221
  except Exception as e:
226
- self.messages.append({"role": "user", "content": str(e)})
222
+ self.messages.append({"role": "user", "content": f"Tool call failed: {e}"})
223
+ console.print(f" [red]Tool call failed: {str(e).strip()}[/red]")
227
224
  return self.call_llm()
228
225
 
229
- def read_file(self, path: str, start: int = 1, num_lines: int = 1000) -> str:
230
- if start == 1 and num_lines == 1000:
231
- console.print(f" └ Reading file [bold]{path}[/]...")
232
- else:
233
- last_line = start + num_lines - 1
234
- console.print(f" └ Reading file [bold]{path}[/] (lines {start}-{last_line})...")
235
-
236
- try:
237
- result = subprocess.run(
238
- f"cat -n {path}",
239
- shell=True,
240
- capture_output=True,
241
- text=True,
242
- )
243
- except Exception as e:
244
- console.print(" [red]read_file failed[/red]")
245
- console.print(f" [red]{str(e).strip()}[/red]")
246
- return f"read_file failed: {str(e)}"
247
-
248
- out = result.stdout
249
- err = result.stderr.strip()
250
- if result.returncode != 0:
251
- console.print(" [red]read_file failed[/red]")
252
- if err:
253
- console.print(f" [red]{err}[/red]")
254
- return f"read_file failed: {err}"
255
-
256
- lines = []
257
- line_num = 1
258
- for line in out.split("\n"):
259
- if line_num < start:
260
- line_num += 1
261
- continue
262
-
263
- lines.append(line)
264
- line_num += 1
265
-
266
- if len(lines) >= num_lines:
267
- lines.append("... (truncated)")
268
- break
269
-
270
- console.print(" [green]Command succeeded[/green]")
271
- return "\n".join(lines)
272
-
273
- def edit_file(self, path: str, edits: list[dict]) -> str:
274
- console.print(json.dumps(edits, indent=2))
275
- for edit in edits:
276
- edit["applied"] = False
277
-
278
- def find_edit(n: int) -> dict | None:
279
- for edit in edits:
280
- if edit["line_start"] <= n <= edit["line_end"]:
281
- return edit
282
-
283
- return None
284
-
285
- file_exists = Path(path).exists()
286
- if file_exists:
287
- with open(path, "r") as f:
288
- original_content = f.read()
289
- else:
290
- original_content = ""
291
-
292
- final_lines = []
293
- original_lines = original_content.split("\n")
294
- diff_text = f"{'Editing' if file_exists else 'Creating'} {path}"
295
- for i, line in enumerate(original_lines):
296
- line_num = i + 1
297
- edit = find_edit(line_num)
298
- if not edit:
299
- final_lines.append(line)
300
- continue
301
-
302
- if edit["applied"]:
303
- continue
304
-
305
- replace_lines = edit["content"].split("\n")
306
- if edit["content"]:
307
- final_lines.extend(replace_lines)
308
- original_lines = original_content.split("\n")
309
- replaced_lines = original_lines[edit["line_start"] - 1:edit["line_end"]]
310
-
311
- prev_line_num = line_num if line_num == 1 else line_num - 1
312
- line_before = "" if i == 0 else f" {original_lines[i - 1]}\n"
313
- line_after = "" if edit["line_end"] == len(original_lines) else f"\n {original_lines[edit['line_end']]}"
314
- replaced_with_minuses = "\n".join([f"-{line}" for line in replaced_lines]) if file_exists else ""
315
- replaced_with_pluses = ""
316
- if edit["content"]:
317
- replaced_with_pluses = "\n" + "\n".join([f"+{line}" for line in edit["content"].split("\n")])
318
- diff_text = f"{diff_text}\n\n@@ -{prev_line_num},{len(replaced_lines)} +{prev_line_num},{len(replace_lines)} @@\n{line_before}{replaced_with_minuses}{replaced_with_pluses}{line_after}"
319
- edit["applied"] = True
320
-
321
- console.print()
322
- console.print(Markdown(f"```diff\n{diff_text}\n```"))
323
- answer = console.input("\n[bold]Run?[/] ([bold]Y[/]/n): ").strip().lower()
324
- if answer not in ("yes", "y", ""):
325
- reason = console.input("Why not? (optional, press Enter to skip): ").strip()
326
- return f"User declined: {reason or 'no reason'}"
327
-
328
- console.print(" └ Running...")
329
- try:
330
- with open(path, "w") as f:
331
- f.write("\n".join(final_lines))
332
- except Exception as e:
333
- console.print(" [red]edit_file failed[/red]")
334
- console.print(f" [red]{str(e).strip()}[/red]")
335
- return f"edit_file failed: {str(e).strip()}"
336
-
337
- console.print(" [green]Command succeeded[/green]")
338
- return f"Successfully edited {path}"
339
-
340
- def execute(self, command: str, explanation: str) -> str:
341
- command = command.strip()
342
- requires_confirmation = not is_read_only_command(command)
343
- if requires_confirmation:
344
- console.print()
345
- console.print(Markdown(f"```shell\n{command}\n```"))
346
- if explanation:
347
- console.print(f"Explanation: {explanation}")
348
- answer = console.input("\n[bold]Run?[/] ([bold]Y[/]/n): ").strip().lower()
349
- if answer not in ("yes", "y", ""):
350
- reason = console.input("Why not? (optional, press Enter to skip): ").strip()
351
- return f"User declined: {reason or 'no reason'}"
352
-
353
- if requires_confirmation:
354
- console.print(" └ Running...")
355
- else:
356
- console.print(f" └ Running [bold]{command}[/] (Explanation: {explanation})...")
357
-
358
- try:
359
- result = subprocess.run(
360
- command,
361
- shell=True,
362
- capture_output=True,
363
- text=True,
364
- )
365
- except Exception as e:
366
- console.print(" [red]subprocess.run failed[/red]")
367
- console.print(f" [red]{str(e).strip()}[/red]")
368
- return f"subprocess.run failed: {str(e).strip()}"
369
-
370
- out = result.stdout
371
- err = result.stderr.strip()
372
- if result.returncode == 0:
373
- console.print(" [green]Command succeeded[/green]")
374
- else:
375
- console.print(f" [red]Command failed[/red] (code {result.returncode})")
376
- if err:
377
- console.print(f" [red]{err}[/red]")
378
-
379
- if len(out.split("\n")) > 1000:
380
- out_first_1000 = "\n".join(out.split("\n")[:1000])
381
- out = f"{out_first_1000}... (Truncated)"
382
-
383
- if len(err.split("\n")) > 1000:
384
- err_first_1000 = "\n".join(err.split("\n")[:1000])
385
- err = f"{err_first_1000}... (Truncated)"
386
-
387
- if len(out) > 20000:
388
- out = f"{out[:20000]}... (Truncated)"
389
-
390
- if len(err) > 20000:
391
- err = f"{err[:20000]}... (Truncated)"
392
-
393
- return f"Command output (exit {result.returncode}):\n{out}\n{err}"
394
-
395
226
  def run(self):
396
227
  try:
397
- self._check_llm_host()
228
+ self.check_llm_host()
398
229
  except KeyboardInterrupt:
399
230
  console.print("\nBye!")
400
231
  return
src/constants.py CHANGED
@@ -1,6 +1,10 @@
1
1
  from pathlib import Path
2
2
 
3
- cwd_path = Path.cwd().resolve()
3
+ from rich.console import Console
4
+
5
+
6
+ console = Console()
7
+ CWD_PATH = Path.cwd().resolve()
4
8
 
5
9
  SYSTEM_PROMPT = f"""You are tass, or Terminal Assistant, a helpful AI that executes shell commands based on natural-language requests.
6
10
 
@@ -8,115 +12,6 @@ If the user's request involves making changes to the filesystem such as creating
8
12
 
9
13
  If a user asks for an answer or explanation to something instead of requesting to run a command, answer briefly and concisely. Do not supply extra information, suggestions, tips, or anything of the sort.
10
14
 
11
- Current working directory: {cwd_path}"""
12
-
13
- TOOLS = [
14
- {
15
- "type": "function",
16
- "function": {
17
- "name": "execute",
18
- "description": "Executes a shell command.",
19
- "parameters": {
20
- "type": "object",
21
- "properties": {
22
- "command": {
23
- "type": "string",
24
- "description": "Full shell command to be executed.",
25
- },
26
- "explanation": {
27
- "type": "string",
28
- "description": "A brief explanation of why you want to run this command. Keep it to a single sentence.",
29
- },
30
- },
31
- "required": ["command", "explanation"],
32
- "$schema": "http://json-schema.org/draft-07/schema#",
33
- },
34
- },
35
- },
36
- {
37
- "type": "function",
38
- "function": {
39
- "name": "edit_file",
40
- "description": "Edits (or creates) a file. Can make multiple edits in one call. Each edit replaces the contents between 'line_start' and 'line_end' inclusive with 'content'. If creating a file, only return a single edit where 'line_start' and 'line_end' are both 1 and 'content' is the entire contents of the file. You must use the read_file tool before editing a file.",
41
- "parameters": {
42
- "type": "object",
43
- "properties": {
44
- "path": {
45
- "type": "string",
46
- "description": "Relative path of the file",
47
- },
48
- "edits": {
49
- "type": "array",
50
- "description": "List of edits to apply. Each edit must contain 'line_start', 'line_end', and 'content'.",
51
- "items": {
52
- "type": "object",
53
- "properties": {
54
- "line_start": {
55
- "type": "integer",
56
- "description": "The first line to remove (inclusive)",
57
- },
58
- "line_end": {
59
- "type": "integer",
60
- "description": "The last line to remove (inclusive)",
61
- },
62
- "content": {
63
- "type": "string",
64
- "description": "The content to replace with. Must have the correct spacing and indentation for all lines.",
65
- },
66
- },
67
- "required": ["line_start", "line_end", "content"],
68
- },
69
- },
70
- },
71
- "required": ["path", "edits"],
72
- "$schema": "http://json-schema.org/draft-07/schema#",
73
- },
74
- },
75
- },
76
- {
77
- "type": "function",
78
- "function": {
79
- "name": "read_file",
80
- "description": "Read a file's contents (the first 1000 lines by default). When reading a file for the first time, do not change the defaults and always read the first 1000 lines unless you are absolutely certain of which lines need to be read. The output will be identical to calling `cat -n <path>` with preceding spaces, line number and a tab.",
81
- "parameters": {
82
- "type": "object",
83
- "properties": {
84
- "path": {
85
- "type": "string",
86
- "description": "Relative path of the file",
87
- },
88
- "start": {
89
- "type": "integer",
90
- "description": "Which line to start reading from",
91
- "default": 1,
92
- },
93
- "num_lines": {
94
- "type": "integer",
95
- "description": "Number of lines to read, defaults to 1000",
96
- "default": 1000,
97
- },
98
- },
99
- "required": ["path"],
100
- "$schema": "http://json-schema.org/draft-07/schema#",
101
- },
102
- },
103
- },
104
- ]
15
+ This app has a feature where the user can refer to files or directories by typing @ which will open an file autocomplete dropdown. When this feature is used, the @ will remain in the filename. When working with said file, ignore the preceding @.
105
16
 
106
- READ_ONLY_COMMANDS = [
107
- "ls",
108
- "cat",
109
- "less",
110
- "more",
111
- "echo",
112
- "head",
113
- "tail",
114
- "wc",
115
- "grep",
116
- "find",
117
- "ack",
118
- "which",
119
- "sed",
120
- "find",
121
- "test",
122
- ]
17
+ Current working directory: {CWD_PATH}"""
src/llm_client.py ADDED
@@ -0,0 +1,51 @@
1
+ import os
2
+ from typing import Literal
3
+
4
+ import requests
5
+
6
+
7
+ class LLMClient:
8
+
9
+ def __init__(self):
10
+ self.host = os.environ.get("TASS_HOST", "http://localhost:8080")
11
+ self.api_key = os.environ.get("TASS_API_KEY", "")
12
+
13
+ def request(
14
+ self,
15
+ method: Literal["get", "post"],
16
+ url: str,
17
+ *args,
18
+ **kwargs,
19
+ ):
20
+ return requests.request(
21
+ method,
22
+ f"{self.host}{url}",
23
+ headers={
24
+ "Authorization": f"Bearer {self.api_key}",
25
+ },
26
+ *args,
27
+ **kwargs,
28
+ )
29
+
30
+ def get(self, url: str, *args, **kwargs):
31
+ return self.request("get", url, *args, **kwargs)
32
+
33
+ def post(self, url: str, *args, **kwargs):
34
+ return self.request("post", url, *args, **kwargs)
35
+
36
+ def get_models(self):
37
+ return self.get("/v1/models", timeout=2)
38
+
39
+ def get_chat_completions(self, messages: list[dict], tools: list[dict], stream: bool = False):
40
+ return self.post(
41
+ "/v1/chat/completions",
42
+ json={
43
+ "messages": messages,
44
+ "tools": tools,
45
+ "stream": stream,
46
+ "chat_template_kwargs": {
47
+ "reasoning_effort": "medium",
48
+ },
49
+ },
50
+ stream=stream,
51
+ )
src/tools/__init__.py ADDED
@@ -0,0 +1,12 @@
1
+ from .edit_file import EDIT_FILE_TOOL, edit_file
2
+ from .execute import EXECUTE_TOOL, execute
3
+ from .read_file import READ_FILE_TOOL, read_file
4
+
5
+ __all__ = [
6
+ "EDIT_FILE_TOOL",
7
+ "EXECUTE_TOOL",
8
+ "READ_FILE_TOOL",
9
+ "edit_file",
10
+ "execute",
11
+ "read_file",
12
+ ]
src/tools/edit_file.py ADDED
@@ -0,0 +1,178 @@
1
+ from dataclasses import dataclass
2
+ from difflib import SequenceMatcher, unified_diff
3
+ from pathlib import Path
4
+
5
+ from rich.markdown import Markdown
6
+
7
+ from src.constants import console
8
+
9
+
10
+ EDIT_FILE_TOOL = {
11
+ "type": "function",
12
+ "function": {
13
+ "name": "edit_file",
14
+ "description": "Edits (or creates) a file. Can make multiple edits in one call. Each edit finds the instance of 'find' and replaces it with 'replace'. When creating a file, only return a single edit where 'find' is empty and 'replace' is the entire contents of the file. Both 'find' and 'replace' must always be entire lines and never parts of a line, and they must always have correct dnd complete indentation. You must use the read_file tool before editing a file.",
15
+ "parameters": {
16
+ "type": "object",
17
+ "properties": {
18
+ "path": {
19
+ "type": "string",
20
+ "description": "Relative path of the file",
21
+ },
22
+ "edits": {
23
+ "type": "array",
24
+ "description": "List of edits to apply.",
25
+ "items": {
26
+ "type": "object",
27
+ "properties": {
28
+ "find": {
29
+ "type": "string",
30
+ "description": "Content to find. Include additional previous/following lines if necessary to uniquely identify the section.",
31
+ },
32
+ "replace": {
33
+ "type": "string",
34
+ "description": "The content to replace with. Must have the correct spacing and indentation for all lines.",
35
+ },
36
+ },
37
+ "required": ["find", "replace"],
38
+ },
39
+ },
40
+ },
41
+ "required": ["path", "edits"],
42
+ "$schema": "http://json-schema.org/draft-07/schema#",
43
+ },
44
+ },
45
+ }
46
+
47
+
48
+ @dataclass
49
+ class LineEdit:
50
+
51
+ line_start: int
52
+ line_end: int
53
+ replace: str
54
+ applied: bool = False
55
+
56
+
57
+ def remove_empty_lines(s: str) -> str:
58
+ while "\n\n" in s:
59
+ s = s.replace("\n\n", "\n")
60
+ return s
61
+
62
+
63
+ def fuzzy_match(edit_find: str, lines: list[str]) -> tuple[int, int] | None:
64
+ if not lines:
65
+ return None
66
+
67
+ num_edit_find_lines = len(edit_find.split("\n"))
68
+ edit_find_trimmed = remove_empty_lines(edit_find)
69
+ best_ratio = 0.0
70
+ best_start = -1
71
+ best_window_len = 1
72
+ for i in range(len(lines)):
73
+ for j in range(1, min(num_edit_find_lines * 2, len(lines) - i)):
74
+ window_text = remove_empty_lines("\n".join(lines[i : i + j]))
75
+ ratio = SequenceMatcher(None, edit_find_trimmed, window_text).ratio()
76
+ if ratio > best_ratio:
77
+ best_ratio = ratio
78
+ best_start = i
79
+ best_window_len = j
80
+ if best_ratio == 1.0:
81
+ return best_start + 1, best_start + best_window_len
82
+
83
+ if best_ratio >= 0.95 and best_start >= 0:
84
+ return best_start + 1, best_start + best_window_len
85
+
86
+ return None
87
+
88
+
89
+ def convert_edit_to_line_edit(edit: dict, original_content: str) -> LineEdit:
90
+ if not original_content and not edit["find"]:
91
+ return LineEdit(1, 1, edit["replace"], False)
92
+
93
+ lines = original_content.split("\n")
94
+ edit_lines = edit["find"].split("\n")
95
+
96
+ # First try exact matches
97
+ for i in range(len(lines)):
98
+ if lines[i : i + len(edit_lines)] == edit_lines:
99
+ return LineEdit(i + 1, i + len(edit_lines), edit["replace"], False)
100
+
101
+ # Then try matching without spacing
102
+ for i in range(len(lines)):
103
+ if [line.strip() for line in lines[i : i + len(edit_lines)]] == [line.strip() for line in edit_lines]:
104
+ return LineEdit(i + 1, i + len(edit_lines), edit["replace"], False)
105
+
106
+ # Finally try sequence matching while ignoring whitespace
107
+ fuzzy_edit = fuzzy_match(edit["find"], lines)
108
+ if fuzzy_edit:
109
+ return LineEdit(*fuzzy_edit, edit["replace"], False)
110
+
111
+ raise Exception("Edit not found in file")
112
+
113
+
114
+ def edit_file(path: str, edits: list[dict]) -> str:
115
+ def find_line_edit(n: int) -> LineEdit | None:
116
+ for line_edit in line_edits:
117
+ if line_edit.line_start <= n <= line_edit.line_end:
118
+ return line_edit
119
+
120
+ return None
121
+
122
+ file_exists = Path(path).exists()
123
+ if file_exists:
124
+ with open(path, "r") as f:
125
+ original_content = f.read()
126
+ else:
127
+ original_content = ""
128
+
129
+ line_edits: list[LineEdit] = [
130
+ convert_edit_to_line_edit(edit, original_content)
131
+ for edit in edits
132
+ ]
133
+
134
+ final_lines = []
135
+ original_lines = original_content.split("\n")
136
+ for i, line in enumerate(original_lines):
137
+ line_num = i + 1
138
+ line_edit = find_line_edit(line_num)
139
+ if not line_edit:
140
+ final_lines.append(line)
141
+ continue
142
+
143
+ if line_edit.applied:
144
+ continue
145
+
146
+ replace_lines = line_edit.replace.split("\n")
147
+ if line_edit.replace:
148
+ final_lines.extend(replace_lines)
149
+ original_lines = original_content.split("\n")
150
+ line_edit.applied = True
151
+
152
+ unified_diff_md = ""
153
+ for line in unified_diff(
154
+ [f"{line}\n" for line in original_lines],
155
+ [f"{line}\n" for line in final_lines],
156
+ fromfile=path,
157
+ tofile=path,
158
+ ):
159
+ unified_diff_md += line
160
+
161
+ console.print()
162
+ console.print(Markdown(f"```diff\n{unified_diff_md}\n```"))
163
+ answer = console.input("\n[bold]Run?[/] ([bold]Y[/]/n): ").strip().lower()
164
+ if answer not in ("yes", "y", ""):
165
+ reason = console.input("Why not? (optional, press Enter to skip): ").strip()
166
+ return f"User declined: {reason or 'no reason'}"
167
+
168
+ console.print(" └ Running...")
169
+ try:
170
+ with open(path, "w") as f:
171
+ f.write("\n".join(final_lines))
172
+ except Exception as e:
173
+ console.print(" [red]edit_file failed[/red]")
174
+ console.print(f" [red]{str(e).strip()}[/red]")
175
+ return f"edit_file failed: {str(e).strip()}"
176
+
177
+ console.print(" [green]Command succeeded[/green]")
178
+ return f"Successfully edited {path}"
src/tools/execute.py ADDED
@@ -0,0 +1,127 @@
1
+ import subprocess
2
+
3
+ from rich.markdown import Markdown
4
+
5
+ from src.constants import (
6
+ CWD_PATH,
7
+ console,
8
+ )
9
+
10
+ READ_ONLY_COMMANDS = [
11
+ "ls",
12
+ "cat",
13
+ "less",
14
+ "more",
15
+ "echo",
16
+ "head",
17
+ "tail",
18
+ "wc",
19
+ "grep",
20
+ "find",
21
+ "ack",
22
+ "which",
23
+ "sed",
24
+ "find",
25
+ "test",
26
+ ]
27
+
28
+ EXECUTE_TOOL = {
29
+ "type": "function",
30
+ "function": {
31
+ "name": "execute",
32
+ "description": f"Executes a shell command. The current working directory for all commands will be {CWD_PATH}",
33
+ "parameters": {
34
+ "type": "object",
35
+ "properties": {
36
+ "command": {
37
+ "type": "string",
38
+ "description": "Full shell command to be executed.",
39
+ },
40
+ "explanation": {
41
+ "type": "string",
42
+ "description": "A brief explanation of why you want to run this command. Keep it to a single sentence.",
43
+ },
44
+ },
45
+ "required": ["command", "explanation"],
46
+ "$schema": "http://json-schema.org/draft-07/schema#",
47
+ },
48
+ },
49
+ }
50
+
51
+
52
+ def is_read_only_command(command: str) -> bool:
53
+ """A simple check to see if the command is only for reading files.
54
+
55
+ Not a comprehensive or foolproof check by any means, and will
56
+ return false negatives to be safe.
57
+ """
58
+ if ">" in command:
59
+ return False
60
+
61
+ # Replace everything that potentially runs another command with a pipe
62
+ command = command.replace("&&", "|")
63
+ command = command.replace("||", "|")
64
+ command = command.replace(";", "|")
65
+
66
+ pipes = command.split("|")
67
+ for pipe in pipes:
68
+ if pipe.strip().split()[0] not in READ_ONLY_COMMANDS:
69
+ return False
70
+
71
+ return True
72
+
73
+
74
+ def execute(command: str, explanation: str) -> str:
75
+ command = command.strip()
76
+ requires_confirmation = not is_read_only_command(command)
77
+ if requires_confirmation:
78
+ console.print()
79
+ console.print(Markdown(f"```shell\n{command}\n```"))
80
+ if explanation:
81
+ console.print(f"Explanation: {explanation}")
82
+ answer = console.input("\n[bold]Run?[/] ([bold]Y[/]/n): ").strip().lower()
83
+ if answer not in ("yes", "y", ""):
84
+ reason = console.input("Why not? (optional, press Enter to skip): ").strip()
85
+ return f"User declined: {reason or 'no reason'}"
86
+
87
+ if requires_confirmation:
88
+ console.print(" └ Running...")
89
+ else:
90
+ console.print(f" └ Running [bold]{command}[/] (Explanation: {explanation})...")
91
+
92
+ try:
93
+ result = subprocess.run(
94
+ command,
95
+ shell=True,
96
+ capture_output=True,
97
+ text=True,
98
+ )
99
+ except Exception as e:
100
+ console.print(" [red]subprocess.run failed[/red]")
101
+ console.print(f" [red]{str(e).strip()}[/red]")
102
+ return f"subprocess.run failed: {str(e).strip()}"
103
+
104
+ out = result.stdout
105
+ err = result.stderr.strip()
106
+ if result.returncode == 0:
107
+ console.print(" [green]Command succeeded[/green]")
108
+ else:
109
+ console.print(f" [red]Command failed[/red] (code {result.returncode})")
110
+ if err:
111
+ console.print(f" [red]{err}[/red]")
112
+
113
+ if len(out.split("\n")) > 1000:
114
+ out_first_1000 = "\n".join(out.split("\n")[:1000])
115
+ out = f"{out_first_1000}... (Truncated)"
116
+
117
+ if len(err.split("\n")) > 1000:
118
+ err_first_1000 = "\n".join(err.split("\n")[:1000])
119
+ err = f"{err_first_1000}... (Truncated)"
120
+
121
+ if len(out) > 20000:
122
+ out = f"{out[:20000]}... (Truncated)"
123
+
124
+ if len(err) > 20000:
125
+ err = f"{err[:20000]}... (Truncated)"
126
+
127
+ return f"Command output (exit {result.returncode}):\n{out}\n{err}"
src/tools/read_file.py ADDED
@@ -0,0 +1,62 @@
1
+ from src.constants import console
2
+
3
+
4
+ READ_FILE_TOOL = {
5
+ "type": "function",
6
+ "function": {
7
+ "name": "read_file",
8
+ "description": "Read a file's contents (the first 1000 lines by default). When reading a file for the first time, do not change the defaults and always read the first 1000 lines unless you are absolutely certain of which lines need to be read.",
9
+ "parameters": {
10
+ "type": "object",
11
+ "properties": {
12
+ "path": {
13
+ "type": "string",
14
+ "description": "Relative path of the file",
15
+ },
16
+ "start": {
17
+ "type": "integer",
18
+ "description": "Which line to start reading from",
19
+ "default": 1,
20
+ },
21
+ "num_lines": {
22
+ "type": "integer",
23
+ "description": "Number of lines to read, defaults to 1000",
24
+ "default": 1000,
25
+ },
26
+ },
27
+ "required": ["path"],
28
+ "$schema": "http://json-schema.org/draft-07/schema#",
29
+ },
30
+ },
31
+ }
32
+
33
+
34
+ def read_file(path: str, start: int = 1, num_lines: int = 1000) -> str:
35
+ if start == 1 and num_lines == 1000:
36
+ console.print(f" └ Reading file [bold]{path}[/]...")
37
+ else:
38
+ last_line = start + num_lines - 1
39
+ console.print(f" └ Reading file [bold]{path}[/] (lines {start}-{last_line})...")
40
+
41
+ try:
42
+ with open(path) as f:
43
+ lines = []
44
+ line_num = 1
45
+ for line in f:
46
+ if line_num < start:
47
+ line_num += 1
48
+ continue
49
+
50
+ lines.append(line)
51
+ line_num += 1
52
+
53
+ if len(lines) >= num_lines:
54
+ lines.append("... (truncated)")
55
+ break
56
+
57
+ console.print(" [green]Command succeeded[/green]")
58
+ return "\n".join(lines)
59
+ except Exception as e:
60
+ console.print(" [red]read_file failed[/red]")
61
+ console.print(f" [red]{str(e).strip()}[/red]")
62
+ return f"read_file failed: {str(e)}"
src/utils.py CHANGED
@@ -7,31 +7,7 @@ from prompt_toolkit.document import Document
7
7
  from prompt_toolkit.key_binding import KeyBindings
8
8
  from prompt_toolkit.keys import Keys
9
9
 
10
- from src.constants import (
11
- READ_ONLY_COMMANDS,
12
- cwd_path,
13
- )
14
-
15
- def is_read_only_command(command: str) -> bool:
16
- """A simple check to see if the command is only for reading files.
17
-
18
- Not a comprehensive or foolproof check by any means, and will
19
- return false negatives to be safe.
20
- """
21
- if ">" in command:
22
- return False
23
-
24
- # Replace everything that potentially runs another command with a pipe
25
- command = command.replace("&&", "|")
26
- command = command.replace("||", "|")
27
- command = command.replace(";", "|")
28
-
29
- pipes = command.split("|")
30
- for pipe in pipes:
31
- if pipe.strip().split()[0] not in READ_ONLY_COMMANDS:
32
- return False
33
-
34
- return True
10
+ from src.constants import CWD_PATH
35
11
 
36
12
 
37
13
  class FileCompleter(Completer):
@@ -47,13 +23,13 @@ class FileCompleter(Completer):
47
23
 
48
24
  text_after_at = text[last_at_pos + 1 : cursor_pos]
49
25
 
50
- base_dir = cwd_path
26
+ base_dir = CWD_PATH
51
27
  search_pattern = text_after_at
52
28
  prefix = ""
53
29
 
54
30
  if "/" in text_after_at:
55
31
  dir_part, file_part = text_after_at.rsplit("/", 1)
56
- base_dir = cwd_path / dir_part
32
+ base_dir = CWD_PATH / dir_part
57
33
  search_pattern = file_part
58
34
  prefix = dir_part + "/"
59
35
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tass
3
- Version: 0.1.10
3
+ Version: 0.1.12
4
4
  Summary: A terminal assistant that allows you to ask an LLM to run commands.
5
5
  Project-URL: Homepage, https://github.com/cetincan0/tass
6
6
  Author: Can Cetin
@@ -44,11 +44,13 @@ You can run it with
44
44
  tass
45
45
  ```
46
46
 
47
- tass has only been tested with gpt-oss-120b using llama.cpp so far, but in theory any LLM with tool calling capabilities should work. By default, it will try connecting to http://localhost:8080. If you want to use another host, set the `TASS_HOST` environment variable. At the moment there's no support for connecting tass to a non-local API, nor are there plans for it. For the time being, I plan on keeping tass completely local. There's no telemetry, no logs, just a simple REPL loop.
47
+ tass has only been tested with llama.cpp with LLMs such as gpt-oss-120b and MiniMax M2.1, but any LLM with tool calling capabilities should work.
48
+
49
+ By default, tass will try connecting to http://localhost:8080. To use another host, set the `TASS_HOST` environment variable. If your server requires an API key, you can set the `TASS_API_KEY` environment variable. At the moment there's no support for connecting tass to a non-local API, nor are there plans for it. I plan on keeping tass completely local. There's no telemetry, no logs, just a simple REPL loop.
48
50
 
49
51
  Once it's running, you can ask questions or give commands like "Create an empty file called test.txt" and it will propose a command to run after user confirmation.
50
52
 
51
- You can enter multiline input by ending lines with a backslash (\\). The continuation prompt will appear until you enter a line without a trailing backslash.
53
+ You can enter multiline input by ending lines with a backslash (\\). The continuation prompt will keep appearing until you enter a line without a trailing backslash.
52
54
 
53
55
  ## Upgrade
54
56
 
@@ -0,0 +1,15 @@
1
+ src/__init__.py,sha256=tu2q9W5_pkq30l3tRMTGahColBAAubbLP6LaB3l3IFg,89
2
+ src/app.py,sha256=AlRGV8mIaFSS8g89Z1z8dAR19t8CO5Fct2oVX9iDnr8,9857
3
+ src/cli.py,sha256=op3fYcyfek_KqCCiA-Zdlc9jVZSCi036whMmR2ZjjAs,76
4
+ src/constants.py,sha256=unKrG93sue5HgHIYxtJ_NC8WO8CAxOhSD85yD7T6Qck,936
5
+ src/llm_client.py,sha256=LAQ2iQuCtyMwDMPC_SVqheDN8EyTNr3f_LB-HgLm9bE,1326
6
+ src/utils.py,sha256=knrI8aA0X3krW7aAynnhqsfEXepIM72aJCKbEDpSsD8,2401
7
+ src/tools/__init__.py,sha256=5XmZH5XrwRju52BaI_fG7jl2Jllx7C5mr7wsX2Q46DE,269
8
+ src/tools/edit_file.py,sha256=wuoq9vl32cj2UCVkaZwBAlgNj-FDCOgWpE--LIChFs0,6246
9
+ src/tools/execute.py,sha256=8LHePOjQuLA3ta7PiDhbfhN4pvxHR32Uo9nmwDqMrEE,3723
10
+ src/tools/read_file.py,sha256=oYJCU0g6xpFuTFhru2cLNYxYyClZ2CqPKCu6ycK8tdY,2152
11
+ tass-0.1.12.dist-info/METADATA,sha256=zdRAYXNT3_fBYjOO4SUW8VbiW1op66rpoGw8caDxew0,1797
12
+ tass-0.1.12.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
13
+ tass-0.1.12.dist-info/entry_points.txt,sha256=pviKuIOuHvaQ7_YiFxatJEY8XYfh3EzVWy4LJh0v-A0,38
14
+ tass-0.1.12.dist-info/licenses/LICENSE,sha256=Cdr-_YJHgGaf2vJjcoOsRJySkDaogUhu3yIDvpz7GEQ,1066
15
+ tass-0.1.12.dist-info/RECORD,,
@@ -1,10 +0,0 @@
1
- src/__init__.py,sha256=tu2q9W5_pkq30l3tRMTGahColBAAubbLP6LaB3l3IFg,89
2
- src/app.py,sha256=45r-M59vjJb1TXdkfSkTVJq1waLyNYVLxkafav5t6oI,16472
3
- src/cli.py,sha256=op3fYcyfek_KqCCiA-Zdlc9jVZSCi036whMmR2ZjjAs,76
4
- src/constants.py,sha256=LYNON4xoqCssh4wA7rjkjyY2JhDXUPFmkQlTz_N0oz8,5089
5
- src/utils.py,sha256=Uoi60eko9ivvnF-se68yAuwUDFEOHb9Y2SepDaOAbTU,3069
6
- tass-0.1.10.dist-info/METADATA,sha256=xG6XaXmXrLhDE1uo06tK1nXaSWYz2W8nA-Yx2-ZACHA,1717
7
- tass-0.1.10.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
8
- tass-0.1.10.dist-info/entry_points.txt,sha256=pviKuIOuHvaQ7_YiFxatJEY8XYfh3EzVWy4LJh0v-A0,38
9
- tass-0.1.10.dist-info/licenses/LICENSE,sha256=Cdr-_YJHgGaf2vJjcoOsRJySkDaogUhu3yIDvpz7GEQ,1066
10
- tass-0.1.10.dist-info/RECORD,,
File without changes