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
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! Saved Agent conversations: one append-only JSON Lines file per review session, which
//! `session show` reads and `session send` continues.
//!
//! `$STATE/agent-sessions/` (owner-only) holds `<sessionId>.jsonl`, an owner-only file of
//! one JSON event per line, and `<sessionId>.lock`, which serializes the sends to it:
//!
//! - `review`, first: the session, Run, request and eval ids, the producer and state id,
//!   the backend, model, reasoning, provider parameters, budgets and tool definitions;
//! - `message`: one rig [`Message`] exactly as the provider received or sent it, with the
//!   `turn` (the provider request) that carried it. The system prompt and instructions come
//!   first, then each answer with its reasoning (encrypted reasoning items and thinking
//!   signatures included), tool calls and their results. The repair prompt has `repair`,
//!   and the answer it replaced is the message before it;
//! - `end`: the review's `result`, or its `errorCode` and `error`;
//! - `send` and `answer` around each follow-up, whose messages carry its `send` number.
//!
//! Every event has its time in `at`. Writing never fails a review: an error is reported on
//! stderr and the review goes on without its conversation.

mod gc;

pub use gc::{Collection, Usage, collect, usage};

use std::{
    fmt,
    fs::File,
    io::{BufRead, BufReader, Write},
    path::{Path, PathBuf},
    time::Duration,
};

use rig_core::message::{AssistantContent, Message, ToolResultContent};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use crate::{platform, store::Request};

/// The session store below the state directory.
pub const DIRECTORY: &str = "agent-sessions";
/// The version of the session file's events.
const VERSION: u32 = 1;

/// Where an Agent review's conversation lives: the producing `user@host`, the state (by its
/// stable id), and the Run, request and session ids. Its text form is
/// `user@host/<state>/<runId>/<requestId>/<sessionId>`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionRef {
    pub producer: String,
    pub state: String,
    pub run_id: String,
    pub request_id: String,
    pub session_id: String,
}

impl fmt::Display for SessionRef {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "{}/{}/{}/{}/{}",
            self.producer, self.state, self.run_id, self.request_id, self.session_id
        )
    }
}

impl SessionRef {
    /// The text form; `None` for anything else, such as a bare request or session id.
    pub fn parse(text: &str) -> Option<Self> {
        let mut parts = text.rsplitn(5, '/');
        let (session_id, request_id, run_id, state, producer) = (
            parts.next()?,
            parts.next()?,
            parts.next()?,
            parts.next()?,
            parts.next()?,
        );
        let reference = Self {
            producer: producer.into(),
            state: state.into(),
            run_id: run_id.into(),
            request_id: request_id.into(),
            session_id: session_id.into(),
        };
        reference.valid().then_some(reference)
    }

    /// Bounded, printable fields; the ids are single path segments. A reference from a remote
    /// record is checked before it is kept.
    pub fn valid(&self) -> bool {
        let printable =
            |value: &str| (1..=200).contains(&value.len()) && !value.chars().any(char::is_control);
        printable(&self.producer)
            && [
                &self.state,
                &self.run_id,
                &self.request_id,
                &self.session_id,
            ]
            .into_iter()
            .all(|id| printable(id) && valid_id(id))
    }
}

/// A session or state id: letters, digits, `-`, `_` and `.`, never only dots.
fn valid_id(id: &str) -> bool {
    (1..=200).contains(&id.len())
        && id.bytes().any(|byte| byte != b'.')
        && id
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
}

/// The session store of a state.
pub fn directory(state: &Path) -> PathBuf {
    state.join(DIRECTORY)
}

/// The conversation file of a session id.
pub fn path(state: &Path, id: &str) -> Result<PathBuf, String> {
    if !valid_id(id) {
        return Err(format!("Invalid Agent session id: {id:?}."));
    }
    Ok(directory(state).join(format!("{id}.jsonl")))
}

/// Where new conversations are saved, and as which producer and state; `None` when saving is
/// off (`agentSessions.enabled: false` in `limits.json`).
#[derive(Debug, Clone)]
pub struct Saving {
    pub state: PathBuf,
    pub state_id: String,
    pub producer: String,
}

fn warn(message: &str) {
    let _ = writeln!(std::io::stderr().lock(), "{message}");
}

/// Appends one session's events. It writes nothing when saving is off, and after a failed
/// write it reports the error once and writes nothing more.
pub struct Recorder {
    id: String,
    target: Option<(PathBuf, Value)>,
    reference: Option<SessionRef>,
    file: Option<File>,
    /// The follow-up whose events this appends.
    send: Option<usize>,
}

impl Recorder {
    /// A session that is not saved.
    pub fn off(id: &str) -> Self {
        Self {
            id: id.into(),
            target: None,
            reference: None,
            file: None,
            send: None,
        }
    }

    /// The recorder of a request's new review session `id`.
    pub fn new(saving: Option<&Saving>, request: &Request, id: &str) -> Self {
        let Some(saving) = saving else {
            return Self::off(id);
        };
        let file = match path(&saving.state, id) {
            Ok(path) => path,
            Err(error) => {
                warn(&error);
                return Self::off(id);
            }
        };
        let reference = SessionRef {
            producer: saving.producer.clone(),
            state: saving.state_id.clone(),
            run_id: request.run_id.clone(),
            request_id: request.id.clone(),
            session_id: id.into(),
        };
        let mut identity = json!(reference);
        identity["evalId"] = json!(request.eval_id);
        identity["target"] = json!(request.target);
        Self {
            target: Some((file, identity)),
            ..Self::off(id)
        }
    }

    /// Append follow-up `send` to the saved conversation at `path`.
    pub(crate) fn append(path: &Path, id: &str, send: usize) -> Result<Self, String> {
        let file = platform::open_no_follow(File::options().append(true), path)
            .map_err(|error| format!("Cannot open Agent session {id}: {error}"))?;
        Ok(Self {
            file: Some(file),
            send: Some(send),
            ..Self::off(id)
        })
    }

    pub fn id(&self) -> &str {
        &self.id
    }

    /// The saved conversation's reference, once its first event is written.
    pub fn reference(&self) -> Option<&SessionRef> {
        self.reference.as_ref()
    }

    /// Create the session file with its `review` event: the identity, then `details`.
    pub(crate) fn start(&mut self, details: Value) {
        let Some((path, identity)) = self.target.take() else {
            return;
        };
        let reference = serde_json::from_value(identity.clone()).expect("a session reference");
        match create(&path) {
            Ok(file) => {
                self.file = Some(file);
                let mut event = json!({"kind":"review","version":VERSION});
                for (name, value) in identity
                    .as_object()
                    .into_iter()
                    .chain(details.as_object())
                    .flatten()
                {
                    event[name] = value.clone();
                }
                self.event(event);
                if self.file.is_some() {
                    self.reference = Some(reference);
                }
            }
            Err(error) => self.fail(&error),
        }
    }

    /// One message of `turn`; `repair` marks the prompt that asked for the verdict again.
    pub(crate) fn message(&mut self, turn: usize, message: &Message, repair: bool) {
        if self.file.is_none() {
            return;
        }
        let mut event = json!({"kind":"message","turn":turn,"message":message});
        if repair {
            event["repair"] = json!(true);
        }
        self.event(event);
    }

    /// Append an event, stamped with its time and the follow-up it belongs to.
    pub(crate) fn event(&mut self, mut event: Value) {
        let Some(file) = &mut self.file else {
            return;
        };
        if let Some(send) = self.send {
            event["send"] = json!(send);
        }
        event["at"] = json!(crate::broker::now());
        let mut line = serde_json::to_vec(&event).expect("session events are JSON");
        line.push(b'\n');
        if let Err(error) = file.write_all(&line).and_then(|()| file.flush()) {
            self.fail(&error.to_string());
        }
    }

    fn fail(&mut self, error: &str) {
        self.file = None;
        warn(&format!(
            "Cannot save Agent session {}: {error}; the review goes on without saving it.",
            self.id
        ));
    }
}

/// A new owner-only session file in an owner-only session store.
fn create(path: &Path) -> Result<File, String> {
    let directory = path.parent().expect("a session file has a directory");
    platform::create_private_dir_all(directory).map_err(|e| e.to_string())?;
    if !platform::is_private_dir(directory).map_err(|e| e.to_string())? {
        return Err(format!(
            "{} must have owner-only permissions.",
            directory.display()
        ));
    }
    let file = platform::open_no_follow(
        platform::private_options().append(true).create_new(true),
        path,
    )
    .map_err(|e| e.to_string())?;
    platform::restrict_file(&file).map_err(|e| e.to_string())?;
    Ok(file)
}

/// A saved conversation, read whole.
#[derive(Debug)]
pub struct Conversation {
    pub path: PathBuf,
    pub events: Vec<Value>,
}

impl Conversation {
    /// Read a session file; `None` when it does not exist. A last line cut short by a crash
    /// is left out.
    pub fn load(path: &Path) -> Result<Option<Self>, String> {
        let file = match platform::open_no_follow(File::options().read(true), path) {
            Ok(file) => file,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(error) => return Err(format!("Cannot read {}: {error}", path.display())),
        };
        if !file.metadata().map_err(|e| e.to_string())?.is_file() {
            return Err(format!("{} is not a regular file.", path.display()));
        }
        let lines: Vec<String> = BufReader::new(file)
            .lines()
            .collect::<Result<_, _>>()
            .map_err(|e| format!("Cannot read {}: {e}", path.display()))?;
        let count = lines.len();
        let mut events = Vec::new();
        for (index, line) in lines.into_iter().enumerate() {
            match serde_json::from_str::<Value>(&line) {
                Ok(event) if event.is_object() => events.push(event),
                _ if index + 1 == count => {}
                _ => {
                    return Err(format!(
                        "{} line {} is not a session event.",
                        path.display(),
                        index + 1
                    ));
                }
            }
        }
        if events.first().is_none_or(|event| event["kind"] != "review") {
            return Err(format!("{} has no review event.", path.display()));
        }
        Ok(Some(Self {
            path: path.into(),
            events,
        }))
    }

    /// The `review` event.
    pub fn header(&self) -> &Value {
        &self.events[0]
    }

    /// How many follow-ups were sent.
    pub fn sends(&self) -> usize {
        self.events
            .iter()
            .filter(|event| event["kind"] == "send")
            .count()
    }

    /// Every message in order, the review's and its follow-ups', ready to send again. Tool
    /// calls a stopped review never answered get an error result, since a provider expects
    /// every call answered.
    pub fn history(&self) -> Result<Vec<Message>, String> {
        let mut messages = self
            .events
            .iter()
            .filter(|event| event["kind"] == "message")
            .map(|event| serde_json::from_value::<Message>(event["message"].clone()))
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| format!("{}: {e}", self.path.display()))?;
        if let Some(Message::Assistant { content, .. }) = messages.last() {
            let results: Vec<_> = content
                .iter()
                .filter_map(|part| match part {
                    AssistantContent::ToolCall(call) => {
                        Some(call.result(vec![ToolResultContent::text(
                            "Not run: the review stopped before this tool call completed.",
                        )]))
                    }
                    _ => None,
                })
                .collect();
            if !results.is_empty() {
                messages.push(Message::tool_results(results));
            }
        }
        Ok(messages)
    }
}

/// Hold `<sessionId>.lock` until the returned file drops: sends to one session take turns.
pub async fn lock(state: &Path, id: &str) -> Result<File, String> {
    let path = path(state, id)?.with_extension("lock");
    let file = platform::open_no_follow(
        platform::private_options()
            .read(true)
            .write(true)
            .create(true)
            .truncate(false),
        &path,
    )
    .map_err(|e| format!("Cannot lock Agent session {id}: {e}"))?;
    loop {
        match file.try_lock() {
            Ok(()) => return Ok(file),
            Err(std::fs::TryLockError::WouldBlock) => {
                tokio::time::sleep(Duration::from_millis(25)).await;
            }
            Err(std::fs::TryLockError::Error(error)) => {
                return Err(format!("Cannot lock Agent session {id}: {error}"));
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn reference() -> SessionRef {
        SessionRef {
            producer: "alice@laptop".into(),
            state: "6f1c0a52-8d1e-4c43-9a55-31f6a7f2d0e4".into(),
            run_id: "run-Hq2b9X".into(),
            request_id: "run-Hq2b9X-3".into(),
            session_id: "0e8c7c2e-2a49-4b8e-9f7a-5d7a0c3b1f20".into(),
        }
    }

    #[test]
    fn references_round_trip_through_their_text_form() {
        let reference = reference();
        let text = reference.to_string();
        assert_eq!(
            text,
            "alice@laptop/6f1c0a52-8d1e-4c43-9a55-31f6a7f2d0e4/run-Hq2b9X/run-Hq2b9X-3/0e8c7c2e-2a49-4b8e-9f7a-5d7a0c3b1f20"
        );
        assert_eq!(SessionRef::parse(&text), Some(reference));
        // A producer may hold a slash; the ids never do.
        let odd = SessionRef {
            producer: "a/b@host".into(),
            ..self::reference()
        };
        assert_eq!(SessionRef::parse(&odd.to_string()), Some(odd));
        for text in [
            "run-Hq2b9X-3",
            "0e8c7c2e-2a49-4b8e-9f7a-5d7a0c3b1f20",
            "a/b/c/d",
            "alice@laptop/state/run/../session",
            "alice@laptop/state/run/request/",
            "alice@laptop/st ate/run/request/session",
        ] {
            assert_eq!(SessionRef::parse(text), None, "{text}");
        }
        assert!(path(Path::new("/state"), "..").is_err());
        assert!(path(Path::new("/state"), "a/b").is_err());
    }

    #[test]
    fn a_session_that_cannot_be_written_is_skipped() {
        let root = tempfile::tempdir().unwrap();
        // The store's place is taken by a file, so the session cannot be created.
        let state = root.path().join("state");
        std::fs::create_dir(&state).unwrap();
        std::fs::write(directory(&state), "not a directory").unwrap();
        let reference = reference();
        let mut recorder = Recorder {
            target: Some((
                path(&state, &reference.session_id).unwrap(),
                json!(reference),
            )),
            ..Recorder::off(&reference.session_id)
        };
        recorder.start(json!({"backend":"openai"}));
        recorder.message(1, &Message::user("still recorded nowhere"), false);
        recorder.event(json!({"kind":"end"}));
        assert!(recorder.reference().is_none());
        assert!(std::fs::metadata(directory(&state)).unwrap().is_file());
    }
}