Skip to main content

agent_commander/
result_metadata.rs

1//! Normalized result metadata for tool-specific agent output.
2
3use crate::background_tasks::{
4    assess_background_tasks, extract_observed_models, is_real_model_id, BackgroundTask,
5    StoppedBackgroundTask,
6};
7use crate::completion::{completion_state, outcome_messages};
8use crate::error_text::first_error_text;
9use crate::executor::signal_from_exit_code;
10use crate::usage_limit::{
11    classify_debug_lines, detect_usage_limit_sources, is_recoverable_tool_error, split_output,
12    UsageLimitVerdict,
13};
14use regex::Regex;
15use serde::{Deserialize, Serialize};
16use serde_json::{json, Map, Value};
17use std::sync::LazyLock;
18
19/// Pricing details derived from a tool's public pricing estimate.
20#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
21#[serde(rename_all = "camelCase")]
22pub struct PricingInfo {
23    pub total_cost_usd: f64,
24    pub source: String,
25}
26
27/// Stable metadata that summarizes a completed agent run across tools.
28#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
29#[serde(rename_all = "camelCase")]
30pub struct ResultMetadata {
31    pub tool: String,
32    pub exit_code: i32,
33    /// Signal that ended the process (`SIGTERM`, `SIGKILL`, ...), if any
34    pub signal: Option<String>,
35    pub success: bool,
36    /// The caller stopped the process after its final result
37    pub terminated_after_result: bool,
38    pub session_id: Option<String>,
39    pub limit_reached: bool,
40    pub limit_reset_time: Option<String>,
41    pub limit_timezone: Option<String>,
42    /// Exact reset epoch (seconds) when a structured source reports one
43    pub limit_resets_at: Option<i64>,
44    /// Limit window from a structured source (`five_hour`, `seven_day`, ...)
45    pub limit_window: Option<String>,
46    /// Where a limit found outside the output came from (`codex-rollout`)
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub limit_source: Option<String>,
49    pub anthropic_total_cost_usd: Option<f64>,
50    pub public_pricing_estimate: Option<f64>,
51    pub pricing_info: Option<PricingInfo>,
52    pub result_summary: Option<String>,
53    pub result_model_usage: Option<Value>,
54    /// Real model ids seen in the stream: main thread first, then subagents
55    pub observed_models: Vec<String>,
56    /// Main-thread model observed last
57    pub observed_model: Option<String>,
58    pub stream_token_usage: Option<Value>,
59    pub sub_agent_calls: Option<Vec<Value>>,
60    pub error_during_execution: bool,
61    pub error_type: Option<String>,
62    pub error_message: Option<String>,
63    /// Claude `result.api_error` (or the API error message's `error`)
64    pub api_error: Option<String>,
65    pub api_error_status: Option<i64>,
66    pub terminal_reason: Option<String>,
67    pub request_id: Option<String>,
68    /// Background tasks that never reported an end
69    pub running_background_tasks: Vec<BackgroundTask>,
70    /// Background tasks stopped while the main thread was idle
71    pub background_tasks_stopped: u64,
72    pub stopped_background_tasks: Vec<StoppedBackgroundTask>,
73    /// Claude's print-mode background wait ceiling, when it announced one
74    pub print_wait_ceiling_seconds: Option<u64>,
75}
76
77/// Inputs used to build normalized result metadata.
78#[derive(Debug, Clone, Default)]
79pub struct BuildMetadataOptions<'a> {
80    pub tool: &'a str,
81    pub exit_code: i32,
82    pub plain_output: &'a str,
83    pub parsed_output: Option<&'a [Value]>,
84    pub session_id: Option<String>,
85    pub usage: Option<Value>,
86    /// Signal that ended the process; inferred from a 128 + N exit code when `None`
87    pub signal: Option<String>,
88    /// The caller stopped the process after its final result
89    pub terminated_after_result: bool,
90}
91
92#[derive(Debug, Clone, Default)]
93struct ExecutionError {
94    has_error: bool,
95    error_type: Option<String>,
96    message: Option<String>,
97}
98
99fn parse_json_messages(output: &str) -> Vec<Value> {
100    crate::streaming::parse_json_records(output)
101        .into_iter()
102        .flat_map(|value| match value {
103            Value::Array(values) => values,
104            message => vec![message],
105        })
106        .collect()
107}
108
109fn text_from_value(value: Option<&Value>) -> Option<String> {
110    match value {
111        Some(Value::String(text)) => {
112            let trimmed = text.trim();
113            if trimmed.is_empty() {
114                None
115            } else {
116                Some(trimmed.to_string())
117            }
118        }
119        Some(Value::Array(values)) => {
120            let text = values
121                .iter()
122                .filter_map(|item| text_from_value(Some(item)))
123                .collect::<Vec<_>>()
124                .join("\n");
125            if text.trim().is_empty() {
126                None
127            } else {
128                Some(text)
129            }
130        }
131        Some(Value::Object(map)) => {
132            for key in ["text", "content", "result", "summary", "message"] {
133                if let Some(text) = text_from_value(map.get(key)) {
134                    return Some(text);
135                }
136            }
137            None
138        }
139        _ => None,
140    }
141}
142
143fn tail_chars(value: &str, max_chars: usize) -> String {
144    let chars = value.chars().collect::<Vec<_>>();
145    let start = chars.len().saturating_sub(max_chars);
146    chars[start..].iter().collect()
147}
148
149fn extract_result_summary(messages: &[Value], plain_output: &str) -> Option<String> {
150    let keys = [
151        "result",
152        "response",
153        "summary",
154        "result_summary",
155        "resultSummary",
156        "final_answer",
157        "finalAnswer",
158        "text",
159        "content",
160        "message",
161    ];
162
163    for message in messages.iter().rev() {
164        if !message.is_object() {
165            continue;
166        }
167
168        for key in keys {
169            if let Some(text) = text_from_value(message.get(key)) {
170                return Some(text);
171            }
172        }
173
174        let nested_text = text_from_value(message.pointer("/part/text"))
175            .or_else(|| text_from_value(message.pointer("/item/content")))
176            .or_else(|| text_from_value(message.pointer("/item/text")))
177            .or_else(|| text_from_value(message.pointer("/delta/text")));
178        if nested_text.is_some() {
179            return nested_text;
180        }
181    }
182
183    let trimmed = plain_output.trim();
184    if trimmed.is_empty() {
185        None
186    } else {
187        Some(tail_chars(trimmed, 4000))
188    }
189}
190
191fn first_number(messages: &[Value], keys: &[&str]) -> Option<f64> {
192    for message in messages.iter().rev() {
193        for key in keys {
194            if let Some(value) = message.get(*key).and_then(Value::as_f64) {
195                return Some(value);
196            }
197        }
198    }
199
200    None
201}
202
203fn extract_result_model_usage(messages: &[Value]) -> Option<Value> {
204    for message in messages.iter().rev() {
205        for key in [
206            "resultModelUsage",
207            "result_model_usage",
208            "modelUsage",
209            "model_usage",
210            "usage_by_model",
211        ] {
212            if let Some(value) = message.get(key) {
213                if value.is_object() {
214                    return Some(value.clone());
215                }
216            }
217        }
218    }
219
220    if let Some(models) = messages
221        .iter()
222        .rev()
223        .find_map(|m| m.pointer("/stats/models"))
224    {
225        return Some(models.clone());
226    }
227    let mut usage_by_model = Map::new();
228    for message in messages {
229        let model = message
230            .get("model")
231            .or_else(|| message.pointer("/message/model"))
232            .or_else(|| message.pointer("/part/model"))
233            .and_then(Value::as_str)
234            .filter(|model| is_real_model_id(model));
235        let usage = message
236            .get("usage")
237            .or_else(|| message.pointer("/message/usage"))
238            .or_else(|| message.pointer("/part/tokens"));
239
240        if let (Some(model), Some(usage)) = (model, usage) {
241            let entry = usage_by_model
242                .entry(model.to_string())
243                .or_insert_with(|| Value::Array(Vec::new()));
244            if let Value::Array(values) = entry {
245                values.push(usage.clone());
246            }
247        }
248    }
249
250    if usage_by_model.is_empty() {
251        None
252    } else {
253        Some(Value::Object(usage_by_model))
254    }
255}
256
257fn extract_sub_agent_calls(messages: &[Value]) -> Option<Vec<Value>> {
258    let mut calls = Vec::new();
259
260    for message in messages {
261        for key in [
262            "subAgentCalls",
263            "sub_agent_calls",
264            "subAgents",
265            "sub_agents",
266        ] {
267            if let Some(Value::Array(values)) = message.get(key) {
268                calls.extend(values.iter().cloned());
269            }
270        }
271
272        if let Some(blocks) = message
273            .pointer("/message/content")
274            .and_then(Value::as_array)
275        {
276            for block in blocks {
277                if block["type"] == "tool_use"
278                    && matches!(block["name"].as_str(), Some("Task" | "Agent"))
279                {
280                    calls.push(json!({
281                        "type": "tool_use",
282                        "id": block["id"],
283                        "name": block["name"],
284                        "status": "started",
285                        "summary": block.pointer("/input/description"),
286                    }));
287                }
288            }
289        }
290
291        let message_type = message
292            .pointer("/item/type")
293            .or_else(|| message.get("type"))
294            .or_else(|| message.get("item_type"))
295            .and_then(Value::as_str);
296        if let Some(message_type) = message_type {
297            let lower = message_type.to_ascii_lowercase();
298            if lower.contains("sub_agent")
299                || lower.contains("sub-agent")
300                || lower.contains("subagent")
301                || lower.contains("collab")
302            {
303                calls.push(json!({
304                    "type": message_type,
305                    "id": message
306                        .get("id")
307                        .or_else(|| message.get("call_id"))
308                        .or_else(|| message.pointer("/item/id"))
309                        .cloned()
310                        .unwrap_or(Value::Null),
311                    "name": message
312                        .get("name")
313                        .or_else(|| message.get("tool"))
314                        .or_else(|| message.pointer("/item/name"))
315                        .cloned()
316                        .unwrap_or(Value::Null),
317                    "status": message
318                        .pointer("/item/status")
319                        .or_else(|| message.get("status"))
320                        .or_else(|| message.get("state"))
321                        .cloned()
322                        .unwrap_or(Value::Null),
323                    "summary": extract_result_summary(std::slice::from_ref(message), ""),
324                }));
325            }
326        }
327    }
328
329    if calls.is_empty() {
330        None
331    } else {
332        Some(calls)
333    }
334}
335
336/// Claude's synthetic API error message carries the error code as a string
337/// (`"error":"rate_limit"`) and the readable text in its content.
338fn api_error_code(messages: &[Value]) -> Option<&str> {
339    messages
340        .iter()
341        .rev()
342        .find(|event| {
343            event["type"] == "assistant"
344                && event["is_api_error_message"] == true
345                && event["error"].is_string()
346        })
347        .and_then(|event| event["error"].as_str())
348}
349
350fn non_empty_str(value: Option<&Value>) -> Option<&str> {
351    value
352        .and_then(Value::as_str)
353        .filter(|text| !text.is_empty())
354}
355
356fn extract_error_from_messages(messages: &[Value]) -> ExecutionError {
357    let code = api_error_code(messages);
358    for message in messages.iter().rev() {
359        if !message.is_object() || is_recoverable_tool_error(message) {
360            // A failed tool call is returned to the model; it does not decide the run.
361            continue;
362        }
363        let message_type = non_empty_str(message.get("type"))
364            .or_else(|| non_empty_str(message.get("subtype")))
365            .or_else(|| non_empty_str(message.pointer("/item/type")));
366        let is_error = message.get("is_error").and_then(Value::as_bool) == Some(true)
367            || message
368                .get("error")
369                .is_some_and(|e| !e.is_null() && e != &Value::Bool(false) && e != "")
370            || matches!(message_type, Some("error" | "step_error" | "turn.failed"))
371            || message["status"] == "error"
372            || message["subtype"]
373                .as_str()
374                .is_some_and(|s| s.starts_with("error"));
375
376        if !is_error {
377            continue;
378        }
379
380        let error = message.get("error");
381        let object_error = error.filter(|value| value.is_object());
382        let string_error = non_empty_str(error);
383        let error_type = object_error
384            .and_then(|value| {
385                ["type", "code", "name"]
386                    .iter()
387                    .find_map(|key| non_empty_str(value.get(*key)))
388            })
389            .or(string_error)
390            .or_else(|| non_empty_str(message.get("errorType")))
391            .or_else(|| non_empty_str(message.get("error_type")))
392            .or_else(|| {
393                (message_type == Some("result"))
394                    .then(|| non_empty_str(message.get("api_error")).or(code))
395                    .flatten()
396            })
397            .or(message_type)
398            .unwrap_or("execution_error")
399            .to_string();
400        let error_message = object_error
401            .map(|value| first_error_text(&[value], ""))
402            .filter(|text| !text.is_empty())
403            .or_else(|| text_from_value(message.get("message")))
404            .or_else(|| text_from_value(message.get("result")))
405            .or_else(|| string_error.map(ToString::to_string))
406            .unwrap_or_else(|| "Execution failed".to_string());
407
408        return ExecutionError {
409            has_error: true,
410            error_type: Some(error_type),
411            message: Some(error_message),
412        };
413    }
414
415    ExecutionError::default()
416}
417
418static PREFERRED_EXIT_LINE: LazyLock<Regex> = LazyLock::new(|| {
419    Regex::new(r"(?i)^(?:error\b|fatal:|(?:/\S*/)?(?:ba|z)?sh:\s)").expect("valid pattern")
420});
421
422/// A `tracing` log line (`2026-01-01T00:00:00.000Z DEBUG ...`) names no exit reason.
423static TRACING_LINE: LazyLock<Regex> = LazyLock::new(|| {
424    Regex::new(r"^\S*?\d{4}-\d{2}-\d{2}T[\d:.]+Z\s+(?:TRACE|DEBUG|INFO|WARN|ERROR)\s")
425        .expect("valid pattern")
426});
427
428/// The reason a process exited is a plain text line: JSON records, the
429/// `ANTHROPIC_LOG=debug` dump and its base64 bodies are not (hive-mind#3570).
430fn exit_reason_line(plain_output: &str) -> Option<String> {
431    let (_, lines) = split_output(plain_output);
432    let debug = classify_debug_lines(&lines);
433    let candidates: Vec<&str> = lines
434        .iter()
435        .enumerate()
436        .filter(|(index, _)| !debug.debug_lines.contains(index))
437        .map(|(_, line)| line.trim())
438        .filter(|line| !line.is_empty() && !TRACING_LINE.is_match(line))
439        .collect();
440    candidates
441        .iter()
442        .rev()
443        .find(|line| PREFERRED_EXIT_LINE.is_match(line))
444        .or_else(|| candidates.last())
445        .map(|line| (*line).to_string())
446}
447
448fn exit_code_error(exit_code: i32, signal: Option<&str>, plain_output: &str) -> ExecutionError {
449    let reason = exit_reason_line(plain_output);
450    let Some(signal) = signal else {
451        return ExecutionError {
452            has_error: true,
453            error_type: Some("exit_code".to_string()),
454            message: reason.or_else(|| Some(format!("Process exited with code {exit_code}"))),
455        };
456    };
457    // A signal is the cause; a preferred error line may still say why it came.
458    let preferred = reason
459        .filter(|line| PREFERRED_EXIT_LINE.is_match(line))
460        .map(|line| format!(": {line}"))
461        .unwrap_or_default();
462    ExecutionError {
463        has_error: true,
464        error_type: Some("signal".to_string()),
465        message: Some(format!(
466            "Process exited with code {exit_code} ({signal}){preferred}"
467        )),
468    }
469}
470
471fn detect_execution_error(
472    tool: &str,
473    exit_code: i32,
474    signal: Option<&str>,
475    plain_output: &str,
476    messages: &[Value],
477) -> ExecutionError {
478    if tool == "agent" {
479        let detected = crate::tools::agent::detect_errors(
480            &messages
481                .iter()
482                .map(Value::to_string)
483                .collect::<Vec<_>>()
484                .join("\n"),
485        );
486        if detected.has_error {
487            return ExecutionError {
488                has_error: true,
489                error_type: detected
490                    .error_type
491                    .or_else(|| Some("execution_error".to_string())),
492                message: detected
493                    .message
494                    .or_else(|| Some("Execution failed".to_string())),
495            };
496        }
497    }
498
499    let message_error = extract_error_from_messages(messages);
500    if message_error.has_error {
501        return message_error;
502    }
503
504    if exit_code != 0 {
505        return signal
506            .is_none()
507            .then(|| error_record_in_output(plain_output))
508            .flatten()
509            .unwrap_or_else(|| exit_code_error(exit_code, signal, plain_output));
510    }
511
512    ExecutionError::default()
513}
514
515/// A process that failed without an error event on stdout may have written it
516/// to stderr: Agent prints its fatal errors there (agent `src/cli/output.ts`
517/// `outputError`; hive-mind `agent.lib.mjs` scans both streams). Only explains
518/// a failed exit, so diagnostics cannot fail a successful run.
519fn error_record_in_output(plain_output: &str) -> Option<ExecutionError> {
520    let records: Vec<Value> = parse_json_messages(plain_output)
521        .into_iter()
522        .filter(|record| record.get("type").and_then(Value::as_str) == Some("error"))
523        .collect();
524    Some(extract_error_from_messages(&records)).filter(|error| error.has_error)
525}
526
527struct ApiErrorDetails {
528    api_error: Option<String>,
529    api_error_status: Option<i64>,
530    terminal_reason: Option<String>,
531    request_id: Option<String>,
532}
533
534/// API failure details from Claude's last `result` or its API error message.
535fn extract_api_error_details(messages: &[Value]) -> ApiErrorDetails {
536    let result = messages
537        .iter()
538        .rev()
539        .find(|event| event["type"] == "result");
540    let api_message = messages
541        .iter()
542        .rev()
543        .find(|event| event["type"] == "assistant" && event["is_api_error_message"] == true);
544    let text = |event: Option<&Value>, key: &str| {
545        event
546            .and_then(|event| event.get(key))
547            .and_then(Value::as_str)
548            .map(String::from)
549    };
550    ApiErrorDetails {
551        api_error: text(result, "api_error")
552            .or_else(|| text(result, "error"))
553            .or_else(|| text(api_message, "error")),
554        api_error_status: result
555            .and_then(|result| result.get("api_error_status"))
556            .and_then(Value::as_i64),
557        terminal_reason: text(result, "terminal_reason"),
558        request_id: text(result, "request_id").or_else(|| text(api_message, "request_id")),
559    }
560}
561
562fn extract_session_id(explicit_session_id: Option<String>, messages: &[Value]) -> Option<String> {
563    if explicit_session_id.is_some() {
564        return explicit_session_id;
565    }
566
567    for message in messages {
568        for key in [
569            "session_id",
570            "sessionId",
571            "sessionID",
572            "thread_id",
573            "threadId",
574            "conversation_id",
575            "conversationId",
576        ] {
577            if let Some(session_id) = message.get(key).and_then(Value::as_str) {
578                return Some(session_id.to_string());
579            }
580        }
581    }
582
583    None
584}
585
586fn public_pricing_estimate(tool: &str, usage: Option<&Value>) -> Option<f64> {
587    if tool != "agent" && tool != "opencode" {
588        return None;
589    }
590
591    usage
592        .and_then(|value| value.get("totalCost").or_else(|| value.get("totalCostUSD")))
593        .and_then(Value::as_f64)
594}
595
596/// Build stable, caller-facing metadata from tool-specific agent output.
597pub fn build_normalized_result_metadata(options: BuildMetadataOptions<'_>) -> ResultMetadata {
598    let all_messages = options.parsed_output.map_or_else(
599        || parse_json_messages(options.plain_output),
600        <[Value]>::to_vec,
601    );
602    let messages: Vec<_> = all_messages
603        .iter()
604        .filter(|event| event["parent_tool_use_id"].is_null())
605        .cloned()
606        .collect();
607    let signal = options
608        .signal
609        .clone()
610        .or_else(|| signal_from_exit_code(options.exit_code).map(String::from));
611    let completion = completion_state(options.tool, &messages);
612    // Stopping a process after its completed result is the caller's own
613    // signal, not the tool's verdict (hive-mind#3015 interpretClaudeExitCode).
614    let exit_forgiven = options.terminated_after_result && completion == Some("completed");
615    // The raw stream contains HTTP header names (e.g.
616    // "anthropic-ratelimit-unified-5h-reset") even on a successful run, so a
617    // native completion event wins over the text scan (issue #37).
618    let usage_limit = if completion == Some("completed") {
619        UsageLimitVerdict::default()
620    } else {
621        detect_usage_limit_sources(options.plain_output, &messages)
622    };
623    let mut execution_error = detect_execution_error(
624        options.tool,
625        if exit_forgiven { 0 } else { options.exit_code },
626        signal.as_deref(),
627        options.plain_output,
628        outcome_messages(options.tool, &messages),
629    );
630    if !execution_error.has_error && completion == Some("incomplete") {
631        execution_error = ExecutionError {
632            has_error: true,
633            error_type: Some("incomplete_stream".into()),
634            message: Some("Process exited before the native completion event".into()),
635        };
636    }
637    let background = assess_background_tasks(
638        &all_messages,
639        options.plain_output,
640        options.terminated_after_result,
641    );
642    if !execution_error.has_error && background.incomplete {
643        execution_error = ExecutionError {
644            has_error: true,
645            error_type: Some("background_tasks_stopped".into()),
646            message: background.cause.clone(),
647        };
648    }
649    // A server-side throttle is transient: callers retry instead of waiting for a reset.
650    if execution_error.has_error && usage_limit.throttled {
651        execution_error.error_type = Some("rate_limited".into());
652    }
653    let session_id = extract_session_id(options.session_id, &messages);
654    let public_pricing_estimate = public_pricing_estimate(options.tool, options.usage.as_ref());
655    let pricing_info = public_pricing_estimate.map(|total_cost_usd| PricingInfo {
656        total_cost_usd,
657        source: format!("{}-stream-usage", options.tool),
658    });
659    let (observed_models, observed_model) = extract_observed_models(&all_messages);
660    let api = extract_api_error_details(&messages);
661
662    ResultMetadata {
663        tool: options.tool.to_string(),
664        exit_code: options.exit_code,
665        signal,
666        success: (options.exit_code == 0 || exit_forgiven)
667            && !usage_limit.reached
668            && !execution_error.has_error,
669        terminated_after_result: options.terminated_after_result,
670        session_id,
671        limit_reached: usage_limit.reached,
672        limit_reset_time: usage_limit.reset_time,
673        limit_timezone: usage_limit.timezone,
674        limit_resets_at: usage_limit.resets_at,
675        limit_window: usage_limit.window,
676        limit_source: None,
677        anthropic_total_cost_usd: first_number(
678            &messages,
679            &["total_cost_usd", "totalCostUsd", "anthropicTotalCostUSD"],
680        ),
681        public_pricing_estimate,
682        pricing_info,
683        result_summary: extract_result_summary(&messages, options.plain_output),
684        result_model_usage: extract_result_model_usage(&messages),
685        observed_models,
686        observed_model,
687        stream_token_usage: options.usage,
688        sub_agent_calls: extract_sub_agent_calls(&all_messages),
689        error_during_execution: execution_error.has_error,
690        error_type: execution_error.error_type,
691        error_message: execution_error.message,
692        api_error: api.api_error,
693        api_error_status: api.api_error_status,
694        terminal_reason: api.terminal_reason,
695        request_id: api.request_id,
696        running_background_tasks: background.running_background_tasks,
697        background_tasks_stopped: background.background_tasks_stopped,
698        stopped_background_tasks: background.stopped_background_tasks,
699        print_wait_ceiling_seconds: background.print_wait_ceiling_seconds,
700    }
701}
702
703#[cfg(test)]
704mod tests {
705    use super::{build_normalized_result_metadata, BuildMetadataOptions};
706    use serde_json::json;
707
708    #[test]
709    fn normalizes_codex_thread_id_and_usage() {
710        let usage = json!({
711            "inputTokens": 12,
712            "outputTokens": 4,
713        });
714        let metadata = build_normalized_result_metadata(BuildMetadataOptions {
715            tool: "codex",
716            exit_code: 0,
717            plain_output:
718                "{\"type\":\"session\",\"thread_id\":\"thread-123\"}\n{\"type\":\"message\",\"content\":\"Done.\"}",
719            parsed_output: None,
720            session_id: None,
721            usage: Some(usage.clone()),
722            ..Default::default()
723        });
724
725        assert_eq!(metadata.tool, "codex");
726        assert!(metadata.success);
727        assert_eq!(metadata.session_id, Some("thread-123".to_string()));
728        assert_eq!(metadata.result_summary, Some("Done.".to_string()));
729        assert_eq!(metadata.stream_token_usage, Some(usage));
730    }
731
732    #[test]
733    fn exposes_agent_pricing_and_sub_agent_calls() {
734        let messages = vec![
735            json!({
736                "type": "collab_tool_call",
737                "id": "call-1",
738                "name": "worker",
739                "status": "completed",
740                "summary": "Worker finished."
741            }),
742            json!({
743                "type": "message",
744                "text": "Final summary."
745            }),
746        ];
747        let usage = json!({
748            "inputTokens": 100,
749            "outputTokens": 40,
750            "totalCost": 0.004,
751            "stepCount": 1
752        });
753        let metadata = build_normalized_result_metadata(BuildMetadataOptions {
754            tool: "agent",
755            exit_code: 0,
756            plain_output: "",
757            parsed_output: Some(&messages),
758            session_id: None,
759            usage: Some(usage.clone()),
760            ..Default::default()
761        });
762
763        assert_eq!(metadata.tool, "agent");
764        assert!(metadata.success);
765        assert_eq!(metadata.public_pricing_estimate, Some(0.004));
766        assert_eq!(
767            metadata
768                .pricing_info
769                .as_ref()
770                .map(|pricing| pricing.source.as_str()),
771            Some("agent-stream-usage")
772        );
773        assert_eq!(metadata.result_summary, Some("Final summary.".to_string()));
774        let sub_agent_calls = metadata.sub_agent_calls.unwrap();
775        assert_eq!(sub_agent_calls.len(), 1);
776        assert_eq!(sub_agent_calls[0].get("id"), Some(&json!("call-1")));
777    }
778}