Skip to content

TypeScript SDK Reference

Version Requirements: This documentation is for CodeBuddy Agent SDK v0.1.0 and above.

This document provides a complete API reference for the TypeScript SDK. For quick start and usage examples, please refer to SDK Overview.

Table of Contents

Requirements

DependencyVersion Requirement
Node.js>= 18.0.0
TypeScript>= 5.0.0 (Recommended)

Runtime Support:

  • Node.js (Recommended)
  • Bun
  • Deno

Installation

bash
npm install @tencent-ai/agent-sdk

Or use other package managers:

bash
yarn add @tencent-ai/agent-sdk
pnpm add @tencent-ai/agent-sdk

Environment Variables

Variable NameDescriptionRequired
CODEBUDDY_CODE_PATHCodeBuddy CLI executable pathOptional

Authentication Configuration

The SDK supports authentication using existing login credentials, API Key, or OAuth Client Credentials. See SDK Overview - Authentication Configuration for details.

Functions

query()

Main API entry point that creates a query and returns a message stream.

typescript
function query(params: {
  prompt: string | AsyncIterable<UserMessage>;
  options?: Options;
}): Query;

Parameters:

ParameterTypeDescription
promptstring | AsyncIterable<UserMessage>Query prompt or user message stream
optionsOptionsConfiguration options (optional)

Return Value: Query - Interface that extends AsyncGenerator<Message, void>

Query Interface

typescript
interface Query extends AsyncGenerator<Message, void> {
  // Interrupt current execution
  interrupt(): Promise<void>;

  // Dynamically modify permission mode
  setPermissionMode(mode: PermissionMode): Promise<void>;

  // Dynamically modify model
  setModel(model?: string): Promise<void>;

  // Set maximum thinking tokens
  setMaxThinkingTokens(tokens: number | null): Promise<void>;

  // Get supported slash commands
  supportedCommands(): Promise<SlashCommand[]>;

  // Get supported models list
  supportedModels(): Promise<ModelInfo[]>;

  // Get MCP server status
  mcpServerStatus(): Promise<McpServerStatus[]>;

  // Get account information
  accountInfo(): Promise<AccountInfo>;

  // Stream input user messages
  streamInput(stream: AsyncIterable<UserMessage>): Promise<void>;
}

Constants

typescript
// All supported Hook events
const HOOK_EVENTS: readonly [
  'PreToolUse',
  'PostToolUse',
  'PostToolUseFailure',
  'Notification',
  'UserPromptSubmit',
  'SessionStart',
  'SessionEnd',
  'Stop',
  'SubagentStart',
  'SubagentStop',
  'PreCompact',
  'PermissionRequest'
];

// All exit reasons
const EXIT_REASONS: readonly [
  'user_cancelled',
  'tool_error',
  'max_turns',
  'max_budget_usd',
  'completed',
  'interrupted',
  'hook_blocked'
];

Errors

typescript
class AbortError extends Error {
  // Thrown when operation is aborted
}

Unstable V2 API

Warning: The following APIs are experimental and may change in future versions.

unstable_v2_createSession()

Create a new interactive session.

typescript
function unstable_v2_createSession(options: SessionOptions): Session;

unstable_v2_resumeSession()

Resume an existing session.

typescript
function unstable_v2_resumeSession(
  sessionId: string,
  options: SessionOptions
): Session;

unstable_v2_prompt()

Convenience function for single query.

typescript
function unstable_v2_prompt(
  message: string,
  options: SessionOptions
): Promise<Message[]>;

Session Interface

typescript
interface Session {
  // Session ID (available after initialization)
  readonly sessionId: string;

  // Send message
  send(message: string | UserMessage): Promise<void>;

  // Get response stream
  stream(): AsyncGenerator<Message, void>;

  // Close session
  close(): void;

  // Async disposal
  [Symbol.asyncDispose](): Promise<void>;
}

SessionOptions

typescript
type SessionOptions = {
  model: string;
  pathToCodebuddyCode?: string;
  executable?: 'node' | 'bun';
  executableArgs?: string[];
  env?: Record<string, string | undefined>;
  canUseTool?: CanUseTool;
};

Types

Options

Complete configuration options:

FieldTypeDescription
abortControllerAbortControllerUsed to cancel requests
executable'bun' | 'deno' | 'node'Runtime
executableArgsstring[]Runtime arguments
pathToCodebuddyCodestringCLI path
cwdstringWorking directory
additionalDirectoriesstring[]Additional directories
envRecord<string, string | undefined>Environment variables
modelstringSpecify model
fallbackModelstringFallback model
maxThinkingTokensnumberMaximum thinking tokens
allowedToolsstring[]Allowed tools whitelist
disallowedToolsstring[]Disallowed tools blacklist
canUseToolCanUseToolPermission callback function
permissionModePermissionModePermission mode
allowDangerouslySkipPermissionsbooleanAllow skipping permissions
permissionPromptToolNamestringPermission prompt tool name
continuebooleanContinue recent session
resumestringSession ID to resume
resumeSessionAtstringResume at specific message position
persistSessionbooleanPersist session
forkSessionbooleanFork session
agentsRecord<string, AgentDefinition>Custom agents
hooksPartial<Record<HookEvent, HookCallbackMatcher[]>>Hook configuration
outputFormatOutputFormatOutput format
systemPromptstring | { append: string }System prompt
includePartialMessagesbooleanInclude partial messages
maxTurnsnumberMaximum conversation turns
mcpServersRecord<string, McpServerConfig>MCP server configuration
strictMcpConfigbooleanStrict MCP configuration
sandboxSandboxSettingsSandbox settings
settingSourcesSettingSource[]Setting sources, controls which filesystem configurations are loaded. Default: no configurations are loaded

SettingSource

Controls which filesystem locations the SDK loads configurations from.

typescript
type SettingSource = 'user' | 'project' | 'local';
ValueDescriptionLocation
'user'Global user settings~/.codebuddy/settings.json
'project'Project shared settings.codebuddy/settings.json
'local'Project local settings.codebuddy/settings.local.json

Default Behavior: When settingSources is not specified, the SDK does not load any filesystem configurations. This provides a completely clean runtime environment.

typescript
// Default: no configurations loaded (clean environment)
const q = query({ prompt: '...' });

// Load project configuration
const q = query({
  prompt: '...',
  options: { settingSources: ['project'] }
});

// Load all configurations (similar to CLI behavior)
const q = query({
  prompt: '...',
  options: { settingSources: ['user', 'project', 'local'] }
});

PermissionMode

typescript
type PermissionMode =
  | 'default'           // Default mode, all operations require confirmation
  | 'acceptEdits'       // Automatically approve file edits
  | 'bypassPermissions' // Skip all permission checks
  | 'plan'              // Plan mode, read-only operations allowed

PermissionResult

typescript
type PermissionResult =
  | {
      behavior: 'allow';
      updatedInput: Record<string, unknown>;
      updatedPermissions?: PermissionUpdate[];
      toolUseID?: string;
    }
  | {
      behavior: 'deny';
      message: string;
      interrupt?: boolean;
      toolUseID?: string;
    };

CanUseTool

typescript
type CanUseTool = (
  toolName: string,
  input: Record<string, unknown>,
  options: CanUseToolOptions
) => Promise<PermissionResult>;

type CanUseToolOptions = {
  signal: AbortSignal;
  suggestions?: PermissionUpdate[];
  blockedPath?: string;
  decisionReason?: string;
  toolUseID: string;
  agentID?: string;
};

AgentDefinition

typescript
type AgentDefinition = {
  description: string;          // Agent description
  prompt: string;               // System prompt
  tools?: string[];             // Allowed tools
  disallowedTools?: string[];   // Disallowed tools
  model?: string;               // Model to use
};

McpServerConfig

typescript
// Stdio type
type McpStdioServerConfig = {
  type?: 'stdio';
  command: string;
  args?: string[];
  env?: Record<string, string>;
};

// SSE type
type McpSSEServerConfig = {
  type: 'sse';
  url: string;
  headers?: Record<string, string>;
};

// HTTP type
type McpHttpServerConfig = {
  type: 'http';
  url: string;
  headers?: Record<string, string>;
};

type McpServerConfig =
  | McpStdioServerConfig
  | McpSSEServerConfig
  | McpHttpServerConfig;

HookEvent

typescript
type HookEvent =
  | 'PreToolUse'
  | 'PostToolUse'
  | 'PostToolUseFailure'
  | 'Notification'
  | 'UserPromptSubmit'
  | 'SessionStart'
  | 'SessionEnd'
  | 'Stop'
  | 'SubagentStart'
  | 'SubagentStop'
  | 'PreCompact'
  | 'PermissionRequest';

HookCallback

typescript
type HookCallback = (
  input: HookInput,
  toolUseID: string | undefined,
  options: { signal: AbortSignal }
) => Promise<HookJSONOutput>;

interface HookCallbackMatcher {
  matcher?: string;        // Match pattern (supports regex)
  hooks: HookCallback[];   // Callback function list
  timeout?: number;        // Timeout (milliseconds)
}

HookJSONOutput

typescript
// Sync output
type SyncHookJSONOutput = {
  continue?: boolean;
  suppressOutput?: boolean;
  stopReason?: string;
  decision?: 'approve' | 'block';
  systemMessage?: string;
  reason?: string;
  hookSpecificOutput?: Record<string, unknown>;
};

// Async output
type AsyncHookJSONOutput = {
  async: true;
  asyncTimeout?: number;
};

type HookJSONOutput = SyncHookJSONOutput | AsyncHookJSONOutput;

Message Types

Message

Union of all message types:

typescript
type Message =
  | SystemMessage
  | UserMessage
  | AssistantMessage
  | PartialAssistantMessage
  | ResultMessage
  | CompactBoundaryMessage
  | StatusMessage
  | ToolProgressMessage;

SystemMessage

typescript
type SystemMessage = {
  type: 'system';
  subtype: 'init';
  uuid: string;
  session_id: string;
  apiKeySource?: string;
  cwd?: string;
  tools: string[];
  mcp_servers?: Array<{ name: string; status: string }>;
  model: string;
  permissionMode: PermissionMode;
  slash_commands?: string[];
  codebuddy_code_version?: string;
  skills?: string[];
  plugins?: Array<{ name: string; path: string }>;
};

UserMessage

typescript
type UserMessage = {
  type: 'user';
  uuid?: string;
  session_id: string;
  message: {
    role: 'user';
    content: string | ContentBlock[];
  };
  parent_tool_use_id: string | null;
  isSynthetic?: boolean;
  tool_use_result?: unknown;
};

AssistantMessage

typescript
type AssistantMessage = {
  type: 'assistant';
  uuid: string;
  session_id: string;
  message: {
    id: string;
    type: 'message';
    role: 'assistant';
    model: string;
    content: ContentBlock[];
    stop_reason: StopReason | null;
    stop_sequence: string | null;
    usage: Usage;
  };
  parent_tool_use_id: string | null;
  error?: string;
};

ResultMessage

typescript
type ResultMessage =
  | {
      type: 'result';
      subtype: 'success';
      uuid: string;
      session_id: string;
      duration_ms: number;
      duration_api_ms: number;
      is_error: boolean;
      num_turns: number;
      result: string;
      total_cost_usd: number;
      usage: Usage;
      permission_denials: PermissionDenial[];
      structured_output?: unknown;
    }
  | {
      type: 'result';
      subtype: 'error_during_execution' | 'error_max_turns' | 'error_max_budget_usd';
      uuid: string;
      session_id: string;
      duration_ms: number;
      duration_api_ms: number;
      is_error: boolean;
      num_turns: number;
      total_cost_usd: number;
      usage: Usage;
      permission_denials: PermissionDenial[];
      errors?: string[];
    };

ContentBlock

typescript
// Text content block
interface TextContentBlock {
  type: 'text';
  text: string;
}

// Tool use block
interface ToolUseContentBlock {
  type: 'tool_use';
  id: string;
  name: string;
  input: Record<string, unknown>;
}

// Tool result block
interface ToolResultContentBlock {
  type: 'tool_result';
  tool_use_id: string;
  content?: string | ContentBlock[];
  is_error?: boolean;
}

type ContentBlock =
  | TextContentBlock
  | ToolUseContentBlock
  | ToolResultContentBlock;

Usage

typescript
interface Usage {
  input_tokens: number;
  output_tokens: number;
  cache_read_input_tokens?: number | null;
  cache_creation_input_tokens?: number | null;
}

Input Types

AskUserQuestionInput

typescript
interface AskUserQuestionInput {
  // List of questions to ask (1-4 questions)
  questions: AskUserQuestionQuestion[];
  // User answers (collected by permission component)
  answers?: Record<string, string>;
}

AskUserQuestionQuestion

typescript
interface AskUserQuestionQuestion {
  // Complete question text (should end with ?)
  question: string;
  // Short label (max 12 characters)
  header: string;
  // Available options (2-4 options)
  options: AskUserQuestionOption[];
  // Allow multiple selections
  multiSelect: boolean;
}

AskUserQuestionOption

typescript
interface AskUserQuestionOption {
  // Display text (1-5 words)
  label: string;
  // Option description
  description: string;
}

ToolInputMap

typescript
interface ToolInputMap {
  AskUserQuestion: AskUserQuestionInput;
}

type KnownToolName = keyof ToolInputMap;