claude-session-types 0.1.0

Type definitions for Claude Code session event parsing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
//! Tool result types (Level 5)
//!
//! Found in `.toolUseResult` field of user messages that contain tool results.
//!
//! # Tool Result Types
//!
//! ```text
//! Tool Results (.toolUseResult.type)
//! ├── text (28,313)    - Text output from tools (Bash, Read, Grep)
//! ├── create (1,895)   - File creation result (Write)
//! ├── update (155)     - File update result (Edit)
//! ├── delete           - File deletion result
//! ├── read             - File read result (structured)
//! └── error            - Tool execution error
//! ```
//!
//! # Usage
//!
//! Tool results appear in user messages after tool execution:
//!
//! ```json
//! {
//!   "type": "user",
//!   "toolUseResult": {
//!     "type": "create",
//!     "filePath": "/path/to/new_file.rs",
//!     "content": "// File contents",
//!     "structuredPatch": [],
//!     "originalFile": null
//!   }
//! }
//! ```

use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value as JsonValue;

/// Tool use result discriminator
///
/// Represents the structured result of a tool execution.
///
/// # Links
///
/// - Present in `UserEvent.tool_use_result`
/// - Also in `ToolResultBlock.tool_use_result`
/// - Links to `ToolUseBlock.id` via `tool_use_id`
///
/// # Frequency (per large session)
///
/// - `Text`: ~28k (most common - Bash, Read, etc.)
/// - `Create`: ~1.9k (Write tool)
/// - `Update`: ~155 (Edit tool)
/// - Others: rare
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum ToolUseResult {
    /// Text result (from Bash, Read, Grep, etc.)
    ///
    /// Most common tool result type. Contains plain text output.
    ///
    /// # Example
    ///
    /// ```json
    /// {
    ///   "type": "text",
    ///   "content": "cargo build succeeded"
    /// }
    /// ```
    Text(TextResult),

    /// File creation result (from Write tool)
    ///
    /// Contains full file contents and metadata.
    ///
    /// # Example
    ///
    /// ```json
    /// {
    ///   "type": "create",
    ///   "filePath": "/path/to/new_file.rs",
    ///   "content": "pub fn main() {}",
    ///   "structuredPatch": [],
    ///   "originalFile": null
    /// }
    /// ```
    Create(CreateResult),

    /// File update result (from Edit tool)
    ///
    /// Contains updated file contents and diff information.
    ///
    /// # Example
    ///
    /// ```json
    /// {
    ///   "type": "update",
    ///   "filePath": "/path/to/file.rs",
    ///   "content": "pub fn main() { println!(\"Hello\"); }",
    ///   "structuredPatch": [
    ///     {"oldStart": 1, "oldLines": 1, "newStart": 1, "newLines": 1}
    ///   ],
    ///   "originalFile": "pub fn main() {}"
    /// }
    /// ```
    Update(UpdateResult),

    /// File deletion result
    ///
    /// Confirms file was deleted.
    ///
    /// # Example
    ///
    /// ```json
    /// {
    ///   "type": "delete",
    ///   "filePath": "/path/to/deleted_file.rs"
    /// }
    /// ```
    Delete(DeleteResult),

    /// File read result (structured)
    ///
    /// Structured result from Read tool with metadata.
    ///
    /// # Example
    ///
    /// ```json
    /// {
    ///   "type": "read",
    ///   "filePath": "/path/to/file.rs",
    ///   "content": "pub fn main() {}",
    ///   "lineCount": 1
    /// }
    /// ```
    Read(ReadResult),

    /// Tool execution error
    ///
    /// Contains error details when tool execution fails.
    ///
    /// # Example
    ///
    /// ```json
    /// {
    ///   "type": "error",
    ///   "error": "File not found: /path/to/missing.rs",
    ///   "toolName": "Read"
    /// }
    /// ```
    Error(ErrorResult),

    /// Image result
    ///
    /// Contains image data from tool execution.
    ///
    /// # Example
    ///
    /// ```json
    /// {
    ///   "type": "image",
    ///   "source": {
    ///     "type": "base64",
    ///     "media_type": "image/png",
    ///     "data": "iVBORw0KGgo..."
    ///   }
    /// }
    /// ```
    ///
    /// # Frequency
    ///
    /// ~77 occurrences per large session
    Image(ImageResult),

    /// Unknown tool result type (forward compatibility)
    #[serde(other)]
    Unknown,
}

impl ToolUseResult {
    /// Extract file path if this is a file operation
    pub fn file_path(&self) -> Option<&str> {
        match self {
            Self::Create(r) => Some(&r.file_path),
            Self::Update(r) => Some(&r.file_path),
            Self::Delete(r) => Some(&r.file_path),
            Self::Read(r) => Some(&r.file_path),
            Self::Image(r) => r.file_path.as_deref(),
            _ => None,
        }
    }

    /// Check if this is a file creation
    pub fn is_create(&self) -> bool {
        matches!(self, Self::Create(_))
    }

    /// Check if this is a file update
    pub fn is_update(&self) -> bool {
        matches!(self, Self::Update(_))
    }

    /// Check if this is an error
    pub fn is_error(&self) -> bool {
        matches!(self, Self::Error(_))
    }

    /// Check if this is an image
    pub fn is_image(&self) -> bool {
        matches!(self, Self::Image(_))
    }

    /// Extract text content if available
    pub fn text_content(&self) -> Option<&str> {
        match self {
            Self::Text(r) => Some(&r.content),
            Self::Create(r) => Some(&r.content),
            Self::Update(r) => Some(&r.content),
            Self::Read(r) => Some(&r.content),
            _ => None,
        }
    }

    /// Get create result if this is create
    pub fn as_create(&self) -> Option<&CreateResult> {
        match self {
            Self::Create(r) => Some(r),
            _ => None,
        }
    }

    /// Get update result if this is update
    pub fn as_update(&self) -> Option<&UpdateResult> {
        match self {
            Self::Update(r) => Some(r),
            _ => None,
        }
    }
}

/// Deserialize an optional `toolUseResult` field leniently.
///
/// The `type` tag on a real transcript sometimes matches a known
/// [`ToolUseResult`] variant while the surrounding shape does not — e.g. a
/// `"text"`-tagged result that carries a `file` object instead of the
/// documented plain `content: String` (observed in real system-reminder tool
/// results). Internally tagged enums commit to the matched variant once the
/// tag is read, so a shape mismatch there fails the whole field, and because
/// this field lives on the same struct as the message text, that failure used
/// to drop the entire surrounding event — losing a real human-visible turn
/// over an untyped structured extra. Any shape that does not fit a known
/// variant is treated as absent (`None`) rather than propagated as an error.
pub fn deserialize_tool_use_result_lenient<'de, D>(
    deserializer: D,
) -> Result<Option<ToolUseResult>, D::Error>
where
    D: Deserializer<'de>,
{
    let value: Option<JsonValue> = Option::deserialize(deserializer)?;
    Ok(value.and_then(|raw| serde_json::from_value(raw).ok()))
}

/// Text result (most common)
///
/// Plain text output from tools like Bash, Grep, Glob, etc.
///
/// # Frequency
///
/// ~28k occurrences per large session (most common tool result)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TextResult {
    /// Text content
    pub content: String,
}

/// File creation result
///
/// Result from Write tool creating a new file.
///
/// # Frequency
///
/// ~1,895 occurrences per large session
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateResult {
    /// Path to created file
    #[serde(rename = "filePath")]
    pub file_path: String,

    /// New file contents
    pub content: String,

    /// Structured patch (typically empty for new files)
    #[serde(rename = "structuredPatch")]
    pub structured_patch: Vec<PatchHunk>,

    /// Original file contents (null for new files)
    #[serde(rename = "originalFile")]
    pub original_file: Option<String>,
}

/// File update result
///
/// Result from Edit tool modifying an existing file.
///
/// # Frequency
///
/// ~155 occurrences per large session
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateResult {
    /// Path to updated file
    #[serde(rename = "filePath")]
    pub file_path: String,

    /// Updated file contents
    pub content: String,

    /// Structured patch (diff information)
    #[serde(rename = "structuredPatch")]
    pub structured_patch: Vec<PatchHunk>,

    /// Original file contents (before edit)
    #[serde(rename = "originalFile")]
    pub original_file: Option<String>,
}

/// File deletion result
///
/// Result from tool deleting a file.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeleteResult {
    /// Path to deleted file
    #[serde(rename = "filePath")]
    pub file_path: String,
}

/// File read result (structured)
///
/// Structured result from Read tool with metadata.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReadResult {
    /// Path to read file
    #[serde(rename = "filePath")]
    pub file_path: String,

    /// File contents
    pub content: String,

    /// Number of lines in file
    #[serde(rename = "lineCount")]
    pub line_count: Option<u64>,
}

/// Tool execution error
///
/// Error details when tool execution fails.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorResult {
    /// Error message
    pub error: String,

    /// Tool name that failed
    #[serde(rename = "toolName")]
    pub tool_name: Option<String>,

    /// Additional error context
    #[serde(flatten)]
    pub extra: JsonValue,
}

/// Image result
///
/// Contains image data from tool execution.
///
/// # Frequency
///
/// ~77 occurrences per large session
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageResult {
    /// Image source
    pub source: ImageSource,

    /// Optional file path if image was saved
    #[serde(rename = "filePath")]
    pub file_path: Option<String>,
}

/// Image source for ImageResult
///
/// Contains base64-encoded image data and media type.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageSource {
    /// Source type (typically "base64")
    #[serde(rename = "type")]
    pub source_type: String,

    /// Media type (MIME type)
    ///
    /// Examples: `"image/png"`, `"image/jpeg"`, `"image/webp"`
    #[serde(rename = "media_type")]
    pub media_type: String,

    /// Base64-encoded image data
    pub data: String,
}

/// Patch hunk (unified diff format)
///
/// Represents a single hunk in a diff, describing changes to a file.
///
/// # Example
///
/// ```json
/// {
///   "oldStart": 10,
///   "oldLines": 5,
///   "newStart": 10,
///   "newLines": 7
/// }
/// ```
///
/// This represents:
/// - Lines 10-14 in old file (5 lines)
/// - Replaced with lines 10-16 in new file (7 lines)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PatchHunk {
    /// Starting line in old file
    #[serde(rename = "oldStart")]
    pub old_start: u64,

    /// Number of lines in old file
    #[serde(rename = "oldLines")]
    pub old_lines: u64,

    /// Starting line in new file
    #[serde(rename = "newStart")]
    pub new_start: u64,

    /// Number of lines in new file
    #[serde(rename = "newLines")]
    pub new_lines: u64,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_text_result() {
        let json = r#"{
            "type": "text",
            "content": "cargo build succeeded"
        }"#;

        let result: ToolUseResult = serde_json::from_str(json).unwrap();
        assert!(matches!(result, ToolUseResult::Text(_)));

        if let ToolUseResult::Text(text) = result {
            assert_eq!(text.content, "cargo build succeeded");
        }
    }

    #[test]
    fn test_parse_create_result() {
        let json = r#"{
            "type": "create",
            "filePath": "/test/new_file.rs",
            "content": "pub fn main() {}",
            "structuredPatch": [],
            "originalFile": null
        }"#;

        let result: ToolUseResult = serde_json::from_str(json).unwrap();
        assert!(result.is_create());
        assert_eq!(result.file_path(), Some("/test/new_file.rs"));

        if let ToolUseResult::Create(create) = result {
            assert_eq!(create.file_path, "/test/new_file.rs");
            assert_eq!(create.content, "pub fn main() {}");
            assert!(create.structured_patch.is_empty());
            assert!(create.original_file.is_none());
        }
    }

    #[test]
    fn test_parse_update_result() {
        let json = r#"{
            "type": "update",
            "filePath": "/test/file.rs",
            "content": "pub fn main() { println!(\"Hello\"); }",
            "structuredPatch": [
                {
                    "oldStart": 1,
                    "oldLines": 1,
                    "newStart": 1,
                    "newLines": 1
                }
            ],
            "originalFile": "pub fn main() {}"
        }"#;

        let result: ToolUseResult = serde_json::from_str(json).unwrap();
        assert!(result.is_update());
        assert_eq!(result.file_path(), Some("/test/file.rs"));

        if let ToolUseResult::Update(update) = result {
            assert_eq!(update.file_path, "/test/file.rs");
            assert_eq!(update.content, "pub fn main() { println!(\"Hello\"); }");
            assert_eq!(update.structured_patch.len(), 1);
            assert_eq!(update.original_file, Some("pub fn main() {}".to_string()));

            let patch = &update.structured_patch[0];
            assert_eq!(patch.old_start, 1);
            assert_eq!(patch.old_lines, 1);
            assert_eq!(patch.new_start, 1);
            assert_eq!(patch.new_lines, 1);
        }
    }

    #[test]
    fn test_parse_delete_result() {
        let json = r#"{
            "type": "delete",
            "filePath": "/test/deleted.rs"
        }"#;

        let result: ToolUseResult = serde_json::from_str(json).unwrap();
        assert_eq!(result.file_path(), Some("/test/deleted.rs"));
    }

    #[test]
    fn test_parse_error_result() {
        let json = r#"{
            "type": "error",
            "error": "File not found",
            "toolName": "Read"
        }"#;

        let result: ToolUseResult = serde_json::from_str(json).unwrap();
        assert!(result.is_error());

        if let ToolUseResult::Error(error) = result {
            assert_eq!(error.error, "File not found");
            assert_eq!(error.tool_name, Some("Read".to_string()));
        }
    }

    #[test]
    fn test_parse_image_result() {
        let json = r#"{
            "type": "image",
            "source": {
                "type": "base64",
                "media_type": "image/png",
                "data": "iVBORw0KGgo="
            },
            "filePath": "/tmp/screenshot.png"
        }"#;

        let result: ToolUseResult = serde_json::from_str(json).unwrap();
        assert!(result.is_image());
        assert_eq!(result.file_path(), Some("/tmp/screenshot.png"));

        if let ToolUseResult::Image(image) = result {
            assert_eq!(image.source.source_type, "base64");
            assert_eq!(image.source.media_type, "image/png");
            assert_eq!(image.source.data, "iVBORw0KGgo=");
            assert_eq!(image.file_path, Some("/tmp/screenshot.png".to_string()));
        }
    }

    #[test]
    fn test_lenient_tool_use_result_accepts_matching_shape() {
        #[derive(Deserialize)]
        struct Wrapper {
            #[serde(deserialize_with = "deserialize_tool_use_result_lenient", default)]
            result: Option<ToolUseResult>,
        }

        let json = r#"{"result":{"type":"text","content":"cargo build succeeded"}}"#;
        let wrapper: Wrapper = serde_json::from_str(json).unwrap();
        assert!(matches!(wrapper.result, Some(ToolUseResult::Text(_))));
    }

    #[test]
    fn test_lenient_tool_use_result_drops_mismatched_shape_without_failing() {
        // Real transcripts emit `toolUseResult: {"type":"text","file":{...}}`
        // for system-reminder tool results — a "text" tag whose shape does
        // not match `TextResult { content: String }`. This must not fail the
        // enclosing deserialization.
        #[derive(Deserialize)]
        struct Wrapper {
            #[serde(deserialize_with = "deserialize_tool_use_result_lenient", default)]
            result: Option<ToolUseResult>,
        }

        let json = r#"{"result":{"type":"text","file":{"filePath":"/tmp/x","content":"","numLines":1,"startLine":1,"totalLines":1}}}"#;
        let wrapper: Wrapper = serde_json::from_str(json).unwrap();
        assert!(wrapper.result.is_none());
    }

    #[test]
    fn test_lenient_tool_use_result_accepts_missing_field() {
        #[derive(Deserialize)]
        struct Wrapper {
            #[serde(deserialize_with = "deserialize_tool_use_result_lenient", default)]
            result: Option<ToolUseResult>,
        }

        let wrapper: Wrapper = serde_json::from_str("{}").unwrap();
        assert!(wrapper.result.is_none());
    }

    #[test]
    fn test_text_content_extraction() {
        let text_result = ToolUseResult::Text(TextResult {
            content: "Output".to_string(),
        });
        assert_eq!(text_result.text_content(), Some("Output"));

        let create_result = ToolUseResult::Create(CreateResult {
            file_path: "/test.rs".to_string(),
            content: "Code".to_string(),
            structured_patch: vec![],
            original_file: None,
        });
        assert_eq!(create_result.text_content(), Some("Code"));

        let delete_result = ToolUseResult::Delete(DeleteResult {
            file_path: "/test.rs".to_string(),
        });
        assert_eq!(delete_result.text_content(), None);
    }
}