Skip to main content

ai_agent/utils/
content_array.rs

1//! Content array utilities
2//!
3//! Translated from openclaudecode/src/utils/contentArray.ts
4
5use serde_json::Value;
6
7/// Inserts a block into the content array after the last tool_result block.
8/// Mutates the array in place.
9///
10/// # Arguments
11/// * `content` - The content array to modify
12/// * `block` - The block to insert
13pub fn insert_block_after_tool_results(content: &mut Vec<Value>, block: Value) {
14    // Find position after the last tool_result block
15    let mut last_tool_result_index: isize = -1;
16    for (i, item) in content.iter().enumerate() {
17        if let Some(obj) = item.as_object() {
18            if let Some(type_val) = obj.get("type") {
19                if type_val == "tool_result" {
20                    last_tool_result_index = i as isize;
21                }
22            }
23        }
24    }
25
26    if last_tool_result_index >= 0 {
27        let insert_pos = (last_tool_result_index + 1) as usize;
28        content.insert(insert_pos, block);
29        // Append a text continuation if the inserted block is now last
30        if insert_pos == content.len() - 1 {
31            let text_block = serde_json::json!({
32                "type": "text",
33                "text": "."
34            });
35            content.push(text_block);
36        }
37    } else {
38        // No tool_result blocks — insert before the last block
39        let insert_index = content.len().saturating_sub(1);
40        content.insert(insert_index, block);
41    }
42}