Skip to main content

weirdnet_agent/
testing.rs

1//! Test doubles: a scripted model, a scripted approver and closure-backed tools.
2//! Enabled in this crate's tests and, for downstream crates, with the `testing` feature.
3
4use std::collections::VecDeque;
5use std::sync::Mutex;
6
7use async_trait::async_trait;
8use serde_json::Value;
9
10use crate::cancel::CancelToken;
11use crate::model::{DeltaSink, Message, ModelBackend, ModelError, ModelTurn, ToolCall};
12use crate::policy::ApprovalPrompt;
13use crate::session::{ApprovalAnswer, Approver};
14use crate::tool::{CallTarget, Tool, ToolContext, ToolError, ToolOutput, ToolSpec};
15
16/// Shorthand for a model tool call.
17pub fn call(id: &str, name: &str, arguments: Value) -> ToolCall {
18    ToolCall { id: id.into(), name: name.into(), arguments }
19}
20
21/// Returns pre-written turns in order, streaming each turn's text word by word.
22/// Once the script runs out it returns empty turns.
23pub struct ScriptedModel {
24    turns: Mutex<VecDeque<ModelTurn>>,
25    seen: Mutex<Vec<Vec<Message>>>,
26}
27
28impl ScriptedModel {
29    pub fn new(turns: Vec<ModelTurn>) -> Self {
30        Self { turns: Mutex::new(turns.into()), seen: Mutex::new(Vec::new()) }
31    }
32
33    /// The message history passed on each call.
34    pub fn seen(&self) -> Vec<Vec<Message>> {
35        self.seen.lock().unwrap().clone()
36    }
37}
38
39#[async_trait]
40impl ModelBackend for ScriptedModel {
41    fn name(&self) -> String {
42        "scripted".into()
43    }
44
45    async fn complete(&self, messages: &[Message], _tools: &[ToolSpec], deltas: &DeltaSink, cancel: &CancelToken) -> Result<ModelTurn, ModelError> {
46        if cancel.is_cancelled() {
47            return Err(ModelError::Cancelled);
48        }
49        self.seen.lock().unwrap().push(messages.to_vec());
50        let turn = self.turns.lock().unwrap().pop_front().unwrap_or_default();
51        for piece in turn.text.split_inclusive(' ') {
52            deltas.text(piece);
53        }
54        Ok(turn)
55    }
56}
57
58/// Answers approval cards from a queue (then denies) and records every prompt.
59#[derive(Default)]
60pub struct ScriptedApprover {
61    answers: Mutex<VecDeque<ApprovalAnswer>>,
62    asked: Mutex<Vec<ApprovalPrompt>>,
63}
64
65impl ScriptedApprover {
66    pub fn new(answers: Vec<ApprovalAnswer>) -> Self {
67        Self { answers: Mutex::new(answers.into()), asked: Mutex::new(Vec::new()) }
68    }
69
70    pub fn asked(&self) -> Vec<ApprovalPrompt> {
71        self.asked.lock().unwrap().clone()
72    }
73}
74
75#[async_trait]
76impl Approver for ScriptedApprover {
77    async fn decide(&self, prompt: &ApprovalPrompt, _tool: &ToolSpec) -> ApprovalAnswer {
78        self.asked.lock().unwrap().push(prompt.clone());
79        self.answers.lock().unwrap().pop_front().unwrap_or(ApprovalAnswer::Deny)
80    }
81}
82
83type CallFn = Box<dyn Fn(Value) -> Result<ToolOutput, ToolError> + Send + Sync>;
84type TargetFn = Box<dyn Fn(&Value) -> CallTarget + Send + Sync>;
85
86/// A tool backed by closures.
87pub struct FnTool {
88    spec: ToolSpec,
89    call: CallFn,
90    target: Option<TargetFn>,
91}
92
93impl FnTool {
94    pub fn new(spec: ToolSpec, call: impl Fn(Value) -> Result<ToolOutput, ToolError> + Send + Sync + 'static) -> Self {
95        Self { spec, call: Box::new(call), target: None }
96    }
97
98    pub fn with_target(mut self, target: impl Fn(&Value) -> CallTarget + Send + Sync + 'static) -> Self {
99        self.target = Some(Box::new(target));
100        self
101    }
102}
103
104#[async_trait]
105impl Tool for FnTool {
106    fn spec(&self) -> ToolSpec {
107        self.spec.clone()
108    }
109
110    fn target(&self, args: &Value) -> CallTarget {
111        self.target.as_ref().map(|t| t(args)).unwrap_or_default()
112    }
113
114    async fn call(&self, _ctx: &ToolContext, args: Value) -> Result<ToolOutput, ToolError> {
115        (self.call)(args)
116    }
117}