ultron-usage 1.0.2

Session usage: a session file's usage log (`ultron/usage-cli.ts` reader), its session report and the report's text, for `ultron usage`, `/usage` and `ultron mcp`'s `usage.report`
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
//! A native session file read for the session report without opening the session (`ultron/session-log.ts`): a
//! digest of each entry (who wrote it and what it used, never its text), the latest values of the namespaces the
//! report reads, and every operation's lane and result.

use crate::stats::{cell_apis, classify_nudge};
use indexmap::IndexMap;
use serde_json::{Map, Value};
use session_journal::catalog::HeaderLine;
use session_journal::ns;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct LogUsage {
    pub input: f64,
    pub output: f64,
    pub cache_read: f64,
    pub cache_write: f64,
    pub total_tokens: f64,
    /// Provider-reported cost; None when the response carried none.
    pub cost: Option<f64>,
}

#[derive(Clone, Debug, PartialEq)]
pub struct LogToolCall {
    pub name: String,
    /// For an `rlm` cell: the REPL APIs its code names.
    pub apis: Option<Vec<&'static str>>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EntryKind {
    User,
    Assistant,
    ToolResult,
    Custom,
    Compaction,
    BranchSummary,
    Other,
}

#[derive(Clone, Debug, PartialEq)]
pub struct LogEntry {
    pub id: String,
    pub parent_id: Option<String>,
    pub timestamp: f64,
    pub kind: EntryKind,
    pub provider: Option<String>,
    pub model: Option<String>,
    pub usage: Option<LogUsage>,
    pub tool_calls: Vec<LogToolCall>,
    pub tool_name: Option<String>,
    pub is_error: bool,
    pub redactions: f64,
    pub nudge: Option<&'static str>,
    /// An automatic memory recall (an `ultron.memory` custom message).
    pub recall: Option<Recall>,
}

/// What one automatic recall put in front of the model (session-core `auto_memory::recall_message`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Recall {
    pub memories: usize,
    pub brief: bool,
    pub stale: usize,
}

#[derive(Clone, Debug, PartialEq)]
pub struct LogUsageRow {
    pub usage: LogUsage,
    pub entry_id: Option<String>,
    pub adjustment: bool,
}

/// One model response of a durable runtime conversation other than the root's (an `rlm.spawn` child, a typed agent,
/// another root conversation): its `ultron.assistant` entry in the session's durable records (`ultron.module/durable`).
/// The root conversation's responses are transcript entries already, so they are not listed.
#[derive(Clone, Debug, PartialEq)]
pub struct DurableResponse {
    /// The lane the conversation runs: its owning child task's name (`ultron.rlm-child.<task>`); none for another
    /// root conversation.
    pub lane: Option<String>,
    /// Whether a task (a subagent) owns the conversation.
    pub owned: bool,
    /// `provider/model` of the response.
    pub model: String,
    pub usage: LogUsage,
}

/// What the durable records say, gathered while reading (resolved into [`DurableResponse`]s at the end).
#[derive(Default)]
struct DurableDigest {
    /// Conversation id -> its owning task id (none for a root conversation).
    owners: std::collections::HashMap<u64, Option<u64>>,
    /// Task id -> its `input.name` (a child task's lane).
    task_names: std::collections::HashMap<u64, String>,
    /// (conversation, `provider/model`, usage), in commit order.
    responses: Vec<(u64, String, LogUsage)>,
}

/// A durable commit line: `{"kind":"list","op":"append","seq":N,"namespace":"ultron.module","key":"durable",...}`.
static DURABLE_MARK: std::sync::LazyLock<String> =
    std::sync::LazyLock::new(|| format!(r#""namespace":"{}","key":"{}""#, ns::MODULE, ns::DURABLE_KEY));

/// Whether a list-append line is a durable commit: its namespace and key come within its first bytes (as
/// `state::commit_write` orders a list append's fields).
fn is_durable_commit(line: &str) -> bool {
    let head = &line.as_bytes()[..line.len().min(160)];
    head.windows(DURABLE_MARK.len()).any(|w| w == DURABLE_MARK.as_bytes())
}

impl DurableDigest {
    /// One durable commit (`{seq, writes}`).
    fn commit(&mut self, record: &Value) {
        for write in record.get("writes").and_then(Value::as_array).into_iter().flatten() {
            let value = &write["value"];
            match write.get("type").and_then(Value::as_str) {
                Some("conversation") => {
                    if let Some(id) = value["id"].as_u64() {
                        self.owners.insert(id, value["owner"]["taskId"].as_u64());
                    }
                }
                Some("task") => {
                    if let (Some(id), Some(name)) = (value["id"].as_u64(), value["input"]["name"].as_str()) {
                        self.task_names.entry(id).or_insert_with(|| name.to_string());
                    }
                }
                Some("entry") if value["kind"] == harness::chat::entries::ASSISTANT => {
                    let Some(conversation) = value["conversationId"].as_u64() else {
                        continue;
                    };
                    if conversation == durable::ROOT_CONVERSATION_ID.0 {
                        continue;
                    }
                    let message = &value["model"][0];
                    let Some(usage) = log_usage(message.get("usage")) else {
                        continue;
                    };
                    let model = format!(
                        "{}/{}",
                        message["provider"].as_str().unwrap_or("unknown"),
                        message["model"].as_str().unwrap_or("unknown")
                    );
                    self.responses.push((conversation, model, usage));
                }
                _ => {}
            }
        }
    }

    fn resolve(self) -> Vec<DurableResponse> {
        self.responses
            .into_iter()
            .map(|(conversation, model, usage)| {
                let owner = self.owners.get(&conversation).copied().flatten();
                DurableResponse {
                    lane: owner.and_then(|task| self.task_names.get(&task).cloned()),
                    owned: owner.is_some(),
                    model,
                    usage,
                }
            })
            .collect()
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct LogOperation {
    pub id: String,
    pub lane: String,
    pub kind: String,
    pub started_at: f64,
}

#[derive(Clone, Debug, PartialEq)]
pub struct LogResult {
    pub operation_id: String,
    pub kind: String,
    pub status: String,
    pub from_tip_id: Option<String>,
    pub tip_id: Option<String>,
    pub started_at: f64,
    pub ended_at: f64,
}

#[derive(Clone, Debug, PartialEq)]
pub struct Header {
    pub id: String,
    pub cwd: String,
    pub created_at: f64,
    pub parent_session_id: Option<String>,
}

#[derive(Clone, Debug, PartialEq)]
pub struct SessionLog {
    pub path: PathBuf,
    pub header: Header,
    pub modified_at: f64,
    pub bytes: u64,
    pub entries: Vec<LogEntry>,
    pub usage_rows: Vec<LogUsageRow>,
    /// Latest value by `namespace/key`, for the namespaces in [`KEPT_NAMESPACES`].
    pub values: IndexMap<String, Value>,
    pub operations: IndexMap<String, LogOperation>,
    pub results: Vec<LogResult>,
    /// Responses of the durable runtime's non-root conversations (sub-agents), from its records.
    pub durable_responses: Vec<DurableResponse>,
    pub unreadable_lines: u64,
}

/// A read failure: `Session` for a file that is not a native session (`SessionLogError`), `Io` otherwise.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LogError {
    Session(String),
    Io(String),
}

impl LogError {
    pub fn message(&self) -> &str {
        match self {
            LogError::Session(m) | LogError::Io(m) => m,
        }
    }
}

const KEPT_NAMESPACES: [&str; 9] = [
    ns::SESSION_NAME,
    ns::LANE_CONFIG,
    ns::BRANCH_TIP,
    ns::TASKS,
    ns::USAGE,
    ns::RLM_FRAMES,
    ns::MEMORY_STATE,
    ns::MODULE,
    "ultron.claude-code.lanes",
];

pub fn record(value: Option<&Value>) -> Option<&Map<String, Value>> {
    value.and_then(Value::as_object)
}

fn amount(value: Option<&Value>) -> f64 {
    match value.and_then(Value::as_f64) {
        Some(n) if n.is_finite() && n > 0.0 => n,
        _ => 0.0,
    }
}

pub fn log_usage(value: Option<&Value>) -> Option<LogUsage> {
    let usage = record(value)?;
    let cost = record(usage.get("cost"))
        .and_then(|c| c.get("total"))
        .and_then(Value::as_f64);
    let input = amount(usage.get("input"));
    let output = amount(usage.get("output"));
    let cache_read = amount(usage.get("cacheRead"));
    let cache_write = amount(usage.get("cacheWrite"));
    let total = amount(usage.get("totalTokens"));
    Some(LogUsage {
        input,
        output,
        cache_read,
        cache_write,
        total_tokens: if total != 0.0 {
            total
        } else {
            input + output + cache_read + cache_write
        },
        cost: cost.filter(|c| c.is_finite() && *c >= 0.0),
    })
}

fn text_of(content: Option<&Value>) -> String {
    match content {
        Some(Value::String(s)) => s.clone(),
        Some(Value::Array(parts)) => parts
            .iter()
            .filter_map(Value::as_object)
            .filter(|p| p.get("type").and_then(Value::as_str) == Some("text"))
            .filter_map(|p| p.get("text").and_then(Value::as_str))
            .collect(),
        _ => String::new(),
    }
}

fn timestamp_of(value: Option<&Value>) -> f64 {
    value.and_then(Value::as_f64).filter(|n| n.is_finite()).unwrap_or(0.0)
}

fn string_of(value: Option<&Value>) -> Option<String> {
    value.and_then(Value::as_str).map(str::to_string)
}

fn digest_entry(write: &Map<String, Value>) -> Option<LogEntry> {
    let id = write.get("id")?.as_str()?.to_string();
    let mut entry = LogEntry {
        id,
        parent_id: string_of(write.get("parentId")),
        timestamp: timestamp_of(write.get("timestamp")),
        kind: EntryKind::Other,
        provider: None,
        model: None,
        usage: None,
        tool_calls: Vec::new(),
        tool_name: None,
        is_error: false,
        redactions: 0.0,
        nudge: None,
        recall: None,
    };
    let kind = write.get("type").and_then(Value::as_str);
    if let Some(k) = kind.and_then(|k| match k {
        "compaction" => Some(EntryKind::Compaction),
        "branch_summary" => Some(EntryKind::BranchSummary),
        "custom" => Some(EntryKind::Custom),
        _ => None,
    }) {
        entry.kind = k;
        entry.usage = log_usage(write.get("usage"));
        return Some(entry);
    }
    let Some(message) = record(write.get("message")).filter(|_| kind == Some("message")) else {
        return Some(entry);
    };
    match message.get("role").and_then(Value::as_str) {
        Some("assistant") => {
            entry.kind = EntryKind::Assistant;
            entry.provider = string_of(message.get("provider"));
            entry.model = string_of(message.get("model"));
            entry.usage = log_usage(message.get("usage"));
            for part in message.get("content").and_then(Value::as_array).into_iter().flatten() {
                let Some(item) = part.as_object() else { continue };
                if item.get("type").and_then(Value::as_str) != Some("toolCall") {
                    continue;
                }
                let Some(name) = item.get("name").and_then(Value::as_str) else {
                    continue;
                };
                let code = record(item.get("arguments"))
                    .and_then(|a| a.get("code"))
                    .and_then(Value::as_str);
                entry.tool_calls.push(LogToolCall {
                    name: name.to_string(),
                    apis: code.filter(|_| name == "rlm").map(cell_apis),
                });
            }
        }
        Some("toolResult") => {
            entry.kind = EntryKind::ToolResult;
            entry.tool_name = string_of(message.get("toolName"));
            entry.is_error = message.get("isError") == Some(&Value::Bool(true));
            entry.redactions = (text_of(message.get("content")).matches("[REDACTED:").count()) as f64;
        }
        Some("user") => {
            entry.kind = EntryKind::User;
            entry.nudge = classify_nudge(&text_of(message.get("content")));
        }
        Some("custom") => {
            entry.kind = EntryKind::Custom;
            if message.get("customType").and_then(Value::as_str) == Some(protocol::custom_types::RECALLED_MEMORY) {
                let details = record(message.get("details"));
                let field = |key: &str| details.and_then(|d| d.get(key));
                entry.recall = Some(Recall {
                    memories: field("ids").and_then(Value::as_array).map_or(0, Vec::len),
                    brief: field("digest").is_some_and(|d| !d.is_null()),
                    stale: field("stale").and_then(Value::as_u64).unwrap_or(0) as usize,
                });
            }
        }
        _ => {}
    }
    Some(entry)
}

fn parse_header(line: &str, path: &Path) -> Result<Header, LogError> {
    let shown = path.display();
    let not_native = || LogError::Session(format!("{shown} is not a native Ultron session file"));
    let h = match HeaderLine::parse(line) {
        HeaderLine::NotJson => {
            return Err(LogError::Session(format!(
                "{shown} is not a session file (its first line is not JSON)"
            )));
        }
        HeaderLine::Pi(h) if h.contains_key("version") => {
            return Err(LogError::Session(format!(
                "{shown} is a Pi-format session (version {}); only native Ultron sessions are reported",
                jsrt::value::string(h.get("version"))
            )));
        }
        HeaderLine::Native(h) => h,
        HeaderLine::Pi(_) | HeaderLine::Other => return Err(not_native()),
    };
    let (Some(id), Some(cwd)) = (
        h.get("id").and_then(Value::as_str),
        h.get("cwd").and_then(Value::as_str),
    ) else {
        return Err(not_native());
    };
    Ok(Header {
        id: id.to_string(),
        cwd: cwd.to_string(),
        created_at: timestamp_of(h.get("createdAt")),
        parent_session_id: string_of(h.get("parentSessionId")),
    })
}

/// Lines as `readline` yields them: split on `\n` (a `\r` before it dropped), the last one even without a newline.
fn for_each_line(path: &Path, mut each: impl FnMut(&str) -> Result<bool, LogError>) -> Result<(), LogError> {
    let file = std::fs::File::open(path).map_err(|e| LogError::Io(jsrt::fs::error_message(&e, "open", path)))?;
    let mut reader = BufReader::new(file);
    let mut buffer = Vec::new();
    loop {
        buffer.clear();
        let read = reader
            .read_until(b'\n', &mut buffer)
            .map_err(|e| LogError::Io(e.to_string()))?;
        if read == 0 {
            return Ok(());
        }
        if buffer.last() == Some(&b'\n') {
            buffer.pop();
            if buffer.last() == Some(&b'\r') {
                buffer.pop();
            }
        }
        if !each(&String::from_utf8_lossy(&buffer))? {
            return Ok(());
        }
    }
}

/// Read only a session file's header (its first line).
pub fn read_session_header(path: &Path) -> Result<Header, LogError> {
    let mut header = None;
    for_each_line(path, |line| {
        header = Some(parse_header(line, path)?);
        Ok(false)
    })?;
    header.ok_or_else(|| LogError::Session(format!("{} is empty", path.display())))
}

/// File modification time in milliseconds (`Math.round(stat.mtimeMs)`) and size.
pub fn file_times(path: &Path) -> Result<(f64, u64), LogError> {
    let meta = std::fs::metadata(path).map_err(|e| LogError::Io(jsrt::fs::error_message(&e, "stat", path)))?;
    Ok((meta.modified().map_or(0.0, jsrt::date::mtime_ms).round(), meta.len()))
}

/// Read a native session file. Fails with [`LogError::Session`] for a file that is not one.
pub fn read_session_log(path: &Path) -> Result<SessionLog, LogError> {
    let (modified_at, bytes) = file_times(path)?;
    let header = read_session_header(path)?;
    let mut log = SessionLog {
        path: path.to_path_buf(),
        header,
        modified_at,
        bytes,
        entries: Vec::new(),
        usage_rows: Vec::new(),
        values: IndexMap::new(),
        operations: IndexMap::new(),
        results: Vec::new(),
        durable_responses: Vec::new(),
        unreadable_lines: 0,
    };
    let mut durable = DurableDigest::default();
    // List appends are skipped unread (stream frames are most of a file), except the durable runtime's commits.
    let skip = |line: &str| line.starts_with(r#"{"kind":"list""#) && !is_durable_commit(line);
    session_journal::catalog::scan_writes(path, skip, |writes| {
        let Some(writes) = writes else {
            log.unreadable_lines += 1;
            return;
        };
        for write in writes.iter().filter_map(Value::as_object) {
            apply(&mut log, &mut durable, write);
        }
    })
    .map_err(|e| LogError::Io(jsrt::fs::error_message(&e, "open", path)))?;
    log.durable_responses = durable.resolve();
    Ok(log)
}

fn apply(log: &mut SessionLog, durable: &mut DurableDigest, write: &Map<String, Value>) {
    let kind = write.get("kind").and_then(Value::as_str);
    if kind == Some("list") {
        if write.get("op").and_then(Value::as_str) == Some("append")
            && write.get("namespace").and_then(Value::as_str) == Some(ns::MODULE)
            && write.get("key").and_then(Value::as_str) == Some(ns::DURABLE_KEY)
            && let Some(record) = write.get("value")
        {
            durable.commit(record);
        }
        return;
    }
    if kind == Some("entry") {
        if let Some(entry) = digest_entry(write) {
            log.entries.push(entry);
        }
        return;
    }
    if kind == Some("usage") {
        if let Some(usage) = log_usage(write.get("usage")) {
            log.usage_rows.push(LogUsageRow {
                usage,
                entry_id: string_of(write.get("entryId")),
                adjustment: write.get("adjustment") == Some(&Value::Bool(true)),
            });
        }
        return;
    }
    let (Some("value"), Some(namespace), Some(key)) = (
        kind,
        write.get("namespace").and_then(Value::as_str),
        write.get("key").and_then(Value::as_str),
    ) else {
        return;
    };
    let op = write.get("op").and_then(Value::as_str);
    let value = record(write.get("value"));
    if namespace == ns::OP_META {
        if op == Some("set")
            && let Some(v) = value
            && let Some(lane) = v.get("lane").and_then(Value::as_str)
        {
            let intent = record(v.get("intent"))
                .and_then(|i| i.get("kind"))
                .and_then(Value::as_str);
            log.operations.insert(
                key.to_string(),
                LogOperation {
                    id: key.to_string(),
                    lane: lane.to_string(),
                    kind: intent.unwrap_or("run").to_string(),
                    started_at: timestamp_of(v.get("startedAt")),
                },
            );
        }
        return;
    }
    if namespace == ns::OP_RESULT {
        if op == Some("set")
            && let Some(v) = value
        {
            let text = |k: &str| v.get(k).and_then(Value::as_str);
            log.results.push(LogResult {
                operation_id: text("operationId").unwrap_or(key).to_string(),
                kind: text("kind").unwrap_or("run").to_string(),
                status: text("status").unwrap_or("unknown").to_string(),
                from_tip_id: text("fromTipId").map(str::to_string),
                tip_id: text("tipId").map(str::to_string),
                started_at: timestamp_of(v.get("startedAt")),
                ended_at: timestamp_of(v.get("endedAt")),
            });
        }
        return;
    }
    if !KEPT_NAMESPACES.contains(&namespace) {
        return;
    }
    let address = format!("{namespace}/{key}");
    match op {
        Some("set") => {
            let v = write.get("value").cloned().unwrap_or(Value::Null);
            log.values.insert(address, v);
        }
        Some("delete") => {
            log.values.shift_remove(&address);
        }
        _ => {}
    }
}

impl SessionLog {
    pub fn value(&self, namespace: &str, key: &str) -> Option<&Value> {
        self.values.get(&format!("{namespace}/{key}"))
    }

    /// The latest values of a namespace, by key, in the order they were first written.
    pub fn values_of(&self, namespace: &str) -> Vec<(&str, &Value)> {
        let prefix = format!("{namespace}/");
        self.values
            .iter()
            .filter_map(|(address, value)| address.strip_prefix(&prefix).map(|key| (key, value)))
            .collect()
    }
}