artifactize-core 0.26.0

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
//! The provider-independent Chat tool set, with file and Verify operations scoped to one worktree.
use std::{
    io::{Read, Write},
    path::{Path, PathBuf},
    time::Duration,
};

use artifactize_tools::{
    Builtin, builtin, files,
    scope::{self, Artifact, ArtifactId, Scope},
};
use serde::Deserialize;
use serde_json::{Value, json};
use tokio_util::sync::CancellationToken;

use crate::{
    runs, runtime,
    tools::{Content, ToolDefinition, ToolResult},
    types::RunId,
    verify_tools,
};

/// Bound each write and the amount an edit can read before replacing a single span.
const EDIT_BYTES: usize = 4 * 1024 * 1024;
/// Commands are stoppable and cannot occupy a Chat tool turn indefinitely.
const COMMAND_TIMEOUT: Duration = Duration::from_secs(120);
const READ_TOOLS: [(Builtin, &str); 4] = [
    (Builtin::Read, "read"),
    (Builtin::List, "list"),
    (Builtin::Glob, "glob"),
    (Builtin::Grep, "grep"),
];

pub(crate) struct Tools<'a> {
    context: &'a runs::Context,
    output: &'a Path,
    checkout: Option<Option<&'a crate::repository::Identity>>,
    owner: ArtifactId,
    scope: Scope,
    definitions: Vec<ToolDefinition>,
}

pub(crate) struct Called {
    pub result: ToolResult,
    pub run: Option<RunId>,
}

impl From<ToolResult> for Called {
    fn from(result: ToolResult) -> Self {
        Self { result, run: None }
    }
}

impl<'a> Tools<'a> {
    pub(crate) fn new(context: &'a runs::Context, output: &'a Path) -> Self {
        let owner: ArtifactId =
            ArtifactId::new("worktree").expect("worktree is an Artifact identifier");
        let artifact = Artifact {
            path: scope::Target::Folder(
                PathBuf::new()
                    .try_into()
                    .expect("the root is a local target"),
            ),
            name: "Worktree".into(),
            nested: Default::default(),
            covering_part: None,
        };
        let scope = Scope {
            artifacts: [(owner.clone(), artifact)].into(),
        };
        let tool = |name: &str, description: String, input_schema: Value| ToolDefinition {
            name: name.parse().expect("built-in Chat tool name"),
            artifact_id: "worktree".parse().expect("tool owner name"),
            description,
            input_schema,
        };
        let mut definitions: Vec<_> = READ_TOOLS
            .iter()
            .map(|&(builtin, name)| {
                tool(
                    name,
                    builtin::description(builtin).to_owned(),
                    builtin::input_schema(builtin),
                )
            })
            .collect();
        definitions.extend([
            tool("write", "Write UTF-8 text to a file under the worktree. The parent directory must exist.".into(),
                json!({"type": "object", "properties": {"path":{"type":"string"},"text":{"type":"string"}}, "required":["path","text"], "additionalProperties":false})),
            tool("edit", "Replace exactly one occurrence of old_text with new_text in a UTF-8 worktree file.".into(),
                json!({"type":"object","properties":{"path":{"type":"string"},"old_text":{"type":"string","minLength":1},"new_text":{"type":"string"}},"required":["path","old_text","new_text"],"additionalProperties":false})),
            tool("run_command", "Run a program and its argument vector from the worktree, using the author's terminal environment. Optional cwd is relative to the worktree.".into(),
                json!({"type":"object","properties":{"program":{"type":"string","minLength":1},"args":{"type":"array","items":{"type":"string"}},"cwd":{"type":"string"}},"required":["program"],"additionalProperties":false})),
        ]);
        definitions.extend(
            verify_tools::tools()
                .into_iter()
                .filter(|tool| verify_tools::chat_tool(tool.name))
                .map(|verify| {
                    let mut schema = verify.schema;
                    if let Some(Value::Object(properties)) = schema.get_mut("properties") {
                        properties.remove("project");
                    }
                    tool(
                        verify.name,
                        verify.description.into_owned(),
                        Value::Object(schema),
                    )
                }),
        );
        Self {
            context,
            output,
            checkout: None,
            owner,
            scope,
            definitions,
        }
    }

    pub(crate) fn guard_checkout(
        mut self,
        identity: Option<&'a crate::repository::Identity>,
    ) -> Self {
        self.checkout = Some(identity);
        self
    }

    pub(crate) fn output(&self) -> &Path {
        self.output
    }

    pub(crate) fn list(&self) -> impl Iterator<Item = &ToolDefinition> {
        self.definitions.iter()
    }

    /// Only the allowlisted read-only and Verify tools exposed to ACP Chat agents over the
    /// one-turn Verify MCP bridge (never file/shell or plugin-mutation tools).
    pub(crate) fn verify_only_list(&self) -> impl Iterator<Item = &ToolDefinition> {
        self.definitions
            .iter()
            .filter(|def| crate::acp::verify_bridge::is_allowlisted(def.name.as_str()))
    }

    /// Invoke one allowlisted Verify/read-only tool from the ACP Verify MCP bridge, remapping
    /// any agent-supplied `verify_start` `request_key` into the disjoint `chat/*` namespace.
    pub(crate) async fn call_acp_verify(
        &self,
        session_id: &crate::types::SessionId,
        send: usize,
        name: &str,
        arguments: Value,
        cancellation: CancellationToken,
    ) -> Called {
        match self
            .execute_acp_verify(session_id, send, name, arguments, cancellation)
            .await
        {
            Ok(result) => result,
            Err(error) => ToolResult::error(error).into(),
        }
    }

    async fn execute_acp_verify(
        &self,
        session_id: &crate::types::SessionId,
        send: usize,
        name: &str,
        arguments: Value,
        cancellation: CancellationToken,
    ) -> Result<Called, String> {
        if cancellation.is_cancelled() {
            return Err("The Chat turn was stopped.".into());
        }
        if !crate::acp::verify_bridge::is_allowlisted(name) {
            return Err(format!(
                "Tool {name:?} is not allowlisted on the ACP Verify bridge."
            ));
        }
        let root = self.context.repo();
        if let Some(identity) = self.checkout {
            let path = root.to_owned();
            let identity = identity.cloned();
            crate::task::blocking(move || super::verify_checkout(&path, identity.as_ref()))
                .await??;
        }
        let raw_value = arguments.clone();
        let arguments = match arguments {
            Value::Object(arguments) => arguments,
            _ => return Err("Tool arguments must be an object.".into()),
        };
        let mut call = verify_tools::Call::parse(name, arguments, time::OffsetDateTime::now_utc())
            .map_err(|error| error.to_string())?;
        if call.project.is_some() {
            return Err("Chat Verify tools are scoped to this session's worktree.".into());
        }
        call.remap_acp_chat_key(session_id, send, &raw_value)?;
        let started = call.started_run();
        let result = call
            .execute(self.context, cancellation, |_| async { Ok(()) })
            .await
            .map_err(|error| error.to_string())?;
        let run = started.then(|| result.observed_run().cloned()).flatten();
        Ok(Called {
            result: ToolResult::success(Content::Json {
                data: serde_json::to_value(result).map_err(|error| error.to_string())?,
            }),
            run,
        })
    }

    pub(crate) async fn call(
        &self,
        name: &str,
        arguments: Value,
        cancellation: CancellationToken,
    ) -> Called {
        match self.execute(name, arguments, cancellation).await {
            Ok(result) => result,
            Err(error) => ToolResult::error(error).into(),
        }
    }

    async fn execute(
        &self,
        name: &str,
        arguments: Value,
        cancellation: CancellationToken,
    ) -> Result<Called, String> {
        if cancellation.is_cancelled() {
            return Err("The Chat turn was stopped.".into());
        }
        let root = self.context.repo();
        if let Some(identity) = self.checkout {
            let path = root.to_owned();
            let identity = identity.cloned();
            crate::task::blocking(move || super::verify_checkout(&path, identity.as_ref()))
                .await??;
        }
        if let Some((builtin, _)) = READ_TOOLS.iter().find(|(_, tool)| *tool == name) {
            let input = builtin::Input::parse(*builtin, arguments)?;
            return Ok(builtin::call(input, root, &self.scope, &self.owner, &cancellation).into());
        }
        match name {
            "write" => {
                let WriteFile { path, text } = decode(arguments)?;
                let target = self.file(&path)?;
                write_file(&target, &text)?;
                Ok(ToolResult::success(Content::Text {
                    text: format!("Wrote {}.", path.as_str()),
                })
                .into())
            }
            "edit" => {
                let EditFile {
                    path,
                    old_text,
                    new_text,
                } = decode(arguments)?;
                let file =
                    scope::open_scoped(root, path.as_str()).map_err(|error| error.to_string())?;
                if !file
                    .metadata()
                    .map_err(|error| error.to_string())?
                    .is_file()
                {
                    return Err("An edit needs an existing file.".into());
                }
                let mut text = String::new();
                file.take(EDIT_BYTES as u64 + 1)
                    .read_to_string(&mut text)
                    .map_err(|error| error.to_string())?;
                if text.len() > EDIT_BYTES || old_text.is_empty() {
                    return Err(
                        "An edit needs a nonempty old_text and a file within the edit limit."
                            .into(),
                    );
                }
                let mut matches = text.match_indices(&old_text);
                let Some((start, _)) = matches.next() else {
                    return Err("old_text does not occur in the file.".into());
                };
                if matches.next().is_some() {
                    return Err("old_text occurs more than once; supply a unique span.".into());
                }
                text.replace_range(start..start + old_text.len(), &new_text);
                write_file(&self.file(&path)?, &text)?;
                Ok(ToolResult::success(Content::Text {
                    text: format!("Edited {}.", path.as_str()),
                })
                .into())
            }
            "run_command" => {
                let Command { program, args, cwd } = decode(arguments)?;
                let folder = self
                    .scope
                    .resolve_input(root, &self.owner, cwd.as_str())
                    .map_err(|error| error.to_string())?;
                let program =
                    crate::platform::program_path(&program).map_err(|error| error.to_string())?;
                let command = runtime::Command::prepare(
                    program.into_os_string(),
                    args.into_iter().map(Into::into).collect(),
                    &folder,
                    self.output,
                    Some(COMMAND_TIMEOUT),
                )
                .map_err(|error| error.to_string())?;
                let output = command
                    .output(Vec::new(), cancellation)
                    .await
                    .map_err(|error| error.to_string())?;
                let text = crate::platform::clean_program_text;
                let stdout = text(&output.stdout);
                let stderr = text(&output.stderr);
                let Some(exit_code) = output.status.code() else {
                    return Err(format!(
                        "Command did not succeed: {}\n{stdout}\n{stderr}",
                        output.status
                    ));
                };
                let command = super::details::CommandOutput {
                    exit_code,
                    stdout: stdout.into(),
                    stderr: stderr.into(),
                    truncated: output.truncated,
                };
                let result = if exit_code == 0 {
                    ToolResult::success(Content::Json {
                        data: serde_json::to_value(command).map_err(|error| error.to_string())?,
                    })
                } else {
                    // A ToolResult error is one text block. Use the same JSON envelope as the
                    // success response so the transcript doesn't infer a numeric status from prose.
                    ToolResult::error(
                        serde_json::to_string(&command).map_err(|error| error.to_string())?,
                    )
                };
                Ok(result.into())
            }
            _ => {
                if !verify_tools::chat_tool(name) {
                    return Err(format!("Unknown Chat tool: {name}"));
                }
                let arguments = match arguments {
                    Value::Object(arguments) => arguments,
                    _ => return Err("Tool arguments must be an object.".into()),
                };
                let call =
                    verify_tools::Call::parse(name, arguments, time::OffsetDateTime::now_utc())
                        .map_err(|error| error.to_string())?;
                if call.project.is_some() {
                    return Err("Chat Verify tools are scoped to this session's worktree.".into());
                }
                let started = call.started_run();
                let result = call
                    .execute(self.context, cancellation, |_| async { Ok(()) })
                    .await
                    .map_err(|error| error.to_string())?;
                let run = started.then(|| result.observed_run().cloned()).flatten();
                Ok(Called {
                    result: ToolResult::success(Content::Json {
                        data: serde_json::to_value(result).map_err(|error| error.to_string())?,
                    }),
                    run,
                })
            }
        }
    }

    /// Resolve the existing parent without following links; creation is limited to one entry.
    fn file(&self, path: &ToolPath) -> Result<PathBuf, String> {
        let path = path.as_str();
        let (parent, name) = path.rsplit_once('/').unwrap_or(("", path));
        if name.is_empty() {
            return Err("A file path is required.".into());
        }
        let parent = self
            .scope
            .resolve_input(self.context.repo(), &self.owner, parent)
            .map_err(|error| error.to_string())?;
        Ok(parent.join(files::path_from_text(name).map_err(|error| error.to_string())?))
    }
}

fn write_file(path: &Path, text: &str) -> Result<(), String> {
    if text.len() > EDIT_BYTES {
        return Err(format!("File content exceeds {EDIT_BYTES} bytes."));
    }
    let mut file =
        crate::platform::paths::open_portable_write(path).map_err(|error| error.to_string())?;
    file.set_len(0)
        .and_then(|()| file.write_all(text.as_bytes()))
        .map_err(|error| error.to_string())
}

fn decode<T: serde::de::DeserializeOwned>(value: Value) -> Result<T, String> {
    serde_json::from_value(value).map_err(|error| error.to_string())
}

/// A tool path after validation at the JSON argument boundary.
#[derive(Default)]
struct ToolPath(String);

impl ToolPath {
    fn as_str(&self) -> &str {
        &self.0
    }

    fn parse<E: serde::de::Error>(text: String) -> Result<Self, E> {
        scope::logical_path(&text).map_err(E::custom)?;
        Ok(Self(text))
    }
}

impl<'de> Deserialize<'de> for ToolPath {
    fn deserialize<D: serde::Deserializer<'de>>(input: D) -> Result<Self, D::Error> {
        Self::parse(String::deserialize(input)?)
    }
}

fn command_directory<'de, D: serde::Deserializer<'de>>(input: D) -> Result<ToolPath, D::Error> {
    let text = String::deserialize(input)?;
    if text == "." {
        return Ok(ToolPath::default());
    }
    ToolPath::parse(text)
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct WriteFile {
    path: ToolPath,
    text: String,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct EditFile {
    path: ToolPath,
    old_text: String,
    new_text: String,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Command {
    program: String,
    #[serde(default)]
    args: Vec<String>,
    #[serde(default, deserialize_with = "command_directory")]
    cwd: ToolPath,
}