1use crate::agent::{AgentConfig, AgentLoop};
17use crate::llm::LlmClient;
18use crate::permissions::{PermissionDecision, PermissionPolicy, PermissionRule};
19use crate::skills::{Skill, SkillRegistry};
20use crate::tools::{Tool, ToolContext, ToolExecutor, ToolOutput};
21use anyhow::{anyhow, Result};
22use async_trait::async_trait;
23use serde::{Deserialize, Serialize};
24use serde_json::Value;
25use std::sync::Arc;
26
27#[derive(Debug, Serialize, Deserialize)]
29pub struct SkillArgs {
30 pub skill_name: String,
32 #[serde(default)]
34 pub prompt: Option<String>,
35}
36
37impl SkillArgs {
38 fn from_tool_args(args: &Value) -> Result<Self> {
39 fn parse_from_value(value: &Value) -> Option<SkillArgs> {
40 match value {
41 Value::String(skill_name) => Some(SkillArgs {
42 skill_name: skill_name.clone(),
43 prompt: None,
44 }),
45 Value::Object(map) => {
46 if let Some(skill_name) = map
47 .get("skill_name")
48 .or_else(|| map.get("skillName"))
49 .or_else(|| map.get("name"))
50 .and_then(|v| v.as_str())
51 {
52 let prompt = map
53 .get("prompt")
54 .or_else(|| map.get("query"))
55 .and_then(|v| v.as_str())
56 .map(ToOwned::to_owned);
57 return Some(SkillArgs {
58 skill_name: skill_name.to_string(),
59 prompt,
60 });
61 }
62
63 if let Some(nested) = map.get("input").or_else(|| map.get("arguments")) {
64 if let Some(parsed) = parse_from_value(nested) {
65 return Some(parsed);
66 }
67 }
68
69 None
70 }
71 _ => None,
72 }
73 }
74
75 parse_from_value(args).ok_or_else(|| anyhow!("missing field 'skill_name'"))
76 }
77}
78
79#[derive(Debug, Serialize, Deserialize)]
81pub struct SearchSkillsArgs {
82 pub query: String,
84 #[serde(default)]
86 pub limit: Option<usize>,
87}
88
89impl SearchSkillsArgs {
90 fn from_tool_args(args: &Value) -> Result<Self> {
91 match args {
92 Value::String(query) => Ok(Self {
93 query: query.clone(),
94 limit: None,
95 }),
96 Value::Object(map) => {
97 let query = map
98 .get("query")
99 .or_else(|| map.get("q"))
100 .and_then(|v| v.as_str())
101 .ok_or_else(|| anyhow!("missing field 'query'"))?
102 .to_string();
103 let limit = map
104 .get("limit")
105 .and_then(|v| v.as_u64())
106 .map(|v| v as usize);
107 Ok(Self { query, limit })
108 }
109 _ => Err(anyhow!(
110 "search_skills expects an object with a 'query' field"
111 )),
112 }
113 }
114}
115
116pub struct SearchSkillsTool {
118 skill_registry: Arc<SkillRegistry>,
119}
120
121impl SearchSkillsTool {
122 pub fn new(skill_registry: Arc<SkillRegistry>) -> Self {
123 Self { skill_registry }
124 }
125}
126
127#[async_trait]
128impl Tool for SearchSkillsTool {
129 fn name(&self) -> &str {
130 "search_skills"
131 }
132
133 fn description(&self) -> &str {
134 "Search available skills by name, tag, description, or content. \
135Use this before invoking Skill when specialized instructions may help."
136 }
137
138 fn parameters(&self) -> Value {
139 serde_json::json!({
140 "type": "object",
141 "additionalProperties": false,
142 "properties": {
143 "query": {
144 "type": "string",
145 "description": "Short search query for the skill you need."
146 },
147 "limit": {
148 "type": "integer",
149 "minimum": 1,
150 "maximum": 20,
151 "description": "Maximum number of skills to return. Defaults to 5."
152 }
153 },
154 "required": ["query"]
155 })
156 }
157
158 async fn execute(&self, args: &Value, _ctx: &ToolContext) -> Result<ToolOutput> {
159 let args = SearchSkillsArgs::from_tool_args(args)?;
160 let limit = args.limit.unwrap_or(5).clamp(1, 20);
161 let matches = self.skill_registry.search(&args.query, limit);
162
163 if matches.is_empty() {
164 return Ok(ToolOutput::success(
165 "No matching skills found. Continue with the core tools.".to_string(),
166 ));
167 }
168
169 let mut lines = vec![format!(
170 "Found {} matching skill(s). Invoke one with Skill using its skill_name.",
171 matches.len()
172 )];
173 let metadata: Vec<_> = matches
174 .iter()
175 .map(|skill| {
176 let kind = format!("{:?}", skill.kind).to_lowercase();
177 let allowed_tools = skill.allowed_tools.as_deref().unwrap_or("not specified");
178 lines.push(format!(
179 "- {} ({kind}): {} Allowed tools: {}.",
180 skill.name, skill.description, allowed_tools
181 ));
182 serde_json::json!({
183 "name": skill.name,
184 "description": skill.description,
185 "kind": kind,
186 "tags": skill.tags,
187 "allowed_tools": skill.allowed_tools,
188 })
189 })
190 .collect();
191
192 Ok(ToolOutput {
193 content: lines.join("\n"),
194 success: true,
195 metadata: Some(serde_json::json!({ "skills": metadata })),
196 images: Vec::new(),
197 error_kind: None,
198 })
199 }
200}
201
202pub struct SkillTool {
204 skill_registry: Arc<SkillRegistry>,
205 llm_client: Arc<dyn LlmClient>,
206 tool_executor: Arc<ToolExecutor>,
207 base_config: AgentConfig,
208}
209
210impl SkillTool {
211 pub(crate) fn new(
212 skill_registry: Arc<SkillRegistry>,
213 llm_client: Arc<dyn LlmClient>,
214 tool_executor: Arc<ToolExecutor>,
215 base_config: AgentConfig,
216 ) -> Self {
217 Self {
218 skill_registry,
219 llm_client,
220 tool_executor,
221 base_config,
222 }
223 }
224
225 fn create_skill_permission_policy(skill: &Skill) -> PermissionPolicy {
227 let permissions = skill.parse_allowed_tools();
228
229 if permissions.is_empty() {
230 tracing::warn!(
231 skill = %skill.name,
232 "Skill has no allowed-tools grants; Skill invocation remains fail-secure and will deny tool use"
233 );
234 return PermissionPolicy {
235 deny: Vec::new(),
236 allow: Vec::new(),
237 ask: Vec::new(),
238 default_decision: PermissionDecision::Deny,
239 enabled: true,
240 };
241 }
242
243 let mut allow_rules = Vec::new();
245 for perm in permissions {
246 let rule_str = if perm.pattern == "*" {
248 perm.tool.clone()
249 } else {
250 format!("{}({})", perm.tool, perm.pattern)
251 };
252 allow_rules.push(PermissionRule::new(&rule_str));
253 }
254
255 PermissionPolicy {
256 deny: Vec::new(),
257 allow: allow_rules,
258 ask: Vec::new(),
259 default_decision: PermissionDecision::Deny, enabled: true,
261 }
262 }
263}
264
265#[async_trait]
266impl Tool for SkillTool {
267 fn name(&self) -> &str {
268 "Skill"
269 }
270
271 fn description(&self) -> &str {
272 "Invoke a skill with temporary permission grants. \
273Use a JSON object with the canonical shape {\"skill_name\":\"<skill-name>\",\"prompt\":\"<optional prompt>\"}. \
274Always send the skill name in the 'skill_name' field. Do not use aliases such as 'name' or 'skillName', and do not wrap the payload in 'input' or 'arguments'. \
275The skill's allowed-tools are granted during execution and revoked after completion."
276 }
277
278 fn parameters(&self) -> Value {
279 serde_json::json!({
280 "type": "object",
281 "additionalProperties": false,
282 "properties": {
283 "skill_name": {
284 "type": "string",
285 "description": "Required. Canonical skill identifier to invoke. Always provide this exact field name: 'skill_name'."
286 },
287 "prompt": {
288 "type": "string",
289 "description": "Optional prompt or query to pass to the skill after it is loaded."
290 }
291 },
292 "required": ["skill_name"],
293 "examples": [
294 {
295 "skill_name": "code-review"
296 },
297 {
298 "skill_name": "code-review",
299 "prompt": "Review this patch for correctness and regressions."
300 }
301 ]
302 })
303 }
304
305 async fn execute(&self, args: &Value, ctx: &ToolContext) -> Result<ToolOutput> {
306 let args = SkillArgs::from_tool_args(args)?;
307
308 let skill = self
310 .skill_registry
311 .get(&args.skill_name)
312 .ok_or_else(|| anyhow!("Skill '{}' not found", args.skill_name))?;
313
314 let skill_permission_policy = Self::create_skill_permission_policy(&skill);
316
317 let mut skill_config = self.base_config.clone();
319 if ctx.has_run_governance() {
320 skill_config.permission_checker = ctx.run_permission_checker();
321 skill_config.confirmation_manager = ctx.run_confirmation_manager();
322 }
323
324 let parent_checker = skill_config.permission_checker.take();
329 let parent_policy = skill_config.permission_policy.clone();
330 skill_config.permission_checker = Some(crate::child_run::compose_permission_checker(
331 Arc::new(skill_permission_policy.clone()),
332 Some(skill_permission_policy.clone()),
333 parent_checker,
334 parent_policy,
335 ));
336 skill_config.permission_policy = Some(skill_permission_policy);
337 skill_config.enforce_active_skill_tool_restrictions = true;
338
339 let temp_registry = Arc::new(SkillRegistry::new());
341 temp_registry.register(skill.clone())?;
342 skill_config.skill_registry = Some(temp_registry);
343
344 skill_config.prompt_slots.role = Some(format!(
346 "You are executing the '{}' skill.\n\n{}\n\n{}",
347 skill.name, skill.description, skill.content
348 ));
349
350 let agent_loop = AgentLoop::new(
352 self.llm_client.clone(),
353 self.tool_executor.clone(),
354 ctx.clone(),
355 skill_config,
356 );
357
358 let prompt = args
360 .prompt
361 .unwrap_or_else(|| format!("Execute the '{}' skill", skill.name));
362
363 let cancellation = ctx.cancellation_token();
368 let result = agent_loop
369 .execute_with_session(
370 &[],
371 &prompt,
372 ctx.session_id.as_deref(),
373 None,
374 Some(&cancellation),
375 )
376 .await?;
377 if cancellation.is_cancelled() {
378 anyhow::bail!("Skill '{}' cancelled by caller", skill.name);
379 }
380
381 Ok(ToolOutput {
383 content: result.text,
384 success: true,
385 metadata: Some(serde_json::json!({
386 "skill_name": skill.name,
387 "tool_calls": result.tool_calls_count,
388 "usage": result.usage,
389 })),
390 images: Vec::new(),
391 error_kind: None,
392 })
393 }
394}
395
396#[cfg(test)]
397mod tests {
398 use super::*;
399 use crate::budget::{BudgetDecision, BudgetGuard};
400 use crate::llm::{
401 ContentBlock, LlmClient, LlmResponse, Message, StreamEvent, TokenUsage, ToolDefinition,
402 };
403 use crate::skills::SkillKind;
404 use crate::tools::ToolContext;
405 use anyhow::Result;
406 use async_trait::async_trait;
407 use std::path::PathBuf;
408 use std::sync::atomic::{AtomicUsize, Ordering};
409 use std::sync::Mutex;
410 use std::time::Duration;
411 use tokio::sync::{mpsc, Notify};
412 use tokio_util::sync::CancellationToken;
413
414 struct MockLlmClient {
415 responses: Mutex<Vec<LlmResponse>>,
416 }
417
418 impl MockLlmClient {
419 fn new(responses: Vec<LlmResponse>) -> Self {
420 Self {
421 responses: Mutex::new(responses),
422 }
423 }
424
425 fn text_response(text: &str) -> LlmResponse {
426 LlmResponse {
427 message: Message {
428 role: "assistant".to_string(),
429 content: vec![ContentBlock::Text {
430 text: text.to_string(),
431 }],
432 reasoning_content: None,
433 },
434 usage: TokenUsage {
435 prompt_tokens: 10,
436 completion_tokens: 5,
437 total_tokens: 15,
438 cache_read_tokens: None,
439 cache_write_tokens: None,
440 },
441 stop_reason: Some("end_turn".to_string()),
442 token_logprobs: Vec::new(),
443 meta: None,
444 }
445 }
446
447 fn tool_call_response(id: &str, name: &str, input: serde_json::Value) -> LlmResponse {
448 LlmResponse {
449 message: Message {
450 role: "assistant".to_string(),
451 content: vec![ContentBlock::ToolUse {
452 id: id.to_string(),
453 name: name.to_string(),
454 input,
455 }],
456 reasoning_content: None,
457 },
458 usage: TokenUsage {
459 prompt_tokens: 10,
460 completion_tokens: 5,
461 total_tokens: 15,
462 cache_read_tokens: None,
463 cache_write_tokens: None,
464 },
465 stop_reason: Some("tool_use".to_string()),
466 token_logprobs: Vec::new(),
467 meta: None,
468 }
469 }
470 }
471
472 #[async_trait]
473 impl LlmClient for MockLlmClient {
474 async fn complete(
475 &self,
476 _messages: &[Message],
477 _system: Option<&str>,
478 _tools: &[ToolDefinition],
479 ) -> Result<LlmResponse> {
480 let mut responses = self.responses.lock().unwrap();
481 if responses.is_empty() {
482 anyhow::bail!("No more mock responses available");
483 }
484 Ok(responses.remove(0))
485 }
486
487 async fn complete_streaming(
488 &self,
489 _messages: &[Message],
490 _system: Option<&str>,
491 _tools: &[ToolDefinition],
492 _cancel_token: tokio_util::sync::CancellationToken,
493 ) -> Result<mpsc::Receiver<StreamEvent>> {
494 anyhow::bail!("streaming not used in SkillTool tests")
495 }
496 }
497
498 #[derive(Default)]
499 struct SkillBudgetGuard {
500 checks: AtomicUsize,
501 records: AtomicUsize,
502 sessions: Mutex<Vec<String>>,
503 }
504
505 #[async_trait]
506 impl BudgetGuard for SkillBudgetGuard {
507 async fn check_before_llm(
508 &self,
509 session_id: &str,
510 _estimated_prompt_tokens: usize,
511 ) -> BudgetDecision {
512 self.checks.fetch_add(1, Ordering::SeqCst);
513 self.sessions.lock().unwrap().push(session_id.to_string());
514 BudgetDecision::Allow
515 }
516
517 async fn record_after_llm(&self, _session_id: &str, _usage: &TokenUsage) {
518 self.records.fetch_add(1, Ordering::SeqCst);
519 }
520 }
521
522 struct BlockingSkillClient {
523 started: Arc<Notify>,
524 calls: Arc<AtomicUsize>,
525 }
526
527 struct SkillSideEffectTool {
528 calls: Arc<AtomicUsize>,
529 }
530
531 #[async_trait]
532 impl Tool for SkillSideEffectTool {
533 fn name(&self) -> &str {
534 "side_effect"
535 }
536
537 fn description(&self) -> &str {
538 "Records a test-only side effect"
539 }
540
541 fn parameters(&self) -> serde_json::Value {
542 serde_json::json!({"type": "object", "additionalProperties": false})
543 }
544
545 async fn execute(
546 &self,
547 _args: &serde_json::Value,
548 _ctx: &ToolContext,
549 ) -> Result<ToolOutput> {
550 self.calls.fetch_add(1, Ordering::SeqCst);
551 Ok(ToolOutput::success("unexpected-side-effect"))
552 }
553 }
554
555 #[async_trait]
556 impl LlmClient for BlockingSkillClient {
557 async fn complete(
558 &self,
559 _messages: &[Message],
560 _system: Option<&str>,
561 _tools: &[ToolDefinition],
562 ) -> Result<LlmResponse> {
563 self.calls.fetch_add(1, Ordering::SeqCst);
564 self.started.notify_one();
565 std::future::pending::<Result<LlmResponse>>().await
566 }
567
568 async fn complete_streaming(
569 &self,
570 _messages: &[Message],
571 _system: Option<&str>,
572 _tools: &[ToolDefinition],
573 _cancel_token: CancellationToken,
574 ) -> Result<mpsc::Receiver<StreamEvent>> {
575 anyhow::bail!("streaming not used in SkillTool cancellation tests")
576 }
577 }
578
579 fn test_skill_registry() -> Arc<SkillRegistry> {
580 let registry = Arc::new(SkillRegistry::new());
581 registry.register_unchecked(Arc::new(Skill {
582 name: "test-skill".to_string(),
583 description: "Run a focused skill".to_string(),
584 allowed_tools: None,
585 disable_model_invocation: false,
586 kind: SkillKind::Instruction,
587 content: "Reply with the skill result.".to_string(),
588 tags: vec!["focus".to_string()],
589 version: None,
590 }));
591 registry
592 }
593
594 #[test]
595 fn test_skill_permission_policy() {
596 let skill = Skill {
597 name: "test-skill".to_string(),
598 description: "Test".to_string(),
599 allowed_tools: Some("read(*), grep(*)".to_string()),
600 disable_model_invocation: false,
601 kind: SkillKind::Instruction,
602 content: String::new(),
603 tags: Vec::new(),
604 version: None,
605 };
606
607 let policy = SkillTool::create_skill_permission_policy(&skill);
608
609 assert_eq!(
611 policy.check("read", &serde_json::json!({})),
612 PermissionDecision::Allow
613 );
614 assert_eq!(
615 policy.check("grep", &serde_json::json!({})),
616 PermissionDecision::Allow
617 );
618
619 assert_eq!(
621 policy.check("write", &serde_json::json!({})),
622 PermissionDecision::Deny
623 );
624 }
625
626 #[test]
627 fn test_skill_permission_policy_denies_when_unspecified() {
628 let skill = Skill {
629 name: "test-skill".to_string(),
630 description: "Test".to_string(),
631 allowed_tools: None,
632 disable_model_invocation: false,
633 kind: SkillKind::Instruction,
634 content: String::new(),
635 tags: Vec::new(),
636 version: None,
637 };
638
639 let policy = SkillTool::create_skill_permission_policy(&skill);
640
641 assert_eq!(
642 policy.check("bash", &serde_json::json!({"command": "python --version"})),
643 PermissionDecision::Deny
644 );
645 assert_eq!(
646 policy.check("read", &serde_json::json!({"file_path": "SKILL.md"})),
647 PermissionDecision::Deny
648 );
649 }
650
651 #[test]
652 fn test_skill_permission_policy_accepts_legacy_allowed_tools() {
653 let skill = Skill {
654 name: "test-skill".to_string(),
655 description: "Test".to_string(),
656 allowed_tools: Some("Read Write Edit Bash".to_string()),
657 disable_model_invocation: false,
658 kind: SkillKind::Instruction,
659 content: String::new(),
660 tags: Vec::new(),
661 version: None,
662 };
663
664 let policy = SkillTool::create_skill_permission_policy(&skill);
665
666 assert_eq!(
667 policy.check("bash", &serde_json::json!({"command": "python --version"})),
668 PermissionDecision::Allow
669 );
670 assert_eq!(
671 policy.check("grep", &serde_json::json!({"pattern": "x"})),
672 PermissionDecision::Deny
673 );
674 }
675
676 #[test]
677 fn test_skill_permission_policy_accepts_wildcard_allowed_tools() {
678 let skill = Skill {
679 name: "test-skill".to_string(),
680 description: "Test".to_string(),
681 allowed_tools: Some("*".to_string()),
682 disable_model_invocation: false,
683 kind: SkillKind::Instruction,
684 content: String::new(),
685 tags: Vec::new(),
686 version: None,
687 };
688
689 let policy = SkillTool::create_skill_permission_policy(&skill);
690
691 assert_eq!(
692 policy.check("bash", &serde_json::json!({"command": "python --version"})),
693 PermissionDecision::Allow
694 );
695 assert_eq!(
696 policy.check("parallel_task", &serde_json::json!({"tasks": []})),
697 PermissionDecision::Allow
698 );
699 }
700
701 #[test]
702 fn test_skill_args_accepts_documented_shape() {
703 let args =
704 SkillArgs::from_tool_args(&serde_json::json!({"skill_name": "code-review"})).unwrap();
705 assert_eq!(args.skill_name, "code-review");
706 assert_eq!(args.prompt, None);
707 }
708
709 #[test]
710 fn test_skill_args_accepts_common_aliases_and_wrappers() {
711 let camel =
712 SkillArgs::from_tool_args(&serde_json::json!({"skillName": "code-review"})).unwrap();
713 assert_eq!(camel.skill_name, "code-review");
714
715 let name = SkillArgs::from_tool_args(&serde_json::json!({
716 "name": "code-review",
717 "query": "review this patch"
718 }))
719 .unwrap();
720 assert_eq!(name.skill_name, "code-review");
721 assert_eq!(name.prompt.as_deref(), Some("review this patch"));
722
723 let nested = SkillArgs::from_tool_args(&serde_json::json!({
724 "input": {
725 "skill_name": "code-review",
726 "prompt": "review this patch"
727 }
728 }))
729 .unwrap();
730 assert_eq!(nested.skill_name, "code-review");
731 assert_eq!(nested.prompt.as_deref(), Some("review this patch"));
732
733 let direct = SkillArgs::from_tool_args(&serde_json::json!("code-review")).unwrap();
734 assert_eq!(direct.skill_name, "code-review");
735 }
736
737 #[test]
738 fn test_skill_args_missing_skill_name_errors() {
739 let err =
740 SkillArgs::from_tool_args(&serde_json::json!({"prompt": "do something"})).unwrap_err();
741 assert!(err.to_string().contains("missing field 'skill_name'"));
742 }
743
744 #[test]
745 fn test_search_skills_args_accepts_string_and_object() {
746 let direct = SearchSkillsArgs::from_tool_args(&serde_json::json!("review code")).unwrap();
747 assert_eq!(direct.query, "review code");
748 assert_eq!(direct.limit, None);
749
750 let object =
751 SearchSkillsArgs::from_tool_args(&serde_json::json!({"query": "review", "limit": 2}))
752 .unwrap();
753 assert_eq!(object.query, "review");
754 assert_eq!(object.limit, Some(2));
755 }
756
757 #[tokio::test]
758 async fn test_search_skills_tool_returns_matching_skills() {
759 let registry = Arc::new(SkillRegistry::new());
760 registry.register_unchecked(Arc::new(Skill {
761 name: "code-review".to_string(),
762 description: "Review code changes".to_string(),
763 allowed_tools: Some("read(*), grep(*)".to_string()),
764 disable_model_invocation: false,
765 kind: SkillKind::Instruction,
766 content: "Review instructions".to_string(),
767 tags: vec!["review".to_string()],
768 version: None,
769 }));
770
771 let tool = SearchSkillsTool::new(registry);
772 let result = tool
773 .execute(
774 &serde_json::json!({"query": "review"}),
775 &ToolContext::new(PathBuf::from("/tmp")),
776 )
777 .await
778 .unwrap();
779
780 assert!(result.success);
781 assert!(result.content.contains("code-review"));
782 assert_eq!(result.metadata.unwrap()["skills"][0]["name"], "code-review");
783 }
784
785 #[tokio::test]
786 async fn test_search_skills_tool_clamps_limit_and_excludes_personas() {
787 let registry = Arc::new(SkillRegistry::new());
788 for index in 0..25 {
789 registry.register_unchecked(Arc::new(Skill {
790 name: format!("review-{index:02}"),
791 description: "Review code changes".to_string(),
792 allowed_tools: Some("read(*)".to_string()),
793 disable_model_invocation: false,
794 kind: SkillKind::Instruction,
795 content: "Review instructions".to_string(),
796 tags: vec!["review".to_string()],
797 version: None,
798 }));
799 }
800 registry.register_unchecked(Arc::new(Skill {
801 name: "review-persona".to_string(),
802 description: "Review persona".to_string(),
803 allowed_tools: None,
804 disable_model_invocation: false,
805 kind: SkillKind::Persona,
806 content: "Persona instructions".to_string(),
807 tags: vec!["review".to_string()],
808 version: None,
809 }));
810
811 let tool = SearchSkillsTool::new(registry);
812 let result = tool
813 .execute(
814 &serde_json::json!({"query": "review", "limit": 100}),
815 &ToolContext::new(PathBuf::from("/tmp")),
816 )
817 .await
818 .unwrap();
819
820 let metadata = result.metadata.unwrap();
821 let skills = metadata["skills"].as_array().unwrap();
822 assert_eq!(skills.len(), 20);
823 assert!(skills.iter().all(|skill| skill["kind"] == "instruction"));
824 }
825
826 #[test]
827 fn test_skill_tool_schema_enforces_canonical_shape() {
828 let registry = Arc::new(SkillRegistry::new());
829 let llm = Arc::new(MockLlmClient::new(vec![]));
830 let executor = Arc::new(ToolExecutor::new("/tmp".to_string()));
831 let tool = SkillTool::new(registry, llm, executor, AgentConfig::default());
832
833 let params = tool.parameters();
834 assert_eq!(params["type"], "object");
835 assert_eq!(params["additionalProperties"], serde_json::json!(false));
836 assert_eq!(params["required"], serde_json::json!(["skill_name"]));
837
838 let examples = params["examples"].as_array().unwrap();
839 assert_eq!(examples[0]["skill_name"], "code-review");
840 assert!(examples[0].get("name").is_none());
841 assert!(examples[0].get("skillName").is_none());
842 }
843
844 #[tokio::test]
845 async fn test_skill_tool_execute_runs_skill_and_returns_metadata() {
846 use crate::prompts::PlanningMode;
847
848 let registry = Arc::new(SkillRegistry::new());
849 registry.register_unchecked(Arc::new(Skill {
850 name: "test-skill".to_string(),
851 description: "Run a focused skill".to_string(),
852 allowed_tools: None,
853 disable_model_invocation: false,
854 kind: SkillKind::Instruction,
855 content: "Reply with the skill result.".to_string(),
856 tags: vec!["focus".to_string()],
857 version: None,
858 }));
859
860 let llm = Arc::new(MockLlmClient::new(vec![MockLlmClient::text_response(
861 "skill completed",
862 )]));
863 let executor = Arc::new(ToolExecutor::new("/tmp".to_string()));
864 let config = AgentConfig {
866 planning_mode: PlanningMode::Disabled,
867 continuation_enabled: false,
868 ..Default::default()
869 };
870 let tool = SkillTool::new(registry, llm, executor, config);
871
872 let result = tool
873 .execute(
874 &serde_json::json!({
875 "skill_name": "test-skill",
876 "prompt": "verify the skill result"
877 }),
878 &ToolContext::new(PathBuf::from("/tmp")),
879 )
880 .await
881 .unwrap();
882
883 assert!(result.success);
884 assert_eq!(result.content, "skill completed");
885 let metadata = result.metadata.unwrap();
886 assert_eq!(metadata["skill_name"], "test-skill");
887 assert_eq!(metadata["tool_calls"], 0);
888 }
889
890 #[tokio::test]
891 async fn skill_permissions_cannot_replace_the_parent_host_boundary() {
892 use crate::prompts::PlanningMode;
893
894 let workspace = tempfile::tempdir().unwrap();
895 let registry = Arc::new(SkillRegistry::new());
896 registry.register_unchecked(Arc::new(Skill {
897 name: "bash-skill".to_string(),
898 description: "Attempt a shell call".to_string(),
899 allowed_tools: Some("bash(*)".to_string()),
900 disable_model_invocation: false,
901 kind: SkillKind::Instruction,
902 content: "Use Bash once.".to_string(),
903 tags: Vec::new(),
904 version: None,
905 }));
906 let llm = Arc::new(MockLlmClient::new(vec![
907 MockLlmClient::tool_call_response(
908 "bash-call",
909 "bash",
910 serde_json::json!({"command": "printf leaked > skill-boundary-leak"}),
911 ),
912 MockLlmClient::text_response("The host boundary rejected the call."),
913 ]));
914 let parent_policy = PermissionPolicy::new().deny("bash(*)");
915 let config = AgentConfig {
916 planning_mode: PlanningMode::Disabled,
917 continuation_enabled: false,
918 permission_checker: Some(Arc::new(parent_policy.clone())),
919 permission_policy: Some(parent_policy),
920 ..Default::default()
921 };
922 let tool = SkillTool::new(
923 registry,
924 llm,
925 Arc::new(ToolExecutor::new(
926 workspace.path().to_string_lossy().into_owned(),
927 )),
928 config,
929 );
930
931 let result = tool
932 .execute(
933 &serde_json::json!({"skill_name": "bash-skill"}),
934 &ToolContext::new(workspace.path().to_path_buf()),
935 )
936 .await
937 .unwrap();
938
939 assert!(result.success, "{}", result.content);
940 assert!(
941 !workspace.path().join("skill-boundary-leak").exists(),
942 "a skill-local allow-list must not bypass the parent host boundary"
943 );
944 }
945
946 #[tokio::test]
947 async fn host_direct_context_does_not_leak_into_skill_model_orchestrators() {
948 use crate::prompts::PlanningMode;
949
950 struct RecordingBoundary {
951 checked: Arc<Mutex<Vec<String>>>,
952 }
953
954 impl crate::permissions::PermissionChecker for RecordingBoundary {
955 fn check(&self, tool_name: &str, _args: &serde_json::Value) -> PermissionDecision {
956 self.checked.lock().unwrap().push(tool_name.to_string());
957 if tool_name == "side_effect" {
958 PermissionDecision::Deny
959 } else {
960 PermissionDecision::Allow
961 }
962 }
963 }
964
965 let workspace = tempfile::tempdir().unwrap();
966 let calls = Arc::new(AtomicUsize::new(0));
967 let checked = Arc::new(Mutex::new(Vec::new()));
968 let registry = Arc::new(SkillRegistry::new());
969 registry.register_unchecked(Arc::new(Skill {
970 name: "orchestrator-skill".to_string(),
971 description: "Exercise governed orchestrators".to_string(),
972 allowed_tools: Some("batch(*), program(*), side_effect(*)".to_string()),
973 disable_model_invocation: false,
974 kind: SkillKind::Instruction,
975 content: "Run the requested orchestration.".to_string(),
976 tags: Vec::new(),
977 version: None,
978 }));
979 let llm = Arc::new(MockLlmClient::new(vec![
980 MockLlmClient::tool_call_response(
981 "model-batch",
982 "batch",
983 serde_json::json!({
984 "invocations": [{
985 "tool": "program",
986 "args": {
987 "type": "script",
988 "language": "javascript",
989 "source": "async function run(ctx) { return await ctx.tool('side_effect', {}); }",
990 "allowed_tools": ["side_effect"]
991 }
992 }]
993 }),
994 ),
995 MockLlmClient::text_response("The boundary held."),
996 ]));
997 let executor = Arc::new(ToolExecutor::new(
998 workspace.path().to_string_lossy().into_owned(),
999 ));
1000 executor.register_dynamic_tool(Arc::new(SkillSideEffectTool {
1001 calls: Arc::clone(&calls),
1002 }));
1003 let tool = SkillTool::new(
1004 registry,
1005 llm,
1006 executor,
1007 AgentConfig {
1008 planning_mode: PlanningMode::Disabled,
1009 continuation_enabled: false,
1010 permission_checker: Some(Arc::new(RecordingBoundary {
1011 checked: Arc::clone(&checked),
1012 })),
1013 ..Default::default()
1014 },
1015 );
1016 let context = ToolContext::new(workspace.path().to_path_buf())
1017 .with_host_direct_policy(crate::tools::HostDirectPolicy::TrustedControlPlane);
1018
1019 let result = tool
1020 .execute(
1021 &serde_json::json!({"skill_name": "orchestrator-skill"}),
1022 &context,
1023 )
1024 .await
1025 .unwrap();
1026
1027 assert!(result.success, "{}", result.content);
1028 assert_eq!(result.content, "The boundary held.");
1029 assert_eq!(calls.load(Ordering::SeqCst), 0);
1030 let checked = checked.lock().unwrap();
1031 for expected in ["batch", "program", "side_effect"] {
1032 assert!(
1033 checked.iter().any(|tool| tool == expected),
1034 "{expected} must cross the parent permission boundary: {checked:?}"
1035 );
1036 }
1037 }
1038
1039 #[tokio::test]
1040 async fn skill_child_llm_call_uses_parent_session_budget_scope() {
1041 use crate::prompts::PlanningMode;
1042
1043 let guard = Arc::new(SkillBudgetGuard::default());
1044 let config = AgentConfig {
1045 planning_mode: PlanningMode::Disabled,
1046 continuation_enabled: false,
1047 budget_guard: Some(Arc::clone(&guard) as Arc<dyn BudgetGuard>),
1048 ..Default::default()
1049 };
1050 let tool = SkillTool::new(
1051 test_skill_registry(),
1052 Arc::new(MockLlmClient::new(vec![MockLlmClient::text_response(
1053 "skill completed",
1054 )])),
1055 Arc::new(ToolExecutor::new("/tmp".to_string())),
1056 config,
1057 );
1058 let ctx = ToolContext::new(PathBuf::from("/tmp")).with_session_id("parent-session");
1059
1060 let result = tool
1061 .execute(&serde_json::json!({"skill_name": "test-skill"}), &ctx)
1062 .await
1063 .unwrap();
1064
1065 assert!(result.success);
1066 assert_eq!(guard.checks.load(Ordering::SeqCst), 1);
1067 assert_eq!(guard.records.load(Ordering::SeqCst), 1);
1068 assert_eq!(
1069 guard.sessions.lock().unwrap().as_slice(),
1070 &["parent-session".to_string()]
1071 );
1072 }
1073
1074 #[tokio::test]
1075 async fn skill_child_llm_call_stops_on_parent_cancellation() {
1076 use crate::prompts::PlanningMode;
1077
1078 let started = Arc::new(Notify::new());
1079 let calls = Arc::new(AtomicUsize::new(0));
1080 let tool = SkillTool::new(
1081 test_skill_registry(),
1082 Arc::new(BlockingSkillClient {
1083 started: Arc::clone(&started),
1084 calls: Arc::clone(&calls),
1085 }),
1086 Arc::new(ToolExecutor::new("/tmp".to_string())),
1087 AgentConfig {
1088 planning_mode: PlanningMode::Disabled,
1089 continuation_enabled: false,
1090 ..Default::default()
1091 },
1092 );
1093 let cancellation = CancellationToken::new();
1094 let ctx = ToolContext::new(PathBuf::from("/tmp"))
1095 .with_session_id("parent-session")
1096 .with_cancellation(cancellation.clone());
1097 let started_wait = started.notified();
1098 let run = tokio::spawn(async move {
1099 tool.execute(&serde_json::json!({"skill_name": "test-skill"}), &ctx)
1100 .await
1101 });
1102
1103 tokio::time::timeout(Duration::from_secs(1), started_wait)
1104 .await
1105 .expect("skill provider call should start");
1106 cancellation.cancel();
1107 let error = tokio::time::timeout(Duration::from_secs(1), run)
1108 .await
1109 .expect("parent cancellation must stop the skill child")
1110 .expect("skill join should succeed")
1111 .expect_err("cancelled skill must not return success");
1112
1113 assert!(error.to_string().contains("cancelled"));
1114 assert_eq!(calls.load(Ordering::SeqCst), 1);
1115 }
1116
1117 #[tokio::test]
1118 async fn test_skill_tool_execute_errors_for_unknown_skill() {
1119 let llm = Arc::new(MockLlmClient::new(vec![MockLlmClient::text_response(
1120 "unused",
1121 )]));
1122 let executor = Arc::new(ToolExecutor::new("/tmp".to_string()));
1123 let tool = SkillTool::new(
1124 Arc::new(SkillRegistry::new()),
1125 llm,
1126 executor,
1127 AgentConfig::default(),
1128 );
1129
1130 let err = tool
1131 .execute(
1132 &serde_json::json!({"skill_name": "missing-skill"}),
1133 &ToolContext::new(PathBuf::from("/tmp")),
1134 )
1135 .await
1136 .unwrap_err();
1137
1138 assert!(err.to_string().contains("Skill 'missing-skill' not found"));
1139 }
1140}