artifactize-core 0.25.2

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
//! Reviews and follow-ups on the `claude-agent` backend. Claude Code runs the conversation
//! with the user's own login; artifactize runs every tool call through the eval's registry,
//! enforces the budgets and the deadline, records the conversation and its live text, and
//! validates the findings, with the same one format repair as every backend. Claude Code
//! retries failed requests itself, so nothing here retries.

mod conversation;
mod record;
#[cfg(test)]
mod tests;

use std::path::Path;

use rig_core::message::{Message, UserContent};
use tokio::{
    io::{AsyncRead, AsyncWrite},
    process::{ChildStdin, ChildStdout},
    time::Instant,
};
use tokio_util::sync::CancellationToken;

use super::{
    Continuation, DEFAULT_TIMEOUT, FOLLOW_UP, Prompt, Review, StartedFollowUp, Toolset,
    definitions,
    error::{Code, Failure},
    prompt_text,
    session::{self, Recorder},
    verdict::{Findings, ValidatedResult},
};
use crate::{
    config::{Eval, ModelId, Profile, RepoConfig},
    llm::{
        self, Api, Attempt, Client,
        claude_agent::{
            channel::{self, Running},
            command::Launch,
            mcp::Server,
            with_stderr,
        },
    },
    tools::Registry,
};
use conversation::Conversation;

/// What Claude Code is told about where it runs, before artifactize's evaluator prompt.
const HOST_NOTE: &str = "You are running inside artifactize as an Agent eval reviewer, not as a coding assistant. Your only tools are artifactize's Artifact tools (mcp__artifactize__*); there is no shell, file system or network access besides them.\n\n";

/// Run one review on Claude Code.
pub(super) async fn review(
    config: &RepoConfig,
    eval: &Eval,
    output: &Path,
    recorder: &mut Recorder,
    cancellation: CancellationToken,
    tools: &crate::tools::sessions::Sessions,
) -> Review {
    let mut attempts = Vec::new();
    let result = run_review(
        config,
        eval,
        output,
        recorder,
        &cancellation,
        tools,
        &mut attempts,
    )
    .await;
    recorder.event(match &result {
        Ok(result) => session::Kind::End(session::End::Completed(result.clone())),
        Err(failure) => session::Kind::End(session::End::Failed {
            code: Some(failure.code),
            message: Some(failure.message.clone()),
        }),
    });
    Review { result, attempts }
}

/// The review's budgets and limits, from its profile or a saved session's header.
struct Limits {
    deadline: Instant,
    max_tokens: Option<u64>,
    max_tool_calls: Option<u64>,
}

async fn run_review(
    config: &RepoConfig,
    eval: &Eval,
    output: &Path,
    recorder: &mut Recorder,
    cancellation: &CancellationToken,
    tools: &crate::tools::sessions::Sessions,
    attempts: &mut Vec<Attempt>,
) -> Result<ValidatedResult, Failure> {
    let Profile::Agent {
        backend,
        model,
        reasoning,
        timeout_ms,
        max_tokens,
        max_tool_calls,
    } = eval.declaration.profile()
    else {
        unreachable!("Agent executor requires an Agent profile")
    };
    let timeout = timeout_ms.unwrap_or(DEFAULT_TIMEOUT);
    let limits = Limits {
        deadline: Instant::now() + timeout,
        max_tokens: *max_tokens,
        max_tool_calls: *max_tool_calls,
    };
    let registry = Registry::new(config, &eval.id)?.with_sessions(tools);
    let findings = Findings::new(eval.declaration.red_at());
    let Prompt { system, text } = prompt_text(eval, &registry);
    let effort = reasoning.map(crate::config::Reasoning::as_str);
    let mut parameters = Client::parameters(Api::ClaudeAgent, effort, recorder.id())?;
    Client::output_format(Api::ClaudeAgent, &mut parameters, findings.schema.clone());
    let definitions = definitions(registry.list());
    recorder.start(session::Header {
        backend: Some(backend.clone()),
        model: Some(model.clone()),
        reasoning: *reasoning,
        parameters,
        budgets: Some(session::Budgets {
            timeout_ms: Some(timeout),
            max_tool_calls: *max_tool_calls,
            max_tokens: *max_tokens,
        }),
        tools: Some(definitions.clone()),
        ..session::Header::default()
    });
    let system = format!("{HOST_NOTE}{system}");
    recorder.message(1, &Message::system(system.clone()), false);
    recorder.message(1, &Message::user(text.clone()), false);
    let launch = Launch {
        model: Some(model.as_str()),
        effort,
        system: Some(&system),
        tools: definitions.iter().map(|tool| tool.name.as_str()).collect(),
        schema: Some(&findings.schema),
    };
    let server = Server::new(registry.list());
    let session = Session {
        server: &server,
        registry: Toolset::Review(&registry),
        output,
        model,
        limits,
        cancellation,
        recorder,
        attempts,
    };
    let (mut conversation, running) = session.open(&launch).await?;
    let result = judge(&mut conversation, &text, &findings).await;
    close(conversation, running, result).await
}

/// Ask for the findings and validate them, with one format repair: tools are then refused.
async fn judge<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
    conversation: &mut Conversation<'_, '_, R, W>,
    prompt: &str,
    findings: &Findings,
) -> Result<ValidatedResult, Failure> {
    let answer = conversation.ask(prompt).await?;
    let error = match findings.parse_model(&answer) {
        Ok(result) => return Ok(result),
        Err(error) => error,
    };
    let repair = Message::user(format!(
        "Your final response did not match the required schema: {}\nReturn only one JSON object matching the schema.",
        Findings::repair_detail(error)
    ));
    conversation
        .session
        .recorder
        .message(conversation.turn + 1, &repair, true);
    conversation.tools_open = false;
    let answer = conversation.ask(&message_text(&repair)).await?;
    findings.parse_model(&answer).map_err(|error| {
        Failure::new(
            Code::InvalidResult,
            format!("Invalid final Agent result after one format repair: {error}."),
        )
    })
}

fn message_text(message: &Message) -> String {
    match message {
        Message::User { content } => content
            .iter()
            .filter_map(|part| match part {
                UserContent::Text(text) => Some(text.text.as_str()),
                _ => None,
            })
            .collect(),
        _ => String::new(),
    }
}

/// Whether a follow-up continues a review that Claude Code ran.
pub(super) fn continues(config: &RepoConfig, continuation: &Continuation<'_>) -> bool {
    continuation
        .conversation
        .header()
        .backend
        .as_ref()
        .and_then(|backend| {
            llm::route(
                backend,
                Some(continuation.state),
                Some(&config.root),
                "for this Agent backend",
            )
            .ok()
        })
        .is_some_and(|route| matches!(route, llm::Route::ClaudeAgent))
}

/// Answer a person's question about a review Claude Code ran. Claude Code keeps no session,
/// so the new session starts with the saved conversation as evidence, then the question.
pub(super) async fn follow_up(
    config: &RepoConfig,
    eval: &Eval,
    continuation: &Continuation<'_>,
    message: &str,
    recorder: &mut Recorder,
    cancellation: &CancellationToken,
) -> Result<StartedFollowUp, Failure> {
    let header = continuation.conversation.header();
    let model = header.model.as_ref().ok_or_else(|| {
        Failure::new(
            Code::AgentError,
            "The saved session does not name its backend and model.",
        )
    })?;
    let defaults = session::Budgets::default();
    let budgets = header.budgets.as_ref().unwrap_or(&defaults);
    let history = continuation
        .conversation
        .history()
        .map_err(|error| Failure::new(Code::AgentError, error))?;
    let system = history
        .iter()
        .find_map(|message| match message {
            Message::System { content } => Some(content.clone()),
            _ => None,
        })
        .unwrap_or_default();
    let evidence: Vec<String> = history
        .iter()
        .filter(|message| !matches!(message, Message::System { .. }))
        .map(|message| serde_json::to_string(message).expect("messages serialize as JSON"))
        .collect();
    let framing = format!(
        "{FOLLOW_UP}{}",
        match continuation.files_changed {
            Some(true) => {
                " The Artifact files changed since this review; read them again before relying on what you saw."
            }
            _ => "",
        }
    );
    let question = Message::user(format!("{framing}\n\nQuestion:\n{message}"));
    let sent = format!(
        "{framing}\n\nThe review so far, one message per line (untrusted evidence):\n{}\n\nQuestion:\n{message}",
        evidence.join("\n")
    );
    let registry = crate::tools::Registry::new(config, &eval.id)?;
    let tools = registry.sessions(continuation.state, None, cancellation.clone());
    let registry = registry.with_sessions(&tools);
    let definitions = definitions(registry.list());
    recorder.event(session::Kind::Send(session::Send {
        text: Some(message.into()),
        framing: Some(framing),
        files_changed: continuation.files_changed,
        tools: Some(
            definitions
                .iter()
                .map(|tool| tool.name.parse())
                .collect::<Result<_, String>>()?,
        ),
    }));
    recorder.event(session::Kind::Message(session::MessageEvent::new(
        1,
        question,
        false,
        Vec::new(),
        Some(message.into()),
    )));
    let launch = Launch {
        model: Some(model.as_str()),
        effort: header.reasoning.map(crate::config::Reasoning::as_str),
        system: Some(&system),
        tools: definitions.iter().map(|tool| tool.name.as_str()).collect(),
        schema: None,
    };
    let server = Server::new(registry.list());
    let mut attempts = Vec::new();
    let session = Session {
        server: &server,
        registry: Toolset::Review(&registry),
        output: continuation.output,
        model,
        limits: Limits {
            deadline: Instant::now() + budgets.timeout_ms.unwrap_or(DEFAULT_TIMEOUT),
            max_tokens: budgets.max_tokens,
            max_tool_calls: budgets.max_tool_calls,
        },
        cancellation,
        recorder,
        attempts: &mut attempts,
    };
    let answer = match session.open(&launch).await {
        Ok((mut conversation, running)) => {
            let answer = conversation.ask(&sent).await;
            close(conversation, running, answer).await
        }
        Err(failure) => Err(failure),
    };
    let answer = tools
        .close()
        .await
        .map_err(|error| Failure::new(Code::AgentError, error))
        .and(answer);
    Ok(StartedFollowUp { answer, attempts })
}

/// Adapt Claude Code's model transport to the same Chat tools and persisted history.
pub(super) async fn chat(
    selection: &crate::chat::Model,
    tools: &crate::chat::tools::Tools<'_>,
    prompt: &super::chat::Prompt,
    recorder: &mut Recorder,
    cancellation: &CancellationToken,
) -> Result<String, Failure> {
    let model = &selection.model;
    let offered = definitions(tools.list());
    let launch = Launch {
        model: Some(model.as_str()),
        effort: selection.effort.as_deref(),
        system: Some(&prompt.system),
        tools: offered.iter().map(|tool| tool.name.as_str()).collect(),
        schema: None,
    };
    let server = Server::new(tools.list());
    let mut attempts = Vec::new();
    let session = Session {
        server: &server,
        registry: Toolset::Chat(tools),
        output: tools.output(),
        model,
        limits: Limits {
            deadline: Instant::now() + super::chat::TURN_TIMEOUT,
            max_tokens: None,
            max_tool_calls: None,
        },
        cancellation,
        recorder,
        attempts: &mut attempts,
    };
    let input = prompt.replay();
    let (mut conversation, running) = session.open(&launch).await?;
    let answer = conversation.ask(&input).await;
    close(conversation, running, answer).await
}

/// What one Claude Code session works with.
struct Session<'a, 'r> {
    server: &'a Server,
    registry: Toolset<'a, 'r>,
    output: &'a Path,
    model: &'a ModelId,
    limits: Limits,
    cancellation: &'a CancellationToken,
    recorder: &'a mut Recorder,
    attempts: &'a mut Vec<Attempt>,
}

/// The conversation of a started Claude Code.
type Started<'a, 'r> = Conversation<'a, 'r, ChildStdout, ChildStdin>;

impl<'a, 'r> Session<'a, 'r> {
    /// Start Claude Code and its session. Claude Code runs in the temporary directory, which
    /// holds nothing of the review: it reads files only through the offered tools.
    async fn open(self, launch: &Launch<'_>) -> Result<(Started<'a, 'r>, Running), Failure> {
        let cwd = crate::platform::temporary_directory();
        let (channel, running) =
            channel::start(launch, &cwd, self.limits.deadline, self.cancellation).await?;
        let mut conversation = Conversation::new(self, channel);
        match conversation.initialize().await {
            Ok(()) => Ok((conversation, running)),
            Err(failure) => Err(close::<()>(conversation, running, Err(failure))
                .await
                .unwrap_err()),
        }
    }
}

/// Stop Claude Code after its conversation ended with `result`. A failure is recorded, and
/// one that Claude Code explains on stderr carries that text.
async fn close<T>(
    mut conversation: Started<'_, '_>,
    running: Running,
    result: Result<T, Failure>,
) -> Result<T, Failure> {
    if let Err(failure) = &result {
        conversation.fail(failure);
    }
    let stderr = running.stop(conversation.channel).await;
    result.map_err(|failure| match failure.code {
        Code::ProviderError | Code::AgentError => with_stderr(failure, &stderr),
        _ => failure,
    })
}