Skip to main content

artifactize_core/
tools.rs

1//! Scoped audience-specific tools and language-neutral command protocols.
2
3pub use artifactize_tools::builtin;
4pub mod human;
5#[cfg(test)]
6mod image;
7pub mod pins;
8mod result;
9pub mod sessions;
10pub(crate) use artifactize_tools::schema;
11
12pub use artifactize_tools::{Content, ToolResult};
13
14use std::{
15    collections::BTreeMap,
16    ffi::OsString,
17    path::{Path, PathBuf},
18};
19
20use serde::Serialize;
21use serde_json::{Value, json};
22use tokio_util::sync::CancellationToken;
23
24use crate::{
25    config::{AgentTool, CommandTool, Profile, RepoConfig, ToolProtocol},
26    runtime,
27    scope::{self, ArtifactId, Scope},
28    workspace,
29};
30
31/// A command tool gets two minutes unless its owner declares a deadline.
32const DEFAULT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120);
33/// Capture enough for an 8 MiB normalized multimodal result plus its wire envelope,
34/// but bound raw tool stdout/stderr; truncated JSON is rejected rather than silently reused.
35const OUTPUT_LIMIT: usize = 16 * 1024 * 1024;
36/// Version 1 identifies the JSON command-tool stdin envelope carrying context and args;
37/// owner tools can distinguish future envelopes independently of fingerprint or state formats.
38const JSON_TOOL_INPUT_VERSION: u32 = 1;
39
40#[derive(Debug, Clone, Serialize)]
41#[serde(rename_all = "camelCase")]
42pub struct ToolDefinition {
43    pub name: crate::config::ToolName,
44    pub artifact_id: crate::config::ArtifactName,
45    pub description: String,
46    pub input_schema: Value,
47}
48
49struct RegisteredTool<'a> {
50    definition: ToolDefinition,
51    declaration: &'a AgentTool,
52    validator: jsonschema::Validator,
53}
54
55#[derive(Serialize)]
56#[serde(rename_all = "camelCase")]
57struct ToolContext {
58    artifact_id: crate::config::ArtifactName,
59    #[serde(with = "crate::platform::path_serde")]
60    artifact_path: PathBuf,
61    scope: BTreeMap<crate::config::ArtifactName, ContextArtifact>,
62    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
63    execution_paths: BTreeMap<crate::config::LogicalPath, ContextPath>,
64    #[serde(
65        default,
66        skip_serializing_if = "Option::is_none",
67        with = "crate::platform::path_serde::option"
68    )]
69    output_dir: Option<PathBuf>,
70    #[serde(
71        default,
72        skip_serializing_if = "Option::is_none",
73        with = "crate::platform::path_serde::option"
74    )]
75    tmp_dir: Option<PathBuf>,
76}
77#[derive(Serialize)]
78struct ContextArtifact {
79    #[serde(with = "crate::platform::path_serde")]
80    path: PathBuf,
81    kind: crate::config::ArtifactKind,
82    children: BTreeMap<crate::config::ChildPrefix, crate::config::ArtifactName>,
83    mounts: BTreeMap<crate::config::MountAlias, crate::config::ArtifactName>,
84}
85#[derive(Serialize)]
86struct ContextPath(#[serde(with = "crate::platform::path_serde")] PathBuf);
87
88struct Invocation {
89    cwd: PathBuf,
90    program: OsString,
91    argv: Vec<OsString>,
92    context: ToolContext,
93    protocol: ToolProtocol,
94    timeout_ms: std::time::Duration,
95}
96
97/// Borrows the resolved declarations; discovery and listing never execute owner code.
98/// Calls own their temporary directories, leaving the caller's output root intact.
99pub struct Registry<'a> {
100    config: &'a RepoConfig,
101    scope: Scope<'a>,
102    tools: BTreeMap<crate::config::ToolName, RegisteredTool<'a>>,
103    sessions: Option<&'a sessions::Sessions>,
104}
105
106impl<'a> Registry<'a> {
107    pub fn new(config: &'a RepoConfig, eval_id: &str) -> Result<Self, String> {
108        let eval = config
109            .evals
110            .iter()
111            .find(|eval| eval.id == eval_id)
112            .ok_or_else(|| format!("Unknown eval: {eval_id}"))?;
113        if !matches!(eval.declaration.profile(), Profile::Agent { .. }) {
114            return Err("Agent tools require an Agent eval.".into());
115        }
116        Self::with_scope(
117            config,
118            scope::eval_scope(config, eval).map_err(|e| e.to_string())?,
119        )
120    }
121
122    pub fn for_artifact(config: &'a RepoConfig, artifact_id: &str) -> Result<Self, String> {
123        let artifact_id: crate::config::ArtifactName = artifact_id.parse()?;
124        Self::with_scope(
125            config,
126            scope::artifact_scope(config, &[&artifact_id]).map_err(|e| e.to_string())?,
127        )
128    }
129
130    fn with_scope(config: &'a RepoConfig, scope: Scope<'a>) -> Result<Self, String> {
131        let mut tools = BTreeMap::new();
132        let mut session_names = BTreeMap::new();
133        for (id, artifact) in &scope.artifacts {
134            for (operation, declaration) in &artifact.views.agent_tools {
135                if let AgentTool::Command(command) = declaration
136                    && let Some(session) = &command.session
137                {
138                    let key = format!("{session}_{id}");
139                    let identity = (id, session);
140                    if session_names
141                        .insert(key.clone(), identity)
142                        .is_some_and(|previous| previous != identity)
143                    {
144                        return Err(format!("Artifact tool session names collide: {key}"));
145                    }
146                }
147                let name: crate::config::ToolName = format!("{operation}_{id}")
148                    .parse()
149                    .expect("validated tool and Artifact names");
150                let description = match declaration {
151                    AgentTool::Command(tool) => tool.description.clone(),
152                    AgentTool::Builtin(tool) => {
153                        tool.description
154                            .clone()
155                            .unwrap_or_else(|| match &tool.args {
156                                Some(args) => builtin::fixed_description(tool.builtin, args).into(),
157                                None => builtin::description(tool.builtin).into(),
158                            })
159                    }
160                }
161                .replace("{artifactName}", id);
162                let input_schema = declaration.input_schema();
163                let validator = schema::compile(&input_schema)?;
164                let entry = RegisteredTool {
165                    definition: ToolDefinition {
166                        name: name.clone(),
167                        artifact_id: artifact.name.clone(),
168                        description,
169                        input_schema,
170                    },
171                    declaration,
172                    validator,
173                };
174                if tools.insert(name.clone(), entry).is_some() {
175                    return Err(format!("Artifact tool names collide: {name}"));
176                }
177            }
178        }
179        Ok(Self {
180            config,
181            scope,
182            tools,
183            sessions: None,
184        })
185    }
186
187    pub(crate) fn with_session_scope<'b>(
188        &'b self,
189        sessions: &'b sessions::Sessions,
190    ) -> Result<Registry<'b>, String> {
191        Registry::with_scope(self.config, self.scope.clone())
192            .map(|registry| registry.with_sessions(sessions))
193    }
194
195    pub fn with_sessions(mut self, sessions: &'a sessions::Sessions) -> Self {
196        self.sessions = Some(sessions);
197        self
198    }
199
200    pub fn list(&self) -> impl Iterator<Item = &ToolDefinition> {
201        self.tools.values().map(|tool| &tool.definition)
202    }
203
204    /// Resolve static prerequisites without substituting free arguments.
205    pub fn preflight(&self, name: &str) -> Result<(), String> {
206        let tool = self
207            .tools
208            .get(name)
209            .ok_or("Unknown registered Agent tool.")?;
210        let owner = &tool.definition.artifact_id;
211        self.scope
212            .resolve_input(&self.config.root, owner, "")
213            .map_err(|e| e.to_string())?;
214        if let AgentTool::Command(command) = tool.declaration {
215            preflight_executable(&self.config.root, &self.scope, owner, &command.command)?;
216            if let Some(name) = &command.session {
217                let session = &self.scope.artifacts[owner].views.agent_sessions[name];
218                for command in [&session.start, &session.stop] {
219                    preflight_executable(&self.config.root, &self.scope, owner, &command.command)?;
220                    scope::resolve_argv(self.config, &self.scope, owner, &command.args)
221                        .map_err(|error| error.to_string())?;
222                    for path in &command.execution_paths {
223                        scope::scoped_path(&self.config.root, Path::new(path))
224                            .map_err(|error| error.to_string())?;
225                    }
226                }
227            }
228            if matches!(command.protocol, ToolProtocol::Json) {
229                scope::resolve_argv(self.config, &self.scope, owner, &command.args)
230                    .map_err(|e| e.to_string())?;
231            }
232            for path in &command.execution_paths {
233                scope::scoped_path(&self.config.root, Path::new(path))
234                    .map_err(|e| e.to_string())?;
235            }
236        }
237        if let AgentTool::Builtin(declaration) = tool.declaration
238            && let Some(args) = &declaration.args
239        {
240            let owner = ArtifactId::new(owner.as_str()).map_err(|error| error.to_string())?;
241            builtin::validate_target(
242                declaration.builtin,
243                args,
244                &self.config.root,
245                &self.scope.tool_scope(),
246                &owner,
247            )?;
248        }
249        Ok(())
250    }
251
252    pub async fn call(
253        &self,
254        name: &str,
255        args: Value,
256        output_root: &Path,
257        cancellation: CancellationToken,
258    ) -> ToolResult {
259        let Some(tool) = self.tools.get(name) else {
260            return ToolResult::error("Unknown registered Agent tool.");
261        };
262        if let Err(message) = schema::validate(&tool.validator, &args) {
263            return ToolResult::error(message);
264        }
265        if cancellation.is_cancelled() {
266            return ToolResult::error("Agent tool call was cancelled.");
267        }
268        for artifact in self.scope.artifacts.values() {
269            if let Err(error) = scope::validate_file_target(&self.config.root, artifact) {
270                return ToolResult::error(error.to_string());
271            }
272        }
273        let command = match tool.declaration {
274            AgentTool::Command(command) => command,
275            AgentTool::Builtin(tool_declaration) => {
276                if let Some(fixed_args) = &tool_declaration.args {
277                    let owner = scope::tool_id(&tool.definition.artifact_id);
278                    // An Agent's help program gets only the explicit standalone variables.
279                    let launcher = crate::process::Launcher {
280                        env: artifactize_tools::launch::passed_environment(),
281                    };
282                    let scope = self.scope.tool_scope();
283                    let context = builtin::Context {
284                        root: &self.config.root,
285                        scope: &scope,
286                        owner: &owner,
287                        launcher: &launcher,
288                    };
289                    return builtin::call_fixed(
290                        tool_declaration.builtin,
291                        fixed_args,
292                        args,
293                        context,
294                        &cancellation,
295                    )
296                    .await;
297                }
298                let input = match builtin::Input::parse(tool_declaration.builtin, args) {
299                    Ok(input) => input,
300                    Err(error) => return ToolResult::error(error),
301                };
302                let root = self.config.root.clone();
303                let owner = scope::tool_id(&tool.definition.artifact_id);
304                let scope = self.scope.tool_scope();
305                let cancellation = cancellation.child_token();
306                let _cancel_on_drop = cancellation.clone().drop_guard();
307                return crate::task::joined(
308                    tokio::task::spawn_blocking(move || {
309                        builtin::call(input, &root, &scope, &owner, &cancellation)
310                    })
311                    .await,
312                )
313                .unwrap_or_else(|_| ToolResult::error("Built-in Agent tool execution failed."));
314            }
315        };
316        let environment = if let Some(name) = &command.session {
317            let key = sessions::session_key(name, &tool.definition.artifact_id);
318            match self.sessions.and_then(|sessions| sessions.call(&key)) {
319                Some(call) => Some(call),
320                None => return ToolResult::error(format!("The tool session `{name}` ended.")),
321            }
322        } else {
323            None
324        };
325        let invocation = match self.prepare(&tool.definition.artifact_id, command, &args) {
326            Ok(invocation) => invocation,
327            Err(()) => return ToolResult::error("Agent tool preparation failed."),
328        };
329        let workspace = self.config.root.clone();
330        let output_root = output_root.to_owned();
331        let cancellation = cancellation.child_token();
332        let _cancel_on_drop = cancellation.clone().drop_guard();
333        // Keep cleanup alive if the caller drops its future while a command is running.
334        let executor = if environment.is_some() {
335            match sessions::executor() {
336                Ok(executor) => executor.clone(),
337                Err(_) => return ToolResult::error("Agent tool execution failed."),
338            }
339        } else {
340            tokio::runtime::Handle::current()
341        };
342        crate::task::joined(
343            executor
344                .spawn(async move {
345                    invoke(
346                        invocation,
347                        args,
348                        &workspace,
349                        &output_root,
350                        cancellation,
351                        environment,
352                    )
353                    .await
354                })
355                .await,
356        )
357        .unwrap_or_else(|_| ToolResult::error("Agent tool execution failed."))
358    }
359
360    fn prepare_session(
361        &self,
362        owner: &crate::config::ArtifactName,
363        command: &crate::config::SessionCommand,
364    ) -> Result<Invocation, String> {
365        let tool = CommandTool {
366            session: None,
367            description: String::new(),
368            input_schema: json!({"type":"object"}),
369            protocol: ToolProtocol::Json,
370            command: command.command.clone(),
371            args: command.args.clone(),
372            timeout_ms: None,
373            execution_paths: command.execution_paths.clone(),
374            plain_args: Vec::new(),
375        };
376        self.prepare(owner, &tool, &json!({}))
377            .map_err(|()| "Tool session preparation failed.".into())
378    }
379
380    fn prepare(
381        &self,
382        owner: &crate::config::ArtifactName,
383        tool: &CommandTool,
384        args: &Value,
385    ) -> Result<Invocation, ()> {
386        let cwd = scope::scoped_path(&self.config.root, self.config.artifacts[owner].folder())
387            .map_err(|_| ())?;
388        let program = executable(&self.config.root, &self.scope, owner, &tool.command)?;
389        let argv = match tool.protocol {
390            ToolProtocol::Json => {
391                scope::resolve_argv(self.config, &self.scope, owner, &tool.args).map_err(|_| ())?
392            }
393            ToolProtocol::Plain => tool
394                .plain_args
395                .iter()
396                .map(|arg| {
397                    arg.expand(|name| {
398                        if tool.input_schema["properties"].get(name).is_none() {
399                            return Err("Undeclared plain tool placeholder.".into());
400                        }
401                        let value = args.get(name).ok_or("Missing plain tool argument.")?;
402                        let value = match value {
403                            Value::String(value) => value.clone(),
404                            _ => value.to_string(),
405                        };
406                        if value.contains('\0') {
407                            return Err("Plain tool arguments cannot contain NUL.".into());
408                        }
409                        Ok(value)
410                    })
411                })
412                .collect::<Result<Vec<_>, _>>()
413                .map_err(|_| ())?,
414        };
415        let scoped = self
416            .scope
417            .artifacts
418            .values()
419            .map(|artifact| {
420                let path = scope::scoped_path(&self.config.root, &artifact.path).map_err(|_| ())?;
421                Ok((
422                    artifact.name.clone(),
423                    ContextArtifact {
424                        path,
425                        kind: artifact.kind,
426                        children: artifact.children.clone(),
427                        mounts: artifact.mounts.clone(),
428                    },
429                ))
430            })
431            .collect::<Result<BTreeMap<_, _>, ()>>()?;
432        let execution_paths = tool
433            .execution_paths
434            .iter()
435            .map(|path| {
436                let resolved =
437                    scope::scoped_path(&self.config.root, Path::new(path)).map_err(|_| ())?;
438                Ok((path.clone(), ContextPath(resolved)))
439            })
440            .collect::<Result<_, ()>>()?;
441        let owner = &self.scope.artifacts[owner].name;
442        let context = ToolContext {
443            artifact_id: owner.clone(),
444            artifact_path: scoped[owner].path.clone(),
445            scope: scoped,
446            execution_paths,
447            output_dir: None,
448            tmp_dir: None,
449        };
450        Ok(Invocation {
451            cwd,
452            program,
453            argv: argv.into_iter().map(Into::into).collect(),
454            context,
455            protocol: tool.protocol,
456            timeout_ms: tool.timeout_ms.unwrap_or(DEFAULT_TIMEOUT),
457        })
458    }
459}
460
461fn executable(
462    root: &Path,
463    scope: &Scope<'_>,
464    owner: &crate::config::ArtifactName,
465    command: &str,
466) -> Result<OsString, ()> {
467    scope::executable(root, scope, owner, command).map_err(|_| ())
468}
469
470fn preflight_executable(
471    root: &Path,
472    scope: &Scope<'_>,
473    owner: &crate::config::ArtifactName,
474    command: &str,
475) -> Result<(), String> {
476    let program = executable(root, scope, owner, command)
477        .map_err(|_| "Tool executable path is unavailable or outside scope.".to_owned())?;
478    let cwd = scope::scoped_path(root, scope.artifacts[owner].folder())
479        .map_err(|error| error.to_string())?;
480    crate::platform::program::resolve(&program, &cwd)
481        .map(|_| ())
482        .map_err(|_| {
483            format!(
484                "Tool executable is unavailable: {}",
485                crate::platform::path_text(Path::new(command))
486            )
487        })
488}
489
490async fn invoke(
491    invocation: Invocation,
492    args: Value,
493    workspace: &Path,
494    output_root: &Path,
495    cancellation: CancellationToken,
496    environment: Option<sessions::ownership::Call>,
497) -> ToolResult {
498    let run = || {
499        let root = workspace::prepare_directory(output_root, workspace).map_err(|_| ())?;
500        tempfile::Builder::new()
501            .prefix("tool-")
502            .tempdir_in(root)
503            .map_err(|_| ())
504    };
505    let Ok(directory) = run() else {
506        return ToolResult::error("Agent tool preparation failed.");
507    };
508    let Invocation {
509        cwd,
510        program,
511        argv,
512        mut context,
513        protocol,
514        timeout_ms,
515    } = invocation;
516    let result = async {
517        let mut command =
518            runtime::Command::prepare(program, argv, workspace, directory.path(), Some(timeout_ms))
519                .map_err(|_| "Agent tool preparation failed.")?;
520        command.cwd = cwd;
521        if let Some(environment) = &environment {
522            command.inherit_session(&environment.environment);
523        }
524        let output_dir = command.directory().join("output");
525        context.output_dir = Some(output_dir.clone());
526        context.tmp_dir = Some(command.directory().join("tmp"));
527        let input = match protocol {
528            ToolProtocol::Json => {
529                json!({"version":JSON_TOOL_INPUT_VERSION,"context":context,"args":args})
530                    .to_string()
531                    .into_bytes()
532            }
533            ToolProtocol::Plain => Vec::new(),
534        };
535        let output = match environment {
536            Some(call) => {
537                call.run(
538                    command.into_process(),
539                    input,
540                    OUTPUT_LIMIT,
541                    cancellation.clone(),
542                )
543                .await
544            }
545            None => {
546                command
547                    .tool_output(input, OUTPUT_LIMIT, cancellation.clone())
548                    .await
549            }
550        }
551        .map_err(|error| {
552            error.argument_refusal().unwrap_or_else(|| match error {
553                crate::process::Error::Timeout => "Agent tool timed out.".into(),
554                crate::process::Error::Cancelled => "Agent tool call was cancelled.".into(),
555                _ => "Agent tool execution failed.".into(),
556            })
557        })?;
558        match protocol {
559            ToolProtocol::Json => {
560                if !output.status.success() {
561                    return Err("Agent tool execution failed.".to_owned());
562                }
563                if output.truncated {
564                    return Err("Agent tool returned invalid output.".to_owned());
565                }
566                result::parse(&output.stdout, &output_dir)
567                    .map_err(|_| "Agent tool returned invalid output.".to_owned())
568            }
569            ToolProtocol::Plain => Ok(result::plain(&output)),
570        }
571    }
572    .await;
573    let cleaned = directory.close();
574    if cancellation.is_cancelled() {
575        return ToolResult::error("Agent tool call was cancelled.");
576    }
577    if cleaned.is_err() {
578        return ToolResult::error("Agent tool cleanup failed.");
579    }
580    result.unwrap_or_else(ToolResult::error)
581}
582
583#[cfg(test)]
584mod tests;
585
586#[cfg(test)]
587#[path = "tools/builtin/tests.rs"]
588mod builtin_tests;