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