feat(ai): add Claude Code CLI provider
This commit is contained in:
1 parent
89fca90dbc
commit
d3947d246c
28 files changed
+1723
-176
No files matched your search
@@ -101,7 +101,7 @@ pub async fn run_agent_loop(
|
||||
let contract_system_prompt = augment_system_prompt_with_task_contract(system_prompt, task_contract, is_agent_mode);
|
||||
let system_prompt = contract_system_prompt.as_str();
|
||||
|
||||
if matches!(config.provider, AiProvider::CodexCli) {
|
||||
if matches!(config.provider, AiProvider::CodexCli | AiProvider::ClaudeCodeCli) {
|
||||
let connection_name = {
|
||||
let configs = agent_ctx.state.configs.read().await;
|
||||
configs
|
||||
@@ -109,24 +109,27 @@ pub async fn run_agent_loop(
|
||||
.map(|config| config.name.clone())
|
||||
.unwrap_or_else(|| agent_ctx.connection_id.clone())
|
||||
};
|
||||
let options = crate::ai_cli_agent::CliAgentRunOptions {
|
||||
connection_id: agent_ctx.connection_id.clone(),
|
||||
connection_name,
|
||||
database: agent_ctx.database.clone(),
|
||||
agent_mode: is_agent_mode,
|
||||
allow_writes: agent_ctx.sql_permissions.allow_writes,
|
||||
allow_dangerous: agent_ctx.sql_permissions.allow_dangerous,
|
||||
mcp_server_command: agent_ctx.cli_mcp_server_command.clone(),
|
||||
};
|
||||
if matches!(config.provider, AiProvider::ClaudeCodeCli) {
|
||||
let prompt = crate::ai_claude_code_cli::build_claude_code_prompt(
|
||||
system_prompt,
|
||||
messages,
|
||||
agent_ctx.sql_permissions.allow_writes,
|
||||
);
|
||||
return crate::ai_claude_code_cli::run_claude_code_agent(config, &prompt, options, cancelled, on_event)
|
||||
.await;
|
||||
}
|
||||
let prompt =
|
||||
crate::ai_codex_cli::build_codex_prompt(system_prompt, messages, agent_ctx.sql_permissions.allow_writes);
|
||||
return crate::ai_codex_cli::run_codex_agent(
|
||||
config,
|
||||
&prompt,
|
||||
crate::ai_codex_cli::CodexRunOptions {
|
||||
connection_id: agent_ctx.connection_id.clone(),
|
||||
connection_name,
|
||||
database: agent_ctx.database.clone(),
|
||||
agent_mode: is_agent_mode,
|
||||
allow_writes: agent_ctx.sql_permissions.allow_writes,
|
||||
allow_dangerous: agent_ctx.sql_permissions.allow_dangerous,
|
||||
mcp_server_command: agent_ctx.cli_mcp_server_command.clone(),
|
||||
},
|
||||
cancelled,
|
||||
on_event,
|
||||
)
|
||||
.await;
|
||||
return crate::ai_codex_cli::run_codex_agent(config, &prompt, options, cancelled, on_event).await;
|
||||
}
|
||||
|
||||
// Auto-degrade: providers without function calling fall back to text-only completion.
|
||||
|
||||
+110
-16
@@ -61,6 +61,8 @@ pub enum AiProvider {
|
||||
OpenaiCompatible,
|
||||
#[serde(rename = "codex-cli")]
|
||||
CodexCli,
|
||||
#[serde(rename = "claude-code-cli")]
|
||||
ClaudeCodeCli,
|
||||
Custom,
|
||||
}
|
||||
|
||||
@@ -74,6 +76,7 @@ impl AiProvider {
|
||||
AiProvider::Qwen => "qwen",
|
||||
AiProvider::Ollama => "ollama",
|
||||
AiProvider::OpenaiCompatible => "openai-compatible",
|
||||
AiProvider::ClaudeCodeCli => "claude-code-cli",
|
||||
AiProvider::CodexCli => "codex-cli",
|
||||
AiProvider::Custom => "custom",
|
||||
}
|
||||
@@ -107,6 +110,8 @@ pub enum AiReasoningLevel {
|
||||
Low,
|
||||
Medium,
|
||||
High,
|
||||
Xhigh,
|
||||
Max,
|
||||
}
|
||||
|
||||
impl AiReasoningLevel {
|
||||
@@ -117,6 +122,43 @@ impl AiReasoningLevel {
|
||||
AiReasoningLevel::Low => Some("low"),
|
||||
AiReasoningLevel::Medium => Some("medium"),
|
||||
AiReasoningLevel::High => Some("high"),
|
||||
AiReasoningLevel::Xhigh | AiReasoningLevel::Max => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_claude_code_effort(&self) -> Option<&'static str> {
|
||||
match self {
|
||||
AiReasoningLevel::Default | AiReasoningLevel::Minimal => None,
|
||||
AiReasoningLevel::Low => Some("low"),
|
||||
AiReasoningLevel::Medium => Some("medium"),
|
||||
AiReasoningLevel::High => Some("high"),
|
||||
AiReasoningLevel::Xhigh => Some("xhigh"),
|
||||
AiReasoningLevel::Max => Some("max"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum AiEffortLevel {
|
||||
Low,
|
||||
Medium,
|
||||
High,
|
||||
Xhigh,
|
||||
Max,
|
||||
}
|
||||
|
||||
impl std::str::FromStr for AiEffortLevel {
|
||||
type Err = ();
|
||||
|
||||
fn from_str(value: &str) -> Result<Self, Self::Err> {
|
||||
match value {
|
||||
"low" => Ok(Self::Low),
|
||||
"medium" => Ok(Self::Medium),
|
||||
"high" => Ok(Self::High),
|
||||
"xhigh" => Ok(Self::Xhigh),
|
||||
"max" => Ok(Self::Max),
|
||||
_ => Err(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -144,6 +186,8 @@ pub struct AiModelListItem {
|
||||
pub name: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub label: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub supported_effort_levels: Vec<AiEffortLevel>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -176,6 +220,10 @@ pub struct AiConfig {
|
||||
pub codex_cli_path: Option<String>,
|
||||
#[serde(default)]
|
||||
pub codex_cli_env: HashMap<String, String>,
|
||||
#[serde(default)]
|
||||
pub claude_code_cli_path: Option<String>,
|
||||
#[serde(default)]
|
||||
pub claude_code_cli_env: HashMap<String, String>,
|
||||
}
|
||||
|
||||
fn default_enable_thinking() -> bool {
|
||||
@@ -273,6 +321,14 @@ pub struct AiModelInfo {
|
||||
pub id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub display_name: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub supported_effort_levels: Vec<AiEffortLevel>,
|
||||
}
|
||||
|
||||
impl AiModelInfo {
|
||||
pub fn new(id: impl Into<String>, display_name: Option<String>) -> Self {
|
||||
Self { id: id.into(), display_name, supported_effort_levels: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of an AI connection test (mirrors CC-Switch's StreamCheckResult).
|
||||
@@ -358,7 +414,7 @@ pub fn resolve_endpoint(config: &AiConfig) -> String {
|
||||
format!("{base}/chat/completions")
|
||||
}
|
||||
}
|
||||
AiProvider::Claude | AiProvider::CodexCli | AiProvider::Gemini => unreachable!(),
|
||||
AiProvider::Claude | AiProvider::CodexCli | AiProvider::ClaudeCodeCli | AiProvider::Gemini => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -746,7 +802,7 @@ fn emit_responses_function_call_item(
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn validate_config(config: &AiConfig) -> Result<(), String> {
|
||||
if matches!(config.provider, AiProvider::CodexCli) {
|
||||
if matches!(config.provider, AiProvider::CodexCli | AiProvider::ClaudeCodeCli) {
|
||||
return Ok(());
|
||||
}
|
||||
if !matches!(config.provider, AiProvider::Ollama) && config.api_key.trim().is_empty() {
|
||||
@@ -762,7 +818,7 @@ fn validate_config(config: &AiConfig) -> Result<(), String> {
|
||||
}
|
||||
|
||||
fn validate_model_list_config(config: &AiConfig) -> Result<(), String> {
|
||||
if matches!(config.provider, AiProvider::CodexCli) {
|
||||
if matches!(config.provider, AiProvider::CodexCli | AiProvider::ClaudeCodeCli) {
|
||||
return Ok(());
|
||||
}
|
||||
if !matches!(config.provider, AiProvider::Ollama) && config.api_key.trim().is_empty() {
|
||||
@@ -854,7 +910,7 @@ fn parse_model_list_response(data: &serde_json::Value) -> Result<Vec<AiModelInfo
|
||||
.filter(|name| !name.trim().is_empty() && *name != id)
|
||||
.map(ToString::to_string);
|
||||
|
||||
models.push(AiModelInfo { id: id.to_string(), display_name });
|
||||
models.push(AiModelInfo::new(id, display_name));
|
||||
}
|
||||
|
||||
Ok(models)
|
||||
@@ -901,6 +957,9 @@ pub async fn list_models_core(config: &AiConfig) -> Result<Vec<AiModelInfo>, Str
|
||||
if matches!(config.provider, AiProvider::CodexCli) {
|
||||
return crate::ai_codex_cli::list_codex_models(config).await;
|
||||
}
|
||||
if matches!(config.provider, AiProvider::ClaudeCodeCli) {
|
||||
return crate::ai_claude_code_cli::list_claude_code_models(config).await;
|
||||
}
|
||||
validate_model_list_config(config)?;
|
||||
|
||||
let client = build_ai_http_client(config, 30)?;
|
||||
@@ -919,7 +978,7 @@ pub async fn list_models_core(config: &AiConfig) -> Result<Vec<AiModelInfo>, Str
|
||||
list_openai_compatible_models(&client, config).await
|
||||
}
|
||||
}
|
||||
AiProvider::CodexCli => unreachable!(),
|
||||
AiProvider::CodexCli | AiProvider::ClaudeCodeCli => unreachable!(),
|
||||
AiProvider::Gemini => {
|
||||
Err("Model listing is only supported for OpenAI-compatible and Claude providers".to_string())
|
||||
}
|
||||
@@ -1133,6 +1192,9 @@ pub async fn test_connection_core(config: &AiConfig) -> Result<AiTestConnectionR
|
||||
if matches!(config.provider, AiProvider::CodexCli) {
|
||||
return crate::ai_codex_cli::test_codex_connection(config).await;
|
||||
}
|
||||
if matches!(config.provider, AiProvider::ClaudeCodeCli) {
|
||||
return crate::ai_claude_code_cli::test_claude_code_connection(config).await;
|
||||
}
|
||||
validate_config(config)?;
|
||||
|
||||
let client = build_ai_http_client(config, 15)?;
|
||||
@@ -1308,8 +1370,8 @@ fn classify_error(msg: &str) -> &'static str {
|
||||
pub async fn complete(request: &AiCompletionRequest) -> Result<String, String> {
|
||||
validate_config(&request.config)?;
|
||||
|
||||
if matches!(request.config.provider, AiProvider::CodexCli) {
|
||||
return Err("Codex CLI provider is only supported in DBX AI agent mode".to_string());
|
||||
if matches!(request.config.provider, AiProvider::CodexCli | AiProvider::ClaudeCodeCli) {
|
||||
return Err("CLI providers are only supported in DBX AI agent mode".to_string());
|
||||
}
|
||||
|
||||
let client = build_ai_http_client(&request.config, 60)?;
|
||||
@@ -1317,7 +1379,7 @@ pub async fn complete(request: &AiCompletionRequest) -> Result<String, String> {
|
||||
match request.config.provider {
|
||||
AiProvider::Claude => call_claude(&client, request.clone()).await,
|
||||
AiProvider::Gemini => call_gemini(&client, request.clone()).await,
|
||||
AiProvider::CodexCli => unreachable!(),
|
||||
AiProvider::CodexCli | AiProvider::ClaudeCodeCli => unreachable!(),
|
||||
AiProvider::Openai
|
||||
| AiProvider::Deepseek
|
||||
| AiProvider::Qwen
|
||||
@@ -1353,8 +1415,8 @@ pub async fn stream(
|
||||
) -> Result<(), String> {
|
||||
validate_config(&request.config)?;
|
||||
|
||||
if matches!(request.config.provider, AiProvider::CodexCli) {
|
||||
return Err("Codex CLI provider is only supported in DBX AI agent mode".to_string());
|
||||
if matches!(request.config.provider, AiProvider::CodexCli | AiProvider::ClaudeCodeCli) {
|
||||
return Err("CLI providers are only supported in DBX AI agent mode".to_string());
|
||||
}
|
||||
|
||||
let stream_timeout = if request.config.enable_thinking { 600 } else { 120 };
|
||||
@@ -1363,7 +1425,7 @@ pub async fn stream(
|
||||
match request.config.provider {
|
||||
AiProvider::Claude => stream_claude(&client, session_id, request, cancelled, &on_chunk).await,
|
||||
AiProvider::Gemini => stream_gemini(&client, session_id, request, cancelled, &on_chunk).await,
|
||||
AiProvider::CodexCli => unreachable!(),
|
||||
AiProvider::CodexCli | AiProvider::ClaudeCodeCli => unreachable!(),
|
||||
AiProvider::Openai
|
||||
| AiProvider::Deepseek
|
||||
| AiProvider::Qwen
|
||||
@@ -2422,6 +2484,9 @@ pub async fn stream_with_tools(
|
||||
on_chunk: impl Fn(AiStreamChunk),
|
||||
) -> Result<(Vec<crate::agent_events::ToolCall>, Option<TokenUsage>), String> {
|
||||
validate_config(config)?;
|
||||
if matches!(config.provider, AiProvider::CodexCli | AiProvider::ClaudeCodeCli) {
|
||||
return Err("CLI providers are only supported through the DBX AI agent loop".to_string());
|
||||
}
|
||||
|
||||
let stream_timeout = if config.enable_thinking { 600 } else { 120 };
|
||||
let client = build_ai_http_client(config, stream_timeout)?;
|
||||
@@ -2606,6 +2671,8 @@ mod tests {
|
||||
assert_eq!(config.proxy_url, "");
|
||||
assert!(config.enable_thinking);
|
||||
assert_eq!(config.auth_method, AiAuthMethod::ApiKey);
|
||||
assert!(config.claude_code_cli_path.is_none());
|
||||
assert!(config.claude_code_cli_env.is_empty());
|
||||
assert!(config.codex_cli_env.is_empty());
|
||||
}
|
||||
|
||||
@@ -2626,6 +2693,8 @@ mod tests {
|
||||
context_window: None,
|
||||
codex_cli_path: None,
|
||||
codex_cli_env: Default::default(),
|
||||
claude_code_cli_path: None,
|
||||
claude_code_cli_env: Default::default(),
|
||||
};
|
||||
|
||||
let err = build_ai_http_client(&config, 1).unwrap_err();
|
||||
@@ -2650,6 +2719,8 @@ mod tests {
|
||||
context_window: None,
|
||||
codex_cli_path: None,
|
||||
codex_cli_env: Default::default(),
|
||||
claude_code_cli_path: None,
|
||||
claude_code_cli_env: Default::default(),
|
||||
};
|
||||
|
||||
build_ai_http_client(&config, 1).unwrap();
|
||||
@@ -2672,6 +2743,8 @@ mod tests {
|
||||
context_window: None,
|
||||
codex_cli_path: None,
|
||||
codex_cli_env: Default::default(),
|
||||
claude_code_cli_path: None,
|
||||
claude_code_cli_env: Default::default(),
|
||||
};
|
||||
|
||||
build_ai_http_client(&config, 1).unwrap();
|
||||
@@ -2694,6 +2767,8 @@ mod tests {
|
||||
context_window: None,
|
||||
codex_cli_path: None,
|
||||
codex_cli_env: Default::default(),
|
||||
claude_code_cli_path: None,
|
||||
claude_code_cli_env: Default::default(),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
@@ -2720,6 +2795,8 @@ mod tests {
|
||||
context_window: None,
|
||||
codex_cli_path: None,
|
||||
codex_cli_env: Default::default(),
|
||||
claude_code_cli_path: None,
|
||||
claude_code_cli_env: Default::default(),
|
||||
};
|
||||
|
||||
assert_eq!(resolve_endpoint(&ollama), "http://localhost:11434/v1/chat/completions");
|
||||
@@ -2743,6 +2820,8 @@ mod tests {
|
||||
context_window: None,
|
||||
codex_cli_path: None,
|
||||
codex_cli_env: Default::default(),
|
||||
claude_code_cli_path: None,
|
||||
claude_code_cli_env: Default::default(),
|
||||
};
|
||||
assert_eq!(resolve_model_list_endpoint(&openai).unwrap(), "https://api.openai.com/v1/models");
|
||||
|
||||
@@ -2761,6 +2840,8 @@ mod tests {
|
||||
context_window: None,
|
||||
codex_cli_path: None,
|
||||
codex_cli_env: Default::default(),
|
||||
claude_code_cli_path: None,
|
||||
claude_code_cli_env: Default::default(),
|
||||
};
|
||||
assert_eq!(resolve_model_list_endpoint(&claude).unwrap(), "https://api.anthropic.com/v1/models");
|
||||
}
|
||||
@@ -2782,6 +2863,8 @@ mod tests {
|
||||
context_window: None,
|
||||
codex_cli_path: None,
|
||||
codex_cli_env: Default::default(),
|
||||
claude_code_cli_path: None,
|
||||
claude_code_cli_env: Default::default(),
|
||||
};
|
||||
|
||||
assert!(uses_anthropic_messages_api(&config));
|
||||
@@ -2827,6 +2910,8 @@ mod tests {
|
||||
context_window: None,
|
||||
codex_cli_path: None,
|
||||
codex_cli_env: Default::default(),
|
||||
claude_code_cli_path: None,
|
||||
claude_code_cli_env: Default::default(),
|
||||
};
|
||||
assert_eq!(resolve_endpoint(&config), "https://api.example.com/v1/chat/completions");
|
||||
assert_eq!(resolve_model_list_endpoint(&config).unwrap(), "https://api.example.com/v1/models");
|
||||
@@ -2884,6 +2969,8 @@ mod tests {
|
||||
context_window: None,
|
||||
codex_cli_path: None,
|
||||
codex_cli_env: Default::default(),
|
||||
claude_code_cli_path: None,
|
||||
claude_code_cli_env: Default::default(),
|
||||
};
|
||||
|
||||
let api_key_headers = claude_headers(&config).unwrap();
|
||||
@@ -2923,11 +3010,8 @@ mod tests {
|
||||
assert_eq!(
|
||||
parse_model_list_response(&data).unwrap(),
|
||||
vec![
|
||||
AiModelInfo { id: "gpt-4o-mini".to_string(), display_name: None },
|
||||
AiModelInfo {
|
||||
id: "claude-sonnet-4-20250514".to_string(),
|
||||
display_name: Some("Claude Sonnet 4".to_string())
|
||||
},
|
||||
AiModelInfo::new("gpt-4o-mini", None),
|
||||
AiModelInfo::new("claude-sonnet-4-20250514", Some("Claude Sonnet 4".to_string())),
|
||||
]
|
||||
);
|
||||
}
|
||||
@@ -3173,6 +3257,8 @@ mod tests {
|
||||
context_window: None,
|
||||
codex_cli_path: None,
|
||||
codex_cli_env: Default::default(),
|
||||
claude_code_cli_path: None,
|
||||
claude_code_cli_env: Default::default(),
|
||||
};
|
||||
|
||||
let mut body = serde_json::json!({
|
||||
@@ -3239,6 +3325,8 @@ mod tests {
|
||||
context_window: None,
|
||||
codex_cli_path: None,
|
||||
codex_cli_env: Default::default(),
|
||||
claude_code_cli_path: None,
|
||||
claude_code_cli_env: Default::default(),
|
||||
};
|
||||
let mut body = serde_json::json!({
|
||||
"model": &config.model,
|
||||
@@ -3270,6 +3358,8 @@ mod tests {
|
||||
context_window: None,
|
||||
codex_cli_path: None,
|
||||
codex_cli_env: Default::default(),
|
||||
claude_code_cli_path: None,
|
||||
claude_code_cli_env: Default::default(),
|
||||
};
|
||||
let mut body = serde_json::json!({ "model": &config.model });
|
||||
|
||||
@@ -3307,6 +3397,8 @@ mod tests {
|
||||
context_window: None,
|
||||
codex_cli_path: None,
|
||||
codex_cli_env: Default::default(),
|
||||
claude_code_cli_path: None,
|
||||
claude_code_cli_env: Default::default(),
|
||||
};
|
||||
let mut body = serde_json::json!({ "model": &config.model });
|
||||
|
||||
@@ -3338,6 +3430,8 @@ mod tests {
|
||||
context_window: None,
|
||||
codex_cli_path: None,
|
||||
codex_cli_env: Default::default(),
|
||||
claude_code_cli_path: None,
|
||||
claude_code_cli_env: Default::default(),
|
||||
};
|
||||
let mut body = serde_json::json!({
|
||||
"model": &config.model,
|
||||
|
||||
@@ -0,0 +1,855 @@
|
||||
use crate::agent_events::AgentEvent;
|
||||
use crate::ai::{AiConfig, AiEffortLevel, AiModelInfo, AiTestConnectionResult};
|
||||
use crate::ai_cli_agent::{
|
||||
build_cli_agent_prompt, cli_command, dbx_mcp_enabled_tools, dbx_mcp_scope_env, model_infos, parse_cli_jsonl_event,
|
||||
run_cli_jsonl_agent, CliAgentCommandSpec, CliAgentJsonlDialect, CliAgentProcessSpec, CliAgentRunOptions,
|
||||
};
|
||||
use serde_json::{json, Map, Value};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::env;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Stdio;
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::sync::Notify;
|
||||
|
||||
const DEFAULT_CLAUDE_CODE_MODELS: &[&str] = &["default", "sonnet", "opus", "fable"];
|
||||
const CLAUDE_CODE_MODEL_DISCOVERY_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const CLAUDE_CODE_SETTING_SOURCES: &str = "user";
|
||||
|
||||
pub type ClaudeCodeRunOptions = CliAgentRunOptions;
|
||||
pub type ClaudeCodeCommandSpec = CliAgentCommandSpec;
|
||||
|
||||
struct ClaudeCodeIsolatedCwd {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl ClaudeCodeIsolatedCwd {
|
||||
fn create() -> Result<Self, String> {
|
||||
let path = env::temp_dir().join(format!("dbx-claude-code-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir(&path).map_err(|error| {
|
||||
format!("[claudeCodeRunFailed] Failed to create isolated Claude Code directory: {error}")
|
||||
})?;
|
||||
Ok(Self { path })
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ClaudeCodeIsolatedCwd {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
fn append_claude_code_isolation_args(args: &mut Vec<String>) {
|
||||
// User settings retain authentication and preferences without loading project hooks or local overrides.
|
||||
args.extend(["--setting-sources".to_string(), CLAUDE_CODE_SETTING_SOURCES.to_string()]);
|
||||
}
|
||||
|
||||
fn claude_code_program(config: &AiConfig) -> String {
|
||||
config
|
||||
.claude_code_cli_path
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|path| !path.is_empty())
|
||||
.unwrap_or("claude")
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn claude_code_process_env(
|
||||
config: &AiConfig,
|
||||
command: &ClaudeCodeCommandSpec,
|
||||
) -> Result<Vec<(String, String)>, String> {
|
||||
let mut env = BTreeMap::from_iter(claude_code_cli_env(config)?);
|
||||
if let Some(dir) = command_parent_dir(command) {
|
||||
let user_path = env.get("PATH").map(String::as_str);
|
||||
env.insert("PATH".to_string(), merged_path_with_dir(&dir, user_path));
|
||||
}
|
||||
Ok(env.into_iter().collect())
|
||||
}
|
||||
|
||||
fn command_parent_dir(command: &ClaudeCodeCommandSpec) -> Option<String> {
|
||||
Path::new(&command.program)
|
||||
.parent()
|
||||
.filter(|parent| !parent.as_os_str().is_empty())
|
||||
.map(|parent| parent.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
fn merged_path_with_dir(dir: &str, user_path: Option<&str>) -> String {
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut dirs = vec![PathBuf::from(dir)];
|
||||
if let Some(path) = user_path {
|
||||
dirs.extend(env::split_paths(path));
|
||||
}
|
||||
dirs.extend(common_executable_dirs());
|
||||
let paths = dirs.into_iter().filter(|path| seen.insert(path.clone())).collect::<Vec<_>>();
|
||||
env::join_paths(paths).unwrap_or_default().to_string_lossy().to_string()
|
||||
}
|
||||
|
||||
fn common_executable_dirs() -> Vec<PathBuf> {
|
||||
let mut dirs = Vec::new();
|
||||
if let Ok(path) = env::var("PATH") {
|
||||
dirs.extend(env::split_paths(&path));
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
if let Ok(app_data) = env::var("APPDATA") {
|
||||
dirs.push(PathBuf::from(app_data).join("npm"));
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
dirs.extend([
|
||||
PathBuf::from("/opt/homebrew/bin"),
|
||||
PathBuf::from("/usr/local/bin"),
|
||||
PathBuf::from("/usr/bin"),
|
||||
PathBuf::from("/bin"),
|
||||
PathBuf::from("/usr/sbin"),
|
||||
PathBuf::from("/sbin"),
|
||||
]);
|
||||
}
|
||||
dirs
|
||||
}
|
||||
|
||||
fn validate_claude_code_program(config: &AiConfig) -> Result<String, String> {
|
||||
let program = claude_code_program(config);
|
||||
if starts_with_env_assignment(&program) {
|
||||
return Err("[claudeCodeCliPathInvalid] Claude Code CLI path should contain only the executable path. Add environment variables in the Claude Code CLI environment variables section.".to_string());
|
||||
}
|
||||
if is_path_like_program(&program) {
|
||||
let expanded = crate::path_utils::expand_tilde(&program);
|
||||
let path = Path::new(&expanded);
|
||||
if path.is_dir() {
|
||||
return launchable_program_in_dir(path, "claude").ok_or_else(|| {
|
||||
"[claudeCodeCliPathInvalid] Claude Code CLI path should point to the claude executable or a directory containing claude."
|
||||
.to_string()
|
||||
});
|
||||
}
|
||||
return Ok(expanded);
|
||||
}
|
||||
Ok(program)
|
||||
}
|
||||
|
||||
fn launchable_program_in_dir(dir: &Path, program: &str) -> Option<String> {
|
||||
program_path_candidates(dir, program)
|
||||
.into_iter()
|
||||
.find(|candidate| is_launchable_program_path(candidate) && candidate.is_file())
|
||||
.map(|path| path.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn program_path_candidates(dir: &Path, program: &str) -> Vec<PathBuf> {
|
||||
vec![dir.join(program)]
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn program_path_candidates(dir: &Path, program: &str) -> Vec<PathBuf> {
|
||||
let path = Path::new(program);
|
||||
if path.extension().is_some() {
|
||||
return vec![dir.join(program)];
|
||||
}
|
||||
[".cmd", ".exe", ".bat", ".com", ""].iter().map(|extension| dir.join(format!("{program}{extension}"))).collect()
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn is_launchable_program_path(_path: &Path) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn is_launchable_program_path(path: &Path) -> bool {
|
||||
matches!(
|
||||
path.extension().and_then(|extension| extension.to_str()).map(str::to_ascii_lowercase).as_deref(),
|
||||
Some("exe" | "cmd" | "bat" | "com")
|
||||
)
|
||||
}
|
||||
|
||||
fn is_path_like_program(program: &str) -> bool {
|
||||
program.contains('/') || program.contains('\\') || program.starts_with('~')
|
||||
}
|
||||
|
||||
fn starts_with_env_assignment(program: &str) -> bool {
|
||||
let Some(first_token) = program.split_whitespace().next() else {
|
||||
return false;
|
||||
};
|
||||
let Some((key, _)) = first_token.split_once('=') else {
|
||||
return false;
|
||||
};
|
||||
is_env_var_name(key)
|
||||
}
|
||||
|
||||
fn is_env_var_name(name: &str) -> bool {
|
||||
let mut chars = name.chars();
|
||||
let Some(first) = chars.next() else {
|
||||
return false;
|
||||
};
|
||||
(first == '_' || first.is_ascii_alphabetic()) && chars.all(|ch| ch == '_' || ch.is_ascii_alphanumeric())
|
||||
}
|
||||
|
||||
fn is_reserved_dbx_mcp_env_name(name: &str) -> bool {
|
||||
name.to_ascii_uppercase().starts_with("DBX_MCP_")
|
||||
}
|
||||
|
||||
pub fn claude_code_cli_env(config: &AiConfig) -> Result<Vec<(String, String)>, String> {
|
||||
let mut env = BTreeMap::new();
|
||||
for (key, value) in &config.claude_code_cli_env {
|
||||
let key = key.trim();
|
||||
if key.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if !is_env_var_name(key) {
|
||||
return Err(format!(
|
||||
"[claudeCodeEnvInvalid] Invalid Claude Code CLI environment variable name `{key}`. Use names like HTTPS_PROXY."
|
||||
));
|
||||
}
|
||||
if is_reserved_dbx_mcp_env_name(key) {
|
||||
return Err(format!(
|
||||
"[claudeCodeEnvReserved] `{key}` is managed by DBX for the scoped MCP server and cannot be set here."
|
||||
));
|
||||
}
|
||||
env.insert(key.to_string(), value.clone());
|
||||
}
|
||||
Ok(env.into_iter().collect())
|
||||
}
|
||||
|
||||
pub fn claude_code_enabled_tools(agent_mode: bool) -> Vec<String> {
|
||||
dbx_mcp_enabled_tools(agent_mode).into_iter().map(|tool| format!("mcp__dbx__{tool}")).collect()
|
||||
}
|
||||
|
||||
fn claude_code_mcp_config(options: &ClaudeCodeRunOptions) -> String {
|
||||
let mcp_command =
|
||||
options.mcp_server_command.as_ref().map(|command| command.program.as_str()).unwrap_or("dbx-mcp-server");
|
||||
let mut server = Map::new();
|
||||
server.insert("command".to_string(), Value::String(mcp_command.to_string()));
|
||||
if let Some(command) = options.mcp_server_command.as_ref().filter(|command| !command.args.is_empty()) {
|
||||
server.insert("args".to_string(), json!(command.args));
|
||||
}
|
||||
|
||||
let env = dbx_mcp_scope_env(options)
|
||||
.into_iter()
|
||||
.map(|(name, value)| (name.to_string(), Value::String(value)))
|
||||
.collect::<Map<_, _>>();
|
||||
server.insert("env".to_string(), Value::Object(env));
|
||||
|
||||
json!({
|
||||
"mcpServers": {
|
||||
"dbx": Value::Object(server)
|
||||
}
|
||||
})
|
||||
.to_string()
|
||||
}
|
||||
|
||||
pub fn build_claude_code_command(
|
||||
config: &AiConfig,
|
||||
_prompt: &str,
|
||||
options: &ClaudeCodeRunOptions,
|
||||
) -> ClaudeCodeCommandSpec {
|
||||
let enabled_tools = claude_code_enabled_tools(options.agent_mode);
|
||||
let mut args = vec![
|
||||
"--print".to_string(),
|
||||
"--output-format".to_string(),
|
||||
"stream-json".to_string(),
|
||||
"--verbose".to_string(),
|
||||
"--input-format".to_string(),
|
||||
"text".to_string(),
|
||||
"--no-session-persistence".to_string(),
|
||||
"--permission-mode".to_string(),
|
||||
"dontAsk".to_string(),
|
||||
"--mcp-config".to_string(),
|
||||
claude_code_mcp_config(options),
|
||||
"--strict-mcp-config".to_string(),
|
||||
];
|
||||
append_claude_code_isolation_args(&mut args);
|
||||
args.push("--tools".to_string());
|
||||
args.extend(enabled_tools.iter().cloned());
|
||||
args.push("--allowedTools".to_string());
|
||||
args.extend(enabled_tools);
|
||||
|
||||
let model = config.model.trim();
|
||||
if !model.is_empty() && !model.eq_ignore_ascii_case("default") {
|
||||
args.push("--model".to_string());
|
||||
args.push(model.to_string());
|
||||
}
|
||||
if let Some(effort) = config.reasoning_level.as_claude_code_effort() {
|
||||
args.push("--effort".to_string());
|
||||
args.push(effort.to_string());
|
||||
}
|
||||
|
||||
ClaudeCodeCommandSpec { program: claude_code_program(config), args }
|
||||
}
|
||||
|
||||
pub fn build_claude_code_prompt(
|
||||
system_prompt: &str,
|
||||
messages: &[crate::ai::AiMessage],
|
||||
allow_write_sql: bool,
|
||||
) -> String {
|
||||
build_cli_agent_prompt("Claude Code", system_prompt, messages, allow_write_sql)
|
||||
}
|
||||
|
||||
pub async fn list_claude_code_models(config: &AiConfig) -> Result<Vec<AiModelInfo>, String> {
|
||||
let program = validate_claude_code_program(config)?;
|
||||
Ok(discover_claude_code_models(config, program).await.unwrap_or_else(|| model_infos(DEFAULT_CLAUDE_CODE_MODELS)))
|
||||
}
|
||||
|
||||
async fn discover_claude_code_models(config: &AiConfig, program: String) -> Option<Vec<AiModelInfo>> {
|
||||
let mut command = ClaudeCodeCommandSpec {
|
||||
program,
|
||||
args: vec![
|
||||
"--print".to_string(),
|
||||
"--output-format".to_string(),
|
||||
"stream-json".to_string(),
|
||||
"--input-format".to_string(),
|
||||
"stream-json".to_string(),
|
||||
"--verbose".to_string(),
|
||||
],
|
||||
};
|
||||
append_claude_code_isolation_args(&mut command.args);
|
||||
let env = claude_code_process_env(config, &command).ok()?;
|
||||
let isolated_cwd = ClaudeCodeIsolatedCwd::create().ok()?;
|
||||
let mut process = cli_command(&command.program);
|
||||
process
|
||||
.args(command.args.iter().map(String::as_str))
|
||||
.envs(env.iter().map(|(key, value)| (key.as_str(), value.as_str())))
|
||||
.env_remove("CLAUDECODE")
|
||||
.current_dir(&isolated_cwd.path)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true);
|
||||
|
||||
let mut child = process.spawn().ok()?;
|
||||
let mut stdin = child.stdin.take()?;
|
||||
let mut request = serde_json::to_vec(&json!({
|
||||
"type": "control_request",
|
||||
"request_id": "dbx_model_discovery",
|
||||
"request": { "subtype": "initialize" }
|
||||
}))
|
||||
.ok()?;
|
||||
request.push(b'\n');
|
||||
stdin.write_all(&request).await.ok()?;
|
||||
drop(stdin);
|
||||
|
||||
let output =
|
||||
tokio::time::timeout(CLAUDE_CODE_MODEL_DISCOVERY_TIMEOUT, child.wait_with_output()).await.ok()?.ok()?;
|
||||
parse_claude_code_models(&String::from_utf8_lossy(&output.stdout))
|
||||
}
|
||||
|
||||
fn parse_claude_code_models(stdout: &str) -> Option<Vec<AiModelInfo>> {
|
||||
for line in stdout.lines() {
|
||||
let Ok(event) = serde_json::from_str::<Value>(line.trim()) else {
|
||||
continue;
|
||||
};
|
||||
if event.get("type").and_then(Value::as_str) != Some("control_response") {
|
||||
continue;
|
||||
}
|
||||
|
||||
let Some(response) = event.get("response") else {
|
||||
continue;
|
||||
};
|
||||
let data = response.get("response").unwrap_or(response);
|
||||
let Some(models) = data.get("models").and_then(Value::as_array) else {
|
||||
continue;
|
||||
};
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut result = Vec::new();
|
||||
for model in models {
|
||||
let Some(id) = model
|
||||
.get("value")
|
||||
.and_then(Value::as_str)
|
||||
.or_else(|| model.get("id").and_then(Value::as_str))
|
||||
.map(str::trim)
|
||||
.filter(|id| !id.is_empty())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if !seen.insert(id.to_string()) {
|
||||
continue;
|
||||
}
|
||||
let display_name = model
|
||||
.get("displayName")
|
||||
.and_then(Value::as_str)
|
||||
.or_else(|| model.get("display_name").and_then(Value::as_str))
|
||||
.map(str::trim)
|
||||
.filter(|name| !name.is_empty())
|
||||
.map(ToString::to_string);
|
||||
let mut info = AiModelInfo::new(id, display_name);
|
||||
info.supported_effort_levels = parse_claude_code_effort_levels(model);
|
||||
result.push(info);
|
||||
}
|
||||
|
||||
if result.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if seen.insert("default".to_string()) {
|
||||
result.insert(0, AiModelInfo::new("default", Some("Default".to_string())));
|
||||
}
|
||||
return Some(result);
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn parse_claude_code_effort_levels(model: &Value) -> Vec<AiEffortLevel> {
|
||||
if model.get("supportsEffort").or_else(|| model.get("supports_effort")).and_then(Value::as_bool) == Some(false) {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(levels) =
|
||||
model.get("supportedEffortLevels").or_else(|| model.get("supported_effort_levels")).and_then(Value::as_array)
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let mut seen = BTreeSet::new();
|
||||
levels
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.filter_map(|level| level.parse::<AiEffortLevel>().ok())
|
||||
.filter(|level| seen.insert(*level))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub async fn test_claude_code_connection(config: &AiConfig) -> Result<AiTestConnectionResult, String> {
|
||||
let start = Instant::now();
|
||||
let claude_command = ClaudeCodeCommandSpec { program: validate_claude_code_program(config)?, args: Vec::new() };
|
||||
let mut command = cli_command(&claude_command.program);
|
||||
command.args(claude_command.args.iter().map(String::as_str));
|
||||
command.args(["auth", "status"]);
|
||||
command.envs(
|
||||
claude_code_process_env(config, &claude_command)?.iter().map(|(key, value)| (key.as_str(), value.as_str())),
|
||||
);
|
||||
|
||||
let output = command.output().await.map_err(|e| classify_claude_code_spawn_error(&e.to_string()))?;
|
||||
|
||||
if output.status.success() {
|
||||
Ok(AiTestConnectionResult {
|
||||
success: true,
|
||||
message: format!("OK - {}ms", start.elapsed().as_millis()),
|
||||
latency_ms: Some(start.elapsed().as_millis() as u64),
|
||||
model_used: config.model.trim().to_string(),
|
||||
error_category: None,
|
||||
})
|
||||
} else {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let message =
|
||||
[stderr.trim(), stdout.trim()].into_iter().filter(|part| !part.is_empty()).collect::<Vec<_>>().join("\n");
|
||||
Err(classify_claude_code_run_error(&message))
|
||||
}
|
||||
}
|
||||
|
||||
fn classify_claude_code_spawn_error(message: &str) -> String {
|
||||
if message.contains("No such file") || message.contains("not found") {
|
||||
"[claudeCodeNotInstalled] Claude Code CLI was not found. Install Claude Code or set the Claude Code CLI path in DBX AI settings."
|
||||
.to_string()
|
||||
} else if is_command_line_too_long_error(message) {
|
||||
"[claudeCodeCommandLineTooLong] Claude Code CLI command line is too long.".to_string()
|
||||
} else {
|
||||
format!("[claudeCodeRunFailed] Failed to start Claude Code CLI: {message}")
|
||||
}
|
||||
}
|
||||
|
||||
fn is_command_line_too_long_error(message: &str) -> bool {
|
||||
let lower = message.to_ascii_lowercase();
|
||||
message.contains("os error 206")
|
||||
|| message.contains("文件名或扩展名太长")
|
||||
|| lower.contains("filename or extension is too long")
|
||||
|| lower.contains("the filename or extension is too long")
|
||||
}
|
||||
|
||||
fn classify_claude_code_run_error(stderr: &str) -> String {
|
||||
let lower = stderr.to_ascii_lowercase();
|
||||
if lower.contains("not authenticated") || lower.contains("login") || lower.contains("auth") {
|
||||
format!(
|
||||
"[claudeCodeNotAuthenticated] Claude Code CLI is not authenticated. Run `claude auth login` and try again. {stderr}"
|
||||
)
|
||||
} else if lower.contains("dbx-mcp-server") || lower.contains("enoent") {
|
||||
format!("[dbxMcpMissing] DBX MCP server was not found. Install @dbx-app/mcp-server and try again. {stderr}")
|
||||
} else if lower.contains("mcp") && (lower.contains("dbx") || lower.contains("server")) {
|
||||
format!("[claudeCodeMcpStartupFailed] Claude Code could not start the DBX MCP server. {stderr}")
|
||||
} else {
|
||||
format!("[claudeCodeRunFailed] Claude Code CLI failed. {stderr}")
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_claude_code_jsonl_event(line: &str) -> Option<Vec<AgentEvent>> {
|
||||
parse_cli_jsonl_event(line, CliAgentJsonlDialect::ClaudeCodePrint)
|
||||
}
|
||||
|
||||
pub async fn run_claude_code_agent(
|
||||
config: &AiConfig,
|
||||
prompt: &str,
|
||||
options: ClaudeCodeRunOptions,
|
||||
cancelled: &Notify,
|
||||
on_event: impl Fn(AgentEvent) + Send + Sync + 'static,
|
||||
) -> Result<String, String> {
|
||||
let program = validate_claude_code_program(config)?;
|
||||
let mut command = build_claude_code_command(config, prompt, &options);
|
||||
command.program = program;
|
||||
let env = claude_code_process_env(config, &command)?;
|
||||
let isolated_cwd = ClaudeCodeIsolatedCwd::create()?;
|
||||
let result = run_cli_jsonl_agent(
|
||||
CliAgentProcessSpec {
|
||||
command,
|
||||
env,
|
||||
current_dir: Some(isolated_cwd.path.clone()),
|
||||
stdin: Some(prompt.to_string()),
|
||||
dialect: CliAgentJsonlDialect::ClaudeCodePrint,
|
||||
classify_spawn_error: classify_claude_code_spawn_error,
|
||||
classify_run_error: classify_claude_code_run_error,
|
||||
},
|
||||
cancelled,
|
||||
on_event,
|
||||
)
|
||||
.await;
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
build_claude_code_command, claude_code_cli_env, claude_code_enabled_tools, parse_claude_code_jsonl_event,
|
||||
parse_claude_code_models, validate_claude_code_program, ClaudeCodeRunOptions, DEFAULT_CLAUDE_CODE_MODELS,
|
||||
};
|
||||
#[cfg(unix)]
|
||||
use super::{list_claude_code_models, run_claude_code_agent};
|
||||
use crate::agent_events::AgentEvent;
|
||||
use crate::ai::{AiApiStyle, AiAuthMethod, AiConfig, AiEffortLevel, AiModelInfo, AiProvider, AiReasoningLevel};
|
||||
use crate::ai_cli_agent::{model_infos, CliAgentCommandSpec};
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
#[cfg(unix)]
|
||||
use tokio::sync::Notify;
|
||||
|
||||
fn claude_code_config(model: &str) -> AiConfig {
|
||||
AiConfig {
|
||||
provider: AiProvider::ClaudeCodeCli,
|
||||
api_key: String::new(),
|
||||
auth_method: AiAuthMethod::Bearer,
|
||||
endpoint: String::new(),
|
||||
model: model.to_string(),
|
||||
models: Vec::new(),
|
||||
api_style: AiApiStyle::Completions,
|
||||
proxy_enabled: false,
|
||||
proxy_url: String::new(),
|
||||
enable_thinking: true,
|
||||
reasoning_level: AiReasoningLevel::Default,
|
||||
context_window: None,
|
||||
codex_cli_path: None,
|
||||
codex_cli_env: Default::default(),
|
||||
claude_code_cli_path: None,
|
||||
claude_code_cli_env: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn run_options() -> ClaudeCodeRunOptions {
|
||||
ClaudeCodeRunOptions {
|
||||
connection_id: "conn-1".to_string(),
|
||||
connection_name: "local".to_string(),
|
||||
database: "demo".to_string(),
|
||||
agent_mode: true,
|
||||
allow_writes: false,
|
||||
allow_dangerous: false,
|
||||
mcp_server_command: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn isolated_cli_test_config() -> (AiConfig, std::path::PathBuf, std::path::PathBuf) {
|
||||
let project_dir = std::env::temp_dir().join(format!("dbx-claude-project-test-{}", uuid::Uuid::new_v4()));
|
||||
let claude_dir = project_dir.join(".claude");
|
||||
let user_config_dir = project_dir.join("user-config");
|
||||
let hook_marker = project_dir.join("project-hook-loaded");
|
||||
std::fs::create_dir_all(&claude_dir).unwrap();
|
||||
std::fs::create_dir_all(&user_config_dir).unwrap();
|
||||
std::fs::write(user_config_dir.join("auth-marker"), "authenticated").unwrap();
|
||||
std::fs::write(
|
||||
claude_dir.join("settings.json"),
|
||||
serde_json::to_vec(&serde_json::json!({
|
||||
"model": "project-model-must-not-load",
|
||||
"hooks": {
|
||||
"SessionStart": [{
|
||||
"matcher": "",
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"command": format!("printf loaded > {}", hook_marker.display())
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}))
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let executable = project_dir.join("claude");
|
||||
std::fs::write(
|
||||
&executable,
|
||||
r#"#!/bin/sh
|
||||
user_settings=false
|
||||
previous=""
|
||||
for arg in "$@"; do
|
||||
if [ "$previous" = "--setting-sources" ] && [ "$arg" = "user" ]; then
|
||||
user_settings=true
|
||||
fi
|
||||
previous="$arg"
|
||||
done
|
||||
if [ "$user_settings" != "true" ] || [ "$PWD" = "$DBX_TEST_PROJECT_DIR" ]; then
|
||||
printf loaded > "$DBX_TEST_HOOK_MARKER"
|
||||
fi
|
||||
if [ ! -f "$CLAUDE_CONFIG_DIR/auth-marker" ]; then
|
||||
exit 9
|
||||
fi
|
||||
input=$(cat)
|
||||
case " $* " in
|
||||
*" --input-format stream-json "*)
|
||||
printf '%s\n' '{"type":"control_response","response":{"response":{"models":[{"value":"claude-user-model","displayName":"User Model"}]}}}'
|
||||
;;
|
||||
*)
|
||||
printf '%s\n' '{"type":"assistant","message":{"content":[{"type":"text","text":"isolated execution"}]}}'
|
||||
printf '%s\n' '{"type":"result","subtype":"success"}'
|
||||
;;
|
||||
esac
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
let mut permissions = std::fs::metadata(&executable).unwrap().permissions();
|
||||
permissions.set_mode(0o755);
|
||||
std::fs::set_permissions(&executable, permissions).unwrap();
|
||||
|
||||
let mut config = claude_code_config("default");
|
||||
config.claude_code_cli_path = Some(executable.to_string_lossy().to_string());
|
||||
config
|
||||
.claude_code_cli_env
|
||||
.insert("CLAUDE_CONFIG_DIR".to_string(), user_config_dir.to_string_lossy().to_string());
|
||||
config
|
||||
.claude_code_cli_env
|
||||
.insert("DBX_TEST_PROJECT_DIR".to_string(), project_dir.to_string_lossy().to_string());
|
||||
config
|
||||
.claude_code_cli_env
|
||||
.insert("DBX_TEST_HOOK_MARKER".to_string(), hook_marker.to_string_lossy().to_string());
|
||||
|
||||
(config, project_dir, hook_marker)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_claude_code_command_with_scoped_mcp_and_default_model() {
|
||||
let spec = build_claude_code_command(&claude_code_config("default"), "hello", &run_options());
|
||||
|
||||
assert_eq!(spec.program, "claude");
|
||||
assert!(spec.args.contains(&"--print".to_string()));
|
||||
assert!(spec.args.contains(&"stream-json".to_string()));
|
||||
assert!(spec.args.contains(&"--mcp-config".to_string()));
|
||||
assert!(spec.args.windows(2).any(|args| args == ["--setting-sources", "user"]));
|
||||
assert!(
|
||||
spec.args.iter().position(|arg| arg == "--setting-sources")
|
||||
< spec.args.iter().position(|arg| arg == "--tools")
|
||||
);
|
||||
assert!(!spec.args.contains(&"hello".to_string()));
|
||||
assert!(!spec.args.contains(&"--model".to_string()));
|
||||
assert!(!spec.args.contains(&"--effort".to_string()));
|
||||
assert!(spec.args.iter().any(|arg| arg.contains("\"command\":\"dbx-mcp-server\"")));
|
||||
assert!(spec.args.iter().any(|arg| arg.contains("\"DBX_MCP_ALLOW_WRITES\":\"0\"")));
|
||||
assert!(spec.args.iter().any(|arg| arg.contains("\"DBX_MCP_SCOPE_CONNECTION_ID\":\"conn-1\"")));
|
||||
assert!(spec.args.iter().any(|arg| arg.contains("mcp__dbx__dbx_execute_query")));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn model_discovery_uses_user_settings_from_an_isolated_directory() {
|
||||
let (config, project_dir, hook_marker) = isolated_cli_test_config();
|
||||
|
||||
let models = list_claude_code_models(&config).await.unwrap();
|
||||
|
||||
assert!(models.iter().any(|model| model.id == "claude-user-model"));
|
||||
assert!(!hook_marker.exists());
|
||||
let _ = std::fs::remove_dir_all(project_dir);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn execution_uses_user_settings_from_an_isolated_directory() {
|
||||
let (config, project_dir, hook_marker) = isolated_cli_test_config();
|
||||
|
||||
let output = run_claude_code_agent(&config, "hello", run_options(), &Notify::new(), |_| {}).await.unwrap();
|
||||
|
||||
assert_eq!(output, "isolated execution");
|
||||
assert!(!hook_marker.exists());
|
||||
let _ = std::fs::remove_dir_all(project_dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_claude_code_command_with_custom_mcp_server_and_ask_tools() {
|
||||
let mut options = run_options();
|
||||
options.agent_mode = false;
|
||||
options.mcp_server_command = Some(CliAgentCommandSpec {
|
||||
program: "/opt/dbx/bin/dbx-mcp-server".to_string(),
|
||||
args: vec!["--stdio".to_string()],
|
||||
});
|
||||
let spec = build_claude_code_command(&claude_code_config("sonnet"), "hello", &options);
|
||||
|
||||
let model_pos = spec.args.iter().position(|arg| arg == "--model").unwrap();
|
||||
assert_eq!(spec.args[model_pos + 1], "sonnet");
|
||||
assert!(spec.args.iter().any(|arg| arg.contains("\"command\":\"/opt/dbx/bin/dbx-mcp-server\"")));
|
||||
assert!(spec.args.iter().any(|arg| arg.contains("\"args\":[\"--stdio\"]")));
|
||||
assert!(!claude_code_enabled_tools(false).iter().any(|tool| tool == "mcp__dbx__dbx_execute_query"));
|
||||
assert!(!spec.args.iter().any(|arg| arg.contains("mcp__dbx__dbx_execute_query")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_claude_code_command_with_supported_effort() {
|
||||
let mut config = claude_code_config("sonnet");
|
||||
config.reasoning_level = AiReasoningLevel::Xhigh;
|
||||
|
||||
let spec = build_claude_code_command(&config, "hello", &run_options());
|
||||
|
||||
let effort_pos = spec.args.iter().position(|arg| arg == "--effort").unwrap();
|
||||
assert_eq!(spec.args[effort_pos + 1], "xhigh");
|
||||
|
||||
config.reasoning_level = AiReasoningLevel::Minimal;
|
||||
let spec = build_claude_code_command(&config, "hello", &run_options());
|
||||
assert!(!spec.args.contains(&"--effort".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_model_list_matches_supported_aliases() {
|
||||
assert_eq!(model_infos(DEFAULT_CLAUDE_CODE_MODELS), model_infos(&["default", "sonnet", "opus", "fable"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_discovered_claude_code_models() {
|
||||
let stdout = concat!(
|
||||
"not json\n",
|
||||
r#"{"type":"system","subtype":"init"}"#,
|
||||
"\n",
|
||||
r#"{"type":"control_response","response":{"subtype":"success","response":{"commands":[]}}}"#,
|
||||
"\n",
|
||||
r#"{"type":"control_response","response":{"subtype":"success","request_id":"dbx_model_discovery","response":{"models":[{"value":"default","displayName":"Default","resolvedModel":"claude-sonnet"},{"value":"claude-sonnet-4-6","displayName":"Sonnet 4.6","supportsEffort":true,"supportedEffortLevels":["low","medium","high","max","high","future"]},{"value":"claude-sonnet-4-6","displayName":"Duplicate"},{"value":"claude-opus-4-8","display_name":"Opus 4.8","supports_effort":false,"supported_effort_levels":["low"]}]}}}"#
|
||||
);
|
||||
|
||||
let models = parse_claude_code_models(stdout).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
models,
|
||||
vec![
|
||||
AiModelInfo::new("default", Some("Default".to_string())),
|
||||
AiModelInfo {
|
||||
id: "claude-sonnet-4-6".to_string(),
|
||||
display_name: Some("Sonnet 4.6".to_string()),
|
||||
supported_effort_levels: vec![
|
||||
AiEffortLevel::Low,
|
||||
AiEffortLevel::Medium,
|
||||
AiEffortLevel::High,
|
||||
AiEffortLevel::Max
|
||||
],
|
||||
},
|
||||
AiModelInfo::new("claude-opus-4-8", Some("Opus 4.8".to_string())),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adds_default_to_discovered_claude_code_models_when_missing() {
|
||||
let stdout = r#"{"type":"control_response","response":{"models":[{"id":"claude-haiku-4-5","displayName":"Haiku 4.5"}]}}"#;
|
||||
|
||||
let models = parse_claude_code_models(stdout).unwrap();
|
||||
|
||||
assert_eq!(models[0].id, "default");
|
||||
assert_eq!(models[1].id, "claude-haiku-4-5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_claude_code_initialize_response_without_models() {
|
||||
let stdout = r#"{"type":"control_response","response":{"subtype":"success","response":{"commands":[]}}}"#;
|
||||
|
||||
assert!(parse_claude_code_models(stdout).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalizes_claude_code_cli_env() {
|
||||
let mut config = claude_code_config("default");
|
||||
config.claude_code_cli_env.insert(" HTTPS_PROXY ".to_string(), "http://proxy:9800".to_string());
|
||||
config.claude_code_cli_env.insert("NO_PROXY".to_string(), "localhost,127.0.0.1".to_string());
|
||||
|
||||
let env = claude_code_cli_env(&config).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
env,
|
||||
vec![
|
||||
("HTTPS_PROXY".to_string(), "http://proxy:9800".to_string()),
|
||||
("NO_PROXY".to_string(), "localhost,127.0.0.1".to_string())
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_reserved_dbx_mcp_env_name() {
|
||||
let mut config = claude_code_config("default");
|
||||
config.claude_code_cli_env.insert("DBX_MCP_SCOPE_DATABASE".to_string(), "main".to_string());
|
||||
|
||||
let err = claude_code_cli_env(&config).unwrap_err();
|
||||
|
||||
assert!(err.contains("[claudeCodeEnvReserved]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_shell_style_env_prefix_in_claude_code_cli_path() {
|
||||
let mut config = claude_code_config("default");
|
||||
config.claude_code_cli_path = Some("HTTPS_PROXY=http://proxy:9800 /opt/homebrew/bin/claude".to_string());
|
||||
|
||||
let err = validate_claude_code_program(&config).unwrap_err();
|
||||
|
||||
assert!(err.contains("[claudeCodeCliPathInvalid]"));
|
||||
assert!(err.contains("environment variables section"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_claude_code_executable_from_configured_directory() {
|
||||
let dir = std::env::temp_dir().join(format!("dbx-claude-code-dir-test-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let executable = dir.join(if cfg!(windows) { "claude.cmd" } else { "claude" });
|
||||
std::fs::write(&executable, "").unwrap();
|
||||
let mut config = claude_code_config("default");
|
||||
config.claude_code_cli_path = Some(dir.to_string_lossy().to_string());
|
||||
|
||||
let resolved = validate_claude_code_program(&config).unwrap();
|
||||
|
||||
assert_eq!(resolved, executable.to_string_lossy());
|
||||
let _ = std::fs::remove_file(executable);
|
||||
let _ = std::fs::remove_dir(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_claude_code_jsonl_events() {
|
||||
let started = parse_claude_code_jsonl_event(
|
||||
r#"{"type":"assistant","message":{"content":[{"type":"tool_use","id":"tool-1","name":"mcp__dbx__dbx_list_tables","input":{"schema":"public"}}]}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(
|
||||
matches!(&started[0], AgentEvent::ToolCallStart { tool_name, args, .. } if tool_name == "mcp__dbx__dbx_list_tables" && args["schema"] == "public")
|
||||
);
|
||||
|
||||
let text = parse_claude_code_jsonl_event(
|
||||
r#"{"type":"assistant","message":{"content":[{"type":"text","text":"Done"}]}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(&text[0], AgentEvent::TextDelta { delta } if delta == "Done"));
|
||||
|
||||
let tool_result = parse_claude_code_jsonl_event(
|
||||
r#"{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"tool-1","content":[{"type":"text","text":"users"}],"is_error":false}]}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(
|
||||
matches!(&tool_result[0], AgentEvent::ToolCallEnd { tool_call_id, result, is_error, .. } if tool_call_id == "tool-1" && result[0]["text"] == "users" && !is_error)
|
||||
);
|
||||
|
||||
let done = parse_claude_code_jsonl_event(
|
||||
r#"{"type":"result","subtype":"success","usage":{"input_tokens":12,"output_tokens":3}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(&done[0], AgentEvent::AgentEnd { input_tokens: Some(12), output_tokens: Some(3) }));
|
||||
|
||||
let failed = parse_claude_code_jsonl_event(
|
||||
r#"{"type":"result","subtype":"error_max_turns","message":"too many turns"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(&failed[0], AgentEvent::Error { message } if message == "too many turns"));
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ use crate::ai::{AiMessage, AiModelInfo};
|
||||
use crate::token_usage::TokenUsage;
|
||||
use serde_json::Value;
|
||||
use std::ffi::OsStr;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Stdio;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::process::Command;
|
||||
@@ -28,11 +29,13 @@ pub struct CliAgentCommandSpec {
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CliAgentJsonlDialect {
|
||||
CodexExec,
|
||||
ClaudeCodePrint,
|
||||
}
|
||||
|
||||
pub struct CliAgentProcessSpec {
|
||||
pub command: CliAgentCommandSpec,
|
||||
pub env: Vec<(String, String)>,
|
||||
pub current_dir: Option<PathBuf>,
|
||||
pub stdin: Option<String>,
|
||||
pub dialect: CliAgentJsonlDialect,
|
||||
pub classify_spawn_error: fn(&str) -> String,
|
||||
@@ -109,7 +112,7 @@ pub fn build_cli_agent_prompt(
|
||||
}
|
||||
|
||||
pub fn model_infos(ids: &[&str]) -> Vec<AiModelInfo> {
|
||||
ids.iter().map(|id| AiModelInfo { id: (*id).to_string(), display_name: None }).collect()
|
||||
ids.iter().map(|id| AiModelInfo::new(*id, None)).collect()
|
||||
}
|
||||
|
||||
pub fn cli_command(program: impl AsRef<OsStr>) -> Command {
|
||||
@@ -143,8 +146,8 @@ pub async fn list_json_models_or_default(
|
||||
if models.is_empty() {
|
||||
Ok(model_infos(default_models))
|
||||
} else {
|
||||
let mut result = vec![AiModelInfo { id: "default".to_string(), display_name: None }];
|
||||
result.extend(models.into_iter().map(|id| AiModelInfo { id, display_name: None }));
|
||||
let mut result = vec![AiModelInfo::new("default", None)];
|
||||
result.extend(models.into_iter().map(|id| AiModelInfo::new(id, None)));
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
@@ -190,6 +193,7 @@ pub fn parse_cli_jsonl_event(line: &str, dialect: CliAgentJsonlDialect) -> Optio
|
||||
fn parse_cli_jsonl_line(line: &str, dialect: CliAgentJsonlDialect) -> ParsedCliAgentEvent {
|
||||
match dialect {
|
||||
CliAgentJsonlDialect::CodexExec => parse_codex_jsonl_line(line),
|
||||
CliAgentJsonlDialect::ClaudeCodePrint => parse_claude_code_jsonl_line(line),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -351,15 +355,154 @@ fn codex_error_message(value: &Value) -> String {
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn parse_claude_code_jsonl_line(line: &str) -> ParsedCliAgentEvent {
|
||||
let Ok(value) = serde_json::from_str::<Value>(line) else {
|
||||
return ParsedCliAgentEvent::default();
|
||||
};
|
||||
|
||||
match value.get("type").and_then(Value::as_str).unwrap_or_default() {
|
||||
"assistant" => parse_claude_code_assistant(&value),
|
||||
"user" => parse_claude_code_user(&value),
|
||||
"result" => parse_claude_code_result(&value),
|
||||
"error" => {
|
||||
let message = claude_code_error_message(&value);
|
||||
ParsedCliAgentEvent {
|
||||
error: Some(message.clone()),
|
||||
events: vec![AgentEvent::Error { message }],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
_ => ParsedCliAgentEvent::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_claude_code_assistant(value: &Value) -> ParsedCliAgentEvent {
|
||||
let content = value.get("message").and_then(|message| message.get("content")).or_else(|| value.get("content"));
|
||||
let Some(content) = content else {
|
||||
return ParsedCliAgentEvent::default();
|
||||
};
|
||||
|
||||
let mut events = Vec::new();
|
||||
let mut final_text = String::new();
|
||||
for block in claude_content_blocks(content) {
|
||||
match block.get("type").and_then(Value::as_str).unwrap_or_default() {
|
||||
"text" => {
|
||||
if let Some(text) = block.get("text").and_then(Value::as_str).filter(|text| !text.is_empty()) {
|
||||
final_text.push_str(text);
|
||||
events.push(AgentEvent::TextDelta { delta: text.to_string() });
|
||||
}
|
||||
}
|
||||
"thinking" => {
|
||||
if let Some(text) = block.get("thinking").and_then(Value::as_str).filter(|text| !text.is_empty()) {
|
||||
events.push(AgentEvent::ReasoningDelta { delta: text.to_string() });
|
||||
}
|
||||
}
|
||||
"tool_use" => {
|
||||
events.push(AgentEvent::ToolCallStart {
|
||||
tool_call_id: block
|
||||
.get("id")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("claude-code-tool-call")
|
||||
.to_string(),
|
||||
tool_name: block.get("name").and_then(Value::as_str).unwrap_or("claude_code_tool").to_string(),
|
||||
args: block.get("input").cloned().unwrap_or_else(|| Value::Object(Default::default())),
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
ParsedCliAgentEvent { final_text: (!final_text.is_empty()).then_some(final_text), events, ..Default::default() }
|
||||
}
|
||||
|
||||
fn parse_claude_code_user(value: &Value) -> ParsedCliAgentEvent {
|
||||
let content = value.get("message").and_then(|message| message.get("content")).or_else(|| value.get("content"));
|
||||
let Some(content) = content else {
|
||||
return ParsedCliAgentEvent::default();
|
||||
};
|
||||
|
||||
let mut events = Vec::new();
|
||||
for block in claude_content_blocks(content) {
|
||||
if block.get("type").and_then(Value::as_str) != Some("tool_result") {
|
||||
continue;
|
||||
}
|
||||
events.push(AgentEvent::ToolCallEnd {
|
||||
tool_call_id: block
|
||||
.get("tool_use_id")
|
||||
.and_then(Value::as_str)
|
||||
.or_else(|| block.get("id").and_then(Value::as_str))
|
||||
.unwrap_or("claude-code-tool-call")
|
||||
.to_string(),
|
||||
tool_name: "mcp_tool".to_string(),
|
||||
result: block.get("content").cloned().unwrap_or(Value::Null),
|
||||
is_error: block.get("is_error").and_then(Value::as_bool).unwrap_or(false),
|
||||
});
|
||||
}
|
||||
|
||||
ParsedCliAgentEvent { events, ..Default::default() }
|
||||
}
|
||||
|
||||
fn parse_claude_code_result(value: &Value) -> ParsedCliAgentEvent {
|
||||
let subtype = value.get("subtype").and_then(Value::as_str).unwrap_or("success");
|
||||
if subtype != "success" {
|
||||
let message = claude_code_error_message(value);
|
||||
return ParsedCliAgentEvent {
|
||||
error: Some(message.clone()),
|
||||
events: vec![AgentEvent::Error { message }],
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
|
||||
let usage = value.get("usage").and_then(|usage| {
|
||||
let input =
|
||||
usage.get("input_tokens").or_else(|| usage.get("prompt_tokens")).and_then(Value::as_u64).unwrap_or(0)
|
||||
as u32;
|
||||
let output =
|
||||
usage.get("output_tokens").or_else(|| usage.get("completion_tokens")).and_then(Value::as_u64).unwrap_or(0)
|
||||
as u32;
|
||||
(input > 0 || output > 0).then_some(TokenUsage { input_tokens: input, output_tokens: output })
|
||||
});
|
||||
|
||||
ParsedCliAgentEvent {
|
||||
events: vec![AgentEvent::AgentEnd {
|
||||
input_tokens: usage.as_ref().and_then(|u| (u.input_tokens > 0).then_some(u.input_tokens)),
|
||||
output_tokens: usage.as_ref().and_then(|u| (u.output_tokens > 0).then_some(u.output_tokens)),
|
||||
}],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn claude_content_blocks(content: &Value) -> Vec<Value> {
|
||||
match content {
|
||||
Value::Array(blocks) => blocks.clone(),
|
||||
Value::String(text) => vec![serde_json::json!({ "type": "text", "text": text })],
|
||||
Value::Object(_) => vec![content.clone()],
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn claude_code_error_message(value: &Value) -> String {
|
||||
value
|
||||
.get("error")
|
||||
.and_then(Value::as_str)
|
||||
.or_else(|| value.get("message").and_then(Value::as_str))
|
||||
.or_else(|| value.get("error").and_then(|error| error.get("message")).and_then(Value::as_str))
|
||||
.or_else(|| value.get("result").and_then(Value::as_str))
|
||||
.unwrap_or("Claude Code CLI failed")
|
||||
.to_string()
|
||||
}
|
||||
|
||||
pub async fn run_cli_jsonl_agent(
|
||||
spec: CliAgentProcessSpec,
|
||||
cancelled: &Notify,
|
||||
on_event: impl Fn(AgentEvent) + Send + Sync + 'static,
|
||||
) -> Result<String, String> {
|
||||
let mut command = cli_command(&spec.command.program);
|
||||
command.args(&spec.command.args).envs(spec.env.iter().map(|(key, value)| (key.as_str(), value.as_str())));
|
||||
if let Some(current_dir) = &spec.current_dir {
|
||||
command.current_dir(current_dir);
|
||||
}
|
||||
let mut child = command
|
||||
.args(&spec.command.args)
|
||||
.envs(spec.env.iter().map(|(key, value)| (key.as_str(), value.as_str())))
|
||||
.stdin(if spec.stdin.is_some() { Stdio::piped() } else { Stdio::null() })
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
@@ -476,6 +619,7 @@ mod tests {
|
||||
],
|
||||
},
|
||||
env: vec![("DBX_TEST_ENV".to_string(), "from-env".to_string())],
|
||||
current_dir: None,
|
||||
stdin: None,
|
||||
dialect: CliAgentJsonlDialect::CodexExec,
|
||||
classify_spawn_error,
|
||||
@@ -498,6 +642,7 @@ mod tests {
|
||||
],
|
||||
},
|
||||
env: Vec::new(),
|
||||
current_dir: None,
|
||||
stdin: Some("prompt from stdin".to_string()),
|
||||
dialect: CliAgentJsonlDialect::CodexExec,
|
||||
classify_spawn_error,
|
||||
@@ -524,6 +669,7 @@ mod tests {
|
||||
let spec = CliAgentProcessSpec {
|
||||
command: CliAgentCommandSpec { program: "sh".to_string(), args: vec!["-c".to_string(), script] },
|
||||
env: Vec::new(),
|
||||
current_dir: None,
|
||||
stdin: None,
|
||||
dialect: CliAgentJsonlDialect::CodexExec,
|
||||
classify_spawn_error,
|
||||
|
||||
@@ -463,7 +463,7 @@ fn parse_codex_models(stdout: &str) -> Option<Vec<AiModelInfo>> {
|
||||
let data = serde_json::from_str::<Value>(&stdout[json_start..]).ok()?;
|
||||
let models = data.get("models").and_then(Value::as_array)?;
|
||||
|
||||
let mut result = vec![AiModelInfo { id: "default".to_string(), display_name: Some("Default".to_string()) }];
|
||||
let mut result = vec![AiModelInfo::new("default", Some("Default".to_string()))];
|
||||
for model in models {
|
||||
let Some(id) = model
|
||||
.get("slug")
|
||||
@@ -483,7 +483,7 @@ fn parse_codex_models(stdout: &str) -> Option<Vec<AiModelInfo>> {
|
||||
.map(str::trim)
|
||||
.filter(|name| !name.is_empty())
|
||||
.map(ToString::to_string);
|
||||
result.push(AiModelInfo { id: id.to_string(), display_name });
|
||||
result.push(AiModelInfo::new(id, display_name));
|
||||
}
|
||||
|
||||
(result.len() > 1).then_some(result)
|
||||
@@ -568,6 +568,7 @@ pub async fn run_codex_agent(
|
||||
CliAgentProcessSpec {
|
||||
command,
|
||||
env,
|
||||
current_dir: None,
|
||||
stdin: Some(prompt.to_string()),
|
||||
dialect: CliAgentJsonlDialect::CodexExec,
|
||||
classify_spawn_error: classify_codex_spawn_error,
|
||||
@@ -614,6 +615,8 @@ mod tests {
|
||||
context_window: None,
|
||||
codex_cli_path: None,
|
||||
codex_cli_env: Default::default(),
|
||||
claude_code_cli_path: None,
|
||||
claude_code_cli_env: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1074,6 +1074,8 @@ mod tests {
|
||||
context_window: None,
|
||||
codex_cli_path: None,
|
||||
codex_cli_env: Default::default(),
|
||||
claude_code_cli_path: None,
|
||||
claude_code_cli_env: Default::default(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ pub mod agent_runtime;
|
||||
pub mod agent_service;
|
||||
pub mod agent_tools;
|
||||
pub mod ai;
|
||||
pub mod ai_claude_code_cli;
|
||||
pub mod ai_cli_agent;
|
||||
pub mod ai_codex_cli;
|
||||
pub mod changelog;
|
||||
|
||||
@@ -3752,7 +3752,9 @@ mod tests {
|
||||
|
||||
// ---- AI Config tests ----
|
||||
|
||||
use crate::ai::{AiApiStyle, AiAuthMethod, AiConfig, AiConfigItem, AiProvider, AiReasoningLevel};
|
||||
use crate::ai::{
|
||||
AiApiStyle, AiAuthMethod, AiConfig, AiConfigItem, AiEffortLevel, AiModelListItem, AiProvider, AiReasoningLevel,
|
||||
};
|
||||
|
||||
fn make_ai_config(name: &str, is_default: bool) -> AiConfigItem {
|
||||
AiConfigItem {
|
||||
@@ -3774,6 +3776,8 @@ mod tests {
|
||||
context_window: None,
|
||||
codex_cli_path: None,
|
||||
codex_cli_env: std::collections::HashMap::new(),
|
||||
claude_code_cli_path: None,
|
||||
claude_code_cli_env: std::collections::HashMap::new(),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -3783,7 +3787,15 @@ mod tests {
|
||||
let db = temp_db_path("ai-roundtrip");
|
||||
let storage = Storage::open(&db).await.unwrap();
|
||||
|
||||
let cfg = make_ai_config("test-config", true);
|
||||
let mut cfg = make_ai_config("test-config", true);
|
||||
cfg.config.provider = AiProvider::ClaudeCodeCli;
|
||||
cfg.config.model = "claude-sonnet-4-6".to_string();
|
||||
cfg.config.reasoning_level = AiReasoningLevel::Xhigh;
|
||||
cfg.config.models = vec![AiModelListItem {
|
||||
name: "claude-sonnet-4-6".to_string(),
|
||||
label: Some("Sonnet 4.6".to_string()),
|
||||
supported_effort_levels: vec![AiEffortLevel::Low, AiEffortLevel::High, AiEffortLevel::Xhigh],
|
||||
}];
|
||||
storage.save_ai_config_item(&cfg).await.unwrap();
|
||||
|
||||
let loaded = storage.load_ai_configs().await.unwrap();
|
||||
@@ -3791,7 +3803,14 @@ mod tests {
|
||||
assert_eq!(loaded[0].id, "cfg-test-config");
|
||||
assert_eq!(loaded[0].name, "test-config");
|
||||
assert!(loaded[0].is_default);
|
||||
assert_eq!(loaded[0].config.model, "gpt-4o");
|
||||
assert_eq!(loaded[0].config.model, "claude-sonnet-4-6");
|
||||
assert_eq!(loaded[0].config.reasoning_level, AiReasoningLevel::Xhigh);
|
||||
assert_eq!(loaded[0].config.models.len(), 1);
|
||||
assert_eq!(loaded[0].config.models[0].name, "claude-sonnet-4-6");
|
||||
assert_eq!(
|
||||
loaded[0].config.models[0].supported_effort_levels,
|
||||
vec![AiEffortLevel::Low, AiEffortLevel::High, AiEffortLevel::Xhigh]
|
||||
);
|
||||
|
||||
std::fs::remove_file(&db).ok();
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user