Skip to main content

agent_commander/
result_metadata.rs

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