Skip to content

Personal AI, On Personal Devices

Python

feat(cli): interactive TUI model picker and Ollama runtime panel (#384)

dozeyUDKd6f705870174
diff --git a/docs/user-guide/cli-interactive-picker.md b/docs/user-guide/cli-interactive-picker.md
new file mode 100644
index 00000000..d9f96971
--- /dev/null
+++ b/docs/user-guide/cli-interactive-picker.md
@@ -0,0 +1,72 @@
+# Interactive CLI model and runtime picker (TUI)
+
+Optional terminal UX for `jarvis chat` and bare `jarvis` on an interactive TTY.
+Upstream previously relied on `default_model` in config or `-m` / `--model` only.
+
+## Who may find this useful
+
+- Local Ollama users who switch models often and want a numbered list at session start.
+- People tuning context window or GPU layer offload per session without editing config.
+- Power users who keep presets in `[intelligence]` (`model_chat`, `model_long`, etc.) but
+ still want to override interactively sometimes.
+
+Non-interactive use (CI, pipes, scripts) is unchanged when stdin is not a TTY or when
+skip env vars are set.
+
+## Behavior
+
+### Model picker
+
+On a TTY (unless skipped):
+
+1. Lists models from the active engine (`engine.list_models()` — for Ollama, live `/api/tags`).
+2. User picks by index, exact id, or Enter to fall back to config.
+3. Resolution order after picker: `-m` / `--model` → `model_*` preset → `default_model` → first discovered model.
+4. `-m smart` uses the variant preset (e.g. `model_chat`) like a named default.
+
+Skip picker:
+
+- `JARVIS_SKIP_MODEL_PICK=1`
+- `jarvis chat` without bare `jarvis` (picker only auto-runs on bare `jarvis` unless `--pick-model`)
+- `jarvis chat --pick-model` forces the list
+
+### Runtime panel (Ollama-focused)
+
+After model selection, optional prompts:
+
+- **num_ctx** — context tokens (capped at 200,000)
+- **num_gpu** — GPU layers (-1 = all, 0 = CPU); only shown for engine `ollama`
+
+Skip panel:
+
+- `JARVIS_SKIP_RUNTIME_PANEL=1`
+- `--skip-runtime-panel`
+- `--num-ctx` / `--num-gpu` (values applied directly, no prompts)
+
+Session summary appears in the chat banner (`Runtime: ctx=…, gpu=…`). In-chat `/runtime` shows current values.
+
+### Config additions
+
+```toml
+[intelligence]
+default_model = "qwen3.5:4b"
+model_chat = ""
+model_short = ""
+model_long = ""
+model_code = ""
+```
+
+## Security notes
+
+- Model ids from TTY/CLI are sanitized (control characters stripped, max length 512).
+- Picker accepts only ids present in the engine list (no free-form path-like strings).
+- Runtime kwargs forwarded to the engine are limited to `num_ctx` and `num_gpu`.
+- Agent `engine_options` are filtered to the same allowlist before `engine.generate()`.
+
+## Related commands
+
+| Command | Role |
+|---------|------|
+| `jarvis model list` | Inspect models without starting chat |
+| `jarvis chat -m MODEL` | Skip picker, fixed model |
+| `jarvis chat --num-ctx N --num-gpu N` | Skip runtime panel |
diff --git a/src/openjarvis/agents/_stubs.py b/src/openjarvis/agents/_stubs.py
index c8354c69..b456fdf0 100644
--- a/src/openjarvis/agents/_stubs.py
+++ b/src/openjarvis/agents/_stubs.py
@@ -18,6 +18,8 @@ from openjarvis.core.events import EventBus, EventType
from openjarvis.core.types import Conversation, Message, Role, ToolResult
from openjarvis.engine._stubs import InferenceEngine
+_ALLOWED_ENGINE_OPTION_KEYS = frozenset({"num_ctx", "num_gpu"})
+
@dataclass(slots=True)
class AgentContext:
@@ -71,11 +73,13 @@ class BaseAgent(ABC):
temperature: Optional[float] = None,
max_tokens: Optional[int] = None,
prompt_builder: Optional[Any] = None,
+ engine_options: Optional[Dict[str, Any]] = None,
) -> None:
self._engine = engine
self._model = model
self._bus = bus
self._prompt_builder = prompt_builder
+ self._engine_options: Dict[str, Any] = dict(engine_options or {})
# Three-tier resolution: explicit arg > config > class default > hardcoded
if temperature is not None and max_tokens is not None:
@@ -223,12 +227,23 @@ class BaseAgent(ABC):
{"model": self._model, "engine": engine_id},
)
+ # Stored engine options originate in CLI/runtime configuration and are
+ # intentionally allowlisted. Per-call kwargs originate in the agent
+ # implementation itself (for example ``tools`` or ``response_format``)
+ # and must reach the engine adapter unchanged. Filtering the merged
+ # mapping silently stripped function-calling tools from every agent.
+ gen_kwargs = {
+ key: value
+ for key, value in self._engine_options.items()
+ if key in _ALLOWED_ENGINE_OPTION_KEYS
+ }
+ gen_kwargs.update(extra_kwargs)
result = self._engine.generate(
messages,
model=self._model,
temperature=self._temperature,
max_tokens=self._max_tokens,
- **extra_kwargs,
+ **gen_kwargs,
)
if self._bus and not getattr(self._engine, "_publishes_events", False):
diff --git a/src/openjarvis/cli/__init__.py b/src/openjarvis/cli/__init__.py
index e3d9a395..86420db8 100644
--- a/src/openjarvis/cli/__init__.py
+++ b/src/openjarvis/cli/__init__.py
@@ -41,14 +41,25 @@ def _should_skip_update_check(ctx: click.Context, argv: list[str]) -> bool:
@click.version_option(version=openjarvis.__version__, prog_name="jarvis")
@click.option("--verbose", is_flag=True, default=False, help="Enable debug logging")
@click.option("--quiet", is_flag=True, default=False, help="Suppress non-error output")
+ "--pick-model",
+ "pick_model_bare",
+ is_flag=True,
+ default=False,
+ help=(
+ "Bare ``jarvis``: force interactive model list "
+ "(overrides JARVIS_SKIP_MODEL_PICK)."
+ ),
+)
@click.pass_context
-def cli(ctx: click.Context, verbose: bool, quiet: bool) -> None:
+def cli(ctx: click.Context, verbose: bool, quiet: bool, pick_model_bare: bool) -> None:
"""Top-level CLI group."""
from openjarvis.cli.log_config import setup_logging
ctx.ensure_object(dict)
ctx.obj["verbose"] = verbose
ctx.obj["quiet"] = quiet
+ ctx.obj["pick_model_bare"] = pick_model_bare
setup_logging(verbose=verbose, quiet=quiet)
# Check for updates on interactive commands. The banner is noise in
diff --git a/src/openjarvis/cli/_first_run.py b/src/openjarvis/cli/_first_run.py
index e15f634a..00882c0e 100644
--- a/src/openjarvis/cli/_first_run.py
+++ b/src/openjarvis/cli/_first_run.py
@@ -4,10 +4,16 @@ When the user types ``jarvis`` with no subcommand, route them to the
chat command if a config exists, otherwise into the init wizard with
the ``--from-bare-jarvis`` flag (which lets init suppress the
launch-chat prompt and auto-confirm downstream questions).
+
+On an interactive terminal, bare ``jarvis`` opens the model picker first
+(unless ``JARVIS_SKIP_MODEL_PICK=1``). Use ``jarvis --pick-model`` to
+force the picker even when that env is set.
"""
from __future__ import annotations
+import os
+import sys
from typing import TYPE_CHECKING
from openjarvis.core import config as _cfg
@@ -30,6 +36,13 @@ def check_and_route(ctx: click.Context) -> None:
from openjarvis.cli.init_cmd import init as init_cmd
if _cfg.DEFAULT_CONFIG_PATH.exists():
- ctx.invoke(chat_cmd)
+ pick_bare = bool(getattr(ctx, "obj", None) and ctx.obj.get("pick_model_bare"))
+ skip = (os.environ.get("JARVIS_SKIP_MODEL_PICK", "") or "").strip().lower() in (
+ "1",
+ "true",
+ "yes",
+ )
+ use_pick = pick_bare or (sys.stdin.isatty() and not skip)
+ ctx.invoke(chat_cmd, pick_model=use_pick)
else:
ctx.invoke(init_cmd, from_bare_jarvis=True)
diff --git a/src/openjarvis/cli/_model_switch.py b/src/openjarvis/cli/_model_switch.py
new file mode 100644
index 00000000..4fb64db7
--- /dev/null
+++ b/src/openjarvis/cli/_model_switch.py
@@ -0,0 +1,138 @@
+"""Resolve chat CLI model: per-command presets, ``-m smart``, ``default_model``."""
+
+from __future__ import annotations
+
+import re
+from typing import Any, Optional
+
+from rich.markup import escape
+
+SMART_MODEL_TOKEN = "smart"
+MAX_MODEL_ID_LEN = 512
+_CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f]")
+
+
+def sanitize_model_id(raw: str) -> str:
+ """Normalize a model id from CLI or TTY input (length + control chars)."""
+ text = _CONTROL_CHARS.sub("", (raw or "").strip())
+ if len(text) > MAX_MODEL_ID_LEN:
+ text = text[:MAX_MODEL_ID_LEN]
+ return text
+
+
+_VARIANT_ATTR: dict[str, str] = {
+ "chat": "model_chat",
+ "short": "model_short",
+ "long": "model_long",
+ "code": "model_code",
+}
+
+
+def tty_wants_model_picker(cli_flag: bool) -> bool:
+ """Return whether this explicit ``chat`` invocation requested a picker.
+
+ Bare ``jarvis`` owns the TTY auto-prompt policy in ``_first_run`` and
+ passes ``pick_model=True`` when appropriate. Keeping the subcommand gate
+ flag-only prevents ``jarvis chat`` from unexpectedly reading stdin before
+ the chat loop.
+ """
+ return bool(cli_flag)
+
+
+def variant_preset_model(config: Any, chat_variant: str) -> str:
+ """Return ``[intelligence] model_<variant>`` if set, else ``\"\"``."""
+ intel = getattr(config, "intelligence", None)
+ if intel is None:
+ return ""
+ attr = _VARIANT_ATTR.get(chat_variant, "model_chat")
+ raw = (getattr(intel, attr, None) or "").strip()
+ return raw
+
+
+def interactive_pick_model(console: Any, engine: Any) -> Optional[str]:
+ """List engine models and read user choice. Returns ``None`` if cancelled."""
+ models: list[str] = []
+ try:
+ models = [
+ model
+ for raw_model in engine.list_models()
+ if (model := sanitize_model_id(str(raw_model)))
+ ]
+ except Exception:
+ models = []
+ if not models:
+ console.print(
+ "[yellow]Engine did not return any models — cannot pick "
+ "interactively.[/yellow]",
+ )
+ return None
+ console.print("[bold]Available models[/bold] (number or exact id):")
+ for i, mid in enumerate(models, 1):
+ console.print(f" {i:2}) [cyan]{escape(mid)}[/cyan]")
+ try:
+ raw = input(
+ "Choose model [1–%d], id, or Enter for config default: " % len(models)
+ )
+ except (EOFError, KeyboardInterrupt):
+ return None
+ choice = (raw or "").strip()
+ if not choice:
+ return None
+ choice = sanitize_model_id(choice)
+ if not choice:
+ return None
+ if choice.isdigit():
+ idx = int(choice)
+ if 1 <= idx <= len(models):
+ return models[idx - 1]
+ return None
+ if choice in models:
+ return choice
+ return None
+
+
+def resolve_chat_cli_model(
+ *,
+ console: Any,
+ config: Any,
+ engine: Any,
+ engine_name: str,
+ cli_model: Optional[str],
+ chat_variant: str,
+) -> str:
+ """Resolve model from ``-m``, ``smart`` / presets, or ``default_model``.
+
+ Interactive picking is handled in ``chat`` before this runs.
+ """
+ explicit = sanitize_model_id(cli_model or "")
+ if explicit and explicit.lower() != SMART_MODEL_TOKEN:
+ return explicit
+
+ preset = variant_preset_model(config, chat_variant)
+ if preset:
+ return sanitize_model_id(preset)
+
+ dm = (getattr(config.intelligence, "default_model", None) or "").strip()
+ if dm:
+ return sanitize_model_id(dm)
+
+ from openjarvis.engine import discover_engines, discover_models
+
+ all_engines = discover_engines(config)
+ all_models = discover_models(all_engines)
+ engine_models = all_models.get(engine_name, [])
+ if engine_models:
+ return sanitize_model_id(str(engine_models[0]))
+
+ return ""
+
+
+__all__ = [
+ "MAX_MODEL_ID_LEN",
+ "SMART_MODEL_TOKEN",
+ "interactive_pick_model",
+ "resolve_chat_cli_model",
+ "sanitize_model_id",
+ "tty_wants_model_picker",
+ "variant_preset_model",
+]
diff --git a/src/openjarvis/cli/_runtime_panel.py b/src/openjarvis/cli/_runtime_panel.py
new file mode 100644
index 00000000..62f72794
--- /dev/null
+++ b/src/openjarvis/cli/_runtime_panel.py
@@ -0,0 +1,167 @@
+"""Interactive runtime panel: GPU offload and context window (Ollama)."""
+
+from __future__ import annotations
+
+import os
+from dataclasses import dataclass
+from typing import Any, Optional
+
+MAX_NUM_CTX = 200_000
+MAX_NUM_GPU_LAYERS = 999
+
+
+@dataclass(frozen=True, slots=True)
+class ChatRuntimeOptions:
+ """Per-session inference options chosen after model pick."""
+
+ num_ctx: Optional[int] = None
+ num_gpu: Optional[int] = None
+
+ def to_engine_kwargs(self, *, engine_name: str) -> dict[str, Any]:
+ """Return only options implemented by the selected engine."""
+ if engine_name != "ollama":
+ return {}
+ out: dict[str, Any] = {}
+ if self.num_ctx is not None and self.num_ctx > 0:
+ out["num_ctx"] = min(int(self.num_ctx), MAX_NUM_CTX)
+ if self.num_gpu is not None:
+ # Ollama: large num_gpu = offload all layers; -1 means "all".
+ if self.num_gpu < 0:
+ out["num_gpu"] = MAX_NUM_GPU_LAYERS
+ else:
+ out["num_gpu"] = min(int(self.num_gpu), MAX_NUM_GPU_LAYERS)
+ return out
+
+ def summary(self, *, engine_name: str) -> str:
+ if engine_name != "ollama":
+ return "engine defaults (runtime controls require Ollama)"
+ parts: list[str] = []
+ if self.num_ctx is not None and self.num_ctx > 0:
+ parts.append(f"ctx={self.num_ctx:,}")
+ else:
+ parts.append("ctx=default")
+ if engine_name == "ollama":
+ if self.num_gpu is None:
+ parts.append("gpu=default")
+ elif self.num_gpu < 0:
+ parts.append("gpu=all layers")
+ elif self.num_gpu == 0:
+ parts.append("gpu=0 (CPU)")
+ else:
+ parts.append(f"gpu={self.num_gpu} layers")
+ return ", ".join(parts)
+
+
+def tty_wants_runtime_panel(cli_skip: bool = False) -> bool:
+ """Show runtime panel on TTY unless skipped."""
+ import sys
+
+ if cli_skip:
+ return False
+ skip = (os.environ.get("JARVIS_SKIP_RUNTIME_PANEL", "") or "").strip().lower() in (
+ "1",
+ "true",
+ "yes",
+ )
+ return sys.stdin.isatty() and not skip
+
+
+def _parse_int(raw: str, *, default: Optional[int]) -> Optional[int]:
+ text = (raw or "").strip()
+ if not text:
+ return default
+ try:
+ return int(text.replace("_", "").replace(",", ""))
+ except ValueError:
+ return default
+
+
+def interactive_pick_runtime_options(
+ console: Any,
+ *,
+ engine_name: str,
+ cli_num_ctx: Optional[int] = None,
+ cli_num_gpu: Optional[int] = None,
+) -> ChatRuntimeOptions:
+ """Prompt for context size and GPU offload after model selection."""
+ # These option names and semantics are Ollama-specific. In particular,
+ # forwarding them to OpenAI-compatible engines becomes an invalid API
+ # request rather than a harmless no-op.
+ if engine_name != "ollama":
+ return ChatRuntimeOptions()
+ if cli_num_ctx is not None or cli_num_gpu is not None:
+ return ChatRuntimeOptions(num_ctx=cli_num_ctx, num_gpu=cli_num_gpu)
+
+ console.print(
+ "\n[bold]Runtime[/bold] "
+ "[dim](Enter = engine default; applies this session)[/dim]",
+ )
+ console.print(
+ " [dim]num_ctx[/dim] — context window (tokens, max "
+ f"{MAX_NUM_CTX:,}). [dim]num_gpu[/dim] — layers on GPU "
+ "(-1 = all, 0 = CPU only).",
+ )
+
+ try:
+ raw_ctx = input(
+ f"Max context tokens [0–{MAX_NUM_CTX}, 0=default]: ",
+ )
+ except (EOFError, KeyboardInterrupt):
+ return ChatRuntimeOptions()
+
+ num_ctx = _parse_int(raw_ctx, default=None)
+ if num_ctx is not None:
+ if num_ctx <= 0:
+ num_ctx = None
+ else:
+ num_ctx = min(num_ctx, MAX_NUM_CTX)
+
+ num_gpu: Optional[int] = None
+ try:
+ raw_gpu = input(
+ "GPU layer offload [-1=all, 0=CPU, N=layers, Enter=default]: ",
+ )
+ except (EOFError, KeyboardInterrupt):
+ return ChatRuntimeOptions(num_ctx=num_ctx)
+ parsed = _parse_int(raw_gpu, default=None)
+ if parsed is not None:
+ num_gpu = parsed
+
+ opts = ChatRuntimeOptions(num_ctx=num_ctx, num_gpu=num_gpu)
+ console.print(f"[dim]Runtime: {opts.summary(engine_name=engine_name)}[/dim]\n")
+ return opts
+
+
+def runtime_cli_options(command: Any) -> Any:
+ """Click decorator: ``--num-ctx``, ``--num-gpu``, ``--skip-runtime-panel``."""
+ import click
+
+ command = click.option(
+ "--num-ctx",
+ type=int,
+ default=None,
+ help="Context window (tokens, max 200k). Skips runtime panel when set.",
+ )(command)
+ command = click.option(
+ "--num-gpu",
+ type=int,
+ default=None,
+ help="Ollama GPU layers (-1=all, 0=CPU). Skips runtime panel when set.",
+ )(command)
+ command = click.option(
+ "--skip-runtime-panel",
+ is_flag=True,
+ default=False,
+ help="Do not prompt for context/GPU after model pick.",
+ )(command)
+ return command
+
+
+__all__ = [
+ "MAX_NUM_CTX",
+ "MAX_NUM_GPU_LAYERS",
+ "ChatRuntimeOptions",
+ "interactive_pick_runtime_options",
+ "runtime_cli_options",
+ "tty_wants_runtime_panel",
+]
diff --git a/src/openjarvis/cli/chat_cmd.py b/src/openjarvis/cli/chat_cmd.py
index 62833dec..c78f2fb7 100644
--- a/src/openjarvis/cli/chat_cmd.py
+++ b/src/openjarvis/cli/chat_cmd.py
@@ -9,7 +9,9 @@ from typing import List, Optional
import click
from rich.console import Console
from rich.markdown import Markdown
+from rich.markup import escape
+from openjarvis.cli._runtime_panel import runtime_cli_options
from openjarvis.cli._tool_names import resolve_tool_names
from openjarvis.core.config import load_config
from openjarvis.core.events import EventBus
@@ -19,6 +21,13 @@ from openjarvis.memory import publish_completed_exchange
logger = logging.getLogger(__name__)
+def _safe_rich_label(value: object) -> str:
+ """Strip terminal controls and escape Rich markup in dynamic labels."""
+ from openjarvis.cli._model_switch import sanitize_model_id
+
+ return escape(sanitize_model_id(str(value)))
+
+
def _read_input(prompt: str = "You> ") -> Optional[str]:
"""Read user input with graceful EOF handling."""
try:
@@ -29,7 +38,26 @@ def _read_input(prompt: str = "You> ") -> Optional[str]:
@click.command()
@click.option("-e", "--engine", "engine_key", default=None, help="Engine backend.")
[email protected]("-m", "--model", "model_name", default=None, help="Model to use.")
+ "-m",
+ "--model",
+ "model_name",
+ default=None,
+ help=(
+ "Model id. Omit or use ``smart`` for preset: [intelligence] model_chat / "
+ "model_short / model_long / model_code, then default_model."
+ ),
+)
+ "--pick-model",
+ "pick_model",
+ is_flag=True,
+ default=False,
+ help=(
+ "Show the model list before chat. Bare ``jarvis`` already does this on a TTY "
+ "unless JARVIS_SKIP_MODEL_PICK=1."
+ ),
+)
@click.option("-a", "--agent", "agent_name", default=None, help="Agent type.")
@click.option("--tools", default=None, help="Comma-separated tool names.")
@click.option("--system", "system_prompt", default=None, help="Custom system prompt.")
@@ -42,20 +70,31 @@ def _read_input(prompt: str = "You> ") -> Optional[str]:
"(overrides config). Pass 'none' to disable all persona files."
),
)
+@runtime_cli_options
def chat(
engine_key: str | None,
model_name: str | None,
+ pick_model: bool,
agent_name: str | None,
tools: str | None,
system_prompt: str | None,
persona_name: str | None,
+ num_ctx: int | None,
+ num_gpu: int | None,
+ skip_runtime_panel: bool,
) -> None:
"""Start an interactive multi-turn chat session.
+ Model: omit ``-m`` to use ``[intelligence] model_chat`` if set, else
+ ``default_model``; ``-m smart`` is the same. Use ``--pick-model`` to open the
+ engine list first (bare ``jarvis`` does this on a TTY unless
+ ``JARVIS_SKIP_MODEL_PICK=1``).
+
Commands during chat:
/quit, /exit — end session
/clear — clear conversation history
/model — show current model
+ /runtime — Ollama context + GPU offload for this session
/help — show available commands
/history — show conversation history
"""
@@ -84,18 +123,56 @@ def chat(
sys.exit(1)
engine_name, engine = resolved
- model = model_name or config.intelligence.default_model
+ from openjarvis.cli._model_switch import (
+ interactive_pick_model,
+ resolve_chat_cli_model,
+ tty_wants_model_picker,
+ )
+
+ model = ""
+ if tty_wants_model_picker(pick_model):
+ console.print(
+ "[dim]Pick a model below, or press Enter for config default "
+ "(intelligence presets / default_model).[/dim]\n",
+ )
+ picked = interactive_pick_model(console, engine)
+ if picked:
+ model = picked
+ if not model:
+ model = resolve_chat_cli_model(
+ console=console,
+ config=config,
+ engine=engine,
+ engine_name=engine_name,
+ cli_model=model_name,
+ chat_variant="chat",
+ )
if not model:
- from openjarvis.engine import discover_engines, discover_models
+ console.print("[red]No model available.[/red]")
+ sys.exit(1)
- all_engines = discover_engines(config)
- all_models = discover_models(all_engines)
- engine_models = all_models.get(engine_name, [])
- if engine_models:
- model = engine_models[0]
- else:
- console.print("[red]No model available.[/red]")
- sys.exit(1)
+ from openjarvis.cli._runtime_panel import (
+ ChatRuntimeOptions,
+ interactive_pick_runtime_options,
+ tty_wants_runtime_panel,
+ )
+
+ if engine_name != "ollama" and (num_ctx is not None or num_gpu is not None):
+ raise click.UsageError(
+ "--num-ctx and --num-gpu are supported only with --engine ollama"
+ )
+ if engine_name == "ollama" and tty_wants_runtime_panel(skip_runtime_panel):
+ runtime_opts = interactive_pick_runtime_options(
+ console,
+ engine_name=engine_name,
+ cli_num_ctx=num_ctx,
+ cli_num_gpu=num_gpu,
+ )
+ elif engine_name == "ollama" and (num_ctx is not None or num_gpu is not None):
+ runtime_opts = ChatRuntimeOptions(num_ctx=num_ctx, num_gpu=num_gpu)
+ else:
+ runtime_opts = ChatRuntimeOptions()
+ engine_kwargs = runtime_opts.to_engine_kwargs(engine_name=engine_name)
# Resolve agent (optional)
agent = None
@@ -160,15 +237,24 @@ def chat(
)
agent = agent_cls(engine, model, **kwargs)
+ if agent is not None and engine_kwargs:
+ # Agents like NativeReActAgent do not accept engine_options
+ # in __init__; session opts live on BaseAgent._engine_options.
+ setattr(agent, "_engine_options", dict(engine_kwargs))
except Exception as exc:
- console.print(f"[yellow]Agent '{agent_key}' failed: {exc}[/yellow]")
+ console.print(
+ f"[yellow]Agent '{_safe_rich_label(agent_key)}' failed: "
+ f"{escape(str(exc))}[/yellow]"
+ )
# Print banner
console.print(
f"[green bold]OpenJarvis Chat[/green bold]\n"
- f" Engine: [cyan]{engine_name}[/cyan] Model: [cyan]{model}[/cyan]"
- f" Agent: [cyan]{agent_key or 'direct'}[/cyan]\n"
- f" Type /help for commands, /quit to exit.\n"
+ f" Engine: [cyan]{_safe_rich_label(engine_name)}[/cyan] "
+ f"Model: [cyan]{_safe_rich_label(model)}[/cyan]"
+ f" Agent: [cyan]{_safe_rich_label(agent_key or 'direct')}[/cyan]\n"
+ f" Runtime: [cyan]{runtime_opts.summary(engine_name=engine_name)}[/cyan]\n"
+ f" Type /help for commands, /quit to exit.\n",
)
# Background-work status banner (disappears after first user message)
@@ -248,15 +334,24 @@ def chat(
continue
elif cmd == "/model":
console.print(
- f"Model: [cyan]{model}[/cyan] Engine: [cyan]{engine_name}[/cyan]"
+ f"Model: [cyan]{_safe_rich_label(model)}[/cyan] "
+ f"Engine: [cyan]{_safe_rich_label(engine_name)}[/cyan]"
)
continue
+ elif cmd == "/runtime":
+ console.print(
+ f"Runtime: [cyan]{runtime_opts.summary(engine_name=engine_name)}[/cyan]"
+ )
+ if engine_kwargs:
+ console.print(f" engine kwargs: {engine_kwargs}")
+ continue
elif cmd == "/help":
console.print(
"[bold]Commands:[/bold]\n"
" /quit, /exit — end session\n"
" /clear — clear conversation\n"
" /model — show model info\n"
+ " /runtime — Ollama context + GPU offload for this session\n"
" /history — show conversation\n"
" /help — this message"
)
@@ -324,7 +419,11 @@ def chat(
response.content if hasattr(response, "content") else str(response)
)
else:
- result = engine.generate(generation_history, model=model)
+ result = engine.generate(
+ generation_history,
+ model=model,
+ **engine_kwargs,
+ )
content = (
result.get("content", "")
if isinstance(result, dict)
diff --git a/src/openjarvis/core/config.py b/src/openjarvis/core/config.py
index b3ed8999..701c0e0f 100644
--- a/src/openjarvis/core/config.py
+++ b/src/openjarvis/core/config.py
@@ -587,6 +587,11 @@ class IntelligenceConfig:
"""The model — identity, paths, quantization, and generation defaults."""
default_model: str = ""
+ # Optional per-CLI preset (used when ``-m`` omitted or ``-m smart``).
+ model_chat: str = ""
+ model_short: str = ""
+ model_long: str = ""
+ model_code: str = ""
fallback_model: str = ""
model_path: str = "" # Local weights (HF repo, GGUF file, etc.)
checkpoint_path: str = "" # Checkpoint/adapter path
diff --git a/src/openjarvis/engine/ollama.py b/src/openjarvis/engine/ollama.py
index ae07e3cc..ba419666 100644
--- a/src/openjarvis/engine/ollama.py
+++ b/src/openjarvis/engine/ollama.py
@@ -83,6 +83,26 @@ def _default_num_ctx() -> int:
return 16384
+def _ollama_request_options(
+ *,
+ temperature: float,
+ max_tokens: int,
+ kwargs: Dict[str, Any],
+) -> Dict[str, Any]:
+ """Build Ollama ``options`` dict from generate/stream kwargs."""
+ options: Dict[str, Any] = {
+ "temperature": temperature,
+ "num_predict": max_tokens,
+ }
+ if kwargs.get("num_ctx") is not None:
+ options["num_ctx"] = int(kwargs["num_ctx"])
+ else:
+ options["num_ctx"] = _default_num_ctx()
+ if kwargs.get("num_gpu") is not None:
+ options["num_gpu"] = int(kwargs["num_gpu"])
+ return options
+
+
@EngineRegistry.register("ollama")
class OllamaEngine(AsyncHTTPEngineMixin, InferenceEngine):
"""Ollama backend via its native HTTP API."""
@@ -142,11 +162,11 @@ class OllamaEngine(AsyncHTTPEngineMixin, InferenceEngine):
"model": model,
"messages": msg_dicts,
"stream": False,
- "options": {
- "temperature": temperature,
- "num_predict": max_tokens,
- "num_ctx": kwargs.get("num_ctx", _default_num_ctx()),
- },
+ "options": _ollama_request_options(
+ temperature=temperature,
+ max_tokens=max_tokens,
+ kwargs=kwargs,
+ ),
}
# Disable extended thinking by default (Qwen3.5 etc.).
# When enabled, thinking tokens consume the entire budget and
@@ -264,11 +284,11 @@ class OllamaEngine(AsyncHTTPEngineMixin, InferenceEngine):
"model": model,
"messages": messages_to_dicts(messages),
"stream": True,
- "options": {
- "temperature": temperature,
- "num_predict": max_tokens,
- "num_ctx": kwargs.get("num_ctx", _default_num_ctx()),
- },
+ "options": _ollama_request_options(
+ temperature=temperature,
+ max_tokens=max_tokens,
+ kwargs=kwargs,
+ ),
}
# Mirror generate()'s default: disable extended thinking unless the
# caller opted in. Qwen3/etc. with thinking on can stall the visible
@@ -363,11 +383,11 @@ class OllamaEngine(AsyncHTTPEngineMixin, InferenceEngine):
"model": model,
"messages": msg_dicts,
"stream": True,
- "options": {
- "temperature": temperature,
- "num_predict": max_tokens,
- "num_ctx": kwargs.get("num_ctx", _default_num_ctx()),
- },
+ "options": _ollama_request_options(
+ temperature=temperature,
+ max_tokens=max_tokens,
+ kwargs=kwargs,
+ ),
}
if "think" not in kwargs:
payload["think"] = False
diff --git a/tests/agents/test_base_agent.py b/tests/agents/test_base_agent.py
index 94f1c4cf..a378c356 100644
--- a/tests/agents/test_base_agent.py
+++ b/tests/agents/test_base_agent.py
@@ -339,13 +339,22 @@ class TestGenerate:
assert call_kwargs["temperature"] == 0.5
assert call_kwargs["max_tokens"] == 100
- def test_extra_kwargs(self):
+ def test_extra_kwargs_are_forwarded_without_filtering(self):
engine = MagicMock()
engine.generate.return_value = {"content": "hi"}
agent = _ConcreteAgent(engine, "m")
- agent._generate([Message(role=Role.USER, content="hi")], tools=["t"])
+ tools = [{"type": "function", "function": {"name": "search"}}]
+ response_format = {"type": "json_object"}
+ agent._generate(
+ [Message(role=Role.USER, content="hi")],
+ tools=tools,
+ response_format=response_format,
+ stop=["DONE"],
+ )
call_kwargs = engine.generate.call_args[1]
- assert call_kwargs["tools"] == ["t"]
+ assert call_kwargs["tools"] is tools
+ assert call_kwargs["response_format"] is response_format
+ assert call_kwargs["stop"] == ["DONE"]
class TestMaxTurnsResult:
diff --git a/tests/cli/test_chat_cmd.py b/tests/cli/test_chat_cmd.py
index 48080306..7509f73b 100644
--- a/tests/cli/test_chat_cmd.py
+++ b/tests/cli/test_chat_cmd.py
@@ -71,6 +71,9 @@ class TestChatCommand:
assert result.exit_code == 0
assert "--engine" in result.output
assert "--model" in result.output
+ assert "--pick-model" in result.output
+ assert "--num-ctx" in result.output
+ assert "--num-gpu" in result.output
assert "--agent" in result.output
assert "--tools" in result.output
assert "--system" in result.output
@@ -221,6 +224,14 @@ class TestChatAgents:
patch("openjarvis.cli.chat_cmd.load_config", return_value=config),
patch("openjarvis.engine.get_engine", return_value=("mock", engine)),
patch("openjarvis.intelligence.register_builtin_models"),
+ patch(
+ "openjarvis.cli._model_switch.tty_wants_model_picker",
+ return_value=False,
+ ),
+ patch(
+ "openjarvis.cli._runtime_panel.tty_wants_runtime_panel",
+ return_value=False,
+ ),
):
result = CliRunner().invoke(
chat,
@@ -418,6 +429,14 @@ class TestChatAgents:
patch("openjarvis.cli.chat_cmd.load_config", return_value=config),
patch("openjarvis.engine.get_engine", return_value=("mock", engine)),
patch("openjarvis.intelligence.register_builtin_models"),
+ patch(
+ "openjarvis.cli._model_switch.tty_wants_model_picker",
+ return_value=False,
+ ),
+ patch(
+ "openjarvis.cli._runtime_panel.tty_wants_runtime_panel",
+ return_value=False,
+ ),
):
result = CliRunner().invoke(
chat,
diff --git a/tests/cli/test_cli_picker_integration.py b/tests/cli/test_cli_picker_integration.py
new file mode 100644
index 00000000..481cd8de
--- /dev/null
+++ b/tests/cli/test_cli_picker_integration.py
@@ -0,0 +1,397 @@
+"""Integration tests for CLI model picker and runtime panel paths."""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock, patch
+
+from click.testing import CliRunner
+
+from openjarvis.cli._model_switch import (
+ interactive_pick_model,
+ resolve_chat_cli_model,
+ variant_preset_model,
+)
+from openjarvis.cli._runtime_panel import (
+ ChatRuntimeOptions,
+ interactive_pick_runtime_options,
+ runtime_cli_options,
+ tty_wants_runtime_panel,
+)
+from openjarvis.cli.chat_cmd import chat
+from openjarvis.core.config import JarvisConfig
+
+
+def _chat_patches(engine: MagicMock, config: JarvisConfig | None = None):
+ cfg = config or JarvisConfig()
+ cfg.intelligence.default_model = "default-m"
+ return (
+ patch("openjarvis.cli.chat_cmd.load_config", return_value=cfg),
+ patch("openjarvis.engine.get_engine", return_value=("ollama", engine)),
+ patch("openjarvis.intelligence.register_builtin_models"),
+ )
+
+
+class TestModelSwitchBranches:
+ def test_variant_preset_no_intelligence(self) -> None:
+ assert variant_preset_model(object(), "chat") == ""
+
+ def test_interactive_pick_by_index(self) -> None:
+ engine = MagicMock()
+ engine.list_models.return_value = ["a", "b"]
+ with patch("builtins.input", return_value="2"):
+ assert interactive_pick_model(MagicMock(), engine) == "b"
+
+ def test_interactive_pick_enter_default(self) -> None:
+ engine = MagicMock()
+ engine.list_models.return_value = ["only"]
+ with patch("builtins.input", return_value=""):
+ assert interactive_pick_model(MagicMock(), engine) is None
+
+ def test_interactive_pick_list_models_raises(self) -> None:
+ engine = MagicMock()
+ engine.list_models.side_effect = RuntimeError("down")
+ console = MagicMock()
+ assert interactive_pick_model(console, engine) is None
+ console.print.assert_called()
+
+ def test_interactive_pick_empty_catalog(self) -> None:
+ engine = MagicMock()
+ engine.list_models.return_value = []
+ console = MagicMock()
+ assert interactive_pick_model(console, engine) is None
+
+ def test_interactive_pick_keyboard_interrupt(self) -> None:
+ engine = MagicMock()
+ engine.list_models.return_value = ["m"]
+ with patch("builtins.input", side_effect=KeyboardInterrupt):
+ assert interactive_pick_model(MagicMock(), engine) is None
+
+ def test_resolve_falls_back_to_discovered_model(self) -> None:
+ cfg = JarvisConfig()
+ cfg.intelligence.default_model = ""
+ eng = MagicMock()
+ with (
+ patch(
+ "openjarvis.engine.discover_engines",
+ return_value=[("ollama", eng)],
+ ),
+ patch(
+ "openjarvis.engine.discover_models",
+ return_value={"ollama": ["discovered"]},
+ ),
+ ):
+ m = resolve_chat_cli_model(
+ console=MagicMock(),
+ config=cfg,
+ engine=eng,
+ engine_name="ollama",
+ cli_model=None,
+ chat_variant="chat",
+ )
+ assert m == "discovered"
+
+
+class TestRuntimePanelBranches:
+ def test_summary_gpu_all_and_layers(self) -> None:
+ assert "all layers" in ChatRuntimeOptions(num_gpu=-1).summary(
+ engine_name="ollama"
+ )
+ assert "gpu=4 layers" in ChatRuntimeOptions(num_gpu=4).summary(
+ engine_name="ollama"
+ )
+ assert "gpu=default" in ChatRuntimeOptions().summary(engine_name="ollama")
+
+ def test_tty_skip_flag(self) -> None:
+ assert tty_wants_runtime_panel(True) is False
+
+ def test_interactive_runtime_ollama_full_flow(self) -> None:
+ console = MagicMock()
+ with patch(
+ "builtins.input",
+ side_effect=["65536", "0"],
+ ):
+ opts = interactive_pick_runtime_options(console, engine_name="ollama")
+ assert opts.num_ctx == 65536
+ assert opts.num_gpu == 0
+
+ def test_interactive_runtime_non_ollama_does_not_prompt(self) -> None:
+ console = MagicMock()
+ with patch("builtins.input") as read_input:
+ opts = interactive_pick_runtime_options(console, engine_name="vllm")
+ assert opts == ChatRuntimeOptions()
+ read_input.assert_not_called()
+
+ def test_interactive_runtime_ctx_interrupt(self) -> None:
+ with patch("builtins.input", side_effect=KeyboardInterrupt):
+ opts = interactive_pick_runtime_options(MagicMock(), engine_name="ollama")
+ assert opts == ChatRuntimeOptions()
+
+ def test_interactive_runtime_gpu_interrupt_keeps_ctx(self) -> None:
+ with patch("builtins.input", side_effect=["4096", KeyboardInterrupt]):
+ opts = interactive_pick_runtime_options(MagicMock(), engine_name="ollama")
+ assert opts.num_ctx == 4096
+ assert opts.num_gpu is None
+
+ def test_cli_flags_skip_prompts(self) -> None:
+ opts = interactive_pick_runtime_options(
+ MagicMock(),
+ engine_name="ollama",
+ cli_num_ctx=32_000,
+ cli_num_gpu=-1,
+ )
+ assert opts.to_engine_kwargs(engine_name="ollama") == {
+ "num_ctx": 32000,
+ "num_gpu": 999,
+ }
+
+ def test_runtime_cli_options_attached(self) -> None:
+ import click
+
+ @runtime_cli_options
+ @click.command()
+ def _cmd() -> None:
+ pass
+
+ param_names = [p.name for p in _cmd.params]
+ assert "num_ctx" in param_names
+ assert "num_gpu" in param_names
+ assert "skip_runtime_panel" in param_names
+
+
+class TestChatPickerIntegration:
+ def test_cloud_chat_never_receives_ollama_runtime_kwargs(self) -> None:
+ engine = MagicMock()
+ engine.generate.return_value = {"content": "ok"}
+ cfg = JarvisConfig()
+ cfg.intelligence.default_model = "gpt-4o-mini"
+ with (
+ patch("openjarvis.cli.chat_cmd.load_config", return_value=cfg),
+ patch("openjarvis.engine.get_engine", return_value=("cloud", engine)),
+ patch("openjarvis.intelligence.register_builtin_models"),
+ patch(
+ "openjarvis.cli._model_switch.tty_wants_model_picker",
+ return_value=False,
+ ),
+ patch(
+ "openjarvis.cli._runtime_panel.tty_wants_runtime_panel",
+ return_value=True,
+ ) as wants_panel,
+ ):
+ result = CliRunner().invoke(
+ chat,
+ ["--agent", "none"],
+ input="hello\n/quit\n",
+ )
+
+ assert result.exit_code == 0
+ wants_panel.assert_not_called()
+ engine.generate.assert_called_once()
+ assert engine.generate.call_args.kwargs == {"model": "gpt-4o-mini"}
+
+ def test_cloud_chat_rejects_ollama_runtime_flags(self) -> None:
+ engine = MagicMock()
+ cfg = JarvisConfig()
+ cfg.intelligence.default_model = "gpt-4o-mini"
+ with (
+ patch("openjarvis.cli.chat_cmd.load_config", return_value=cfg),
+ patch("openjarvis.engine.get_engine", return_value=("cloud", engine)),
+ patch("openjarvis.intelligence.register_builtin_models"),
+ patch(
+ "openjarvis.cli._model_switch.tty_wants_model_picker",
+ return_value=False,
+ ),
+ ):
+ result = CliRunner().invoke(
+ chat,
+ ["--agent", "none", "--num-ctx", "4096"],
+ )
+
+ assert result.exit_code == 2
+ assert "supported only with --engine ollama" in result.output
+ engine.generate.assert_not_called()
+
+ def test_rich_markup_in_runtime_labels_is_rendered_literally(self) -> None:
+ engine = MagicMock()
+ engine.generate.return_value = {"content": "ok"}
+ cfg = JarvisConfig()
+ cfg.intelligence.default_model = "default-m"
+ with (
+ patch("openjarvis.cli.chat_cmd.load_config", return_value=cfg),
+ patch(
+ "openjarvis.engine.get_engine",
+ return_value=("[bold]engine[/bold]", engine),
+ ),
+ patch("openjarvis.intelligence.register_builtin_models"),
+ patch(
+ "openjarvis.cli._runtime_panel.tty_wants_runtime_panel",
+ return_value=False,
+ ),
+ ):
+ result = CliRunner().invoke(
+ chat,
+ ["--agent", "none", "--model", "[red]model[/red]"],
+ input="/model\n/quit\n",
+ )
+
+ assert result.exit_code == 0
+ assert "[bold]engine[/bold]" in result.output
+ assert "[red]model[/red]" in result.output
+
+ def test_native_react_gets_engine_options_via_setattr(self) -> None:
+ """NativeReActAgent rejects engine_options kwarg; chat uses setattr."""
+ import openjarvis.agents # noqa: F401
+ from openjarvis.agents.native_react import NativeReActAgent
+ from openjarvis.core.registry import AgentRegistry
+
+ if not AgentRegistry.contains("native_react"):
+ AgentRegistry.register_value("native_react", NativeReActAgent)
+
+ engine = MagicMock()
+ engine.generate.return_value = {"content": "ok"}
+ cfg = JarvisConfig()
+ cfg.intelligence.default_model = "gemma4:e4b"
+ cfg.agent.default_agent = "native_react"
+ p = _chat_patches(engine, cfg)
+ with (
+ p[0],
+ p[1],
+ p[2],
+ patch(
+ "openjarvis.cli._model_switch.tty_wants_model_picker",
+ return_value=False,
+ ),
+ patch(
+ "openjarvis.cli._runtime_panel.tty_wants_runtime_panel",
+ return_value=False,
+ ),
+ ):
+ result = CliRunner().invoke(
+ chat,
+ ["--num-ctx", "8192", "--num-gpu", "0"],
+ input="/quit\n",
+ )
+ assert result.exit_code == 0
+ assert "failed" not in result.output.lower()
+
+ def test_picker_selects_model_and_shows_runtime_banner(self) -> None:
+ engine = MagicMock()
+ engine.list_models.return_value = ["picked-model"]
+ engine.generate.return_value = {"content": "hi"}
+ p = _chat_patches(engine)
+ with (
+ p[0],
+ p[1],
+ p[2],
+ patch(
+ "openjarvis.cli._model_switch.tty_wants_model_picker",
+ return_value=True,
+ ),
+ patch(
+ "openjarvis.cli._runtime_panel.tty_wants_runtime_panel",
+ return_value=False,
+ ),
+ patch(
+ "openjarvis.cli._model_switch.interactive_pick_model",
+ return_value="picked-model",
+ ),
+ ):
+ result = CliRunner().invoke(
+ chat,
+ ["--agent", "none"],
+ input="/model\n/runtime\n/quit\n",
+ )
+ assert result.exit_code == 0
+ assert "picked-model" in result.output
+ assert "Runtime:" in result.output
+
+ def test_num_ctx_num_gpu_cli_bypasses_panel(self) -> None:
+ engine = MagicMock()
+ engine.generate.return_value = {"content": "ok"}
+ p = _chat_patches(engine)
+ with (
+ p[0],
+ p[1],
+ p[2],
+ patch(
+ "openjarvis.cli._model_switch.tty_wants_model_picker",
+ return_value=False,
+ ),
+ patch(
+ "openjarvis.cli._runtime_panel.tty_wants_runtime_panel",
+ return_value=True,
+ ),
+ ):
+ result = CliRunner().invoke(
+ chat,
+ [
+ "--agent",
+ "none",
+ "-m",
+ "m1",
+ "--num-ctx",
+ "12000",
+ "--num-gpu",
+ "8",
+ ],
+ input="hello\n/runtime\n/quit\n",
+ )
+ assert result.exit_code == 0
+ assert "ctx=12,000" in result.output
+ assert "gpu=8 layers" in result.output
+ engine.generate.assert_called_once()
+ call_kw = engine.generate.call_args[1]
+ assert call_kw.get("num_ctx") == 12000
+ assert call_kw.get("num_gpu") == 8
+
+ def test_no_model_available_exits(self) -> None:
+ engine = MagicMock()
+ cfg = JarvisConfig()
+ cfg.intelligence.default_model = ""
+ p = _chat_patches(engine, cfg)
+ with (
+ p[0],
+ p[1],
+ p[2],
+ patch(
+ "openjarvis.cli._model_switch.tty_wants_model_picker",
+ return_value=False,
+ ),
+ patch(
+ "openjarvis.cli._runtime_panel.tty_wants_runtime_panel",
+ return_value=False,
+ ),
+ patch(
+ "openjarvis.cli._model_switch.resolve_chat_cli_model",
+ return_value="",
+ ),
+ ):
+ result = CliRunner().invoke(chat, [])
+ assert result.exit_code == 1
+ assert "No model available" in result.output
+
+ def test_smart_preset_used_when_no_flag(self) -> None:
+ cfg = JarvisConfig()
+ cfg.intelligence.model_chat = "preset-chat"
+ eng = MagicMock()
+ eng.generate.return_value = {"content": "x"}
+ p = _chat_patches(eng, cfg)
+ with (
+ p[0],
+ p[1],
+ p[2],
+ patch(
+ "openjarvis.cli._model_switch.tty_wants_model_picker",
+ return_value=False,
+ ),
+ patch(
+ "openjarvis.cli._runtime_panel.tty_wants_runtime_panel",
+ return_value=False,
+ ),
+ ):
+ result = CliRunner().invoke(
+ chat,
+ ["-m", "smart", "--agent", "none"],
+ input="/quit\n",
+ )
+ assert result.exit_code == 0
+ assert "preset-chat" in result.output
diff --git a/tests/cli/test_cli_picker_security.py b/tests/cli/test_cli_picker_security.py
new file mode 100644
index 00000000..e6065338
--- /dev/null
+++ b/tests/cli/test_cli_picker_security.py
@@ -0,0 +1,162 @@
+"""Security tests for CLI model picker and runtime panel layers."""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from openjarvis.cli._model_switch import (
+ MAX_MODEL_ID_LEN,
+ interactive_pick_model,
+ resolve_chat_cli_model,
+ sanitize_model_id,
+ tty_wants_model_picker,
+)
+from openjarvis.cli._runtime_panel import (
+ MAX_NUM_CTX,
+ ChatRuntimeOptions,
+ _parse_int,
+ tty_wants_runtime_panel,
+)
+from openjarvis.core.config import JarvisConfig
+
+
+class TestSanitizeModelId:
+ def test_strips_control_characters(self) -> None:
+ raw = "gemma\x00\x1f4:e4b\n"
+ assert "\x00" not in sanitize_model_id(raw)
+ assert "\n" not in sanitize_model_id(raw)
+
+ def test_truncates_oversized_ids(self) -> None:
+ raw = "m" * (MAX_MODEL_ID_LEN + 50)
+ assert len(sanitize_model_id(raw)) == MAX_MODEL_ID_LEN
+
+ def test_rejects_empty_after_sanitize(self) -> None:
+ assert sanitize_model_id(" \t\x00 ") == ""
+
+
+class TestRuntimePanelSecurity:
+ def test_num_ctx_capped_at_max(self) -> None:
+ opts = ChatRuntimeOptions(num_ctx=MAX_NUM_CTX + 50_000)
+ assert opts.to_engine_kwargs(engine_name="ollama")["num_ctx"] == MAX_NUM_CTX
+
+ def test_parse_int_rejects_non_numeric(self) -> None:
+ assert _parse_int("12abc", default=None) is None
+ assert _parse_int("0x1000", default=None) is None
+ assert _parse_int("1e6", default=None) is None
+
+ def test_engine_kwargs_only_expected_keys(self) -> None:
+ opts = ChatRuntimeOptions(num_ctx=4096, num_gpu=10)
+ assert set(opts.to_engine_kwargs(engine_name="ollama").keys()) <= {
+ "num_ctx",
+ "num_gpu",
+ }
+
+ def test_negative_num_ctx_not_forwarded(self) -> None:
+ opts = ChatRuntimeOptions(num_ctx=-1)
+ assert "num_ctx" not in opts.to_engine_kwargs(engine_name="ollama")
+
+ def test_num_gpu_all_layers_maps_to_bounded_value(self) -> None:
+ opts = ChatRuntimeOptions(num_gpu=-1)
+ assert opts.to_engine_kwargs(engine_name="ollama")["num_gpu"] == 999
+
+ def test_extreme_num_gpu_capped(self) -> None:
+ from openjarvis.cli._runtime_panel import MAX_NUM_GPU_LAYERS
+
+ opts = ChatRuntimeOptions(num_gpu=10**9)
+ assert (
+ opts.to_engine_kwargs(engine_name="ollama")["num_gpu"] == MAX_NUM_GPU_LAYERS
+ )
+
+
+class TestModelPickerSecurity:
+ def test_arbitrary_freeform_choice_not_accepted(self) -> None:
+ """Unknown ids must not be passed through (only listed models)."""
+ engine = MagicMock()
+ engine.list_models.return_value = ["safe-model:latest"]
+ console = MagicMock()
+ with patch("builtins.input", return_value="../../../etc/passwd"):
+ picked = interactive_pick_model(console, engine)
+ assert picked is None
+
+ def test_exact_listed_model_accepted(self) -> None:
+ engine = MagicMock()
+ engine.list_models.return_value = ["safe-model:latest"]
+ console = MagicMock()
+ with patch("builtins.input", return_value="safe-model:latest"):
+ picked = interactive_pick_model(console, engine)
+ assert picked == "safe-model:latest"
+
+ def test_resolve_sanitizes_explicit_cli_model(self) -> None:
+ cfg = JarvisConfig()
+ eng = MagicMock()
+ eng.list_models.return_value = []
+ model = resolve_chat_cli_model(
+ console=MagicMock(),
+ config=cfg,
+ engine=eng,
+ engine_name="ollama",
+ cli_model="ok\x00model",
+ chat_variant="chat",
+ )
+ assert "\x00" not in model
+
+ def test_substring_match_cannot_select_unlisted_model(self) -> None:
+ engine = MagicMock()
+ engine.list_models.return_value = ["prod-model:v1", "prod-model:v2"]
+ console = MagicMock()
+ with patch("builtins.input", return_value="prod"):
+ picked = interactive_pick_model(console, engine)
+ assert picked is None
+
+ def test_catalog_labels_are_sanitized_and_rich_escaped(self) -> None:
+ engine = MagicMock()
+ engine.list_models.return_value = ["[red]safe-id[/red]\n"]
+ console = MagicMock()
+ with patch("builtins.input", return_value="1"):
+ picked = interactive_pick_model(console, engine)
+
+ assert picked == "[red]safe-id[/red]"
+ rendered = "\n".join(str(call.args[0]) for call in console.print.call_args_list)
+ assert r"\[red]safe-id\[/red]" in rendered
+
+
+class TestTtyGates:
+ def test_explicit_chat_does_not_auto_prompt_on_tty(self) -> None:
+ with patch("sys.stdin.isatty", return_value=True):
+ assert tty_wants_model_picker(False) is False
+
+ def test_explicit_picker_flag_is_honored(self) -> None:
+ assert tty_wants_model_picker(True) is True
+
+ def test_skip_env_disables_runtime_panel(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.setenv("JARVIS_SKIP_RUNTIME_PANEL", "1")
+ with patch("sys.stdin.isatty", return_value=True):
+ assert tty_wants_runtime_panel(False) is False
+
+
+class TestAgentEngineOptionsIsolation:
+ def test_engine_options_merge_does_not_leak_extra_keys(self) -> None:
+ from openjarvis.agents._stubs import _ALLOWED_ENGINE_OPTION_KEYS
+ from openjarvis.agents.simple import SimpleAgent
+ from openjarvis.core.registry import AgentRegistry
+ from openjarvis.core.types import Message, Role
+
+ engine = MagicMock()
+ engine.generate.return_value = {"content": "x"}
+ if not AgentRegistry.contains("simple"):
+ AgentRegistry.register_value("simple", SimpleAgent)
+
+ agent = SimpleAgent(
+ engine,
+ "m",
+ engine_options={"num_ctx": 8192, "evil": "payload"},
+ )
+ assert _ALLOWED_ENGINE_OPTION_KEYS == frozenset({"num_ctx", "num_gpu"})
+ agent._generate([Message(role=Role.USER, content="hi")])
+ call_kwargs = engine.generate.call_args[1]
+ assert "evil" not in call_kwargs
+ assert call_kwargs.get("num_ctx") == 8192
diff --git a/tests/cli/test_first_run_picker.py b/tests/cli/test_first_run_picker.py
new file mode 100644
index 00000000..2f2eaaca
--- /dev/null
+++ b/tests/cli/test_first_run_picker.py
@@ -0,0 +1,52 @@
+"""Tests for bare ``jarvis`` routing with model picker."""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from openjarvis.cli._first_run import check_and_route
+from openjarvis.cli.chat_cmd import chat as chat_cmd
+from openjarvis.cli.init_cmd import init as init_cmd
+from openjarvis.core import config as _cfg
+
+
+def config_path(tmp_path, monkeypatch: pytest.MonkeyPatch):
+ path = tmp_path / "config.toml"
+ path.write_text("[engine]\ndefault = 'ollama'\n", encoding="utf-8")
+ monkeypatch.setattr(_cfg, "DEFAULT_CONFIG_PATH", path)
+ return path
+
+
+def test_check_and_route_enables_picker_on_tty(config_path) -> None:
+ ctx = MagicMock()
+ ctx.invoked_subcommand = None
+ ctx.obj = {}
+ with patch("sys.stdin.isatty", return_value=True):
+ check_and_route(ctx)
+ ctx.invoke.assert_called_once_with(chat_cmd, pick_model=True)
+
+
+def test_check_and_route_skips_picker_with_env(
+ config_path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setenv("JARVIS_SKIP_MODEL_PICK", "1")
+ ctx = MagicMock()
+ ctx.invoked_subcommand = None
+ ctx.obj = {}
+ with patch("sys.stdin.isatty", return_value=True):
+ check_and_route(ctx)
+ ctx.invoke.assert_called_once_with(chat_cmd, pick_model=False)
+
+
+def test_check_and_route_runs_init_without_config(
+ tmp_path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ missing = tmp_path / "no-config.toml"
+ monkeypatch.setattr(_cfg, "DEFAULT_CONFIG_PATH", missing)
+ ctx = MagicMock()
+ ctx.invoked_subcommand = None
+ check_and_route(ctx)
+ ctx.invoke.assert_called_once_with(init_cmd, from_bare_jarvis=True)
diff --git a/tests/cli/test_model_switch.py b/tests/cli/test_model_switch.py
new file mode 100644
index 00000000..db504ccf
--- /dev/null
+++ b/tests/cli/test_model_switch.py
@@ -0,0 +1,106 @@
+"""Tests for CLI model preset / smart resolution."""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock, patch
+
+from openjarvis.cli._model_switch import (
+ interactive_pick_model,
+ resolve_chat_cli_model,
+ tty_wants_model_picker,
+ variant_preset_model,
+)
+from openjarvis.core.config import JarvisConfig
+
+
+def test_variant_preset_long() -> None:
+ cfg = JarvisConfig()
+ cfg.intelligence.model_long = "devstral:q4"
+ assert variant_preset_model(cfg, "long") == "devstral:q4"
+ assert variant_preset_model(cfg, "chat") == ""
+
+
+def test_resolve_explicit_model() -> None:
+ cfg = JarvisConfig()
+ cfg.intelligence.default_model = "fallback"
+ cfg.intelligence.model_long = "preset-long"
+ eng = MagicMock()
+ eng.list_models.return_value = ["a"]
+ m = resolve_chat_cli_model(
+ console=MagicMock(),
+ config=cfg,
+ engine=eng,
+ engine_name="ollama",
+ cli_model="explicit-only",
+ chat_variant="long",
+ )
+ assert m == "explicit-only"
+
+
+def test_resolve_smart_uses_preset() -> None:
+ cfg = JarvisConfig()
+ cfg.intelligence.default_model = "fallback"
+ cfg.intelligence.model_code = "coder-model"
+ eng = MagicMock()
+ eng.list_models.return_value = ["a"]
+ m = resolve_chat_cli_model(
+ console=MagicMock(),
+ config=cfg,
+ engine=eng,
+ engine_name="ollama",
+ cli_model="smart",
+ chat_variant="code",
+ )
+ assert m == "coder-model"
+
+
+def test_tty_wants_model_picker_flag() -> None:
+ assert tty_wants_model_picker(True) is True
+
+
+def test_invalid_index_returns_none() -> None:
+ engine = MagicMock()
+ engine.list_models.return_value = ["only"]
+ with patch("builtins.input", return_value="99"):
+ assert interactive_pick_model(MagicMock(), engine) is None
+
+
+def test_preset_chat_variant() -> None:
+ cfg = JarvisConfig()
+ cfg.intelligence.model_chat = "chat-preset"
+ assert variant_preset_model(cfg, "chat") == "chat-preset"
+
+
+def test_resolve_returns_empty_when_nothing_found() -> None:
+ cfg = JarvisConfig()
+ cfg.intelligence.default_model = ""
+ eng = MagicMock()
+ with (
+ patch("openjarvis.engine.discover_engines", return_value=[]),
+ patch("openjarvis.engine.discover_models", return_value={}),
+ ):
+ m = resolve_chat_cli_model(
+ console=MagicMock(),
+ config=cfg,
+ engine=eng,
+ engine_name="ollama",
+ cli_model=None,
+ chat_variant="chat",
+ )
+ assert m == ""
+
+
+def test_resolve_omitted_uses_default() -> None:
+ cfg = JarvisConfig()
+ cfg.intelligence.default_model = "defm"
+ eng = MagicMock()
+ eng.list_models.return_value = ["x"]
+ m = resolve_chat_cli_model(
+ console=MagicMock(),
+ config=cfg,
+ engine=eng,
+ engine_name="ollama",
+ cli_model=None,
+ chat_variant="short",
+ )
+ assert m == "defm"
diff --git a/tests/cli/test_runtime_panel.py b/tests/cli/test_runtime_panel.py
new file mode 100644
index 00000000..264c5d72
--- /dev/null
+++ b/tests/cli/test_runtime_panel.py
@@ -0,0 +1,56 @@
+"""Tests for CLI runtime panel (context / GPU offload)."""
+
+from __future__ import annotations
+
+from openjarvis.cli._runtime_panel import (
+ MAX_NUM_CTX,
+ ChatRuntimeOptions,
+ _parse_int,
+)
+
+
+def test_parse_int_underscores() -> None:
+ assert _parse_int("32_768", default=None) == 32768
+
+
+def test_chat_runtime_options_engine_kwargs() -> None:
+ opts = ChatRuntimeOptions(num_ctx=65536, num_gpu=-1)
+ kw = opts.to_engine_kwargs(engine_name="ollama")
+ assert kw["num_ctx"] == 65536
+ assert kw["num_gpu"] == 999
+
+
+def test_runtime_summary_ollama() -> None:
+ opts = ChatRuntimeOptions(num_ctx=150_000, num_gpu=0)
+ s = opts.summary(engine_name="ollama")
+ assert "ctx=150,000" in s
+ assert "gpu=0 (CPU)" in s
+
+
+def test_max_num_ctx_constant() -> None:
+ assert MAX_NUM_CTX == 200_000
+
+
+def test_zero_ctx_treated_as_default() -> None:
+ opts = ChatRuntimeOptions(num_ctx=0)
+ assert "num_ctx" not in opts.to_engine_kwargs(engine_name="ollama")
+
+
+def test_non_ollama_engine_gets_no_runtime_kwargs() -> None:
+ opts = ChatRuntimeOptions(num_ctx=65536, num_gpu=12)
+
+ assert opts.to_engine_kwargs(engine_name="cloud") == {}
+
+
+def test_parse_int_commas() -> None:
+ assert _parse_int("150,000", default=None) == 150_000
+
+
+def test_interactive_zero_ctx_becomes_default() -> None:
+ from unittest.mock import MagicMock, patch
+
+ from openjarvis.cli._runtime_panel import interactive_pick_runtime_options
+
+ with patch("builtins.input", side_effect=["0", ""]):
+ opts = interactive_pick_runtime_options(MagicMock(), engine_name="ollama")
+ assert opts.num_ctx is None
diff --git a/tests/engine/test_ollama_runtime_options.py b/tests/engine/test_ollama_runtime_options.py
new file mode 100644
index 00000000..ab338495
--- /dev/null
+++ b/tests/engine/test_ollama_runtime_options.py
@@ -0,0 +1,26 @@
+"""Tests for Ollama runtime option wiring (num_ctx / num_gpu)."""
+
+from __future__ import annotations
+
+from openjarvis.engine.ollama import _ollama_request_options
+
+
+def test_with_explicit_runtime_kwargs() -> None:
+ opts = _ollama_request_options(
+ temperature=0.5,
+ max_tokens=512,
+ kwargs={"num_ctx": 64000, "num_gpu": 12},
+ )
+ assert opts["num_ctx"] == 64000
+ assert opts["num_gpu"] == 12
+
+
+def test_default_num_ctx_when_omitted(monkeypatch) -> None: # noqa: ANN001
+ monkeypatch.setenv("JARVIS_NUM_CTX", "24576")
+ opts = _ollama_request_options(
+ temperature=0.7,
+ max_tokens=1024,
+ kwargs={},
+ )
+ assert opts["num_ctx"] == 24576
+ assert "num_gpu" not in opts