# Claude Agent SDK - Undocumented & Internal Features

**Version**: 2.0.22

---

## Table of Contents

1. [Deprecated Features](#deprecated-features)
2. [Internal Fields](#internal-fields)
3. [Beta Features](#beta-features)
4. [Hidden Message Types](#hidden-message-types)
5. [Internal Utilities](#internal-utilities)
6. [CLI Implementation Details](#cli-implementation-details)
7. [Environment Variables](#environment-variables)
8. [Undocumented Options](#undocumented-options)
9. [Research Limitations](#research-limitations)

---

## Deprecated Features

### 1. Old Claude Code SDK Entry Point

**Location**: `sdkTypes.d.ts:407-427`

```typescript
/**
 * @deprecated The Claude Code SDK is now the Claude Agent SDK!
 * Please install and use @anthropic-ai/claude-agent-sdk instead.
 * This SDK entrypoint will be going away on October 21.
 * See https://docs.claude.com/en/docs/claude-code/sdk/migration-guide for migration instructions.
 */
export declare function query({
  prompt,
  options,
}: {
  prompt: string | AsyncIterable<SDKUserMessage>;
  options?: Options;
}): Query;
```

**Details**:
- Package was renamed from `@anthropic-ai/claude-code-sdk` to `@anthropic-ai/claude-agent-sdk`
- Old entry point deprecated as of October 21, 2025
- Migration guide available at: https://docs.claude.com/en/docs/claude-code/sdk/migration-guide

**Impact**: 
- Old import paths will stop working after deprecation date
- Users must migrate to new package name

---

## Internal Fields

### 1. isSynthetic (SDKUserMessage)

**Location**: `sdkTypes.d.ts:296-301`

```typescript
/**
 * True if this is a 'synthetic' user message which did not originate from
 * the user directly, but instead was generated by the system.
 */
isSynthetic?: boolean;
```

**Purpose**: 
- Distinguishes system-generated messages from actual user input
- Used internally for message flow control
- Not typically set by SDK users

**Use Cases**:
- System-injected context
- Automatic continuation messages
- Sub-agent communication

### 2. isReplay (SDKUserMessageReplay)

**Location**: `sdkTypes.d.ts:307-312`

```typescript
/**
 * True if this is a replay/acknowledgment of a user message that was already
 * added to the messages array. Used internally to prevent duplicate messages.
 */
isReplay: true;
```

**Purpose**:
- Prevents duplicate message processing
- Used in session resume logic
- Internal deduplication mechanism

### 3. parent_tool_use_id

**Location**: Throughout message types

```typescript
parent_tool_use_id: string | null;
```

**Purpose**:
- Tracks tool call hierarchy
- Used for sub-agent delegation
- Links messages to their triggering tool use

**Hierarchy Example**:
```
User Message (parent_tool_use_id: null)
  └─> Assistant uses "agent" tool (tool_use_id: "abc123")
      └─> Sub-agent message (parent_tool_use_id: "abc123")
          └─> Sub-agent result (parent_tool_use_id: "abc123")
```

---

## Beta Features

### Anthropic SDK Beta Imports

**Location**: `sdkTypes.d.ts:2`

```typescript
import type {
  BetaMessage as APIAssistantMessage,
  BetaUsage as Usage,
  BetaRawMessageStreamEvent as RawMessageStreamEvent
} from '@anthropic-ai/sdk/resources/beta/messages/messages.mjs';
```

**Details**:
- SDK uses **beta** features from Anthropic's official SDK
- Beta message types for assistant responses
- Beta streaming events
- May change without notice as beta features

**Risk**:
- Beta API changes could break SDK functionality
- Future versions may require migration

---

## Hidden Message Types

### 1. SDKHookResponseMessage

**Location**: `sdkTypes.d.ts:382-389`

```typescript
export type SDKHookResponseMessage = SDKMessageBase & {
  type: 'system';
  subtype: 'hook_response';
  hook_name: string;
  hook_event: string;
  stdout: string;
  stderr: string;
  exit_code?: number;
};
```

**Purpose**:
- Reports results from hook execution
- Captures stdout/stderr from hooks
- Provides exit codes for hook scripts

**Not Documented In**:
- Main API reference doesn't list this message type
- Not in official SDK documentation
- Discovered through type definitions

### 2. Permission Denial Tracking

**Location**: `sdkTypes.d.ts:319-323`

```typescript
export type SDKPermissionDenial = {
  tool_name: string;
  tool_use_id: string;
  tool_input: Record<string, unknown>;
};
```

**Purpose**:
- Tracks denied tool uses
- Included in SDKResultMessage
- Useful for debugging permission issues

**Usage**:
```typescript
for await (const message of q) {
  if (message.type === 'result') {
    console.log('Permission denials:', message.permission_denials);
  }
}
```

---

## Internal Utilities

### 1. stdin/stdout Control

**Location**: Implied by CLI architecture

**Details**:
- CLI uses stdin for input streaming
- stdout/stderr separated for output
- Binary JSON-RPC-like protocol over stdio

**Not User-Facing**:
- SDK abstracts this completely
- Users work with AsyncGenerator
- Internal IPC mechanism

### 2. Session Storage

**Location**: Implicit in session management

**Details**:
- Transcript files stored locally
- Session IDs reference transcript files
- Resume/fork uses transcript path

**Location Pattern** (inferred):
```
~/.claude/sessions/<session_id>/transcript.jsonl
```

**Not Documented**:
- Exact storage location
- Transcript format details
- Cleanup policies

---

## CLI Implementation Details

### 1. Minified CLI

**File**: `cli.js` (9.3MB minified)

**Details**:
- Heavily minified single-file bundle
- Contains all dependencies
- Difficult to extract implementation details

**Notable**:
- CLI Version: `2.0.22` (separate from package version 0.1.22)
- Version comment at line 4: `// Version: 2.0.22`
- Recruitment message at line 6: `// Want to see the unminified source? We're hiring!`
- Job link at line 7: `https://job-boards.greenhouse.io/anthropic/jobs/4816199008`

### 2. Bundled with Vendor Dependencies

**ripgrep**: Multi-platform search binaries
- Used by Grep tool for fast content search
- ~24MB across all platforms
- Native binaries for ARM64/x64 on macOS/Linux/Windows
- Includes both `rg` binaries and `ripgrep.node` modules

**JetBrains Plugin**: IDE integration
- 33 JAR files (~12MB total)
- Kotlin-based implementation (v2.1.20)
- Ktor HTTP framework (v3.0.2) for server/client
- Includes kotlinx-coroutines, kotlinx-serialization, and other dependencies

**yoga.wasm**: Layout engine
- Facebook's Flexbox implementation
- 86.6KB WebAssembly (87K on disk)
- Used for TUI layout

---

## Environment Variables

### Documented

```bash
WORKSPACE_ROOT  # Set workspace boundary
CLAUDE_API_KEY  # API key (user/project/org/temporary)
```

### Potentially Undocumented (Inferred)

```bash
# PATH manipulation
PATH  # Extended with node_modules/.bin

# Debugging (possibly)
DEBUG=*  # May enable debug output
NODE_ENV=development  # May affect behavior

# MCP-related (inferred)
MCP_SERVER_<NAME>_URL  # MCP server URLs
```

---

## Undocumented Options

### 1. stderr Callback

**Location**: `sdkTypes.d.ts:259`

```typescript
stderr?: (data: string) => void;
```

**Purpose**: Capture stderr from CLI process

**Usage**:
```typescript
const q = query({
  prompt: 'Hello',
  options: {
    stderr: (data) => console.error('CLI stderr:', data)
  }
});
```

**Not Well Documented**:
- When stderr is emitted
- What kind of data to expect
- Performance implications

### 2. strictMcpConfig

**Location**: `sdkTypes.d.ts:260`

```typescript
strictMcpConfig?: boolean;
```

**Purpose**: Enforce strict MCP configuration validation (inferred)

**Behavior** (inferred):
- `true`: Fail if MCP servers don't connect
- `false`: Continue with available MCP servers
- Default: Likely `false`

**Undocumented**:
- Exact validation behavior
- Error messages
- Impact on execution

### 3. pathToClaudeCodeExecutable

**Location**: `sdkTypes.d.ts` (in Options)

```typescript
pathToClaudeCodeExecutable?: string;
```

**Purpose**: Override CLI executable path

**Use Cases**:
- Development/testing with custom CLI builds
- Using different CLI versions
- Advanced debugging

**Undocumented**:
- Default resolution logic
- Fallback behavior
- Version compatibility checking

### 4. includePartialMessages

**Location**: `sdkTypes.d.ts` (in Options)

```typescript
includePartialMessages?: boolean;
```

**Purpose**: Control whether streaming events are yielded

**Behavior**:
- `true`: Yield SDKPartialAssistantMessage during streaming
- `false`: Only yield complete SDKAssistantMessage
- Default: Likely `false`

**Use Cases**:
- Real-time UI updates
- Progress indicators
- Token-by-token rendering

**Undocumented**:
- Performance impact
- Memory considerations
- Interaction with hooks

---

## Research Limitations

### What We Couldn't Extract

Due to CLI minification, the following remain unclear:

1. **Internal System Prompts**
   - Exact text of main system prompt
   - Agent-specific prompts (explore, security review, etc.)
   - Tool usage guidelines embedded in prompts
   - Context-specific prompt variations

2. **Slash Commands**
   - Complete list of slash commands
   - Command implementations
   - Command parameters and validation
   - Hidden/admin commands

3. **CLI Flags**
   - All command-line flags
   - Flag aliases
   - Flag interactions
   - Debug/development flags

4. **Agent Types**
   - Full list of specialized agents
   - Agent capabilities and restrictions
   - Agent model preferences
   - Agent prompt templates

5. **Error Handling**
   - Internal error types
   - Error recovery strategies
   - Retry logic
   - Error messages

6. **Performance Optimizations**
   - Caching strategies
   - Token management
   - Context compaction logic
   - Streaming optimizations

### How to Extract More

**1. Runtime Analysis**
```bash
# Run CLI with debug flags
npx @anthropic-ai/claude-agent-sdk --debug --help

# Intercept stdio
node -r ./intercept.js $(which claude-agent-sdk)

# Use process inspector
node --inspect-brk $(which claude-agent-sdk)
```

**2. Network Interception**
```bash
# Proxy API calls
mitmproxy -p 8080

# Log all HTTP traffic
export https_proxy=http://localhost:8080
```

**3. Source Code Access**
- Request unminified source from Anthropic
- Contribute to open source (if/when open sourced)
- Hire: https://job-boards.greenhouse.io/anthropic/jobs/4816199008

**4. Type Definitions as Documentation**
- TypeScript definitions are accurate
- Use as source of truth
- Cross-reference with official docs

---

## Internal Implementation Patterns

### 1. Process Architecture

```
SDK Process (your code)
  ↓ (spawn)
CLI Process (cli.js)
  ↓ (stdio JSON-RPC-like protocol)
  ├─ stdin: Commands and prompts
  └─ stdout: JSON messages (SDKMessage types)
```

### 2. Message Flow

```
1. User calls query()
2. SDK spawns CLI subprocess
3. SDK writes to CLI stdin
4. CLI processes and calls Anthropic API
5. CLI writes SDKMessage to stdout
6. SDK yields message from AsyncGenerator
7. Repeat until completion
```

### 3. Hook Execution

```
1. CLI detects hook event
2. CLI sends control request to SDK
3. SDK invokes user's hook callback
4. SDK returns hook result to CLI
5. CLI continues based on hook output
```

---

## Known Gotchas

### 1. Beta API Dependency

**Issue**: SDK depends on Anthropic beta APIs  
**Risk**: Breaking changes without notice  
**Mitigation**: Pin SDK version, test before upgrading

### 2. CLI Subprocess Overhead

**Issue**: Each query() spawns new CLI process  
**Cost**: ~500ms-2s startup time, ~50-100MB memory  
**Mitigation**: Reuse sessions with `resume` option

### 3. Minified CLI Debugging

**Issue**: Stack traces are useless  
**Workaround**: Use TypeScript definitions for API understanding  
**Future**: Hope for source maps or unminified builds

### 4. Permission Denials Silent

**Issue**: Permission denials only visible in result message  
**Impact**: No real-time feedback during execution  
**Workaround**: Use `PreToolUse` hook for early feedback

### 5. Streaming Partial Messages

**Issue**: Partial messages add overhead  
**Cost**: More AsyncGenerator iterations  
**Consideration**: Enable only when needed for UI

---

## Security Considerations

### 1. Subprocess Security

- CLI runs with same permissions as SDK
- Can execute arbitrary bash commands
- Has filesystem access based on `additionalDirectories`
- No sandboxing by default

**Recommendations**:
- Use `permissionMode: 'default'` in production
- Implement `canUseTool` callback for sensitive operations
- Restrict `additionalDirectories` to necessary paths
- Never run untrusted prompts with `bypassPermissions`

### 2. Environment Variable Exposure

- CLI inherits process environment
- Sensitive env vars accessible to tools
- API keys passed via environment

**Recommendations**:
- Use `env` option to control passed variables
- Don't store secrets in environment
- Use temporary API keys when possible

### 3. MCP Server Trust

- MCP servers run in separate processes
- STDIO servers can execute arbitrary code
- HTTP/SSE servers make network requests

**Recommendations**:
- Only use trusted MCP servers
- Review MCP server source code
- Use `strictMcpConfig` for production
- Implement authentication for remote MCP servers

---

## Future Research Directions

### High Priority

1. **Extract System Prompts**
   - De-minify or decompile CLI
   - Runtime interception
   - Request from Anthropic

2. **Document All Slash Commands**
   - Runtime discovery via `supportedCommands()`
   - Test each command
   - Document behavior

3. **Map Agent Types**
   - Discover all built-in agents
   - Document agent capabilities
   - Find agent prompt templates

### Medium Priority

4. **CLI Flag Reference**
   - Complete flag documentation
   - Flag interactions
   - Hidden debug flags

5. **Error Catalog**
   - All error types
   - Error messages
   - Recovery strategies

6. **Performance Tuning**
   - Token optimization
   - Streaming configuration
   - Memory management

### Low Priority

7. **Internal Utilities**
   - Helper functions
   - Validation logic
   - Formatting utilities

8. **Test Coverage**
   - Unit test patterns
   - Integration test examples
   - Mocking strategies

---

## Conclusion

While the SDK provides a comprehensive public API, many implementation details remain hidden due to CLI minification. The TypeScript type definitions are the most reliable source of truth for understanding the SDK's capabilities.

**Key Takeaways**:
1. Trust TypeScript definitions over documentation
2. Beta API dependency introduces risk
3. Many internal fields and utilities exist
4. CLI minification limits prompt extraction
5. Runtime analysis needed for complete understanding

**For Complete Understanding**:
- Monitor SDK releases for changes
- Test behavior with edge cases
- Contribute findings back to community
- Request official documentation for gaps

---

