Overview
CodebuffClient is the primary class for interacting with the Codebuff SDK. It manages configuration, API authentication, and provides methods to run agents and check connection status.
Constructor
new CodebuffClient ( options : CodebuffClientOptions )
Creates a new Codebuff client instance with the specified configuration.
Parameters
options
CodebuffClientOptions
required
Configuration options for the client Show CodebuffClientOptions properties
Your Codebuff API key. If not provided, will attempt to read from CODEBUFF_API_KEY environment variable.
Current working directory for file operations. Defaults to process.cwd().
Optional directory path to load skills from. Skills found here will be available to the skill tool.
All files in your project as key-value pairs. Keys are file paths (relative to cwd), values are file contents. This helps Codebuff pick good source files for context. Example: { "src/index.ts": "console.log('hi')" }
Knowledge files to inject into every run() call. Same schema as projectFiles. These files are added directly to the agent’s context.
Maximum number of steps the agent can take before stopping. Use as a safety measure (recommended: ~20).
Environment variables to pass to terminal commands executed by the agent. Merged with process environment.
handleEvent
(event: PrintModeEvent) => void | Promise<void>
Callback function that receives events during execution (assistant messages, tool calls, errors, etc.). Event types:
{ type: 'error', message: string } - Error occurred
{ type: 'assistant_message', content: string } - Agent message
{ type: 'tool_call', toolName: string, input: any } - Tool invocation
handleStreamChunk
(chunk: string | object) => void | Promise<void>
Callback for token-by-token streaming. Receives:
Plain strings for main agent output
{ type: 'subagent_chunk', agentId: string, agentType: string, chunk: string } for subagent output
{ type: 'reasoning_chunk', agentId: string, ancestorRunIds: string[], chunk: string } for reasoning tokens
Optional filter to classify files before reading (runs before gitignore check). Type: (filePath: string) => { status: 'blocked' | 'allow-example' | 'allow' }
Override default tool implementations. Useful for customizing file operations, terminal commands, etc. Example: overrideTools : {
read_files : async ({ filePaths }) => {
// Custom file reading logic
return { 'file.txt' : 'content' }
}
}
Array of custom tool definitions that extend the agent’s capabilities. See CustomTool for details. fsSource
Source<CodebuffFileSystem>
Custom filesystem implementation. Defaults to Node.js fs.promises.
Custom process spawning implementation. Defaults to Node.js child_process.spawn.
Custom logger implementation. Defaults to no-op logger. Interface: {
debug : ( obj ?: any , msg ?: string ) => void
info : ( obj ?: any , msg ?: string ) => void
warn : ( obj ?: any , msg ?: string ) => void
error : ( obj ?: any , msg ?: string ) => void
}
Throws
Throws an error if API key is not provided and cannot be found in environment variables.
Example
import { CodebuffClient } from '@codebuff/sdk'
const client = new CodebuffClient ({
apiKey: 'your-api-key' ,
cwd: process . cwd (),
maxAgentSteps: 20 ,
handleEvent : ( event ) => {
if ( event . type === 'error' ) {
console . error ( 'Error:' , event . message )
}
}
})
Methods
run()
Run a Codebuff agent with the specified options.
async run ( options : RunOptions & CodebuffClientOptions ): Promise < RunState >
options
RunOptions & CodebuffClientOptions
required
Run configuration options. Accepts all CodebuffClientOptions plus: Show RunOptions properties
agent
string | AgentDefinition
required
The agent to run. Use ‘base’ for the default agent, or specify a custom agent ID if you made your own agent config. Can also be an inline AgentDefinition object.
The user prompt describing what you want the agent to do.
Content array for multimodal messages (text + images). type MessageContent =
| { type : 'text' , text : string }
| { type : 'image' , image : string , mediaType : string } // base64 encoded
Additional parameters for the agent. Most agents don’t use this, but some custom agents can take a JSON object as input.
JSON state returned from a previous run() call. Use this to continue a conversation or session with the agent.
Additional tool result messages to inject into the conversation.
AbortSignal for canceling the run. Use with AbortController. Example: const controller = new AbortController ()
client . run ({ agent: 'base' , prompt: 'Hello' , signal: controller . signal })
// Later: controller.abort()
Cost optimization mode. Defaults to ‘normal’.
Returns a RunState object containing session state and output. Opaque session state object. Pass to subsequent run() calls to continue the conversation.
The agent’s output result. Success: { type : 'success' , message : string }
Error: { type : 'error' , message : string , statusCode ?: number }
Example
const result = await client . run ({
agent: 'base' ,
prompt: 'List all TypeScript files in the src directory' ,
})
if ( result . output . type === 'success' ) {
console . log ( 'Success:' , result . output . message )
} else {
console . error ( 'Error:' , result . output . message )
}
// Continue the conversation
const followUp = await client . run ({
agent: 'base' ,
prompt: 'Now analyze the first file' ,
previousRun: result
})
checkConnection()
Check connection to the Codebuff backend by hitting the /healthz endpoint.
async checkConnection (): Promise < boolean >
Returns true if connected successfully, false otherwise. Times out after 5 seconds.
Example
const isConnected = await client . checkConnection ()
if ( ! isConnected ) {
console . error ( 'Cannot connect to Codebuff backend' )
}
Properties
options
The resolved client configuration including API key and fingerprint ID.
public options : CodebuffClientOptions & {
apiKey : string
fingerprintId : string
}