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
//! Turns one session's runtime events and saved transcript into the wire
//! events the daemon streams to attached clients ([`WireEvent`]).
//!
//! [`LiveEvents`] maps a loaded session's live runtime events as a turn
//! emits them; a [`SavedTranscript`] replays the display rows a client that
//! attaches with a reset receives first. Both open a tool call with the same card (title,
//! kind, raw input, locations), attach the card Rho's TUI draws for it from
//! the same presenter (`ToolCallUpdate::display`), and close calls left
//! unfinished as `failed`,
//! so a conversation reads the same whether a client watched it live or
//! received it replayed, apart from how its text was chunked. Only live
//! turns report usage, compactions, discarded responses, provider retries,
//! the provider's hosted tools, and steers' ids and deliveries; saved rows
//! hold none, and the daemon tells titles itself.
//!
//! [`outcome`] says how a turn ended, for the daemon's clients and
//! `rho run` alike.
//!
//! The ACP adapter maps these wire events to ACP updates
//! (`acp/updates.rs`).

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

use rho_protocol::display::{NotificationInfo, ToolHeader};
use rho_protocol::{
    CardTone, ContentBlock, Location, PlanEntry, PlanStatus, SessionEvent as WireEvent, SteerId,
    ToolCallId, ToolCallUpdate, ToolContent, ToolStatus,
};
use rho_sdk::{
    model,
    tool::{ToolMetadata, ToolOutput},
};
use serde_json::Value;

use crate::{
    app::interactive_presenter::call_header,
    display_transcript::{DisplayRow, DisplayTranscript},
    tools::{
        mcp::exported_name::McpToolNames,
        todo::{TodoState, TodoStatus},
    },
};
use rho_protocol::display::NotificationTone;

mod live;
mod message_ids;
pub(crate) mod outcome;
mod replay;
#[cfg(test)]
mod test_support;
mod tools;

pub(crate) use live::{CompactionEnd, LiveEvents};
pub(crate) use message_ids::user_message_id;
pub(crate) use replay::{row_locations, SavedTranscript, SavedTurn};

/// A wire event, with what a client is sent beside it
/// ([`rho_protocol::SessionEventEnvelope`]): when it happened, in unix
/// milliseconds, and the typed notification of a card that shows one. A
/// replayed event carries when its row was saved; the daemon's feed times a
/// live one as it sends it.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct FeedEvent {
    pub(crate) event: WireEvent,
    pub(crate) at: Option<u64>,
    pub(crate) notification: Option<Box<NotificationInfo>>,
}

impl From<WireEvent> for FeedEvent {
    fn from(event: WireEvent) -> Self {
        Self {
            event,
            at: None,
            notification: None,
        }
    }
}

impl FeedEvent {
    /// The event as a subscription carries it, under `seq`.
    pub(crate) fn into_stream(self, seq: rho_protocol::Seq) -> rho_protocol::StreamEvent {
        let mut sent = rho_protocol::StreamEvent::new(seq, self.event);
        sent.at = self.at;
        sent.notification = self.notification;
        sent
    }

    /// How many bytes it takes as JSON, event and notification, or `None`
    /// when JSON cannot hold it ([`encoded_len`]).
    pub(crate) fn encoded_len(&self) -> Option<usize> {
        let notification = match &self.notification {
            Some(notification) => encoded_len(notification)?,
            None => 0,
        };
        Some(encoded_len(&self.event)? + notification)
    }
}

/// Hands out wire ids for tool calls. Providers may reuse a call id across
/// turns, and a reused wire id would update the earlier card, so each call
/// opened under a provider id after its first is numbered (`id#2`, ...). A
/// call without an id is numbered by how many such calls came before.
#[derive(Clone, Debug, Default)]
struct CallIds {
    /// How many calls each provider id has opened.
    opened: HashMap<String, usize>,
}

impl CallIds {
    /// The wire id of the next call opened under provider id `provider`.
    fn open(&mut self, provider: &str) -> ToolCallId {
        let count = self.opened.entry(provider.to_owned()).or_default();
        *count += 1;
        match (provider.is_empty(), *count) {
            (false, 1) => ToolCallId::new(provider),
            (false, n) => ToolCallId::new(format!("{provider}#{n}")),
            (true, n) => ToolCallId::new(format!("unnamed-call-{n}")),
        }
    }

    /// Counts every id at least as often as `other` does, so no id either
    /// of them handed out is handed out again.
    fn cover(&mut self, other: &Self) {
        for (provider, &count) in &other.opened {
            let own = self.opened.entry(provider.clone()).or_default();
            *own = (*own).max(count);
        }
    }
}

/// How many bytes `event` encodes to as JSON, or `None`, logged, for one
/// JSON cannot hold, such as one with a non-UTF-8 path. A connection's
/// forwarder relies on every event it is given encoding (`Publisher`), so
/// the daemon's feed sends none this rejects: it checks each live event as
/// it publishes it, and [`SavedTurn`] each saved one as its turn saves.
/// Counts the bytes without keeping them.
pub(crate) fn encoded_len(event: &impl serde::Serialize) -> Option<usize> {
    struct Counter(usize);
    impl std::io::Write for Counter {
        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
            self.0 += bytes.len();
            Ok(bytes.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }
    let mut counter = Counter(0);
    match serde_json::to_writer(&mut counter, event) {
        Ok(()) => Some(counter.0),
        Err(error) => {
            tracing::warn!(%error, "dropped a session event JSON cannot hold");
            None
        }
    }
}

/// Title for a tool call whose name the mapper never saw.
const UNNAMED_TOOL_TITLE: &str = "tool";

/// A tool call as it opens, live or replayed: its title, kind, arguments
/// and the files it names, `in_progress`. `metadata` is what the call's tool
/// reported at start; replay asks the session's tool for it, since saved
/// calls keep none.
fn opened_call(
    id: ToolCallId,
    name: &str,
    arguments: Option<Value>,
    metadata: &ToolMetadata,
    cwd: &Path,
    mcp_tools: &McpToolNames,
) -> ToolCallUpdate {
    let locations = tools::started_locations(name, arguments.as_ref(), metadata, cwd);
    ToolCallUpdate {
        status: Some(ToolStatus::InProgress),
        locations: non_empty(locations),
        ..named_call(id, name, arguments, metadata, cwd, mcp_tools)
    }
}

/// A call's identity without a status: its title, kind and arguments.
fn named_call(
    id: ToolCallId,
    name: &str,
    arguments: Option<Value>,
    metadata: &ToolMetadata,
    cwd: &Path,
    mcp_tools: &McpToolNames,
) -> ToolCallUpdate {
    ToolCallUpdate {
        title: Some(tool_title(
            name,
            arguments.as_ref(),
            metadata,
            cwd,
            mcp_tools,
        )),
        kind: Some(tools::kind(name, arguments.as_ref(), metadata)),
        raw_input: arguments,
        ..status_update(id, /*status*/ None)
    }
}

/// An update that changes at most a call's status; every other field is
/// absent, so it stays as the client has it.
fn status_update(id: ToolCallId, status: Option<ToolStatus>) -> ToolCallUpdate {
    ToolCallUpdate {
        id,
        title: None,
        kind: None,
        status,
        raw_input: None,
        content: None,
        locations: None,
        display: None,
    }
}

/// What a call does, as the interactive card header says it. The title
/// names the call, never a live phase:
/// - a shell call is its bare command: the call's `command_line` metadata,
///   else the command read from its arguments;
/// - a status-first header keeps its identity and drops the phase, except
///   a `sessions` call's, which is its action and the session, query, or
///   prompt it names;
/// - an MCP call leads with its server.
///
/// A replayed call whose tool the session no longer has gets no metadata,
/// so a tool that describes itself through `command_summary` is titled by
/// name alone.
fn tool_title(
    name: &str,
    arguments: Option<&Value>,
    metadata: &ToolMetadata,
    cwd: &Path,
    mcp_tools: &McpToolNames,
) -> String {
    if let Some(command) = metadata.command_line_text().filter(|c| !c.is_empty()) {
        return command.to_owned();
    }
    let title = match call_header(name, arguments, metadata, cwd, mcp_tools) {
        ToolHeader::Shell {
            command: Some(command),
            ..
        } => command,
        // A shell call with no command yet; `$` alone would read as one.
        ToolHeader::Shell { command: None, .. } => name.to_owned(),
        // Its verb has a tense, which a title set once would keep after
        // the call ended: the action names it instead.
        ToolHeader::StatusFirst { detail, .. } if name == crate::session::search::TOOL_NAME => {
            match arguments.and_then(|arguments| arguments.get("action")?.as_str()) {
                Some(action) => format!("{action} {detail}"),
                None => name.to_owned(),
            }
        }
        ToolHeader::StatusFirst { identity, .. } => identity,
        ToolHeader::Call {
            verb,
            primary: Some(primary),
        } if !primary.is_empty() => format!("{verb}({primary})"),
        ToolHeader::Call { verb, .. } => verb,
        // Rho's presenter writes no `Unknown` header.
        _ => name.to_owned(),
    };
    match mcp_tools.identify(name) {
        Some(identity) => format!("{}/{title}", identity.server),
        None => title,
    }
}

/// The id the run accepted a steer under, as the wire names the steer.
pub(crate) fn steer_to_wire(id: &rho_sdk::SteeringId) -> SteerId {
    SteerId::new(id.as_str())
}

/// A user message's content. Empty text says nothing, and a user message
/// never holds tool calls.
fn user_content(blocks: &[model::ContentBlock]) -> Vec<ContentBlock> {
    blocks
        .iter()
        .filter_map(|block| match block {
            model::ContentBlock::Text(text) if !text.is_empty() => {
                Some(ContentBlock::Text { text: text.clone() })
            }
            model::ContentBlock::Image(image) => Some(ContentBlock::Image {
                mime_type: image.mime_type.clone(),
                data: image.data.clone(),
            }),
            model::ContentBlock::Text(_) | model::ContentBlock::ToolCall(_) => None,
        })
        .collect()
}

/// A tool result's content: its text, unless empty, then its images. Live
/// and saved results both start with this, so a replayed call shows what
/// the live one did.
fn result_content(text: &str, images: &[model::ImageContent]) -> Vec<ToolContent> {
    let text = (!text.is_empty()).then(|| text_content(text));
    text.into_iter()
        .chain(images.iter().map(|image| ToolContent::Image {
            mime_type: image.mime_type.clone(),
            data: image.data.clone(),
        }))
        .collect()
}

fn text_content(text: impl Into<String>) -> ToolContent {
    ToolContent::Text { text: text.into() }
}

/// A tool's output as a call's content: what the model got, as replay shows
/// it, then the files it changed. A change is a diff of whole texts; output
/// that only carries a patch shows the patch as text. A move also reports
/// its source deleted, so it is a diff of each path and then the move.
fn output_content(output: &ToolOutput, cwd: &Path) -> Vec<ToolContent> {
    let mut content = result_content(output.content(), output.images());
    let metadata = output.presentation();
    if metadata.file_changes().is_empty() {
        content.extend(metadata.unified_diff().map(text_content));
    }
    for change in metadata.file_changes() {
        let path = cwd.join(change.path());
        let moved = change.moved_from().map(|from| ToolContent::Moved {
            from: cwd.join(from),
            path: path.clone(),
        });
        content.push(ToolContent::Diff {
            path,
            old_text: change.old_text().map(str::to_owned),
            new_text: change.new_text().to_owned(),
            deleted: change.is_deleted(),
        });
        content.extend(moved);
    }
    content
}

/// One card per row of a background result's transcript: the rows a turn
/// shows where it applied the result, and saves for replay. Such a
/// transcript holds no compaction rows, which a replay sends as compaction
/// events instead.
fn cards(transcript: &DisplayTranscript) -> impl Iterator<Item = FeedEvent> + '_ {
    transcript.0.iter().map(card)
}

/// The card that shows `row`, with a notification's typed side.
fn card(row: &DisplayRow) -> FeedEvent {
    let text = row.card_text();
    let (display, notification) = match row {
        DisplayRow::Notification(row) => (
            Some(Box::new(row.card.clone())),
            row.info.clone().map(Box::new),
        ),
        DisplayRow::Notice(_) | DisplayRow::Compaction(_) => (None, None),
    };
    FeedEvent {
        event: WireEvent::Card {
            title: text.title.to_owned(),
            markdown: text.markdown,
            plain: text.plain,
            tone: card_tone(row),
            display,
        },
        at: None,
        notification,
    }
}

/// How a row's card reads: a notification card's tone; any other is neutral.
fn card_tone(row: &DisplayRow) -> CardTone {
    match row {
        DisplayRow::Notification(row) => match row.card.tone {
            NotificationTone::Neutral => CardTone::Neutral,
            NotificationTone::Accent => CardTone::Accent,
            NotificationTone::Success => CardTone::Success,
            NotificationTone::Warning => CardTone::Warning,
            NotificationTone::Error => CardTone::Error,
            // `Unknown`, or a tone a newer protocol adds.
            _ => CardTone::Neutral,
        },
        DisplayRow::Notice(_) | DisplayRow::Compaction(_) => CardTone::Neutral,
    }
}

/// The session's todo checklist as a plan; empty while there is none.
fn plan_entries(todo: &TodoState) -> Vec<PlanEntry> {
    let Some(list) = todo.list() else {
        return Vec::new();
    };
    list.todos
        .iter()
        .map(|item| PlanEntry {
            content: item.content.clone(),
            status: match item.status {
                TodoStatus::Pending => PlanStatus::Pending,
                TodoStatus::InProgress => PlanStatus::InProgress,
                TodoStatus::Completed => PlanStatus::Completed,
            },
        })
        .collect()
}

/// `locations`, or `None` when there are none, so the wire leaves the
/// field out.
fn non_empty(locations: Vec<Location>) -> Option<Vec<Location>> {
    Some(locations).filter(|locations| !locations.is_empty())
}