Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Add DeepSeek Harness to unsloth start (#10097)
Nilay2ecb19df7e76
diff --git a/.github/scripts/agent-guides-drive.sh b/.github/scripts/agent-guides-drive.shindex 9d55900c8d7..a3ba87cf7ec 100755--- a/.github/scripts/agent-guides-drive.sh+++ b/.github/scripts/agent-guides-drive.sh@@ -8,8 +8,8 @@# already installed, so a failure here means the documented recipe in# unsloth_cli/commands/start.py no longer produces a working flow.#-# Self-updating: for all six agents (claude, codex, hermes, openclaw,-# opencode, pi) we obtain the exact env + command from+# Self-updating: for all seven agents (claude, codex, hermes, openclaw,+# opencode, pi, dsh) we obtain the exact env + command from# `unsloth start <agent> --no-launch` and run THAT, so a recipe change is# exercised automatically.#@@ -225,7 +225,11 @@ parse_connect() {# here, the same intent as claude/codex's per-call bypass flags.local yolo=()[ -n "${CONNECT_YOLO:-}" ] && yolo=(--yolo)- if ! unsloth start "$AGENT" --no-launch "${yolo[@]}" --api-key "$UNSLOTH_API_KEY" > "$raw" 2>&1; then+ # dsh's `--profile headless`: its default recipe opens the browser UI instead.+ # shellcheck disable=SC2206+ local passthrough=(${CONNECT_START_ARGS:-})+ if ! unsloth start "$AGENT" --no-launch "${yolo[@]}" --api-key "$UNSLOTH_API_KEY" \+ "${passthrough[@]}" > "$raw" 2>&1; thencat_redacted "$raw"guide_fail "'unsloth start ${AGENT} --no-launch' exited non-zero"fi@@ -297,6 +301,18 @@ crosscheck_contract() {cp "$cfg" "$REDACTED_DIR/pi-models.json"fi;;+ dsh)+ grep -q 'UNSLOTH_API_KEY' "$raw" \+ || guide_fail "dsh env key is no longer UNSLOTH_API_KEY (start.py _DSH_ENV_KEY)"+ home="$(raw_env DSH_HOME)"+ [ -n "$home" ] || guide_fail "DSH_HOME missing from connect output (start.py dsh())"+ cfg="$home/settings.yaml"+ if [ -f "$cfg" ]; then+ grep -q 'openai-completions' "$cfg" \+ || echo "::warning::dsh provider api is no longer 'openai-completions' (write_dsh_config)"+ cp "$cfg" "$REDACTED_DIR/dsh-settings.yaml"+ fi+ ;;esacredact "$REDACTED_DIR"/* 2>/dev/null || true}@@ -435,6 +451,7 @@ case "$MODE" inconnection)PROMPT='Reply with exactly the single word: pong'OUT="$LOGS_DIR/${AGENT}-connection.txt"+ case "$AGENT" in dsh) CONNECT_START_ARGS='--profile headless' ;; esacparse_connectcrosscheck_contract# claude/codex run in print mode via the flags start.py emits@@ -493,7 +510,11 @@ case "$MODE" in# from the repo root BEFORE cd-ing into the scratch work dir. opencode/openclaw# gate tool approval through their config (prompting by default), so file-edit# opts them into auto-approval to run edits/commands headlessly.- case "$AGENT" in opencode|openclaw) CONNECT_YOLO=1 ;; esac+ case "$AGENT" in+ opencode|openclaw) CONNECT_YOLO=1 ;;+ # A headless run has nobody to answer dsh's approval asks.+ dsh) CONNECT_YOLO=1; CONNECT_START_ARGS='--profile headless' ;;+ esacparse_connectcrosscheck_contract# File-edit needs real tools, so we cannot zero them as in connection.diff --git a/.github/scripts/agent-guides-install.sh b/.github/scripts/agent-guides-install.shindex 66c0b6ef040..b1df4f1955b 100755--- a/.github/scripts/agent-guides-install.sh+++ b/.github/scripts/agent-guides-install.sh@@ -10,7 +10,7 @@# unsloth_cli/commands/start.py at HEAD.## Usage: agent-guides-install.sh <agent>-# agent in: claude codex hermes openclaw opencode pi+# agent in: claude codex hermes openclaw opencode pi dshset -uo pipefailAGENT="${1:?usage: agent-guides-install.sh <agent>}"@@ -110,6 +110,10 @@ case "$AGENT" innpm_retry --ignore-scripts "@earendil-works/pi-coding-agent" \|| install_fail "npm install -g --ignore-scripts @earendil-works/pi-coding-agent failed";;+ dsh)+ # start.py install_hint: npm install -g @deepseek-ai/dsh+ npm_retry "@deepseek-ai/dsh" || install_fail "npm install -g @deepseek-ai/dsh failed"+ ;;*)install_fail "unknown agent '$AGENT'";;diff --git a/.github/workflows/local-agent-guides-ci.yml b/.github/workflows/local-agent-guides-ci.ymlindex a331bc0a6ea..871026a7bfb 100644--- a/.github/workflows/local-agent-guides-ci.yml+++ b/.github/workflows/local-agent-guides-ci.yml@@ -150,7 +150,7 @@ jobs:strategy:fail-fast: falsematrix:- agent: [claude, codex, hermes, openclaw, opencode, pi]+ agent: [claude, codex, hermes, openclaw, opencode, pi, dsh]opencode_channel: [stable]include:# OpenClaw needs Node 24; everything else is happy on 22.@@ -392,13 +392,16 @@ jobs:strategy:fail-fast: falsematrix:- agent: [claude, codex, hermes, openclaw, opencode, pi]+ agent: [claude, codex, hermes, openclaw, opencode, pi, dsh]include:- agent: openclawnode: '24'best_effort: true- agent: hermesbest_effort: true+ # dsh has no resume: turn 2 is a fresh session that re-reads hello.py.+ - agent: dsh+ best_effort: trueenv:# gemma-4-E4B served as a flat GGUF file (cache size tracks the .gguf 1:1,# no xet-chunk inflation; the -MTP- repo ships no separate draft file).diff --git a/README.md b/README.mdindex 9c9a99fb1fd..13214bdde62 100644--- a/README.md+++ b/README.md@@ -98,6 +98,7 @@ unsloth start claude --model unsloth/Qwen3.8-27B-GGUF:UD-Q4_K_XL| Hermes Agent | `unsloth start hermes` || OpenClaw | `unsloth start openclaw` || OpenCode | `unsloth start opencode` |+| DeepSeek Harness | `unsloth start dsh` |## 📥 InstallUnsloth can be used in three ways: **[Unsloth Desktop](https://unsloth.ai/download)**, the desktop app; **[Unsloth Studio](https://unsloth.ai/docs/new/studio/)**, the web UI; or **Unsloth Core**, the code based version.@@ -232,7 +233,7 @@ Read our [guide](https://unsloth.ai/docs/get-started/fine-tuning-llms-guide). Ad## 🦥 Unsloth News- **AMD training**: Train, run RL, chat and deploy on AMD GPUs across Windows, WSL and Linux. [Guide](https://unsloth.ai/docs/basics/amd)-- **Local models for any agent**: Use `unsloth start` with Claude Code, Codex, Hermes, OpenCode, OpenClaw and more through Unsloth's OpenAI- and Anthropic-compatible APIs. [Guide](https://unsloth.ai/docs/basics/api)+- **Local models for any agent**: Use `unsloth start` with Claude Code, Codex, Hermes, OpenCode, OpenClaw, DeepSeek Harness and more through Unsloth's OpenAI- and Anthropic-compatible APIs. [Guide](https://unsloth.ai/docs/basics/api)- **GLM-5.2**: Run Z.ai's 744B-parameter, 1M-context open model locally with Unsloth Dynamic GGUFs. [Guide](https://unsloth.ai/docs/models/glm-5.2)- **DeepSeek-V4**: Run DeepSeek-V4-Flash locally with corrected multi-turn and tool-calling behavior. [Guide](https://unsloth.ai/docs/models/deepseek-v4)- **Gemma 4**: Run and train Gemma 4 text, image and audio models with QAT, MTP, GGUF and MLX support. [Guide](https://unsloth.ai/docs/models/gemma-4)diff --git a/studio/backend/tests/test_coding_agents.py b/studio/backend/tests/test_coding_agents.pyindex b19da1dded6..8f5b401f01e 100644--- a/studio/backend/tests/test_coding_agents.py+++ b/studio/backend/tests/test_coding_agents.py@@ -3,16 +3,23 @@"""Tests for coding-agent CLI detection used by the API-keys settings panel."""+import os++from subprocess import CompletedProcessfrom unittest.mock import patch-from utils.coding_agents import CODING_AGENTS, detect_installed_coding_agents+from utils.coding_agents import (+ CODING_AGENTS,+ detect_installed_coding_agents,+ is_deepseek_harness_executable,+)def test_matches_unsloth_start_subcommands():# Each entry must be an actual `unsloth start <agent>` subcommand name# (unsloth_cli/commands/start.py). Spelled out here rather than imported# from that module, which pulls in the CLI's heavier dependencies.- assert CODING_AGENTS == ("claude", "codex", "openclaw", "opencode", "hermes", "pi")+ assert CODING_AGENTS == ("claude", "codex", "openclaw", "opencode", "hermes", "pi", "dsh")def test_detects_only_agents_present_on_path():@@ -48,3 +55,90 @@ def test_treats_a_path_lookup_error_as_not_installed():with patch("utils.coding_agents.shutil.which", side_effect = flaky_which):assert detect_installed_coding_agents() == ["claude"]+++def test_rejects_distributed_shell_as_deepseek_harness():+ with (+ patch(+ "utils.coding_agents.shutil.which",+ side_effect = lambda name, path = None: "/usr/bin/dsh" if name == "dsh" else None,+ ),+ patch("utils.coding_agents.is_deepseek_harness_executable", return_value = False),+ ):+ assert detect_installed_coding_agents() == []+++def test_detects_harness_behind_an_unrelated_earlier_path_entry(monkeypatch):+ system_dir = os.path.abspath("system-bin")+ harness_dir = os.path.abspath("user-bin")+ monkeypatch.setenv("PATH", os.pathsep.join((system_dir, harness_dir)))++ def which(name, path = None):+ if name != "dsh":+ return None+ return os.path.join(system_dir if path is None else path, "dsh")++ with (+ patch("utils.coding_agents.shutil.which", side_effect = which),+ patch(+ "utils.coding_agents.is_deepseek_harness_executable",+ side_effect = lambda executable, **_: os.path.dirname(executable) == harness_dir,+ ),+ ):+ assert detect_installed_coding_agents() == ["dsh"]+++def test_detects_dsh_that_identifies_as_deepseek_harness():+ with (+ patch(+ "utils.coding_agents.shutil.which",+ side_effect = lambda name: "/usr/local/bin/dsh" if name == "dsh" else None,+ ),+ patch("utils.coding_agents.is_deepseek_harness_executable", return_value = True),+ ):+ assert detect_installed_coding_agents() == ["dsh"]+++def test_identifies_an_npm_dsh_launcher_without_executing_it(tmp_path):+ launcher = tmp_path / "dsh"+ launcher.write_text(+ '#!/bin/sh\nexec node /usr/lib/node_modules/@deepseek-ai/dsh/lib/bin.js "$@"\n'+ )+ with patch(+ "utils.coding_agents.subprocess.run",+ side_effect = AssertionError("advisory detection must not execute the launcher"),+ ):+ assert is_deepseek_harness_executable(str(launcher), allow_execution = False)+++def test_explicit_launch_can_probe_a_custom_dsh_wrapper(tmp_path):+ launcher = tmp_path / "dsh"+ launcher.write_text("#!/bin/sh\n")+ with patch(+ "utils.coding_agents.subprocess.run",+ return_value = CompletedProcess(+ [str(launcher), "--help"],+ 0,+ stdout = "dsh: boot a DeepSeek Harness profile\n",+ stderr = "",+ ),+ ):+ assert is_deepseek_harness_executable(str(launcher))+++def test_explicit_probe_replaces_undecodable_help_bytes(tmp_path):+ launcher = tmp_path / "dsh"+ launcher.write_text("#!/bin/sh\n")++ def probe(command, **kwargs):+ assert kwargs["encoding"] == "utf-8"+ assert kwargs["errors"] == "replace"+ return CompletedProcess(+ command,+ 0,+ stdout = "\ufffd dsh: boot a DeepSeek Harness profile\n",+ stderr = "",+ )++ with patch("utils.coding_agents.subprocess.run", side_effect = probe):+ assert is_deepseek_harness_executable(str(launcher))diff --git a/studio/backend/utils/coding_agents.py b/studio/backend/utils/coding_agents.pyindex 2d863bff747..0878360a18d 100644--- a/studio/backend/utils/coding_agents.py+++ b/studio/backend/utils/coding_agents.py@@ -10,19 +10,97 @@ the frontend a way to ask which of those CLIs are actually installed so it candefault to one the user can run immediately."""+import osimport shutil+import subprocess+from typing import Optional-# Keep in sync with the `unsloth start <agent>` subcommands defined in unsloth_cli/commands/start.py. Each entry is the-# exact executable name that subcommand launches, so a hit here means the binary is on PATH without the user installing-# anything first.-CODING_AGENTS: tuple[str, ...] = ("claude", "codex", "openclaw", "opencode", "hermes", "pi")++_DEEPSEEK_HARNESS_HELP_MARKER = "DeepSeek Harness"+_DEEPSEEK_HARNESS_FILE_MARKERS = (+ b"deepseek harness",+ b"@deepseek-ai/dsh",+ b"@deepseek-ai+dsh",+)++# Keep in sync with the `unsloth start <agent>` subcommands defined in+# unsloth_cli/commands/start.py. Each entry is the exact executable name that+# subcommand launches, so a hit here means `unsloth start <agent>` can find the+# binary on PATH without the user installing anything first.+CODING_AGENTS: tuple[str, ...] = ("claude", "codex", "openclaw", "opencode", "hermes", "pi", "dsh")+++def is_deepseek_harness_executable(executable: str, *, allow_execution: bool = True) -> bool:+ """Return whether ``executable`` identifies itself as DeepSeek Harness."""+ try:+ with open(executable, "rb") as launcher:+ contents = launcher.read(256 * 1024).lower()+ except OSError:+ contents = b""+ if any(marker in contents for marker in _DEEPSEEK_HARNESS_FILE_MARKERS):+ return True+ if not allow_execution:+ return False+ try:+ result = subprocess.run(+ [executable, "--help"],+ check = False,+ capture_output = True,+ text = True,+ encoding = "utf-8",+ errors = "replace",+ timeout = 5,+ )+ except (OSError, subprocess.TimeoutExpired):+ return False+ output = (result.stdout or "") + (result.stderr or "")+ return result.returncode == 0 and _DEEPSEEK_HARNESS_HELP_MARKER in output+++def deepseek_harness_executables_on_path(path: Optional[str] = None) -> list[str]:+ """Return every distinct ``dsh`` executable in PATH order."""+ if path is None:+ path = os.environ.get("PATH")+ if path is None:+ path = os.defpath+ executables = []+ seen = set()+ for directory in path.split(os.pathsep):+ try:+ executable = shutil.which("dsh", path = directory)+ except OSError:+ continue+ if executable is None:+ continue+ key = os.path.normcase(os.path.abspath(executable))+ if key in seen:+ continue+ seen.add(key)+ executables.append(executable)+ return executablesdef _is_on_path(agent: str) -> bool:# shutil.which returns None on a miss but PATH lookups can still raise, and this is advisory, so a lookup failure# reads as "not installed" rather than breaking the endpoint.try:- return shutil.which(agent) is not None+ executable = shutil.which(agent)+ if executable is None:+ return False+ if agent == "dsh":+ # Detection runs when the settings panel opens, so it must not execute an+ # arbitrary same-named program. Official npm/pnpm launchers contain one of+ # the package or product markers above; explicit launches may additionally+ # use the bounded --help probe for custom wrappers.+ if is_deepseek_harness_executable(executable, allow_execution = False):+ return True+ return any(+ is_deepseek_harness_executable(candidate, allow_execution = False)+ for candidate in deepseek_harness_executables_on_path()+ if os.path.normcase(os.path.abspath(candidate))+ != os.path.normcase(os.path.abspath(executable))+ )+ return Trueexcept OSError:return Falsediff --git a/studio/frontend/src/features/settings/components/usage-examples.tsx b/studio/frontend/src/features/settings/components/usage-examples.tsxindex 066870abd5f..cf8cda50fd1 100644--- a/studio/frontend/src/features/settings/components/usage-examples.tsx+++ b/studio/frontend/src/features/settings/components/usage-examples.tsx@@ -134,12 +134,16 @@ const DOC_LINKS = [label: "Hermes Agent",href: "https://unsloth.ai/docs/integrations/hermes-agent",},+ {+ label: "DeepSeek Harness",+ href: "https://github.com/deepseek-ai/deepseek-harness",+ },];// Fallback until the backend's installed-CLI check resolves. Mirrors// CODING_AGENTS in studio/backend/utils/coding_agents.py, minus HIDDEN_AGENTS// (see ../api/coding-agents.ts).-const DEFAULT_AGENTS = ["claude", "codex", "openclaw", "opencode", "hermes"];+const DEFAULT_AGENTS = ["claude", "codex", "openclaw", "opencode", "hermes", "dsh"];// The agent selection resets to this whenever an auto-pick is no longer// trustworthy (leaving loopback, or the only compatible detected agent// stops being compatible) rather than lingering on a stale choice.@@ -150,6 +154,7 @@ const AGENT_LABELS: Record<string, string> = {openclaw: "OpenClaw",opencode: "OpenCode",hermes: "Hermes",+ dsh: "DeepSeek Harness",};const j = (s: string): string => JSON.stringify(s);diff --git a/studio/frontend/src/features/settings/tabs/agents-tab.tsx b/studio/frontend/src/features/settings/tabs/agents-tab.tsxindex 5f33ebd22de..46ad640e197 100644--- a/studio/frontend/src/features/settings/tabs/agents-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/agents-tab.tsx@@ -185,6 +185,13 @@ const SUPPORTED_AGENTS: AgentDetails[] = [icon: "opencode-light.svg",darkIcon: "opencode-dark.svg",},+ {+ id: "dsh",+ name: "DeepSeek Harness",+ docsUrl: "https://github.com/deepseek-ai/deepseek-harness",+ color: "#4D6BFE",+ mark: "ds",+ },];const FALLBACK_AGENT = SUPPORTED_AGENTS[0];diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 385c16bf086..609c63fab76 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -1243,7 +1243,7 @@ export const ar = {description:"اربط وكلاء البرمجة مثل Claude Code وCodex بنموذج محلي باستخدام unsloth start.",intro:- "يربط Claude Code وCodex وHermes وOpenClaw وOpenCode وغيرها من الوكلاء بنموذج يقدّمه Unsloth محليًا، دون اتصال بالإنترنت تمامًا. يشغّل خادمًا متوافقًا مع OpenAI ولا يمسّ ملفات إعدادات وكيلك إطلاقًا.",+ "يربط Claude Code وCodex وDeepSeek Harness وHermes وOpenClaw وOpenCode وغيرها من الوكلاء بنموذج يقدّمه Unsloth محليًا، دون اتصال بالإنترنت تمامًا. يشغّل خادمًا متوافقًا مع OpenAI ولا يمسّ ملفات إعدادات وكيلك إطلاقًا.",readDocs: "قراءة التوثيق",copy: "نسخ",copied: "تم النسخ",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 4c29c2234c0..4d064dd3f4e 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -1272,7 +1272,7 @@ export const de = {description:"Verbinden Sie Coding-Agenten wie Claude Code und Codex über unsloth start mit einem lokalen Modell.",intro:- "verbindet Claude Code, Codex, Hermes, OpenClaw, OpenCode und weitere Agenten mit einem lokal von Unsloth bereitgestellten Modell, vollständig offline. Es startet einen OpenAI-kompatiblen Server und verändert nie die Konfigurationsdateien Ihres Agenten.",+ "verbindet Claude Code, Codex, DeepSeek Harness, Hermes, OpenClaw, OpenCode und weitere Agenten mit einem lokal von Unsloth bereitgestellten Modell, vollständig offline. Es startet einen OpenAI-kompatiblen Server und verändert nie die Konfigurationsdateien Ihres Agenten.",readDocs: "Dokumentation lesen",copy: "Kopieren",copied: "Kopiert",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex a309bcf6845..956f6990fa5 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -1240,7 +1240,7 @@ export const en = {description:"Connect coding agents like Claude Code and Codex to a local model with unsloth start.",intro:- "connects Claude Code, Codex, Hermes, OpenClaw, OpenCode and other agents to a model served locally by Unsloth, fully offline. It runs an OpenAI-compatible server and never touches your agent's config files.",+ "connects Claude Code, Codex, DeepSeek Harness, Hermes, OpenClaw, OpenCode and other agents to a model served locally by Unsloth, fully offline. It runs an OpenAI-compatible server and never touches your agent's config files.",readDocs: "Read the docs",copy: "Copy",copied: "Copied",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex f45970efe90..6120f03d59a 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -1266,7 +1266,7 @@ export const es = {description:"Conecta agentes de programación como Claude Code y Codex a un modelo local con unsloth start.",intro:- "conecta Claude Code, Codex, Hermes, OpenClaw, OpenCode y otros agentes a un modelo servido localmente por Unsloth, totalmente sin conexión. Ejecuta un servidor compatible con OpenAI y nunca modifica los archivos de configuración de tu agente.",+ "conecta Claude Code, Codex, DeepSeek Harness, Hermes, OpenClaw, OpenCode y otros agentes a un modelo servido localmente por Unsloth, totalmente sin conexión. Ejecuta un servidor compatible con OpenAI y nunca modifica los archivos de configuración de tu agente.",readDocs: "Leer la documentación",copy: "Copiar",copied: "Copiado",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex de7637f6997..3222489f5cc 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -1270,7 +1270,7 @@ export const fr = {description:"Connectez des agents de codage comme Claude Code et Codex à un modèle local avec unsloth start.",intro:- "connecte Claude Code, Codex, Hermes, OpenClaw, OpenCode et d'autres agents à un modèle servi localement par Unsloth, entièrement hors ligne. Il lance un serveur compatible OpenAI et ne touche jamais aux fichiers de configuration de votre agent.",+ "connecte Claude Code, Codex, DeepSeek Harness, Hermes, OpenClaw, OpenCode et d'autres agents à un modèle servi localement par Unsloth, entièrement hors ligne. Il lance un serveur compatible OpenAI et ne touche jamais aux fichiers de configuration de votre agent.",readDocs: "Lire la documentation",copy: "Copier",copied: "Copié",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 786e200708f..3f2734b2ed0 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -1246,7 +1246,7 @@ export const hi = {description:"unsloth start की मदद से Claude Code और Codex जैसे कोडिंग एजेंट को लोकल मॉडल से जोड़ें।",intro:- "Claude Code, Codex, Hermes, OpenClaw, OpenCode और दूसरे एजेंट को Unsloth द्वारा लोकली सर्व किए गए मॉडल से जोड़ता है, पूरी तरह ऑफ़लाइन। यह एक OpenAI-संगत सर्वर चलाता है और आपके एजेंट की कॉन्फ़िगरेशन फ़ाइलों को कभी नहीं छूता।",+ "Claude Code, Codex, DeepSeek Harness, Hermes, OpenClaw, OpenCode और दूसरे एजेंट को Unsloth द्वारा लोकली सर्व किए गए मॉडल से जोड़ता है, पूरी तरह ऑफ़लाइन। यह एक OpenAI-संगत सर्वर चलाता है और आपके एजेंट की कॉन्फ़िगरेशन फ़ाइलों को कभी नहीं छूता।",readDocs: "दस्तावेज़ पढ़ें",copy: "कॉपी करें",copied: "कॉपी किया गया",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex c21f360b04c..ef8a5eb2e36 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -1238,7 +1238,7 @@ export const it = {description:"Collega agenti di programmazione come Claude Code e Codex a un modello locale con unsloth start.",intro:- "collega Claude Code, Codex, Hermes, OpenClaw, OpenCode e altri agenti a un modello servito localmente da Unsloth, completamente offline. Avvia un server compatibile con le API OpenAI e non modifica i file di configurazione del tuo agente.",+ "collega Claude Code, Codex, DeepSeek Harness, Hermes, OpenClaw, OpenCode e altri agenti a un modello servito localmente da Unsloth, completamente offline. Avvia un server compatibile con le API OpenAI e non modifica i file di configurazione del tuo agente.",readDocs: "Leggi la documentazione",copy: "Copia",copied: "Copiato",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 150ab4a2512..4ef4cb463e9 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -1225,7 +1225,7 @@ export const ja = {description:"unsloth start で Claude Code や Codex などのコーディングエージェントをローカルモデルに接続します。",intro:- "は Claude Code、Codex、Hermes、OpenClaw、OpenCode などのエージェントを、Unsloth がローカルで提供するモデルに完全オフラインで接続します。OpenAI 互換サーバーを起動し、エージェントの設定ファイルには一切手を加えません。",+ "は Claude Code、Codex、DeepSeek Harness、Hermes、OpenClaw、OpenCode などのエージェントを、Unsloth がローカルで提供するモデルに完全オフラインで接続します。OpenAI 互換サーバーを起動し、エージェントの設定ファイルには一切手を加えません。",readDocs: "ドキュメントを読む",copy: "コピー",copied: "コピーしました",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex c784e4332e1..24bef3b8ec9 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -1239,7 +1239,7 @@ export const ko = {description:"unsloth start로 Claude Code, Codex 같은 코딩 에이전트를 로컬 모델에 연결하세요.",intro:- "명령은 Claude Code, Codex, Hermes, OpenClaw, OpenCode를 비롯한 에이전트를 Unsloth가 로컬에서 제공하는 모델에 완전히 오프라인으로 연결합니다. OpenAI 호환 서버를 실행하며 에이전트의 설정 파일은 전혀 건드리지 않습니다.",+ "명령은 Claude Code, Codex, DeepSeek Harness, Hermes, OpenClaw, OpenCode를 비롯한 에이전트를 Unsloth가 로컬에서 제공하는 모델에 완전히 오프라인으로 연결합니다. OpenAI 호환 서버를 실행하며 에이전트의 설정 파일은 전혀 건드리지 않습니다.",readDocs: "문서 보기",copy: "복사",copied: "복사됨",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex e5fd4b52b90..9c9bb570c3a 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -1254,7 +1254,7 @@ export const ptBR = {description:"Conecte agentes de código como Claude Code e Codex a um modelo local com unsloth start.",intro:- "conecta Claude Code, Codex, Hermes, OpenClaw, OpenCode e outros agentes a um modelo servido localmente pelo Unsloth, totalmente offline. Ele executa um servidor compatível com a API da OpenAI e nunca altera os arquivos de configuração do seu agente.",+ "conecta Claude Code, Codex, DeepSeek Harness, Hermes, OpenClaw, OpenCode e outros agentes a um modelo servido localmente pelo Unsloth, totalmente offline. Ele executa um servidor compatível com a API da OpenAI e nunca altera os arquivos de configuração do seu agente.",readDocs: "Ler a documentação",copy: "Copiar",copied: "Copiado",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 8e293c30031..ff30d75409d 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -1249,7 +1249,7 @@ export const ru = {description:"Подключение кодинг-агентов, таких как Claude Code и Codex, к локальной модели с помощью unsloth start.",intro:- "подключает Claude Code, Codex, Hermes, OpenClaw, OpenCode и других агентов к модели, которую Unsloth обслуживает локально, полностью офлайн. Запускается OpenAI-совместимый сервер, а файлы конфигурации вашего агента остаются нетронутыми.",+ "подключает Claude Code, Codex, DeepSeek Harness, Hermes, OpenClaw, OpenCode и других агентов к модели, которую Unsloth обслуживает локально, полностью офлайн. Запускается OpenAI-совместимый сервер, а файлы конфигурации вашего агента остаются нетронутыми.",readDocs: "Открыть документацию",copy: "Копировать",copied: "Скопировано",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 3f7a016ccd0..16f07e270a2 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -1216,7 +1216,7 @@ export const zhCN = {description:"使用 unsloth start 将 Claude Code、Codex 等编程智能体连接到本地模型。",intro:- "可将 Claude Code、Codex、Hermes、OpenClaw、OpenCode 等智能体连接到由 Unsloth 在本地提供服务的模型,全程离线。它会启动一个兼容 OpenAI 的服务器,并且从不改动智能体的配置文件。",+ "可将 Claude Code、Codex、DeepSeek Harness、Hermes、OpenClaw、OpenCode 等智能体连接到由 Unsloth 在本地提供服务的模型,全程离线。它会启动一个兼容 OpenAI 的服务器,并且从不改动智能体的配置文件。",readDocs: "查看文档",copy: "复制",copied: "已复制",diff --git a/unsloth_cli/__init__.py b/unsloth_cli/__init__.pyindex fc601c4eeb2..e7526431509 100644--- a/unsloth_cli/__init__.py+++ b/unsloth_cli/__init__.py@@ -210,7 +210,8 @@ if not _windows_studio_mutation_entry:app.add_typer(start_app,name = "start",- help = "Start a coding agent (Claude, Codex, OpenClaw, OpenCode, Hermes, Pi) against Unsloth.",+ help = "Start a coding agent (Claude, Codex, OpenClaw, OpenCode, Hermes, Pi, dsh) "+ "against Unsloth.",)# backwards-compatible hidden alias: `unsloth connect` routes to `unsloth start`.app.add_typer(diff --git a/unsloth_cli/commands/start.py b/unsloth_cli/commands/start.pyindex acd84804b38..713bf2635ef 100644--- a/unsloth_cli/commands/start.py+++ b/unsloth_cli/commands/start.py@@ -31,6 +31,10 @@ import clickimport typerfrom typer.core import TyperCommand+from studio.backend.utils.coding_agents import (+ deepseek_harness_executables_on_path,+ is_deepseek_harness_executable,+)from unsloth_cli._inference import (_USER_AGENT,_studio_token,@@ -99,6 +103,14 @@ _HERMES_POSIX_INSTALL_HINT = (# overrides in config.yaml. write_hermes_config claims this value for smaller# windows and scales the compaction threshold back down to the real window._HERMES_MIN_CONTEXT = 65536+_DSH_PROVIDER = "unsloth"+_DSH_ENV_KEY = "UNSLOTH_API_KEY"+_DSH_PACKAGE = "@deepseek-ai/dsh"+# dsh picks its sandbox+approval preset from DSH_PERMISSION_MODE via ??, so omitting it+# would inherit a danger-full-access exported in the parent shell, and "" is not unset+# to ??. Pin the mode in both directions instead of only setting it for --yolo.+_DSH_SAFE_PERMISSION_MODE = "workspace-write"+_DSH_YOLO_PERMISSION_MODE = "danger-full-access"_PI_PROVIDER = "unsloth"_SUBAGENT_NAME = "unsloth"_SUBAGENT_DESCRIPTION = (@@ -371,7 +383,7 @@ _PERSIST_OPTION = typer.Option(rich_help_panel = _PANEL_SESSION,help = ("Keep this agent's Unsloth-managed session dir so you can resume it later. "- "codex/openclaw/hermes/pi have their whole home relocated into an Unsloth dir "+ "codex/openclaw/hermes/pi/dsh have their whole home relocated into an Unsloth dir ""that is a throwaway temp dir (wiped on exit) by default; with --persist it ""lives under the Unsloth agents dir and survives, so their own resume can reopen ""it. claude and opencode keep sessions in your own stores (~/.claude, "@@ -596,6 +608,18 @@ def _hermes_resume_oneshot_args(args: list[str]) -> list[str]:return args+_DSH_LAUNCHER_ARGS = frozenset(+ "--profile --patch --dump-config --dump-default-config -V --version plugin web".split()+)+++def _dsh_command(args: list[str]) -> list[str]:+ head = args[0] if args else ""+ if head in _DSH_LAUNCHER_ARGS or head.startswith(("--profile=", "--patch=")):+ return ["dsh", *args]+ return ["dsh", "web", *args]++class LoadOptions(NamedTuple):"""Model-load knobs forwarded to /api/inference/load when --model triggers a load."""@@ -1487,6 +1511,20 @@ def _write_private_text(path: Path, text: str) -> None:handle.write(text)+def _read_yaml_object(path: Path) -> Optional[dict]:+ import yaml++ if not path.exists():+ return {}+ try:+ data = yaml.safe_load(path.read_text(encoding = "utf-8"))+ except (yaml.YAMLError, OSError):+ return None+ if data is None:+ return {}+ return data if isinstance(data, dict) else None++def _read_json_object(path: Path) -> Optional[dict]:# {} when missing, None when it can't be parsed as an object (so the caller# leaves a user-managed file untouched rather than clobbering it).@@ -3872,6 +3910,23 @@ def _which_with_install_dirs(name: str) -> Optional[str]:os.environ["PATH"] = original+def _which_deepseek_harness_with_install_dirs() -> Optional[str]:+ """Find the first valid DeepSeek Harness even when another ``dsh`` shadows it."""+ original = os.environ.get("PATH")+ _augment_path_with_install_dirs()+ try:+ for executable in deepseek_harness_executables_on_path():+ executable = _prefer_windows_cmd_sibling(executable)+ if executable is not None and is_deepseek_harness_executable(executable):+ return executable+ return None+ finally:+ if original is None:+ os.environ.pop("PATH", None)+ else:+ os.environ["PATH"] = original++def _install_source(install_hint: str) -> Optional[str]:"""The first http(s) URL an install hint fetches, or None (e.g. an npm install)."""match = re.search(r"https?://[^\s'\")]+", install_hint)@@ -4019,10 +4074,32 @@ def _install_agent(name: str, install_hint: str) -> Optional[str]:def _resolve_or_install_agent(name: str, install_hint: str, resolver) -> str:- executable = resolver(name) or _install_agent(name, install_hint)- if executable is None:- _fail(f"`{name}` not found on PATH. Install it with: {install_hint}")- return executable+ executable = resolver(name)+ invalid_executable = None+ if executable is not None:+ if name != "dsh" or is_deepseek_harness_executable(executable):+ return executable+ invalid_executable = executable+ executable = _which_deepseek_harness_with_install_dirs()+ if executable is not None:+ return executable++ executable = _install_agent(name, install_hint)+ if executable is not None:+ if name != "dsh" or is_deepseek_harness_executable(executable):+ return executable+ invalid_executable = executable+ if name == "dsh":+ executable = _which_deepseek_harness_with_install_dirs()+ if executable is not None:+ return executable++ if invalid_executable is not None:+ _fail(+ f"`{invalid_executable}` is not DeepSeek Harness. Install DeepSeek Harness "+ f"with: {install_hint}"+ )+ _fail(f"`{name}` not found on PATH. Install it with: {install_hint}")def _require_agent_for_launch(name: str, install_hint: str, launch: bool) -> Optional[str]:@@ -4922,6 +4999,43 @@ def write_pi_subagent_config()+def write_dsh_config(base: str, model: dict, path: Path) -> None:+ import yaml++ config = _read_yaml_object(path)+ if config is None:+ typer.echo(+ f"Warning: couldn't parse {path} — add an '{_DSH_PROVIDER}' provider "+ "there yourself, or move the file aside and re-run.",+ err = True,+ )+ return+ model_entry = {"id": model["id"]}+ window = model.get("context_length") or model.get("max_context_length")+ if window:+ window = int(window)+ model_entry["contextWindow"] = window+ model_entry["maxTokens"] = min(window // 4, 8192)+ _subdict(_subdict(config, "llm-pi-ai"), "providers")[_DSH_PROVIDER] = {+ "displayName": "Unsloth Studio",+ "api": "openai-completions",+ "baseURL": f"{base}/v1",+ "apiKeyEnv": _DSH_ENV_KEY,+ # pi-ai reads an unknown base URL as OpenAI itself.+ "compat": {"supportsDeveloperRole": False, "maxTokensField": "max_tokens"},+ "models": [model_entry],+ }+ _subdict(config, "agent-default-model").update(+ provider = _DSH_PROVIDER,+ model = model["id"],+ )+ text = yaml.safe_dump(config, sort_keys = False)+ if not path.exists() or path.read_text(encoding = "utf-8") != text:+ path.parent.mkdir(parents = True, exist_ok = True)+ path.write_text(text, encoding = "utf-8")+ typer.echo(f"Updated {path}")++@start_app.command("claude", cls = _PassthroughCommand, context_settings = _PASSTHROUGH)def claude(ctx: typer.Context,@@ -5652,3 +5766,69 @@ def pi(install_hint = install_hint,clear_screen = True,)+++@start_app.command("dsh", cls = _PassthroughCommand, context_settings = _PASSTHROUGH)+def dsh(+ ctx: typer.Context,+ model: Optional[str] = _MODEL_OPTION,+ api_key: Optional[str] = _KEY_OPTION,+ launch: bool = _LAUNCH_OPTION,+ gguf_variant: Optional[str] = _GGUF_VARIANT_OPTION,+ max_seq_length: int = _CONTEXT_OPTION,+ load_in_4bit: bool = _LOAD_4BIT_OPTION,+ tensor_parallel: bool = _TENSOR_PARALLEL_OPTION,+ gpu_memory_mode: Optional[Literal["auto", "manual"]] = _GPU_MEMORY_MODE_OPTION,+ enable_tools: bool = _ENABLE_TOOLS_OPTION,+ tool_call_healing: Optional[bool] = _TOOL_CALL_HEALING_OPTION,+ tool_call_nudging: Optional[bool] = _TOOL_CALL_NUDGING_OPTION,+ reasoning: Optional[Literal["on", "off", "auto"]] = _REASONING_OPTION,+ reasoning_effort: Optional[str] = _REASONING_EFFORT_OPTION,+ temperature: Optional[float] = _TEMPERATURE_OPTION,+ top_p: Optional[float] = _TOP_P_OPTION,+ top_k: Optional[int] = _TOP_K_OPTION,+ min_p: Optional[float] = _MIN_P_OPTION,+ repetition_penalty: Optional[float] = _REPETITION_PENALTY_OPTION,+ presence_penalty: Optional[float] = _PRESENCE_PENALTY_OPTION,+ serve: bool = _SERVE_OPTION,+ yolo: bool = _YOLO_OPTION,+ persist: bool = _PERSIST_OPTION,+):+ """Point DeepSeek Harness (dsh) at the running Unsloth server and start it."""+ model, ctx.args[:] = _consume_positional_model(model, ctx.args)+ _reject_as_subagent("dsh", ctx.args)+ command = _dsh_command(ctx.args)+ install_hint = _npm_install_hint(_DSH_PACKAGE)+ _require_agent_for_launch("dsh", install_hint, launch)+ base, key, entry = _connect(+ api_key,+ model,+ LoadOptions(gguf_variant, max_seq_length, load_in_4bit, tensor_parallel, gpu_memory_mode),+ serve = serve,+ launch = launch,+ server_options = ServerOptions(+ enable_tools = enable_tools,+ tool_call_healing = tool_call_healing,+ tool_call_nudging = tool_call_nudging,+ reasoning = reasoning,+ reasoning_effort = reasoning_effort,+ temperature = temperature,+ top_p = top_p,+ top_k = top_k,+ min_p = min_p,+ repetition_penalty = repetition_penalty,+ presence_penalty = presence_penalty,+ ),+ )+ with _session_config("dsh", launch, persist = persist) as home:+ write_dsh_config(base, entry, home / "settings.yaml")+ env = {+ _DSH_ENV_KEY: key,+ "DSH_HOME": str(home),+ # dsh uploads session records once a user records /feedback.+ "DSH_TELEMETRY_DISABLED": "1",+ "DSH_PERMISSION_MODE": (+ _DSH_YOLO_PERMISSION_MODE if yolo else _DSH_SAFE_PERMISSION_MODE+ ),+ }+ _run(base, entry, env, command, launch = launch, install_hint = install_hint)diff --git a/unsloth_cli/tests/test_start.py b/unsloth_cli/tests/test_start.pyindex 127d5b1ec5b..dc6e59c9851 100644--- a/unsloth_cli/tests/test_start.py+++ b/unsloth_cli/tests/test_start.py@@ -1282,7 +1282,7 @@ def test_subagent_model_id_warns_when_status_unavailable(monkeypatch, capsys):assert "could not verify the loaded GGUF variant" in capsys.readouterr().err[email protected]("agent", ["openclaw", "hermes"])[email protected]("agent", ["openclaw", "hermes", "dsh"])@pytest.mark.parametrize("flag", ["--as-subagent", "--as-subagent=true", "--as-subagent=false"])def test_unsupported_agents_reject_as_subagent(agent, flag):result = CliRunner().invoke(start.start_app, [agent, flag])@@ -1290,7 +1290,9 @@ def test_unsupported_agents_reject_as_subagent(agent, flag):assert f"--as-subagent is not supported for {agent}." in result.output[email protected]("agent", ["claude", "codex", "openclaw", "opencode", "hermes", "pi"])+ "agent", ["claude", "codex", "openclaw", "opencode", "hermes", "pi", "dsh"]+)def test_launch_preflights_agent_before_connect(agent, monkeypatch):events = []if agent == "opencode":@@ -1315,6 +1317,57 @@ def test_launch_preflights_agent_before_connect(agent, monkeypatch):assert events == ["agent", "connect"]+def test_dsh_rejects_an_unrelated_executable_before_connect(monkeypatch):+ monkeypatch.setattr(start, "_which_with_install_dirs", lambda _: "/usr/bin/dsh")+ monkeypatch.setattr(start, "is_deepseek_harness_executable", lambda _: False)+ monkeypatch.setattr(start, "_install_agent", lambda *_: None)+ monkeypatch.setattr(+ start,+ "_connect",+ lambda *args, **kwargs: pytest.fail("the wrong dsh must be rejected before connection"),+ )++ result = CliRunner().invoke(start.start_app, ["dsh"])++ assert result.exit_code == 1+ assert "`/usr/bin/dsh` is not DeepSeek Harness" in result.output+++def test_dsh_resolver_searches_past_an_unrelated_earlier_path_entry(monkeypatch, tmp_path):+ shadow_dir = tmp_path / "system-bin"+ harness_dir = tmp_path / "user-bin"+ shadow_dir.mkdir()+ harness_dir.mkdir()+ suffix = ".cmd" if os.name == "nt" else ""+ for directory in (shadow_dir, harness_dir):+ executable = directory / f"dsh{suffix}"+ executable.write_text("@echo off\n" if os.name == "nt" else "#!/bin/sh\n")+ if os.name != "nt":+ executable.chmod(0o755)++ monkeypatch.setenv("PATH", os.pathsep.join((str(shadow_dir), str(harness_dir))))+ monkeypatch.setattr(start.Path, "home", lambda: tmp_path / "missing-home")+ monkeypatch.setattr(start, "_managed_node_tools", lambda: None)+ monkeypatch.setattr(+ start,+ "is_deepseek_harness_executable",+ lambda executable: Path(executable).parent == harness_dir,+ )+ monkeypatch.setattr(+ start,+ "_install_agent",+ lambda *_: pytest.fail("an existing later Harness must be used without reinstalling"),+ )++ resolved = start._resolve_or_install_agent(+ "dsh",+ "npm install -g @deepseek-ai/dsh",+ start._which_with_install_dirs,+ )++ assert Path(resolved).parent == harness_dir++def test_declined_opencode_subagent_install_stops_before_connect(monkeypatch):installs = []monkeypatch.setattr(start, "_which_with_install_dirs", lambda _: None)@@ -1336,7 +1389,9 @@ def test_declined_opencode_subagent_install_stops_before_connect(monkeypatch):assert installs[0][0] == "opencode"[email protected]("agent", ["claude", "codex", "openclaw", "opencode", "hermes", "pi"])+ "agent", ["claude", "codex", "openclaw", "opencode", "hermes", "pi", "dsh"]+)def test_noninteractive_missing_agent_stops_before_connect(agent, monkeypatch):monkeypatch.setattr(start, "_which_with_install_dirs", lambda _: None)monkeypatch.setattr(@@ -1356,7 +1411,7 @@ def test_noninteractive_missing_agent_stops_before_connect(agent, monkeypatch):assert f"`{agent}` not found on PATH" in result.output[email protected]("agent", ["claude", "codex", "openclaw", "hermes", "pi"])[email protected]("agent", ["claude", "codex", "openclaw", "hermes", "pi", "dsh"])def test_no_launch_skips_agent_resolution(agent, monkeypatch):monkeypatch.setattr(start,@@ -3347,7 +3402,7 @@ def test_connect_load_knobs_reach_server_even_when_id_loaded(fake_studio):@pytest.mark.parametrize(- "command_name", ["claude", "codex", "openclaw", "opencode", "hermes", "pi"]+ "command_name", ["claude", "codex", "openclaw", "opencode", "hermes", "pi", "dsh"])def test_start_agents_expose_gpu_memory_mode_option(command_name):import inspect@@ -5380,6 +5435,175 @@ def test_connect_pi_no_launch_windows_relocates_userprofile(fake_studio, tmp_patassert f'$env:USERPROFILE = "{home}"' in result.output+# ── DeepSeek Harness (OpenAI /v1, key via env, ~/.dsh relocated) ─────+++def dsh_settings(tmp_path):+ return tmp_path / "settings.yaml"+++def test_write_dsh_config_fresh(dsh_settings):+ yaml = pytest.importorskip("yaml")+ start.write_dsh_config(BASE, MODEL, dsh_settings)+ config = yaml.safe_load(dsh_settings.read_text())+ provider = config["llm-pi-ai"]["providers"]["unsloth"]+ assert provider["api"] == "openai-completions"+ assert provider["baseURL"] == f"{BASE}/v1"+ assert provider["apiKeyEnv"] == "UNSLOTH_API_KEY"+ assert "sk-unsloth" not in dsh_settings.read_text()+ assert provider["compat"] == {"supportsDeveloperRole": False, "maxTokensField": "max_tokens"}+ assert provider["models"] == [+ {"id": MODEL["id"], "contextWindow": MODEL["context_length"], "maxTokens": 8192}+ ]+ assert config["agent-default-model"] == {"provider": "unsloth", "model": MODEL["id"]}+++def test_write_dsh_config_without_window_omits_limits(dsh_settings):+ yaml = pytest.importorskip("yaml")+ start.write_dsh_config(BASE, {"id": "unsloth/unknown-window"}, dsh_settings)+ config = yaml.safe_load(dsh_settings.read_text())+ assert config["llm-pi-ai"]["providers"]["unsloth"]["models"] == [+ {"id": "unsloth/unknown-window"}+ ]+++def test_write_dsh_config_preserves_and_idempotent(dsh_settings):+ yaml = pytest.importorskip("yaml")+ dsh_settings.write_text(+ yaml.safe_dump(+ {+ "ui-onboarding": {"welcomeNoticeVersion": "2026-08-13.1"},+ "llm-pi-ai": {"providers": {"anthropic": {"apiKeyEnv": "ANTHROPIC_API_KEY"}}},+ }+ )+ )+ start.write_dsh_config(BASE, MODEL, dsh_settings)+ config = yaml.safe_load(dsh_settings.read_text())+ assert config["ui-onboarding"] == {"welcomeNoticeVersion": "2026-08-13.1"}+ assert config["llm-pi-ai"]["providers"]["anthropic"] == {"apiKeyEnv": "ANTHROPIC_API_KEY"}+ assert config["llm-pi-ai"]["providers"]["unsloth"]["baseURL"] == f"{BASE}/v1"+ before = dsh_settings.read_text()+ start.write_dsh_config(BASE, MODEL, dsh_settings)+ assert dsh_settings.read_text() == before+++def test_write_dsh_config_preserves_non_mapping_file(dsh_settings, capsys):+ pytest.importorskip("yaml")+ original = "- just\n- a\n- list\n" # valid YAML, but not a mapping+ dsh_settings.write_text(original)+ start.write_dsh_config(BASE, MODEL, dsh_settings)+ assert dsh_settings.read_text() == original # user-managed file left untouched+ assert "couldn't parse" in capsys.readouterr().err+++ ("args", "expected"),+ [+ ([], ["dsh", "web"]),+ (["--no-open"], ["dsh", "web", "--no-open"]),+ (["--port", "3099"], ["dsh", "web", "--port", "3099"]),+ (["--profile", "headless", "fix the bug"], ["dsh", "--profile", "headless", "fix the bug"]),+ (["--profile=headless", "fix"], ["dsh", "--profile=headless", "fix"]),+ (+ ["plugin", "--profile", "web", "add", "x"],+ ["dsh", "plugin", "--profile", "web", "add", "x"],+ ),+ (["web", "--no-open"], ["dsh", "web", "--no-open"]),+ ],+)+def test_dsh_command_selects_web_only_for_app_arguments(args, expected):+ assert start._dsh_command(args) == expected+++def test_connect_dsh_no_launch(fake_studio, tmp_path):+ yaml = pytest.importorskip("yaml")+ result = CliRunner().invoke(start.start_app, ["dsh", "--no-launch"])+ assert result.exit_code == 0, result.output+ _assert_env_set(result.output, "UNSLOTH_API_KEY", "sk-unsloth-feedfacefeedface")+ home = tmp_path / "agents" / "dsh"+ _assert_env_set(result.output, "DSH_HOME", str(home))+ _assert_env_set(result.output, "DSH_TELEMETRY_DISABLED", "1")+ assert _launch_command(result.output) == ["dsh", "web"]+ config = yaml.safe_load((home / "settings.yaml").read_text())+ assert config["agent-default-model"] == {"provider": "unsloth", "model": MODEL["id"]}+ assert config["llm-pi-ai"]["providers"]["unsloth"]["baseURL"] == f"{BASE}/v1"+++def test_dsh_yolo_sets_permission_mode(fake_studio):+ result = CliRunner().invoke(start.start_app, ["dsh", "--yolo", "--no-launch"])+ assert result.exit_code == 0, result.output+ _assert_env_set(result.output, "DSH_PERMISSION_MODE", "danger-full-access")+++def test_dsh_without_yolo_pins_the_safe_permission_mode(fake_studio):+ result = CliRunner().invoke(start.start_app, ["dsh", "--no-launch"])+ assert result.exit_code == 0, result.output+ _assert_env_set(result.output, "DSH_PERMISSION_MODE", "workspace-write")+++ ("argv", "expected"),+ [+ (["dsh"], "workspace-write"),+ (["dsh", "--yolo"], "danger-full-access"),+ ],+)+def test_dsh_permission_mode_overrides_an_inherited_bypass(+ argv, expected, fake_studio, monkeypatch+):+ # dsh reads DSH_PERMISSION_MODE with ??, so merely omitting it would let a+ # danger-full-access exported in the parent shell survive a run without --yolo.+ monkeypatch.setenv("DSH_PERMISSION_MODE", "danger-full-access")+ monkeypatch.setattr(start.shutil, "which", lambda _: "/usr/local/bin/dsh")+ monkeypatch.setattr(start, "is_deepseek_harness_executable", lambda _: True)+ captured = _capture_launch(monkeypatch, argv)+ assert captured["env"]["DSH_PERMISSION_MODE"] == expected+++def test_start_dsh_forwards_reasoning_effort(fake_studio, monkeypatch):+ # --reasoning-effort is a shared server option: it must reach ServerOptions rather+ # than pass through to `dsh web`, which does not accept it.+ monkeypatch.setenv("UNSLOTH_STUDIO_URL", "http://127.0.0.1:8888")+ monkeypatch.setattr(start, "find_studio_server", lambda: None)+ captured = {}+ fake = SimpleNamespace(pid = 1, poll = lambda: None)++ def fake_start(+ base,+ model,+ load,+ server_options = None,+ ):+ captured["server_options"] = server_options+ start._auto_served_server = fake+ return fake++ monkeypatch.setattr(start, "_start_studio_server", fake_start)+ monkeypatch.setattr(start, "_shutdown_server", lambda server: None)+ monkeypatch.setattr(start, "_managed_node_tools", lambda: None)+ monkeypatch.setattr(start.shutil, "which", lambda _: "/usr/local/bin/dsh")+ monkeypatch.setattr(start, "is_deepseek_harness_executable", lambda _: True)++ def run(+ command,+ env = None,+ **kwargs,+ ):+ captured["command"] = command+ return SimpleNamespace(returncode = 0)++ monkeypatch.setattr(start.subprocess, "run", run)++ result = CliRunner().invoke(+ start.start_app,+ ["dsh", "--model", "unsloth/gemma-4-E2B-it-GGUF", "--reasoning-effort", "high"],+ )+ assert result.exit_code == 0, result.output+ assert captured["server_options"].reasoning_effort == "high"+ assert "--reasoning-effort" not in captured["command"]++# ── WSLENV path translation + PowerShell quoting (helper units) ──@@ -6451,6 +6675,7 @@ _RESUME_ENV_VAR = {"openclaw": "OPENCLAW_STATE_DIR","hermes": "HERMES_HOME","pi": "HOME",+ "dsh": "DSH_HOME",}@@ -6476,6 +6701,8 @@ def _capture_launch(monkeypatch, argv):@pytest.mark.parametrize("agent", sorted(_RESUME_ENV_VAR))def test_resume_persists_agent_home_to_stable_dir(agent, fake_studio, tmp_path, monkeypatch):monkeypatch.setattr(start.shutil, "which", lambda _: f"/usr/local/bin/{agent}")+ if agent == "dsh":+ monkeypatch.setattr(start, "is_deepseek_harness_executable", lambda _: True)captured = _capture_launch(monkeypatch, [agent, "--persist"])stable = tmp_path / "agents" / agentassert captured["env"][_RESUME_ENV_VAR[agent]] == str(stable)@@ -6486,6 +6713,8 @@ def test_resume_persists_agent_home_to_stable_dir(agent, fake_studio, tmp_path,@pytest.mark.parametrize("agent", sorted(_RESUME_ENV_VAR))def test_default_launch_home_is_ephemeral(agent, fake_studio, tmp_path, monkeypatch):monkeypatch.setattr(start.shutil, "which", lambda _: f"/usr/local/bin/{agent}")+ if agent == "dsh":+ monkeypatch.setattr(start, "is_deepseek_harness_executable", lambda _: True)captured = _capture_launch(monkeypatch, [agent])home = captured["env"][_RESUME_ENV_VAR[agent]]parent = start._ephemeral_session_parent(agent)@@ -6547,8 +6776,10 @@ def test_default_launch_has_no_resume_token(fake_studio, monkeypatch):def test_resume_persist_only_agents_have_no_resume_token(fake_studio, monkeypatch):# Persistence alone must not select a session.- for agent in ("openclaw", "hermes"):+ for agent in ("openclaw", "hermes", "dsh"):monkeypatch.setattr(start.shutil, "which", lambda _, a = agent: f"/usr/local/bin/{a}")+ if agent == "dsh":+ monkeypatch.setattr(start, "is_deepseek_harness_executable", lambda _: True)captured = _capture_launch(monkeypatch, [agent, "--persist"])assert "resume" not in captured["command"]assert "--continue" not in captured["command"]