zag-agent 0.12.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
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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
/// Unified output structures for all agents.
///
/// This module provides a common interface for processing output from different
/// AI coding agents (Claude, Codex, Gemini, Copilot). By normalizing outputs into
/// a unified format, we can provide consistent logging, debugging, and observability
/// across all agents.
use log::debug;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// A unified event stream output from an agent session.
///
/// This represents the complete output from an agent execution, containing
/// all events that occurred during the session.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentOutput {
    /// The agent that produced this output
    pub agent: String,

    /// Unique session identifier
    pub session_id: String,

    /// Events that occurred during the session
    pub events: Vec<Event>,

    /// Final result text (if any)
    pub result: Option<String>,

    /// Whether the session ended in an error
    pub is_error: bool,

    /// Process exit code from the underlying provider (if available)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exit_code: Option<i32>,

    /// Human-readable error message from the provider (if any)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error_message: Option<String>,

    /// Total cost in USD (if available)
    pub total_cost_usd: Option<f64>,

    /// Aggregated usage statistics
    pub usage: Option<Usage>,
}

/// A single event in an agent session.
///
/// Events represent discrete steps in the conversation flow, such as
/// initialization, messages, tool calls, and results.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Event {
    /// Session initialization event
    Init {
        model: String,
        tools: Vec<String>,
        working_directory: Option<String>,
        metadata: HashMap<String, serde_json::Value>,
    },

    /// Message from the user (replayed via --replay-user-messages)
    UserMessage { content: Vec<ContentBlock> },

    /// Message from the assistant
    AssistantMessage {
        content: Vec<ContentBlock>,
        usage: Option<Usage>,
        /// If this message comes from a sub-agent, the tool_use_id of the
        /// parent Agent tool call that spawned it.
        #[serde(skip_serializing_if = "Option::is_none")]
        parent_tool_use_id: Option<String>,
    },

    /// Tool execution event
    ToolExecution {
        tool_name: String,
        tool_id: String,
        input: serde_json::Value,
        result: ToolResult,
        /// If this execution belongs to a sub-agent, the tool_use_id of the
        /// parent Agent tool call that spawned it.
        #[serde(skip_serializing_if = "Option::is_none")]
        parent_tool_use_id: Option<String>,
    },

    /// End of a single assistant turn.
    ///
    /// In bidirectional streaming mode, this fires exactly once per turn,
    /// after the final [`Event::AssistantMessage`] / [`Event::ToolExecution`]
    /// of the turn and immediately before the per-turn [`Event::Result`].
    /// Prefer this over `Result` as the turn-boundary signal in new code.
    ///
    /// For providers that don't expose a bidirectional streaming session
    /// (currently everything except Claude), this event is not emitted.
    TurnComplete {
        /// Reason the turn stopped, as reported by the provider.
        ///
        /// For Claude, well-known values are `end_turn`, `tool_use`,
        /// `max_tokens`, and `stop_sequence`. `None` when the provider
        /// didn't surface a stop reason (for example, interrupted turns
        /// or providers that don't report one).
        stop_reason: Option<String>,
        /// Zero-based monotonic turn index within the streaming session.
        turn_index: u32,
        /// Usage reported for the final assistant message of this turn.
        usage: Option<Usage>,
    },

    /// Session-final or per-turn result summary from the provider.
    ///
    /// In bidirectional streaming mode this fires after
    /// [`Event::TurnComplete`] at the end of every turn. In batch mode it
    /// fires once when the provider reports the session-final result.
    Result {
        success: bool,
        message: Option<String>,
        duration_ms: Option<u64>,
        num_turns: Option<u32>,
    },

    /// An error occurred
    Error {
        message: String,
        details: Option<serde_json::Value>,
    },

    /// Permission was requested
    PermissionRequest {
        tool_name: String,
        description: String,
        granted: bool,
    },
}

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

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

/// Result from a tool execution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolResult {
    /// Whether the tool execution succeeded
    pub success: bool,

    /// Text output from the tool
    pub output: Option<String>,

    /// Error message (if failed)
    pub error: Option<String>,

    /// Structured result data (tool-specific)
    pub data: Option<serde_json::Value>,
}

/// Usage statistics for an agent session.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Usage {
    /// Total input tokens
    pub input_tokens: u64,

    /// Total output tokens
    pub output_tokens: u64,

    /// Tokens read from cache (if applicable)
    pub cache_read_tokens: Option<u64>,

    /// Tokens written to cache (if applicable)
    pub cache_creation_tokens: Option<u64>,

    /// Number of web search requests (if applicable)
    pub web_search_requests: Option<u32>,

    /// Number of web fetch requests (if applicable)
    pub web_fetch_requests: Option<u32>,
}

/// Log level for agent events.
///
/// Used to categorize events for filtering and display.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LogLevel {
    Debug,
    Info,
    Warn,
    Error,
}

/// A log entry extracted from agent output.
///
/// This is a simplified view of events suitable for logging and debugging.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogEntry {
    /// Log level
    pub level: LogLevel,

    /// Log message
    pub message: String,

    /// Optional structured data
    pub data: Option<serde_json::Value>,

    /// Timestamp (if available)
    pub timestamp: Option<String>,
}

impl AgentOutput {
    /// Create a minimal AgentOutput from captured text.
    ///
    /// Used by non-Claude agents when `capture_output` is enabled (e.g., for auto-selection).
    pub fn from_text(agent: &str, text: &str) -> Self {
        debug!(
            "Creating AgentOutput from text: agent={}, len={}",
            agent,
            text.len()
        );
        Self {
            agent: agent.to_string(),
            session_id: String::new(),
            events: vec![Event::Result {
                success: true,
                message: Some(text.to_string()),
                duration_ms: None,
                num_turns: None,
            }],
            result: Some(text.to_string()),
            is_error: false,
            exit_code: None,
            error_message: None,
            total_cost_usd: None,
            usage: None,
        }
    }

    /// Extract log entries from the agent output.
    ///
    /// This converts events into a flat list of log entries suitable for
    /// display or filtering.
    pub fn to_log_entries(&self, min_level: LogLevel) -> Vec<LogEntry> {
        debug!(
            "Extracting log entries from {} events (min_level={:?})",
            self.events.len(),
            min_level
        );
        let mut entries = Vec::new();

        for event in &self.events {
            if let Some(entry) = event_to_log_entry(event)
                && entry.level >= min_level
            {
                entries.push(entry);
            }
        }

        entries
    }

    /// Get the final result text.
    pub fn final_result(&self) -> Option<&str> {
        self.result.as_deref()
    }

    /// Check if the session completed successfully.
    #[allow(dead_code)]
    pub fn is_success(&self) -> bool {
        !self.is_error
    }

    /// Get all tool executions from the session.
    #[allow(dead_code)]
    pub fn tool_executions(&self) -> Vec<&Event> {
        self.events
            .iter()
            .filter(|e| matches!(e, Event::ToolExecution { .. }))
            .collect()
    }

    /// Get all errors from the session.
    #[allow(dead_code)]
    pub fn errors(&self) -> Vec<&Event> {
        self.events
            .iter()
            .filter(|e| matches!(e, Event::Error { .. }))
            .collect()
    }
}

/// Convert an event to a log entry.
fn event_to_log_entry(event: &Event) -> Option<LogEntry> {
    match event {
        Event::Init { model, .. } => Some(LogEntry {
            level: LogLevel::Info,
            message: format!("Initialized with model {}", model),
            data: None,
            timestamp: None,
        }),

        Event::AssistantMessage { content, .. } => {
            // Extract text from content blocks
            let texts: Vec<String> = content
                .iter()
                .filter_map(|block| match block {
                    ContentBlock::Text { text } => Some(text.clone()),
                    _ => None,
                })
                .collect();

            if !texts.is_empty() {
                Some(LogEntry {
                    level: LogLevel::Debug,
                    message: texts.join("\n"),
                    data: None,
                    timestamp: None,
                })
            } else {
                None
            }
        }

        Event::ToolExecution {
            tool_name, result, ..
        } => {
            let level = if result.success {
                LogLevel::Debug
            } else {
                LogLevel::Warn
            };

            let message = if result.success {
                format!("Tool '{}' executed successfully", tool_name)
            } else {
                format!(
                    "Tool '{}' failed: {}",
                    tool_name,
                    result.error.as_deref().unwrap_or("unknown error")
                )
            };

            Some(LogEntry {
                level,
                message,
                data: result.data.clone(),
                timestamp: None,
            })
        }

        Event::Result {
            success, message, ..
        } => {
            let level = if *success {
                LogLevel::Info
            } else {
                LogLevel::Error
            };

            Some(LogEntry {
                level,
                message: message.clone().unwrap_or_else(|| {
                    if *success {
                        "Session completed".to_string()
                    } else {
                        "Session failed".to_string()
                    }
                }),
                data: None,
                timestamp: None,
            })
        }

        Event::Error { message, details } => Some(LogEntry {
            level: LogLevel::Error,
            message: message.clone(),
            data: details.clone(),
            timestamp: None,
        }),

        Event::PermissionRequest {
            tool_name, granted, ..
        } => {
            let level = if *granted {
                LogLevel::Debug
            } else {
                LogLevel::Warn
            };

            let message = if *granted {
                format!("Permission granted for tool '{}'", tool_name)
            } else {
                format!("Permission denied for tool '{}'", tool_name)
            };

            Some(LogEntry {
                level,
                message,
                data: None,
                timestamp: None,
            })
        }

        Event::UserMessage { content } => {
            let texts: Vec<String> = content
                .iter()
                .filter_map(|b| {
                    if let ContentBlock::Text { text } = b {
                        Some(text.clone())
                    } else {
                        None
                    }
                })
                .collect();
            if texts.is_empty() {
                None
            } else {
                Some(LogEntry {
                    level: LogLevel::Info,
                    message: texts.join("\n"),
                    data: None,
                    timestamp: None,
                })
            }
        }

        Event::TurnComplete {
            stop_reason,
            turn_index,
            ..
        } => Some(LogEntry {
            level: LogLevel::Debug,
            message: format!(
                "Turn {} complete (stop_reason: {})",
                turn_index,
                stop_reason.as_deref().unwrap_or("none")
            ),
            data: None,
            timestamp: None,
        }),
    }
}

impl std::fmt::Display for LogEntry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let level_str = match self.level {
            LogLevel::Debug => "DEBUG",
            LogLevel::Info => "INFO",
            LogLevel::Warn => "WARN",
            LogLevel::Error => "ERROR",
        };

        write!(f, "[{}] {}", level_str, self.message)
    }
}

/// Get a consistent color for a tool ID using round-robin color selection.
fn get_tool_id_color(tool_id: &str) -> &'static str {
    // 10 distinct colors for tool IDs
    const TOOL_COLORS: [&str; 10] = [
        "\x1b[38;5;33m",  // Blue
        "\x1b[38;5;35m",  // Green
        "\x1b[38;5;141m", // Purple
        "\x1b[38;5;208m", // Orange
        "\x1b[38;5;213m", // Pink
        "\x1b[38;5;51m",  // Cyan
        "\x1b[38;5;226m", // Yellow
        "\x1b[38;5;205m", // Magenta
        "\x1b[38;5;87m",  // Aqua
        "\x1b[38;5;215m", // Peach
    ];

    // Hash the tool_id to get a consistent color
    let hash: u32 = tool_id.bytes().map(|b| b as u32).sum();
    let index = (hash as usize) % TOOL_COLORS.len();
    TOOL_COLORS[index]
}

/// Format a single event as beautiful text output.
///
/// This can be used to stream events in real-time with nice formatting.
pub fn format_event_as_text(event: &Event) -> Option<String> {
    const INDENT: &str = "    ";
    const INDENT_RESULT: &str = "      "; // 6 spaces for tool result continuation
    const RECORD_ICON: &str = "";
    const ARROW_ICON: &str = "";
    const ORANGE: &str = "\x1b[38;5;208m";
    const GREEN: &str = "\x1b[32m";
    const RED: &str = "\x1b[31m";
    const DIM: &str = "\x1b[38;5;240m"; // Gray color for better visibility than dim
    const RESET: &str = "\x1b[0m";

    match event {
        Event::Init { model, .. } => {
            Some(format!("\x1b[32m✓\x1b[0m Initialized with model {}", model))
        }

        Event::UserMessage { content } => {
            let texts: Vec<String> = content
                .iter()
                .filter_map(|block| {
                    if let ContentBlock::Text { text } = block {
                        Some(format!("{}> {}{}", DIM, text, RESET))
                    } else {
                        None
                    }
                })
                .collect();
            if texts.is_empty() {
                None
            } else {
                Some(texts.join("\n"))
            }
        }

        Event::AssistantMessage { content, .. } => {
            let formatted: Vec<String> = content
                .iter()
                .filter_map(|block| match block {
                    ContentBlock::Text { text } => {
                        // Orange text with record icon, indented
                        // Handle multi-line text - first line with icon, rest indented 6 spaces
                        let lines: Vec<&str> = text.lines().collect();
                        if lines.is_empty() {
                            None
                        } else {
                            let mut formatted_lines = Vec::new();
                            for (i, line) in lines.iter().enumerate() {
                                if i == 0 {
                                    // First line with record icon
                                    formatted_lines.push(format!(
                                        "{}{}{} {}{}",
                                        INDENT, ORANGE, RECORD_ICON, line, RESET
                                    ));
                                } else {
                                    // Subsequent lines, indented 6 spaces (still orange)
                                    formatted_lines.push(format!(
                                        "{}{}{}{}",
                                        INDENT_RESULT, ORANGE, line, RESET
                                    ));
                                }
                            }
                            Some(formatted_lines.join("\n"))
                        }
                    }
                    ContentBlock::ToolUse { id, name, input } => {
                        // Tool call with colored id (last 4 chars)
                        let id_suffix = &id[id.len().saturating_sub(4)..];
                        let id_color = get_tool_id_color(id_suffix);
                        const BLUE: &str = "\x1b[34m";

                        // Special formatting for Bash tool
                        if name == "Bash"
                            && let serde_json::Value::Object(obj) = input
                        {
                            let description = obj
                                .get("description")
                                .and_then(|v| v.as_str())
                                .unwrap_or("Run command");
                            let command = obj.get("command").and_then(|v| v.as_str()).unwrap_or("");

                            return Some(format!(
                                "{}{}{} {}{} {}[{}]{}\n{}{}└── {}{}",
                                INDENT,
                                BLUE,
                                RECORD_ICON,
                                description,
                                RESET,
                                id_color,
                                id_suffix,
                                RESET,
                                INDENT_RESULT,
                                DIM,
                                command,
                                RESET
                            ));
                        }

                        // Format input parameters for non-Bash tools
                        let input_str = if let serde_json::Value::Object(obj) = input {
                            if obj.is_empty() {
                                String::new()
                            } else {
                                // Format the parameters as key=value pairs
                                let params: Vec<String> = obj
                                    .iter()
                                    .map(|(key, value)| {
                                        let value_str = match value {
                                            serde_json::Value::String(s) => {
                                                // Truncate long strings
                                                if s.len() > 60 {
                                                    format!("\"{}...\"", &s[..57])
                                                } else {
                                                    format!("\"{}\"", s)
                                                }
                                            }
                                            serde_json::Value::Number(n) => n.to_string(),
                                            serde_json::Value::Bool(b) => b.to_string(),
                                            serde_json::Value::Null => "null".to_string(),
                                            _ => "...".to_string(),
                                        };
                                        format!("{}={}", key, value_str)
                                    })
                                    .collect();
                                params.join(", ")
                            }
                        } else {
                            "...".to_string()
                        };

                        Some(format!(
                            "{}{}{} {}({}) {}[{}]{}",
                            INDENT, BLUE, RECORD_ICON, name, input_str, id_color, id_suffix, RESET
                        ))
                    }
                })
                .collect();

            if !formatted.is_empty() {
                // Add blank line after
                Some(format!("{}\n", formatted.join("\n")))
            } else {
                None
            }
        }

        Event::ToolExecution {
            tool_id, result, ..
        } => {
            let id_suffix = &tool_id[tool_id.len().saturating_sub(4)..];
            let id_color = get_tool_id_color(id_suffix);
            let (icon_color, status_text) = if result.success {
                (GREEN, "success")
            } else {
                (RED, "failed")
            };

            // Get full result text (all lines)
            let result_text = if result.success {
                result.output.as_deref().unwrap_or(status_text)
            } else {
                result.error.as_deref().unwrap_or(status_text)
            };

            // Split into lines and format each one
            let mut lines: Vec<&str> = result_text.lines().collect();
            if lines.is_empty() {
                lines.push(status_text);
            }

            let mut formatted_lines = Vec::new();

            // First line: arrow icon with tool ID
            formatted_lines.push(format!(
                "{}{}{}{} {}[{}]{}",
                INDENT, icon_color, ARROW_ICON, RESET, id_color, id_suffix, RESET
            ));

            // All result lines indented at 6 spaces
            for line in lines.iter() {
                formatted_lines.push(format!("{}{}{}{}", INDENT_RESULT, DIM, line, RESET));
            }

            // Add blank line after
            Some(format!("{}\n", formatted_lines.join("\n")))
        }

        Event::TurnComplete { .. } => {
            // Turn boundary marker — not surfaced in terminal display.
            None
        }

        Event::Result { .. } => {
            // Don't output the final result since it's already been streamed
            None
        }

        Event::Error { message, .. } => Some(format!("\x1b[31mError:\x1b[0m {}", message)),

        Event::PermissionRequest {
            tool_name, granted, ..
        } => {
            if *granted {
                Some(format!(
                    "\x1b[32m✓\x1b[0m Permission granted for tool '{}'",
                    tool_name
                ))
            } else {
                Some(format!(
                    "\x1b[33m!\x1b[0m Permission denied for tool '{}'",
                    tool_name
                ))
            }
        }
    }
}

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