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,242 @@
1
+ """Search tools: glob, grep and ls.
2
+
3
+ Implemented in pure Python on purpose: `rg`/`grep` are not guaranteed to exist in
4
+ non-interactive shells, and the agent must behave the same everywhere.
5
+ """
6
+
7
+ import os
8
+ import re
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from coderagent.tools.base import ToolContext, ToolResult, resolve_path
13
+ from coderagent.tools.permissions import glob_to_regex
14
+
15
+ IGNORED_DIRS = {".git", "node_modules", "__pycache__", ".venv", ".mypy_cache", ".pytest_cache", ".ruff_cache"}
16
+ GLOB_LIMIT = 200
17
+ GREP_LIMIT = 100
18
+ CANCEL_EVERY = 64
19
+ """How many files a search reads before it asks whether the turn is still going on."""
20
+
21
+
22
+ def _interrupted(ctx: ToolContext) -> bool:
23
+ """Whether the turn was stopped while the search was running."""
24
+ return ctx.cancel is not None and ctx.cancel()
25
+
26
+
27
+ def _iter_files(root: Path):
28
+ """Yield every file below `root`, skipping ignored directories."""
29
+ for dirpath, dirnames, filenames in os.walk(root):
30
+ dirnames[:] = sorted(d for d in dirnames if d not in IGNORED_DIRS)
31
+ for name in sorted(filenames):
32
+ yield Path(dirpath) / name
33
+
34
+
35
+ def _is_ignored(path: Path, root: Path) -> bool:
36
+ return any(part in IGNORED_DIRS for part in path.relative_to(root).parts[:-1])
37
+
38
+
39
+ class GlobTool:
40
+ name = "glob"
41
+ description = (
42
+ "Find files by pattern. `*` matches within one path segment, `**` crosses directories. "
43
+ "Returns up to 200 paths, sorted."
44
+ )
45
+ parameters = {
46
+ "type": "object",
47
+ "properties": {
48
+ "pattern": {"type": "string", "description": "Glob pattern, e.g. `**/*.py`."},
49
+ "path": {"type": "string", "description": "Directory to search in. Defaults to the working directory."},
50
+ },
51
+ "required": ["pattern"],
52
+ }
53
+
54
+ def run(self, params: dict[str, Any], ctx: ToolContext) -> ToolResult:
55
+ pattern = params.get("pattern")
56
+ if not isinstance(pattern, str) or not pattern:
57
+ return ToolResult("Error: `pattern` is required and must be a non-empty string.", is_error=True)
58
+ root = resolve_path(ctx, params.get("path") or ".")
59
+ if not root.is_dir():
60
+ return ToolResult(f"Error: not a directory: {params.get('path') or '.'}", is_error=True)
61
+
62
+ matcher = glob_to_regex(pattern)
63
+ matches = []
64
+ for index, path in enumerate(_iter_files(root)):
65
+ if index % CANCEL_EVERY == 0 and _interrupted(ctx):
66
+ """A search of a big tree takes a while: the turn may be stopped in the middle."""
67
+ return ToolResult(
68
+ "Error: the turn was interrupted, so the search did not finish.",
69
+ is_error=True,
70
+ )
71
+ relative = path.relative_to(root).as_posix()
72
+ if matcher.match(relative):
73
+ matches.append(relative)
74
+ matches.sort()
75
+
76
+ if not matches:
77
+ return ToolResult(f"No files matched '{pattern}' under {root}.")
78
+ truncated = matches[GLOB_LIMIT:]
79
+ matches = matches[:GLOB_LIMIT]
80
+ output = "\n".join(matches)
81
+ if truncated:
82
+ output += f"\n... ({len(truncated)} more matches not shown, narrow the pattern)"
83
+ return ToolResult(output, metadata={"count": len(matches)})
84
+
85
+
86
+ class GrepTool:
87
+ name = "grep"
88
+ description = (
89
+ "Search file contents with a regular expression. "
90
+ "Use `output_mode` to get matching lines, the matching file names, or a per-file count."
91
+ )
92
+ parameters = {
93
+ "type": "object",
94
+ "properties": {
95
+ "pattern": {"type": "string", "description": "Regular expression to search for."},
96
+ "path": {
97
+ "type": "string",
98
+ "description": "File or directory to search. Defaults to the working directory.",
99
+ },
100
+ "glob": {"type": "string", "description": "Only search files matching this glob, e.g. `**/*.py`."},
101
+ "output_mode": {
102
+ "type": "string",
103
+ "enum": ["content", "files_with_matches", "count"],
104
+ "description": "What to return. Defaults to `content`.",
105
+ },
106
+ "-i": {"type": "boolean", "description": "Case-insensitive search."},
107
+ },
108
+ "required": ["pattern"],
109
+ }
110
+
111
+ def run(self, params: dict[str, Any], ctx: ToolContext) -> ToolResult:
112
+ pattern = params.get("pattern")
113
+ if not isinstance(pattern, str) or not pattern:
114
+ return ToolResult("Error: `pattern` is required and must be a non-empty string.", is_error=True)
115
+ mode = params.get("output_mode", "content")
116
+ if mode not in ("content", "files_with_matches", "count"):
117
+ return ToolResult(
118
+ f"Error: `output_mode` must be one of content, files_with_matches, count (got '{mode}').",
119
+ is_error=True,
120
+ )
121
+ try:
122
+ regex = re.compile(pattern, re.IGNORECASE if params.get("-i") else 0)
123
+ except re.error as error:
124
+ return ToolResult(f"Error: invalid regular expression '{pattern}': {error}", is_error=True)
125
+
126
+ root = resolve_path(ctx, params.get("path") or ".")
127
+ if not root.exists():
128
+ return ToolResult(f"Error: path not found: {params.get('path') or '.'}", is_error=True)
129
+
130
+ glob_pattern = params.get("glob")
131
+ matcher = glob_to_regex(glob_pattern) if isinstance(glob_pattern, str) and glob_pattern else None
132
+ candidates = [root] if root.is_file() else _iter_files(root)
133
+
134
+ lines: list[str] = []
135
+ files: list[str] = []
136
+ counts: list[str] = []
137
+ total = 0
138
+ for index, path in enumerate(candidates):
139
+ if index % CANCEL_EVERY == 0 and _interrupted(ctx):
140
+ """A search of a big tree takes a while: the turn may be stopped in the middle."""
141
+ return ToolResult(
142
+ "Error: the turn was interrupted, so the search did not finish.",
143
+ is_error=True,
144
+ )
145
+ if root.is_dir() and _is_ignored(path, root):
146
+ continue
147
+ if path.is_symlink() and not ctx.policy.within_bounds(str(path)):
148
+ """A symlink may lead out of the working directory: the file is not read."""
149
+ continue
150
+ if matcher and not matcher.match(path.name if root.is_file() else path.relative_to(root).as_posix()):
151
+ continue
152
+ try:
153
+ data = path.read_bytes()
154
+ except OSError:
155
+ continue
156
+ if b"\x00" in data:
157
+ continue
158
+ try:
159
+ text = data.decode("utf-8")
160
+ except UnicodeDecodeError:
161
+ continue
162
+ hits = [line for line in text.splitlines() if regex.search(line)]
163
+ if not hits:
164
+ continue
165
+ relative = path.name if root.is_file() else path.relative_to(root).as_posix()
166
+ files.append(relative)
167
+ counts.append(f"{relative}:{len(hits)}")
168
+ for number, line in enumerate(text.splitlines(), start=1):
169
+ if regex.search(line):
170
+ total += 1
171
+ if mode == "content" and len(lines) < GREP_LIMIT:
172
+ lines.append(f"{relative}:{number}:{line}")
173
+
174
+ if mode == "files_with_matches":
175
+ output = "\n".join(files)
176
+ elif mode == "count":
177
+ output = "\n".join(counts)
178
+ else:
179
+ output = "\n".join(lines)
180
+ if not output:
181
+ return ToolResult(f"No matches for '{pattern}'.")
182
+ if mode == "content" and total > len(lines):
183
+ output += f"\n... ({total - len(lines)} more matches not shown, use a more specific pattern)"
184
+ return ToolResult(output, metadata={"matches": total, "files": files})
185
+
186
+
187
+ def list_entries(target: Path, depth: int = 1) -> list[tuple[Path, str]]:
188
+ """The entries below a directory: the absolute path and `d` or `f`."""
189
+ entries = []
190
+ for dirpath, dirnames, filenames in os.walk(target):
191
+ level = len(Path(dirpath).relative_to(target).parts)
192
+ if depth >= 0 and level >= depth:
193
+ dirnames[:] = []
194
+ filenames = []
195
+ dirnames[:] = sorted(d for d in dirnames if d not in IGNORED_DIRS)
196
+ for name in sorted(dirnames):
197
+ entries.append((Path(dirpath) / name, "d"))
198
+ for name in sorted(filenames):
199
+ entries.append((Path(dirpath) / name, "f"))
200
+ entries.sort()
201
+ return entries
202
+
203
+
204
+ class LsTool:
205
+ name = "ls"
206
+ description = (
207
+ "List directory entries. Directories end with '/', files show their size. "
208
+ "`depth` of -1 lists the whole tree recursively."
209
+ )
210
+ parameters = {
211
+ "type": "object",
212
+ "properties": {
213
+ "path": {"type": "string", "description": "Directory to list. Defaults to the working directory."},
214
+ "depth": {
215
+ "type": "integer",
216
+ "description": "Recursion depth. 1 (default) lists one level, -1 is unlimited.",
217
+ },
218
+ },
219
+ "required": [],
220
+ }
221
+
222
+ def run(self, params: dict[str, Any], ctx: ToolContext) -> ToolResult:
223
+ target = resolve_path(ctx, params.get("path") or ".")
224
+ if not target.exists():
225
+ return ToolResult(f"Error: path not found: {params.get('path') or '.'}", is_error=True)
226
+ if not target.is_dir():
227
+ return ToolResult(f"Error: not a directory: {params.get('path') or '.'}", is_error=True)
228
+
229
+ depth = params.get("depth", 1)
230
+ depth = int(depth) if isinstance(depth, int) else 1
231
+ entries = list_entries(target, depth)
232
+ if not entries:
233
+ return ToolResult(f"Directory {target} is empty.")
234
+ lines = []
235
+ for path, kind in entries:
236
+ relative = path.relative_to(target).as_posix()
237
+ if kind == "d":
238
+ lines.append(f"{relative}/")
239
+ else:
240
+ """The size of the link itself, like `ls -l` shows it."""
241
+ lines.append(f"{relative} ({path.lstat().st_size} B)")
242
+ return ToolResult("\n".join(lines), metadata={"count": len(entries)})
@@ -0,0 +1,336 @@
1
+ """Shell tool: `bash` plus the background task helpers `bash_output` and `bash_kill`."""
2
+
3
+ import atexit
4
+ import os
5
+ import shutil
6
+ import signal
7
+ import subprocess
8
+ import tempfile
9
+ import threading
10
+ import time
11
+ import uuid
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from coderagent.core.tokens import trim_text
16
+ from coderagent.environments import LocalEnvironment, is_local
17
+ from coderagent.tools.base import ToolContext, ToolResult
18
+
19
+ CHARS_PER_TOKEN = 3.5
20
+ POLL_SECONDS = 0.05
21
+ """How often a running command is asked whether the turn is still going on."""
22
+
23
+ _TASKS: list[dict] = []
24
+ """The background tasks of this process. None of them outlives it."""
25
+
26
+
27
+ class CodingEnvironment(LocalEnvironment):
28
+ """The local environment of the coding agent.
29
+
30
+ A coding agent ends a turn when the model says so, not when a shell command prints a
31
+ sentinel string.
32
+ """
33
+
34
+ def _check_finished(self, output: dict) -> None:
35
+ return None
36
+
37
+ def execute_cancellable(self, action: dict, cwd: str = "", *, timeout: int = 30, cancel=None) -> dict:
38
+ """Run a command that can be stopped while it runs.
39
+
40
+ The turn can be interrupted while a command is running. The command is then
41
+ killed, together with the children it started, and the output it produced so
42
+ far is returned. A command in a remote sandbox cannot be killed, which is why
43
+ this is here and not in the remote environments.
44
+ """
45
+ command = action.get("command", "")
46
+ cwd = cwd or self.config.cwd or os.getcwd()
47
+ process = subprocess.Popen( # noqa: S602
48
+ command,
49
+ shell=True,
50
+ text=True,
51
+ cwd=cwd,
52
+ env=self.environment(),
53
+ encoding="utf-8",
54
+ errors="replace",
55
+ stdout=subprocess.PIPE,
56
+ stderr=subprocess.STDOUT,
57
+ start_new_session=os.name == "posix",
58
+ )
59
+ text, interrupted, timed_out = self._drain(process, timeout, cancel)
60
+ if interrupted:
61
+ return {"output": text, "returncode": -1, "interrupted": True, "exception_info": ""}
62
+ if timed_out:
63
+ return {
64
+ "output": text,
65
+ "returncode": -1,
66
+ "exception_info": f"An error occurred while executing the command: Command '{command}' timed out after {timeout} seconds",
67
+ }
68
+ return {"output": text, "returncode": process.returncode, "exception_info": ""}
69
+
70
+ def _drain(self, process, timeout: int, cancel) -> tuple[str, bool, bool]:
71
+ """Read the output of a command until it ends, is interrupted or times out."""
72
+ collected: list[str] = []
73
+ reader = threading.Thread(target=lambda: collected.append(process.stdout.read() or ""), daemon=True)
74
+ reader.start()
75
+ deadline = time.time() + timeout
76
+ interrupted = False
77
+ timed_out = False
78
+ while process.poll() is None:
79
+ if cancel is not None and cancel():
80
+ interrupted = True
81
+ _kill(process)
82
+ break
83
+ if time.time() >= deadline:
84
+ timed_out = True
85
+ _kill(process)
86
+ break
87
+ time.sleep(POLL_SECONDS)
88
+ reader.join(timeout=2)
89
+ return "".join(collected), interrupted, timed_out
90
+
91
+
92
+ def _kill(process) -> None:
93
+ """Stop a command and the children it started."""
94
+ try:
95
+ if os.name == "posix":
96
+ os.killpg(os.getpgid(process.pid), signal.SIGTERM)
97
+ else:
98
+ process.terminate()
99
+ except ProcessLookupError:
100
+ """The command ended by itself between the check and the kill."""
101
+ return
102
+ try:
103
+ process.wait(timeout=5)
104
+ except subprocess.TimeoutExpired:
105
+ if os.name == "posix":
106
+ os.killpg(os.getpgid(process.pid), signal.SIGKILL)
107
+ else:
108
+ process.kill()
109
+
110
+
111
+ def reap_background(tasks: list[dict]) -> None:
112
+ """Stop the background tasks and take their logs away.
113
+
114
+ A task that still runs is killed, together with the children it started,
115
+ and the directory of its log goes away with it. A background task belongs
116
+ to the session that started it: it does not outlive the process.
117
+ """
118
+ for task in tasks:
119
+ if task["process"].poll() is None:
120
+ _kill(task["process"])
121
+ try:
122
+ task["handle"].close()
123
+ except (OSError, ValueError):
124
+ """The handle is already closed."""
125
+ pass
126
+ shutil.rmtree(task["log"].parent, ignore_errors=True)
127
+ tasks.clear()
128
+
129
+
130
+ @atexit.register
131
+ def _reap_at_exit() -> None:
132
+ """Nothing of a session stays behind when the process ends."""
133
+ reap_background(_TASKS)
134
+
135
+
136
+ def trim_output(text: str, max_output_tokens: int) -> str:
137
+ """Keep the head and the tail of long output, elide the middle."""
138
+ return trim_text(text, max_output_tokens)[0]
139
+
140
+
141
+ def read_head_and_tail(path: Path, limit: int) -> str:
142
+ """The head and the tail of a file, without reading all of it.
143
+
144
+ A background task may print a lot. Its log is not read into memory just to
145
+ show the ends of it.
146
+ """
147
+ try:
148
+ size = path.stat().st_size
149
+ except OSError:
150
+ return ""
151
+ if size <= limit:
152
+ return path.read_text(encoding="utf-8", errors="replace")
153
+ half = limit // 2
154
+ with path.open("rb") as handle:
155
+ head = handle.read(half)
156
+ handle.seek(-half, os.SEEK_END)
157
+ tail = handle.read()
158
+ return (
159
+ f"{head.decode('utf-8', 'replace')}\n"
160
+ f"... [the middle of the log is not shown] ...\n"
161
+ f"{tail.decode('utf-8', 'replace')}"
162
+ )
163
+
164
+
165
+ def _confined(command: str, ctx: ToolContext) -> str:
166
+ """The command with the sandbox of the operating system in front of it.
167
+
168
+ The permission layer has already had its say on the command itself, so the
169
+ sandbox only gets to hold the line where the disk and the network are.
170
+ """
171
+ if ctx.sandbox is None:
172
+ return command
173
+ return ctx.sandbox.wrap(command)
174
+
175
+
176
+ class BashTool:
177
+ name = "bash"
178
+ description = (
179
+ "Run a shell command in the working directory. Use it for pipelines, builds and tests; "
180
+ "use the dedicated file tools for reading and editing files. The commands that only look "
181
+ "around go through; the ones that destroy something or send it out ask for approval, and "
182
+ "a path outside the working directory is refused."
183
+ )
184
+ parameters = {
185
+ "type": "object",
186
+ "properties": {
187
+ "command": {"type": "string", "description": "The command to run."},
188
+ "timeout": {"type": "integer", "description": "Timeout in seconds. Defaults to the configured timeout."},
189
+ "run_in_background": {
190
+ "type": "boolean",
191
+ "description": "Start the command and return a task id at once. Only a local environment can do this.",
192
+ },
193
+ },
194
+ "required": ["command"],
195
+ }
196
+
197
+ def run(self, params: dict[str, Any], ctx: ToolContext) -> ToolResult:
198
+ command = params.get("command")
199
+ if not isinstance(command, str) or not command.strip():
200
+ return ToolResult("Error: `command` is required and must be a non-empty string.", is_error=True)
201
+ timeout = params.get("timeout")
202
+ timeout = int(timeout) if isinstance(timeout, int) and timeout > 0 else ctx.config.bash_timeout
203
+ if params.get("run_in_background"):
204
+ return self._start_background(command, ctx)
205
+
206
+ env = ctx.env if hasattr(ctx.env, "execute") else CodingEnvironment(cwd=str(ctx.cwd))
207
+ """A remote sandbox has its own working directory, the path of the host means nothing there."""
208
+ cwd = str(ctx.cwd) if is_local(env) else ""
209
+ result = self._execute(env, _confined(command, ctx), cwd, timeout, ctx)
210
+ output = str(result.get("output", ""))
211
+ content = trim_output(output, ctx.config.max_output_tokens)
212
+ returncode = result.get("returncode", 0)
213
+ interrupted = bool(result.get("interrupted"))
214
+ if interrupted:
215
+ content = f"{content}\n[interrupted]".strip()
216
+ elif result.get("exception_info"):
217
+ content = f"{content}\n{result['exception_info']}".strip()
218
+ elif returncode != 0:
219
+ content = f"{content}\n[exit code {returncode}]".strip()
220
+ return ToolResult(
221
+ content,
222
+ is_error=returncode != 0 and not interrupted,
223
+ metadata={"returncode": returncode, "interrupted": interrupted},
224
+ )
225
+
226
+ def _execute(self, env, command: str, cwd: str, timeout: int, ctx: ToolContext) -> dict:
227
+ """Run the command, and stop it when the turn is interrupted.
228
+
229
+ A command that runs on this machine can be killed. A command in a remote
230
+ sandbox cannot, so there the turn stops after the command is done.
231
+ """
232
+ if ctx.cancel is not None and isinstance(env, CodingEnvironment):
233
+ return env.execute_cancellable({"command": command}, cwd=cwd, timeout=timeout, cancel=ctx.cancel)
234
+ return env.execute({"command": command}, cwd=cwd, timeout=timeout)
235
+
236
+ def _start_background(self, command: str, ctx: ToolContext) -> ToolResult:
237
+ """Start a command that goes on while the agent does something else.
238
+
239
+ The command runs in the environment of the session. A container cannot
240
+ start a command in the background, so it is refused there: the command
241
+ would run on the machine of the user, outside of the boundary of the
242
+ session.
243
+ """
244
+ env = ctx.env if hasattr(ctx.env, "execute") else CodingEnvironment(cwd=str(ctx.cwd))
245
+ if not is_local(env):
246
+ return ToolResult(
247
+ "Error: a background task cannot run in this environment: it would run outside of it. "
248
+ "Run the command in the foreground instead.",
249
+ is_error=True,
250
+ )
251
+ task_id = uuid.uuid4().hex[:8]
252
+ directory = Path(tempfile.mkdtemp(prefix="coderagent-bg-"))
253
+ log_path = directory / "output.log"
254
+ handle = log_path.open("w", encoding="utf-8")
255
+ process = subprocess.Popen( # noqa: S602
256
+ _confined(command, ctx),
257
+ shell=True,
258
+ text=True,
259
+ cwd=str(ctx.cwd),
260
+ env=env.environment(),
261
+ encoding="utf-8",
262
+ errors="replace",
263
+ stdout=handle,
264
+ stderr=subprocess.STDOUT,
265
+ start_new_session=os.name == "posix",
266
+ )
267
+ task = {"process": process, "handle": handle, "log": log_path, "command": command}
268
+ ctx.background[task_id] = task
269
+ _TASKS.append(task)
270
+ return ToolResult(
271
+ f"Started background task {task_id}: {command}\nUse `bash_output` with task_id={task_id} to check it.",
272
+ metadata={"task_id": task_id},
273
+ )
274
+
275
+
276
+ class BashOutputTool:
277
+ name = "bash_output"
278
+ description = "Show the output collected so far by a background bash task."
279
+ parameters = {
280
+ "type": "object",
281
+ "properties": {
282
+ "task_id": {"type": "string", "description": "The id returned when the task was started."},
283
+ },
284
+ "required": ["task_id"],
285
+ }
286
+
287
+ def run(self, params: dict[str, Any], ctx: ToolContext) -> ToolResult:
288
+ task = ctx.background.get(str(params.get("task_id", "")))
289
+ if task is None:
290
+ return ToolResult(f"Error: unknown task id '{params.get('task_id')}'.", is_error=True)
291
+ process = task["process"]
292
+ limit = int(ctx.config.max_output_tokens * CHARS_PER_TOKEN)
293
+ output = read_head_and_tail(task["log"], limit)
294
+ status = "running" if process.poll() is None else f"exited with code {process.returncode}"
295
+ content = trim_output(output, ctx.config.max_output_tokens)
296
+ return ToolResult(f"{content}\n[status: {status}]", metadata={"status": status})
297
+
298
+
299
+ class BashKillTool:
300
+ name = "bash_kill"
301
+ description = "Kill a running background bash task."
302
+ parameters = {
303
+ "type": "object",
304
+ "properties": {
305
+ "task_id": {"type": "string", "description": "The id returned when the task was started."},
306
+ },
307
+ "required": ["task_id"],
308
+ }
309
+
310
+ def run(self, params: dict[str, Any], ctx: ToolContext) -> ToolResult:
311
+ task_id = str(params.get("task_id", ""))
312
+ task = ctx.background.get(task_id)
313
+ if task is None:
314
+ return ToolResult(f"Error: unknown task id '{task_id}'.", is_error=True)
315
+ process = task["process"]
316
+ if process.poll() is None:
317
+ if os.name == "posix":
318
+ os.killpg(os.getpgid(process.pid), signal.SIGTERM)
319
+ else:
320
+ process.terminate()
321
+ try:
322
+ process.wait(timeout=5)
323
+ except subprocess.TimeoutExpired:
324
+ if os.name == "posix":
325
+ os.killpg(os.getpgid(process.pid), signal.SIGKILL)
326
+ else:
327
+ process.kill()
328
+ task["handle"].close()
329
+ return ToolResult(f"Killed background task {task_id}.")
330
+
331
+
332
+ def wait_for_background(task: dict, timeout: float = 5.0) -> None:
333
+ """Wait a bit for a background task to finish. Used by tests."""
334
+ deadline = time.time() + timeout
335
+ while time.time() < deadline and task["process"].poll() is None:
336
+ time.sleep(0.05)
@@ -0,0 +1,41 @@
1
+ """The `skill` tool: the instructions of a skill, when the model needs them."""
2
+
3
+ from typing import Any
4
+
5
+ from coderagent.skills import Skill
6
+ from coderagent.tools.base import ToolContext, ToolResult
7
+
8
+
9
+ class SkillTool:
10
+ """Load a skill: its instructions, and where its files are."""
11
+
12
+ name = "skill"
13
+ description = (
14
+ "Load the instructions of a skill. A skill is a package of steps, scripts and templates "
15
+ "for a kind of task. Call this when the description of a skill fits what the user asked for, "
16
+ "then follow the instructions it gives."
17
+ )
18
+ parameters = {
19
+ "type": "object",
20
+ "properties": {
21
+ "name": {"type": "string", "description": "The name of the skill."},
22
+ },
23
+ "required": ["name"],
24
+ }
25
+
26
+ def __init__(self, skills: dict[str, Skill] | None = None) -> None:
27
+ self.skills = skills or {}
28
+
29
+ def run(self, params: dict[str, Any], ctx: ToolContext) -> ToolResult:
30
+ name = str(params.get("name", ""))
31
+ skill = self.skills.get(name)
32
+ if skill is None:
33
+ return ToolResult(
34
+ f"Error: unknown skill '{name}'. Available skills: {', '.join(sorted(self.skills)) or 'none'}.",
35
+ is_error=True,
36
+ )
37
+ where = f"\n\nThe files of the skill are in {skill.directory}." if skill.directory else ""
38
+ return ToolResult(skill.render() + where)
39
+
40
+
41
+ __all__ = ["SkillTool"]
@@ -0,0 +1,53 @@
1
+ """The `task` tool: hand a self contained job to a sub agent."""
2
+
3
+ from typing import Any
4
+
5
+ from coderagent.core.subagent import SubagentSpec, render_result
6
+ from coderagent.tools.base import ToolContext, ToolResult
7
+
8
+
9
+ class TaskTool:
10
+ """Delegate a task to a sub agent that works in its own context."""
11
+
12
+ name = "task"
13
+ description = (
14
+ "Delegate a self contained job to a sub agent. The sub agent works in its own context, "
15
+ "so its intermediate output does not fill up yours. Give it everything it needs: it "
16
+ "cannot see this conversation. Good for: searching the whole code base, doing a broad "
17
+ "refactor, checking a result independently."
18
+ )
19
+ parameters = {
20
+ "type": "object",
21
+ "properties": {
22
+ "subagent_type": {"type": "string", "description": "The name of the sub agent."},
23
+ "description": {"type": "string", "description": "What the job is, in one sentence."},
24
+ "prompt": {"type": "string", "description": "The full instructions for the sub agent."},
25
+ },
26
+ "required": ["subagent_type", "description", "prompt"],
27
+ }
28
+
29
+ def __init__(self, runner=None, specs: dict[str, SubagentSpec] | None = None) -> None:
30
+ self.runner = runner
31
+ """The thing that runs the sub agent. Set by the assembly of the agent."""
32
+ self.specs = specs or {}
33
+ """The sub agents that are available, by name."""
34
+
35
+ def run(self, params: dict[str, Any], ctx: ToolContext) -> ToolResult:
36
+ name = str(params.get("subagent_type", ""))
37
+ spec = self.specs.get(name)
38
+ if spec is None:
39
+ return ToolResult(
40
+ f"Error: unknown sub agent '{name}'. Available sub agents: {', '.join(sorted(self.specs)) or 'none'}.",
41
+ is_error=True,
42
+ )
43
+ if self.runner is None:
44
+ return ToolResult("Error: the sub agents are not available in this session.", is_error=True)
45
+ description = str(params.get("description", ""))
46
+ prompt = str(params.get("prompt", ""))
47
+ result = self.runner.run(spec, description, prompt)
48
+ return ToolResult(
49
+ render_result({**result, "purpose": spec.model_purpose}), is_error=result["status"] == "error"
50
+ )
51
+
52
+
53
+ __all__ = ["TaskTool"]