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    /// Only beside [`user_message_uuid`](Self::user_message_uuid): `true`
469    /// when a person sent that message (origin `human`), for example from a
470    /// Remote Control client, so a host that did not send it can follow the
471    /// reset as the person's. Absence does not mean that no person did:
472    /// CLIs before 2.1.329 and cloud sessions never send it. Upstream types
473    /// it as the literal `true`. Marked `@internal` upstream.
474    #[serde(default, skip_serializing_if = "Option::is_none")]
475    pub user_message_from_human: Option<bool>,
476    /// When the reset happened, as an ISO 8601 string in UTC from the clock
477    /// of the process that performed it. Meant for display, not for ordering
478    /// frames. Absent from CLIs before 2.1.281; fall back to the time the
479    /// frame was received.
480    #[serde(default, skip_serializing_if = "Option::is_none")]
481    pub timestamp: Option<String>,
482}
483
484/// What discarded the conversation ([`ConversationResetMessage::trigger`],
485/// CLI 2.1.281+).
486#[derive(Debug, Clone, PartialEq, Eq, Hash)]
487pub enum ConversationResetTrigger {
488    /// The `/clear` command (or its `/reset` and `/new` aliases).
489    Clear,
490    /// Leaving plan mode with the clear-context option.
491    PlanModeExit,
492    /// A flow that starts a fresh session to implement an approved plan.
493    FreshSession,
494    /// An onboarding flow re-run inside an existing session.
495    Onboarding,
496    /// A trigger not yet known to this version of the crate.
497    Unknown(String),
498}
499
500impl ConversationResetTrigger {
501    pub fn as_str(&self) -> &str {
502        match self {
503            Self::Clear => "clear",
504            Self::PlanModeExit => "plan_mode_exit",
505            Self::FreshSession => "fresh_session",
506            Self::Onboarding => "onboarding",
507            Self::Unknown(s) => s.as_str(),
508        }
509    }
510}
511
512impl std::fmt::Display for ConversationResetTrigger {
513    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
514        f.write_str(self.as_str())
515    }
516}
517
518impl From<&str> for ConversationResetTrigger {
519    fn from(s: &str) -> Self {
520        match s {
521            "clear" => Self::Clear,
522            "plan_mode_exit" => Self::PlanModeExit,
523            "fresh_session" => Self::FreshSession,
524            "onboarding" => Self::Onboarding,
525            other => Self::Unknown(other.to_string()),
526        }
527    }
528}
529
530impl Serialize for ConversationResetTrigger {
531    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
532        serializer.serialize_str(self.as_str())
533    }
534}
535
536impl<'de> Deserialize<'de> for ConversationResetTrigger {
537    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
538        let s = String::deserialize(deserializer)?;
539        Ok(Self::from(s.as_str()))
540    }
541}
542
543/// Raw preserved record for Claude Code transcript-only message types.
544///
545/// These events are emitted in `~/.claude/projects/**/*.jsonl`, not in the
546/// public `--output-format stream-json` protocol. Keeping them typed at the
547/// top level lets corpus tests parse real transcript files without losing the
548/// original payload.
549#[derive(Debug, Clone, Serialize, Deserialize)]
550pub struct TranscriptMessage {
551    #[serde(flatten)]
552    pub data: Map<String, Value>,
553}
554
555impl ClaudeOutput {
556    /// Get the message type as a string
557    pub fn message_type(&self) -> String {
558        match self {
559            ClaudeOutput::System(_) => "system".to_string(),
560            ClaudeOutput::User(_) => "user".to_string(),
561            ClaudeOutput::Assistant(_) => "assistant".to_string(),
562            ClaudeOutput::Result(_) => "result".to_string(),
563            ClaudeOutput::TranscriptResult(_) => "result".to_string(),
564            ClaudeOutput::ControlRequest(_) => "control_request".to_string(),
565            ClaudeOutput::ControlResponse(_) => "control_response".to_string(),
566            ClaudeOutput::ControlCancelRequest(_) => "control_cancel_request".to_string(),
567            ClaudeOutput::Error(_) => "error".to_string(),
568            ClaudeOutput::RateLimitEvent(_) => "rate_limit_event".to_string(),
569            ClaudeOutput::StreamEvent(_) => "stream_event".to_string(),
570            ClaudeOutput::ToolProgress(_) => "tool_progress".to_string(),
571            ClaudeOutput::CommandLifecycle(_) => "command_lifecycle".to_string(),
572            ClaudeOutput::AuthStatus(_) => "auth_status".to_string(),
573            ClaudeOutput::ToolUseSummary(_) => "tool_use_summary".to_string(),
574            ClaudeOutput::PromptSuggestion(_) => "prompt_suggestion".to_string(),
575            ClaudeOutput::ConversationReset(_) => "conversation_reset".to_string(),
576            ClaudeOutput::Progress(_) => "progress".to_string(),
577            ClaudeOutput::QueueOperation(_) => "queue-operation".to_string(),
578            ClaudeOutput::PrLink(_) => "pr-link".to_string(),
579            ClaudeOutput::FileHistorySnapshot(_) => "file-history-snapshot".to_string(),
580            ClaudeOutput::Summary(_) => "summary".to_string(),
581            ClaudeOutput::Mode(_) => "mode".to_string(),
582            ClaudeOutput::PermissionMode(_) => "permission-mode".to_string(),
583            ClaudeOutput::Attachment(_) => "attachment".to_string(),
584            ClaudeOutput::AiTitle(_) => "ai-title".to_string(),
585            ClaudeOutput::LastPrompt(_) => "last-prompt".to_string(),
586            ClaudeOutput::Started(_) => "started".to_string(),
587        }
588    }
589
590    /// Check if this is a control request (tool permission request)
591    pub fn is_control_request(&self) -> bool {
592        matches!(self, ClaudeOutput::ControlRequest(_))
593    }
594
595    /// Check if this is a control response
596    pub fn is_control_response(&self) -> bool {
597        matches!(self, ClaudeOutput::ControlResponse(_))
598    }
599
600    /// Check if this is an Anthropic API error
601    pub fn is_api_error(&self) -> bool {
602        matches!(self, ClaudeOutput::Error(_))
603    }
604
605    /// Get the control request if this is one
606    pub fn as_control_request(&self) -> Option<&ControlRequest> {
607        match self {
608            ClaudeOutput::ControlRequest(req) => Some(req),
609            _ => None,
610        }
611    }
612
613    /// Check if this is a control cancel request
614    pub fn is_control_cancel_request(&self) -> bool {
615        matches!(self, ClaudeOutput::ControlCancelRequest(_))
616    }
617
618    /// Get the control cancel request if this is one
619    pub fn as_control_cancel_request(&self) -> Option<&ControlCancelRequest> {
620        match self {
621            ClaudeOutput::ControlCancelRequest(req) => Some(req),
622            _ => None,
623        }
624    }
625
626    /// Get the Anthropic error if this is one
627    ///
628    /// # Example
629    /// ```
630    /// use claude_codes::ClaudeOutput;
631    ///
632    /// let json = r#"{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}"#;
633    /// let output: ClaudeOutput = serde_json::from_str(json).unwrap();
634    ///
635    /// if let Some(err) = output.as_anthropic_error() {
636    ///     if err.is_overloaded() {
637    ///         println!("API is overloaded, retrying...");
638    ///     }
639    /// }
640    /// ```
641    pub fn as_anthropic_error(&self) -> Option<&AnthropicError> {
642        match self {
643            ClaudeOutput::Error(err) => Some(err),
644            _ => None,
645        }
646    }
647
648    /// Check if this is a rate limit event
649    pub fn is_rate_limit_event(&self) -> bool {
650        matches!(self, ClaudeOutput::RateLimitEvent(_))
651    }
652
653    /// Get the rate limit event if this is one
654    pub fn as_rate_limit_event(&self) -> Option<&RateLimitEvent> {
655        match self {
656            ClaudeOutput::RateLimitEvent(evt) => Some(evt),
657            _ => None,
658        }
659    }
660
661    /// Check if this is a result with error
662    pub fn is_error(&self) -> bool {
663        matches!(self, ClaudeOutput::Result(r) if r.is_error)
664    }
665
666    /// Check if this is an assistant message
667    pub fn is_assistant_message(&self) -> bool {
668        matches!(self, ClaudeOutput::Assistant(_))
669    }
670
671    /// Check if this is a system message
672    pub fn is_system_message(&self) -> bool {
673        matches!(self, ClaudeOutput::System(_))
674    }
675
676    /// Check if this is a system init message
677    ///
678    /// # Example
679    /// ```
680    /// use claude_codes::ClaudeOutput;
681    ///
682    /// let json = r#"{"type":"system","subtype":"init","session_id":"abc"}"#;
683    /// let output: ClaudeOutput = serde_json::from_str(json).unwrap();
684    /// assert!(output.is_system_init());
685    /// ```
686    pub fn is_system_init(&self) -> bool {
687        matches!(self, ClaudeOutput::System(sys) if sys.is_init())
688    }
689
690    /// Get the session ID from any message type that has one.
691    ///
692    /// Returns the session ID from System, Assistant, or Result messages.
693    /// Returns `None` for User, ControlRequest, and ControlResponse messages.
694    ///
695    /// # Example
696    /// ```
697    /// use claude_codes::ClaudeOutput;
698    ///
699    /// let json = r#"{"type":"result","subtype":"success","is_error":false,
700    ///     "duration_ms":100,"duration_api_ms":200,"num_turns":1,
701    ///     "session_id":"my-session","total_cost_usd":0.01}"#;
702    /// let output: ClaudeOutput = serde_json::from_str(json).unwrap();
703    /// assert_eq!(output.session_id(), Some("my-session"));
704    /// ```
705    pub fn session_id(&self) -> Option<&str> {
706        match self {
707            ClaudeOutput::System(sys) => sys
708                .data
709                .get("session_id")
710                .or_else(|| sys.data.get("sessionId"))
711                .and_then(|v| v.as_str()),
712            ClaudeOutput::Assistant(ass) => Some(&ass.session_id),
713            ClaudeOutput::Result(res) => Some(&res.session_id),
714            ClaudeOutput::TranscriptResult(msg) => msg
715                .data
716                .get("session_id")
717                .or_else(|| msg.data.get("sessionId"))
718                .and_then(|v| v.as_str()),
719            ClaudeOutput::User(_) => None,
720            ClaudeOutput::ControlRequest(_) => None,
721            ClaudeOutput::ControlResponse(_) => None,
722            ClaudeOutput::ControlCancelRequest(msg) => msg.session_id.as_deref(),
723            ClaudeOutput::Error(_) => None,
724            ClaudeOutput::RateLimitEvent(evt) => Some(&evt.session_id),
725            ClaudeOutput::StreamEvent(msg) => Some(&msg.session_id),
726            ClaudeOutput::ToolProgress(msg) => Some(&msg.session_id),
727            ClaudeOutput::CommandLifecycle(msg) => Some(&msg.session_id),
728            ClaudeOutput::AuthStatus(msg) => Some(&msg.session_id),
729            ClaudeOutput::ToolUseSummary(msg) => Some(&msg.session_id),
730            ClaudeOutput::PromptSuggestion(msg) => Some(&msg.session_id),
731            ClaudeOutput::ConversationReset(msg) => Some(&msg.session_id),
732            ClaudeOutput::Progress(msg)
733            | ClaudeOutput::QueueOperation(msg)
734            | ClaudeOutput::PrLink(msg)
735            | ClaudeOutput::FileHistorySnapshot(msg)
736            | ClaudeOutput::Summary(msg)
737            | ClaudeOutput::Mode(msg)
738            | ClaudeOutput::PermissionMode(msg)
739            | ClaudeOutput::Attachment(msg)
740            | ClaudeOutput::AiTitle(msg)
741            | ClaudeOutput::LastPrompt(msg)
742            | ClaudeOutput::Started(msg) => msg
743                .data
744                .get("session_id")
745                .or_else(|| msg.data.get("sessionId"))
746                .and_then(|v| v.as_str()),
747        }
748    }
749
750    /// Get a specific tool use by name from an assistant message.
751    ///
752    /// Returns the first `ToolUseBlock` with the given name, or `None` if this
753    /// is not an assistant message or doesn't contain the specified tool.
754    ///
755    /// # Example
756    /// ```
757    /// use claude_codes::ClaudeOutput;
758    ///
759    /// let json = r#"{"type":"assistant","message":{"id":"msg_1","role":"assistant",
760    ///     "model":"claude-3","content":[{"type":"tool_use","id":"tu_1",
761    ///     "name":"Bash","input":{"command":"ls"}}]},"session_id":"abc"}"#;
762    /// let output: ClaudeOutput = serde_json::from_str(json).unwrap();
763    ///
764    /// if let Some(bash) = output.as_tool_use("Bash") {
765    ///     assert_eq!(bash.name, "Bash");
766    /// }
767    /// ```
768    pub fn as_tool_use(&self, tool_name: &str) -> Option<&ToolUseBlock> {
769        match self {
770            ClaudeOutput::Assistant(ass) => {
771                ass.message.content.iter().find_map(|block| match block {
772                    ContentBlock::ToolUse(tu) if tu.name == tool_name => Some(tu),
773                    _ => None,
774                })
775            }
776            _ => None,
777        }
778    }
779
780    /// Get all tool uses from an assistant message.
781    ///
782    /// Returns an iterator over all `ToolUseBlock`s in the message, or an empty
783    /// iterator if this is not an assistant message.
784    ///
785    /// # Example
786    /// ```
787    /// use claude_codes::ClaudeOutput;
788    ///
789    /// let json = r#"{"type":"assistant","message":{"id":"msg_1","role":"assistant",
790    ///     "model":"claude-3","content":[
791    ///         {"type":"tool_use","id":"tu_1","name":"Read","input":{"file_path":"/tmp/a"}},
792    ///         {"type":"tool_use","id":"tu_2","name":"Write","input":{"file_path":"/tmp/b","content":"x"}}
793    ///     ]},"session_id":"abc"}"#;
794    /// let output: ClaudeOutput = serde_json::from_str(json).unwrap();
795    ///
796    /// let tools: Vec<_> = output.tool_uses().collect();
797    /// assert_eq!(tools.len(), 2);
798    /// ```
799    pub fn tool_uses(&self) -> impl Iterator<Item = &ToolUseBlock> {
800        let content = match self {
801            ClaudeOutput::Assistant(ass) => Some(&ass.message.content),
802            _ => None,
803        };
804
805        content
806            .into_iter()
807            .flat_map(|c| c.iter())
808            .filter_map(|block| match block {
809                ContentBlock::ToolUse(tu) => Some(tu),
810                _ => None,
811            })
812    }
813
814    /// Get text content from an assistant message.
815    ///
816    /// Returns the concatenated text from all text blocks in the message,
817    /// or `None` if this is not an assistant message or has no text content.
818    ///
819    /// # Example
820    /// ```
821    /// use claude_codes::ClaudeOutput;
822    ///
823    /// let json = r#"{"type":"assistant","message":{"id":"msg_1","role":"assistant",
824    ///     "model":"claude-3","content":[{"type":"text","text":"Hello, world!"}]},
825    ///     "session_id":"abc"}"#;
826    /// let output: ClaudeOutput = serde_json::from_str(json).unwrap();
827    /// assert_eq!(output.text_content(), Some("Hello, world!".to_string()));
828    /// ```
829    pub fn text_content(&self) -> Option<String> {
830        match self {
831            ClaudeOutput::Assistant(ass) => {
832                let texts: Vec<&str> = ass
833                    .message
834                    .content
835                    .iter()
836                    .filter_map(|block| match block {
837                        ContentBlock::Text(t) => Some(t.text.as_str()),
838                        _ => None,
839                    })
840                    .collect();
841
842                if texts.is_empty() {
843                    None
844                } else {
845                    Some(texts.join(""))
846                }
847            }
848            _ => None,
849        }
850    }
851
852    /// Get the assistant message if this is one.
853    ///
854    /// # Example
855    /// ```
856    /// use claude_codes::ClaudeOutput;
857    ///
858    /// let json = r#"{"type":"assistant","message":{"id":"msg_1","role":"assistant",
859    ///     "model":"claude-3","content":[]},"session_id":"abc"}"#;
860    /// let output: ClaudeOutput = serde_json::from_str(json).unwrap();
861    ///
862    /// if let Some(assistant) = output.as_assistant() {
863    ///     assert_eq!(assistant.message.model, "claude-3");
864    /// }
865    /// ```
866    pub fn as_assistant(&self) -> Option<&AssistantMessage> {
867        match self {
868            ClaudeOutput::Assistant(ass) => Some(ass),
869            _ => None,
870        }
871    }
872
873    /// Get the result message if this is one.
874    ///
875    /// # Example
876    /// ```
877    /// use claude_codes::ClaudeOutput;
878    ///
879    /// let json = r#"{"type":"result","subtype":"success","is_error":false,
880    ///     "duration_ms":100,"duration_api_ms":200,"num_turns":1,
881    ///     "session_id":"abc","total_cost_usd":0.01}"#;
882    /// let output: ClaudeOutput = serde_json::from_str(json).unwrap();
883    ///
884    /// if let Some(result) = output.as_result() {
885    ///     assert!(!result.is_error);
886    /// }
887    /// ```
888    pub fn as_result(&self) -> Option<&ResultMessage> {
889        match self {
890            ClaudeOutput::Result(res) => Some(res),
891            _ => None,
892        }
893    }
894
895    /// Get the system message if this is one.
896    pub fn as_system(&self) -> Option<&SystemMessage> {
897        match self {
898            ClaudeOutput::System(sys) => Some(sys),
899            _ => None,
900        }
901    }
902
903    /// Parse a JSON string, handling potential ANSI escape codes and other prefixes
904    /// This method will:
905    /// 1. First try to parse as-is
906    /// 2. If that fails, trim until it finds a '{' and try again
907    pub fn parse_json_tolerant(s: &str) -> Result<ClaudeOutput, ParseError> {
908        // First try to parse as-is
909        match Self::parse_json(s) {
910            Ok(output) => Ok(output),
911            Err(first_error) => {
912                // If that fails, look for the first '{' character
913                if let Some(json_start) = s.find('{') {
914                    let trimmed = &s[json_start..];
915                    match Self::parse_json(trimmed) {
916                        Ok(output) => Ok(output),
917                        Err(_) => {
918                            // Return the original error if both attempts fail
919                            Err(first_error)
920                        }
921                    }
922                } else {
923                    Err(first_error)
924                }
925            }
926        }
927    }
928
929    /// Parse a JSON string, returning ParseError with raw JSON if it doesn't match our types
930    pub fn parse_json(s: &str) -> Result<ClaudeOutput, ParseError> {
931        // First try to parse as a Value
932        let value: Value = serde_json::from_str(s).map_err(|e| ParseError {
933            raw_line: s.to_string(),
934            raw_json: None,
935            error_message: format!("Invalid JSON: {}", e),
936        })?;
937
938        // Then try to parse that Value as ClaudeOutput
939        serde_json::from_value::<ClaudeOutput>(value.clone()).map_err(|e| ParseError {
940            raw_line: s.to_string(),
941            raw_json: Some(value),
942            error_message: e.to_string(),
943        })
944    }
945}
946
947impl<'de> Deserialize<'de> for ClaudeOutput {
948    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
949        let value = Value::deserialize(deserializer)?;
950        let message_type = value
951            .get("type")
952            .and_then(|v| v.as_str())
953            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
954        let mut payload = value.clone();
955        if let Some(obj) = payload.as_object_mut() {
956            obj.remove("type");
957        }
958
959        fn parse<T, E>(value: Value) -> Result<T, E>
960        where
961            T: serde::de::DeserializeOwned,
962            E: serde::de::Error,
963        {
964            serde_json::from_value(value).map_err(E::custom)
965        }
966
967        match message_type {
968            "system" => parse(payload).map(Self::System),
969            "user" => parse(payload).map(Self::User),
970            "assistant" => parse(payload).map(Self::Assistant),
971            "result" if value.get("subtype").is_some() => parse(payload).map(Self::Result),
972            "result" => parse(payload).map(Self::TranscriptResult),
973            "control_request" => parse(payload).map(Self::ControlRequest),
974            "control_response" => parse(payload).map(Self::ControlResponse),
975            "control_cancel_request" => parse(payload).map(Self::ControlCancelRequest),
976            "error" => parse(payload).map(Self::Error),
977            "rate_limit_event" => parse(payload).map(Self::RateLimitEvent),
978            "stream_event" => parse(payload).map(Self::StreamEvent),
979            "tool_progress" => parse(payload).map(Self::ToolProgress),
980            "command_lifecycle" => parse(payload).map(Self::CommandLifecycle),
981            "auth_status" => parse(payload).map(Self::AuthStatus),
982            "tool_use_summary" => parse(payload).map(Self::ToolUseSummary),
983            "prompt_suggestion" => parse(payload).map(Self::PromptSuggestion),
984            "conversation_reset" => parse(payload).map(Self::ConversationReset),
985            "progress" => parse(payload).map(Self::Progress),
986            "queue-operation" => parse(payload).map(Self::QueueOperation),
987            "pr-link" => parse(payload).map(Self::PrLink),
988            "file-history-snapshot" => parse(payload).map(Self::FileHistorySnapshot),
989            "summary" => parse(payload).map(Self::Summary),
990            "mode" => parse(payload).map(Self::Mode),
991            "permission-mode" => parse(payload).map(Self::PermissionMode),
992            "attachment" => parse(payload).map(Self::Attachment),
993            "ai-title" => parse(payload).map(Self::AiTitle),
994            "last-prompt" => parse(payload).map(Self::LastPrompt),
995            "started" => parse(payload).map(Self::Started),
996            other => Err(serde::de::Error::unknown_variant(
997                other,
998                &[
999                    "system",
1000                    "user",
1001                    "assistant",
1002                    "result",
1003                    "control_request",
1004                    "control_response",
1005                    "control_cancel_request",
1006                    "error",
1007                    "rate_limit_event",
1008                    "stream_event",
1009                    "tool_progress",
1010                    "command_lifecycle",
1011                    "auth_status",
1012                    "tool_use_summary",
1013                    "prompt_suggestion",
1014                    "conversation_reset",
1015                    "progress",
1016                    "queue-operation",
1017                    "pr-link",
1018                    "file-history-snapshot",
1019                    "summary",
1020                    "mode",
1021                    "permission-mode",
1022                    "attachment",
1023                    "ai-title",
1024                    "last-prompt",
1025                    "started",
1026                ],
1027            )),
1028        }
1029    }
1030}
1031
1032#[cfg(test)]
1033mod tests {
1034    use super::*;
1035
1036    #[test]
1037    fn test_deserialize_control_cancel_request() {
1038        let json = r#"{"request_id":"00aea85d-70f9-4cc4-becc-b0f05f5037f3","type":"control_cancel_request"}"#;
1039        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1040        assert!(output.is_control_cancel_request());
1041        assert_eq!(output.message_type(), "control_cancel_request");
1042        assert_eq!(output.session_id(), None);
1043        let cancel = output.as_control_cancel_request().unwrap();
1044        assert_eq!(cancel.request_id, "00aea85d-70f9-4cc4-becc-b0f05f5037f3");
1045
1046        let round_trip: Value = serde_json::to_value(&output).unwrap();
1047        assert_eq!(round_trip, serde_json::from_str::<Value>(json).unwrap());
1048
1049        let bridged = r#"{"type":"control_cancel_request","request_id":"r1","session_id":"s1"}"#;
1050        let output: ClaudeOutput = serde_json::from_str(bridged).unwrap();
1051        assert_eq!(output.session_id(), Some("s1"));
1052    }
1053
1054    #[test]
1055    fn test_deserialize_assistant_message() {
1056        let json = r#"{
1057            "type": "assistant",
1058            "message": {
1059                "id": "msg_123",
1060                "role": "assistant",
1061                "model": "claude-3-sonnet",
1062                "content": [{"type": "text", "text": "Hello! How can I help you?"}]
1063            },
1064            "session_id": "123"
1065        }"#;
1066
1067        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1068        assert!(output.is_assistant_message());
1069    }
1070
1071    #[test]
1072    fn test_deserialize_new_top_level_message_types() {
1073        let cases = [
1074            (
1075                r#"{"type":"stream_event","event":{"type":"content_block_delta"},"parent_tool_use_id":null,"uuid":"u1","session_id":"s1","ttft_ms":12}"#,
1076                "stream_event",
1077            ),
1078            (
1079                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"}"#,
1080                "tool_progress",
1081            ),
1082            (
1083                r#"{"type":"auth_status","isAuthenticating":true,"output":["login"],"uuid":"u3","session_id":"s3"}"#,
1084                "auth_status",
1085            ),
1086            (
1087                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"}"#,
1088                "tool_use_summary",
1089            ),
1090            (
1091                r#"{"type":"prompt_suggestion","suggestion":"Run tests","uuid":"u5","session_id":"s5"}"#,
1092                "prompt_suggestion",
1093            ),
1094            (
1095                r#"{"type":"conversation_reset","new_conversation_id":"new-session","uuid":"u6","session_id":"s6"}"#,
1096                "conversation_reset",
1097            ),
1098            (
1099                r#"{"type":"command_lifecycle","command_uuid":"cmd-1","state":"queued","uuid":"u7","session_id":"s7"}"#,
1100                "command_lifecycle",
1101            ),
1102        ];
1103
1104        for (json, message_type) in cases {
1105            let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1106            assert_eq!(output.message_type(), message_type);
1107            assert!(output.session_id().is_some());
1108        }
1109    }
1110
1111    #[test]
1112    fn test_command_lifecycle_states_roundtrip() {
1113        for state in ["queued", "started", "completed", "cancelled", "discarded"] {
1114            let json = format!(
1115                r#"{{"type":"command_lifecycle","command_uuid":"cmd-1","state":"{}","uuid":"u1","session_id":"s1"}}"#,
1116                state
1117            );
1118            let output: ClaudeOutput = serde_json::from_str(&json).unwrap();
1119            let ClaudeOutput::CommandLifecycle(msg) = &output else {
1120                panic!("expected CommandLifecycle");
1121            };
1122            assert_eq!(msg.state.as_str(), state);
1123            assert!(!matches!(msg.state, CommandLifecycleState::Unknown(_)));
1124            assert_eq!(serde_json::to_string(&output).unwrap(), json);
1125        }
1126
1127        // Unknown states survive decode and round-trip verbatim.
1128        let json = r#"{"type":"command_lifecycle","command_uuid":"cmd-2","state":"parked","uuid":"u2","session_id":"s2"}"#;
1129        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1130        let ClaudeOutput::CommandLifecycle(msg) = &output else {
1131            panic!("expected CommandLifecycle");
1132        };
1133        assert_eq!(
1134            msg.state,
1135            CommandLifecycleState::Unknown("parked".to_string())
1136        );
1137        assert_eq!(serde_json::to_string(&output).unwrap(), json);
1138    }
1139
1140    #[test]
1141    fn test_tool_progress_heartbeat_and_subagent_retry() {
1142        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"}}"#;
1143        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1144        let ClaudeOutput::ToolProgress(msg) = &output else {
1145            panic!("expected ToolProgress");
1146        };
1147        assert_eq!(msg.heartbeat, Some(true));
1148        assert_eq!(msg.subagent_type.as_deref(), Some("Explore"));
1149        let retry = msg.subagent_retry.as_ref().unwrap();
1150        assert_eq!(retry.attempt, 2);
1151        assert_eq!(retry.error_status, Some(529));
1152        assert_eq!(retry.error_category, "overloaded");
1153
1154        // Null error_status parses too.
1155        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"}}"#;
1156        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1157        let ClaudeOutput::ToolProgress(msg) = &output else {
1158            panic!("expected ToolProgress");
1159        };
1160        assert_eq!(msg.subagent_retry.as_ref().unwrap().error_status, None);
1161    }
1162
1163    #[test]
1164    fn test_deserialize_transcript_only_message_types() {
1165        let cases = [
1166            (
1167                r#"{"type":"progress","sessionId":"s1","content":"delta"}"#,
1168                "progress",
1169                Some("s1"),
1170            ),
1171            (
1172                r#"{"type":"queue-operation","sessionId":"s2","operation":"push"}"#,
1173                "queue-operation",
1174                Some("s2"),
1175            ),
1176            (
1177                r#"{"type":"pr-link","sessionId":"s3","url":"https://example.invalid/pr"}"#,
1178                "pr-link",
1179                Some("s3"),
1180            ),
1181            (
1182                r#"{"type":"file-history-snapshot","sessionId":"s4","files":[]}"#,
1183                "file-history-snapshot",
1184                Some("s4"),
1185            ),
1186            (r#"{"type":"summary","summary":"Done"}"#, "summary", None),
1187            (
1188                r#"{"type":"mode","mode":"normal","sessionId":"s5"}"#,
1189                "mode",
1190                Some("s5"),
1191            ),
1192            (
1193                r#"{"type":"permission-mode","permissionMode":"default","sessionId":"s6"}"#,
1194                "permission-mode",
1195                Some("s6"),
1196            ),
1197            (
1198                r#"{"type":"attachment","attachment":{"type":"task_reminder"},"sessionId":"s7"}"#,
1199                "attachment",
1200                Some("s7"),
1201            ),
1202            (
1203                r#"{"type":"ai-title","aiTitle":"Title","sessionId":"s8"}"#,
1204                "ai-title",
1205                Some("s8"),
1206            ),
1207            (
1208                r#"{"type":"last-prompt","lastPrompt":"prompt","sessionId":"s9"}"#,
1209                "last-prompt",
1210                Some("s9"),
1211            ),
1212            (
1213                r#"{"type":"started","sessionId":"s10"}"#,
1214                "started",
1215                Some("s10"),
1216            ),
1217            (
1218                r#"{"type":"result","key":"k","agentId":"a","result":{"ok":true}}"#,
1219                "result",
1220                None,
1221            ),
1222        ];
1223
1224        for (json, message_type, session_id) in cases {
1225            let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1226            assert_eq!(output.message_type(), message_type);
1227            assert_eq!(output.session_id(), session_id);
1228        }
1229    }
1230
1231    #[test]
1232    fn test_transcript_assistant_accepts_camel_case_session_id() {
1233        let json = r#"{
1234            "type": "assistant",
1235            "sessionId": "camel-session",
1236            "message": {
1237                "id": "msg_123",
1238                "role": "assistant",
1239                "model": "claude-3-sonnet",
1240                "content": [{"type": "text", "text": "Hello"}]
1241            }
1242        }"#;
1243
1244        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1245        assert_eq!(output.session_id(), Some("camel-session"));
1246    }
1247
1248    #[test]
1249    fn test_is_system_init() {
1250        let init_json = r#"{
1251            "type": "system",
1252            "subtype": "init",
1253            "session_id": "test-session"
1254        }"#;
1255        let output: ClaudeOutput = serde_json::from_str(init_json).unwrap();
1256        assert!(output.is_system_init());
1257
1258        let status_json = r#"{
1259            "type": "system",
1260            "subtype": "status",
1261            "session_id": "test-session"
1262        }"#;
1263        let output: ClaudeOutput = serde_json::from_str(status_json).unwrap();
1264        assert!(!output.is_system_init());
1265    }
1266
1267    #[test]
1268    fn test_session_id() {
1269        // Result message
1270        let result_json = r#"{
1271            "type": "result",
1272            "subtype": "success",
1273            "is_error": false,
1274            "duration_ms": 100,
1275            "duration_api_ms": 200,
1276            "num_turns": 1,
1277            "session_id": "result-session",
1278            "total_cost_usd": 0.01
1279        }"#;
1280        let output: ClaudeOutput = serde_json::from_str(result_json).unwrap();
1281        assert_eq!(output.session_id(), Some("result-session"));
1282
1283        // Assistant message
1284        let assistant_json = r#"{
1285            "type": "assistant",
1286            "message": {
1287                "id": "msg_1",
1288                "role": "assistant",
1289                "model": "claude-3",
1290                "content": []
1291            },
1292            "session_id": "assistant-session"
1293        }"#;
1294        let output: ClaudeOutput = serde_json::from_str(assistant_json).unwrap();
1295        assert_eq!(output.session_id(), Some("assistant-session"));
1296
1297        // System message
1298        let system_json = r#"{
1299            "type": "system",
1300            "subtype": "init",
1301            "session_id": "system-session"
1302        }"#;
1303        let output: ClaudeOutput = serde_json::from_str(system_json).unwrap();
1304        assert_eq!(output.session_id(), Some("system-session"));
1305    }
1306
1307    #[test]
1308    fn test_as_tool_use() {
1309        let json = r#"{
1310            "type": "assistant",
1311            "message": {
1312                "id": "msg_1",
1313                "role": "assistant",
1314                "model": "claude-3",
1315                "content": [
1316                    {"type": "text", "text": "Let me run that command."},
1317                    {"type": "tool_use", "id": "tu_1", "name": "Bash", "input": {"command": "ls -la"}},
1318                    {"type": "tool_use", "id": "tu_2", "name": "Read", "input": {"file_path": "/tmp/test"}}
1319                ]
1320            },
1321            "session_id": "abc"
1322        }"#;
1323        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1324
1325        // Find Bash tool
1326        let bash = output.as_tool_use("Bash");
1327        assert!(bash.is_some());
1328        assert_eq!(bash.unwrap().id, "tu_1");
1329
1330        // Find Read tool
1331        let read = output.as_tool_use("Read");
1332        assert!(read.is_some());
1333        assert_eq!(read.unwrap().id, "tu_2");
1334
1335        // Non-existent tool
1336        assert!(output.as_tool_use("Write").is_none());
1337
1338        // Not an assistant message
1339        let result_json = r#"{
1340            "type": "result",
1341            "subtype": "success",
1342            "is_error": false,
1343            "duration_ms": 100,
1344            "duration_api_ms": 200,
1345            "num_turns": 1,
1346            "session_id": "abc",
1347            "total_cost_usd": 0.01
1348        }"#;
1349        let result: ClaudeOutput = serde_json::from_str(result_json).unwrap();
1350        assert!(result.as_tool_use("Bash").is_none());
1351    }
1352
1353    #[test]
1354    fn test_tool_uses() {
1355        let json = r#"{
1356            "type": "assistant",
1357            "message": {
1358                "id": "msg_1",
1359                "role": "assistant",
1360                "model": "claude-3",
1361                "content": [
1362                    {"type": "text", "text": "Running commands..."},
1363                    {"type": "tool_use", "id": "tu_1", "name": "Bash", "input": {"command": "ls"}},
1364                    {"type": "tool_use", "id": "tu_2", "name": "Read", "input": {"file_path": "/tmp/a"}},
1365                    {"type": "tool_use", "id": "tu_3", "name": "Write", "input": {"file_path": "/tmp/b", "content": "x"}}
1366                ]
1367            },
1368            "session_id": "abc"
1369        }"#;
1370        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1371
1372        let tools: Vec<_> = output.tool_uses().collect();
1373        assert_eq!(tools.len(), 3);
1374        assert_eq!(tools[0].name, "Bash");
1375        assert_eq!(tools[1].name, "Read");
1376        assert_eq!(tools[2].name, "Write");
1377    }
1378
1379    #[test]
1380    fn test_text_content() {
1381        // Single text block
1382        let json = r#"{
1383            "type": "assistant",
1384            "message": {
1385                "id": "msg_1",
1386                "role": "assistant",
1387                "model": "claude-3",
1388                "content": [{"type": "text", "text": "Hello, world!"}]
1389            },
1390            "session_id": "abc"
1391        }"#;
1392        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1393        assert_eq!(output.text_content(), Some("Hello, world!".to_string()));
1394
1395        // Multiple text blocks
1396        let json = r#"{
1397            "type": "assistant",
1398            "message": {
1399                "id": "msg_1",
1400                "role": "assistant",
1401                "model": "claude-3",
1402                "content": [
1403                    {"type": "text", "text": "Hello, "},
1404                    {"type": "tool_use", "id": "tu_1", "name": "Bash", "input": {}},
1405                    {"type": "text", "text": "world!"}
1406                ]
1407            },
1408            "session_id": "abc"
1409        }"#;
1410        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1411        assert_eq!(output.text_content(), Some("Hello, world!".to_string()));
1412
1413        // No text blocks
1414        let json = r#"{
1415            "type": "assistant",
1416            "message": {
1417                "id": "msg_1",
1418                "role": "assistant",
1419                "model": "claude-3",
1420                "content": [{"type": "tool_use", "id": "tu_1", "name": "Bash", "input": {}}]
1421            },
1422            "session_id": "abc"
1423        }"#;
1424        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1425        assert_eq!(output.text_content(), None);
1426
1427        // Not an assistant message
1428        let json = r#"{
1429            "type": "result",
1430            "subtype": "success",
1431            "is_error": false,
1432            "duration_ms": 100,
1433            "duration_api_ms": 200,
1434            "num_turns": 1,
1435            "session_id": "abc",
1436            "total_cost_usd": 0.01
1437        }"#;
1438        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1439        assert_eq!(output.text_content(), None);
1440    }
1441
1442    #[test]
1443    fn test_as_assistant() {
1444        let json = r#"{
1445            "type": "assistant",
1446            "message": {
1447                "id": "msg_1",
1448                "role": "assistant",
1449                "model": "claude-sonnet-4",
1450                "content": []
1451            },
1452            "session_id": "abc"
1453        }"#;
1454        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1455
1456        let assistant = output.as_assistant();
1457        assert!(assistant.is_some());
1458        assert_eq!(assistant.unwrap().message.model, "claude-sonnet-4");
1459
1460        // Not an assistant
1461        let result_json = r#"{
1462            "type": "result",
1463            "subtype": "success",
1464            "is_error": false,
1465            "duration_ms": 100,
1466            "duration_api_ms": 200,
1467            "num_turns": 1,
1468            "session_id": "abc",
1469            "total_cost_usd": 0.01
1470        }"#;
1471        let result: ClaudeOutput = serde_json::from_str(result_json).unwrap();
1472        assert!(result.as_assistant().is_none());
1473    }
1474
1475    #[test]
1476    fn test_as_result() {
1477        let json = r#"{
1478            "type": "result",
1479            "subtype": "success",
1480            "is_error": false,
1481            "duration_ms": 100,
1482            "duration_api_ms": 200,
1483            "num_turns": 5,
1484            "session_id": "abc",
1485            "total_cost_usd": 0.05
1486        }"#;
1487        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1488
1489        let result = output.as_result();
1490        assert!(result.is_some());
1491        assert_eq!(result.unwrap().num_turns, 5);
1492        assert_eq!(result.unwrap().total_cost_usd, 0.05);
1493
1494        // Not a result
1495        let assistant_json = r#"{
1496            "type": "assistant",
1497            "message": {
1498                "id": "msg_1",
1499                "role": "assistant",
1500                "model": "claude-3",
1501                "content": []
1502            },
1503            "session_id": "abc"
1504        }"#;
1505        let assistant: ClaudeOutput = serde_json::from_str(assistant_json).unwrap();
1506        assert!(assistant.as_result().is_none());
1507    }
1508
1509    #[test]
1510    fn test_as_system() {
1511        let json = r#"{
1512            "type": "system",
1513            "subtype": "init",
1514            "session_id": "abc",
1515            "model": "claude-3"
1516        }"#;
1517        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1518
1519        let system = output.as_system();
1520        assert!(system.is_some());
1521        assert!(system.unwrap().is_init());
1522
1523        // Not a system message
1524        let result_json = r#"{
1525            "type": "result",
1526            "subtype": "success",
1527            "is_error": false,
1528            "duration_ms": 100,
1529            "duration_api_ms": 200,
1530            "num_turns": 1,
1531            "session_id": "abc",
1532            "total_cost_usd": 0.01
1533        }"#;
1534        let result: ClaudeOutput = serde_json::from_str(result_json).unwrap();
1535        assert!(result.as_system().is_none());
1536    }
1537}