rho-coding-agent 2.26.0

A fast Rust agent harness with a small footprint and opinionated defaults
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
//! Rho host input requests as ACP form elicitation (`elicitation/create`).
//!
//! Each question becomes one property keyed by its ID. On hosts that draw
//! the standard schema, a choice question that also accepts other answers
//! gets a free-text companion, single selects carry titled `oneOf` options,
//! and multiple selects are string arrays. T3 Code reads only a top-level
//! `enum` and lets every question take free text, so it gets one string
//! property per question instead (see [`FormDialect::T3Code`]). The
//! response's `accept`, `decline`, and `cancel` become answers,
//! [`HostInputRefusal::Declined`], and [`HostInputRefusal::Dismissed`].

use std::collections::BTreeMap;

use agent_client_protocol::schema::v1::{
    BooleanPropertySchema, CreateElicitationRequest, CreateElicitationResponse, ElicitationAction,
    ElicitationContentValue, ElicitationFormMode, ElicitationSchema, ElicitationSessionScope,
    EnumOption, MultiSelectPropertySchema, SessionId, StringPropertySchema, ToolCallId,
};
use rho_sdk::{
    DefaultSelection, HostChoice, HostInputRefusal, HostInputRequest, HostInputResponse,
    HostQuestion, SelectionMode,
};

use super::host_updates::FormDialect;

/// Suffix of the free-text property beside a choice question that also
/// accepts its own answer, on hosts that draw the standard schema.
const OTHER_SUFFIX: &str = ".other";

/// The form control a question maps to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Field {
    /// Only an "other" answer: the questionnaire tool's and MCP's encoding
    /// of a text field.
    Text,
    /// A yes/no single select, drawn as a checkbox.
    Confirm,
    Select(SelectionMode),
    /// A select plus a free-text answer of the user's own.
    SelectOrOther(SelectionMode),
}

fn field(question: &HostQuestion) -> Field {
    let selection = question.selection();
    match question.choices() {
        [only] if question.permits_other() && only.value() == "other" => Field::Text,
        [yes, no]
            if selection == SelectionMode::One
                && !question.permits_other()
                && yes.value().eq_ignore_ascii_case("yes")
                && no.value().eq_ignore_ascii_case("no") =>
        {
            Field::Confirm
        }
        _ if question.permits_other() => Field::SelectOrOther(selection),
        _ => Field::Select(selection),
    }
}

/// The key of `question`'s free-text companion, unique among the request's
/// question IDs (MCP property names may contain `.`).
fn other_key(request: &HostInputRequest, question: &HostQuestion) -> String {
    let mut key = format!("{}{OTHER_SUFFIX}", question.id());
    while request.questions().iter().any(|other| other.id() == key) {
        key.push('_');
    }
    key
}

/// The form for `request`. `call_id` ties it to the tool call that asked,
/// so the host can draw it on that call's card.
pub(super) fn elicitation_request(
    request: &HostInputRequest,
    session_id: &SessionId,
    call_id: Option<&rho_sdk::ToolCallId>,
    dialect: FormDialect,
) -> CreateElicitationRequest {
    let mut schema = ElicitationSchema::new();
    for question in request.questions() {
        schema = match dialect {
            FormDialect::Standard => add_question(schema, request, question),
            FormDialect::T3Code => add_t3_question(schema, question),
        };
    }
    let scope = ElicitationSessionScope::new(session_id.clone())
        .tool_call_id(call_id.map(|id| ToolCallId::new(id.as_str())));
    let message = match request.title() {
        "" => "Rho needs your input",
        title => title,
    };
    CreateElicitationRequest::new(ElicitationFormMode::new(scope, schema), message)
}

/// A property's title and description. T3 Code shows the title as the
/// question's label and the description as its text, so the full prompt
/// goes in the description when a short header takes the title.
fn title_and_description(question: &HostQuestion) -> (String, Option<String>) {
    match question.header_text() {
        Some(header) => (
            header.to_owned(),
            Some(match question.help_text() {
                Some(help) => format!("{}\n\n{help}", question.prompt()),
                None => question.prompt().to_owned(),
            }),
        ),
        None => (
            question.prompt().to_owned(),
            question.help_text().map(str::to_owned),
        ),
    }
}

fn checkbox(
    question: &HostQuestion,
    title: String,
    description: Option<String>,
    defaults: &[String],
) -> BooleanPropertySchema {
    let yes = question.choices()[0].value();
    let checked = defaults
        .first()
        .map(|value| value.eq_ignore_ascii_case(yes) || value == "true");
    BooleanPropertySchema::new()
        .title(title)
        .description(description)
        .default_value(checked)
}

fn add_question(
    schema: ElicitationSchema,
    request: &HostInputRequest,
    question: &HostQuestion,
) -> ElicitationSchema {
    let id = question.id();
    let (title, description) = title_and_description(question);
    let defaults = selected_defaults(question);
    let required = question.is_required();
    match field(question) {
        Field::Text => {
            let text = StringPropertySchema::new()
                .title(title)
                .description(description)
                .default_value(defaults.into_iter().next());
            schema.property(id, text, required)
        }
        Field::Confirm => schema.property(
            id,
            checkbox(question, title, description, &defaults),
            required,
        ),
        Field::Select(selection) => schema.property(
            id,
            select(question, selection, title, description, defaults),
            required,
        ),
        // Either property may carry the answer, so neither is required on
        // the form; answer validation enforces the question's own rule.
        Field::SelectOrOther(selection) => {
            let (known, other): (Vec<_>, Vec<_>) = defaults
                .into_iter()
                .partition(|value| question.choices().iter().any(|c| c.value() == value));
            let other = StringPropertySchema::new()
                .title(format!("{title} (other)"))
                .description("Your own answer instead of a listed choice")
                .default_value((!other.is_empty()).then(|| other.join(", ")));
            schema
                .property(
                    id,
                    select(question, selection, title, description, known),
                    false,
                )
                .property(other_key(request, question), other, false)
        }
    }
}

/// T3 Code's shape: one string property per question whose `enum` lists
/// the choice labels it shows. Its free text replaces the `.other`
/// companion, and a multiple choice is typed as a comma-separated list.
fn add_t3_question(schema: ElicitationSchema, question: &HostQuestion) -> ElicitationSchema {
    let id = question.id();
    let (title, description) = title_and_description(question);
    let required = question.is_required();
    let selection = match field(question) {
        Field::Text => {
            let text = StringPropertySchema::new()
                .title(title)
                .description(description);
            return schema.property(id, text, required);
        }
        Field::Confirm => {
            return schema.property(id, checkbox(question, title, description, &[]), required);
        }
        Field::Select(selection) | Field::SelectOrOther(selection) => selection,
    };
    let hint = match (selection, Separator::for_question(question)) {
        (SelectionMode::Many, Some(separator)) => Some(format!(
            "Pick one or more; separate several with {}.",
            separator.name()
        )),
        (SelectionMode::Many, None) => Some("Pick one.".to_owned()),
        _ => None,
    };
    let description = match (description, hint) {
        (Some(text), Some(hint)) => Some(format!("{text}\n\n{hint}")),
        (text, hint) => text.or(hint),
    };
    let labels = question
        .choices()
        .iter()
        .map(|choice| choice.label().to_owned())
        .collect::<Vec<_>>();
    let select = StringPropertySchema::new()
        .title(title)
        .description(description)
        .enum_values(labels);
    schema.property(id, select, required)
}

fn select(
    question: &HostQuestion,
    selection: SelectionMode,
    title: String,
    description: Option<String>,
    defaults: Vec<String>,
) -> agent_client_protocol::schema::v1::ElicitationPropertySchema {
    let options = question.choices().iter().map(option).collect::<Vec<_>>();
    if selection == SelectionMode::Many {
        return MultiSelectPropertySchema::titled(options)
            .title(title)
            .description(description)
            .default_value((!defaults.is_empty()).then_some(defaults))
            .into();
    }
    let values = question
        .choices()
        .iter()
        .map(|choice| choice.value().to_owned())
        .collect::<Vec<_>>();
    StringPropertySchema::new()
        .title(title)
        .description(description)
        .enum_values(values)
        .one_of(options)
        .default_value(defaults.into_iter().next())
        .into()
}

fn option(choice: &HostChoice) -> EnumOption {
    EnumOption::new(choice.value(), choice.label())
        .description(choice.description_text().map(str::to_owned))
}

/// Defaults the question pre-selects. A focused default only highlights a
/// choice, which a form cannot express, so it is left unset.
fn selected_defaults(question: &HostQuestion) -> Vec<String> {
    if question.default_selection_mode() != DefaultSelection::Selected {
        return Vec::new();
    }
    let values = match question.default_value_ref() {
        Some(serde_json::Value::Array(values)) => values.iter().collect(),
        Some(value) => vec![value],
        None => Vec::new(),
    };
    values
        .into_iter()
        .filter_map(|value| match value {
            serde_json::Value::String(value) if !value.is_empty() => Some(value.clone()),
            serde_json::Value::Bool(value) => Some(value.to_string()),
            serde_json::Value::Number(value) => Some(value.to_string()),
            _ => None,
        })
        // A default names a choice by value; one that names it by label
        // still means that choice.
        .map(|value| {
            let choices = question.choices();
            choices
                .iter()
                .find(|choice| choice.value() == value)
                .or_else(|| find_choice(question, &value))
                .map_or(value, |choice| choice.value().to_owned())
        })
        .collect()
}

/// The run's answer to `request` from the host's response. Content that does
/// not answer the request counts as declined: the user submitted something,
/// but not an answer Rho can use.
pub(super) fn host_answer(
    request: &HostInputRequest,
    response: CreateElicitationResponse,
    dialect: FormDialect,
) -> Result<HostInputResponse, HostInputRefusal> {
    let content = match response.action {
        ElicitationAction::Accept(accept) => accept.content.unwrap_or_default(),
        ElicitationAction::Cancel => return Err(HostInputRefusal::Dismissed),
        ElicitationAction::Decline => return Err(HostInputRefusal::Declined),
        // Unknown actions are not answers; treat them like a decline.
        _ => return Err(HostInputRefusal::Declined),
    };
    let answers = answers(request, &content, dialect);
    match request.validate(&answers) {
        Ok(()) => Ok(answers),
        Err(error) => {
            tracing::warn!(%error, "ACP host accepted a form without a valid answer");
            Err(HostInputRefusal::Declined)
        }
    }
}

fn answers(
    request: &HostInputRequest,
    content: &BTreeMap<String, ElicitationContentValue>,
    dialect: FormDialect,
) -> HostInputResponse {
    let mut response = HostInputResponse::new();
    for question in request.questions() {
        let id = question.id();
        let values = content.get(id).map(strings).unwrap_or_default();
        let values = match (dialect, field(question)) {
            (_, Field::Text) => values,
            // A checkbox answers with a boolean, or with its text when the
            // host draws it as a true/false choice (T3 Code).
            (_, Field::Confirm) => {
                let [yes, no] = question.choices() else {
                    unreachable!("a confirm question has exactly two choices")
                };
                values
                    .into_iter()
                    .map(|value| match value.to_ascii_lowercase().as_str() {
                        "true" => yes.value().to_owned(),
                        "false" => no.value().to_owned(),
                        _ => choice_value(question, value),
                    })
                    .collect()
            }
            (FormDialect::Standard, Field::Select(_)) => values,
            // A typed answer of the user's own replaces a single choice the
            // host could not clear, and joins a multiple choice.
            (FormDialect::Standard, Field::SelectOrOther(selection)) => {
                let other = content
                    .get(&other_key(request, question))
                    .map(strings)
                    .unwrap_or_default();
                match selection {
                    SelectionMode::Many => dedup(values.into_iter().chain(other)),
                    _ if !other.is_empty() => other,
                    _ => values,
                }
            }
            (FormDialect::T3Code, Field::Select(selection) | Field::SelectOrOther(selection)) => {
                t3_choices(question, selection, values)
            }
        };
        if !values.is_empty() {
            response = response.answer(id, values);
        }
    }
    response
}

/// What a T3 Code multiple choice is typed with: a character no choice
/// label contains, so a typed list splits back into exactly the choices
/// the user listed. Common punctuation comes first; past it, the first free
/// visible character from Unicode's arrow-to-symbol blocks. Labels that use
/// every one leave none, and the question then takes a single typed choice.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Separator(char);

impl Separator {
    fn for_question(question: &HostQuestion) -> Option<Self> {
        let labels = question.choices().iter().map(HostChoice::label);
        let free = |c: &char| labels.clone().all(|label| !label.contains(*c));
        [',', ';', '|', '/', '+', '•']
            .into_iter()
            .chain('\u{2190}'..='\u{2BFF}')
            .find(free)
            .map(Self)
    }

    /// The separator as the form's hint names it.
    fn name(self) -> String {
        match self.0 {
            ',' => "commas".to_owned(),
            ';' => "semicolons".to_owned(),
            c => format!("\"{c}\""),
        }
    }
}

/// T3 Code answers with a chosen label or typed text; a multiple choice
/// types several, split by the question's [`Separator`] when it has one.
fn t3_choices(
    question: &HostQuestion,
    selection: SelectionMode,
    values: Vec<String>,
) -> Vec<String> {
    let separator = Separator::for_question(question);
    let pieces = values
        .into_iter()
        .flat_map(|value| match (selection, separator) {
            (SelectionMode::Many, Some(Separator(separator))) => value
                .split(separator)
                .map(|piece| piece.trim().to_owned())
                .filter(|piece| !piece.is_empty())
                .collect(),
            _ => vec![value],
        });
    dedup(pieces.map(|value| choice_value(question, value)))
}

/// The choice `text` names: its exact displayed label first, since T3 Code
/// answers with labels, then its value, then its label in any case.
fn find_choice<'a>(question: &'a HostQuestion, text: &str) -> Option<&'a HostChoice> {
    let choices = question.choices();
    choices
        .iter()
        .find(|choice| choice.label() == text)
        .or_else(|| choices.iter().find(|choice| choice.value() == text))
        .or_else(|| {
            choices
                .iter()
                .find(|choice| choice.label().eq_ignore_ascii_case(text))
        })
}

/// The value of the choice `text` names by value or label, or `text` itself
/// as the user's own answer.
fn choice_value(question: &HostQuestion, text: String) -> String {
    find_choice(question, &text).map_or(text, |choice| choice.value().to_owned())
}

fn dedup(values: impl IntoIterator<Item = String>) -> Vec<String> {
    let mut unique = Vec::new();
    for value in values {
        if !unique.contains(&value) {
            unique.push(value);
        }
    }
    unique
}

/// A content value as answers; blank text is no answer.
fn strings(value: &ElicitationContentValue) -> Vec<String> {
    let values = match value {
        ElicitationContentValue::String(value) => vec![value.trim().to_owned()],
        ElicitationContentValue::StringArray(values) => values.clone(),
        ElicitationContentValue::Integer(value) => vec![value.to_string()],
        ElicitationContentValue::Number(value) => vec![value.to_string()],
        ElicitationContentValue::Boolean(value) => vec![value.to_string()],
        _ => Vec::new(),
    };
    values
        .into_iter()
        .filter(|value| !value.is_empty())
        .collect()
}

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