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
//! Rho's v1 `session/update` notifications in ACP v2 form.
//!
//! The session host emits v1 updates; a v2 connection rewrites each one here
//! before it reaches the wire. Shapes that only gained optional fields or open
//! enums in v2 cross through [`bridge`]; everything v2 redesigned is mapped
//! field by field:
//!
//! - `tool_call` becomes the first `tool_call_update` for its ID, which v2
//!   treats as the creating upsert.
//! - A v1 update field that is absent means "unchanged", which is v2's
//!   undefined, never its `null` (clear).
//! - A location's `line` counts from 1 in v2, where Rho's v1 lines count
//!   from 0.
//! - `plan` becomes `plan_update` for Rho's single todo plan, and
//!   `plan_removed` once the todo list is cleared.
//! - `current_mode_update` is dropped: the mode is a config option in v2, and
//!   every mode change also refreshes `config_option_update`.
//! - A v1 diff of complete file texts becomes structured `changes` plus a
//!   `git_patch`. A move, which v1 shows as the source's deletion and a new
//!   file, becomes one `move` change.

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

use agent_client_protocol::Error as AcpError;
use agent_client_protocol::{schema::MaybeUndefined, v1::schema as v1, v2::schema as v2};
use rho_protocol::SubagentRef;

use super::{bridge, git_patch::FileContents, subagents::child_id};
use crate::app::acp::markers;

/// The ID of Rho's todo list plan.
const TODO_PLAN_ID: &str = "rho-todos";

/// The ID of the plan a plan-mode session proposes (`exit_plan_mode`).
const PROPOSED_PLAN_ID: &str = "rho-plan";

/// The v2 notification for `notification`, or `None` when v2 has no
/// counterpart.
pub(super) fn notification(
    notification: v1::SessionNotification,
) -> Result<Option<v2::UpdateSessionNotification>, AcpError> {
    let v1::SessionNotification {
        session_id,
        update,
        meta,
        ..
    } = notification;
    let Some(update) = session_update(update)? else {
        return Ok(None);
    };
    Ok(Some(
        v2::UpdateSessionNotification::new(bridge::<_, v2::SessionId>(&session_id)?, update)
            .meta(meta),
    ))
}

fn session_update(update: v1::SessionUpdate) -> Result<Option<v2::SessionUpdate>, AcpError> {
    use v1::SessionUpdate as V1;
    use v2::SessionUpdate as V2;
    Ok(Some(match update {
        V1::UserMessageChunk(chunk) => V2::UserMessageChunk(content_chunk(chunk)?),
        V1::AgentMessageChunk(chunk) => V2::AgentMessageChunk(content_chunk(chunk)?),
        V1::AgentThoughtChunk(chunk) => V2::AgentThoughtChunk(content_chunk(chunk)?),
        V1::ToolCall(call) => V2::ToolCallUpdate(created_tool_call(call)?),
        V1::ToolCallUpdate(update) => V2::ToolCallUpdate(tool_call_update(update)?),
        // The todo list was cleared; v2 removes the plan rather than
        // emptying it.
        V1::Plan(plan) if plan.entries.is_empty() => {
            V2::PlanRemoved(v2::PlanRemoved::new(TODO_PLAN_ID).meta(plan.meta))
        }
        V1::Plan(plan) => V2::PlanUpdate(
            v2::PlanUpdate::new(v2::PlanUpdateContent::Items(v2::PlanItems::new(
                TODO_PLAN_ID,
                bridge(&plan.entries)?,
            )))
            .meta(plan.meta),
        ),
        V1::AvailableCommandsUpdate(update) => V2::AvailableCommandsUpdate(
            v2::AvailableCommandsUpdate::new(available_commands(update.available_commands)?)
                .meta(update.meta),
        ),
        V1::CurrentModeUpdate(_) => return Ok(None),
        V1::ConfigOptionUpdate(update) => V2::ConfigOptionUpdate(
            v2::ConfigOptionUpdate::new(config_options(update.config_options)?).meta(update.meta),
        ),
        V1::SessionInfoUpdate(update) => V2::SessionInfoUpdate(bridge(&update)?),
        V1::UsageUpdate(update) => V2::UsageUpdate(bridge(&update)?),
        V1::Notice(notice) => V2::Notice(bridge(&notice)?),
        V1::CompactionUpdate(update) => V2::CompactionUpdate(bridge(&update)?),
        V1::CompactionSummaryChunk(chunk) => V2::CompactionSummaryChunk(bridge(&chunk)?),
        _ => return Err(AcpError::internal_error().data("no ACP v2 form for this session update")),
    }))
}

/// The plan a plan-mode session proposes for approval, as markdown. A later
/// proposal replaces it.
pub(super) fn proposed_plan(markdown: &str) -> v2::SessionUpdate {
    v2::SessionUpdate::PlanUpdate(v2::PlanUpdate::new(v2::PlanUpdateContent::Markdown(
        v2::PlanMarkdown::new(PROPOSED_PLAN_ID, markdown),
    )))
}

/// Removes the proposed plan, which is no longer proposed.
pub(super) fn withdrawn_plan() -> v2::SessionUpdate {
    v2::SessionUpdate::PlanRemoved(v2::PlanRemoved::new(PROPOSED_PLAN_ID))
}

/// The message a chunk belongs to.
pub(super) fn chunk_message_id(
    notification: &v2::UpdateSessionNotification,
) -> Option<&v2::MessageId> {
    use v2::SessionUpdate as V2;
    match &notification.update {
        V2::UserMessageChunk(chunk)
        | V2::AgentMessageChunk(chunk)
        | V2::AgentThoughtChunk(chunk) => Some(&chunk.message_id),
        _ => None,
    }
}

/// The children Rho's v1 `update` links, which v2 shows as `session`
/// content items: the host must have been told of each first, and one
/// with a session of its own can be relayed from the link alone.
pub(super) fn linked_children(update: &v1::SessionUpdate) -> Vec<SubagentRef> {
    let contents: &[v1::ToolCallContent] = match update {
        v1::SessionUpdate::ToolCall(call) => &call.content,
        v1::SessionUpdate::ToolCallUpdate(call) => call.fields.content.as_deref().unwrap_or(&[]),
        _ => &[],
    };
    contents
        .iter()
        .filter_map(|content| match content {
            v1::ToolCallContent::Content(content) => markers::subagent_in(content.meta.as_ref()),
            _ => None,
        })
        .collect()
}

/// For a message chunk, the update that resets its message to no content.
/// v2 requires one before a replayed message's chunks, since a host appends
/// chunks to content it already holds.
pub(super) fn reset(
    notification: &v2::UpdateSessionNotification,
) -> Option<v2::UpdateSessionNotification> {
    use v2::SessionUpdate as V2;
    let update = match &notification.update {
        V2::UserMessageChunk(chunk) => {
            V2::UserMessage(v2::UserMessage::new(chunk.message_id.clone()).content(Vec::new()))
        }
        V2::AgentMessageChunk(chunk) => {
            V2::AgentMessage(v2::AgentMessage::new(chunk.message_id.clone()).content(Vec::new()))
        }
        V2::AgentThoughtChunk(chunk) => {
            V2::AgentThought(v2::AgentThought::new(chunk.message_id.clone()).content(Vec::new()))
        }
        _ => return None,
    };
    Some(
        v2::UpdateSessionNotification::new(notification.session_id.clone(), update)
            .meta(notification.meta.clone()),
    )
}

/// Rho names every message chunk it sends; v2 requires the name.
fn content_chunk(chunk: v1::ContentChunk) -> Result<v2::ContentChunk, AcpError> {
    let Some(message_id) = chunk.message_id else {
        return Err(AcpError::internal_error().data("ACP v2 message chunk without a message id"));
    };
    Ok(v2::ContentChunk::new(
        bridge(&chunk.content)?,
        bridge::<_, v2::MessageId>(&message_id)?,
    )
    .meta(chunk.meta))
}

/// A v1 `tool_call` states every field, so each one is set on the creating
/// upsert.
fn created_tool_call(call: v1::ToolCall) -> Result<v2::ToolCallUpdate, AcpError> {
    let v1::ToolCall {
        tool_call_id,
        title,
        name,
        kind,
        status,
        content,
        locations,
        raw_input,
        raw_output,
        meta,
        ..
    } = call;
    let fields = v1::ToolCallUpdateFields::new()
        .title(title)
        .name(name)
        .kind(kind)
        .status(status)
        .content(content)
        .locations(locations)
        .raw_input(raw_input)
        .raw_output(raw_output);
    tool_call_update(v1::ToolCallUpdate::new(tool_call_id, fields).meta(meta))
}

pub(super) fn tool_call_update(update: v1::ToolCallUpdate) -> Result<v2::ToolCallUpdate, AcpError> {
    let v1::ToolCallUpdate {
        tool_call_id,
        fields,
        mut meta,
        ..
    } = update;
    let cancelled = markers::take_flag(&mut meta, markers::TOOL_CANCELLED);
    let v1::ToolCallUpdateFields {
        kind,
        status,
        title,
        name,
        content,
        locations,
        raw_input,
        raw_output,
        ..
    } = fields;
    let content = content.map(tool_call_contents).transpose()?;
    Ok(
        v2::ToolCallUpdate::new(bridge::<_, v2::ToolCallId>(&tool_call_id)?)
            .title(unchanged_if_absent(title))
            .name(unchanged_if_absent(name))
            .kind(unchanged_if_absent(
                kind.map(|kind| bridge(&kind)).transpose()?,
            ))
            .status(unchanged_if_absent(match status {
                Some(_) if cancelled => Some(v2::ToolCallStatus::Cancelled),
                status => status.map(|status| bridge(&status)).transpose()?,
            }))
            .content(unchanged_if_absent(content))
            .locations(unchanged_if_absent(
                locations.map(|locations| locations.into_iter().map(location).collect()),
            ))
            .raw_input(unchanged_if_absent(raw_input))
            .raw_output(unchanged_if_absent(raw_output))
            .meta(unchanged_if_absent(meta)),
    )
}

/// Both versions count `line` from 1, so the v1 row carries over unchanged.
fn location(location: v1::ToolCallLocation) -> v2::ToolCallLocation {
    v2::ToolCallLocation::new(location.path)
        .line(location.line)
        .meta(location.meta)
}

/// v1 leaves a field out to keep it; v2 does too, while `null` clears it.
fn unchanged_if_absent<T>(value: Option<T>) -> MaybeUndefined<T> {
    match value {
        Some(value) => MaybeUndefined::Value(value),
        None => MaybeUndefined::Undefined,
    }
}

/// A tool call's content in v2 form. A move's source deletion is left out:
/// the move's own change covers it.
fn tool_call_contents(
    content: Vec<v1::ToolCallContent>,
) -> Result<Vec<v2::ToolCallContent>, AcpError> {
    let pieces: Vec<Piece> = content.into_iter().map(Piece::of).collect();
    // NEXT_MAJOR(rho-protocol): drop the pairing once the wire's diff names
    // its source and the source's deletion is no longer reported beside it.
    let mut deletions: HashMap<&Path, (usize, &MarkedDiff)> = pieces
        .iter()
        .enumerate()
        .filter_map(|(index, piece)| match piece {
            Piece::Diff(diff) if diff.deleted => Some((diff.diff.path.as_path(), (index, diff))),
            _ => None,
        })
        .collect();
    let sources: Vec<_> = pieces
        .iter()
        .map(|piece| match piece {
            Piece::Diff(MarkedDiff {
                moved_from: Some(from),
                ..
            }) => deletions.remove(from.as_path()),
            _ => None,
        })
        .collect();
    let covered: HashSet<usize> = sources.iter().flatten().map(|&(index, _)| index).collect();
    pieces
        .iter()
        .zip(sources)
        .enumerate()
        .filter(|(index, _)| !covered.contains(index))
        .map(|(_, (piece, source))| match piece {
            Piece::Diff(diff) => Ok(v2::ToolCallContent::from(file_diff(
                diff,
                source.map(|(_, source)| source),
            ))),
            Piece::Session(child) => Ok(v2::ToolCallContent::Session(v2::SessionReference::new(
                child.clone(),
            ))),
            Piece::Other(content) => other_content(content),
        })
        .collect()
}

/// A piece of a v1 call's content, read for Rho's markers.
enum Piece {
    Diff(MarkedDiff),
    /// The child session of the subagent an `agent` call started.
    Session(v2::SessionId),
    Other(Box<v1::ToolCallContent>),
}

impl Piece {
    fn of(content: v1::ToolCallContent) -> Self {
        match content {
            v1::ToolCallContent::Diff(mut diff) => {
                let deleted = markers::take_flag(&mut diff.meta, markers::DELETED_FILE);
                let moved_from = markers::take_path(&mut diff.meta, markers::MOVED_FROM);
                Self::Diff(MarkedDiff {
                    diff,
                    deleted,
                    moved_from,
                })
            }
            v1::ToolCallContent::Content(mut content) => {
                match markers::take_subagent(&mut content.meta) {
                    Some(child) => Self::Session(v2::SessionId::new(child_id(
                        &child.run,
                        child.session.as_ref(),
                    ))),
                    None => Self::Other(Box::new(v1::ToolCallContent::Content(content))),
                }
            }
            other => Self::Other(Box::new(other)),
        }
    }
}

/// A v1 diff, less the markers Rho put in its `_meta`: v1 shows a deletion
/// as an emptied file, and a move as the source's deletion and a new file.
struct MarkedDiff {
    diff: v1::Diff,
    deleted: bool,
    moved_from: Option<PathBuf>,
}

fn other_content(content: &v1::ToolCallContent) -> Result<v2::ToolCallContent, AcpError> {
    Ok(match content {
        v1::ToolCallContent::Content(content) => v2::ToolCallContent::Content(Box::new(
            v2::Content::new(bridge::<_, v2::ContentBlock>(&content.content)?)
                .meta(content.meta.clone()),
        )),
        // A background process the call started: its display-only terminal.
        v1::ToolCallContent::Terminal(terminal) => v2::ToolCallContent::Terminal(bridge(terminal)?),
        _ => return Err(AcpError::internal_error().data("no ACP v2 form for this tool content")),
    })
}

/// A v1 diff holds the complete old and new texts of one file, so the change
/// and its patch can be rebuilt. `source` is the deletion of the file a move
/// came from, whose text is the move's old text.
fn file_diff(diff: &MarkedDiff, source: Option<&MarkedDiff>) -> v2::Diff {
    let path = diff.diff.path.as_path();
    let new = diff.diff.new_text.as_str();
    let (change, contents) = match (source, &diff.diff.old_text, diff.deleted) {
        (Some(source), _, _) => {
            let from: &Path = &source.diff.path;
            (
                v2::DiffChange::move_file(from.to_path_buf(), path.to_path_buf()),
                FileContents::Moved {
                    from,
                    old: source.diff.old_text.as_deref().unwrap_or_default(),
                    new,
                },
            )
        }
        (None, None, _) => (
            v2::DiffChange::add(path.to_path_buf()),
            FileContents::Created(new),
        ),
        (None, Some(old), true) => (
            v2::DiffChange::delete(path.to_path_buf()),
            FileContents::Deleted(old),
        ),
        (None, Some(old), false) => (
            v2::DiffChange::modify(path.to_path_buf()),
            FileContents::Modified { old, new },
        ),
    };
    let patch = super::git_patch::file_patch(path, contents);
    v2::Diff::new(vec![change.file_type(v2::DiffFileType::Text)])
        .with_patch(patch.map(v2::DiffPatch::new))
        .meta(diff.diff.meta.clone())
}

/// v2 tags free-text command input as `type: "text"`.
pub(super) fn available_commands(
    commands: Vec<v1::AvailableCommand>,
) -> Result<Vec<v2::AvailableCommand>, AcpError> {
    commands
        .into_iter()
        .map(|command| {
            let input = match command.input {
                Some(v1::AvailableCommandInput::Unstructured(input)) => {
                    Some(v2::AvailableCommandInput::Text(
                        v2::TextCommandInput::new(input.hint).meta(input.meta),
                    ))
                }
                None => None,
                Some(_) => {
                    return Err(AcpError::internal_error().data("no ACP v2 form for command input"))
                }
            };
            Ok(v2::AvailableCommand::Command(
                v2::Command::new(command.name, command.description)
                    .input(input)
                    .meta(command.meta),
            ))
        })
        .collect()
}

/// v2 renames a config option's `id` to `configId` and a select group's
/// `group` to `groupId`.
pub(super) fn config_options(
    options: Vec<v1::SessionConfigOption>,
) -> Result<Vec<v2::SessionConfigOption>, AcpError> {
    options.into_iter().map(config_option).collect()
}

fn config_option(option: v1::SessionConfigOption) -> Result<v2::SessionConfigOption, AcpError> {
    let kind = match option.kind {
        v1::SessionConfigKind::Select(select) => {
            let options = match select.options {
                v1::SessionConfigSelectOptions::Ungrouped(options) => {
                    v2::SessionConfigSelectOptions::Ungrouped(bridge(&options)?)
                }
                v1::SessionConfigSelectOptions::Grouped(groups) => {
                    v2::SessionConfigSelectOptions::Grouped(
                        groups
                            .into_iter()
                            .map(|group| {
                                Ok(v2::SessionConfigSelectGroup::new(
                                    group.group.0.clone(),
                                    group.name,
                                    bridge(&group.options)?,
                                )
                                .meta(group.meta))
                            })
                            .collect::<Result<_, AcpError>>()?,
                    )
                }
                _ => {
                    return Err(AcpError::internal_error().data("no ACP v2 form for these options"))
                }
            };
            v2::SessionConfigKind::Select(v2::SessionConfigSelect::new(
                select.current_value.0.clone(),
                options,
            ))
        }
        v1::SessionConfigKind::Boolean(boolean) => {
            v2::SessionConfigKind::Boolean(v2::SessionConfigBoolean::new(boolean.current_value))
        }
        _ => return Err(AcpError::internal_error().data("no ACP v2 form for this config option")),
    };
    Ok(
        v2::SessionConfigOption::new(option.id.0.clone(), option.name, kind)
            .description(option.description)
            .category(
                option
                    .category
                    .map(|category| bridge(&category))
                    .transpose()?,
            )
            .meta(option.meta),
    )
}

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