rho-coding-agent 2.9.1

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
//! SDK implementations for app-owned skill and host-input features.

use std::{path::Path, sync::Arc};

use crate::app::subagent_messaging::NoticeDelivery;

use rho_sdk::{
    tool::{
        OperationKind, PreparedToolInvocation, Tool as SdkTool, ToolContext as SdkToolContext,
        ToolError as SdkToolError, ToolErrorKind, ToolFuture, ToolInvocation, ToolInvocationSource,
        ToolMetadata, ToolOutput, ToolPreparationContext, ToolPrepareFuture, ToolResource,
        ToolResourceAccess, ToolSecurity,
    },
    CapabilityKind, CapabilityRequest, CapabilitySource, HostChoice, HostInputRequest,
    HostQuestion, SelectionMode,
};
use rho_tools::{
    sdk_support::required_string,
    tool::{truncate, Tool as _},
};

pub(super) fn skill_bundle(max_output_bytes: usize) -> super::sdk_registry::StaticToolBundle {
    super::sdk_registry::StaticToolBundle::new(vec![Arc::new(SdkSkillTool::new(max_output_bytes))])
}

pub(super) fn questionnaire_bundle() -> super::sdk_registry::StaticToolBundle {
    super::sdk_registry::StaticToolBundle::new(vec![Arc::new(QuestionnaireTool)])
}

pub(crate) fn message_parent_bundle(
    poster: Arc<dyn crate::app::subagent_messaging::NoticePoster>,
) -> super::sdk_registry::StaticToolBundle {
    super::sdk_registry::StaticToolBundle::new(vec![
        Arc::new(MessageParentTool {
            poster: Arc::clone(&poster),
            delivery: NoticeDelivery::NextTurn,
        }),
        Arc::new(MessageParentTool {
            poster,
            delivery: NoticeDelivery::ParentActionRequired,
        }),
    ])
}

impl SdkSkillTool {
    pub(super) fn new(max_output_bytes: usize) -> Self {
        Self { max_output_bytes }
    }

    /// Shared preparation for filesystem-backed skills: loose `File` skills
    /// and plugin skills. The workspace grants only the skill directory, so
    /// resource access stays inside the skill's permitted root.
    fn prepare_fs_skill(
        &self,
        name: &str,
        source_display: String,
        requested: &Path,
        skill_directory: &Path,
        context: &ToolPreparationContext,
    ) -> Result<PreparedToolInvocation<'_>, SdkToolError> {
        let workspace = preparation_workspace(context)?;
        let skill_workspace = workspace
            .clone()
            .with_granted_root(skill_directory)
            .map_err(|error| SdkToolError::new(ToolErrorKind::Execution, error.to_string()))?;
        let resolved = skill_workspace
            .resolve_for_read(requested)
            .map_err(|error| SdkToolError::new(ToolErrorKind::Execution, error.to_string()))?;
        let capability = CapabilityRequest::skill(
            name,
            Some(resolved.path().to_path_buf()),
            CapabilitySource::built_in_tool("skill"),
        );
        let access = ToolResourceAccess::shared(ToolResource::workspace_path(resolved.path()));
        let directory_display = crate::paths::display(skill_directory);
        let max_output_bytes = self.max_output_bytes;
        let name = name.to_string();
        let metadata = ToolMetadata::new().operation(OperationKind::Read);
        Ok(PreparedToolInvocation::resource_aware(
            [access],
            [capability],
            metadata,
            move |_context| {
                Box::pin(async move {
                    skill_workspace.revalidate(&resolved).map_err(|error| {
                        SdkToolError::new(ToolErrorKind::PolicyDenied, error.to_string())
                    })?;
                    let contents =
                        tokio::fs::read_to_string(resolved.path())
                            .await
                            .map_err(|error| {
                                SdkToolError::new(ToolErrorKind::Execution, error.to_string())
                            })?;
                    let content = format!(
                        "Loaded skill: {name}\nSource: {source_display}\nReferences are relative to {directory_display}.\n\n{contents}"
                    );
                    Ok(ToolOutput::text(truncate(content, max_output_bytes)))
                })
            },
        ))
    }
}

pub(super) struct SdkSkillTool {
    max_output_bytes: usize,
}

impl SdkTool for SdkSkillTool {
    fn spec(&self) -> rho_sdk::model::ToolSpec {
        super::skill::Skill.spec()
    }

    fn security(&self) -> ToolSecurity {
        ToolSecurity::built_in([CapabilityKind::Skill])
    }

    fn prepare<'a>(
        &'a self,
        invocation: ToolInvocation,
        context: ToolPreparationContext,
    ) -> ToolPrepareFuture<'a> {
        Box::pin(async move {
            let invocation_source = invocation.source();
            let name = required_string(invocation.arguments(), "name")?.to_string();
            if !valid_skill_name(&name) {
                return Err(SdkToolError::new(
                    ToolErrorKind::InvalidArguments,
                    "skill name must contain only ASCII letters, digits, '-' or '_'",
                ));
            }
            let skill = match crate::skills::find_builtin(&name) {
                Some(skill) => skill,
                None => {
                    let workspace = preparation_workspace(&context)?;
                    crate::skills::discover(workspace.root())
                        .into_iter()
                        .find(|skill| skill.name == name)
                        .ok_or_else(|| {
                            SdkToolError::new(
                                ToolErrorKind::InvalidArguments,
                                format!("unknown skill: {name}"),
                            )
                        })?
                }
            };
            if skill.disable_model_invocation
                && !matches!(invocation_source, ToolInvocationSource::Host)
            {
                return Err(SdkToolError::new(
                    ToolErrorKind::PolicyDenied,
                    format!("skill '{name}' requires direct user invocation"),
                ));
            }
            let source_display = skill.source.to_string();
            match skill.source {
                crate::skills::SkillSource::BuiltIn => {
                    let metadata = ToolMetadata::new().operation(OperationKind::Read);
                    let capability = CapabilityRequest::skill(
                        &name,
                        None,
                        CapabilitySource::built_in_tool("skill"),
                    );
                    let access = ToolResourceAccess::shared(ToolResource::opaque(
                        "rho.skill.builtin",
                        &name,
                    ));
                    let content = truncate(
                        format!(
                            "Loaded skill: {name}\nSource: {source_display}\n\n{}",
                            skill.contents
                        ),
                        self.max_output_bytes,
                    );
                    Ok(PreparedToolInvocation::resource_aware(
                        [access],
                        [capability],
                        metadata,
                        move |_context| Box::pin(async move { Ok(ToolOutput::text(content)) }),
                    ))
                }
                crate::skills::SkillSource::Filesystem { skill_file, .. } => {
                    let skill_directory = skill_file.parent().ok_or_else(|| {
                        SdkToolError::new(
                            ToolErrorKind::Execution,
                            format!(
                                "skill path '{}' has no parent directory",
                                skill_file.display()
                            ),
                        )
                    })?;
                    self.prepare_fs_skill(
                        &name,
                        source_display,
                        &skill_file,
                        skill_directory,
                        &context,
                    )
                }
            }
        })
    }
}

fn preparation_workspace(
    context: &ToolPreparationContext,
) -> Result<&rho_sdk::Workspace, SdkToolError> {
    context.workspace().ok_or_else(|| {
        SdkToolError::new(
            ToolErrorKind::Execution,
            "skill requires a configured workspace",
        )
    })
}

fn valid_skill_name(name: &str) -> bool {
    !name.is_empty()
        && name
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
}

pub(super) struct QuestionnaireTool;

impl SdkTool for QuestionnaireTool {
    fn spec(&self) -> rho_sdk::model::ToolSpec {
        crate::questionnaire::tool_spec()
    }

    fn security(&self) -> ToolSecurity {
        ToolSecurity::built_in([])
    }

    fn call<'a>(&'a self, invocation: ToolInvocation, context: SdkToolContext) -> ToolFuture<'a> {
        Box::pin(async move {
            let request = crate::questionnaire::parse_request(invocation.into_arguments())
                .map_err(|message| SdkToolError::new(ToolErrorKind::InvalidArguments, message))?;
            let questions = request
                .questions
                .iter()
                .map(host_question)
                .collect::<Result<Vec<_>, _>>()?;
            let title = request
                .title
                .clone()
                .unwrap_or_else(|| "questionnaire".into());
            let mut host_request =
                HostInputRequest::questionnaire(title, questions).map_err(map_sdk_error)?;
            if let Some(fallback) = request.on_timeout {
                host_request = host_request
                    .with_timeout_fallback(fallback.host_response(), fallback.reason)
                    .map_err(map_sdk_error)?;
            }
            let response = context
                .request_host_input(host_request)
                .await
                .map_err(map_sdk_error)?;
            let answers = response
                .answers()
                .iter()
                .map(|(id, values)| crate::questionnaire::QuestionnaireAnswer {
                    id: id.clone(),
                    answer: if values.len() == 1 {
                        serde_json::Value::String(values[0].clone())
                    } else {
                        serde_json::Value::Array(
                            values
                                .iter()
                                .cloned()
                                .map(serde_json::Value::String)
                                .collect(),
                        )
                    },
                })
                .collect();
            let content = crate::questionnaire::response_content(
                &crate::questionnaire::QuestionnaireResponse {
                    answers,
                    source: response.source(),
                },
            );
            Ok(ToolOutput::text(content).metadata(
                ToolMetadata::new().operation(OperationKind::Other("questionnaire".into())),
            ))
        })
    }
}

/// Non-blocking plain-text notice from a delegated child to its parent.
struct MessageParentTool {
    poster: Arc<dyn crate::app::subagent_messaging::NoticePoster>,
    delivery: NoticeDelivery,
}

impl MessageParentTool {
    fn name(&self) -> &'static str {
        match self.delivery {
            NoticeDelivery::NextTurn => "message_parent",
            NoticeDelivery::ParentActionRequired => "request_parent_action",
        }
    }
}

impl SdkTool for MessageParentTool {
    fn spec(&self) -> rho_sdk::model::ToolSpec {
        let (description, message_description) = match self.delivery {
            NoticeDelivery::NextTurn => (
                "Queue a short plain-text finding for the parent's next turn without waking it or waiting for a reply. Prefer saving findings for your final result. Do not send acknowledgments, progress updates, or completion previews. Keep the message under 8 KiB.",
                "Useful finding that can wait until the parent's next turn",
            ),
            NoticeDelivery::ParentActionRequired => (
                "Request parent action for a blocking decision or immediate coordination that cannot wait for your final result. This may wake the parent; it does not wait for a reply. State the specific action needed. Do not use for ordinary findings, status, acknowledgments, or completion previews. Keep the message under 8 KiB.",
                "Specific parent action needed now and why it cannot wait",
            ),
        };
        rho_sdk::model::ToolSpec {
            name: self.name().into(),
            description: description.into(),
            input_schema: serde_json::json!({
                "type": "object",
                "properties": {
                    "message": {
                        "type": "string",
                        "description": message_description
                    }
                },
                "required": ["message"],
                "additionalProperties": false
            }),
        }
    }

    fn security(&self) -> ToolSecurity {
        ToolSecurity::built_in([])
    }

    fn call<'a>(&'a self, invocation: ToolInvocation, _context: SdkToolContext) -> ToolFuture<'a> {
        Box::pin(async move {
            let arguments = invocation.into_arguments();
            let message = required_string(&arguments, "message").map_err(|error| {
                SdkToolError::new(ToolErrorKind::InvalidArguments, error.to_string())
            })?;
            let message = crate::app::subagent_messaging::ValidatedMessage::parse(message)
                .map_err(|error| {
                    SdkToolError::new(ToolErrorKind::InvalidArguments, error.to_string())
                })?;
            self.poster
                .post(message, self.delivery)
                .map_err(|error| SdkToolError::new(ToolErrorKind::Execution, error.to_string()))?;
            Ok(ToolOutput::text("notice queued for the parent session")
                .metadata(ToolMetadata::new().operation(OperationKind::Other(self.name().into()))))
        })
    }
}

fn host_question(
    question: &crate::questionnaire::QuestionnaireQuestion,
) -> Result<HostQuestion, SdkToolError> {
    use crate::questionnaire::QuestionnaireQuestionKind;

    let selection = match question.kind {
        QuestionnaireQuestionKind::MultiSelect => SelectionMode::Many,
        QuestionnaireQuestionKind::Choice
        | QuestionnaireQuestionKind::Confirm
        | QuestionnaireQuestionKind::Text => SelectionMode::One,
    };
    let choices = match question.kind {
        QuestionnaireQuestionKind::Choice | QuestionnaireQuestionKind::MultiSelect => question
            .choices
            .iter()
            .map(|choice| {
                let host = HostChoice::new(&choice.label, &choice.label);
                match &choice.description {
                    Some(description) => host.description(description),
                    None => host,
                }
            })
            .collect(),
        QuestionnaireQuestionKind::Confirm => {
            vec![HostChoice::new("yes", "Yes"), HostChoice::new("no", "No")]
        }
        QuestionnaireQuestionKind::Text => vec![HostChoice::new("other", "Other")],
    };
    let mut host = HostQuestion::new(&question.id, &question.question, choices, selection)
        .map_err(map_sdk_error)?;
    if question.allow_other || matches!(question.kind, QuestionnaireQuestionKind::Text) {
        host = host.allow_other();
    }
    if let Some(header) = &question.header {
        host = host.header(header);
    }
    if let Some(help) = &question.help {
        host = host.help(help);
    }
    if let Some(default) = &question.default {
        host = host.default_value(default.clone());
    }
    host = host.default_selection(question.default_selection.into());
    if !question.required {
        host = host.optional();
    }
    Ok(host)
}

fn map_sdk_error(error: rho_sdk::Error) -> SdkToolError {
    match error {
        rho_sdk::Error::Cancelled => SdkToolError::cancelled(),
        error => SdkToolError::new(ToolErrorKind::Execution, error.to_string()),
    }
}

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