aether_cli/show_prompt/
run.rs1use std::collections::BTreeMap;
2
3use super::PromptArgs;
4use crate::error::CliError;
5use crate::resolve::resolve_agent_spec;
6use crate::runtime::RuntimeBuilder;
7use aether_core::core::Prompt;
8use llm::ToolDefinition;
9use serde_json::Value;
10
11pub async fn run_prompt(args: PromptArgs) -> Result<(), CliError> {
12 let cwd = args.cwd.canonicalize().map_err(CliError::IoError)?;
13 let catalog = args.settings_source.load_agent_catalog(&cwd).map_err(|e| CliError::AgentError(e.to_string()))?;
14 let spec = resolve_agent_spec(&catalog, args.agent.as_deref())?;
15
16 let info = RuntimeBuilder::from_spec(cwd.clone(), spec)
17 .mcp_sources(args.mcp_config.sources(&cwd))
18 .build_prompt_info()
19 .await?;
20
21 let system_prompt = build_prompt(&info.spec.prompts, args.system_prompt.as_deref()).await?;
22 let tools_output = build_tools(&info.tool_definitions);
23
24 println!("{system_prompt}");
25
26 if !tools_output.is_empty() {
27 println!();
28 println!("--- Tools ({} tools) ---", info.tool_definitions.len());
29 println!();
30 println!("{tools_output}");
31 }
32
33 println!();
34 println!("{}", format_stats(system_prompt.len(), tools_output.len(), info.tool_definitions.len()));
35
36 Ok(())
37}
38
39pub async fn build_prompt(prompts: &[Prompt], custom: Option<&str>) -> Result<String, CliError> {
40 let mut prompts = prompts.to_vec();
41 if let Some(custom) = custom {
42 prompts.push(Prompt::text(custom));
43 }
44 Prompt::build_all(&prompts).await.map_err(|e| CliError::AgentError(e.to_string()))
45}
46
47pub fn build_tools(tools: &[ToolDefinition]) -> String {
48 if tools.is_empty() {
49 return String::new();
50 }
51
52 let mut grouped: BTreeMap<&str, Vec<Value>> = BTreeMap::new();
53 for tool in tools {
54 let server = tool.server.as_deref().unwrap_or("(built-in)");
55 let entry = serde_json::json!({
56 "name": tool.name,
57 "description": tool.description,
58 "input_schema": tool.parameters,
59 });
60 grouped.entry(server).or_default().push(entry);
61 }
62
63 let mut sections = Vec::new();
64 for (server, entries) in &grouped {
65 let json = serde_json::to_string_pretty(entries).unwrap_or_default();
66 sections.push(format!("Server: {server}\n{json}"));
67 }
68
69 sections.join("\n\n")
70}
71
72pub fn format_stats(prompt_chars: usize, tool_schema_chars: usize, tool_count: usize) -> String {
73 let est_tokens = (prompt_chars + tool_schema_chars) / 4;
74 format!(
75 "---\n\
76 Prompt chars: {prompt_chars:>8}\n\
77 Tool schema chars:{tool_schema_chars:>8}\n\
78 Est. tokens: ~{est_tokens:>8}\n\
79 MCP tools: {tool_count:>8}"
80 )
81}
82
83#[cfg(test)]
84mod tests {
85 use super::*;
86
87 fn tool(name: &str, desc: &str, params: &str, server: Option<&str>) -> ToolDefinition {
88 let mut tool = ToolDefinition::new(name, desc, serde_json::from_str(params).unwrap());
89 tool.server = server.map(String::from);
90 tool
91 }
92
93 #[test]
94 fn format_stats_computes_token_estimate() {
95 let output = format_stats(12000, 8500, 14);
96 assert_eq!(
97 output,
98 "---\n\
99 Prompt chars: 12000\n\
100 Tool schema chars: 8500\n\
101 Est. tokens: ~ 5125\n\
102 MCP tools: 14"
103 );
104 }
105
106 #[test]
107 fn format_stats_handles_zero() {
108 let output = format_stats(0, 0, 0);
109 assert_eq!(
110 output,
111 "---\n\
112 Prompt chars: 0\n\
113 Tool schema chars: 0\n\
114 Est. tokens: ~ 0\n\
115 MCP tools: 0"
116 );
117 }
118
119 #[test]
120 fn format_stats_handles_small_values() {
121 let output = format_stats(3, 0, 1);
122 assert_eq!(
123 output,
124 "---\n\
125 Prompt chars: 3\n\
126 Tool schema chars: 0\n\
127 Est. tokens: ~ 0\n\
128 MCP tools: 1"
129 );
130 }
131
132 #[test]
133 fn build_tools_groups_by_server() {
134 let tools = vec![
135 tool("fs_read", "Read a file", r#"{"type":"object"}"#, Some("filesystem")),
136 tool("git_log", "Show log", r#"{"type":"object"}"#, Some("git")),
137 tool("fs_write", "Write a file", r#"{"type":"object"}"#, Some("filesystem")),
138 ];
139 let output = build_tools(&tools);
140 let fs_pos = output.find("Server: filesystem").unwrap();
142 let git_pos = output.find("Server: git").unwrap();
143 assert!(fs_pos < git_pos);
144 assert!(output.contains("fs_read"));
146 assert!(output.contains("fs_write"));
147 }
148
149 #[test]
150 fn build_tools_handles_no_server() {
151 let tools = vec![tool("builtin_tool", "A built-in", r#"{"type":"object"}"#, None)];
152 let output = build_tools(&tools);
153 assert!(output.contains("Server: (built-in)"));
154 assert!(output.contains("builtin_tool"));
155 }
156
157 #[test]
158 fn build_tools_produces_api_format() {
159 let tools = vec![tool("my_tool", "Does stuff", r#"{"type":"object","properties":{}}"#, Some("test"))];
160 let output = build_tools(&tools);
161 let json_start = output.find('[').unwrap();
163 let parsed: Vec<Value> = serde_json::from_str(&output[json_start..]).unwrap();
164 assert_eq!(parsed.len(), 1);
165 let entry = &parsed[0];
166 assert_eq!(entry["name"], "my_tool");
167 assert_eq!(entry["description"], "Does stuff");
168 assert!(entry["input_schema"].is_object());
169 }
170
171 #[test]
172 fn build_tools_empty() {
173 assert_eq!(build_tools(&[]), "");
174 }
175}