# Complete Guide to the Core Exports of the Freebuff SDK

> Explore the core exports of the Freebuff SDK, including runtime functions, client classes, file utilities, agent loaders, and LLM helpers. Access the full API from a single entry point.

- Repository: [Codebuff/freebuff](https://github.com/CodebuffAI/freebuff)
- Tags: api-reference
- Published: 2026-09-01

---

**The Freebuff SDK exposes its entire public API through a single barrel file at [`src/index.ts`](https://github.com/CodebuffAI/freebuff/blob/main/src/index.ts), which re‑exports runtime functions, client classes, file utilities, agent loaders, and low‑level LLM helpers.**

The **Freebuff SDK** (maintained in the `CodebuffAI/freebuff` repository) is a TypeScript toolkit for building AI agents that interact with filesystems, execute terminal commands, and leverage Tree‑Sitter code analysis. Understanding the core exports of the Freebuff SDK is essential for developers who want to initialize clients, run agents, or extend functionality with custom tools. Every public symbol flows through [`sdk/src/index.ts`](https://github.com/CodebuffAI/freebuff/blob/main/sdk/src/index.ts), making it the definitive catalog of the SDK’s surface area.

## Core Runtime and Execution

The foundation of the SDK is the **agent execution engine**. At `src/index.ts#L13–14`, the module exposes:

- **`run`** – The primary entry point for executing an agent with a given prompt and configuration.
- **`STATE_SNAPSHOT_INTERRUPTION_MESSAGE`** – A constant used to signal stream‑based interruptions during long‑running sessions.

These exports originate in [`sdk/src/run.ts`](https://github.com/CodebuffAI/freebuff/blob/main/sdk/src/run.ts), which orchestrates the complete agent lifecycle from initialization to event emission.

## File System Utilities

For workspace introspection, `src/index.ts#L14–16` exports:

- **`getFiles`** – Async helper for recursively reading directory contents.
- **`FileFilter`** – Interface for defining inclusion/exclusion patterns.
- **`FileFilterResult`** – Return type describing matched file sets.

These utilities abstract away platform‑specific file walking and respect `.gitignore` semantics by default.

## Client and Authentication

The main class for platform interaction is exported at `src/index.ts#L34–36`:

- **`CodebuffClient`** – Instantiated with an API key and working directory, this class handles all communication with the Codebuff cloud service.
- **`getUserInfoFromApiKey`** – Utility to validate credentials and retrieve account metadata.
- **`credentials`** – Helper for secure credential storage.

The client implementation lives in [`sdk/src/client.ts`](https://github.com/CodebuffAI/freebuff/blob/main/sdk/src/client.ts) and manages request signing, retry logic, and event streaming.

## Extensibility: Custom Tools and Native Bindings

Developer extensibility is provided through:

- **`* from './custom-tool'`** (`src/index.ts#L35`) – Enables registration of bespoke tool implementations that agents can invoke during execution.
- **`* from './native/ripgrep'`** (`src/index.ts#L36`) – Direct access to the bundled `ripgrep` binary for high‑performance code search without external dependencies.

## Run‑State Management and Tool Helpers

Long‑running agents require persistence:

- **`* from './run-state'`** (`src/index.ts#L37`) – Types and helpers for serializing execution state, allowing runs to pause and resume across process restarts.
- **`ToolHelpers`** (`src/index.ts#L38`) – A consolidated toolbox exposing filesystem operations, process spawners, and other primitives used internally by agents.

## Agent Loading and Validation

The SDK provides comprehensive agent lifecycle management at `src/index.ts#L43–46` and `src/index.ts#L60–62`:

- **`loadLocalAgents`** – Import agents from local file paths.
- **`loadMCPConfig`** / **`loadMCPConfigSync`** – Load Model Context Protocol configurations (async and synchronous variants).
- **`loadSkills`** / **`loadSkillsSync`** – Discover and parse skill definitions from directories.
- **`parseSkillFileContent`** – Parse individual skill files without filesystem access.
- **`validateAgents`** – Runtime validation of agent definitions with detailed error reporting.
- **`ValidationResult`** / **`ValidateAgentsOptions`** – Supporting types for validation outcomes.

## Error Handling and Retry Configuration

Robust network resilience is built into the SDK through exports at `src/index.ts#L68–89`:

- **`isRetryableStatusCode`** – Determines if an HTTP status warrants automatic retry.
- **`createHttpError`** / **`HttpError`** – Standardized error classes with metadata.
- **`MAX_RETRIES_PER_MESSAGE`** – Global retry limit constant.
- **`RETRY_BACKOFF_BASE_DELAY_MS`** – Configurable exponential backoff parameter.

These utilities ensure consistent handling of transient failures when communicating with the Codebuff API.

## Code Intelligence and Tree‑Sitter

Low‑level code analysis is exposed at `src/index.ts#L94–107`:

- **`getFileTokenScores`** – Uses Tree‑Sitter to compute token relevance scores for a given file.
- **`setWasmDir`** / **`setTreeSitterWasmPath`** – Configure paths to Tree‑Sitter WebAssembly binaries (required before invoking parser functions).
- **`FileTokenData`** / **`TokenCallerMap`** – Types representing parsed AST nodes and token relationships.

These exports interface with the bundled `@codebuff/code-map` WASM modules for fast, language‑aware code navigation.

## Terminal and Process Management

Safe shell execution is provided at `src/index.ts#L109–118`:

- **`runTerminalCommand`** – Spawns shell commands with timeout controls, output streaming, and automatic working‑directory resolution.
- **`getActiveTerminalCommandProcesses`** – Inspector for currently running subprocesses managed by the SDK.

## Direct LLM Access

For applications requiring custom prompting workflows, `src/index.ts#L119–123` exports:

- **`promptAiSdk`** – Single‑turn LLM completion with structured output support.
- **`promptAiSdkStream`** – Streaming variant for real‑time token generation.
- **`promptAiSdkStructured`** – Enforces JSON schema validation on model outputs.

These functions reside in [`sdk/src/impl/llm.ts`](https://github.com/CodebuffAI/freebuff/blob/main/sdk/src/impl/llm.ts) and bypass the higher‑level agent orchestration for direct model access.

## Type Re‑exports

Throughout [`src/index.ts`](https://github.com/CodebuffAI/freebuff/blob/main/src/index.ts) (lines 5–12, 17–22, 26–33, 48–52), the SDK re‑exports TypeScript interfaces from internal packages:

- JSON payload types for messages and content parts.
- Agent configuration schemas.
- Tool definition structures.
- Filesystem abstraction interfaces.

Importing these ensures type safety when extending SDK capabilities.

## Practical Examples

### Initializing a Client and Running an Agent

```typescript
import { CodebuffClient, run } from '@codebuff/sdk'

const client = new CodebuffClient({
  apiKey: process.env.CODEBUFF_API_KEY!,
  cwd: process.cwd(),
})

await client.run({
  agent: 'codebuff/base@0.0.16',
  prompt: 'Write a Node.js hello‑world script',
  handleEvent: (e) => console.log('Event →', e),
})

```

### Loading Skills and Registering Custom Tools

```typescript
import { loadSkills, customTool, runTerminalCommand } from '@codebuff/sdk'

const { skills } = await loadSkills({ cwd: './my-skills' })

const myTool = customTool({
  name: 'listFiles',
  description: 'List files in a directory',
  run: async ({ dir }: { dir: string }) => {
    const result = await runTerminalCommand({ command: `ls -1 ${dir}` })
    return result.stdout
  },
})

await client.run({
  agent: 'codebuff/base@0.0.16',
  prompt: `Use the listFiles tool to show files in ./src`,
  tools: [myTool],
})

```

### Using Tree‑Sitter for Token Analysis

```typescript
import { getFileTokenScores, setWasmDir } from '@codebuff/sdk'

// Required once per process
setWasmDir('./node_modules/@codebuff/code-map/wasm')

const scores = await getFileTokenScores({
  filePath: './src/impl/llm.ts',
  language: 'typescript',
})
console.log(scores)

```

## Summary

- **Single Entry Point**: All functionality is reachable through [`sdk/src/index.ts`](https://github.com/CodebuffAI/freebuff/blob/main/sdk/src/index.ts), which serves as the SDK’s public barrel file.
- **Execution Primitives**: The `run` function and `CodebuffClient` class provide high‑level agent orchestration.
- **Extensibility**: Developers can inject behavior via `customTool`, load local agents with `loadLocalAgents`, and parse code with Tree‑Sitter utilities.
- **Resilience**: Built‑in retry logic (`isRetryableStatusCode`, `MAX_RETRIES_PER_MESSAGE`) and error standardization protect against network instability.
- **Type Safety**: Comprehensive TypeScript definitions are re‑exported for all public interfaces, ensuring compile‑time validation of agent configurations and tool signatures.

## Frequently Asked Questions

### How do I import the Freebuff SDK into my project?

Install the package via npm or yarn (`npm install @codebuff/sdk`), then import specific symbols from the main barrel. Because [`src/index.ts`](https://github.com/CodebuffAI/freebuff/blob/main/src/index.ts) re‑exports every public API, you can use named imports like `import { CodebuffClient, run } from '@codebuff/sdk'` without deep‑linking into subdirectories.

### What is the difference between sync and async agent loading functions?

The SDK provides parallel implementations for several loaders: `loadMCPConfig` vs. `loadMCPConfigSync`, and `loadSkills` vs. `loadSkillsSync`. The async variants perform non‑blocking filesystem operations and should be used in production servers, while the synchronous versions are convenience exports for build scripts or CLI tools where blocking I/O is acceptable.

### Can I use the Tree‑Sitter exports without running a full agent?

Yes. The `getFileTokenScores` function and its associated configuration methods (`setWasmDir`, `setTreeSitterWasmPath`) are standalone utilities exported from [`src/index.ts`](https://github.com/CodebuffAI/freebuff/blob/main/src/index.ts). You can initialize the WASM parser once and call these functions independently to analyze code structure without invoking the `run` function or instantiating `CodebuffClient`.