tencent cloud

Quick Start

Download
Focus Mode
Font Size
Last updated: 2026-10-08 10:59:47
AI-Translated
Version Requirements: This document applies to CodeBuddy Agent SDK v0.1.0 and later versions.
Feature Status: The SDK is currently in the Preview stage, and its interfaces and behaviors may be adjusted in future versions.
Important: Environment Isolation
By default, the SDK does not load any file system configuration, including settings.json, CODEBUDDY.md, MCP servers, subagents, slash commands, Rules, and Skills. This is a key difference from using the CLI directly, ensuring that the behavior of SDK applications is fully controlled by code, with predictability and consistency.
To load these configurations, use the settingSources option to explicitly specify them.
CodeBuddy Agent SDK allows you to programmatically control CodeBuddy Agent within your applications. It supports TypeScript/JavaScript and Python, enabling scenarios such as automated task execution, custom permission control, and building AI-driven development tools.

Why Use SDK

CodeBuddy Agent SDK gives you programmatic access to the full capabilities of CodeBuddy, not just through command-line interaction.

Capabilities Beyond the Command Line

Programmatic Control: Embed an AI coding assistant in your applications to enable automated workflows.
Custom Interaction: Build user interfaces and interaction methods that meet your needs.
Batch Processing: Perform batch AI operations on multiple files or projects.
Integrate with Existing Systems: Seamlessly integrate AI capabilities into CI/CD, IDE plugins, or other development tools.

Fine-Grained Control

Permission Control: Implement enterprise-level permission policies through the canUseTool callback.
Behavior Customization: Use the Hook system to intercept and modify Agent behavior.
Resource Limits: Control token consumption, execution time, and cost budgets.
Session Management: Persist and restore conversation context.

Scalability

Custom Agents: Create specialized sub-agents to handle domain-specific tasks.
MCP Integration: Connect custom tools and services.
Multi-Model Support: Flexibly switch between and configure different AI models.

What Can You Build

Development Tool Enhancements

IDE Plugin: Build an intelligent coding assistant for IDEs such as VS Code and JetBrains.
Code Review Tool: Automate code quality checks and security scans.
Documentation Generator: Automatically generate API documentation, README files, and code comments.

Automation Workflows

CI/CD Integration: Perform intelligent code analysis and fixes in the pipeline.
Test Generation: Automatically generate unit tests and integration tests.
Refactoring Assistant: Perform code refactoring and migration tasks in batches.

Enterprise Applications

Internal Developer Platform: Build an enterprise-grade AI coding platform.
Knowledge Base Q&A: An intelligent question-answering system built on the codebase.
Training Tool: An interactive system for programming learning and code review.

Feature Overview

Message Streaming: Receive system messages, assistant responses, and tool call results in real time.
Multi-turn Conversation: Support maintaining conversation context across multiple inference calls.
Session Management: Continue or resume an existing conversation by session ID.
Permission Control: Fine-grained management of tool access permissions.
Hook System: Insert custom logic before and after tool execution.
Custom Agent: Define specialized sub-agents to handle specific tasks.
MCP Integration: Support configuring custom MCP servers to extend functionality.

Installation

TypeScript
Python
npm install @tencent-ai/agent-sdk
# or
yarn add @tencent-ai/agent-sdk
# or
pnpm add @tencent-ai/agent-sdk
uv add codebuddy-agent-sdk
# or
pip install codebuddy-agent-sdk

Environment Requirement

Language
Version Requirement
TypeScript/JavaScript
Node.js >= 18.20
Python
Python >= 3.10

Authentication Configuration

Using Existing Login Credentials

If you have already completed interactive login in the terminal using the codebuddy command, the SDK automatically uses that authentication information, requiring no additional configuration.

Using API Keys

If you are not logged in or need to use different credentials, you can authenticate with an API Key:
export CODEBUDDY_API_KEY="your-api-key"
Obtain an API Key:
Version
Obtaining the Address
Overseas Edition
China Edition
Note:
When using CODEBUDDY_API_KEY, you must correctly configure the CODEBUDDY_INTERNET_ENVIRONMENT environment variable according to your version:
Overseas edition: Not set (default)
China edition: export CODEBUDDY_INTERNET_ENVIRONMENT=internal
iOA edition: export CODEBUDDY_INTERNET_ENVIRONMENT=ioa
Dedicated edition: export CODEBUDDY_INTERNET_ENVIRONMENT=cloudhosted
Self-hosted deployment: export CODEBUDDY_INTERNET_ENVIRONMENT=selfhosted
You can also pass it in your code through the env option:
TypeScript
Python
const q = query({
prompt: '...',
options: {
// Required only for Dedicated edition or self-hosted deployment users. Enter your enterprise service address:
// endpoint: 'https://your-company.copilot.qq.com',
env: {
CODEBUDDY_API_KEY: process.env.MY_API_KEY,
// Required for China edition users:
// CODEBUDDY_INTERNET_ENVIRONMENT: 'internal'
// Required for iOA edition users:
// CODEBUDDY_INTERNET_ENVIRONMENT: 'ioa'
// Required for Dedicated edition users:
// CODEBUDDY_INTERNET_ENVIRONMENT: 'cloudhosted'
// Required for self-hosted deployment users:
// CODEBUDDY_INTERNET_ENVIRONMENT: 'selfhosted'
}
}
});
options = CodeBuddyAgentOptions(
# Required only for Dedicated edition or self-hosted deployment users. Enter your enterprise service address:
# endpoint="https://your-company.copilot.qq.com",
env={
"CODEBUDDY_API_KEY": os.environ.get("MY_API_KEY"),
# Required for China edition users:
# "CODEBUDDY_INTERNET_ENVIRONMENT": "internal"
# Required for iOA edition users:
# "CODEBUDDY_INTERNET_ENVIRONMENT": "ioa"
# Required for Dedicated edition users:
# "CODEBUDDY_INTERNET_ENVIRONMENT": "cloudhosted"
# Required for self-hosted deployment users:
# "CODEBUDDY_INTERNET_ENVIRONMENT": "selfhosted"
}
)

Enterprise Users: OAuth Client Credentials

Currently, only the Client Credentials authorization method is introduced, which is suitable for server-side applications and CI/CD scenarios.
Prerequisites: Enterprise users must purchase CodeBuddy Ultimate before they can use OAuth authentication. For details, see Team Edition - Quick Start.
Enterprise users must first obtain an access token through the OAuth 2.0 Client Credentials flow, and then pass it to the SDK.
Step 1: Create an application to obtain credentials
Refer to Enterprise Developer Quick Start to create an application and obtain the Client ID and Client Secret.
Step 2: Obtain a token and call the SDK
TypeScript
Python
async function getOAuthToken(clientId: string, clientSecret: string): Promise<string> {
const response = await fetch('https://copilot.tencent.com/oauth2/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'client_credentials',
client_id: clientId,
client_secret: clientSecret,
}),
});
const data = await response.json();
return data.access_token;
}

// Obtain a token and call the SDK
const token = await getOAuthToken('your-client-id', 'your-client-secret');

for await (const msg of query({
prompt: 'Hello',
options: {
env: { CODEBUDDY_AUTH_TOKEN: token },
},
})) {
console.log(msg);
}
import httpx
from codebuddy_agent_sdk import query, CodeBuddyAgentOptions

async def get_oauth_token(client_id: str, client_secret: str) -> str:
async with httpx.AsyncClient() as client:
response = await client.post(
"https://copilot.tencent.com/oauth2/token",
data={
"grant_type": "client_credentials",
"client_id": client_id,
"client_secret": client_secret,
},
)
return response.json()["access_token"]

# Obtain a token and call the SDK
token = await get_oauth_token("your-client-id", "your-client-secret")

options = CodeBuddyAgentOptions(
env={"CODEBUDDY_AUTH_TOKEN": token}
)

async for msg in query(prompt="Hello", options=options):
print(msg)
For detailed authentication configuration instructions, see Authentication.

Other Environment Variables

Variable Name
Description
Required
CODEBUDDY_CODE_PATH
CodeBuddy CLI executable file path
Optional
If not set, the SDK automatically attempts to locate the CLI.

Basic Usage

Simple queries

The most basic usage is to send a prompt and process the response:
TypeScript
Python
import { query } from '@tencent-ai/agent-sdk';

async function main() {
const q = query({
prompt: 'Please explain what a recursive function is',
options: {
permissionMode: 'bypassPermissions'
}
});

for await (const message of q) {
if (message.type === 'assistant') {
for (const block of message.message.content) {
if (block.type === 'text') {
console.log(block.text);
}
}
}
}
}

main();
import asyncio
from codebuddy_agent_sdk import query, CodeBuddyAgentOptions
from codebuddy_agent_sdk import AssistantMessage, TextBlock

async def main():
options = CodeBuddyAgentOptions(
permission_mode="bypassPermissions"
)

async for message in query(prompt="Please explain what a recursive function is", options=options):
if isinstance(message, AssistantMessage):
for block in message.content:
if isinstance(block, TextBlock):
print(block.text)

asyncio.run(main())

Extraction Result

After the query is complete, a result message is received, which contains execution statistics:
TypeScript
Python
for await (const message of q) {
if (message.type === 'result') {
if (message.subtype === 'success') {
console.log('Done! Duration:', message.duration_ms, 'ms');
console.log('Cost:', message.total_cost_usd, 'USD');
} else {
console.log('Execution error');
}
}
}
from codebuddy_agent_sdk import ResultMessage

async for message in query(prompt="...", options=options):
if isinstance(message, ResultMessage):
if message.subtype == "success":
print(f"Done! Duration: {message.duration_ms} ms")
print(f"Cost: {message.total_cost_usd} USD")
else:
print("Execution error")

Message Type Handling

The SDK returns multiple types of messages:
TypeScript
Python
for await (const message of q) {
switch (message.type) {
case 'system':
// Session initialization message
console.log('Session ID:', message.session_id);
console.log('Available tools:', message.tools);
break;

case 'assistant':
// AI assistant response
for (const block of message.message.content) {
if (block.type === 'text') {
console.log('[Text]', block.text);
} else if (block.type === 'tool_use') {
console.log('[Tool call]', block.name, block.input);
} else if (block.type === 'tool_result') {
console.log('[Tool result]', block.content);
}
}
break;

case 'result':
// Query completed
console.log('Execution completed. Duration:', message.duration_ms, 'ms');
break;
}
}
from codebuddy_agent_sdk import (
SystemMessage, AssistantMessage, ResultMessage,
TextBlock, ToolUseBlock, ToolResultBlock
)

async for message in query(prompt="...", options=options):
if isinstance(message, SystemMessage):
# Session initialization message
print(f"Session ID: {message.data.get('session_id')}")
print(f"Available tools: {message.data.get('tools')}")

elif isinstance(message, AssistantMessage):
# AI assistant response
for block in message.content:
if isinstance(block, TextBlock):
print(f"[Text] {block.text}")
elif isinstance(block, ToolUseBlock):
print(f"[Tool call] {block.name}: {block.input}")
elif isinstance(block, ToolResultBlock):
print(f"[Tool result] {block.content}")

elif isinstance(message, ResultMessage):
# Query completed
print(f"Execution completed. Duration: {message.duration_ms} ms")

Configuration Option

Permission Mode

Control the permission behavior of tool calls through permissionMode:
Mode
Description
default
Default mode. All operations require confirmation.
acceptEdits
Automatically approves file edits. Bash still requires confirmation.
plan
Planning mode. Only read operations are allowed.
bypassPermissions
Skip all permission checks. Use with caution.
TypeScript
Python
const q = query({
prompt: 'Analyze the project structure',
options: {
permissionMode: 'plan' // Read-only mode
}
});
options = CodeBuddyAgentOptions(
permission_mode="plan" # Read-only mode
)
async for msg in query(prompt="Analyze the project structure", options=options):
pass

Working Directory

Specify the working directory for the Agent:
TypeScript
Python
const q = query({
prompt: 'Read package.json',
options: {
cwd: '/path/to/project'
}
});
options = CodeBuddyAgentOptions(
cwd="/path/to/project"
)

Model Selection

Specify the AI model to use:
TypeScript
Python
const q = query({
prompt: '...',
options: {
model: 'deepseek-v3.1',
fallbackModel: 'deepseek-v3.1'
}
});
options = CodeBuddyAgentOptions(
model="deepseek-v3.1",
fallback_model="deepseek-v3.1"
)

Resource limitations

Limit the execution scope:
TypeScript
Python
const q = query({
prompt: '...',
options: {
maxTurns:20 // Maximum number of conversation turns
}
});
options = CodeBuddyAgentOptions(
max_turns=20, # Maximum number of conversation turns
)

Environment Isolation (settingSources)

Design Philosophy

By default, the SDK does not load any file system configuration, providing a completely clean runtime environment. This is a key difference from using the CLI directly.

Why Is It Designed This Way?

1. Predictability: The behavior of SDK applications is fully controlled by code and is not affected by user or project configuration files.
2. Isolation: Prevents user preferences or project settings from interfering with the logic of SDK applications.
3. Security: Sensitive configurations (such as hooks and permission rules) are not accidentally leaked into the SDK environment.
4. Consistency: Behavior remains consistent when the system is run on different machines.

Default Behavior Comparison

Scenario
Settings
Memory
MCP
Subagent
Commands
Rules
Skills
SDK call (default)
✖ Not loaded
✖ Not loaded
✖ Not loaded
✖ Not loaded
✖ Not loaded
✖ Not loaded
✖ Not loaded
Direct CLI run
✔ Load all
✔ Load all
✔ Load all
✔ Load all
✔ Load all
✔ Load all
✔ Load all
Configuration file location reference:
Configuration Type
User-Level Location
Project-Level Location
Description
Settings
~/.codebuddy/settings.json
.codebuddy/settings.json
Permissions, hooks, Environment Variables, and More
Memory
~/.codebuddy/CODEBUDDY.md
CODEBUDDY.md
Project instructions and context
MCP
~/.codebuddy/.mcp.json
.mcp.json
MCP server configuration
Subagent
~/.codebuddy/agents/
.codebuddy/agents/
Custom subagents
Commands
~/.codebuddy/commands/
.codebuddy/commands/
Custom slash commands
Rules
~/.codebuddy/rules/
.codebuddy/rules/
Modular rule files
Skills
~/.codebuddy/skills/
.codebuddy/skills/
Skills automatically invoked by AI

Explicitly Loading Configurations

To load file system configurations, use settingSources to explicitly specify them:
TypeScript
Python
const q = query({
prompt: '...',
options: {
// Load project configuration (.codebuddy/settings.json, CODEBUDDY.md)
settingSources: ['project'],

// Or load all configurations.
// settingSources: ['user', 'project', 'local']
}
});
options = CodeBuddyAgentOptions(
# Load project configuration
setting_sources=["project"],

# Or load all configurations.
# setting_sources=["user", "project", "local"]
)

Configuration Source Description

Value
Description
Position
'user'
Global user settings
~/.codebuddy/settings.json, ~/.codebuddy/CODEBUDDY.md
'project'
Project-shared settings
.codebuddy/settings.json, CODEBUDDY.md
'local'
Project-local settings
.codebuddy/settings.local.json, CODEBUDDY.local.md

Typical Use Cases

CI/CD environment:
TypeScript
Python
// Load only the project configuration and ignore user and local configurations.
const q = query({
prompt: 'Run tests',
options: {
settingSources: ['project'],
permissionMode: 'bypassPermissions'
}
});
# Load only the project configuration and ignore user and local configurations.
options = CodeBuddyAgentOptions(
setting_sources=["project"],
permission_mode="bypassPermissions"
)
Fully programmatic control:
TypeScript
Python
// Default behavior: Do not load any configuration.
// All behaviors are explicitly defined through options.
const q = query({
prompt: '...',
options: {
agents: { /* Custom agent */ },
mcpServers: { /* Custom MCP */ },
allowedTools: ['Read', 'Grep', 'Glob']
}
});
# Default behavior: Do not load any configuration.
# All behaviors are explicitly defined through options.
options = CodeBuddyAgentOptions(
agents={"reviewer": AgentDefinition(...)},
mcp_servers={"db": {...}},
allowed_tools=["Read", "Grep", "Glob"]
)

Permission Control

canUseTool Callback

Implement fine-grained permission control through the canUseTool callback:
TypeScript
Python
import { query } from '@tencent-ai/agent-sdk';

const q = query({
prompt: 'Analyze the project structure',
options: {
canUseTool: async (toolName, input, options) => {
// Only read-only tools are allowed.
const readOnlyTools = ['Read', 'Glob', 'Grep'];

if (readOnlyTools.includes(toolName)) {
return {
behavior: 'allow',
updatedInput: input
};
}

// Deny other tools.
return {
behavior: 'deny',
message: `Tool ${toolName} is not allowed.`
};
}
}
});
from codebuddy_agent_sdk import (
query, CodeBuddyAgentOptions,
CanUseToolOptions, PermissionResultAllow, PermissionResultDeny
)

async def can_use_tool(
tool_name: str,
input_data: dict,
options: CanUseToolOptions
):
# Only read-only tools are allowed.
read_only_tools = ["Read", "Glob", "Grep"]

if tool_name in read_only_tools:
return PermissionResultAllow(updated_input=input_data)

# Deny other tools.
return PermissionResultDeny(
message=f"Tool {tool_name} is not allowed."
)

options = CodeBuddyAgentOptions(can_use_tool=can_use_tool)

Intercepting Dangerous Operations

Block dangerous commands through permission callbacks:
TypeScript
Python
const dangerousCommands = ['rm -rf', 'sudo', 'chmod 777'];

const q = query({
prompt: 'Clean up temporary files',
options: {
canUseTool: async (toolName, input) => {
if (toolName === 'Bash') {
const command = input.command as string;
for (const dangerous of dangerousCommands) {
if (command.includes(dangerous)) {
return {
behavior: 'deny',
message: `Dangerous command blocked: ${dangerous}`,
interrupt: true // Interrupt the entire session.
};
}
}
}
return { behavior: 'allow', updatedInput: input };
}
}
});
dangerous_commands = ["rm -rf", "sudo", "chmod 777"]

async def can_use_tool(tool_name, input_data, options):
if tool_name == "Bash":
command = input_data.get("command", "")
for dangerous in dangerous_commands:
if dangerous in command:
return PermissionResultDeny(
message=f"Dangerous command blocked: {dangerous}",
interrupt=True # Interrupt the entire session.
)
return PermissionResultAllow(updated_input=input_data)

Multi-Turn Conversation

Using Session/Client APIs

For scenarios that require multi-turn interaction, use the Session (TypeScript) or Client (Python) API:
TypeScript
Python
import { unstable_v2_createSession } from '@tencent-ai/agent-sdk';

async function main() {
const session = unstable_v2_createSession({
model: 'deepseek-v3.1'
});

// First round of conversation
await session.send('Analyze the architecture of this project');
for await (const message of session.stream()) {
console.log(message);
}

// Second round of conversation (maintain context)
await session.send('Please explain the third point in detail');
for await (const message of session.stream()) {
console.log(message);
}

session.close();
}
import { unstable_v2_createSession } from '@tencent-ai/agent-sdk';

async function main() {
const session = unstable_v2_createSession({
model: 'deepseek-v3.1'
});

// First round of conversation
await session.send('Analyze the architecture of this project');
for await (const message of session.stream()) {
console.log(message);
}

// Second round of conversation (maintain context)
await session.send('Please explain the third point in detail');
for await (const message of session.stream()) {
console.log(message);
}

session.close();
}

Interrupting Execution

To interrupt execution during runtime:
TypeScript
Python
const q = query({ prompt: 'Execute a long-running task...' });

let count = 0;
for await (const message of q) {
if (message.type === 'assistant') {
for (const block of message.message.content) {
if (block.type === 'tool_use') {
count++;
if (count >= 10) {
await q.interrupt(); // Interrupt execution
break;
}
}
}
}
}
async with CodeBuddySDKClient(options=options) as client:
await client.query("Execute a long-running task...")

count = 0
async for message in client.receive_messages():
if isinstance(message, AssistantMessage):
for block in message.content:
if isinstance(block, ToolUseBlock):
count += 1
if count >= 10:
await client.interrupt() # Interrupt execution
break

Hook System

Hooks allow you to insert custom logic before and after tool execution.

PreToolUse Hook

Intercept and process before tool execution:
TypeScript
Python
const q = query({
prompt: 'Clean up temporary files',
options: {
hooks: {
PreToolUse: [{
matcher: 'Bash', // Match only the Bash tool
hooks: [
async (input, toolUseId) => {
console.log('About to run the command:', input.command);

// Can prevent execution
if (input.command.includes('rm')) {
return {
decision: 'block',
reason: 'Delete command blocked'
};
}

return { continue: true };
}
]
}]
}
}
});
from codebuddy_agent_sdk import HookMatcher, HookContext

async def pre_tool_hook(input_data, tool_use_id, context: HookContext):
print(f"About to run the command: {input_data.get('command')}")

# Can prevent execution
if "rm" in input_data.get("command", ""):
return {"continue_": False, "reason": "Delete command blocked"}

return {"continue_": True}

options = CodeBuddyAgentOptions(
hooks={
"PreToolUse": [
HookMatcher(matcher="Bash", hooks=[pre_tool_hook])
]
}
)

Hook Event Types

Event
Trigger Timing
PreToolUse
Before tool execution
PostToolUse
After tool execution succeeds
PostToolUseFailure
After tool execution fails
UserPromptSubmit
When a user submits a prompt
SessionStart
Session start
SessionEnd
Session end
WorktreeCreate
When creating an isolated worktree
WorktreeRemove
When deleting an isolated worktree

Scalability

Custom Agent

Define specialized sub-agents:
TypeScript
Python
const q = query({
prompt: 'Use code-reviewer to review the code',
options: {
agents: {
'code-reviewer': {
description: 'Professional code review assistant',
tools: ['Read', 'Glob', 'Grep'], // Read-only access is allowed.
disallowedTools: ['Bash', 'Write', 'Edit'],
prompt: `You are a code review expert. Please check:
1. Code standards
2. Potential bugs
3. Performance issues
4. Security vulnerabilities`,
model: 'deepseek-v3.1'
}
}
}
});
from codebuddy_agent_sdk import AgentDefinition

options = CodeBuddyAgentOptions(
agents={
"code-reviewer": AgentDefinition(
description="Professional code review assistant",
tools=["Read", "Glob", "Grep"], # Read-only access is allowed.
disallowed_tools=["Bash", "Write", "Edit"],
prompt="""You are a code review expert. Please check:
1. Code standards
2. Potential bugs
3. Performance issues
4. Security vulnerabilities""",
model="deepseek-v3.1"
)
}
)

MCP Server Configuration

Integrate custom MCP servers:
TypeScript
Python
const q = query({
prompt: 'Query the database',
options: {
mcpServers: {
'database': {
type: 'stdio',
command: 'node',
args: ['./mcp-servers/db-server.js'],
env: {
DB_HOST: 'localhost',
DB_PORT: '5432'
}
}
}
}
});
options = CodeBuddyAgentOptions(
mcp_servers={
"database": {
"type": "stdio",
"command": "node",
"args": ["./mcp-servers/db-server.js"],
"env": {
"DB_HOST": "localhost",
"DB_PORT": "5432"
}
}
}
)

Handling AskUserQuestion

The AI may ask the user questions through the AskUserQuestion tool, which can be handled in the permission callback:
TypeScript
Python
const q = query({
prompt: 'Configure the database connection',
options: {
canUseTool: async (toolName, input) => {
if (toolName === 'AskUserQuestion') {
const questions = input.questions as any[];
const answers: Record<string, string> = {};

for (const q of questions) {
console.log(`Question: ${q.question}`);
// You can integrate actual user interaction here
answers[q.question] = q.options[0].label;
}

return {
behavior: 'allow',
updatedInput: { ...input, answers }
};
}
return { behavior: 'allow', updatedInput: input };
}
}
})
async def can_use_tool(tool_name, input_data, options):
if tool_name == "AskUserQuestion":
questions = input_data.get("questions", [])
answers = {}

for q in questions:
print(f"Question: {q['question']}")
# You can integrate actual user interaction here
answers[q["question"]] = q["options"][0]["label"]

return PermissionResultAllow(
updated_input={**input_data, "answers": answers}
)

return PermissionResultAllow(updated_input=input_data)

Error Handling

TypeScript
Python
import { query, AbortError } from '@tencent-ai/agent-sdk';

try {
const q = query({ prompt: '...' });
for await (const message of q) {
// ...
}
} catch (error) {
if (error instanceof AbortError) {
console.log('Operation aborted');
} else {
console.error('An error occurred:', error);
}
}
from codebuddy_agent_sdk import (
query, CodeBuddySDKError,
CLIConnectionError, CLINotFoundError
)

try:
async for message in query(prompt="..."):
pass
except CLINotFoundError as e:
print(f"CLI not found: {e}")
except CLIConnectionError as e:
print(f"Connection failed: {e}")
except CodeBuddySDKError as e:
print(f"SDK error: {e}")

Tips

1. Permission control: Use canUseTool to implement fine-grained permissions in production environments, and avoid using bypassPermissions
2. Resource Limits: Use maxTurns to limit the execution scope and prevent unexpected resource consumption.
3. Error handling: Always handle the error status in the result message.
4. Hook timeout: Set a reasonable timeout for the Hook.

References

TypeScript SDK Reference - Detailed TypeScript API Reference
Python SDK Reference - Detailed Python API Reference
Hook Reference Guide - Detailed Hook Configuration Instructions
MCP Integration - MCP Server Configuration Guide
Sub-Agent System - Detailed Description of Sub-Agents


Help and Support

Was this page helpful?

Help us improve! Rate your documentation experience in 5 mins.

Feedback