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