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
//! Cards for the calls that act on sessions the daemon has: every action
//! of `session_control`. Results name the session's `title` where it has
//! one; a card names a session by its title, else its short id.

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

use rho_protocol::{
    display::{ToolBody, ToolCard, ToolCardStatus, ToolFact, ToolFamily, ToolHeader},
    Ask, InputRequest, JobState, QuestionAsk, SessionId, TurnOutcome,
};
use serde::{de::DeserializeOwned, Deserialize};
use serde_json::Value;

use super::{body, counted, quoted_first_line, result, session_arg, short_id, string_arg, Verb};
use crate::app::session_control::{
    Action, AnswerResult, CancelResult, ListResult, NewResult, PromptResult, ReadResult,
    SteerResult, Titled, WaitResult,
};

fn verb(action: Action) -> Verb {
    match action {
        Action::List => Verb::new("listing", "listed"),
        Action::Read => Verb::new("reading", "read"),
        Action::New => Verb::new("starting", "started"),
        Action::Prompt => Verb::new("prompting", "prompted"),
        Action::Steer => Verb::new("steering", "steered"),
        Action::Cancel => Verb::new("cancelling", "cancelled"),
        Action::Wait => Verb::new("waiting on", "waited"),
        Action::Answer => Verb::new("answering", "answered"),
    }
}

/// The header before the result: a new session's first prompt, else the
/// session the arguments name, shortened.
pub(super) fn preview_header(
    action: Action,
    arguments: &Value,
    status: ToolCardStatus,
) -> ToolHeader {
    let target = match action {
        Action::List => "sessions".to_owned(),
        Action::New => first_prompt(arguments),
        Action::Read
        | Action::Prompt
        | Action::Steer
        | Action::Cancel
        | Action::Wait
        | Action::Answer => session_arg(arguments),
    };
    verb(action).header(status, target)
}

/// A new session's first prompt, quoted: it has no title yet.
fn first_prompt(arguments: &Value) -> String {
    string_arg(arguments, "prompt").map_or_else(
        || "session".to_owned(),
        |prompt| quoted_first_line(&prompt).0,
    )
}

/// The card of a call that succeeded with `content`, if it reads as the
/// action's result.
pub(super) fn finished_card(action: Action, arguments: &Value, content: &str) -> Option<ToolCard> {
    let status = ToolCardStatus::Ok;
    let card = |target: String| {
        ToolCard::new(
            status,
            ToolFamily::Default,
            verb(action).header(status, target),
        )
    };
    let meta = |text: String| ToolFact::Meta { text };
    // The session a titled result `T` names, and the result.
    fn titled<T: DeserializeOwned>(
        content: &str,
        session: impl Fn(&T) -> &SessionId,
    ) -> Option<(String, T)> {
        let titled: Titled<T> = result(content)?;
        let name = titled
            .title
            .unwrap_or_else(|| short_id(session(&titled.result).as_str()));
        Some((name, titled.result))
    }
    Some(match action {
        Action::List => list_card(card, result(content)?, arguments),
        Action::New => {
            let started: NewResult = result(content)?;
            let mut card = card(first_prompt(arguments));
            let mut place = vec![
                short_id(started.session.as_str()),
                dir_name(&started.workspace),
            ];
            place.extend(
                started
                    .worktree
                    .map(|tree| format!("worktree {}", tree.branch)),
            );
            card.push_fact(meta(place.join(" · ")));
            let runs_as: Vec<String> = [
                string_arg(arguments, "agent").map(|agent| format!("as {agent}")),
                string_arg(arguments, "model"),
            ]
            .into_iter()
            .flatten()
            .collect();
            if !runs_as.is_empty() {
                card.push_fact(meta(runs_as.join(" · ")));
            }
            push_message_body(&mut card, string_arg(arguments, "prompt"));
            card
        }
        Action::Prompt | Action::Steer => {
            let name = match action {
                Action::Steer => titled(content, |steered: &SteerResult| &steered.session)?.0,
                _ => titled(content, |prompted: &PromptResult| &prompted.session)?.0,
            };
            let mut card = card(name);
            // NEXT_MAJOR(rho mcp serve): read `prompt` alone once its `text` alias goes.
            let message = string_arg(arguments, "prompt").or_else(|| string_arg(arguments, "text"));
            if let Some(message) = &message {
                card.push_fact(meta(quoted_first_line(message).0));
            }
            push_message_body(&mut card, message);
            card
        }
        Action::Cancel => {
            let mut card = card(titled(content, |cancelled: &CancelResult| &cancelled.session)?.0);
            card.push_fact(meta("its turn was asked to stop".to_owned()));
            card
        }
        Action::Answer => {
            let mut card = card(titled(content, |answered: &AnswerResult| &answered.session)?.0);
            push_answers(&mut card, arguments);
            card
        }
        Action::Read => {
            let (name, window) = titled(content, |read: &ReadResult| &read.session)?;
            let mut card = card(name);
            let mut summary = format!(
                "transcript · chars {}–{} of {}",
                window.start, window.end, window.total_chars
            );
            if window.next_start.is_some() {
                summary.push_str(" · more available");
            }
            card.push_fact(meta(summary));
            card.body = body(window.text.lines().map(str::to_owned).collect());
            card
        }
        Action::Wait => {
            let (name, waited) = titled(content, |waited: &WaitResult| &waited.session)?;
            wait_card(card, name, waited, arguments)
        }
    })
}

/// A list: how many sessions, a tally of their states and the filters, and
/// a table of them to expand.
fn list_card(card: impl Fn(String) -> ToolCard, listed: ListResult, arguments: &Value) -> ToolCard {
    let count = listed.sessions.len();
    let mut card = card(match count {
        0 => "no sessions".to_owned(),
        count => counted(count, "session"),
    });
    let mut tally: Vec<(&str, usize)> = Vec::new();
    for entry in &listed.sessions {
        let state = state_name(entry.state);
        match tally.iter_mut().find(|(name, _)| *name == state) {
            Some((_, seen)) => *seen += 1,
            None => tally.push((state, 1)),
        }
    }
    let mut facts: Vec<String> = tally
        .into_iter()
        .map(|(state, count)| format!("{count} {state}"))
        .collect();
    if listed.more {
        facts.push("more not listed".to_owned());
    }
    if !facts.is_empty() {
        card.push_fact(ToolFact::Meta {
            text: facts.join(" · "),
        });
    }
    let filters = list_filters(arguments);
    if !filters.is_empty() {
        card.push_fact(ToolFact::Meta {
            text: filters.join(" · "),
        });
    }
    let state_width = listed
        .sessions
        .iter()
        .map(|entry| state_name(entry.state).chars().count())
        .max()
        .unwrap_or_default();
    let rows = listed.sessions.iter().map(|entry| {
        let title = entry.title.as_deref().unwrap_or("untitled");
        let place = match &entry.worktree {
            Some(tree) => format!("worktree {}", tree.branch),
            None => dir_name(&entry.workspace),
        };
        format!(
            "{:state_width$}  {}  {:40}  {place}",
            state_name(entry.state),
            short_id(entry.session.as_str()),
            super::truncate(title, 40),
        )
        .trim_end()
        .to_owned()
    });
    card.body = body(rows.collect());
    card
}

/// The filters a list's arguments set, as the card shows them.
fn list_filters(arguments: &Value) -> Vec<String> {
    let mut filters = Vec::new();
    if let Some(workspace) = string_arg(arguments, "workspace") {
        filters.push(format!("in {}", dir_name(Path::new(&workspace))));
    }
    let state = arguments
        .get("state")
        .and_then(|state| JobState::deserialize(state).ok());
    if let Some(state) = state {
        filters.push(format!("only {}", state_name(state)));
    }
    if let Some(opener) = string_arg(arguments, "opened_by") {
        filters.push(format!("opened by {opener}"));
    }
    if arguments.get("hide_idle").and_then(Value::as_bool) == Some(true) {
        filters.push("idle hidden".to_owned());
    }
    filters
}

/// A wait: the session and how it stands in the header, then what it
/// answered, failed with, or asks.
fn wait_card(
    card: impl Fn(String) -> ToolCard,
    name: String,
    waited: WaitResult,
    arguments: &Value,
) -> ToolCard {
    let standing = if !waited.done {
        "still running"
    } else {
        match waited.inputs.first().map(|input| &input.ask) {
            Some(Ask::Question(_)) => "needs an answer",
            Some(Ask::Approval(_) | Ask::PlanApproval(_)) => "needs approval",
            Some(_) | None => state_name(waited.state),
        }
    };
    let mut card = card(format!("{name} · {standing}"));
    let mut lines = Vec::new();
    match &waited.outcome {
        Some(TurnOutcome::Answered { text, .. }) => push_answer(&mut card, &mut lines, text),
        Some(TurnOutcome::MaxSteps { text }) => {
            card.push_fact(ToolFact::Meta {
                text: "stopped at its step limit".to_owned(),
            });
            push_answer(&mut card, &mut lines, text);
        }
        Some(TurnOutcome::Failed { error }) => {
            let first = error.message.lines().next().unwrap_or_default();
            card.push_fact(ToolFact::Error {
                text: super::truncate(first, 160),
            });
            lines.extend(error.message.lines().map(str::to_owned));
        }
        Some(TurnOutcome::TimedOut { timeout_ms }) => card.push_fact(ToolFact::Meta {
            text: format!("timed out after {}s", timeout_ms / 1000),
        }),
        // No turn ended yet; `Cancelled`, which the header says; or
        // `Unknown` and outcomes a newer daemon sends, which it cannot.
        _ => {}
    }
    for input in &waited.inputs {
        push_input(&mut card, &mut lines, input);
    }
    if !waited.done && waited.outcome.is_none() {
        let waited_for = arguments.get("timeout_secs").and_then(Value::as_u64);
        card.push_fact(ToolFact::Meta {
            text: match waited_for {
                Some(secs) => format!("no answer yet after {secs}s"),
                None => "no answer yet".to_owned(),
            },
        });
    }
    card.body = body(lines);
    card
}

/// A final answer: its first line on the card, all of it to expand.
fn push_answer(card: &mut ToolCard, body: &mut Vec<String>, text: &str) {
    let first = text.lines().map(str::trim).find(|line| !line.is_empty());
    if let Some(first) = first {
        card.push_fact(ToolFact::Meta {
            text: super::truncate(first, 160),
        });
    }
    push_section(body, text.trim().lines().map(str::to_owned));
}

/// What a session waits on: a question's summary on the card and its
/// questions and choices to expand, or the approval it waits for.
fn push_input(card: &mut ToolCard, body: &mut Vec<String>, input: &InputRequest) {
    let text = match &input.ask {
        Ask::Question(ask) => {
            push_section(body, question_lines(ask));
            format!(
                "asks \"{}\" · {} · request {}",
                ask.title,
                counted(ask.questions.len(), "question"),
                input.id
            )
        }
        Ask::Approval(ask) => format!("waits for a person to approve: {}", ask.reason),
        Ask::PlanApproval(_) => "waits for a person to approve its plan".to_owned(),
        // `Unknown`, or an ask a newer daemon sends.
        _ => "waits for a person".to_owned(),
    };
    card.push_fact(ToolFact::Meta { text });
}

/// A question ask's reason, then its questions, each with its choices, the
/// default marked.
fn question_lines(ask: &QuestionAsk) -> Vec<String> {
    // Why it asks, which a person needs to choose.
    let mut lines: Vec<String> = ask
        .reason
        .iter()
        .flat_map(|reason| reason.lines())
        .map(str::to_owned)
        .collect();
    for question in &ask.questions {
        let label = question.header.as_deref().unwrap_or(&question.id);
        lines.push(format!("{label}: {}", question.prompt));
        let defaults = question
            .default
            .as_ref()
            .map_or(&[][..], |default| default.values.as_slice());
        for choice in &question.choices {
            let default = if defaults.contains(&choice.value) {
                " (default)"
            } else {
                ""
            };
            lines.push(format!("  • {}{default}", choice.label));
        }
    }
    lines
}

/// Appends `lines` to `body`, a blank line apart from what it holds.
fn push_section(body: &mut Vec<String>, lines: impl IntoIterator<Item = String>) {
    if !body.is_empty() {
        body.push(String::new());
    }
    body.extend(lines);
}

/// The whole message a call sent, to expand, when its quoted first line
/// left some out.
fn push_message_body(card: &mut ToolCard, message: Option<String>) {
    if let Some(message) = message.filter(|message| quoted_first_line(message).1) {
        card.body = ToolBody::Lines(message.lines().map(str::to_owned).collect());
    }
}

/// An answer's answers, `question: value, value` each, on one line, with
/// all of them to expand when that line left some out; or that it declined.
fn push_answers(card: &mut ToolCard, arguments: &Value) {
    let answers = arguments
        .get("answers")
        .and_then(|answers| BTreeMap::<String, Vec<String>>::deserialize(answers).ok());
    let Some(answers) = answers else {
        card.push_fact(ToolFact::Meta {
            text: "declined".to_owned(),
        });
        return;
    };
    let answers: Vec<String> = answers
        .iter()
        .map(|(question, values)| format!("{question}: {}", values.join(", ")))
        .collect();
    let whole = answers.join(" · ");
    let shown = super::truncate(&whole, 120);
    let cut = shown != whole;
    card.push_fact(ToolFact::Meta { text: shown });
    if cut {
        card.body = body(
            answers
                .iter()
                .flat_map(|answer| answer.lines())
                .map(str::to_owned)
                .collect(),
        );
    }
}

/// A session state as cards say it.
fn state_name(state: JobState) -> &'static str {
    match state {
        JobState::Idle => "idle",
        JobState::Queued => "queued",
        JobState::Running => "running",
        JobState::WaitingForInput => "needs input",
        JobState::Completed => "completed",
        JobState::Failed => "failed",
        JobState::Cancelled => "cancelled",
        JobState::TimedOut => "timed out",
        JobState::Interrupted => "interrupted",
        // `Unknown`, or a state a newer daemon sends.
        _ => "unknown",
    }
}

/// The last component of `path`, which names a workspace well enough.
fn dir_name(path: &Path) -> String {
    path.file_name()
        .unwrap_or(path.as_os_str())
        .to_string_lossy()
        .into_owned()
}