1use super::{
4 AgentTool, ArtifactName, BuiltinTool, CommandTool, EvalDeclaration, HumanTool, LogicalPath,
5 MAX_DECLARED_ITEMS, ToolOperationName, ToolSession, artifact_name,
6 eval::declared_evals,
7 identifier,
8 location::{self, Location},
9 schemas, settings,
10 validation::{path, paths, present, script, tags, text, timeout},
11};
12use artifactize_tools::artf::{Masked, mask};
13use serde::{Deserialize, Serialize};
14use serde_json::{Map, Value};
15use std::collections::{BTreeMap, BTreeSet};
16
17#[derive(Debug, Clone, Default, Serialize, Deserialize)]
18#[serde(
19 rename_all(serialize = "camelCase", deserialize = "snake_case"),
20 deny_unknown_fields
21)]
22pub struct Views {
23 #[serde(default)]
24 pub agent_sessions: BTreeMap<ToolOperationName, ToolSession>,
25 #[serde(default)]
26 pub agent_tools: BTreeMap<ToolOperationName, AgentTool>,
27 #[serde(default)]
28 pub human_tools: BTreeMap<ToolOperationName, HumanTool>,
29}
30
31impl Views {
32 fn parse(location: &Location<'_, '_>) -> Result<Self, String> {
33 let mut views = Self::default();
34 for (key, _) in location.table()? {
35 let field = location.child(key.get_ref());
36 match key.get_ref().as_ref() {
37 "agent_sessions" => views.agent_sessions = tool_map(&field, |value, _| value.deserialize())?,
38 "agent_tools" => views.agent_tools = tool_map(&field, |value, tool| {
39 if tool.get("builtin").is_some() {
40 value.deserialize::<BuiltinTool>().map(AgentTool::Builtin)
41 } else {
42 value.deserialize::<CommandTool>().map(AgentTool::Command)
43 }
44 })?,
45 "human_tools" => views.human_tools = tool_map(&field, |value, _| value.deserialize())?,
46 name => return Err(location.key(name).error(format!(
47 "unknown field `{name}`, expected `agent_sessions`, `agent_tools`, or `human_tools`"
48 ))),
49 }
50 }
51 Ok(views)
52 }
53
54 pub(super) fn validate(
55 &self,
56 location: &Location<'_, '_>,
57 schemas: &mut schemas::Schemas,
58 plugin: Option<&super::ArtifactType>,
59 ) -> Result<(), String> {
60 for (name, session) in &self.agent_sessions {
61 let sessions = location.child("agent_sessions");
62 sessions
63 .child(name)
64 .child("start")
65 .check(session.start.validate())?;
66 sessions
67 .child(name)
68 .child("stop")
69 .check(session.stop.validate())?;
70 }
71 for (name, tool) in &self.agent_tools {
72 let tools = location.child("agent_tools");
73 if let AgentTool::Command(tool) = tool
74 && let Some(session) = &tool.session
75 && plugin.is_none()
76 && !self.agent_sessions.contains_key(session)
77 {
78 return Err(tools
79 .child(name)
80 .child("session")
81 .error(format!("Unknown tool session: {session}")));
82 }
83 tools.child(name).check(
84 tool.validate(schemas)
85 .map_err(|e| format!("Tool {name}: {e}")),
86 )?;
87 }
88 for (name, tool) in &self.human_tools {
89 let tools = location.child("human_tools");
90 tools
91 .child(name)
92 .check(tool.validate().map_err(|e| format!("Tool {name}: {e}")))?;
93 }
94 Ok(())
95 }
96
97 pub(super) fn validate_sessions(&self) -> Result<(), String> {
98 for (name, tool) in &self.agent_tools {
99 if let AgentTool::Command(tool) = tool
100 && let Some(session) = &tool.session
101 && !self.agent_sessions.contains_key(session)
102 {
103 return Err(format!(
104 "Agent tool {name}: unknown tool session {session}."
105 ));
106 }
107 }
108 Ok(())
109 }
110}
111
112fn tool_map<T>(
113 location: &Location<'_, '_>,
114 parse: impl Fn(Location<'_, '_>, &toml::de::DeValue<'_>) -> Result<T, String>,
115) -> Result<BTreeMap<ToolOperationName, T>, String> {
116 location
117 .table()?
118 .iter()
119 .map(|(name, value)| {
120 let name = name.get_ref().as_ref();
121 let id = location.key(name).check(name.parse())?;
122 let tool = parse(location.child(name), value.get_ref())?;
123 Ok((id, tool))
124 })
125 .collect()
126}
127
128#[derive(Debug, Clone, Serialize, Deserialize)]
132#[serde(try_from = "Map<String, Value>", into = "Value")]
133pub enum Fingerprint {
134 Graph,
136 Script {
137 command: String,
138 args: Vec<crate::scope::Argument>,
139 files: Vec<LogicalPath>,
141 timeout_ms: Option<std::time::Duration>,
142 },
143 Artifactsum {
144 files: Vec<LogicalPath>,
145 ignore: crate::cache::IgnorePatterns,
146 },
147}
148
149#[derive(Deserialize)]
150#[serde(deny_unknown_fields)]
151struct ScriptForm {
152 script: ScriptFields,
153}
154
155#[derive(Deserialize)]
156#[serde(rename_all = "snake_case", deny_unknown_fields)]
157struct ScriptFields {
158 command: String,
159 args: Vec<crate::scope::Argument>,
160 #[serde(default)]
161 files: Vec<LogicalPath>,
162 #[serde(
163 default,
164 deserialize_with = "timeout",
165 serialize_with = "validation::milliseconds::serialize"
166 )]
167 timeout_ms: Option<std::time::Duration>,
168}
169
170#[derive(Deserialize)]
171#[serde(deny_unknown_fields)]
172struct ArtifactsumForm {
173 #[serde(default = "owner_root")]
174 files: Vec<LogicalPath>,
175 #[serde(default)]
176 ignore: crate::cache::IgnorePatterns,
177}
178
179fn owner_root() -> Vec<LogicalPath> {
180 vec![".".parse().expect("owner root logical path")]
181}
182
183impl Default for Fingerprint {
184 fn default() -> Self {
185 Self::Artifactsum {
186 files: owner_root(),
187 ignore: Default::default(),
188 }
189 }
190}
191
192fn default_fingerprint() -> Option<Fingerprint> {
193 Some(Fingerprint::default())
194}
195
196const INVALID_FINGERPRINT: &str =
197 "fingerprint must be false or an object declaring artifactsum (files, ignore) or a script.";
198const REMOVED_DEPENDENCIES: &str = "fingerprint.dependencies was removed in 0.5: a fingerprint covers only its own Artifact, and an eval's reuse key adds the fingerprints of its children and referenced Artifacts. Remove the field.";
199
200fn declared_fingerprint<'de, D: serde::Deserializer<'de>>(
201 deserializer: D,
202) -> Result<Option<Fingerprint>, D::Error> {
203 use serde::de::Error;
204 match Value::deserialize(deserializer)? {
205 Value::Bool(false) => Ok(None),
206 Value::Object(object) => Fingerprint::try_from(object)
207 .map(Some)
208 .map_err(D::Error::custom),
209 _ => Err(D::Error::custom(INVALID_FINGERPRINT)),
210 }
211}
212
213impl From<ScriptForm> for Fingerprint {
214 fn from(form: ScriptForm) -> Self {
215 let ScriptFields {
216 command,
217 args,
218 files,
219 timeout_ms,
220 } = form.script;
221 Self::Script {
222 command,
223 args,
224 files,
225 timeout_ms,
226 }
227 }
228}
229
230impl From<ArtifactsumForm> for Fingerprint {
231 fn from(form: ArtifactsumForm) -> Self {
232 let ArtifactsumForm { files, ignore } = form;
233 Self::Artifactsum { files, ignore }
234 }
235}
236
237impl TryFrom<Map<String, Value>> for Fingerprint {
238 type Error = serde_json::Error;
239
240 fn try_from(object: Map<String, Value>) -> Result<Self, Self::Error> {
241 Ok(if object.contains_key("script") {
242 serde_json::from_value::<ScriptForm>(Value::Object(object))?.into()
243 } else {
244 if object.contains_key("dependencies") {
245 return Err(serde::de::Error::custom(REMOVED_DEPENDENCIES));
246 }
247 serde_json::from_value::<ArtifactsumForm>(Value::Object(object))?.into()
248 })
249 }
250}
251
252impl From<Fingerprint> for Value {
253 fn from(fingerprint: Fingerprint) -> Self {
254 match fingerprint {
255 Fingerprint::Graph => serde_json::json!({"graph": true}),
256 Fingerprint::Script {
257 command,
258 args,
259 files,
260 timeout_ms,
261 } => serde_json::json!({
262 "script": {
263 "command": crate::platform::program_text(&command),
264 "args": args,
265 "files": files,
266 "timeoutMs": timeout_ms.map(|value| value.as_millis()),
267 },
268 }),
269 Fingerprint::Artifactsum { files, ignore } => {
270 serde_json::json!({"files": files, "ignore": ignore})
271 }
272 }
273 }
274}
275
276impl Fingerprint {
277 fn parse(
278 location: &Location<'_, '_>,
279 value: &toml::de::DeValue<'_>,
280 ) -> Result<Option<Self>, String> {
281 use toml::de::DeValue;
282 match value {
283 DeValue::Boolean(false) => Ok(None),
284 DeValue::Table(fields) if fields.contains_key("script") => location
285 .deserialize::<ScriptForm>()
286 .map(|form| Some(form.into())),
287 DeValue::Table(fields) if fields.contains_key("dependencies") => {
288 Err(location.child("dependencies").error(REMOVED_DEPENDENCIES))
289 }
290 DeValue::Table(_) => location
291 .deserialize::<ArtifactsumForm>()
292 .map(|form| Some(form.into())),
293 _ => Err(location.error(INVALID_FINGERPRINT)),
294 }
295 }
296
297 pub fn kind(&self) -> crate::types::FingerprintKind {
298 match self {
299 Self::Graph => crate::types::FingerprintKind::Graph,
300 Self::Artifactsum { .. } => crate::types::FingerprintKind::Artifactsum,
301 Self::Script { .. } => crate::types::FingerprintKind::Script,
302 }
303 }
304
305 fn validate(&self, location: &Location<'_, '_>) -> Result<(), String> {
306 match self {
307 Self::Graph => Ok(()),
308 Self::Script {
309 command,
310 args,
311 files,
312 ..
313 } => {
314 location.child("script").check(script(command, args))?;
315 location
316 .child("script")
317 .child("files")
318 .check(paths(files, "fingerprint.script.files"))
319 }
320 Self::Artifactsum { files, .. } => {
321 if files.is_empty()
322 || files.len() > MAX_DECLARED_ITEMS
323 || files.iter().collect::<BTreeSet<_>>().len() != files.len()
324 {
325 return Err(location.child("files").error(
326 "fingerprint.files must contain 1–64 unique owner-relative paths.",
327 ));
328 }
329 for file in files.iter().filter(|file| *file != ".") {
330 location.child("files").check(
331 path(file).map_err(|message| format!("fingerprint.files: {message}")),
332 )?;
333 }
334 Ok(())
335 }
336 }
337 }
338}
339
340#[derive(Debug, Clone, Deserialize)]
341#[serde(rename_all = "snake_case", deny_unknown_fields)]
342pub struct ArtifactDeclaration {
343 pub name: ArtifactName,
344 #[serde(rename = "type")]
345 pub type_name: Option<super::ArtifactType>,
346 #[serde(default)]
347 pub tags: Vec<String>,
348 #[serde(default, deserialize_with = "declared_evals")]
349 pub evals: Vec<EvalDeclaration>,
350 #[serde(default)]
351 pub views: Views,
352 #[serde(default, deserialize_with = "present")]
353 pub basis: Option<bool>,
354 #[serde(
355 default = "default_fingerprint",
356 deserialize_with = "declared_fingerprint"
357 )]
358 pub fingerprint: Option<Fingerprint>,
359 #[serde(default, deserialize_with = "present")]
361 pub select: Option<Vec<LogicalPath>>,
362 #[serde(default, deserialize_with = "present")]
364 pub parts: Option<Vec<ArtifactName>>,
365}
366
367impl ArtifactDeclaration {
368 fn share(&mut self, schemas: &mut schemas::Schemas) {
370 for tool in self.views.agent_tools.values_mut() {
371 if let AgentTool::Command(tool) = tool {
372 tool.input_schema = schemas.tool(&tool.input_schema);
373 }
374 }
375 for eval in &mut self.evals {
376 eval.share(schemas);
377 }
378 }
379
380 fn validate(
381 &self,
382 location: &Location<'_, '_>,
383 schemas: &mut schemas::Schemas,
384 ) -> Result<(), String> {
385 location
386 .child("name")
387 .check(artifact_name(&self.name, "Artifact name"))?;
388 location.child("tags").check(tags(&self.tags))?;
389 for eval in &self.evals {
390 eval.validate(&location.child("evals").key(&eval.id), schemas)
391 .map_err(|message| format!("Eval {}: {message}", eval.id))?;
392 }
393 if self.basis == Some(true) && !self.evals.is_empty() {
394 return Err(location
395 .child("basis")
396 .error(format!("Basis Artifact {} cannot own Evals.", self.name)));
397 }
398 self.views
399 .validate(&location.child("views"), schemas, self.type_name.as_ref())?;
400 if self.type_name.is_none()
401 && self
402 .views
403 .human_tools
404 .values()
405 .any(|tool| matches!(tool, HumanTool::Viewer(_)))
406 {
407 return Err(location
408 .child("views")
409 .child("human_tools")
410 .error("A viewer Human tool needs an Artifact type with a viewer entry."));
411 }
412 if let Some(fingerprint) = &self.fingerprint {
413 fingerprint.validate(&location.child("fingerprint"))?;
414 }
415 if let Some(parts) = &self.parts {
416 let parts_location = location.child("parts");
417 if parts.is_empty()
418 || parts.len() > MAX_DECLARED_ITEMS
419 || parts.iter().collect::<BTreeSet<_>>().len() != parts.len()
420 {
421 return Err(parts_location.error("parts must name 1–64 unique Artifacts."));
422 }
423 if parts.contains(&self.name) {
424 return Err(
425 parts_location.error(format!("{} cannot be a part of itself.", self.name))
426 );
427 }
428 }
429 if let Some(select) = &self.select {
430 let select_location = location.child("select");
431 if select.is_empty()
432 || select.len() > MAX_DECLARED_ITEMS
433 || select.iter().collect::<BTreeSet<_>>().len() != select.len()
434 {
435 return Err(select_location
436 .error("select must contain 1–64 unique paths relative to the declaration."));
437 }
438 for selected in select {
439 select_location
440 .check(path(selected).map_err(|message| format!("select: {message}")))?;
441 }
442 }
443 Ok(())
444 }
445}
446
447pub fn parse_declaration(source: &str) -> Result<ArtifactDeclaration, String> {
449 let masked = mask(source)
450 .map_err(|error| location::positioned_message(source, error.offset, error.message))?;
451 let table = toml::de::DeTable::parse(&masked.toml)
452 .map_err(|error| location::toml_error(source, &masked, error))?;
453 parse_declaration_table(
454 source,
455 &masked,
456 &settings::Settings::default(),
457 &mut schemas::Schemas::default(),
458 None,
459 table,
460 )
461}
462
463pub(super) fn parse_declaration_table(
464 source: &str,
465 masked: &Masked,
466 settings: &settings::Settings,
467 schemas: &mut schemas::Schemas,
468 name: Option<&ArtifactName>,
469 mut table: toml::Spanned<toml::de::DeTable<'_>>,
470) -> Result<ArtifactDeclaration, String> {
471 if let Some(name) = name {
472 table.get_mut().remove("path");
473 table.get_mut().remove("annotations");
474 table.get_mut().insert(
475 toml::Spanned::new(0..0, std::borrow::Cow::Borrowed("name")),
476 toml::Spanned::new(
477 0..0,
478 toml::de::DeValue::String(std::borrow::Cow::Owned(name.to_string())),
479 ),
480 );
481 }
482 let span = table.span();
483 let document = toml::Spanned::new(span, toml::de::DeValue::Table(table.into_inner()));
484 let location = Location::root_masked(source, &document, Some(masked));
485 for (key, value) in document.get_ref().as_table().unwrap() {
486 reject_non_json_values(value, key.get_ref().as_ref(), source, |offset| {
487 masked.original_offset(offset)
488 })?;
489 }
490 if document.get_ref().get("family").is_some() {
491 return Err(location
492 .child("family")
493 .error("family was removed in 0.9.0; declare each instance as its own Artifact."));
494 }
495 for key in ["stale_key", "stale"] {
496 if document.get_ref().get(key).is_some() {
497 return Err(location.child(key).error(format!(
498 "{key} was renamed to fingerprint: use fingerprint = {{ files = [\".\"], ignore = [] }} or [fingerprint.script]."
499 )));
500 }
501 }
502 if let Some(evals) = document
503 .get_ref()
504 .get("evals")
505 .and_then(|value| value.get_ref().as_table())
506 {
507 for (id, eval) in evals {
508 if eval.get_ref().get("gate").is_some() {
509 return Err(location
510 .child("evals")
511 .child(id.get_ref())
512 .child("gate")
513 .error(format!(
514 "Eval {}: gate was removed in 0.16.0; remove it. A Human sign-off never holds up other evals.",
515 id.get_ref()
516 )));
517 }
518 if eval.get_ref().get("result_check").is_some() {
519 return Err(location
520 .child("evals")
521 .child(id.get_ref())
522 .child("result_check")
523 .error(format!(
524 "Eval {}: result_check was removed in 0.6.0; remove it. The review's tool calls are in its saved session (artifactize session show).",
525 id.get_ref()
526 )));
527 }
528 }
529 }
530 validate_identity_locations(&location, &document)?;
533 let mut body = document.get_ref().as_table().unwrap().clone();
536 let mut consumed = vec![false; masked.invocations().len()];
537 let evals = if body.remove("evals").is_some() {
538 EvalDeclaration::parse_map(
539 &location.child("evals"),
540 source,
541 masked,
542 settings,
543 &mut consumed,
544 )?
545 } else {
546 Vec::new()
547 };
548 if let Some(invocation) = masked
549 .invocations()
550 .iter()
551 .zip(consumed)
552 .find_map(|(invocation, used)| (!used).then_some(invocation))
553 {
554 return Err(location::positioned_message(
555 source,
556 invocation.span.start,
557 format!(
558 "Profile alias `!{}` can be used only as an eval profile or profile variant.",
559 invocation.name
560 ),
561 ));
562 }
563 let views = if body.remove("views").is_some() {
564 Views::parse(&location.child("views"))?
565 } else {
566 Views::default()
567 };
568 let fingerprint = match body
569 .remove("fingerprint")
570 .as_ref()
571 .map(toml::Spanned::get_ref)
572 {
573 Some(value) => Fingerprint::parse(&location.child("fingerprint"), value)?,
574 None => default_fingerprint(),
575 };
576 let mut declaration = ArtifactDeclaration::deserialize(toml::de::ValueDeserializer::from(
577 toml::Spanned::new(document.span(), toml::de::DeValue::Table(body)),
578 ))
579 .map_err(|error| location::toml_error(source, masked, error))?;
580 declaration.evals = evals;
581 declaration.views = views;
582 declaration.fingerprint = fingerprint;
583 declaration.share(schemas);
584 declaration.validate(&location, schemas)?;
585 Ok(declaration)
586}
587
588fn validate_identity_locations(
589 location: &Location<'_, '_>,
590 document: &toml::Spanned<toml::de::DeValue<'_>>,
591) -> Result<(), String> {
592 use toml::de::DeValue;
593 if let Some(name) = document.get_ref().get("name")
594 && let DeValue::String(name) = name.get_ref()
595 {
596 location
597 .child("name")
598 .check(artifact_name(name, "Artifact name"))?;
599 }
600 if let Some(evals) = document
601 .get_ref()
602 .get("evals")
603 .and_then(|value| value.get_ref().as_table())
604 {
605 for (id, eval) in evals {
606 let eval_location = location.child("evals").key(id.get_ref());
607 eval_location.check(identifier(id.get_ref(), "Eval id"))?;
608 if let Some(model) = eval
609 .get_ref()
610 .get("profile")
611 .and_then(|profile| profile.get_ref().get("model"))
612 && let DeValue::String(model) = model.get_ref()
613 {
614 eval_location
615 .child("profile")
616 .child("model")
617 .check(text(model, "Agent profile model"))?;
618 }
619 if let Some(variants) = eval
620 .get_ref()
621 .get("profile_variants")
622 .and_then(|value| value.get_ref().as_table())
623 {
624 for (name, profile) in variants {
625 let variant = eval_location.child("profile_variants").key(name.get_ref());
626 variant.check(identifier(name.get_ref(), "Profile variant name"))?;
627 if let Some(model) = profile.get_ref().get("model")
628 && let DeValue::String(model) = model.get_ref()
629 {
630 variant
631 .child("model")
632 .check(text(model, "Agent profile model"))?;
633 }
634 }
635 }
636 }
637 }
638 Ok(())
639}
640
641pub(super) fn reject_non_json_values(
643 value: &toml::Spanned<toml::de::DeValue<'_>>,
644 path: &str,
645 source: &str,
646 map_offset: impl Copy + Fn(usize) -> usize,
647) -> Result<(), String> {
648 use toml::de::DeValue;
649 let diagnostic =
650 |message| location::positioned(source, map_offset(value.span().start), path, message);
651 match value.get_ref() {
652 DeValue::Datetime(_) => Err(diagnostic(
653 "TOML date/time values have no JSON equivalent; use a quoted string.",
654 )),
655 DeValue::Float(number)
656 if matches!(
657 number.as_str(),
658 "inf" | "+inf" | "-inf" | "nan" | "+nan" | "-nan"
659 ) =>
660 {
661 Err(diagnostic(
662 "TOML non-finite floats have no JSON equivalent.",
663 ))
664 }
665 DeValue::Array(items) => {
666 for (index, item) in items.iter().enumerate() {
667 reject_non_json_values(item, &format!("{path}[{index}]"), source, map_offset)?;
668 }
669 Ok(())
670 }
671 DeValue::Table(table) => {
672 for (key, value) in table {
673 reject_non_json_values(
674 value,
675 &format!("{path}.{}", key.get_ref()),
676 source,
677 map_offset,
678 )?;
679 }
680 Ok(())
681 }
682 _ => Ok(()),
683 }
684}