1use crate::{host::Host, mcp::McpHandler, memory::Memory, os, skill, skill::SkillHandler};
9use std::{
10 collections::BTreeMap,
11 path::{Path, PathBuf},
12};
13use wcore::{AgentConfig, AgentEvent, Hook, ToolRegistry, model::Message};
14
15#[derive(Default)]
17pub struct AgentScope {
18 pub(crate) tools: Vec<String>,
19 pub(crate) members: Vec<String>,
20 pub(crate) skills: Vec<String>,
21 pub(crate) mcps: Vec<String>,
22}
23
24const BASE_TOOLS: &[&str] = &["bash", "ask_user"];
26
27const SKILL_TOOLS: &[&str] = &["skill"];
29
30const MCP_TOOLS: &[&str] = &["mcp"];
32
33const MEMORY_TOOLS: &[&str] = &["recall", "remember", "memory", "forget"];
35
36const TASK_TOOLS: &[&str] = &["delegate"];
38
39pub struct Env<H: Host = crate::NoHost> {
40 pub(crate) skills: SkillHandler,
41 pub(crate) mcp: McpHandler,
42 pub(crate) cwd: PathBuf,
43 pub(crate) memory: Option<Memory>,
44 pub(crate) scopes: BTreeMap<String, AgentScope>,
45 pub(crate) agent_descriptions: BTreeMap<String, String>,
46 pub host: H,
48}
49
50impl<H: Host> Env<H> {
51 pub fn new(
53 skills: SkillHandler,
54 mcp: McpHandler,
55 cwd: PathBuf,
56 memory: Option<Memory>,
57 host: H,
58 ) -> Self {
59 Self {
60 skills,
61 mcp,
62 cwd,
63 memory,
64 scopes: BTreeMap::new(),
65 agent_descriptions: BTreeMap::new(),
66 host,
67 }
68 }
69
70 pub fn memory(&self) -> Option<&Memory> {
72 self.memory.as_ref()
73 }
74
75 pub fn mcp_servers(&self) -> Vec<(String, Vec<String>)> {
77 self.mcp.cached_list()
78 }
79
80 pub fn register_scope(&mut self, name: String, config: &AgentConfig) {
82 if name != wcore::paths::DEFAULT_AGENT && !config.description.is_empty() {
83 self.agent_descriptions
84 .insert(name.clone(), config.description.clone());
85 }
86 self.scopes.insert(
87 name,
88 AgentScope {
89 tools: config.tools.clone(),
90 members: config.members.clone(),
91 skills: config.skills.clone(),
92 mcps: config.mcps.clone(),
93 },
94 );
95 }
96
97 fn apply_scope(&self, config: &mut AgentConfig) {
99 let has_scoping =
100 !config.skills.is_empty() || !config.mcps.is_empty() || !config.members.is_empty();
101 if !has_scoping {
102 return;
103 }
104
105 let mut whitelist: Vec<String> = BASE_TOOLS.iter().map(|&s| s.to_owned()).collect();
106 if self.memory.is_some() {
107 for &t in MEMORY_TOOLS {
108 whitelist.push(t.to_owned());
109 }
110 }
111 let mut scope_lines = Vec::new();
112
113 if !config.skills.is_empty() {
114 for &t in SKILL_TOOLS {
115 whitelist.push(t.to_owned());
116 }
117 scope_lines.push(format!("skills: {}", config.skills.join(", ")));
118 }
119
120 if !config.mcps.is_empty() {
121 for &t in MCP_TOOLS {
122 whitelist.push(t.to_owned());
123 }
124 let server_names: Vec<&str> = config.mcps.iter().map(|s| s.as_str()).collect();
125 scope_lines.push(format!("mcp servers: {}", server_names.join(", ")));
126 }
127
128 if !config.members.is_empty() {
129 for &t in TASK_TOOLS {
130 whitelist.push(t.to_owned());
131 }
132 scope_lines.push(format!("members: {}", config.members.join(", ")));
133 }
134
135 if !scope_lines.is_empty() {
136 let scope_block = format!("\n\n<scope>\n{}\n</scope>", scope_lines.join("\n"));
137 config.system_prompt.push_str(&scope_block);
138 }
139
140 config.tools = whitelist;
141 }
142
143 fn resolve_slash_skill(&self, agent: &str, content: &str) -> String {
145 let trimmed = content.trim_start();
146 let Some(rest) = trimmed.strip_prefix('/') else {
147 return content.to_owned();
148 };
149
150 let end = rest
151 .find(|c: char| !c.is_ascii_lowercase() && !c.is_ascii_digit() && c != '-')
152 .unwrap_or(rest.len());
153 let name = &rest[..end];
154 let remainder = &rest[end..];
155
156 if name.is_empty() || name.contains("..") {
157 return content.to_owned();
158 }
159
160 if let Some(scope) = self.scopes.get(agent)
162 && !scope.skills.is_empty()
163 && !scope.skills.iter().any(|s| s == name)
164 {
165 return content.to_owned();
166 }
167
168 for dir in &self.skills.skill_dirs {
170 let skill_file = dir.join(name).join("SKILL.md");
171 let Ok(file_content) = std::fs::read_to_string(&skill_file) else {
172 continue;
173 };
174 let Ok(skill) = skill::loader::parse_skill_md(&file_content) else {
175 continue;
176 };
177 let body = remainder.trim_start();
178 let block = format!("<skill name=\"{name}\">\n{}\n</skill>", skill.body);
179 return if body.is_empty() {
180 block
181 } else {
182 format!("{body}\n\n{block}")
183 };
184 }
185
186 content.to_owned()
187 }
188
189 async fn dispatch_delegate(&self, args: &str, agent: &str) -> String {
191 let input: crate::task::Delegate = match serde_json::from_str(args) {
192 Ok(v) => v,
193 Err(e) => return format!("invalid arguments: {e}"),
194 };
195 if input.tasks.is_empty() {
196 return "no tasks provided".to_owned();
197 }
198 if let Some(scope) = self.scopes.get(agent)
200 && !scope.members.is_empty()
201 {
202 for task in &input.tasks {
203 if !scope.members.iter().any(|m| m == &task.agent) {
204 return format!("agent '{}' is not in your members list", task.agent);
205 }
206 }
207 }
208 self.host.dispatch_delegate(args, agent).await
209 }
210
211 pub async fn dispatch_tool(
213 &self,
214 name: &str,
215 args: &str,
216 agent: &str,
217 sender: &str,
218 conversation_id: Option<u64>,
219 ) -> String {
220 if let Some(scope) = self.scopes.get(agent)
222 && !scope.tools.is_empty()
223 && !scope.tools.iter().any(|t| t.as_str() == name)
224 {
225 return format!("tool not available: {name}");
226 }
227 match name {
228 "mcp" => self.dispatch_mcp(args, agent).await,
229 "skill" => self.dispatch_skill(args, agent).await,
230 "bash" if sender.contains(':') => {
231 "bash is only available in the command line interface".to_owned()
232 }
233 "bash" => self.dispatch_bash(args, conversation_id).await,
234 "recall" => self.dispatch_recall(args).await,
235 "remember" => self.dispatch_remember(args).await,
236 "memory" => self.dispatch_memory(args).await,
237 "forget" => self.dispatch_forget(args).await,
238 "delegate" => self.dispatch_delegate(args, agent).await,
239 "ask_user" => self.host.dispatch_ask_user(args, conversation_id).await,
240 name => {
241 self.host
242 .dispatch_custom_tool(name, args, agent, conversation_id)
243 .await
244 }
245 }
246 }
247}
248
249impl<H: Host + 'static> Hook for Env<H> {
250 fn on_build_agent(&self, mut config: AgentConfig) -> AgentConfig {
251 config.system_prompt.push_str(&os::environment_block());
252
253 if let Some(ref mem) = self.memory {
254 let prompt = mem.build_prompt();
255 if !prompt.is_empty() {
256 config.system_prompt.push_str(&prompt);
257 }
258 }
259
260 let mut hints = Vec::new();
261 let mcp_servers = self.mcp.cached_list();
262 if !mcp_servers.is_empty() {
263 let names: Vec<&str> = mcp_servers.iter().map(|(n, _)| n.as_str()).collect();
264 hints.push(format!(
265 "MCP servers: {}. Use the mcp tool to list or call tools.",
266 names.join(", ")
267 ));
268 }
269 if let Ok(reg) = self.skills.registry.try_lock() {
270 let visible: Vec<_> = if config.skills.is_empty() {
271 reg.skills.iter().collect()
272 } else {
273 reg.skills
274 .iter()
275 .filter(|s| config.skills.iter().any(|n| n == &s.name))
276 .collect()
277 };
278 if !visible.is_empty() {
279 let lines: Vec<String> = visible
280 .iter()
281 .map(|s| {
282 if s.description.is_empty() {
283 format!("- {}", s.name)
284 } else {
285 format!("- {}: {}", s.name, s.description)
286 }
287 })
288 .collect();
289 hints.push(format!(
290 "Skills:\n\
291 When a <skill> tag appears in a message, it has been pre-loaded by the system. \
292 Follow its instructions directly — do not announce or re-load it.\n\
293 Use the skill tool to discover available skills or load one by name.\n{}",
294 lines.join("\n")
295 ));
296 }
297 }
298 if !hints.is_empty() {
299 config.system_prompt.push_str(&format!(
300 "\n\n<resources>\n{}\n</resources>",
301 hints.join("\n")
302 ));
303 }
304
305 self.apply_scope(&mut config);
306 config
307 }
308
309 fn preprocess(&self, agent: &str, content: &str) -> String {
310 self.resolve_slash_skill(agent, content)
311 }
312
313 fn on_before_run(
314 &self,
315 agent: &str,
316 conversation_id: u64,
317 history: &[Message],
318 ) -> Vec<Message> {
319 let mut messages = Vec::new();
320 let has_members = self
321 .scopes
322 .get(agent)
323 .is_some_and(|s| !s.members.is_empty());
324 if has_members && !self.agent_descriptions.is_empty() {
325 let mut block = String::from("<agents>\n");
326 for (name, desc) in &self.agent_descriptions {
327 block.push_str(&format!("- {name}: {desc}\n"));
328 }
329 block.push_str("</agents>");
330 let mut msg = Message::user(block);
331 msg.auto_injected = true;
332 messages.push(msg);
333 }
334 if let Some(ref mem) = self.memory {
335 messages.extend(mem.before_run(history));
336 }
337 let cwd = self
338 .host
339 .conversation_cwd(conversation_id)
340 .unwrap_or_else(|| self.cwd.clone());
341 let mut cwd_msg = Message::user(format!(
342 "<environment>\nworking_directory: {}\n</environment>",
343 cwd.display()
344 ));
345 cwd_msg.auto_injected = true;
346 messages.push(cwd_msg);
347 if let Some(instructions) = discover_instructions(&cwd) {
348 let mut msg = Message::user(format!("<instructions>\n{instructions}\n</instructions>"));
349 msg.auto_injected = true;
350 messages.push(msg);
351 }
352 if history.iter().any(|m| !m.agent.is_empty()) {
355 let mut msg = Message::user(
356 "Messages wrapped in <from agent=\"...\"> tags are from guest agents \
357 who were consulted in this conversation. Continue responding as yourself."
358 .to_string(),
359 );
360 msg.auto_injected = true;
361 messages.push(msg);
362 }
363 messages
364 }
365
366 async fn on_register_tools(&self, tools: &mut ToolRegistry) {
367 self.mcp.register_tools(tools);
368 tools.insert_all(os::tool::tools());
369 tools.insert_all(skill::tool::tools());
370 tools.insert_all(crate::task::tools());
371 tools.insert_all(crate::ask_user::tools());
372 if self.memory.is_some() {
373 tools.insert_all(crate::memory::tool::tools());
374 }
375 }
376
377 fn on_event(&self, agent: &str, conversation_id: u64, event: &AgentEvent) {
378 self.host.on_agent_event(agent, conversation_id, event);
379 }
380}
381
382fn discover_instructions(cwd: &Path) -> Option<String> {
386 let config_dir = &*wcore::paths::CONFIG_DIR;
387 let mut layers = Vec::new();
388
389 let global = config_dir.join("Crab.md");
391 if let Ok(content) = std::fs::read_to_string(&global) {
392 layers.push(content);
393 }
394
395 let mut found = Vec::new();
397 let mut dir = cwd;
398 loop {
399 let candidate = dir.join("Crab.md");
400 if candidate.is_file()
401 && !candidate.starts_with(config_dir)
402 && let Ok(content) = std::fs::read_to_string(&candidate)
403 {
404 found.push(content);
405 }
406 match dir.parent() {
407 Some(p) => dir = p,
408 None => break,
409 }
410 }
411 found.reverse();
412 layers.extend(found);
413
414 if layers.is_empty() {
415 return None;
416 }
417 Some(layers.join("\n\n"))
418}