Skip to main content

claude_codes/io/
claude_output.rs

1use serde::{Deserialize, Deserializer, Serialize};
2use serde_json::{Map, Value};
3
4use super::content_blocks::{ContentBlock, ToolUseBlock};
5use super::control::{ControlCancelRequest, ControlRequest, ControlResponse};
6use super::errors::{AnthropicError, ParseError};
7use super::message_types::{AssistantMessage, SystemMessage, UserMessage};
8use super::rate_limit::RateLimitEvent;
9use super::result::ResultMessage;
10
11/// Top-level enum for all possible Claude output messages
12#[allow(clippy::large_enum_variant)]
13#[derive(Debug, Clone, Serialize)]
14#[serde(tag = "type", rename_all = "snake_case")]
15pub enum ClaudeOutput {
16    /// System initialization message
17    System(SystemMessage),
18
19    /// User message echoed back
20    User(UserMessage),
21
22    /// Assistant response
23    Assistant(AssistantMessage),
24
25    /// Result message (completion of a query)
26    Result(ResultMessage),
27
28    /// Claude Code internal workflow-journal result event.
29    #[serde(rename = "result")]
30    TranscriptResult(TranscriptMessage),
31
32    /// Control request from CLI (tool permissions, hooks, etc.)
33    ControlRequest(ControlRequest),
34
35    /// Control response from CLI (ack for initialization, etc.)
36    ControlResponse(ControlResponse),
37
38    /// Withdrawal of an earlier control request (e.g. a permission prompt
39    /// that is no longer needed). Dismiss any pending UI for its `request_id`.
40    ControlCancelRequest(ControlCancelRequest),
41
42    /// API error from Anthropic (500, 529 overloaded, etc.)
43    Error(AnthropicError),
44
45    /// Rate limit status event
46    RateLimitEvent(RateLimitEvent),
47
48    /// Raw API stream event emitted with `--include-partial-messages`.
49    StreamEvent(StreamEventMessage),
50
51    /// Progress update for a running tool.
52    ToolProgress(ToolProgressMessage),
53
54    /// Fate of a queued command (slash command or queued user prompt).
55    CommandLifecycle(CommandLifecycleMessage),
56
57    /// Authentication status update.
58    AuthStatus(AuthStatusMessage),
59
60    /// Summary of preceding tool uses.
61    ToolUseSummary(ToolUseSummaryMessage),
62
63    /// Predicted next user prompt.
64    PromptSuggestion(PromptSuggestionMessage),
65
66    /// Conversation reset notification.
67    ConversationReset(ConversationResetMessage),
68
69    /// Claude Code internal transcript progress event.
70    Progress(TranscriptMessage),
71
72    /// Claude Code internal queue event.
73    #[serde(rename = "queue-operation")]
74    QueueOperation(TranscriptMessage),
75
76    /// Claude Code internal PR link metadata event.
77    #[serde(rename = "pr-link")]
78    PrLink(TranscriptMessage),
79
80    /// Claude Code internal file history snapshot event.
81    #[serde(rename = "file-history-snapshot")]
82    FileHistorySnapshot(TranscriptMessage),
83
84    /// Claude Code internal session summary event.
85    Summary(TranscriptMessage),
86
87    /// Claude Code internal mode metadata event.
88    Mode(TranscriptMessage),
89
90    /// Claude Code internal permission mode metadata event.
91    #[serde(rename = "permission-mode")]
92    PermissionMode(TranscriptMessage),
93
94    /// Claude Code internal attachment metadata event.
95    Attachment(TranscriptMessage),
96
97    /// Claude Code internal AI-generated title event.
98    #[serde(rename = "ai-title")]
99    AiTitle(TranscriptMessage),
100
101    /// Claude Code internal last prompt pointer event.
102    #[serde(rename = "last-prompt")]
103    LastPrompt(TranscriptMessage),
104
105    /// Claude Code internal session started event.
106    Started(TranscriptMessage),
107}
108
109#[derive(Debug, Clone, Serialize, Deserialize)]
110pub struct StreamEventMessage {
111    pub event: Value,
112    pub parent_tool_use_id: Option<String>,
113    pub uuid: String,
114    pub session_id: String,
115    #[serde(skip_serializing_if = "Option::is_none")]
116    pub ttft_ms: Option<u64>,
117    /// Client uuid of the user message that triggered this turn, stamped on
118    /// the turn's first non-ping stream event so a consumer can bind the
119    /// reply stream to the send it answers. Since CLI 2.1.269 the turn's
120    /// first complete assistant message is stamped too, independently, so
121    /// the same uuid may appear on both frames. Absent on later stream
122    /// events, on synthetic/scheduled turns, and from CLIs before 2.1.259.
123    #[serde(default, skip_serializing_if = "Option::is_none")]
124    pub user_message_uuid: Option<String>,
125    /// Client uuids of every user message whose prompt this turn has consumed
126    /// so far, in consumption order. Always contains `user_message_uuid`; at
127    /// most 64 entries. Present exactly when `user_message_uuid` is; absent
128    /// from CLIs before 2.1.259 (fall back to `user_message_uuid`).
129    #[serde(default, skip_serializing_if = "Vec::is_empty")]
130    pub user_message_uuids: Vec<String>,
131    /// Why this frame's turn is the automatic re-run of a turn a worker
132    /// restart interrupted: the host's `CLAUDE_CODE_RESUME_REASON` when it set
133    /// one, else `interrupted_turn`. Stamped on the same reply frames as
134    /// `user_message_uuid`, so a consumer can tell the re-run's first reply
135    /// from the interrupted attempt's. Absent on every other turn, on
136    /// `thinking_tokens` frames, and from CLIs before 2.1.268.
137    #[serde(default, skip_serializing_if = "Option::is_none")]
138    pub resume_reason: Option<String>,
139    /// The `thinking.display` value Claude Code put in the API request body
140    /// for the response this event belongs to — i.e. which display the
141    /// thinking text was *requested* with, not how to show it. Set on
142    /// `message_start`, on a thinking block's `content_block_start` and on
143    /// `thinking_delta` events when the request body had a display; absent
144    /// on every other event, on Remote Control sessions and from CLIs before
145    /// 2.1.283. Two responses of one turn can differ. Marked `@internal`
146    /// upstream, so treat the value set as open.
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub thinking_display: Option<String>,
149    /// Set on a `message_stop` that Claude Code produced itself after it
150    /// stopped reading a response because the API's stream failed, stalled
151    /// or ended early: that response's content blocks from
152    /// [`AbandonedBlocks::from_block_index`] up have no assistant message and
153    /// never will, so a consumer that drew them from stream events can remove
154    /// them. Absent on every other `message_stop`, on Remote Control sessions
155    /// and from CLIs before 2.1.292. Marked `@internal` upstream.
156    #[serde(default, skip_serializing_if = "Option::is_none")]
157    pub abandoned_blocks: Option<AbandonedBlocks>,
158    /// The API's id (`msg_…`) of the response this event belongs to:
159    /// `event.message.id` on its `message_start`, `message.id` on its
160    /// assistant messages. Not a message `uuid`. Set on every event from a
161    /// response's `message_start` to its `message_stop`, so a consumer that
162    /// missed the `message_start` can still tell responses apart; a replayed
163    /// `message_start` can make two responses share an id. Absent on pings,
164    /// on Remote Control sessions, on some plugin-produced events and from
165    /// CLIs before 2.1.295. An absent key states nothing about which
166    /// response the event belongs to. Marked `@internal` upstream.
167    #[serde(default, skip_serializing_if = "Option::is_none")]
168    pub api_message_id: Option<String>,
169    /// Always `true` when present. Set on a response's `message_start` when
170    /// `CLAUDE_CODE_WEBSEARCH_CITATIONS` is on in a non-interactive session:
171    /// each run of adjacent text blocks then arrives as one assistant message
172    /// with one joined text block, whose non-`web_search_result_location`
173    /// citations carry `span_start`/`span_end` (Unicode code points, end
174    /// exclusive) into the joined text. The `content_block_*` events still
175    /// show each block by its own index. Absent from CLIs before 2.1.295.
176    /// Marked `@internal` upstream.
177    #[serde(default, skip_serializing_if = "Option::is_none")]
178    pub text_runs_joined: Option<bool>,
179    /// The uuids of the `project_doc_reads` rows that this turn wrote ahead
180    /// of its first model request and that give the text of an added
181    /// claude.ai Project document (Claude Code's own read of the Project's
182    /// documents). A row with only replaced, edited or removed documents is
183    /// not listed, nor is a row from before the conversation's first reply.
184    /// `Some(vec![])` when the turn wrote no row to list, so a consumer that
185    /// read the transcript at the turn's start can tell whether that read
186    /// lacks such a row; the rows may not have reached the session server
187    /// yet. Present exactly when
188    /// [`user_message_uuid`](Self::user_message_uuid) is; absent from older
189    /// producers, and then it states nothing. Marked `@internal` upstream
190    /// (CLI 2.1.323+).
191    #[serde(default, skip_serializing_if = "Option::is_none")]
192    pub owed_rows: Option<Vec<String>>,
193}
194
195/// The cut-short response named by [`StreamEventMessage::abandoned_blocks`].
196#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
197pub struct AbandonedBlocks {
198    /// The API's id (`msg_…`) of the response that was cut short:
199    /// `event.message.id` on its `message_start`, `message.id` on its
200    /// assistant messages. Not a message `uuid`.
201    pub api_message_id: String,
202    /// Blocks of the response at this `event.index` and above have no
203    /// assistant message and never will. 0 means the whole response; can be
204    /// higher than every index the consumer has seen.
205    pub from_block_index: u64,
206}
207
208#[derive(Debug, Clone, Serialize, Deserialize)]
209pub struct ToolProgressMessage {
210    pub tool_use_id: String,
211    pub tool_name: String,
212    pub parent_tool_use_id: Option<String>,
213    pub elapsed_time_seconds: f64,
214    #[serde(skip_serializing_if = "Option::is_none")]
215    pub task_id: Option<String>,
216    pub uuid: String,
217    pub session_id: String,
218    /// True when this event was emitted only to keep the stream alive, not
219    /// because the tool reported progress.
220    #[serde(default, skip_serializing_if = "Option::is_none")]
221    pub heartbeat: Option<bool>,
222    /// Subagent type for progress from a `Task` tool's subagent.
223    #[serde(default, skip_serializing_if = "Option::is_none")]
224    pub subagent_type: Option<String>,
225    /// Present while a subagent API call is being retried after an error.
226    #[serde(default, skip_serializing_if = "Option::is_none")]
227    pub subagent_retry: Option<SubagentRetry>,
228}
229
230/// Retry state carried on a [`ToolProgressMessage`] while a subagent API
231/// call is retried after an error.
232#[derive(Debug, Clone, Serialize, Deserialize)]
233pub struct SubagentRetry {
234    pub agent_id: String,
235    pub attempt: u64,
236    pub max_retries: u64,
237    pub retry_delay_ms: u64,
238    pub error_status: Option<u16>,
239    pub error_category: String,
240}
241
242/// `command_lifecycle` message — the fate of a queued command (slash command
243/// or queued user prompt): `queued` when the inbound message enters the
244/// command queue, `started` when it drains into a turn, then exactly one
245/// terminal state (`completed`, `cancelled`, or `discarded`). Commands
246/// enqueued without a client-supplied uuid emit no lifecycle events. Not a
247/// strict pairing — a terminal state may arrive for a `command_uuid` that
248/// never emitted `started`, and internally-enqueued commands skip `queued`.
249#[derive(Debug, Clone, Serialize, Deserialize)]
250pub struct CommandLifecycleMessage {
251    /// The queued command's uuid — the client-supplied uuid on the inbound
252    /// message (distinct from the universal per-frame `uuid`).
253    pub command_uuid: String,
254    pub state: CommandLifecycleState,
255    /// Present, and true, only on a repeated `queued` frame written to the
256    /// VS Code panel: the plugin hooks of this `immediate` command, typed
257    /// during a turn, have run and answered ahead of its turn. The command is
258    /// still queued, and its own turn prints the answer (CLI 2.1.300+).
259    #[serde(default, skip_serializing_if = "Option::is_none")]
260    pub ran_ahead: Option<bool>,
261    /// Only on `started`, and only when the command being started is a
262    /// scheduler fire; matches the `UserPromptSubmit` hook's `source`. A fire
263    /// removed from the queue without being started gets only its terminal
264    /// state, without this key. Advertised by the
265    /// `lifecycle_wakeup_source_v1` capability on `system/init`
266    /// (CLI 2.1.307+).
267    #[serde(default, skip_serializing_if = "Option::is_none")]
268    pub wakeup_source: Option<CommandWakeupSource>,
269    /// Only beside [`CommandWakeupSource::LoopWakeup`]: the epoch-millisecond
270    /// time the fired wakeup was set for (the `scheduledFor` of the
271    /// `ScheduleWakeup` call that armed it). The fire itself can come earlier
272    /// or later. A host keeping an idle session alive for a wakeup should stop
273    /// waiting only when this equals the time it is waiting for, and needs a
274    /// time limit of its own past it, since a fire that never starts sends no
275    /// such frame (CLI 2.1.307+).
276    #[serde(default, skip_serializing_if = "Option::is_none")]
277    pub scheduled_for: Option<f64>,
278    pub uuid: String,
279    pub session_id: String,
280}
281
282/// Which scheduler fired a command, from
283/// [`CommandLifecycleMessage::wakeup_source`].
284#[derive(Debug, Clone, PartialEq, Eq, Hash)]
285pub enum CommandWakeupSource {
286    /// A `ScheduleWakeup` (dynamic `/loop`) wakeup fired.
287    LoopWakeup,
288    /// Any other scheduled-task fire, such as a `CronCreate` job or the
289    /// notice for scheduled tasks that were missed.
290    ScheduleWakeup,
291    /// A source not yet known to this version of the crate.
292    Unknown(String),
293}
294
295impl CommandWakeupSource {
296    pub fn as_str(&self) -> &str {
297        match self {
298            Self::LoopWakeup => "loop_wakeup",
299            Self::ScheduleWakeup => "schedule_wakeup",
300            Self::Unknown(s) => s.as_str(),
301        }
302    }
303}
304
305impl std::fmt::Display for CommandWakeupSource {
306    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
307        f.write_str(self.as_str())
308    }
309}
310
311impl From<&str> for CommandWakeupSource {
312    fn from(s: &str) -> Self {
313        match s {
314            "loop_wakeup" => Self::LoopWakeup,
315            "schedule_wakeup" => Self::ScheduleWakeup,
316            other => Self::Unknown(other.to_string()),
317        }
318    }
319}
320
321impl Serialize for CommandWakeupSource {
322    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
323        serializer.serialize_str(self.as_str())
324    }
325}
326
327impl<'de> Deserialize<'de> for CommandWakeupSource {
328    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
329        let s = String::deserialize(deserializer)?;
330        Ok(Self::from(s.as_str()))
331    }
332}
333
334/// Lifecycle state carried by a [`CommandLifecycleMessage`].
335#[derive(Debug, Clone, PartialEq, Eq, Hash)]
336pub enum CommandLifecycleState {
337    /// The inbound message entered the command queue.
338    Queued,
339    /// The command drained into a turn.
340    Started,
341    /// The turn that consumed the command ended cleanly.
342    Completed,
343    /// Removed by cancel, swept by an interrupt with `cancel_queued: true`
344    /// (or, on CLI 2.1.321+ in a remote session behind a flag, by a plain
345    /// interrupt, which cancels only messages the server had re-sent; see
346    /// `cancelled` on the interrupt's response), caught before dispatch, or
347    /// consumed into a turn that was aborted or died on a hard failure.
348    Cancelled,
349    /// The session ended with the command still queued.
350    Discarded,
351    /// A state not yet known to this version of the crate.
352    Unknown(String),
353}
354
355impl CommandLifecycleState {
356    pub fn as_str(&self) -> &str {
357        match self {
358            Self::Queued => "queued",
359            Self::Started => "started",
360            Self::Completed => "completed",
361            Self::Cancelled => "cancelled",
362            Self::Discarded => "discarded",
363            Self::Unknown(s) => s.as_str(),
364        }
365    }
366}
367
368impl std::fmt::Display for CommandLifecycleState {
369    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
370        f.write_str(self.as_str())
371    }
372}
373
374impl From<&str> for CommandLifecycleState {
375    fn from(s: &str) -> Self {
376        match s {
377            "queued" => Self::Queued,
378            "started" => Self::Started,
379            "completed" => Self::Completed,
380            "cancelled" => Self::Cancelled,
381            "discarded" => Self::Discarded,
382            other => Self::Unknown(other.to_string()),
383        }
384    }
385}
386
387impl Serialize for CommandLifecycleState {
388    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
389        serializer.serialize_str(self.as_str())
390    }
391}
392
393impl<'de> Deserialize<'de> for CommandLifecycleState {
394    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
395        let s = String::deserialize(deserializer)?;
396        Ok(Self::from(s.as_str()))
397    }
398}
399
400#[derive(Debug, Clone, Serialize, Deserialize)]
401pub struct AuthStatusMessage {
402    #[serde(rename = "isAuthenticating")]
403    pub is_authenticating: bool,
404    pub output: Vec<String>,
405    #[serde(skip_serializing_if = "Option::is_none")]
406    pub error: Option<String>,
407    pub uuid: String,
408    pub session_id: String,
409}
410
411#[derive(Debug, Clone, Serialize, Deserialize)]
412pub struct ToolUseSummaryMessage {
413    pub summary: String,
414    pub preceding_tool_use_ids: Vec<String>,
415    pub uuid: String,
416    pub session_id: String,
417    #[serde(skip_serializing_if = "Option::is_none")]
418    pub timestamp: Option<String>,
419}
420
421#[derive(Debug, Clone, Serialize, Deserialize)]
422pub struct PromptSuggestionMessage {
423    pub suggestion: String,
424    pub uuid: String,
425    pub session_id: String,
426}
427
428/// Emitted when the conversation is reset mid-stream (e.g. `/clear` sent as
429/// user input). **Identity semantics, measured live against CLI 2.1.232 —
430/// two traps here:**
431///
432/// 1. **The session id rotates.** After this frame the same process re-inits
433///    and every subsequent frame carries a NEW `session_id`; both the old
434///    and new ids get real transcript files on disk. A consumer keying a
435///    live stream's transcript by its first-seen session id will
436///    mis-attribute everything after a reset — treat this frame as a
437///    session-identity boundary and adopt the next `system` init's id.
438/// 2. **`new_conversation_id` is not the successor session id.** In live
439///    measurement it matched nothing: not the post-reset `session_id`, no
440///    transcript file, never referenced by any later frame. Do not key on
441///    it.
442///
443/// Pinned by `conversation_reset_rotates_the_session_id` in the live
444/// integration tests.
445#[derive(Debug, Clone, Serialize, Deserialize)]
446pub struct ConversationResetMessage {
447    /// A fresh id announced for the new conversation. **Not** observed to
448    /// match the post-reset `session_id` or anything else on the wire or
449    /// disk — see the type-level docs before using.
450    pub new_conversation_id: String,
451    pub uuid: String,
452    /// The OLD session id — the identity being retired by this reset.
453    pub session_id: String,
454    /// What discarded the conversation. Informational: reset on every
455    /// `conversation_reset` frame whatever this says, and treat an absent
456    /// (CLI before 2.1.281) or unrecognized value as an unspecified reset.
457    #[serde(default, skip_serializing_if = "Option::is_none")]
458    pub trigger: Option<ConversationResetTrigger>,
459    /// Only with trigger `clear`: the uuid of the user message whose
460    /// `/clear` was executed (the client's own uuid for that message when it
461    /// came from a Remote Control or stream-json client, otherwise the uuid
462    /// the CLI assigned to the typed command). Lets a consumer match this
463    /// frame to a `/clear` message it has already seen, wiping once whichever
464    /// arrives first. Absent for the other triggers, when that uuid is not a
465    /// canonical UUID, and from CLIs before 2.1.281.
466    #[serde(default, skip_serializing_if = "Option::is_none")]
467    pub user_message_uuid: Option<String>,
468    /// When the reset happened, as an ISO 8601 string in UTC from the clock
469    /// of the process that performed it. Meant for display, not for ordering
470    /// frames. Absent from CLIs before 2.1.281; fall back to the time the
471    /// frame was received.
472    #[serde(default, skip_serializing_if = "Option::is_none")]
473    pub timestamp: Option<String>,
474}
475
476/// What discarded the conversation ([`ConversationResetMessage::trigger`],
477/// CLI 2.1.281+).
478#[derive(Debug, Clone, PartialEq, Eq, Hash)]
479pub enum ConversationResetTrigger {
480    /// The `/clear` command (or its `/reset` and `/new` aliases).
481    Clear,
482    /// Leaving plan mode with the clear-context option.
483    PlanModeExit,
484    /// A flow that starts a fresh session to implement an approved plan.
485    FreshSession,
486    /// An onboarding flow re-run inside an existing session.
487    Onboarding,
488    /// A trigger not yet known to this version of the crate.
489    Unknown(String),
490}
491
492impl ConversationResetTrigger {
493    pub fn as_str(&self) -> &str {
494        match self {
495            Self::Clear => "clear",
496            Self::PlanModeExit => "plan_mode_exit",
497            Self::FreshSession => "fresh_session",
498            Self::Onboarding => "onboarding",
499            Self::Unknown(s) => s.as_str(),
500        }
501    }
502}
503
504impl std::fmt::Display for ConversationResetTrigger {
505    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
506        f.write_str(self.as_str())
507    }
508}
509
510impl From<&str> for ConversationResetTrigger {
511    fn from(s: &str) -> Self {
512        match s {
513            "clear" => Self::Clear,
514            "plan_mode_exit" => Self::PlanModeExit,
515            "fresh_session" => Self::FreshSession,
516            "onboarding" => Self::Onboarding,
517            other => Self::Unknown(other.to_string()),
518        }
519    }
520}
521
522impl Serialize for ConversationResetTrigger {
523    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
524        serializer.serialize_str(self.as_str())
525    }
526}
527
528impl<'de> Deserialize<'de> for ConversationResetTrigger {
529    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
530        let s = String::deserialize(deserializer)?;
531        Ok(Self::from(s.as_str()))
532    }
533}
534
535/// Raw preserved record for Claude Code transcript-only message types.
536///
537/// These events are emitted in `~/.claude/projects/**/*.jsonl`, not in the
538/// public `--output-format stream-json` protocol. Keeping them typed at the
539/// top level lets corpus tests parse real transcript files without losing the
540/// original payload.
541#[derive(Debug, Clone, Serialize, Deserialize)]
542pub struct TranscriptMessage {
543    #[serde(flatten)]
544    pub data: Map<String, Value>,
545}
546
547impl ClaudeOutput {
548    /// Get the message type as a string
549    pub fn message_type(&self) -> String {
550        match self {
551            ClaudeOutput::System(_) => "system".to_string(),
552            ClaudeOutput::User(_) => "user".to_string(),
553            ClaudeOutput::Assistant(_) => "assistant".to_string(),
554            ClaudeOutput::Result(_) => "result".to_string(),
555            ClaudeOutput::TranscriptResult(_) => "result".to_string(),
556            ClaudeOutput::ControlRequest(_) => "control_request".to_string(),
557            ClaudeOutput::ControlResponse(_) => "control_response".to_string(),
558            ClaudeOutput::ControlCancelRequest(_) => "control_cancel_request".to_string(),
559            ClaudeOutput::Error(_) => "error".to_string(),
560            ClaudeOutput::RateLimitEvent(_) => "rate_limit_event".to_string(),
561            ClaudeOutput::StreamEvent(_) => "stream_event".to_string(),
562            ClaudeOutput::ToolProgress(_) => "tool_progress".to_string(),
563            ClaudeOutput::CommandLifecycle(_) => "command_lifecycle".to_string(),
564            ClaudeOutput::AuthStatus(_) => "auth_status".to_string(),
565            ClaudeOutput::ToolUseSummary(_) => "tool_use_summary".to_string(),
566            ClaudeOutput::PromptSuggestion(_) => "prompt_suggestion".to_string(),
567            ClaudeOutput::ConversationReset(_) => "conversation_reset".to_string(),
568            ClaudeOutput::Progress(_) => "progress".to_string(),
569            ClaudeOutput::QueueOperation(_) => "queue-operation".to_string(),
570            ClaudeOutput::PrLink(_) => "pr-link".to_string(),
571            ClaudeOutput::FileHistorySnapshot(_) => "file-history-snapshot".to_string(),
572            ClaudeOutput::Summary(_) => "summary".to_string(),
573            ClaudeOutput::Mode(_) => "mode".to_string(),
574            ClaudeOutput::PermissionMode(_) => "permission-mode".to_string(),
575            ClaudeOutput::Attachment(_) => "attachment".to_string(),
576            ClaudeOutput::AiTitle(_) => "ai-title".to_string(),
577            ClaudeOutput::LastPrompt(_) => "last-prompt".to_string(),
578            ClaudeOutput::Started(_) => "started".to_string(),
579        }
580    }
581
582    /// Check if this is a control request (tool permission request)
583    pub fn is_control_request(&self) -> bool {
584        matches!(self, ClaudeOutput::ControlRequest(_))
585    }
586
587    /// Check if this is a control response
588    pub fn is_control_response(&self) -> bool {
589        matches!(self, ClaudeOutput::ControlResponse(_))
590    }
591
592    /// Check if this is an Anthropic API error
593    pub fn is_api_error(&self) -> bool {
594        matches!(self, ClaudeOutput::Error(_))
595    }
596
597    /// Get the control request if this is one
598    pub fn as_control_request(&self) -> Option<&ControlRequest> {
599        match self {
600            ClaudeOutput::ControlRequest(req) => Some(req),
601            _ => None,
602        }
603    }
604
605    /// Check if this is a control cancel request
606    pub fn is_control_cancel_request(&self) -> bool {
607        matches!(self, ClaudeOutput::ControlCancelRequest(_))
608    }
609
610    /// Get the control cancel request if this is one
611    pub fn as_control_cancel_request(&self) -> Option<&ControlCancelRequest> {
612        match self {
613            ClaudeOutput::ControlCancelRequest(req) => Some(req),
614            _ => None,
615        }
616    }
617
618    /// Get the Anthropic error if this is one
619    ///
620    /// # Example
621    /// ```
622    /// use claude_codes::ClaudeOutput;
623    ///
624    /// let json = r#"{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}"#;
625    /// let output: ClaudeOutput = serde_json::from_str(json).unwrap();
626    ///
627    /// if let Some(err) = output.as_anthropic_error() {
628    ///     if err.is_overloaded() {
629    ///         println!("API is overloaded, retrying...");
630    ///     }
631    /// }
632    /// ```
633    pub fn as_anthropic_error(&self) -> Option<&AnthropicError> {
634        match self {
635            ClaudeOutput::Error(err) => Some(err),
636            _ => None,
637        }
638    }
639
640    /// Check if this is a rate limit event
641    pub fn is_rate_limit_event(&self) -> bool {
642        matches!(self, ClaudeOutput::RateLimitEvent(_))
643    }
644
645    /// Get the rate limit event if this is one
646    pub fn as_rate_limit_event(&self) -> Option<&RateLimitEvent> {
647        match self {
648            ClaudeOutput::RateLimitEvent(evt) => Some(evt),
649            _ => None,
650        }
651    }
652
653    /// Check if this is a result with error
654    pub fn is_error(&self) -> bool {
655        matches!(self, ClaudeOutput::Result(r) if r.is_error)
656    }
657
658    /// Check if this is an assistant message
659    pub fn is_assistant_message(&self) -> bool {
660        matches!(self, ClaudeOutput::Assistant(_))
661    }
662
663    /// Check if this is a system message
664    pub fn is_system_message(&self) -> bool {
665        matches!(self, ClaudeOutput::System(_))
666    }
667
668    /// Check if this is a system init message
669    ///
670    /// # Example
671    /// ```
672    /// use claude_codes::ClaudeOutput;
673    ///
674    /// let json = r#"{"type":"system","subtype":"init","session_id":"abc"}"#;
675    /// let output: ClaudeOutput = serde_json::from_str(json).unwrap();
676    /// assert!(output.is_system_init());
677    /// ```
678    pub fn is_system_init(&self) -> bool {
679        matches!(self, ClaudeOutput::System(sys) if sys.is_init())
680    }
681
682    /// Get the session ID from any message type that has one.
683    ///
684    /// Returns the session ID from System, Assistant, or Result messages.
685    /// Returns `None` for User, ControlRequest, and ControlResponse messages.
686    ///
687    /// # Example
688    /// ```
689    /// use claude_codes::ClaudeOutput;
690    ///
691    /// let json = r#"{"type":"result","subtype":"success","is_error":false,
692    ///     "duration_ms":100,"duration_api_ms":200,"num_turns":1,
693    ///     "session_id":"my-session","total_cost_usd":0.01}"#;
694    /// let output: ClaudeOutput = serde_json::from_str(json).unwrap();
695    /// assert_eq!(output.session_id(), Some("my-session"));
696    /// ```
697    pub fn session_id(&self) -> Option<&str> {
698        match self {
699            ClaudeOutput::System(sys) => sys
700                .data
701                .get("session_id")
702                .or_else(|| sys.data.get("sessionId"))
703                .and_then(|v| v.as_str()),
704            ClaudeOutput::Assistant(ass) => Some(&ass.session_id),
705            ClaudeOutput::Result(res) => Some(&res.session_id),
706            ClaudeOutput::TranscriptResult(msg) => msg
707                .data
708                .get("session_id")
709                .or_else(|| msg.data.get("sessionId"))
710                .and_then(|v| v.as_str()),
711            ClaudeOutput::User(_) => None,
712            ClaudeOutput::ControlRequest(_) => None,
713            ClaudeOutput::ControlResponse(_) => None,
714            ClaudeOutput::ControlCancelRequest(msg) => msg.session_id.as_deref(),
715            ClaudeOutput::Error(_) => None,
716            ClaudeOutput::RateLimitEvent(evt) => Some(&evt.session_id),
717            ClaudeOutput::StreamEvent(msg) => Some(&msg.session_id),
718            ClaudeOutput::ToolProgress(msg) => Some(&msg.session_id),
719            ClaudeOutput::CommandLifecycle(msg) => Some(&msg.session_id),
720            ClaudeOutput::AuthStatus(msg) => Some(&msg.session_id),
721            ClaudeOutput::ToolUseSummary(msg) => Some(&msg.session_id),
722            ClaudeOutput::PromptSuggestion(msg) => Some(&msg.session_id),
723            ClaudeOutput::ConversationReset(msg) => Some(&msg.session_id),
724            ClaudeOutput::Progress(msg)
725            | ClaudeOutput::QueueOperation(msg)
726            | ClaudeOutput::PrLink(msg)
727            | ClaudeOutput::FileHistorySnapshot(msg)
728            | ClaudeOutput::Summary(msg)
729            | ClaudeOutput::Mode(msg)
730            | ClaudeOutput::PermissionMode(msg)
731            | ClaudeOutput::Attachment(msg)
732            | ClaudeOutput::AiTitle(msg)
733            | ClaudeOutput::LastPrompt(msg)
734            | ClaudeOutput::Started(msg) => msg
735                .data
736                .get("session_id")
737                .or_else(|| msg.data.get("sessionId"))
738                .and_then(|v| v.as_str()),
739        }
740    }
741
742    /// Get a specific tool use by name from an assistant message.
743    ///
744    /// Returns the first `ToolUseBlock` with the given name, or `None` if this
745    /// is not an assistant message or doesn't contain the specified tool.
746    ///
747    /// # Example
748    /// ```
749    /// use claude_codes::ClaudeOutput;
750    ///
751    /// let json = r#"{"type":"assistant","message":{"id":"msg_1","role":"assistant",
752    ///     "model":"claude-3","content":[{"type":"tool_use","id":"tu_1",
753    ///     "name":"Bash","input":{"command":"ls"}}]},"session_id":"abc"}"#;
754    /// let output: ClaudeOutput = serde_json::from_str(json).unwrap();
755    ///
756    /// if let Some(bash) = output.as_tool_use("Bash") {
757    ///     assert_eq!(bash.name, "Bash");
758    /// }
759    /// ```
760    pub fn as_tool_use(&self, tool_name: &str) -> Option<&ToolUseBlock> {
761        match self {
762            ClaudeOutput::Assistant(ass) => {
763                ass.message.content.iter().find_map(|block| match block {
764                    ContentBlock::ToolUse(tu) if tu.name == tool_name => Some(tu),
765                    _ => None,
766                })
767            }
768            _ => None,
769        }
770    }
771
772    /// Get all tool uses from an assistant message.
773    ///
774    /// Returns an iterator over all `ToolUseBlock`s in the message, or an empty
775    /// iterator if this is not an assistant message.
776    ///
777    /// # Example
778    /// ```
779    /// use claude_codes::ClaudeOutput;
780    ///
781    /// let json = r#"{"type":"assistant","message":{"id":"msg_1","role":"assistant",
782    ///     "model":"claude-3","content":[
783    ///         {"type":"tool_use","id":"tu_1","name":"Read","input":{"file_path":"/tmp/a"}},
784    ///         {"type":"tool_use","id":"tu_2","name":"Write","input":{"file_path":"/tmp/b","content":"x"}}
785    ///     ]},"session_id":"abc"}"#;
786    /// let output: ClaudeOutput = serde_json::from_str(json).unwrap();
787    ///
788    /// let tools: Vec<_> = output.tool_uses().collect();
789    /// assert_eq!(tools.len(), 2);
790    /// ```
791    pub fn tool_uses(&self) -> impl Iterator<Item = &ToolUseBlock> {
792        let content = match self {
793            ClaudeOutput::Assistant(ass) => Some(&ass.message.content),
794            _ => None,
795        };
796
797        content
798            .into_iter()
799            .flat_map(|c| c.iter())
800            .filter_map(|block| match block {
801                ContentBlock::ToolUse(tu) => Some(tu),
802                _ => None,
803            })
804    }
805
806    /// Get text content from an assistant message.
807    ///
808    /// Returns the concatenated text from all text blocks in the message,
809    /// or `None` if this is not an assistant message or has no text content.
810    ///
811    /// # Example
812    /// ```
813    /// use claude_codes::ClaudeOutput;
814    ///
815    /// let json = r#"{"type":"assistant","message":{"id":"msg_1","role":"assistant",
816    ///     "model":"claude-3","content":[{"type":"text","text":"Hello, world!"}]},
817    ///     "session_id":"abc"}"#;
818    /// let output: ClaudeOutput = serde_json::from_str(json).unwrap();
819    /// assert_eq!(output.text_content(), Some("Hello, world!".to_string()));
820    /// ```
821    pub fn text_content(&self) -> Option<String> {
822        match self {
823            ClaudeOutput::Assistant(ass) => {
824                let texts: Vec<&str> = ass
825                    .message
826                    .content
827                    .iter()
828                    .filter_map(|block| match block {
829                        ContentBlock::Text(t) => Some(t.text.as_str()),
830                        _ => None,
831                    })
832                    .collect();
833
834                if texts.is_empty() {
835                    None
836                } else {
837                    Some(texts.join(""))
838                }
839            }
840            _ => None,
841        }
842    }
843
844    /// Get the assistant message if this is one.
845    ///
846    /// # Example
847    /// ```
848    /// use claude_codes::ClaudeOutput;
849    ///
850    /// let json = r#"{"type":"assistant","message":{"id":"msg_1","role":"assistant",
851    ///     "model":"claude-3","content":[]},"session_id":"abc"}"#;
852    /// let output: ClaudeOutput = serde_json::from_str(json).unwrap();
853    ///
854    /// if let Some(assistant) = output.as_assistant() {
855    ///     assert_eq!(assistant.message.model, "claude-3");
856    /// }
857    /// ```
858    pub fn as_assistant(&self) -> Option<&AssistantMessage> {
859        match self {
860            ClaudeOutput::Assistant(ass) => Some(ass),
861            _ => None,
862        }
863    }
864
865    /// Get the result message if this is one.
866    ///
867    /// # Example
868    /// ```
869    /// use claude_codes::ClaudeOutput;
870    ///
871    /// let json = r#"{"type":"result","subtype":"success","is_error":false,
872    ///     "duration_ms":100,"duration_api_ms":200,"num_turns":1,
873    ///     "session_id":"abc","total_cost_usd":0.01}"#;
874    /// let output: ClaudeOutput = serde_json::from_str(json).unwrap();
875    ///
876    /// if let Some(result) = output.as_result() {
877    ///     assert!(!result.is_error);
878    /// }
879    /// ```
880    pub fn as_result(&self) -> Option<&ResultMessage> {
881        match self {
882            ClaudeOutput::Result(res) => Some(res),
883            _ => None,
884        }
885    }
886
887    /// Get the system message if this is one.
888    pub fn as_system(&self) -> Option<&SystemMessage> {
889        match self {
890            ClaudeOutput::System(sys) => Some(sys),
891            _ => None,
892        }
893    }
894
895    /// Parse a JSON string, handling potential ANSI escape codes and other prefixes
896    /// This method will:
897    /// 1. First try to parse as-is
898    /// 2. If that fails, trim until it finds a '{' and try again
899    pub fn parse_json_tolerant(s: &str) -> Result<ClaudeOutput, ParseError> {
900        // First try to parse as-is
901        match Self::parse_json(s) {
902            Ok(output) => Ok(output),
903            Err(first_error) => {
904                // If that fails, look for the first '{' character
905                if let Some(json_start) = s.find('{') {
906                    let trimmed = &s[json_start..];
907                    match Self::parse_json(trimmed) {
908                        Ok(output) => Ok(output),
909                        Err(_) => {
910                            // Return the original error if both attempts fail
911                            Err(first_error)
912                        }
913                    }
914                } else {
915                    Err(first_error)
916                }
917            }
918        }
919    }
920
921    /// Parse a JSON string, returning ParseError with raw JSON if it doesn't match our types
922    pub fn parse_json(s: &str) -> Result<ClaudeOutput, ParseError> {
923        // First try to parse as a Value
924        let value: Value = serde_json::from_str(s).map_err(|e| ParseError {
925            raw_line: s.to_string(),
926            raw_json: None,
927            error_message: format!("Invalid JSON: {}", e),
928        })?;
929
930        // Then try to parse that Value as ClaudeOutput
931        serde_json::from_value::<ClaudeOutput>(value.clone()).map_err(|e| ParseError {
932            raw_line: s.to_string(),
933            raw_json: Some(value),
934            error_message: e.to_string(),
935        })
936    }
937}
938
939impl<'de> Deserialize<'de> for ClaudeOutput {
940    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
941        let value = Value::deserialize(deserializer)?;
942        let message_type = value
943            .get("type")
944            .and_then(|v| v.as_str())
945            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
946        let mut payload = value.clone();
947        if let Some(obj) = payload.as_object_mut() {
948            obj.remove("type");
949        }
950
951        fn parse<T, E>(value: Value) -> Result<T, E>
952        where
953            T: serde::de::DeserializeOwned,
954            E: serde::de::Error,
955        {
956            serde_json::from_value(value).map_err(E::custom)
957        }
958
959        match message_type {
960            "system" => parse(payload).map(Self::System),
961            "user" => parse(payload).map(Self::User),
962            "assistant" => parse(payload).map(Self::Assistant),
963            "result" if value.get("subtype").is_some() => parse(payload).map(Self::Result),
964            "result" => parse(payload).map(Self::TranscriptResult),
965            "control_request" => parse(payload).map(Self::ControlRequest),
966            "control_response" => parse(payload).map(Self::ControlResponse),
967            "control_cancel_request" => parse(payload).map(Self::ControlCancelRequest),
968            "error" => parse(payload).map(Self::Error),
969            "rate_limit_event" => parse(payload).map(Self::RateLimitEvent),
970            "stream_event" => parse(payload).map(Self::StreamEvent),
971            "tool_progress" => parse(payload).map(Self::ToolProgress),
972            "command_lifecycle" => parse(payload).map(Self::CommandLifecycle),
973            "auth_status" => parse(payload).map(Self::AuthStatus),
974            "tool_use_summary" => parse(payload).map(Self::ToolUseSummary),
975            "prompt_suggestion" => parse(payload).map(Self::PromptSuggestion),
976            "conversation_reset" => parse(payload).map(Self::ConversationReset),
977            "progress" => parse(payload).map(Self::Progress),
978            "queue-operation" => parse(payload).map(Self::QueueOperation),
979            "pr-link" => parse(payload).map(Self::PrLink),
980            "file-history-snapshot" => parse(payload).map(Self::FileHistorySnapshot),
981            "summary" => parse(payload).map(Self::Summary),
982            "mode" => parse(payload).map(Self::Mode),
983            "permission-mode" => parse(payload).map(Self::PermissionMode),
984            "attachment" => parse(payload).map(Self::Attachment),
985            "ai-title" => parse(payload).map(Self::AiTitle),
986            "last-prompt" => parse(payload).map(Self::LastPrompt),
987            "started" => parse(payload).map(Self::Started),
988            other => Err(serde::de::Error::unknown_variant(
989                other,
990                &[
991                    "system",
992                    "user",
993                    "assistant",
994                    "result",
995                    "control_request",
996                    "control_response",
997                    "control_cancel_request",
998                    "error",
999                    "rate_limit_event",
1000                    "stream_event",
1001                    "tool_progress",
1002                    "command_lifecycle",
1003                    "auth_status",
1004                    "tool_use_summary",
1005                    "prompt_suggestion",
1006                    "conversation_reset",
1007                    "progress",
1008                    "queue-operation",
1009                    "pr-link",
1010                    "file-history-snapshot",
1011                    "summary",
1012                    "mode",
1013                    "permission-mode",
1014                    "attachment",
1015                    "ai-title",
1016                    "last-prompt",
1017                    "started",
1018                ],
1019            )),
1020        }
1021    }
1022}
1023
1024#[cfg(test)]
1025mod tests {
1026    use super::*;
1027
1028    #[test]
1029    fn test_deserialize_control_cancel_request() {
1030        let json = r#"{"request_id":"00aea85d-70f9-4cc4-becc-b0f05f5037f3","type":"control_cancel_request"}"#;
1031        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1032        assert!(output.is_control_cancel_request());
1033        assert_eq!(output.message_type(), "control_cancel_request");
1034        assert_eq!(output.session_id(), None);
1035        let cancel = output.as_control_cancel_request().unwrap();
1036        assert_eq!(cancel.request_id, "00aea85d-70f9-4cc4-becc-b0f05f5037f3");
1037
1038        let round_trip: Value = serde_json::to_value(&output).unwrap();
1039        assert_eq!(round_trip, serde_json::from_str::<Value>(json).unwrap());
1040
1041        let bridged = r#"{"type":"control_cancel_request","request_id":"r1","session_id":"s1"}"#;
1042        let output: ClaudeOutput = serde_json::from_str(bridged).unwrap();
1043        assert_eq!(output.session_id(), Some("s1"));
1044    }
1045
1046    #[test]
1047    fn test_deserialize_assistant_message() {
1048        let json = r#"{
1049            "type": "assistant",
1050            "message": {
1051                "id": "msg_123",
1052                "role": "assistant",
1053                "model": "claude-3-sonnet",
1054                "content": [{"type": "text", "text": "Hello! How can I help you?"}]
1055            },
1056            "session_id": "123"
1057        }"#;
1058
1059        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1060        assert!(output.is_assistant_message());
1061    }
1062
1063    #[test]
1064    fn test_deserialize_new_top_level_message_types() {
1065        let cases = [
1066            (
1067                r#"{"type":"stream_event","event":{"type":"content_block_delta"},"parent_tool_use_id":null,"uuid":"u1","session_id":"s1","ttft_ms":12}"#,
1068                "stream_event",
1069            ),
1070            (
1071                r#"{"type":"tool_progress","tool_use_id":"toolu_1","tool_name":"Bash","parent_tool_use_id":null,"elapsed_time_seconds":1.25,"task_id":"task-1","uuid":"u2","session_id":"s2"}"#,
1072                "tool_progress",
1073            ),
1074            (
1075                r#"{"type":"auth_status","isAuthenticating":true,"output":["login"],"uuid":"u3","session_id":"s3"}"#,
1076                "auth_status",
1077            ),
1078            (
1079                r#"{"type":"tool_use_summary","summary":"read files","preceding_tool_use_ids":["toolu_1"],"uuid":"u4","session_id":"s4","timestamp":"2026-07-09T17:46:33Z"}"#,
1080                "tool_use_summary",
1081            ),
1082            (
1083                r#"{"type":"prompt_suggestion","suggestion":"Run tests","uuid":"u5","session_id":"s5"}"#,
1084                "prompt_suggestion",
1085            ),
1086            (
1087                r#"{"type":"conversation_reset","new_conversation_id":"new-session","uuid":"u6","session_id":"s6"}"#,
1088                "conversation_reset",
1089            ),
1090            (
1091                r#"{"type":"command_lifecycle","command_uuid":"cmd-1","state":"queued","uuid":"u7","session_id":"s7"}"#,
1092                "command_lifecycle",
1093            ),
1094        ];
1095
1096        for (json, message_type) in cases {
1097            let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1098            assert_eq!(output.message_type(), message_type);
1099            assert!(output.session_id().is_some());
1100        }
1101    }
1102
1103    #[test]
1104    fn test_command_lifecycle_states_roundtrip() {
1105        for state in ["queued", "started", "completed", "cancelled", "discarded"] {
1106            let json = format!(
1107                r#"{{"type":"command_lifecycle","command_uuid":"cmd-1","state":"{}","uuid":"u1","session_id":"s1"}}"#,
1108                state
1109            );
1110            let output: ClaudeOutput = serde_json::from_str(&json).unwrap();
1111            let ClaudeOutput::CommandLifecycle(msg) = &output else {
1112                panic!("expected CommandLifecycle");
1113            };
1114            assert_eq!(msg.state.as_str(), state);
1115            assert!(!matches!(msg.state, CommandLifecycleState::Unknown(_)));
1116            assert_eq!(serde_json::to_string(&output).unwrap(), json);
1117        }
1118
1119        // Unknown states survive decode and round-trip verbatim.
1120        let json = r#"{"type":"command_lifecycle","command_uuid":"cmd-2","state":"parked","uuid":"u2","session_id":"s2"}"#;
1121        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1122        let ClaudeOutput::CommandLifecycle(msg) = &output else {
1123            panic!("expected CommandLifecycle");
1124        };
1125        assert_eq!(
1126            msg.state,
1127            CommandLifecycleState::Unknown("parked".to_string())
1128        );
1129        assert_eq!(serde_json::to_string(&output).unwrap(), json);
1130    }
1131
1132    #[test]
1133    fn test_tool_progress_heartbeat_and_subagent_retry() {
1134        let json = r#"{"type":"tool_progress","tool_use_id":"toolu_1","tool_name":"Task","parent_tool_use_id":null,"elapsed_time_seconds":30,"uuid":"u1","session_id":"s1","heartbeat":true,"subagent_type":"Explore","subagent_retry":{"agent_id":"agent-1","attempt":2,"max_retries":5,"retry_delay_ms":4000,"error_status":529,"error_category":"overloaded"}}"#;
1135        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1136        let ClaudeOutput::ToolProgress(msg) = &output else {
1137            panic!("expected ToolProgress");
1138        };
1139        assert_eq!(msg.heartbeat, Some(true));
1140        assert_eq!(msg.subagent_type.as_deref(), Some("Explore"));
1141        let retry = msg.subagent_retry.as_ref().unwrap();
1142        assert_eq!(retry.attempt, 2);
1143        assert_eq!(retry.error_status, Some(529));
1144        assert_eq!(retry.error_category, "overloaded");
1145
1146        // Null error_status parses too.
1147        let json = r#"{"type":"tool_progress","tool_use_id":"toolu_2","tool_name":"Task","parent_tool_use_id":null,"elapsed_time_seconds":1,"uuid":"u2","session_id":"s2","subagent_retry":{"agent_id":"agent-2","attempt":1,"max_retries":3,"retry_delay_ms":500,"error_status":null,"error_category":"network"}}"#;
1148        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1149        let ClaudeOutput::ToolProgress(msg) = &output else {
1150            panic!("expected ToolProgress");
1151        };
1152        assert_eq!(msg.subagent_retry.as_ref().unwrap().error_status, None);
1153    }
1154
1155    #[test]
1156    fn test_deserialize_transcript_only_message_types() {
1157        let cases = [
1158            (
1159                r#"{"type":"progress","sessionId":"s1","content":"delta"}"#,
1160                "progress",
1161                Some("s1"),
1162            ),
1163            (
1164                r#"{"type":"queue-operation","sessionId":"s2","operation":"push"}"#,
1165                "queue-operation",
1166                Some("s2"),
1167            ),
1168            (
1169                r#"{"type":"pr-link","sessionId":"s3","url":"https://example.invalid/pr"}"#,
1170                "pr-link",
1171                Some("s3"),
1172            ),
1173            (
1174                r#"{"type":"file-history-snapshot","sessionId":"s4","files":[]}"#,
1175                "file-history-snapshot",
1176                Some("s4"),
1177            ),
1178            (r#"{"type":"summary","summary":"Done"}"#, "summary", None),
1179            (
1180                r#"{"type":"mode","mode":"normal","sessionId":"s5"}"#,
1181                "mode",
1182                Some("s5"),
1183            ),
1184            (
1185                r#"{"type":"permission-mode","permissionMode":"default","sessionId":"s6"}"#,
1186                "permission-mode",
1187                Some("s6"),
1188            ),
1189            (
1190                r#"{"type":"attachment","attachment":{"type":"task_reminder"},"sessionId":"s7"}"#,
1191                "attachment",
1192                Some("s7"),
1193            ),
1194            (
1195                r#"{"type":"ai-title","aiTitle":"Title","sessionId":"s8"}"#,
1196                "ai-title",
1197                Some("s8"),
1198            ),
1199            (
1200                r#"{"type":"last-prompt","lastPrompt":"prompt","sessionId":"s9"}"#,
1201                "last-prompt",
1202                Some("s9"),
1203            ),
1204            (
1205                r#"{"type":"started","sessionId":"s10"}"#,
1206                "started",
1207                Some("s10"),
1208            ),
1209            (
1210                r#"{"type":"result","key":"k","agentId":"a","result":{"ok":true}}"#,
1211                "result",
1212                None,
1213            ),
1214        ];
1215
1216        for (json, message_type, session_id) in cases {
1217            let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1218            assert_eq!(output.message_type(), message_type);
1219            assert_eq!(output.session_id(), session_id);
1220        }
1221    }
1222
1223    #[test]
1224    fn test_transcript_assistant_accepts_camel_case_session_id() {
1225        let json = r#"{
1226            "type": "assistant",
1227            "sessionId": "camel-session",
1228            "message": {
1229                "id": "msg_123",
1230                "role": "assistant",
1231                "model": "claude-3-sonnet",
1232                "content": [{"type": "text", "text": "Hello"}]
1233            }
1234        }"#;
1235
1236        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1237        assert_eq!(output.session_id(), Some("camel-session"));
1238    }
1239
1240    #[test]
1241    fn test_is_system_init() {
1242        let init_json = r#"{
1243            "type": "system",
1244            "subtype": "init",
1245            "session_id": "test-session"
1246        }"#;
1247        let output: ClaudeOutput = serde_json::from_str(init_json).unwrap();
1248        assert!(output.is_system_init());
1249
1250        let status_json = r#"{
1251            "type": "system",
1252            "subtype": "status",
1253            "session_id": "test-session"
1254        }"#;
1255        let output: ClaudeOutput = serde_json::from_str(status_json).unwrap();
1256        assert!(!output.is_system_init());
1257    }
1258
1259    #[test]
1260    fn test_session_id() {
1261        // Result message
1262        let result_json = r#"{
1263            "type": "result",
1264            "subtype": "success",
1265            "is_error": false,
1266            "duration_ms": 100,
1267            "duration_api_ms": 200,
1268            "num_turns": 1,
1269            "session_id": "result-session",
1270            "total_cost_usd": 0.01
1271        }"#;
1272        let output: ClaudeOutput = serde_json::from_str(result_json).unwrap();
1273        assert_eq!(output.session_id(), Some("result-session"));
1274
1275        // Assistant message
1276        let assistant_json = r#"{
1277            "type": "assistant",
1278            "message": {
1279                "id": "msg_1",
1280                "role": "assistant",
1281                "model": "claude-3",
1282                "content": []
1283            },
1284            "session_id": "assistant-session"
1285        }"#;
1286        let output: ClaudeOutput = serde_json::from_str(assistant_json).unwrap();
1287        assert_eq!(output.session_id(), Some("assistant-session"));
1288
1289        // System message
1290        let system_json = r#"{
1291            "type": "system",
1292            "subtype": "init",
1293            "session_id": "system-session"
1294        }"#;
1295        let output: ClaudeOutput = serde_json::from_str(system_json).unwrap();
1296        assert_eq!(output.session_id(), Some("system-session"));
1297    }
1298
1299    #[test]
1300    fn test_as_tool_use() {
1301        let json = r#"{
1302            "type": "assistant",
1303            "message": {
1304                "id": "msg_1",
1305                "role": "assistant",
1306                "model": "claude-3",
1307                "content": [
1308                    {"type": "text", "text": "Let me run that command."},
1309                    {"type": "tool_use", "id": "tu_1", "name": "Bash", "input": {"command": "ls -la"}},
1310                    {"type": "tool_use", "id": "tu_2", "name": "Read", "input": {"file_path": "/tmp/test"}}
1311                ]
1312            },
1313            "session_id": "abc"
1314        }"#;
1315        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1316
1317        // Find Bash tool
1318        let bash = output.as_tool_use("Bash");
1319        assert!(bash.is_some());
1320        assert_eq!(bash.unwrap().id, "tu_1");
1321
1322        // Find Read tool
1323        let read = output.as_tool_use("Read");
1324        assert!(read.is_some());
1325        assert_eq!(read.unwrap().id, "tu_2");
1326
1327        // Non-existent tool
1328        assert!(output.as_tool_use("Write").is_none());
1329
1330        // Not an assistant message
1331        let result_json = r#"{
1332            "type": "result",
1333            "subtype": "success",
1334            "is_error": false,
1335            "duration_ms": 100,
1336            "duration_api_ms": 200,
1337            "num_turns": 1,
1338            "session_id": "abc",
1339            "total_cost_usd": 0.01
1340        }"#;
1341        let result: ClaudeOutput = serde_json::from_str(result_json).unwrap();
1342        assert!(result.as_tool_use("Bash").is_none());
1343    }
1344
1345    #[test]
1346    fn test_tool_uses() {
1347        let json = r#"{
1348            "type": "assistant",
1349            "message": {
1350                "id": "msg_1",
1351                "role": "assistant",
1352                "model": "claude-3",
1353                "content": [
1354                    {"type": "text", "text": "Running commands..."},
1355                    {"type": "tool_use", "id": "tu_1", "name": "Bash", "input": {"command": "ls"}},
1356                    {"type": "tool_use", "id": "tu_2", "name": "Read", "input": {"file_path": "/tmp/a"}},
1357                    {"type": "tool_use", "id": "tu_3", "name": "Write", "input": {"file_path": "/tmp/b", "content": "x"}}
1358                ]
1359            },
1360            "session_id": "abc"
1361        }"#;
1362        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1363
1364        let tools: Vec<_> = output.tool_uses().collect();
1365        assert_eq!(tools.len(), 3);
1366        assert_eq!(tools[0].name, "Bash");
1367        assert_eq!(tools[1].name, "Read");
1368        assert_eq!(tools[2].name, "Write");
1369    }
1370
1371    #[test]
1372    fn test_text_content() {
1373        // Single text block
1374        let json = r#"{
1375            "type": "assistant",
1376            "message": {
1377                "id": "msg_1",
1378                "role": "assistant",
1379                "model": "claude-3",
1380                "content": [{"type": "text", "text": "Hello, world!"}]
1381            },
1382            "session_id": "abc"
1383        }"#;
1384        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1385        assert_eq!(output.text_content(), Some("Hello, world!".to_string()));
1386
1387        // Multiple text blocks
1388        let json = r#"{
1389            "type": "assistant",
1390            "message": {
1391                "id": "msg_1",
1392                "role": "assistant",
1393                "model": "claude-3",
1394                "content": [
1395                    {"type": "text", "text": "Hello, "},
1396                    {"type": "tool_use", "id": "tu_1", "name": "Bash", "input": {}},
1397                    {"type": "text", "text": "world!"}
1398                ]
1399            },
1400            "session_id": "abc"
1401        }"#;
1402        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1403        assert_eq!(output.text_content(), Some("Hello, world!".to_string()));
1404
1405        // No text blocks
1406        let json = r#"{
1407            "type": "assistant",
1408            "message": {
1409                "id": "msg_1",
1410                "role": "assistant",
1411                "model": "claude-3",
1412                "content": [{"type": "tool_use", "id": "tu_1", "name": "Bash", "input": {}}]
1413            },
1414            "session_id": "abc"
1415        }"#;
1416        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1417        assert_eq!(output.text_content(), None);
1418
1419        // Not an assistant message
1420        let json = r#"{
1421            "type": "result",
1422            "subtype": "success",
1423            "is_error": false,
1424            "duration_ms": 100,
1425            "duration_api_ms": 200,
1426            "num_turns": 1,
1427            "session_id": "abc",
1428            "total_cost_usd": 0.01
1429        }"#;
1430        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1431        assert_eq!(output.text_content(), None);
1432    }
1433
1434    #[test]
1435    fn test_as_assistant() {
1436        let json = r#"{
1437            "type": "assistant",
1438            "message": {
1439                "id": "msg_1",
1440                "role": "assistant",
1441                "model": "claude-sonnet-4",
1442                "content": []
1443            },
1444            "session_id": "abc"
1445        }"#;
1446        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1447
1448        let assistant = output.as_assistant();
1449        assert!(assistant.is_some());
1450        assert_eq!(assistant.unwrap().message.model, "claude-sonnet-4");
1451
1452        // Not an assistant
1453        let result_json = r#"{
1454            "type": "result",
1455            "subtype": "success",
1456            "is_error": false,
1457            "duration_ms": 100,
1458            "duration_api_ms": 200,
1459            "num_turns": 1,
1460            "session_id": "abc",
1461            "total_cost_usd": 0.01
1462        }"#;
1463        let result: ClaudeOutput = serde_json::from_str(result_json).unwrap();
1464        assert!(result.as_assistant().is_none());
1465    }
1466
1467    #[test]
1468    fn test_as_result() {
1469        let json = r#"{
1470            "type": "result",
1471            "subtype": "success",
1472            "is_error": false,
1473            "duration_ms": 100,
1474            "duration_api_ms": 200,
1475            "num_turns": 5,
1476            "session_id": "abc",
1477            "total_cost_usd": 0.05
1478        }"#;
1479        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1480
1481        let result = output.as_result();
1482        assert!(result.is_some());
1483        assert_eq!(result.unwrap().num_turns, 5);
1484        assert_eq!(result.unwrap().total_cost_usd, 0.05);
1485
1486        // Not a result
1487        let assistant_json = r#"{
1488            "type": "assistant",
1489            "message": {
1490                "id": "msg_1",
1491                "role": "assistant",
1492                "model": "claude-3",
1493                "content": []
1494            },
1495            "session_id": "abc"
1496        }"#;
1497        let assistant: ClaudeOutput = serde_json::from_str(assistant_json).unwrap();
1498        assert!(assistant.as_result().is_none());
1499    }
1500
1501    #[test]
1502    fn test_as_system() {
1503        let json = r#"{
1504            "type": "system",
1505            "subtype": "init",
1506            "session_id": "abc",
1507            "model": "claude-3"
1508        }"#;
1509        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1510
1511        let system = output.as_system();
1512        assert!(system.is_some());
1513        assert!(system.unwrap().is_init());
1514
1515        // Not a system message
1516        let result_json = r#"{
1517            "type": "result",
1518            "subtype": "success",
1519            "is_error": false,
1520            "duration_ms": 100,
1521            "duration_api_ms": 200,
1522            "num_turns": 1,
1523            "session_id": "abc",
1524            "total_cost_usd": 0.01
1525        }"#;
1526        let result: ClaudeOutput = serde_json::from_str(result_json).unwrap();
1527        assert!(result.as_system().is_none());
1528    }
1529}