coder-agent 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.
Files changed (163) hide show
  1. coder_agent-0.1.0.dist-info/METADATA +262 -0
  2. coder_agent-0.1.0.dist-info/RECORD +163 -0
  3. coder_agent-0.1.0.dist-info/WHEEL +5 -0
  4. coder_agent-0.1.0.dist-info/entry_points.txt +2 -0
  5. coder_agent-0.1.0.dist-info/licenses/LICENSE.md +21 -0
  6. coder_agent-0.1.0.dist-info/top_level.txt +1 -0
  7. coderagent/__init__.py +20 -0
  8. coderagent/compat/__init__.py +27 -0
  9. coderagent/compat/cache_control.py +69 -0
  10. coderagent/compat/config_spec.py +60 -0
  11. coderagent/compat/exceptions.py +20 -0
  12. coderagent/compat/retry.py +27 -0
  13. coderagent/compat/serialize.py +31 -0
  14. coderagent/config/__init__.py +1 -0
  15. coderagent/config/defaults.yaml +103 -0
  16. coderagent/config/loader.py +264 -0
  17. coderagent/config/schema.py +548 -0
  18. coderagent/config/writer.py +218 -0
  19. coderagent/core/__init__.py +1 -0
  20. coderagent/core/budget.py +47 -0
  21. coderagent/core/capabilities.py +136 -0
  22. coderagent/core/checkpoint.py +164 -0
  23. coderagent/core/content.py +156 -0
  24. coderagent/core/context.py +618 -0
  25. coderagent/core/events.py +83 -0
  26. coderagent/core/history.py +56 -0
  27. coderagent/core/instructions.py +99 -0
  28. coderagent/core/loop.py +702 -0
  29. coderagent/core/memory.py +56 -0
  30. coderagent/core/mentions.py +81 -0
  31. coderagent/core/os_sandbox.py +191 -0
  32. coderagent/core/otel.py +214 -0
  33. coderagent/core/protocols.py +38 -0
  34. coderagent/core/redact.py +49 -0
  35. coderagent/core/sandbox.py +82 -0
  36. coderagent/core/schema.py +107 -0
  37. coderagent/core/session.py +344 -0
  38. coderagent/core/shell_env.py +74 -0
  39. coderagent/core/subagent.py +474 -0
  40. coderagent/core/summarize.py +312 -0
  41. coderagent/core/telemetry.py +209 -0
  42. coderagent/core/tokens.py +132 -0
  43. coderagent/core/trust.py +301 -0
  44. coderagent/environments/__init__.py +11 -0
  45. coderagent/environments/bubblewrap.py +150 -0
  46. coderagent/environments/contree.py +146 -0
  47. coderagent/environments/docker.py +160 -0
  48. coderagent/environments/local.py +110 -0
  49. coderagent/environments/singularity.py +138 -0
  50. coderagent/environments/swerex_docker.py +79 -0
  51. coderagent/environments/swerex_modal.py +123 -0
  52. coderagent/eval/__init__.py +1 -0
  53. coderagent/eval/compare.py +190 -0
  54. coderagent/eval/report.py +141 -0
  55. coderagent/eval/runner.py +368 -0
  56. coderagent/eval/task.py +194 -0
  57. coderagent/extensions/__init__.py +1 -0
  58. coderagent/extensions/hooks.py +121 -0
  59. coderagent/extensions/plugins.py +217 -0
  60. coderagent/extensions/reflect.py +342 -0
  61. coderagent/models/__init__.py +33 -0
  62. coderagent/models/backends.py +218 -0
  63. coderagent/models/call.py +18 -0
  64. coderagent/models/check.py +139 -0
  65. coderagent/models/gateway.py +60 -0
  66. coderagent/models/litellm_config.py +70 -0
  67. coderagent/models/provider.py +98 -0
  68. coderagent/models/reasoning.py +28 -0
  69. coderagent/models/router.py +136 -0
  70. coderagent/models/settings.py +172 -0
  71. coderagent/models/streaming.py +122 -0
  72. coderagent/models/verbosity.py +14 -0
  73. coderagent/paths.py +31 -0
  74. coderagent/run.py +454 -0
  75. coderagent/skills/__init__.py +119 -0
  76. coderagent/skills/errors.py +11 -0
  77. coderagent/skills/install.py +340 -0
  78. coderagent/skills/presets/code-review/SKILL.md +35 -0
  79. coderagent/skills/presets/codebase-onboarding/SKILL.md +33 -0
  80. coderagent/skills/presets/data-analysis/SKILL.md +35 -0
  81. coderagent/skills/presets/deep-research/SKILL.md +38 -0
  82. coderagent/skills/presets/frontend-dev/SKILL.md +32 -0
  83. coderagent/skills/presets/long-document/SKILL.md +37 -0
  84. coderagent/skills/presets/long-document/scripts/pdf_text.py +37 -0
  85. coderagent/skills/presets/office-docx/SKILL.md +36 -0
  86. coderagent/skills/presets/office-docx/scripts/docx_text.py +36 -0
  87. coderagent/skills/presets/office-pptx/SKILL.md +32 -0
  88. coderagent/skills/presets/office-xlsx/SKILL.md +34 -0
  89. coderagent/skills/presets/office-xlsx/scripts/xlsx_text.py +72 -0
  90. coderagent/skills/presets/writing/SKILL.md +31 -0
  91. coderagent/skills/sandbox.py +269 -0
  92. coderagent/skills/sites.py +177 -0
  93. coderagent/skills/source.py +404 -0
  94. coderagent/testing/__init__.py +5 -0
  95. coderagent/testing/factory.py +59 -0
  96. coderagent/testing/scripted_model.py +54 -0
  97. coderagent/tools/__init__.py +1 -0
  98. coderagent/tools/base.py +54 -0
  99. coderagent/tools/bash_policy.py +486 -0
  100. coderagent/tools/builtin/__init__.py +35 -0
  101. coderagent/tools/builtin/fs.py +283 -0
  102. coderagent/tools/builtin/patch.py +279 -0
  103. coderagent/tools/builtin/search.py +242 -0
  104. coderagent/tools/builtin/shell.py +336 -0
  105. coderagent/tools/builtin/skill.py +41 -0
  106. coderagent/tools/builtin/task.py +53 -0
  107. coderagent/tools/builtin/todo.py +63 -0
  108. coderagent/tools/executor.py +243 -0
  109. coderagent/tools/mcp.py +317 -0
  110. coderagent/tools/permissions.py +472 -0
  111. coderagent/tools/registry.py +83 -0
  112. coderagent/tools/rules.py +138 -0
  113. coderagent/ui/__init__.py +1 -0
  114. coderagent/ui/cli.py +498 -0
  115. coderagent/ui/commands/__init__.py +109 -0
  116. coderagent/ui/commands/builtin.py +778 -0
  117. coderagent/ui/commands/compact.py +12 -0
  118. coderagent/ui/commands/resume.py +26 -0
  119. coderagent/ui/commands/review.py +73 -0
  120. coderagent/ui/commands/rewind.py +28 -0
  121. coderagent/ui/custom_commands.py +179 -0
  122. coderagent/ui/notify.py +46 -0
  123. coderagent/ui/open_file.py +48 -0
  124. coderagent/ui/render.py +62 -0
  125. coderagent/ui/spinner.py +68 -0
  126. coderagent/ui/tui.py +610 -0
  127. coderagent/ui/widgets/__init__.py +29 -0
  128. coderagent/ui/widgets/approval_prompt.py +129 -0
  129. coderagent/ui/widgets/diff_view.py +97 -0
  130. coderagent/ui/widgets/file_tree.py +105 -0
  131. coderagent/ui/widgets/markdown_message.py +44 -0
  132. coderagent/ui/widgets/markup.py +10 -0
  133. coderagent/ui/widgets/message_block.py +61 -0
  134. coderagent/ui/widgets/path_suggester.py +66 -0
  135. coderagent/ui/widgets/session_picker.py +49 -0
  136. coderagent/ui/widgets/status_bar.py +44 -0
  137. coderagent/ui/widgets/todo_panel.py +40 -0
  138. coderagent/ui/widgets/tool_card.py +104 -0
  139. coderagent/ui/widgets/working_dots.py +26 -0
  140. coderagent/version.py +7 -0
  141. coderagent/web/__init__.py +5 -0
  142. coderagent/web/api.py +449 -0
  143. coderagent/web/app.py +113 -0
  144. coderagent/web/approver.py +73 -0
  145. coderagent/web/config_api.py +53 -0
  146. coderagent/web/events.py +159 -0
  147. coderagent/web/files.py +115 -0
  148. coderagent/web/i18n.py +346 -0
  149. coderagent/web/server.py +100 -0
  150. coderagent/web/sessions.py +404 -0
  151. coderagent/web/skills_api.py +376 -0
  152. coderagent/web/static/app.css +283 -0
  153. coderagent/web/static/app.js +1466 -0
  154. coderagent/web/templates/en/base.html +31 -0
  155. coderagent/web/templates/en/chat.html +60 -0
  156. coderagent/web/templates/en/macros.html +9 -0
  157. coderagent/web/templates/en/settings.html +80 -0
  158. coderagent/web/templates/en/skills.html +64 -0
  159. coderagent/web/templates/zh/base.html +31 -0
  160. coderagent/web/templates/zh/chat.html +60 -0
  161. coderagent/web/templates/zh/macros.html +9 -0
  162. coderagent/web/templates/zh/settings.html +77 -0
  163. coderagent/web/templates/zh/skills.html +61 -0
@@ -0,0 +1,283 @@
1
+ """File tools: read, write, edit and multi_edit."""
2
+
3
+ import difflib
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ from coderagent.core.tokens import trim_lines
8
+ from coderagent.tools.base import ToolContext, ToolResult, resolve_path
9
+
10
+ MAX_LINE_LENGTH = 2000
11
+ DEFAULT_READ_LIMIT = 2000
12
+
13
+
14
+ def _read_text(path: Path) -> tuple[str, str]:
15
+ """Return (content, error message)."""
16
+ try:
17
+ data = path.read_bytes()
18
+ except IsADirectoryError:
19
+ return "", f"Error: '{path.name}' is a directory. Use `ls` to list it."
20
+ if b"\x00" in data:
21
+ return "", f"Error: '{path.name}' is a binary file."
22
+ try:
23
+ return data.decode("utf-8"), ""
24
+ except UnicodeDecodeError:
25
+ return "", f"Error: '{path.name}' is a binary file."
26
+
27
+
28
+ def _write_text(path: Path, content: str) -> None:
29
+ with path.open("w", encoding="utf-8", newline="") as f:
30
+ f.write(content)
31
+
32
+
33
+ def _apply_edit(content: str, path: str, old_string: str, new_string: str, replace_all: bool) -> tuple[str, int, str]:
34
+ """Replace `old_string` with `new_string`. Returns (content, replacements, error)."""
35
+ old_variants = [old_string]
36
+ new_variants = [new_string]
37
+ if "\r\n" in content and "\r\n" not in old_string:
38
+ old_variants.append(old_string.replace("\n", "\r\n"))
39
+ new_variants.append(new_string.replace("\n", "\r\n"))
40
+ for old_variant, new_variant in zip(old_variants, new_variants):
41
+ count = content.count(old_variant)
42
+ if count == 0:
43
+ continue
44
+ if count > 1 and not replace_all:
45
+ lines = [str(i + 1) for i, line in enumerate(content.splitlines()) if old_variant in line]
46
+ return (
47
+ content,
48
+ 0,
49
+ f"Error: old_string is not unique in {path}: it appears {count} times (lines {', '.join(lines)}). "
50
+ "Include more surrounding context to make it unique, or set replace_all=true.",
51
+ )
52
+ return content.replace(old_variant, new_variant, -1 if replace_all else 1), count, ""
53
+ return (
54
+ content,
55
+ 0,
56
+ f"Error: old_string not found in {path}. Use `read` to see the exact content, then retry with more context.",
57
+ )
58
+
59
+
60
+ def unified_diff(old: str, new: str, path: str) -> str:
61
+ """The difference between two versions of a file."""
62
+ return "\n".join(
63
+ difflib.unified_diff(old.splitlines(), new.splitlines(), fromfile=f"a/{path}", tofile=f"b/{path}", lineterm="")
64
+ )
65
+
66
+
67
+ class ReadTool:
68
+ name = "read"
69
+ description = "Read a file from the filesystem. Returns the content with line numbers."
70
+ parameters = {
71
+ "type": "object",
72
+ "properties": {
73
+ "path": {"type": "string", "description": "File path, relative to the working directory."},
74
+ "offset": {"type": "integer", "description": "First line to read, 1-based. Defaults to 1."},
75
+ "limit": {"type": "integer", "description": "Maximum number of lines to read. Defaults to 2000."},
76
+ },
77
+ "required": ["path"],
78
+ }
79
+
80
+ def run(self, params: dict[str, Any], ctx: ToolContext) -> ToolResult:
81
+ path = params.get("path")
82
+ if not isinstance(path, str) or not path:
83
+ return ToolResult("Error: `path` is required and must be a string.", is_error=True)
84
+ target = resolve_path(ctx, path)
85
+ if not target.exists():
86
+ return ToolResult(
87
+ f"Error: file not found: {path}. Use `ls` to see what is in that directory.",
88
+ is_error=True,
89
+ )
90
+ content, error = _read_text(target)
91
+ if error:
92
+ return ToolResult(error, is_error=True)
93
+
94
+ lines = content.splitlines()
95
+ offset = max(1, int(params.get("offset") or 1))
96
+ limit = max(1, int(params.get("limit") or DEFAULT_READ_LIMIT))
97
+ if not lines:
98
+ return ToolResult(f"{path} is empty.")
99
+ if offset > len(lines):
100
+ """An offset past the end says nothing: the model has to know that it is over."""
101
+ return ToolResult(
102
+ f"Error: offset {offset} is past the end of {path}: the file has {len(lines)} lines.",
103
+ is_error=True,
104
+ )
105
+ selected = lines[offset - 1 : offset - 1 + limit]
106
+ truncated, info = trim_lines(selected, ctx.config.max_output_tokens)
107
+ head = info.get("head_lines", len(truncated))
108
+ if info:
109
+ tail_start = offset + info["end_line"] - 1
110
+ numbered = (
111
+ [(offset + index, line) for index, line in enumerate(truncated[:head])]
112
+ + [(0, truncated[head])]
113
+ + [(tail_start + index, line) for index, line in enumerate(truncated[head + 1 :])]
114
+ )
115
+ else:
116
+ numbered = [(offset + index, line) for index, line in enumerate(truncated)]
117
+ width = len(str(max((number for number, _ in numbered), default=0)))
118
+ rendered = []
119
+ for number, line in numbered:
120
+ if len(line) > MAX_LINE_LENGTH:
121
+ line = line[:MAX_LINE_LENGTH] + "... [line truncated]"
122
+ rendered.append(f"{number:>{width}}\t{line}" if number else line)
123
+ output = "\n".join(rendered)
124
+ last = offset + len(selected) - 1
125
+ if last < len(lines):
126
+ if info:
127
+ output += f"\n... ({len(lines)} lines in the file, use offset={last + 1} to continue)"
128
+ else:
129
+ output += f"\n... (showing lines {offset}-{last} of {len(lines)}, use offset={last + 1} to continue)"
130
+ metadata: dict[str, Any] = {"path": str(target), "lines": len(lines)}
131
+ if info:
132
+ metadata["truncated"] = {
133
+ "path": path,
134
+ "start_line": offset + info["start_line"] - 1,
135
+ "end_line": offset + info["end_line"] - 1,
136
+ "elided_lines": info["elided_lines"],
137
+ }
138
+ return ToolResult(output, metadata=metadata)
139
+
140
+
141
+ class WriteTool:
142
+ name = "write"
143
+ description = "Write a file, creating it if needed. Overwrites existing content."
144
+ parameters = {
145
+ "type": "object",
146
+ "properties": {
147
+ "path": {"type": "string", "description": "File path, relative to the working directory."},
148
+ "content": {"type": "string", "description": "The full content of the file."},
149
+ },
150
+ "required": ["path", "content"],
151
+ }
152
+
153
+ def run(self, params: dict[str, Any], ctx: ToolContext) -> ToolResult:
154
+ path = params.get("path")
155
+ content = params.get("content")
156
+ if not isinstance(path, str) or not path:
157
+ return ToolResult("Error: `path` is required and must be a string.", is_error=True)
158
+ if not isinstance(content, str):
159
+ return ToolResult("Error: `content` is required and must be a string.", is_error=True)
160
+ target = resolve_path(ctx, path)
161
+ existed = target.exists()
162
+ old_content = None
163
+ if existed:
164
+ old_content, error = _read_text(target)
165
+ if error:
166
+ return ToolResult(error, is_error=True)
167
+ target.parent.mkdir(parents=True, exist_ok=True)
168
+ _write_text(target, content)
169
+ lines = len(content.splitlines())
170
+ return ToolResult(
171
+ f"{'Updated' if existed else 'Created'} {path} ({lines} lines)",
172
+ metadata={
173
+ "path": str(target),
174
+ "diff": unified_diff(old_content or "", content, path),
175
+ "old_content": old_content,
176
+ "created": not existed,
177
+ },
178
+ )
179
+
180
+
181
+ class EditTool:
182
+ name = "edit"
183
+ description = (
184
+ "Replace an exact string in a file. `old_string` must appear exactly once unless `replace_all` is true."
185
+ )
186
+ parameters = {
187
+ "type": "object",
188
+ "properties": {
189
+ "path": {"type": "string", "description": "File path, relative to the working directory."},
190
+ "old_string": {"type": "string", "description": "The exact text to replace."},
191
+ "new_string": {"type": "string", "description": "The text to replace it with."},
192
+ "replace_all": {"type": "boolean", "description": "Replace every occurrence. Defaults to false."},
193
+ },
194
+ "required": ["path", "old_string", "new_string"],
195
+ }
196
+
197
+ def run(self, params: dict[str, Any], ctx: ToolContext) -> ToolResult:
198
+ path = params.get("path")
199
+ old_string = params.get("old_string")
200
+ new_string = params.get("new_string")
201
+ if not isinstance(path, str) or not path:
202
+ return ToolResult("Error: `path` is required and must be a string.", is_error=True)
203
+ if not isinstance(old_string, str) or not old_string:
204
+ return ToolResult("Error: `old_string` is required and must be a non-empty string.", is_error=True)
205
+ if not isinstance(new_string, str):
206
+ return ToolResult("Error: `new_string` is required and must be a string.", is_error=True)
207
+
208
+ target = resolve_path(ctx, path)
209
+ if not target.exists():
210
+ return ToolResult(f"Error: file not found: {path}.", is_error=True)
211
+ content, error = _read_text(target)
212
+ if error:
213
+ return ToolResult(error, is_error=True)
214
+
215
+ replace_all = bool(params.get("replace_all"))
216
+ new_content, replacements, error = _apply_edit(content, path, old_string, new_string, replace_all)
217
+ if error:
218
+ return ToolResult(error, is_error=True)
219
+ _write_text(target, new_content)
220
+ return ToolResult(
221
+ f"Replaced {replacements} occurrence(s) in {path}",
222
+ metadata={"path": str(target), "diff": unified_diff(content, new_content, path), "old_content": content},
223
+ )
224
+
225
+
226
+ class MultiEditTool:
227
+ name = "multi_edit"
228
+ description = "Apply several edits to one file. Either all of them are applied or none of them."
229
+ parameters = {
230
+ "type": "object",
231
+ "properties": {
232
+ "path": {"type": "string", "description": "File path, relative to the working directory."},
233
+ "edits": {
234
+ "type": "array",
235
+ "description": "Edits to apply in order.",
236
+ "items": {
237
+ "type": "object",
238
+ "properties": {
239
+ "old_string": {"type": "string"},
240
+ "new_string": {"type": "string"},
241
+ "replace_all": {"type": "boolean"},
242
+ },
243
+ "required": ["old_string", "new_string"],
244
+ },
245
+ },
246
+ },
247
+ "required": ["path", "edits"],
248
+ }
249
+
250
+ def run(self, params: dict[str, Any], ctx: ToolContext) -> ToolResult:
251
+ path = params.get("path")
252
+ edits = params.get("edits")
253
+ if not isinstance(path, str) or not path:
254
+ return ToolResult("Error: `path` is required and must be a string.", is_error=True)
255
+ if not isinstance(edits, list) or not edits:
256
+ return ToolResult("Error: `edits` is required and must be a non-empty array.", is_error=True)
257
+
258
+ target = resolve_path(ctx, path)
259
+ if not target.exists():
260
+ return ToolResult(f"Error: file not found: {path}.", is_error=True)
261
+ content, error = _read_text(target)
262
+ if error:
263
+ return ToolResult(error, is_error=True)
264
+
265
+ updated = content
266
+ for index, edit in enumerate(edits):
267
+ if not isinstance(edit, dict):
268
+ return ToolResult(f"Error: edit #{index + 1} must be an object.", is_error=True)
269
+ old_string = edit.get("old_string")
270
+ new_string = edit.get("new_string")
271
+ if not isinstance(old_string, str) or not old_string:
272
+ return ToolResult(f"Error: edit #{index + 1} needs a non-empty `old_string`.", is_error=True)
273
+ if not isinstance(new_string, str):
274
+ return ToolResult(f"Error: edit #{index + 1} needs a string `new_string`.", is_error=True)
275
+ updated, _, error = _apply_edit(updated, path, old_string, new_string, bool(edit.get("replace_all")))
276
+ if error:
277
+ return ToolResult(f"Edit #{index + 1} failed, no changes were written. {error}", is_error=True)
278
+
279
+ _write_text(target, updated)
280
+ return ToolResult(
281
+ f"Applied {len(edits)} edit(s) to {path}",
282
+ metadata={"path": str(target), "diff": unified_diff(content, updated, path), "old_content": content},
283
+ )
@@ -0,0 +1,279 @@
1
+ """The `apply_patch` tool: a patch with context, the way Codex writes one.
2
+
3
+ *** Begin Patch
4
+ *** Update File: src/app.py
5
+ @@ def main():
6
+ the line that stays
7
+ -the line that goes
8
+ +the line that comes
9
+ *** Add File: notes.md
10
+ +a new file
11
+ *** Delete File: old.md
12
+ *** End Patch
13
+
14
+ The patch costs fewer tokens than the whole file, so the model sends the lines
15
+ that change and a few lines around them.
16
+ """
17
+
18
+ from dataclasses import dataclass, field
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ from coderagent.tools.base import ToolContext, ToolResult, resolve_path
23
+ from coderagent.tools.builtin.fs import unified_diff
24
+
25
+ BEGIN = "*** Begin Patch"
26
+ END = "*** End Patch"
27
+
28
+
29
+ class PatchError(Exception):
30
+ """The patch cannot be applied."""
31
+
32
+
33
+ @dataclass
34
+ class Hunk:
35
+ header: str = ""
36
+ """The text after the `@@`, a hint about where the hunk belongs."""
37
+ lines: list[str] = field(default_factory=list)
38
+ """The lines of the hunk, with their prefix."""
39
+
40
+
41
+ @dataclass
42
+ class FilePatch:
43
+ action: str
44
+ """`update`, `add` or `delete`."""
45
+ path: str
46
+ hunks: list[Hunk] = field(default_factory=list)
47
+ lines: list[str] = field(default_factory=list)
48
+ """The lines of a file that is added."""
49
+
50
+
51
+ def parse_patch(text: str) -> list[FilePatch]:
52
+ """The files the patch changes. Raises `PatchError` when the patch is malformed."""
53
+ lines = text.splitlines()
54
+ if not lines or lines[0].strip() != BEGIN:
55
+ raise PatchError(f"the patch must start with '{BEGIN}'")
56
+ patches: list[FilePatch] = []
57
+ current: FilePatch | None = None
58
+ hunk: Hunk | None = None
59
+ ended = False
60
+ for raw in lines[1:]:
61
+ if raw.strip() == END:
62
+ ended = True
63
+ break
64
+ if raw.startswith("*** Update File: "):
65
+ current = FilePatch("update", raw[len("*** Update File: ") :].strip())
66
+ patches.append(current)
67
+ hunk = None
68
+ elif raw.startswith("*** Add File: "):
69
+ current = FilePatch("add", raw[len("*** Add File: ") :].strip())
70
+ patches.append(current)
71
+ hunk = None
72
+ elif raw.startswith("*** Delete File: "):
73
+ current = FilePatch("delete", raw[len("*** Delete File: ") :].strip())
74
+ patches.append(current)
75
+ hunk = None
76
+ elif raw.startswith("@@"):
77
+ if current is None or current.action != "update":
78
+ raise PatchError("a hunk must belong to a file to update")
79
+ hunk = Hunk(header=raw[2:].strip())
80
+ current.hunks.append(hunk)
81
+ elif raw.startswith(("+", "-", " ")):
82
+ if current is None:
83
+ raise PatchError("the patch has lines before it says which file it changes")
84
+ if current.action == "add":
85
+ current.lines.append(raw[1:])
86
+ elif current.action == "update":
87
+ if hunk is None:
88
+ raise PatchError(
89
+ "the lines of a file to update belong to a hunk, so they need a line that starts with @@"
90
+ )
91
+ hunk.lines.append(raw)
92
+ else:
93
+ raise PatchError("a file to delete has no lines")
94
+ elif raw.strip() == "":
95
+ """An empty line is a line of context that has nothing in it."""
96
+ if current is None or current.action != "update" or hunk is None:
97
+ raise PatchError("the patch has an empty line that belongs to nothing")
98
+ hunk.lines.append(" ")
99
+ else:
100
+ raise PatchError(f"unexpected line in the patch: {raw!r}")
101
+ if not ended:
102
+ raise PatchError(f"the patch must end with '{END}'")
103
+ if not patches:
104
+ raise PatchError("the patch does not change any file")
105
+ return patches
106
+
107
+
108
+ def _hunk_parts(hunk: Hunk) -> tuple[list[str], list[str]]:
109
+ """The lines the hunk expects and the lines it puts there."""
110
+ old: list[str] = []
111
+ new: list[str] = []
112
+ for raw in hunk.lines:
113
+ if raw.startswith("-"):
114
+ old.append(raw[1:])
115
+ elif raw.startswith("+"):
116
+ new.append(raw[1:])
117
+ else:
118
+ text = raw[1:] if raw.startswith(" ") else raw
119
+ old.append(text)
120
+ new.append(text)
121
+ return old, new
122
+
123
+
124
+ def _locate(lines: list[str], old: list[str], cursor: int, header: str) -> int | None:
125
+ """Where the block of the hunk is in the file. None when it is not there."""
126
+ if not old:
127
+ return None
128
+ candidates: list[int] = []
129
+ if header:
130
+ for index, line in enumerate(lines):
131
+ if header in line:
132
+ candidates.append(index)
133
+ break
134
+ candidates += [cursor, 0]
135
+ candidates += list(range(len(lines)))
136
+ for start in candidates:
137
+ if start < 0 or start + len(old) > len(lines):
138
+ continue
139
+ if lines[start : start + len(old)] == old:
140
+ return start
141
+ """The file may have spaces at the end of its lines that the patch does not show."""
142
+ stripped = [line.rstrip() for line in old]
143
+ for start in candidates:
144
+ if start < 0 or start + len(old) > len(lines):
145
+ continue
146
+ if [line.rstrip() for line in lines[start : start + len(old)]] == stripped:
147
+ return start
148
+ return None
149
+
150
+
151
+ def apply_to_text(original: str, patch: FilePatch) -> str:
152
+ """The content of the file after the patch. Raises `PatchError` when it does not fit."""
153
+ if patch.action == "add":
154
+ return "\n".join(patch.lines) + "\n" if patch.lines else ""
155
+ lines = original.splitlines()
156
+ result = list(lines)
157
+ cursor = 0
158
+ for hunk in patch.hunks:
159
+ old, new = _hunk_parts(hunk)
160
+ index = _locate(result, old, cursor, hunk.header)
161
+ if index is None:
162
+ first = old[0].strip()[:60] if old else ""
163
+ raise PatchError(
164
+ f"the context of the hunk does not match {patch.path}: '{first}' is not where the patch says it is. "
165
+ "Read the file again and use the lines that are really there."
166
+ )
167
+ result[index : index + len(old)] = new
168
+ cursor = index + len(new)
169
+ text = "\n".join(result)
170
+ if original.endswith("\n") or not original:
171
+ text += "\n"
172
+ return text
173
+
174
+
175
+ def touched_paths(patch_text: str) -> list[str]:
176
+ """The files the patch touches. Empty when the patch cannot be read."""
177
+ try:
178
+ return [patch.path for patch in parse_patch(patch_text)]
179
+ except PatchError:
180
+ return []
181
+
182
+
183
+ def preview(patch_text: str, cwd: Path) -> str:
184
+ """The diff the patch would make, without changing anything."""
185
+ try:
186
+ patches = parse_patch(patch_text)
187
+ except PatchError:
188
+ return ""
189
+ diffs = []
190
+ for patch in patches:
191
+ target = Path(patch.path)
192
+ if not target.is_absolute():
193
+ target = cwd / target
194
+ before = target.read_text(encoding="utf-8") if target.is_file() else ""
195
+ try:
196
+ after = apply_to_text(before, patch)
197
+ except PatchError:
198
+ continue
199
+ if before != after:
200
+ diffs.append(unified_diff(before, after, patch.path))
201
+ return "\n".join(diffs)
202
+
203
+
204
+ class ApplyPatchTool:
205
+ name = "apply_patch"
206
+ description = (
207
+ "Apply a patch to the files of the working directory. The patch looks like this: "
208
+ "'*** Begin Patch', then '*** Update File: path' with hunks that start with '@@', the lines that stay "
209
+ "(with a space), the lines that go (with a -) and the lines that come (with a +), then "
210
+ "'*** Add File: path' with the lines of the new file and '*** Delete File: path'. "
211
+ "It ends with '*** End Patch'. A patch costs fewer tokens than the whole file."
212
+ )
213
+ parameters = {
214
+ "type": "object",
215
+ "properties": {
216
+ "patch": {"type": "string", "description": "The patch to apply."},
217
+ },
218
+ "required": ["patch"],
219
+ }
220
+
221
+ def run(self, params: dict[str, Any], ctx: ToolContext) -> ToolResult:
222
+ patch_text = params.get("patch")
223
+ if not isinstance(patch_text, str) or not patch_text.strip():
224
+ return ToolResult("Error: `patch` is required and must be a non-empty string.", is_error=True)
225
+ try:
226
+ patches = parse_patch(patch_text)
227
+ except PatchError as error:
228
+ return ToolResult(f"Error: {error}", is_error=True)
229
+
230
+ changes: list[tuple[Path, str, str]] = []
231
+ """The file, what it was and what it becomes."""
232
+ for patch in patches:
233
+ target = resolve_path(ctx, patch.path)
234
+ if not ctx.policy.within_bounds(str(target)):
235
+ return ToolResult(
236
+ f"Error: '{patch.path}' is outside the working directory {ctx.policy.cwd}.",
237
+ is_error=True,
238
+ )
239
+ if patch.action == "delete":
240
+ if not target.exists():
241
+ return ToolResult(f"Error: file not found: {patch.path}.", is_error=True)
242
+ changes.append((target, target.read_text(encoding="utf-8"), ""))
243
+ continue
244
+ if patch.action == "add" and target.exists():
245
+ return ToolResult(f"Error: the file {patch.path} exists already.", is_error=True)
246
+ if patch.action == "update" and not target.exists():
247
+ return ToolResult(f"Error: file not found: {patch.path}.", is_error=True)
248
+ before = target.read_text(encoding="utf-8") if target.exists() else ""
249
+ try:
250
+ after = apply_to_text(before, patch)
251
+ except PatchError as error:
252
+ return ToolResult(f"Error: {error}", is_error=True)
253
+ changes.append((target, before, after))
254
+
255
+ for target, _, after in changes:
256
+ if after == "" and target.exists():
257
+ target.unlink()
258
+ continue
259
+ target.parent.mkdir(parents=True, exist_ok=True)
260
+ target.write_text(after, encoding="utf-8", newline="")
261
+
262
+ names = [
263
+ str(target.relative_to(ctx.cwd)) if target.is_relative_to(ctx.cwd) else str(target)
264
+ for target, _, _ in changes
265
+ ]
266
+ diffs = [
267
+ unified_diff(before, after, name)
268
+ for (target, before, after), name in zip(changes, names)
269
+ if before != after
270
+ ]
271
+ return ToolResult(
272
+ f"Applied the patch to {len(changes)} file(s): {', '.join(names)}",
273
+ metadata={"diff": "\n".join(diffs), "paths": [str(target) for target, _, _ in changes]},
274
+ )
275
+
276
+ def touched_paths(self, params: dict[str, Any]) -> list[str]:
277
+ """The files the patch touches, so that they get a checkpoint."""
278
+ patch_text = params.get("patch")
279
+ return touched_paths(patch_text) if isinstance(patch_text, str) else []