### Initialize Codebuff Project Source: https://www.codebuff.com/docs/walkthroughs/creating-your-first-agent Starts the Codebuff CLI in your project directory and uses the `/init` command to set up project context files. This creates `knowledge.md` for project context and a directory for agent type definitions. ```bash codebuff ``` ```text /init ``` -------------------------------- ### Example: Notion Integration Agent Source: https://www.codebuff.com/docs/agents/mcp-servers A complete example demonstrating how to configure an agent to use the Notion MCP server. ```APIDOC ## Example: Notion Integration Here's a complete example that connects to Notion using the official Notion MCP server: **.agents/notion-agent.ts** ```typescript import type { AgentDefinition } from './types/agent-definition' const definition: AgentDefinition = { id: 'notion-query-agent', displayName: 'Notion Query Agent', model: 'anthropic/claude-sonnet-4.5', spawnerPrompt: 'Expert at querying Notion databases and pages to find information and answer questions about content stored in Notion workspaces.', inputSchema: { prompt: { type: 'string', description', 'A question or request about information stored in your Notion workspace', }, }, outputMode: 'last_message', includeMessageHistory: false, mcpServers: { notionApi: { command: 'npx', args: ['-y', '@notionhq/notion-mcp-server'], env: { NOTION_TOKEN: '$NOTION_TOKEN', }, }, }, systemPrompt: `You are a Notion expert who helps users find and retrieve information from their Notion workspace. You can search across pages and databases, read specific pages, and query databases with filters.`, instructionsPrompt: `Instructions: 1. Use the Notion tools to search for relevant information based on the user's question. Start with a broad search. 2. If you find relevant pages or databases, read them in detail or query them with appropriate filters 3. Provide a comprehensive answer based on the information found in Notion. `, } export default definition ``` **Steps:** 1. Run `/init` within Codebuff to set up your `.agents` directory. 2. Save this file to `.agents/notion-agent.ts` in your project. 3. Get your Notion key and set it as an environment variable. 4. Start Codebuff and ask it to use your new Notion agent! Use similar steps to create new agents with other mcp tools! ``` -------------------------------- ### SDK Installation Source: https://www.codebuff.com/docs/advanced/sdk Install the Codebuff SDK using npm. ```APIDOC ## Installation ```bash npm install @codebuff/sdk ``` ``` -------------------------------- ### Agent Step Handling Example 1 (JavaScript Generator) Source: https://www.codebuff.com/docs/agents/agent-reference Example demonstrating `handleSteps` to read files using the 'read_files' tool, then proceeding with 'STEP_ALL', and finally setting the output using the 'set_output' tool. ```javascript function* handleSteps({ agentState, prompt, params, logger }) { logger.info('Starting file read process') const { toolResult } = yield { toolName: 'read_files', input: { paths: ['file1.txt', 'file2.txt'] } } yield 'STEP_ALL' // Optionally do a post-processing step here... logger.info('Files read successfully, setting output') yield { toolName: 'set_output', input: { output: 'The files were read successfully.', }, } } ``` -------------------------------- ### Install Codebuff SDK Source: https://www.codebuff.com/docs/advanced/sdk Installs the @codebuff/sdk package using npm. This is the first step to using the SDK in your project. ```bash npm install @codebuff/sdk ``` -------------------------------- ### Quick Start: Running an Agent Source: https://www.codebuff.com/docs/advanced/sdk Initialize the Codebuff client and run a basic agent task. ```APIDOC ## Quick Start Use the `base` agent (or any agent from the Agent Store) to run tasks: ```typescript import { CodebuffClient } from '@codebuff/sdk' const client = new CodebuffClient({ apiKey: process.env.CODEBUFF_API_KEY, cwd: process.cwd(), }) const result = await client.run({ agent: 'codebuff/base@0.0.16', prompt: 'Create a simple calculator class', handleEvent: (event) => { console.log('Event:', event.type) }, }) ``` ``` -------------------------------- ### Example: Test Generation Source: https://www.codebuff.com/docs/advanced/sdk An example demonstrating how to generate unit tests for provided code using the SDK. ```APIDOC ## Examples ### Test Generation ```typescript import { CodebuffClient } from '@codebuff/sdk' const CODE_TO_TEST = ` function add(a: number, b: number): number { return a + b; } function divide(a: number, b: number): number { if (b === 0) throw new Error('Division by zero'); return a / b; } ` async function generateTests(code: string) { const client = new CodebuffClient({ apiKey: process.env.CODEBUFF_API_KEY, }) const { output } = await client.run({ agent: 'codebuff/base@latest', prompt: `Generate unit tests for these functions using Jest:\n\n${code}`, }) return output } ``` ``` -------------------------------- ### Agent Spawning Example Source: https://www.codebuff.com/docs/agents/agent-reference Example TypeScript code demonstrating how to use the 'spawn_agents' tool to create a 'documentation-writer' agent. ```APIDOC ## Agent Spawning Example ### Description This example demonstrates how to use the 'spawn_agents' tool within a TypeScript environment to initiate the 'documentation-writer' agent. It includes steps for searching code, reading files, and conditionally spawning the documentation writer based on search results. ### Method N/A (Code Example) ### Endpoint N/A (Code Example) ### Parameters #### Query Parameters - **searchPattern** (string) - Optional - The pattern to use for code search. ### Request Example ```typescript const { toolResult: searchResults } = yield { toolName: 'code_search', input: { pattern: params.searchPattern || 'TODO' }, } const files = JSON.parse(searchResults || '[]').slice(0, 10) if (files.length) { yield { toolName: 'read_files', input: { paths: files } } } if (files.some((file) => file.includes('security'))) { yield { toolName: 'spawn_agents', input: { agents: [ { agent_type: 'security-reviewer', prompt: `Review security implications in: ${files.join(', ')}`, }, ], }, } } yield 'STEP_ALL' ``` ### Response #### Success Response (200) N/A (Code Example) #### Response Example N/A (Code Example) ``` -------------------------------- ### Example Global knowledge.md Content Source: https://www.codebuff.com/docs/tips/knowledge-files Provides an example of the content that can be included in a global `~/.knowledge.md` file. It covers user preferences for coding style, communication, and preferred tools/frameworks. ```markdown # User Preferences ## Coding Style - Always use TypeScript over JavaScript - Prefer functional programming patterns - Use descriptive variable names - Add JSDoc comments to exported functions ## Communication - Be concise in explanations - Show examples when explaining concepts - Ask for clarification on ambiguous requests ## Tools & Frameworks - I prefer React over Vue - Use Tailwind CSS for styling - Prefer pnpm over npm ``` -------------------------------- ### Quick Start: Run a Codebuff Agent Source: https://www.codebuff.com/docs/advanced/sdk Initializes the Codebuff client and runs the 'codebuff/base' agent to generate a calculator class. It demonstrates basic agent execution and event handling. ```typescript import { CodebuffClient } from '@codebuff/sdk' const client = new CodebuffClient({ apiKey: process.env.CODEBUFF_API_KEY, cwd: process.cwd(), }) const result = await client.run({ agent: 'codebuff/base@0.0.16', prompt: 'Create a simple calculator class', handleEvent: (event) => { console.log('Event:', event.type) }, }) ``` -------------------------------- ### Agent Directory Structure Example Source: https://www.codebuff.com/docs/agents/troubleshooting-agent-customization Illustrates the recommended directory structure for organizing agent files, types, and prompts within the `.agents/` directory. ```markdown your-project/ ├── .agents/ │ ├── my-agent.ts │ ├── types/ │ │ └── agent-definition.ts │ └── prompts/ │ └── my-prompts.md ``` -------------------------------- ### Agent Step Handling Example 2 (JavaScript Generator) Source: https://www.codebuff.com/docs/agents/agent-reference Example showing `handleSteps` in a loop to spawn 'thinker' agents, stepping the process with 'STEP', and breaking the loop when `stepsComplete` is true. ```javascript handleSteps: function* ({ agentState, prompt, params, logger }) { while (true) { logger.debug('Spawning thinker agent') yield { toolName: 'spawn_agents', input: { agents: [ { agent_type: 'thinker', prompt: 'Think deeply about the user request', }, ], }, } const { stepsComplete } = yield 'STEP' if (stepsComplete) break } } ``` -------------------------------- ### Use Cases Source: https://www.codebuff.com/docs/advanced/sdk Examples of how the Codebuff SDK can be utilized. ```APIDOC ## Use Cases * CI/CD pipelines: code review, test generation, refactoring * Batch processing * VS Code extensions, web apps * Automation scripts ``` -------------------------------- ### Install Codebuff using npm Source: https://www.codebuff.com/docs/help/quick-start Installs the Codebuff CLI globally using npm. This command should be run in your terminal or IDE's integrated terminal. ```bash npm install -g codebuff ``` -------------------------------- ### Check Node and npm Paths for Conflicts Source: https://www.codebuff.com/docs/advanced/troubleshooting Conflicting Node.js and npm installations, especially between Homebrew and nvm, can cause issues. Use `which node` and `which npm` to verify paths. If they point to Homebrew, uninstalling Node via Homebrew and relying on nvm is recommended. ```bash which node which npm brew uninstall node ``` -------------------------------- ### Agent Configuration Examples (TypeScript) Source: https://www.codebuff.com/docs/agents/agent-reference Illustrates how to configure an agent's core, model, and reasoning options in TypeScript. This includes setting unique IDs, display names, spawner prompts, and specifying the AI model to be used, along with enabling and configuring reasoning behavior. ```typescript const definition = { id: 'code-reviewer', displayName: 'Code Review Specialist', spawnerPrompt: 'Spawn this agent for thorough code review, focusing on bugs, security issues, and best practices', model: 'anthropic/claude-sonnet-4.5', reasoningOptions: { enabled: true, exclude: false, effort: 'high', }, outputMode: 'last_message' } ``` -------------------------------- ### Path Not Found Error Example Source: https://www.codebuff.com/docs/agents/troubleshooting-agent-customization Demonstrates the 'Path not found' error when a prompt file or other resource cannot be located. This is often due to incorrect relative pathing. ```text Error: Cannot resolve prompt file './my-prompt.md' ``` -------------------------------- ### Apply Agent Override Configuration Source: https://www.codebuff.com/docs/agents/troubleshooting-agent-customization Example JSON configuration for applying an override to an existing agent, including setting `override: true` and specifying `systemPrompt` changes. ```json { "id": "CodebuffAI/reviewer", // ✅ Exact match required "override": true, // ✅ Must be true for overrides "systemPrompt": { "type": "append", // ✅ Valid override type "content": "Custom instructions..." } } ``` -------------------------------- ### Programmatic Agent Step Execution Example (TypeScript) Source: https://www.codebuff.com/docs/agents/agent-reference An example of a generator function for programmatic agent control in TypeScript. It illustrates yielding tool calls for reading files and spawning agents, as well as controlling the execution flow with 'STEP_ALL'. ```typescript handleSteps: function* ({ prompt }) { const { toolResult } = yield { toolName: 'read_files', input: { paths: ['src/index.ts', 'src/config.ts'] }, } yield { toolName: 'spawn_agents', input: { agents: [{ agent_type: 'thinker', prompt: 'Analyze this code structure' }], }, } yield 'STEP_ALL' } ``` -------------------------------- ### Example Post-Change Verification Commands Source: https://www.codebuff.com/docs/tips/knowledge-files This snippet shows how to define commands within a `knowledge.md` file for Codebuff to execute after code changes. These commands are used to verify the correctness of modifications, such as type checking and running tests. ```markdown ## Verifying Changes After any code changes, run these commands to verify correctness: - Run `npm run typecheck` to check for type errors - Run `npm test` to ensure tests pass ``` -------------------------------- ### Generating Components with Project Context using Codebuff SDK Source: https://www.codebuff.com/docs/advanced/sdk This example shows how to generate a new component by providing existing project files as context to the Codebuff SDK. It reads specified files, includes them in the `projectFiles` object, and prompts the agent to create a new component based on existing patterns. Requires file system access and the CODEBUFF_API_KEY. ```typescript import { CodebuffClient } from '@codebuff/sdk' import * as fs from 'fs' async function generateComponentWithContext() { const client = new CodebuffClient({ apiKey: process.env.CODEBUFF_API_KEY, }) // Provide existing files as context const projectFiles = { 'src/types.ts': fs.readFileSync('src/types.ts', 'utf-8'), 'src/components/Button.tsx': fs.readFileSync('src/components/Button.tsx', 'utf-8'), } const { output } = await client.run({ agent: 'codebuff/base@latest', prompt: 'Create a new Card component that follows the same patterns as Button', projectFiles, }) return output } ``` -------------------------------- ### Use Economical Model for Cost Savings Source: https://www.codebuff.com/docs/agents/troubleshooting-agent-customization JSON configuration example for selecting a more cost-effective model, such as 'google/gemini-2.5-flash', to reduce credit usage. ```json { "model": "google/gemini-2.5-flash" // More economical } ``` -------------------------------- ### Agent Output Mode Configuration (JSON) Source: https://www.codebuff.com/docs/agents/agent-reference Demonstrates the configuration for handling agent output using the `outputMode` property. This example shows how to set the output mode to return only the last message from the conversation. ```json { "outputMode": "last_message" } ``` -------------------------------- ### Complete Agent Definition Example (TypeScript) Source: https://www.codebuff.com/docs/agents/troubleshooting-agent-customization A correctly structured TypeScript agent definition including all required fields such as `id`, `displayName`, `model`, `toolNames`, and `instructionsPrompt`. ```typescript import type { AgentDefinition } from './types/agent-definition' const definition: AgentDefinition = { id: 'my-agent', displayName: 'My Agent', model: 'anthropic/claude-sonnet-4.5', toolNames: ['read_files', 'write_file', 'end_turn'], instructionsPrompt: 'Process the user\'s request...', } export default definition ``` -------------------------------- ### Advanced Conditional Workflow with TypeScript Agents Source: https://www.codebuff.com/docs/agents/creating-new-agents Presents an advanced TypeScript example for `handleSteps`, showcasing a conditional workflow. It involves spawning a 'thinker' agent for analysis, conditionally finding files based on the analysis, writing to files, and finally spawning a 'reviewer' agent before yielding to 'STEP_ALL' for completion. ```typescript handleSteps: function* ({ agentState, prompt, params }) { // Step 1: Analyze the codebase const { toolResult: analysis } = yield { toolName: 'spawn_agents', input: { agents: [{ agent_type: 'thinker', prompt: `Analyze: ${prompt}` }] } } // Step 2: Based on analysis, choose action if (analysis?.includes('refactor')) { // Get all files that need refactoring const { toolResult: files } = yield { toolName: 'find_files', input: { query: 'needs refactoring' } } // Step 3: Refactor each file for (const file of JSON.parse(files || '[]')) { yield { toolName: 'write_file', input: { path: file, instructions: 'Refactor for better performance', content: '// ... refactored code ...' } } } } // Step 4: Final review yield { toolName: 'spawn_agents', input: { agents: [{ agent_type: 'reviewer', prompt: 'Review all changes' }] } } // Let the agent summarize yield 'STEP_ALL' } ``` -------------------------------- ### Agent Prompt Configurations Source: https://www.codebuff.com/docs/agents/agent-reference Configures various prompts to guide agent behavior. Includes `spawnerPrompt` for agent spawning, `includeMessageHistory` to incorporate conversation history, `inheritParentSystemPrompt` to reuse parent system prompts, `systemPrompt` for background information, `instructionsPrompt` for core instructions, and `stepPrompt` for step-specific guidance. ```typescript /** Prompt for when and why to spawn this agent. Include the main purpose and use cases. */ spawnerPrompt?: string /** Whether to include conversation history from the parent agent in context. */ includeMessageHistory?: boolean /** Whether to inherit the parent agent's system prompt instead of using this agent's own systemPrompt. */ inheritParentSystemPrompt?: boolean /** Background information for the agent. */ systemPrompt?: string /** Instructions for the agent. */ instructionsPrompt?: string /** Prompt inserted at each agent step. */ stepPrompt?: string ``` -------------------------------- ### Programmatic Tool Call Example (TypeScript) Source: https://www.codebuff.com/docs/agents/agent-reference Demonstrates how to programmatically control agent steps using a generator function in TypeScript. It shows yielding a tool call object to execute a tool and handle its result or error. ```typescript const { toolResult, toolError } = yield { toolName: 'read_files', input: { paths: ['file.ts'] }, } // use toolResult or handle toolError ``` -------------------------------- ### Test Agent Locally Source: https://www.codebuff.com/docs/walkthroughs/creating-your-first-agent Initiates the Codebuff CLI and then invokes the 'Simple Code Reviewer' agent to review recent local code changes. Ensure local changes are made before invoking the agent. ```bash codebuff ``` ```text @Simple Code Reviewer please review my recent changes ``` -------------------------------- ### Export Environment Variable (Bash) Source: https://www.codebuff.com/docs/agents/mcp-servers Provides an example of how to export an environment variable in a bash shell configuration file. This is necessary for the MCP server to access secrets like the Notion integration token. ```bash export NOTION_TOKEN="your-notion-integration-token" ``` -------------------------------- ### Batch Docstring Generation with Codebuff SDK Source: https://www.codebuff.com/docs/advanced/sdk This TypeScript example demonstrates how to add JSDoc comments to multiple files using the Codebuff SDK's base agent. It reads code from specified file paths, sends it to the agent for docstring generation, and returns the results. Requires file system access and the CODEBUFF_API_KEY. ```typescript import { CodebuffClient } from '@codebuff/sdk' import * as fs from 'fs' import * as path from 'path' async function addDocstringsToFiles(filePaths: string[]) { const client = new CodebuffClient({ apiKey: process.env.CODEBUFF_API_KEY, }) const results = [] for (const filePath of filePaths) { const code = fs.readFileSync(filePath, 'utf-8') const { output } = await client.run({ agent: 'codebuff/base@latest', prompt: `Add JSDoc comments to all functions in this file:\n\n${code}`, }) results.push({ filePath, output }) } return results } // Usage const files = ['src/utils.ts', 'src/helpers.ts', 'src/api.ts'] await addDocstringsToFiles(files) ``` -------------------------------- ### Define an API Documentation Agent with TypeScript Source: https://www.codebuff.com/docs/agents/creating-new-agents This TypeScript code defines an 'api-documenter' agent designed to write REST and GraphQL documentation. It utilizes the 'researcher' agent for lookups and includes tools for file operations, code searching, and agent spawning. The agent is configured with specific prompts for generating API documentation, including examples, schemas, and error codes. ```typescript import { AgentDefinition } from './types/agent-definition' const definition: AgentDefinition = { id: 'api-documenter', version: '1.0.0', displayName: 'API Documentation Specialist', spawnerPrompt: 'Spawn this agent to write API documentation with examples, schemas, and error codes', model: 'anthropic/claude-sonnet-4.5', outputMode: 'last_message', includeMessageHistory: true, toolNames: [ 'read_files', 'code_search', 'write_file', 'spawn_agents', 'end_turn', ], spawnableAgents: ['codebuff/researcher@0.0.1'], // Use full name for built-in agents inputSchema: { prompt: { type: 'string', description: 'What API endpoints or schemas to document', }, }, systemPrompt: 'You are an API documentation specialist. Write clear documentation for REST APIs and GraphQL schemas with examples, request/response formats, and error codes.', instructionsPrompt: 'Analyze the specified API endpoints and create documentation including examples, parameters, and response schemas.', stepPrompt: 'Continue documenting the API. Include practical examples and edge cases. Use end_turn when complete.', } export default definition ``` -------------------------------- ### Fix npm Permissions Error During Global Install Source: https://www.codebuff.com/docs/advanced/troubleshooting Permission errors during `npm install -g codebuff` can be resolved by changing the ownership of the target directory to your user. If this doesn't work, reinstalling Node.js using a version manager like nvm or fnm is recommended. ```bash # Mac/Linux sudo chown -R $(whoami) # Windows cmd takeown /F /R /D Y ``` -------------------------------- ### Minimal Agent Override Configuration Source: https://www.codebuff.com/docs/agents/troubleshooting-agent-customization A basic example of overriding an agent's configuration, starting with just the model, as a best practice for gradual debugging. ```json { "id": "CodebuffAI/reviewer", "override": true, "model": "anthropic/claude-sonnet-4.5" } ``` -------------------------------- ### Remove npm Temporary Directory for 'Directory Not Empty' Error Source: https://www.codebuff.com/docs/advanced/troubleshooting The 'ENOTEMPTY: directory not empty' error during npm installation indicates a leftover temporary directory. This directory can be safely deleted to resolve the issue. ```bash rm -rf /some/path/to/node_modules/.codebuff-SOMEHASH ``` -------------------------------- ### Clean npm Cache and Reinstall Codebuff Source: https://www.codebuff.com/docs/advanced/troubleshooting If Codebuff is not updating correctly despite npm indicating a successful installation, cleaning the npm cache and reinstalling globally can resolve the issue. This is often caused by a corrupted npm cache. ```bash npm cache clean --force npm install -g codebuff ``` -------------------------------- ### Navigate to Project Directory Source: https://www.codebuff.com/docs/help/quick-start Changes the current directory to your project's root folder. Replace '/path/to/your-repo' with the actual path to your project. ```bash cd /path/to/your-repo ``` -------------------------------- ### Manually Create knowledge.md Source: https://www.codebuff.com/docs/tips/knowledge-files Demonstrates two methods for manually creating a `knowledge.md` file. The first uses the `touch` command to create an empty file, while the second uses Codebuff to generate the file with initial project information. ```bash touch knowledge.md codebuff "Please create a knowledge.md file with initial project information" ``` -------------------------------- ### Define and Run Custom Agents Source: https://www.codebuff.com/docs/advanced/sdk Shows how to define a custom agent using `AgentDefinition` and then run it with `client.run`. Custom agents allow for specialized behavior and tool usage. ```typescript import type { AgentDefinition } from '@codebuff/sdk' const myAgent: AgentDefinition = { id: 'my-custom-agent', model: 'anthropic/claude-sonnet-4.5', displayName: 'My Custom Agent', toolNames: ['read_files', 'write_file'], instructionsPrompt: 'You are a helpful coding assistant.', } await client.run({ agent: 'my-custom-agent', prompt: 'Help me refactor this code', agentDefinitions: [myAgent], }) ``` -------------------------------- ### Create Project-Specific knowledge.md Files Source: https://www.codebuff.com/docs/tips/knowledge-files Illustrates how to create `knowledge.md` files in subdirectories for larger projects. This allows for context-specific knowledge to be kept close to the relevant code, improving organization. ```bash touch backend/knowledge.md frontend/knowledge.md ``` -------------------------------- ### Initialize knowledge.md with Codebuff CLI Source: https://www.codebuff.com/docs/tips/knowledge-files This snippet shows how to use the Codebuff CLI to automatically generate a `knowledge.md` file. The command analyzes the project and populates the file with relevant information such as build commands, project structure, and conventions. ```bash codebuff /init ``` -------------------------------- ### Valid JSON Override Types Source: https://www.codebuff.com/docs/agents/troubleshooting-agent-customization Provides examples of valid `type` values for JSON overrides, such as 'append', 'prepend', and 'replace'. ```json { "systemPrompt": { "type": "append", // ✅ Valid: append, prepend, replace "content": "..." } } ``` -------------------------------- ### CodebuffClient Initialization Source: https://www.codebuff.com/docs/advanced/sdk Initialize the `CodebuffClient` with your API key and optional working directory. ```APIDOC ### `CodebuffClient` ```typescript const client = new CodebuffClient({ apiKey: string, // Required: Your Codebuff API key cwd?: string, // Working directory for file operations }) ``` ``` -------------------------------- ### Invalid Spawnable Agent Error Example Source: https://www.codebuff.com/docs/agents/troubleshooting-agent-customization Shows the 'Invalid spawnable agent' error, which happens when an agent ID listed in `spawnableAgents` does not exist or is misspelled. ```text Validation error: spawnableAgents contains invalid agent 'researcher-typo' ``` -------------------------------- ### client.run(options) Parameters Source: https://www.codebuff.com/docs/advanced/sdk Lists the parameters available for the `client.run` method, including agent, prompt, event handling, previous run state, and custom definitions. ```typescript agent| string| Agent ID from the store or custom agent ID prompt| string| The user prompt params| object| Additional parameters for the agent handleEvent| function| Callback for streaming events previousRun| RunState| Previous run state to continue conversation projectFiles| object| Project files as { path: content } knowledgeFiles| object| Knowledge files to inject into context agentDefinitions| array| Custom agent definitions customToolDefinitions| array| Custom tool definitions maxAgentSteps| number| Maximum steps before stopping (default: ~20) ``` -------------------------------- ### Create Global knowledge.md File Source: https://www.codebuff.com/docs/tips/knowledge-files Shows the command to create a global knowledge file (`~/.knowledge.md`) in the user's home directory. This file is used for personal preferences and settings that apply across all projects. ```bash touch ~/.knowledge.md ``` -------------------------------- ### Check Codebuff Startup Logs Source: https://www.codebuff.com/docs/agents/troubleshooting-agent-customization Instructs the user to run the `codebuff` command and observe the output for any error messages that appear during startup, which can help diagnose issues. ```bash codebuff # Look for error messages on startup ``` -------------------------------- ### Define and Use Custom Tools Source: https://www.codebuff.com/docs/advanced/sdk Illustrates how to create a custom tool using `getCustomToolDefinition` with Zod for schema validation. The custom tool can then be passed to `client.run` for the agent to use. ```typescript import { z } from 'zod/v4' import { getCustomToolDefinition } from '@codebuff/sdk' const fetchTool = getCustomToolDefinition({ toolName: 'fetch_api_data', description: 'Fetch data from an API endpoint', inputSchema: z.object({ url: z.url(), method: z.enum(['GET', 'POST']).default('GET'), }), execute: async ({ url, method }) => { const response = await fetch(url, { method }) const data = await response.text() return [{ type: 'json', value: { data } }] }, }) await client.run({ agent: 'my-custom-agent', prompt: 'Fetch the latest data', customToolDefinitions: [fetchTool], }) ``` -------------------------------- ### Agent Not Found Error Example Source: https://www.codebuff.com/docs/agents/troubleshooting-agent-customization Illustrates the 'Agent not found' error message. This typically occurs due to a typo in the agent ID or incorrect file location. ```text Error: Agent 'my-custom-agent' not found ``` -------------------------------- ### client.run() Method Source: https://www.codebuff.com/docs/advanced/sdk Execute an agent task with various configuration options. ```APIDOC ### `client.run(options)` Parameter| Type| Description ---|---|--- agent| string| Agent ID from the store or custom agent ID prompt| string| The user prompt params| object| Additional parameters for the agent handleEvent| function| Callback for streaming events previousRun| RunState| Previous run state to continue conversation projectFiles| object| Project files as { path: content } knowledgeFiles| object| Knowledge files to inject into context agentDefinitions| array| Custom agent definitions customToolDefinitions| array| Custom tool definitions maxAgentSteps| number| Maximum steps before stopping (default: ~20) ``` -------------------------------- ### Publish Agent Source: https://www.codebuff.com/docs/walkthroughs/creating-your-first-agent Publishes the 'simple-code-reviewer' agent using the Codebuff CLI. This command makes the agent available for use by others, provided it has a publisher ID configured. ```bash codebuff publish simple-code-reviewer ``` -------------------------------- ### Initialize Codebuff Project Settings Source: https://www.codebuff.com/docs/help/quick-start Initializes Codebuff for a specific project by creating configuration files like knowledge.md and setting up agent type definitions. This is useful for new projects or when building custom agents. ```text /init ``` -------------------------------- ### Use Faster Model for Performance Source: https://www.codebuff.com/docs/agents/troubleshooting-agent-customization JSON configuration snippet showing how to select a faster, potentially less powerful model like 'openai/gpt-5-mini' to improve agent response times. ```json { "model": "openai/gpt-5-mini" // Faster model } ``` -------------------------------- ### Fix npm Permissions (Mac/Linux) Source: https://www.codebuff.com/docs/help/quick-start Command to fix potential permission issues when installing Node.js packages globally on macOS or Linux systems. It ensures the current user has ownership of the necessary npm directories. ```bash sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share} ``` -------------------------------- ### Configure Stdio MCP Server (TypeScript) Source: https://www.codebuff.com/docs/agents/mcp-servers Illustrates the configuration structure for running an MCP server as a local process using stdin/stdout. It defines the command, arguments, and environment variables required for the server. ```typescript mcpServers: { serverName: { type: 'stdio', // Optional, defaults to 'stdio' command: string, // Command to run the MCP server args: string[], // Arguments to pass to the command env: { // Environment variables for the server VAR_NAME: string, // Use '$VAR_NAME' to reference environment variables }, }, } ``` -------------------------------- ### Add Publisher ID to Agent Definition Source: https://www.codebuff.com/docs/walkthroughs/creating-your-first-agent Modifies the agent definition to include a publisher ID, which is necessary for publishing the agent. This involves adding the `publisher` field to the `AgentDefinition` object. ```typescript // Add this field to your agent definition const definition: AgentDefinition = { id: 'simple-code-reviewer', displayName: 'Simple Code Reviewer', publisher: 'your-publisher-id', // ← Add this line model: 'anthropic/claude-sonnet-4.5', // ... rest of your definition } ``` -------------------------------- ### Helper Script for tmux Codebuff Automation Source: https://www.codebuff.com/docs/advanced/troubleshooting A helper function `send_to_codebuff` simplifies sending text to a tmux session using bracketed paste mode, ensuring reliable automation of Codebuff commands. ```bash send_to_codebuff() { local session="$1" local text="$2" tmux send-keys -t "$session" $'.\e[200~"$text"\e[201~' } # Usage: send_to_codebuff my-session "fix the bug in main.ts" mux send-keys -t my-session Enter ``` -------------------------------- ### JSON Configuration for Agent Model Selection Source: https://www.codebuff.com/docs/agents/agent-reference Presents a JSON example for configuring the `model` property of an agent. This required field specifies the AI model to be used by the agent, referencing a model string from OpenRouter. ```json { "model": "anthropic/claude-sonnet-4.5" } ``` -------------------------------- ### Environment Variables Source: https://www.codebuff.com/docs/agents/mcp-servers Demonstrates how to reference environment variables within MCP server configurations. ```APIDOC ## Environment Variables Use the `$VAR_NAME` syntax to reference environment variables from your shell. For example: ```typescript env: { NOTION_TOKEN: '$NOTION_TOKEN', API_KEY: '$MY_API_KEY', } ``` This reads `NOTION_TOKEN` and `MY_API_KEY` from your environment and passes them to the MCP server. **Setup:** Add your token to your shell configuration (e.g., `.bashrc`, `.zshrc`): ```bash export NOTION_TOKEN="your-notion-integration-token" ``` Or use a `.env` file in your project root. ``` -------------------------------- ### Use Published Agent Source: https://www.codebuff.com/docs/walkthroughs/creating-your-first-agent Invokes a published agent using the Codebuff CLI, specifying the publisher ID and agent name with version. This allows users to interact with agents that have been published to the Codebuff platform. ```bash codebuff --agent your-publisher-id/simple-code-reviewer@0.0.1 ``` -------------------------------- ### Verify File Permissions (Bash) Source: https://www.codebuff.com/docs/agents/troubleshooting-agent-customization Command to list file details, including permissions, for files within the `.agents/` directory. Useful for diagnosing loading issues. ```bash ls -la .agents/ ```