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: crate::config::CommandKind,
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 crate::config::CommandKind::Launch => {
375 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 }
385 crate::config::CommandKind::Output => {
386 let command = process::Command {
387 program,
388 args: args.into_iter().map(Into::into).collect(),
389 cwd,
390 env: crate::platform::environment::snapshot(),
391 timeout: declaration.timeout_ms.unwrap_or(DEFAULT_TIMEOUT),
392 };
393 match process::run_watched(command, cancellation, &run).await {
394 Ok(output) => {
395 run.end(End::exited(&output.status));
396 output_result(&output)
397 }
398 Err(process::Error::Timeout) => {
399 run.end(End::TimedOut);
400 ToolResult::error("Human tool timed out.")
401 }
402 Err(process::Error::Cancelled) => {
403 run.end(End::Cancelled);
404 ToolResult::error("Human tool call was cancelled.")
405 }
406 Err(error) => failed(
407 run,
408 error
409 .argument_refusal()
410 .unwrap_or_else(|| "Human tool execution failed.".into()),
411 ),
412 }
413 }
414 }
415 }
416
417 async fn call_builtin(
418 &self,
419 owner: &crate::config::ArtifactName,
420 declaration: &crate::config::HumanBuiltinTool,
421 cancellation: CancellationToken,
422 run: Run,
423 ) -> ToolResult {
424 let failed = |run: Run, message: String| {
425 run.end(End::Failed(message.clone()));
426 ToolResult::error(message)
427 };
428 for artifact in self.scope.artifacts.values() {
429 if let Err(error) = scope::validate_file_target(&self.config.root, artifact) {
430 return failed(run, error.to_string());
431 }
432 }
433 if declaration.builtin == crate::config::Builtin::Graph {
434 return match crate::graph_structure::launch(&self.config.root, run) {
436 Ok(()) => ToolResult::success(Content::Launch { launched: true }),
437 Err((error, run)) => failed(run, error),
438 };
439 }
440 let (owner, args) = match scope::builtin_args(self.config, &self.scope, owner, declaration)
441 {
442 Ok(args) => args,
443 Err(error) => return failed(run, error.to_string()),
444 };
445 let owner = scope::tool_id(&owner);
446 let tool_scope = self.scope.tool_scope();
447 if declaration.builtin == crate::config::Builtin::Open {
448 let target = if artifactize_tools::builtin::is_url(&args[0]) {
449 std::ffi::OsString::from(&args[0])
450 } else {
451 match tool_scope.resolve_input(&self.config.root, &owner, &args[0]) {
452 Ok(path) => path.into_os_string(),
453 Err(error) => return failed(run, error.to_string()),
454 }
455 };
456 return match artifactize_tools::opener::open_cancellable(&target, &cancellation).await {
458 Ok(()) => {
459 run.end(End::Launched);
460 ToolResult::success(Content::Launch { launched: true })
461 }
462 Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {
463 run.end(End::Cancelled);
464 ToolResult::error("Human tool call was cancelled.")
465 }
466 Err(error) => failed(run, error.to_string()),
467 };
468 }
469 let launcher = process::Launcher {
472 env: crate::platform::environment::snapshot(),
473 };
474 let context = artifactize_tools::builtin::Context {
475 root: &self.config.root,
476 scope: &tool_scope,
477 owner: &owner,
478 launcher: &launcher,
479 };
480 let result = artifactize_tools::builtin::call_fixed(
481 declaration.builtin,
482 &args,
483 serde_json::json!({}),
484 context,
485 &cancellation,
486 )
487 .await;
488 let error = result.is_error();
489 let output = result
490 .into_content()
491 .into_iter()
492 .map(|content| match content {
493 artifactize_tools::Content::Text { text } => text,
494 artifactize_tools::Content::Json { data } => {
495 serde_json::to_string_pretty(&data).expect("builtin JSON")
496 }
497 artifactize_tools::Content::Image { .. } => {
498 unreachable!("Human builtins never produce images")
499 }
500 })
501 .collect::<Vec<_>>()
502 .join("\n");
503 let text = text(output.as_bytes(), String::new(), false);
504 if error {
505 run.text(Stream::Stderr, &text);
506 run.end(End::Failed("the builtin failed".into()));
507 ToolResult::error(text)
508 } else {
509 run.text(Stream::Stdout, &text);
510 run.end(End::Done);
511 ToolResult::success(Content::Text { text })
512 }
513 }
514}
515
516fn output_result(output: &process::Output) -> ToolResult {
517 let failed = !output.status.success();
518 let stdout = if failed {
519 format!("Human tool exited unsuccessfully ({}).\n", output.status)
520 } else {
521 String::new()
522 };
523 let mut content = vec![Content::Text {
524 text: text(&output.stdout, stdout, output.truncated),
525 }];
526 if !output.stderr.is_empty() {
527 content.push(Content::Text {
528 text: text(&output.stderr, "stderr:\n".into(), output.truncated),
529 });
530 }
531 if failed {
532 ToolResult::error_blocks(content)
533 } else {
534 ToolResult::success_blocks(content)
535 }
536}
537
538fn text(bytes: &[u8], mut prefix: String, truncated: bool) -> String {
539 prefix.push_str(&crate::platform::clean_program_text(bytes));
540 if prefix.len() > TEXT_LIMIT || truncated {
541 let suffix = "\n[output truncated]";
542 let mut end = (TEXT_LIMIT - suffix.len()).min(prefix.len());
543 while !prefix.is_char_boundary(end) {
544 end -= 1;
545 }
546 prefix.truncate(end);
547 prefix.push_str(suffix);
548 }
549 prefix
550}