artifactize-harness 0.27.1

The Agent evaluation harness for Artifactize.
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
//! Claude Code's own sign-in, behind `login`, `logout` and Settings for the `claude-agent`
//! backend. artifactize only asks and launches: it runs the user's `claude auth status`,
//! `claude auth login` and `claude auth logout`, and never reads, copies or stores the login
//! Claude Code keeps.
//!
//! Without a terminal, `claude auth login` opens the browser itself, prints a URL to open
//! when the browser did not, and then waits until the browser returns to it or the code that
//! URL's page shows is written to its input.

use std::{io, path::Path, time::Duration};

use serde::Deserialize;
use tokio::{
    io::{AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWriteExt, BufReader},
    sync::oneshot,
    time::Instant,
};
use tokio_util::sync::CancellationToken;

use super::{command, shown};
use crate::platform::{self, Environment, ProcessOutcome};

/// Auth commands run outside the project with the same user environment as the eval.
pub struct Host<'a> {
    pub directory: &'a Path,
    pub environment: Environment,
}

/// `claude auth status` reads local files and answers at once; a stalled one is stopped well
/// before a person would give up on Settings.
const ASK_TIMEOUT: Duration = Duration::from_secs(25);
/// Give a person ten minutes to sign in, which on claude.ai may include a code sent by
/// email, without leaving Claude Code waiting indefinitely.
const LOGIN_TIMEOUT: Duration = Duration::from_secs(10 * 60);
/// Keep this much of what Claude Code writes, for the error it fails with; it writes a few
/// lines.
const KEPT_BYTES: usize = 16 * 1024;

/// Read Claude Code's stderr a page at a time: it writes a few lines.
const READ_CHUNK: usize = 4096;

const MISSING: &str =
    "Claude Code (`claude`) is not on PATH; install it to use the claude-agent backend.";

/// Claude Code's sign-in, as Claude Code itself reports it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Status {
    /// `claude` is not on `PATH`.
    Missing,
    SignedOut,
    /// Signed in with `method` (for example `claude.ai`), on `plan` (for example `max`) when
    /// it names one.
    SignedIn {
        method: String,
        plan: Option<String>,
    },
    /// Claude Code could not tell, and why.
    Failed {
        error: String,
    },
}

/// The fields of `claude auth status --json` artifactize shows; the account's email and
/// organization are left unread.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Reported {
    logged_in: bool,
    #[serde(default)]
    auth_method: Option<String>,
    #[serde(default)]
    subscription_type: Option<String>,
}

struct Output {
    status: ProcessOutcome,
    stdout: Vec<u8>,
    stderr: Vec<u8>,
}

/// A descendant outside the group may hold a pipe after cleanup. Keep the wait bounded.
const OUTPUT_CLOSE_GRACE: Duration = Duration::from_secs(5);

#[derive(Debug, thiserror::Error)]
enum AskError {
    #[error("process could not be spawned: {0}")]
    Spawn(#[source] io::Error),
    #[error("process supervision failed: {0}")]
    Wait(#[source] io::Error),
    #[error("process cleanup could not be confirmed: {0}")]
    Cleanup(#[source] io::Error),
    #[error("process timed out")]
    Timeout,
    #[error("process output could not be captured: {0}; the process had ended ({1})")]
    Capture(String, ProcessOutcome),
}

impl Host<'_> {
    fn command(self, args: &[&str], input: bool) -> io::Result<platform::Command> {
        platform::command(
            command::PROGRAM,
            args,
            self.directory,
            &command::environment(self.environment),
            input,
        )
    }
}

async fn prefix(
    mut pipe: impl AsyncRead + Unpin,
    name: &str,
    gone: &CancellationToken,
) -> Result<Vec<u8>, String> {
    let mut output = Vec::new();
    let mut buffer = [0; READ_CHUNK];
    let mut grace = None;
    loop {
        let count = if let Some(deadline) = grace {
            tokio::time::timeout_at(deadline, pipe.read(&mut buffer))
                .await
                .map_err(|_| format!("{name} was still open {}s after the process group was gone, so a process outside the group holds it", OUTPUT_CLOSE_GRACE.as_secs()))?
        } else {
            tokio::select! {
                biased;
                result = pipe.read(&mut buffer) => result,
                _ = gone.cancelled() => {
                    grace = Some(Instant::now() + OUTPUT_CLOSE_GRACE);
                    continue;
                }
            }
        }.map_err(|error| format!("{name} could not be read: {error}"))?;
        if count == 0 {
            return Ok(output);
        }
        output.extend_from_slice(&buffer[..count.min(KEPT_BYTES - output.len())]);
    }
}

async fn capture(host: Host<'_>, args: &[&str]) -> Result<Output, AskError> {
    let deadline = Instant::now() + ASK_TIMEOUT;
    let command = host.command(args, false).map_err(AskError::Spawn)?;
    let mut child = platform::spawn_now(command)
        .await
        .map_err(AskError::Spawn)?;
    let stdout = child.stdout().take().expect("stdout is piped");
    let stderr = child.stderr().take().expect("stderr is piped");
    let gone = CancellationToken::new();
    let wait = async {
        let status = tokio::select! {
            biased;
            _ = tokio::time::sleep_until(deadline) => Err(AskError::Timeout),
            status = child.wait() => status.map_err(AskError::Wait),
        };
        let cleanup = if status.is_err() {
            platform::terminate(&mut child).await
        } else {
            child.cleanup().await.map(|_| ())
        };
        gone.cancel();
        cleanup.map_err(AskError::Cleanup)?;
        status
    };
    let (status, stdout, stderr) = tokio::join!(
        wait,
        prefix(stdout, "stdout", &gone),
        prefix(stderr, "stderr", &gone)
    );
    let status = status?;
    match (stdout, stderr) {
        (Ok(stdout), Ok(stderr)) => Ok(Output {
            status,
            stdout,
            stderr,
        }),
        (Err(error), Ok(_)) | (Ok(_), Err(error)) => Err(AskError::Capture(error, status)),
        (Err(stdout), Err(stderr)) => Err(AskError::Capture(format!("{stdout}; {stderr}"), status)),
    }
}

/// Run `claude` with `args` to its end; `None` when it is not on `PATH`.
async fn ask(host: Host<'_>, args: &[&str]) -> Result<Option<Output>, String> {
    match capture(host, args).await {
        Ok(output) => Ok(Some(output)),
        Err(AskError::Spawn(error)) if error.kind() == io::ErrorKind::NotFound => Ok(None),
        Err(AskError::Timeout) => Err(format!(
            "Claude Code did not answer within {} seconds.",
            ASK_TIMEOUT.as_secs()
        )),
        Err(error) => Err(format!("Cannot run Claude Code: {error}.")),
    }
}

/// Identify the installed native executable without opening a session or signing in.
pub async fn cli_version(host: Host<'_>) -> Result<Option<semver::Version>, String> {
    let Some(output) = ask(host, &["--version"]).await? else {
        return Ok(None);
    };
    output
        .status
        .success()
        .then(|| platform::output_text(&output.stdout))
        .and_then(|text| {
            text.split_whitespace()
                .find_map(|word| semver::Version::parse(word.trim_start_matches('v')).ok())
        })
        .map(Some)
        .ok_or_else(|| "Cannot read the Claude Code version (`claude --version`).".into())
}

/// Ask Claude Code whether it is signed in (`claude auth status --json`).
pub async fn status(host: Host<'_>) -> Status {
    match ask(host, &["auth", "status", "--json"]).await {
        Ok(None) => Status::Missing,
        Ok(Some(output)) => read_status(&output.stdout, &output.stderr, &output.status),
        Err(error) => Status::Failed { error },
    }
}

/// What `claude auth status --json` printed. It prints its JSON also when signed out, then
/// with exit status 1.
fn read_status(stdout: &[u8], stderr: &[u8], ended: &ProcessOutcome) -> Status {
    match serde_json::from_slice::<Reported>(stdout) {
        Ok(reported) if reported.logged_in => Status::SignedIn {
            method: reported
                .auth_method
                .filter(|method| !method.is_empty())
                .unwrap_or_else(|| "unknown".into()),
            plan: reported.subscription_type.filter(|plan| !plan.is_empty()),
        },
        Ok(_) => Status::SignedOut,
        Err(_) => Status::Failed {
            error: failure("could not report its sign-in", stdout, stderr, ended),
        },
    }
}

/// Why Claude Code failed to `doing`: what it wrote on stderr, else on stdout, else how it
/// ended.
fn failure(doing: &str, stdout: &[u8], stderr: &[u8], ended: &ProcessOutcome) -> String {
    let said = [stderr, stdout]
        .into_iter()
        .map(|bytes| shown(&crate::platform::output_text(bytes)))
        .find(|text| !text.is_empty());
    match said {
        Some(said) => format!("Claude Code {doing}: {said}"),
        None => format!("Claude Code {doing}; it ended with {}.", ended),
    }
}

/// Sign Claude Code out (`claude auth logout`).
pub async fn logout(host: Host<'_>) -> Result<(), String> {
    let output = ask(host, &["auth", "logout"]).await?.ok_or(MISSING)?;
    if output.status.success() {
        Ok(())
    } else {
        Err(failure(
            "could not sign out",
            &output.stdout,
            &output.stderr,
            &output.status,
        ))
    }
}

/// What a sign-in asks the person to do: open `url` when the browser Claude Code opened did
/// not, and paste the code its page then shows.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Prompt {
    pub url: url::Url,
}

/// The code Claude Code's sign-in page shows, as pasted: one line, written to Claude Code's
/// input as it is.
fn code(pasted: &str) -> Result<String, String> {
    let code = pasted.trim();
    if code.is_empty() || code.chars().any(char::is_control) {
        Err("Paste the code Claude Code's sign-in page shows, on one line.".into())
    } else {
        Ok(code.to_owned())
    }
}

/// The first `http(s)://` URL in `line`.
fn url_in(line: &str) -> Option<url::Url> {
    let start = line.find("https://").or_else(|| line.find("http://"))?;
    line[start..].split_whitespace().next()?.parse().ok()
}

/// Read `reader` to its end, keeping its last [`KEPT_BYTES`].
async fn tail(reader: Option<impl AsyncRead + Unpin>) -> Vec<u8> {
    let Some(mut reader) = reader else {
        return Vec::new();
    };
    let mut kept = Vec::new();
    let mut buffer = [0; READ_CHUNK];
    while let Ok(count) = reader.read(&mut buffer).await {
        if count == 0 {
            break;
        }
        kept.extend_from_slice(&buffer[..count]);
        if kept.len() > KEPT_BYTES {
            kept.drain(..kept.len() - KEPT_BYTES);
        }
    }
    kept
}

/// The sign-in behind `login claude-agent` for any interface: run `claude auth login`, give
/// `show` the URL it prints once it has opened the browser, and write a code arriving on
/// `pasted` to its input. It ends when Claude Code exits, signed in or with its error, or
/// after ten minutes; dropping the future stops Claude Code and
/// whatever it started, which Claude Code ending on its own leaves running.
pub async fn login_with(
    host: Host<'_>,
    pasted: Option<oneshot::Receiver<String>>,
    show: impl FnOnce(&Prompt),
) -> Result<(), String> {
    let deadline = Instant::now() + LOGIN_TIMEOUT;
    let command = host.command(&["auth", "login"], true);
    let spawned = match command {
        Ok(command) => platform::spawn_windowless(command).await,
        Err(error) => Err(error),
    };
    let mut child = match spawned {
        Ok(child) => child,
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Err(MISSING.into()),
        Err(error) => {
            return Err(format!(
                "Cannot start Claude Code: process could not be spawned: {error}."
            ));
        }
    };
    let mut input = child.stdin().take().expect("stdin is piped");
    let stdout = child.stdout().take().expect("stdout is piped");
    let stderr = child.stderr().take();
    let signing_in = async {
        let mut reader = BufReader::new(stdout);
        let mut bytes = Vec::new();
        let mut said = Vec::new();
        let mut show = Some(show);
        // The URL comes first; what follows is kept for the error Claude Code may end with.
        while reader
            .read_until(b'\n', &mut bytes)
            .await
            .map_err(|error| format!("Cannot read Claude Code's sign-in output: {error}."))?
            > 0
        {
            let line = crate::platform::output_line(&bytes);
            let text = crate::platform::output_text(line);
            if let Some(url) = url_in(&text)
                && let Some(show) = show.take()
            {
                show(&Prompt { url });
            } else {
                said.extend_from_slice(line);
                said.push(b'\n');
                if said.len() > KEPT_BYTES {
                    said.drain(..said.len() - KEPT_BYTES);
                }
            }
            bytes.clear();
        }
        Ok(said)
    };
    let paste = async move {
        // Held open until a code arrives: without one, only the browser finishes the sign-in.
        if let Some(pasted) = pasted
            && let Ok(pasted) = pasted.await
        {
            let code = code(&pasted)?;
            input
                .write_all(format!("{code}\n").as_bytes())
                .await
                .map_err(|error| {
                    format!("Cannot send the sign-in code to Claude Code: {error}.")
                })?;
            // One code per sign-in: Claude Code reads it, then its input closes.
            drop(input);
        }
        std::future::pending::<Result<(), String>>().await
    };
    let (said, errors, exited) = tokio::select! {
        biased;
        ended = async {
            tokio::try_join!(signing_in, async { Ok(tail(stderr).await) }, async {
                child.wait_leader().await.map_err(|error| format!("Cannot wait for Claude Code: {error}."))
            })
        } => ended?,
        Err(error) = paste => return Err(error),
        () = tokio::time::sleep_until(deadline) => {
            return Err("Claude Code sign-in timed out; run `artifactize login claude-agent` again.".into());
        }
    };
    // Claude Code ended on its own: what it started, such as the browser, goes on.
    child
        .release()
        .map_err(|error| format!("Cannot let go of Claude Code's sign-in: {error}."))?;
    if exited.success() {
        Ok(())
    } else {
        Err(failure("could not sign in", &said, &errors, &exited))
    }
}

/// Sign Claude Code in from a terminal: the URL goes to stderr, also with --json, and a code
/// pasted into this process's input goes to Claude Code.
pub async fn login(host: Host<'_>) -> Result<(), String> {
    let (send, receive) = oneshot::channel();
    // Detached: a sign-in finished in the browser leaves this read unanswered.
    std::thread::Builder::new()
        .name("claude-agent-login-input".into())
        .spawn(move || {
            let line = std::io::stdin()
                .lines()
                .map_while(Result::ok)
                .find(|line| !line.trim().is_empty());
            if let Some(line) = line {
                let _ = send.send(line);
            }
        })
        .map_err(|error| format!("Cannot start Claude Code sign-in input: {error}"))?;
    login_with(host, Some(receive), |prompt| {
        use std::io::Write;
        let _ = writeln!(
            std::io::stderr().lock(),
            "Claude Code opened the browser to sign in. If it did not open, open this URL, then paste the code its page shows and press Enter:\n{}",
            prompt.url
        );
    })
    .await
}

#[cfg(test)]
mod tests;