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