ailoy 0.3.3

Agents that drive a language model through tool-augmented turns, in a virtx console.
Documentation
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use super::Memory;
use crate::{
    datatype::Value,
    model::{LangModelOptions, ThinkingEffort},
    tool::{
        ToolDesc, WebSearchEngineKind,
        r#impl::{
            get_apply_patch_tool_desc, get_edit_tool_desc, get_imgread_tool_desc,
            get_read_file_tool_desc, get_read_tool_desc, get_shell_tool_desc,
            get_web_fetch_tool_desc, get_web_search_tool_desc, get_write_tool_desc,
        },
    },
};

/// What makes an agent distinct: its model, instruction and tools.
///
/// Tools are built through the providers set with
/// [`set_tool_provider`](crate::tool::set_tool_provider); the console lives on
/// [`AgentState`](super::AgentState).
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
pub struct AgentSpec {
    /// The model's desc, as [`create_lang_model`](crate::model::create_lang_model)
    /// takes it (e.g. `"anthropic/claude-sonnet-5-5"`).
    pub model: String,

    /// System prompt that shapes how the model works.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instruction: Option<String>,

    /// Tool descriptions exposed to the model. Each [`ToolDesc::name`] must have a
    /// [`ToolProvider`](crate::tool::ToolProvider) set for it.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tools: Vec<ToolDesc>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub model_options: Option<LangModelOptions>,

    /// Engines used by the `web_search` tool. `None` (or not provided) means
    /// all available engines. Only meaningful when `web_search` is listed in `tools`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub web_search_engines: Option<Vec<WebSearchEngineKind>>,

    /// Skill directories in the console, each holding a `SKILL.md`. See
    /// [`skill`](Self::skill).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub skills: Vec<String>,

    /// The folder on this host whose `MEMORY.md` the agent keeps notes on the user in. See
    /// [`memory`](Self::memory).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memory: Option<Memory>,
}

/// The org a desc names (`"anthropic"` of `"anthropic/claude-sonnet-5-5"`) and the name
/// after it.
pub(super) fn split_desc(desc: &str) -> (&str, &str) {
    desc.split_once('/').unwrap_or((desc, ""))
}

/// The shell and file tools for a sandbox, in the style of the model's org.
fn sandbox_tool_descs(org: &str) -> Vec<ToolDesc> {
    let mut descs = vec![get_shell_tool_desc()];
    // GPT reads files through `shell`, as in Codex.
    if org == "openai" {
        descs.push(get_apply_patch_tool_desc());
    } else {
        // DeepSeek, Kimi and GLM serve Anthropic-compatible APIs for Claude Code, so
        // likely follow the Claude style.
        descs.push(match org {
            "google" => get_read_file_tool_desc(),
            _ => get_read_tool_desc(),
        });
        descs.push(get_write_tool_desc());
        descs.push(get_edit_tool_desc());
    }

    // `imgread` only where the image reaches the model: the backends of these take tool
    // results as text alone (an image becomes a label), even for vision models.
    if !matches!(
        org,
        "deepseek-ai" | "moonshotai" | "zai-org" | "Qwen" | "LGAI-EXAONE"
    ) {
        descs.push(get_imgread_tool_desc());
    }
    descs
}

impl AgentSpec {
    pub fn new(model: impl Into<String>) -> Self {
        Self {
            model: model.into(),
            instruction: None,
            tools: Vec::new(),
            model_options: None,
            web_search_engines: None,
            skills: Vec::new(),
            memory: None,
        }
    }

    pub fn instruction(mut self, inst: impl Into<String>) -> Self {
        self.instruction = Some(inst.into());
        self
    }

    /// Give this agent the skill in `dir`, a directory in the console holding a `SKILL.md`.
    ///
    /// At construction the frontmatter `name` and `description` are read through the
    /// console and listed in the system message with the skill's location; the agent reads
    /// the rest itself, so it needs a console and a file-reading tool.
    ///
    /// Skills are added only to the instruction-built system message, never to one already
    /// in the history.
    pub fn skill(mut self, dir: impl Into<String>) -> Self {
        self.skills.push(dir.into());
        self
    }

    /// Let this agent keep short notes on the user in `MEMORY.md` in the folder `memory`
    /// names on this host: a path such as `/data/agent1`, relative to the current directory
    /// when the agent is built unless absolute. It needs no sandbox.
    ///
    /// Adds the `memory` tool, which writes the notes, and a section at the end of the system
    /// message that shows them as they were when the agent was built, so a change shows from
    /// the next agent on. Building the agent makes the folder, and those on the way to it, and
    /// fails if it cannot, or if [`tools`](Self::tools) has a `memory` tool of its own; the
    /// file is made by the first note. Like skills, the section goes only into the system
    /// message built from the instruction, never into one already in the history.
    pub fn memory(mut self, memory: impl Into<Memory>) -> Self {
        self.memory = Some(memory.into());
        self
    }

    pub fn tool(mut self, tool: ToolDesc) -> Self {
        self.tools.push(tool);
        self
    }

    pub fn tools(mut self, tools: impl IntoIterator<Item = ToolDesc>) -> Self {
        self.tools.extend(tools);
        self
    }

    /// Add the shell and file tools for a sandbox, in the style of the model's org, skipping
    /// any the spec already has. [`AgentBuilder::sandbox`](super::AgentBuilder::sandbox) adds
    /// them itself.
    pub fn sandbox_tools(mut self) -> Self {
        for desc in sandbox_tool_descs(split_desc(&self.model).0) {
            if !self.tools.iter().any(|t| t.name == desc.name) {
                self.tools.push(desc);
            }
        }
        self
    }

    /// Add `web_search`; a non-empty `engines` restricts it to those, empty uses all.
    pub fn web_search_tool(mut self, engines: Vec<WebSearchEngineKind>) -> Self {
        self.tools.push(get_web_search_tool_desc());
        if !engines.is_empty() {
            self.web_search_engines = Some(engines);
        }
        self
    }

    /// Add the `web_fetch` tool to the spec.
    ///
    /// The tool fetches one `url` per call, pages long bodies
    /// through `offset`, and allows one request per second per host.
    pub fn web_fetch_tool(mut self) -> Self {
        self.tools.push(get_web_fetch_tool_desc());
        self
    }

    pub fn thinking_effort(mut self, effort: ThinkingEffort) -> Self {
        self.model_options
            .get_or_insert_with(LangModelOptions::default)
            .thinking_effort = Some(effort);
        self
    }

    /// JSON schema the model's answers must match.
    pub fn output_schema(mut self, schema: Value) -> Self {
        self.model_options
            .get_or_insert_with(LangModelOptions::default)
            .output_schema = Some(schema);
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn names(spec: &AgentSpec) -> Vec<&str> {
        spec.tools.iter().map(|t| t.name.as_str()).collect()
    }

    fn system_names(org: &str) -> Vec<String> {
        sandbox_tool_descs(org)
            .into_iter()
            .map(|t| t.name)
            .collect()
    }

    #[test]
    fn test_sandbox_tools_follow_the_model() {
        assert_eq!(system_names("openai"), ["shell", "apply_patch", "imgread"]);
        assert!(system_names("google").contains(&"read_file".into()));

        let claude = system_names("anthropic");
        assert!(claude.contains(&"read".into()), "{claude:?}");
        assert!(claude.contains(&"imgread".into()), "{claude:?}");

        assert!(!system_names("deepseek-ai").contains(&"imgread".into()));
        assert!(!system_names("moonshotai").contains(&"imgread".into()));
        assert!(!system_names("LGAI-EXAONE").contains(&"imgread".into()));
    }

    #[test]
    fn test_sandbox_tools_skip_tools_already_there() {
        let spec = AgentSpec::new("openai/gpt-6-luna")
            .sandbox_tools()
            .sandbox_tools();
        assert_eq!(names(&spec), ["shell", "apply_patch", "imgread"]);
    }

    #[test]
    fn test_web_search_tool_empty_engines_keeps_field_none() {
        let spec = AgentSpec::new("anthropic").web_search_tool(vec![]);
        assert!(spec.web_search_engines.is_none());
        assert_eq!(names(&spec), ["web_search"]);
    }

    #[test]
    fn test_spec_roundtrip() {
        let spec = AgentSpec::new("anthropic/claude-sonnet-5-5")
            .instruction("Be brief.")
            .thinking_effort(ThinkingEffort::Low)
            .web_search_tool(vec![WebSearchEngineKind::Google]);
        let json = serde_json::to_string(&spec).unwrap();
        let back: AgentSpec = serde_json::from_str(&json).unwrap();
        assert_eq!(back.model, "anthropic/claude-sonnet-5-5");
        assert_eq!(
            back.model_options.unwrap().thinking_effort,
            Some(ThinkingEffort::Low)
        );
        assert_eq!(
            back.web_search_engines.as_deref(),
            Some([WebSearchEngineKind::Google].as_slice())
        );
    }
}