1822 lines
59 KiB
TypeScript
1822 lines
59 KiB
TypeScript
/**
|
|
* Permission types for MCP server-level control
|
|
*/
|
|
/**
|
|
* Permission level for an MCP server
|
|
* - 'whitelist': All tools from this MCP server are automatically allowed
|
|
* - 'blacklist': All tools from this MCP server are automatically denied
|
|
* - 'ask': Prompt user for each tool usage from this MCP server
|
|
*/
|
|
type MCPServerPermission = 'whitelist' | 'blacklist' | 'ask';
|
|
/**
|
|
* Configuration mapping MCP server names to their permission levels
|
|
*/
|
|
interface MCPServerPermissionConfig {
|
|
[serverName: string]: MCPServerPermission;
|
|
}
|
|
/**
|
|
* Tool-level permission setting
|
|
* - 'allow': Tool is allowed
|
|
* - 'deny': Tool is denied
|
|
* - 'ask': Prompt user when tool is used
|
|
*/
|
|
type ToolPermission$1 = 'allow' | 'deny' | 'ask';
|
|
/**
|
|
* Detailed permission configuration for an MCP server
|
|
*/
|
|
interface MCPServerDetailedPermission {
|
|
/** Default permission for all tools from this server */
|
|
defaultPermission: ToolPermission$1;
|
|
/** Optional tool-specific permissions that override the default */
|
|
tools?: {
|
|
[toolName: string]: ToolPermission$1;
|
|
};
|
|
}
|
|
/**
|
|
* Extended permission configuration supporting both simple and detailed formats
|
|
*/
|
|
type MCPServerPermissionConfigExtended = {
|
|
[serverName: string]: MCPServerPermission | MCPServerDetailedPermission;
|
|
};
|
|
|
|
/**
|
|
* Configuration file types for mcpconfig.json/yaml support
|
|
*/
|
|
|
|
/**
|
|
* Schema version for configuration files
|
|
*/
|
|
type ConfigVersion = '1.0';
|
|
/**
|
|
* Supported configuration file formats
|
|
*/
|
|
type ConfigFormat = 'json' | 'yaml';
|
|
/**
|
|
* MCP server configuration in config file
|
|
*/
|
|
interface MCPServerConfig {
|
|
/** Default permission for all tools from this server */
|
|
defaultPermission: ToolPermission$1;
|
|
/** Optional tool-specific permissions */
|
|
tools?: {
|
|
[toolName: string]: ToolPermission$1;
|
|
};
|
|
}
|
|
/**
|
|
* Global settings in configuration file
|
|
*/
|
|
interface GlobalConfigSettings {
|
|
/** Default permission for all tools */
|
|
defaultToolPermission?: ToolPermission$1;
|
|
/** Permission mode (default, acceptEdits, bypassPermissions) */
|
|
permissionMode?: PermissionMode;
|
|
/** Default model to use */
|
|
model?: string;
|
|
/** Default timeout in milliseconds */
|
|
timeout?: number;
|
|
/** Working directory */
|
|
cwd?: string;
|
|
/** Environment variables */
|
|
env?: Record<string, string>;
|
|
/** Temperature for model responses */
|
|
temperature?: number;
|
|
/** Maximum tokens for model responses */
|
|
maxTokens?: number;
|
|
}
|
|
/**
|
|
* Main configuration file schema for mcpconfig.json
|
|
*/
|
|
interface MCPConfigSchema {
|
|
/** Configuration schema version */
|
|
version: ConfigVersion;
|
|
/** MCP server configurations */
|
|
mcpServers?: {
|
|
[serverName: string]: MCPServerConfig;
|
|
};
|
|
/** Global settings */
|
|
globalSettings?: GlobalConfigSettings;
|
|
/** Tool-level permissions (independent of MCP servers) */
|
|
tools?: {
|
|
allowed?: ToolName[];
|
|
denied?: ToolName[];
|
|
};
|
|
}
|
|
/**
|
|
* Configuration loading options
|
|
*/
|
|
interface ConfigLoadOptions {
|
|
/** Whether to validate the configuration against schema */
|
|
validate?: boolean;
|
|
/** Whether to merge with existing configuration */
|
|
merge?: boolean;
|
|
/** Custom schema for validation */
|
|
schema?: unknown;
|
|
/** Override format detection */
|
|
format?: ConfigFormat;
|
|
/** Use strict YAML parsing (default: true) */
|
|
strict?: boolean;
|
|
}
|
|
|
|
/**
|
|
* Role and persona system types
|
|
*/
|
|
|
|
/**
|
|
* Role definition with comprehensive configuration
|
|
*/
|
|
interface RoleDefinition {
|
|
/** Unique name for the role */
|
|
name: string;
|
|
/** Optional description of the role's purpose */
|
|
description?: string;
|
|
/** Model to use for this role (e.g., 'opus', 'sonnet') */
|
|
model: string;
|
|
/** Permission configuration for the role */
|
|
permissions: {
|
|
/** MCP server-level permissions */
|
|
mcpServers?: MCPServerPermissionConfig;
|
|
/** Tool-level permissions */
|
|
tools?: {
|
|
/** Explicitly allowed tools */
|
|
allowed?: ToolName[];
|
|
/** Explicitly denied tools */
|
|
denied?: ToolName[];
|
|
};
|
|
/** Permission mode for the role */
|
|
mode?: PermissionMode;
|
|
};
|
|
/** Custom prompting template for this role */
|
|
promptingTemplate?: string;
|
|
/** System prompt to prepend to queries */
|
|
systemPrompt?: string;
|
|
/** Context configuration */
|
|
context?: {
|
|
/** Maximum tokens for responses */
|
|
maxTokens?: number;
|
|
/** Temperature for model responses */
|
|
temperature?: number;
|
|
/** Additional context to include */
|
|
additionalContext?: string[];
|
|
};
|
|
/** Parent role to inherit from */
|
|
extends?: string;
|
|
/** Metadata for the role */
|
|
metadata?: {
|
|
/** Role creator */
|
|
author?: string;
|
|
/** Creation date */
|
|
created?: string;
|
|
/** Last modified date */
|
|
modified?: string;
|
|
/** Role version */
|
|
version?: string;
|
|
/** Tags for categorization */
|
|
tags?: string[];
|
|
};
|
|
}
|
|
/**
|
|
* Roles configuration file schema
|
|
*/
|
|
interface RolesConfig {
|
|
/** Configuration schema version */
|
|
version: '1.0';
|
|
/** Role definitions */
|
|
roles: {
|
|
[roleName: string]: Omit<RoleDefinition, 'name'>;
|
|
};
|
|
/** Default role to use if none specified */
|
|
defaultRole?: string;
|
|
}
|
|
/**
|
|
* Role application options
|
|
*/
|
|
interface RoleApplicationOptions {
|
|
/** Whether to override existing settings */
|
|
override?: boolean;
|
|
/** Whether to merge arrays (tools, context) */
|
|
mergeArrays?: boolean;
|
|
/** Whether to apply prompting template */
|
|
applyPrompting?: boolean;
|
|
}
|
|
/**
|
|
* Role validation result
|
|
*/
|
|
interface RoleValidationResult {
|
|
/** Whether the role is valid */
|
|
valid: boolean;
|
|
/** Validation errors if any */
|
|
errors?: string[];
|
|
/** Validation warnings if any */
|
|
warnings?: string[];
|
|
}
|
|
/**
|
|
* Role inheritance chain
|
|
*/
|
|
interface RoleInheritanceChain {
|
|
/** Ordered list of roles from child to parent */
|
|
chain: string[];
|
|
/** Whether the chain has circular dependencies */
|
|
hasCircularDependency: boolean;
|
|
/** Merged role definition */
|
|
merged?: RoleDefinition;
|
|
}
|
|
|
|
/**
|
|
* Base error class to avoid circular dependencies
|
|
*/
|
|
declare class BaseSDKError extends Error {
|
|
constructor(message: string);
|
|
}
|
|
|
|
/**
|
|
* Enhanced error types for better error handling
|
|
*/
|
|
|
|
declare class APIError extends BaseSDKError {
|
|
readonly statusCode?: number | undefined;
|
|
readonly headers?: Record<string, string> | undefined;
|
|
constructor(message: string, statusCode?: number | undefined, headers?: Record<string, string> | undefined);
|
|
}
|
|
declare class RateLimitError extends APIError {
|
|
readonly retryAfter: number;
|
|
readonly limit?: number | undefined;
|
|
readonly remaining?: number | undefined;
|
|
readonly resetAt?: Date | undefined;
|
|
constructor(message: string, retryAfter: number, limit?: number | undefined, remaining?: number | undefined, resetAt?: Date | undefined);
|
|
}
|
|
declare class AuthenticationError extends APIError {
|
|
readonly authMethod?: "oauth" | "cli" | undefined;
|
|
readonly requiredAction?: string | undefined;
|
|
constructor(message: string, authMethod?: "oauth" | "cli" | undefined, requiredAction?: string | undefined);
|
|
}
|
|
declare class ModelNotAvailableError extends APIError {
|
|
readonly model: string;
|
|
readonly availableModels?: string[] | undefined;
|
|
readonly reason?: "not_found" | "access_denied" | "deprecated" | undefined;
|
|
constructor(model: string, availableModels?: string[] | undefined, reason?: "not_found" | "access_denied" | "deprecated" | undefined);
|
|
}
|
|
declare class ContextLengthExceededError extends APIError {
|
|
readonly currentTokens: number;
|
|
readonly maxTokens: number;
|
|
readonly truncationStrategy?: "beginning" | "middle" | "end" | undefined;
|
|
constructor(currentTokens: number, maxTokens: number, truncationStrategy?: "beginning" | "middle" | "end" | undefined);
|
|
}
|
|
declare class PermissionError extends BaseSDKError {
|
|
readonly resource?: string | undefined;
|
|
readonly action?: string | undefined;
|
|
constructor(message: string, resource?: string | undefined, action?: string | undefined);
|
|
}
|
|
declare class ToolPermissionError extends PermissionError {
|
|
readonly tool: string;
|
|
readonly permission: 'allow' | 'deny' | 'ask';
|
|
readonly reason?: string | undefined;
|
|
readonly context?: {
|
|
serverName?: string;
|
|
roleApplied?: string;
|
|
configSource?: "global" | "role" | "query";
|
|
} | undefined;
|
|
constructor(tool: string, permission: 'allow' | 'deny' | 'ask', reason?: string | undefined, context?: {
|
|
serverName?: string;
|
|
roleApplied?: string;
|
|
configSource?: "global" | "role" | "query";
|
|
} | undefined);
|
|
}
|
|
declare class MCPServerPermissionError extends PermissionError {
|
|
readonly serverName: string;
|
|
readonly permission: 'whitelist' | 'blacklist' | 'ask';
|
|
readonly requestedTools?: string[] | undefined;
|
|
constructor(serverName: string, permission: 'whitelist' | 'blacklist' | 'ask', requestedTools?: string[] | undefined);
|
|
}
|
|
declare class NetworkError extends BaseSDKError {
|
|
readonly code?: string | undefined;
|
|
readonly syscall?: string | undefined;
|
|
constructor(message: string, code?: string | undefined, syscall?: string | undefined);
|
|
}
|
|
declare class ConnectionTimeoutError extends NetworkError {
|
|
readonly timeout: number;
|
|
readonly operation?: string | undefined;
|
|
constructor(timeout: number, operation?: string | undefined);
|
|
}
|
|
declare class ConnectionRefusedError extends NetworkError {
|
|
readonly host?: string | undefined;
|
|
readonly port?: number | undefined;
|
|
constructor(host?: string | undefined, port?: number | undefined);
|
|
}
|
|
declare class StreamingError extends BaseSDKError {
|
|
readonly partialData?: unknown | undefined;
|
|
readonly bytesReceived?: number | undefined;
|
|
constructor(message: string, partialData?: unknown | undefined, bytesReceived?: number | undefined);
|
|
}
|
|
declare class StreamAbortedError extends StreamingError {
|
|
readonly reason?: string | undefined;
|
|
readonly abortedAt?: number | undefined;
|
|
constructor(reason?: string | undefined, abortedAt?: number | undefined, partialData?: unknown);
|
|
}
|
|
declare class StreamPausedError extends StreamingError {
|
|
readonly pausedAt: number;
|
|
readonly canResume: boolean;
|
|
constructor(pausedAt: number, canResume?: boolean);
|
|
}
|
|
declare class MaxRetriesExceededError extends BaseSDKError {
|
|
readonly lastError: Error;
|
|
readonly attempts: number;
|
|
readonly totalDelay?: number | undefined;
|
|
constructor(lastError: Error, attempts: number, totalDelay?: number | undefined);
|
|
}
|
|
declare class CircuitOpenError extends BaseSDKError {
|
|
readonly openedAt: Date;
|
|
readonly failureCount: number;
|
|
readonly nextRetryAt?: Date | undefined;
|
|
constructor(openedAt: Date, failureCount: number, nextRetryAt?: Date | undefined);
|
|
}
|
|
declare function isRateLimitError(error: unknown): error is RateLimitError;
|
|
declare function isAuthenticationError(error: unknown): error is AuthenticationError;
|
|
declare function isToolPermissionError(error: unknown): error is ToolPermissionError;
|
|
declare function isStreamAbortedError(error: unknown): error is StreamAbortedError;
|
|
declare function isNetworkError(error: unknown): error is NetworkError;
|
|
declare function isTimeoutError(error: unknown): error is TimeoutError;
|
|
declare function isValidationError(error: unknown): error is ValidationError;
|
|
declare function isAPIError(error: unknown): error is APIError;
|
|
declare function isRetryableError(error: unknown): boolean;
|
|
interface ErrorDetectionPattern {
|
|
pattern: RegExp;
|
|
errorFactory: (match: RegExpMatchArray, output: string) => Error;
|
|
}
|
|
type ErrorType = 'api_error' | 'rate_limit_error' | 'authentication_error' | 'model_not_available_error' | 'context_length_exceeded_error' | 'tool_permission_error' | 'network_error' | 'timeout_error' | 'connection_refused_error' | 'stream_aborted_error' | 'validation_error';
|
|
declare class TimeoutError extends NetworkError {
|
|
constructor(message: string, _timeout?: number);
|
|
}
|
|
declare class ValidationError extends BaseSDKError {
|
|
readonly field?: string | undefined;
|
|
readonly value?: unknown | undefined;
|
|
constructor(message: string, field?: string | undefined, value?: unknown | undefined);
|
|
}
|
|
declare const ErrorDetectionPatterns: Record<ErrorType, RegExp[]>;
|
|
declare const ERROR_PATTERNS: ErrorDetectionPattern[];
|
|
|
|
/**
|
|
* Token-level streaming interfaces for enhanced real-time control
|
|
*/
|
|
|
|
interface TokenChunk {
|
|
/** The token text */
|
|
token: string;
|
|
/** Timestamp when the token was emitted */
|
|
timestamp: number;
|
|
/** Optional metadata about the token */
|
|
metadata?: TokenMetadata;
|
|
}
|
|
interface TokenMetadata {
|
|
/** Message ID this token belongs to */
|
|
messageId?: string;
|
|
/** Block index within the message */
|
|
blockIndex?: number;
|
|
/** Token probability (if available) */
|
|
probability?: number;
|
|
/** Alternative tokens that could have been generated */
|
|
alternativeTokens?: string[];
|
|
/** Token position in the stream */
|
|
position?: number;
|
|
}
|
|
interface StreamController {
|
|
/** Pause the stream */
|
|
pause(): void;
|
|
/** Resume a paused stream */
|
|
resume(): void;
|
|
/** Abort the stream with optional reason */
|
|
abort(reason?: string): void;
|
|
/** Check if stream is paused */
|
|
readonly isPaused: boolean;
|
|
/** Check if stream is aborted */
|
|
readonly isAborted: boolean;
|
|
/** Get abort reason if aborted */
|
|
readonly abortReason?: string;
|
|
}
|
|
type StreamState = 'active' | 'paused' | 'aborted' | 'completed' | 'error';
|
|
interface StreamMetrics {
|
|
/** Total tokens emitted */
|
|
tokensEmitted: number;
|
|
/** Stream duration in milliseconds */
|
|
duration: number;
|
|
/** Current stream state */
|
|
state: StreamState;
|
|
/** Average tokens per second */
|
|
averageTokensPerSecond: number;
|
|
/** Bytes received (if available) */
|
|
bytesReceived?: number;
|
|
/** Last token timestamp */
|
|
lastTokenTime?: number;
|
|
/** Pause count */
|
|
pauseCount?: number;
|
|
/** Total pause duration */
|
|
totalPauseDuration?: number;
|
|
}
|
|
interface StreamOptions {
|
|
/** Model being used (affects tokenization) */
|
|
model?: string;
|
|
/** Buffer size for token history */
|
|
bufferSize?: number;
|
|
/** Enable token probability metadata */
|
|
includeTokenProbabilities?: boolean;
|
|
/** Throttle token emission rate (ms between tokens) */
|
|
throttleMs?: number;
|
|
/** Auto-abort on specific patterns */
|
|
abortPatterns?: RegExp[];
|
|
/** Auto-pause on specific patterns */
|
|
pausePatterns?: RegExp[];
|
|
}
|
|
interface TokenStream {
|
|
/** Async iterator for tokens */
|
|
tokens(): AsyncGenerator<TokenChunk>;
|
|
/** Get the stream controller */
|
|
getController(): StreamController;
|
|
/** Get current snapshot of buffered tokens */
|
|
getSnapshot(): TokenChunk[];
|
|
/** Get stream metrics */
|
|
getMetrics(): StreamMetrics;
|
|
/** Wait for stream completion */
|
|
waitForCompletion(): Promise<void>;
|
|
/** Add event listener */
|
|
on(event: StreamEvent, handler: StreamEventHandler): void;
|
|
/** Remove event listener */
|
|
off(event: StreamEvent, handler: StreamEventHandler): void;
|
|
}
|
|
type StreamEvent = 'token' | 'pause' | 'resume' | 'abort' | 'complete' | 'error' | 'metrics';
|
|
type StreamEventHandler = TokenEventHandler | StateEventHandler | MetricsEventHandler | ErrorEventHandler;
|
|
interface TokenEventHandler {
|
|
(chunk: TokenChunk): void;
|
|
}
|
|
interface StateEventHandler {
|
|
(state: StreamState, reason?: string): void;
|
|
}
|
|
interface MetricsEventHandler {
|
|
(metrics: StreamMetrics): void;
|
|
}
|
|
interface ErrorEventHandler {
|
|
(error: Error): void;
|
|
}
|
|
interface EnhancedStreamController extends StreamController {
|
|
/** Set stream speed multiplier (1.0 = normal, 2.0 = double speed) */
|
|
setSpeed(multiplier: number): void;
|
|
/** Skip to end (abort but mark as completed) */
|
|
skipToEnd(): void;
|
|
/** Rewind to a previous token position */
|
|
rewind(position: number): void;
|
|
/** Fast forward by N tokens */
|
|
fastForward(tokens: number): void;
|
|
}
|
|
interface TokenStreamWithControl {
|
|
/** The token stream */
|
|
stream: TokenStream;
|
|
/** The controller */
|
|
controller: StreamController;
|
|
/** Convenience method to iterate tokens */
|
|
[Symbol.asyncIterator](): AsyncIterator<TokenChunk>;
|
|
}
|
|
interface Tokenizer {
|
|
/** Tokenize text into chunks */
|
|
tokenize(text: string): TokenChunk[];
|
|
/** Estimate token count */
|
|
estimateTokens(text: string): number;
|
|
/** Model name this tokenizer is for */
|
|
readonly model: string;
|
|
}
|
|
interface TokenStreamFactory {
|
|
/** Create a token stream from a message generator */
|
|
fromMessages(messages: AsyncGenerator<Message>, options?: StreamOptions): TokenStream;
|
|
/** Create a token stream from text chunks */
|
|
fromTextChunks(chunks: AsyncGenerator<string>, options?: StreamOptions): TokenStream;
|
|
/** Create a replay stream from recorded tokens */
|
|
fromRecording(tokens: TokenChunk[], options?: StreamOptions): TokenStream;
|
|
}
|
|
|
|
/**
|
|
* Per-call permission interfaces for fine-grained tool control
|
|
*/
|
|
|
|
type ToolPermission = 'allow' | 'deny' | 'ask';
|
|
interface ToolOverrides {
|
|
/** Tools to allow for this specific call */
|
|
allow?: ToolName[];
|
|
/** Tools to deny for this specific call */
|
|
deny?: ToolName[];
|
|
/** Specific permissions per tool */
|
|
permissions?: Record<ToolName, ToolPermission>;
|
|
/** Dynamic permissions based on context */
|
|
dynamicPermissions?: Record<ToolName, DynamicPermissionFunction>;
|
|
}
|
|
type PermissionContext = QueryContext;
|
|
interface QueryContext {
|
|
/** The prompt being executed */
|
|
prompt: string;
|
|
/** The model being used */
|
|
model?: string;
|
|
/** Timestamp of the query */
|
|
timestamp: number;
|
|
/** User-provided metadata */
|
|
metadata?: Record<string, any>;
|
|
/** Current environment */
|
|
environment?: 'development' | 'staging' | 'production';
|
|
/** User role (if applicable) */
|
|
userRole?: string;
|
|
}
|
|
type DynamicPermissionFunction = (context: QueryContext) => ToolPermission | Promise<ToolPermission>;
|
|
interface PermissionResolution {
|
|
/** The tool being resolved */
|
|
tool: ToolName;
|
|
/** The resolved permission */
|
|
permission: ToolPermission;
|
|
/** Source of the permission */
|
|
source: PermissionSource;
|
|
/** Context used for resolution */
|
|
context: PermissionContext;
|
|
/** Optional override that was applied */
|
|
override?: ToolOverrides;
|
|
/** Timestamp of resolution */
|
|
timestamp: number;
|
|
}
|
|
type PermissionSource = 'default' | 'global' | 'role' | 'dynamic' | 'query';
|
|
interface ResolvedPermissions {
|
|
/** Final list of allowed tools */
|
|
allowed: ToolName[];
|
|
/** Final list of denied tools */
|
|
denied: ToolName[];
|
|
/** Source of each permission decision */
|
|
sources?: Record<ToolName, PermissionSource>;
|
|
}
|
|
interface PermissionSourceDetails {
|
|
/** Where the permission came from */
|
|
level: PermissionSource;
|
|
/** The permission value */
|
|
permission: ToolPermission;
|
|
/** Additional context */
|
|
context?: string;
|
|
}
|
|
interface PermissionResolverConfig {
|
|
/** Enable detailed permission tracking */
|
|
trackSources?: boolean;
|
|
/** Default permission when not specified */
|
|
defaultPermission?: ToolPermission;
|
|
/** Strict mode - deny by default */
|
|
strictMode?: boolean;
|
|
}
|
|
type ConflictResolution = 'deny-wins' | 'allow-wins' | 'last-wins' | 'query-wins';
|
|
interface AdvancedPermissionOptions {
|
|
/** How to resolve conflicts between permission levels */
|
|
conflictResolution?: ConflictResolution;
|
|
/** Enable audit logging of permission decisions */
|
|
auditLog?: boolean;
|
|
/** Callback for permission decisions */
|
|
onPermissionDecision?: (tool: ToolName, decision: PermissionDecision) => void;
|
|
}
|
|
interface PermissionDecision {
|
|
/** The tool in question */
|
|
tool: ToolName;
|
|
/** The final decision */
|
|
decision: 'allow' | 'deny';
|
|
/** Reason for the decision */
|
|
reason: string;
|
|
/** All sources that were considered */
|
|
consideredSources: PermissionSourceDetails[];
|
|
/** The winning source */
|
|
winningSource: PermissionSourceDetails;
|
|
/** Query context if available */
|
|
context?: QueryContext;
|
|
}
|
|
|
|
/**
|
|
* Log levels for the logging framework
|
|
*/
|
|
declare enum LogLevel {
|
|
ERROR = 0,
|
|
WARN = 1,
|
|
INFO = 2,
|
|
DEBUG = 3,
|
|
TRACE = 4
|
|
}
|
|
/**
|
|
* Log entry structure
|
|
*/
|
|
interface LogEntry {
|
|
level: LogLevel;
|
|
message: string;
|
|
timestamp: Date;
|
|
context?: Record<string, unknown>;
|
|
error?: Error;
|
|
}
|
|
/**
|
|
* Logger interface for pluggable logging
|
|
*
|
|
* @example
|
|
* ```typescript
|
|
* class CustomLogger implements Logger {
|
|
* log(entry: LogEntry): void {
|
|
* // Send to your logging service
|
|
* }
|
|
* }
|
|
*
|
|
* const result = await claude()
|
|
* .withLogger(new CustomLogger())
|
|
* .query('Hello');
|
|
* ```
|
|
*/
|
|
interface Logger {
|
|
/**
|
|
* Log an entry
|
|
*/
|
|
log(entry: LogEntry): void;
|
|
/**
|
|
* Convenience methods
|
|
*/
|
|
error(message: string, context?: Record<string, unknown>): void;
|
|
warn(message: string, context?: Record<string, unknown>): void;
|
|
info(message: string, context?: Record<string, unknown>): void;
|
|
debug(message: string, context?: Record<string, unknown>): void;
|
|
trace(message: string, context?: Record<string, unknown>): void;
|
|
}
|
|
/**
|
|
* Console logger implementation
|
|
*/
|
|
declare class ConsoleLogger implements Logger {
|
|
private minLevel;
|
|
private prefix;
|
|
constructor(minLevel?: LogLevel, prefix?: string);
|
|
log(entry: LogEntry): void;
|
|
error(message: string, context?: Record<string, unknown>): void;
|
|
warn(message: string, context?: Record<string, unknown>): void;
|
|
info(message: string, context?: Record<string, unknown>): void;
|
|
debug(message: string, context?: Record<string, unknown>): void;
|
|
trace(message: string, context?: Record<string, unknown>): void;
|
|
}
|
|
/**
|
|
* Structured logger that outputs JSON
|
|
*/
|
|
declare class JSONLogger implements Logger {
|
|
private minLevel;
|
|
private output;
|
|
constructor(minLevel?: LogLevel, output?: (json: string) => void);
|
|
log(entry: LogEntry): void;
|
|
error(message: string, context?: Record<string, unknown>): void;
|
|
warn(message: string, context?: Record<string, unknown>): void;
|
|
info(message: string, context?: Record<string, unknown>): void;
|
|
debug(message: string, context?: Record<string, unknown>): void;
|
|
trace(message: string, context?: Record<string, unknown>): void;
|
|
}
|
|
/**
|
|
* Multi-logger that sends logs to multiple loggers
|
|
*/
|
|
declare class MultiLogger implements Logger {
|
|
private loggers;
|
|
constructor(loggers: Logger[]);
|
|
log(entry: LogEntry): void;
|
|
error(message: string, context?: Record<string, unknown>): void;
|
|
warn(message: string, context?: Record<string, unknown>): void;
|
|
info(message: string, context?: Record<string, unknown>): void;
|
|
debug(message: string, context?: Record<string, unknown>): void;
|
|
trace(message: string, context?: Record<string, unknown>): void;
|
|
}
|
|
/**
|
|
* Null logger that discards all logs (useful for testing)
|
|
*/
|
|
declare class NullLogger implements Logger {
|
|
log(_entry: LogEntry): void;
|
|
error(_message: string, _context?: Record<string, any>): void;
|
|
warn(_message: string, _context?: Record<string, any>): void;
|
|
info(_message: string, _context?: Record<string, any>): void;
|
|
debug(_message: string, _context?: Record<string, any>): void;
|
|
trace(_message: string, _context?: Record<string, any>): void;
|
|
}
|
|
|
|
/**
|
|
* OpenTelemetry integration interfaces for observability
|
|
*/
|
|
|
|
interface TelemetryContext {
|
|
/** Trace ID for distributed tracing */
|
|
traceId?: string;
|
|
/** Span ID for the current operation */
|
|
spanId?: string;
|
|
/** Parent span ID */
|
|
parentSpanId?: string;
|
|
/** User ID for attribution */
|
|
userId?: string;
|
|
/** Session ID for grouping */
|
|
sessionId?: string;
|
|
/** Additional baggage */
|
|
baggage?: Record<string, string>;
|
|
}
|
|
type SpanStatus = 'unset' | 'ok' | 'error';
|
|
type SpanKind = 'internal' | 'server' | 'client' | 'producer' | 'consumer';
|
|
interface TelemetrySpan {
|
|
/** End the span */
|
|
end(): void;
|
|
/** Set span status */
|
|
setStatus(status: SpanStatus, message?: string): void;
|
|
/** Add an event to the span */
|
|
addEvent(name: string, attributes?: Record<string, any>): void;
|
|
/** Set an attribute on the span */
|
|
setAttribute(key: string, value: unknown): void;
|
|
/** Set multiple attributes */
|
|
setAttributes(attributes: Record<string, any>): void;
|
|
/** Record an exception */
|
|
recordException(error: Error): void;
|
|
/** Get span context */
|
|
getSpanContext(): TelemetryContext;
|
|
/** Update span name */
|
|
updateName(name: string): void;
|
|
}
|
|
interface TelemetryLogger extends Logger {
|
|
/** Start a new span */
|
|
startSpan(name: string, options?: SpanOptions): TelemetrySpan;
|
|
/** Record a metric */
|
|
recordMetric(name: string, value: number, labels?: Record<string, string>): void;
|
|
/** Set telemetry context */
|
|
setContext(context: TelemetryContext): void;
|
|
/** Get current context */
|
|
getContext(): TelemetryContext | undefined;
|
|
/** Create a child logger with context */
|
|
child(context: TelemetryContext): TelemetryLogger;
|
|
}
|
|
interface SpanOptions {
|
|
/** Parent context */
|
|
parent?: TelemetryContext;
|
|
/** Span kind */
|
|
kind?: SpanKind;
|
|
/** Initial attributes */
|
|
attributes?: Record<string, any>;
|
|
/** Start time (if not now) */
|
|
startTime?: number;
|
|
/** Links to other spans */
|
|
links?: SpanLink[];
|
|
}
|
|
interface SpanLink {
|
|
/** Context of the linked span */
|
|
context: TelemetryContext;
|
|
/** Attributes for the link */
|
|
attributes?: Record<string, any>;
|
|
}
|
|
type MetricType = 'counter' | 'gauge' | 'histogram' | 'summary';
|
|
interface MetricDefinition {
|
|
/** Metric name */
|
|
name: string;
|
|
/** Metric type */
|
|
type: MetricType;
|
|
/** Description */
|
|
description?: string;
|
|
/** Unit of measurement */
|
|
unit?: string;
|
|
/** Value boundaries for histogram */
|
|
boundaries?: number[];
|
|
}
|
|
interface QueryMetrics {
|
|
/** Total number of queries */
|
|
totalQueries: number;
|
|
/** Successful queries */
|
|
successfulQueries: number;
|
|
/** Failed queries */
|
|
failedQueries: number;
|
|
/** Total tokens used */
|
|
totalTokens: number;
|
|
/** Input tokens */
|
|
inputTokens: number;
|
|
/** Output tokens */
|
|
outputTokens: number;
|
|
/** Cache hits */
|
|
cacheHits: number;
|
|
/** Cache misses */
|
|
cacheMisses: number;
|
|
/** Average query duration in ms */
|
|
averageQueryDuration: number;
|
|
/** P95 query duration in ms */
|
|
p95QueryDuration: number;
|
|
/** P99 query duration in ms */
|
|
p99QueryDuration: number;
|
|
}
|
|
interface ToolMetrics {
|
|
/** Tool name */
|
|
tool: string;
|
|
/** Number of executions */
|
|
executionCount: number;
|
|
/** Number of failures */
|
|
failureCount: number;
|
|
/** Average execution time in ms */
|
|
averageExecutionTime: number;
|
|
/** Total execution time in ms */
|
|
totalExecutionTime: number;
|
|
/** Error rate */
|
|
errorRate: number;
|
|
}
|
|
interface TelemetryProvider {
|
|
/** Initialize the provider */
|
|
initialize(config: TelemetryConfig): Promise<void>;
|
|
/** Get a logger instance */
|
|
getLogger(name?: string): TelemetryLogger;
|
|
/** Shutdown the provider */
|
|
shutdown(): Promise<void>;
|
|
/** Force flush all pending data */
|
|
forceFlush(): Promise<void>;
|
|
/** Get query metrics */
|
|
getQueryMetrics(): QueryMetrics;
|
|
/** Get tool metrics */
|
|
getToolMetrics(): Map<string, ToolMetrics>;
|
|
}
|
|
interface TelemetryConfig {
|
|
/** Service name */
|
|
serviceName: string;
|
|
/** Service version */
|
|
serviceVersion?: string;
|
|
/** Environment */
|
|
environment?: string;
|
|
/** General endpoint (can be used for both traces and metrics) */
|
|
endpoint?: string;
|
|
/** Endpoint for traces */
|
|
traceEndpoint?: string;
|
|
/** Endpoint for metrics */
|
|
metricsEndpoint?: string;
|
|
/** Headers for authentication */
|
|
headers?: Record<string, string>;
|
|
/** Export interval in ms */
|
|
exportInterval?: number;
|
|
/** Batch size for export */
|
|
batchSize?: number;
|
|
/** Additional resource attributes */
|
|
resourceAttributes?: Record<string, any>;
|
|
/** Sampling configuration */
|
|
sampling?: SamplingConfig;
|
|
/** Enable auto-instrumentation */
|
|
autoInstrumentation?: boolean;
|
|
}
|
|
interface SamplingConfig {
|
|
/** Sampling strategy */
|
|
strategy: 'always' | 'never' | 'probability' | 'adaptive';
|
|
/** Probability for probability sampling (0-1) */
|
|
probability?: number;
|
|
/** Rate limit for adaptive sampling */
|
|
rateLimit?: number;
|
|
/** Rules for specific operations */
|
|
rules?: SamplingRule[];
|
|
}
|
|
interface SamplingRule {
|
|
/** Operation name pattern */
|
|
operation: string | RegExp;
|
|
/** Sampling probability for this operation */
|
|
probability: number;
|
|
}
|
|
interface TelemetryEvents {
|
|
/** Query lifecycle events */
|
|
query: {
|
|
start: QueryStartEvent;
|
|
end: QueryEndEvent;
|
|
error: QueryErrorEvent;
|
|
};
|
|
/** Tool execution events */
|
|
tool: {
|
|
start: ToolStartEvent;
|
|
end: ToolEndEvent;
|
|
error: ToolErrorEvent;
|
|
};
|
|
/** Stream events */
|
|
stream: {
|
|
start: StreamStartEvent;
|
|
chunk: StreamChunkEvent;
|
|
end: StreamEndEvent;
|
|
abort: StreamAbortEvent;
|
|
};
|
|
}
|
|
interface QueryStartEvent {
|
|
/** Unique query ID */
|
|
queryId: string;
|
|
/** Prompt */
|
|
prompt: string;
|
|
/** Options */
|
|
options: ClaudeCodeOptions;
|
|
/** Timestamp */
|
|
timestamp: number;
|
|
/** Parent context */
|
|
parentContext?: TelemetryContext;
|
|
}
|
|
interface QueryEndEvent {
|
|
/** Query ID */
|
|
queryId: string;
|
|
/** Duration in ms */
|
|
duration: number;
|
|
/** Token usage */
|
|
usage?: {
|
|
input_tokens?: number;
|
|
output_tokens?: number;
|
|
cache_creation_input_tokens?: number;
|
|
cache_read_input_tokens?: number;
|
|
};
|
|
/** Success status */
|
|
success: boolean;
|
|
/** Result summary */
|
|
resultSummary?: string;
|
|
/** Error if failed */
|
|
error?: Error;
|
|
}
|
|
interface QueryErrorEvent {
|
|
/** Query ID */
|
|
queryId: string;
|
|
/** Error */
|
|
error: Error;
|
|
/** Error type */
|
|
errorType: string;
|
|
/** Retry attempt */
|
|
retryAttempt?: number;
|
|
}
|
|
interface ToolStartEvent {
|
|
/** Tool use ID */
|
|
toolUseId: string;
|
|
/** Tool name */
|
|
tool: string;
|
|
/** Tool input */
|
|
input: unknown;
|
|
/** Parent query ID */
|
|
queryId: string;
|
|
/** Timestamp */
|
|
timestamp: number;
|
|
}
|
|
interface ToolEndEvent {
|
|
/** Tool use ID */
|
|
toolUseId: string;
|
|
/** Tool name */
|
|
tool: string;
|
|
/** Duration in ms */
|
|
duration: number;
|
|
/** Success status */
|
|
success: boolean;
|
|
/** Result size in bytes */
|
|
resultSize?: number;
|
|
/** Error if failed */
|
|
error?: Error;
|
|
}
|
|
interface ToolErrorEvent {
|
|
/** Tool use ID */
|
|
toolUseId: string;
|
|
/** Error */
|
|
error: Error;
|
|
/** Error type */
|
|
errorType: string;
|
|
}
|
|
interface StreamStartEvent {
|
|
/** Stream ID */
|
|
streamId: string;
|
|
/** Parent query ID */
|
|
queryId: string;
|
|
/** Expected chunks */
|
|
expectedChunks?: number;
|
|
/** Timestamp */
|
|
timestamp: number;
|
|
}
|
|
interface StreamChunkEvent {
|
|
/** Stream ID */
|
|
streamId: string;
|
|
/** Chunk index */
|
|
chunkIndex: number;
|
|
/** Chunk size in bytes */
|
|
chunkSize: number;
|
|
/** Chunk type */
|
|
chunkType: 'text' | 'tool_use' | 'tool_result';
|
|
}
|
|
interface StreamEndEvent {
|
|
/** Stream ID */
|
|
streamId: string;
|
|
/** Total chunks */
|
|
totalChunks: number;
|
|
/** Total bytes */
|
|
totalBytes: number;
|
|
/** Duration in ms */
|
|
duration: number;
|
|
}
|
|
interface StreamAbortEvent {
|
|
/** Stream ID */
|
|
streamId: string;
|
|
/** Abort reason */
|
|
reason: string;
|
|
/** Chunks received before abort */
|
|
chunksReceived: number;
|
|
}
|
|
declare const BUILTIN_METRICS: Record<string, MetricDefinition>;
|
|
|
|
/**
|
|
* Retry and backoff interfaces for resilient API calls
|
|
*/
|
|
interface RetryOptions {
|
|
/** Maximum number of retry attempts */
|
|
maxAttempts?: number;
|
|
/** Initial delay in milliseconds */
|
|
initialDelay?: number;
|
|
/** Maximum delay in milliseconds */
|
|
maxDelay?: number;
|
|
/** Backoff multiplier */
|
|
multiplier?: number;
|
|
/** Add random jitter to delays */
|
|
jitter?: boolean;
|
|
/** Jitter factor (0-1) */
|
|
jitterFactor?: number;
|
|
/** List of retryable error types */
|
|
retryableErrors?: Array<new (...args: unknown[]) => Error>;
|
|
/** Custom retry predicate */
|
|
shouldRetry?: (error: Error, attempt: number) => boolean;
|
|
/** Callback on each retry attempt */
|
|
onRetry?: (attempt: number, error: Error, nextDelay: number) => void | Promise<void>;
|
|
/** Abort signal for cancellation */
|
|
signal?: AbortSignal;
|
|
/** Timeout for individual attempts */
|
|
attemptTimeout?: number;
|
|
/** Total timeout for all attempts */
|
|
totalTimeout?: number;
|
|
}
|
|
interface RetryResult<T> {
|
|
/** The successful result */
|
|
value: T;
|
|
/** Number of attempts made */
|
|
attempts: number;
|
|
/** Total time spent retrying */
|
|
totalDuration: number;
|
|
/** Errors encountered during retries */
|
|
errors: Error[];
|
|
}
|
|
type BackoffStrategy = 'exponential' | 'linear' | 'constant' | 'fibonacci' | 'polynomial';
|
|
interface AdvancedRetryOptions extends RetryOptions {
|
|
/** Backoff strategy to use */
|
|
strategy?: BackoffStrategy;
|
|
/** Polynomial degree for polynomial backoff */
|
|
polynomialDegree?: number;
|
|
/** Base for exponential backoff */
|
|
exponentialBase?: number;
|
|
/** Rate limiting */
|
|
rateLimit?: RateLimitOptions;
|
|
/** Circuit breaker integration */
|
|
circuitBreaker?: CircuitBreakerOptions;
|
|
}
|
|
interface RateLimitOptions {
|
|
/** Maximum requests per window */
|
|
maxRequests: number;
|
|
/** Time window in milliseconds */
|
|
windowMs: number;
|
|
/** Strategy when rate limited */
|
|
strategy: 'delay' | 'drop' | 'queue';
|
|
/** Maximum queue size for 'queue' strategy */
|
|
maxQueueSize?: number;
|
|
}
|
|
interface CircuitBreakerOptions {
|
|
/** Failure threshold to open circuit */
|
|
failureThreshold: number;
|
|
/** Success threshold to close circuit */
|
|
successThreshold?: number;
|
|
/** Timeout before attempting half-open */
|
|
resetTimeout: number;
|
|
/** Requests allowed in half-open state */
|
|
halfOpenLimit?: number;
|
|
/** Callback when circuit opens */
|
|
onOpen?: (failures: number) => void;
|
|
/** Callback when circuit closes */
|
|
onClose?: () => void;
|
|
/** Callback when circuit enters half-open */
|
|
onHalfOpen?: () => void;
|
|
}
|
|
type CircuitState = 'closed' | 'open' | 'half-open';
|
|
interface CircuitBreaker {
|
|
/** Current state */
|
|
readonly state: CircuitState;
|
|
/** Execute function with circuit breaker */
|
|
execute<T>(fn: () => Promise<T>): Promise<T>;
|
|
/** Reset the circuit breaker */
|
|
reset(): void;
|
|
/** Get circuit statistics */
|
|
getStats(): CircuitBreakerStats;
|
|
}
|
|
interface CircuitBreakerStats {
|
|
/** Current state */
|
|
state: CircuitState;
|
|
/** Total requests */
|
|
totalRequests: number;
|
|
/** Successful requests */
|
|
successfulRequests: number;
|
|
/** Failed requests */
|
|
failedRequests: number;
|
|
/** Consecutive failures */
|
|
consecutiveFailures: number;
|
|
/** Consecutive successes */
|
|
consecutiveSuccesses: number;
|
|
/** Last failure time */
|
|
lastFailureTime?: number;
|
|
/** Last success time */
|
|
lastSuccessTime?: number;
|
|
/** Time circuit opened */
|
|
openedAt?: number;
|
|
/** Next retry time (if open) */
|
|
nextRetryAt?: number;
|
|
}
|
|
interface RetryStrategy {
|
|
/** Calculate next delay */
|
|
calculateDelay(attempt: number, baseDelay: number): number;
|
|
/** Check if should retry */
|
|
shouldRetry(error: Error, attempt: number): boolean;
|
|
/** Reset strategy state */
|
|
reset(): void;
|
|
}
|
|
declare class ExponentialBackoffStrategy implements RetryStrategy {
|
|
private options;
|
|
constructor(options?: {
|
|
multiplier?: number;
|
|
maxDelay?: number;
|
|
jitter?: boolean;
|
|
jitterFactor?: number;
|
|
base?: number;
|
|
});
|
|
calculateDelay(attempt: number, baseDelay: number): number;
|
|
shouldRetry(_error: Error, _attempt: number): boolean;
|
|
reset(): void;
|
|
}
|
|
declare class LinearBackoffStrategy implements RetryStrategy {
|
|
private options;
|
|
constructor(options?: {
|
|
increment?: number;
|
|
maxDelay?: number;
|
|
jitter?: boolean;
|
|
});
|
|
calculateDelay(attempt: number, baseDelay: number): number;
|
|
shouldRetry(_error: Error, _attempt: number): boolean;
|
|
reset(): void;
|
|
}
|
|
declare class FibonacciBackoffStrategy implements RetryStrategy {
|
|
private options;
|
|
private sequence;
|
|
constructor(options?: {
|
|
maxDelay?: number;
|
|
jitter?: boolean;
|
|
});
|
|
calculateDelay(attempt: number, baseDelay: number): number;
|
|
shouldRetry(_error: Error, _attempt: number): boolean;
|
|
reset(): void;
|
|
}
|
|
interface RetryExecutor {
|
|
/** Execute function with retry logic */
|
|
execute<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T>;
|
|
/** Execute with detailed result */
|
|
executeWithResult<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<RetryResult<T>>;
|
|
/** Set default options */
|
|
setDefaults(options: RetryOptions): void;
|
|
/** Get statistics */
|
|
getStats(): RetryExecutorStats;
|
|
/** Reset statistics */
|
|
resetStats(): void;
|
|
}
|
|
interface RetryExecutorStats {
|
|
/** Total executions */
|
|
totalExecutions: number;
|
|
/** Successful on first attempt */
|
|
successfulFirstAttempts: number;
|
|
/** Successful after retry */
|
|
successfulRetries: number;
|
|
/** Failed after all retries */
|
|
totalFailures: number;
|
|
/** Total retry attempts */
|
|
totalRetryAttempts: number;
|
|
/** Average attempts per execution */
|
|
averageAttempts: number;
|
|
/** Maximum attempts for any execution */
|
|
maxAttempts: number;
|
|
}
|
|
declare class RetryUtils {
|
|
/** Default retryable errors */
|
|
static readonly DEFAULT_RETRYABLE_ERRORS: string[];
|
|
/** Check if error is retryable by default */
|
|
static isRetryableError(error: Error): boolean;
|
|
/** Sleep for specified milliseconds */
|
|
static sleep(ms: number): Promise<void>;
|
|
/** Create retry function with defaults */
|
|
static withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): () => Promise<T>;
|
|
}
|
|
declare class SimpleRetryExecutor implements RetryExecutor {
|
|
private defaults;
|
|
private stats;
|
|
execute<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T>;
|
|
executeWithResult<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<RetryResult<T>>;
|
|
setDefaults(options: RetryOptions): void;
|
|
getStats(): RetryExecutorStats;
|
|
resetStats(): void;
|
|
private shouldRetry;
|
|
private calculateDelay;
|
|
private updateStats;
|
|
}
|
|
|
|
type PermissionMode = 'default' | 'acceptEdits' | 'bypassPermissions';
|
|
type ToolName = 'Read' | 'Write' | 'Edit' | 'Bash' | 'Grep' | 'Glob' | 'LS' | 'MultiEdit' | 'NotebookRead' | 'NotebookEdit' | 'WebFetch' | 'TodoRead' | 'TodoWrite' | 'WebSearch' | 'Task' | 'MCPTool';
|
|
interface TextBlock {
|
|
type: 'text';
|
|
text: string;
|
|
}
|
|
interface ToolUseBlock {
|
|
type: 'tool_use';
|
|
id: string;
|
|
name: string;
|
|
input: Record<string, unknown>;
|
|
}
|
|
interface ToolResultBlock {
|
|
type: 'tool_result';
|
|
tool_use_id: string;
|
|
content: string | Array<TextBlock | unknown>;
|
|
is_error?: boolean;
|
|
}
|
|
type ContentBlock = TextBlock | ToolUseBlock | ToolResultBlock;
|
|
interface UserMessage {
|
|
type: 'user';
|
|
content: string;
|
|
session_id?: string;
|
|
}
|
|
interface AssistantMessage {
|
|
type: 'assistant';
|
|
content: ContentBlock[];
|
|
session_id?: string;
|
|
}
|
|
interface SystemMessage {
|
|
type: 'system';
|
|
subtype?: string;
|
|
data?: unknown;
|
|
session_id?: string;
|
|
}
|
|
interface ResultMessage {
|
|
type: 'result';
|
|
subtype?: string;
|
|
content: string;
|
|
session_id?: string;
|
|
usage?: {
|
|
input_tokens?: number;
|
|
output_tokens?: number;
|
|
cache_creation_input_tokens?: number;
|
|
cache_read_input_tokens?: number;
|
|
};
|
|
cost?: {
|
|
input_cost?: number;
|
|
output_cost?: number;
|
|
cache_creation_cost?: number;
|
|
cache_read_cost?: number;
|
|
total_cost?: number;
|
|
};
|
|
}
|
|
type Message = UserMessage | AssistantMessage | SystemMessage | ResultMessage;
|
|
interface MCPServer {
|
|
command: string;
|
|
args?: string[];
|
|
env?: Record<string, string>;
|
|
}
|
|
|
|
interface ClaudeCodeOptions {
|
|
model?: string;
|
|
tools?: ToolName[];
|
|
allowedTools?: ToolName[];
|
|
deniedTools?: ToolName[];
|
|
mcpServers?: MCPServer[];
|
|
permissionMode?: PermissionMode;
|
|
context?: string[];
|
|
maxTokens?: number;
|
|
temperature?: number;
|
|
cwd?: string;
|
|
env?: Record<string, string>;
|
|
timeout?: number;
|
|
debug?: boolean;
|
|
mcpServerPermissions?: MCPServerPermissionConfig;
|
|
configFile?: string;
|
|
role?: string;
|
|
systemPrompt?: string;
|
|
signal?: AbortSignal;
|
|
sessionId?: string;
|
|
addDirectories?: string[];
|
|
}
|
|
interface CLIMessage {
|
|
type: 'message';
|
|
data: Message;
|
|
}
|
|
interface CLIError {
|
|
type: 'error';
|
|
error: {
|
|
message: string;
|
|
code?: string;
|
|
stack?: string;
|
|
};
|
|
}
|
|
interface CLIEnd {
|
|
type: 'end';
|
|
}
|
|
interface CLIAssistantOutput {
|
|
type: 'assistant';
|
|
message: {
|
|
content: ContentBlock[];
|
|
};
|
|
session_id?: string;
|
|
}
|
|
interface CLISystemOutput {
|
|
type: 'system';
|
|
subtype?: string;
|
|
session_id?: string;
|
|
}
|
|
interface CLIResultOutput {
|
|
type: 'result';
|
|
subtype?: string;
|
|
content?: string;
|
|
session_id?: string;
|
|
usage?: {
|
|
input_tokens?: number;
|
|
output_tokens?: number;
|
|
cache_creation_input_tokens?: number;
|
|
cache_read_input_tokens?: number;
|
|
};
|
|
cost?: {
|
|
total_cost_usd?: number;
|
|
};
|
|
}
|
|
interface CLIErrorOutput {
|
|
type: 'error';
|
|
error: {
|
|
message: string;
|
|
code?: string;
|
|
stack?: string;
|
|
};
|
|
}
|
|
type CLIOutput = CLIAssistantOutput | CLISystemOutput | CLIResultOutput | CLIErrorOutput | CLIMessage | CLIError | CLIEnd;
|
|
|
|
declare class ClaudeSDKError extends Error {
|
|
readonly code?: string | undefined;
|
|
constructor(message: string, code?: string | undefined);
|
|
}
|
|
declare class CLIConnectionError extends ClaudeSDKError {
|
|
constructor(message: string);
|
|
}
|
|
declare class CLINotFoundError extends ClaudeSDKError {
|
|
constructor(message?: string);
|
|
}
|
|
declare class ProcessError extends ClaudeSDKError {
|
|
readonly exitCode?: number | null | undefined;
|
|
readonly signal?: (NodeJS.Signals | null) | undefined;
|
|
constructor(message: string, exitCode?: number | null | undefined, signal?: (NodeJS.Signals | null) | undefined);
|
|
}
|
|
declare class AbortError extends ClaudeSDKError {
|
|
constructor(message?: string);
|
|
}
|
|
declare class CLIJSONDecodeError extends ClaudeSDKError {
|
|
readonly rawOutput: string;
|
|
constructor(message: string, rawOutput: string);
|
|
}
|
|
declare class ConfigValidationError extends ClaudeSDKError {
|
|
constructor(message: string);
|
|
}
|
|
|
|
declare function detectErrorType(message: string): ErrorType;
|
|
declare function createTypedError(errorType: ErrorType, message: string, _originalError?: {
|
|
code?: string;
|
|
stack?: string;
|
|
}): Error;
|
|
|
|
type ErrorCategory = 'auth' | 'network' | 'timeout' | 'validation' | 'subprocess' | 'parsing' | 'permission' | 'configuration' | 'unknown';
|
|
interface EnhancedErrorOptions {
|
|
category: ErrorCategory;
|
|
context?: Record<string, unknown>;
|
|
retryable?: boolean;
|
|
resolution?: string;
|
|
helpUrl?: string;
|
|
statusCode?: number;
|
|
cause?: Error;
|
|
}
|
|
/**
|
|
* Type guard to check if an error is an enhanced error
|
|
*/
|
|
declare function isEnhancedError(error: unknown): error is Error & EnhancedErrorOptions;
|
|
/**
|
|
* Check if an error has resolution information
|
|
*/
|
|
declare function hasResolution(error: unknown): boolean;
|
|
|
|
/**
|
|
* Safe environment variable loading for Claude Code SDK
|
|
*
|
|
* IMPORTANT: This module intentionally does NOT load API keys from environment
|
|
* variables to prevent accidental billing charges. API keys must be explicitly
|
|
* provided by the user.
|
|
*/
|
|
|
|
/**
|
|
* Warning message for API key safety
|
|
*/
|
|
declare const API_KEY_SAFETY_WARNING: string;
|
|
|
|
/**
|
|
* Response parser for extracting and transforming Claude messages
|
|
* Provides convenient methods for common parsing patterns
|
|
*
|
|
* @example
|
|
* ```typescript
|
|
* const result = await claude()
|
|
* .query('Create a hello.txt file')
|
|
* .asText(); // Returns just the text content
|
|
*
|
|
* const files = await claude()
|
|
* .query('Read all config files')
|
|
* .findToolResults('Read'); // Returns all Read tool results
|
|
* ```
|
|
*/
|
|
declare class ResponseParser {
|
|
private generator;
|
|
private handlers;
|
|
private logger?;
|
|
private messages;
|
|
private consumed;
|
|
constructor(generator: AsyncGenerator<Message>, handlers?: Array<(message: Message) => void>, logger?: Logger | undefined);
|
|
/**
|
|
* Get all messages as an array (consumes the generator)
|
|
*/
|
|
asArray(): Promise<Message[]>;
|
|
/**
|
|
* Get only the text content from assistant messages
|
|
*/
|
|
asText(): Promise<string>;
|
|
/**
|
|
* Get the final result message content
|
|
*/
|
|
asResult(): Promise<string | null>;
|
|
/**
|
|
* Get all tool uses with their results
|
|
*/
|
|
asToolExecutions(): Promise<ToolExecution[]>;
|
|
/**
|
|
* Find all tool results for a specific tool
|
|
*/
|
|
findToolResults(toolName: string): Promise<unknown[]>;
|
|
/**
|
|
* Get first tool result for a specific tool
|
|
*/
|
|
findToolResult(toolName: string): Promise<unknown | null>;
|
|
/**
|
|
* Extract structured data from the response
|
|
*/
|
|
asJSON<T = unknown>(): Promise<T | null>;
|
|
/**
|
|
* Get usage statistics
|
|
*/
|
|
getUsage(): Promise<UsageStats | null>;
|
|
/**
|
|
* Get the session ID if available
|
|
*/
|
|
getSessionId(): Promise<string | null>;
|
|
/**
|
|
* Stream messages with a callback (doesn't consume for other methods)
|
|
*/
|
|
stream(callback: (message: Message) => void | Promise<void>): Promise<void>;
|
|
/**
|
|
* Wait for completion and return success status
|
|
*/
|
|
succeeded(): Promise<boolean>;
|
|
/**
|
|
* Get all error messages
|
|
*/
|
|
getErrors(): Promise<string[]>;
|
|
/**
|
|
* Transform messages using a custom transformer
|
|
*/
|
|
transform<T>(transformer: (messages: Message[]) => T): Promise<T>;
|
|
/**
|
|
* Consume the generator if not already consumed
|
|
*/
|
|
private consume;
|
|
}
|
|
/**
|
|
* Represents a tool execution with its input and result
|
|
*/
|
|
interface ToolExecution {
|
|
tool: string;
|
|
input: Record<string, unknown>;
|
|
result: unknown;
|
|
isError: boolean;
|
|
}
|
|
/**
|
|
* Usage statistics for a query
|
|
*/
|
|
interface UsageStats {
|
|
inputTokens: number;
|
|
outputTokens: number;
|
|
cacheCreationTokens: number;
|
|
cacheReadTokens: number;
|
|
totalTokens: number;
|
|
totalCost: number;
|
|
}
|
|
|
|
/**
|
|
* Fluent API for building Claude Code queries with chainable methods
|
|
*
|
|
* @example
|
|
* ```typescript
|
|
* const result = await claude()
|
|
* .withModel('opus')
|
|
* .allowTools('Read', 'Write')
|
|
* .skipPermissions()
|
|
* .withTimeout(30000)
|
|
* .onMessage(msg => console.log('Got:', msg.type))
|
|
* .query('Create a README file')
|
|
* .asText();
|
|
* ```
|
|
*/
|
|
declare class QueryBuilder {
|
|
private options;
|
|
private messageHandlers;
|
|
private logger?;
|
|
private permissionManager;
|
|
private configLoader;
|
|
private roleManager;
|
|
private rolePromptingTemplate?;
|
|
private roleTemplateVariables?;
|
|
constructor();
|
|
/**
|
|
* Set the model to use
|
|
*/
|
|
withModel(model: string): this;
|
|
/**
|
|
* Set allowed tools
|
|
* Use allowTools() with no arguments to enforce read-only mode (denies all tools)
|
|
*/
|
|
allowTools(...tools: ToolName[]): this;
|
|
/**
|
|
* Set denied tools
|
|
*/
|
|
denyTools(...tools: ToolName[]): this;
|
|
/**
|
|
* Set permission mode
|
|
*/
|
|
withPermissions(mode: PermissionMode): this;
|
|
/**
|
|
* Skip all permissions (shorthand for bypassPermissions)
|
|
*/
|
|
skipPermissions(): this;
|
|
/**
|
|
* Accept all edits automatically
|
|
*/
|
|
acceptEdits(): this;
|
|
/**
|
|
* Set working directory
|
|
*/
|
|
inDirectory(cwd: string): this;
|
|
/**
|
|
* Set environment variables
|
|
*/
|
|
withEnv(env: Record<string, string>): this;
|
|
/**
|
|
* Set timeout in milliseconds
|
|
*/
|
|
withTimeout(ms: number): this;
|
|
/**
|
|
* Set AbortSignal for cancellation
|
|
*/
|
|
withSignal(signal: AbortSignal): this;
|
|
/**
|
|
* Set session ID for continuing an existing conversation
|
|
*/
|
|
withSessionId(sessionId: string): this;
|
|
/**
|
|
* Enable debug mode
|
|
*/
|
|
debug(enabled?: boolean): this;
|
|
/**
|
|
* Add MCP servers
|
|
*/
|
|
withMCP(...servers: NonNullable<ClaudeCodeOptions['mcpServers']>): this;
|
|
/**
|
|
* Add directory(-ies) to include in the context
|
|
*/
|
|
addDirectory(directories: string | string[]): this;
|
|
/**
|
|
* Set logger
|
|
*/
|
|
withLogger(logger: Logger): this;
|
|
/**
|
|
* Add message handler
|
|
*/
|
|
onMessage(handler: (message: Message) => void): this;
|
|
/**
|
|
* Add handler for specific message type
|
|
*/
|
|
onAssistant(handler: (content: ContentBlock[]) => void): this;
|
|
/**
|
|
* Add handler for tool usage
|
|
*/
|
|
onToolUse(handler: (tool: {
|
|
name: string;
|
|
input: Record<string, unknown>;
|
|
}) => void): this;
|
|
/**
|
|
* Set MCP server permission
|
|
*/
|
|
withMCPServerPermission(serverName: string, permission: MCPServerPermission): this;
|
|
/**
|
|
* Set multiple MCP server permissions
|
|
*/
|
|
withMCPServerPermissions(permissions: MCPServerPermissionConfig): this;
|
|
/**
|
|
* Load configuration from file
|
|
*/
|
|
withConfigFile(filePath: string): Promise<this>;
|
|
/**
|
|
* Apply configuration object
|
|
*/
|
|
withConfig(config: MCPConfigSchema): this;
|
|
/**
|
|
* Load roles from file
|
|
*/
|
|
withRolesFile(filePath: string): Promise<this>;
|
|
/**
|
|
* Apply a role by name
|
|
*/
|
|
withRole(roleName: string): this;
|
|
/**
|
|
* Apply a role definition directly with template variables
|
|
*/
|
|
withRole(role: RoleDefinition, templateVariables?: Record<string, string>): this;
|
|
/**
|
|
* Apply configuration to options
|
|
*/
|
|
private applyConfig;
|
|
/**
|
|
* Execute query and return response parser
|
|
*/
|
|
query(prompt: string): ResponseParser;
|
|
/**
|
|
* Execute query and return raw async generator (for backward compatibility)
|
|
*/
|
|
queryRaw(prompt: string): AsyncGenerator<Message>;
|
|
/**
|
|
* Static factory method for cleaner syntax
|
|
*/
|
|
static create(): QueryBuilder;
|
|
}
|
|
/**
|
|
* Factory function for creating a new query builder
|
|
*
|
|
* @example
|
|
* ```typescript
|
|
* const response = await claude()
|
|
* .withModel('sonnet')
|
|
* .query('Hello')
|
|
* .asText();
|
|
* ```
|
|
*/
|
|
declare function claude(): QueryBuilder;
|
|
|
|
/**
|
|
* Token-level streaming implementation for Claude SDK
|
|
*/
|
|
|
|
declare class TokenStreamImpl implements TokenStream {
|
|
private controller;
|
|
private snapshot;
|
|
private metrics;
|
|
private messageGenerator;
|
|
private tokenGenerator?;
|
|
private completionPromise;
|
|
private completionResolve?;
|
|
private completionReject?;
|
|
private eventHandlers;
|
|
private startTime;
|
|
constructor(messageGenerator: AsyncGenerator<Message>);
|
|
tokens(): AsyncGenerator<TokenChunk>;
|
|
private createTokenGenerator;
|
|
private tokenizeText;
|
|
private updateMetrics;
|
|
getController(): StreamController;
|
|
getSnapshot(): TokenChunk[];
|
|
getMetrics(): StreamMetrics;
|
|
waitForCompletion(): Promise<void>;
|
|
on(event: StreamEvent, handler: StreamEventHandler): void;
|
|
off(event: StreamEvent, handler: StreamEventHandler): void;
|
|
private emit;
|
|
}
|
|
declare function createTokenStream(messageGenerator: AsyncGenerator<Message>): TokenStream;
|
|
|
|
/**
|
|
* Per-call tool permission implementation
|
|
*/
|
|
|
|
declare class ToolPermissionManager {
|
|
private globalPermissions;
|
|
private rolePermissions;
|
|
private resolutionLog;
|
|
constructor(options: ClaudeCodeOptions, rolePermissions?: Record<ToolName, ToolPermission>);
|
|
private initializeGlobalPermissions;
|
|
/**
|
|
* Resolve permissions for a specific tool with optional overrides
|
|
*/
|
|
resolvePermission(tool: ToolName, context: PermissionContext, overrides?: ToolOverrides): Promise<PermissionResolution>;
|
|
/**
|
|
* Check query-level overrides
|
|
*/
|
|
private checkOverrides;
|
|
/**
|
|
* Check dynamic permissions
|
|
*/
|
|
private checkDynamicPermissions;
|
|
/**
|
|
* Get permission resolution history
|
|
*/
|
|
getResolutionHistory(): PermissionResolution[];
|
|
/**
|
|
* Clear resolution history
|
|
*/
|
|
clearHistory(): void;
|
|
/**
|
|
* Update role permissions
|
|
*/
|
|
updateRolePermissions(permissions: Record<ToolName, ToolPermission>): void;
|
|
/**
|
|
* Check if a tool is allowed with current configuration
|
|
*/
|
|
isToolAllowed(tool: ToolName, context: PermissionContext, overrides?: ToolOverrides): Promise<boolean>;
|
|
/**
|
|
* Get effective permissions for a context
|
|
*/
|
|
getEffectivePermissions(context: PermissionContext, overrides?: ToolOverrides): Promise<Map<ToolName, PermissionResolution>>;
|
|
}
|
|
declare function createPermissionManager(options: ClaudeCodeOptions, rolePermissions?: Record<ToolName, ToolPermission>): ToolPermissionManager;
|
|
|
|
/**
|
|
* Simplified OpenTelemetry provider stub
|
|
*/
|
|
|
|
declare class ClaudeTelemetryProvider implements TelemetryProvider {
|
|
initialize(_config: TelemetryConfig): Promise<void>;
|
|
getLogger(_name?: string): TelemetryLogger;
|
|
shutdown(): Promise<void>;
|
|
forceFlush(): Promise<void>;
|
|
getQueryMetrics(): QueryMetrics;
|
|
getToolMetrics(): Map<string, ToolMetrics>;
|
|
}
|
|
declare function createTelemetryProvider(): TelemetryProvider;
|
|
declare class TelemetryUtils {
|
|
static extractTraceContext(_headers: Record<string, string>): unknown;
|
|
static injectTraceContext(_context: unknown, _headers: Record<string, string>): void;
|
|
static createNoOpProvider(): TelemetryProvider;
|
|
}
|
|
|
|
/**
|
|
* Retry executor implementation with exponential backoff
|
|
*/
|
|
|
|
declare class ClaudeRetryExecutor implements RetryExecutor {
|
|
private defaults;
|
|
private stats;
|
|
private strategy;
|
|
constructor(options?: RetryOptions, strategy?: RetryStrategy);
|
|
execute<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T>;
|
|
executeWithResult<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<RetryResult<T>>;
|
|
setDefaults(options: RetryOptions): void;
|
|
getStats(): RetryExecutorStats;
|
|
resetStats(): void;
|
|
private shouldRetry;
|
|
private sleep;
|
|
private updateStats;
|
|
}
|
|
declare function createRetryExecutor(options?: RetryOptions): RetryExecutor;
|
|
declare function createExponentialRetryExecutor(options?: RetryOptions): RetryExecutor;
|
|
declare function createLinearRetryExecutor(options?: RetryOptions & {
|
|
increment?: number;
|
|
}): RetryExecutor;
|
|
declare function createFibonacciRetryExecutor(options?: RetryOptions): RetryExecutor;
|
|
declare function withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): () => Promise<T>;
|
|
|
|
/**
|
|
* Query Claude Code with a prompt and options.
|
|
*
|
|
* @param prompt - The prompt to send to Claude Code
|
|
* @param options - Configuration options for the query
|
|
* @returns An async iterator that yields messages from Claude Code
|
|
*
|
|
* @example
|
|
* ```typescript
|
|
* import { query } from '@instantlyeasy/claude-code-sdk-ts';
|
|
*
|
|
* for await (const message of query('Create a hello.txt file')) {
|
|
* console.log(message);
|
|
* }
|
|
* ```
|
|
*
|
|
* @example
|
|
* ```typescript
|
|
* import { query, ClaudeCodeOptions } from '@instantlyeasy/claude-code-sdk-ts';
|
|
*
|
|
* const options: ClaudeCodeOptions = {
|
|
* allowedTools: ['Read', 'Write'],
|
|
* permissionMode: 'acceptEdits',
|
|
* cwd: '/Users/me/projects'
|
|
* };
|
|
*
|
|
* for await (const message of query('Analyze this codebase', options)) {
|
|
* if (message.type === 'assistant') {
|
|
* // Handle assistant messages
|
|
* } else if (message.type === 'result') {
|
|
* // Handle final result
|
|
* }
|
|
* }
|
|
* ```
|
|
*/
|
|
declare function query(prompt: string, options?: ClaudeCodeOptions): AsyncGenerator<Message>;
|
|
|
|
export { APIError, API_KEY_SAFETY_WARNING, AbortError, type AdvancedPermissionOptions, type AdvancedRetryOptions, type AssistantMessage, AuthenticationError, BUILTIN_METRICS, type BackoffStrategy, type CLIAssistantOutput, CLIConnectionError, type CLIEnd, type CLIError, type CLIErrorOutput, CLIJSONDecodeError, type CLIMessage, CLINotFoundError, type CLIOutput, type CLIResultOutput, type CLISystemOutput, type CircuitBreaker, type CircuitBreakerOptions, type CircuitBreakerStats, CircuitOpenError, type CircuitState, type ClaudeCodeOptions, ClaudeRetryExecutor, ClaudeSDKError, ClaudeTelemetryProvider, type ConfigFormat, type ConfigLoadOptions, ConfigValidationError, type ConfigVersion, type ConflictResolution, ConnectionRefusedError, ConnectionTimeoutError, ConsoleLogger, type ContentBlock, ContextLengthExceededError, type DynamicPermissionFunction, ERROR_PATTERNS, type EnhancedStreamController, type ErrorDetectionPattern, ErrorDetectionPatterns, type ErrorEventHandler, type ErrorType, ExponentialBackoffStrategy, FibonacciBackoffStrategy, type GlobalConfigSettings, JSONLogger, LinearBackoffStrategy, type LogEntry, LogLevel, type Logger, type MCPConfigSchema, type MCPServer, type MCPServerConfig, type MCPServerDetailedPermission, type MCPServerPermission, type MCPServerPermissionConfig, type MCPServerPermissionConfigExtended, MCPServerPermissionError, MaxRetriesExceededError, type Message, type MetricDefinition, type MetricType, type MetricsEventHandler, ModelNotAvailableError, MultiLogger, NetworkError, NullLogger, type PermissionContext, type PermissionDecision, PermissionError, type PermissionMode, type PermissionResolution, type PermissionResolverConfig, type PermissionSource, type PermissionSourceDetails, ProcessError, QueryBuilder, type QueryContext, type QueryEndEvent, type QueryErrorEvent, type QueryMetrics, type QueryStartEvent, RateLimitError, type RateLimitOptions, type ResolvedPermissions, ResponseParser, type ResultMessage, type RetryExecutor, type RetryExecutorStats, type RetryOptions, type RetryResult, type RetryStrategy, RetryUtils, type RoleApplicationOptions, type RoleDefinition, type RoleInheritanceChain, type RoleValidationResult, type RolesConfig, type SamplingConfig, type SamplingRule, SimpleRetryExecutor, type SpanKind, type SpanLink, type SpanOptions, type SpanStatus, type StateEventHandler, type StreamAbortEvent, StreamAbortedError, type StreamChunkEvent, type StreamController, type StreamEndEvent, type StreamEvent, type StreamEventHandler, type StreamMetrics, type StreamOptions, StreamPausedError, type StreamStartEvent, type StreamState, StreamingError, type SystemMessage, type TelemetryConfig, type TelemetryContext, type TelemetryEvents, type TelemetryLogger, type TelemetryProvider, type TelemetrySpan, TelemetryUtils, type TextBlock, TimeoutError, type TokenChunk, type TokenEventHandler, type TokenMetadata, type TokenStream, type TokenStreamFactory, TokenStreamImpl, type TokenStreamWithControl, type Tokenizer, type ToolEndEvent, type ToolErrorEvent, type ToolExecution, type ToolMetrics, type ToolName, type ToolOverrides, type ToolPermission$1 as ToolPermission, ToolPermissionError, ToolPermissionManager, type ToolResultBlock, type ToolStartEvent, type ToolUseBlock, type UsageStats, type UserMessage, ValidationError, claude, createExponentialRetryExecutor, createFibonacciRetryExecutor, createLinearRetryExecutor, createPermissionManager, createRetryExecutor, createTelemetryProvider, createTokenStream, createTypedError, detectErrorType, hasResolution, isAPIError, isAuthenticationError, isEnhancedError, isNetworkError, isRateLimitError, isRetryableError, isStreamAbortedError, isTimeoutError, isToolPermissionError, isValidationError, query, withRetry };
|