Skip to main content

artifactize_core/config/
tools.rs

1use std::sync::Arc;
2
3use serde::{Deserialize, Serialize};
4use serde_json::Value;
5
6/// Keep descriptions usable in provider tool listings, measured as JSON client UTF-16 units.
7const MAX_DESCRIPTION_CHARS: usize = 4000;
8
9use super::validation::{paths, present, script, text, timeout};
10
11#[derive(Debug, Clone, Serialize)]
12#[serde(untagged)]
13pub enum AgentTool {
14    Command(CommandTool),
15    Builtin(BuiltinTool),
16}
17
18impl<'de> Deserialize<'de> for AgentTool {
19    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
20        use serde::de::Error;
21        let value = Value::deserialize(deserializer)?;
22        if value.get("builtin").is_some() {
23            serde_json::from_value(value).map(Self::Builtin)
24        } else {
25            serde_json::from_value(value).map(Self::Command)
26        }
27        .map_err(D::Error::custom)
28    }
29}
30
31#[derive(Debug, Clone, Serialize, Deserialize)]
32#[serde(
33    rename_all(serialize = "camelCase", deserialize = "snake_case"),
34    deny_unknown_fields,
35    try_from = "CommandToolInput"
36)]
37pub struct CommandTool {
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    pub session: Option<super::ToolFqn>,
40    pub description: String,
41    /// Shared with every declaration of an equal schema in the same read.
42    #[serde(default = "empty_schema")]
43    pub input_schema: Arc<Value>,
44    pub protocol: ToolProtocol,
45    #[serde(serialize_with = "crate::platform::serialize_program")]
46    pub command: String,
47    pub args: Vec<crate::scope::Argument>,
48    #[serde(
49        default,
50        deserialize_with = "timeout",
51        serialize_with = "super::validation::milliseconds::serialize",
52        skip_serializing_if = "Option::is_none"
53    )]
54    pub timeout_ms: Option<std::time::Duration>,
55    #[serde(default, skip_serializing_if = "Vec::is_empty")]
56    pub execution_paths: Vec<super::LogicalPath>,
57    #[serde(skip)]
58    pub(crate) plain_args: Vec<super::plain::PlainArgument>,
59}
60
61#[derive(Debug, Clone, Serialize, Deserialize)]
62#[serde(
63    rename_all(serialize = "camelCase", deserialize = "snake_case"),
64    deny_unknown_fields
65)]
66struct CommandToolInput {
67    #[serde(default)]
68    pub session: Option<super::ToolFqn>,
69    pub description: String,
70    #[serde(default = "empty_schema")]
71    pub input_schema: Value,
72    pub protocol: ToolProtocol,
73    pub command: String,
74    pub args: Vec<crate::scope::Argument>,
75    #[serde(
76        default,
77        deserialize_with = "timeout",
78        serialize_with = "super::validation::milliseconds::serialize",
79        skip_serializing_if = "Option::is_none"
80    )]
81    pub timeout_ms: Option<std::time::Duration>,
82    #[serde(default, skip_serializing_if = "Vec::is_empty")]
83    pub execution_paths: Vec<super::LogicalPath>,
84}
85
86impl TryFrom<CommandToolInput> for CommandTool {
87    type Error = String;
88    fn try_from(input: CommandToolInput) -> Result<Self, Self::Error> {
89        let plain_args = if input.protocol == ToolProtocol::Plain {
90            input
91                .args
92                .iter()
93                .map(|arg| {
94                    let template = arg.literal().ok_or(
95                        "A plain tool's args are `{property}` templates; a `@{path …}` slot needs protocol = \"json\".",
96                    )?;
97                    super::plain::PlainArgument::parse(template, &input.input_schema)
98                })
99                .collect::<Result<_, _>>()?
100        } else {
101            Vec::new()
102        };
103        Ok(Self {
104            session: input.session,
105            description: input.description,
106            input_schema: Arc::new(input.input_schema),
107            protocol: input.protocol,
108            command: input.command,
109            args: input.args,
110            timeout_ms: input.timeout_ms,
111            execution_paths: input.execution_paths,
112            plain_args,
113        })
114    }
115}
116
117#[derive(Debug, Clone, Serialize, Deserialize)]
118#[serde(deny_unknown_fields)]
119pub struct ToolSession {
120    pub start: SessionCommand,
121    pub stop: SessionCommand,
122}
123
124#[derive(Debug, Clone, Serialize, Deserialize)]
125#[serde(
126    rename_all(serialize = "camelCase", deserialize = "snake_case"),
127    deny_unknown_fields
128)]
129pub struct SessionCommand {
130    #[serde(serialize_with = "crate::platform::serialize_program")]
131    pub command: String,
132    pub args: Vec<crate::scope::Argument>,
133    #[serde(default, skip_serializing_if = "Vec::is_empty")]
134    pub execution_paths: Vec<super::LogicalPath>,
135}
136
137impl SessionCommand {
138    pub(super) fn validate(&self) -> Result<(), String> {
139        script(&self.command, &self.args)?;
140        if self.command.contains(['{', '}']) {
141            return Err("Session command must not contain placeholders.".into());
142        }
143        paths(&self.execution_paths, "execution_paths")
144    }
145}
146
147#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
148#[serde(rename_all = "lowercase")]
149pub enum ToolProtocol {
150    Json,
151    Plain,
152}
153
154#[derive(Debug, Clone, Serialize, Deserialize)]
155#[serde(deny_unknown_fields)]
156pub struct BuiltinTool {
157    pub builtin: Builtin,
158    #[serde(
159        default,
160        deserialize_with = "present",
161        skip_serializing_if = "Option::is_none"
162    )]
163    pub args: Option<Vec<String>>,
164    #[serde(
165        default,
166        deserialize_with = "present",
167        skip_serializing_if = "Option::is_none"
168    )]
169    pub description: Option<String>,
170}
171
172pub use artifactize_tools::Builtin;
173
174impl AgentTool {
175    /// Its description and input schema are bounded, as a provider receives them.
176    pub(super) fn validate(&self, schemas: &mut super::schemas::Schemas) -> Result<(), String> {
177        match self {
178            Self::Command(tool) => {
179                description(&tool.description)?;
180                script(&tool.command, &tool.args)?;
181                if tool.command.contains(['{', '}']) {
182                    return Err("Tool command must not contain placeholders.".into());
183                }
184                paths(&tool.execution_paths, "execution_paths")?;
185                schemas.check(&tool.input_schema, |schema| {
186                    crate::tools::schema::compile(schema).map(drop)
187                })
188            }
189            Self::Builtin(tool) => {
190                if let Some(value) = &tool.description {
191                    description(value)?;
192                }
193                artifactize_tools::builtin::validate_args(
194                    tool.builtin,
195                    tool.args.as_deref(),
196                    false,
197                )?;
198                if let Some(args) = &tool.args {
199                    validate_agent_target(tool.builtin, args)?;
200                }
201                Ok(())
202            }
203        }
204    }
205    pub fn input_schema(&self) -> Value {
206        match self {
207            Self::Command(tool) => Value::clone(&tool.input_schema),
208            Self::Builtin(tool) => match &tool.args {
209                Some(args) => crate::tools::builtin::fixed_schema(tool.builtin, args),
210                None => crate::tools::builtin::input_schema(tool.builtin),
211            },
212        }
213    }
214}
215
216#[derive(Debug, Clone, Serialize)]
217#[serde(untagged)]
218pub enum HumanTool {
219    Command(HumanCommandTool),
220    Builtin(HumanBuiltinTool),
221    Viewer(HumanViewerTool),
222}
223
224impl<'de> Deserialize<'de> for HumanTool {
225    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
226        use serde::de::Error;
227        let value = Value::deserialize(deserializer)?;
228        if value.get("kind").and_then(Value::as_str) == Some("viewer") {
229            serde_json::from_value(value).map(Self::Viewer)
230        } else if value.get("builtin").is_some() {
231            serde_json::from_value(value).map(Self::Builtin)
232        } else {
233            serde_json::from_value(value).map(Self::Command)
234        }
235        .map_err(D::Error::custom)
236    }
237}
238
239#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
240#[serde(deny_unknown_fields)]
241pub struct HumanViewerTool {
242    pub kind: ViewerKind,
243    pub description: String,
244    /// The plugin whose viewer it opens; its page stays in the plugin, never in a saved
245    /// declaration.
246    pub plugin: super::PluginName,
247}
248
249#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
250#[serde(rename_all = "lowercase")]
251pub enum ViewerKind {
252    Viewer,
253}
254
255#[derive(Debug, Clone, Serialize, Deserialize)]
256#[serde(
257    rename_all(serialize = "camelCase", deserialize = "snake_case"),
258    deny_unknown_fields
259)]
260pub struct HumanCommandTool {
261    pub description: String,
262    pub kind: HumanToolKind,
263    #[serde(serialize_with = "crate::platform::serialize_program")]
264    pub command: String,
265    pub args: Vec<crate::scope::Argument>,
266    #[serde(
267        default,
268        deserialize_with = "timeout",
269        serialize_with = "super::validation::milliseconds::serialize",
270        skip_serializing_if = "Option::is_none"
271    )]
272    pub timeout_ms: Option<std::time::Duration>,
273}
274
275#[derive(Debug, Clone)]
276pub struct HumanBuiltinTool {
277    pub builtin: Builtin,
278    pub description: String,
279    pub args: Vec<crate::scope::Argument>,
280}
281
282impl<'de> Deserialize<'de> for HumanBuiltinTool {
283    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
284        use serde::de::Error;
285        #[derive(Deserialize)]
286        #[serde(deny_unknown_fields)]
287        struct Declaration {
288            builtin: Builtin,
289            #[serde(default, deserialize_with = "present")]
290            description: Option<String>,
291            #[serde(default, deserialize_with = "present")]
292            kind: Option<HumanToolKind>,
293            args: Vec<crate::scope::Argument>,
294        }
295        let declaration = Declaration::deserialize(deserializer)?;
296        let args: Vec<String> = declaration
297            .args
298            .iter()
299            .map(|arg| arg.literal().map_or_else(|| arg.to_string(), str::to_owned))
300            .collect();
301        artifactize_tools::builtin::validate_args(declaration.builtin, Some(&args), true)
302            .map_err(D::Error::custom)?;
303        let kind = if matches!(declaration.builtin, Builtin::Open | Builtin::Graph) {
304            HumanToolKind::Launch
305        } else {
306            HumanToolKind::Output
307        };
308        if declaration.kind.is_some_and(|declared| declared != kind) {
309            return Err(D::Error::custom(
310                "Human builtin kind disagrees with its tool.",
311            ));
312        }
313        Ok(Self {
314            builtin: declaration.builtin,
315            description: declaration.description.unwrap_or_else(|| {
316                crate::tools::builtin::fixed_description(declaration.builtin, &args).into()
317            }),
318            args: declaration.args,
319        })
320    }
321}
322
323#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
324#[serde(rename_all = "lowercase")]
325pub enum HumanToolKind {
326    Launch,
327    Output,
328    Viewer,
329}
330
331impl HumanTool {
332    pub fn description(&self) -> &str {
333        match self {
334            Self::Command(tool) => &tool.description,
335            Self::Builtin(tool) => &tool.description,
336            Self::Viewer(tool) => &tool.description,
337        }
338    }
339    pub fn kind(&self) -> HumanToolKind {
340        match self {
341            Self::Command(tool) => tool.kind,
342            Self::Builtin(tool) => tool.kind(),
343            Self::Viewer(_) => HumanToolKind::Viewer,
344        }
345    }
346    pub(super) fn validate(&self) -> Result<(), String> {
347        description(self.description())?;
348        match self {
349            Self::Viewer(_) => {}
350            Self::Command(tool) => {
351                script(&tool.command, &tool.args)?;
352            }
353            Self::Builtin(tool) => {
354                if !matches!(tool.builtin, Builtin::Help | Builtin::Graph)
355                    && let crate::scope::Argument::Literal(target) = &tool.args[0]
356                    && !(tool.builtin == Builtin::Open
357                        && artifactize_tools::builtin::is_url(target))
358                {
359                    artifactize_tools::scope::logical_path(target)
360                        .map_err(|error| error.to_string())?;
361                }
362                if tool.builtin == Builtin::Help
363                    && tool
364                        .args
365                        .iter()
366                        .any(|arg| matches!(arg, crate::scope::Argument::Reference { .. }))
367                {
368                    return Err(
369                        "Help args are literal program/subcommand names, not path placeholders."
370                            .into(),
371                    );
372                }
373            }
374        }
375        Ok(())
376    }
377}
378
379fn validate_agent_target(builtin: Builtin, args: &[String]) -> Result<(), String> {
380    if matches!(builtin, Builtin::Graph | Builtin::Declarations) {
381        return Ok(());
382    }
383    if builtin == Builtin::Help {
384        if args.iter().any(|arg| arg.contains(['{', '}'])) {
385            return Err("Help args are literal program/subcommand names.".into());
386        }
387        return Ok(());
388    }
389    artifactize_tools::scope::logical_path(&args[0]).map_err(|error| error.to_string())
390}
391
392fn empty_schema() -> Value {
393    serde_json::json!({"type":"object", "additionalProperties":false})
394}
395
396pub(super) fn description(value: &str) -> Result<(), String> {
397    text(value, "Tool description")?;
398    if value.encode_utf16().count() > MAX_DESCRIPTION_CHARS {
399        return Err(format!(
400            "Tool description is limited to {MAX_DESCRIPTION_CHARS} characters."
401        ));
402    }
403    Ok(())
404}
405
406impl HumanBuiltinTool {
407    pub fn kind(&self) -> HumanToolKind {
408        if matches!(self.builtin, Builtin::Open | Builtin::Graph) {
409            HumanToolKind::Launch
410        } else {
411            HumanToolKind::Output
412        }
413    }
414}
415impl Serialize for HumanBuiltinTool {
416    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
417        #[derive(Serialize)]
418        struct Stored<'a> {
419            builtin: Builtin,
420            description: &'a str,
421            kind: HumanToolKind,
422            args: &'a [crate::scope::Argument],
423        }
424        Stored {
425            builtin: self.builtin,
426            description: &self.description,
427            kind: self.kind(),
428            args: &self.args,
429        }
430        .serialize(serializer)
431    }
432}