argmend 0.4.0

Argmend repairs broken tool-call arguments into JSON.
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
//! Fence unwrap, unique truncation, and XML parameter objects.

use serde_json::Value;

use crate::{RepairError, RepairOutcome, Rewrite};

pub(crate) fn unwrap_fence(raw: &str) -> Option<String> {
    let trimmed = raw.trim();
    let rest = trimmed.strip_prefix("```")?;
    let rest = strip_fence_info(rest);
    let rest = rest.strip_prefix('\n').unwrap_or(rest);
    if let Some(end) = rest.rfind("```") {
        let tail = &rest[end + 3..];
        if tail.trim().is_empty() || tail_is_comment(tail) || suffix_is_only_prose(tail) {
            return Some(rest[..end].trim().to_string());
        }
        return None;
    }
    let body = rest.trim();
    if body.is_empty() {
        None
    } else {
        Some(body.to_string())
    }
}

/// A comment after the closing fence is not another JSON value.
fn tail_is_comment(tail: &str) -> bool {
    let tail = tail.trim();
    if let Some(rest) = tail.strip_prefix("/*") {
        let Some(end) = rest.find("*/") else {
            return false;
        };
        return rest[end + 2..].trim().is_empty();
    }
    let Some(rest) = tail.strip_prefix("//").or_else(|| tail.strip_prefix('#')) else {
        return false;
    };
    match rest.split_once('\n') {
        None => true,
        Some((_, after)) => after.trim().is_empty(),
    }
}

/// Keep one finished object or array and drop a sentence after it.
///
/// A second JSON value, a number, or a string stays in place. Dropping
/// that tail would hide another value.
pub(crate) fn without_trailing_prose(text: &str) -> Option<String> {
    let mut stream = serde_json::Deserializer::from_str(text).into_iter::<Value>();
    let value = stream.next()?.ok()?;
    if !matches!(value, Value::Object(_) | Value::Array(_)) {
        return None;
    }
    // `[TODO] fix it` becomes `["TODO"] fix it` after bare-word quoting.
    // Those words are the text, not a sentence after a JSON value.
    if let Value::Array(items) = &value
        && items.len() == 1
        && items[0].is_string()
    {
        return None;
    }
    let offset = stream.byte_offset();
    let rest = text.get(offset..)?;
    if !suffix_is_only_prose(rest) {
        return None;
    }
    Some(text[..offset].trim_end().to_string())
}

/// `tail` is a sentence, not another JSON value.
fn suffix_is_only_prose(tail: &str) -> bool {
    let rest = tail.trim();
    if rest.is_empty()
        || rest.contains('{')
        || rest.contains('[')
        || rest.contains('}')
        || rest.contains(']')
        || rest.contains('`')
        || rest.contains(':')
    {
        return false;
    }
    let Some(first) = rest.chars().next() else {
        return false;
    };
    if first.is_ascii_digit()
        || matches!(first, '"' | '-' | '+' | ';' | ',' | ':' | '/' | '}' | ']')
    {
        return false;
    }
    let word_end = rest
        .find(|ch: char| !ch.is_ascii_alphanumeric() && ch != '_')
        .unwrap_or(rest.len());
    let word = &rest[..word_end];
    !matches!(
        word,
        "true" | "false" | "null" | "True" | "False" | "None" | "undefined" | "NaN" | "Infinity"
    )
}

fn suffix_is_only_prose_at(chars: &[char], index: usize) -> bool {
    let mut start = index;
    while start < chars.len() && chars[start].is_whitespace() {
        start += 1;
    }
    let rest: String = chars[start..].iter().collect();
    suffix_is_only_prose(&rest)
}

/// Drop a fence info string such as `json`, `jsonc`, or `json5` when it is a tag.
///
/// The tag may contain a digit. A space or tab before the tag is ignored,
/// so `json` with a leading space unwraps, and `json5foo` with a leading
/// space stays in the body.
fn strip_fence_info(rest: &str) -> &str {
    let skipped = rest.trim_start_matches([' ', '\t']);
    let end = skipped
        .char_indices()
        .find(|(_, ch)| !ch.is_ascii_alphanumeric())
        .map(|(idx, _)| idx)
        .unwrap_or(skipped.len());
    if end == 0 {
        return rest;
    }
    let tag = &skipped[..end];
    let allowed = matches!(
        tag,
        "json" | "JSON" | "jsonc" | "JSONC" | "json5" | "JSON5" | "javascript" | "js" | "JS"
    );
    if !allowed {
        return rest;
    }
    let after = &skipped[end..];
    if after.starts_with(['{', '[', ' ', '\t', '\n', '\r']) || after.is_empty() {
        after
    } else {
        rest
    }
}

pub(crate) struct Truncation {
    pub text: String,
    pub dropped_prose: bool,
}

/// Close an open `{` / `[` stack when every string is already finished.
///
/// An open string is left alone. Closing it would invent the end of a path
/// or a key. A trailing `:` or `,` is also left alone, because the value is
/// missing. A `{` or `[` that has not started a value is left alone too.
/// Closing it would invent an empty container. A closer for an outer
/// container inserts the missing inner closers first. A sentence while an
/// outer container is still open is left outside that container. A digit
/// that is the last character stays open, because the number may have
/// been cut off. Whitespace after that digit means the number ended.
pub(crate) fn close_truncated(raw: &str) -> Option<Truncation> {
    let number_already_ended = raw.trim_end().len() != raw.len();
    let trimmed = raw.trim();
    if !trimmed.starts_with('{') && !trimmed.starts_with('[') {
        return None;
    }
    let chars: Vec<char> = trimmed.chars().collect();
    let mut stack = Vec::new();
    let mut in_string = false;
    let mut escape = false;
    let mut out = String::with_capacity(trimmed.len() + 4);
    let mut last_sig = None;
    let mut inserted = false;
    let mut dropped_prose = false;
    // A space run after `]` does not change the prose decision. Rebuilding
    // the suffix on every space made a padded tool call quadratic.
    let mut prose_clear_until = 0usize;
    for (idx, &ch) in chars.iter().enumerate() {
        if idx >= prose_clear_until
            && !in_string
            && !stack.is_empty()
            && matches!(last_sig, Some('}') | Some(']'))
        {
            if suffix_is_only_prose_at(&chars, idx) {
                dropped_prose = true;
                break;
            }
            if ch.is_whitespace() {
                let mut next = idx + 1;
                while next < chars.len() && chars[next].is_whitespace() {
                    next += 1;
                }
                prose_clear_until = next;
            }
        }
        if in_string {
            out.push(ch);
            if escape {
                escape = false;
                continue;
            }
            if ch == '\\' {
                escape = true;
                continue;
            }
            if ch == '"' {
                in_string = false;
                last_sig = Some('"');
            }
            continue;
        }
        match ch {
            '"' => {
                in_string = true;
                out.push(ch);
            }
            '{' => {
                stack.push('}');
                out.push(ch);
                last_sig = Some('{');
            }
            '[' => {
                stack.push(']');
                out.push(ch);
                last_sig = Some('[');
            }
            '}' | ']' => {
                if stack.last() == Some(&ch) {
                    stack.pop();
                    out.push(ch);
                    last_sig = Some(ch);
                    continue;
                }
                if stack.contains(&ch) {
                    while stack.last().copied() != Some(ch) {
                        let Some(closer) = stack.pop() else {
                            break;
                        };
                        out.push(closer);
                        inserted = true;
                    }
                    stack.pop();
                    out.push(ch);
                    last_sig = Some(ch);
                    continue;
                }
                out.push(ch);
                last_sig = Some(ch);
            }
            other if other.is_whitespace() => out.push(other),
            other => {
                out.push(other);
                last_sig = Some(other);
            }
        }
    }
    if in_string {
        return None;
    }
    if matches!(
        last_sig,
        None | Some(':') | Some(',') | Some('{') | Some('[')
    ) {
        return None;
    }
    if last_sig.is_some_and(|ch| ch.is_ascii_digit()) && !number_already_ended {
        return None;
    }
    while let Some(closer) = stack.pop() {
        out.push(closer);
        inserted = true;
    }
    if !inserted && !dropped_prose {
        return None;
    }
    Some(Truncation {
        text: out,
        dropped_prose,
    })
}

/// One object, array, or fence after a prefix, or the inside of one
/// `<tool_call>` tag. `None` means the text already starts at that value.
/// Two of those values is ambiguous, so the caller does not pick one.
pub(crate) fn isolate_leading_value(text: &str) -> Result<Option<String>, RepairError> {
    if let Some(inner) = tool_call_body(text)? {
        return Ok(Some(inner));
    }
    let trimmed = text.trim();
    let Some(start) = leading_json_start(trimmed) else {
        return Ok(None);
    };
    if start == 0 {
        return Ok(None);
    }
    Ok(Some(trimmed[start..].to_string()))
}

fn tool_call_body(text: &str) -> Result<Option<String>, RepairError> {
    const OPEN: &str = "<tool_call>";
    const CLOSE: &str = "</tool_call>";
    let Some(first) = text.find(OPEN) else {
        return Ok(None);
    };
    if has_json_start(&text[..first]) || text[first + OPEN.len()..].contains(OPEN) {
        return Err(RepairError::Ambiguous("more than one JSON value".into()));
    }
    let rest = &text[first + OPEN.len()..];
    let Some(end) = rest.find(CLOSE) else {
        return Ok(None);
    };
    if has_json_start(&rest[end + CLOSE.len()..]) {
        return Err(RepairError::Ambiguous("more than one JSON value".into()));
    }
    Ok(Some(rest[..end].trim().to_string()))
}

fn has_json_start(text: &str) -> bool {
    text.contains('{') || text.contains('[') || text.contains("```")
}

fn leading_json_start(text: &str) -> Option<usize> {
    let brace = text.find(['{', '[']);
    let fence = text.find("```");
    match (brace, fence) {
        (Some(left), Some(right)) => Some(left.min(right)),
        (Some(left), None) => Some(left),
        (None, Some(right)) => Some(right),
        (None, None) => None,
    }
}

pub(crate) fn xml_parameters(raw: &str) -> Result<Option<(Value, Vec<Rewrite>)>, RepairError> {
    let trimmed = raw.trim();
    if !trimmed.starts_with("<parameter") {
        return Ok(None);
    }
    let mut object = serde_json::Map::new();
    let mut rewrites = Vec::new();
    let mut rest = trimmed;
    let mut found = false;
    while let Some(start) = rest.find("<parameter") {
        if !rest[..start].trim().is_empty() {
            return Err(RepairError::Unfixable(
                "trailing text after xml parameters".into(),
            ));
        }
        found = true;
        let after = &rest[start + "<parameter".len()..];
        let (name, after_name) = parameter_name(after)?;
        let Some(content_end) = after_name.find("</parameter>") else {
            return Err(RepairError::Unfixable(
                "xml parameter tag is not closed".into(),
            ));
        };
        let content = after_name[..content_end].trim();
        if object.contains_key(&name) {
            return Err(RepairError::Ambiguous(format!(
                "xml parameter '{name}' is repeated"
            )));
        }
        let (value, more) = parameter_value(content)?;
        rewrites.extend(more);
        object.insert(name, value);
        rest = &after_name[content_end + "</parameter>".len()..];
    }
    if !rest.trim().is_empty() {
        return Err(RepairError::Unfixable(
            "trailing text after xml parameters".into(),
        ));
    }
    if !found || object.is_empty() {
        return Err(RepairError::Unfixable(
            "xml parameter tag could not be read".into(),
        ));
    }
    Ok(Some((Value::Object(object), rewrites)))
}

fn parameter_name(after: &str) -> Result<(String, &str), RepairError> {
    let after = after.trim_start();
    if let Some(rest) = after.strip_prefix('=') {
        let rest = rest.trim_start();
        let end = rest
            .find('>')
            .ok_or_else(|| RepairError::Unfixable("xml parameter name is not closed".into()))?;
        let name = rest[..end].trim();
        if name.is_empty() {
            return Err(RepairError::Unfixable("xml parameter name is empty".into()));
        }
        return Ok((name.to_string(), &rest[end + 1..]));
    }
    let Some(rest) = after.strip_prefix("name=") else {
        return Err(RepairError::Unfixable("xml parameter has no name".into()));
    };
    let quote = rest
        .chars()
        .next()
        .filter(|ch| *ch == '"' || *ch == '\'')
        .ok_or_else(|| RepairError::Unfixable("xml parameter name is not quoted".into()))?;
    let rest = &rest[1..];
    // A `'` before a letter or digit stays in the name (`O'Reilly`, `L'été`).
    // Any other `'`, including `>`, whitespace, or end, closes it. `"` still
    // closes at the first quote.
    let end = if quote == '\'' {
        rest.char_indices().find_map(|(index, ch)| {
            if ch != '\'' {
                return None;
            }
            let inside = rest[index + 1..]
                .chars()
                .next()
                .is_some_and(|next| next.is_alphanumeric());
            if inside { None } else { Some(index) }
        })
    } else {
        rest.find(quote)
    }
    .ok_or_else(|| RepairError::Unfixable("xml parameter name quote is not closed".into()))?;
    let name = &rest[..end];
    if name.is_empty() {
        return Err(RepairError::Unfixable("xml parameter name is empty".into()));
    }
    let after_name = &rest[end + 1..];
    let gt = after_name
        .find('>')
        .ok_or_else(|| RepairError::Unfixable("xml parameter tag is not closed".into()))?;
    Ok((name.to_string(), &after_name[gt + 1..]))
}

fn parameter_value(content: &str) -> Result<(Value, Vec<Rewrite>), RepairError> {
    let trimmed = content.trim();
    // `{` and `[` with no body are cut-off containers. A repaired string is
    // file text: `"use strict";` must keep the quotes and the semicolon.
    // A string that was already JSON is the parsed text.
    if trimmed == "{" || trimmed == "[" {
        return Err(RepairError::Unfixable(
            "xml parameter container is truncated".into(),
        ));
    }
    match crate::repair_json(trimmed) {
        RepairOutcome::Valid(value)
            if value.is_object() || value.is_array() || value.is_string() =>
        {
            Ok((value, Vec::new()))
        }
        RepairOutcome::Ambiguous(reason) => Err(RepairError::Ambiguous(reason)),
        RepairOutcome::Repaired { value, repairs }
            if value.is_object() || (value.is_array() && !bare_bracket_word(trimmed)) =>
        {
            Ok((value, repairs))
        }
        _ => Ok((Value::String(content.to_string()), Vec::new())),
    }
}

/// `[package]` and `[package,]` are file text. Quote repair would turn the
/// word into a one-element array. A real array already has a JSON value.
fn bare_bracket_word(trimmed: &str) -> bool {
    let Some(inner) = trimmed
        .strip_prefix('[')
        .and_then(|rest| rest.strip_suffix(']'))
    else {
        return false;
    };
    let inner = inner.trim().trim_end_matches(',').trim();
    if inner.is_empty() || matches!(inner, "true" | "false" | "null" | "True" | "False" | "None") {
        return false;
    }
    inner
        .chars()
        .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '_' | '.' | '-'))
        && inner.chars().any(|ch| ch.is_ascii_alphabetic())
}