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 tool_declaration.builtin == crate::config::Builtin::Graph {
312                    return match crate::graph_structure::read(&self.config.root) {
313                        Ok(graph) => ToolResult::success(Content::Text { text: graph.tree() }),
314                        Err(error) => ToolResult::error(error),
315                    };
316                }
317                if let Some(fixed_args) = &tool_declaration.args {
318                    let owner = scope::tool_id(&tool.definition.artifact_id);
319                    // An Agent's help program gets only the explicit standalone variables.
320                    let launcher = crate::process::Launcher {
321                        env: artifactize_tools::launch::passed_environment(),
322                    };
323                    let scope = self.scope.tool_scope();
324                    let context = builtin::Context {
325                        root: &self.config.root,
326                        scope: &scope,
327                        owner: &owner,
328                        launcher: &launcher,
329                    };
330                    return builtin::call_fixed(
331                        tool_declaration.builtin,
332                        fixed_args,
333                        args,
334                        context,
335                        &cancellation,
336                    )
337                    .await;
338                }
339                let input = match builtin::Input::parse(tool_declaration.builtin, args) {
340                    Ok(input) => input,
341                    Err(error) => return ToolResult::error(error),
342                };
343                let root = self.config.root.clone();
344                let owner = scope::tool_id(&tool.definition.artifact_id);
345                let scope = self.scope.tool_scope();
346                let cancellation = cancellation.child_token();
347                let _cancel_on_drop = cancellation.clone().drop_guard();
348                return crate::task::joined(
349                    tokio::task::spawn_blocking(move || {
350                        builtin::call(input, &root, &scope, &owner, &cancellation)
351                    })
352                    .await,
353                )
354                .unwrap_or_else(|_| ToolResult::error("Built-in Agent tool execution failed."));
355            }
356        };
357        let environment = if let Some(name) = &command.session {
358            let key = sessions::session_key(name, &tool.definition.artifact_id);
359            let Some(sessions) = self.sessions else {
360                return ToolResult::error(format!("The tool session `{name}` ended."));
361            };
362            match sessions.call(&key).await {
363                Ok(call) => Some(call),
364                Err(error) => return ToolResult::error(error),
365            }
366        } else {
367            None
368        };
369        let invocation = match self.prepare(&tool.definition.artifact_id, command, &args) {
370            Ok(invocation) => invocation,
371            Err(()) => return ToolResult::error("Agent tool preparation failed."),
372        };
373        let workspace = self.config.root.clone();
374        let output_root = output_root.to_owned();
375        let cancellation = cancellation.child_token();
376        let _cancel_on_drop = cancellation.clone().drop_guard();
377        // Keep cleanup alive if the caller drops its future while a command is running.
378        let executor = if environment.is_some() {
379            match sessions::executor() {
380                Ok(executor) => executor.clone(),
381                Err(_) => return ToolResult::error("Agent tool execution failed."),
382            }
383        } else {
384            tokio::runtime::Handle::current()
385        };
386        crate::task::joined(
387            executor
388                .spawn(async move {
389                    invoke(
390                        invocation,
391                        args,
392                        &workspace,
393                        &output_root,
394                        cancellation,
395                        environment,
396                        cleanup,
397                    )
398                    .await
399                })
400                .await,
401        )
402        .unwrap_or_else(|_| ToolResult::error("Agent tool execution failed."))
403    }
404
405    fn prepare_session(
406        &self,
407        owner: &crate::config::ArtifactName,
408        command: &crate::config::SessionCommand,
409    ) -> Result<Invocation, String> {
410        let tool = CommandTool {
411            session: None,
412            description: String::new(),
413            input_schema: std::sync::Arc::new(json!({"type":"object"})),
414            protocol: ToolProtocol::Json,
415            command: command.command.clone(),
416            args: command.args.clone(),
417            timeout_ms: None,
418            execution_paths: command.execution_paths.clone(),
419            plain_args: Vec::new(),
420        };
421        self.prepare(owner, &tool, &json!({}))
422            .map_err(|()| "Tool session preparation failed.".into())
423    }
424
425    fn prepare(
426        &self,
427        owner: &crate::config::ArtifactName,
428        tool: &CommandTool,
429        args: &Value,
430    ) -> Result<Invocation, ()> {
431        let cwd = scope::scoped_path(&self.config.root, self.config.artifacts[owner].folder())
432            .map_err(|_| ())?;
433        let program = executable(&self.config.root, &self.scope, owner, &tool.command)?;
434        let argv = match tool.protocol {
435            ToolProtocol::Json => {
436                scope::resolve_argv(self.config, &self.scope, owner, &tool.args).map_err(|_| ())?
437            }
438            ToolProtocol::Plain => tool
439                .plain_args
440                .iter()
441                .map(|arg| {
442                    arg.expand(|name| {
443                        if tool.input_schema["properties"].get(name).is_none() {
444                            return Err("Undeclared plain tool placeholder.".into());
445                        }
446                        let value = args.get(name).ok_or("Missing plain tool argument.")?;
447                        let value = match value {
448                            Value::String(value) => value.clone(),
449                            _ => value.to_string(),
450                        };
451                        if value.contains('\0') {
452                            return Err("Plain tool arguments cannot contain NUL.".into());
453                        }
454                        Ok(value)
455                    })
456                })
457                .collect::<Result<Vec<_>, _>>()
458                .map_err(|_| ())?,
459        };
460        let scoped = self
461            .scope
462            .artifacts
463            .values()
464            .map(|artifact| {
465                let path = match &artifact.path {
466                    crate::config::Target::Live(uri) => ContextTarget::Live(uri.clone()),
467                    _ => ContextTarget::Local(ContextPath(
468                        scope::scoped_path(
469                            &self.config.root,
470                            artifact.referenced_path().ok_or(())?,
471                        )
472                        .map_err(|_| ())?,
473                    )),
474                };
475                Ok((
476                    artifact.name.clone(),
477                    ContextArtifact {
478                        path,
479                        kind: artifact.kind(),
480                        nested: artifact.nested.clone(),
481                        covering_part: artifact.covering_part.clone(),
482                        select: artifact.select().to_vec(),
483                    },
484                ))
485            })
486            .collect::<Result<BTreeMap<_, _>, ()>>()?;
487        let execution_paths = tool
488            .execution_paths
489            .iter()
490            .map(|path| {
491                let resolved =
492                    scope::scoped_path(&self.config.root, Path::new(path)).map_err(|_| ())?;
493                Ok((path.clone(), ContextPath(resolved)))
494            })
495            .collect::<Result<_, ()>>()?;
496        let owner = &self.scope.artifacts[owner].name;
497        let context = ToolContext {
498            artifact_id: owner.clone(),
499            artifact_path: scoped[owner].path.clone(),
500            scope: scoped,
501            execution_paths,
502            output_dir: None,
503            tmp_dir: None,
504        };
505        Ok(Invocation {
506            cwd,
507            program,
508            argv: argv.into_iter().map(Into::into).collect(),
509            context,
510            protocol: tool.protocol,
511            timeout_ms: tool.timeout_ms.unwrap_or(DEFAULT_TIMEOUT),
512        })
513    }
514}
515
516fn executable(
517    root: &Path,
518    scope: &Scope<'_>,
519    owner: &crate::config::ArtifactName,
520    command: &str,
521) -> Result<OsString, ()> {
522    scope::executable(root, scope, owner, command).map_err(|_| ())
523}
524
525fn preflight_executable(
526    root: &Path,
527    scope: &Scope<'_>,
528    owner: &crate::config::ArtifactName,
529    command: &str,
530) -> Result<(), String> {
531    let program = executable(root, scope, owner, command)
532        .map_err(|_| "Tool executable path is unavailable or outside scope.".to_owned())?;
533    let cwd = scope::scoped_path(root, scope.artifacts[owner].folder())
534        .map_err(|error| error.to_string())?;
535    crate::platform::program::resolve(Path::new(&program), &cwd)
536        .map(|_| ())
537        .map_err(|_| {
538            format!(
539                "Tool executable is unavailable: {}",
540                crate::platform::path_text(Path::new(command))
541            )
542        })
543}
544
545async fn invoke(
546    invocation: Invocation,
547    args: Value,
548    workspace: &Path,
549    output_root: &Path,
550    cancellation: CancellationToken,
551    environment: Option<sessions::ownership::Call>,
552    cleanup: impl FnOnce(crate::platform::PrivateTempDir) -> std::io::Result<()>,
553) -> ToolResult {
554    let run = || {
555        let root = workspace::prepare_directory(output_root, workspace).map_err(|_| ())?;
556        crate::platform::private_tempdir_in("tool-", &root).map_err(|_| ())
557    };
558    let Ok(directory) = run() else {
559        return ToolResult::error("Agent tool preparation failed.");
560    };
561    let Invocation {
562        cwd,
563        program,
564        argv,
565        mut context,
566        protocol,
567        timeout_ms,
568    } = invocation;
569    let result = async {
570        let mut command =
571            runtime::Command::prepare(program, argv, workspace, directory.path(), Some(timeout_ms))
572                .map_err(|_| "Agent tool preparation failed.")?;
573        command.cwd = cwd;
574        if let Some(environment) = &environment {
575            command.inherit_session(&environment.environment);
576        }
577        let output_dir = command.directory().join("output");
578        context.output_dir = Some(output_dir.clone());
579        context.tmp_dir = Some(command.directory().join("tmp"));
580        let input = match protocol {
581            ToolProtocol::Json => {
582                json!({"version":JSON_TOOL_INPUT_VERSION,"context":context,"args":args})
583                    .to_string()
584                    .into_bytes()
585            }
586            ToolProtocol::Plain => Vec::new(),
587        };
588        let output = match environment {
589            Some(call) => {
590                call.run(
591                    command.into_process(),
592                    input,
593                    OUTPUT_LIMIT,
594                    cancellation.clone(),
595                )
596                .await
597            }
598            None => {
599                command
600                    .tool_output(input, OUTPUT_LIMIT, cancellation.clone())
601                    .await
602            }
603        }
604        .map_err(|error| {
605            error.argument_refusal().unwrap_or_else(|| match error {
606                crate::process::Error::Timeout => "Agent tool timed out.".into(),
607                crate::process::Error::Cancelled => "Agent tool call was cancelled.".into(),
608                _ => "Agent tool execution failed.".into(),
609            })
610        })?;
611        match protocol {
612            ToolProtocol::Json => {
613                if !output.status.success() {
614                    return Err("Agent tool execution failed.".to_owned());
615                }
616                if output.truncated {
617                    return Err("Agent tool returned invalid output.".to_owned());
618                }
619                result::parse(&output.stdout, &output_dir)
620                    .map_err(|_| "Agent tool returned invalid output.".to_owned())
621            }
622            ToolProtocol::Plain => Ok(result::plain(&output)),
623        }
624    }
625    .await;
626    let cleaned = cleanup(directory);
627    if cancellation.is_cancelled() {
628        return ToolResult::error("Agent tool call was cancelled.");
629    }
630    if cleaned.is_err() {
631        return ToolResult::error("Agent tool cleanup failed.");
632    }
633    result.unwrap_or_else(ToolResult::error)
634}
635
636#[cfg(test)]
637mod tests;
638
639#[cfg(test)]
640#[path = "tools/builtin/tests.rs"]
641mod builtin_tests;