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
//! Internal implementation detail module for macro-generated code.
//!
//! **Not public API** — exported only for macro expansions generated by `#[llm_tool]`,
//! `#[llm_prompt]`, and `#[llm_resource]`.
#[doc(hidden)]
pub mod __private {
// Re-exports for generated code to work in no_std contexts.
#[cfg(not(feature = "std"))]
pub use alloc::borrow::Cow;
#[cfg(not(feature = "std"))]
use alloc::{
format,
string::{String, ToString},
};
pub use core::{convert::Into, result::Result};
#[cfg(feature = "std")]
pub use std::borrow::Cow;
/// Lazy initializer — [`std::sync::LazyLock`] under `std`,
/// [`spin::LazyLock`] under `no_std`.
#[cfg(feature = "std")]
pub use std::sync::LazyLock as Lazy;
/// Lazy initializer — [`std::sync::LazyLock`] under `std`,
/// [`spin::LazyLock`] under `no_std`.
#[cfg(not(feature = "std"))]
pub use spin::LazyLock as Lazy;
use crate::types::{Json, Sanitized, ToolError, ToolOutput, Untrusted};
/// Report a runtime tool-description template render failure.
///
/// Called by `#[llm_tool(..., context = ...)]`-generated `description()`
/// code: on a render error the tool falls back to its static description
/// body rather than panicking. Logs to stderr under `std`; a no-op under
/// `no_std` (where no logger is available).
#[cfg(feature = "std")]
pub fn log_description_render_error(tool: &str, err: &dyn core::fmt::Display) {
tracing::warn!(
tool,
error = %err,
"llm-tool: tool description template failed to render; falling back to static description"
);
}
/// `no_std` no-op counterpart of the `std` logger above.
#[cfg(not(feature = "std"))]
#[inline]
pub fn log_description_render_error(_tool: &str, _err: &dyn core::fmt::Display) {}
/// Wrapper enabling compile-time method dispatch for tool output conversion.
pub struct Wrap<T>(pub T);
// ── Inherent methods (highest priority in method resolution) ──
impl Wrap<ToolOutput> {
/// `ToolOutput` → identity pass-through.
pub fn __convert(self) -> Result<ToolOutput, ToolError> {
Ok(self.0)
}
}
impl Wrap<String> {
/// `String` → wrap as plain text (no JSON encoding).
pub fn __convert(self) -> Result<ToolOutput, ToolError> {
Ok(ToolOutput::new(self.0))
}
pub fn __convert_prompt(self) -> Result<crate::types::PromptOutput, ToolError> {
Ok(crate::types::PromptOutput::user(self.0))
}
pub fn __convert_resource(
self,
uri: &str,
mime_type: Option<&str>,
) -> Result<crate::types::ResourceOutput, ToolError> {
Ok(crate::types::ResourceOutput::text(uri, mime_type, self.0))
}
}
impl Wrap<&str> {
/// `&str` → wrap as plain text (no JSON encoding).
pub fn __convert(self) -> Result<ToolOutput, ToolError> {
Ok(ToolOutput::new(self.0))
}
pub fn __convert_prompt(self) -> Result<crate::types::PromptOutput, ToolError> {
Ok(crate::types::PromptOutput::user(self.0))
}
pub fn __convert_resource(
self,
uri: &str,
mime_type: Option<&str>,
) -> Result<crate::types::ResourceOutput, ToolError> {
Ok(crate::types::ResourceOutput::text(uri, mime_type, self.0))
}
}
impl Wrap<Sanitized<ToolOutput>> {
/// `Sanitized<ToolOutput>` → neutralize control tokens on the inner `ToolOutput`.
pub fn __convert(self) -> Result<ToolOutput, ToolError> {
Ok(self.0.0.sanitized())
}
}
impl Wrap<Sanitized<String>> {
/// `Sanitized<String>` → wrap as plain text and neutralize control tokens.
pub fn __convert(self) -> Result<ToolOutput, ToolError> {
Ok(ToolOutput::new(self.0.0).sanitized())
}
}
impl Wrap<Sanitized<&str>> {
/// `Sanitized<&str>` → wrap as plain text and neutralize control tokens.
pub fn __convert(self) -> Result<ToolOutput, ToolError> {
Ok(ToolOutput::new(self.0.0).sanitized())
}
}
impl Wrap<Untrusted<ToolOutput>> {
/// `Untrusted<ToolOutput>` → quarantine the inner `ToolOutput`.
pub fn __convert(self) -> Result<ToolOutput, ToolError> {
Ok(self.0.0.quarantined())
}
}
impl Wrap<Untrusted<String>> {
/// `Untrusted<String>` → wrap as plain text and quarantine.
pub fn __convert(self) -> Result<ToolOutput, ToolError> {
Ok(ToolOutput::new(self.0.0).quarantined())
}
}
impl Wrap<Untrusted<&str>> {
/// `Untrusted<&str>` → wrap as plain text and quarantine.
pub fn __convert(self) -> Result<ToolOutput, ToolError> {
Ok(ToolOutput::new(self.0.0).quarantined())
}
}
impl Wrap<crate::types::PromptOutput> {
pub fn __convert_prompt(self) -> Result<crate::types::PromptOutput, ToolError> {
Ok(self.0)
}
}
impl Wrap<crate::types::ResourceOutput> {
pub fn __convert_resource(
self,
_uri: &str,
_mime_type: Option<&str>,
) -> Result<crate::types::ResourceOutput, ToolError> {
Ok(self.0)
}
}
fn serialize_to_tool_output<T: serde::Serialize>(val: &T) -> Result<ToolOutput, ToolError> {
let json_value = serde_json::to_value(val)
.map_err(|e| ToolError::new(format!("serialization failed: {e}")))?;
let content = json_value.to_string();
match json_value {
serde_json::Value::Object(map) => Ok(ToolOutput {
content,
metadata: map.into_iter().collect(),
}),
_ => Ok(ToolOutput::new(content)),
}
}
impl<T: serde::Serialize> Wrap<Json<T>> {
/// `Json<T>` → serialize to JSON string.
pub fn __convert(self) -> Result<ToolOutput, ToolError> {
serialize_to_tool_output(&self.0.0)
}
}
impl<T: serde::Serialize> Wrap<Sanitized<Json<T>>> {
/// `Sanitized<Json<T>>` → serialize to JSON string and neutralize control tokens.
pub fn __convert(self) -> Result<ToolOutput, ToolError> {
serialize_to_tool_output(&Sanitized(self.0.0.0)).map(ToolOutput::sanitized)
}
}
impl<T: serde::Serialize> Wrap<Untrusted<Json<T>>> {
/// `Untrusted<Json<T>>` → serialize to JSON string and quarantine.
pub fn __convert(self) -> Result<ToolOutput, ToolError> {
serialize_to_tool_output(&self.0.0.0).map(ToolOutput::quarantined)
}
}
// ── Trait fallback (lower priority in method resolution) ──
/// Fallback conversion for any `T: Serialize` not covered by inherent methods.
///
/// Method resolution checks:
/// 1. Inherent methods on `Wrap<...>` (`ToolOutput`, `String`, `&str`, `Json<T>`,
/// and their `Sanitized<...>` / `Untrusted<...>` counterparts).
/// 2. Value-receiver `SerializeFallback` impls on `Wrap<Sanitized<T>>` and
/// `Wrap<Untrusted<T>>` for arbitrary `T: Serialize`.
/// 3. Autoref-receiver `SerializeFallback` impl on `&Wrap<T>` for arbitrary `T: Serialize`.
pub trait SerializeFallback {
/// Serialize `self` to JSON and wrap as [`ToolOutput`].
fn __convert(self) -> Result<ToolOutput, ToolError>;
}
impl<T: serde::Serialize> SerializeFallback for Wrap<Sanitized<T>> {
fn __convert(self) -> Result<ToolOutput, ToolError> {
serialize_to_tool_output(&self.0).map(ToolOutput::sanitized)
}
}
impl<T: serde::Serialize> SerializeFallback for Wrap<Untrusted<T>> {
fn __convert(self) -> Result<ToolOutput, ToolError> {
serialize_to_tool_output(&self.0.0).map(ToolOutput::quarantined)
}
}
impl<T: serde::Serialize> SerializeFallback for &Wrap<T> {
fn __convert(self) -> Result<ToolOutput, ToolError> {
serialize_to_tool_output(&self.0)
}
}
}