Skip to main content
The Codebuff SDK exports several utility functions for advanced use cases.

Agent Loading

loadLocalAgents()

Load custom agent definitions from local directories.
import { loadLocalAgents } from '@codebuff/sdk'

const result = await loadLocalAgents({
  directories: ['./agents', './.agents'],
  cwd: process.cwd()
})

console.log('Loaded agents:', Object.keys(result.agents))
directories
string[]
required
Array of directory paths to search for agent definitions
cwd
string
required
Current working directory (base path for relative paths)
Returns: Promise<LoadLocalAgentsResult>
agents
LoadedAgents
Object mapping agent IDs to loaded agent definitions
errors
AgentValidationError[]
Array of validation errors encountered during loading

loadMCPConfig()

Load MCP (Model Context Protocol) server configuration from file.
import { loadMCPConfig } from '@codebuff/sdk'

const mcpConfig = await loadMCPConfig('./mcp-config.json')
configPath
string
required
Path to the MCP configuration file
Returns: Promise<LoadedMCPConfig | null> Returns the loaded MCP configuration or null if the file doesn’t exist.

validateAgents()

Validate agent definitions against the schema.
import { validateAgents } from '@codebuff/sdk'

const result = validateAgents(agentDefinitions, {
  cwd: process.cwd(),
  strictMode: true
})

if (!result.valid) {
  console.error('Validation errors:', result.errors)
}
agents
Record<string, AgentDefinition>
required
Object mapping agent IDs to agent definitions
options
ValidateAgentsOptions
Validation options
Returns: ValidationResult
valid
boolean
Whether all agents passed validation
errors
AgentValidationError[]
Array of validation errors if any

File Operations

getFiles()

Read multiple files from the filesystem with filtering.
import { getFiles } from '@codebuff/sdk'

const files = await getFiles({
  filePaths: ['src/index.ts', 'package.json'],
  cwd: process.cwd(),
  fs: require('fs').promises
})
filePaths
string[]
required
Array of file paths to read
cwd
string
required
Current working directory
fs
CodebuffFileSystem
required
Filesystem implementation
fileFilter
FileFilter
Optional filter to classify files before reading
Returns: Promise<Record<string, string | null>> Returns an object mapping file paths to their contents (or null if unreadable).

runTerminalCommand()

Execute a terminal command and capture output.
import { runTerminalCommand } from '@codebuff/sdk'

const result = await runTerminalCommand({
  command: 'npm test',
  cwd: process.cwd()
})

console.log('Exit code:', result.exitCode)
console.log('Output:', result.stdout)
command
string
required
Command to execute
cwd
string
required
Working directory for command execution
timeout
number
Timeout in milliseconds (default: 30000)
Returns: Promise<CommandResult>
exitCode
number
Command exit code
stdout
string
Standard output
stderr
string
Standard error output

Message Building

buildUserMessageContent()

Build message content from various input types.
import { buildUserMessageContent } from '@codebuff/sdk'

const content = buildUserMessageContent('Hello, Codebuff!')
// Or with images
const contentWithImage = buildUserMessageContent([
  { type: 'text', text: 'Analyze this image' },
  { type: 'image', source: { type: 'base64', data: '...' } }
])
input
string | MessageContent[]
required
Text string or array of content parts
Returns: MessageContent[] Returns normalized message content array.

Advanced Utilities

getUserInfoFromApiKey()

Retrieve user information from an API key.
import { getUserInfoFromApiKey } from '@codebuff/sdk'

const userInfo = await getUserInfoFromApiKey('your-api-key')
console.log('User ID:', userInfo.userId)
apiKey
string
required
Codebuff API key
Returns: Promise<UserInfo>
userId
string
User’s unique identifier
email
string
User’s email address

Code Mapping (Tree-sitter)

getFileTokenScores()

Analyze file token relevance using tree-sitter.
import { getFileTokenScores } from '@codebuff/sdk'

const scores = await getFileTokenScores({
  filePath: 'src/index.ts',
  fileContent: sourceCode,
  language: 'typescript'
})
filePath
string
required
Path to the file being analyzed
fileContent
string
required
File content to analyze
language
string
required
Programming language (e.g., ‘typescript’, ‘python’)
Returns: Promise<FileTokenData> Returns token scoring data for context optimization.

setWasmDir()

Set the directory for tree-sitter WASM files.
import { setWasmDir } from '@codebuff/sdk'

setWasmDir('./tree-sitter-wasm')
dir
string
required
Directory path containing WASM parser files

AI SDK Integration

promptAiSdk()

Make AI completion requests using the AI SDK.
import { promptAiSdk } from '@codebuff/sdk'

const response = await promptAiSdk({
  model: 'openai/gpt-4',
  messages: [{ role: 'user', content: 'Hello!' }]
})

promptAiSdkStream()

Stream AI completion responses.
import { promptAiSdkStream } from '@codebuff/sdk'

const stream = await promptAiSdkStream({
  model: 'anthropic/claude-3.5-sonnet',
  messages: [{ role: 'user', content: 'Write a story' }]
})

for await (const chunk of stream) {
  process.stdout.write(chunk)
}

promptAiSdkStructured()

Get structured output from AI models.
import { promptAiSdkStructured } from '@codebuff/sdk'
import { z } from 'zod'

const result = await promptAiSdkStructured({
  model: 'openai/gpt-4',
  messages: [{ role: 'user', content: 'Extract person info' }],
  schema: z.object({
    name: z.string(),
    age: z.number()
  })
})

console.log(result.name, result.age)

Error Handling Utilities

Error Type Checking

import {
  isRetryableStatusCode,
  getErrorStatusCode,
  sanitizeErrorMessage
} from '@codebuff/sdk'

if (isRetryableStatusCode(statusCode)) {
  // Retry the request
}

const status = getErrorStatusCode(error)
const safeMessage = sanitizeErrorMessage(error)

Error Creators

import {
  createHttpError,
  createAuthError,
  createForbiddenError,
  createPaymentRequiredError,
  createServerError,
  createNetworkError
} from '@codebuff/sdk'

throw createAuthError('Invalid API key')
throw createPaymentRequiredError('Insufficient credits')

Retry Configuration

Constants for retry logic:
import {
  MAX_RETRIES_PER_MESSAGE,
  RETRY_BACKOFF_BASE_DELAY_MS,
  RETRY_BACKOFF_MAX_DELAY_MS,
  RECONNECTION_MESSAGE_DURATION_MS,
  RECONNECTION_RETRY_DELAY_MS
} from '@codebuff/sdk'

See Also

Build docs developers (and LLMs) love