toolnexus 0.24.0

Vendor-neutral tool layer for LLM agents: ACP agents, MCP servers, agent skills behind one Tool interface (Rust port of toolnexus).
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
//! Simple judgments (SPEC §8B "Simple judgments — ask / gate"): builders,
//! [`ask`], [`gate`], [`Policy`] and [`Tape`] over any [`Classifier`]. The wire
//! is unchanged — the builders produce exactly the `evaluate` inputs a host
//! would write by hand. Ported from `golang/judge.go`.

pub mod batteries;

use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};

use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};

use crate::classifier::{
    ChoiceQuestion, Classifier, ClassifierError, ClassifierOptions, ClassifierStyle, Decision,
    DecisionAnswer, EvalContext, NoulCriteria, NoulQuestion, Question, Questions, RecordedDecision,
    ScoreQuestion, create_classifier,
};
use crate::tool::Request;

/// One named question. Build with [`noul`] / [`choice`] / [`score`] and pass an
/// ORDERED list; a repeated name is an error.
#[derive(Debug, Clone, PartialEq)]
pub struct JudgeQuestion {
    pub name: String,
    pub question: Question,
}

/// "How likely is this true?"
pub fn noul(name: &str, instructions: &str) -> JudgeQuestion {
    JudgeQuestion {
        name: name.into(),
        question: NoulQuestion {
            instructions: instructions.into(),
            criteria: None,
        }
        .into(),
    }
}

/// [`noul`] with criteria labelling the true and false cases.
pub fn noul_with(
    name: &str,
    instructions: &str,
    when_true: &str,
    when_false: &str,
) -> JudgeQuestion {
    JudgeQuestion {
        name: name.into(),
        question: NoulQuestion {
            instructions: instructions.into(),
            criteria: Some(NoulCriteria {
                when_true: when_true.into(),
                when_false: when_false.into(),
            }),
        }
        .into(),
    }
}

/// Pick one option id; `options` maps id -> what picking it MEANS.
pub fn choice<K: Into<String>, V: Into<String>>(
    name: &str,
    instructions: &str,
    options: impl IntoIterator<Item = (K, V)>,
) -> JudgeQuestion {
    JudgeQuestion {
        name: name.into(),
        question: ChoiceQuestion {
            instructions: instructions.into(),
            criteria: options
                .into_iter()
                .map(|(k, v)| (k.into(), v.into()))
                .collect(),
        }
        .into(),
    }
}

/// Rate on ordered levels, lowest first.
pub fn score<S: Into<String>>(
    name: &str,
    instructions: &str,
    levels: impl IntoIterator<Item = S>,
) -> JudgeQuestion {
    JudgeQuestion {
        name: name.into(),
        question: ScoreQuestion {
            instructions: instructions.into(),
            criteria: levels.into_iter().map(Into::into).collect(),
        }
        .into(),
    }
}

/// The ordered list as the §8B map; a repeated name is an error naming it.
pub fn questions(qs: &[JudgeQuestion]) -> Result<Questions, ClassifierError> {
    let mut m = Questions::new();
    for q in qs {
        if m.contains_key(&q.name) {
            return Err(ClassifierError(format!(
                "duplicate question name {:?}",
                q.name
            )));
        }
        m.insert(q.name.clone(), q.question.clone());
    }
    Ok(m)
}

/// The public question -> §8B wire conversion.
pub fn question_wire(q: &Question) -> Value {
    q.wire()
}

/// `role` next to `data`'s fields at the top level; a non-object `data` goes
/// under `"data"`. The role is never copied into instructions (ADR 0035 D7).
pub fn state(role: &str, data: impl Serialize) -> Map<String, Value> {
    let mut s = match serde_json::to_value(data) {
        Ok(Value::Object(m)) => m,
        Ok(Value::Null) | Err(_) => Map::new(),
        Ok(v) => {
            let mut m = Map::new();
            m.insert("data".into(), v);
            m
        }
    };
    s.insert("role".into(), json!(role));
    s
}

/// State sugar: `{"context": ctx, "message": msg}` plus `extra`.
pub fn message_state(ctx: &str, message: &str, extra: Map<String, Value>) -> Map<String, Value> {
    let mut s = Map::new();
    s.insert("context".into(), json!(ctx));
    s.insert("message".into(), json!(message));
    s.extend(extra);
    s
}

// ---------------------------------------------------------------- bands

/// Confidence cut-points: no / uncertain / yes. EXCLUSIVE on the confident
/// side — exactly `low` or exactly `high` is uncertain.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct Bands {
    pub low: f64,
    pub high: f64,
}

/// 0.30 / 0.70.
pub const DEFAULT_BANDS: Bands = Bands {
    low: 0.30,
    high: 0.70,
};

pub const BAND_YES: &str = "yes";
pub const BAND_NO: &str = "no";
pub const BAND_UNCERTAIN: &str = "uncertain";

impl Bands {
    /// Noul: value against the cuts. Choice: yes only if confidence > high and
    /// not near-uniform. Score: yes only if confidence > high.
    pub fn band(&self, a: &DecisionAnswer) -> &'static str {
        match a {
            DecisionAnswer::Noul(x) => {
                if x.noul < self.low {
                    return BAND_NO;
                }
                if x.noul > self.high {
                    return BAND_YES;
                }
            }
            DecisionAnswer::Choice(x) => {
                if !x.near_uniform && x.confidence > self.high {
                    return BAND_YES;
                }
            }
            DecisionAnswer::Score(x) => {
                if x.confidence > self.high {
                    return BAND_YES;
                }
            }
        }
        BAND_UNCERTAIN
    }
}

/// `None` or the zero value ⇒ [`DEFAULT_BANDS`].
pub(crate) fn pick_bands(b: Option<Bands>) -> Bands {
    match b {
        Some(b) if b != Bands::default() => b,
        _ => DEFAULT_BANDS,
    }
}

/// A classifier answer plus its band (`sure` is band == yes).
#[derive(Debug, Clone, PartialEq)]
pub struct JudgeAnswer {
    pub answer: DecisionAnswer,
    pub band: String,
    pub sure: bool,
}

impl JudgeAnswer {
    /// The one number: noul probability, score value, choice confidence.
    pub fn value(&self) -> f64 {
        match &self.answer {
            DecisionAnswer::Noul(x) => x.noul,
            DecisionAnswer::Score(x) => x.score,
            DecisionAnswer::Choice(x) => x.confidence,
        }
    }

    /// The picked option id (`""` for noul/score).
    pub fn choice(&self) -> &str {
        match &self.answer {
            DecisionAnswer::Choice(x) => &x.choice,
            _ => "",
        }
    }
}

/// Serialises FLAT: the wire fields plus `type`, then `band` (noul) or `sure`.
impl Serialize for JudgeAnswer {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        let mut m = self.answer.wire();
        if matches!(self.answer, DecisionAnswer::Noul(_)) {
            m.insert("band".into(), json!(self.band));
        } else {
            m.insert("sure".into(), json!(self.sure));
        }
        m.serialize(s)
    }
}

/// Answers by question name. A question the model did not answer is absent.
pub type Answers = BTreeMap<String, JudgeAnswer>;

pub(crate) fn band_all(d: &Decision, b: Bands) -> Answers {
    d.answers
        .iter()
        .map(|(k, a)| {
            let band = b.band(a);
            (
                k.clone(),
                JudgeAnswer {
                    answer: a.clone(),
                    band: band.into(),
                    sure: band == BAND_YES,
                },
            )
        })
        .collect()
}

/// Evaluate once and band every answer (`None` ⇒ 0.30 / 0.70).
pub async fn ask(
    c: &Classifier,
    state: impl Serialize,
    qs: &[JudgeQuestion],
    bands: Option<Bands>,
) -> Result<Answers, ClassifierError> {
    ask_ctx(EvalContext::default(), c, state, qs, bands).await
}

/// [`ask`] with an [`EvalContext`] (cancellation, tape call name).
pub async fn ask_ctx(
    ctx: EvalContext,
    c: &Classifier,
    state: impl Serialize,
    qs: &[JudgeQuestion],
    bands: Option<Bands>,
) -> Result<Answers, ClassifierError> {
    let m = questions(qs)?;
    let st = serde_json::to_value(state).map_err(|e| ClassifierError(e.to_string()))?;
    let d = c.evaluate_ctx(ctx, st, &m).await?;
    Ok(band_all(&d, pick_bands(bands)))
}

// ---------------------------------------------------------------- gate

/// One gate. Exactly one of `below` / `at_least` / `is` applies.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Rule {
    pub question: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub below: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub at_least: Option<f64>,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub is: String,
    #[serde(default)]
    pub action: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub target: String,
}

/// An action fired, or escalated with a §10 `input` Request, or neither
/// (`action` "" — fall through).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Outcome {
    pub action: String,
    pub target: String,
    pub rule: Option<Rule>,
    pub answers: Answers,
    pub escalated: bool,
    pub request: Option<Request>,
}

/// Ask once and apply rules first-match. A rule whose answer is missing or
/// uncertain ESCALATES (`needs_input`) instead of deciding.
pub async fn gate(
    c: &Classifier,
    state: impl Serialize,
    qs: &[JudgeQuestion],
    rules: &[Rule],
    bands: Option<Bands>,
) -> Result<Outcome, ClassifierError> {
    let a = ask(c, state, qs, bands).await?;
    Ok(apply_rules(a, rules))
}

/// The pure half of [`gate`].
pub fn apply_rules(a: Answers, rules: &[Rule]) -> Outcome {
    apply(a, rules, false)
}

fn raw_answers(a: &Answers) -> Value {
    Value::Object(
        a.iter()
            .map(|(k, v)| (k.clone(), Value::Object(v.answer.wire())))
            .collect(),
    )
}

fn apply(a: Answers, rules: &[Rule], skip_uncertain: bool) -> Outcome {
    for (i, r) in rules.iter().enumerate() {
        if skip_uncertain
            && let Some(x) = a.get(&r.question)
            && x.band == BAND_UNCERTAIN
        {
            continue;
        }
        let (fired, reason) = check_rule(&a, r);
        if !reason.is_empty() {
            let mut data = Map::new();
            data.insert("question".into(), json!(r.question));
            data.insert("reason".into(), json!(reason));
            data.insert("answers".into(), raw_answers(&a));
            data.insert(
                "rule".into(),
                serde_json::to_value(r).unwrap_or(Value::Null),
            );
            let request = Request {
                id: format!("gate:{i}:{}", r.question),
                kind: "input".into(),
                prompt: format!(
                    "Classifier is unsure about {:?} ({reason}). Decide rule {i} ({}).",
                    r.question, r.action
                ),
                data: Some(data),
                ..Default::default()
            };
            return Outcome {
                action: "needs_input".into(),
                rule: Some(r.clone()),
                answers: a,
                escalated: true,
                request: Some(request),
                ..Default::default()
            };
        }
        if fired {
            return Outcome {
                action: r.action.clone(),
                target: r.target.clone(),
                rule: Some(r.clone()),
                answers: a,
                ..Default::default()
            };
        }
    }
    Outcome {
        answers: a,
        ..Default::default()
    }
}

/// (fired, escalate reason); a non-empty reason means ask a human.
fn check_rule(answers: &Answers, r: &Rule) -> (bool, String) {
    let Some(a) = answers.get(&r.question) else {
        return (false, format!("missing answer \"{}\"", r.question));
    };
    if a.band == BAND_UNCERTAIN {
        return (false, format!("uncertain answer \"{}\"", r.question));
    }
    match &a.answer {
        DecisionAnswer::Noul(_) | DecisionAnswer::Score(_) => {
            let v = a.value();
            if let Some(b) = r.below {
                return (v < b, String::new());
            }
            if let Some(at) = r.at_least {
                return (v >= at, String::new());
            }
        }
        DecisionAnswer::Choice(_) => {
            if !r.is.is_empty() {
                return (a.choice() == r.is, String::new());
            }
        }
    }
    (
        false,
        format!("rule does not fit {} answer", a.answer.answer_type()),
    )
}

/// [`gate`] with a DECLARED fall-through: `default` names the action when no
/// rule fires; `""` escalates with reason "no rule fired". With
/// `skip_uncertain`, an uncertain answer skips its rule instead of escalating.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Policy {
    pub rules: Vec<Rule>,
    pub default: String,
    /// `None` ⇒ [`DEFAULT_BANDS`].
    pub bands: Option<Bands>,
    pub skip_uncertain: bool,
}

impl Policy {
    /// Apply the rules, then the declared default.
    pub fn decide(&self, a: Answers) -> Outcome {
        let mut o = apply(a, &self.rules, self.skip_uncertain);
        if !o.action.is_empty() || o.escalated {
            return o;
        }
        if !self.default.is_empty() {
            o.action = self.default.clone();
            return o;
        }
        let mut data = Map::new();
        data.insert("question".into(), json!(""));
        data.insert("reason".into(), json!("no rule fired"));
        data.insert("answers".into(), raw_answers(&o.answers));
        o.escalated = true;
        o.action = "needs_input".into();
        o.request = Some(Request {
            id: "gate:default".into(),
            kind: "input".into(),
            prompt: "No rule fired: the answers are confident but in between. Decide.".into(),
            data: Some(data),
            ..Default::default()
        });
        o
    }

    /// Ask once and decide.
    pub async fn gate(
        &self,
        c: &Classifier,
        state: impl Serialize,
        qs: &[JudgeQuestion],
    ) -> Result<Outcome, ClassifierError> {
        let a = ask(c, state, qs, self.bands).await?;
        Ok(self.decide(a))
    }
}

// ---------------------------------------------------------------- static / tape

/// One static-corpus entry; `response` is the backend body as JSON.
pub fn recorded(state: impl Serialize, questions: Questions, response: &Value) -> RecordedDecision {
    RecordedDecision {
        state: serde_json::to_value(state).unwrap_or(Value::Null),
        questions,
        response: serde_json::to_vec(response).unwrap_or_default(),
    }
}

/// The one-line static classifier over recorded decisions.
pub fn static_classifier(decisions: Vec<RecordedDecision>) -> Result<Classifier, ClassifierError> {
    create_classifier(ClassifierOptions {
        style: ClassifierStyle::Static,
        decisions,
        ..Default::default()
    })
}

/// Records live decisions BY CALL NAME ([`EvalContext::call_name`]) and replays
/// them offline. A replay miss names the key.
#[derive(Debug, Default)]
pub struct Tape {
    decisions: Mutex<BTreeMap<String, Value>>,
}

impl Tape {
    pub fn new() -> Arc<Tape> {
        Arc::new(Tape::default())
    }

    /// Read a tape file.
    pub fn load(path: impl AsRef<std::path::Path>) -> Result<Arc<Tape>, ClassifierError> {
        let b = std::fs::read(path).map_err(|e| ClassifierError(e.to_string()))?;
        #[derive(Deserialize)]
        struct File {
            #[serde(default)]
            decisions: Option<BTreeMap<String, Value>>,
        }
        let f: File = serde_json::from_slice(&b).map_err(|e| ClassifierError(e.to_string()))?;
        Ok(Arc::new(Tape {
            decisions: Mutex::new(f.decisions.unwrap_or_default()),
        }))
    }

    /// Write the tape (sorted keys, 2-space indent, trailing newline).
    pub fn save(&self, path: impl AsRef<std::path::Path>) -> Result<(), ClassifierError> {
        let d = self.decisions.lock().unwrap_or_else(|e| e.into_inner());
        let v = if d.is_empty() {
            json!({"decisions": null})
        } else {
            json!({"decisions": *d})
        };
        drop(d);
        let mut s = serde_json::to_string_pretty(&v).map_err(|e| ClassifierError(e.to_string()))?;
        s.push('\n');
        std::fs::write(path, s).map_err(|e| ClassifierError(e.to_string()))
    }

    /// The recorded decisions by call name (wire shape).
    pub fn decisions(&self) -> BTreeMap<String, Value> {
        self.decisions
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .clone()
    }

    /// Wrap a live classifier: every call is forwarded and taped.
    pub fn recording(self: &Arc<Self>, live: Classifier) -> Result<Classifier, ClassifierError> {
        let tape = self.clone();
        create_classifier(ClassifierOptions {
            style: ClassifierStyle::Custom,
            evaluate: Some(Arc::new(move |ctx: EvalContext, state, qs| {
                let (tape, live) = (tape.clone(), live.clone());
                Box::pin(async move {
                    let name = ctx.call_name.clone();
                    let d = live.evaluate_ctx(ctx, state, &qs).await.map_err(|e| e.0)?;
                    tape.decisions
                        .lock()
                        .unwrap_or_else(|e| e.into_inner())
                        .insert(name, d.to_value());
                    Ok(d)
                })
            })),
            ..Default::default()
        })
    }

    /// Answer from the tape by call name, with no network.
    pub fn replayer(self: &Arc<Self>) -> Result<Classifier, ClassifierError> {
        let tape = self.clone();
        create_classifier(ClassifierOptions {
            style: ClassifierStyle::Custom,
            evaluate: Some(Arc::new(move |ctx: EvalContext, _state, _qs| {
                let tape = tape.clone();
                Box::pin(async move {
                    let raw = tape
                        .decisions
                        .lock()
                        .unwrap_or_else(|e| e.into_inner())
                        .get(&ctx.call_name)
                        .cloned();
                    match raw {
                        None => Err(format!(
                            "tape: no recorded decision for call \"{}\"",
                            ctx.call_name
                        )),
                        Some(v) => Decision::from_value(&v).map_err(|e| e.0),
                    }
                })
            })),
            ..Default::default()
        })
    }
}