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