tass 0.1.0__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/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ from .app import TassApp
2
+ from .cli import main
3
+
4
+ __all__ = [
5
+ "TassApp",
6
+ "main",
7
+ ]
src/app.py ADDED
@@ -0,0 +1,186 @@
1
+ import json
2
+ import os
3
+ import subprocess
4
+
5
+ import requests
6
+ from rich.console import Console
7
+ from rich.markdown import Markdown
8
+
9
+ from src.constants import (
10
+ SYSTEM_PROMPT,
11
+ TOOLS,
12
+ )
13
+ from src.third_party.apply_patch import apply_patch
14
+ from src.utils import (
15
+ is_read_only_command,
16
+ )
17
+
18
+ console = Console()
19
+
20
+
21
+ class TassApp:
22
+
23
+ def __init__(self):
24
+ self.messages: list[dict] = [{"role": "system", "content": SYSTEM_PROMPT}]
25
+ self.host = os.environ.get("TASS_HOST", "http://localhost:8080")
26
+ self.TOOLS_MAP = {
27
+ "execute": self.execute,
28
+ "apply_patch": self.apply_patch_tass,
29
+ "read_file": self.read_file,
30
+ }
31
+
32
+ def call_llm(self) -> str | None:
33
+ response = requests.post(
34
+ f"{self.host}/v1/chat/completions",
35
+ json={
36
+ "messages": self.messages,
37
+ "tools": TOOLS,
38
+ "chat_template_kwargs": {
39
+ "reasoning_effort": "medium",
40
+ }
41
+ },
42
+ )
43
+
44
+ data = response.json()
45
+ if "tool_calls" in data["choices"][0]["message"]:
46
+ tool_name = data["choices"][0]["message"]["tool_calls"][0]["function"]["name"]
47
+ tool_args_str = data["choices"][0]["message"]["tool_calls"][0]["function"]["arguments"]
48
+ self.messages.append(
49
+ {
50
+ "role": "assistant",
51
+ "tool_calls": [
52
+ {
53
+ "index": 0,
54
+ "id": "id1",
55
+ "type": "function",
56
+ "function": {
57
+ "name": tool_name,
58
+ "arguments": tool_args_str
59
+ }
60
+ }
61
+ ]
62
+ }
63
+ )
64
+ try:
65
+ tool = self.TOOLS_MAP[tool_name]
66
+ tool_args = json.loads(tool_args_str)
67
+ result = tool(**tool_args)
68
+ self.messages.append({"role": "tool", "content": result})
69
+ except Exception as e:
70
+ self.messages.append({"role": "user", "content": str(e)})
71
+ return self.call_llm()
72
+
73
+ return data["choices"][0]["message"]["content"]
74
+
75
+ def read_file(self, path: str, start: int = 1) -> str:
76
+ console.print(f" └ Reading file [bold]{path}[/] (start={start})...")
77
+
78
+ lines = []
79
+ with open(path) as f:
80
+ line_num = 1
81
+ for line in f:
82
+ if line_num < start:
83
+ line_num += 1
84
+ continue
85
+
86
+ lines.append(line)
87
+ line_num += 1
88
+
89
+ if len(lines) >= 1000:
90
+ break
91
+
92
+ console.print(" [green]Command succeeded[/green]")
93
+ return "".join(lines)
94
+
95
+ def apply_patch_tass(self, patch: str) -> str:
96
+ console.print()
97
+ console.print(Markdown(f"```diff\n{patch}\n```"))
98
+ answer = console.input("\n[bold]Run?[/] ([bold]Y[/]/n): ").strip().lower()
99
+ if answer not in ("yes", "y", ""):
100
+ reason = console.input("Why not? (optional, press Enter to skip): ").strip()
101
+ return f"User declined: {reason or 'no reason'}"
102
+
103
+ console.print(" └ Running...")
104
+
105
+ try:
106
+ apply_patch(patch)
107
+ except Exception as e:
108
+ console.print(" [red]apply_patch failed[/red]")
109
+ console.print(f" [red]{str(e)}[/red]")
110
+ return f"apply_patch failed: {str(e)}"
111
+
112
+ console.print(" [green]Command succeeded[/green]")
113
+
114
+ return "Command output (exit 0): apply_patch succeeded"
115
+
116
+ def execute(self, command: str, explanation: str) -> str:
117
+ command = command.strip()
118
+ requires_confirmation = not is_read_only_command(command)
119
+ if requires_confirmation:
120
+ console.print()
121
+ console.print(Markdown(f"```shell\n{command}\n```"))
122
+ if explanation:
123
+ console.print(f"Explanation: {explanation}")
124
+ answer = console.input("\n[bold]Run?[/] ([bold]Y[/]/n): ").strip().lower()
125
+ if answer not in ("yes", "y", ""):
126
+ reason = console.input("Why not? (optional, press Enter to skip): ").strip()
127
+ return f"User declined: {reason or 'no reason'}"
128
+
129
+ if requires_confirmation:
130
+ console.print(" └ Running...")
131
+ else:
132
+ console.print(f" └ Running [bold]{command}[/] (Explanation: {explanation})...")
133
+
134
+ try:
135
+ result = subprocess.run(
136
+ command,
137
+ shell=True,
138
+ capture_output=True,
139
+ text=True,
140
+ )
141
+ except Exception as e:
142
+ console.print(" [red]subprocess.run failed[/red]")
143
+ console.print(f" [red]{str(e)}[/red]")
144
+ return f"subprocess.run failed: {str(e)}"
145
+
146
+ out = result.stdout.strip()
147
+ err = result.stderr.strip()
148
+ if result.returncode == 0:
149
+ console.print(" [green]Command succeeded[/green]")
150
+ else:
151
+ console.print(f" [red]Command failed[/red] (code {result.returncode})")
152
+ console.print(f" [red]{err}[/red]")
153
+
154
+ if len(out) > 5000:
155
+ out = f"{out[:5000]}... (Truncated)"
156
+
157
+ if len(err) > 5000:
158
+ err = f"{err[:5000]}... (Truncated)"
159
+
160
+ return f"Command output (exit {result.returncode}):\n{out}\n{err}"
161
+
162
+ def run(self):
163
+ console.print("Terminal Assistant")
164
+
165
+ while True:
166
+ try:
167
+ user_input = console.input("\n> ").strip()
168
+ except KeyboardInterrupt:
169
+ console.print("\nBye!")
170
+ break
171
+
172
+ if not user_input:
173
+ continue
174
+
175
+ if user_input.lower().strip() == "exit":
176
+ console.print("\nBye!")
177
+ break
178
+
179
+ self.messages.append({"role": "user", "content": user_input})
180
+
181
+ while True:
182
+ llm_resp = self.call_llm()
183
+ if llm_resp is not None:
184
+ console.print("")
185
+ console.print(Markdown(llm_resp))
186
+ break
src/cli.py ADDED
@@ -0,0 +1,6 @@
1
+ from src.app import TassApp
2
+
3
+
4
+ def main():
5
+ app = TassApp()
6
+ app.run()
src/constants.py ADDED
@@ -0,0 +1,94 @@
1
+ from pathlib import Path
2
+
3
+ _apply_patch_path = Path(__file__).resolve().parent / "third_party" / "apply_patch.md"
4
+ APPLY_PATCH_PROMPT = _apply_patch_path.read_text().strip()
5
+
6
+ SYSTEM_PROMPT = f"""You are Terminal-Assistant, a helpful AI that executes shell commands based on natural-language requests.
7
+
8
+ If the user's request involves making changes to the filesystem such as creating or deleting files or directories, you MUST first check whether the file or directory exists before proceeding.
9
+
10
+ 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.
11
+
12
+ {APPLY_PATCH_PROMPT}"""
13
+
14
+ TOOLS = [
15
+ {
16
+ "type": "function",
17
+ "function": {
18
+ "name": "execute",
19
+ "description": "Executes a shell command.",
20
+ "parameters": {
21
+ "type": "object",
22
+ "properties": {
23
+ "command": {
24
+ "type": "string",
25
+ "description": "Full shell command to be executed.",
26
+ },
27
+ "explanation": {
28
+ "type": "string",
29
+ "description": "A brief explanation of why you want to run this command.",
30
+ },
31
+ },
32
+ "required": ["command", "explanation"],
33
+ "$schema": "http://json-schema.org/draft-07/schema#",
34
+ },
35
+ },
36
+ },
37
+ {
38
+ "type": "function",
39
+ "function": {
40
+ "name": "apply_patch",
41
+ "description": "Patch a file",
42
+ "parameters": {
43
+ "type": "object",
44
+ "properties": {
45
+ "patch": {
46
+ "type": "string",
47
+ "description": "Formatted patch code",
48
+ "default": "*** Begin Patch\n*** End Patch\n",
49
+ },
50
+ },
51
+ "required": ["patch"],
52
+ "$schema": "http://json-schema.org/draft-07/schema#",
53
+ },
54
+ },
55
+ },
56
+ {
57
+ "type": "function",
58
+ "function": {
59
+ "name": "read_file",
60
+ "description": "Read a file's contents (up to 1000 lines)",
61
+ "parameters": {
62
+ "type": "object",
63
+ "properties": {
64
+ "path": {
65
+ "type": "string",
66
+ "description": "Relative path of the file",
67
+ },
68
+ "start": {
69
+ "type": "integer",
70
+ "description": "Which line to start reading from",
71
+ "default": 1,
72
+ },
73
+ },
74
+ "required": ["path"],
75
+ "$schema": "http://json-schema.org/draft-07/schema#",
76
+ },
77
+ },
78
+ },
79
+ ]
80
+
81
+ READ_ONLY_COMMANDS = [
82
+ "ls",
83
+ "cat",
84
+ "less",
85
+ "more",
86
+ "echo",
87
+ "tail",
88
+ "wc",
89
+ "grep",
90
+ "find",
91
+ "ack",
92
+ "which",
93
+ "sed",
94
+ ]
@@ -0,0 +1 @@
1
+ These files are taken directly from https://github.com/openai/gpt-oss to assist with gpt-oss-120b's code editing capabilities. No modifications have been made.
File without changes
@@ -0,0 +1,64 @@
1
+ When requested to perform coding-related tasks, you MUST adhere to the following criteria when executing the task:
2
+
3
+ - Use `apply_patch` to edit files.
4
+ - If completing the user's task requires writing or modifying files:
5
+ - Your code and final answer should follow these _CODING GUIDELINES_:
6
+ - Avoid unneeded complexity in your solution. Minimize program size.
7
+ - Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task.
8
+ - NEVER add copyright or license headers unless specifically requested.
9
+ - Never implement function stubs. Provide complete working implementations.
10
+
11
+ § `apply_patch` Specification
12
+
13
+ Your patch language is a stripped‑down, file‑oriented diff format designed to be easy to parse and safe to apply. You can think of it as a high‑level envelope:
14
+
15
+ *** Begin Patch
16
+ [ one or more file sections ]
17
+ *** End Patch
18
+
19
+ Within that envelope, you get a sequence of file operations.
20
+ You MUST include a header to specify the action you are taking.
21
+ Each operation starts with one of three headers:
22
+
23
+ *** Add File: <path> - create a new file. Every following line is a + line (the initial contents).
24
+ *** Delete File: <path> - remove an existing file. Nothing follows.
25
+ *** Update File: <path> - patch an existing file in place (optionally with a rename).
26
+
27
+ May be immediately followed by *** Move to: <new path> if you want to rename the file.
28
+ Then one or more “hunks”, each introduced by @@ (optionally followed by a hunk header).
29
+ Within a hunk each line starts with:
30
+
31
+ - for inserted text,
32
+
33
+ * for removed text, or
34
+ space ( ) for context.
35
+ At the end of a truncated hunk you can emit *** End of File.
36
+
37
+ Patch := Begin { FileOp } End
38
+ Begin := "*** Begin Patch" NEWLINE
39
+ End := "*** End Patch" NEWLINE
40
+ FileOp := AddFile | DeleteFile | UpdateFile
41
+ AddFile := "*** Add File: " path NEWLINE { "+" line NEWLINE }
42
+ DeleteFile := "*** Delete File: " path NEWLINE
43
+ UpdateFile := "*** Update File: " path NEWLINE [ MoveTo ] { Hunk }
44
+ MoveTo := "*** Move to: " newPath NEWLINE
45
+ Hunk := "@@" [ header ] NEWLINE { HunkLine } [ "*** End of File" NEWLINE ]
46
+ HunkLine := (" " | "-" | "+") text NEWLINE
47
+
48
+ A full patch can combine several operations:
49
+
50
+ *** Begin Patch
51
+ *** Add File: hello.txt
52
+ +Hello world
53
+ *** Update File: src/app.py
54
+ *** Move to: src/main.py
55
+ @@ def greet():
56
+ -print("Hi")
57
+ +print("Hello, world!")
58
+ *** Delete File: obsolete.txt
59
+ *** End Patch
60
+
61
+ It is important to remember:
62
+
63
+ - You must include a header with your intended action (Add/Delete/Update)
64
+ - You must prefix new lines with `+` even when creating a new file
@@ -0,0 +1,529 @@
1
+ #!/usr/bin/env python3
2
+
3
+ """
4
+ A self-contained **pure-Python 3.9+** utility for applying human-readable
5
+ “pseudo-diff” patch files to a collection of text files.
6
+
7
+ Source: https://cookbook.openai.com/examples/gpt4-1_prompting_guide
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import pathlib
13
+ from dataclasses import dataclass, field
14
+ from enum import Enum
15
+ from typing import (
16
+ Callable,
17
+ Dict,
18
+ List,
19
+ Optional,
20
+ Tuple,
21
+ Union,
22
+ )
23
+
24
+
25
+ # --------------------------------------------------------------------------- #
26
+ # Domain objects
27
+ # --------------------------------------------------------------------------- #
28
+ class ActionType(str, Enum):
29
+ ADD = "add"
30
+ DELETE = "delete"
31
+ UPDATE = "update"
32
+
33
+
34
+ @dataclass
35
+ class FileChange:
36
+ type: ActionType
37
+ old_content: Optional[str] = None
38
+ new_content: Optional[str] = None
39
+ move_path: Optional[str] = None
40
+
41
+
42
+ @dataclass
43
+ class Commit:
44
+ changes: Dict[str, FileChange] = field(default_factory=dict)
45
+
46
+
47
+ # --------------------------------------------------------------------------- #
48
+ # Exceptions
49
+ # --------------------------------------------------------------------------- #
50
+ class DiffError(ValueError):
51
+ """Any problem detected while parsing or applying a patch."""
52
+
53
+
54
+ # --------------------------------------------------------------------------- #
55
+ # Helper dataclasses used while parsing patches
56
+ # --------------------------------------------------------------------------- #
57
+ @dataclass
58
+ class Chunk:
59
+ orig_index: int = -1
60
+ del_lines: List[str] = field(default_factory=list)
61
+ ins_lines: List[str] = field(default_factory=list)
62
+
63
+
64
+ @dataclass
65
+ class PatchAction:
66
+ type: ActionType
67
+ new_file: Optional[str] = None
68
+ chunks: List[Chunk] = field(default_factory=list)
69
+ move_path: Optional[str] = None
70
+
71
+
72
+ @dataclass
73
+ class Patch:
74
+ actions: Dict[str, PatchAction] = field(default_factory=dict)
75
+
76
+
77
+ # --------------------------------------------------------------------------- #
78
+ # Patch text parser
79
+ # --------------------------------------------------------------------------- #
80
+ @dataclass
81
+ class Parser:
82
+ current_files: Dict[str, str]
83
+ lines: List[str]
84
+ index: int = 0
85
+ patch: Patch = field(default_factory=Patch)
86
+ fuzz: int = 0
87
+
88
+ # ------------- low-level helpers -------------------------------------- #
89
+ def _cur_line(self) -> str:
90
+ if self.index >= len(self.lines):
91
+ raise DiffError("Unexpected end of input while parsing patch")
92
+ return self.lines[self.index]
93
+
94
+ @staticmethod
95
+ def _norm(line: str) -> str:
96
+ """Strip CR so comparisons work for both LF and CRLF input."""
97
+ return line.rstrip("\r")
98
+
99
+ # ------------- scanning convenience ----------------------------------- #
100
+ def is_done(self, prefixes: Optional[Tuple[str, ...]] = None) -> bool:
101
+ if self.index >= len(self.lines):
102
+ return True
103
+ if (
104
+ prefixes
105
+ and len(prefixes) > 0
106
+ and self._norm(self._cur_line()).startswith(prefixes)
107
+ ):
108
+ return True
109
+ return False
110
+
111
+ def startswith(self, prefix: Union[str, Tuple[str, ...]]) -> bool:
112
+ return self._norm(self._cur_line()).startswith(prefix)
113
+
114
+ def read_str(self, prefix: str) -> str:
115
+ """
116
+ Consume the current line if it starts with *prefix* and return the text
117
+ **after** the prefix. Raises if prefix is empty.
118
+ """
119
+ if prefix == "":
120
+ raise ValueError("read_str() requires a non-empty prefix")
121
+ if self._norm(self._cur_line()).startswith(prefix):
122
+ text = self._cur_line()[len(prefix) :]
123
+ self.index += 1
124
+ return text
125
+ return ""
126
+
127
+ def read_line(self) -> str:
128
+ """Return the current raw line and advance."""
129
+ line = self._cur_line()
130
+ self.index += 1
131
+ return line
132
+
133
+ # ------------- public entry point -------------------------------------- #
134
+ def parse(self) -> None:
135
+ while not self.is_done(("*** End Patch",)):
136
+ # ---------- UPDATE ---------- #
137
+ path = self.read_str("*** Update File: ")
138
+ if path:
139
+ if path in self.patch.actions:
140
+ raise DiffError(f"Duplicate update for file: {path}")
141
+ move_to = self.read_str("*** Move to: ")
142
+ if path not in self.current_files:
143
+ raise DiffError(f"Update File Error - missing file: {path}")
144
+ text = self.current_files[path]
145
+ action = self._parse_update_file(text)
146
+ action.move_path = move_to or None
147
+ self.patch.actions[path] = action
148
+ continue
149
+
150
+ # ---------- DELETE ---------- #
151
+ path = self.read_str("*** Delete File: ")
152
+ if path:
153
+ if path in self.patch.actions:
154
+ raise DiffError(f"Duplicate delete for file: {path}")
155
+ if path not in self.current_files:
156
+ raise DiffError(f"Delete File Error - missing file: {path}")
157
+ self.patch.actions[path] = PatchAction(type=ActionType.DELETE)
158
+ continue
159
+
160
+ # ---------- ADD ---------- #
161
+ path = self.read_str("*** Add File: ")
162
+ if path:
163
+ if path in self.patch.actions:
164
+ raise DiffError(f"Duplicate add for file: {path}")
165
+ if path in self.current_files:
166
+ raise DiffError(f"Add File Error - file already exists: {path}")
167
+ self.patch.actions[path] = self._parse_add_file()
168
+ continue
169
+
170
+ raise DiffError(f"Unknown line while parsing: {self._cur_line()}")
171
+
172
+ if not self.startswith("*** End Patch"):
173
+ raise DiffError("Missing *** End Patch sentinel")
174
+ self.index += 1 # consume sentinel
175
+
176
+ # ------------- section parsers ---------------------------------------- #
177
+ def _parse_update_file(self, text: str) -> PatchAction:
178
+ action = PatchAction(type=ActionType.UPDATE)
179
+ lines = text.split("\n")
180
+ index = 0
181
+ while not self.is_done(
182
+ (
183
+ "*** End Patch",
184
+ "*** Update File:",
185
+ "*** Delete File:",
186
+ "*** Add File:",
187
+ "*** End of File",
188
+ )
189
+ ):
190
+ def_str = self.read_str("@@ ")
191
+ section_str = ""
192
+ if not def_str and self._norm(self._cur_line()) == "@@":
193
+ section_str = self.read_line()
194
+
195
+ if not (def_str or section_str or index == 0):
196
+ raise DiffError(f"Invalid line in update section:\n{self._cur_line()}")
197
+
198
+ if def_str.strip():
199
+ found = False
200
+ if def_str not in lines[:index]:
201
+ for i, s in enumerate(lines[index:], index):
202
+ if s == def_str:
203
+ index = i + 1
204
+ found = True
205
+ break
206
+ if not found and def_str.strip() not in [
207
+ s.strip() for s in lines[:index]
208
+ ]:
209
+ for i, s in enumerate(lines[index:], index):
210
+ if s.strip() == def_str.strip():
211
+ index = i + 1
212
+ self.fuzz += 1
213
+ found = True
214
+ break
215
+
216
+ next_ctx, chunks, end_idx, eof = peek_next_section(self.lines, self.index)
217
+ new_index, fuzz = find_context(lines, next_ctx, index, eof)
218
+ if new_index == -1:
219
+ ctx_txt = "\n".join(next_ctx)
220
+ raise DiffError(
221
+ f"Invalid {'EOF ' if eof else ''}context at {index}:\n{ctx_txt}"
222
+ )
223
+ self.fuzz += fuzz
224
+ for ch in chunks:
225
+ ch.orig_index += new_index
226
+ action.chunks.append(ch)
227
+ index = new_index + len(next_ctx)
228
+ self.index = end_idx
229
+ return action
230
+
231
+ def _parse_add_file(self) -> PatchAction:
232
+ lines: List[str] = []
233
+ while not self.is_done(
234
+ ("*** End Patch", "*** Update File:", "*** Delete File:", "*** Add File:")
235
+ ):
236
+ s = self.read_line()
237
+ if not s.startswith("+"):
238
+ raise DiffError(f"Invalid Add File line (missing '+'): {s}")
239
+ lines.append(s[1:]) # strip leading '+'
240
+ return PatchAction(type=ActionType.ADD, new_file="\n".join(lines))
241
+
242
+
243
+ # --------------------------------------------------------------------------- #
244
+ # Helper functions
245
+ # --------------------------------------------------------------------------- #
246
+ def find_context_core(
247
+ lines: List[str], context: List[str], start: int
248
+ ) -> Tuple[int, int]:
249
+ if not context:
250
+ return start, 0
251
+
252
+ for i in range(start, len(lines)):
253
+ if lines[i : i + len(context)] == context:
254
+ return i, 0
255
+ for i in range(start, len(lines)):
256
+ if [s.rstrip() for s in lines[i : i + len(context)]] == [
257
+ s.rstrip() for s in context
258
+ ]:
259
+ return i, 1
260
+ for i in range(start, len(lines)):
261
+ if [s.strip() for s in lines[i : i + len(context)]] == [
262
+ s.strip() for s in context
263
+ ]:
264
+ return i, 100
265
+ return -1, 0
266
+
267
+
268
+ def find_context(
269
+ lines: List[str], context: List[str], start: int, eof: bool
270
+ ) -> Tuple[int, int]:
271
+ if eof:
272
+ new_index, fuzz = find_context_core(lines, context, len(lines) - len(context))
273
+ if new_index != -1:
274
+ return new_index, fuzz
275
+ new_index, fuzz = find_context_core(lines, context, start)
276
+ return new_index, fuzz + 10_000
277
+ return find_context_core(lines, context, start)
278
+
279
+
280
+ def peek_next_section(
281
+ lines: List[str], index: int
282
+ ) -> Tuple[List[str], List[Chunk], int, bool]:
283
+ old: List[str] = []
284
+ del_lines: List[str] = []
285
+ ins_lines: List[str] = []
286
+ chunks: List[Chunk] = []
287
+ mode = "keep"
288
+ orig_index = index
289
+
290
+ while index < len(lines):
291
+ s = lines[index]
292
+ if s.startswith(
293
+ (
294
+ "@@",
295
+ "*** End Patch",
296
+ "*** Update File:",
297
+ "*** Delete File:",
298
+ "*** Add File:",
299
+ "*** End of File",
300
+ )
301
+ ):
302
+ break
303
+ if s == "***":
304
+ break
305
+ if s.startswith("***"):
306
+ raise DiffError(f"Invalid Line: {s}")
307
+ index += 1
308
+
309
+ last_mode = mode
310
+ if s == "":
311
+ s = " "
312
+ if s[0] == "+":
313
+ mode = "add"
314
+ elif s[0] == "-":
315
+ mode = "delete"
316
+ elif s[0] == " ":
317
+ mode = "keep"
318
+ else:
319
+ raise DiffError(f"Invalid Line: {s}")
320
+ s = s[1:]
321
+
322
+ if mode == "keep" and last_mode != mode:
323
+ if ins_lines or del_lines:
324
+ chunks.append(
325
+ Chunk(
326
+ orig_index=len(old) - len(del_lines),
327
+ del_lines=del_lines,
328
+ ins_lines=ins_lines,
329
+ )
330
+ )
331
+ del_lines, ins_lines = [], []
332
+
333
+ if mode == "delete":
334
+ del_lines.append(s)
335
+ old.append(s)
336
+ elif mode == "add":
337
+ ins_lines.append(s)
338
+ elif mode == "keep":
339
+ old.append(s)
340
+
341
+ if ins_lines or del_lines:
342
+ chunks.append(
343
+ Chunk(
344
+ orig_index=len(old) - len(del_lines),
345
+ del_lines=del_lines,
346
+ ins_lines=ins_lines,
347
+ )
348
+ )
349
+
350
+ if index < len(lines) and lines[index] == "*** End of File":
351
+ index += 1
352
+ return old, chunks, index, True
353
+
354
+ if index == orig_index:
355
+ raise DiffError("Nothing in this section")
356
+ return old, chunks, index, False
357
+
358
+
359
+ # --------------------------------------------------------------------------- #
360
+ # Patch → Commit and Commit application
361
+ # --------------------------------------------------------------------------- #
362
+ def _get_updated_file(text: str, action: PatchAction, path: str) -> str:
363
+ if action.type is not ActionType.UPDATE:
364
+ raise DiffError("_get_updated_file called with non-update action")
365
+ orig_lines = text.split("\n")
366
+ dest_lines: List[str] = []
367
+ orig_index = 0
368
+
369
+ for chunk in action.chunks:
370
+ if chunk.orig_index > len(orig_lines):
371
+ raise DiffError(
372
+ f"{path}: chunk.orig_index {chunk.orig_index} exceeds file length"
373
+ )
374
+ if orig_index > chunk.orig_index:
375
+ raise DiffError(
376
+ f"{path}: overlapping chunks at {orig_index} > {chunk.orig_index}"
377
+ )
378
+
379
+ dest_lines.extend(orig_lines[orig_index : chunk.orig_index])
380
+ orig_index = chunk.orig_index
381
+
382
+ dest_lines.extend(chunk.ins_lines)
383
+ orig_index += len(chunk.del_lines)
384
+
385
+ dest_lines.extend(orig_lines[orig_index:])
386
+ return "\n".join(dest_lines)
387
+
388
+
389
+ def patch_to_commit(patch: Patch, orig: Dict[str, str]) -> Commit:
390
+ commit = Commit()
391
+ for path, action in patch.actions.items():
392
+ if action.type is ActionType.DELETE:
393
+ commit.changes[path] = FileChange(
394
+ type=ActionType.DELETE, old_content=orig[path]
395
+ )
396
+ elif action.type is ActionType.ADD:
397
+ if action.new_file is None:
398
+ raise DiffError("ADD action without file content")
399
+ commit.changes[path] = FileChange(
400
+ type=ActionType.ADD, new_content=action.new_file
401
+ )
402
+ elif action.type is ActionType.UPDATE:
403
+ new_content = _get_updated_file(orig[path], action, path)
404
+ commit.changes[path] = FileChange(
405
+ type=ActionType.UPDATE,
406
+ old_content=orig[path],
407
+ new_content=new_content,
408
+ move_path=action.move_path,
409
+ )
410
+ return commit
411
+
412
+
413
+ # --------------------------------------------------------------------------- #
414
+ # User-facing helpers
415
+ # --------------------------------------------------------------------------- #
416
+ def text_to_patch(text: str, orig: Dict[str, str]) -> Tuple[Patch, int]:
417
+ lines = text.splitlines() # preserves blank lines, no strip()
418
+ if (
419
+ len(lines) < 2
420
+ or not Parser._norm(lines[0]).startswith("*** Begin Patch")
421
+ or Parser._norm(lines[-1]) != "*** End Patch"
422
+ ):
423
+ raise DiffError("Invalid patch text - missing sentinels")
424
+
425
+ parser = Parser(current_files=orig, lines=lines, index=1)
426
+ parser.parse()
427
+ return parser.patch, parser.fuzz
428
+
429
+
430
+ def identify_files_needed(text: str) -> List[str]:
431
+ lines = text.splitlines()
432
+ return [
433
+ line[len("*** Update File: ") :]
434
+ for line in lines
435
+ if line.startswith("*** Update File: ")
436
+ ] + [
437
+ line[len("*** Delete File: ") :]
438
+ for line in lines
439
+ if line.startswith("*** Delete File: ")
440
+ ]
441
+
442
+
443
+ def identify_files_added(text: str) -> List[str]:
444
+ lines = text.splitlines()
445
+ return [
446
+ line[len("*** Add File: ") :]
447
+ for line in lines
448
+ if line.startswith("*** Add File: ")
449
+ ]
450
+
451
+
452
+ # --------------------------------------------------------------------------- #
453
+ # File-system helpers
454
+ # --------------------------------------------------------------------------- #
455
+ def load_files(paths: List[str], open_fn: Callable[[str], str]) -> Dict[str, str]:
456
+ return {path: open_fn(path) for path in paths}
457
+
458
+
459
+ def apply_commit(
460
+ commit: Commit,
461
+ write_fn: Callable[[str, str], None],
462
+ remove_fn: Callable[[str], None],
463
+ ) -> None:
464
+ for path, change in commit.changes.items():
465
+ if change.type is ActionType.DELETE:
466
+ remove_fn(path)
467
+ elif change.type is ActionType.ADD:
468
+ if change.new_content is None:
469
+ raise DiffError(f"ADD change for {path} has no content")
470
+ write_fn(path, change.new_content)
471
+ elif change.type is ActionType.UPDATE:
472
+ if change.new_content is None:
473
+ raise DiffError(f"UPDATE change for {path} has no new content")
474
+ target = change.move_path or path
475
+ write_fn(target, change.new_content)
476
+ if change.move_path:
477
+ remove_fn(path)
478
+
479
+
480
+ def open_file(path: str) -> str:
481
+ with open(path, "rt", encoding="utf-8") as fh:
482
+ return fh.read()
483
+
484
+
485
+ def write_file(path: str, content: str) -> None:
486
+ target = pathlib.Path(path)
487
+ target.parent.mkdir(parents=True, exist_ok=True)
488
+ with target.open("wt", encoding="utf-8") as fh:
489
+ fh.write(content)
490
+
491
+
492
+ def remove_file(path: str) -> None:
493
+ pathlib.Path(path).unlink(missing_ok=True)
494
+
495
+
496
+
497
+ def apply_patch(
498
+ text: str,
499
+ open_fn: Callable[[str], str] = open_file,
500
+ write_fn: Callable[[str, str], None] = write_file,
501
+ remove_fn: Callable[[str], None] = remove_file,
502
+ ) -> str:
503
+ if not text.startswith("*** Begin Patch"):
504
+ raise DiffError("Patch text must start with *** Begin Patch")
505
+ paths = identify_files_needed(text)
506
+ orig = load_files(paths, open_fn)
507
+ patch, _fuzz = text_to_patch(text, orig)
508
+ commit = patch_to_commit(patch, orig)
509
+ apply_commit(commit, write_fn, remove_fn)
510
+ return "Done!"
511
+
512
+
513
+ def main() -> None:
514
+ import sys
515
+
516
+ patch_text = sys.stdin.read()
517
+ if not patch_text:
518
+ print("Please pass patch text through stdin", file=sys.stderr)
519
+ return
520
+ try:
521
+ result = apply_patch(patch_text)
522
+ except DiffError as exc:
523
+ print(exc, file=sys.stderr)
524
+ return
525
+ print(result)
526
+
527
+
528
+ if __name__ == "__main__":
529
+ main()
src/utils.py ADDED
@@ -0,0 +1,18 @@
1
+ from src.constants import READ_ONLY_COMMANDS
2
+
3
+
4
+ def is_read_only_command(command: str) -> bool:
5
+ """A simple check to see if the command is only for reading files.
6
+
7
+ Not a comprehensive or foolproof check by any means, and will
8
+ return false negatives to be safe.
9
+ """
10
+ if ">" in command:
11
+ return False
12
+
13
+ pipes = command.split("|")
14
+ for pipe in pipes:
15
+ if pipe.strip().split()[0] not in READ_ONLY_COMMANDS:
16
+ return False
17
+
18
+ return True
@@ -0,0 +1,36 @@
1
+ Metadata-Version: 2.4
2
+ Name: tass
3
+ Version: 0.1.0
4
+ Summary: A terminal assistant that allows you to ask an LLM to run commands.
5
+ Project-URL: Homepage, https://github.com/cetincan0/tass
6
+ Author: Can Cetin
7
+ License: Apache-2.0
8
+ License-File: LICENSE
9
+ Requires-Python: >=3.10
10
+ Requires-Dist: requests>=2.32.5
11
+ Requires-Dist: rich>=14.2.0
12
+ Description-Content-Type: text/markdown
13
+
14
+ # tass
15
+
16
+ A terminal assistant that allows you to ask an LLM to run commands.
17
+
18
+ ## Warning
19
+
20
+ This tool can run commands including ones that can modify, move, or delete files. Use at your own risk.
21
+
22
+ ## Installation
23
+
24
+ ```
25
+ uv tools install tass
26
+ ```
27
+
28
+ You can run it with
29
+
30
+ ```
31
+ tass
32
+ ```
33
+
34
+ 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.
35
+
36
+ Once it's running, you can ask questions like "Can you create an empty file called test.txt?" and it will propose a command to run after user confirmation.
@@ -0,0 +1,14 @@
1
+ src/__init__.py,sha256=tu2q9W5_pkq30l3tRMTGahColBAAubbLP6LaB3l3IFg,89
2
+ src/app.py,sha256=WO6KIHrQI8sL9IBLazeyiTaFp9UWG9n9GPiPxt9dRKs,6214
3
+ src/cli.py,sha256=op3fYcyfek_KqCCiA-Zdlc9jVZSCi036whMmR2ZjjAs,76
4
+ src/constants.py,sha256=qzqqLwVp6bVCbelvxGZlSYSnMKZFEjFvBWF-bW86ER8,3097
5
+ src/utils.py,sha256=KLVKfTECfSCXqSkWmT9rK1wtjFvb6FJhusy5q7FGO_A,483
6
+ src/third_party/README.md,sha256=fjgAoAM_Vp1xOCdSYZT1menMom5dVDXa48h9VbDJfVI,160
7
+ src/third_party/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ src/third_party/apply_patch.md,sha256=Q0bRVZepyrP0wF-IzNiNEfkXYcbFKJ42y7Hrl5Uxyfc,2578
9
+ src/third_party/apply_patch.py,sha256=zZNWPp4bKuvHikGFQ_aHtDaWZ2ZH39c59J9Fb6NprCE,17575
10
+ tass-0.1.0.dist-info/METADATA,sha256=oIKaTt006wFfm6a30O73pkQwM3dolzg_S4JgCaYNu3s,1071
11
+ tass-0.1.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
12
+ tass-0.1.0.dist-info/entry_points.txt,sha256=pviKuIOuHvaQ7_YiFxatJEY8XYfh3EzVWy4LJh0v-A0,38
13
+ tass-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
14
+ tass-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.28.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ tass = src.cli:main
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.