canact 0.1.0

Probe an LLM and return host policy: max tools, edit format, XML fallback, JSON repair
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
//! Individual capability probes.
//!
//! Each probe sends a single lightweight request to the LLM and scores the
//! response along one capability dimension.

mod code_syntax;
mod context_faithfulness;
mod context_ladder;
mod edit_format;
mod json_output;
mod max_tokens_compliance;
mod multi_turn_memory;
mod multi_turn_task_sequencing;
mod one_shot_tool_plan;
mod parallel_tool_scale;
mod streaming_tool_calls;
mod system_message_adherence;
mod token_efficiency;
mod tool_calling;
mod vision;
mod xml_fallback;

pub use code_syntax::probe_code_syntax;
pub use context_faithfulness::probe_context_faithfulness;
pub use context_ladder::{ContextLadder, probe_effective_context_tokens};
pub use edit_format::{probe_search_replace, probe_unified_diff};
pub use json_output::{probe_instruction_following, probe_json_output};
pub use max_tokens_compliance::probe_max_tokens_compliance;
pub use multi_turn_memory::probe_multi_turn_memory;
pub use multi_turn_task_sequencing::probe_multi_turn_task_sequencing;
pub use one_shot_tool_plan::probe_one_shot_tool_plan;
pub use parallel_tool_scale::probe_parallel_tool_scale;
pub use streaming_tool_calls::probe_streaming_tool_calls;
pub use system_message_adherence::probe_system_message_adherence;
pub use token_efficiency::probe_token_efficiency;
pub use tool_calling::{
    probe_complex_tool_calling, probe_nested_arguments, probe_tool_calling, probe_tool_selection,
};
pub use vision::probe_vision;
pub use xml_fallback::probe_xml_tool_calling;

use crate::client::{
    ProbeContent, ProbeFinish, ProbeMessage, ProbeResponse, ProbeRole, ProbeTool, ProbeToolCall,
};
use crate::error::ProbeError;

pub(crate) fn user_text(text: impl Into<String>) -> ProbeMessage {
    ProbeMessage {
        role: ProbeRole::User,
        content: ProbeContent::Text(text.into()),
        tool_calls: None,
        tool_call_id: None,
    }
}

pub(crate) fn system_text(text: impl Into<String>) -> ProbeMessage {
    ProbeMessage {
        role: ProbeRole::System,
        content: ProbeContent::Text(text.into()),
        tool_calls: None,
        tool_call_id: None,
    }
}

pub(crate) fn assistant_text(text: impl Into<String>) -> ProbeMessage {
    ProbeMessage {
        role: ProbeRole::Assistant,
        content: ProbeContent::Text(text.into()),
        tool_calls: None,
        tool_call_id: None,
    }
}

pub(crate) fn assistant_tool_calls(
    text: impl Into<String>,
    tool_calls: Vec<ProbeToolCall>,
) -> ProbeMessage {
    ProbeMessage {
        role: ProbeRole::Assistant,
        content: ProbeContent::Text(text.into()),
        tool_calls: Some(tool_calls),
        tool_call_id: None,
    }
}

pub(crate) fn tool_result(
    tool_call_id: impl Into<String>,
    text: impl Into<String>,
) -> ProbeMessage {
    ProbeMessage {
        role: ProbeRole::Tool,
        content: ProbeContent::Text(text.into()),
        tool_calls: None,
        tool_call_id: Some(tool_call_id.into()),
    }
}

/// Try to isolate a JSON value from text that may be wrapped in markdown
/// fences or surrounded by prose. An array is kept only when it wraps
/// the object (`[{...}]`), not when citation `[1]` precedes an object.
pub(crate) fn extract_json_from_text(text: &str) -> &str {
    let trimmed = text.trim();

    if let Some(body) = fenced_json_body(trimmed) {
        return body;
    }

    let object = match (trimmed.find('{'), trimmed.rfind('}')) {
        (Some(start), Some(end)) if end > start => Some((start, end)),
        _ => None,
    };
    let array = match (trimmed.find('['), trimmed.rfind(']')) {
        (Some(start), Some(end)) if end > start => Some((start, end)),
        _ => None,
    };
    match (object, array) {
        (Some((os, oe)), Some((as_, ae))) if as_ < os && ae >= oe => {
            return &trimmed[as_..=ae];
        }
        (Some((start, end)), _) => return &trimmed[start..=end],
        (None, Some((start, end))) => return &trimmed[start..=end],
        _ => {}
    }

    trimmed
}

fn fenced_json_body(trimmed: &str) -> Option<&str> {
    let start = trimmed.find("```")?;
    let after = &trimmed[start + 3..];
    let (inner, _) = after.split_once("```")?;
    let inner = inner.trim_start_matches('\r');
    let body = if let Some((first, rest)) = inner.split_once('\n') {
        let tag = first.trim().trim_end_matches('\r');
        if is_fence_language_tag(tag) {
            rest
        } else {
            inner
        }
    } else {
        inner
    };
    let body = body.trim();
    if body.starts_with('{') || body.starts_with('[') {
        Some(body)
    } else {
        None
    }
}

fn is_fence_language_tag(tag: &str) -> bool {
    !tag.is_empty()
        && tag
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '_'))
}

/// Prefix that never splits a UTF-8 code point.
pub(crate) fn utf8_prefix(s: &str, max: usize) -> &str {
    if s.len() <= max {
        return s;
    }
    let mut end = max;
    while end > 0 && !s.is_char_boundary(end) {
        end -= 1;
    }
    &s[..end]
}

/// True when `s` has a character that is not whitespace or a format/ZWSP mark.
pub(crate) fn has_visible_arg_text(s: &str) -> bool {
    s.chars().any(|c| {
        !c.is_whitespace()
            && !matches!(
                c,
                '\u{200B}' | '\u{200C}' | '\u{200D}' | '\u{2060}' | '\u{FEFF}'
            )
    })
}

/// True when `key` is a string with at least one non-whitespace character.
pub(crate) fn nonempty_string_arg(
    args: &serde_json::Map<String, serde_json::Value>,
    key: &str,
) -> bool {
    args.get(key)
        .and_then(|v| v.as_str())
        .is_some_and(has_visible_arg_text)
}

/// True when any of `keys` is a nonempty string (old_text / old_string aliases).
pub(crate) fn nonempty_string_arg_any(
    args: &serde_json::Map<String, serde_json::Value>,
    keys: &[&str],
) -> bool {
    keys.iter().any(|key| nonempty_string_arg(args, key))
}

pub(crate) fn tool(name: &str, description: &str, parameters: serde_json::Value) -> ProbeTool {
    ProbeTool {
        name: name.to_string(),
        description: description.to_string(),
        parameters,
    }
}

/// Length with no tool call is a short budget, not a 30-day Weak card.
pub fn refuse_truncated_tool_call(resp: &ProbeResponse) -> Result<(), ProbeError> {
    if resp.finish == ProbeFinish::Length && resp.tool_calls.is_empty() {
        Err(ProbeError::Transient(
            "response truncated before a tool call".into(),
        ))
    } else {
        Ok(())
    }
}

/// Length plus a score below Strong is a truncated half-call, not a 30-day Medium.
pub fn refuse_truncated_incomplete(finish: ProbeFinish, score: f32) -> Result<(), ProbeError> {
    if finish == ProbeFinish::Length && score < 1.0 {
        Err(ProbeError::Transient(
            "response truncated before a complete tool call".into(),
        ))
    } else {
        Ok(())
    }
}

#[cfg(test)]
pub(crate) mod test_support {
    use std::collections::VecDeque;
    use std::future::Future;
    use std::sync::Mutex;

    use crate::client::{
        ProbeClient, ProbeContent, ProbeContentPart, ProbeFinish, ProbeRequest, ProbeResponse,
        ProbeRole, ProbeStreamChunk, ProbeToolCall,
    };
    use crate::error::ProbeError;
    use futures::Stream;

    pub(crate) struct MockLlm {
        pub(crate) response: ProbeResponse,
    }

    impl ProbeClient for MockLlm {
        fn chat(
            &self,
            _req: ProbeRequest,
        ) -> impl Future<Output = Result<ProbeResponse, ProbeError>> + Send {
            let resp = self.response.clone();
            async move { Ok(resp) }
        }

        fn stream_chat(
            &self,
            _req: ProbeRequest,
        ) -> impl Stream<Item = Result<ProbeStreamChunk, ProbeError>> + Send {
            futures::stream::empty()
        }

        fn model_id(&self) -> &str {
            "test-model"
        }

        fn provider(&self) -> &str {
            "test-provider"
        }
    }

    pub(crate) struct SequentialMock {
        responses: Mutex<VecDeque<ProbeResponse>>,
    }

    impl SequentialMock {
        pub(crate) fn new(responses: Vec<ProbeResponse>) -> Self {
            Self {
                responses: Mutex::new(VecDeque::from(responses)),
            }
        }
    }

    impl ProbeClient for SequentialMock {
        fn chat(
            &self,
            _req: ProbeRequest,
        ) -> impl Future<Output = Result<ProbeResponse, ProbeError>> + Send {
            let next = self
                .responses
                .lock()
                .expect("sequential mock lock")
                .pop_front()
                .unwrap_or_else(|| text_response("done"));
            async move { Ok(next) }
        }

        fn stream_chat(
            &self,
            _req: ProbeRequest,
        ) -> impl Stream<Item = Result<ProbeStreamChunk, ProbeError>> + Send {
            futures::stream::empty()
        }

        fn model_id(&self) -> &str {
            "test-model"
        }

        fn provider(&self) -> &str {
            "test-provider"
        }
    }

    pub(crate) fn tool_call_response() -> ProbeResponse {
        ProbeResponse {
            text: String::new(),
            tool_calls: vec![ProbeToolCall {
                id: "call_1".into(),
                name: "read_file".into(),
                arguments: serde_json::json!({"path": "/tmp/test.txt"})
                    .as_object()
                    .unwrap()
                    .clone(),
            }],
            finish: ProbeFinish::ToolCalls,
            usage: None,
        }
    }

    pub(crate) fn text_response(text: &str) -> ProbeResponse {
        ProbeResponse {
            text: text.to_string(),
            tool_calls: Vec::new(),
            finish: ProbeFinish::Stop,
            usage: None,
        }
    }

    pub(crate) fn length_text_response(text: &str) -> ProbeResponse {
        ProbeResponse {
            text: text.to_string(),
            tool_calls: Vec::new(),
            finish: ProbeFinish::Length,
            usage: None,
        }
    }

    pub(crate) fn multi_tool_call_response(calls: Vec<ProbeToolCall>) -> ProbeResponse {
        ProbeResponse {
            text: String::new(),
            tool_calls: calls,
            finish: ProbeFinish::ToolCalls,
            usage: None,
        }
    }

    pub(crate) struct RecordingMock {
        inner: MockLlm,
        pub(crate) requests: Mutex<Vec<ProbeRequest>>,
    }

    impl RecordingMock {
        pub(crate) fn new(response: ProbeResponse) -> Self {
            Self {
                inner: MockLlm { response },
                requests: Mutex::new(Vec::new()),
            }
        }
    }

    impl ProbeClient for RecordingMock {
        fn chat(
            &self,
            req: ProbeRequest,
        ) -> impl Future<Output = Result<ProbeResponse, ProbeError>> + Send {
            self.requests.lock().expect("lock").push(req.clone());
            self.inner.chat(req)
        }

        fn stream_chat(
            &self,
            req: ProbeRequest,
        ) -> impl Stream<Item = Result<ProbeStreamChunk, ProbeError>> + Send {
            self.requests.lock().expect("lock").push(req.clone());
            self.inner.stream_chat(req)
        }

        fn model_id(&self) -> &str {
            self.inner.model_id()
        }

        fn provider(&self) -> &str {
            self.inner.provider()
        }
    }

    pub(crate) fn request_user_text(req: &ProbeRequest) -> String {
        let mut out = String::new();
        for message in &req.messages {
            if message.role != ProbeRole::User {
                continue;
            }
            match &message.content {
                ProbeContent::Text(text) => out.push_str(text),
                ProbeContent::Parts(parts) => {
                    for part in parts {
                        if let ProbeContentPart::Text { text } = part {
                            out.push_str(text);
                        }
                    }
                }
            }
        }
        out
    }
}

#[cfg(test)]
mod nonempty_string_arg_tests {
    use super::nonempty_string_arg;

    fn args(value: serde_json::Value) -> serde_json::Map<String, serde_json::Value> {
        value.as_object().unwrap().clone()
    }

    #[test]
    fn nonempty_string_arg_rejects_empty_and_whitespace() {
        assert!(!nonempty_string_arg(
            &args(serde_json::json!({"path": ""})),
            "path"
        ));
        assert!(!nonempty_string_arg(
            &args(serde_json::json!({"path": " "})),
            "path"
        ));
        assert!(!nonempty_string_arg(
            &args(serde_json::json!({"path": "\n"})),
            "path"
        ));
        assert!(!nonempty_string_arg(
            &args(serde_json::json!({"path": 1})),
            "path"
        ));
        assert!(!nonempty_string_arg(&args(serde_json::json!({})), "path"));
        assert!(!nonempty_string_arg(
            &args(serde_json::json!({"path": "\u{200b}"})),
            "path"
        ));
        assert!(nonempty_string_arg(
            &args(serde_json::json!({"path": "/tmp/a"})),
            "path"
        ));
    }
}

#[cfg(test)]
mod extract_json_tests {
    use super::extract_json_from_text;

    #[test]
    fn extract_json_from_bare_object() {
        assert_eq!(extract_json_from_text(r#"  {"a": 1}  "#), r#"{"a": 1}"#);
    }

    #[test]
    fn extract_json_from_fenced_block() {
        let input = "```json\n{\"a\": 1}\n```";
        assert_eq!(extract_json_from_text(input), "{\"a\": 1}");
    }

    #[test]
    fn extract_json_from_uppercase_json_fence() {
        let input = "```JSON\n{\"a\": 1}\n```";
        assert_eq!(extract_json_from_text(input), "{\"a\": 1}");
    }

    #[test]
    fn extract_json_from_jsonc_fence_falls_through_to_object() {
        let input = "```jsonc\n{\"a\": 1}\n```";
        assert_eq!(extract_json_from_text(input), "{\"a\": 1}");
    }

    #[test]
    fn extract_json_does_not_peel_array_wrapper() {
        let input = r#"[{"word": "hello", "length": 5, "reversed": "olleh"}]"#;
        assert_eq!(extract_json_from_text(input), input);
    }

    #[test]
    fn extract_json_keeps_array_when_prose_wraps_it() {
        let input = r#"Here: [{"word": "hello", "length": 5, "reversed": "olleh"}]"#;
        assert_eq!(
            extract_json_from_text(input),
            r#"[{"word": "hello", "length": 5, "reversed": "olleh"}]"#
        );
    }

    #[test]
    fn extract_json_keeps_object_after_citation_brackets() {
        let input = r#"See [1] {"word": "hello", "length": 5, "reversed": "olleh"}"#;
        assert_eq!(
            extract_json_from_text(input),
            r#"{"word": "hello", "length": 5, "reversed": "olleh"}"#
        );
    }

    #[test]
    fn extract_json_unclosed_bracket_still_takes_object() {
        let input = r#"[unclosed {"word": "hello", "length": 5, "reversed": "olleh"}"#;
        assert_eq!(
            extract_json_from_text(input),
            r#"{"word": "hello", "length": 5, "reversed": "olleh"}"#
        );
    }
}

#[cfg(test)]
mod refuse_truncated_tests {
    use super::test_support::{text_response, tool_call_response};
    use super::{refuse_truncated_incomplete, refuse_truncated_tool_call};
    use crate::client::{ProbeFinish, ProbeResponse};
    use crate::error::ProbeError;

    #[test]
    fn refuse_truncated_tool_call_errors_on_length_without_tools() {
        let resp = ProbeResponse {
            text: "leftover reasoning".into(),
            tool_calls: Vec::new(),
            finish: ProbeFinish::Length,
            usage: None,
        };
        let err = refuse_truncated_tool_call(&resp).expect_err("must refuse");
        assert!(
            matches!(&err, ProbeError::Transient(msg) if msg.contains("truncated")),
            "{err:?}"
        );
    }

    #[test]
    fn refuse_truncated_tool_call_allows_stop_without_tools() {
        let resp = text_response("I would read the file");
        assert!(refuse_truncated_tool_call(&resp).is_ok());
    }

    #[test]
    fn refuse_truncated_tool_call_allows_length_with_tools() {
        let mut resp = tool_call_response();
        resp.finish = ProbeFinish::Length;
        assert!(refuse_truncated_tool_call(&resp).is_ok());
    }

    #[test]
    fn refuse_truncated_incomplete_errors_on_length_below_strong() {
        let err = refuse_truncated_incomplete(ProbeFinish::Length, 0.5).expect_err("must refuse");
        assert!(
            matches!(&err, ProbeError::Transient(msg) if msg.contains("truncated")),
            "{err:?}"
        );
    }

    #[test]
    fn refuse_truncated_incomplete_allows_length_at_strong() {
        assert!(refuse_truncated_incomplete(ProbeFinish::Length, 1.0).is_ok());
    }

    #[test]
    fn refuse_truncated_incomplete_allows_stop_below_strong() {
        assert!(refuse_truncated_incomplete(ProbeFinish::Stop, 0.5).is_ok());
    }
}

#[cfg(test)]
mod length_policy_tests {
    use super::test_support::{MockLlm, length_text_response};
    use super::*;
    use crate::error::ProbeError;
    use crate::types::ProbeResult;

    async fn run(name: &str) -> Result<ProbeResult, ProbeError> {
        let llm = MockLlm {
            response: length_text_response("partial"),
        };
        match name {
            "code_syntax" => probe_code_syntax(&llm).await,
            "context_faithfulness" => probe_context_faithfulness(&llm).await,
            "json_output" => probe_json_output(&llm).await,
            "instruction_following" => probe_instruction_following(&llm).await,
            "search_replace" => probe_search_replace(&llm).await,
            "unified_diff" => probe_unified_diff(&llm).await,
            "max_tokens_compliance" => probe_max_tokens_compliance(&llm).await,
            "multi_turn_memory" => probe_multi_turn_memory(&llm).await,
            "multi_turn_task_sequencing" => probe_multi_turn_task_sequencing(&llm).await,
            "one_shot_tool_plan" => probe_one_shot_tool_plan(&llm).await,
            "parallel_tool_scale" => probe_parallel_tool_scale(&llm).await,
            "system_message_adherence" => probe_system_message_adherence(&llm).await,
            "token_efficiency" => probe_token_efficiency(&llm).await,
            "complex_tool_calling" => probe_complex_tool_calling(&llm).await,
            "nested_arguments" => probe_nested_arguments(&llm).await,
            "tool_calling" => probe_tool_calling(&llm).await,
            "tool_selection" => probe_tool_selection(&llm).await,
            "vision" => probe_vision(&llm).await,
            "xml_tool_calling" => probe_xml_tool_calling(&llm).await,
            other => panic!("unknown probe {other}"),
        }
    }

    #[tokio::test]
    async fn length_partial_is_refused_or_allowlisted() {
        const ALLOW: &[&str] = &["max_tokens_compliance", "token_efficiency"];
        const PROBES: &[&str] = &[
            "code_syntax",
            "context_faithfulness",
            "json_output",
            "instruction_following",
            "search_replace",
            "unified_diff",
            "max_tokens_compliance",
            "multi_turn_memory",
            "multi_turn_task_sequencing",
            "one_shot_tool_plan",
            "parallel_tool_scale",
            "system_message_adherence",
            "token_efficiency",
            "complex_tool_calling",
            "nested_arguments",
            "tool_calling",
            "tool_selection",
            "vision",
            "xml_tool_calling",
        ];
        for name in PROBES {
            match run(name).await {
                Ok(pr) => {
                    assert!(
                        ALLOW.contains(name),
                        "{name} scored {} on Length partial; must refuse or be allow-listed",
                        pr.score
                    );
                }
                Err(ProbeError::Transient(msg)) => {
                    assert!(msg.contains("truncated"), "{name}: {msg}");
                    assert!(
                        !ALLOW.contains(name),
                        "{name} is allow-listed but refused: {msg}"
                    );
                }
                Err(other) => panic!("{name}: unexpected error {other:?}"),
            }
        }
    }
}