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