rhei-cli 0.1.0

Command-line driver for the Rhei agent runtime.
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
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Instant, SystemTime};

/// Slot index assigned to a running task invocation.
///
/// The engine allocates one slot per concurrent agent/program and releases the
/// slot when the invocation exits. The renderer uses the slot to update the
/// correct tile without reconciling task ids on every frame. The type is
/// wider than a byte so callers with very large `--parallel` values cannot
/// silently collide into slot 255.
pub type Slot = u16;

/// Outcome of a released slot.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TaskOutcome {
    Completed,
    Failed(String),
    Cancelled,
    TimedOut,
}

/// Aggregate statistics emitted with `RunFinished`.
#[derive(Debug, Clone, Default)]
pub struct RunSummary {
    pub agents_spawned: u32,
    pub programs_spawned: u32,
    pub terminal_tasks: usize,
    pub total_tasks: usize,
    pub accounting: Option<AccountingRunSummary>,
}

/// Severity of an engine log message.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MessageLevel {
    Info,
    Warn,
    Error,
}

/// Agent subprocess stream that produced a live output line.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AgentStream {
    Stdout,
    Stderr,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum DimensionStatus {
    Measured,
    Partial,
    Unsupported,
    Omitted,
    Unknown,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct DimensionSummary {
    pub value: Option<u64>,
    pub status: DimensionStatus,
    pub missing_count: u64,
    pub measured_count: u64,
}

impl Default for DimensionSummary {
    fn default() -> Self {
        Self { value: None, status: DimensionStatus::Unknown, missing_count: 0, measured_count: 0 }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum UsageCoverage {
    Complete,
    Partial,
    Unpriced,
    None,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum UsageStatus {
    Measured,
    UnsupportedAgent,
    ExtractorUnavailable,
    ExtractorFailed,
    NoUsageEmitted,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum PricingStatus {
    Priced,
    PartialPrice,
    Unpriced,
    NotApplicable,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct UsageSummary {
    pub invocation_id: String,
    pub state: String,
    pub agent: String,
    pub provider: Option<String>,
    pub model: Option<String>,
    pub total: DimensionSummary,
    pub input_total: DimensionSummary,
    pub input_cached_read: DimensionSummary,
    pub input_cache_write: DimensionSummary,
    pub output_total: DimensionSummary,
    pub output_cached_read: DimensionSummary,
    pub output_cache_write: DimensionSummary,
    pub cost_micro: Option<u64>,
    pub priced_cost_micro: Option<u64>,
    pub currency: Option<String>,
    pub coverage: UsageCoverage,
    pub status: UsageStatus,
    pub pricing_status: PricingStatus,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct AccountingRunSummary {
    pub total: DimensionSummary,
    pub input_total: DimensionSummary,
    pub input_cached_read: DimensionSummary,
    pub input_cache_write: DimensionSummary,
    pub output_total: DimensionSummary,
    pub output_cached_read: DimensionSummary,
    pub output_cache_write: DimensionSummary,
    pub cost_micro: Option<u64>,
    pub priced_cost_micro: Option<u64>,
    pub currency: Option<String>,
    pub coverage: UsageCoverage,
    pub pricing_status: PricingStatus,
    pub invocation_count: u64,
    pub measured_invocation_count: u64,
    pub missing_invocation_count: u64,
}

/// Summarize invocation usage records into the shared run/task accounting shape.
/// §FS-rhei-cost-accounting.6: rollups summarize invocation records consistently.
pub fn summarize_usage_summaries<'a>(
    usages: impl IntoIterator<Item = &'a UsageSummary>,
) -> Option<AccountingRunSummary> {
    let usages: Vec<&UsageSummary> = usages.into_iter().collect();
    if usages.is_empty() {
        return None;
    }

    let measured_invocation_count =
        usages.iter().filter(|usage| usage.status == UsageStatus::Measured).count() as u64;
    let missing_invocation_count = usages.len() as u64 - measured_invocation_count;
    let priced_cost_micro = sum_options(usages.iter().map(|usage| usage.priced_cost_micro));
    let cost_micro = if usages.iter().all(|usage| usage.cost_micro.is_some()) {
        Some(usages.iter().filter_map(|usage| usage.cost_micro).sum())
    } else {
        None
    };
    let currency = usages.iter().find_map(|usage| usage.currency.clone());
    let pricing_status = summarize_pricing_status(&usages);
    let coverage = summarize_coverage(&usages, cost_micro, priced_cost_micro);

    Some(AccountingRunSummary {
        total: summarize_dimension(usages.iter().map(|usage| &usage.total)),
        input_total: summarize_dimension(usages.iter().map(|usage| &usage.input_total)),
        input_cached_read: summarize_dimension(usages.iter().map(|usage| &usage.input_cached_read)),
        input_cache_write: summarize_dimension(usages.iter().map(|usage| &usage.input_cache_write)),
        output_total: summarize_dimension(usages.iter().map(|usage| &usage.output_total)),
        output_cached_read: summarize_dimension(
            usages.iter().map(|usage| &usage.output_cached_read),
        ),
        output_cache_write: summarize_dimension(
            usages.iter().map(|usage| &usage.output_cache_write),
        ),
        cost_micro,
        priced_cost_micro,
        currency,
        coverage,
        pricing_status,
        invocation_count: usages.len() as u64,
        measured_invocation_count,
        missing_invocation_count,
    })
}

fn summarize_dimension<'a>(
    dimensions: impl IntoIterator<Item = &'a DimensionSummary>,
) -> DimensionSummary {
    let mut value = 0u64;
    let mut saw_value = false;
    let mut missing_count = 0u64;
    let mut measured_count = 0u64;
    let mut unavailable_status = None;

    for dimension in dimensions {
        if let Some(v) = dimension.value {
            value = value.saturating_add(v);
            saw_value = true;
        }
        measured_count = measured_count.saturating_add(dimension.measured_count);
        missing_count = missing_count.saturating_add(dimension.missing_count);
        if dimension.status != DimensionStatus::Measured {
            unavailable_status = Some(dimension.status);
        }
    }

    let status = if saw_value && missing_count == 0 {
        DimensionStatus::Measured
    } else if saw_value {
        DimensionStatus::Partial
    } else {
        unavailable_status.unwrap_or(DimensionStatus::Unknown)
    };

    DimensionSummary { value: saw_value.then_some(value), status, missing_count, measured_count }
}

fn sum_options(values: impl IntoIterator<Item = Option<u64>>) -> Option<u64> {
    let mut total = 0u64;
    let mut saw = false;
    for value in values.into_iter().flatten() {
        total = total.saturating_add(value);
        saw = true;
    }
    saw.then_some(total)
}

fn summarize_pricing_status(usages: &[&UsageSummary]) -> PricingStatus {
    let mut saw_priced = false;
    let mut saw_partial = false;
    let mut saw_unpriced = false;
    let mut saw_applicable = false;
    for usage in usages {
        match usage.pricing_status {
            PricingStatus::Priced => {
                saw_priced = true;
                saw_applicable = true;
            }
            PricingStatus::PartialPrice => {
                saw_partial = true;
                saw_applicable = true;
            }
            PricingStatus::Unpriced => {
                saw_unpriced = true;
                saw_applicable = true;
            }
            PricingStatus::NotApplicable => {}
        }
    }
    if !saw_applicable {
        PricingStatus::NotApplicable
    } else if saw_partial || (saw_priced && saw_unpriced) {
        PricingStatus::PartialPrice
    } else if saw_priced {
        PricingStatus::Priced
    } else {
        PricingStatus::Unpriced
    }
}

fn summarize_coverage(
    usages: &[&UsageSummary],
    cost_micro: Option<u64>,
    priced_cost_micro: Option<u64>,
) -> UsageCoverage {
    if usages.iter().all(|usage| usage.coverage == UsageCoverage::None) {
        return UsageCoverage::None;
    }
    if usages.iter().any(|usage| {
        matches!(usage.coverage, UsageCoverage::Partial) || usage.status != UsageStatus::Measured
    }) {
        return UsageCoverage::Partial;
    }
    if cost_micro.is_some() {
        UsageCoverage::Complete
    } else if priced_cost_micro.is_some() {
        UsageCoverage::Partial
    } else if usages.iter().any(|usage| usage.coverage == UsageCoverage::Unpriced) {
        UsageCoverage::Unpriced
    } else {
        UsageCoverage::None
    }
}

/// Events emitted by the execution engine.
///
/// The shape follows the TUI event surface. `Message` is an additional variant
/// used while the stdout path still emits humanized strings; a TUI frontend can
/// surface these in its journal pane.
// §FS-rhei-run-tui.1.1: Run event surface.
#[derive(Debug, Clone)]
pub enum RunEvent {
    RunStarted {
        workspace: PathBuf,
        parallel: u16,
        total_tasks: usize,
    },
    PassStarted {
        pass: u32,
        ready: Vec<String>,
    },
    /// A worker has been assigned to a task.
    ///
    /// `from` is the task's persisted state at the moment of claim; `to` is
    /// the state the worker is operating in. When `from == to`, the worker
    /// is running an *autonomous* state that the engine did not transition
    /// into as part of the claim — it is "starting work in `to`," not
    /// "moving from `from` to `to`." Renderers must distinguish the two
    /// cases so the UI does not show a phantom `state→state` self-loop.
    SlotAssigned {
        slot: Slot,
        task: String,
        from: String,
        to: String,
        agent: Option<String>,
        template_context: Option<crate::rhei_viz_model::TemplateContext>,
        log_path: PathBuf,
        started_at: Instant,
        wall_clock: SystemTime,
    },
    /// A worker slot has been released.
    ///
    /// `from` is the state at assignment; `to` is the state the task ended
    /// up in. When `from == to`, the worker exited without changing state
    /// (typical for autonomous states that hand control back to the run loop
    /// for re-evaluation) — render as "ended in `to`," not as a transition.
    SlotReleased {
        slot: Slot,
        task: String,
        from: String,
        to: String,
        log_path: PathBuf,
        outcome: TaskOutcome,
        finished_at: Instant,
        wall_clock: SystemTime,
        exit_code: Option<i32>,
        duration_ms: u64,
    },
    PassEnded {
        pass: u32,
        progressed: bool,
    },
    /// Tasks that were eligible this pass but yielded their slot to a same-state
    /// claimant (non-`concurrent` state). They are reconsidered next pass.
    TasksDeferred {
        pass: u32,
        tasks: Vec<String>,
    },
    RunFinished {
        summary: RunSummary,
    },
    Message {
        level: MessageLevel,
        text: String,
    },
    RunLink {
        label: String,
        url: String,
    },
    AgentOutput {
        slot: Slot,
        task: String,
        stream: AgentStream,
        line: String,
        wall_clock: SystemTime,
    },
    /// Accounting event emitted after the durable invocation record is written.
    /// §FS-rhei-cost-accounting.7
    UsageReported {
        slot: Option<Slot>,
        task: String,
        invocation_id: String,
        usage: UsageSummary,
    },
    /// A worker exited `0` and left required artifacts unwritten, so the ticket
    /// did not advance. `entries` are already rendered as `name (path)`, the
    /// ticket's terminal result included under the name `result`.
    ///
    /// The human-readable warning still arrives as a [`RunEvent::Message`]; this
    /// carries the same facts in a form the run report can classify with,
    /// instead of re-deriving them from prose.
    // §FS-rhei-run-report.3.1 §FS-rhei-agents.3.2.1
    TaskOutputsMissing {
        task: String,
        state: String,
        entries: Vec<String>,
    },
}

/// Sink that consumes `RunEvent`s. Implementations must be cheap to clone and
/// safe to share across threads (the engine spawns parallel workers).
pub trait EventSink: Send + Sync {
    fn emit(&self, event: RunEvent);
}

/// Composite sink that forwards every event to each inner sink in order.
#[derive(Clone)]
pub struct Tee {
    inners: Arc<Vec<Arc<dyn EventSink>>>,
}

impl Tee {
    pub fn new(sinks: Vec<Arc<dyn EventSink>>) -> Self {
        Self { inners: Arc::new(sinks) }
    }
}

impl EventSink for Tee {
    fn emit(&self, event: RunEvent) {
        for sink in self.inners.iter() {
            sink.emit(event.clone());
        }
    }
}

/// Sink that discards every event. Useful as the default frontend when the
/// engine is responsible for producing stdout (backward-compatible mode).
pub struct NullSink;

impl EventSink for NullSink {
    fn emit(&self, _event: RunEvent) {}
}