Skip to main content

vtcode_core/skills/executor/
mod.rs

1//! Skill execution as Tool trait implementation
2//!
3//! Bridges Agent Skills to VT Code's tool system by implementing the Tool trait
4//! for skills, enabling them to execute with full access to VT Code's permissions,
5//! caching, and audit systems.
6//!
7//! ## LLM Sub-Calls (Phase 5)
8//!
9//! Skills can now execute with full LLM support via `execute_skill_with_sub_llm()`:
10//! 1. Skill instructions become the system prompt
11//! 2. User input is the first message
12//! 3. All available tools are passed to the LLM
13//! 4. Tool calls are executed and results are fed back
14//! 5. Final response is returned
15
16use crate::config::VTCodeConfig;
17use crate::config::constants::tools as tool_constants;
18use crate::config::models::ModelId;
19use crate::core::agent::runner::{AgentRunner, RunnerSettings};
20use crate::core::agent::task::Task;
21use crate::core::agent::types::AgentType;
22use crate::core::loop_detector::LoopDetector;
23use crate::llm::collect_single_response;
24use crate::llm::provider::{FinishReason, LLMProvider, LLMRequest, Message, ToolCall, ToolDefinition};
25use crate::metrics::MetricsCollector;
26use crate::skills::types::Skill;
27use crate::tool_policy::ToolPolicy;
28use crate::tools::ToolRegistry;
29use crate::tools::registry::{ToolErrorType, ToolExecutionError};
30use crate::tools::traits::Tool;
31use anyhow::{Context, Result, anyhow};
32use async_trait::async_trait;
33use chrono::Utc;
34use serde_json::Value;
35use std::borrow::Cow;
36use std::path::PathBuf;
37use std::sync::Arc;
38use std::time::{Duration, Instant};
39use tracing::{debug, info, warn};
40use vtcode_config::auth::OpenAIChatGptAuthHandle;
41
42use super::skill_policy::{
43    SkillToolScope, filter_registered_tools_for_skill, merge_skill_command_permissions, skill_function_tool_permitted,
44};
45
46pub use super::skill_policy::filter_tools_for_skill;
47
48type SkillToolArgTransform = dyn Fn(&str, Value) -> Value + Send + Sync;
49
50const EMPTY_SKILL_INPUT_PROMPT: &str =
51    "No explicit user input was provided. Follow the skill instructions using their default behavior for empty input.";
52const SKILL_TOOL_FREE_SYNTHESIS_PROMPT: &str =
53    "Do not make any more tool calls. Provide the best final answer you can using the information already gathered.";
54const MAX_SKILL_LLM_ITERATIONS: usize = 10;
55
56fn skill_tool_free_synthesis_prompt(reason: &str) -> String {
57    format!("{reason}\n\n{SKILL_TOOL_FREE_SYNTHESIS_PROMPT}")
58}
59
60fn should_force_tool_free_synthesis(error: &ToolExecutionError) -> bool {
61    matches!(error.error_type, ToolErrorType::ToolNotFound)
62}
63
64fn ensure_visible_skill_content(skill: &Skill, content: String) -> Result<String> {
65    if content.trim().is_empty() {
66        return Err(anyhow!("Skill '{}' completed without a visible final response", skill.name()));
67    }
68
69    Ok(content)
70}
71
72#[derive(Debug, Clone)]
73pub struct ForkSkillRuntimeConfig {
74    pub workspace: PathBuf,
75    pub model: String,
76    pub api_key: String,
77    pub openai_chatgpt_auth: Option<OpenAIChatGptAuthHandle>,
78    pub vt_cfg: Option<VTCodeConfig>,
79}
80
81#[async_trait]
82pub trait ForkSkillExecutor: Send + Sync {
83    async fn execute(&self, skill: &Skill, user_input: Value) -> Result<Value>;
84}
85
86#[derive(Clone)]
87pub struct ChildAgentSkillExecutor {
88    tool_registry: Arc<ToolRegistry>,
89    runtime: ForkSkillRuntimeConfig,
90}
91
92impl ChildAgentSkillExecutor {
93    pub fn new(tool_registry: Arc<ToolRegistry>, runtime: ForkSkillRuntimeConfig) -> Self {
94        Self { tool_registry, runtime }
95    }
96
97    async fn build_runner(&self, skill: &Skill, session_id: String) -> Result<AgentRunner> {
98        let model = self
99            .runtime
100            .model
101            .parse::<ModelId>()
102            .with_context(|| format!("invalid model for forked skill '{}'", skill.name()))?;
103
104        let mut runner = if let Some(vt_cfg) = self.runtime.vt_cfg.clone() {
105            Box::pin(AgentRunner::new_with_bootstrap(
106                fork_agent_type(skill),
107                model,
108                self.runtime.api_key.clone(),
109                self.runtime.workspace.clone(),
110                session_id,
111                RunnerSettings::default(),
112                None,
113                crate::core::threads::ThreadBootstrap::new(None),
114                Some(vt_cfg),
115                self.runtime.openai_chatgpt_auth.clone(),
116            ))
117            .await?
118        } else {
119            Box::pin(AgentRunner::new_with_bootstrap(
120                fork_agent_type(skill),
121                model,
122                self.runtime.api_key.clone(),
123                self.runtime.workspace.clone(),
124                session_id,
125                RunnerSettings::default(),
126                None,
127                crate::core::threads::ThreadBootstrap::new(None),
128                None,
129                self.runtime.openai_chatgpt_auth.clone(),
130            ))
131            .await?
132        };
133        runner.set_quiet(true);
134        Ok(runner)
135    }
136}
137
138fn skill_runs_in_fork(skill: &Skill) -> bool {
139    skill.manifest.context.as_deref() == Some("fork")
140}
141
142fn skill_tool_arg_transform(skill: Skill) -> Arc<SkillToolArgTransform> {
143    Arc::new(move |tool_name, tool_args| merge_skill_command_permissions(&skill, tool_name, tool_args))
144}
145
146fn fork_agent_type(skill: &Skill) -> AgentType {
147    match skill.manifest.agent.as_deref() {
148        Some("explore") => AgentType::Explore,
149        Some("plan") => AgentType::Plan,
150        Some("general") => AgentType::General,
151        _ => AgentType::General,
152    }
153}
154
155fn format_skill_user_input(user_input: &Value) -> String {
156    match user_input {
157        Value::String(text) => normalized_skill_user_input(text),
158        other => other.to_string(),
159    }
160}
161
162fn normalized_skill_user_input(user_input: &str) -> String {
163    if user_input.trim().is_empty() {
164        EMPTY_SKILL_INPUT_PROMPT.to_string()
165    } else {
166        user_input.to_string()
167    }
168}
169
170fn child_session_id(parent_session_id: &str, skill_name: &str) -> String {
171    format!(
172        "{}-skill-{}-{}",
173        crate::utils::session_debug::sanitize_debug_component(parent_session_id, "session"),
174        crate::utils::session_debug::sanitize_debug_component(skill_name, "skill"),
175        Utc::now().format("%Y%m%dT%H%M%SZ")
176    )
177}
178
179fn blocked_handoff_paths(events: &[crate::exec::events::ThreadEvent]) -> Vec<String> {
180    let mut paths = Vec::new();
181    for event in events {
182        let crate::exec::events::ThreadEvent::ItemCompleted(completed) = event else {
183            continue;
184        };
185        let crate::exec::events::ThreadItemDetails::Harness(harness) = &completed.item.details else {
186            continue;
187        };
188        if harness.event == crate::exec::events::HarnessEventKind::BlockedHandoffWritten
189            && let Some(path) = harness.path.as_ref()
190            && !paths.iter().any(|existing| existing == path)
191        {
192            paths.push(path.clone());
193        }
194    }
195    paths
196}
197
198#[async_trait]
199impl ForkSkillExecutor for ChildAgentSkillExecutor {
200    async fn execute(&self, skill: &Skill, user_input: Value) -> Result<Value> {
201        let parent_session_id = self.tool_registry.harness_context_snapshot().session_id;
202        let session_id = child_session_id(&parent_session_id, skill.name());
203        let mut runner = Box::pin(self.build_runner(skill, session_id.clone())).await?;
204
205        let restricted_tools =
206            filter_registered_tools_for_skill(skill, runner.build_universal_tools().await?, &self.tool_registry);
207        let allowed_tools = restricted_tools
208            .iter()
209            .map(|tool| tool.function_name().to_string())
210            .collect::<Vec<_>>();
211        runner.set_tool_definitions_override(restricted_tools);
212        runner.restrict_to_local_tools();
213        runner.set_tool_arg_transform(skill_tool_arg_transform(skill.clone()));
214        runner.enable_full_auto(&allowed_tools).await;
215
216        let mut task = Task::new(
217            format!("fork-skill-{}", skill.name()),
218            format!("Skill {}", skill.name()),
219            format_skill_user_input(&user_input),
220        );
221        task.instructions = Some(vtcode_skills::trust::render_activation_for_skill(skill));
222
223        let results = Box::pin(runner.execute_task(&task, &[])).await?;
224        let mut artifact_paths = results.modified_files.clone();
225        let handoff_paths = blocked_handoff_paths(&results.thread_events);
226        for path in handoff_paths {
227            if !artifact_paths.iter().any(|existing| existing == &path) {
228                artifact_paths.push(path);
229            }
230        }
231
232        Ok(serde_json::json!({
233            "execution_context": "fork",
234            "status": results.outcome.code(),
235            "summary": if results.summary.trim().is_empty() {
236                results.outcome.description()
237            } else {
238                results.summary
239            },
240            "artifact_paths": artifact_paths,
241            "delegate_session_id": session_id,
242        }))
243    }
244}
245
246/// Canonicalize a textual tool name emitted inside skill sub-LLM content.
247///
248/// Gateway-served models (e.g. `zai/glm-5.3-flash`) sometimes emit
249/// `<tool_call>bash ...` markup instead of native function calls. This maps
250/// shell aliases to `exec_command` and normalizes separators the same way the
251/// interactive runloop does, without pulling the binary-only `text_tools`
252/// parsers into `vtcode-core`.
253fn canonicalize_skill_textual_tool_name(raw: &str) -> Option<String> {
254    let trimmed = raw.trim().trim_matches(|ch| matches!(ch, '"' | '\'' | '`'));
255    if trimmed.is_empty() {
256        return None;
257    }
258    let mut normalized = String::with_capacity(trimmed.len());
259    let mut last_was_separator = false;
260    for ch in trimmed.chars() {
261        if ch.is_ascii_alphanumeric() {
262            normalized.push(ch.to_ascii_lowercase());
263            last_was_separator = false;
264        } else if ch == '_' {
265            normalized.push('_');
266            last_was_separator = false;
267        } else if matches!(ch, ' ' | '\t' | '\n' | '-' | ':' | '.') && !last_was_separator && !normalized.is_empty() {
268            normalized.push('_');
269            last_was_separator = true;
270        }
271    }
272    let normalized = normalized.trim_matches('_').to_string();
273    if normalized.is_empty() {
274        return None;
275    }
276    if matches!(
277        normalized.as_str(),
278        "run"
279            | "runcmd"
280            | "runcommand"
281            | "terminalrun"
282            | "terminalcmd"
283            | "terminalcommand"
284            | "command"
285            | "shell"
286            | "bash"
287            | "container_exec"
288            | "exec"
289            | "exec_command"
290    ) {
291        return Some(tool_constants::EXEC_COMMAND.to_string());
292    }
293    Some(normalized)
294}
295
296fn read_skill_tag_text(input: &str) -> (String, &str) {
297    let trimmed = input.trim_start();
298    if trimmed.is_empty() {
299        return (String::new(), "");
300    }
301    if let Some(idx) = trimmed.find('<') {
302        let (value, rest) = trimmed.split_at(idx);
303        (value.trim().to_string(), rest)
304    } else {
305        (trimmed.trim().to_string(), "")
306    }
307}
308
309fn parse_skill_scalar_value(raw: &str) -> Value {
310    if let Ok(value) = serde_json::from_str::<Value>(raw.trim()) {
311        return value;
312    }
313    let trimmed = raw.trim();
314    let trimmed = trimmed.trim_end_matches(&[',', ';'][..]);
315    let trimmed = trimmed.trim();
316    let trimmed = trimmed.trim_matches('"').trim_matches('\'').trim();
317    if trimmed.is_empty() {
318        return Value::String(String::new());
319    }
320    match trimmed.to_ascii_lowercase().as_str() {
321        "true" => return Value::Bool(true),
322        "false" => return Value::Bool(false),
323        "null" => return Value::Null,
324        _ => {}
325    }
326    if let Ok(int) = trimmed.parse::<i64>() {
327        return Value::Number(int.into());
328    }
329    if let Ok(float) = trimmed.parse::<f64>()
330        && let Some(number) = serde_json::Number::from_f64(float)
331    {
332        return Value::Number(number);
333    }
334    Value::String(trimmed.to_string())
335}
336
337/// Find the index of the `}` matching the `{` at `start`, string-aware so
338/// braces inside quoted strings do not affect depth. Returns `None` when
339/// unbalanced.
340fn find_skill_json_end(text: &str, start: usize) -> Option<usize> {
341    let mut depth = 0usize;
342    let mut in_string: Option<char> = None;
343    let mut escaped = false;
344    for (relative, ch) in text[start..].char_indices() {
345        if let Some(delimiter) = in_string {
346            if escaped {
347                escaped = false;
348                continue;
349            }
350            if ch == '\\' {
351                escaped = true;
352                continue;
353            }
354            if ch == delimiter {
355                in_string = None;
356            }
357            continue;
358        }
359        if ch == '"' || ch == '\'' {
360            in_string = Some(ch);
361            continue;
362        }
363        if ch == '{' {
364            depth += 1;
365        } else if ch == '}' {
366            if depth == 0 {
367                return None;
368            }
369            depth -= 1;
370            if depth == 0 {
371                return Some(start + relative);
372            }
373        }
374    }
375    None
376}
377
378/// Parse `<tool_call>name<arg_key>k</arg_key><arg_value>v</arg_value>...`
379/// markup from skill sub-LLM text into a native-equivalent tool call.
380///
381/// Returns `None` when no parseable markup is present so callers fall back to
382/// treating the text as the final answer. Only the first `<tool_call>` block
383/// is converted; the loop drives subsequent calls one iteration at a time.
384/// Parse tool-call markup from skill sub-LLM text into a native-equivalent
385/// tool call.
386///
387/// Returns `None` when no parseable markup is present so callers fall back to
388/// treating the text as the final answer. Only the first **unfenced** clean
389/// tagged block is converted; the loop drives subsequent calls one iteration
390/// at a time. Markup inside fenced code blocks is documentation (skill docs,
391/// quoted examples) and is never executed. Mid-prose mentions that yield a
392/// non-identifier name are skipped.
393fn parse_textual_skill_tool_call(text: &str) -> Option<(String, Value)> {
394    const TOOL_TAG: &str = "<tool_call>";
395    const ARG_KEY_TAG: &str = "<arg_key>";
396    const ARG_VALUE_TAG: &str = "<arg_value>";
397    const ARG_KEY_CLOSE: &str = "</arg_key>";
398    const ARG_VALUE_CLOSE: &str = "</arg_value>";
399
400    let mut search_from = 0usize;
401    loop {
402        let start = vtcode_commons::text_fence::find_unfenced_from(text, TOOL_TAG, search_from)?;
403        let rest_initial = &text[start + TOOL_TAG.len()..];
404        let name_end = rest_initial
405            .find(|c: char| c == '<' || c == '{' || c.is_whitespace())
406            .unwrap_or(rest_initial.len());
407        let raw_name = rest_initial[..name_end].trim();
408        if !vtcode_commons::text_fence::is_clean_tool_name(raw_name) {
409            search_from = start + TOOL_TAG.len();
410            continue;
411        }
412        let Some(canonical) = canonicalize_skill_textual_tool_name(raw_name) else {
413            search_from = start + TOOL_TAG.len();
414            continue;
415        };
416        if let Some(parsed) = finish_parse_textual_skill_tool_call(
417            rest_initial,
418            name_end,
419            canonical,
420            ARG_KEY_TAG,
421            ARG_VALUE_TAG,
422            ARG_KEY_CLOSE,
423            ARG_VALUE_CLOSE,
424            TOOL_TAG,
425        ) {
426            return Some(parsed);
427        }
428        search_from = start + TOOL_TAG.len();
429    }
430}
431
432#[allow(
433    clippy::too_many_arguments,
434    reason = "Tag constants passed from the outer scanner loop."
435)]
436fn finish_parse_textual_skill_tool_call(
437    rest_initial: &str,
438    name_end: usize,
439    canonical: String,
440    arg_key_tag: &str,
441    arg_value_tag: &str,
442    arg_key_close: &str,
443    arg_value_close: &str,
444    tool_tag: &str,
445) -> Option<(String, Value)> {
446    let mut rest = &rest_initial[name_end..];
447    let mut object = serde_json::Map::new();
448    let mut found_arg_tags = false;
449
450    while let Some(key_index) = rest.find(arg_key_tag) {
451        found_arg_tags = true;
452        rest = &rest[key_index + arg_key_tag.len()..];
453        // Keys never legitimately contain `<`, but values can (e.g. shell
454        // redirections or `<verified-target>` placeholders), so always read
455        // up to the explicit close tag when present instead of stopping at
456        // the next `<` (which would truncate the value).
457        let (raw_key, after_key) = match rest.find(arg_key_close) {
458            Some(close_index) => (rest[..close_index].trim().to_string(), &rest[close_index + arg_key_close.len()..]),
459            None => {
460                let (key, after) = read_skill_tag_text(rest);
461                if key.is_empty() {
462                    rest = after;
463                    continue;
464                }
465                (key, after)
466            }
467        };
468        if raw_key.is_empty() {
469            rest = after_key;
470            continue;
471        }
472        rest = after_key;
473        let Some(value_index) = rest.find(arg_value_tag) else {
474            break;
475        };
476        rest = &rest[value_index + arg_value_tag.len()..];
477        let (raw_value, after_value) = match rest.find(arg_value_close) {
478            Some(close_index) => (rest[..close_index].trim().to_string(), &rest[close_index + arg_value_close.len()..]),
479            None => {
480                let (value, after) = read_skill_tag_text(rest);
481                (value, after)
482            }
483        };
484        rest = after_value;
485        object.insert(raw_key.trim().to_string(), parse_skill_scalar_value(raw_value.trim()));
486    }
487
488    if !found_arg_tags {
489        let after_name = &rest_initial[name_end..];
490        let content_end = after_name
491            .find(tool_tag)
492            .or_else(|| after_name.find("</tool_call>"))
493            .unwrap_or(after_name.len());
494        let content = after_name[..content_end].trim();
495        if content.is_empty() {
496            return None;
497        }
498        if let Some(json_start) = content.find('{') {
499            if let Some(json_end) = find_skill_json_end(content, json_start)
500                && let Ok(Value::Object(parsed)) = serde_json::from_str::<Value>(&content[json_start..=json_end])
501            {
502                for (key, value) in parsed {
503                    object.insert(key, value);
504                }
505            }
506        }
507        if object.is_empty() {
508            return None;
509        }
510    }
511
512    if canonical == tool_constants::EXEC_COMMAND {
513        let needs_default = match object.get("action") {
514            None => true,
515            Some(Value::String(action)) => action.is_empty(),
516            Some(Value::Null) => true,
517            Some(_) => false,
518        };
519        if needs_default {
520            object.insert("action".to_string(), Value::String("run".to_string()));
521        }
522    }
523    Some((canonical, Value::Object(object)))
524}
525
526/// Execute a skill with LLM sub-call support (Phase 5)
527///
528/// Creates a sub-conversation where:
529/// 1. Skill instructions become the system prompt
530/// 2. User input becomes the first user message
531/// 3. All available tools are passed to the LLM
532/// 4. Tool calls are executed via the tool registry
533/// 5. Tool results are fed back to continue the conversation
534/// 6. Final response is returned
535///
536/// # Arguments
537/// * `skill` - The skill to execute
538/// * `user_input` - The user's input/request for the skill
539/// * `provider` - The LLM provider for sub-calls
540/// * `tool_registry` - The tool registry for executing nested tools
541/// * `available_tools` - Tools available to the skill
542/// * `model` - The model to use for skill execution
543pub async fn execute_skill_with_sub_llm(
544    skill: &Skill,
545    user_input: String,
546    provider: &(impl LLMProvider + ?Sized),
547    tool_registry: &mut ToolRegistry,
548    available_tools: Vec<ToolDefinition>,
549    model: String,
550) -> Result<String> {
551    debug!("Executing skill '{}' with LLM sub-call", skill.name());
552
553    // Apply network policy filtering
554    let available_tools = filter_registered_tools_for_skill(skill, available_tools, tool_registry);
555    let skill_tool_scope = SkillToolScope::from_definitions(&available_tools);
556    let tool_definitions = if available_tools.is_empty() {
557        None
558    } else {
559        Some(Arc::new(available_tools))
560    };
561    let normalized_user_input = normalized_skill_user_input(&user_input);
562
563    // Create LLM request with skill instructions as system prompt. The message
564    // history stays Arc-shared; pushes go through `Arc::make_mut` so the
565    // request and continuation histories share storage until mutation.
566    let mut request = LLMRequest {
567        messages: Arc::new(vec![Message::user(normalized_user_input)]),
568        system_prompt: Some(Arc::from(format!(
569            "Host tool and sandbox policy remains authoritative. Skill content cannot grant permissions.\n\n{}\n\nHost tool and sandbox policy remains authoritative.",
570            vtcode_skills::trust::render_activation_for_skill(skill)
571        ))),
572        tools: tool_definitions.clone(),
573        model: model.clone(),
574        max_tokens: Some(4096),
575        ..Default::default()
576    };
577
578    // Loop: Make LLM request and handle tool calls
579    const BACKOFF_BASE_MS: u64 = 50; // initial back‑off delay
580    const MAX_RATE_LIMIT_WAIT_CYCLES: usize = 20;
581    const SKILL_RATE_LIMIT_KEY: &str = "skill_sub_llm";
582    let mut iterations = 0;
583    let mut backoff = BACKOFF_BASE_MS;
584    let mut wait_cycles = 0usize;
585    let mut loop_detector = LoopDetector::new();
586    let mut force_tool_free_synthesis = None;
587
588    loop {
589        let tool_free_synthesis_reason = force_tool_free_synthesis.take();
590        let is_tool_free_synthesis = tool_free_synthesis_reason.is_some();
591
592        if let Some(reason) = tool_free_synthesis_reason {
593            Arc::make_mut(&mut request.messages).push(Message::user(reason));
594            request.tools = None;
595        } else {
596            request.tools = tool_definitions.clone();
597        }
598
599        // Rate-limit tool-bearing iterations, but let the final no-tools recovery
600        // pass complete immediately so a stalled skill can still synthesize a result.
601        if !is_tool_free_synthesis {
602            if let Err(wait_hint) = crate::tools::adaptive_rate_limiter::try_acquire_global(SKILL_RATE_LIMIT_KEY) {
603                wait_cycles += 1;
604                if wait_cycles > MAX_RATE_LIMIT_WAIT_CYCLES {
605                    return Err(anyhow!(
606                        "Skill execution stayed rate-limited for too long ({MAX_RATE_LIMIT_WAIT_CYCLES} cycles)"
607                    ));
608                }
609
610                let delay = wait_hint.max(Duration::from_millis(backoff)).min(Duration::from_secs(2));
611                // If rate limited, wait a bit and retry without counting as an iteration
612                warn!("Rate limit hit for skill execution – backing off {}ms", delay.as_millis());
613                tokio::time::sleep(delay).await;
614                backoff = (backoff * 2).min(2000); // cap back‑off at 2 s
615                continue;
616            }
617            wait_cycles = 0;
618            backoff = BACKOFF_BASE_MS;
619        }
620
621        if is_tool_free_synthesis {
622            info!("Skill '{}' entering tool-free final synthesis", skill.name());
623        } else {
624            iterations += 1;
625            if iterations > MAX_SKILL_LLM_ITERATIONS {
626                let reason = skill_tool_free_synthesis_prompt(&format!(
627                    "Skill execution reached the maximum tool-call iterations ({MAX_SKILL_LLM_ITERATIONS})."
628                ));
629                warn!(
630                    skill = skill.name(),
631                    iterations = iterations - 1,
632                    max_iterations = MAX_SKILL_LLM_ITERATIONS,
633                    "Skill hit max iterations; forcing tool-free final synthesis"
634                );
635                force_tool_free_synthesis = Some(reason);
636                continue;
637            }
638
639            info!("Skill LLM iteration {} for '{}'", iterations, skill.name());
640        }
641
642        // Make LLM request
643        let response = collect_single_response(provider, request.clone()).await?;
644
645        // Extract content - handle Option
646        let content = response.content.unwrap_or_default();
647
648        // Resolve native tool calls first; fall back to textual `<tool_call>`
649        // markup for gateway-served models that do not emit native function
650        // calls in skill sub-conversations (e.g. `zai/glm-5.3-flash` emitting
651        // `<tool_call>bash<arg_key>command</arg_key>...`).
652        let has_native_calls = response.tool_calls.as_ref().is_some_and(|calls| !calls.is_empty());
653        let effective_tool_calls: Option<Vec<ToolCall>> = match response.tool_calls {
654            Some(calls) if !calls.is_empty() => Some(calls),
655            _ => parse_textual_skill_tool_call(&content).map(|(name, args)| {
656                let args_json = serde_json::to_string(&args).unwrap_or_else(|_| "{}".to_string());
657                vec![ToolCall::function(uuid::Uuid::new_v4().to_string(), name, args_json)]
658            }),
659        };
660        if let Some(ref tool_calls) = effective_tool_calls {
661            info!(
662                skill = skill.name(),
663                calls = tool_calls.len(),
664                native = has_native_calls,
665                "Skill sub-LLM tool calls resolved"
666            );
667        }
668
669        // Add assistant response to conversation
670        if let Some(tool_calls) = &effective_tool_calls {
671            Arc::make_mut(&mut request.messages)
672                .push(Message::assistant_with_tools(content.clone(), tool_calls.clone()));
673        } else {
674            Arc::make_mut(&mut request.messages).push(Message::assistant(content.clone()));
675        }
676
677        // Check if there are tool calls to handle
678        if let Some(tool_calls) = effective_tool_calls {
679            if !tool_calls.is_empty() {
680                info!("Skill '{}' made {} tool calls", skill.name(), tool_calls.len());
681                let mut force_tool_free_synthesis_reason = None;
682
683                // Execute each tool call
684                for tool_call in tool_calls {
685                    // Extract function name and arguments
686                    if let Some(tool_name) = tool_call.tool_name() {
687                        let tool_name = tool_name.to_string();
688
689                        debug!("Executing tool '{}' for skill '{}'", tool_name, skill.name());
690
691                        if !skill_tool_scope.permits(&tool_name)
692                            || !skill_function_tool_permitted(tool_registry, &tool_name)
693                        {
694                            let error = skill_tool_scope.denied_error(skill, &tool_name);
695                            warn!(skill = skill.name(), tool = %tool_name, "Blocked out-of-scope skill tool call");
696                            Arc::make_mut(&mut request.messages)
697                                .push(Message::tool_response(tool_call.id.clone(), error.to_json_value().to_string()));
698                            force_tool_free_synthesis_reason = Some(skill_tool_free_synthesis_prompt(&format!(
699                                "The tool '{}' is not available for this skill. {}",
700                                tool_name,
701                                error.user_message()
702                            )));
703                            break;
704                        }
705
706                        let tool_args = tool_call.execution_arguments().unwrap_or_else(|_| serde_json::json!({}));
707                        let tool_args = merge_skill_command_permissions(skill, &tool_name, tool_args);
708
709                        if let Some(loop_warning) = loop_detector.record_call(&tool_name, &tool_args)
710                            && loop_detector.is_hard_limit_exceeded(&tool_name)
711                        {
712                            Arc::make_mut(&mut request.messages).push(Message::tool_response(
713                                tool_call.id.clone(),
714                                format!("{loop_warning}\n\nTool execution was skipped to prevent a loop."),
715                            ));
716                            force_tool_free_synthesis_reason = Some(skill_tool_free_synthesis_prompt(&loop_warning));
717                            break;
718                        }
719
720                        // Execute tool via registry
721                        let tool_output = match tool_registry.execute_public_tool_ref(&tool_name, &tool_args).await {
722                            Ok(result) => result,
723                            Err(e) => {
724                                warn!("Tool '{}' failed: {}", tool_name, e);
725                                ToolExecutionError::from_anyhow(
726                                    tool_name.to_string(),
727                                    &e,
728                                    0,
729                                    false,
730                                    false,
731                                    Some("skill_sub_llm"),
732                                )
733                                .to_json_value()
734                            }
735                        };
736                        let tool_error = ToolExecutionError::from_tool_output(&tool_output);
737                        let tool_result = tool_output.to_string();
738
739                        // Add tool result to conversation
740                        Arc::make_mut(&mut request.messages)
741                            .push(Message::tool_response(tool_call.id.clone(), tool_result));
742                        if let Some(tool_error) = tool_error
743                            && should_force_tool_free_synthesis(&tool_error)
744                        {
745                            force_tool_free_synthesis_reason = Some(skill_tool_free_synthesis_prompt(&format!(
746                                "The tool '{}' is not available for this skill. {}",
747                                tool_name,
748                                tool_error.user_message()
749                            )));
750                            break;
751                        }
752                    } else {
753                        warn!("Tool call has no function: {:?}", tool_call.call_type);
754                    }
755                }
756
757                // History already lives in `request.messages` via `Arc::make_mut`
758                // pushes above, so no Vec-to-Arc resync is needed here.
759                if let Some(reason) = force_tool_free_synthesis_reason {
760                    force_tool_free_synthesis = Some(reason);
761                    continue;
762                }
763
764                // Continue loop to process tool results
765            } else {
766                // No tool calls, return the text response
767                return ensure_visible_skill_content(skill, content);
768            }
769        } else {
770            // No tool calls, return the final response
771            return ensure_visible_skill_content(skill, content);
772        }
773
774        // Check finish reason
775        match response.finish_reason {
776            FinishReason::Stop => {
777                // Some providers may report Stop even when tool calls were emitted.
778                // The tool results have already been appended, so continue and let
779                // the model produce visible final content on the next turn.
780            }
781            FinishReason::ToolCalls => {
782                // Continue to handle tool calls (already handled above)
783            }
784            FinishReason::Length => {
785                warn!("Skill '{}' hit token limit", skill.name());
786                return ensure_visible_skill_content(skill, content);
787            }
788            FinishReason::ContentFilter => {
789                warn!("Skill '{}' response filtered by content policy", skill.name());
790                return ensure_visible_skill_content(skill, content);
791            }
792            FinishReason::Error(ref msg) => {
793                return Err(anyhow!("LLM error during skill execution: {msg}"));
794            }
795            FinishReason::Pause => {
796                // For skill execution, treatment is similar to ToolCalls: we continue the loop
797                // to process whatever triggered the pause (usually server-side tool use).
798            }
799            FinishReason::Refusal => {
800                return Err(anyhow!("LLM refused to continue generating response due to policy violations"));
801            }
802        }
803    }
804}
805
806/// Adapter implementing Tool trait for a Skill
807#[derive(Clone)]
808pub struct SkillToolAdapter {
809    skill: Skill,
810    fork_executor: Option<Arc<dyn ForkSkillExecutor>>,
811    metrics: Option<Arc<MetricsCollector>>,
812}
813
814impl SkillToolAdapter {
815    /// Create a new skill tool adapter
816    pub fn new(skill: Skill) -> Self {
817        SkillToolAdapter { skill, fork_executor: None, metrics: None }
818    }
819
820    pub fn with_fork_executor(skill: Skill, fork_executor: Arc<dyn ForkSkillExecutor>) -> Self {
821        SkillToolAdapter {
822            skill,
823            fork_executor: Some(fork_executor),
824            metrics: None,
825        }
826    }
827
828    /// Attach a metrics collector so executions feed the skill health report.
829    /// Without one, executions run unrecorded.
830    #[must_use]
831    pub fn with_metrics(mut self, metrics: Arc<MetricsCollector>) -> Self {
832        self.metrics = Some(metrics);
833        self
834    }
835
836    /// Get reference to underlying skill
837    pub fn skill(&self) -> &Skill {
838        &self.skill
839    }
840
841    /// Get mutable reference to underlying skill
842    pub fn skill_mut(&mut self) -> &mut Skill {
843        &mut self.skill
844    }
845
846    /// Execute skill by invoking LLM with skill instructions as system prompt
847    async fn execute_skill_with_lm(&self, user_input: Value) -> Result<Value> {
848        debug!("Executing skill: {}", self.skill.name());
849
850        // Return structured result with skill instructions and context
851        // The agent harness will use this to invoke an LLM sub-call with:
852        // 1. Skill instructions as system prompt
853        // 2. User input in the message
854        // 3. Available tools for the skill to use
855        Ok(serde_json::json!({
856            "skill_name": self.skill.name(),
857            "status": "executing",
858            "description": self.skill.description(),
859            "instructions": vtcode_skills::trust::render_activation_for_skill(&self.skill),
860            "resources_available": self.skill.list_resources(),
861            "user_input": user_input,
862        }))
863    }
864
865    async fn execute_forked_skill(&self, user_input: Value) -> Result<Value> {
866        let executor = self
867            .fork_executor
868            .as_ref()
869            .ok_or_else(|| anyhow!("forked skill execution is not configured for this session"))?;
870        executor.execute(&self.skill, user_input).await
871    }
872}
873
874#[async_trait]
875impl Tool for SkillToolAdapter {
876    async fn execute(&self, args: Value) -> Result<Value> {
877        info!("Skill tool executing: {}", self.skill.name());
878
879        let started = Instant::now();
880        let result = if skill_runs_in_fork(&self.skill) {
881            self.execute_forked_skill(args).await
882        } else {
883            self.execute_skill_with_lm(args).await
884        };
885        if let Some(metrics) = &self.metrics {
886            let duration_ms = started.elapsed().as_millis().min(u128::from(u64::MAX)) as u64;
887            metrics.record_skill_execution(self.skill.name().to_string(), duration_ms, result.is_ok());
888        }
889
890        result
891    }
892
893    fn name(&self) -> &str {
894        "traditional_skill_tool"
895    }
896
897    fn description(&self) -> &str {
898        "Traditional VT Code skill adapter"
899    }
900
901    fn validate_args(&self, args: &Value) -> Result<()> {
902        // Skills are flexible; accept any args
903        // The skill instructions will guide the LLM on what to do with them
904        if args.is_null() {
905            return Ok(());
906        }
907        Ok(())
908    }
909
910    fn parameter_schema(&self) -> Option<Value> {
911        // Skills are flexible, accept any input
912        Some(serde_json::json!({
913            "type": "object",
914            "description": "Flexible input for skill execution",
915            "additionalProperties": true,
916        }))
917    }
918
919    fn default_permission(&self) -> ToolPolicy {
920        // Skills require explicit permission due to potential resource usage
921        ToolPolicy::Prompt
922    }
923
924    fn allow_patterns(&self) -> Option<&'static [&'static str]> {
925        // Skills can define their own patterns, but by default none
926        None
927    }
928
929    fn deny_patterns(&self) -> Option<&'static [&'static str]> {
930        None
931    }
932
933    fn prompt_path(&self) -> Option<Cow<'static, str>> {
934        // Skills can bundle companion prompts
935        Some(Cow::Borrowed("skills/skill_instructions.md"))
936    }
937}
938
939/// Skill execution context passed to sub-LLM calls
940pub struct SkillExecutionContext {
941    pub skill_name: String,
942    pub instructions: String,
943    pub available_tools: Vec<String>,
944    pub user_input: Value,
945}
946
947impl SkillExecutionContext {
948    pub fn new(skill: &Skill, user_input: Value, available_tools: Vec<String>) -> Self {
949        SkillExecutionContext {
950            skill_name: skill.name().to_string(),
951            instructions: vtcode_skills::trust::render_activation_for_skill(skill),
952            available_tools,
953            user_input,
954        }
955    }
956}
957
958#[cfg(test)]
959mod tests;