rho-coding-agent 1.17.0

A lightweight agent harness inspired by Pi
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
583
584
585
586
use super::ToolView;

const TASK_PREVIEW_BYTES: usize = 160;
/// Live agent prompts are long; show a trailing window so argument streaming keeps
/// moving instead of freezing on a short prefix summary.
const STREAMING_PROMPT_CHARS: usize = 400;
const STREAMING_PROMPT_LINES: usize = 8;

pub(super) fn agent_start_lines_for(arguments: &serde_json::Value) -> Vec<String> {
    task_lines(arguments, starting_heading(arguments))
}

/// Streaming preview for an in-progress `agent` tool call.
///
/// Reads fields from the raw partial JSON argument buffer instead of completing
/// and parsing the whole object. Agent prompts are large; rebuilding a JSON
/// value on every delta is the expensive path this avoids.
pub(super) fn agent_streaming_preview_from_raw(raw_arguments: &str) -> Vec<String> {
    let agent_id = partial_object_string_field(raw_arguments, "agent_id")
        .filter(|id| !id.is_empty())
        .unwrap_or_else(|| "agent".into());
    let background = partial_object_bool_field(raw_arguments, "background").unwrap_or(false);
    let mut lines = vec![starting_heading_for(&agent_id, background)];
    if let Some(prompt) =
        partial_object_string_field(raw_arguments, "prompt").filter(|prompt| !prompt.is_empty())
    {
        lines.extend(live_tail_prompt_lines(&prompt));
    }
    lines
}

pub(super) fn agent_interrupted_lines_for(arguments: &serde_json::Value) -> Vec<String> {
    let agent_id = agent_identity(arguments).unwrap_or("agent");
    task_lines(arguments, format!("{agent_id}  interrupted"))
}

pub(super) fn agents_interrupted_lines_for(arguments: &serde_json::Value) -> Vec<String> {
    let action = string_value(arguments, "action").unwrap_or("request");
    let heading = string_value(arguments, "id").map_or_else(
        || format!("■ delegated agents  {action} interrupted"),
        |id| format!("{id}  {action} interrupted"),
    );
    vec![heading]
}

pub(super) fn agent_progress_lines(view: &ToolView, content: &str) -> Vec<String> {
    let agent_id = agent_identity(&view.arguments).unwrap_or("agent");
    let mut lines = task_lines(&view.arguments, format!("{agent_id}  running"));
    if let Some(run_id) = run_id_from_agent_line(content.lines().next().unwrap_or_default()) {
        lines.push(String::new());
        lines.push(format!("  {run_id} · rho attach {run_id}"));
    }
    lines
}

pub(super) fn agent_finished_lines(view: &ToolView, content: &str, ok: bool) -> Vec<String> {
    if let (true, Some(receipt)) = (ok, parse_background_receipt(content)) {
        let mut lines = task_lines(
            &view.arguments,
            format!("{}  running in background", receipt.agent_id),
        );
        lines.push(String::new());
        lines.push(format!(
            "  {} · rho attach {}",
            receipt.run_id, receipt.run_id
        ));
        return lines;
    }
    if let Some(snapshot) = parse_snapshot(content) {
        return snapshot_lines(view, snapshot, SnapshotDisplay::Completion);
    }
    if !ok {
        let agent_id = agent_identity(&view.arguments).unwrap_or("agent");
        let mut lines = task_lines(&view.arguments, format!("{agent_id}  failed"));
        push_content(&mut lines, content);
        return lines;
    }

    let agent_id = agent_identity(&view.arguments).unwrap_or("agent");
    let mut lines = task_lines(&view.arguments, format!("{agent_id}  completed"));
    push_content(&mut lines, content);
    lines
}

pub(super) fn agents_start_lines_for(arguments: &serde_json::Value) -> Vec<String> {
    match string_value(arguments, "action") {
        Some("list") => vec!["● delegated agents  loading".into()],
        Some("status") => vec![format!(
            "{}  checking status",
            string_value(arguments, "id").unwrap_or("delegated agent")
        )],
        Some("stop") => vec![format!(
            "{}  stopping",
            string_value(arguments, "id").unwrap_or("delegated agent")
        )],
        Some(action) => vec![format!("● agents  {action}")],
        None => vec!["agents".into()],
    }
}

pub(super) fn agents_finished_lines(view: &ToolView, content: &str, ok: bool) -> Vec<String> {
    if !ok {
        let action = string_argument(view, "action").unwrap_or("request");
        let mut lines = vec![format!("✗ agents {action}  failed")];
        push_content(&mut lines, content);
        return lines;
    }

    match string_argument(view, "action") {
        Some("list") => agent_list_lines(content),
        Some(action @ ("status" | "stop")) => parse_snapshot(content)
            .map(|snapshot| {
                let display = if action == "status" || snapshot.has_status_metrics() {
                    SnapshotDisplay::Status
                } else {
                    SnapshotDisplay::Completion
                };
                snapshot_lines(view, snapshot, display)
            })
            .unwrap_or_else(|| agents_result_fallback_lines(view, content)),
        _ => {
            let mut lines = vec!["agents".into()];
            push_content(&mut lines, content);
            lines
        }
    }
}

fn agents_result_fallback_lines(view: &ToolView, content: &str) -> Vec<String> {
    let action = string_argument(view, "action").unwrap_or("request");
    let id = string_argument(view, "id");
    let heading = id.map_or_else(
        || format!("○ agents  {action} result"),
        |id| format!("{id}  {action} result"),
    );
    let mut lines = vec![heading];
    push_content(&mut lines, content);
    lines
}

fn starting_heading(arguments: &serde_json::Value) -> String {
    starting_heading_for(
        agent_identity(arguments).unwrap_or("agent"),
        bool_value(arguments, "background"),
    )
}

fn starting_heading_for(agent_id: &str, background: bool) -> String {
    let mode = if background {
        "starting in background"
    } else {
        "starting"
    };
    format!("{agent_id}  {mode}")
}

fn task_lines(arguments: &serde_json::Value, heading: String) -> Vec<String> {
    let mut lines = vec![heading];
    if let Some(task) = string_value(arguments, "prompt").filter(|task| !task.is_empty()) {
        let task = task.split_whitespace().collect::<Vec<_>>().join(" ");
        if !task.is_empty() {
            lines.push(format!("  {}", truncate_preview(&task)));
        }
    }
    lines
}

/// Pull a string object field out of incomplete tool-call JSON.
///
/// Returns the decoded value seen so far when the opening quote has arrived.
/// Incomplete trailing escapes are dropped so previews stay stable mid-stream.
fn partial_object_string_field(raw: &str, key: &str) -> Option<String> {
    let content = partial_object_field_content(raw, key)?;
    let content = content.trim_start();
    if content.is_empty() {
        return Some(String::new());
    }
    let content = content.strip_prefix('"')?;
    Some(decode_partial_json_string(content))
}

fn partial_object_bool_field(raw: &str, key: &str) -> Option<bool> {
    let content = partial_object_field_content(raw, key)?.trim_start();
    if content.starts_with("true") {
        return Some(true);
    }
    if content.starts_with("false") {
        return Some(false);
    }
    None
}

/// After a top-level object key and colon, return the remainder of `raw`.
///
/// Skips matches that appear inside string values so prompt text cannot spoof
/// later field names.
fn partial_object_field_content<'a>(raw: &'a str, key: &str) -> Option<&'a str> {
    let key_pattern = format!("\"{key}\"");
    let mut in_string = false;
    let mut escaped = false;
    let mut index = 0usize;
    while index < raw.len() {
        let character = raw[index..].chars().next()?;
        let character_len = character.len_utf8();
        if in_string {
            if escaped {
                escaped = false;
            } else {
                match character {
                    '\\' => escaped = true,
                    '"' => in_string = false,
                    _ => {}
                }
            }
            index += character_len;
            continue;
        }
        if character == '"' {
            if raw[index..].starts_with(&key_pattern) {
                let after_key = &raw[index + key_pattern.len()..];
                if let Some(after_colon) = after_key.trim_start().strip_prefix(':') {
                    return Some(after_colon);
                }
            }
            in_string = true;
            index += character_len;
            continue;
        }
        index += character_len;
    }
    None
}

fn decode_partial_json_string(content: &str) -> String {
    let mut decoded = String::new();
    let mut chars = content.chars();
    while let Some(character) = chars.next() {
        match character {
            '"' => break,
            '\\' => match chars.next() {
                Some('n') => decoded.push('\n'),
                Some('r') => decoded.push('\r'),
                Some('t') => decoded.push('\t'),
                Some('"') => decoded.push('"'),
                Some('\\') => decoded.push('\\'),
                Some('/') => decoded.push('/'),
                Some('b') => decoded.push('\u{0008}'),
                Some('f') => decoded.push('\u{000c}'),
                Some('u') => {
                    let hex: String = chars.by_ref().take(4).collect();
                    if hex.len() < 4 {
                        break;
                    }
                    if let Ok(code) = u16::from_str_radix(&hex, 16) {
                        if let Some(unicode) = char::from_u32(u32::from(code)) {
                            decoded.push(unicode);
                        }
                    }
                }
                Some(other) => decoded.push(other),
                None => break,
            },
            other => decoded.push(other),
        }
    }
    decoded
}

fn live_tail_prompt_lines(task: &str) -> Vec<String> {
    // Walk backward once so long prompts do not pay a full char count + rescan.
    let mut kept_chars = 0usize;
    let mut start = 0usize;
    let mut dropped_chars = false;
    for (index, _) in task.char_indices().rev() {
        kept_chars += 1;
        start = index;
        if kept_chars == STREAMING_PROMPT_CHARS {
            dropped_chars = index > 0;
            break;
        }
    }
    let body = &task[start..];

    let raw_lines = body.lines().collect::<Vec<_>>();
    let dropped_lines = raw_lines.len() > STREAMING_PROMPT_LINES;
    let kept = if dropped_lines {
        &raw_lines[raw_lines.len() - STREAMING_PROMPT_LINES..]
    } else {
        raw_lines.as_slice()
    };
    if kept.is_empty() {
        return Vec::new();
    }

    let mark_omission = dropped_chars || dropped_lines;
    kept.iter()
        .enumerate()
        .map(|(index, line)| {
            if index == 0 && mark_omission {
                format!("{}", line.trim_start())
            } else {
                format!("  {line}")
            }
        })
        .collect()
}

fn truncate_preview(text: &str) -> String {
    if text.len() <= TASK_PREVIEW_BYTES {
        return text.to_string();
    }
    let mut boundary = TASK_PREVIEW_BYTES;
    while boundary > 0 && !text.is_char_boundary(boundary) {
        boundary -= 1;
    }
    let prefix = &text[..boundary];
    let boundary = prefix
        .char_indices()
        .rev()
        .find_map(|(index, character)| character.is_whitespace().then_some(index))
        .unwrap_or(boundary);
    format!("{}", text[..boundary].trim_end())
}

fn agent_list_lines(content: &str) -> Vec<String> {
    let mut lines = vec!["delegated agents".into()];
    if matches!(content.trim(), "no delegated agents" | "no subagents") {
        lines.push("  no runs".into());
        return lines;
    }
    lines.extend(content.lines().map(|line| {
        let fields = line.splitn(5, "  ").collect::<Vec<_>>();
        if fields.len() != 5 {
            return format!("  {line}");
        }
        format!(
            "{} {}  {}  {}  {}  {}",
            state_glyph(fields[2]),
            fields[0],
            fields[1],
            display_state(fields[2]),
            fields[3],
            fields[4]
        )
    }));
    lines
}

struct BackgroundReceipt<'a> {
    run_id: &'a str,
    agent_id: &'a str,
}

fn parse_background_receipt(content: &str) -> Option<BackgroundReceipt<'_>> {
    let first = content.lines().next()?;
    let rest = strip_run_prefix(first)?;
    let (run_id, rest) = rest.split_once(" (")?;
    let (agent_id, suffix) = rest.split_once(") ")?;
    (suffix == "started in background").then_some(BackgroundReceipt { run_id, agent_id })
}

struct Snapshot<'a> {
    run_id: &'a str,
    agent_id: &'a str,
    state: &'a str,
    remaining: Vec<&'a str>,
}

impl Snapshot<'_> {
    fn has_status_metrics(&self) -> bool {
        self.remaining
            .iter()
            .any(|line| line.starts_with("elapsed: ") || line.starts_with("attach: "))
    }
}

#[derive(Clone, Copy)]
enum SnapshotDisplay {
    Completion,
    Status,
}

fn parse_snapshot(content: &str) -> Option<Snapshot<'_>> {
    let mut lines = content.split('\n');
    let first = lines.next()?;
    let rest = strip_run_prefix(first)?;
    let (run_id, rest) = rest.split_once(" (")?;
    let (agent_id, state) = rest.split_once("): ")?;
    Some(Snapshot {
        run_id,
        agent_id,
        state,
        remaining: lines.collect(),
    })
}

fn snapshot_lines(
    view: &ToolView,
    snapshot: Snapshot<'_>,
    display: SnapshotDisplay,
) -> Vec<String> {
    let metrics_index = snapshot
        .remaining
        .iter()
        .position(|line| line.starts_with("turns: ") || line.starts_with("elapsed: "));
    let metrics = metrics_index.map(|index| snapshot.remaining[index]);
    let turns = metrics.and_then(turns_from_metrics);
    let elapsed = metrics.and_then(elapsed_from_metrics);

    let mut details = Vec::new();
    if let Some(elapsed) = elapsed {
        details.push(elapsed.to_string());
    }
    if let Some(turns) = turns {
        details.push(turns);
    }
    let detail = if details.is_empty() {
        String::new()
    } else {
        format!(" · {}", details.join(" · "))
    };
    let mut lines = task_lines(
        &view.arguments,
        format!(
            "{} {}  {}{}",
            state_glyph(snapshot.state),
            snapshot.agent_id,
            display_state(snapshot.state),
            detail
        ),
    );

    let tokens = metrics.and_then(tokens_from_metrics);
    let attach = snapshot
        .remaining
        .iter()
        .find_map(|line| line.strip_prefix("attach: "));
    let (summary_lines, result_lines) =
        snapshot_sections(&snapshot.remaining, metrics_index, display);
    lines.extend(summary_lines);

    if tokens.is_some() || attach.is_some() || !snapshot.run_id.is_empty() {
        lines.push(String::new());
        lines.push(match (tokens, attach) {
            (Some(tokens), _) => format!("  {} · {tokens}", snapshot.run_id),
            (None, Some(attach)) => format!("  {} · {attach}", snapshot.run_id),
            (None, None) => format!("  {}", snapshot.run_id),
        });
        if tokens.is_some() {
            if let Some(attach) = attach {
                lines.push(format!("  {attach}"));
            }
        }
    }
    if !result_lines.is_empty() {
        lines.push(String::new());
        lines.extend(result_lines);
    }
    lines
}

fn snapshot_sections(
    remaining: &[&str],
    metrics_index: Option<usize>,
    display: SnapshotDisplay,
) -> (Vec<String>, Vec<String>) {
    let mut summary = Vec::new();
    let mut result = Vec::new();
    let mut in_result = false;
    let mut status_continuation = false;

    for (index, line) in remaining.iter().copied().enumerate() {
        if Some(index) == metrics_index || line.starts_with("attach: ") {
            status_continuation = false;
            continue;
        }
        if matches!(display, SnapshotDisplay::Completion) && !in_result && line.is_empty() {
            in_result = true;
            continue;
        }
        if in_result {
            result.push(line.to_string());
            continue;
        }

        let formatted = if let Some(activity) = line.strip_prefix("activity: ") {
            status_continuation = true;
            format!("  {activity}")
        } else if let Some(latest) = line.strip_prefix("latest: ") {
            status_continuation = true;
            format!("  {latest}")
        } else if line == "completion result uses automatic delivery" {
            status_continuation = false;
            "  result will arrive automatically".into()
        } else if is_snapshot_protocol_line(line) {
            status_continuation = false;
            line.to_string()
        } else if matches!(display, SnapshotDisplay::Status) && status_continuation {
            if line.is_empty() {
                String::new()
            } else {
                format!("  {line}")
            }
        } else {
            line.to_string()
        };
        summary.push(formatted);
    }
    (summary, result)
}

fn is_snapshot_protocol_line(line: &str) -> bool {
    line.starts_with("error: ")
        || line.starts_with("attachment error: ")
        || line == "this delegated task did not complete; treat its work as unverified"
}

fn turns_from_metrics(metrics: &str) -> Option<String> {
    let turns = metrics.split("turns: ").nth(1)?.split(" ·").next()?;
    Some(if turns == "1" {
        "1 turn".into()
    } else {
        format!("{turns} turns")
    })
}

fn elapsed_from_metrics(metrics: &str) -> Option<&str> {
    metrics.strip_prefix("elapsed: ")?.split(" ·").next()
}

fn tokens_from_metrics(metrics: &str) -> Option<&str> {
    metrics.split("tokens: ").nth(1)
}

fn state_glyph(state: &str) -> &'static str {
    match state {
        "starting" | "running" => "",
        "ok" => "",
        "error" => "",
        "stopped" => "",
        _ => "",
    }
}

fn display_state(state: &str) -> &str {
    match state {
        "ok" => "completed",
        "error" => "failed",
        other => other,
    }
}

fn run_id_from_agent_line(line: &str) -> Option<&str> {
    strip_run_prefix(line)?.split_whitespace().next()
}

fn strip_run_prefix(line: &str) -> Option<&str> {
    line.strip_prefix("agent ")
        .or_else(|| line.strip_prefix("subagent "))
}

fn agent_identity(arguments: &serde_json::Value) -> Option<&str> {
    string_value(arguments, "agent_id").or_else(|| string_value(arguments, "preset"))
}

fn string_argument<'a>(view: &'a ToolView, key: &str) -> Option<&'a str> {
    string_value(&view.arguments, key)
}

fn string_value<'a>(arguments: &'a serde_json::Value, key: &str) -> Option<&'a str> {
    arguments.get(key)?.as_str()
}

fn bool_value(arguments: &serde_json::Value, key: &str) -> bool {
    arguments
        .get(key)
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(false)
}

fn push_content(lines: &mut Vec<String>, content: &str) {
    if !content.trim().is_empty() {
        lines.push(String::new());
        lines.push(content.to_string());
    }
}