Skip to content

Commit d13822d

Browse files
committed
tool updates
1 parent a890288 commit d13822d

37 files changed

Lines changed: 1061 additions & 697 deletions

app.log

Lines changed: 144 additions & 0 deletions
Large diffs are not rendered by default.

packages/opencode/.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
node_modules
2+
research
23
dist
34
gen
45
app.log

packages/opencode/AGENTS.md

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,30 @@
11
# OpenCode Agent Guidelines
22

33
## Build/Test Commands
4+
45
- **Install**: `bun install`
56
- **Run**: `bun run index.ts`
67
- **Typecheck**: `bun run typecheck` (npm run typecheck)
78
- **Test**: `bun test` (runs all tests)
89
- **Single test**: `bun test test/tool/tool.test.ts` (specific test file)
910

1011
## Code Style
12+
1113
- **Runtime**: Bun with TypeScript ESM modules
1214
- **Imports**: Use relative imports for local modules, named imports preferred
1315
- **Types**: Zod schemas for validation, TypeScript interfaces for structure
1416
- **Naming**: camelCase for variables/functions, PascalCase for classes/namespaces
1517
- **Error handling**: Use Result patterns, avoid throwing exceptions in tools
1618
- **File structure**: Namespace-based organization (e.g., `Tool.define()`, `Session.create()`)
19+
- DO NOT do unnecessary destructuring of variables
20+
- DO NOT use else statements unless necessary
21+
- DO NOT use try catch if it can be avoided
1722

1823
## Architecture
24+
1925
- **Tools**: Implement `Tool.Info` interface with `execute()` method
2026
- **Context**: Pass `sessionID` in tool context, use `App.provide()` for DI
2127
- **Validation**: All inputs validated with Zod schemas
2228
- **Logging**: Use `Log.create({ service: "name" })` pattern
23-
- **Storage**: Use `Storage` namespace for persistence
29+
- **Storage**: Use `Storage` namespace for persistence
30+

packages/opencode/src/global/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ await Promise.all([
1717
export namespace Global {
1818
export const Path = {
1919
data,
20+
bin: path.join(data, "bin"),
2021
cache,
2122
config,
2223
} as const

packages/opencode/src/provider/provider.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,14 @@ import { Global } from "../global"
99
import { BunProc } from "../bun"
1010
import { BashTool } from "../tool/bash"
1111
import { EditTool } from "../tool/edit"
12-
import { FetchTool } from "../tool/fetch"
12+
import { WebFetchTool } from "../tool/webfetch"
1313
import { GlobTool } from "../tool/glob"
1414
import { GrepTool } from "../tool/grep"
1515
import { ListTool } from "../tool/ls"
1616
import { LspDiagnosticTool } from "../tool/lsp-diagnostics"
1717
import { LspHoverTool } from "../tool/lsp-hover"
1818
import { PatchTool } from "../tool/patch"
19-
import { ViewTool } from "../tool/view"
19+
import { ReadTool } from "../tool/read"
2020
import type { Tool } from "../tool/tool"
2121

2222
export namespace Provider {
@@ -165,18 +165,18 @@ export namespace Provider {
165165
const TOOLS = [
166166
BashTool,
167167
EditTool,
168-
FetchTool,
168+
WebFetchTool,
169169
GlobTool,
170170
GrepTool,
171171
ListTool,
172172
LspDiagnosticTool,
173173
LspHoverTool,
174174
PatchTool,
175-
ViewTool,
175+
ReadTool,
176176
EditTool,
177177
]
178178
const TOOL_MAPPING: Record<string, Tool.Info[]> = {
179-
anthropic: TOOLS,
179+
anthropic: TOOLS.filter((t) => t.id !== "opencode.patch"),
180180
openai: TOOLS,
181181
google: TOOLS,
182182
}
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import { App } from "../app/app"
2+
import path from "path"
3+
import { Global } from "../global"
4+
import fs from "fs/promises"
5+
6+
export namespace Ripgrep {
7+
const PLATFORM = {
8+
darwin: { platform: "apple-darwin", extension: "tar.gz" },
9+
linux: { platform: "unknown-linux-musl", extension: "tar.gz" },
10+
win32: { platform: "pc-windows-msvc", extension: "zip" },
11+
} as const
12+
13+
const state = App.state("ripgrep", async () => {
14+
const filepath = path.join(
15+
Global.Path.bin,
16+
"rg" + (process.platform === "win32" ? ".exe" : ""),
17+
)
18+
19+
const file = Bun.file(filepath)
20+
if (!(await file.exists())) {
21+
const archMap = { x64: "x86_64", arm64: "aarch64" } as const
22+
const arch = archMap[process.arch as keyof typeof archMap] ?? process.arch
23+
24+
const config = PLATFORM[process.platform as keyof typeof PLATFORM]
25+
if (!config) throw new Error(`Unsupported platform: ${process.platform}`)
26+
27+
const version = "14.1.1"
28+
const filename = `ripgrep-${version}-${arch}-${config.platform}.${config.extension}`
29+
const url = `https://github.com/BurntSushi/ripgrep/releases/download/${version}/${filename}`
30+
31+
const response = await fetch(url)
32+
if (!response.ok)
33+
throw new Error(`Failed to download ripgrep: ${response.statusText}`)
34+
35+
const buffer = await response.arrayBuffer()
36+
const archivePath = path.join(Global.Path.bin, filename)
37+
await Bun.write(archivePath, buffer)
38+
if (config.extension === "tar.gz") {
39+
const proc = Bun.spawn(
40+
[
41+
"tar",
42+
"-xzf",
43+
archivePath,
44+
"--strip-components=1",
45+
"--wildcards",
46+
"*/rg",
47+
],
48+
{
49+
cwd: Global.Path.bin,
50+
stderr: "ignore",
51+
stdout: "ignore",
52+
},
53+
)
54+
await proc.exited
55+
}
56+
if (config.extension === "zip") {
57+
const proc = Bun.spawn(
58+
["unzip", "-j", archivePath, "*/rg.exe", "-d", Global.Path.bin],
59+
{
60+
cwd: Global.Path.bin,
61+
stderr: "ignore",
62+
stdout: "ignore",
63+
},
64+
)
65+
await proc.exited
66+
}
67+
68+
await fs.unlink(archivePath)
69+
70+
if (process.platform !== "win32") await fs.chmod(filepath, 0o755)
71+
}
72+
73+
return {
74+
filepath,
75+
}
76+
})
77+
78+
export async function filepath() {
79+
const { filepath } = await state()
80+
return filepath
81+
}
82+
}

packages/opencode/src/session/session.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -444,7 +444,7 @@ ${app.git ? await ListTool.execute({ path: app.path.cwd }, { sessionID: input.se
444444
next.parts.push({
445445
type: "tool-invocation",
446446
toolInvocation: {
447-
state: "call",
447+
state: "partial-call",
448448
toolName: value.toolName,
449449
toolCallId: value.toolCallId,
450450
args: {},

packages/opencode/src/tool/bash.ts

Lines changed: 10 additions & 148 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { z } from "zod"
22
import { Tool } from "./tool"
3+
import DESCRIPTION from "./bash.txt"
34

45
const MAX_OUTPUT_LENGTH = 30000
56
const BANNED_COMMANDS = [
@@ -24,163 +25,23 @@ const BANNED_COMMANDS = [
2425
const DEFAULT_TIMEOUT = 1 * 60 * 1000
2526
const MAX_TIMEOUT = 10 * 60 * 1000
2627

27-
const DESCRIPTION = `Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures.
28-
29-
Before executing the command, please follow these steps:
30-
31-
1. Directory Verification:
32-
- 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
33-
- For example, before running "mkdir foo/bar", first use LS to check that "foo" exists and is the intended parent directory
34-
35-
2. Security Check:
36-
- 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.
37-
- Verify that the command is not one of the banned commands: ${BANNED_COMMANDS.join(", ")}.
38-
39-
3. Command Execution:
40-
- After ensuring proper quoting, execute the command.
41-
- Capture the output of the command.
42-
43-
4. Output Processing:
44-
- If the output exceeds ${MAX_OUTPUT_LENGTH} characters, output will be truncated before being returned to you.
45-
- Prepare the output for display to the user.
46-
47-
5. Return Result:
48-
- Provide the processed output of the command.
49-
- If any errors occurred during execution, include those in the output.
50-
51-
Usage notes:
52-
- The command argument is required.
53-
- You can specify an optional timeout in milliseconds (up to 600000ms / 10 minutes). If not specified, commands will timeout after 30 minutes.
54-
- 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.
55-
- When issuing multiple commands, use the ';' or '&&' operator to separate them. DO NOT use newlines (newlines are ok in quoted strings).
56-
- 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.
57-
- 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.
58-
<good-example>
59-
pytest /foo/bar/tests
60-
</good-example>
61-
<bad-example>
62-
cd /foo/bar && pytest tests
63-
</bad-example>
64-
65-
# Committing changes with git
66-
67-
When the user asks you to create a new git commit, follow these steps carefully:
68-
69-
1. 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!):
70-
- Run a git status command to see all untracked files.
71-
- Run a git diff command to see both staged and unstaged changes that will be committed.
72-
- Run a git log command to see recent commit messages, so that you can follow this repository's commit message style.
73-
74-
2. 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.
75-
76-
3. Analyze all staged changes (both previously staged and newly added) and draft a commit message. Wrap your analysis process in <commit_analysis> tags:
77-
78-
<commit_analysis>
79-
- List the files that have been changed or added
80-
- Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)
81-
- Brainstorm the purpose or motivation behind these changes
82-
- Do not use tools to explore code, beyond what is available in the git context
83-
- Assess the impact of these changes on the overall project
84-
- Check for any sensitive information that shouldn't be committed
85-
- Draft a concise (1-2 sentences) commit message that focuses on the "why" rather than the "what"
86-
- Ensure your language is clear, concise, and to the point
87-
- 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.)
88-
- Ensure the message is not generic (avoid words like "Update" or "Fix" without context)
89-
- Review the draft message to ensure it accurately reflects the changes and their purpose
90-
</commit_analysis>
91-
92-
4. Create the commit with a message ending with:
93-
🤖 Generated with opencode
94-
Co-Authored-By: opencode <noreply@opencode.ai>
95-
96-
- In order to ensure good formatting, ALWAYS pass the commit message via a HEREDOC, a la this example:
97-
<example>
98-
git commit -m "$(cat <<'EOF'
99-
Commit message here.
100-
101-
🤖 Generated with opencode
102-
Co-Authored-By: opencode <noreply@opencode.ai>
103-
EOF
104-
)"
105-
</example>
106-
107-
5. 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.
108-
109-
6. Finally, run git status to make sure the commit succeeded.
110-
111-
Important notes:
112-
- When possible, combine the "git add" and "git commit" commands into a single "git commit -am" command, to speed things up
113-
- 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.
114-
- NEVER update the git config
115-
- DO NOT push to the remote repository
116-
- 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.
117-
- If there are no changes to commit (i.e., no untracked files and no modifications), do not create an empty commit
118-
- Ensure your commit message is meaningful and concise. It should explain the purpose of the changes, not just describe them.
119-
- Return an empty response - the user will see the git output directly
120-
121-
# Creating pull requests
122-
Use 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.
123-
124-
IMPORTANT: When the user asks you to create a pull request, follow these steps carefully:
125-
126-
1. 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!):
127-
- Run a git status command to see all untracked files.
128-
- Run a git diff command to see both staged and unstaged changes that will be committed.
129-
- 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
130-
- 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.)
131-
132-
2. Create new branch if needed
133-
134-
3. Commit changes if needed
135-
136-
4. Push to remote with -u flag if needed
137-
138-
5. 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:
139-
140-
<pr_analysis>
141-
- List the commits since diverging from the main branch
142-
- Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)
143-
- Brainstorm the purpose or motivation behind these changes
144-
- Assess the impact of these changes on the overall project
145-
- Do not use tools to explore code, beyond what is available in the git context
146-
- Check for any sensitive information that shouldn't be committed
147-
- Draft a concise (1-2 bullet points) pull request summary that focuses on the "why" rather than the "what"
148-
- Ensure the summary accurately reflects all changes since diverging from the main branch
149-
- Ensure your language is clear, concise, and to the point
150-
- 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.)
151-
- Ensure the summary is not generic (avoid words like "Update" or "Fix" without context)
152-
- Review the draft summary to ensure it accurately reflects the changes and their purpose
153-
</pr_analysis>
154-
155-
6. Create PR using gh pr create with the format below. Use a HEREDOC to pass the body to ensure correct formatting.
156-
<example>
157-
gh pr create --title "the pr title" --body "$(cat <<'EOF'
158-
## Summary
159-
<1-3 bullet points>
160-
161-
## Test plan
162-
[Checklist of TODOs for testing the pull request...]
163-
164-
🤖 Generated with opencode
165-
EOF
166-
)"
167-
</example>
168-
169-
Important:
170-
- Return an empty response - the user will see the gh output directly
171-
- Never update git config`
172-
17328
export const BashTool = Tool.define({
17429
id: "opencode.bash",
17530
description: DESCRIPTION,
17631
parameters: z.object({
177-
command: z.string(),
32+
command: z.string().describe("The command to execute"),
17833
timeout: z
17934
.number()
18035
.min(0)
18136
.max(MAX_TIMEOUT)
18237
.describe("Optional timeout in milliseconds")
183-
.optional(),
38+
.optional()
39+
.describe("Optional timeout in milliseconds"),
40+
description: z
41+
.string()
42+
.describe(
43+
"Clear, concise description of what this command does in 5-10 words. Examples:\nInput: ls\nOutput: Lists files in current directory\n\nInput: git status\nOutput: Shows working tree status\n\nInput: npm install\nOutput: Installs package dependencies\n\nInput: mkdir foo\nOutput: Creates directory 'foo'",
44+
),
18445
}),
18546
async execute(params) {
18647
const timeout = Math.min(params.timeout ?? DEFAULT_TIMEOUT, MAX_TIMEOUT)
@@ -202,6 +63,7 @@ export const BashTool = Tool.define({
20263
metadata: {
20364
stderr,
20465
stdout,
66+
description: params.description,
20567
},
20668
output: stdout.replaceAll(/\x1b\[[0-9;]*m/g, ""),
20769
}

0 commit comments

Comments
 (0)