@codebuff/sdk

中文文档
0.10.7发布于 2026/03/02Apache-2.0TypeScriptESM + CJS构建来源已验证近 30 天下载 4064

Codebuff的官方SDK——AI编码代理和框架

中文使用文档
文档目录11 节
  1. 安装
  2. 先决条件
  3. 使用量
  4. 基本示例
  5. 例2:自定义代理和工具
  6. API 参考
  7. 知识文件
  8. 文件过滤
  9. loadLocalAgents(options)
  10. client.run(options)
  11. 许可证

@ codebuff/ sdk

Codebuff的官方 SDK - AI编码代理和框架

安装

npm install @codebuff/sdk

先决条件

使用量

基本示例

import { CodebuffClient } from '@codebuff/sdk'

async function main() {
  const client = new CodebuffClient({
    // You need to pass in your own API key here.
    // Get one here: https://www.codebuff.com/api-keys
    apiKey: process.env.CODEBUFF_API_KEY,
    cwd: process.cwd(),
  })

  // First run
  const runState1 = await client.run({
    // The agent id. Any agent on the store (https://codebuff.com/store)
    agent: 'codebuff/[email protected]',
    prompt: 'Create a simple calculator class',
    handleEvent: (event) => {
      // All events that happen during the run: agent start/finish, tool calls/results, text responses, errors.
      console.log('Codebuff Event', JSON.stringify(event))
    },
  })

  // Continue the same session with a follow-up
  const runOrError2 = await client.run({
    agent: 'codebuff/[email protected]',
    prompt: 'Add unit tests for the calculator',
    previousRun: runState1, // <-- this is where your next run differs from the previous run
    handleEvent: (event) => {
      console.log('Codebuff Event', JSON.stringify(event))
    },
  })
}

main()

例2:自定义代理和工具

在这里,我们创建一个完整的代理和自定义工具,可以在运行之间被再利用.

import { z } from 'zod/v4'

import { CodebuffClient, getCustomToolDefinition } from '@codebuff/sdk'

import type { AgentDefinition } from '@codebuff/sdk'

async function main() {
  const client = new CodebuffClient({
    // Note: You need to pass in your own API key.
    // Get it here: https://www.codebuff.com/profile?tab=api-keys
    apiKey: process.env.CODEBUFF_API_KEY,
    // Optional directory agent runs from (if applicable).
    cwd: process.cwd(),
  })

  // Define your own custom agents!
  const myCustomAgent: AgentDefinition = {
    id: 'my-custom-agent',
    model: 'x-ai/grok-4-fast',
    displayName: 'Sentiment analyzer',
    toolNames: ['fetch_api_data'], // Defined below!
    instructionsPrompt: `
1. Describe the different sentiments in the given prompt.
2. Score the prompt along the following 5 dimensions:
  happiness, sadness, anger, fear, and surprise.`,
    // ... other AgentDefinition properties
  }

  // And define your own custom tools!
  const myCustomTool = 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'),
      headers: z.record(z.string(), z.string()).optional(),
    }),
    exampleInputs: [{ url: 'https://api.example.com/data', method: 'GET' }],
    execute: async ({ url, method, headers }) => {
      const response = await fetch(url, { method, headers })
      const data = await response.text()
      return [
        {
          type: 'json' as const,
          value: {
            message: `API Response: ${data.slice(0, 5000)}...`,
          },
        },
      ]
    },
  })

  const { output } = await client.run({
    // Run a custom agent by id. Must match an id in the agentDefinitions field below.
    agent: 'my-custom-agent',
    prompt: "Today I'm feeling very happy!",

    // Provide custom agent and tool definitions:
    agentDefinitions: [myCustomAgent],
    customToolDefinitions: [myCustomTool],

    handleEvent: (event) => {
      // All events that happen during the run: agent start/finish, tool calls/results, text responses, errors.
      console.log('Codebuff Event', JSON.stringify(event))
    },
  })

  if (output.type === 'error') {
    console.error(`The run failed:\n${output.message}`)
  } else {
    console.log('The run succeeded with output:', output)
  }
}

main()

API 参考

知识文件

知识文件为代理提供项目背景. SDK自动发现:

  • 项目文件数字 : knowledge.md, (中文(简体) ), AGENTS.md,或 CLAUDE.md 在每个目录中(优先排序)
  • 用户文件数字 : ~/.knowledge.md, (中文(简体) ), ~/.AGENTS.md,或 ~/.CLAUDE.md (对大小写不敏感)

覆盖 knowledgeFiles (替换项目文件)或 userKnowledgeFiles (与主目录文件合并):

await client.run({
  agent: 'codebuff/[email protected]',
  prompt: 'Help me refactor',
  knowledgeFiles: { 'knowledge.md': '# Guidelines\n- Use TypeScript' },
  userKnowledgeFiles: { '~/.knowledge.md': '# Preferences\n- Be concise' },
})

文件过滤

这个 fileFilter 选项控件,用于文件代理可以读取 :

const client = new CodebuffClient({
  apiKey: process.env.CODEBUFF_API_KEY,
  fileFilter: (filePath) => {
    if (filePath === '.env') return { status: 'blocked' }
    if (filePath.endsWith('.env.example')) return { status: 'allow-example' }
    return { status: 'allow' }
  },
})

状态 : 'blocked' (回报) [BLOCKED], (中文(简体) ), 'allow-example' (前缀内容为 [TEMPLATE], (中文(简体) ), 'allow' (正常读取).

默认行为 : 否时 fileFilter 自动进行gitignore检查。 当a fileFilter IS提供,呼叫者拥有所有过滤器.

loadLocalAgents(options)

装入代理定义 .agents 磁盘上的目录 .

import { loadLocalAgents, CodebuffClient } from '@codebuff/sdk'

// Load from default locations (.agents in cwd, parent, or home)
const agents = await loadLocalAgents({ verbose: true })

// Or load from a specific directory
// const agents = await loadLocalAgents({ agentsPath: './my-agents' })

// Or load and validate agents (invalid agents are filtered out)
// const agents = await loadLocalAgents({ validate: true, verbose: true })

// Access source file path for debugging
for (const agent of Object.values(agents)) {
  console.log(`${agent.id} loaded from ${agent._sourceFilePath}`)
}

// Use the loaded agents with client.run()
const client = new CodebuffClient({ apiKey: process.env.CODEBUFF_API_KEY })
const result = await client.run({
  agent: 'my-custom-agent',
  agentDefinitions: Object.values(agents),
  prompt: 'Hello',
})

参数

  • agentsPath (弦,可选): 特定代理目录的路径 。 如果省略,请在 {cwd}/.agents, (中文(简体) ), {cwd}/../.agents,以及 {homedir}/.agents。 。 。 .
  • verbose (布尔,可选): 装入时是否日志出错 。 默认为 false。 。 。 .
  • validate (布尔,可选): 装入后是否验证代理 。 无效代理被过滤出 。 默认为 false。 。 。 .

回返

回返a Promise<LoadedAgents> - 一个 Record<string, LoadedAgentDefinition> 以身份识别的代理定义.

每个 LoadedAgentDefinition 扩展 AgentDefinition 改为:

  • _sourceFilePath (字符串): 代理服务器装入的文件路径

支持的文件类型

  • .ts, (中文(简体) ), .tsx - 类型脚本文件(自动转接)
  • .js, (中文(简体) ), .mjs, (中文(简体) ), .cjs - JavaScript 文件

结束于 .d.ts 或者说 .test.ts 除外.

client.run(options)

运行带有指定选项的代码代理 .

参数

  • agent (字符串,要求): 代理运行。 使用 'base' 默认代理,或指定自定义代理标识(通过 agentDefinitions (第1款).

  • prompt (字符串,要求): 用户提示描述您想要代理人做什么 .

  • params (对象,可选): 代理人的额外参数. 大多数代理都不使用这个,但一些自定义代理除了用户的快取字符串外,还可以取出一个JSON对象作为输入.

  • handleEvent (职能,可选): 执行期间接收每个事件的回调函数(协助消息,工具调用等). 这使得您可以实时流出代理的进度. 将来我们可能会增加一个逐一回电.

  • previousRun (对象,可选):JSON状态从上一个状态返回 run() 电话 用它来继续和代理商对话或会话,保持以前互动的背景.

  • projectFiles (对象,可选): 您工程中的所有文件作为平版 JavaScript 对象 。 键应该是从您当前目录到每个文件的全部路径,而值应该是文件的字符串内容. 示例 { "src/index.ts": "console.log('hi')" }。这有助于 Codebuff 为上下文选择好的源文件。 说明: 此参数先前已命名 allFiles 但已经更名为清晰.

  • knowledgeFiles (对象,可选): 要注入到每个 run() 电话 使用与 projectFiles - 键是文件路径,值是文件内容。 这些文件直接被添加到代理上下文中.

  • agentDefinitions (阵列,可选): 各种自定义代理定义。 每个对象应满足定义代理类型.

  • customToolDefinitions (阵列,可选): 用于扩展代理机能力的自定义工具组合 。 每个工具定义包括一个名称,用于输入验证的Zod schema,以及一个处理器功能. 这些工具可以在执行过程中被代理人调用.

  • maxAgentSteps (数目,可选): 代理在停止前可以采取的最大步骤数 。 用这个作为安全措施 以防你的特工从铁路上下来 一个合理的数字是20左右.

回返

返回“ 成功” 或“ 失败” 对象的约定 .

  • “成功”对象包含 RunState 对象,可以通过 previousRun 要恢复对话的参数.
  • "失败"对象包含 Error 对象为 a name, (中文(简体) ), message,以及 stack 属性.

这个 RunState 对象包含:

  • sessionState: 内部状态将传递至下一轮运行
  • output: 代理输出(文本、错误或其他类型)

许可证

麻省理工学院

版本与发布记录

@codebuff/sdk 共发布 85 个版本,首次发布于 2025/08/06;过去 12 个月发布了 9 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.10.7latest2026/03/028 个月前
0.10.62026/02/158 个月前
0.10.52026/02/099 个月前
0.10.42026/02/079 个月前
0.10.32026/02/079 个月前
0.10.22025/12/1210 个月前

关于 @codebuff/sdk 的常见问题

@codebuff/sdk 是什么?

Codebuff的官方SDK——AI编码代理和框架

如何安装 @codebuff/sdk?

在项目目录运行 npm install @codebuff/sdk,或使用 pnpm add / yarn add / bun add。

@codebuff/sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@codebuff/sdk 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@codebuff/sdk 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@codebuff/sdk 可以商用吗?

@codebuff/sdk 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@codebuff/sdk 的下载量有多少?

根据 npm 官方下载统计,@codebuff/sdk 在 2026/10/10 – 2026/11/08 这 30 天内被下载 4,064 次,日均约 135 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@codebuff/sdk 还在维护吗?

最新版本 0.10.7 发布于 2026/03/02(8 个月前);至今共发布 85 个版本,其中过去 12 个月发布了 9 个;首次发布于 2025/08/06。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。