Skip to main content

Module io

Module io 

Source
Expand description

Core message types for Claude communication.

This module defines the primary message structures used in the Claude protocol:

§Message Flow

  1. Create a ClaudeInput with your query
  2. Send it to Claude via a client
  3. Receive ClaudeOutput messages in response
  4. Handle different output types (System, Assistant, Result)

§Example

use claude_codes::{ClaudeInput, ClaudeOutput};

// Create an input message
let input = ClaudeInput::user_message("Hello, Claude!", uuid::Uuid::new_v4());

// Parse an output message
let json = r#"{"type":"assistant","message":{"role":"assistant","content":[]}}"#;
match ClaudeOutput::parse_json(json) {
    Ok(output) => println!("Got: {}", output.message_type()),
    Err(e) => eprintln!("Parse error: {}", e),
}

Structs§

AnthropicError
API error message from Anthropic.
AnthropicErrorDetails
Details of an Anthropic API error.
ApiRetryMessage
AssistantMessage
Assistant message
AssistantMessageContent
Nested message content for assistant messages
AssistantUsage
Usage information for assistant messages
AuthStatusMessage
BackgroundTaskInfo
BackgroundTasksChangedMessage
CacheCreationDetails
Detailed cache creation information
Citation
A citation attached to a TextBlock, linking generated text back to a source.
CodeChangePublishedMessage
code_change_published system message — the session is now associated with a published code change (a pull/merge request). Fires on creation and whenever the session contributes to an existing one, so bind on every event; re-emission for the same URL is possible and idempotent. Values are scraped from captured command output — treat them as a binding hint and verify against the forge before routing authenticated requests.
CodeExecutionToolResultBlock
Result from server-side code execution.
CommandInfo
CommandLifecycleMessage
command_lifecycle message — the fate of a queued command (slash command or queued user prompt): queued when the inbound message enters the command queue, started when it drains into a turn, then exactly one terminal state (completed, cancelled, or discarded). Commands enqueued without a client-supplied uuid emit no lifecycle events. Not a strict pairing — a terminal state may arrive for a command_uuid that never emitted started, and internally-enqueued commands skip queued.
CommandsChangedMessage
CompactBoundaryMessage
Compact boundary message - marks where context compaction occurred
CompactMetadata
Metadata about context compaction
ContainerUploadBlock
Container file upload content block.
ControlRequest
Control request from CLI (tool permission requests, hooks, etc.)
ControlRequestMessage
Wrapper for outgoing control requests (includes type tag)
ControlRequestProgressMessage
ControlResponse
Control response to CLI
ControlResponseMessage
Wrapper for outgoing control responses (includes type tag)
ConversationResetMessage
DeferredToolUse
Tool use deferred by a terminal result.
ElicitationCompleteMessage
FailedPersistedFile
FallbackBlock
Model fallback content block.
FallbackModel
A model reference inside a FallbackBlock.
FilesPersistedMessage
FrameAudit
The result of auditing a single raw frame for full typed coverage.
GetUsageResponse
Typed payload returned by the CLI get_usage control request.
HookCallbackRequest
Hook callback request
HookProgressMessage
HookResponseMessage
HookStartedMessage
ImageBlock
Image content block (follows Anthropic API structure)
ImageSource
Image source information
InformationalMessage
InitMessage
Init system message data - sent at session start
InitializeRequest
Initialize request (SDK -> CLI)
LocalCommandOutputMessage
McpHttpServerConfig
MCP HTTP server configuration
McpMessageRequest
MCP message request
McpMeta
MCP metadata passed through on user-message wrappers.
McpServerError
An MCP server config entry that failed validation, reported by system init (e.g. a url entry with no type). The affected server is skipped and absent from InitMessage::mcp_servers.
McpSseServerConfig
MCP SSE server configuration
McpStdioServerConfig
MCP stdio server configuration
McpToolResultBlock
MCP tool result content block.
McpToolUseBlock
MCP tool invocation content block.
MemoryPaths
Memory paths reported by system init.
MemoryRecallItem
MemoryRecallMessage
MessageContent
Message content with role
MessageOrigin
Message provenance. The kind field is the stable discriminator; variant specific fields are preserved in extra for forward-compatible access.
MirrorErrorKey
MirrorErrorMessage
ModelRefusalFallbackMessage
ModelRefusalNoFallbackMessage
ModelScopedRateLimit
ModelUsageEntry
Usage and cost for a single model within a session, as found in ResultMessage::model_usage.
NotificationMessage
OveragePeriodUtilization
Spend-cap utilization for an overage billing period.
ParseError
Error type for parsing failures that preserves the raw input.
Permission
A permission to grant for “remember this decision” functionality.
PermissionDenial
A record of a tool permission that was denied during the session.
PermissionDeniedMessage
PermissionRule
A rule within a permission grant.
PermissionSuggestion
A suggested permission for tool approval.
PersistedFile
PluginDiagnostic
Plugin load diagnostic reported by system init.
PluginInfo
Plugin info from the init message
PluginInstallMessage
PreservedMessages
PreservedSegment
PromptSuggestionMessage
RateLimitEvent
Rate limit event from Claude CLI.
RateLimitInfo
Rate limit status information.
ResultMessage
Result message for completed queries
ServerToolUse
Server tool usage information
ServerToolUseBlock
Server-side tool use content block (e.g., web search, code execution).
SessionStateChangedMessage
StatusMessage
Status system message - sent during operations like context compaction
StreamEventMessage
SubagentResult
Token, timing, and tool-use accounting for a completed subagent (Task) run.
SubagentRetry
Retry state carried on a ToolProgressMessage while a subagent API call is retried after an error.
SubagentToolStats
Per-category tool-use counts for a subagent run, from tool_use_result.toolStats.
SubagentUsageRollup
Session-level subagent token rollup — the <subagent_tokens> / <agent_count> line items the Claude CLI renders in its terminal <usage> block.
SummarizeMetadata
Metadata attached when user-visible transcript content summarizes prior messages.
SystemMessage
System message with metadata
TaskNotificationMessage
task_notification system message — emitted once when a background task completes or fails.
TaskPatch
The partial update carried by a TaskUpdatedMessage. Every field is optional because the CLI only sends the keys that changed.
TaskProgressMessage
task_progress system message — emitted periodically as a background agent task executes tools. Not emitted for local_bash tasks.
TaskStartedMessage
task_started system message — emitted once when a background task begins.
TaskUpdatedMessage
task_updated system message — emitted when a background task’s state changes (e.g. transitions to completed). Carries a partial patch of the fields that changed rather than the full task record.
TaskUsage
Cumulative usage statistics for a background task.
TextBlock
Text content block
ThinkingBlock
Thinking content block
ThinkingTokensMessage
thinking_tokens system message — emitted as the model streams extended thinking, reporting the running estimate of thinking tokens consumed.
ToolCaller
Provenance of a ToolUseBlock — identifies who issued the tool call.
ToolPermissionRequest
Tool permission request details
ToolProgressMessage
ToolResultBlock
Tool result content block
ToolResultMeta
Display metadata for a tool_result block carried on the user wrapper.
ToolUseBlock
Tool use content block
ToolUseMeta
Display metadata for a tool-use block carried on the assistant wrapper.
ToolUseSummaryMessage
TranscriptMessage
Raw preserved record for Claude Code transcript-only message types.
UsageBehavior
UsageBehaviors
UsageInfo
Usage information for the request
UsageModelUsage
UsageRateLimitWindow
UsageRateLimits
UsageSession
UserMessage
User message
VcsStateChangedMessage
vcs_state_changed system message — a harness-observed shell command mutated repository state. A cache-invalidation signal, deliberately payload-free beyond classification: consumers re-read state (branch, head, PR status) instead of decoding the event.
WebSearchToolResultBlock
Result from a web search server tool.
WorkerShuttingDownMessage

Enums§

ApiErrorType
Known Anthropic API error types.
ApiKeySource
How the API key was sourced for the session.
AskUserQuestionResponseError
Errors that can occur when building an AskUserQuestion response via ToolPermissionRequest::answer_questions.
AssistantErrorKind
API error category attached to assistant wrapper frames.
ClaudeInput
Top-level enum for all possible Claude input messages.
ClaudeOutput
Top-level enum for all possible Claude output messages
CommandLifecycleState
Lifecycle state carried by a CommandLifecycleMessage.
CompactionTrigger
What triggered a context compaction.
ContentBlock
Content blocks for messages
ControlRequestPayload
Control request payload variants
ControlResponsePayload
Control response payload
FastModeDisabledReason
Why fast mode can’t serve right now, carried on result frames and system/init (CLI 2.1.219+). Absent when nothing blocks fast mode.
ImageSourceType
Encoding type for image source data.
InitPermissionMode
Permission mode reported in init messages.
KnownSystemEvent
Owned typed view over any known system message subtype.
McpServerConfig
MCP Server configuration types
MediaType
MIME type for image content.
MessageRole
Known message roles.
OutputStyle
Output formatting style for the session.
OverageDisabledReason
Why overage billing is disabled.
OverageStatus
Whether overage billing was accepted or rejected.
PermissionBehavior
The behavior of a permission rule.
PermissionDestination
Where a permission applies.
PermissionModeName
Named permission modes that can be set via setMode.
PermissionResult
Result of a permission decision
PermissionType
The type of a permission grant.
RateLimitErrorCode
Error code carried on a rate limit event when a request was refused.
RateLimitStatus
Current rate limit disposition.
RateLimitWindow
The time window a rate limit applies to.
ResultSubtype
Result subtypes
StatusMessageStatus
Status of an ongoing operation (e.g., context compaction).
StopReason
Reason why the assistant stopped generating.
SystemSubtype
Known system message subtypes.
TaskStatus
Completion status of a background task.
TaskType
The kind of background task.
ToolResultContent
Tool result content type
VcsMutationKind
Mutation class carried by a VcsStateChangedMessage.

Functions§

assert_fully_wrapped
Panic with a detailed report unless raw is fully wrapped.
audit_frame
Audit a single raw frame (one parsed JSONL line) for full typed coverage.