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
unsloth start opencode: size the output limit to the context and add --max-tokens (#12111)
Michael Han07f004d6b090
diff --git a/unsloth_cli/commands/start.py b/unsloth_cli/commands/start.pyindex 0e4764413a1..aadce25fe3a 100644--- a/unsloth_cli/commands/start.py+++ b/unsloth_cli/commands/start.py@@ -130,6 +130,9 @@ _PI_USER_VERBATIM_SETTINGS = ("npmCommand",)_PI_USER_RESOURCES_MANIFEST = ".unsloth-user-resources.json"# OpenCode selects a model by "<providerID>/<modelID>". Use a dedicated id to avoid colliding with a user's providers; provider filters are set in the launch-time overlay._OPENCODE_PROVIDER = "unsloth-studio"+# OpenCode sends min(limit.output, this) as max_tokens unless the env var below raises it.+_OPENCODE_OUTPUT_TOKEN_MAX = 32_000+_OPENCODE_OUTPUT_TOKEN_MAX_ENV = "OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX"_PROVIDER_HEADER = f"[model_providers.{_CODEX_PROFILE}]"_PASSTHROUGH = {"allow_extra_args": True, "ignore_unknown_options": True}@@ -322,6 +325,17 @@ _PRESENCE_PENALTY_OPTION = typer.Option(rich_help_panel = _PANEL_SAMPLING,help = "Pin the presence penalty. Default: unset (per-model recommendation).",)+_MAX_TOKENS_OPTION = typer.Option(+ None,+ "--max-tokens",+ min = 1,+ rich_help_panel = _PANEL_SAMPLING,+ help = (+ "Most tokens the agent may generate in one response. Default: a quarter of the "+ "context window, up to 32,000. Capped at half the window so the conversation "+ "keeps room."+ ),+)# Agent-session knobs._KEY_OPTION = typer.Option(@@ -4527,6 +4541,42 @@ def write_openclaw_config(typer.echo(f"Updated {path}")+def opencode_output_limit(window: int, max_tokens: Optional[int] = None) -> int:+ if max_tokens:+ return max(1, min(int(max_tokens), window // 2))+ return max(1, min(window // 4, _OPENCODE_OUTPUT_TOKEN_MAX))+++def opencode_compaction_reserved(window: int, output: int) -> int:+ return max(1, min(output, max(window // 10, 8192)))+++def _opencode_output_env(model: dict, max_tokens: Optional[int]) -> dict:+ """Lift OpenCode's output ceiling when --max-tokens exceeds it; re-emit an inherited one so a --no-launch recipe keeps it."""+ window = model.get("context_length") or model.get("max_context_length")+ if not max_tokens:+ return {}+ if not window:+ typer.echo(+ "Warning: Studio did not report the model's context length, so --max-tokens is ignored.",+ err = True,+ )+ return {}+ output = opencode_output_limit(int(window), max_tokens)+ if output < max_tokens:+ typer.echo(+ f"Warning: --max-tokens {max_tokens} leaves too little of the {int(window):,}-token "+ f"context for the conversation; using {output:,}.",+ err = True,+ )+ raw = os.environ.get(_OPENCODE_OUTPUT_TOKEN_MAX_ENV, "")+ inherited = int(raw) if raw.isdigit() and int(raw) > 0 else None+ ceiling = inherited or _OPENCODE_OUTPUT_TOKEN_MAX+ if output <= ceiling and inherited is None:+ return {}+ return {_OPENCODE_OUTPUT_TOKEN_MAX_ENV: str(max(output, ceiling))}++def write_opencode_config(base: str,key: str,@@ -4534,6 +4584,7 @@ def write_opencode_config(path: Path,yolo: bool = False,as_subagent: bool = False,+ max_tokens: Optional[int] = None,) -> dict:config = _read_json_object(path)if config is None:@@ -4548,10 +4599,13 @@ def write_opencode_config(# Keep the provider definition in this private session file. The launch path adjusts effective provider filters in the higher-priority inline overlay.model_entry = {"name": model["id"]}window = model.get("context_length") or model.get("max_context_length")+ reserved = Noneif window:window = int(window)- # A custom-provider model with no limit defaults to context 0, which silently disables OpenCode's auto-compaction; declare the real window and a sane output cap so it compacts instead of overflowing the server.- model_entry["limit"] = {"context": window, "output": min(window // 4, 8192)}+ output = opencode_output_limit(window, max_tokens)+ reserved = opencode_compaction_reserved(window, output)+ # Without a limit OpenCode assumes context 0 and never compacts. Without input it compacts at context - output and ignores compaction.reserved.+ model_entry["limit"] = {"context": window, "input": window, "output": output}_subdict(config, "provider")[_OPENCODE_PROVIDER] = {"npm": "@ai-sdk/openai-compatible","name": "Unsloth Studio",@@ -4564,8 +4618,15 @@ def write_opencode_config(for field in ("model", "small_model"):if str(config.get(field) or "").startswith(f"{_OPENCODE_PROVIDER}/"):config.pop(field, None)- managed_compaction = {"auto": True, "reserved": max(1, window // 10)} if window else None- if managed_compaction and config.get("compaction") == managed_compaction:+ # Drop a managed compaction block, current or legacy value.+ managed = {reserved, max(1, window // 10)} if window else set()+ compaction = config.get("compaction")+ if (+ isinstance(compaction, dict)+ and compaction.keys() == {"auto", "reserved"}+ and compaction["auto"] is True+ and compaction["reserved"] in managed+ ):config.pop("compaction", None)_subdict(config, "agent")[_SUBAGENT_NAME] = {"description": _SUBAGENT_DESCRIPTION,@@ -4581,10 +4642,10 @@ def write_opencode_config(if not agents:config.pop("agent", None)if window and not as_subagent:- # Compact with ~10% headroom (near 90% full). The fixed 20k-token default buffer over-compacts, or never settles, on a small local context.+ # The fixed 20k-token default buffer over-compacts, or never settles, on a small local context.compaction = _subdict(config, "compaction")compaction["auto"] = True- compaction["reserved"] = max(1, window // 10)+ compaction["reserved"] = reservedtools = ("edit", "bash", "webfetch", *(("task",) if as_subagent else ()))if yolo:# Fallback for commands without native --auto and for the append-safe bare --no-launch command, where the subcommand is not known yet. Rides inline (OPENCODE_CONFIG_CONTENT) so it wins over a project config. TUI and `run` launches use --auto and call here with yolo=False, letting OpenCode preserve explicit deny rules.@@ -5372,6 +5433,7 @@ def opencode(min_p: Optional[float] = _MIN_P_OPTION,repetition_penalty: Optional[float] = _REPETITION_PENALTY_OPTION,presence_penalty: Optional[float] = _PRESENCE_PENALTY_OPTION,+ max_tokens: Optional[int] = _MAX_TOKENS_OPTION,serve: bool = _SERVE_OPTION,yolo: bool = _YOLO_OPTION,persist: bool = _PERSIST_OPTION,@@ -5433,8 +5495,12 @@ def opencode(config_path,yolo = yolo and not native_auto,as_subagent = True,+ max_tokens = max_tokens,)- env = {"OPENCODE_CONFIG": str(config_path)}+ env = {+ "OPENCODE_CONFIG": str(config_path),+ **_opencode_output_env(subagent_model, max_tokens),+ }inline_config = _opencode_subagent_inline_config(config_path,session_permission,@@ -5495,6 +5561,7 @@ def opencode(entry,config_path,yolo = yolo and not native_auto,+ max_tokens = max_tokens,)# A project's own opencode.json outranks OPENCODE_CONFIG, so the session model pin would silently lose to a repo config; carry it in OPENCODE_CONFIG_CONTENT, which outranks project config, while the API key stays in the private file. Only the config fallback carries a permission: native --auto omits it (auto-approve asks, keep explicit denies) and a non-yolo session omits it too, honoring project rules. V1 filters are ordinary overlays, so scope that session to our provider; V2 turns filters into security policies where global/project rules intentionally win, so keep those policies intact and tell the user above that they must allow our provider. small_model is opencode's separate model for lightweight tasks; pin it to the session model too, or a user/project small_model on another (now filtered) provider would resolve a not-found error mid-session.inline_config: dict = {@@ -5509,6 +5576,7 @@ def opencode(env = {"OPENCODE_CONFIG": str(config_path),"OPENCODE_CONFIG_CONTENT": json.dumps(inline_config),+ **_opencode_output_env(entry, max_tokens),}_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 bb8d0dc10b0..6bf9d2e7eb5 100644--- a/unsloth_cli/tests/test_start.py+++ b/unsloth_cli/tests/test_start.py@@ -5127,7 +5127,10 @@ def test_write_opencode_config_fresh(tmp_path):assert provider["options"] == {"baseURL": f"{BASE}/v1", "apiKey": "sk-unsloth-abc"}# Context limit must be declared, or OpenCode treats it as 0 and disables compaction.assert provider["models"] == {- MODEL["id"]: {"name": MODEL["id"], "limit": {"context": 131072, "output": 8192}}+ MODEL["id"]: {+ "name": MODEL["id"],+ "limit": {"context": 131072, "input": 131072, "output": 32_000},+ }}assert config["model"] == f"{start._OPENCODE_PROVIDER}/{MODEL['id']}"# Provider filters belong to the launch-time inline overlay, not this config writer.@@ -5136,6 +5139,115 @@ def test_write_opencode_config_fresh(tmp_path):assert config["compaction"] == {"auto": True, "reserved": 131072 // 10}+ "window, max_tokens, expected",+ [+ (16_384, None, 4_096),+ (32_768, None, 8_192),+ # No longer pinned at 8,192 (#12009).+ (131_072, None, 32_000),+ (143_616, None, 32_000),+ (143_616, 65_536, 65_536),+ (143_616, 200_000, 71_808),+ (32_768, 4_000, 4_000),+ ],+)+def test_opencode_output_limit(window, max_tokens, expected):+ assert start.opencode_output_limit(window, max_tokens) == expected+++def test_opencode_max_tokens_sets_limit_and_raises_opencode_ceiling(fake_studio, tmp_path):+ result = CliRunner().invoke(+ start.start_app, ["opencode", "--no-launch", "--max-tokens", "65536"]+ )+ assert result.exit_code == 0, result.output+ config_path = tmp_path / "agents" / "opencode" / "opencode.json"+ config = json.loads(config_path.read_text())+ limit = config["provider"][start._OPENCODE_PROVIDER]["models"][MODEL["id"]]["limit"]+ assert limit == {"context": 131072, "input": 131072, "output": 65536}+ _assert_env_set(result.output, "OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX", "65536")+++def test_opencode_limit_input_keeps_compaction_off_the_output_limit(tmp_path):+ # Without input, OpenCode compacts at context - output and a 65,536 limit compacts at half full.+ path = tmp_path / "opencode.json"+ start.write_opencode_config(BASE, "sk-unsloth-abc", MODEL, path, max_tokens = 65536)+ config = json.loads(path.read_text())+ limit = config["provider"][start._OPENCODE_PROVIDER]["models"][MODEL["id"]]["limit"]+ assert limit["input"] == limit["context"] == 131072+ assert config["compaction"]["reserved"] == 131072 // 10+++ "window, expected_reserved, expected_compacts_at",+ [+ (16_384, 4_096, 12_288),+ (32_768, 8_192, 24_576),+ (131_072, 13_107, 117_965),+ (262_144, 26_214, 235_930),+ ],+)+def test_opencode_compaction_reserved(window, expected_reserved, expected_compacts_at):+ reserved = start.opencode_compaction_reserved(window, start.opencode_output_limit(window))+ assert reserved == expected_reserved+ assert window - reserved == expected_compacts_at+++def test_opencode_subagent_drops_the_compaction_a_normal_session_wrote(tmp_path):+ path = tmp_path / "opencode.json"+ small = {**MODEL, "context_length": 16_384}+ start.write_opencode_config(BASE, "sk-unsloth-abc", small, path)+ assert json.loads(path.read_text())["compaction"] == {"auto": True, "reserved": 4_096}+ start.write_opencode_config(BASE, "sk-unsloth-abc", small, path, as_subagent = True)+ assert "compaction" not in json.loads(path.read_text())+++def test_opencode_max_tokens_without_a_window_warns(capsys):+ assert start._opencode_output_env({"id": "m"}, 65536) == {}+ assert "--max-tokens is ignored" in capsys.readouterr().err+++def test_opencode_max_tokens_under_ceiling_leaves_opencode_env_alone(fake_studio, tmp_path):+ result = CliRunner().invoke(+ start.start_app, ["opencode", "--no-launch", "--max-tokens", "16000"]+ )+ assert result.exit_code == 0, result.output+ config = json.loads((tmp_path / "agents" / "opencode" / "opencode.json").read_text())+ limit = config["provider"][start._OPENCODE_PROVIDER]["models"][MODEL["id"]]["limit"]+ assert limit["output"] == 16000+ assert "OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX" not in result.output+++def test_opencode_max_tokens_raises_a_smaller_inherited_ceiling(fake_studio, monkeypatch):+ monkeypatch.setenv("OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX", "8000")+ result = CliRunner().invoke(+ start.start_app, ["opencode", "--no-launch", "--max-tokens", "16000"]+ )+ assert result.exit_code == 0, result.output+ _assert_env_set(result.output, "OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX", "16000")+++def test_opencode_max_tokens_recipe_keeps_a_larger_inherited_ceiling(fake_studio, monkeypatch):+ # The --no-launch recipe must carry the ceiling, or a shell without the export reverts to 32,000.+ monkeypatch.setenv("OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX", "100000")+ result = CliRunner().invoke(+ start.start_app, ["opencode", "--no-launch", "--max-tokens", "65536"]+ )+ assert result.exit_code == 0, result.output+ _assert_env_set(result.output, "OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX", "100000")+++def test_opencode_max_tokens_past_half_the_window_is_capped(fake_studio, tmp_path):+ result = CliRunner().invoke(+ start.start_app, ["opencode", "--no-launch", "--max-tokens", "120000"]+ )+ assert result.exit_code == 0, result.output+ assert "leaves too little" in result.output+ config = json.loads((tmp_path / "agents" / "opencode" / "opencode.json").read_text())+ limit = config["provider"][start._OPENCODE_PROVIDER]["models"][MODEL["id"]]["limit"]+ assert limit["output"] == 131072 // 2++def test_write_opencode_config_preserves_and_idempotent(tmp_path):path = tmp_path / "opencode.json"path.write_text(