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
//! agtrace-sdk: SDK for AI agent observability.
//!
//! **Note**: README.md is auto-generated from this rustdoc using `cargo-rdme`.
//! To update: `cargo rdme --workspace-project agtrace-sdk`
//!
//! # Overview
//!
//! `agtrace-sdk` provides a high-level, stable API for building tools on top of agtrace.
//! It powers agtrace's MCP server (letting agents query their execution history) and CLI tools,
//! and can be embedded in your own applications. The SDK normalizes logs from multiple providers
//! (Claude Code, Codex, Gemini) into a unified data model, enabling cross-provider analysis.
//!
//! # Quickstart
//!
//! ```no_run
//! use agtrace_sdk::{Client, types::SessionFilter};
//!
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Connect to the local workspace
//! let client = Client::connect_default().await?;
//!
//! // List sessions and browse the most recent one
//! let sessions = client.sessions().list(SessionFilter::all())?;
//! if let Some(summary) = sessions.first() {
//! let handle = client.sessions().get(&summary.id)?;
//! let session = handle.assemble()?;
//!
//! println!("Session: {} turns, {} tokens",
//! session.turns.len(),
//! session.stats.total_tokens);
//!
//! // Browse tool calls
//! for turn in &session.turns {
//! for step in &turn.steps {
//! for tool in &step.tools {
//! println!(" {} ({})",
//! tool.call.content.name(),
//! if tool.is_error { "failed" } else { "ok" });
//! }
//! }
//! }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! For complete examples, see the [`examples/`](https://github.com/lanegrid/agtrace/tree/main/crates/agtrace-sdk/examples) directory.
//!
//! # Architecture
//!
//! This SDK acts as a facade over:
//! - `agtrace-types`: Core domain models (AgentEvent, etc.)
//! - `agtrace-providers`: Multi-provider log normalization
//! - `agtrace-engine`: Session assembly and analysis
//! - `agtrace-index`: Metadata storage and querying
//! - `agtrace-runtime`: Internal orchestration layer
//!
//! # Usage Patterns
//!
//! ## Session Browsing
//!
//! Access structured session data (Turn → Step → Tool hierarchy):
//!
//! ```no_run
//! use agtrace_sdk::{Client, types::SessionFilter};
//!
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let client = Client::connect_default().await?;
//! let sessions = client.sessions().list(SessionFilter::all())?;
//!
//! for summary in sessions.iter().take(5) {
//! let handle = client.sessions().get(&summary.id)?;
//! let session = handle.assemble()?;
//! println!("{}: {} turns, {} tokens",
//! summary.id,
//! session.turns.len(),
//! session.stats.total_tokens);
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Real-time Monitoring
//!
//! Watch for events as they happen:
//!
//! ```no_run
//! use agtrace_sdk::Client;
//! use futures::stream::StreamExt;
//!
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let client = Client::connect_default().await?;
//! let mut stream = client.watch().all_providers().start()?;
//! while let Some(event) = stream.next().await {
//! println!("Event: {:?}", event);
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Diagnostics
//!
//! Run diagnostic checks on sessions:
//!
//! ```no_run
//! use agtrace_sdk::{Client, Diagnostic, types::SessionFilter};
//!
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let client = Client::connect_default().await?;
//! let sessions = client.sessions().list(SessionFilter::all())?;
//! if let Some(summary) = sessions.first() {
//! let handle = client.sessions().get(&summary.id)?;
//! let report = handle.analyze()?
//! .check(Diagnostic::Failures)
//! .check(Diagnostic::Loops)
//! .report()?;
//!
//! println!("Health: {}/100", report.score);
//! for insight in &report.insights {
//! println!(" Turn {}: {}", insight.turn_index + 1, insight.message);
//! }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Standalone API (for testing/simulations)
//!
//! ```no_run
//! use agtrace_sdk::{SessionHandle, types::AgentEvent};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // When you have raw events without Client (e.g., testing, simulations)
//! let events: Vec<AgentEvent> = vec![/* ... */];
//! let handle = SessionHandle::from_events(events);
//!
//! let session = handle.assemble()?;
//! println!("Session has {} turns", session.turns.len());
//! # Ok(())
//! # }
//! ```
// Re-export core domain types for convenience
pub use AgentSession;
// Public facade
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
// Query types for MCP and programmatic usage
pub use ;
// ============================================================================
// Low-level Utilities (Power User API)
// ============================================================================
/// Utility functions for building custom observability tools.
///
/// These are stateless, pure functions that power the CLI and can be used
/// by external tool developers to replicate or extend agtrace functionality.
///
/// # When to use this module
///
/// - Building custom TUIs or dashboards that need event stream processing
/// - Writing tests that need to compute project hashes
/// - Implementing custom project detection logic
///
/// # Examples
///
/// ## Event Processing
///
/// ```no_run
/// use agtrace_sdk::{Client, utils};
/// use agtrace_sdk::watch::{StreamEvent, WorkspaceEvent};
/// use futures::stream::StreamExt;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::connect_default().await?;
/// let mut stream = client.watch().all_providers().start()?;
///
/// let mut count = 0;
/// while let Some(workspace_event) = stream.next().await {
/// if let WorkspaceEvent::Stream(StreamEvent::Events { events, .. }) = workspace_event {
/// for event in events {
/// let updates = utils::extract_state_updates(&event);
/// if updates.is_new_turn {
/// println!("New turn started!");
/// }
/// if let Some(usage) = updates.usage {
/// println!("Token usage: {:?}", usage);
/// }
/// }
/// }
/// count += 1;
/// if count >= 10 { break; }
/// }
/// # Ok(())
/// # }
/// ```
///
/// ## Project Hash Computation
///
/// ```no_run
/// use agtrace_sdk::utils;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let project_root = utils::discover_project_root(None)?;
/// let hash = utils::project_hash_from_root(&project_root.to_string_lossy());
/// println!("Project hash: {}", hash);
/// # Ok(())
/// # }
/// ```