@ codebuff/ sdk
Codebuff的官方 SDK - AI编码代理和框架
安装
npm install @codebuff/sdk
先决条件
- 创建 Codebuff 账户并获取您的 这里的代码 API 密钥。 。 。 .
使用量
基本示例
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对象为 aname, (中文(简体) ),message,以及stack属性.
这个 RunState 对象包含:
sessionState: 内部状态将传递至下一轮运行output: 代理输出(文本、错误或其他类型)
许可证
麻省理工学院