2026-07-11 13:16:10 +07:00
|
|
|
use tokio::sync::mpsc;
|
2026-07-11 18:23:01 +07:00
|
|
|
use crate::dto::chat::message::ChatMessage;
|
2026-07-12 03:14:52 +07:00
|
|
|
use crate::dto::provider::request::ToolDef;
|
|
|
|
|
use crate::tool::{all_tools, tool_defs, tool_is_risky};
|
2026-07-11 13:16:10 +07:00
|
|
|
use super::context::SubagentContext;
|
|
|
|
|
use super::event::SubagentEvent;
|
|
|
|
|
|
2026-07-12 10:23:26 +07:00
|
|
|
#[allow(dead_code)]
|
2026-07-12 04:01:10 +07:00
|
|
|
pub const MAX_AGENT_STEPS: usize = usize::MAX;
|
2026-07-11 13:16:10 +07:00
|
|
|
|
2026-07-12 03:14:52 +07:00
|
|
|
/// Maps a subagent's allowed tool names to concrete Tool trait objects and
|
|
|
|
|
/// OpenAI-style tool definitions. When `allowed_tools` is empty every tool is
|
|
|
|
|
/// available; otherwise only explicitly allowed ones are included.
|
|
|
|
|
fn build_subagent_tools(allowed_tools: &[String]) -> (Vec<Box<dyn crate::tool::Tool>>, Vec<ToolDef>) {
|
|
|
|
|
let all = all_tools();
|
|
|
|
|
let filtered: Vec<Box<dyn crate::tool::Tool>> = if allowed_tools.is_empty() {
|
|
|
|
|
all
|
|
|
|
|
} else {
|
|
|
|
|
all.into_iter()
|
|
|
|
|
.filter(|t| allowed_tools.contains(&t.name().to_string()))
|
|
|
|
|
.collect()
|
|
|
|
|
};
|
|
|
|
|
let defs = tool_defs(&filtered);
|
|
|
|
|
(filtered, defs)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Resolves the API key, model, and base URL from the persisted application
|
|
|
|
|
/// configuration rather than environment variables, matching how the main agent
|
|
|
|
|
/// resolves its credentials.
|
|
|
|
|
fn resolve_provider_config() -> (String, String, Option<String>) {
|
|
|
|
|
let settings = crate::model::settings::Settings::load();
|
|
|
|
|
let app_config = crate::model::app_config::AppConfig::load();
|
|
|
|
|
|
2026-07-12 10:50:34 +07:00
|
|
|
let mut api_key = settings.api_keys.get(&settings.provider).cloned().unwrap_or_else(|| {
|
2026-07-12 10:57:32 +07:00
|
|
|
tracing::warn!("[subagent] no API key for provider '{}' in settings, trying env/default", settings.provider);
|
2026-07-12 10:50:34 +07:00
|
|
|
String::new()
|
|
|
|
|
});
|
2026-07-12 03:14:52 +07:00
|
|
|
let model = settings.model.clone();
|
|
|
|
|
let base_url = app_config.providers.get(&settings.provider)
|
|
|
|
|
.map(|p| p.api_base.clone());
|
|
|
|
|
|
|
|
|
|
if api_key.is_empty() {
|
|
|
|
|
if let Some(provider_cfg) = app_config.providers.get(&settings.provider) {
|
|
|
|
|
api_key = provider_cfg.api_key_env.as_ref()
|
|
|
|
|
.and_then(|env| std::env::var(env).ok())
|
|
|
|
|
.or_else(|| provider_cfg.default_api_key.clone())
|
2026-07-12 10:50:34 +07:00
|
|
|
.unwrap_or_else(|| {
|
2026-07-12 10:57:32 +07:00
|
|
|
tracing::warn!("[subagent] all API key resolution paths exhausted for '{}'", settings.provider);
|
2026-07-12 10:50:34 +07:00
|
|
|
String::new()
|
|
|
|
|
});
|
2026-07-11 18:23:01 +07:00
|
|
|
}
|
|
|
|
|
}
|
2026-07-12 03:14:52 +07:00
|
|
|
|
|
|
|
|
(api_key, model, base_url)
|
2026-07-11 18:23:01 +07:00
|
|
|
}
|
|
|
|
|
|
2026-07-11 13:16:10 +07:00
|
|
|
pub fn run_subagent(ctx: SubagentContext, tx: mpsc::Sender<SubagentEvent>) -> anyhow::Result<String> {
|
|
|
|
|
let mut output = String::new();
|
2026-07-11 18:23:01 +07:00
|
|
|
let mut messages: Vec<ChatMessage> = Vec::new();
|
|
|
|
|
messages.push(ChatMessage::system(ctx.system_prompt.clone()));
|
|
|
|
|
|
2026-07-11 20:21:59 +07:00
|
|
|
let tool_ctx = crate::tool::ToolCtx::builder()
|
|
|
|
|
.session_dir(ctx.session_dir.clone())
|
|
|
|
|
.origin(crate::app::state::types::Origin::SubAgent)
|
|
|
|
|
.build();
|
|
|
|
|
|
2026-07-12 03:14:52 +07:00
|
|
|
// Build tool list once before the loop
|
|
|
|
|
let (tools, tdefs) = build_subagent_tools(&ctx.allowed_tools);
|
|
|
|
|
let tdefs_opt: Option<Vec<ToolDef>> = if tdefs.is_empty() { None } else { Some(tdefs) };
|
|
|
|
|
|
2026-07-12 10:23:26 +07:00
|
|
|
for step in 0..ctx.max_steps {
|
2026-07-12 03:14:52 +07:00
|
|
|
let (api_key, model, base_url) = resolve_provider_config();
|
|
|
|
|
let client = crate::service::provider::LlmClient::new(api_key, model, base_url);
|
2026-07-11 18:23:01 +07:00
|
|
|
|
2026-07-12 03:14:52 +07:00
|
|
|
// Use the structured tool-calling API so the LLM can request tools with
|
|
|
|
|
// proper arguments, exactly like the main agent does.
|
|
|
|
|
let (response, _usage) = match client.chat_with_tools_non_streaming(&messages, tdefs_opt.clone()) {
|
|
|
|
|
Ok(result) => result,
|
2026-07-11 18:23:01 +07:00
|
|
|
Err(e) => {
|
|
|
|
|
let _ = tx.blocking_send(SubagentEvent::StepFailed {
|
2026-07-11 23:45:13 +07:00
|
|
|
_step: step,
|
|
|
|
|
_error: e.to_string(),
|
2026-07-11 18:23:01 +07:00
|
|
|
});
|
|
|
|
|
anyhow::bail!("subagent call failed at step {}: {}", step, e);
|
|
|
|
|
}
|
2026-07-11 13:16:10 +07:00
|
|
|
};
|
2026-07-11 18:23:01 +07:00
|
|
|
|
2026-07-12 03:14:52 +07:00
|
|
|
let has_tool_calls = response.tool_calls.is_some()
|
|
|
|
|
&& response.tool_calls.as_ref().is_some_and(|tc| !tc.is_empty());
|
2026-07-11 18:23:01 +07:00
|
|
|
|
2026-07-12 03:14:52 +07:00
|
|
|
let content = response.content.clone().unwrap_or_default();
|
|
|
|
|
|
|
|
|
|
if has_tool_calls {
|
|
|
|
|
let tool_calls = response.tool_calls.clone().unwrap_or_default();
|
|
|
|
|
// Push the assistant message with tool_calls into the conversation
|
|
|
|
|
messages.push(response);
|
|
|
|
|
|
|
|
|
|
for tool_call in &tool_calls {
|
|
|
|
|
let tool_name = &tool_call.function.name;
|
|
|
|
|
let args = crate::dto::chat::tool::sanitize_tool_arguments(&tool_call.function.arguments);
|
2026-07-11 20:21:59 +07:00
|
|
|
let explicitly_allowed = ctx.allowed_tools.contains(tool_name);
|
|
|
|
|
let generally_allowed = ctx.allowed_tools.is_empty() || explicitly_allowed;
|
|
|
|
|
|
2026-07-12 03:14:52 +07:00
|
|
|
let _ = tx.blocking_send(SubagentEvent::ToolCall {
|
|
|
|
|
_tool: tool_name.clone(),
|
|
|
|
|
_args: args.clone(),
|
|
|
|
|
});
|
|
|
|
|
|
2026-07-11 20:21:59 +07:00
|
|
|
if !generally_allowed {
|
2026-07-11 18:23:01 +07:00
|
|
|
let msg = format!("tool '{}' not allowed for this subagent", tool_name);
|
2026-07-12 03:14:52 +07:00
|
|
|
messages.push(ChatMessage::tool_result(tool_call.id.clone(), msg.clone()));
|
2026-07-11 20:21:59 +07:00
|
|
|
let _ = tx.blocking_send(SubagentEvent::ToolResult {
|
2026-07-11 23:45:13 +07:00
|
|
|
_tool: tool_name.clone(),
|
|
|
|
|
_output: msg,
|
2026-07-11 20:21:59 +07:00
|
|
|
});
|
2026-07-11 18:23:01 +07:00
|
|
|
continue;
|
|
|
|
|
}
|
2026-07-11 20:21:59 +07:00
|
|
|
|
|
|
|
|
if tool_is_risky(tool_name) && !explicitly_allowed {
|
|
|
|
|
let msg = format!("risky tool '{}' requires explicit permission; not allowed for this subagent", tool_name);
|
2026-07-12 03:14:52 +07:00
|
|
|
messages.push(ChatMessage::tool_result(tool_call.id.clone(), msg.clone()));
|
2026-07-11 20:21:59 +07:00
|
|
|
let _ = tx.blocking_send(SubagentEvent::ToolResult {
|
2026-07-11 23:45:13 +07:00
|
|
|
_tool: tool_name.clone(),
|
|
|
|
|
_output: msg,
|
2026-07-11 20:21:59 +07:00
|
|
|
});
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-12 03:14:52 +07:00
|
|
|
let result = match tools.iter().find(|t| t.name() == tool_name.as_str()) {
|
|
|
|
|
Some(tool) => tool.run(&tool_ctx, &args),
|
2026-07-11 20:21:59 +07:00
|
|
|
None => Err(anyhow::anyhow!("tool '{}' not found", tool_name)),
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
match result {
|
|
|
|
|
Ok(output_text) => {
|
2026-07-12 03:14:52 +07:00
|
|
|
messages.push(ChatMessage::tool_result(tool_call.id.clone(), output_text.clone()));
|
2026-07-11 20:21:59 +07:00
|
|
|
let _ = tx.blocking_send(SubagentEvent::ToolResult {
|
2026-07-11 23:45:13 +07:00
|
|
|
_tool: tool_name.clone(),
|
|
|
|
|
_output: output_text,
|
2026-07-11 20:21:59 +07:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
Err(e) => {
|
|
|
|
|
let msg = format!("tool '{}' failed: {}", tool_name, e);
|
2026-07-12 03:14:52 +07:00
|
|
|
messages.push(ChatMessage::tool_result(tool_call.id.clone(), msg.clone()));
|
2026-07-11 20:21:59 +07:00
|
|
|
let _ = tx.blocking_send(SubagentEvent::ToolResult {
|
2026-07-11 23:45:13 +07:00
|
|
|
_tool: tool_name.clone(),
|
|
|
|
|
_output: msg,
|
2026-07-11 20:21:59 +07:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-07-11 18:23:01 +07:00
|
|
|
}
|
2026-07-12 03:14:52 +07:00
|
|
|
} else {
|
|
|
|
|
// Text-only response — accumulate and finish
|
|
|
|
|
if !content.is_empty() {
|
|
|
|
|
output.push_str(&content);
|
|
|
|
|
output.push('\n');
|
|
|
|
|
}
|
2026-07-11 18:23:01 +07:00
|
|
|
let _ = tx.blocking_send(SubagentEvent::StepCompleted {
|
2026-07-11 23:45:13 +07:00
|
|
|
_step: step,
|
2026-07-12 03:14:52 +07:00
|
|
|
_output: content.clone(),
|
2026-07-11 18:23:01 +07:00
|
|
|
});
|
2026-07-12 03:14:52 +07:00
|
|
|
// Break only when we got real content; empty means something went wrong
|
|
|
|
|
if !content.is_empty() {
|
|
|
|
|
break;
|
|
|
|
|
}
|
2026-07-11 18:23:01 +07:00
|
|
|
}
|
2026-07-11 13:16:10 +07:00
|
|
|
}
|
2026-07-11 18:23:01 +07:00
|
|
|
|
2026-07-11 23:45:13 +07:00
|
|
|
let _ = tx.blocking_send(SubagentEvent::Completed { _output: output.clone() });
|
2026-07-11 13:16:10 +07:00
|
|
|
Ok(output)
|
|
|
|
|
}
|