use std::path::{Path, PathBuf};
use anyhow::Context;
use super::common;
use super::{exec_with_env, find_on_path, has_flag, server, Effort};
const DSH_API_KEY_ENV: &str = "LLMMAN_API_KEY";
pub(super) const DSH_MISSING: &str =
"dsh is not installed, and there is no npx on PATH to run it with";
pub(super) fn launch_dsh(
model: &str,
api_key: &str,
vision: bool,
effort: Option<&Effort>,
extra_args: &[String],
) -> anyhow::Result<()> {
let launcher = dsh_launcher(extra_args);
if has_flag(launcher.args, "--patch", None) {
anyhow::bail!("llmman launch dsh manages --patch itself; pass other dsh flags after --");
}
if let Some(command) = launcher.command {
anyhow::bail!(
"dsh's `{command}` command cannot be combined with the --patch llmman passes it.\n\
Select a profile with `--profile {}` instead, or omit it for the default.",
if command == "web" { "web" } else { "<name>" }
);
}
let (bin, prefix) = find_dsh().ok_or_else(|| anyhow::anyhow!("{DSH_MISSING}"))?;
let dir = dsh_config_dir()?;
let settings_path = dir.join("settings.yaml");
write_dsh_settings(&settings_path, model, vision, effort)?;
let patch_path = dir.join("llmman.cordis.yml");
write_dsh_patch(&patch_path, &settings_path)?;
let mut args = prefix;
if !args.is_empty() {
eprintln!("[llmman] dsh is not installed; running {DSH_NPM_PACKAGE} with npx");
}
args.extend(dsh_args(&patch_path, extra_args));
exec_with_env(&bin, &args, &[(DSH_API_KEY_ENV, api_key)])
}
const DSH_NPM_PACKAGE: &str = "@deepseek-ai/dsh@latest";
pub(super) fn find_dsh() -> Option<(PathBuf, Vec<String>)> {
dsh_command(find_on_path("dsh"), || find_on_path("npx"))
}
fn dsh_command(
dsh: Option<PathBuf>,
npx: impl FnOnce() -> Option<PathBuf>,
) -> Option<(PathBuf, Vec<String>)> {
match dsh {
Some(bin) => Some((bin, Vec::new())),
None => Some((npx()?, vec!["--yes".into(), DSH_NPM_PACKAGE.into()])),
}
}
fn dsh_launcher(extra_args: &[String]) -> DshLauncher<'_> {
let mut end = 0;
let mut command = None;
while let Some(arg) = extra_args.get(end) {
if arg == "--" {
break;
}
end += match arg.as_str() {
"--profile" | "--patch" => 2,
found @ ("web" | "plugin") => {
command = command.or(Some(found));
1
}
_ if arg.starts_with('-') => 1,
_ => break,
};
}
DshLauncher {
args: &extra_args[..end.min(extra_args.len())],
command,
}
}
struct DshLauncher<'a> {
args: &'a [String],
command: Option<&'a str>,
}
fn dsh_args(patch_path: &Path, extra_args: &[String]) -> Vec<String> {
let mut args = Vec::new();
if !has_flag(dsh_launcher(extra_args).args, "--profile", None) {
args.push("web".to_string());
}
args.push("--patch".to_string());
args.push(patch_path.to_string_lossy().into_owned());
args.extend_from_slice(extra_args);
args
}
pub(super) fn dsh_config_dir() -> anyhow::Result<PathBuf> {
let conf = crate::config::user_path().context("no home directory")?;
let dir = conf.parent().context("llmman.conf has no directory")?;
Ok(dir.join("launch").join("dsh"))
}
fn write_dsh_settings(
path: &Path,
model: &str,
vision: bool,
effort: Option<&Effort>,
) -> anyhow::Result<()> {
let quoted_model = common::yaml_quote(model);
let base_url = common::yaml_quote(&format!("{}/v1", server()));
let input = if vision { "[text, image]" } else { "[text]" };
let (reasoning, efforts) = effort.map_or_else(Default::default, |e| {
let map: Vec<String> = (e.levels.iter())
.map(|&l| format!("{l}: {}", if l == "off" { "none" } else { l }))
.collect();
(
format!(" reasoning: {}\n", e.default),
format!(" reasoningEfforts: {{ {} }}\n", map.join(", ")),
)
});
let contents = format!(
"# Written by `llmman launch dsh`; edits are overwritten.\n\
agent-default-model:\n provider: llmman\n model: {quoted_model}\n\
llm-pi-ai:\n providers:\n llmman:\n displayName: llmman\n \
apiKeyEnv: {DSH_API_KEY_ENV}\n api: openai-completions\n baseURL: {base_url}\n\
{reasoning} \
models:\n - id: {quoted_model}\n name: {quoted_model}\n input: {input}\n\
{efforts}"
);
write_dsh_file(path, &contents)
}
fn write_dsh_patch(path: &Path, settings_path: &Path) -> anyhow::Result<()> {
write_dsh_file(path, &dsh_patch_document(settings_path))
}
fn dsh_patch_document(settings_path: &Path) -> String {
let quoted_settings_path = common::yaml_quote(&settings_path.to_string_lossy());
format!(
"# Written by `llmman launch dsh`; edits are overwritten.\n\
- id: settings\n config:\n path: {quoted_settings_path}\n"
)
}
fn write_dsh_file(path: &Path, contents: &str) -> anyhow::Result<()> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
}
crate::fsutil::write_atomic(path, contents.as_bytes())
.with_context(|| format!("write {}", path.display()))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::daemon;
#[test]
fn write_dsh_settings_points_at_llmman_with_the_key_in_the_environment() {
let dir = std::env::temp_dir().join(format!(
"llmman-dsh-settings-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let path = dir.join("settings.yaml");
write_dsh_settings(&path, "qwen3.5:0.8b", false, None).unwrap();
let contents = std::fs::read_to_string(&path).unwrap();
assert!(contents.contains("provider: llmman"));
assert!(contents.contains("model: \"qwen3.5:0.8b\""));
assert!(contents.contains(&format!("apiKeyEnv: {DSH_API_KEY_ENV}")));
assert!(contents.contains("api: openai-completions"));
assert!(contents.contains(&format!("baseURL: \"{}/v1\"", daemon::server())));
assert!(contents.contains("id: \"qwen3.5:0.8b\""));
assert!(!contents.contains("apiKey:"), "no literal key in the file");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn write_dsh_settings_declares_image_input_only_for_a_vision_model() {
let dir = std::env::temp_dir().join(format!(
"llmman-dsh-vision-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let path = dir.join("settings.yaml");
write_dsh_settings(&path, "m", true, None).unwrap();
assert!(std::fs::read_to_string(&path)
.unwrap()
.contains("input: [text, image]"));
write_dsh_settings(&path, "m", false, None).unwrap();
assert!(std::fs::read_to_string(&path)
.unwrap()
.contains("input: [text]"));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn dsh_falls_back_to_the_published_package_under_npx() {
let dsh = PathBuf::from("/usr/local/bin/dsh");
let npx = PathBuf::from("/usr/local/bin/npx");
assert_eq!(
dsh_command(Some(dsh.clone()), || panic!("npx looked up anyway")),
Some((dsh, Vec::new()))
);
assert_eq!(
dsh_command(None, || Some(npx.clone())),
Some((npx, vec!["--yes".to_string(), DSH_NPM_PACKAGE.to_string()]))
);
assert!(DSH_NPM_PACKAGE.starts_with("@deepseek-ai/dsh@"));
assert_eq!(dsh_command(None, || None), None);
}
#[test]
fn write_dsh_patch_names_the_settings_document() {
let dir = std::env::temp_dir().join(format!(
"llmman-dsh-patch-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let settings_path = dir.join("settings.yaml");
let patch_path = dir.join("llmman.cordis.yml");
write_dsh_patch(&patch_path, &settings_path).unwrap();
let contents = std::fs::read_to_string(&patch_path).unwrap();
assert!(contents.contains("id: settings"));
assert!(contents.contains(&format!(
"path: {}",
common::yaml_quote(&settings_path.to_string_lossy())
)));
let _ = std::fs::remove_dir_all(&dir);
let win = Path::new(r"C:\Users\hb\.config\llmman\launch\dsh\settings.yaml");
let rendered = dsh_patch_document(win);
assert!(rendered.contains(r#"path: "C:\\Users\\hb\\"#), "{rendered}");
assert!(!rendered.contains(r#"path: "C:\Users"#), "{rendered}");
}
#[test]
fn dsh_checks_stop_at_dshs_own_argument_boundary() {
let args = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
let forwarded_patch = args(&["--profile", "headless", "--", "--patch"]);
assert_eq!(
dsh_launcher(&forwarded_patch).args,
args(&["--profile", "headless"])
);
assert!(!has_flag(
dsh_launcher(&forwarded_patch).args,
"--patch",
None
));
let forwarded_profile = args(&["--", "--profile", "headless"]);
assert!(dsh_launcher(&forwarded_profile).args.is_empty());
assert_eq!(
dsh_args(Path::new("/p.yml"), &forwarded_profile),
["web", "--patch", "/p.yml", "--", "--profile", "headless"]
);
let task_mentions_patch = args(&["--profile", "headless", "explain", "the", "--patch"]);
assert_eq!(
dsh_launcher(&task_mentions_patch).args,
args(&["--profile", "headless"])
);
assert!(!has_flag(
dsh_launcher(&task_mentions_patch).args,
"--patch",
None
));
let app_level_profile = args(&["sometask", "--profile", "headless"]);
assert!(dsh_launcher(&app_level_profile).args.is_empty());
assert_eq!(
dsh_args(Path::new("/p.yml"), &app_level_profile),
[
"web",
"--patch",
"/p.yml",
"sometask",
"--profile",
"headless"
]
);
assert_eq!(
dsh_launcher(&args(&["--dump-config", "task"])).args,
args(&["--dump-config"])
);
assert_eq!(
dsh_launcher(&args(&["--profile=headless", "task"])).args,
args(&["--profile=headless"])
);
for command in ["web", "plugin"] {
let via_command = args(&[command, "--port", "8080"]);
assert_eq!(dsh_launcher(&via_command).command, Some(command));
let err = launch_dsh("m", "k", false, None, &via_command).unwrap_err();
assert!(err.to_string().contains("--profile"), "{err}");
}
let profile_web = args(&["--profile", "web", "--no-open"]);
assert_eq!(dsh_launcher(&profile_web).command, None);
assert_eq!(
dsh_args(Path::new("/p.yml"), &profile_web),
["--patch", "/p.yml", "--profile", "web", "--no-open"]
);
assert_eq!(dsh_launcher(&args(&["--patch", "web"])).command, None);
assert_eq!(dsh_launcher(&args(&["sometask", "web"])).command, None);
let plain = args(&["--profile", "headless"]);
assert_eq!(dsh_launcher(&plain).args, plain);
assert_eq!(
dsh_launcher(&args(&["--profile"])).args,
args(&["--profile"])
);
}
#[test]
fn launch_dsh_refuses_a_conflicting_patch_flag() {
let word = vec!["--patch".to_string(), "/tmp/x.yml".to_string()];
let err = launch_dsh("m", "k", false, None, &word).unwrap_err();
assert!(err.to_string().contains("--patch"), "{err}");
let joined = vec!["--patch=/tmp/x.yml".to_string()];
let err = launch_dsh("m", "k", false, None, &joined).unwrap_err();
assert!(err.to_string().contains("--patch"), "{err}");
}
#[test]
fn dsh_args_defaults_to_web_but_yields_to_a_caller_supplied_profile() {
let path = Path::new("/tmp/x/llmman.cordis.yml");
let none: Vec<String> = vec![];
assert_eq!(
dsh_args(path, &none),
["web", "--patch", "/tmp/x/llmman.cordis.yml"]
);
let headless = vec![
"--profile".to_string(),
"headless".to_string(),
"hi".to_string(),
];
assert_eq!(
dsh_args(path, &headless),
[
"--patch",
"/tmp/x/llmman.cordis.yml",
"--profile",
"headless",
"hi"
]
);
let joined = vec!["--profile=headless".to_string(), "hi".to_string()];
assert_eq!(
dsh_args(path, &joined),
[
"--patch",
"/tmp/x/llmman.cordis.yml",
"--profile=headless",
"hi"
]
);
}
#[test]
fn dsh_settings_start_the_route_at_the_variant() {
let path = std::env::temp_dir()
.join(format!("llmman-dsh-variant-{}", std::process::id()))
.join("settings.yaml");
let effort = Effort {
default: "low",
levels: vec!["off", "low", "high"],
};
write_dsh_settings(&path, "m", false, Some(&effort)).unwrap();
let contents = std::fs::read_to_string(&path).unwrap();
let _ = std::fs::remove_dir_all(path.parent().unwrap());
let doc: serde_json::Value = yaml_serde::from_str(&contents).expect("valid YAML");
let route = &doc["llm-pi-ai"]["providers"]["llmman"];
assert_eq!(route["reasoning"], "low");
assert_eq!(route["baseURL"], format!("{}/v1", daemon::server()));
assert_eq!(
route["models"][0]["reasoningEfforts"],
serde_json::json!({ "off": "none", "low": "low", "high": "high" })
);
}
}