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    artifact_path: ContextTarget,
60    scope: BTreeMap<crate::config::ArtifactName, ContextArtifact>,
61    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
62    execution_paths: BTreeMap<crate::config::LogicalPath, ContextPath>,
63    #[serde(
64        default,
65        skip_serializing_if = "Option::is_none",
66        serialize_with = "crate::platform::path_serde::native::serialize"
67    )]
68    output_dir: Option<PathBuf>,
69    // The tool program writes into these folders: they are given in native spelling.
70    #[serde(
71        default,
72        skip_serializing_if = "Option::is_none",
73        serialize_with = "crate::platform::path_serde::native::serialize"
74    )]
75    tmp_dir: Option<PathBuf>,
76}
77#[derive(Serialize)]
78struct ContextArtifact {
79    path: ContextTarget,
80    kind: crate::config::ArtifactKind,
81    nested: BTreeMap<crate::config::ChildPrefix, crate::config::ArtifactName>,
82    #[serde(skip_serializing_if = "Option::is_none")]
83    covering_part: Option<crate::config::ArtifactName>,
84    /// An aspect's selected paths below `path`.
85    #[serde(skip_serializing_if = "Vec::is_empty")]
86    select: Vec<crate::config::LogicalPath>,
87}
88/// Tool context exposes absolute physical paths, not project-relative Artifact targets.
89#[derive(Clone, Serialize)]
90#[serde(untagged)]
91enum ContextTarget {
92    Local(ContextPath),
93    Live(crate::config::Uri),
94}
95#[derive(Clone, Serialize)]
96// The tool program opens these paths: they are given in native spelling.
97struct ContextPath(
98    #[serde(serialize_with = "crate::platform::path_serde::native::serialize_path")] PathBuf,
99);
100
101struct Invocation {
102    cwd: PathBuf,
103    program: OsString,
104    argv: Vec<OsString>,
105    context: ToolContext,
106    protocol: ToolProtocol,
107    timeout_ms: std::time::Duration,
108}
109
110/// Borrows the resolved declarations; discovery and listing never execute owner code.
111/// Calls own their temporary directories, leaving the caller's output root intact.
112pub struct Registry<'a> {
113    config: &'a RepoConfig,
114    scope: Scope<'a>,
115    tools: BTreeMap<crate::config::ToolName, RegisteredTool<'a>>,
116    sessions: Option<&'a sessions::Sessions>,
117}
118
119impl<'a> Registry<'a> {
120    pub fn new(config: &'a RepoConfig, eval_id: &crate::types::EvalId) -> Result<Self, String> {
121        let eval = config
122            .evals
123            .iter()
124            .find(|eval| &eval.id == eval_id)
125            .ok_or_else(|| format!("Unknown eval: {eval_id}"))?;
126        if !matches!(eval.declaration.profile(), Profile::Agent { .. }) {
127            return Err("Agent tools require an Agent eval.".into());
128        }
129        Self::with_scope(
130            config,
131            scope::eval_scope(config, eval).map_err(|e| e.to_string())?,
132        )
133    }
134
135    pub fn for_artifact(
136        config: &'a RepoConfig,
137        artifact_id: &crate::config::ArtifactName,
138    ) -> Result<Self, String> {
139        Self::with_scope(
140            config,
141            scope::artifact_scope(config, &[artifact_id]).map_err(|e| e.to_string())?,
142        )
143    }
144
145    fn with_scope(config: &'a RepoConfig, scope: Scope<'a>) -> Result<Self, String> {
146        let mut tools = BTreeMap::new();
147        let mut session_names = BTreeMap::new();
148        for (id, artifact) in &scope.artifacts {
149            for (operation, declaration) in &artifact.views.agent_tools {
150                if let AgentTool::Command(command) = declaration
151                    && let Some(session) = &command.session
152                {
153                    let key = format!("{session}_{}", id);
154                    let identity = (id, session);
155                    if session_names
156                        .insert(key.clone(), identity)
157                        .is_some_and(|previous| previous != identity)
158                    {
159                        return Err(format!("Artifact tool session names collide: {key}"));
160                    }
161                }
162                let name: crate::config::ToolName = format!("{operation}_{}", id)
163                    .parse()
164                    .expect("validated tool and Artifact names");
165                let description = match declaration {
166                    AgentTool::Command(tool) => tool.description.clone(),
167                    AgentTool::Builtin(tool) => {
168                        tool.description
169                            .clone()
170                            .unwrap_or_else(|| match &tool.args {
171                                Some(args) => builtin::fixed_description(tool.builtin, args).into(),
172                                None => builtin::description(tool.builtin).into(),
173                            })
174                    }
175                }
176                .replace("{artifactName}", id);
177                let input_schema = declaration.input_schema();
178                let validator = schema::compile(&input_schema)?;
179                let entry = RegisteredTool {
180                    definition: ToolDefinition {
181                        name: name.clone(),
182                        artifact_id: artifact.name.clone(),
183                        description,
184                        input_schema,
185                    },
186                    declaration,
187                    validator,
188                };
189                if tools.insert(name.clone(), entry).is_some() {
190                    return Err(format!("Artifact tool names collide: {name}"));
191                }
192            }
193        }
194        Ok(Self {
195            config,
196            scope,
197            tools,
198            sessions: None,
199        })
200    }
201
202    pub(crate) fn with_session_scope<'b>(
203        &'b self,
204        sessions: &'b sessions::Sessions,
205    ) -> Result<Registry<'b>, String> {
206        Registry::with_scope(self.config, self.scope.clone())
207            .map(|registry| registry.with_sessions(sessions))
208    }
209
210    pub fn with_sessions(mut self, sessions: &'a sessions::Sessions) -> Self {
211        self.sessions = Some(sessions);
212        self
213    }
214
215    pub fn list(&self) -> impl Iterator<Item = &ToolDefinition> {
216        self.tools.values().map(|tool| &tool.definition)
217    }
218
219    /// Resolve static prerequisites without substituting free arguments.
220    pub fn preflight(&self, name: &str) -> Result<(), String> {
221        let tool = self
222            .tools
223            .get(name)
224            .ok_or("Unknown registered Agent tool.")?;
225        let owner = &tool.definition.artifact_id;
226        if self.scope.artifacts[owner].path.local().is_some() {
227            self.scope
228                .resolve_input(&self.config.root, owner, "")
229                .map_err(|e| e.to_string())?;
230        }
231        if let AgentTool::Command(command) = tool.declaration {
232            preflight_executable(&self.config.root, &self.scope, owner, &command.command)?;
233            if let Some(name) = &command.session {
234                let session = &self.scope.artifacts[owner].views.agent_sessions[name];
235                for command in [&session.start, &session.stop] {
236                    preflight_executable(&self.config.root, &self.scope, owner, &command.command)?;
237                    scope::resolve_argv(self.config, &self.scope, owner, &command.args)
238                        .map_err(|error| error.to_string())?;
239                    for path in &command.execution_paths {
240                        scope::scoped_path(&self.config.root, Path::new(path))
241                            .map_err(|error| error.to_string())?;
242                    }
243                }
244            }
245            if matches!(command.protocol, ToolProtocol::Json) {
246                scope::resolve_argv(self.config, &self.scope, owner, &command.args)
247                    .map_err(|e| e.to_string())?;
248            }
249            for path in &command.execution_paths {
250                scope::scoped_path(&self.config.root, Path::new(path))
251                    .map_err(|e| e.to_string())?;
252            }
253        }
254        if let AgentTool::Builtin(declaration) = tool.declaration
255            && let Some(args) = &declaration.args
256        {
257            let owner = ArtifactId::new(owner.as_str()).map_err(|error| error.to_string())?;
258            builtin::validate_target(
259                declaration.builtin,
260                args,
261                &self.config.root,
262                &self.scope.tool_scope(),
263                &owner,
264            )?;
265        }
266        Ok(())
267    }
268
269    pub async fn call(
270        &self,
271        name: &str,
272        args: Value,
273        output_root: &Path,
274        cancellation: CancellationToken,
275    ) -> ToolResult {
276        self.call_with_cleanup(
277            name,
278            args,
279            output_root,
280            cancellation,
281            crate::platform::PrivateTempDir::close,
282        )
283        .await
284    }
285
286    async fn call_with_cleanup(
287        &self,
288        name: &str,
289        args: Value,
290        output_root: &Path,
291        cancellation: CancellationToken,
292        cleanup: impl FnOnce(crate::platform::PrivateTempDir) -> std::io::Result<()> + Send + 'static,
293    ) -> ToolResult {
294        let Some(tool) = self.tools.get(name) else {
295            return ToolResult::error("Unknown registered Agent tool.");
296        };
297        if let Err(message) = schema::validate(&tool.validator, &args) {
298            return ToolResult::error(message);
299        }
300        if cancellation.is_cancelled() {
301            return ToolResult::error("Agent tool call was cancelled.");
302        }
303        for artifact in self.scope.artifacts.values() {
304            if let Err(error) = scope::validate_file_target(&self.config.root, artifact) {
305                return ToolResult::error(error.to_string());
306            }
307        }
308        let command = match tool.declaration {
309            AgentTool::Command(command) => command,
310            AgentTool::Builtin(tool_declaration) => {
311                if matches!(
312                    tool_declaration.builtin,
313                    crate::config::Builtin::Graph | crate::config::Builtin::Declarations
314                ) {
315                    let graph = if tool_declaration.builtin == crate::config::Builtin::Declarations
316                    {
317                        crate::graph_structure::read_scoped(
318                            &self.config.root,
319                            &self.config.artifacts[&tool.definition.artifact_id],
320                        )
321                    } else {
322                        crate::graph_structure::read(&self.config.root)
323                    };
324                    return match graph {
325                        Ok(graph) => ToolResult::success(Content::Text { text: graph.tree() }),
326                        Err(error) => ToolResult::error(error),
327                    };
328                }
329                if let Some(fixed_args) = &tool_declaration.args {
330                    let owner = scope::tool_id(&tool.definition.artifact_id);
331                    // An Agent's help program gets only the explicit standalone variables.
332                    let launcher = crate::process::Launcher {
333                        env: artifactize_tools::launch::passed_environment(),
334                    };
335                    let scope = self.scope.tool_scope();
336                    let context = builtin::Context {
337                        root: &self.config.root,
338                        scope: &scope,
339                        owner: &owner,
340                        launcher: &launcher,
341                    };
342                    return builtin::call_fixed(
343                        tool_declaration.builtin,
344                        fixed_args,
345                        args,
346                        context,
347                        &cancellation,
348                    )
349                    .await;
350                }
351                let input = match builtin::Input::parse(tool_declaration.builtin, args) {
352                    Ok(input) => input,
353                    Err(error) => return ToolResult::error(error),
354                };
355                let root = self.config.root.clone();
356                let owner = scope::tool_id(&tool.definition.artifact_id);
357                let scope = self.scope.tool_scope();
358                let cancellation = cancellation.child_token();
359                let _cancel_on_drop = cancellation.clone().drop_guard();
360                return crate::task::joined(
361                    tokio::task::spawn_blocking(move || {
362                        builtin::call(input, &root, &scope, &owner, &cancellation)
363                    })
364                    .await,
365                )
366                .unwrap_or_else(|_| ToolResult::error("Built-in Agent tool execution failed."));
367            }
368        };
369        let environment = if let Some(name) = &command.session {
370            let key = sessions::session_key(name, &tool.definition.artifact_id);
371            let Some(sessions) = self.sessions else {
372                return ToolResult::error(format!("The tool session `{name}` ended."));
373            };
374            match sessions.call(&key).await {
375                Ok(call) => Some(call),
376                Err(error) => return ToolResult::error(error),
377            }
378        } else {
379            None
380        };
381        let invocation = match self.prepare(&tool.definition.artifact_id, command, &args) {
382            Ok(invocation) => invocation,
383            Err(()) => return ToolResult::error("Agent tool preparation failed."),
384        };
385        let workspace = self.config.root.clone();
386        let output_root = output_root.to_owned();
387        let cancellation = cancellation.child_token();
388        let _cancel_on_drop = cancellation.clone().drop_guard();
389        // Keep cleanup alive if the caller drops its future while a command is running.
390        let executor = if environment.is_some() {
391            match sessions::executor() {
392                Ok(executor) => executor.clone(),
393                Err(_) => return ToolResult::error("Agent tool execution failed."),
394            }
395        } else {
396            tokio::runtime::Handle::current()
397        };
398        crate::task::joined(
399            executor
400                .spawn(async move {
401                    invoke(
402                        invocation,
403                        args,
404                        &workspace,
405                        &output_root,
406                        cancellation,
407                        environment,
408                        cleanup,
409                    )
410                    .await
411                })
412                .await,
413        )
414        .unwrap_or_else(|_| ToolResult::error("Agent tool execution failed."))
415    }
416
417    fn prepare_session(
418        &self,
419        owner: &crate::config::ArtifactName,
420        command: &crate::config::SessionCommand,
421    ) -> Result<Invocation, String> {
422        let tool = CommandTool {
423            session: None,
424            description: String::new(),
425            input_schema: std::sync::Arc::new(json!({"type":"object"})),
426            protocol: ToolProtocol::Json,
427            command: command.command.clone(),
428            args: command.args.clone(),
429            timeout_ms: None,
430            execution_paths: command.execution_paths.clone(),
431            plain_args: Vec::new(),
432        };
433        self.prepare(owner, &tool, &json!({}))
434            .map_err(|()| "Tool session preparation failed.".into())
435    }
436
437    fn prepare(
438        &self,
439        owner: &crate::config::ArtifactName,
440        tool: &CommandTool,
441        args: &Value,
442    ) -> Result<Invocation, ()> {
443        let cwd = scope::scoped_path(&self.config.root, self.config.artifacts[owner].folder())
444            .map_err(|_| ())?;
445        let program = executable(&self.config.root, &self.scope, owner, &tool.command)?;
446        let argv = match tool.protocol {
447            ToolProtocol::Json => {
448                scope::resolve_argv(self.config, &self.scope, owner, &tool.args).map_err(|_| ())?
449            }
450            ToolProtocol::Plain => tool
451                .plain_args
452                .iter()
453                .map(|arg| {
454                    arg.expand(|name| {
455                        if tool.input_schema["properties"].get(name).is_none() {
456                            return Err("Undeclared plain tool placeholder.".into());
457                        }
458                        let value = args.get(name).ok_or("Missing plain tool argument.")?;
459                        let value = match value {
460                            Value::String(value) => value.clone(),
461                            _ => value.to_string(),
462                        };
463                        if value.contains('\0') {
464                            return Err("Plain tool arguments cannot contain NUL.".into());
465                        }
466                        Ok(value)
467                    })
468                })
469                .collect::<Result<Vec<_>, _>>()
470                .map_err(|_| ())?,
471        };
472        let scoped = self
473            .scope
474            .artifacts
475            .values()
476            .map(|artifact| {
477                let path = match &artifact.path {
478                    crate::config::Target::Live(uri) => ContextTarget::Live(uri.clone()),
479                    _ => ContextTarget::Local(ContextPath(
480                        scope::scoped_path(
481                            &self.config.root,
482                            artifact.referenced_path().ok_or(())?,
483                        )
484                        .map_err(|_| ())?,
485                    )),
486                };
487                Ok((
488                    artifact.name.clone(),
489                    ContextArtifact {
490                        path,
491                        kind: artifact.kind(),
492                        nested: artifact.nested.clone(),
493                        covering_part: artifact.covering_part.clone(),
494                        select: artifact.select().to_vec(),
495                    },
496                ))
497            })
498            .collect::<Result<BTreeMap<_, _>, ()>>()?;
499        let execution_paths = tool
500            .execution_paths
501            .iter()
502            .map(|path| {
503                let resolved =
504                    scope::scoped_path(&self.config.root, Path::new(path)).map_err(|_| ())?;
505                Ok((path.clone(), ContextPath(resolved)))
506            })
507            .collect::<Result<_, ()>>()?;
508        let owner = &self.scope.artifacts[owner].name;
509        let context = ToolContext {
510            artifact_id: owner.clone(),
511            artifact_path: scoped[owner].path.clone(),
512            scope: scoped,
513            execution_paths,
514            output_dir: None,
515            tmp_dir: None,
516        };
517        Ok(Invocation {
518            cwd,
519            program,
520            argv: argv.into_iter().map(Into::into).collect(),
521            context,
522            protocol: tool.protocol,
523            timeout_ms: tool.timeout_ms.unwrap_or(DEFAULT_TIMEOUT),
524        })
525    }
526}
527
528fn executable(
529    root: &Path,
530    scope: &Scope<'_>,
531    owner: &crate::config::ArtifactName,
532    command: &str,
533) -> Result<OsString, ()> {
534    scope::executable(root, scope, owner, command).map_err(|_| ())
535}
536
537fn preflight_executable(
538    root: &Path,
539    scope: &Scope<'_>,
540    owner: &crate::config::ArtifactName,
541    command: &str,
542) -> Result<(), String> {
543    let program = executable(root, scope, owner, command)
544        .map_err(|_| "Tool executable path is unavailable or outside scope.".to_owned())?;
545    let cwd = scope::scoped_path(root, scope.artifacts[owner].folder())
546        .map_err(|error| error.to_string())?;
547    crate::platform::program::resolve(Path::new(&program), &cwd)
548        .map(|_| ())
549        .map_err(|_| {
550            format!(
551                "Tool executable is unavailable: {}",
552                crate::platform::program_text(command)
553            )
554        })
555}
556
557async fn invoke(
558    invocation: Invocation,
559    args: Value,
560    workspace: &Path,
561    output_root: &Path,
562    cancellation: CancellationToken,
563    environment: Option<sessions::ownership::Call>,
564    cleanup: impl FnOnce(crate::platform::PrivateTempDir) -> std::io::Result<()>,
565) -> ToolResult {
566    let run = || {
567        let root = workspace::prepare_directory(output_root, workspace).map_err(|_| ())?;
568        crate::platform::private_tempdir_in("tool-", &root).map_err(|_| ())
569    };
570    let Ok(directory) = run() else {
571        return ToolResult::error("Agent tool preparation failed.");
572    };
573    let Invocation {
574        cwd,
575        program,
576        argv,
577        mut context,
578        protocol,
579        timeout_ms,
580    } = invocation;
581    let result = async {
582        let mut command =
583            runtime::Command::prepare(program, argv, workspace, directory.path(), Some(timeout_ms))
584                .map_err(|_| "Agent tool preparation failed.")?;
585        command.cwd = cwd;
586        if let Some(environment) = &environment {
587            command.inherit_session(&environment.environment);
588        }
589        let output_dir = command.directory().join("output");
590        context.output_dir = Some(output_dir.clone());
591        context.tmp_dir = Some(command.directory().join("tmp"));
592        let input = match protocol {
593            ToolProtocol::Json => {
594                json!({"version":JSON_TOOL_INPUT_VERSION,"context":context,"args":args})
595                    .to_string()
596                    .into_bytes()
597            }
598            ToolProtocol::Plain => Vec::new(),
599        };
600        let output = match environment {
601            Some(call) => {
602                call.run(
603                    command.into_process(),
604                    input,
605                    OUTPUT_LIMIT,
606                    cancellation.clone(),
607                )
608                .await
609            }
610            None => {
611                command
612                    .tool_output(input, OUTPUT_LIMIT, cancellation.clone())
613                    .await
614            }
615        }
616        .map_err(|error| {
617            error.argument_refusal().unwrap_or_else(|| match error {
618                crate::process::Error::Timeout => "Agent tool timed out.".into(),
619                crate::process::Error::Cancelled => "Agent tool call was cancelled.".into(),
620                _ => "Agent tool execution failed.".into(),
621            })
622        })?;
623        match protocol {
624            ToolProtocol::Json => {
625                if !output.status.success() {
626                    return Err("Agent tool execution failed.".to_owned());
627                }
628                if output.truncated {
629                    return Err("Agent tool returned invalid output.".to_owned());
630                }
631                result::parse(&output.stdout, &output_dir)
632                    .map_err(|_| "Agent tool returned invalid output.".to_owned())
633            }
634            ToolProtocol::Plain => Ok(result::plain(&output)),
635        }
636    }
637    .await;
638    let cleaned = cleanup(directory);
639    if cancellation.is_cancelled() {
640        return ToolResult::error("Agent tool call was cancelled.");
641    }
642    if cleaned.is_err() {
643        return ToolResult::error("Agent tool cleanup failed.");
644    }
645    result.unwrap_or_else(ToolResult::error)
646}
647
648#[cfg(test)]
649mod tests;
650
651#[cfg(test)]
652#[path = "tools/builtin/tests.rs"]
653mod builtin_tests;