zag-agent 0.2.4

Core library for zag — a unified interface for AI coding agents
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
/// Claude-specific JSON output models.
///
/// These structures directly map to the JSON output format produced by the
/// Claude CLI when running with `--output json` (verbose mode). They can be
/// deserialized from JSON and then converted to the unified `AgentOutput` format.
///
/// See README.md in this directory for detailed documentation on the output format.
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use crate::output::{
    AgentOutput, ContentBlock as UnifiedContentBlock, Event as UnifiedEvent, ToolResult,
    Usage as UnifiedUsage,
};

/// The root structure: an array of events.
pub type ClaudeOutput = Vec<ClaudeEvent>;

/// A single event in Claude's output stream.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ClaudeEvent {
    /// System initialization event
    System {
        subtype: String,
        session_id: String,
        cwd: Option<String>,
        model: String,
        tools: Vec<String>,
        #[serde(default)]
        mcp_servers: Vec<serde_json::Value>,
        #[serde(rename = "permissionMode")]
        permission_mode: Option<String>,
        #[serde(default)]
        slash_commands: Vec<String>,
        #[serde(default)]
        agents: Vec<String>,
        #[serde(default)]
        skills: Vec<serde_json::Value>,
        #[serde(default)]
        plugins: Vec<Plugin>,
        uuid: String,
        #[serde(flatten)]
        extra: HashMap<String, serde_json::Value>,
    },

    /// Assistant message event
    Assistant {
        message: Message,
        parent_tool_use_id: Option<String>,
        session_id: String,
        uuid: String,
    },

    /// User message event (tool results)
    User {
        message: UserMessage,
        parent_tool_use_id: Option<String>,
        session_id: String,
        uuid: String,
        tool_use_result: Option<serde_json::Value>,
    },

    /// Final result event
    Result {
        subtype: String,
        is_error: bool,
        duration_ms: u64,
        duration_api_ms: u64,
        num_turns: u32,
        result: String,
        session_id: String,
        total_cost_usd: f64,
        usage: Usage,
        #[serde(default, rename = "modelUsage")]
        model_usage: HashMap<String, ModelUsage>,
        #[serde(default)]
        permission_denials: Vec<PermissionDenial>,
        uuid: String,
    },

    /// Unknown/unhandled event type (e.g., rate_limit_event) — silently ignored
    #[serde(other)]
    Other,
}

/// An assistant message from Claude.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message {
    pub model: String,
    pub id: String,
    #[serde(rename = "type")]
    pub message_type: String,
    pub role: String,
    pub content: Vec<ContentBlock>,
    pub stop_reason: Option<String>,
    pub stop_sequence: Option<String>,
    pub usage: Usage,
    pub context_management: Option<serde_json::Value>,
}

/// A user message containing tool results and other content.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserMessage {
    pub role: String,
    pub content: Vec<UserContentBlock>,
}

/// A content block in an assistant message.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ContentBlock {
    /// Text content
    Text { text: String },

    /// Tool invocation
    ToolUse {
        id: String,
        name: String,
        input: serde_json::Value,
    },

    /// Thinking content (extended thinking)
    Thinking {
        #[serde(default)]
        thinking: String,
        #[serde(flatten)]
        extra: HashMap<String, serde_json::Value>,
    },
}

/// A content block in a user message (tool results, text, or other types).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum UserContentBlock {
    /// Tool result
    ToolResult {
        tool_use_id: String,
        content: String,
        #[serde(default)]
        is_error: bool,
    },

    /// Text content
    Text { text: String },

    /// Any other content type
    #[serde(other)]
    Other,
}

/// Usage statistics for a message or session.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Usage {
    pub input_tokens: u64,
    #[serde(default)]
    pub cache_creation_input_tokens: u64,
    #[serde(default)]
    pub cache_read_input_tokens: u64,
    pub output_tokens: u64,
    #[serde(default)]
    pub cache_creation: Option<CacheCreation>,
    #[serde(default)]
    pub server_tool_use: Option<ServerToolUse>,
    #[serde(default)]
    pub service_tier: Option<String>,
}

/// Cache creation details.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheCreation {
    #[serde(default)]
    pub ephemeral_5m_input_tokens: u64,
    #[serde(default)]
    pub ephemeral_1h_input_tokens: u64,
}

/// Server-side tool usage.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerToolUse {
    #[serde(default)]
    pub web_search_requests: u32,
    #[serde(default)]
    pub web_fetch_requests: u32,
}

/// Per-model usage statistics.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelUsage {
    #[serde(rename = "inputTokens")]
    pub input_tokens: u64,
    #[serde(rename = "outputTokens")]
    pub output_tokens: u64,
    #[serde(default, rename = "cacheReadInputTokens")]
    pub cache_read_input_tokens: u64,
    #[serde(default, rename = "cacheCreationInputTokens")]
    pub cache_creation_input_tokens: u64,
    #[serde(default, rename = "webSearchRequests")]
    pub web_search_requests: u32,
    #[serde(rename = "costUSD")]
    pub cost_usd: f64,
    #[serde(default, rename = "contextWindow")]
    pub context_window: u64,
    #[serde(default, rename = "maxOutputTokens")]
    pub max_output_tokens: u64,
}

/// Information about a denied permission request.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionDenial {
    pub tool_name: String,
    pub tool_use_id: String,
    pub tool_input: serde_json::Value,
}

/// Plugin information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Plugin {
    pub name: String,
    pub path: String,
}

/// Convert Claude output to unified agent output.
pub fn claude_output_to_agent_output(claude_output: ClaudeOutput) -> AgentOutput {
    let mut session_id = String::from("unknown");
    let mut result = None;
    let mut is_error = false;
    let mut total_cost_usd = None;
    let mut usage = None;
    let mut events = Vec::new();

    for event in claude_output {
        match event {
            ClaudeEvent::System {
                session_id: sid,
                model,
                tools,
                cwd,
                mut extra,
                ..
            } => {
                session_id = sid;

                // Include all extra fields as metadata
                if let Some(cwd) = cwd {
                    extra.insert("cwd".to_string(), serde_json::json!(cwd));
                }

                events.push(UnifiedEvent::Init {
                    model,
                    tools,
                    working_directory: extra
                        .get("cwd")
                        .and_then(|v| v.as_str().map(|s| s.to_string())),
                    metadata: extra,
                });
            }

            ClaudeEvent::Assistant {
                message,
                session_id: sid,
                ..
            } => {
                session_id = sid;

                // Convert content blocks (skip thinking blocks)
                let content: Vec<UnifiedContentBlock> = message
                    .content
                    .into_iter()
                    .filter_map(|block| match block {
                        ContentBlock::Text { text } => Some(UnifiedContentBlock::Text { text }),
                        ContentBlock::ToolUse { id, name, input } => {
                            Some(UnifiedContentBlock::ToolUse { id, name, input })
                        }
                        ContentBlock::Thinking { .. } => None,
                    })
                    .collect();

                // Convert usage
                let msg_usage = Some(UnifiedUsage {
                    input_tokens: message.usage.input_tokens,
                    output_tokens: message.usage.output_tokens,
                    cache_read_tokens: Some(message.usage.cache_read_input_tokens),
                    cache_creation_tokens: Some(message.usage.cache_creation_input_tokens),
                    web_search_requests: message
                        .usage
                        .server_tool_use
                        .as_ref()
                        .map(|s| s.web_search_requests),
                    web_fetch_requests: message
                        .usage
                        .server_tool_use
                        .as_ref()
                        .map(|s| s.web_fetch_requests),
                });

                events.push(UnifiedEvent::AssistantMessage {
                    content,
                    usage: msg_usage,
                });
            }

            ClaudeEvent::User {
                message,
                tool_use_result,
                session_id: sid,
                ..
            } => {
                session_id = sid;

                // Convert tool results to tool execution events (skip non-tool-result blocks)
                for block in message.content {
                    if let UserContentBlock::ToolResult {
                        tool_use_id,
                        content,
                        is_error,
                    } = block
                    {
                        let tool_name = find_tool_name(&events, &tool_use_id)
                            .unwrap_or_else(|| "unknown".to_string());

                        let tool_result = ToolResult {
                            success: !is_error,
                            output: if !is_error {
                                Some(content.clone())
                            } else {
                                None
                            },
                            error: if is_error {
                                Some(content.clone())
                            } else {
                                None
                            },
                            data: tool_use_result.clone(),
                        };

                        events.push(UnifiedEvent::ToolExecution {
                            tool_name,
                            tool_id: tool_use_id,
                            input: serde_json::Value::Null,
                            result: tool_result,
                        });
                    }
                }
            }

            ClaudeEvent::Other => {
                log::debug!("Skipping unknown Claude event type during output conversion");
            }

            ClaudeEvent::Result {
                is_error: err,
                result: res,
                total_cost_usd: cost,
                usage: u,
                duration_ms,
                num_turns,
                permission_denials,
                session_id: sid,
                subtype: _,
                ..
            } => {
                session_id = sid;
                is_error = err;
                result = Some(res.clone());
                total_cost_usd = Some(cost);

                // Convert usage
                usage = Some(UnifiedUsage {
                    input_tokens: u.input_tokens,
                    output_tokens: u.output_tokens,
                    cache_read_tokens: Some(u.cache_read_input_tokens),
                    cache_creation_tokens: Some(u.cache_creation_input_tokens),
                    web_search_requests: u.server_tool_use.as_ref().map(|s| s.web_search_requests),
                    web_fetch_requests: u.server_tool_use.as_ref().map(|s| s.web_fetch_requests),
                });

                // Add permission denial events
                for denial in permission_denials {
                    events.push(UnifiedEvent::PermissionRequest {
                        tool_name: denial.tool_name,
                        description: format!(
                            "Permission denied for tool input: {}",
                            serde_json::to_string(&denial.tool_input).unwrap_or_default()
                        ),
                        granted: false,
                    });
                }

                // Add final result event
                events.push(UnifiedEvent::Result {
                    success: !err,
                    message: Some(res),
                    duration_ms: Some(duration_ms),
                    num_turns: Some(num_turns),
                });
            }
        }
    }

    AgentOutput {
        agent: "claude".to_string(),
        session_id,
        events,
        result,
        is_error,
        total_cost_usd,
        usage,
    }
}

/// Find the tool name for a given tool_use_id by searching previous events.
fn find_tool_name(events: &[UnifiedEvent], tool_use_id: &str) -> Option<String> {
    for event in events.iter().rev() {
        if let UnifiedEvent::AssistantMessage { content, .. } = event {
            for block in content {
                if let UnifiedContentBlock::ToolUse { id, name, .. } = block
                    && id == tool_use_id
                {
                    return Some(name.clone());
                }
            }
        }
    }
    None
}

#[cfg(test)]
#[path = "models_tests.rs"]
mod tests;