1use std::sync::Arc;
2
3use serde::{Deserialize, Serialize};
4use serde_json::Value;
5
6const 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::ToolOperationName>,
40 pub description: String,
41 #[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::ToolOperationName>,
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 super::plain::PlainArgument::parse(&arg.to_string(), &input.input_schema)
95 })
96 .collect::<Result<_, _>>()?
97 } else {
98 Vec::new()
99 };
100 Ok(Self {
101 session: input.session,
102 description: input.description,
103 input_schema: Arc::new(input.input_schema),
104 protocol: input.protocol,
105 command: input.command,
106 args: input.args,
107 timeout_ms: input.timeout_ms,
108 execution_paths: input.execution_paths,
109 plain_args,
110 })
111 }
112}
113
114#[derive(Debug, Clone, Serialize, Deserialize)]
115#[serde(deny_unknown_fields)]
116pub struct ToolSession {
117 pub start: SessionCommand,
118 pub stop: SessionCommand,
119}
120
121#[derive(Debug, Clone, Serialize, Deserialize)]
122#[serde(
123 rename_all(serialize = "camelCase", deserialize = "snake_case"),
124 deny_unknown_fields
125)]
126pub struct SessionCommand {
127 #[serde(serialize_with = "crate::platform::serialize_program")]
128 pub command: String,
129 pub args: Vec<crate::scope::Argument>,
130 #[serde(default, skip_serializing_if = "Vec::is_empty")]
131 pub execution_paths: Vec<super::LogicalPath>,
132}
133
134impl SessionCommand {
135 pub(super) fn validate(&self) -> Result<(), String> {
136 script(&self.command, &self.args)?;
137 if self.command.contains(['{', '}']) {
138 return Err("Session command must not contain placeholders.".into());
139 }
140 paths(&self.execution_paths, "execution_paths")
141 }
142}
143
144#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
145#[serde(rename_all = "lowercase")]
146pub enum ToolProtocol {
147 Json,
148 Plain,
149}
150
151#[derive(Debug, Clone, Serialize, Deserialize)]
152#[serde(deny_unknown_fields)]
153pub struct BuiltinTool {
154 pub builtin: Builtin,
155 #[serde(
156 default,
157 deserialize_with = "present",
158 skip_serializing_if = "Option::is_none"
159 )]
160 pub args: Option<Vec<String>>,
161 #[serde(
162 default,
163 deserialize_with = "present",
164 skip_serializing_if = "Option::is_none"
165 )]
166 pub description: Option<String>,
167}
168
169pub use artifactize_tools::Builtin;
170
171impl AgentTool {
172 pub(super) fn validate(&self, schemas: &mut super::schemas::Schemas) -> Result<(), String> {
174 match self {
175 Self::Command(tool) => {
176 description(&tool.description)?;
177 script(&tool.command, &tool.args)?;
178 if tool.command.contains(['{', '}']) {
179 return Err("Tool command must not contain placeholders.".into());
180 }
181 paths(&tool.execution_paths, "execution_paths")?;
182 schemas.check(&tool.input_schema, |schema| {
183 crate::tools::schema::compile(schema).map(drop)
184 })
185 }
186 Self::Builtin(tool) => {
187 if let Some(value) = &tool.description {
188 description(value)?;
189 }
190 artifactize_tools::builtin::validate_args(
191 tool.builtin,
192 tool.args.as_deref(),
193 false,
194 )?;
195 if let Some(args) = &tool.args {
196 validate_agent_target(tool.builtin, args)?;
197 }
198 Ok(())
199 }
200 }
201 }
202 pub fn input_schema(&self) -> Value {
203 match self {
204 Self::Command(tool) => Value::clone(&tool.input_schema),
205 Self::Builtin(tool) => match &tool.args {
206 Some(args) => crate::tools::builtin::fixed_schema(tool.builtin, args),
207 None => crate::tools::builtin::input_schema(tool.builtin),
208 },
209 }
210 }
211}
212
213#[derive(Debug, Clone, Serialize)]
214#[serde(untagged)]
215pub enum HumanTool {
216 Command(HumanCommandTool),
217 Builtin(HumanBuiltinTool),
218 Viewer(HumanViewerTool),
219}
220
221impl<'de> Deserialize<'de> for HumanTool {
222 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
223 use serde::de::Error;
224 let value = Value::deserialize(deserializer)?;
225 if value.get("kind").and_then(Value::as_str) == Some("viewer") {
226 serde_json::from_value(value).map(Self::Viewer)
227 } else if value.get("builtin").is_some() {
228 serde_json::from_value(value).map(Self::Builtin)
229 } else {
230 serde_json::from_value(value).map(Self::Command)
231 }
232 .map_err(D::Error::custom)
233 }
234}
235
236#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
237#[serde(deny_unknown_fields)]
238pub struct HumanViewerTool {
239 pub kind: ViewerKind,
240 pub description: String,
241}
242
243#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
244#[serde(rename_all = "lowercase")]
245pub enum ViewerKind {
246 Viewer,
247}
248
249#[derive(Debug, Clone, Serialize, Deserialize)]
250#[serde(
251 rename_all(serialize = "camelCase", deserialize = "snake_case"),
252 deny_unknown_fields
253)]
254pub struct HumanCommandTool {
255 pub description: String,
256 pub kind: HumanToolKind,
257 #[serde(serialize_with = "crate::platform::serialize_program")]
258 pub command: String,
259 #[serde(deserialize_with = "crate::scope::human_arguments")]
260 pub args: Vec<crate::scope::Argument>,
261 #[serde(
262 default,
263 deserialize_with = "timeout",
264 serialize_with = "super::validation::milliseconds::serialize",
265 skip_serializing_if = "Option::is_none"
266 )]
267 pub timeout_ms: Option<std::time::Duration>,
268}
269
270#[derive(Debug, Clone)]
271pub struct HumanBuiltinTool {
272 pub builtin: Builtin,
273 pub description: String,
274 pub args: Vec<crate::scope::Argument>,
275}
276
277impl<'de> Deserialize<'de> for HumanBuiltinTool {
278 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
279 use serde::de::Error;
280 #[derive(Deserialize)]
281 #[serde(deny_unknown_fields)]
282 struct Declaration {
283 builtin: Builtin,
284 #[serde(default, deserialize_with = "present")]
285 description: Option<String>,
286 #[serde(default, deserialize_with = "present")]
287 kind: Option<HumanToolKind>,
288 #[serde(deserialize_with = "crate::scope::human_arguments")]
289 args: Vec<crate::scope::Argument>,
290 }
291 let declaration = Declaration::deserialize(deserializer)?;
292 let args: Vec<String> = declaration.args.iter().map(ToString::to_string).collect();
293 artifactize_tools::builtin::validate_args(declaration.builtin, Some(&args), true)
294 .map_err(D::Error::custom)?;
295 let kind = if matches!(declaration.builtin, Builtin::Open | Builtin::Graph) {
296 HumanToolKind::Launch
297 } else {
298 HumanToolKind::Output
299 };
300 if declaration.kind.is_some_and(|declared| declared != kind) {
301 return Err(D::Error::custom(
302 "Human builtin kind disagrees with its tool.",
303 ));
304 }
305 Ok(Self {
306 builtin: declaration.builtin,
307 description: declaration.description.unwrap_or_else(|| {
308 crate::tools::builtin::fixed_description(declaration.builtin, &args).into()
309 }),
310 args: declaration.args,
311 })
312 }
313}
314
315#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
316#[serde(rename_all = "lowercase")]
317pub enum HumanToolKind {
318 Launch,
319 Output,
320 Viewer,
321}
322
323impl HumanTool {
324 pub fn description(&self) -> &str {
325 match self {
326 Self::Command(tool) => &tool.description,
327 Self::Builtin(tool) => &tool.description,
328 Self::Viewer(tool) => &tool.description,
329 }
330 }
331 pub fn kind(&self) -> HumanToolKind {
332 match self {
333 Self::Command(tool) => tool.kind,
334 Self::Builtin(tool) => tool.kind(),
335 Self::Viewer(_) => HumanToolKind::Viewer,
336 }
337 }
338 pub(super) fn validate(&self) -> Result<(), String> {
339 description(self.description())?;
340 match self {
341 Self::Viewer(_) => {}
342 Self::Command(tool) => {
343 script(&tool.command, &tool.args)?;
344 if tool.command.contains(['{', '}']) {
345 return Err("Tool command must not contain placeholders.".into());
346 }
347 for argument in &tool.args {
348 crate::scope::validate_human_argument(argument)
349 .map_err(|error| error.to_string())?;
350 }
351 }
352 Self::Builtin(tool) => {
353 for argument in &tool.args {
354 crate::scope::validate_human_argument(argument)
355 .map_err(|error| error.to_string())?;
356 }
357 if !matches!(tool.builtin, Builtin::Help | Builtin::Graph)
358 && let crate::scope::Argument::Literal(target) = &tool.args[0]
359 && !(tool.builtin == Builtin::Open
360 && artifactize_tools::builtin::is_url(target))
361 {
362 artifactize_tools::scope::logical_path(target)
363 .map_err(|error| error.to_string())?;
364 }
365 if tool.builtin == Builtin::Help
366 && tool
367 .args
368 .iter()
369 .any(|arg| matches!(arg, crate::scope::Argument::Reference { .. }))
370 {
371 return Err(
372 "Help args are literal program/subcommand names, not path placeholders."
373 .into(),
374 );
375 }
376 }
377 }
378 Ok(())
379 }
380}
381
382fn validate_agent_target(builtin: Builtin, args: &[String]) -> Result<(), String> {
383 if matches!(builtin, Builtin::Graph | Builtin::Declarations) {
384 return Ok(());
385 }
386 if builtin == Builtin::Help {
387 if args.iter().any(|arg| arg.contains(['{', '}'])) {
388 return Err("Help args are literal program/subcommand names.".into());
389 }
390 return Ok(());
391 }
392 artifactize_tools::scope::logical_path(&args[0]).map_err(|error| error.to_string())
393}
394
395fn empty_schema() -> Value {
396 serde_json::json!({"type":"object", "additionalProperties":false})
397}
398
399pub(super) fn description(value: &str) -> Result<(), String> {
400 text(value, "Tool description")?;
401 if value.encode_utf16().count() > MAX_DESCRIPTION_CHARS
402 || value.replace("{artifactName}", "").contains(['{', '}'])
403 {
404 return Err(
405 "Tool description is limited to 4000 characters and supports only {artifactName}."
406 .into(),
407 );
408 }
409 Ok(())
410}
411
412impl HumanBuiltinTool {
413 pub fn kind(&self) -> HumanToolKind {
414 if matches!(self.builtin, Builtin::Open | Builtin::Graph) {
415 HumanToolKind::Launch
416 } else {
417 HumanToolKind::Output
418 }
419 }
420}
421impl Serialize for HumanBuiltinTool {
422 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
423 #[derive(Serialize)]
424 struct Stored<'a> {
425 builtin: Builtin,
426 description: &'a str,
427 kind: HumanToolKind,
428 args: &'a [crate::scope::Argument],
429 }
430 Stored {
431 builtin: self.builtin,
432 description: &self.description,
433 kind: self.kind(),
434 args: &self.args,
435 }
436 .serialize(serializer)
437 }
438}