Overview
ToolHelpers provides direct access to the internal tool implementations used by Codebuff agents. These utilities can be used in custom tools, scripts, or agent logic to perform common operations.
Usage
import { ToolHelpers } from '@codebuff/sdk'
const files = await ToolHelpers.getFiles({
filePaths: ['src/index.ts', 'package.json'],
cwd: process.cwd(),
fs: require('fs').promises
})
Available Methods
getFiles()
Read multiple files from the filesystem with filtering and validation.
ToolHelpers.getFiles({
filePaths: string[],
cwd: string,
fs: CodebuffFileSystem,
fileFilter?: FileFilter
}): Promise<Record<string, string | null>>
Array of file paths to read (relative to cwd)
Current working directory (base path for relative paths)
fs
CodebuffFileSystem
required
Filesystem implementation (e.g., require('fs').promises)
Optional filter to classify files before readingtype FileFilter = (filePath: string) => {
status: 'blocked' | 'allow-example' | 'allow'
}
Returns: Record<string, string | null> where keys are file paths and values are:
- File content (string) if successful
null if file doesn’t exist
- Special markers for errors:
"[IGNORED]" - File is gitignored or blocked
"[OUTSIDE_PROJECT]" - Path is outside project directory
"[TOO_LARGE] [X.XXMb]" - File exceeds 1MB limit
"[DOES_NOT_EXIST]" - File not found
"[ERROR_READING_FILE]" - Read error
Example:
const files = await ToolHelpers.getFiles({
filePaths: ['src/index.ts', 'README.md', 'missing.txt'],
cwd: '/project',
fs: require('fs').promises
})
// Result:
// {
// 'src/index.ts': 'export function main() {...}',
// 'README.md': '# My Project\n...',
// 'missing.txt': '[DOES_NOT_EXIST]'
// }
runTerminalCommand()
Execute a shell command and capture output.
ToolHelpers.runTerminalCommand({
command: string,
process_type: 'SYNC' | 'BACKGROUND',
cwd: string,
timeout_seconds: number,
env?: NodeJS.ProcessEnv
}): Promise<CodebuffToolOutput<'run_terminal_command'>>
process_type
'SYNC' | 'BACKGROUND'
required
Execution mode. Currently only 'SYNC' is supported.
Working directory for the command
Maximum execution time in seconds. Use -1 for no timeout.
Environment variables for the command. Merged with system environment.
Returns: Promise resolving to tool output:
[{
type: 'json',
value: {
command: string
stdout: string
stderr?: string
exitCode?: number
}
}]
Example:
const result = await ToolHelpers.runTerminalCommand({
command: 'npm test',
process_type: 'SYNC',
cwd: '/project',
timeout_seconds: 60,
env: { NODE_ENV: 'test' }
})
const output = result[0].value
console.log('Exit code:', output.exitCode)
console.log('Output:', output.stdout)
codeSearch()
Search codebase using ripgrep with regex patterns.
ToolHelpers.codeSearch({
projectPath: string,
pattern: string,
flags?: string,
cwd?: string,
maxResults?: number,
globalMaxResults?: number,
maxOutputStringLength?: number,
timeoutSeconds?: number,
logger?: Logger
}): Promise<CodebuffToolOutput<'code_search'>>
Regex pattern to search for
Additional ripgrep flags (e.g., '-i' for case-insensitive, '-g *.ts' to filter files)
Subdirectory to search within (relative to projectPath)
Maximum matches per file (default: 15)
Maximum total matches across all files (default: 250)
Maximum output string length (default: 20,000)
Search timeout in seconds (default: 10)
Optional logger for debugging
Returns: Promise resolving to tool output with search results formatted as filename:line:content
Example:
const result = await ToolHelpers.codeSearch({
projectPath: '/project',
pattern: 'TODO|FIXME',
flags: '-i', // case-insensitive
maxResults: 10
})
const output = result[0].value
console.log('Search results:', output.stdout)
// Output:
// src/index.ts:42:// TODO: refactor this
// src/utils.ts:15:// FIXME: handle edge case
glob()
Find files matching a glob pattern.
ToolHelpers.glob({
pattern: string,
projectPath: string,
cwd?: string,
fs: CodebuffFileSystem
}): Promise<ToolResultOutput[]>
Glob pattern (e.g., '**/*.ts', 'src/**/*.test.js')
Subdirectory to search within
fs
CodebuffFileSystem
required
Filesystem implementation
Example:
const result = await ToolHelpers.glob({
pattern: '**/*.ts',
projectPath: '/project',
fs: require('fs').promises
})
const files = result[0].value
console.log('TypeScript files:', files)
listDirectory()
List contents of a directory.
ToolHelpers.listDirectory({
directoryPath: string,
projectPath: string,
fs: CodebuffFileSystem
}): Promise<ToolResultOutput[]>
Directory to list (relative to projectPath)
fs
CodebuffFileSystem
required
Filesystem implementation
Example:
const result = await ToolHelpers.listDirectory({
directoryPath: 'src',
projectPath: '/project',
fs: require('fs').promises
})
const listing = result[0].value
console.log('Directory contents:', listing)
changeFile()
Create or modify a file (implements write_file and str_replace tools).
ToolHelpers.changeFile({
parameters: {
path: string,
content?: string,
oldStr?: string,
newStr?: string
},
cwd: string,
fs: CodebuffFileSystem
}): Promise<ToolResultOutput[]>
File path (relative to cwd)
New file content (for write_file mode)
String to find (for str_replace mode)
Replacement string (for str_replace mode)
fs
CodebuffFileSystem
required
Filesystem implementation
Example:
// Write new file
await ToolHelpers.changeFile({
parameters: {
path: 'src/new.ts',
content: 'export const foo = "bar"'
},
cwd: '/project',
fs: require('fs').promises
})
// Find and replace
await ToolHelpers.changeFile({
parameters: {
path: 'src/config.ts',
oldStr: 'port: 3000',
newStr: 'port: 8080'
},
cwd: '/project',
fs: require('fs').promises
})
runFileChangeHooks()
Run file change hooks (no-op in SDK - only relevant in CLI).
ToolHelpers.runFileChangeHooks(): Promise<void>
Note: This is a no-op in SDK mode. File change hooks are only executed in the Codebuff CLI environment.
Type Definitions
FileFilter
type FileFilter = (filePath: string) => FileFilterResult
type FileFilterResult = {
status: 'blocked' | 'allow-example' | 'allow'
}
CodebuffFileSystem
type CodebuffFileSystem = {
readFile: (path: string, encoding: string) => Promise<string>
writeFile: (path: string, data: string) => Promise<void>
readdir: (path: string) => Promise<string[]>
stat: (path: string) => Promise<{ size: number }>
// ... other fs methods
}
Logger
type Logger = {
debug?: (obj?: any, msg?: string) => void
info: (obj?: any, msg?: string) => void
warn: (obj?: any, msg?: string) => void
error: (obj?: any, msg?: string) => void
}
import { z } from 'zod/v4'
import { getCustomToolDefinition, ToolHelpers } from '@codebuff/sdk'
import fs from 'fs/promises'
const analyzeProjectTool = getCustomToolDefinition({
toolName: 'analyze_project',
inputSchema: z.object({
pattern: z.string(),
fileType: z.string().default('**/*.ts')
}),
description: 'Analyze project files for specific patterns',
execute: async ({ pattern, fileType }) => {
// Find files matching type
const globResult = await ToolHelpers.glob({
pattern: fileType,
projectPath: process.cwd(),
fs
})
const files = globResult[0].value.files || []
// Search for pattern
const searchResult = await ToolHelpers.codeSearch({
projectPath: process.cwd(),
pattern,
flags: `-g "${fileType}"`,
maxResults: 50
})
return [{
type: 'json',
value: {
totalFiles: files.length,
matches: searchResult[0].value.stdout
}
}]
}
})