Skip to main content

agent_commander/
result_metadata.rs

1//! Normalized result metadata for tool-specific agent output.
2
3use crate::completion::{completion_state, outcome_messages};
4use serde::{Deserialize, Serialize};
5use serde_json::{json, Map, Value};
6
7/// Pricing details derived from a tool's public pricing estimate.
8#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
9#[serde(rename_all = "camelCase")]
10pub struct PricingInfo {
11    pub total_cost_usd: f64,
12    pub source: String,
13}
14
15/// Stable metadata that summarizes a completed agent run across tools.
16#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
17#[serde(rename_all = "camelCase")]
18pub struct ResultMetadata {
19    pub tool: String,
20    pub exit_code: i32,
21    pub success: bool,
22    pub session_id: Option<String>,
23    pub limit_reached: bool,
24    pub limit_reset_time: Option<String>,
25    pub limit_timezone: Option<String>,
26    pub anthropic_total_cost_usd: Option<f64>,
27    pub public_pricing_estimate: Option<f64>,
28    pub pricing_info: Option<PricingInfo>,
29    pub result_summary: Option<String>,
30    pub result_model_usage: Option<Value>,
31    pub stream_token_usage: Option<Value>,
32    pub sub_agent_calls: Option<Vec<Value>>,
33    pub error_during_execution: bool,
34    pub error_type: Option<String>,
35    pub error_message: Option<String>,
36}
37
38/// Inputs used to build normalized result metadata.
39#[derive(Debug, Clone)]
40pub struct BuildMetadataOptions<'a> {
41    pub tool: &'a str,
42    pub exit_code: i32,
43    pub plain_output: &'a str,
44    pub parsed_output: Option<&'a [Value]>,
45    pub session_id: Option<String>,
46    pub usage: Option<Value>,
47}
48
49#[derive(Debug, Clone, Default)]
50struct UsageLimit {
51    reached: bool,
52    reset_time: Option<String>,
53    timezone: Option<String>,
54}
55
56#[derive(Debug, Clone, Default)]
57struct ExecutionError {
58    has_error: bool,
59    error_type: Option<String>,
60    message: Option<String>,
61}
62
63fn parse_json_messages(output: &str) -> Vec<Value> {
64    if output.trim().is_empty() {
65        return Vec::new();
66    }
67
68    if let Ok(parsed) = serde_json::from_str::<Value>(output) {
69        return match parsed {
70            Value::Array(messages) => messages,
71            message => vec![message],
72        };
73    }
74
75    output
76        .lines()
77        .filter_map(|line| {
78            let trimmed = line.trim();
79            if trimmed.is_empty() || (!trimmed.starts_with('{') && !trimmed.starts_with('[')) {
80                return None;
81            }
82
83            serde_json::from_str::<Value>(trimmed).ok()
84        })
85        .flat_map(|value| match value {
86            Value::Array(values) => values,
87            message => vec![message],
88        })
89        .collect()
90}
91
92fn limit_reached(output: &str) -> bool {
93    let lower = output.to_ascii_lowercase();
94    [
95        "usage limit reached",
96        "usage limit exceeded",
97        "rate limit",
98        "rate_limit",
99        "limit reached",
100        "billing hard limit",
101        "please try again at",
102        "available again at",
103        "session limit reached",
104        "weekly limit reached",
105        "daily limit reached",
106        "monthly limit reached",
107        "freeusagelimiterror",
108        "resets ",
109    ]
110    .iter()
111    .any(|pattern| lower.contains(pattern))
112}
113
114fn clean_reset_time(value: &str) -> Option<String> {
115    let cleaned = value
116        .trim()
117        .trim_matches(|c: char| c == ')' || c == ',' || c == ';')
118        .trim();
119    if cleaned.is_empty() || cleaned.len() > 120 {
120        return None;
121    }
122
123    Some(cleaned.to_string())
124}
125
126fn extract_reset_time(output: &str) -> Option<String> {
127    let lower = output.to_ascii_lowercase();
128    for marker in [
129        "limit resets at",
130        "reset time:",
131        "resets at",
132        "reset at",
133        "try again at",
134        "available again at",
135        "available at",
136        "resets",
137        "reset",
138    ] {
139        if let Some(index) = lower.find(marker) {
140            let tail = &output[index + marker.len()..];
141            let candidate = tail.split(['\n', '.']).next().unwrap_or_default().trim();
142            if let Some(cleaned) = clean_reset_time(candidate) {
143                return Some(cleaned);
144            }
145        }
146    }
147
148    None
149}
150
151fn looks_like_timezone(value: &str) -> bool {
152    let value = value.trim();
153    if value.starts_with("UTC") {
154        return true;
155    }
156    if value.contains('/') {
157        return value
158            .chars()
159            .all(|c| c.is_ascii_alphabetic() || c == '/' || c == '_' || c == '-');
160    }
161    value.len() >= 2 && value.len() <= 5 && value.chars().all(|c| c.is_ascii_uppercase())
162}
163
164fn extract_timezone(output: &str, reset_time: Option<&str>) -> Option<String> {
165    for part in output.split('(').skip(1) {
166        if let Some(candidate) = part.split(')').next() {
167            if looks_like_timezone(candidate) {
168                return Some(candidate.trim().to_string());
169            }
170        }
171    }
172
173    if let Some(reset_time) = reset_time {
174        for token in reset_time.split_whitespace() {
175            let candidate = token.trim_matches(|c: char| c == '(' || c == ')' || c == ',');
176            if looks_like_timezone(candidate) {
177                return Some(candidate.to_string());
178            }
179        }
180    }
181
182    None
183}
184
185fn detect_usage_limit(output: &str) -> UsageLimit {
186    if !limit_reached(output) {
187        return UsageLimit::default();
188    }
189
190    let reset_time = extract_reset_time(output);
191    let timezone = extract_timezone(output, reset_time.as_deref());
192
193    UsageLimit {
194        reached: true,
195        reset_time,
196        timezone,
197    }
198}
199
200fn text_from_value(value: Option<&Value>) -> Option<String> {
201    match value {
202        Some(Value::String(text)) => {
203            let trimmed = text.trim();
204            if trimmed.is_empty() {
205                None
206            } else {
207                Some(trimmed.to_string())
208            }
209        }
210        Some(Value::Array(values)) => {
211            let text = values
212                .iter()
213                .filter_map(|item| text_from_value(Some(item)))
214                .collect::<Vec<_>>()
215                .join("\n");
216            if text.trim().is_empty() {
217                None
218            } else {
219                Some(text)
220            }
221        }
222        Some(Value::Object(map)) => {
223            for key in ["text", "content", "result", "summary", "message"] {
224                if let Some(text) = text_from_value(map.get(key)) {
225                    return Some(text);
226                }
227            }
228            None
229        }
230        _ => None,
231    }
232}
233
234fn tail_chars(value: &str, max_chars: usize) -> String {
235    let chars = value.chars().collect::<Vec<_>>();
236    let start = chars.len().saturating_sub(max_chars);
237    chars[start..].iter().collect()
238}
239
240fn extract_result_summary(messages: &[Value], plain_output: &str) -> Option<String> {
241    let keys = [
242        "result",
243        "response",
244        "summary",
245        "result_summary",
246        "resultSummary",
247        "final_answer",
248        "finalAnswer",
249        "text",
250        "content",
251        "message",
252    ];
253
254    for message in messages.iter().rev() {
255        if !message.is_object() {
256            continue;
257        }
258
259        for key in keys {
260            if let Some(text) = text_from_value(message.get(key)) {
261                return Some(text);
262            }
263        }
264
265        let nested_text = text_from_value(message.pointer("/part/text"))
266            .or_else(|| text_from_value(message.pointer("/item/content")))
267            .or_else(|| text_from_value(message.pointer("/item/text")))
268            .or_else(|| text_from_value(message.pointer("/delta/text")));
269        if nested_text.is_some() {
270            return nested_text;
271        }
272    }
273
274    let trimmed = plain_output.trim();
275    if trimmed.is_empty() {
276        None
277    } else {
278        Some(tail_chars(trimmed, 4000))
279    }
280}
281
282fn first_number(messages: &[Value], keys: &[&str]) -> Option<f64> {
283    for message in messages.iter().rev() {
284        for key in keys {
285            if let Some(value) = message.get(*key).and_then(Value::as_f64) {
286                return Some(value);
287            }
288        }
289    }
290
291    None
292}
293
294fn extract_result_model_usage(messages: &[Value]) -> Option<Value> {
295    for message in messages.iter().rev() {
296        for key in [
297            "resultModelUsage",
298            "result_model_usage",
299            "modelUsage",
300            "model_usage",
301            "usage_by_model",
302        ] {
303            if let Some(value) = message.get(key) {
304                if value.is_object() {
305                    return Some(value.clone());
306                }
307            }
308        }
309    }
310
311    if let Some(models) = messages
312        .iter()
313        .rev()
314        .find_map(|m| m.pointer("/stats/models"))
315    {
316        return Some(models.clone());
317    }
318    let mut usage_by_model = Map::new();
319    for message in messages {
320        let model = message
321            .get("model")
322            .or_else(|| message.pointer("/message/model"))
323            .or_else(|| message.pointer("/part/model"))
324            .and_then(Value::as_str);
325        let usage = message
326            .get("usage")
327            .or_else(|| message.pointer("/message/usage"))
328            .or_else(|| message.pointer("/part/tokens"));
329
330        if let (Some(model), Some(usage)) = (model, usage) {
331            let entry = usage_by_model
332                .entry(model.to_string())
333                .or_insert_with(|| Value::Array(Vec::new()));
334            if let Value::Array(values) = entry {
335                values.push(usage.clone());
336            }
337        }
338    }
339
340    if usage_by_model.is_empty() {
341        None
342    } else {
343        Some(Value::Object(usage_by_model))
344    }
345}
346
347fn extract_sub_agent_calls(messages: &[Value]) -> Option<Vec<Value>> {
348    let mut calls = Vec::new();
349
350    for message in messages {
351        for key in [
352            "subAgentCalls",
353            "sub_agent_calls",
354            "subAgents",
355            "sub_agents",
356        ] {
357            if let Some(Value::Array(values)) = message.get(key) {
358                calls.extend(values.iter().cloned());
359            }
360        }
361
362        if let Some(blocks) = message
363            .pointer("/message/content")
364            .and_then(Value::as_array)
365        {
366            for block in blocks {
367                if block["type"] == "tool_use"
368                    && matches!(block["name"].as_str(), Some("Task" | "Agent"))
369                {
370                    calls.push(json!({
371                        "type": "tool_use",
372                        "id": block["id"],
373                        "name": block["name"],
374                        "status": "started",
375                        "summary": block.pointer("/input/description"),
376                    }));
377                }
378            }
379        }
380
381        let message_type = message
382            .pointer("/item/type")
383            .or_else(|| message.get("type"))
384            .or_else(|| message.get("item_type"))
385            .and_then(Value::as_str);
386        if let Some(message_type) = message_type {
387            let lower = message_type.to_ascii_lowercase();
388            if lower.contains("sub_agent")
389                || lower.contains("sub-agent")
390                || lower.contains("subagent")
391                || lower.contains("collab")
392            {
393                calls.push(json!({
394                    "type": message_type,
395                    "id": message
396                        .get("id")
397                        .or_else(|| message.get("call_id"))
398                        .or_else(|| message.pointer("/item/id"))
399                        .cloned()
400                        .unwrap_or(Value::Null),
401                    "name": message
402                        .get("name")
403                        .or_else(|| message.get("tool"))
404                        .or_else(|| message.pointer("/item/name"))
405                        .cloned()
406                        .unwrap_or(Value::Null),
407                    "status": message
408                        .pointer("/item/status")
409                        .or_else(|| message.get("status"))
410                        .or_else(|| message.get("state"))
411                        .cloned()
412                        .unwrap_or(Value::Null),
413                    "summary": extract_result_summary(std::slice::from_ref(message), ""),
414                }));
415            }
416        }
417    }
418
419    if calls.is_empty() {
420        None
421    } else {
422        Some(calls)
423    }
424}
425
426fn extract_error_from_messages(messages: &[Value]) -> ExecutionError {
427    for message in messages.iter().rev() {
428        let message_type = message
429            .get("type")
430            .or_else(|| message.get("subtype"))
431            .or_else(|| message.pointer("/item/type"))
432            .and_then(Value::as_str);
433        let is_error = message.get("is_error").and_then(Value::as_bool) == Some(true)
434            || message
435                .get("error")
436                .is_some_and(|e| !e.is_null() && e != &Value::Bool(false))
437            || matches!(message_type, Some("error" | "step_error" | "turn.failed"))
438            || message["status"] == "error"
439            || message["subtype"]
440                .as_str()
441                .is_some_and(|s| s.starts_with("error"));
442
443        if !is_error {
444            continue;
445        }
446
447        let error = message.get("error");
448        let error_type = error
449            .and_then(|value| value.get("type").or_else(|| value.get("code")))
450            .and_then(Value::as_str)
451            .or_else(|| message.get("errorType").and_then(Value::as_str))
452            .or_else(|| message.get("error_type").and_then(Value::as_str))
453            .or(message_type)
454            .unwrap_or("execution_error")
455            .to_string();
456        let error_message = error
457            .and_then(Value::as_str)
458            .map(ToString::to_string)
459            .or_else(|| {
460                error
461                    .and_then(|value| value.get("message").or_else(|| value.get("details")))
462                    .and_then(Value::as_str)
463                    .map(ToString::to_string)
464            })
465            .or_else(|| text_from_value(message.get("message")))
466            .or_else(|| text_from_value(message.get("result")))
467            .unwrap_or_else(|| "Execution failed".to_string());
468
469        return ExecutionError {
470            has_error: true,
471            error_type: Some(error_type),
472            message: Some(error_message),
473        };
474    }
475
476    ExecutionError::default()
477}
478
479fn detect_execution_error(
480    tool: &str,
481    exit_code: i32,
482    plain_output: &str,
483    messages: &[Value],
484) -> ExecutionError {
485    if tool == "agent" {
486        let detected = crate::tools::agent::detect_errors(
487            &messages
488                .iter()
489                .map(Value::to_string)
490                .collect::<Vec<_>>()
491                .join("\n"),
492        );
493        if detected.has_error {
494            return ExecutionError {
495                has_error: true,
496                error_type: detected
497                    .error_type
498                    .or_else(|| Some("execution_error".to_string())),
499                message: detected
500                    .message
501                    .or_else(|| Some("Execution failed".to_string())),
502            };
503        }
504    }
505
506    let message_error = extract_error_from_messages(messages);
507    if message_error.has_error {
508        return message_error;
509    }
510
511    if exit_code != 0 {
512        let last_line = plain_output
513            .trim()
514            .lines()
515            .rev()
516            .find(|line| !line.trim().is_empty())
517            .map(str::trim)
518            .filter(|line| !line.is_empty())
519            .map(ToString::to_string);
520        return ExecutionError {
521            has_error: true,
522            error_type: Some("exit_code".to_string()),
523            message: last_line.or_else(|| Some(format!("Process exited with code {}", exit_code))),
524        };
525    }
526
527    ExecutionError::default()
528}
529
530fn extract_session_id(explicit_session_id: Option<String>, messages: &[Value]) -> Option<String> {
531    if explicit_session_id.is_some() {
532        return explicit_session_id;
533    }
534
535    for message in messages {
536        for key in [
537            "session_id",
538            "sessionId",
539            "sessionID",
540            "thread_id",
541            "threadId",
542            "conversation_id",
543            "conversationId",
544        ] {
545            if let Some(session_id) = message.get(key).and_then(Value::as_str) {
546                return Some(session_id.to_string());
547            }
548        }
549    }
550
551    None
552}
553
554fn public_pricing_estimate(tool: &str, usage: Option<&Value>) -> Option<f64> {
555    if tool != "agent" && tool != "opencode" {
556        return None;
557    }
558
559    usage
560        .and_then(|value| value.get("totalCost").or_else(|| value.get("totalCostUSD")))
561        .and_then(Value::as_f64)
562}
563
564/// Build stable, caller-facing metadata from tool-specific agent output.
565pub fn build_normalized_result_metadata(options: BuildMetadataOptions<'_>) -> ResultMetadata {
566    let all_messages = options.parsed_output.map_or_else(
567        || parse_json_messages(options.plain_output),
568        <[Value]>::to_vec,
569    );
570    let messages: Vec<_> = all_messages
571        .iter()
572        .filter(|event| event["parent_tool_use_id"].is_null())
573        .cloned()
574        .collect();
575    let completion = completion_state(options.tool, &messages);
576    let usage_limit = if completion == Some("completed") {
577        UsageLimit::default()
578    } else {
579        detect_usage_limit(options.plain_output)
580    };
581    let mut execution_error = detect_execution_error(
582        options.tool,
583        options.exit_code,
584        options.plain_output,
585        outcome_messages(options.tool, &messages),
586    );
587    if !execution_error.has_error && completion == Some("incomplete") {
588        execution_error = ExecutionError {
589            has_error: true,
590            error_type: Some("incomplete_stream".into()),
591            message: Some("Process exited before the native completion event".into()),
592        };
593    }
594    let session_id = extract_session_id(options.session_id, &messages);
595    let public_pricing_estimate = public_pricing_estimate(options.tool, options.usage.as_ref());
596    let pricing_info = public_pricing_estimate.map(|total_cost_usd| PricingInfo {
597        total_cost_usd,
598        source: format!("{}-stream-usage", options.tool),
599    });
600
601    ResultMetadata {
602        tool: options.tool.to_string(),
603        exit_code: options.exit_code,
604        success: options.exit_code == 0 && !usage_limit.reached && !execution_error.has_error,
605        session_id,
606        limit_reached: usage_limit.reached,
607        limit_reset_time: usage_limit.reset_time,
608        limit_timezone: usage_limit.timezone,
609        anthropic_total_cost_usd: first_number(
610            &messages,
611            &["total_cost_usd", "totalCostUsd", "anthropicTotalCostUSD"],
612        ),
613        public_pricing_estimate,
614        pricing_info,
615        result_summary: extract_result_summary(&messages, options.plain_output),
616        result_model_usage: extract_result_model_usage(&messages),
617        stream_token_usage: options.usage,
618        sub_agent_calls: extract_sub_agent_calls(&all_messages),
619        error_during_execution: execution_error.has_error,
620        error_type: execution_error.error_type,
621        error_message: execution_error.message,
622    }
623}
624
625#[cfg(test)]
626mod tests {
627    use super::{build_normalized_result_metadata, BuildMetadataOptions};
628    use serde_json::json;
629
630    #[test]
631    fn normalizes_codex_thread_id_and_usage() {
632        let usage = json!({
633            "inputTokens": 12,
634            "outputTokens": 4,
635        });
636        let metadata = build_normalized_result_metadata(BuildMetadataOptions {
637            tool: "codex",
638            exit_code: 0,
639            plain_output:
640                "{\"type\":\"session\",\"thread_id\":\"thread-123\"}\n{\"type\":\"message\",\"content\":\"Done.\"}",
641            parsed_output: None,
642            session_id: None,
643            usage: Some(usage.clone()),
644        });
645
646        assert_eq!(metadata.tool, "codex");
647        assert!(metadata.success);
648        assert_eq!(metadata.session_id, Some("thread-123".to_string()));
649        assert_eq!(metadata.result_summary, Some("Done.".to_string()));
650        assert_eq!(metadata.stream_token_usage, Some(usage));
651    }
652
653    #[test]
654    fn exposes_agent_pricing_and_sub_agent_calls() {
655        let messages = vec![
656            json!({
657                "type": "collab_tool_call",
658                "id": "call-1",
659                "name": "worker",
660                "status": "completed",
661                "summary": "Worker finished."
662            }),
663            json!({
664                "type": "message",
665                "text": "Final summary."
666            }),
667        ];
668        let usage = json!({
669            "inputTokens": 100,
670            "outputTokens": 40,
671            "totalCost": 0.004,
672            "stepCount": 1
673        });
674        let metadata = build_normalized_result_metadata(BuildMetadataOptions {
675            tool: "agent",
676            exit_code: 0,
677            plain_output: "",
678            parsed_output: Some(&messages),
679            session_id: None,
680            usage: Some(usage.clone()),
681        });
682
683        assert_eq!(metadata.tool, "agent");
684        assert!(metadata.success);
685        assert_eq!(metadata.public_pricing_estimate, Some(0.004));
686        assert_eq!(
687            metadata
688                .pricing_info
689                .as_ref()
690                .map(|pricing| pricing.source.as_str()),
691            Some("agent-stream-usage")
692        );
693        assert_eq!(metadata.result_summary, Some("Final summary.".to_string()));
694        let sub_agent_calls = metadata.sub_agent_calls.unwrap();
695        assert_eq!(sub_agent_calls.len(), 1);
696        assert_eq!(sub_agent_calls[0].get("id"), Some(&json!("call-1")));
697    }
698}