rho-coding-agent 3.10.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
//! Stateful protocol-to-artifact translation; terminal decisions stay in the driver.

use std::{collections::HashMap, path::PathBuf};

use agent_client_protocol::v1::schema::{
    ContentBlock, Cost, Plan, PlanEntryStatus, SessionUpdate, StopReason, ToolCall, ToolCallId,
    ToolCallStatus, ToolCallUpdate, UsageUpdate,
};
use rho_protocol::{display::ToolCardStatus, PlanEntry, PlanStatus};
use rho_sdk::model::ContextUsage;

use crate::{
    cli_runtime::{
        stream_effect::{StatusPatch, StreamEffect, MAX_TOOL_PAYLOAD_CHARS},
        stream_format::{
            bound_result_text, bound_text, reasoning_effects, text_effects, MAX_TOOL_BODY_LINES,
        },
    },
    run_artifacts::AttachmentEvent,
};

use super::{
    served::{OpenCards, ServedCalls, ServedState},
    tool_cards::{content_notice, finished_card, started_card, StartedTool},
    AgentEvent, ServedCard,
};

/// Bound on tool calls retained while in flight, the calls of served tools
/// the renderer tracks (`served.rs`) included. Carried over from the
/// deleted Cursor `-p` mapper: its spike peaked at 33 sequential calls, and
/// parallel fan-out inside one turn is the only way to exceed this. Overflow
/// only loses update enrichment, or shows a served call's card as the
/// agent's, and is announced with a notice.
pub(crate) const MAX_ACTIVE_TOOLS: usize = 256;

/// A reported session cost in US dollars, or why Rho cannot record it.
/// Status can represent USD only; never silently relabel another currency.
pub(crate) fn usd_cost(cost: &Cost) -> Result<f64, String> {
    if !cost.currency.eq_ignore_ascii_case("USD") {
        Err(format!("acp: unsupported cost currency {}", cost.currency))
    } else if !cost.amount.is_finite() || cost.amount < 0.0 {
        Err("acp: invalid session cost".into())
    } else {
        Ok(cost.amount)
    }
}

/// Renders one external-agent session, retaining only bounded tool snapshots
/// and final assistant text. The cwd is used for display paths, never I/O.
#[derive(Debug)]
pub(crate) struct EventRenderer {
    active_tools: HashMap<ToolCallId, StartedTool>,
    /// The agent's calls of the tools the run serves it, which the served
    /// calls draw instead.
    served: ServedCalls,
    /// The served calls' own cards not yet ended.
    open_cards: OpenCards,
    cwd: PathBuf,
    step_started: bool,
    result_text: String,
    /// Turns that reached a stop reason, including ones a later cancel or
    /// disconnect interrupts the result of.
    turns: u64,
    /// A tool call or turn end closed the current assistant segment; the next
    /// text chunk starts a fresh result instead of appending to narration.
    result_segment_closed: bool,
}

impl EventRenderer {
    pub(crate) fn new(cwd: PathBuf) -> Self {
        Self {
            active_tools: HashMap::new(),
            served: ServedCalls::default(),
            open_cards: OpenCards::default(),
            cwd,
            step_started: false,
            result_text: String::new(),
            turns: 0,
            result_segment_closed: false,
        }
    }

    /// Bounded final assistant text for the driver's result.json: the text after
    /// the last tool call or turn boundary, matching `-p` runtimes' `result`.
    /// Earlier segments are kept only until a newer segment produces text.
    pub(crate) fn result_text(&self) -> &str {
        &self.result_text
    }

    /// Completed turns rendered so far.
    pub(crate) fn turns(&self) -> u64 {
        self.turns
    }

    /// What the run's end shows: the calls of served tools still held,
    /// and the served calls' cards still open, as interrupted. The run's
    /// end stops every served call, and none draws after it: a call the
    /// stdio bridge parked past the agent's end of its call draws its end
    /// only once the run stopped rendering.
    pub(crate) fn run_ended(&mut self) -> Vec<StreamEffect> {
        let mut effects = self.release_held();
        let mut cut_off = Vec::new();
        for (id, mut card) in self.open_cards.take() {
            card.status = ToolCardStatus::Interrupted;
            cut_off.push(StreamEffect::Attachment(AttachmentEvent::ToolFinished {
                key: Some(id.to_string()),
                presentation: card.into(),
            }));
        }
        effects.extend(self.with_step_started(cut_off));
        effects
    }

    pub(crate) fn render(&mut self, event: AgentEvent) -> Vec<StreamEffect> {
        match event {
            AgentEvent::Update(update) => self.render_update(*update),
            AgentEvent::TurnEnded(reason) => {
                // The turn's held calls, which the agent never ran.
                let mut effects = self.release_held();
                self.turns += 1;
                self.step_started = false;
                self.result_segment_closed = true;
                let label = match reason {
                    StopReason::EndTurn => "end_turn",
                    StopReason::MaxTokens => "max_tokens",
                    StopReason::MaxTurnRequests => "max_turn_requests",
                    StopReason::Refusal => "refusal",
                    StopReason::Cancelled => "cancelled",
                    _ => {
                        effects.extend(notice("acp: unhandled stop reason".into()));
                        return effects;
                    }
                };
                effects.push(StreamEffect::Status(StatusPatch {
                    last_activity: Some(format!("turn ended: {label}")),
                    ..StatusPatch::default()
                }));
                effects
            }
            AgentEvent::Notice(message) => notice(message),
            AgentEvent::ServedToolCall(call) => self.render_served_call(*call),
            AgentEvent::ServedHidden(call) => self.render_hidden(call),
            AgentEvent::Served { call, card } => self.render_served(call, card),
        }
    }

    /// The agent announced `call` of a tool the run serves it: held, while
    /// it runs, for the served call to draw. One the agent announces
    /// already ended shows as the agent's, unless the served call drew it.
    fn render_served_call(&mut self, call: ToolCall) -> Vec<StreamEffect> {
        let id = call.tool_call_id.clone();
        let drawn = matches!(
            self.served.state(&id),
            Some(ServedState::Drawn | ServedState::AgentEnded)
        );
        let (tool, notices) = started_card(&call, &self.cwd);
        match tool.card.status {
            ToolCardStatus::Running if drawn => {
                self.result_segment_closed = true;
                self.with_step_started(notices.into_iter().flat_map(notice).collect())
            }
            ToolCardStatus::Running => {
                let held = matches!(self.served.state(&id), Some(ServedState::Held(_)));
                if !held && !self.has_room() {
                    // Past the budget: the agent's card shows, and says so,
                    // until the served call draws its own.
                    return self.render_update(SessionUpdate::ToolCall(call));
                }
                self.result_segment_closed = true;
                self.served.set(id, ServedState::Held(tool));
                // Its card waits; what it says of the protocol does not.
                self.with_step_started(notices.into_iter().flat_map(notice).collect())
            }
            ToolCardStatus::Ok | ToolCardStatus::Error | ToolCardStatus::Interrupted if drawn => {
                // The agent ended its card: the served call's stands.
                self.result_segment_closed = true;
                self.agent_ended(&id);
                self.with_step_started(notices.into_iter().flat_map(notice).collect())
            }
            ToolCardStatus::Ok | ToolCardStatus::Error | ToolCardStatus::Interrupted => {
                let mut effects = Vec::new();
                if self.has_tool_capacity(&mut effects) {
                    self.served.set(id, ServedState::Released);
                }
                effects.extend(self.render_update(SessionUpdate::ToolCall(call)));
                effects
            }
            // `Unknown`, which no ACP status maps to.
            _ => self.render_update(SessionUpdate::ToolCall(call)),
        }
    }

    /// Served call `call` shows on another call's card: the agent's card
    /// for it shows nothing, from its announcement to its end. One shown
    /// already, as the agent's past the budget, stays.
    fn render_hidden(&mut self, call: ToolCallId) -> Vec<StreamEffect> {
        let mut effects = Vec::new();
        match self.served.state(&call) {
            // Its card shows as the agent's already, closed.
            Some(ServedState::Released) => {
                self.served.forget(&call);
            }
            Some(ServedState::Held(_) | ServedState::Drawn) => {
                self.served.set(call, ServedState::Drawn);
            }
            // Its served card stands until its end.
            Some(ServedState::AgentEnded) => {}
            None => {
                if !self.active_tools.contains_key(&call) && self.has_tool_capacity(&mut effects) {
                    self.served.set(call, ServedState::Drawn);
                }
            }
        }
        effects
    }

    /// Served call `call` drew `card`, on the agent's call's card: the
    /// agent's card, if it showed as no served call's, is the served
    /// call's from now on. One the agent ended before any served card is
    /// dropped, so the card the agent closed stays closed.
    fn render_served(&mut self, call: ToolCallId, card: ServedCard) -> Vec<StreamEffect> {
        let mut effects = Vec::new();
        match self.served.state(&call) {
            Some(ServedState::Released) => {
                if matches!(card, ServedCard::Finished { .. }) {
                    // The served call's last card: nothing comes after it.
                    self.served.forget(&call);
                }
                return Vec::new();
            }
            Some(ServedState::Held(_) | ServedState::Drawn) => {
                self.served.set(call.clone(), ServedState::Drawn);
            }
            Some(ServedState::AgentEnded) => {
                if matches!(card, ServedCard::Finished { .. }) {
                    // The served call's last card: its slot is free.
                    self.served.forget(&call);
                }
            }
            None => {
                // Shown as the agent's past the budget: the slot it took
                // is the served call's now.
                let was_active = self.active_tools.remove(&call).is_some();
                if was_active || self.has_tool_capacity(&mut effects) {
                    self.served.set(call.clone(), ServedState::Drawn);
                }
            }
        }
        let key = call.to_string();
        let (event, content) = match card {
            ServedCard::Started(card) => {
                self.result_segment_closed = true;
                self.open_cards.drew(&call, &card);
                let event = AttachmentEvent::ToolStarted {
                    key: Some(key.clone()),
                    card,
                };
                (event, Vec::new())
            }
            ServedCard::Updated { card, content } => {
                self.open_cards.drew(&call, &card);
                let event = AttachmentEvent::ToolUpdated {
                    key: Some(key.clone()),
                    card,
                };
                (event, content)
            }
            ServedCard::Finished {
                presentation,
                content,
            } => {
                self.open_cards.ended(&call);
                let event = AttachmentEvent::ToolFinished {
                    key: Some(key.clone()),
                    presentation,
                };
                (event, content)
            }
        };
        effects.push(StreamEffect::Attachment(event));
        if !content.is_empty() {
            effects.push(StreamEffect::Attachment(AttachmentEvent::ToolContent {
                key,
                content,
            }));
        }
        self.with_step_started(effects)
    }

    /// The agent ended its card of drawn call `id`: forgotten, unless the
    /// served call's own card is still open, as for a call the stdio
    /// bridge parked, whose later cards then still update and end it.
    fn agent_ended(&mut self, id: &ToolCallId) {
        if self.open_cards.is_open(id) {
            self.served.set(id.clone(), ServedState::AgentEnded);
        } else {
            self.served.forget(id);
        }
    }

    /// Shows the calls of served tools still held as the agent's cards,
    /// interrupted: no served call drew them, and none will now.
    fn release_held(&mut self) -> Vec<StreamEffect> {
        let mut effects = Vec::new();
        for (id, mut tool) in self.served.release_held() {
            tool.card.status = ToolCardStatus::Interrupted;
            effects.extend(self.render_started(id, tool, Vec::new()));
        }
        effects
    }

    fn render_update(&mut self, update: SessionUpdate) -> Vec<StreamEffect> {
        match update {
            SessionUpdate::AgentMessageChunk(chunk) => match chunk.content {
                ContentBlock::Text(text) => {
                    if std::mem::take(&mut self.result_segment_closed) {
                        self.result_text.clear();
                    }
                    self.result_text.push_str(&text.text);
                    self.result_text = bound_result_text(&self.result_text);
                    self.with_step_started(text_effects(&text.text))
                }
                other => content_notice(&other).map_or_else(Vec::new, notice),
            },
            SessionUpdate::AgentThoughtChunk(chunk) => match chunk.content {
                ContentBlock::Text(text) => self.with_step_started(reasoning_effects(&text.text)),
                other => content_notice(&other).map_or_else(Vec::new, notice),
            },
            SessionUpdate::UserMessageChunk(_) => Vec::new(),
            SessionUpdate::ToolCall(call) => {
                let (tool, notices) = started_card(&call, &self.cwd);
                self.render_started(call.tool_call_id, tool, notices)
            }
            SessionUpdate::ToolCallUpdate(update) => self.render_tool_update(update),
            SessionUpdate::Plan(plan) => self.render_plan(plan),
            SessionUpdate::CurrentModeUpdate(mode) => vec![StreamEffect::Status(StatusPatch {
                last_activity: Some(format!("mode: {}", mode.current_mode_id)),
                ..StatusPatch::default()
            })],
            SessionUpdate::UsageUpdate(usage) => self.render_usage(usage),
            SessionUpdate::AvailableCommandsUpdate(_)
            | SessionUpdate::ConfigOptionUpdate(_)
            | SessionUpdate::SessionInfoUpdate(_) => Vec::new(),
            _ => notice("acp: unhandled session update".into()),
        }
    }

    /// Shows the agent's call `key` starting with card `tool`, after the
    /// `notices` its snapshot raised.
    fn render_started(
        &mut self,
        key: ToolCallId,
        tool: StartedTool,
        notices: Vec<String>,
    ) -> Vec<StreamEffect> {
        self.result_segment_closed = true;
        let mut effects = notices.into_iter().flat_map(notice).collect::<Vec<_>>();
        effects.push(StreamEffect::Attachment(AttachmentEvent::ToolStarted {
            key: Some(key.to_string()),
            card: tool.card.clone(),
        }));
        // Terminal initial snapshots still render as ToolStarted, but
        // need no retained state unless an update follows.
        match tool.card.status {
            ToolCardStatus::Running => {
                if self.active_tools.contains_key(&key) || self.has_tool_capacity(&mut effects) {
                    self.active_tools.insert(key, tool);
                }
            }
            ToolCardStatus::Ok | ToolCardStatus::Error | ToolCardStatus::Interrupted => {
                self.active_tools.remove(&key);
            }
            // `Unknown`, which no ACP status maps to: never retained.
            _ => {
                self.active_tools.remove(&key);
            }
        }
        self.with_step_started(effects)
    }

    /// Shows the agent's `update` of one of its calls. A served call's
    /// card shows what the agent's would, and more: the agent's shows only
    /// for a call it ends before a served call drew it.
    fn render_tool_update(&mut self, update: ToolCallUpdate) -> Vec<StreamEffect> {
        let key = update.tool_call_id.clone();
        let ends = ends(&update);
        match self.served.state(&key) {
            Some(ServedState::Drawn) => {
                if ends {
                    self.agent_ended(&key);
                }
                return Vec::new();
            }
            Some(ServedState::AgentEnded) => return Vec::new(),
            Some(ServedState::Held(_)) if !ends => {
                let notices = self
                    .served
                    .held_mut(&key)
                    .map(|tool| finished_card(tool, &update, &self.cwd).1)
                    .unwrap_or_default();
                // Its card waits; what it says of the protocol does not.
                return self.with_step_started(notices.into_iter().flat_map(notice).collect());
            }
            Some(ServedState::Held(_)) => {
                // Shown as the agent's after all, through the path any of
                // its calls takes; a served card that comes later is
                // dropped.
                if let Some(tool) = self.served.release(&key) {
                    let mut effects = self.render_started(key, tool, Vec::new());
                    effects.extend(self.render_agent_update(update));
                    return effects;
                }
            }
            Some(ServedState::Released) | None => {}
        }
        self.render_agent_update(update)
    }

    /// Shows the agent's `update` of a call whose card is the agent's.
    fn render_agent_update(&mut self, update: ToolCallUpdate) -> Vec<StreamEffect> {
        let key = update.tool_call_id.clone();
        let known = self.active_tools.contains_key(&key);
        let mut tool = self
            .active_tools
            .remove(&key)
            .unwrap_or_else(StartedTool::unknown);
        let (card, notices) = finished_card(&mut tool, &update, &self.cwd);
        let mut effects = notices.into_iter().flat_map(notice).collect::<Vec<_>>();
        let finished = match card.status {
            ToolCardStatus::Ok | ToolCardStatus::Error => true,
            ToolCardStatus::Running | ToolCardStatus::Interrupted => false,
            // `Unknown`, which no ACP status maps to: never retained.
            _ => true,
        };
        let event = if finished {
            AttachmentEvent::ToolFinished {
                key: Some(key.to_string()),
                presentation: card.into(),
            }
        } else {
            if known || self.has_tool_capacity(&mut effects) {
                self.active_tools.insert(key.clone(), tool);
            }
            AttachmentEvent::ToolUpdated {
                key: Some(key.to_string()),
                card,
            }
        };
        effects.push(StreamEffect::Attachment(event));
        self.with_step_started(effects)
    }

    /// Records the agent's whole plan as it stands, which replaces the one
    /// before: its first [`MAX_TOOL_BODY_LINES`] steps, and of their text
    /// [`MAX_TOOL_PAYLOAD_CHARS`] in all, the bounds the plan's card kept
    /// in the journal before plans were recorded as such. A notice says
    /// when the plan is longer.
    fn render_plan(&mut self, plan: Plan) -> Vec<StreamEffect> {
        let mut effects = Vec::new();
        let mut entries = Vec::new();
        let steps = plan.entries.len();
        let mut text_left = MAX_TOOL_PAYLOAD_CHARS;
        let mut cut = false;
        for entry in plan.entries.into_iter().take(MAX_TOOL_BODY_LINES) {
            if text_left == 0 {
                cut = true;
                break;
            }
            let chars = entry.content.chars().count();
            let content = if chars > text_left {
                cut = true;
                bound_text(&entry.content, text_left, "plan step")
            } else {
                entry.content
            };
            text_left = text_left.saturating_sub(chars);
            let status = match entry.status {
                PlanEntryStatus::Pending => PlanStatus::Pending,
                PlanEntryStatus::InProgress => PlanStatus::InProgress,
                PlanEntryStatus::Completed => PlanStatus::Completed,
                // A status a newer agent sends: the step still shows, as
                // not started.
                _ => {
                    effects.extend(notice("acp: unhandled plan entry status".into()));
                    PlanStatus::Pending
                }
            };
            entries.push(PlanEntry { content, status });
        }
        if cut || entries.len() < steps {
            effects.extend(notice(format!(
                "acp: the agent's plan has {steps} steps; recorded the first {} \
                 ({MAX_TOOL_BODY_LINES} at most, {MAX_TOOL_PAYLOAD_CHARS} characters in all)",
                entries.len()
            )));
        }
        effects.push(StreamEffect::Attachment(AttachmentEvent::Plan(entries)));
        self.with_step_started(effects)
    }

    fn render_usage(&self, usage: UsageUpdate) -> Vec<StreamEffect> {
        let mut effects = vec![StreamEffect::Attachment(AttachmentEvent::ContextUsage(
            ContextUsage::provider_reported(usage.used, Some(usage.size)),
        ))];
        match usage.cost.as_ref().map(usd_cost) {
            Some(Ok(amount)) => effects.push(StreamEffect::Status(StatusPatch {
                total_cost_usd: Some(amount),
                ..StatusPatch::default()
            })),
            Some(Err(problem)) => effects.extend(notice(problem)),
            None => {}
        }
        effects
    }

    /// Losing enrichment is fail-soft, but the budget must be visible.
    fn has_tool_capacity(&mut self, effects: &mut Vec<StreamEffect>) -> bool {
        if self.has_room() {
            return true;
        }
        let asked = self.in_flight() + 1;
        effects.extend(notice(format!(
            "acp: active tool budget {MAX_ACTIVE_TOOLS}, requested {asked}; card renders without retained update state"
        )));
        false
    }

    /// Whether one more call fits [`MAX_ACTIVE_TOOLS`], making room by
    /// forgetting a released served call if need be. Say so when not
    /// ([`Self::has_tool_capacity`]).
    fn has_room(&mut self) -> bool {
        self.in_flight() < MAX_ACTIVE_TOOLS
            || (self.served.forget_a_released() && self.in_flight() < MAX_ACTIVE_TOOLS)
    }

    /// The calls retained in flight: the agent's, and the served calls
    /// tracked.
    fn in_flight(&self) -> usize {
        self.active_tools.len() + self.served.len()
    }

    fn with_step_started(&mut self, mut effects: Vec<StreamEffect>) -> Vec<StreamEffect> {
        if !self.step_started && !effects.is_empty() {
            self.step_started = true;
            effects.insert(0, StreamEffect::Attachment(AttachmentEvent::StepStarted));
        }
        effects
    }
}

/// Whether `update` ends the agent's call.
fn ends(update: &ToolCallUpdate) -> bool {
    match update.fields.status {
        Some(ToolCallStatus::Completed | ToolCallStatus::Failed) => true,
        Some(ToolCallStatus::Pending | ToolCallStatus::InProgress) | None => false,
        // A status a newer protocol adds.
        Some(_) => false,
    }
}

fn notice(message: String) -> Vec<StreamEffect> {
    vec![StreamEffect::Attachment(AttachmentEvent::Notice(message))]
}

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