artifactize 0.5.6

The AI-native collaboration layer for one-of-a-kind teammates and their agents: split a project into Artifacts with their own evals, and reuse every review while it still holds.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Scoped audience-specific tools and language-neutral command protocols.

pub mod builtin;
pub mod human;
mod image;
pub mod pins;
mod result;
pub(crate) mod schema;

pub use result::{Content, ToolResult};

use std::{
    collections::BTreeMap,
    ffi::OsString,
    path::{Path, PathBuf},
};

use serde::Serialize;
use serde_json::{Value, json};
use tokio_util::sync::CancellationToken;

use crate::{
    config::{AgentTool, CommandTool, Profile, RepoConfig, ToolProtocol},
    runtime,
    scope::{self, Scope},
    workspace,
};

const DEFAULT_TIMEOUT_MS: u32 = 120_000;
const OUTPUT_LIMIT: usize = 16 * 1024 * 1024;

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolDefinition {
    pub name: String,
    pub artifact_id: String,
    pub description: String,
    pub input_schema: Value,
}

struct RegisteredTool<'a> {
    definition: ToolDefinition,
    declaration: &'a AgentTool,
    validator: jsonschema::Validator,
}

struct Invocation {
    program: OsString,
    argv: Vec<OsString>,
    context: Value,
    protocol: ToolProtocol,
    timeout_ms: u32,
}

/// Borrows the resolved declarations; discovery and listing never execute owner code.
/// Calls own their temporary directories, leaving the caller's output root intact.
pub struct Registry<'a> {
    config: &'a RepoConfig,
    scope: Scope<'a>,
    tools: BTreeMap<String, RegisteredTool<'a>>,
}

impl<'a> Registry<'a> {
    pub fn new(config: &'a RepoConfig, eval_id: &str) -> Result<Self, String> {
        let eval = config
            .evals
            .iter()
            .find(|eval| eval.id == eval_id)
            .ok_or_else(|| format!("Unknown eval: {eval_id}"))?;
        if !matches!(eval.declaration.profile, Profile::Agent { .. }) {
            return Err("Agent tools require an Agent eval.".into());
        }
        Self::with_scope(
            config,
            scope::eval_scope(config, eval).map_err(|e| e.to_string())?,
        )
    }

    pub fn for_artifact(config: &'a RepoConfig, artifact_id: &str) -> Result<Self, String> {
        Self::with_scope(
            config,
            scope::artifact_scope(config, &[artifact_id]).map_err(|e| e.to_string())?,
        )
    }

    fn with_scope(config: &'a RepoConfig, scope: Scope<'a>) -> Result<Self, String> {
        let mut tools = BTreeMap::new();
        for (id, artifact) in &scope.artifacts {
            for (operation, declaration) in &artifact.views.agent_tools {
                let name = format!("{operation}_{id}");
                let description = match declaration {
                    AgentTool::Command(tool) => tool.description.clone(),
                    AgentTool::Builtin(tool) => tool
                        .description
                        .clone()
                        .unwrap_or_else(|| builtin::description(tool.builtin).into()),
                }
                .replace("{artifactName}", id);
                let input_schema = declaration.input_schema();
                let validator = schema::compile(&input_schema)?;
                let entry = RegisteredTool {
                    definition: ToolDefinition {
                        name: name.clone(),
                        artifact_id: (*id).into(),
                        description,
                        input_schema,
                    },
                    declaration,
                    validator,
                };
                if tools.insert(name.clone(), entry).is_some() {
                    return Err(format!("Artifact tool names collide: {name}"));
                }
            }
        }
        Ok(Self {
            config,
            scope,
            tools,
        })
    }

    pub fn list(&self) -> impl Iterator<Item = &ToolDefinition> {
        self.tools.values().map(|tool| &tool.definition)
    }

    /// Resolve static prerequisites without substituting free arguments.
    pub fn preflight(&self, name: &str) -> Result<(), String> {
        let tool = self
            .tools
            .get(name)
            .ok_or("Unknown registered Agent tool.")?;
        let owner = &tool.definition.artifact_id;
        self.scope
            .resolve_input(&self.config.root, owner, "")
            .map_err(|e| e.to_string())?;
        if let AgentTool::Command(command) = tool.declaration {
            preflight_executable(&self.config.root, &self.scope, owner, &command.command)?;
            if matches!(command.protocol, ToolProtocol::Json) {
                scope::resolve_argv(self.config, &self.scope, owner, &command.args)
                    .map_err(|e| e.to_string())?;
            }
            for path in &command.execution_paths {
                scope::scoped_path(&self.config.root, Path::new(path))
                    .map_err(|e| e.to_string())?;
            }
        }
        Ok(())
    }

    pub async fn call(
        &self,
        name: &str,
        args: Value,
        output_root: &Path,
        cancellation: CancellationToken,
    ) -> ToolResult {
        let Some(tool) = self.tools.get(name) else {
            return ToolResult::error("Unknown registered Agent tool.");
        };
        if let Err(message) = schema::validate(&tool.validator, &args) {
            return ToolResult::error(message);
        }
        if cancellation.is_cancelled() {
            return ToolResult::error("Agent tool call was cancelled.");
        }
        let command = match tool.declaration {
            AgentTool::Command(command) => command,
            AgentTool::Builtin(tool_declaration) => {
                let builtin = tool_declaration.builtin;
                let root = self.config.root.clone();
                let owner = tool.definition.artifact_id.clone();
                let artifacts: BTreeMap<_, _> = self
                    .scope
                    .artifacts
                    .iter()
                    .map(|(id, artifact)| ((*id).to_owned(), (*artifact).clone()))
                    .collect();
                let cancellation = cancellation.child_token();
                let _cancel_on_drop = cancellation.clone().drop_guard();
                return tokio::task::spawn_blocking(move || {
                    let scope = Scope {
                        artifacts: artifacts
                            .iter()
                            .map(|(id, artifact)| (id.as_str(), artifact))
                            .collect(),
                    };
                    builtin::call(builtin, &root, &scope, &owner, &args, &cancellation)
                })
                .await
                .unwrap_or_else(|_| ToolResult::error("Built-in Agent tool execution failed."));
            }
        };
        let invocation = match self.prepare(&tool.definition.artifact_id, command, &args) {
            Ok(invocation) => invocation,
            Err(()) => return ToolResult::error("Agent tool preparation failed."),
        };
        let workspace = self.config.root.clone();
        let output_root = output_root.to_owned();
        let cancellation = cancellation.child_token();
        let _cancel_on_drop = cancellation.clone().drop_guard();
        // Keep cleanup alive if the caller drops its future while a command is running.
        tokio::spawn(async move {
            invoke(invocation, args, &workspace, &output_root, cancellation).await
        })
        .await
        .unwrap_or_else(|_| ToolResult::error("Agent tool execution failed."))
    }

    fn prepare(&self, owner: &str, tool: &CommandTool, args: &Value) -> Result<Invocation, ()> {
        let cwd = self
            .scope
            .resolve_input(&self.config.root, owner, "")
            .map_err(|_| ())?;
        let program = executable(&self.config.root, &self.scope, owner, &tool.command)?;
        let argv = match tool.protocol {
            ToolProtocol::Json => {
                scope::resolve_argv(self.config, &self.scope, owner, &tool.args).map_err(|_| ())?
            }
            ToolProtocol::Plain => tool
                .args
                .iter()
                .map(|arg| {
                    plain_argument(arg, |name| {
                        if tool.input_schema["properties"].get(name).is_none() {
                            return Err("Undeclared plain tool placeholder.".into());
                        }
                        let value = args.get(name).ok_or("Missing plain tool argument.")?;
                        let value = match value {
                            Value::String(value) => value.clone(),
                            _ => value.to_string(),
                        };
                        if value.contains('\0') {
                            return Err("Plain tool arguments cannot contain NUL.".into());
                        }
                        Ok(value)
                    })
                })
                .collect::<Result<Vec<_>, _>>()
                .map_err(|_| ())?,
        };
        let mut scoped = serde_json::Map::new();
        for (id, artifact) in &self.scope.artifacts {
            let path = scope::scoped_path(&self.config.root, &artifact.path).map_err(|_| ())?;
            let mut entry =
                json!({"path":path,"children":artifact.children,"mounts":artifact.mounts});
            if let Some(family) = &artifact.family {
                for material in &family.material {
                    scope::scoped_path(&path, Path::new(material)).map_err(|_| ())?;
                }
                entry["family"] = json!({"name":family.name,"material":family.material});
            }
            scoped.insert((*id).into(), entry);
        }
        let mut context = json!({"artifactId":owner,"artifactPath":cwd,"scope":scoped});
        if !tool.execution_paths.is_empty() {
            let mut paths = serde_json::Map::new();
            for path in &tool.execution_paths {
                let resolved =
                    scope::scoped_path(&self.config.root, Path::new(path)).map_err(|_| ())?;
                paths.insert(path.clone(), json!(resolved));
            }
            context["executionPaths"] = paths.into();
        }
        Ok(Invocation {
            program,
            argv: argv.into_iter().map(Into::into).collect(),
            context,
            protocol: tool.protocol,
            timeout_ms: tool.timeout_ms.unwrap_or(DEFAULT_TIMEOUT_MS),
        })
    }
}

fn executable(root: &Path, scope: &Scope<'_>, owner: &str, command: &str) -> Result<OsString, ()> {
    if !Path::new(command).is_absolute() && command.contains('/') {
        let relative = command.strip_prefix("./").unwrap_or(command);
        let program = scope.resolve_input(root, owner, relative).map_err(|_| ())?;
        if !program.is_file() {
            return Err(());
        }
        Ok(program.into_os_string())
    } else {
        Ok(command.into())
    }
}

fn preflight_executable(
    root: &Path,
    scope: &Scope<'_>,
    owner: &str,
    command: &str,
) -> Result<(), String> {
    let program = executable(root, scope, owner, command)
        .map_err(|_| "Tool executable path is unavailable or outside scope.".to_owned())?;
    let found = if Path::new(&program).is_absolute() {
        crate::platform::is_executable(Path::new(&program))
    } else {
        let cwd = scope
            .resolve_input(root, owner, "")
            .map_err(|e| e.to_string())?;
        std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default())
            .any(|dir| crate::platform::is_executable(&cwd.join(dir).join(&program)))
    };
    if found {
        Ok(())
    } else {
        Err(format!("Tool executable is unavailable: {command}"))
    }
}

async fn invoke(
    invocation: Invocation,
    args: Value,
    workspace: &Path,
    output_root: &Path,
    cancellation: CancellationToken,
) -> ToolResult {
    let run = || {
        let root = workspace::prepare_directory(output_root, workspace).map_err(|_| ())?;
        tempfile::Builder::new()
            .prefix("tool-")
            .tempdir_in(root)
            .map_err(|_| ())
    };
    let Ok(directory) = run() else {
        return ToolResult::error("Agent tool preparation failed.");
    };
    let Invocation {
        program,
        argv,
        mut context,
        protocol,
        timeout_ms,
    } = invocation;
    let result = async {
        let mut command =
            runtime::Command::prepare(program, argv, workspace, directory.path(), Some(timeout_ms))
                .map_err(|_| "Agent tool preparation failed.")?;
        command.cwd = PathBuf::from(
            context["artifactPath"]
                .as_str()
                .ok_or("Agent tool preparation failed.")?,
        );
        let output_dir = command.directory().join("output");
        context["outputDir"] = json!(output_dir);
        context["tmpDir"] = json!(command.directory().join("tmp"));
        let input = match protocol {
            ToolProtocol::Json => json!({"version":1,"context":context,"args":args})
                .to_string()
                .into_bytes(),
            ToolProtocol::Plain => Vec::new(),
        };
        let output = command
            .tool_output(input, OUTPUT_LIMIT, cancellation.clone())
            .await
            .map_err(|error| match error {
                crate::process::Error::Timeout => "Agent tool timed out.",
                crate::process::Error::Cancelled => "Agent tool call was cancelled.",
                _ => "Agent tool execution failed.",
            })?;
        match protocol {
            ToolProtocol::Json => {
                if !output.status.success() {
                    return Err("Agent tool execution failed.");
                }
                if output.truncated {
                    return Err("Agent tool returned invalid output.");
                }
                result::parse(&output.stdout, &output_dir)
                    .map_err(|_| "Agent tool returned invalid output.")
            }
            ToolProtocol::Plain => Ok(result::plain(&output)),
        }
    }
    .await;
    let cleaned = directory.close();
    if cancellation.is_cancelled() {
        return ToolResult::error("Agent tool call was cancelled.");
    }
    if cleaned.is_err() {
        return ToolResult::error("Agent tool cleanup failed.");
    }
    result.unwrap_or_else(ToolResult::error)
}

/// Single-pass expansion: substituted values are never interpreted as templates.
/// Doubled braces represent literal braces in a plain argv template.
pub(crate) fn plain_argument(
    template: &str,
    mut value: impl FnMut(&str) -> Result<String, String>,
) -> Result<String, String> {
    let mut result = String::new();
    let mut rest = template;
    while !rest.is_empty() {
        if rest.starts_with("{{") || rest.starts_with("}}") {
            result.push(rest.chars().next().unwrap());
            rest = &rest[2..];
        } else if let Some(tail) = rest.strip_prefix('{') {
            let (name, tail) = tail
                .split_once('}')
                .ok_or("Unclosed plain tool placeholder.")?;
            if name.is_empty() || name.contains('{') {
                return Err("Invalid plain tool placeholder.".into());
            }
            result.push_str(&value(name)?);
            rest = tail;
        } else {
            let character = rest.chars().next().unwrap();
            if character == '}' {
                return Err("Unmatched plain tool closing brace.".into());
            }
            result.push(character);
            rest = &rest[character.len_utf8()..];
        }
    }
    Ok(result)
}

#[cfg(test)]
mod tests;