rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! 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,
};
use rho_tools::{sdk_support::required_string, tool::truncate};

/// The `skill` tool, which finds a project plugin's skills only under the
/// session's `project_trust`.
pub(super) fn skill_bundle(
    max_output_bytes: usize,
    project_trust: crate::workspace::ProjectTrusts,
) -> super::sdk_registry::StaticToolBundle {
    super::sdk_registry::StaticToolBundle::new(vec![Arc::new(SdkSkillTool {
        max_output_bytes,
        project_trust,
    })])
}

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 {
    /// 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 = skill_metadata();
        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 instructions = crate::skills::instructions(&contents);
                    let content = format!(
                        "Loaded skill: {name}\nSource: {source_display}\nReferences are relative to {directory_display}.\n\n{instructions}"
                    );
                    Ok(ToolOutput::text(truncate(content, max_output_bytes)))
                })
            },
        ))
    }
}

pub(super) struct SdkSkillTool {
    max_output_bytes: usize,
    /// The session's project trust.
    project_trust: crate::workspace::ProjectTrusts,
}

impl SdkTool for SdkSkillTool {
    fn spec(&self) -> rho_sdk::model::ToolSpec {
        rho_sdk::model::ToolSpec {
            name: "skill".into(),
            description: "Load the instructions for a skill listed under available skills, by its exact name. Returns the SKILL.md body without its YAML frontmatter; for file-backed skills, relative paths inside it resolve against the skill's directory. Unknown names return an error. Output beyond the tool-output limit is truncated.".into(),
            input_schema: serde_json::json!({
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string",
                        "description": "The skill name to load"
                    }
                },
                "required": ["name"],
                "additionalProperties": false
            }),
        }
    }

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

    fn start_metadata(&self, _arguments: &serde_json::Value) -> ToolMetadata {
        skill_metadata()
    }

    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(), self.project_trust)
                        .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 = skill_metadata();
                    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{}",
                            crate::skills::instructions(&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'_'))
}

/// 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()))))
        })
    }
}

/// Loading a skill reads its files.
fn skill_metadata() -> ToolMetadata {
    ToolMetadata::new().operation(OperationKind::Read)
}

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