1pub mod log;
4
5use std::{collections::BTreeMap, ffi::OsString, path::PathBuf};
6
7use serde::{Deserialize, Serialize};
8use tokio_util::sync::CancellationToken;
9
10use crate::{
11 config::{HumanTool, HumanToolKind, Profile, RepoConfig},
12 process, runtime,
13 scope::{self, Scope},
14};
15
16use super::{DEFAULT_TIMEOUT, executable};
17use log::{End, Run, Stream};
18
19const TEXT_LIMIT: usize = 64 * 1024;
21
22#[derive(Debug, Clone, Serialize)]
23#[serde(rename_all = "camelCase")]
24pub struct ToolDefinition {
25 pub name: crate::config::ToolName,
26 pub artifact_id: crate::config::ArtifactName,
27 pub description: String,
28 pub kind: HumanToolKind,
29}
30
31#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
32#[serde(tag = "type", rename_all = "lowercase", deny_unknown_fields)]
33pub enum Content {
34 Text { text: String },
35 Launch { launched: bool },
36}
37
38#[derive(Debug, Clone, PartialEq)]
41pub struct ErrorText(artifactize_tools::result::ContentBlocks<Content>);
42
43impl ErrorText {
44 fn new(content: Vec<Content>) -> Result<Self, String> {
45 for block in &content {
46 let Content::Text { text } = block else {
47 return Err("Human tool error must contain only text blocks".into());
48 };
49 artifactize_tools::result::ErrorMessage::new(text.clone())
50 .map_err(|error| error.to_string())?;
51 }
52 artifactize_tools::result::ContentBlocks::new(content)
53 .map(Self)
54 .map_err(|error| error.to_string())
55 }
56}
57
58#[derive(Debug, Clone, PartialEq)]
59pub enum ToolResult {
60 Success(artifactize_tools::result::ContentBlocks<Content>),
61 Error(ErrorText),
62}
63
64impl ToolResult {
65 pub fn success(content: Content) -> Self {
66 Self::success_blocks(vec![content])
67 }
68
69 fn success_blocks(content: Vec<Content>) -> Self {
70 Self::Success(
71 artifactize_tools::result::ContentBlocks::new(content)
72 .expect("Human output always has one or two blocks"),
73 )
74 }
75
76 pub fn error(message: impl Into<String>) -> Self {
78 let message = artifactize_tools::result::ErrorMessage::diagnostic(message);
79 Self::error_blocks(vec![Content::Text {
80 text: message.as_str().to_owned(),
81 }])
82 }
83
84 fn error_blocks(content: Vec<Content>) -> Self {
85 Self::Error(ErrorText::new(content).expect("Human failures contain nonblank text"))
86 }
87
88 pub fn is_error(&self) -> bool {
89 matches!(self, Self::Error(_))
90 }
91
92 pub fn content(&self) -> &[Content] {
93 match self {
94 Self::Success(content) => content.as_slice(),
95 Self::Error(content) => content.0.as_slice(),
96 }
97 }
98}
99
100impl Serialize for ToolResult {
101 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
102 use serde::ser::SerializeStruct;
103 let mut result = serializer.serialize_struct("ToolResult", 2)?;
105 result.serialize_field("content", self.content())?;
106 result.serialize_field("isError", &self.is_error())?;
107 result.end()
108 }
109}
110
111impl<'de> Deserialize<'de> for ToolResult {
112 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
113 #[derive(Deserialize)]
114 #[serde(rename_all = "camelCase", deny_unknown_fields)]
115 struct SavedResult {
116 content: Vec<Content>,
117 is_error: bool,
118 }
119 let saved = SavedResult::deserialize(deserializer)?;
120 if saved.is_error {
121 ErrorText::new(saved.content)
122 .map(Self::Error)
123 .map_err(serde::de::Error::custom)
124 } else {
125 artifactize_tools::result::ContentBlocks::new(saved.content)
126 .map(Self::Success)
127 .map_err(serde::de::Error::custom)
128 }
129 }
130}
131
132#[derive(Debug, Clone, PartialEq, Eq)]
134pub struct CommandLine {
135 pub repo: PathBuf,
136 pub kind: HumanToolKind,
137 pub program: OsString,
138 pub args: Vec<String>,
139 pub(crate) shown_args: Vec<String>,
140 pub cwd: PathBuf,
141}
142
143struct RegisteredTool<'a> {
144 definition: ToolDefinition,
145 declaration: &'a HumanTool,
146}
147
148pub struct Registry<'a> {
150 config: &'a RepoConfig,
151 scope: Scope<'a>,
152 tools: BTreeMap<crate::config::ToolName, RegisteredTool<'a>>,
153}
154
155impl<'a> Registry<'a> {
156 pub fn new(config: &'a RepoConfig, eval_id: &crate::types::EvalId) -> Result<Self, String> {
157 let eval = config
158 .evals
159 .iter()
160 .find(|eval| &eval.id == eval_id)
161 .ok_or_else(|| format!("Unknown eval: {eval_id}"))?;
162 if !matches!(eval.declaration.profile(), Profile::Human {}) {
163 return Err("Human tools require a Human eval.".into());
164 }
165 Self::with_scope(
166 config,
167 scope::eval_scope(config, eval).map_err(|e| e.to_string())?,
168 )
169 }
170
171 pub fn for_artifact(
172 config: &'a RepoConfig,
173 artifact_id: &crate::config::ArtifactName,
174 ) -> Result<Self, String> {
175 Self::with_scope(
176 config,
177 scope::artifact_scope(config, &[artifact_id]).map_err(|e| e.to_string())?,
178 )
179 }
180
181 fn with_scope(config: &'a RepoConfig, scope: Scope<'a>) -> Result<Self, String> {
182 let mut tools = BTreeMap::new();
183 for (id, artifact) in &scope.artifacts {
184 for (operation, declaration) in &artifact.views.human_tools {
185 let name: crate::config::ToolName = format!("{operation}_{}", id)
186 .parse()
187 .expect("validated tool and Artifact names");
188 let entry = RegisteredTool {
189 definition: ToolDefinition {
190 name: name.clone(),
191 artifact_id: artifact.name.clone(),
192 description: declaration.description().replace("{artifactName}", id),
193 kind: declaration.kind(),
194 },
195 declaration,
196 };
197 if tools.insert(name.clone(), entry).is_some() {
198 return Err(format!("Artifact tool names collide: {name}"));
199 }
200 }
201 }
202 Ok(Self {
203 config,
204 scope,
205 tools,
206 })
207 }
208
209 pub fn list(&self) -> impl Iterator<Item = &ToolDefinition> {
210 self.tools.values().map(|tool| &tool.definition)
211 }
212
213 pub fn is_command(&self, name: &crate::config::ToolName) -> bool {
214 self.tools
215 .get(name)
216 .is_some_and(|tool| matches!(tool.declaration, HumanTool::Command(_)))
217 }
218
219 pub fn preflight(&self, name: &crate::config::ToolName) -> Result<(), String> {
220 let tool = self
221 .tools
222 .get(name)
223 .ok_or("Unknown registered Human tool.")?;
224 let owner = &tool.definition.artifact_id;
225 self.scope
226 .resolve_input(&self.config.root, owner, "")
227 .map_err(|e| e.to_string())?;
228 match tool.declaration {
229 HumanTool::Command(declaration) => {
230 super::preflight_executable(
231 &self.config.root,
232 &self.scope,
233 owner,
234 &declaration.command,
235 )?;
236 scope::resolve_human_argv(self.config, &self.scope, owner, &declaration.args)
237 .map_err(|error| error.to_string())?;
238 }
239 HumanTool::Builtin(declaration) => {
240 scope::builtin_args(self.config, &self.scope, owner, declaration)
241 .map_err(|error| error.to_string())?;
242 }
243 }
244 Ok(())
245 }
246
247 pub fn command(&self, name: &crate::config::ToolName) -> Result<CommandLine, String> {
249 let tool = self
250 .tools
251 .get(name)
252 .ok_or("Unknown registered Human tool.")?;
253 let owner = &tool.definition.artifact_id;
254 let HumanTool::Command(declaration) = tool.declaration else {
255 return Err("Builtin Human tools have no executable command line.".into());
256 };
257 for artifact in self.scope.artifacts.values() {
258 scope::validate_file_target(&self.config.root, artifact)
259 .map_err(|error| error.to_string())?;
260 }
261 let cwd = scope::scoped_path(&self.config.root, self.config.artifacts[owner].folder())
262 .map_err(|e| e.to_string())?;
263 let program = executable(&self.config.root, &self.scope, owner, &declaration.command)
264 .map_err(|()| "Tool executable path is unavailable or outside scope.".to_owned())?;
265 let args = scope::resolve_human_argv(self.config, &self.scope, owner, &declaration.args)
266 .map_err(|e| e.to_string())?;
267 Ok(CommandLine {
268 repo: self.config.root.clone(),
269 kind: declaration.kind,
270 program,
271 args: args.iter().map(|arg| arg.native()).collect(),
272 shown_args: args.iter().map(|arg| arg.shown()).collect(),
273 cwd,
274 })
275 }
276
277 pub async fn call(
278 &self,
279 name: &crate::config::ToolName,
280 cancellation: CancellationToken,
281 ) -> ToolResult {
282 self.call_logged(name, cancellation, Run::unwatched()).await
283 }
284
285 pub async fn call_logged(
288 &self,
289 name: &crate::config::ToolName,
290 cancellation: CancellationToken,
291 run: Run,
292 ) -> ToolResult {
293 let failed = |run: Run, message: String| {
294 run.end(End::Failed(message.clone()));
295 ToolResult::error(message)
296 };
297 let Some(tool) = self.tools.get(name) else {
298 return failed(run, "Unknown registered Human tool.".into());
299 };
300 if cancellation.is_cancelled() {
301 run.end(End::Cancelled);
302 return ToolResult::error("Human tool call was cancelled.");
303 }
304 let declaration = match tool.declaration {
305 HumanTool::Builtin(declaration) => {
306 return self
307 .call_builtin(&tool.definition.artifact_id, declaration, cancellation, run)
308 .await;
309 }
310 HumanTool::Command(declaration) => declaration,
311 };
312 let Ok(CommandLine {
313 program, args, cwd, ..
314 }) = self.command(name)
315 else {
316 return failed(run, "Human tool preparation failed.".into());
317 };
318 if cancellation.is_cancelled() {
319 run.end(End::Cancelled);
320 return ToolResult::error("Human tool call was cancelled.");
321 }
322 match declaration.kind {
323 HumanToolKind::Launch => match process::launch_watched(&program, &args, &cwd, run) {
324 Ok(()) => ToolResult::success(Content::Launch { launched: true }),
325 Err((error, run)) => failed(
326 run,
327 error
328 .argument_refusal()
329 .unwrap_or_else(|| "Human tool could not be launched.".into()),
330 ),
331 },
332 HumanToolKind::Output => {
333 let command = process::Command {
334 program,
335 args: args.into_iter().map(Into::into).collect(),
336 cwd,
337 env: crate::platform::environment::snapshot(),
338 timeout: declaration.timeout_ms.unwrap_or(DEFAULT_TIMEOUT),
339 };
340 match process::run_watched(command, cancellation, &run).await {
341 Ok(output) => {
342 run.end(End::exited(&output.status));
343 output_result(&output)
344 }
345 Err(process::Error::Timeout) => {
346 run.end(End::TimedOut);
347 ToolResult::error("Human tool timed out.")
348 }
349 Err(process::Error::Cancelled) => {
350 run.end(End::Cancelled);
351 ToolResult::error("Human tool call was cancelled.")
352 }
353 Err(error) => failed(
354 run,
355 error
356 .argument_refusal()
357 .unwrap_or_else(|| "Human tool execution failed.".into()),
358 ),
359 }
360 }
361 }
362 }
363
364 async fn call_builtin(
365 &self,
366 owner: &crate::config::ArtifactName,
367 declaration: &crate::config::HumanBuiltinTool,
368 cancellation: CancellationToken,
369 run: Run,
370 ) -> ToolResult {
371 let failed = |run: Run, message: String| {
372 run.end(End::Failed(message.clone()));
373 ToolResult::error(message)
374 };
375 for artifact in self.scope.artifacts.values() {
376 if let Err(error) = scope::validate_file_target(&self.config.root, artifact) {
377 return failed(run, error.to_string());
378 }
379 }
380 if declaration.builtin == crate::config::Builtin::Graph {
381 return match crate::graph_structure::launch(&self.config.root, run) {
383 Ok(()) => ToolResult::success(Content::Launch { launched: true }),
384 Err((error, run)) => failed(run, error),
385 };
386 }
387 let (owner, args) = match scope::builtin_args(self.config, &self.scope, owner, declaration)
388 {
389 Ok(args) => args,
390 Err(error) => return failed(run, error.to_string()),
391 };
392 let owner = scope::tool_id(&owner);
393 let tool_scope = self.scope.tool_scope();
394 if declaration.builtin == crate::config::Builtin::Open {
395 let target = if artifactize_tools::builtin::is_url(&args[0]) {
396 std::ffi::OsString::from(&args[0])
397 } else {
398 match tool_scope.resolve_input(&self.config.root, &owner, &args[0]) {
399 Ok(path) => path.into_os_string(),
400 Err(error) => return failed(run, error.to_string()),
401 }
402 };
403 return tokio::select! {
405 _ = cancellation.cancelled() => {
406 run.end(End::Cancelled);
407 ToolResult::error("Human tool call was cancelled.")
408 }
409 result = crate::platform::program::open_desktop(std::ffi::OsStr::new(&target)) => match result {
410 Ok(()) => {
411 run.end(End::Launched);
412 ToolResult::success(Content::Launch { launched: true })
413 }
414 Err(error) => failed(run, error.to_string()),
415 }
416 };
417 }
418 let launcher = process::Launcher {
421 env: crate::platform::environment::snapshot(),
422 };
423 let context = artifactize_tools::builtin::Context {
424 root: &self.config.root,
425 scope: &tool_scope,
426 owner: &owner,
427 launcher: &launcher,
428 };
429 let result = artifactize_tools::builtin::call_fixed(
430 declaration.builtin,
431 &args,
432 serde_json::json!({}),
433 context,
434 &cancellation,
435 )
436 .await;
437 let error = result.is_error();
438 let output = result
439 .into_content()
440 .into_iter()
441 .map(|content| match content {
442 artifactize_tools::Content::Text { text } => text,
443 artifactize_tools::Content::Json { data } => {
444 serde_json::to_string_pretty(&data).expect("builtin JSON")
445 }
446 artifactize_tools::Content::Image { .. } => {
447 unreachable!("Human builtins never produce images")
448 }
449 })
450 .collect::<Vec<_>>()
451 .join("\n");
452 let text = text(output.as_bytes(), String::new(), false);
453 if error {
454 run.text(Stream::Stderr, &text);
455 run.end(End::Failed("the builtin failed".into()));
456 ToolResult::error(text)
457 } else {
458 run.text(Stream::Stdout, &text);
459 run.end(End::Done);
460 ToolResult::success(Content::Text { text })
461 }
462 }
463}
464
465fn output_result(output: &process::Output) -> ToolResult {
466 let failed = !output.status.success();
467 let stdout = if failed {
468 format!("Human tool exited unsuccessfully ({}).\n", output.status)
469 } else {
470 String::new()
471 };
472 let mut content = vec![Content::Text {
473 text: text(&output.stdout, stdout, output.truncated),
474 }];
475 if !output.stderr.is_empty() {
476 content.push(Content::Text {
477 text: text(&output.stderr, "stderr:\n".into(), output.truncated),
478 });
479 }
480 if failed {
481 ToolResult::error_blocks(content)
482 } else {
483 ToolResult::success_blocks(content)
484 }
485}
486
487fn text(bytes: &[u8], mut prefix: String, truncated: bool) -> String {
488 prefix
489 .push_str(&String::from_utf8(runtime::clean_output(bytes)).expect("clean output is UTF-8"));
490 if prefix.len() > TEXT_LIMIT || truncated {
491 let suffix = "\n[output truncated]";
492 let mut end = (TEXT_LIMIT - suffix.len()).min(prefix.len());
493 while !prefix.is_char_boundary(end) {
494 end -= 1;
495 }
496 prefix.truncate(end);
497 prefix.push_str(suffix);
498 }
499 prefix
500}