kolega-code 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.
- kolega_code/__init__.py +151 -0
- kolega_code/agent/__init__.py +42 -0
- kolega_code/agent/baseagent.py +998 -0
- kolega_code/agent/browseragent.py +123 -0
- kolega_code/agent/coder.py +157 -0
- kolega_code/agent/common.py +41 -0
- kolega_code/agent/compression.py +81 -0
- kolega_code/agent/context.py +112 -0
- kolega_code/agent/conversation.py +408 -0
- kolega_code/agent/generalagent.py +146 -0
- kolega_code/agent/investigationagent.py +123 -0
- kolega_code/agent/planningagent.py +187 -0
- kolega_code/agent/prompt_provider.py +196 -0
- kolega_code/agent/prompt_templates/agents/browser.j2 +102 -0
- kolega_code/agent/prompt_templates/agents/coder_cli_mode.j2 +127 -0
- kolega_code/agent/prompt_templates/agents/general.j2 +68 -0
- kolega_code/agent/prompt_templates/agents/investigation.j2 +72 -0
- kolega_code/agent/prompt_templates/common/frontend_guidance.md +36 -0
- kolega_code/agent/prompt_templates/common/kolega_md_instructions.md +14 -0
- kolega_code/agent/prompt_templates/environment_variables/workspace_env_vars.md +11 -0
- kolega_code/agent/prompt_templates/template_guidance/expo-template.md +379 -0
- kolega_code/agent/prompt_templates/template_guidance/html-website-template.md +3 -0
- kolega_code/agent/prompt_templates/template_guidance/mern-stack-template.md +3 -0
- kolega_code/agent/prompt_templates/template_guidance/react-vite-shadcdn-template.md +182 -0
- kolega_code/agent/prompts.py +192 -0
- kolega_code/agent/tests/__init__.py +0 -0
- kolega_code/agent/tests/llm/__init__.py +0 -0
- kolega_code/agent/tests/llm/test_anthropic_token_counting.py +633 -0
- kolega_code/agent/tests/llm/test_billing_openai_cache.py +74 -0
- kolega_code/agent/tests/llm/test_client.py +773 -0
- kolega_code/agent/tests/llm/test_dashscope_mapping.py +32 -0
- kolega_code/agent/tests/llm/test_error_boundary.py +322 -0
- kolega_code/agent/tests/llm/test_exceptions.py +249 -0
- kolega_code/agent/tests/llm/test_instrumented_client.py +536 -0
- kolega_code/agent/tests/llm/test_instrumented_client_integration.py +547 -0
- kolega_code/agent/tests/llm/test_langfuse_normalization.py +39 -0
- kolega_code/agent/tests/llm/test_model_specs.py +17 -0
- kolega_code/agent/tests/llm/test_openai_cached_tokens.py +58 -0
- kolega_code/agent/tests/llm/test_openai_cached_tokens_stream.py +74 -0
- kolega_code/agent/tests/llm/test_openai_message_conversion.py +30 -0
- kolega_code/agent/tests/llm/test_openai_token_counting.py +687 -0
- kolega_code/agent/tests/llm/test_tool_execution_ids.py +193 -0
- kolega_code/agent/tests/services/__init__.py +1 -0
- kolega_code/agent/tests/services/test_browser.py +447 -0
- kolega_code/agent/tests/services/test_browser_parity.py +353 -0
- kolega_code/agent/tests/services/test_file_system.py +699 -0
- kolega_code/agent/tests/services/test_sandbox_terminal_input.py +98 -0
- kolega_code/agent/tests/services/test_terminal.py +154 -0
- kolega_code/agent/tests/services/test_terminal_command_tracking.py +385 -0
- kolega_code/agent/tests/services/test_terminal_state_serializer.py +262 -0
- kolega_code/agent/tests/test_agent_tools_inventory.py +267 -0
- kolega_code/agent/tests/test_base_agent.py +1942 -0
- kolega_code/agent/tests/test_coder_attachments.py +330 -0
- kolega_code/agent/tests/test_coder_prompt_extensions.py +61 -0
- kolega_code/agent/tests/test_commands.py +179 -0
- kolega_code/agent/tests/test_duplicate_tool_results.py +556 -0
- kolega_code/agent/tests/test_empty_message_handling.py +48 -0
- kolega_code/agent/tests/test_general_agent.py +242 -0
- kolega_code/agent/tests/test_html.py +320 -0
- kolega_code/agent/tests/test_parallel_tool_calls.py +291 -0
- kolega_code/agent/tests/test_planning_agent.py +227 -0
- kolega_code/agent/tests/test_prompt_provider.py +271 -0
- kolega_code/agent/tests/test_tool_registry.py +102 -0
- kolega_code/agent/tests/test_tools.py +549 -0
- kolega_code/agent/tests/tool_backend/__init__.py +0 -0
- kolega_code/agent/tests/tool_backend/test_agent_tool.py +356 -0
- kolega_code/agent/tests/tool_backend/test_base_tool.py +147 -0
- kolega_code/agent/tests/tool_backend/test_browser_tool.py +335 -0
- kolega_code/agent/tests/tool_backend/test_build_tool.py +93 -0
- kolega_code/agent/tests/tool_backend/test_create_file_tool.py +115 -0
- kolega_code/agent/tests/tool_backend/test_glob_tool.py +196 -0
- kolega_code/agent/tests/tool_backend/test_glob_tool_sandbox_parity.py +230 -0
- kolega_code/agent/tests/tool_backend/test_list_directory_tool.py +292 -0
- kolega_code/agent/tests/tool_backend/test_read_file_tool.py +173 -0
- kolega_code/agent/tests/tool_backend/test_replace_entire_file_tool.py +115 -0
- kolega_code/agent/tests/tool_backend/test_replace_lines_tool.py +141 -0
- kolega_code/agent/tests/tool_backend/test_search_and_replace_tool.py +174 -0
- kolega_code/agent/tests/tool_backend/test_search_codebase_tool.py +228 -0
- kolega_code/agent/tests/tool_backend/test_terminal_tool.py +482 -0
- kolega_code/agent/tests/tool_backend/test_think_hard_integration.py +189 -0
- kolega_code/agent/tests/tool_backend/test_think_hard_streaming.py +445 -0
- kolega_code/agent/tests/tool_backend/test_web_fetch_tool.py +194 -0
- kolega_code/agent/tool_backend/agent_tool.py +414 -0
- kolega_code/agent/tool_backend/apply_edit_tool.py +98 -0
- kolega_code/agent/tool_backend/apply_patch_tool.py +514 -0
- kolega_code/agent/tool_backend/base_tool.py +217 -0
- kolega_code/agent/tool_backend/browser_tool.py +271 -0
- kolega_code/agent/tool_backend/build_tool.py +93 -0
- kolega_code/agent/tool_backend/create_file_tool.py +52 -0
- kolega_code/agent/tool_backend/glob_tool.py +323 -0
- kolega_code/agent/tool_backend/list_directory_tool.py +300 -0
- kolega_code/agent/tool_backend/memory_tool.py +79 -0
- kolega_code/agent/tool_backend/read_file_tool.py +119 -0
- kolega_code/agent/tool_backend/replace_entire_file_tool.py +40 -0
- kolega_code/agent/tool_backend/replace_lines_tool.py +97 -0
- kolega_code/agent/tool_backend/search_and_replace_tool.py +146 -0
- kolega_code/agent/tool_backend/search_codebase_tool.py +377 -0
- kolega_code/agent/tool_backend/streaming_tool.py +47 -0
- kolega_code/agent/tool_backend/terminal_tool.py +643 -0
- kolega_code/agent/tool_backend/think_hard_tool.py +211 -0
- kolega_code/agent/tool_backend/web_fetch_tool.py +205 -0
- kolega_code/agent/tools.py +1704 -0
- kolega_code/agent/utils/commands.py +94 -0
- kolega_code/cli/__init__.py +1 -0
- kolega_code/cli/app.py +2756 -0
- kolega_code/cli/config.py +280 -0
- kolega_code/cli/connection.py +49 -0
- kolega_code/cli/file_index.py +147 -0
- kolega_code/cli/main.py +564 -0
- kolega_code/cli/mentions.py +155 -0
- kolega_code/cli/messages.py +89 -0
- kolega_code/cli/provider_registry.py +96 -0
- kolega_code/cli/session_store.py +207 -0
- kolega_code/cli/settings.py +87 -0
- kolega_code/cli/skills.py +409 -0
- kolega_code/cli/slash_commands.py +108 -0
- kolega_code/cli/tests/__init__.py +1 -0
- kolega_code/cli/tests/test_app.py +4251 -0
- kolega_code/cli/tests/test_cli_config.py +171 -0
- kolega_code/cli/tests/test_connection.py +26 -0
- kolega_code/cli/tests/test_file_index.py +103 -0
- kolega_code/cli/tests/test_main.py +455 -0
- kolega_code/cli/tests/test_mentions.py +108 -0
- kolega_code/cli/tests/test_session_store.py +67 -0
- kolega_code/cli/tests/test_settings.py +62 -0
- kolega_code/cli/tests/test_skills.py +157 -0
- kolega_code/cli/tests/test_slash_commands.py +88 -0
- kolega_code/cli/theme.py +180 -0
- kolega_code/config.py +154 -0
- kolega_code/events.py +202 -0
- kolega_code/llm/client.py +300 -0
- kolega_code/llm/exceptions.py +285 -0
- kolega_code/llm/instrumented_client.py +520 -0
- kolega_code/llm/models.py +1368 -0
- kolega_code/llm/providers/__init__.py +0 -0
- kolega_code/llm/providers/anthropic.py +387 -0
- kolega_code/llm/providers/base.py +71 -0
- kolega_code/llm/providers/google.py +157 -0
- kolega_code/llm/providers/models.py +37 -0
- kolega_code/llm/providers/openai.py +363 -0
- kolega_code/llm/ratelimit.py +40 -0
- kolega_code/llm/specs.py +67 -0
- kolega_code/llm/tool_execution_ids.py +18 -0
- kolega_code/models/__init__.py +9 -0
- kolega_code/models/sandbox_terminal_state.py +47 -0
- kolega_code/runtime.py +50 -0
- kolega_code/sandbox/README.md +200 -0
- kolega_code/sandbox/__init__.py +21 -0
- kolega_code/sandbox/async_filesystem.py +475 -0
- kolega_code/sandbox/base.py +297 -0
- kolega_code/sandbox/browser.py +25 -0
- kolega_code/sandbox/event_loop.py +43 -0
- kolega_code/sandbox/filesystem.py +341 -0
- kolega_code/sandbox/local.py +118 -0
- kolega_code/sandbox/serializer.py +175 -0
- kolega_code/sandbox/terminal.py +868 -0
- kolega_code/sandbox/utils.py +216 -0
- kolega_code/services/base.py +255 -0
- kolega_code/services/browser.py +444 -0
- kolega_code/services/file_system.py +749 -0
- kolega_code/services/html.py +221 -0
- kolega_code/services/terminal.py +903 -0
- kolega_code/tools/__init__.py +22 -0
- kolega_code/tools/core.py +33 -0
- kolega_code/tools/definitions.py +81 -0
- kolega_code/tools/registry.py +73 -0
- kolega_code-0.1.0.dist-info/METADATA +157 -0
- kolega_code-0.1.0.dist-info/RECORD +171 -0
- kolega_code-0.1.0.dist-info/WHEEL +4 -0
- kolega_code-0.1.0.dist-info/entry_points.txt +2 -0
- kolega_code-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,514 @@
|
|
|
1
|
+
import pathlib
|
|
2
|
+
from dataclasses import dataclass, field
|
|
3
|
+
from enum import Enum
|
|
4
|
+
from typing import (
|
|
5
|
+
Callable,
|
|
6
|
+
Dict,
|
|
7
|
+
List,
|
|
8
|
+
Optional,
|
|
9
|
+
Tuple,
|
|
10
|
+
Union,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
from .base_tool import BaseTool
|
|
14
|
+
|
|
15
|
+
APPLY_PATCH_TOOL_DESC = """This is a custom utility that makes it more convenient to add, remove, move, or edit code files. `apply_patch` effectively allows you to execute a diff/patch against a file, but the format of the diff specification is unique to this task, so pay careful attention to these instructions. To use the `apply_patch` command, you should pass a message of the following structure as "input":
|
|
16
|
+
|
|
17
|
+
%%bash
|
|
18
|
+
apply_patch <<"EOF"
|
|
19
|
+
*** Begin Patch
|
|
20
|
+
[YOUR_PATCH]
|
|
21
|
+
*** End Patch
|
|
22
|
+
EOF
|
|
23
|
+
|
|
24
|
+
Where [YOUR_PATCH] is the actual content of your patch, specified in the following V4A diff format.
|
|
25
|
+
|
|
26
|
+
*** [ACTION] File: [path/to/file] -> ACTION can be one of Add, Update, or Delete.
|
|
27
|
+
For each snippet of code that needs to be changed, repeat the following:
|
|
28
|
+
[context_before] -> See below for further instructions on context.
|
|
29
|
+
- [old_code] -> Precede the old code with a minus sign.
|
|
30
|
+
+ [new_code] -> Precede the new, replacement code with a plus sign.
|
|
31
|
+
[context_after] -> See below for further instructions on context.
|
|
32
|
+
|
|
33
|
+
For instructions on [context_before] and [context_after]:
|
|
34
|
+
- By default, show 3 lines of code immediately above and 3 lines immediately below each change. If a change is within 3 lines of a previous change, do NOT duplicate the first change’s [context_after] lines in the second change’s [context_before] lines.
|
|
35
|
+
- If 3 lines of context is insufficient to uniquely identify the snippet of code within the file, use the @@ operator to indicate the class or function to which the snippet belongs. For instance, we might have:
|
|
36
|
+
@@ class BaseClass
|
|
37
|
+
[3 lines of pre-context]
|
|
38
|
+
- [old_code]
|
|
39
|
+
+ [new_code]
|
|
40
|
+
[3 lines of post-context]
|
|
41
|
+
|
|
42
|
+
- If a code block is repeated so many times in a class or function such that even a single @@ statement and 3 lines of context cannot uniquely identify the snippet of code, you can use multiple `@@` statements to jump to the right context. For instance:
|
|
43
|
+
|
|
44
|
+
@@ class BaseClass
|
|
45
|
+
@@ def method():
|
|
46
|
+
[3 lines of pre-context]
|
|
47
|
+
- [old_code]
|
|
48
|
+
+ [new_code]
|
|
49
|
+
[3 lines of post-context]
|
|
50
|
+
|
|
51
|
+
Note, then, that we do not use line numbers in this diff format, as the context is enough to uniquely identify code. An example of a message that you might pass as "input" to this function, in order to apply a patch, is shown below.
|
|
52
|
+
|
|
53
|
+
%%bash
|
|
54
|
+
apply_patch <<"EOF"
|
|
55
|
+
*** Begin Patch
|
|
56
|
+
*** Update File: pygorithm/searching/binary_search.py
|
|
57
|
+
@@ class BaseClass
|
|
58
|
+
@@ def search():
|
|
59
|
+
- pass
|
|
60
|
+
+ raise NotImplementedError()
|
|
61
|
+
|
|
62
|
+
@@ class Subclass
|
|
63
|
+
@@ def search():
|
|
64
|
+
- pass
|
|
65
|
+
+ raise NotImplementedError()
|
|
66
|
+
|
|
67
|
+
*** End Patch
|
|
68
|
+
EOF
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
# Filesystem helpers will be replaced with filesystem service calls in apply_patch method
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
# Patch types
|
|
76
|
+
class ActionType(str, Enum):
|
|
77
|
+
ADD = "add"
|
|
78
|
+
DELETE = "delete"
|
|
79
|
+
UPDATE = "update"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass
|
|
83
|
+
class FileChange:
|
|
84
|
+
type: ActionType
|
|
85
|
+
old_content: Optional[str] = None
|
|
86
|
+
new_content: Optional[str] = None
|
|
87
|
+
move_path: Optional[str] = None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass
|
|
91
|
+
class Commit:
|
|
92
|
+
changes: Dict[str, FileChange] = field(default_factory=dict)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@dataclass
|
|
96
|
+
class Chunk:
|
|
97
|
+
orig_index: int = -1
|
|
98
|
+
del_lines: List[str] = field(default_factory=list)
|
|
99
|
+
ins_lines: List[str] = field(default_factory=list)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@dataclass
|
|
103
|
+
class PatchAction:
|
|
104
|
+
type: ActionType
|
|
105
|
+
new_file: Optional[str] = None
|
|
106
|
+
chunks: List[Chunk] = field(default_factory=list)
|
|
107
|
+
move_path: Optional[str] = None
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@dataclass
|
|
111
|
+
class Patch:
|
|
112
|
+
actions: Dict[str, PatchAction] = field(default_factory=dict)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
# Errors
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class DiffError(ValueError):
|
|
119
|
+
"""Any problem detected while parsing or applying a patch."""
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
# Patch helpers
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def find_context_core(lines: List[str], context: List[str], start: int) -> Tuple[int, int]:
|
|
126
|
+
if not context:
|
|
127
|
+
return start, 0
|
|
128
|
+
|
|
129
|
+
for i in range(start, len(lines)):
|
|
130
|
+
if lines[i : i + len(context)] == context:
|
|
131
|
+
return i, 0
|
|
132
|
+
for i in range(start, len(lines)):
|
|
133
|
+
if [s.rstrip() for s in lines[i : i + len(context)]] == [s.rstrip() for s in context]:
|
|
134
|
+
return i, 1
|
|
135
|
+
for i in range(start, len(lines)):
|
|
136
|
+
if [s.strip() for s in lines[i : i + len(context)]] == [s.strip() for s in context]:
|
|
137
|
+
return i, 100
|
|
138
|
+
return -1, 0
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def find_context(lines: List[str], context: List[str], start: int, eof: bool) -> Tuple[int, int]:
|
|
142
|
+
if eof:
|
|
143
|
+
new_index, fuzz = find_context_core(lines, context, len(lines) - len(context))
|
|
144
|
+
if new_index != -1:
|
|
145
|
+
return new_index, fuzz
|
|
146
|
+
new_index, fuzz = find_context_core(lines, context, start)
|
|
147
|
+
return new_index, fuzz + 10_000
|
|
148
|
+
return find_context_core(lines, context, start)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def peek_next_section(lines: List[str], index: int) -> Tuple[List[str], List[Chunk], int, bool]:
|
|
152
|
+
old: List[str] = []
|
|
153
|
+
del_lines: List[str] = []
|
|
154
|
+
ins_lines: List[str] = []
|
|
155
|
+
chunks: List[Chunk] = []
|
|
156
|
+
mode = "keep"
|
|
157
|
+
orig_index = index
|
|
158
|
+
|
|
159
|
+
while index < len(lines):
|
|
160
|
+
s = lines[index]
|
|
161
|
+
if s.startswith(
|
|
162
|
+
(
|
|
163
|
+
"@@",
|
|
164
|
+
"*** End Patch",
|
|
165
|
+
"*** Update File:",
|
|
166
|
+
"*** Delete File:",
|
|
167
|
+
"*** Add File:",
|
|
168
|
+
"*** End of File",
|
|
169
|
+
)
|
|
170
|
+
):
|
|
171
|
+
break
|
|
172
|
+
if s == "***":
|
|
173
|
+
break
|
|
174
|
+
if s.startswith("***"):
|
|
175
|
+
raise DiffError(f"Invalid Line: {s}")
|
|
176
|
+
index += 1
|
|
177
|
+
|
|
178
|
+
last_mode = mode
|
|
179
|
+
if s == "":
|
|
180
|
+
s = " "
|
|
181
|
+
if s[0] == "+":
|
|
182
|
+
mode = "add"
|
|
183
|
+
elif s[0] == "-":
|
|
184
|
+
mode = "delete"
|
|
185
|
+
elif s[0] == " ":
|
|
186
|
+
mode = "keep"
|
|
187
|
+
else:
|
|
188
|
+
raise DiffError(f"Invalid Line: {s}")
|
|
189
|
+
s = s[1:]
|
|
190
|
+
|
|
191
|
+
if mode == "keep" and last_mode != mode:
|
|
192
|
+
if ins_lines or del_lines:
|
|
193
|
+
chunks.append(
|
|
194
|
+
Chunk(
|
|
195
|
+
orig_index=len(old) - len(del_lines),
|
|
196
|
+
del_lines=del_lines,
|
|
197
|
+
ins_lines=ins_lines,
|
|
198
|
+
)
|
|
199
|
+
)
|
|
200
|
+
del_lines, ins_lines = [], []
|
|
201
|
+
|
|
202
|
+
if mode == "delete":
|
|
203
|
+
del_lines.append(s)
|
|
204
|
+
old.append(s)
|
|
205
|
+
elif mode == "add":
|
|
206
|
+
ins_lines.append(s)
|
|
207
|
+
elif mode == "keep":
|
|
208
|
+
old.append(s)
|
|
209
|
+
|
|
210
|
+
if ins_lines or del_lines:
|
|
211
|
+
chunks.append(
|
|
212
|
+
Chunk(
|
|
213
|
+
orig_index=len(old) - len(del_lines),
|
|
214
|
+
del_lines=del_lines,
|
|
215
|
+
ins_lines=ins_lines,
|
|
216
|
+
)
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
if index < len(lines) and lines[index] == "*** End of File":
|
|
220
|
+
index += 1
|
|
221
|
+
return old, chunks, index, True
|
|
222
|
+
|
|
223
|
+
if index == orig_index:
|
|
224
|
+
raise DiffError("Nothing in this section")
|
|
225
|
+
return old, chunks, index, False
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
@dataclass
|
|
229
|
+
class Parser:
|
|
230
|
+
current_files: Dict[str, str]
|
|
231
|
+
lines: List[str]
|
|
232
|
+
index: int = 0
|
|
233
|
+
patch: Patch = field(default_factory=Patch)
|
|
234
|
+
fuzz: int = 0
|
|
235
|
+
|
|
236
|
+
# ------------- low-level helpers -------------------------------------- #
|
|
237
|
+
def _cur_line(self) -> str:
|
|
238
|
+
if self.index >= len(self.lines):
|
|
239
|
+
raise DiffError("Unexpected end of input while parsing patch")
|
|
240
|
+
return self.lines[self.index]
|
|
241
|
+
|
|
242
|
+
@staticmethod
|
|
243
|
+
def _norm(line: str) -> str:
|
|
244
|
+
"""Strip CR so comparisons work for both LF and CRLF input."""
|
|
245
|
+
return line.rstrip("\r")
|
|
246
|
+
|
|
247
|
+
# ------------- scanning convenience ----------------------------------- #
|
|
248
|
+
def is_done(self, prefixes: Optional[Tuple[str, ...]] = None) -> bool:
|
|
249
|
+
if self.index >= len(self.lines):
|
|
250
|
+
return True
|
|
251
|
+
if prefixes and len(prefixes) > 0 and self._norm(self._cur_line()).startswith(prefixes):
|
|
252
|
+
return True
|
|
253
|
+
return False
|
|
254
|
+
|
|
255
|
+
def startswith(self, prefix: Union[str, Tuple[str, ...]]) -> bool:
|
|
256
|
+
return self._norm(self._cur_line()).startswith(prefix)
|
|
257
|
+
|
|
258
|
+
def read_str(self, prefix: str) -> str:
|
|
259
|
+
"""
|
|
260
|
+
Consume the current line if it starts with *prefix* and return the text
|
|
261
|
+
**after** the prefix. Raises if prefix is empty.
|
|
262
|
+
"""
|
|
263
|
+
if prefix == "":
|
|
264
|
+
raise ValueError("read_str() requires a non-empty prefix")
|
|
265
|
+
if self._norm(self._cur_line()).startswith(prefix):
|
|
266
|
+
text = self._cur_line()[len(prefix) :]
|
|
267
|
+
self.index += 1
|
|
268
|
+
return text
|
|
269
|
+
return ""
|
|
270
|
+
|
|
271
|
+
def read_line(self) -> str:
|
|
272
|
+
"""Return the current raw line and advance."""
|
|
273
|
+
line = self._cur_line()
|
|
274
|
+
self.index += 1
|
|
275
|
+
return line
|
|
276
|
+
|
|
277
|
+
# ------------- public entry point -------------------------------------- #
|
|
278
|
+
def parse(self) -> None:
|
|
279
|
+
while not self.is_done(("*** End Patch",)):
|
|
280
|
+
# ---------- UPDATE ---------- #
|
|
281
|
+
path = self.read_str("*** Update File: ")
|
|
282
|
+
if path:
|
|
283
|
+
if path in self.patch.actions:
|
|
284
|
+
raise DiffError(f"Duplicate update for file: {path}")
|
|
285
|
+
move_to = self.read_str("*** Move to: ")
|
|
286
|
+
if path not in self.current_files:
|
|
287
|
+
raise DiffError(f"Update File Error - missing file: {path}")
|
|
288
|
+
text = self.current_files[path]
|
|
289
|
+
action = self._parse_update_file(text)
|
|
290
|
+
action.move_path = move_to or None
|
|
291
|
+
self.patch.actions[path] = action
|
|
292
|
+
continue
|
|
293
|
+
|
|
294
|
+
# ---------- DELETE ---------- #
|
|
295
|
+
path = self.read_str("*** Delete File: ")
|
|
296
|
+
if path:
|
|
297
|
+
if path in self.patch.actions:
|
|
298
|
+
raise DiffError(f"Duplicate delete for file: {path}")
|
|
299
|
+
if path not in self.current_files:
|
|
300
|
+
raise DiffError(f"Delete File Error - missing file: {path}")
|
|
301
|
+
self.patch.actions[path] = PatchAction(type=ActionType.DELETE)
|
|
302
|
+
continue
|
|
303
|
+
|
|
304
|
+
# ---------- ADD ---------- #
|
|
305
|
+
path = self.read_str("*** Add File: ")
|
|
306
|
+
if path:
|
|
307
|
+
if path in self.patch.actions:
|
|
308
|
+
raise DiffError(f"Duplicate add for file: {path}")
|
|
309
|
+
if path in self.current_files:
|
|
310
|
+
raise DiffError(f"Add File Error - file already exists: {path}")
|
|
311
|
+
self.patch.actions[path] = self._parse_add_file()
|
|
312
|
+
continue
|
|
313
|
+
|
|
314
|
+
raise DiffError(f"Unknown line while parsing: {self._cur_line()}")
|
|
315
|
+
|
|
316
|
+
if not self.startswith("*** End Patch"):
|
|
317
|
+
raise DiffError("Missing *** End Patch sentinel")
|
|
318
|
+
self.index += 1 # consume sentinel
|
|
319
|
+
|
|
320
|
+
# ------------- section parsers ---------------------------------------- #
|
|
321
|
+
def _parse_update_file(self, text: str) -> PatchAction:
|
|
322
|
+
action = PatchAction(type=ActionType.UPDATE)
|
|
323
|
+
lines = text.split("\n")
|
|
324
|
+
index = 0
|
|
325
|
+
while not self.is_done(
|
|
326
|
+
(
|
|
327
|
+
"*** End Patch",
|
|
328
|
+
"*** Update File:",
|
|
329
|
+
"*** Delete File:",
|
|
330
|
+
"*** Add File:",
|
|
331
|
+
"*** End of File",
|
|
332
|
+
)
|
|
333
|
+
):
|
|
334
|
+
def_str = self.read_str("@@ ")
|
|
335
|
+
section_str = ""
|
|
336
|
+
if not def_str and self._norm(self._cur_line()) == "@@":
|
|
337
|
+
section_str = self.read_line()
|
|
338
|
+
|
|
339
|
+
if not (def_str or section_str or index == 0):
|
|
340
|
+
raise DiffError(f"Invalid line in update section:\n{self._cur_line()}")
|
|
341
|
+
|
|
342
|
+
if def_str.strip():
|
|
343
|
+
found = False
|
|
344
|
+
if def_str not in lines[:index]:
|
|
345
|
+
for i, s in enumerate(lines[index:], index):
|
|
346
|
+
if s == def_str:
|
|
347
|
+
index = i + 1
|
|
348
|
+
found = True
|
|
349
|
+
break
|
|
350
|
+
if not found and def_str.strip() not in [s.strip() for s in lines[:index]]:
|
|
351
|
+
for i, s in enumerate(lines[index:], index):
|
|
352
|
+
if s.strip() == def_str.strip():
|
|
353
|
+
index = i + 1
|
|
354
|
+
self.fuzz += 1
|
|
355
|
+
found = True
|
|
356
|
+
break
|
|
357
|
+
|
|
358
|
+
next_ctx, chunks, end_idx, eof = peek_next_section(self.lines, self.index)
|
|
359
|
+
new_index, fuzz = find_context(lines, next_ctx, index, eof)
|
|
360
|
+
if new_index == -1:
|
|
361
|
+
ctx_txt = "\n".join(next_ctx)
|
|
362
|
+
raise DiffError(f"Invalid {'EOF ' if eof else ''}context at {index}:\n{ctx_txt}")
|
|
363
|
+
self.fuzz += fuzz
|
|
364
|
+
for ch in chunks:
|
|
365
|
+
ch.orig_index += new_index
|
|
366
|
+
action.chunks.append(ch)
|
|
367
|
+
index = new_index + len(next_ctx)
|
|
368
|
+
self.index = end_idx
|
|
369
|
+
return action
|
|
370
|
+
|
|
371
|
+
def _parse_add_file(self) -> PatchAction:
|
|
372
|
+
lines: List[str] = []
|
|
373
|
+
while not self.is_done(("*** End Patch", "*** Update File:", "*** Delete File:", "*** Add File:")):
|
|
374
|
+
s = self.read_line()
|
|
375
|
+
if not s.startswith("+"):
|
|
376
|
+
raise DiffError(f"Invalid Add File line (missing '+'): {s}")
|
|
377
|
+
lines.append(s[1:]) # strip leading '+'
|
|
378
|
+
return PatchAction(type=ActionType.ADD, new_file="\n".join(lines))
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _get_updated_file(text: str, action: PatchAction, path: str) -> str:
|
|
382
|
+
if action.type is not ActionType.UPDATE:
|
|
383
|
+
raise DiffError("_get_updated_file called with non-update action")
|
|
384
|
+
orig_lines = text.split("\n")
|
|
385
|
+
dest_lines: List[str] = []
|
|
386
|
+
orig_index = 0
|
|
387
|
+
|
|
388
|
+
for chunk in action.chunks:
|
|
389
|
+
if chunk.orig_index > len(orig_lines):
|
|
390
|
+
raise DiffError(f"{path}: chunk.orig_index {chunk.orig_index} exceeds file length")
|
|
391
|
+
if orig_index > chunk.orig_index:
|
|
392
|
+
raise DiffError(f"{path}: overlapping chunks at {orig_index} > {chunk.orig_index}")
|
|
393
|
+
|
|
394
|
+
dest_lines.extend(orig_lines[orig_index : chunk.orig_index])
|
|
395
|
+
orig_index = chunk.orig_index
|
|
396
|
+
|
|
397
|
+
dest_lines.extend(chunk.ins_lines)
|
|
398
|
+
orig_index += len(chunk.del_lines)
|
|
399
|
+
|
|
400
|
+
dest_lines.extend(orig_lines[orig_index:])
|
|
401
|
+
return "\n".join(dest_lines)
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
class ApplyPatchTool(BaseTool):
|
|
405
|
+
|
|
406
|
+
def load_files(self, paths: List[str], open_fn: Callable[[str], str]) -> Dict[str, str]:
|
|
407
|
+
return {path: open_fn(path) for path in paths}
|
|
408
|
+
|
|
409
|
+
def identify_files_needed(self, text):
|
|
410
|
+
lines = text.splitlines()
|
|
411
|
+
return [line[len("*** Update File: ") :] for line in lines if line.startswith("*** Update File: ")] + [
|
|
412
|
+
line[len("*** Delete File: ") :] for line in lines if line.startswith("*** Delete File: ")
|
|
413
|
+
]
|
|
414
|
+
|
|
415
|
+
def text_to_patch(self, text: str, orig: Dict[str, str]) -> Tuple[Patch, int]:
|
|
416
|
+
lines = text.splitlines() # preserves blank lines, no strip()
|
|
417
|
+
if (
|
|
418
|
+
len(lines) < 2
|
|
419
|
+
or not Parser._norm(lines[0]).startswith("*** Begin Patch")
|
|
420
|
+
or Parser._norm(lines[-1]) != "*** End Patch"
|
|
421
|
+
):
|
|
422
|
+
raise DiffError("Invalid patch text - missing sentinels")
|
|
423
|
+
|
|
424
|
+
parser = Parser(current_files=orig, lines=lines, index=1)
|
|
425
|
+
parser.parse()
|
|
426
|
+
return parser.patch, parser.fuzz
|
|
427
|
+
|
|
428
|
+
def patch_to_commit(self, patch: Patch, orig: Dict[str, str]) -> Commit:
|
|
429
|
+
commit = Commit()
|
|
430
|
+
for path, action in patch.actions.items():
|
|
431
|
+
if action.type is ActionType.DELETE:
|
|
432
|
+
commit.changes[path] = FileChange(type=ActionType.DELETE, old_content=orig[path])
|
|
433
|
+
elif action.type is ActionType.ADD:
|
|
434
|
+
if action.new_file is None:
|
|
435
|
+
raise DiffError("ADD action without file content")
|
|
436
|
+
commit.changes[path] = FileChange(type=ActionType.ADD, new_content=action.new_file)
|
|
437
|
+
elif action.type is ActionType.UPDATE:
|
|
438
|
+
new_content = _get_updated_file(orig[path], action, path)
|
|
439
|
+
commit.changes[path] = FileChange(
|
|
440
|
+
type=ActionType.UPDATE,
|
|
441
|
+
old_content=orig[path],
|
|
442
|
+
new_content=new_content,
|
|
443
|
+
move_path=action.move_path,
|
|
444
|
+
)
|
|
445
|
+
return commit
|
|
446
|
+
|
|
447
|
+
def apply_commit(
|
|
448
|
+
self,
|
|
449
|
+
commit: Commit,
|
|
450
|
+
write_fn: Callable[[str, str], None],
|
|
451
|
+
remove_fn: Callable[[str], None],
|
|
452
|
+
) -> None:
|
|
453
|
+
for path, change in commit.changes.items():
|
|
454
|
+
if change.type is ActionType.DELETE:
|
|
455
|
+
remove_fn(path)
|
|
456
|
+
elif change.type is ActionType.ADD:
|
|
457
|
+
if change.new_content is None:
|
|
458
|
+
raise DiffError(f"ADD change for {path} has no content")
|
|
459
|
+
write_fn(path, change.new_content)
|
|
460
|
+
elif change.type is ActionType.UPDATE:
|
|
461
|
+
if change.new_content is None:
|
|
462
|
+
raise DiffError(f"UPDATE change for {path} has no new content")
|
|
463
|
+
target = change.move_path or path
|
|
464
|
+
write_fn(target, change.new_content)
|
|
465
|
+
if change.move_path:
|
|
466
|
+
remove_fn(path)
|
|
467
|
+
|
|
468
|
+
async def apply_patch(self, text: str) -> str:
|
|
469
|
+
"""
|
|
470
|
+
Based on OpenAI's reference implementation:
|
|
471
|
+
https://cookbook.openai.com/examples/gpt4-1_prompting_guide#reference-implementation-apply_patchpy
|
|
472
|
+
"""
|
|
473
|
+
if not text.startswith("*** Begin Patch"):
|
|
474
|
+
raise DiffError("Patch text must start with *** Begin Patch")
|
|
475
|
+
|
|
476
|
+
paths = self.identify_files_needed(text)
|
|
477
|
+
|
|
478
|
+
# Preflight: if any path is blocked, short-circuit with the message
|
|
479
|
+
for p in paths:
|
|
480
|
+
blocked_msg = self._enforce_vibe_edit_policy(p)
|
|
481
|
+
if blocked_msg:
|
|
482
|
+
return blocked_msg
|
|
483
|
+
|
|
484
|
+
# Create filesystem-aware helper functions
|
|
485
|
+
def open_file_fs(path: str) -> str:
|
|
486
|
+
return self.filesystem.read_text(path)
|
|
487
|
+
|
|
488
|
+
def write_file_fs(path: str, content: str) -> None:
|
|
489
|
+
# Enforce vibe-mode edit policy before writing
|
|
490
|
+
msg = self._enforce_vibe_edit_policy(path)
|
|
491
|
+
if msg:
|
|
492
|
+
# Abort by raising to unwind; apply_patch will have preflighted, so this is a safeguard
|
|
493
|
+
raise ValueError(msg)
|
|
494
|
+
parent_dir = self.filesystem.get_parent(path)
|
|
495
|
+
if parent_dir and not self.filesystem.exists(parent_dir):
|
|
496
|
+
self.filesystem.create_directory(parent_dir)
|
|
497
|
+
self.filesystem.write_text(path, content)
|
|
498
|
+
|
|
499
|
+
def remove_file_fs(path: str) -> None:
|
|
500
|
+
# Enforce vibe-mode edit policy before removing
|
|
501
|
+
msg = self._enforce_vibe_edit_policy(path)
|
|
502
|
+
if msg:
|
|
503
|
+
raise ValueError(msg)
|
|
504
|
+
if self.filesystem.exists(path):
|
|
505
|
+
self.filesystem.delete(path)
|
|
506
|
+
|
|
507
|
+
orig = self.load_files(paths, open_file_fs)
|
|
508
|
+
|
|
509
|
+
patch, _fuzz = self.text_to_patch(text, orig)
|
|
510
|
+
commit = self.patch_to_commit(patch, orig)
|
|
511
|
+
|
|
512
|
+
self.apply_commit(commit, write_file_fs, remove_file_fs)
|
|
513
|
+
|
|
514
|
+
return f"Applied patch:\n```\n{text}```\n"
|