weirdnet-agent 0.4.2

Weirdnet agent runtime: a model-agnostic agent loop with streaming events and cancellation, tool sources and registry, tiered approval policy with per-site grants and standing allows, research budgets, traces with citation checks, and remote inference (infer/1 and infer/2, catalog, pool with failover and resume).
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
//! Tools, tool sources and the registry.
//!
//! A [`ToolSource`] is anything that lists and runs tools: [`LocalTools`] for
//! in-process tools today, MCP servers and remote nodes later. The
//! [`ToolRegistry`] merges sources, applies per-source and per-tool switches and
//! stricter tier overrides, and resolves a tool name to its source.

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

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::cancel::CancelToken;
use crate::identity::AgentIdentity;
use crate::policy::{Tier, site_of};
use crate::trace::{SessionMark, StepKind};

/// Which budget counter a call draws from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum BudgetCharge {
    #[default]
    None,
    Search,
    Page,
}

/// MCP-style hints used to derive the default tier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct ToolAnnotations {
    pub read_only: bool,
    pub destructive: bool,
    pub open_world: bool,
}

/// What the model sees about a tool, plus how the runtime treats it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolSpec {
    pub name: String,
    pub description: String,
    /// JSON Schema for the arguments.
    pub input_schema: Value,
    pub annotations: ToolAnnotations,
    pub tier: Tier,
    #[serde(default)]
    pub charge: BudgetCharge,
}

impl ToolSpec {
    /// A tool with an empty object schema and the conservative default tier (Navigate).
    pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            input_schema: serde_json::json!({ "type": "object", "properties": {} }),
            annotations: ToolAnnotations::default(),
            tier: Tier::Navigate,
            charge: BudgetCharge::None,
        }
    }

    pub fn schema(mut self, schema: Value) -> Self {
        self.input_schema = schema;
        self
    }

    /// Sets annotations and derives the tier from them.
    pub fn annotations(mut self, a: ToolAnnotations) -> Self {
        self.annotations = a;
        self.tier = Tier::from_annotations(a.read_only, a.destructive, a.open_world);
        self
    }

    /// Sets the tier directly (for first-party tools that know their tier).
    pub fn tier(mut self, tier: Tier) -> Self {
        self.tier = tier;
        self
    }

    pub fn charge(mut self, charge: BudgetCharge) -> Self {
        self.charge = charge;
        self
    }
}

/// What a call touches, so the policy can check site grants and providers.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct CallTarget {
    pub url: Option<String>,
    pub site: Option<String>,
    pub provider: Option<String>,
}

impl CallTarget {
    pub fn url(url: impl Into<String>) -> Self {
        let url = url.into();
        Self { site: site_of(&url), url: Some(url), provider: None }
    }

    pub fn provider(provider: impl Into<String>) -> Self {
        Self { provider: Some(provider.into()), ..Self::default() }
    }

    /// Site from `site`, else from `url`.
    pub fn resolved_site(&self) -> Option<String> {
        self.site.clone().or_else(|| self.url.as_deref().and_then(site_of))
    }
}

/// Passed to every call.
#[derive(Debug, Clone)]
pub struct ToolContext {
    pub agent: AgentIdentity,
    pub task_id: String,
    pub session: SessionMark,
    pub cancel: CancelToken,
}

/// A tool's result. `steps` are recorded in the trace in order; when empty the
/// runtime records one generic tool step.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct ToolOutput {
    pub content: String,
    #[serde(default)]
    pub is_error: bool,
    #[serde(default)]
    pub steps: Vec<StepKind>,
}

impl ToolOutput {
    pub fn text(content: impl Into<String>) -> Self {
        Self { content: content.into(), ..Self::default() }
    }

    pub fn error(content: impl Into<String>) -> Self {
        Self { content: content.into(), is_error: true, steps: Vec::new() }
    }

    pub fn with_step(mut self, step: StepKind) -> Self {
        self.steps.push(step);
        self
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
#[serde(rename_all = "snake_case", tag = "error", content = "detail")]
#[non_exhaustive]
pub enum ToolError {
    #[error("unknown tool {0}")]
    NotFound(String),
    #[error("tool {0} is turned off")]
    Disabled(String),
    #[error("invalid arguments: {0}")]
    InvalidArgs(String),
    #[error("{0}")]
    Failed(String),
    #[error("timed out")]
    Timeout,
    #[error("cancelled")]
    Cancelled,
}

/// One in-process tool.
#[async_trait]
pub trait Tool: Send + Sync {
    fn spec(&self) -> ToolSpec;

    /// What a call with these arguments touches. Defaults to nothing.
    fn target(&self, _args: &Value) -> CallTarget {
        CallTarget::default()
    }

    async fn call(&self, ctx: &ToolContext, args: Value) -> Result<ToolOutput, ToolError>;
}

/// Where tools come from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum SourceKind {
    Local,
    Mcp,
    Node,
}

/// A set of tools behind one connection (in-process, an MCP server, a remote node).
#[async_trait]
pub trait ToolSource: Send + Sync {
    fn id(&self) -> &str;
    fn kind(&self) -> SourceKind;
    async fn list(&self) -> Result<Vec<ToolSpec>, ToolError>;
    fn target(&self, _tool: &str, _args: &Value) -> CallTarget {
        CallTarget::default()
    }
    async fn call(&self, tool: &str, ctx: &ToolContext, args: Value) -> Result<ToolOutput, ToolError>;
}

/// In-process tools.
pub struct LocalTools {
    id: String,
    tools: BTreeMap<String, Arc<dyn Tool>>,
}

impl LocalTools {
    pub fn new(id: impl Into<String>) -> Self {
        Self { id: id.into(), tools: BTreeMap::new() }
    }

    pub fn with(mut self, tool: impl Tool + 'static) -> Self {
        self.add(Arc::new(tool));
        self
    }

    pub fn add(&mut self, tool: Arc<dyn Tool>) {
        self.tools.insert(tool.spec().name, tool);
    }
}

#[async_trait]
impl ToolSource for LocalTools {
    fn id(&self) -> &str {
        &self.id
    }

    fn kind(&self) -> SourceKind {
        SourceKind::Local
    }

    async fn list(&self) -> Result<Vec<ToolSpec>, ToolError> {
        Ok(self.tools.values().map(|t| t.spec()).collect())
    }

    fn target(&self, tool: &str, args: &Value) -> CallTarget {
        self.tools.get(tool).map(|t| t.target(args)).unwrap_or_default()
    }

    async fn call(&self, tool: &str, ctx: &ToolContext, args: Value) -> Result<ToolOutput, ToolError> {
        let t = self.tools.get(tool).ok_or_else(|| ToolError::NotFound(tool.to_string()))?;
        t.call(ctx, args).await
    }
}

#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum RegistryError {
    #[error("tool {tool} is offered by both {first} and {second}")]
    Duplicate { tool: String, first: String, second: String },
    #[error("source {source_id} failed to list tools: {error}")]
    List { source_id: String, error: ToolError },
    #[error("tier override for {tool} would loosen it")]
    LooserTier { tool: String },
}

/// Merged view of all sources for one session.
#[derive(Default)]
pub struct ToolRegistry {
    sources: Vec<Arc<dyn ToolSource>>,
    index: BTreeMap<String, (usize, ToolSpec)>,
    disabled_sources: BTreeSet<String>,
    disabled_tools: BTreeSet<String>,
    tier_overrides: BTreeMap<String, Tier>,
}

impl ToolRegistry {
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a source. Call [`refresh`](Self::refresh) afterwards.
    pub fn add_source(&mut self, source: Arc<dyn ToolSource>) {
        self.sources.push(source);
    }

    pub fn source_ids(&self) -> impl Iterator<Item = &str> {
        self.sources.iter().map(|s| s.id())
    }

    /// Re-lists every source. Tool names must be unique across sources.
    pub async fn refresh(&mut self) -> Result<(), RegistryError> {
        let mut index = BTreeMap::new();
        for (i, src) in self.sources.iter().enumerate() {
            let specs = src.list().await.map_err(|error| RegistryError::List { source_id: src.id().to_string(), error })?;
            for spec in specs {
                if let Some((j, _)) = index.get(&spec.name) {
                    let first: &Arc<dyn ToolSource> = &self.sources[*j];
                    return Err(RegistryError::Duplicate { tool: spec.name, first: first.id().to_string(), second: src.id().to_string() });
                }
                index.insert(spec.name.clone(), (i, spec));
            }
        }
        self.index = index;
        Ok(())
    }

    pub fn set_source_enabled(&mut self, source_id: &str, on: bool) {
        if on {
            self.disabled_sources.remove(source_id);
        } else {
            self.disabled_sources.insert(source_id.to_string());
        }
    }

    pub fn set_tool_enabled(&mut self, tool: &str, on: bool) {
        if on {
            self.disabled_tools.remove(tool);
        } else {
            self.disabled_tools.insert(tool.to_string());
        }
    }

    /// Makes a tool stricter. Loosening (including below Interact for destructive tools) is refused.
    pub fn set_tier_override(&mut self, tool: &str, tier: Tier) -> Result<(), RegistryError> {
        if let Some((_, spec)) = self.index.get(tool)
            && !spec.tier.allows_override_to(tier)
        {
            return Err(RegistryError::LooserTier { tool: tool.to_string() });
        }
        self.tier_overrides.insert(tool.to_string(), tier);
        Ok(())
    }

    fn effective(&self, idx: usize, spec: &ToolSpec) -> Option<ToolSpec> {
        let src = &self.sources[idx];
        if self.disabled_sources.contains(src.id()) || self.disabled_tools.contains(&spec.name) {
            return None;
        }
        let mut spec = spec.clone();
        if let Some(t) = self.tier_overrides.get(&spec.name)
            && spec.tier.allows_override_to(*t)
        {
            spec.tier = *t;
        }
        Some(spec)
    }

    /// Enabled tools offered to the model. Tier `Never` tools are never offered.
    pub fn specs(&self) -> Vec<ToolSpec> {
        self.index.values().filter_map(|(i, s)| self.effective(*i, s)).filter(|s| s.tier != Tier::Never).collect()
    }

    /// Resolves an enabled tool to its source and effective spec.
    pub fn lookup(&self, tool: &str) -> Result<(Arc<dyn ToolSource>, ToolSpec), ToolError> {
        let (i, spec) = self.index.get(tool).ok_or_else(|| ToolError::NotFound(tool.to_string()))?;
        let spec = self.effective(*i, spec).ok_or_else(|| ToolError::Disabled(tool.to_string()))?;
        Ok((self.sources[*i].clone(), spec))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::testing::FnTool;

    fn src(id: &str, names: &[&str]) -> Arc<dyn ToolSource> {
        let mut l = LocalTools::new(id);
        for n in names {
            l.add(Arc::new(FnTool::new(ToolSpec::new(*n, "t"), |_| Ok(ToolOutput::text("ok")))));
        }
        Arc::new(l)
    }

    #[tokio::test]
    async fn registry_merges_switches_and_rejects_duplicates() {
        let mut r = ToolRegistry::new();
        r.add_source(src("browser", &["tabs.open", "page.click"]));
        r.add_source(src("mcp:mouser", &["search_issues"]));
        r.refresh().await.unwrap();
        assert_eq!(r.specs().len(), 3);
        r.set_source_enabled("mcp:mouser", false);
        assert_eq!(r.lookup("search_issues").err(), Some(ToolError::Disabled("search_issues".into())));
        r.set_source_enabled("mcp:mouser", true);
        r.set_tool_enabled("page.click", false);
        assert_eq!(r.specs().len(), 2);
        assert_eq!(r.lookup("nope").err(), Some(ToolError::NotFound("nope".into())));
        assert_eq!(r.source_ids().collect::<Vec<_>>(), vec!["browser", "mcp:mouser"]);

        r.add_source(src("other", &["tabs.open"]));
        assert!(matches!(r.refresh().await, Err(RegistryError::Duplicate { .. })));
    }

    #[tokio::test]
    async fn tier_overrides_only_tighten() {
        let mut l = LocalTools::new("mcp:x");
        l.add(Arc::new(FnTool::new(ToolSpec::new("delete", "d").annotations(ToolAnnotations { destructive: true, ..Default::default() }), |_| {
            Ok(ToolOutput::text(""))
        })));
        l.add(Arc::new(FnTool::new(ToolSpec::new("read", "r").annotations(ToolAnnotations { read_only: true, ..Default::default() }), |_| {
            Ok(ToolOutput::text(""))
        })));
        let mut r = ToolRegistry::new();
        r.add_source(Arc::new(l));
        r.refresh().await.unwrap();
        assert_eq!(r.lookup("delete").unwrap().1.tier, Tier::Interact);
        assert!(r.set_tier_override("delete", Tier::Navigate).is_err());
        r.set_tier_override("read", Tier::Interact).unwrap();
        assert_eq!(r.lookup("read").unwrap().1.tier, Tier::Interact);
        r.set_tier_override("delete", Tier::Never).unwrap();
        assert!(r.specs().iter().all(|s| s.name != "delete"));
    }

    #[test]
    fn call_target_resolves_site() {
        let t = CallTarget::url("https://www.Docs.rs/tokio");
        assert_eq!(t.resolved_site().as_deref(), Some("docs.rs"));
        assert_eq!(CallTarget::provider("kagi").resolved_site(), None);
    }
}