tools_core 0.3.3

Core functionality and schema generation for the tools collection system
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
//! Typestate-based builder for [`ToolCollection`].
//!
//! ```ignore
//! use tools_core::ToolsBuilder;
//! use std::sync::Arc;
//!
//! // Simple — same as collect_tools():
//! let tools = ToolsBuilder::new().collect()?;
//!
//! // With context:
//! let tools = ToolsBuilder::new()
//!     .with_context(Arc::new(my_state))
//!     .with_meta::<MyPolicy>()
//!     .collect()?;
//! ```

use std::{
    any::{Any, TypeId},
    marker::PhantomData,
    path::PathBuf,
    sync::Arc,
};

use serde::de::DeserializeOwned;

use crate::{NoMeta, ToolCollection, ToolError, collect_inventory_inner};
use crate::ffi::{Language, leak_string, load_language};

// ============================================================================
// TYPESTATE MARKERS
// ============================================================================

mod sealed {
    pub trait Sealed {}
}

/// Marker trait for [`ToolsBuilder`] states. Sealed — cannot be implemented
/// outside this crate.
pub trait BuilderState: sealed::Sealed {}

/// Initial state: no context, no FFI adapters configured.
pub struct Blank;

/// Context has been provided. FFI adapter methods are unavailable.
pub struct Native;

/// At least one FFI adapter source has been added. `with_context()` is
/// unavailable. (Transition methods added behind feature flags.)
pub struct Scripted;

impl sealed::Sealed for Blank {}
impl sealed::Sealed for Native {}
impl sealed::Sealed for Scripted {}

impl BuilderState for Blank {}
impl BuilderState for Native {}
impl BuilderState for Scripted {}

// ============================================================================
// BUILDER INTERNALS
// ============================================================================

struct BuilderInner {
    ctx: Option<Arc<dyn Any + Send + Sync>>,
    ctx_type_id: Option<TypeId>,
    ctx_type_name: &'static str,
    language: Option<Language>,
    script_paths: Vec<PathBuf>,
}

impl BuilderInner {
    fn empty() -> Self {
        Self {
            ctx: None,
            ctx_type_id: None,
            ctx_type_name: "",
            language: None,
            script_paths: Vec::new(),
        }
    }
}

// ============================================================================
// TOOLS BUILDER
// ============================================================================

/// Typestate builder for [`ToolCollection`].
///
/// The type parameter `S` tracks the builder state:
///
/// - [`Blank`] — initial. Can call [`with_context`][Self::with_context] or
///   (in the future) FFI adapter methods.
/// - [`Native`] — context was set. FFI methods unavailable.
/// - [`Scripted`] — FFI adapters added. `with_context` unavailable.
///
/// `M` is the metadata type, defaulting to [`NoMeta`]. Change it via
/// [`with_meta`][ToolsBuilder::with_meta].
///
/// # Typestate enforcement
///
/// Calling `with_context` after it has already been called does not compile:
///
/// ```compile_fail
/// use tools_core::builder::{ToolsBuilder, Native};
/// use std::sync::Arc;
///
/// // ERROR: ToolsBuilder<Native, _> has no method `with_context`
/// let b = ToolsBuilder::new()
///     .with_context(Arc::new(42_u32))
///     .with_context(Arc::new(42_u32));
/// ```
pub struct ToolsBuilder<S: BuilderState = Blank, M = NoMeta> {
    inner: BuilderInner,
    _marker: PhantomData<fn() -> (S, M)>,
}

// ── Blank ──────────────────────────────────────────────────────────────

impl ToolsBuilder<Blank, NoMeta> {
    /// Create a new builder in the [`Blank`] state with [`NoMeta`].
    /// Use [`with_meta`][ToolsBuilder::with_meta] to change the metadata
    /// type.
    pub fn new() -> Self {
        Self {
            inner: BuilderInner::empty(),
            _marker: PhantomData,
        }
    }
}

impl Default for ToolsBuilder<Blank, NoMeta> {
    fn default() -> Self {
        Self::new()
    }
}

impl<M> ToolsBuilder<Blank, M> {
    /// Set a shared context that will be injected into every tool whose
    /// first parameter is named `ctx`. Transitions to the [`Native`]
    /// state, locking out FFI adapter methods.
    ///
    /// ```compile_fail
    /// # use tools_core::builder::ToolsBuilder;
    /// # use std::sync::Arc;
    /// // ERROR: with_language not available after with_context
    /// let b = ToolsBuilder::new()
    ///     .with_context(Arc::new(42_u32))
    ///     .with_language(tools_core::Language::Python);
    /// ```
    pub fn with_context<T: Send + Sync + 'static>(
        self,
        ctx: Arc<T>,
    ) -> ToolsBuilder<Native, M> {
        ToolsBuilder {
            inner: BuilderInner {
                ctx: Some(ctx),
                ctx_type_id: Some(TypeId::of::<T>()),
                ctx_type_name: std::any::type_name::<T>(),
                language: None,
                script_paths: Vec::new(),
            },
            _marker: PhantomData,
        }
    }

    /// Set the scripting language for FFI tool loading. Transitions to
    /// the [`Scripted`] state, locking out [`with_context`][Self::with_context].
    ///
    /// Use [`from_path`][ToolsBuilder::<Scripted, M>::from_path] to add
    /// script directories after calling this.
    ///
    /// ```compile_fail
    /// # use tools_core::builder::ToolsBuilder;
    /// # use std::sync::Arc;
    /// // ERROR: with_context not available after with_language
    /// let b = ToolsBuilder::new()
    ///     .with_language(tools_core::Language::Python)
    ///     .with_context(Arc::new(42_u32));
    /// ```
    pub fn with_language(self, lang: Language) -> ToolsBuilder<Scripted, M> {
        ToolsBuilder {
            inner: BuilderInner {
                language: Some(lang),
                script_paths: Vec::new(),
                ctx: None,
                ctx_type_id: None,
                ctx_type_name: "",
            },
            _marker: PhantomData,
        }
    }
}

// ── Any state: with_meta ───────────────────────────────────────────────

impl<S: BuilderState, M> ToolsBuilder<S, M> {
    /// Change the metadata type. This is a phantom-only transition — no
    /// data is stored. `M2` is used at [`collect`] time to deserialize
    /// each tool's `#[tool(...)]` attributes.
    pub fn with_meta<M2>(self) -> ToolsBuilder<S, M2> {
        ToolsBuilder {
            inner: self.inner,
            _marker: PhantomData,
        }
    }
}

// ── collect() per state ────────────────────────────────────────────────

impl<M: DeserializeOwned> ToolsBuilder<Blank, M> {
    /// Build the collection from the global tool inventory (no context).
    /// Tools that require context will produce a [`ToolError::MissingCtx`]
    /// error.
    pub fn collect(self) -> Result<ToolCollection<M>, ToolError> {
        collect_inventory_inner(None, None, "")
    }
}

impl<M: DeserializeOwned> ToolsBuilder<Native, M> {
    /// Build the collection from the global tool inventory, injecting the
    /// stored context into tools that require it. Validates that every
    /// context-requiring tool expects the same type.
    pub fn collect(self) -> Result<ToolCollection<M>, ToolError> {
        collect_inventory_inner(
            self.inner.ctx,
            self.inner.ctx_type_id,
            self.inner.ctx_type_name,
        )
    }
}

// ── Scripted: from_path + collect ───────────────────────────────────

impl<M> ToolsBuilder<Scripted, M> {
    /// Add a script path to load tools from. Can be called multiple
    /// times to load from several paths.
    pub fn from_path(mut self, path: impl Into<PathBuf>) -> Self {
        self.inner.script_paths.push(path.into());
        self
    }
}

impl<M: DeserializeOwned> ToolsBuilder<Scripted, M> {
    /// Build the collection. Collects `#[tool]` inventory tools (no
    /// context), then loads scripted tools from configured paths via
    /// the selected language adapter.
    ///
    /// No paths configured = inventory tools only.
    #[cfg_attr(
        not(any(feature = "python", feature = "lua", feature = "js")),
        allow(unreachable_code, unused_variables)
    )]
    pub fn collect(self) -> Result<ToolCollection<M>, ToolError> {
        let lang = self
            .inner
            .language
            .expect("Scripted state must have a language set");

        let mut collection: ToolCollection<M> = collect_inventory_inner(None, None, "")?;

        for path in &self.inner.script_paths {
            let defs = load_language(lang, path)?;
            for def in defs {
                let name = leak_string(def.name);
                let desc = leak_string(def.description);
                let meta: M =
                    serde_json::from_value(def.meta).map_err(|e| ToolError::BadMeta {
                        tool: name,
                        error: e.to_string(),
                    })?;
                let func = def.func;
                collection.register_raw(name, desc, def.parameters, move |v| func(v), meta)?;
            }
        }

        Ok(collection)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::Deserialize;
    use serde_json::json;

    #[test]
    fn blank_collect_returns_collection() {
        let tools: ToolCollection = ToolsBuilder::new().collect().unwrap();
        // No panic, collection created. Tool count depends on what's
        // registered via #[tool] in the test binary — just check it works.
        let _ = tools.json().unwrap();
    }

    #[test]
    fn with_meta_changes_type() {
        #[derive(Debug, Default, Deserialize)]
        #[serde(default)]
        struct Policy {
            _flag: bool,
        }

        let tools = ToolsBuilder::new()
            .with_meta::<Policy>()
            .collect()
            .unwrap();

        let _ = tools.json().unwrap();
    }

    #[test]
    fn with_context_then_collect() {
        let ctx = Arc::new(42_u32);
        // No ctx-requiring tools in this test binary, but the builder
        // should still work — context is stored and unused tools are fine.
        let tools: ToolCollection = ToolsBuilder::new()
            .with_context(ctx)
            .collect()
            .unwrap();

        let _ = tools.json().unwrap();
    }

    #[test]
    fn register_raw_works() {
        let mut tools: ToolCollection = ToolsBuilder::new().collect().unwrap();

        tools
            .register_raw(
                "echo",
                "Echoes input back",
                json!({
                    "type": "object",
                    "properties": {
                        "msg": { "type": "string" }
                    },
                    "required": ["msg"]
                }),
                |v| {
                    Box::pin(async move {
                        let msg = v.get("msg").and_then(|m| m.as_str()).unwrap_or("");
                        Ok(serde_json::Value::String(msg.to_string()))
                    })
                },
                (),
            )
            .unwrap();

        let decls = tools.json().unwrap();
        let arr = decls.as_array().unwrap();
        assert!(arr.iter().any(|d| d["name"] == "echo"));
    }

    #[tokio::test]
    async fn register_raw_callable() {
        let mut tools: ToolCollection = ToolsBuilder::new().collect().unwrap();

        tools
            .register_raw(
                "double",
                "Doubles a number",
                json!({
                    "type": "object",
                    "properties": { "n": { "type": "integer" } },
                    "required": ["n"]
                }),
                |v| {
                    Box::pin(async move {
                        let n = v.get("n").and_then(|n| n.as_i64()).unwrap_or(0);
                        Ok(serde_json::Value::Number((n * 2).into()))
                    })
                },
                (),
            )
            .unwrap();

        let resp = tools
            .call(crate::FunctionCall::new(
                "double".to_string(),
                json!({ "n": 21 }),
            ))
            .await
            .unwrap();

        assert_eq!(resp.result, json!(42));
    }

    #[cfg(feature = "python")]
    #[test]
    fn scripted_no_paths_collects_inventory() {
        let tools: ToolCollection = ToolsBuilder::new()
            .with_language(crate::Language::Python)
            .collect()
            .unwrap();

        let _ = tools.json().unwrap();
    }

    #[cfg(feature = "python")]
    #[test]
    fn scripted_with_path_errors_not_implemented() {
        let err = ToolsBuilder::new()
            .with_language(crate::Language::Python)
            .from_path("/some/script.py")
            .collect()
            .err()
            .expect("should error");

        assert!(
            err.to_string().contains("not yet implemented"),
            "expected 'not yet implemented', got: {err}"
        );
    }

    #[cfg(feature = "python")]
    #[test]
    fn scripted_from_path_chainable() {
        let err = ToolsBuilder::new()
            .with_language(crate::Language::Python)
            .from_path("/first.py")
            .from_path("/second.py")
            .collect()
            .err()
            .expect("should error");

        assert!(err.to_string().contains("not yet implemented"));
    }
}