rho-coding-agent 3.7.0

A fast Rust agent harness with a small footprint and opinionated defaults
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
//! A session's daemon events (`wire::SessionEvent`) as ACP session updates.
//!
//! The wire event mirrors ACP (`rho-protocol` `event.rs`), so most events
//! map field for field. [`Updates::map`] is pure apart from what the stream
//! itself decides: which tool calls the host already saw, so the first
//! report of a call opens its card and later ones patch it, the IDs it
//! mints for messages and cards the daemon gives none, and what
//! [`Updates::observe`] found missing of a turn's answer.
//!
//! A turn's end maps to the answer text its chunks did not show, as one
//! more agent chunk ([`StreamedReply`]): a provider that returns a reply
//! without streaming it leaves it only there. So that it knows what the
//! host was shown, the stream reader passes [`Updates::observe`] every
//! event it reads, mapped or not, before mapping any.
//!
//! Other events that are not transcript updates map to nothing here; the
//! session pump handles them (`sessions/pump.rs`), as it does `TurnEnded`,
//! which also ends a prompt: `State` tracks the attachment's job and
//! Herdr, `Input*` open or close host prompts (`inputs.rs`), and
//! `OptionsChanged` is diffed against what the host last saw
//! ([`options_changed`]).

use std::{
    collections::{HashMap, HashSet},
    path::Path,
};

use agent_client_protocol::v1::schema::{
    AvailableCommandsUpdate, CompactionId, CompactionStatus, CompactionUpdate, ConfigOptionUpdate,
    ContentBlock, ContentChunk, Cost, CurrentModeUpdate, Diff, EmbeddedResource,
    EmbeddedResourceResource, ImageContent, MessageId, Notice, NoticeSeverity, Plan, PlanEntry,
    PlanEntryPriority, PlanEntryStatus, ResourceLink, SessionId, SessionInfoUpdate,
    SessionNotification, SessionUpdate, Terminal, TextResourceContents, ToolCall, ToolCallContent,
    ToolCallId, ToolCallLocation, ToolCallStatus, ToolCallUpdate, ToolCallUpdateFields, ToolKind,
    UsageUpdate,
};
use rho_protocol::{self as wire, SessionEvent};
use serde_json::Value;

use super::{host_features::HostFeatures, markers, options, permission};
use crate::{
    app::streamed_reply::{MissingReply, StreamedReply},
    permission::PermissionMode,
};

/// Hosts with their own transcript use this marker to avoid duplicating it.
const REPLAY_META_KEY: &str = "isReplay";

/// The `_meta` that marks a notification as replayed history.
pub(super) fn replay_meta() -> serde_json::Map<String, Value> {
    serde_json::Map::from_iter([(REPLAY_META_KEY.to_owned(), Value::Bool(true))])
}

/// Shown when the provider's response was dropped and is being retried.
const RESPONSE_DISCARDED_NOTICE: &str = "[provider response discarded; retrying]";

/// A tool call the daemon reported without a title, until it names one.
const UNNAMED_TOOL_TITLE: &str = "tool";

/// One session's event mapping, kept for as long as its stream.
pub(super) struct Updates {
    features: HostFeatures,
    /// Tool calls the host already holds a card for.
    seen_tools: HashSet<String>,
    /// Compactions seen starting and not yet ended. One that ends unseen
    /// is a saved one, which a replay sends as its end alone.
    started_compactions: HashSet<String>,
    /// What the host was shown of the turn's reply, which its end completes.
    reply: StreamedReply,
    /// The answer text the last observed turn end carried that no chunk
    /// showed, until that end is mapped.
    missing_reply: Option<MissingReply>,
    /// Prefix of the IDs this mapping mints, unique per process, so hosts
    /// that keep their transcript across reconnects never merge two.
    nonce: String,
    minted: u64,
}

impl Updates {
    pub(super) fn new(features: HostFeatures) -> Self {
        Self::with_nonce(features, uuid::Uuid::new_v4().to_string())
    }

    fn with_nonce(features: HostFeatures, nonce: String) -> Self {
        Self {
            features,
            seen_tools: HashSet::new(),
            started_compactions: HashSet::new(),
            reply: StreamedReply::default(),
            missing_reply: None,
            nonce,
            minted: 0,
        }
    }

    /// Takes `event` as the stream delivered it: once for every event,
    /// whether the host is shown it, has it already (a resume without
    /// replay skips the history), or follows it another way (its own
    /// prompt), and before [`Self::map`] maps it.
    pub(super) fn observe(&mut self, event: &SessionEvent) {
        self.missing_reply = self.reply.observe(event);
    }

    /// The ACP updates `event` shows as. A turn's end shows what
    /// [`Self::observe`] found missing of its answer.
    pub(super) fn map(&mut self, event: &SessionEvent) -> Vec<SessionUpdate> {
        match event {
            // A steer shows as the user message it applied as.
            SessionEvent::UserMessage {
                message,
                content,
                steer: _,
            } => content
                .iter()
                .filter_map(content_block)
                .map(|block| SessionUpdate::UserMessageChunk(chunk(block, message)))
                .collect(),
            SessionEvent::AgentMessageChunk { message, text } => {
                vec![SessionUpdate::AgentMessageChunk(chunk(
                    ContentBlock::from(text.as_str()),
                    message,
                ))]
            }
            SessionEvent::ThoughtChunk { message, text } => {
                vec![SessionUpdate::AgentThoughtChunk(chunk(
                    ContentBlock::from(text.as_str()),
                    message,
                ))]
            }
            SessionEvent::ToolCall(update) => self.tool_call(update).into_iter().collect(),
            SessionEvent::Plan { entries } => vec![SessionUpdate::Plan(Plan::new(
                entries.iter().map(plan_entry).collect(),
            ))],
            SessionEvent::Usage {
                used_tokens,
                window_tokens,
                cost_usd_micros,
            } => vec![SessionUpdate::UsageUpdate(usage_update(
                *used_tokens,
                *window_tokens,
                *cost_usd_micros,
            ))],
            SessionEvent::TitleChanged { title } => vec![SessionUpdate::SessionInfoUpdate(
                SessionInfoUpdate::new().title(title.clone()),
            )],
            SessionEvent::Compaction { id, status } if self.features.compaction => {
                Vec::from_iter(compaction_update(id, status))
            }
            // A host without cards sees a live compaction only in
            // `usage_update`; a saved one, which no usage follows, shows as
            // a notice where it happened.
            SessionEvent::Compaction { id, status } => {
                let started = self.started_compactions.remove(id.as_str());
                match status {
                    wire::CompactionStatus::Started { .. } => {
                        self.started_compactions.insert(id.as_str().to_owned());
                        Vec::new()
                    }
                    wire::CompactionStatus::Completed { counts } if !started => {
                        vec![self.notice(&crate::compaction::counts_summary(counts))]
                    }
                    _ => Vec::new(),
                }
            }
            // The retried response starts a message of its own.
            SessionEvent::ResponseDiscarded => {
                let id = self.mint("rho-msg");
                vec![SessionUpdate::AgentThoughtChunk(
                    ContentChunk::new(ContentBlock::from(RESPONSE_DISCARDED_NOTICE))
                        .message_id(MessageId::new(id)),
                )]
            }
            SessionEvent::Card {
                title,
                markdown,
                plain,
                tone,
                // The TUI's drawing of it; ACP clients draw their own.
                display: _,
            } => vec![self.card(title, markdown, plain, *tone)],
            SessionEvent::Notice { text } => vec![self.notice(text)],
            SessionEvent::TurnEnded { .. } => self
                .missing_reply
                .take()
                .map(|missing| {
                    let message = missing
                        .continues
                        .unwrap_or_else(|| wire::MessageId::new(self.mint("rho-msg")));
                    SessionUpdate::AgentMessageChunk(chunk(
                        ContentBlock::from(missing.text),
                        &message,
                    ))
                })
                .into_iter()
                .collect(),
            SessionEvent::State { .. }
            | SessionEvent::InputRequested { .. }
            | SessionEvent::InputResolved { .. }
            | SessionEvent::InputHeld { .. }
            | SessionEvent::OptionsChanged { .. }
            // The pump reports them, where the protocol has a place for them.
            | SessionEvent::Background { .. }
            // ACP's prompt ends with its turn; nothing follows a settle.
            | SessionEvent::Activity { .. }
            // ACP has no place for the agent a session runs as.
            | SessionEvent::Agent { .. }
            // Nor for what the sessions it starts open with.
            | SessionEvent::StartedSessionDefaults(_)
            // Nor for a session's pull requests.
            | SessionEvent::PullRequests { .. }
            // Nor for how a person marked the session.
            | SessionEvent::MarkChanged { .. }
            // ACP has no update for what the turn is doing.
            | SessionEvent::ProviderRequest
            | SessionEvent::ProviderRetry { .. }
            // The steer shows once it applies, as a user message.
            | SessionEvent::SteeringDelivered { .. } => Vec::new(),
            // `Unknown`, or an event a newer daemon sends.
            _ => {
                tracing::debug!("skipping a session event this rho does not know");
                Vec::new()
            }
        }
    }

    /// Information for the user that is not part of the conversation: an ACP
    /// `notice` when the host shows them, else an agent message.
    fn notice(&mut self, text: &str) -> SessionUpdate {
        if self.features.notices {
            return SessionUpdate::Notice(Notice::new(NoticeSeverity::Info, text));
        }
        let id = self.mint("rho-msg");
        SessionUpdate::AgentMessageChunk(
            ContentChunk::new(ContentBlock::from(text)).message_id(MessageId::new(id)),
        )
    }

    /// The first report of a call opens its card; later ones patch only the
    /// fields they carry.
    /// Nothing for a patch that carries only a `display`, which ACP has no
    /// field for: a call's card follows its streamed arguments.
    fn tool_call(&mut self, update: &wire::ToolCallUpdate) -> Option<SessionUpdate> {
        let id = ToolCallId::new(update.id.as_str());
        let content = update
            .content
            .as_ref()
            .map(|content| tool_contents(content, self.features));
        let locations = update
            .locations
            .as_ref()
            .map(|locations| locations.iter().map(location).collect::<Vec<_>>());
        let meta = (update.status == Some(wire::ToolStatus::Cancelled))
            .then(|| markers::flag(markers::TOOL_CANCELLED));
        if self.seen_tools.insert(update.id.as_str().to_owned()) {
            let title = update.title.as_deref().unwrap_or(UNNAMED_TOOL_TITLE);
            let mut call = ToolCall::new(id, title)
                .kind(update.kind.map_or(ToolKind::Other, tool_kind))
                .status(update.status.map_or(ToolCallStatus::Pending, tool_status))
                .raw_input(update.raw_input.clone())
                .meta(meta);
            if let Some(content) = content {
                call = call.content(content);
            }
            if let Some(locations) = locations {
                call = call.locations(locations);
            }
            return Some(SessionUpdate::ToolCall(call));
        }
        if update.title.is_none()
            && update.kind.is_none()
            && update.status.is_none()
            && update.raw_input.is_none()
            && content.is_none()
            && locations.is_none()
        {
            return None;
        }
        let fields = ToolCallUpdateFields::new()
            .title(update.title.clone())
            .kind(update.kind.map(tool_kind))
            .status(update.status.map(tool_status))
            .raw_input(update.raw_input.clone())
            .content(content)
            .locations(locations);
        Some(SessionUpdate::ToolCallUpdate(
            ToolCallUpdate::new(id, fields).meta(meta),
        ))
    }

    /// A background result's card, as a finished tool call. Cards keep it out
    /// of the agent's message text, and hosts already render them beside the
    /// tool calls that started the work. Rows carry no identity of their own,
    /// so each card gets a fresh ID, which keeps hosts from merging two.
    fn card(
        &mut self,
        title: &str,
        markdown: &str,
        plain: &str,
        tone: wire::CardTone,
    ) -> SessionUpdate {
        let status = match tone {
            wire::CardTone::Error => ToolCallStatus::Failed,
            wire::CardTone::Neutral
            | wire::CardTone::Accent
            | wire::CardTone::Success
            | wire::CardTone::Warning => ToolCallStatus::Completed,
            // `Unknown`, or a tone a newer daemon sends.
            _ => ToolCallStatus::Completed,
        };
        let id = self.mint("rho-notice");
        let mut call = ToolCall::new(ToolCallId::new(id), title)
            .kind(ToolKind::Other)
            .status(status);
        // Content is markdown for hosts that render it. Hosts that show a
        // tool's output as is, such as T3 Code, read `rawOutput` first, so it
        // carries the plain form without code fences.
        if !plain.trim().is_empty() {
            call = call
                .content(vec![ToolCallContent::from(markdown)])
                .raw_output(Value::String(plain.to_owned()));
        }
        SessionUpdate::ToolCall(call)
    }

    fn mint(&mut self, kind: &str) -> String {
        self.minted += 1;
        format!("{kind}-{}-{}", self.nonce, self.minted)
    }
}

/// How an update reaches the host.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Delivery {
    /// As it happens.
    Live,
    /// As history a loaded session replays, marked so hosts with their own
    /// transcript skip it.
    Replay,
}

/// `update` for `session`, delivered as `delivery` says.
pub(super) fn notification(
    session: &SessionId,
    update: SessionUpdate,
    delivery: Delivery,
) -> SessionNotification {
    let notification = SessionNotification::new(session.clone(), update);
    match delivery {
        Delivery::Live => notification,
        Delivery::Replay => notification.meta(replay_meta()),
    }
}

/// What the host must hear when the session's options move from `old` to
/// `new`: the whole config when any option changed, the mode when it did
/// (hosts learn of an agent-initiated switch only from this), and the
/// command menu when it changed. Nothing when nothing did.
pub(super) fn options_changed(
    old: &wire::SessionOptions,
    new: &wire::SessionOptions,
    features: HostFeatures,
) -> Vec<SessionUpdate> {
    let mut updates = Vec::new();
    let config = options::config_options(new, features.toggles);
    if config != options::config_options(old, features.toggles) {
        updates.push(SessionUpdate::ConfigOptionUpdate(ConfigOptionUpdate::new(
            config,
        )));
    }
    if new.permission_mode.current != old.permission_mode.current {
        if let Ok(mode) = PermissionMode::try_from(new.permission_mode.current) {
            updates.push(SessionUpdate::CurrentModeUpdate(CurrentModeUpdate::new(
                permission::mode_id(mode),
            )));
        }
    }
    if new.commands != old.commands {
        updates.push(commands_update(&new.commands));
    }
    updates
}

/// The ACP `compaction_update` card for compaction `id` reaching `status`,
/// for hosts that advertise `clientCapabilities.session.compaction`;
/// nothing for a status a newer daemon sends.
///
/// A card opens `in_progress` and ends with exactly one terminal update; a
/// replayed one, from saved history, arrives `completed` alone. Its ID is
/// the daemon's compaction ID, unique per compaction (random live, from its
/// saved node on replay): hosts such as T3 Code keep their transcript
/// across reconnects, so an ID that restarted per process would patch an
/// earlier card in place. Cards carry
/// no `summary`: ACP reserves it for retained summary content, not status
/// text such as the before and after counts, which hosts get from
/// `usage_update`.
fn compaction_update(
    id: &wire::CompactionId,
    status: &wire::CompactionStatus,
) -> Option<SessionUpdate> {
    let id = CompactionId::new(id.as_str());
    let update = match status {
        wire::CompactionStatus::Started { .. } => {
            CompactionUpdate::new(id, CompactionStatus::InProgress)
        }
        wire::CompactionStatus::Completed { .. } => {
            CompactionUpdate::new(id, CompactionStatus::Completed)
        }
        wire::CompactionStatus::Cancelled => CompactionUpdate::new(id, CompactionStatus::Cancelled),
        wire::CompactionStatus::Failed { error } => {
            CompactionUpdate::new(id, CompactionStatus::Failed).error(error.clone())
        }
        // `Unknown`, or a status a newer daemon sends.
        _ => return None,
    };
    Some(SessionUpdate::CompactionUpdate(update))
}

/// The session's whole command menu.
pub(super) fn commands_update(commands: &[wire::SessionCommand]) -> SessionUpdate {
    SessionUpdate::AvailableCommandsUpdate(AvailableCommandsUpdate::new(
        options::available_commands(commands),
    ))
}

/// A text or other block of message `message`; every chunk Rho sends names
/// its message.
fn chunk(block: ContentBlock, message: &wire::MessageId) -> ContentChunk {
    ContentChunk::new(block).message_id(MessageId::new(message.as_str()))
}

fn content_block(block: &wire::ContentBlock) -> Option<ContentBlock> {
    Some(match block {
        wire::ContentBlock::Text { text } => ContentBlock::from(text.as_str()),
        wire::ContentBlock::Image { mime_type, data } => {
            ContentBlock::Image(ImageContent::new(data.as_str(), mime_type.as_str()))
        }
        wire::ContentBlock::Resource { uri, text } => ContentBlock::Resource(
            EmbeddedResource::new(EmbeddedResourceResource::TextResourceContents(
                TextResourceContents::new(text.as_str(), uri.as_str()),
            )),
        ),
        wire::ContentBlock::ResourceLink {
            uri,
            name,
            description,
        } => ContentBlock::ResourceLink(
            ResourceLink::new(name.as_str(), uri.as_str()).description(description.clone()),
        ),
        // Only a prompt carries context; a user message never holds it.
        wire::ContentBlock::Context { .. } => return None,
        // `Unknown`, or a block a newer daemon sends.
        _ => return None,
    })
}

fn tool_kind(kind: wire::ToolKind) -> ToolKind {
    match kind {
        wire::ToolKind::Read => ToolKind::Read,
        wire::ToolKind::Edit => ToolKind::Edit,
        wire::ToolKind::Delete => ToolKind::Delete,
        wire::ToolKind::Move => ToolKind::Move,
        wire::ToolKind::Search => ToolKind::Search,
        wire::ToolKind::Execute => ToolKind::Execute,
        wire::ToolKind::Think => ToolKind::Think,
        wire::ToolKind::Fetch => ToolKind::Fetch,
        wire::ToolKind::SwitchMode => ToolKind::SwitchMode,
        wire::ToolKind::Other => ToolKind::Other,
        // `Unknown`, or a kind a newer daemon sends.
        _ => ToolKind::Other,
    }
}

fn tool_status(status: wire::ToolStatus) -> ToolCallStatus {
    match status {
        wire::ToolStatus::Pending => ToolCallStatus::Pending,
        wire::ToolStatus::InProgress => ToolCallStatus::InProgress,
        wire::ToolStatus::Completed => ToolCallStatus::Completed,
        wire::ToolStatus::Failed => ToolCallStatus::Failed,
        // v1 has no `cancelled`; `tool_call` marks it in `_meta`.
        wire::ToolStatus::Cancelled => ToolCallStatus::Failed,
        // `Unknown`, or a status a newer daemon sends: still running.
        _ => ToolCallStatus::InProgress,
    }
}

/// A call's content, which v1 shows piece by piece. A move is the
/// source's deletion and a new file, which names its source.
fn tool_contents(content: &[wire::ToolContent], features: HostFeatures) -> Vec<ToolCallContent> {
    let moves: HashMap<&Path, &Path> = content
        .iter()
        .filter_map(|content| match content {
            wire::ToolContent::Moved { from, path } => Some((path.as_path(), from.as_path())),
            _ => None,
        })
        .collect();
    content
        .iter()
        .filter_map(|content| {
            Some(match content {
                wire::ToolContent::Text { text } => ToolCallContent::from(text.as_str()),
                wire::ToolContent::Image { mime_type, data } => ToolCallContent::from(
                    ContentBlock::Image(ImageContent::new(data.as_str(), mime_type.as_str())),
                ),
                wire::ToolContent::Diff {
                    path,
                    old_text,
                    new_text,
                    deleted,
                } => {
                    let meta = if *deleted {
                        Some(markers::flag(markers::DELETED_FILE))
                    } else {
                        moves
                            .get(path.as_path())
                            .and_then(|from| markers::path(markers::MOVED_FROM, from))
                    };
                    ToolCallContent::Diff(
                        Diff::new(path.clone(), new_text.as_str())
                            .old_text(old_text.clone())
                            .meta(meta),
                    )
                }
                // ACP v2 maps it to its display-only terminal (`v2::updates`).
                wire::ToolContent::Terminal { process } if features.display_terminals() => {
                    ToolCallContent::Terminal(Terminal::new(process.clone()))
                }
                // ACP v2 maps it to a `session` content item naming the
                // child (`v2::updates`); v1 has no such content.
                wire::ToolContent::Subagent(child) if features.child_sessions() => {
                    ToolCallContent::Content(
                        agent_client_protocol::v1::schema::Content::new(ContentBlock::from(""))
                            .meta(markers::subagent(child)),
                    )
                }
                // A peer session a `sessions` call named: ACP v2's `session`
                // content may only name a session the host already knows,
                // through its own setup or a child's announcement, and a
                // peer session is neither. The call's text names it.
                wire::ToolContent::Session(_) => return None,
                // `Moved` marks the diffs above; `Unknown`, content a newer
                // daemon sends, or a terminal or child a v1 host could not
                // show.
                _ => return None,
            })
        })
        .collect()
}

/// ACP counts `line` from 1 on v1 and v2 alike; the daemon's rows count from 0.
fn location(location: &wire::Location) -> ToolCallLocation {
    ToolCallLocation::new(location.path.clone())
        .line(location.line.map(|row| row.saturating_add(1)))
}

fn plan_entry(entry: &wire::PlanEntry) -> PlanEntry {
    let status = match entry.status {
        wire::PlanStatus::Pending => PlanEntryStatus::Pending,
        wire::PlanStatus::InProgress => PlanEntryStatus::InProgress,
        wire::PlanStatus::Completed => PlanEntryStatus::Completed,
        // `Unknown`, or a status a newer daemon sends.
        _ => PlanEntryStatus::Pending,
    };
    // The todo tool has no priorities; Medium is the neutral ACP value.
    PlanEntry::new(entry.content.clone(), PlanEntryPriority::Medium, status)
}

/// Context fill and cumulative cost. ACP's `size` is required; 0 means the
/// window is unknown, which clients render as no maximum. Cost is omitted,
/// never sent as 0, while no request has a price.
/// The `usage_update` of a daemon `Usage` event.
pub(super) fn usage_update(
    used: u64,
    window: Option<u64>,
    cost_usd_micros: Option<u64>,
) -> UsageUpdate {
    let cost = cost_usd_micros.map(|micros| Cost::new(micros as f64 / 1_000_000.0, "USD"));
    UsageUpdate::new(used, window.unwrap_or(0)).cost(cost)
}

#[cfg(test)]
#[path = "updates_tests.rs"]
mod tests;