ClaudeCode.Message (ClaudeCode v0.36.3)

View Source

Utilities for working with messages from the Claude CLI.

Messages can be system initialization, assistant responses, user tool results, result messages, stream events, conversation compaction boundaries, or informational messages (rate limits, tool progress, auth status, etc.). This module provides functions to parse and work with any message type.

Summary

Functions

Checks if a value is any type of message.

Returns the type atom of a message.

Parses a message-level delta from a message_delta stream event.

Parses a role string from CLI JSON into an atom.

Parses a stop reason string from the CLI into an atom.

Types

delta()

@type delta() :: %{stop_reason: stop_reason() | nil, stop_sequence: String.t() | nil}

role()

@type role() :: :user | :assistant

stop_reason()

@type stop_reason() ::
  :end_turn
  | :max_tokens
  | :stop_sequence
  | :tool_use
  | :pause_turn
  | :compaction
  | :refusal
  | :model_context_window_exceeded
  | String.t()

t()

Functions

message?(msg)

@spec message?(any()) :: boolean()

Checks if a value is any type of message.

message_type(map)

@spec message_type(t()) ::
  :system
  | :assistant
  | :user
  | :result
  | :stream_event
  | :rate_limit_event
  | :tool_progress
  | :tool_use_summary
  | :auth_status
  | :prompt_suggestion

Returns the type atom of a message.

All ClaudeCode.Message.SystemMessage.* subtypes (Init, CompactBoundary, HookStarted, etc.) return :system since they all carry type: :system. SystemMessage.t() is part of t().

parse_delta(delta)

@spec parse_delta(map() | nil) :: delta() | nil

Parses a message-level delta from a message_delta stream event.

Extracts stop_reason via parse_stop_reason/1 for consistency with AssistantMessage and ResultMessage.

Examples

iex> ClaudeCode.Message.parse_delta(%{"stop_reason" => "end_turn", "stop_sequence" => nil})
%{stop_reason: :end_turn, stop_sequence: nil}

iex> ClaudeCode.Message.parse_delta(nil)
nil

parse_role(value)

@spec parse_role(String.t() | nil) :: role() | String.t() | nil

Parses a role string from CLI JSON into an atom.

Examples

iex> ClaudeCode.Message.parse_role("assistant")
:assistant

iex> ClaudeCode.Message.parse_role("user")
:user

iex> ClaudeCode.Message.parse_role("future_role")
"future_role"

iex> ClaudeCode.Message.parse_role(nil)
nil

parse_stop_reason(value)

@spec parse_stop_reason(String.t() | nil) :: stop_reason() | nil

Parses a stop reason string from the CLI into an atom.

Returns nil for nil input. Unrecognized values are kept as strings for forward compatibility without risking atom table exhaustion.

Examples

iex> ClaudeCode.Message.parse_stop_reason("end_turn")
:end_turn

iex> ClaudeCode.Message.parse_stop_reason("tool_use")
:tool_use

iex> ClaudeCode.Message.parse_stop_reason("future_reason")
"future_reason"

iex> ClaudeCode.Message.parse_stop_reason(nil)
nil