artifactize-core 0.13.0

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
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
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Bound serialized declarations before validating or sending tool schemas to a provider.
const MAX_DECLARATION_BYTES: usize = 8 * 1024 * 1024;
/// Keep descriptions usable in provider tool listings, measured as JSON client UTF-16 units.
const MAX_DESCRIPTION_CHARS: usize = 4000;

use super::validation::{paths, present, script, text, timeout};

#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum AgentTool {
    Command(CommandTool),
    Builtin(BuiltinTool),
}

impl<'de> Deserialize<'de> for AgentTool {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        use serde::de::Error;
        let value = Value::deserialize(deserializer)?;
        if value.get("builtin").is_some() {
            serde_json::from_value(value).map(Self::Builtin)
        } else {
            serde_json::from_value(value).map(Self::Command)
        }
        .map_err(D::Error::custom)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(
    rename_all(serialize = "camelCase", deserialize = "snake_case"),
    deny_unknown_fields,
    try_from = "CommandToolInput"
)]
pub struct CommandTool {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session: Option<super::ToolOperationName>,
    pub description: String,
    #[serde(default = "empty_schema")]
    pub input_schema: Value,
    pub protocol: ToolProtocol,
    pub command: String,
    pub args: Vec<crate::scope::Argument>,
    #[serde(
        default,
        deserialize_with = "timeout",
        serialize_with = "super::validation::milliseconds::serialize",
        skip_serializing_if = "Option::is_none"
    )]
    pub timeout_ms: Option<std::time::Duration>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub execution_paths: Vec<super::LogicalPath>,
    #[serde(skip)]
    pub(crate) plain_args: Vec<super::plain::PlainArgument>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(
    rename_all(serialize = "camelCase", deserialize = "snake_case"),
    deny_unknown_fields
)]
struct CommandToolInput {
    #[serde(default)]
    pub session: Option<super::ToolOperationName>,
    pub description: String,
    #[serde(default = "empty_schema")]
    pub input_schema: Value,
    pub protocol: ToolProtocol,
    pub command: String,
    pub args: Vec<crate::scope::Argument>,
    #[serde(
        default,
        deserialize_with = "timeout",
        serialize_with = "super::validation::milliseconds::serialize",
        skip_serializing_if = "Option::is_none"
    )]
    pub timeout_ms: Option<std::time::Duration>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub execution_paths: Vec<super::LogicalPath>,
}

impl TryFrom<CommandToolInput> for CommandTool {
    type Error = String;
    fn try_from(input: CommandToolInput) -> Result<Self, Self::Error> {
        let plain_args = if input.protocol == ToolProtocol::Plain {
            input
                .args
                .iter()
                .map(|arg| {
                    super::plain::PlainArgument::parse(&arg.to_string(), &input.input_schema)
                })
                .collect::<Result<_, _>>()?
        } else {
            Vec::new()
        };
        Ok(Self {
            session: input.session,
            description: input.description,
            input_schema: input.input_schema,
            protocol: input.protocol,
            command: input.command,
            args: input.args,
            timeout_ms: input.timeout_ms,
            execution_paths: input.execution_paths,
            plain_args,
        })
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ToolSession {
    pub start: SessionCommand,
    pub stop: SessionCommand,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(
    rename_all(serialize = "camelCase", deserialize = "snake_case"),
    deny_unknown_fields
)]
pub struct SessionCommand {
    pub command: String,
    pub args: Vec<crate::scope::Argument>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub execution_paths: Vec<super::LogicalPath>,
}

impl SessionCommand {
    pub(super) fn validate(&self) -> Result<(), String> {
        script(&self.command, &self.args)?;
        if self.command.contains(['{', '}']) {
            return Err("Session command must not contain placeholders.".into());
        }
        paths(&self.execution_paths, "execution_paths")
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ToolProtocol {
    Json,
    Plain,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BuiltinTool {
    pub builtin: Builtin,
    #[serde(
        default,
        deserialize_with = "present",
        skip_serializing_if = "Option::is_none"
    )]
    pub args: Option<Vec<String>>,
    #[serde(
        default,
        deserialize_with = "present",
        skip_serializing_if = "Option::is_none"
    )]
    pub description: Option<String>,
}

pub use artifactize_tools::Builtin;

impl AgentTool {
    pub(super) fn validate(&self) -> Result<(), String> {
        if serde_json::to_vec(self).map_err(|e| e.to_string())?.len() > MAX_DECLARATION_BYTES {
            return Err("Tool declaration exceeds 8 MiB.".into());
        }
        match self {
            Self::Command(tool) => {
                description(&tool.description)?;
                script(&tool.command, &tool.args)?;
                if tool.command.contains(['{', '}']) {
                    return Err("Tool command must not contain placeholders.".into());
                }
                paths(&tool.execution_paths, "execution_paths")?;
                crate::tools::schema::compile(&tool.input_schema)?;
                Ok(())
            }
            Self::Builtin(tool) => {
                if let Some(value) = &tool.description {
                    description(value)?;
                }
                artifactize_tools::builtin::validate_args(
                    tool.builtin,
                    tool.args.as_deref(),
                    false,
                )?;
                if let Some(args) = &tool.args {
                    validate_agent_target(tool.builtin, args)?;
                }
                Ok(())
            }
        }
    }
    pub fn input_schema(&self) -> Value {
        match self {
            Self::Command(tool) => tool.input_schema.clone(),
            Self::Builtin(tool) => match &tool.args {
                Some(args) => crate::tools::builtin::fixed_schema(tool.builtin, args),
                None => crate::tools::builtin::input_schema(tool.builtin),
            },
        }
    }
}

#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum HumanTool {
    Command(HumanCommandTool),
    Builtin(HumanBuiltinTool),
}

impl<'de> Deserialize<'de> for HumanTool {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        use serde::de::Error;
        let value = Value::deserialize(deserializer)?;
        if value.get("builtin").is_some() {
            serde_json::from_value(value).map(Self::Builtin)
        } else {
            serde_json::from_value(value).map(Self::Command)
        }
        .map_err(D::Error::custom)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(
    rename_all(serialize = "camelCase", deserialize = "snake_case"),
    deny_unknown_fields
)]
pub struct HumanCommandTool {
    pub description: String,
    pub kind: HumanToolKind,
    pub command: String,
    #[serde(deserialize_with = "crate::scope::human_arguments")]
    pub args: Vec<crate::scope::Argument>,
    #[serde(
        default,
        deserialize_with = "timeout",
        serialize_with = "super::validation::milliseconds::serialize",
        skip_serializing_if = "Option::is_none"
    )]
    pub timeout_ms: Option<std::time::Duration>,
}

#[derive(Debug, Clone)]
pub struct HumanBuiltinTool {
    pub builtin: Builtin,
    pub description: String,
    pub args: Vec<crate::scope::Argument>,
}

impl<'de> Deserialize<'de> for HumanBuiltinTool {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        use serde::de::Error;
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct Declaration {
            builtin: Builtin,
            #[serde(default, deserialize_with = "present")]
            description: Option<String>,
            #[serde(default, deserialize_with = "present")]
            kind: Option<HumanToolKind>,
            #[serde(deserialize_with = "crate::scope::human_arguments")]
            args: Vec<crate::scope::Argument>,
        }
        let declaration = Declaration::deserialize(deserializer)?;
        let args: Vec<String> = declaration.args.iter().map(ToString::to_string).collect();
        artifactize_tools::builtin::validate_args(declaration.builtin, Some(&args), true)
            .map_err(D::Error::custom)?;
        let kind = if matches!(declaration.builtin, Builtin::Open | Builtin::Graph) {
            HumanToolKind::Launch
        } else {
            HumanToolKind::Output
        };
        if declaration.kind.is_some_and(|declared| declared != kind) {
            return Err(D::Error::custom(
                "Human builtin kind disagrees with its tool.",
            ));
        }
        Ok(Self {
            builtin: declaration.builtin,
            description: declaration.description.unwrap_or_else(|| {
                crate::tools::builtin::fixed_description(declaration.builtin, &args).into()
            }),
            args: declaration.args,
        })
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum HumanToolKind {
    Launch,
    Output,
}

impl HumanTool {
    pub fn description(&self) -> &str {
        match self {
            Self::Command(tool) => &tool.description,
            Self::Builtin(tool) => &tool.description,
        }
    }
    pub fn kind(&self) -> HumanToolKind {
        match self {
            Self::Command(tool) => tool.kind,
            Self::Builtin(tool) => tool.kind(),
        }
    }
    pub(super) fn validate(&self) -> Result<(), String> {
        description(self.description())?;
        match self {
            Self::Command(tool) => {
                script(&tool.command, &tool.args)?;
                if tool.command.contains(['{', '}']) {
                    return Err("Tool command must not contain placeholders.".into());
                }
                for argument in &tool.args {
                    crate::scope::validate_human_argument(argument)
                        .map_err(|error| error.to_string())?;
                }
            }
            Self::Builtin(tool) => {
                for argument in &tool.args {
                    crate::scope::validate_human_argument(argument)
                        .map_err(|error| error.to_string())?;
                }
                if !matches!(tool.builtin, Builtin::Help | Builtin::Graph)
                    && let crate::scope::Argument::Literal(target) = &tool.args[0]
                    && !(tool.builtin == Builtin::Open
                        && artifactize_tools::builtin::is_url(target))
                {
                    artifactize_tools::scope::logical_path(target)
                        .map_err(|error| error.to_string())?;
                }
                if tool.builtin == Builtin::Help
                    && tool
                        .args
                        .iter()
                        .any(|arg| matches!(arg, crate::scope::Argument::Reference { .. }))
                {
                    return Err(
                        "Help args are literal program/subcommand names, not path placeholders."
                            .into(),
                    );
                }
            }
        }
        Ok(())
    }
}

fn validate_agent_target(builtin: Builtin, args: &[String]) -> Result<(), String> {
    if builtin == Builtin::Graph {
        return Ok(());
    }
    if builtin == Builtin::Help {
        if args.iter().any(|arg| arg.contains(['{', '}'])) {
            return Err("Help args are literal program/subcommand names.".into());
        }
        return Ok(());
    }
    artifactize_tools::scope::logical_path(&args[0]).map_err(|error| error.to_string())
}

fn empty_schema() -> Value {
    serde_json::json!({"type":"object", "additionalProperties":false})
}

pub(super) fn description(value: &str) -> Result<(), String> {
    text(value, "Tool description")?;
    if value.encode_utf16().count() > MAX_DESCRIPTION_CHARS
        || value.replace("{artifactName}", "").contains(['{', '}'])
    {
        return Err(
            "Tool description is limited to 4000 characters and supports only {artifactName}."
                .into(),
        );
    }
    Ok(())
}

impl HumanBuiltinTool {
    pub fn kind(&self) -> HumanToolKind {
        if matches!(self.builtin, Builtin::Open | Builtin::Graph) {
            HumanToolKind::Launch
        } else {
            HumanToolKind::Output
        }
    }
}
impl Serialize for HumanBuiltinTool {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        #[derive(Serialize)]
        struct Stored<'a> {
            builtin: Builtin,
            description: &'a str,
            kind: HumanToolKind,
            args: &'a [crate::scope::Argument],
        }
        Stored {
            builtin: self.builtin,
            description: &self.description,
            kind: self.kind(),
            args: &self.args,
        }
        .serialize(serializer)
    }
}