claude-code-sdk-rust 0.2.0

Async Rust SDK for the Claude Code CLI: streaming agent turns, tool use, and sessions.
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
use crate::error::{ClaudeSDKError, Result};
use crate::session_store::{
    project_key_for_directory, SessionKey, SessionStoreEntry, SessionStoreHandle,
};
use crate::session_summary::{fold_session_summary, summary_entry_to_sdk_info};
use serde::{Deserialize, Serialize};
use std::path::Path;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SDKSessionInfo {
    pub session_id: String,
    pub summary: String,
    pub last_modified: i64,
    pub file_size: Option<i64>,
    pub custom_title: Option<String>,
    pub first_prompt: Option<String>,
    pub git_branch: Option<String>,
    pub cwd: Option<String>,
    pub tag: Option<String>,
    pub created_at: Option<i64>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SDKSessionMessage {
    pub r#type: String,
    pub uuid: String,
    pub session_id: String,
    pub message: serde_json::Value,
    pub parent_tool_use_id: Option<String>,
}

pub async fn rename_session_via_store(
    session_store: &SessionStoreHandle,
    session_id: &str,
    title: &str,
    directory: Option<&str>,
) -> Result<()> {
    validate_session_id(session_id)?;
    let title = title.trim();
    if title.is_empty() {
        return Err(ClaudeSDKError::Session(
            "title must be non-empty".to_string(),
        ));
    }
    let project_key = project_key_for_directory(directory.map(Path::new));
    session_store
        .append(
            SessionKey {
                project_key,
                session_id: session_id.to_string(),
                subpath: None,
            },
            vec![metadata_entry(
                "custom-title",
                session_id,
                [("customTitle", serde_json::Value::String(title.to_string()))],
            )],
        )
        .await
}

pub async fn tag_session_via_store(
    session_store: &SessionStoreHandle,
    session_id: &str,
    tag: Option<&str>,
    directory: Option<&str>,
) -> Result<()> {
    validate_session_id(session_id)?;
    let tag = tag.map(sanitize_tag).transpose()?;
    let project_key = project_key_for_directory(directory.map(Path::new));
    session_store
        .append(
            SessionKey {
                project_key,
                session_id: session_id.to_string(),
                subpath: None,
            },
            vec![metadata_entry(
                "tag",
                session_id,
                [("tag", serde_json::Value::String(tag.unwrap_or_default()))],
            )],
        )
        .await
}

pub async fn delete_session_via_store(
    session_store: &SessionStoreHandle,
    session_id: &str,
    directory: Option<&str>,
) -> Result<()> {
    validate_session_id(session_id)?;
    let project_key = project_key_for_directory(directory.map(Path::new));
    session_store
        .delete(SessionKey {
            project_key,
            session_id: session_id.to_string(),
            subpath: None,
        })
        .await
}

pub async fn list_sessions_from_store(
    session_store: &SessionStoreHandle,
    directory: Option<&str>,
    limit: Option<usize>,
    offset: usize,
) -> Result<Vec<SDKSessionInfo>> {
    let project_path = canonical_project_path(directory);
    let project_key = project_key_for_directory(Some(Path::new(&project_path)));
    let listing = session_store.list_sessions(&project_key).await?;
    let summaries = session_store
        .list_session_summaries(&project_key)
        .await
        .unwrap_or_default();

    let mut infos = Vec::new();
    let mut covered = std::collections::HashSet::new();
    let known_mtimes = listing
        .iter()
        .map(|entry| (entry.session_id.clone(), entry.mtime))
        .collect::<std::collections::HashMap<_, _>>();

    for summary in summaries {
        if let Some(known_mtime) = known_mtimes.get(&summary.session_id) {
            if summary.mtime < *known_mtime {
                continue;
            }
        }
        covered.insert(summary.session_id.clone());
        if let Some(info) = summary_entry_to_sdk_info(&summary, Some(&project_path)) {
            infos.push(info);
        }
    }

    for entry in listing {
        if covered.contains(&entry.session_id) {
            continue;
        }
        match derive_session_info_from_store(
            session_store,
            &project_key,
            &project_path,
            &entry.session_id,
        )
        .await
        {
            Ok(Some(mut info)) => {
                info.last_modified = entry.mtime;
                infos.push(info);
            }
            Ok(None) => {}
            Err(_) => infos.push(degraded_session_info(&entry.session_id, entry.mtime)),
        }
    }

    Ok(sort_limit_offset(infos, limit, offset))
}

fn degraded_session_info(session_id: &str, last_modified: i64) -> SDKSessionInfo {
    SDKSessionInfo {
        session_id: session_id.to_string(),
        summary: String::new(),
        last_modified,
        file_size: None,
        custom_title: None,
        first_prompt: None,
        git_branch: None,
        cwd: None,
        tag: None,
        created_at: None,
    }
}

pub async fn get_session_info_from_store(
    session_store: &SessionStoreHandle,
    session_id: &str,
    directory: Option<&str>,
) -> Result<Option<SDKSessionInfo>> {
    if !is_uuid(session_id) {
        return Ok(None);
    }
    let project_path = canonical_project_path(directory);
    let project_key = project_key_for_directory(Some(Path::new(&project_path)));
    derive_session_info_from_store(session_store, &project_key, &project_path, session_id).await
}

pub async fn get_session_messages_from_store(
    session_store: &SessionStoreHandle,
    session_id: &str,
    directory: Option<&str>,
    limit: Option<usize>,
    offset: usize,
) -> Result<Vec<SDKSessionMessage>> {
    if !is_uuid(session_id) {
        return Ok(Vec::new());
    }
    let project_key = project_key_for_directory(directory.map(Path::new));
    let key = SessionKey {
        project_key,
        session_id: session_id.to_string(),
        subpath: None,
    };
    let Some(entries) = session_store.load(key).await? else {
        return Ok(Vec::new());
    };
    Ok(entries_to_session_messages(
        session_id, entries, limit, offset,
    ))
}

pub async fn list_subagents_from_store(
    session_store: &SessionStoreHandle,
    session_id: &str,
    directory: Option<&str>,
) -> Result<Vec<String>> {
    if !is_uuid(session_id) {
        return Ok(Vec::new());
    }
    let project_key = project_key_for_directory(directory.map(Path::new));
    let subkeys = session_store
        .list_subkeys(crate::session_store::SessionListSubkeysKey {
            project_key,
            session_id: session_id.to_string(),
        })
        .await?;
    let mut seen = std::collections::HashSet::new();
    let mut ids = Vec::new();
    for subkey in subkeys {
        if let Some(agent_id) = subagent_id_from_subkey(&subkey) {
            if seen.insert(agent_id.to_string()) {
                ids.push(agent_id.to_string());
            }
        }
    }
    Ok(ids)
}

pub async fn get_subagent_messages_from_store(
    session_store: &SessionStoreHandle,
    session_id: &str,
    agent_id: &str,
    directory: Option<&str>,
    limit: Option<usize>,
    offset: usize,
) -> Result<Vec<SDKSessionMessage>> {
    if !is_uuid(session_id) || agent_id.is_empty() {
        return Ok(Vec::new());
    }
    let project_key = project_key_for_directory(directory.map(Path::new));
    let subpath = find_subagent_subpath(session_store, &project_key, session_id, agent_id).await?;
    let Some(entries) = session_store
        .load(SessionKey {
            project_key,
            session_id: session_id.to_string(),
            subpath: Some(subpath),
        })
        .await?
    else {
        return Ok(Vec::new());
    };
    let entries = entries
        .into_iter()
        .filter(|entry| {
            entry.get("type").and_then(|value| value.as_str()) != Some("agent_metadata")
        })
        .collect();
    Ok(entries_to_session_messages(
        session_id, entries, limit, offset,
    ))
}

async fn find_subagent_subpath(
    session_store: &SessionStoreHandle,
    project_key: &str,
    session_id: &str,
    agent_id: &str,
) -> Result<String> {
    let target = format!("agent-{agent_id}");
    let subkeys = session_store
        .list_subkeys(crate::session_store::SessionListSubkeysKey {
            project_key: project_key.to_string(),
            session_id: session_id.to_string(),
        })
        .await
        .unwrap_or_default();
    Ok(subkeys
        .into_iter()
        .find(|subkey| {
            subkey.starts_with("subagents/") && subkey.rsplit('/').next() == Some(target.as_str())
        })
        .unwrap_or_else(|| format!("subagents/{target}")))
}

async fn derive_session_info_from_store(
    session_store: &SessionStoreHandle,
    project_key: &str,
    project_path: &str,
    session_id: &str,
) -> Result<Option<SDKSessionInfo>> {
    let key = SessionKey {
        project_key: project_key.to_string(),
        session_id: session_id.to_string(),
        subpath: None,
    };
    let Some(entries) = session_store.load(key.clone()).await? else {
        return Ok(None);
    };
    if entries.is_empty() {
        return Ok(None);
    }
    let summary = fold_session_summary(None, &key, &entries);
    Ok(summary_entry_to_sdk_info(&summary, Some(project_path)))
}

fn entries_to_session_messages(
    session_id: &str,
    entries: Vec<SessionStoreEntry>,
    limit: Option<usize>,
    offset: usize,
) -> Vec<SDKSessionMessage> {
    entries
        .into_iter()
        .filter_map(|entry| session_message_from_entry(session_id, entry))
        .skip(offset)
        .take(limit.filter(|limit| *limit > 0).unwrap_or(usize::MAX))
        .collect()
}

fn session_message_from_entry(
    fallback_session_id: &str,
    entry: SessionStoreEntry,
) -> Option<SDKSessionMessage> {
    let message_type = entry.get("type")?.as_str()?;
    if message_type != "user" && message_type != "assistant" {
        return None;
    }
    let uuid = entry.get("uuid")?.as_str()?.to_string();
    let message = entry.get("message")?.clone();
    Some(SDKSessionMessage {
        r#type: message_type.to_string(),
        uuid,
        session_id: entry
            .get("session_id")
            .and_then(|value| value.as_str())
            .unwrap_or(fallback_session_id)
            .to_string(),
        message,
        parent_tool_use_id: entry
            .get("parent_tool_use_id")
            .and_then(|value| value.as_str())
            .map(String::from),
    })
}

fn subagent_id_from_subkey(subkey: &str) -> Option<&str> {
    if !subkey.starts_with("subagents/") {
        return None;
    }
    subkey.rsplit('/').next()?.strip_prefix("agent-")
}

fn sort_limit_offset(
    mut infos: Vec<SDKSessionInfo>,
    limit: Option<usize>,
    offset: usize,
) -> Vec<SDKSessionInfo> {
    infos.sort_by_key(|info| std::cmp::Reverse(info.last_modified));
    let infos = if offset > 0 {
        infos.into_iter().skip(offset).collect()
    } else {
        infos
    };
    if let Some(limit) = limit.filter(|limit| *limit > 0) {
        infos.into_iter().take(limit).collect()
    } else {
        infos
    }
}

fn canonical_project_path(directory: Option<&str>) -> String {
    let path = directory.map(Path::new).unwrap_or_else(|| Path::new("."));
    let absolute = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()
            .unwrap_or_else(|_| ".".into())
            .join(path)
    };
    std::fs::canonicalize(&absolute)
        .unwrap_or(absolute)
        .to_string_lossy()
        .to_string()
}

fn is_uuid(value: &str) -> bool {
    uuid::Uuid::parse_str(value).is_ok()
}

fn validate_session_id(session_id: &str) -> Result<()> {
    if is_uuid(session_id) {
        Ok(())
    } else {
        Err(ClaudeSDKError::Session(format!(
            "Invalid session_id: {session_id}"
        )))
    }
}

fn sanitize_tag(tag: &str) -> Result<String> {
    let sanitized = tag
        .chars()
        .filter(|ch| !ch.is_control())
        .collect::<String>()
        .trim()
        .to_string();
    if sanitized.is_empty() {
        Err(ClaudeSDKError::Session(
            "tag must be non-empty (use None to clear)".to_string(),
        ))
    } else {
        Ok(sanitized)
    }
}

fn metadata_entry<const N: usize>(
    entry_type: &str,
    session_id: &str,
    fields: [(&str, serde_json::Value); N],
) -> SessionStoreEntry {
    let mut entry = serde_json::Map::new();
    entry.insert("type".to_string(), serde_json::json!(entry_type));
    entry.insert("sessionId".to_string(), serde_json::json!(session_id));
    entry.insert(
        "uuid".to_string(),
        serde_json::json!(uuid::Uuid::new_v4().to_string()),
    );
    entry.insert(
        "timestamp".to_string(),
        serde_json::json!(chrono::Utc::now().to_rfc3339()),
    );
    for (key, value) in fields {
        entry.insert(key.to_string(), value);
    }
    entry
}