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