argentor-builtins 1.4.7

50+ built-in skills (web search, crypto, file ops, security, data processing) for Argentor
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
//! Excel (XLSX) spreadsheet loader skill.
//!
//! XLSX is a ZIP of XML parts. This loader reads:
//! - `xl/workbook.xml` to list sheets
//! - `xl/sharedStrings.xml` for interned strings
//! - `xl/worksheets/sheetN.xml` for cells
//!
//! Supports listing sheets, reading a sheet as rows/cells, querying a single
//! cell, row counting, and simple CSV/JSON conversion. Formulas are not
//! evaluated — the cached value (if present) is returned.

use argentor_core::{ArgentorResult, ToolCall, ToolResult};
use argentor_skills::skill::{Skill, SkillDescriptor};
use async_trait::async_trait;
use base64::Engine;
use regex::Regex;
use serde_json::{json, Value};

use crate::zip_reader::{read_central_directory, read_entry_utf8, ZipEntry};
use std::collections::HashMap;

/// Excel XLSX spreadsheet loader.
pub struct ExcelLoaderSkill {
    descriptor: SkillDescriptor,
}

impl ExcelLoaderSkill {
    /// Create a new Excel loader skill.
    pub fn new() -> Self {
        Self {
            descriptor: SkillDescriptor {
                name: "excel_loader".to_string(),
                description: "XLSX loader: list_sheets, read_sheet, get_cell, count_rows, to_csv, to_json. Accepts base64-encoded XLSX bytes.".to_string(),
                parameters_schema: json!({
                    "type": "object",
                    "properties": {
                        "operation": {
                            "type": "string",
                            "enum": ["list_sheets", "read_sheet", "get_cell", "count_rows", "to_csv", "to_json"],
                            "description": "The XLSX operation to perform"
                        },
                        "data": {
                            "type": "string",
                            "description": "Base64-encoded XLSX bytes"
                        },
                        "sheet": {
                            "type": "string",
                            "description": "Sheet name (for read_sheet/get_cell/count_rows/to_csv/to_json)"
                        },
                        "cell": {
                            "type": "string",
                            "description": "Cell reference like 'A1' for get_cell"
                        }
                    },
                    "required": ["operation", "data"]
                }),
                required_capabilities: vec![],
                requires_approval: false,
            },
        }
    }
}

impl Default for ExcelLoaderSkill {
    fn default() -> Self {
        Self::new()
    }
}

/// Parsed workbook state.
struct Workbook {
    /// Sheet name -> sheetN.xml path (relative to xl/ directory).
    sheets: Vec<(String, String)>,
    /// Shared strings by index.
    shared_strings: Vec<String>,
    /// Raw archive bytes for lazy reads.
    bytes: Vec<u8>,
    /// Central directory entries.
    entries: HashMap<String, ZipEntry>,
}

impl Workbook {
    fn load(data: &str) -> Result<Self, String> {
        let bytes = base64::engine::general_purpose::STANDARD
            .decode(data)
            .map_err(|e| format!("Invalid base64: {e}"))?;
        let entries = read_central_directory(&bytes)?;

        // Workbook sheets list
        let wb_entry = entries
            .get("xl/workbook.xml")
            .ok_or_else(|| "Missing xl/workbook.xml".to_string())?;
        let wb_xml = read_entry_utf8(&bytes, wb_entry)?;
        let sheets = parse_workbook_sheets(&wb_xml);

        // Shared strings (optional)
        let shared_strings = if let Some(e) = entries.get("xl/sharedStrings.xml") {
            let xml = read_entry_utf8(&bytes, e).unwrap_or_default();
            parse_shared_strings(&xml)
        } else {
            Vec::new()
        };

        Ok(Self {
            sheets,
            shared_strings,
            bytes,
            entries,
        })
    }

    /// Read a sheet's cell grid. Returns rows as vectors of strings.
    fn read_sheet(&self, sheet_name: &str) -> Result<Vec<Vec<String>>, String> {
        let sheet_idx = self
            .sheets
            .iter()
            .position(|(n, _)| n == sheet_name)
            .ok_or_else(|| format!("Sheet '{sheet_name}' not found"))?;
        let path = format!("xl/worksheets/sheet{}.xml", sheet_idx + 1);
        let entry = self
            .entries
            .get(&path)
            .ok_or_else(|| format!("Worksheet file '{path}' missing from archive"))?;
        let xml = read_entry_utf8(&self.bytes, entry)?;
        Ok(parse_sheet_xml(&xml, &self.shared_strings))
    }
}

/// Parse `<sheet name="..." ... />` entries from workbook.xml.
fn parse_workbook_sheets(xml: &str) -> Vec<(String, String)> {
    let mut sheets = Vec::new();
    if let Ok(re) = Regex::new(r#"(?is)<sheet\s[^>]*name=["']([^"']+)["'][^/>]*/?>"#) {
        for c in re.captures_iter(xml) {
            if let Some(m) = c.get(1) {
                let name = m.as_str().to_string();
                sheets.push((name.clone(), name));
            }
        }
    }
    sheets
}

/// Parse `xl/sharedStrings.xml` into a vector indexed by shared-string id.
fn parse_shared_strings(xml: &str) -> Vec<String> {
    let mut strings = Vec::new();
    // Match <si>...</si> blocks
    if let Ok(si_re) = Regex::new(r"(?is)<si[^>]*>(.*?)</si>") {
        if let Ok(t_re) = Regex::new(r"(?is)<t(?:\s[^>]*)?>(.*?)</t>") {
            for si in si_re.captures_iter(xml) {
                if let Some(inner) = si.get(1) {
                    let mut combined = String::new();
                    for t in t_re.captures_iter(inner.as_str()) {
                        if let Some(m) = t.get(1) {
                            combined.push_str(&decode_xml_entities(m.as_str()));
                        }
                    }
                    strings.push(combined);
                }
            }
        }
    }
    strings
}

/// Parse a single sheetN.xml into a grid of cell values as strings.
fn parse_sheet_xml(xml: &str, shared_strings: &[String]) -> Vec<Vec<String>> {
    let mut rows: Vec<Vec<String>> = Vec::new();
    let row_re = match Regex::new(r"(?is)<row[^>]*>(.*?)</row>") {
        Ok(r) => r,
        Err(_) => return rows,
    };
    // Match each cell as a tag + content. Parse attributes manually from tag.
    let cell_re = match Regex::new(r"(?is)<c(\s[^>]*)?>(.*?)</c>") {
        Ok(r) => r,
        Err(_) => return rows,
    };
    let r_attr_re = Regex::new(r#"(?is)r=["']([A-Z]+)(\d+)["']"#);
    let t_attr_re = Regex::new(r#"(?is)\st=["']([^"']+)["']"#);
    let value_re = Regex::new(r"(?is)<v>(.*?)</v>");
    let is_text_re = Regex::new(r"(?is)<is><t(?:\s[^>]*)?>(.*?)</t></is>");

    for row_cap in row_re.captures_iter(xml) {
        let row_inner = match row_cap.get(1) {
            Some(x) => x.as_str(),
            None => continue,
        };

        let mut cells: Vec<(usize, String)> = Vec::new();
        let mut max_col: usize = 0;
        for c in cell_re.captures_iter(row_inner) {
            let attrs = c.get(1).map_or("", |m| m.as_str());
            let inner = c.get(2).map_or("", |m| m.as_str());

            let (col_letters, _row_num) = if let Ok(ref re) = r_attr_re {
                re.captures(attrs)
                    .map(|cap| {
                        (
                            cap.get(1)
                                .map_or("A".to_string(), |m| m.as_str().to_string()),
                            cap.get(2)
                                .map_or("1".to_string(), |m| m.as_str().to_string()),
                        )
                    })
                    .unwrap_or(("A".to_string(), "1".to_string()))
            } else {
                ("A".to_string(), "1".to_string())
            };
            let col_idx = column_letters_to_index(&col_letters);
            let t_type = if let Ok(ref re) = t_attr_re {
                re.captures(attrs)
                    .and_then(|cap| cap.get(1).map(|m| m.as_str().to_string()))
                    .unwrap_or_default()
            } else {
                String::new()
            };
            let t_type = t_type.as_str();

            let raw_value = if let Ok(ref re) = value_re {
                re.captures(inner)
                    .and_then(|cap| cap.get(1).map(|m| m.as_str().to_string()))
                    .unwrap_or_default()
            } else {
                String::new()
            };

            let value = match t_type {
                "s" => {
                    // Shared string: raw_value is the index
                    raw_value
                        .parse::<usize>()
                        .ok()
                        .and_then(|idx| shared_strings.get(idx).cloned())
                        .unwrap_or(raw_value)
                }
                "inlineStr" => {
                    if let Ok(ref re) = is_text_re {
                        re.captures(inner)
                            .and_then(|cap| cap.get(1).map(|m| decode_xml_entities(m.as_str())))
                            .unwrap_or(raw_value)
                    } else {
                        raw_value
                    }
                }
                _ => decode_xml_entities(&raw_value),
            };

            cells.push((col_idx, value));
            if col_idx > max_col {
                max_col = col_idx;
            }
        }

        let mut row = vec![String::new(); max_col + 1];
        for (idx, val) in cells {
            if idx < row.len() {
                row[idx] = val;
            }
        }
        rows.push(row);
    }

    rows
}

/// Convert Excel column letters (A, Z, AA, AB, ...) to a 0-indexed column.
fn column_letters_to_index(letters: &str) -> usize {
    let mut idx: usize = 0;
    for c in letters.chars() {
        if c.is_ascii_alphabetic() {
            idx = idx * 26 + (c.to_ascii_uppercase() as usize - 'A' as usize + 1);
        }
    }
    idx.saturating_sub(1)
}

/// Decode basic XML entities.
fn decode_xml_entities(s: &str) -> String {
    s.replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&quot;", "\"")
        .replace("&apos;", "'")
        .replace("&amp;", "&")
}

/// Parse a cell reference like "B3" into (col_idx, row_number_1indexed).
fn parse_cell_ref(cell: &str) -> Option<(usize, usize)> {
    let letters: String = cell.chars().take_while(char::is_ascii_alphabetic).collect();
    let digits: String = cell.chars().skip_while(char::is_ascii_alphabetic).collect();
    if letters.is_empty() || digits.is_empty() {
        return None;
    }
    let col = column_letters_to_index(&letters);
    let row: usize = digits.parse().ok()?;
    Some((col, row))
}

#[async_trait]
impl Skill for ExcelLoaderSkill {
    fn descriptor(&self) -> &SkillDescriptor {
        &self.descriptor
    }

    async fn execute(&self, call: ToolCall) -> ArgentorResult<ToolResult> {
        let operation = match call.arguments["operation"].as_str() {
            Some(op) => op,
            None => {
                return Ok(ToolResult::error(
                    &call.id,
                    "Missing required parameter: 'operation'",
                ))
            }
        };
        let data = match call.arguments["data"].as_str() {
            Some(d) => d,
            None => {
                return Ok(ToolResult::error(
                    &call.id,
                    "Missing required parameter: 'data'",
                ))
            }
        };

        let wb = match Workbook::load(data) {
            Ok(w) => w,
            Err(e) => return Ok(ToolResult::error(&call.id, e)),
        };

        match operation {
            "list_sheets" => {
                let names: Vec<&str> = wb.sheets.iter().map(|(n, _)| n.as_str()).collect();
                Ok(ToolResult::success(
                    &call.id,
                    json!({
                        "sheets": names,
                        "count": names.len(),
                    })
                    .to_string(),
                ))
            }
            "read_sheet" => {
                let sheet = match call.arguments["sheet"].as_str() {
                    Some(s) => s,
                    None => return Ok(ToolResult::error(&call.id, "Missing 'sheet'")),
                };
                match wb.read_sheet(sheet) {
                    Ok(rows) => Ok(ToolResult::success(
                        &call.id,
                        json!({
                            "rows": rows,
                            "row_count": rows.len(),
                        })
                        .to_string(),
                    )),
                    Err(e) => Ok(ToolResult::error(&call.id, e)),
                }
            }
            "count_rows" => {
                let sheet = match call.arguments["sheet"].as_str() {
                    Some(s) => s,
                    None => return Ok(ToolResult::error(&call.id, "Missing 'sheet'")),
                };
                match wb.read_sheet(sheet) {
                    Ok(rows) => Ok(ToolResult::success(
                        &call.id,
                        json!({ "rows": rows.len() }).to_string(),
                    )),
                    Err(e) => Ok(ToolResult::error(&call.id, e)),
                }
            }
            "get_cell" => {
                let sheet = match call.arguments["sheet"].as_str() {
                    Some(s) => s,
                    None => return Ok(ToolResult::error(&call.id, "Missing 'sheet'")),
                };
                let cell = match call.arguments["cell"].as_str() {
                    Some(c) => c,
                    None => return Ok(ToolResult::error(&call.id, "Missing 'cell'")),
                };
                let (col, row_1) = match parse_cell_ref(cell) {
                    Some(v) => v,
                    None => {
                        return Ok(ToolResult::error(
                            &call.id,
                            format!("Invalid cell reference: '{cell}'"),
                        ))
                    }
                };
                match wb.read_sheet(sheet) {
                    Ok(rows) => {
                        let value = rows
                            .get(row_1.saturating_sub(1))
                            .and_then(|r| r.get(col))
                            .cloned()
                            .unwrap_or_default();
                        Ok(ToolResult::success(
                            &call.id,
                            json!({
                                "cell": cell,
                                "value": value,
                                "found": !value.is_empty(),
                            })
                            .to_string(),
                        ))
                    }
                    Err(e) => Ok(ToolResult::error(&call.id, e)),
                }
            }
            "to_csv" => {
                let sheet = match call.arguments["sheet"].as_str() {
                    Some(s) => s,
                    None => return Ok(ToolResult::error(&call.id, "Missing 'sheet'")),
                };
                match wb.read_sheet(sheet) {
                    Ok(rows) => {
                        let csv: String = rows
                            .iter()
                            .map(|r| {
                                r.iter()
                                    .map(|v| {
                                        if v.contains(',') || v.contains('"') || v.contains('\n') {
                                            format!("\"{}\"", v.replace('"', "\"\""))
                                        } else {
                                            v.clone()
                                        }
                                    })
                                    .collect::<Vec<_>>()
                                    .join(",")
                            })
                            .collect::<Vec<_>>()
                            .join("\n");
                        Ok(ToolResult::success(
                            &call.id,
                            json!({ "csv": csv, "rows": rows.len() }).to_string(),
                        ))
                    }
                    Err(e) => Ok(ToolResult::error(&call.id, e)),
                }
            }
            "to_json" => {
                let sheet = match call.arguments["sheet"].as_str() {
                    Some(s) => s,
                    None => return Ok(ToolResult::error(&call.id, "Missing 'sheet'")),
                };
                match wb.read_sheet(sheet) {
                    Ok(rows) => {
                        // Treat first row as headers
                        let json_rows: Vec<Value> = if rows.len() > 1 {
                            let headers = &rows[0];
                            rows[1..]
                                .iter()
                                .map(|row| {
                                    let mut obj = serde_json::Map::new();
                                    for (i, h) in headers.iter().enumerate() {
                                        let val = row.get(i).cloned().unwrap_or_default();
                                        obj.insert(h.clone(), Value::String(val));
                                    }
                                    Value::Object(obj)
                                })
                                .collect()
                        } else {
                            Vec::new()
                        };
                        Ok(ToolResult::success(
                            &call.id,
                            json!({ "rows": json_rows, "count": json_rows.len() }).to_string(),
                        ))
                    }
                    Err(e) => Ok(ToolResult::error(&call.id, e)),
                }
            }
            _ => Ok(ToolResult::error(
                &call.id,
                format!("Unknown operation: '{operation}'. Supported: list_sheets, read_sheet, get_cell, count_rows, to_csv, to_json"),
            )),
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::zip_reader::build_stored_zip_for_tests;

    fn build_sample_xlsx() -> Vec<u8> {
        let workbook = r#"<?xml version="1.0"?>
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheets>
<sheet name="Data" sheetId="1" r:id="rId1"/>
<sheet name="Summary" sheetId="2" r:id="rId2"/>
</sheets>
</workbook>"#;

        let shared_strings = r#"<?xml version="1.0"?>
<sst count="3" uniqueCount="3">
<si><t>Name</t></si>
<si><t>Age</t></si>
<si><t>Alice</t></si>
</sst>"#;

        // Sheet1: A1=Name(s=0), B1=Age(s=1), A2=Alice(s=2), B2=30
        let sheet1 = r#"<?xml version="1.0"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetData>
<row r="1"><c r="A1" t="s"><v>0</v></c><c r="B1" t="s"><v>1</v></c></row>
<row r="2"><c r="A2" t="s"><v>2</v></c><c r="B2"><v>30</v></c></row>
</sheetData>
</worksheet>"#;

        let sheet2 = r#"<?xml version="1.0"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetData>
<row r="1"><c r="A1"><v>42</v></c></row>
</sheetData>
</worksheet>"#;

        build_stored_zip_for_tests(&[
            ("xl/workbook.xml", workbook.as_bytes()),
            ("xl/sharedStrings.xml", shared_strings.as_bytes()),
            ("xl/worksheets/sheet1.xml", sheet1.as_bytes()),
            ("xl/worksheets/sheet2.xml", sheet2.as_bytes()),
        ])
    }

    fn make_call(args: Value) -> ToolCall {
        ToolCall {
            id: "test".to_string(),
            name: "excel_loader".to_string(),
            arguments: args,
        }
    }

    #[tokio::test]
    async fn test_list_sheets() {
        let skill = ExcelLoaderSkill::new();
        let encoded = base64::engine::general_purpose::STANDARD.encode(build_sample_xlsx());
        let call = make_call(json!({"operation": "list_sheets", "data": encoded}));
        let result = skill.execute(call).await.unwrap();
        assert!(!result.is_error, "Result: {}", result.content);
        let parsed: Value = serde_json::from_str(&result.content).unwrap();
        assert_eq!(parsed["count"], 2);
        let sheets = parsed["sheets"].as_array().unwrap();
        assert_eq!(sheets[0], "Data");
        assert_eq!(sheets[1], "Summary");
    }

    #[tokio::test]
    async fn test_read_sheet() {
        let skill = ExcelLoaderSkill::new();
        let encoded = base64::engine::general_purpose::STANDARD.encode(build_sample_xlsx());
        let call = make_call(json!({"operation": "read_sheet", "data": encoded, "sheet": "Data"}));
        let result = skill.execute(call).await.unwrap();
        assert!(!result.is_error, "Result: {}", result.content);
        let parsed: Value = serde_json::from_str(&result.content).unwrap();
        assert_eq!(parsed["row_count"], 2);
        let rows = parsed["rows"].as_array().unwrap();
        assert_eq!(rows[0][0], "Name");
        assert_eq!(rows[0][1], "Age");
        assert_eq!(rows[1][0], "Alice");
        assert_eq!(rows[1][1], "30");
    }

    #[tokio::test]
    async fn test_get_cell() {
        let skill = ExcelLoaderSkill::new();
        let encoded = base64::engine::general_purpose::STANDARD.encode(build_sample_xlsx());
        let call = make_call(json!({
            "operation": "get_cell",
            "data": encoded,
            "sheet": "Data",
            "cell": "A2"
        }));
        let result = skill.execute(call).await.unwrap();
        assert!(!result.is_error);
        let parsed: Value = serde_json::from_str(&result.content).unwrap();
        assert_eq!(parsed["value"], "Alice");
        assert_eq!(parsed["found"], true);
    }

    #[tokio::test]
    async fn test_get_cell_empty() {
        let skill = ExcelLoaderSkill::new();
        let encoded = base64::engine::general_purpose::STANDARD.encode(build_sample_xlsx());
        let call = make_call(json!({
            "operation": "get_cell",
            "data": encoded,
            "sheet": "Data",
            "cell": "Z99"
        }));
        let result = skill.execute(call).await.unwrap();
        assert!(!result.is_error);
        let parsed: Value = serde_json::from_str(&result.content).unwrap();
        assert_eq!(parsed["found"], false);
    }

    #[tokio::test]
    async fn test_count_rows() {
        let skill = ExcelLoaderSkill::new();
        let encoded = base64::engine::general_purpose::STANDARD.encode(build_sample_xlsx());
        let call = make_call(json!({
            "operation": "count_rows",
            "data": encoded,
            "sheet": "Data"
        }));
        let result = skill.execute(call).await.unwrap();
        assert!(!result.is_error);
        let parsed: Value = serde_json::from_str(&result.content).unwrap();
        assert_eq!(parsed["rows"], 2);
    }

    #[tokio::test]
    async fn test_to_csv() {
        let skill = ExcelLoaderSkill::new();
        let encoded = base64::engine::general_purpose::STANDARD.encode(build_sample_xlsx());
        let call = make_call(json!({
            "operation": "to_csv",
            "data": encoded,
            "sheet": "Data"
        }));
        let result = skill.execute(call).await.unwrap();
        assert!(!result.is_error);
        let parsed: Value = serde_json::from_str(&result.content).unwrap();
        let csv = parsed["csv"].as_str().unwrap();
        assert!(csv.contains("Name,Age"));
        assert!(csv.contains("Alice,30"));
    }

    #[tokio::test]
    async fn test_to_json() {
        let skill = ExcelLoaderSkill::new();
        let encoded = base64::engine::general_purpose::STANDARD.encode(build_sample_xlsx());
        let call = make_call(json!({
            "operation": "to_json",
            "data": encoded,
            "sheet": "Data"
        }));
        let result = skill.execute(call).await.unwrap();
        assert!(!result.is_error);
        let parsed: Value = serde_json::from_str(&result.content).unwrap();
        assert_eq!(parsed["count"], 1);
        let rows = parsed["rows"].as_array().unwrap();
        assert_eq!(rows[0]["Name"], "Alice");
        assert_eq!(rows[0]["Age"], "30");
    }

    #[tokio::test]
    async fn test_sheet_not_found() {
        let skill = ExcelLoaderSkill::new();
        let encoded = base64::engine::general_purpose::STANDARD.encode(build_sample_xlsx());
        let call = make_call(json!({
            "operation": "read_sheet",
            "data": encoded,
            "sheet": "Nonexistent"
        }));
        let result = skill.execute(call).await.unwrap();
        assert!(result.is_error);
        assert!(result.content.contains("not found"));
    }

    #[tokio::test]
    async fn test_invalid_cell_reference() {
        let skill = ExcelLoaderSkill::new();
        let encoded = base64::engine::general_purpose::STANDARD.encode(build_sample_xlsx());
        let call = make_call(json!({
            "operation": "get_cell",
            "data": encoded,
            "sheet": "Data",
            "cell": "invalid!"
        }));
        let result = skill.execute(call).await.unwrap();
        assert!(result.is_error);
    }

    #[tokio::test]
    async fn test_invalid_base64() {
        let skill = ExcelLoaderSkill::new();
        let call = make_call(json!({"operation": "list_sheets", "data": "!!!"}));
        let result = skill.execute(call).await.unwrap();
        assert!(result.is_error);
    }

    #[tokio::test]
    async fn test_missing_operation() {
        let skill = ExcelLoaderSkill::new();
        let encoded = base64::engine::general_purpose::STANDARD.encode(build_sample_xlsx());
        let call = make_call(json!({"data": encoded}));
        let result = skill.execute(call).await.unwrap();
        assert!(result.is_error);
    }

    #[tokio::test]
    async fn test_missing_sheet_param() {
        let skill = ExcelLoaderSkill::new();
        let encoded = base64::engine::general_purpose::STANDARD.encode(build_sample_xlsx());
        let call = make_call(json!({"operation": "read_sheet", "data": encoded}));
        let result = skill.execute(call).await.unwrap();
        assert!(result.is_error);
    }

    #[tokio::test]
    async fn test_unknown_operation() {
        let skill = ExcelLoaderSkill::new();
        let encoded = base64::engine::general_purpose::STANDARD.encode(build_sample_xlsx());
        let call = make_call(json!({"operation": "pivot_table", "data": encoded}));
        let result = skill.execute(call).await.unwrap();
        assert!(result.is_error);
        assert!(result.content.contains("Unknown operation"));
    }

    #[test]
    fn test_column_letters_to_index() {
        assert_eq!(column_letters_to_index("A"), 0);
        assert_eq!(column_letters_to_index("B"), 1);
        assert_eq!(column_letters_to_index("Z"), 25);
        assert_eq!(column_letters_to_index("AA"), 26);
        assert_eq!(column_letters_to_index("AB"), 27);
    }

    #[test]
    fn test_parse_cell_ref() {
        assert_eq!(parse_cell_ref("A1"), Some((0, 1)));
        assert_eq!(parse_cell_ref("B3"), Some((1, 3)));
        assert_eq!(parse_cell_ref("AA100"), Some((26, 100)));
        assert_eq!(parse_cell_ref(""), None);
        assert_eq!(parse_cell_ref("A"), None);
        assert_eq!(parse_cell_ref("123"), None);
    }

    #[test]
    fn test_descriptor_name() {
        let skill = ExcelLoaderSkill::new();
        assert_eq!(skill.descriptor().name, "excel_loader");
    }
}