1package tools
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "strings"
8 "time"
9
10 "github.com/opencode-ai/opencode/internal/config"
11 "github.com/opencode-ai/opencode/internal/llm/tools/shell"
12 "github.com/opencode-ai/opencode/internal/permission"
13)
14
15type BashParams struct {
16 Command string `json:"command"`
17 Timeout int `json:"timeout"`
18}
19
20type BashPermissionsParams struct {
21 Command string `json:"command"`
22 Timeout int `json:"timeout"`
23}
24
25type BashResponseMetadata struct {
26 StartTime int64 `json:"start_time"`
27 EndTime int64 `json:"end_time"`
28}
29type bashTool struct {
30 permissions permission.Service
31}
32
33const (
34 BashToolName = "bash"
35
36 DefaultTimeout = 1 * 60 * 1000 // 1 minutes in milliseconds
37 MaxTimeout = 10 * 60 * 1000 // 10 minutes in milliseconds
38 MaxOutputLength = 30000
39)
40
41var bannedCommands = []string{
42 "alias", "curl", "curlie", "wget", "axel", "aria2c",
43 "nc", "telnet", "lynx", "w3m", "links", "httpie", "xh",
44 "http-prompt", "chrome", "firefox", "safari",
45}
46
47var safeReadOnlyCommands = []string{
48 "ls", "echo", "pwd", "date", "cal", "uptime", "whoami", "id", "groups", "env", "printenv", "set", "unset", "which", "type", "whereis",
49 "whatis", "uname", "hostname", "df", "du", "free", "top", "ps", "kill", "killall", "nice", "nohup", "time", "timeout",
50
51 "git status", "git log", "git diff", "git show", "git branch", "git tag", "git remote", "git ls-files", "git ls-remote",
52 "git rev-parse", "git config --get", "git config --list", "git describe", "git blame", "git grep", "git shortlog",
53
54 "go version", "go help", "go list", "go env", "go doc", "go vet", "go fmt", "go mod", "go test", "go build", "go run", "go install", "go clean",
55}
56
57func bashDescription() string {
58 bannedCommandsStr := strings.Join(bannedCommands, ", ")
59 return fmt.Sprintf(`Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures.
60
61Before executing the command, please follow these steps:
62
631. Directory Verification:
64 - If the command will create new directories or files, first use the LS tool to verify the parent directory exists and is the correct location
65 - For example, before running "mkdir foo/bar", first use LS to check that "foo" exists and is the intended parent directory
66
672. Security Check:
68 - For security and to limit the threat of a prompt injection attack, some commands are limited or banned. If you use a disallowed command, you will receive an error message explaining the restriction. Explain the error to the User.
69 - Verify that the command is not one of the banned commands: %s.
70
713. Command Execution:
72 - After ensuring proper quoting, execute the command.
73 - Capture the output of the command.
74
754. Output Processing:
76 - If the output exceeds %d characters, output will be truncated before being returned to you.
77 - Prepare the output for display to the user.
78
795. Return Result:
80 - Provide the processed output of the command.
81 - If any errors occurred during execution, include those in the output.
82
83Usage notes:
84- The command argument is required.
85- You can specify an optional timeout in milliseconds (up to 600000ms / 10 minutes). If not specified, commands will timeout after 30 minutes.
86- VERY IMPORTANT: You MUST avoid using search commands like 'find' and 'grep'. Instead use Grep, Glob, or Agent tools to search. You MUST avoid read tools like 'cat', 'head', 'tail', and 'ls', and use FileRead and LS tools to read files.
87- When issuing multiple commands, use the ';' or '&&' operator to separate them. DO NOT use newlines (newlines are ok in quoted strings).
88- IMPORTANT: All commands share the same shell session. Shell state (environment variables, virtual environments, current directory, etc.) persist between commands. For example, if you set an environment variable as part of a command, the environment variable will persist for subsequent commands.
89- Try to maintain your current working directory throughout the session by using absolute paths and avoiding usage of 'cd'. You may use 'cd' if the User explicitly requests it.
90<good-example>
91pytest /foo/bar/tests
92</good-example>
93<bad-example>
94cd /foo/bar && pytest tests
95</bad-example>
96
97# Committing changes with git
98
99When the user asks you to create a new git commit, follow these steps carefully:
100
1011. Start with a single message that contains exactly three tool_use blocks that do the following (it is VERY IMPORTANT that you send these tool_use blocks in a single message, otherwise it will feel slow to the user!):
102 - Run a git status command to see all untracked files.
103 - Run a git diff command to see both staged and unstaged changes that will be committed.
104 - Run a git log command to see recent commit messages, so that you can follow this repository's commit message style.
105
1062. Use the git context at the start of this conversation to determine which files are relevant to your commit. Add relevant untracked files to the staging area. Do not commit files that were already modified at the start of this conversation, if they are not relevant to your commit.
107
1083. Analyze all staged changes (both previously staged and newly added) and draft a commit message. Wrap your analysis process in <commit_analysis> tags:
109
110<commit_analysis>
111- List the files that have been changed or added
112- Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)
113- Brainstorm the purpose or motivation behind these changes
114- Do not use tools to explore code, beyond what is available in the git context
115- Assess the impact of these changes on the overall project
116- Check for any sensitive information that shouldn't be committed
117- Draft a concise (1-2 sentences) commit message that focuses on the "why" rather than the "what"
118- Ensure your language is clear, concise, and to the point
119- Ensure the message accurately reflects the changes and their purpose (i.e. "add" means a wholly new feature, "update" means an enhancement to an existing feature, "fix" means a bug fix, etc.)
120- Ensure the message is not generic (avoid words like "Update" or "Fix" without context)
121- Review the draft message to ensure it accurately reflects the changes and their purpose
122</commit_analysis>
123
1244. Create the commit with a message ending with:
125🤖 Generated with opencode
126Co-Authored-By: opencode <noreply@opencode.ai>
127
128- In order to ensure good formatting, ALWAYS pass the commit message via a HEREDOC, a la this example:
129<example>
130git commit -m "$(cat <<'EOF'
131 Commit message here.
132
133 🤖 Generated with opencode
134 Co-Authored-By: opencode <noreply@opencode.ai>
135 EOF
136 )"
137</example>
138
1395. If the commit fails due to pre-commit hook changes, retry the commit ONCE to include these automated changes. If it fails again, it usually means a pre-commit hook is preventing the commit. If the commit succeeds but you notice that files were modified by the pre-commit hook, you MUST amend your commit to include them.
140
1416. Finally, run git status to make sure the commit succeeded.
142
143Important notes:
144- When possible, combine the "git add" and "git commit" commands into a single "git commit -am" command, to speed things up
145- However, be careful not to stage files (e.g. with 'git add .') for commits that aren't part of the change, they may have untracked files they want to keep around, but not commit.
146- NEVER update the git config
147- DO NOT push to the remote repository
148- IMPORTANT: Never use git commands with the -i flag (like git rebase -i or git add -i) since they require interactive input which is not supported.
149- If there are no changes to commit (i.e., no untracked files and no modifications), do not create an empty commit
150- Ensure your commit message is meaningful and concise. It should explain the purpose of the changes, not just describe them.
151- Return an empty response - the user will see the git output directly
152
153# Creating pull requests
154Use the gh command via the Bash tool for ALL GitHub-related tasks including working with issues, pull requests, checks, and releases. If given a Github URL use the gh command to get the information needed.
155
156IMPORTANT: When the user asks you to create a pull request, follow these steps carefully:
157
1581. Understand the current state of the branch. Remember to send a single message that contains multiple tool_use blocks (it is VERY IMPORTANT that you do this in a single message, otherwise it will feel slow to the user!):
159 - Run a git status command to see all untracked files.
160 - Run a git diff command to see both staged and unstaged changes that will be committed.
161 - Check if the current branch tracks a remote branch and is up to date with the remote, so you know if you need to push to the remote
162 - Run a git log command and 'git diff main...HEAD' to understand the full commit history for the current branch (from the time it diverged from the 'main' branch.)
163
1642. Create new branch if needed
165
1663. Commit changes if needed
167
1684. Push to remote with -u flag if needed
169
1705. Analyze all changes that will be included in the pull request, making sure to look at all relevant commits (not just the latest commit, but all commits that will be included in the pull request!), and draft a pull request summary. Wrap your analysis process in <pr_analysis> tags:
171
172<pr_analysis>
173- List the commits since diverging from the main branch
174- Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)
175- Brainstorm the purpose or motivation behind these changes
176- Assess the impact of these changes on the overall project
177- Do not use tools to explore code, beyond what is available in the git context
178- Check for any sensitive information that shouldn't be committed
179- Draft a concise (1-2 bullet points) pull request summary that focuses on the "why" rather than the "what"
180- Ensure the summary accurately reflects all changes since diverging from the main branch
181- Ensure your language is clear, concise, and to the point
182- Ensure the summary accurately reflects the changes and their purpose (ie. "add" means a wholly new feature, "update" means an enhancement to an existing feature, "fix" means a bug fix, etc.)
183- Ensure the summary is not generic (avoid words like "Update" or "Fix" without context)
184- Review the draft summary to ensure it accurately reflects the changes and their purpose
185</pr_analysis>
186
1876. Create PR using gh pr create with the format below. Use a HEREDOC to pass the body to ensure correct formatting.
188<example>
189gh pr create --title "the pr title" --body "$(cat <<'EOF'
190## Summary
191<1-3 bullet points>
192
193## Test plan
194[Checklist of TODOs for testing the pull request...]
195
196🤖 Generated with opencode
197EOF
198)"
199</example>
200
201Important:
202- Return an empty response - the user will see the gh output directly
203- Never update git config`, bannedCommandsStr, MaxOutputLength)
204}
205
206func NewBashTool(permission permission.Service) BaseTool {
207 return &bashTool{
208 permissions: permission,
209 }
210}
211
212func (b *bashTool) Info() ToolInfo {
213 return ToolInfo{
214 Name: BashToolName,
215 Description: bashDescription(),
216 Parameters: map[string]any{
217 "command": map[string]any{
218 "type": "string",
219 "description": "The command to execute",
220 },
221 "timeout": map[string]any{
222 "type": "number",
223 "description": "Optional timeout in milliseconds (max 600000)",
224 },
225 },
226 Required: []string{"command"},
227 }
228}
229
230func (b *bashTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
231 var params BashParams
232 if err := json.Unmarshal([]byte(call.Input), ¶ms); err != nil {
233 return NewTextErrorResponse("invalid parameters"), nil
234 }
235
236 if params.Timeout > MaxTimeout {
237 params.Timeout = MaxTimeout
238 } else if params.Timeout <= 0 {
239 params.Timeout = DefaultTimeout
240 }
241
242 if params.Command == "" {
243 return NewTextErrorResponse("missing command"), nil
244 }
245
246 baseCmd := strings.Fields(params.Command)[0]
247 for _, banned := range bannedCommands {
248 if strings.EqualFold(baseCmd, banned) {
249 return NewTextErrorResponse(fmt.Sprintf("command '%s' is not allowed", baseCmd)), nil
250 }
251 }
252
253 isSafeReadOnly := false
254 cmdLower := strings.ToLower(params.Command)
255
256 for _, safe := range safeReadOnlyCommands {
257 if strings.HasPrefix(cmdLower, strings.ToLower(safe)) {
258 if len(cmdLower) == len(safe) || cmdLower[len(safe)] == ' ' || cmdLower[len(safe)] == '-' {
259 isSafeReadOnly = true
260 break
261 }
262 }
263 }
264
265 sessionID, messageID := GetContextValues(ctx)
266 if sessionID == "" || messageID == "" {
267 return ToolResponse{}, fmt.Errorf("session ID and message ID are required for creating a new file")
268 }
269 if !isSafeReadOnly {
270 p := b.permissions.Request(
271 permission.CreatePermissionRequest{
272 SessionID: sessionID,
273 Path: config.WorkingDirectory(),
274 ToolName: BashToolName,
275 Action: "execute",
276 Description: fmt.Sprintf("Execute command: %s", params.Command),
277 Params: BashPermissionsParams{
278 Command: params.Command,
279 },
280 },
281 )
282 if !p {
283 return ToolResponse{}, permission.ErrorPermissionDenied
284 }
285 }
286 startTime := time.Now()
287 shell := shell.GetPersistentShell(config.WorkingDirectory())
288 stdout, stderr, exitCode, interrupted, err := shell.Exec(ctx, params.Command, params.Timeout)
289 if err != nil {
290 return ToolResponse{}, fmt.Errorf("error executing command: %w", err)
291 }
292
293 stdout = truncateOutput(stdout)
294 stderr = truncateOutput(stderr)
295
296 errorMessage := stderr
297 if interrupted {
298 if errorMessage != "" {
299 errorMessage += "\n"
300 }
301 errorMessage += "Command was aborted before completion"
302 } else if exitCode != 0 {
303 if errorMessage != "" {
304 errorMessage += "\n"
305 }
306 errorMessage += fmt.Sprintf("Exit code %d", exitCode)
307 }
308
309 hasBothOutputs := stdout != "" && stderr != ""
310
311 if hasBothOutputs {
312 stdout += "\n"
313 }
314
315 if errorMessage != "" {
316 stdout += "\n" + errorMessage
317 }
318
319 metadata := BashResponseMetadata{
320 StartTime: startTime.UnixMilli(),
321 EndTime: time.Now().UnixMilli(),
322 }
323 if stdout == "" {
324 return WithResponseMetadata(NewTextResponse("no output"), metadata), nil
325 }
326 return WithResponseMetadata(NewTextResponse(stdout), metadata), nil
327}
328
329func truncateOutput(content string) string {
330 if len(content) <= MaxOutputLength {
331 return content
332 }
333
334 halfLength := MaxOutputLength / 2
335 start := content[:halfLength]
336 end := content[len(content)-halfLength:]
337
338 truncatedLinesCount := countLines(content[halfLength : len(content)-halfLength])
339 return fmt.Sprintf("%s\n\n... [%d lines truncated] ...\n\n%s", start, truncatedLinesCount, end)
340}
341
342func countLines(s string) int {
343 if s == "" {
344 return 0
345 }
346 return len(strings.Split(s, "\n"))
347}