claude-codes 2.1.117

A tightly typed Rust interface for the Claude Code JSON protocol
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
//! Message types for the Claude Code protocol

use crate::types::*;
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Base message trait for all protocol messages
pub trait Message: Serialize + for<'de> Deserialize<'de> {
    fn message_type(&self) -> &str;
}

/// Request message sent to Claude Code
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Request {
    #[serde(rename = "type")]
    pub message_type: String,

    pub id: Id,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_id: Option<SessionId>,

    pub payload: RequestPayload,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Metadata>,
}

/// Different types of request payloads
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "action", rename_all = "snake_case")]
pub enum RequestPayload {
    Initialize(InitializeRequest),
    Execute(ExecuteRequest),
    Complete(CompleteRequest),
    Cancel(CancelRequest),
    GetStatus(GetStatusRequest),
    Custom(Value),
}

/// Initialize a new session
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InitializeRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub working_directory: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub environment: Option<Vec<EnvironmentVariable>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub capabilities: Option<Vec<Capability>>,
}

/// Environment variable
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnvironmentVariable {
    pub name: String,
    pub value: String,
}

/// Execute a command or task
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecuteRequest {
    pub command: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub arguments: Option<Vec<String>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub input: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub timeout_ms: Option<u64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub working_directory: Option<String>,
}

/// Request completion suggestions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompleteRequest {
    pub prompt: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub context: Option<CompletionContext>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_suggestions: Option<usize>,
}

/// Context for completion requests
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompletionContext {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file_path: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub cursor_position: Option<CursorPosition>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub surrounding_code: Option<String>,
}

/// Cursor position in a file
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CursorPosition {
    pub line: usize,
    pub column: usize,
}

/// Cancel a running operation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CancelRequest {
    pub target_id: Id,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

/// Get status of an operation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetStatusRequest {
    pub target_id: Id,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_details: Option<bool>,
}

/// Response message from Claude Code
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Response {
    #[serde(rename = "type")]
    pub message_type: String,

    pub id: Id,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub request_id: Option<Id>,

    pub status: Status,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub payload: Option<ResponsePayload>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<ErrorDetail>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Metadata>,
}

/// Different types of response payloads
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "result_type", rename_all = "snake_case")]
pub enum ResponsePayload {
    Initialize(InitializeResponse),
    Execute(ExecuteResponse),
    Complete(CompleteResponse),
    Status(StatusResponse),
    Stream(StreamResponse),
    Custom(Value),
}

/// Response to initialization
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InitializeResponse {
    pub session_id: SessionId,
    pub version: String,
    pub capabilities: Vec<Capability>,
}

/// Response to execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecuteResponse {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_output: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub exit_code: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution_time_ms: Option<u64>,
}

/// Response to completion request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompleteResponse {
    pub suggestions: Vec<CompletionSuggestion>,
}

/// A single completion suggestion
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompletionSuggestion {
    pub text: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub score: Option<f32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<SuggestionMetadata>,
}

/// Metadata for a completion suggestion.
///
/// This struct captures common metadata fields while allowing additional
/// custom fields through the `extra` field.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SuggestionMetadata {
    /// The source of the suggestion (e.g., "history", "model", "cache")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,

    /// Priority level for the suggestion
    #[serde(skip_serializing_if = "Option::is_none")]
    pub priority: Option<i32>,

    /// Category of the suggestion
    #[serde(skip_serializing_if = "Option::is_none")]
    pub category: Option<String>,

    /// Any additional metadata fields
    #[serde(flatten)]
    pub extra: std::collections::HashMap<String, Value>,
}

/// Status response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StatusResponse {
    pub status: Status,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub progress: Option<Progress>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<StatusDetails>,
}

/// Details for a status response.
///
/// This struct captures common status detail fields while allowing additional
/// custom fields through the `extra` field.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StatusDetails {
    /// Error message if the status indicates an error
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,

    /// Reason for the current status
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,

    /// Human-readable description of the status
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Any additional detail fields
    #[serde(flatten)]
    pub extra: std::collections::HashMap<String, Value>,
}

/// Progress information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Progress {
    pub current: usize,
    pub total: Option<usize>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub percentage: Option<f32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

/// Streaming response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StreamResponse {
    pub chunk: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub stream_id: Option<String>,

    pub is_final: bool,
}

/// Event message for notifications
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Event {
    #[serde(rename = "type")]
    pub message_type: String,

    pub event_type: EventType,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_id: Option<SessionId>,

    pub payload: Value,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Metadata>,
}

/// Types of events
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EventType {
    Log,
    Progress,
    StateChange,
    Error,
    Warning,
    Info,
    Debug,
    Custom(String),
}

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

    #[test]
    fn test_suggestion_metadata_parsing() {
        let json = r#"{
            "source": "history",
            "priority": 5,
            "category": "command",
            "custom_field": "custom_value"
        }"#;

        let metadata: SuggestionMetadata = serde_json::from_str(json).unwrap();
        assert_eq!(metadata.source, Some("history".to_string()));
        assert_eq!(metadata.priority, Some(5));
        assert_eq!(metadata.category, Some("command".to_string()));
        assert_eq!(
            metadata.extra.get("custom_field").unwrap(),
            &serde_json::json!("custom_value")
        );
    }

    #[test]
    fn test_suggestion_metadata_minimal() {
        let json = r#"{}"#;

        let metadata: SuggestionMetadata = serde_json::from_str(json).unwrap();
        assert_eq!(metadata.source, None);
        assert_eq!(metadata.priority, None);
        assert!(metadata.extra.is_empty());
    }

    #[test]
    fn test_suggestion_metadata_roundtrip() {
        let mut extra = std::collections::HashMap::new();
        extra.insert("key".to_string(), serde_json::json!("value"));

        let metadata = SuggestionMetadata {
            source: Some("model".to_string()),
            priority: Some(10),
            category: None,
            extra,
        };

        let json = serde_json::to_string(&metadata).unwrap();
        let parsed: SuggestionMetadata = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, metadata);
    }

    #[test]
    fn test_status_details_parsing() {
        let json = r#"{
            "error": "Connection failed",
            "reason": "timeout",
            "description": "The server did not respond in time",
            "retry_count": 3
        }"#;

        let details: StatusDetails = serde_json::from_str(json).unwrap();
        assert_eq!(details.error, Some("Connection failed".to_string()));
        assert_eq!(details.reason, Some("timeout".to_string()));
        assert_eq!(
            details.description,
            Some("The server did not respond in time".to_string())
        );
        assert_eq!(
            details.extra.get("retry_count").unwrap(),
            &serde_json::json!(3)
        );
    }

    #[test]
    fn test_status_details_minimal() {
        let json = r#"{}"#;

        let details: StatusDetails = serde_json::from_str(json).unwrap();
        assert_eq!(details.error, None);
        assert_eq!(details.reason, None);
        assert!(details.extra.is_empty());
    }

    #[test]
    fn test_status_details_roundtrip() {
        let details = StatusDetails {
            error: Some("Error message".to_string()),
            reason: None,
            description: Some("Description".to_string()),
            extra: std::collections::HashMap::new(),
        };

        let json = serde_json::to_string(&details).unwrap();
        let parsed: StatusDetails = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, details);
    }

    #[test]
    fn test_completion_suggestion_with_metadata() {
        let json = r#"{
            "text": "git status",
            "description": "Show repository status",
            "score": 0.95,
            "metadata": {
                "source": "history",
                "priority": 1
            }
        }"#;

        let suggestion: CompletionSuggestion = serde_json::from_str(json).unwrap();
        assert_eq!(suggestion.text, "git status");
        assert_eq!(
            suggestion.description,
            Some("Show repository status".to_string())
        );
        assert_eq!(suggestion.score, Some(0.95));
        assert!(suggestion.metadata.is_some());

        let meta = suggestion.metadata.unwrap();
        assert_eq!(meta.source, Some("history".to_string()));
        assert_eq!(meta.priority, Some(1));
    }

    #[test]
    fn test_status_response_with_details() {
        let json = r#"{
            "status": "in_progress",
            "progress": {
                "current": 50,
                "total": 100,
                "percentage": 0.5
            },
            "details": {
                "reason": "processing",
                "description": "Processing request"
            }
        }"#;

        let response: StatusResponse = serde_json::from_str(json).unwrap();
        assert!(matches!(response.status, Status::InProgress));
        assert!(response.progress.is_some());
        assert!(response.details.is_some());

        let details = response.details.unwrap();
        assert_eq!(details.reason, Some("processing".to_string()));
    }
}