Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(workspace): let the user register terminal CLIs of their own
rubenluetke10-beep9a37e95d2ce0
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.pyindex abceecc8ed..214026b294 100644--- a/jarvis/agentic_ide/session.py+++ b/jarvis/agentic_ide/session.py@@ -754,6 +754,15 @@ def agent_argv(agent: str) -> tuple[str, ...] | None:exe = shutil.which(binary)if exe is None:return None+ if spec.shell_launch:+ # A user-added entry whose command is shell SOURCE — a pipeline, a+ # variable assignment, two commands chained. There is no argv to exec,+ # so it runs through a shell that EXITS with it (never `-NoExit`/`/k`:+ # a surviving prompt would look like a live agent to every readiness+ # check). The PATH lookup above still had to succeed, so an entry whose+ # first word is not installed is reported missing rather than opening a+ # pane that says "command not found".+ return workspace_agents.shell_run_argv(spec.launch_command or "")if sys.platform == "win32":lowered = exe.lower()if lowered.endswith((".cmd", ".bat")):diff --git a/jarvis/core/paths.py b/jarvis/core/paths.pyindex a67ebe3f5a..a79ab822ec 100644--- a/jarvis/core/paths.py+++ b/jarvis/core/paths.py@@ -59,6 +59,23 @@ def user_clis_dir() -> Path:return user_data_dir() / "clis"+def workspace_clis_dir() -> Path:+ """Where the user's own terminal CLIs and their logos are kept.++ Deliberately NOT :func:`user_clis_dir`, which holds specs for the shared CLI+ catalog — those become brain-callable tools. An entry here is only ever+ something a workspace terminal RUNS (see ``jarvis.workspace.custom_clis``),+ and keeping the two directories apart is what keeps a command the user typed+ into a terminal picker from quietly becoming a tool an LLM may call.+ """+ return user_data_dir() / "workspace-clis"+++def workspace_clis_path() -> Path:+ """JSON file listing the user's own terminal CLIs."""+ return workspace_clis_dir() / "custom.json"++def cli_usage_db_path() -> Path:"""SQLite database containing CLI invocation metadata (CLI integration)."""return user_data_dir() / "cli_usage.db"@@ -217,6 +234,8 @@ __all__ = ["user_memory_dir","user_logs_dir","user_clis_dir",+ "workspace_clis_dir",+ "workspace_clis_path","cli_usage_db_path","cli_custom_catalog_path","skill_link_health_db_path",diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex 48bdae5e66..685a4d344a 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -607,6 +607,22 @@ class AgentStatus(BaseModel):),)description: str = Field(default="", description="One line for a picker.")+ custom: bool = Field(+ default=False,+ description=(+ "True for a CLI the user added themselves. A surface uses this to "+ "offer editing or removing it, which makes no sense for a shipped "+ "entry."+ ),+ )+ logo_url: str = Field(+ default="",+ description=(+ "Where to fetch this entry's mark. Empty for a shipped entry, whose "+ "logo is a local asset the client already has, and for a custom one "+ "with no logo, which falls back to a monogram."+ ),+ )class AgentsResponse(BaseModel):@@ -1217,6 +1233,8 @@ async def get_agents() -> AgentsResponse:install_command=info.install_command,kind=info.kind,description=info.description,+ custom=info.custom,+ logo_url=info.logo_url,)for info in infos]diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex 712b6fd7b9..05b6dea479 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -396,6 +396,7 @@ class WebServer:from .wiki_routes import router as wiki_routerfrom .wiki_ws import router as wiki_ws_routerfrom .workflows_routes import router as workflows_router+ from .workspace_clis_routes import router as workspace_clis_routerfrom .workspace_routes import router as workspace_router# Conductor is an external package in the same monorepo. Import# defensively — anyone who checks out the repo without conductor would@@ -471,6 +472,7 @@ class WebServer:# Provides agent detection, workspace launch planning, and PTY WebSocket# for in-app Claude Code / Codex terminals (xterm panes, not OS windows).app.include_router(workspace_router)+ app.include_router(workspace_clis_router)# Agentic IDE (/api/agentic-ide/*) — a chosen folder plus named terminals# running Claude Code / Codex, addressable by voice ("what is Mika# doing?") and promptable from Jarvis. Reuses the same PTY stack as thediff --git a/jarvis/ui/web/workspace_clis_routes.py b/jarvis/ui/web/workspace_clis_routes.pynew file mode 100644index 0000000000..37e90ca31c--- /dev/null+++ b/jarvis/ui/web/workspace_clis_routes.py@@ -0,0 +1,258 @@+"""REST routes for the terminal CLIs the user added themselves.++The HTTP face of :mod:`jarvis.workspace.custom_clis`. Everything these routes+touch ends up in the same registry the shipped CLIs live in, so a CLI created+here is immediately offered by the setup wizard's terminal allocation, the+"open a terminal — what?" picker, the pane split menu and the voice catalog —+no restart, no second list to keep in step.++Mount alongside the other routers::++ from .workspace_clis_routes import router as workspace_clis_router+ app.include_router(workspace_clis_router)++**Why the write routes are marked dangerous.** A stored entry is a command line+this app will start in a terminal. That is exactly what the user is asking for+when they type it into the form themselves — and exactly what must not happen+because a model decided it would be helpful. The metadata keeps the generated+CLI and the tool broker asking first (CLAUDE.md §5, AP-14).+"""+from __future__ import annotations++import logging+from typing import Annotated, Any++from fastapi import APIRouter, File, HTTPException, UploadFile+from fastapi.responses import FileResponse+from pydantic import BaseModel, Field++from jarvis.workspace import custom_clis+from jarvis.workspace.agents import refresh_custom_agents++log = logging.getLogger(__name__)++router = APIRouter(prefix="/api/workspace-clis", tags=["workspace-clis"])+++class CustomCliModel(BaseModel):+ """One user-added CLI as the UI sees it."""++ id: str = Field(description="Stable registry key. Never changes on a rename.")+ display_name: str+ command: str = Field(description="The command line that starts this CLI.")+ description: str = ""+ file_reference: str = Field(+ default="quoted",+ description=(+ "How a dropped file is written into this CLI's prompt: 'at' for "+ "@path (most modern coding CLIs) or 'quoted' for \"path\"."+ ),+ )+ logo_url: str = Field(+ default="",+ description="Where to fetch this entry's mark; empty when it has none.",+ )+ runs_through_shell: bool = Field(+ default=False,+ description=(+ "True when the command is shell source (a pipeline, an environment "+ "assignment, two commands chained) and therefore starts inside a "+ "shell rather than as the pane's own process."+ ),+ )+ binary: str = Field(+ default="",+ description="The word that has to be on PATH for this command to start.",+ )+++class CustomCliListResponse(BaseModel):+ clis: list[CustomCliModel]+ max_name_length: int = custom_clis.MAX_NAME_LEN+ max_command_length: int = custom_clis.MAX_COMMAND_LEN+ max_logo_bytes: int = custom_clis.MAX_LOGO_BYTES+ logo_extensions: list[str] = Field(+ default_factory=lambda: sorted(custom_clis.LOGO_TYPES)+ )+++class CreateCustomCliRequest(BaseModel):+ display_name: str+ command: str+ description: str = ""+ file_reference: str = "quoted"+++class UpdateCustomCliRequest(BaseModel):+ """Every field optional — an omitted one is left exactly as it was."""++ display_name: str | None = None+ command: str | None = None+ description: str | None = None+ file_reference: str | None = None+++def _model(entry: custom_clis.CustomCli) -> CustomCliModel:+ return CustomCliModel(+ id=entry.id,+ display_name=entry.display_name,+ command=entry.command,+ description=entry.description,+ file_reference=entry.file_reference,+ logo_url=custom_clis.logo_url(entry),+ runs_through_shell=custom_clis.needs_shell(entry.command),+ binary=entry.binary,+ )+++def _published(entry: custom_clis.CustomCli) -> CustomCliModel:+ """Return the entry AND make the registry aware of the change.++ Every write goes through here, because a stored entry that the registry has+ not re-read is one the user can see in the list and cannot open in a pane —+ which reads as the feature being broken rather than as a stale cache.+ """+ refresh_custom_agents()+ return _model(entry)+++def _bad_request(exc: custom_clis.CustomCliError) -> HTTPException:+ """A validation complaint, phrased for the person who typed the form."""+ return HTTPException(status_code=422, detail=str(exc))++[email protected]("", response_model=CustomCliListResponse, summary="List your own CLIs")+async def list_clis() -> CustomCliListResponse:+ """Every CLI the user added, plus the limits the form has to respect."""+ return CustomCliListResponse(+ clis=[_model(entry) for entry in custom_clis.list_custom_clis()]+ )+++ "",+ response_model=CustomCliModel,+ summary="Add a CLI of your own",+ openapi_extra={"x-jarvis-dangerous": True},+)+async def create_cli(req: CreateCustomCliRequest) -> CustomCliModel:+ """Store a new CLI and offer it everywhere a terminal can be opened."""+ try:+ entry = custom_clis.create_custom_cli(+ req.display_name,+ req.command,+ description=req.description,+ file_reference=req.file_reference,+ )+ except custom_clis.CustomCliError as exc:+ raise _bad_request(exc) from exc+ log.info("workspace-clis: added %r (%s)", entry.display_name, entry.id)+ return _published(entry)+++ "/{cli_id}",+ response_model=CustomCliModel,+ summary="Change one of your CLIs",+ openapi_extra={"x-jarvis-dangerous": True},+)+async def update_cli(cli_id: str, req: UpdateCustomCliRequest) -> CustomCliModel:+ """Edit a stored CLI. Panes already running it keep the command they started+ with — a live process cannot be re-launched under it."""+ try:+ entry = custom_clis.update_custom_cli(+ cli_id,+ display_name=req.display_name,+ command=req.command,+ description=req.description,+ file_reference=req.file_reference,+ )+ except custom_clis.CustomCliError as exc:+ raise _bad_request(exc) from exc+ return _published(entry)+++ "/{cli_id}",+ summary="Remove one of your CLIs",+ openapi_extra={"x-jarvis-dangerous": True},+)+async def delete_cli(cli_id: str) -> dict[str, Any]:+ """Forget a CLI and its logo. Open panes running it are left alone."""+ try:+ entry = custom_clis.delete_custom_cli(cli_id)+ except custom_clis.CustomCliError as exc:+ raise _bad_request(exc) from exc+ refresh_custom_agents()+ log.info("workspace-clis: removed %r (%s)", entry.display_name, entry.id)+ return {"ok": True, "id": entry.id, "display_name": entry.display_name}+++ "/{cli_id}/logo",+ response_model=CustomCliModel,+ summary="Set a CLI's logo",+ openapi_extra={"x-jarvis-dangerous": True},+)+async def upload_logo(+ cli_id: str, file: Annotated[UploadFile, File()]+) -> CustomCliModel:+ """Store an image as this CLI's mark in every picker.++ Read with a ceiling rather than whole: ``UploadFile`` will happily spool a+ multi-gigabyte body to disk before anything gets to reject it, so the size+ limit is applied to the read itself. One byte over the limit is enough to+ know, and the rest of the body is never touched.+ """+ limit = custom_clis.MAX_LOGO_BYTES+ data = await file.read(limit + 1)+ try:+ entry = custom_clis.set_logo(cli_id, data, file.filename or "")+ except custom_clis.CustomCliError as exc:+ raise _bad_request(exc) from exc+ return _published(entry)+++ "/{cli_id}/logo",+ response_model=CustomCliModel,+ summary="Remove a CLI's logo",+ openapi_extra={"x-jarvis-dangerous": True},+)+async def remove_logo(cli_id: str) -> CustomCliModel:+ """Drop the logo; the picker falls back to the monogram it draws without one."""+ try:+ entry = custom_clis.clear_logo(cli_id)+ except custom_clis.CustomCliError as exc:+ raise _bad_request(exc) from exc+ return _published(entry)++[email protected]("/{cli_id}/logo", summary="A CLI's logo")+async def get_logo(cli_id: str) -> FileResponse:+ """Serve the stored image.++ Two headers earn their place. ``Content-Security-Policy: sandbox`` because+ SVG is a document format: a mark fetched into an ``<img>`` cannot run its+ own script, but the same URL opened in a tab could, and the header closes+ that door for both. ``X-Content-Type-Options: nosniff`` so a browser that+ disagrees with our media type does not go looking for a better one.+ """+ found = custom_clis.logo_file(cli_id)+ if found is None:+ raise HTTPException(status_code=404, detail="This CLI has no logo.")+ path, media_type = found+ return FileResponse(+ path,+ media_type=media_type,+ headers={+ "Content-Security-Policy": "sandbox; default-src 'none'",+ "X-Content-Type-Options": "nosniff",+ # The picker asks for this on every render, and a logo the user+ # just replaced has to be the one they see.+ "Cache-Control": "no-cache",+ },+ )+++__all__ = ["router"]diff --git a/jarvis/ui/web/workspace_routes.py b/jarvis/ui/web/workspace_routes.pyindex 0c9dfb0cfd..7389591980 100644--- a/jarvis/ui/web/workspace_routes.py+++ b/jarvis/ui/web/workspace_routes.py@@ -21,9 +21,9 @@ from pydantic import BaseModel, Fieldfrom jarvis.core.paths import repo_rootfrom jarvis.terminal.pty_manager import PtyManagerfrom jarvis.workspace.agents import (- AGENT_NAMES,build_agent_argv,build_install_argv,+ coding_agent_names,detect_agents,pty_available,)@@ -67,7 +67,8 @@ async def get_agents() -> AgentsResponse:# split is validated against the same list — offering the plain-terminal# entry here would put a choice in front of the user that ``/launch`` then# rejects. A plain shell is offered where it belongs: the Agentic-IDE grid.- infos = [i for i in await detect_agents() if i.name in AGENT_NAMES]+ coding = set(coding_agent_names())+ infos = [i for i in await detect_agents() if i.name in coding]return AgentsResponse(cwd=str(repo_root()),terminal_available=pty_available(),@@ -127,14 +128,18 @@ async def workspace_pty(ws: WebSocket, key: str) -> None:rows = _safe_int(qp.get("rows"), 24)cwd = str(repo_root())+ # Asked once per connection, and asked LIVE: a CLI the user added while the+ # app was running is a legitimate answer here, and the import-time snapshot+ # this used to test against could never contain one.+ known = set(coding_agent_names())if agent:- if agent not in AGENT_NAMES:+ if agent not in known:await ws.close(code=4400, reason="unknown agent")returnensure_trusted(repo_root(), [agent]) # idempotent, skips the trust dialogargv = build_agent_argv(agent)elif install:- if install not in AGENT_NAMES:+ if install not in known:await ws.close(code=4400, reason="unknown agent")returnargv = build_install_argv(install)diff --git a/jarvis/workspace/agents.py b/jarvis/workspace/agents.pyindex 2c743b3ae9..684c5499e3 100644--- a/jarvis/workspace/agents.py+++ b/jarvis/workspace/agents.py@@ -258,6 +258,20 @@ class WorkspaceAgent:#: The per-project instructions file this CLI reads (CLAUDE.md, AGENTS.md).instruction_filename: str = ""+ # --- Where the entry came from ------------------------------------------+ #: True for an entry the USER added (:mod:`jarvis.workspace.custom_clis`)+ #: rather than one this app ships. Read by the surfaces that may offer to+ #: edit or remove it, and by detection, which cannot run a stranger's+ #: ``--version`` on the event loop the wake microphone is delivered on.+ custom: bool = False+ #: Where the UI fetches this entry's mark. Empty for a built-in, whose logo+ #: is a local asset the frontend already ships.+ logo_url: str = ""+ #: Start this through a shell instead of as the pane's own process. Needed+ #: by a command that is shell SOURCE rather than an argv — a pipeline, a+ #: variable expansion, two commands chained — which cannot be exec'd.+ shell_launch: bool = False+# --- How a person refers to it ------------------------------------------#: Spellings a transcript may carry for this product. Matching DATA, not#: prose: speech recognition writes a product name by ear, and one unmatched@@ -673,6 +687,156 @@ _AGENTS: dict[str, WorkspaceAgent] = {}+#: The entries the USER added, rebuilt from their store whenever it changes.+#:+#: Kept apart from ``_AGENTS`` rather than merged into it, because the two are+#: owned by different people: ``_AGENTS`` holds what this app ships plus+#: whatever a plugin registered in code, and re-reading a FILE must never be+#: able to drop one of those on the floor.+_CUSTOM_AGENTS: dict[str, WorkspaceAgent] = {}+#: Store revision the dict above was built from; ``-1`` means "never built".+_custom_revision: int = -1+++def builtin_names() -> tuple[str, ...]:+ """Every registry key this app ships or a plugin registered in code.++ Read by the custom-CLI store, which has to know which names are already+ spoken for before it hands one to a new entry.+ """+ return tuple(_AGENTS)+++def _custom_aliases(display_name: str, entry_id: str) -> tuple[str, ...]:+ """Spellings a transcript may carry for a user-added entry.++ Deliberately conservative, because these spellings are matched against+ everything the user says. The full name counts (a whole phrase matching by+ accident is unlikely), and a SINGLE-word name counts only from four letters+ up — an entry someone called "Test" or "Go" would otherwise turn every+ sentence containing that ordinary word into a request to open a terminal.+ Anything richer is the built-ins' business: they list their misspellings by+ hand because someone checked how speech recognition writes them.+ """+ out: list[str] = []+ name = " ".join(str(display_name or "").lower().split())+ words = name.split()+ if len(words) > 1:+ out.append(name)+ elif words and len(words[0]) >= 4 and words[0].isalpha():+ out.append(words[0])+ slug = str(entry_id or "").lower()+ if len(slug) >= 4 and slug.isalpha() and slug not in out:+ out.append(slug)+ return tuple(out)+++def _custom_agent(entry: Any) -> WorkspaceAgent:+ """Turn one stored :class:`~jarvis.workspace.custom_clis.CustomCli` into an+ entry the rest of this module cannot tell apart from a built-in.++ Deliberately ``spec=None``. A spec is a DETECTION plan — "run this with+ ``--version`` and parse the answer" — and we have no promise a stranger's+ CLI answers that flag rather than opening its TUI and holding the event+ loop the wake microphone runs on. Detection for these entries is a PATH+ lookup instead (see :func:`_sweep_agents`), which costs no subprocess and+ reports no version rather than a guessed one.+ """+ from jarvis.workspace import custom_clis++ through_shell = custom_clis.needs_shell(entry.command)+ return WorkspaceAgent(+ name=entry.id,+ display_name=entry.display_name,+ kind="cli",+ spoken_aliases=_custom_aliases(entry.display_name, entry.id),+ spec=None,+ launch_command=entry.command,+ # Nothing is known about this CLI's trust file, so there is nothing to+ # pre-seed. Its own dialog, if it has one, is answered by the user in+ # the pane — which is exactly what happens today outside this app.+ needs_trust=False,+ description=entry.description,+ binary=entry.binary,+ # Empty for a shell launch: the whole line goes to the shell verbatim,+ # so a second, half-parsed copy of it here would only be something a+ # future caller could pick up and get wrong.+ launch_args=()+ if through_shell+ else custom_clis.split_command(entry.command)[1:],+ file_reference=entry.file_reference,+ custom=True,+ logo_url=custom_clis.logo_url(entry),+ shell_launch=through_shell,+ )+++def _sync_custom_agents() -> None:+ """Rebuild the user's entries when their store has changed.++ Called from every read below rather than once at import, because the store+ is edited while the app runs: a CLI added in the wizard has to be openable+ from the pane menu in the same session, without a restart.+ """+ global _custom_revision+ from jarvis.workspace import custom_clis++ revision = custom_clis.revision()+ if revision == _custom_revision:+ return+ try:+ entries = custom_clis.list_custom_clis()+ except Exception as exc: # noqa: BLE001 - a broken store must not hide the built-ins+ log.warning("workspace agents: custom entries unavailable: %s", exc)+ entries = []+ _custom_revision = revision+ _CUSTOM_AGENTS.clear()+ for entry in entries:+ if entry.id in _AGENTS:+ # A name a built-in already answers to. The store refuses to create+ # one, so this is a hand-edited file; the shipped entry wins,+ # because a pane running the wrong tool is the worse failure.+ log.warning(+ "workspace agents: custom entry %r shadows a built-in; ignoring it",+ entry.id,+ )+ continue+ _CUSTOM_AGENTS[entry.id] = _custom_agent(entry)+ _forget_command_catalog()+++def refresh_custom_agents() -> None:+ """Re-read the user's entries now, and forget the last detection sweep.++ For the routes that just changed the store: the next question about "what+ can this machine run" has to see the new entry, and the sweep's answer for+ it (installed or not) has not been asked yet.+ """+ global _custom_revision+ _custom_revision = -1+ _sync_custom_agents()+ invalidate_agent_detection()+++def _registry() -> dict[str, WorkspaceAgent]:+ """Every entry, built-ins first, in the order the UI should list them.++ The plain terminal stays LAST even though it is registered among the+ built-ins: it is the "no agent at all" choice, and a menu that buries it+ between coding CLIs reads as though it were one of them.+ """+ _sync_custom_agents()+ merged: dict[str, WorkspaceAgent] = {}+ shell = _AGENTS.get(PLAIN_TERMINAL)+ for name, agent in _AGENTS.items():+ if name != PLAIN_TERMINAL:+ merged[name] = agent+ merged.update(_CUSTOM_AGENTS)+ if shell is not None:+ merged[PLAIN_TERMINAL] = shell+ return merged++def register_agent(agent: WorkspaceAgent, *, replace: bool = False) -> WorkspaceAgent:"""Add ``agent`` to the registry and return it.@@ -709,16 +873,16 @@ def _forget_command_catalog() -> None:def list_agents() -> list[WorkspaceAgent]:"""Every registered entry, in registration order."""- return list(_AGENTS.values())+ return list(_registry().values())def get_agent(name: str) -> WorkspaceAgent | None:- return _AGENTS.get(name)+ return _registry().get(name)def agent_names() -> tuple[str, ...]:"""Every registered name, plain terminal included."""- return tuple(_AGENTS)+ return tuple(_registry())def coding_agent_names() -> tuple[str, ...]:@@ -727,20 +891,26 @@ def coding_agent_names() -> tuple[str, ...]:The "Make It Yours" launcher plans a grid of agents that extend Jarvis, soit asks this rather than :func:`agent_names`."""- return tuple(name for name, agent in _AGENTS.items() if agent.is_coding_agent)+ return tuple(+ name for name, agent in _registry().items() if agent.is_coding_agent+ )def needs_trust(name: str) -> bool:"""Does opening this entry require pre-seeding folder trust?"""- agent = _AGENTS.get(name)+ agent = get_agent(name)return bool(agent and agent.needs_trust)-# Kept as a module constant for the many call sites that read it directly. It is-# a snapshot of the CODING agents at import time, which is what every existing-# reader means by "the agents" — a plain terminal is not one, and a dynamically-# registered CLI is reachable through ``coding_agent_names()``.-AGENT_NAMES: tuple[str, ...] = coding_agent_names()+# Kept for the call sites that import this name directly. It is a snapshot of+# the SHIPPED coding agents at import time and cannot see an entry registered+# afterwards — neither one a plugin added nor one the user typed into the+# wizard. Anything deciding whether a name is runnable must call+# ``coding_agent_names()``, which asks the live registry; a membership test+# against this tuple rejects the user's own CLI with "unknown agent".+AGENT_NAMES: tuple[str, ...] = tuple(+ name for name, agent in _AGENTS.items() if agent.is_coding_agent+)def install_command(name: str) -> str | None:@@ -756,7 +926,7 @@ def install_command(name: str) -> str | None:method for THIS platform is shown as not installed without being offered acommand that cannot work."""- agent = _AGENTS.get(name)+ agent = get_agent(name)if agent is None or agent.spec is None:return Nonemethods = agent.spec.install@@ -776,7 +946,7 @@ def install_command(name: str) -> str | None:def coding_agents() -> list[WorkspaceAgent]:"""Every registered entry that runs a coding agent, in registration order."""- return [a for a in _AGENTS.values() if a.is_coding_agent]+ return [a for a in _registry().values() if a.is_coding_agent]def generation_of(name: str) -> str | None:@@ -785,7 +955,7 @@ def generation_of(name: str) -> str | None:``None`` for every entry whose vendor ships exactly one thing under onebinary name — which is all of them but Kimi."""- agent = _AGENTS.get(name)+ agent = get_agent(name)if agent is None or agent.generation_probe is None:return Nonetry:@@ -803,7 +973,7 @@ def spoken_aliases() -> dict[str, str]:only the caller knows whether the product's second word followed."""out: dict[str, str] = {}- for agent in _AGENTS.values():+ for agent in _registry().values():for spelling in (*agent.spoken_aliases, *agent.spoken_aliases_needing_suffix):out.setdefault(spelling, agent.name)return out@@ -819,7 +989,7 @@ def aliases_needing_suffix() -> dict[str, tuple[str, str]]:"""return {spelling: (agent.name, agent.alias_suffix)- for agent in _AGENTS.values()+ for agent in _registry().values()for spelling in agent.spoken_aliases_needing_suffix}@@ -840,7 +1010,7 @@ def reserved_call_signs() -> frozenset[str]:name, and the spellings people actually say."""names: set[str] = set()- for agent in _AGENTS.values():+ for agent in _registry().values():if not agent.is_coding_agent:continuenames.add(agent.name.lower())@@ -865,6 +1035,11 @@ class AgentInfo:launch_command: strkind: str = "cli"description: str = ""+ #: True for an entry the user added, so a surface can offer to edit it.+ custom: bool = False+ #: Where to fetch this entry's mark; empty means the UI's own asset or the+ #: monogram it falls back to.+ logo_url: str = ""#: How long a completed detection sweep answers for.@@ -953,13 +1128,72 @@ async def detect_agents(return list(infos)+def _on_path(binary: str) -> bool:+ """Is ``binary`` resolvable the way a pane would resolve it?++ The whole detection story for a user-added entry. No subprocess: see+ :func:`_custom_agent` for why a stranger's ``--version`` is not something+ this sweep may run. ``ensure_cli_paths`` first, because a GUI-launched+ process starts with a minimal PATH and would otherwise report a correctly+ installed CLI as missing on macOS and Linux.+ """+ import shutil++ if not binary:+ return False+ try:+ from jarvis.core.path_augment import ensure_cli_paths++ ensure_cli_paths()+ except Exception: # noqa: BLE001, S110 - PATH augmentation is best-effort+ pass+ return shutil.which(binary) is not None++async def _sweep_agents(prober: CliStatusProber) -> list[AgentInfo]:- """One real detection pass — a subprocess per registered CLI."""- specs = [a.spec for a in _AGENTS.values() if a.spec is not None]+ """One real detection pass — a subprocess per SHIPPED CLI.++ Three kinds of answer, and what an entry gets is decided by what it+ declares rather than by its name:++ * a detection spec — the shared prober runs it and reports a version;+ * a user-added CLI (no spec, still a coding agent) — its first word is+ looked up on PATH, off the event loop because that touches the disk;+ * the plain terminal — "does this host have a shell", which is not a+ question a ``--version`` probe can ask.+ """+ registry = _registry()+ specs = [a.spec for a in registry.values() if a.spec is not None]statuses = await prober.probe_all(specs) if specs else {}shell = default_shell()+ unspecced = [a for a in registry.values() if a.spec is None and a.is_coding_agent]+ found: dict[str, bool] = {}+ if unspecced:+ found = await asyncio.to_thread(+ lambda: {a.name: _on_path(a.executable) for a in unspecced}+ )+out: list[AgentInfo] = []- for agent in _AGENTS.values():+ for agent in registry.values():+ if agent.spec is None and agent.is_coding_agent:+ out.append(+ AgentInfo(+ name=agent.name,+ display_name=agent.display_name,+ installed=found.get(agent.name, False),+ # Deliberately none. Asking would be the subprocess this+ # path exists to avoid, and a made-up number beside+ # someone's own command is worse than a blank one.+ version=None,+ install_command=None,+ launch_command=agent.launch_command or "",+ kind=agent.kind,+ description=agent.description,+ custom=agent.custom,+ logo_url=agent.logo_url,+ )+ )+ continueif agent.spec is None:out.append(AgentInfo(@@ -1005,6 +1239,33 @@ def _build_pty_argv(command: str) -> tuple[str, ...] | None:return (path, "-c", f"{command}; exec {path}")+def shell_run_argv(command: str) -> tuple[str, ...] | None:+ """Shell argv that runs ``command`` and EXITS with it.++ The counterpart to :func:`_build_pty_argv`, which keeps the shell open+ afterwards. Both exist because the two callers want opposite things: the+ workspace launcher opens a terminal the user goes on typing in, while an+ Agentic-IDE pane IS its agent — when the agent exits the pane is finished,+ and a shell surviving it would leave a prompt that looks like a running+ agent to every readiness check in the app.++ Used for a user-added CLI whose command is shell source rather than an argv+ (a pipeline, ``VAR=x cmd``, two commands chained), which cannot be exec'd+ directly. ``None`` on a host with no shell, which reads the same as a+ missing binary.+ """+ shell = default_shell()+ if shell is None:+ return None+ path = shell.argv[0]+ if shell.id in ("pwsh", "powershell"):+ return (path, "-NoLogo", "-NoProfile", "-Command", command)+ if shell.id == "cmd":+ # /c, never /k — see the docstring: the shell has to die with the agent.+ return (path, "/c", command)+ return (path, "-c", command)++def plain_terminal_argv() -> tuple[str, ...] | None:"""Full PTY argv for a plain shell session — no agent wrapped around it.@@ -1023,7 +1284,7 @@ def build_agent_argv(name: str) -> tuple[str, ...] | None:A CLI is launched inside a shell (trust pre-seeded); the plain terminal ISthe shell."""- agent = _AGENTS.get(name)+ agent = get_agent(name)if agent is None:return Noneif agent.launch_command is None:@@ -1069,6 +1330,7 @@ __all__ = ["aliases_needing_suffix","build_agent_argv","build_install_argv",+ "builtin_names","coding_agent_names","coding_agents","detect_agents",@@ -1083,7 +1345,9 @@ __all__ = ["needs_trust","plain_terminal_argv","pty_available",+ "refresh_custom_agents","register_agent","reserved_call_signs",+ "shell_run_argv","spoken_aliases",]diff --git a/jarvis/workspace/custom_clis.py b/jarvis/workspace/custom_clis.pynew file mode 100644index 0000000000..bb337b5f41--- /dev/null+++ b/jarvis/workspace/custom_clis.py@@ -0,0 +1,574 @@+"""Terminal CLIs the USER adds — the same registry, filled from a file.++:mod:`jarvis.workspace.agents` is deliberately an open registry: a new+interactive CLI is a spec rather than a code change spread across detection,+launching and the UI. Until now the only way to put something in it was to ship+Python, so an install could run exactly the CLIs this project happened to know+about. That is the wrong boundary for a tool whose whole job is to open other+people's terminals: a coding CLI is released roughly monthly, and waiting for+a release of THIS app to be able to open one is not a workflow.++So an entry here is the same :class:`~jarvis.workspace.agents.WorkspaceAgent`+the built-ins are, built from four things the user actually knows — a name, the+command that starts it, a line of description, and (optionally) a logo. Once+stored it is offered by every surface that reads the registry: the setup+wizard's terminal allocation, the "open a terminal — what?" picker, the pane+split menu, the CLI and the voice catalog.++**Not the shared CLI catalog.** ``jarvis/clis/catalog`` also has a custom.json,+and it is a different thing on purpose: entries there become brain-callable+tools. An entry here is only ever something a terminal RUNS, chosen by a person+looking at a picker. Keeping the two stores apart is what stops a command typed+into a terminal picker from quietly becoming a tool an LLM may call (AP-5/14).++**What a custom entry deliberately does NOT get**, because guessing would be+worse than the honest gap:++* *A version number.* Detection for built-ins runs ``<binary> --version`` — one+ subprocess per entry on the shared event loop, which is where the wake+ microphone is delivered. A stranger's command has no promise to answer that+ flag; plenty of TUIs would simply OPEN, and the pane's boot would then hold+ the loop the wake word arrives on. A custom entry is therefore detected by+ looking its first word up on PATH, and reports no version at all.+* *An install command.* We do not know how it is installed, and offering a+ command that cannot work is worse than saying nothing.+* *Trust pre-seeding, several subscriptions, conversation resume.* Each of+ those is a file format belonging to one specific vendor. Every layer already+ degrades honestly when an entry declares none of them.++Cross-platform: the command is stored verbatim and started through this host's+own shell (``jarvis.terminal.shells``), so a Windows entry may be a ``.cmd`` and+a Linux one a shell function without either needing to know about the other.+"""+from __future__ import annotations++import json+import logging+import os+import re+import shlex+import unicodedata+from collections.abc import Iterable, Mapping+from dataclasses import dataclass, replace+from pathlib import Path+from typing import Any, Literal++from jarvis.core.paths import workspace_clis_dir, workspace_clis_path++log = logging.getLogger(__name__)++#: Bumped whenever the stored set changes, so the agent registry can notice+#: without re-reading the file on every lookup.+_revision = 0++#: Longest a name may be. Long enough for "Antigravity Coding Plan", short+#: enough that the picker row it lands in stays one line.+MAX_NAME_LEN = 60+#: A command line, not a script. Anything longer is a shell script that wants to+#: live in a file and be called by name.+MAX_COMMAND_LEN = 500+MAX_DESCRIPTION_LEN = 200++#: Upload ceiling for a logo. A brand mark is a few KB of SVG or a small PNG;+#: a megabyte is already a photograph that will be drawn at 20 pixels.+MAX_LOGO_BYTES = 1024 * 1024++#: Image kinds a logo may be, mapped to what the browser is told they are.+LOGO_TYPES: dict[str, str] = {+ ".svg": "image/svg+xml",+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".webp": "image/webp",+ ".gif": "image/gif",+}++#: First bytes that prove a file is what its extension claims. Checked because+#: the store hands these bytes back out over HTTP: an "svg" that is really a+#: zip is not a logo, and the honest moment to say so is the upload.+_MAGIC: dict[str, tuple[bytes, ...]] = {+ ".png": (b"\x89PNG\r\n\x1a\n",),+ ".jpg": (b"\xff\xd8\xff",),+ ".jpeg": (b"\xff\xd8\xff",),+ ".gif": (b"GIF87a", b"GIF89a"),+ ".webp": (b"RIFF",),+}++#: Shell characters that mean the command cannot be exec'd as a single process.+#: Their presence is not an error — it decides HOW the entry is started, see+#: :func:`needs_shell`.+_SHELL_META = set("|&;<>()$`\n\r")++_SLUG_RE = re.compile(r"[^a-z0-9]+")++#: ``NAME=value`` — an environment assignment in front of the actual command.+_ASSIGNMENT_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")+++def _is_assignment(token: str) -> bool:+ """Is this token an environment assignment rather than a program name?++ ``KIMI_NO_UPDATE=1 kimi`` is a shape people copy straight out of a README,+ and reading its first word as the binary looks for a program called+ ``KIMI_NO_UPDATE=1``, never finds it, and reports a working command as+ "not installed".+ """+ return bool(_ASSIGNMENT_RE.match(token))+++@dataclass(frozen=True, slots=True)+class CustomCli:+ """One CLI the user added, exactly as it is stored.++ ``id`` is assigned once, at creation, and never changes again — renaming the+ entry must not orphan the open panes, saved workspaces and resume offers+ that recorded which agent they were running.+ """++ id: str+ display_name: str+ command: str+ description: str = ""+ #: Logo file name inside :func:`logo_dir`, or empty for none.+ logo: str = ""+ #: How a dropped file is written into this CLI's prompt. Same meaning as+ #: :attr:`~jarvis.workspace.agents.WorkspaceAgent.file_reference`; ``@path``+ #: is what most modern coding CLIs read, but a wrong guess silently pastes+ #: a path a CLI treats as prose, so it stays the user's choice.+ file_reference: Literal["at", "quoted"] = "quoted"++ def to_dict(self) -> dict[str, Any]:+ return {+ "id": self.id,+ "display_name": self.display_name,+ "command": self.command,+ "description": self.description,+ "logo": self.logo,+ "file_reference": self.file_reference,+ }++ @property+ def binary(self) -> str:+ """The word that has to be on PATH for this command to start.++ Usually the first one — but not when the line opens with environment+ assignments (``KIMI_NO_UPDATE=1 kimi``), which is a shape people copy+ straight out of a README. Taking the first word literally there looks+ for a binary called ``KIMI_NO_UPDATE=1``, never finds it, and reports a+ perfectly good command as "not installed". Empty when nothing in the+ line looks like a command name, which the caller reads as "this cannot+ be checked ahead of time".+ """+ for part in split_command(self.command):+ if _is_assignment(part):+ continue+ return part+ return ""+++class CustomCliError(ValueError):+ """A stored entry was asked for something it cannot be given.++ Carries a message meant to be READ by the person who typed the form, so+ every raise site says what to change rather than what went wrong.+ """+++# --------------------------------------------------------------------------+# Command handling+# --------------------------------------------------------------------------+++def split_command(command: str) -> tuple[str, ...]:+ """Split a command line into words, the same way on every OS.++ Not :func:`shlex.split`. Its POSIX mode treats a backslash as an escape+ character, which turns ``C:\\tools\\agy.exe`` into ``C:toolsagy.exe`` — a+ binary that does not exist, reported as "not installed" on the one platform+ where that path shape is normal. Its non-POSIX mode keeps the quotes glued+ to the token instead, which fails the same lookup for a different reason.++ So: quotes group, whitespace separates, and a backslash is just a character.+ """+ lexer = shlex.shlex(command, posix=True)+ lexer.whitespace_split = True+ lexer.escape = ""+ lexer.commenters = ""+ try:+ return tuple(part for part in lexer if part)+ except ValueError:+ # An unbalanced quote. The command is still storable and still runnable+ # through a shell, which is where the user will see the real complaint.+ return tuple(part for part in command.split() if part)+++def needs_shell(command: str) -> bool:+ """Does this command need a shell around it, or can it be exec'd directly?++ A pipeline, a variable expansion or a chain of two commands is not an argv —+ it is shell source. Launching it as a process would look for a binary whose+ name contains a pipe character. An environment assignment in front counts+ too: only a shell knows that ``FOO=1 tool`` means "set FOO, then run tool"+ rather than "run a program called FOO=1".++ Answered on the text rather than stored, because it is a property of the+ command and would only be one more field to keep in step with it.+ """+ if any(char in _SHELL_META for char in command):+ return True+ words = split_command(command)+ return bool(words) and _is_assignment(words[0])+++# --------------------------------------------------------------------------+# Store+# --------------------------------------------------------------------------+++def logo_dir() -> Path:+ return workspace_clis_dir() / "logos"+++def revision() -> int:+ """Changes since this process started — a cache key for the registry."""+ return _revision+++def _bump() -> None:+ global _revision+ _revision += 1+++def _read_raw() -> list[dict[str, Any]]:+ path = workspace_clis_path()+ if not path.is_file():+ return []+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ except Exception as exc: # noqa: BLE001 - a corrupt store must not brick boot+ log.warning("workspace-clis: %s is unreadable (%s); ignoring it", path, exc)+ return []+ entries = data if isinstance(data, list) else data.get("entries", [])+ return [e for e in entries if isinstance(e, dict)]+++def _parse(raw: Mapping[str, Any]) -> CustomCli | None:+ """One stored record, or ``None`` when it is not usable.++ Skipping beats raising: one hand-edited entry must not take the other five+ down with it, and the user's route to fixing it is the same UI that lists+ the ones that survived.+ """+ entry_id = str(raw.get("id") or "").strip()+ name = str(raw.get("display_name") or "").strip()+ command = str(raw.get("command") or "").strip()+ if not entry_id or not name or not command:+ log.warning("workspace-clis: skipping incomplete entry %r", raw)+ return None+ reference = str(raw.get("file_reference") or "quoted")+ return CustomCli(+ id=entry_id,+ display_name=name[:MAX_NAME_LEN],+ command=command[:MAX_COMMAND_LEN],+ description=str(raw.get("description") or "")[:MAX_DESCRIPTION_LEN],+ logo=str(raw.get("logo") or "").strip(),+ file_reference="at" if reference == "at" else "quoted",+ )+++def list_custom_clis() -> list[CustomCli]:+ """Every stored entry, in the order the user put them in."""+ out: list[CustomCli] = []+ seen: set[str] = set()+ for raw in _read_raw():+ entry = _parse(raw)+ if entry is None or entry.id in seen:+ continue+ seen.add(entry.id)+ out.append(entry)+ return out+++def get_custom_cli(entry_id: str) -> CustomCli | None:+ return next((e for e in list_custom_clis() if e.id == entry_id), None)+++def _write(entries: Iterable[CustomCli]) -> None:+ """Persist the whole list, atomically.++ Written to a sibling and moved into place: a half-written store is a store+ that reads as empty on the next boot, and the user's own CLIs quietly+ disappearing is the one failure this file must not have.+ """+ path = workspace_clis_path()+ path.parent.mkdir(parents=True, exist_ok=True)+ payload = {+ "schema_version": "1",+ "entries": [entry.to_dict() for entry in entries],+ }+ tmp = path.with_name(path.name + ".tmp")+ tmp.write_text(+ json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"+ )+ os.replace(tmp, path)+ _bump()+++# --------------------------------------------------------------------------+# Validation+# --------------------------------------------------------------------------+++def _clean_name(value: str) -> str:+ name = " ".join(str(value or "").split())+ if not name:+ raise CustomCliError("Give the CLI a name.")+ if len(name) > MAX_NAME_LEN:+ raise CustomCliError(f"Keep the name under {MAX_NAME_LEN} characters.")+ return name+++def _clean_command(value: str) -> str:+ command = str(value or "").strip()+ if not command:+ raise CustomCliError("Give the command that starts this CLI.")+ if "\n" in command or "\r" in command:+ raise CustomCliError("The command has to be a single line.")+ if len(command) > MAX_COMMAND_LEN:+ raise CustomCliError(f"Keep the command under {MAX_COMMAND_LEN} characters.")+ return command+++def _clean_description(value: str) -> str:+ text = " ".join(str(value or "").split())+ return text[:MAX_DESCRIPTION_LEN]+++def _slug(name: str) -> str:+ """A stable, filesystem- and URL-safe id derived from the name.++ Accents are folded rather than dropped, so "Café CLI" becomes ``cafe-cli``+ rather than ``cli`` — an id built only from the ASCII that survived is one+ the user cannot recognise as theirs.+ """+ folded = unicodedata.normalize("NFKD", name)+ ascii_only = folded.encode("ascii", "ignore").decode("ascii").lower()+ slug = _SLUG_RE.sub("-", ascii_only).strip("-")+ return slug or "cli"+++def _taken_ids() -> set[str]:+ """Every name a new entry may not claim — built-in registry keys included.++ A second thing answering to "codex" is the kind of collision that surfaces+ as a pane running the wrong tool, so the check covers the built-ins even+ though they live in a different module.+ """+ from jarvis.workspace import agents as workspace_agents++ taken = {entry.id for entry in list_custom_clis()}+ taken |= set(workspace_agents.builtin_names())+ return taken+++def _free_id(name: str) -> str:+ base = _slug(name)+ taken = _taken_ids()+ if base not in taken:+ return base+ for suffix in range(2, 100):+ candidate = f"{base}-{suffix}"+ if candidate not in taken:+ return candidate+ raise CustomCliError("Too many CLIs with that name — pick a different one.")+++# --------------------------------------------------------------------------+# Mutations+# --------------------------------------------------------------------------+++def create_custom_cli(+ display_name: str,+ command: str,+ *,+ description: str = "",+ file_reference: str = "quoted",+) -> CustomCli:+ """Store a new entry and return it, id assigned."""+ name = _clean_name(display_name)+ entry = CustomCli(+ id=_free_id(name),+ display_name=name,+ command=_clean_command(command),+ description=_clean_description(description),+ file_reference="at" if file_reference == "at" else "quoted",+ )+ _write([*list_custom_clis(), entry])+ return entry+++def update_custom_cli(+ entry_id: str,+ *,+ display_name: str | None = None,+ command: str | None = None,+ description: str | None = None,+ file_reference: str | None = None,+) -> CustomCli:+ """Change a stored entry in place. The id is never touched — see the class."""+ entries = list_custom_clis()+ index = next((i for i, e in enumerate(entries) if e.id == entry_id), -1)+ if index < 0:+ raise CustomCliError("That CLI is not in the list any more.")+ entry = entries[index]+ if display_name is not None:+ entry = replace(entry, display_name=_clean_name(display_name))+ if command is not None:+ entry = replace(entry, command=_clean_command(command))+ if description is not None:+ entry = replace(entry, description=_clean_description(description))+ if file_reference is not None:+ entry = replace(+ entry, file_reference="at" if file_reference == "at" else "quoted"+ )+ entries[index] = entry+ _write(entries)+ return entry+++def delete_custom_cli(entry_id: str) -> CustomCli:+ """Forget an entry and its logo. Open panes running it are left alone.++ A pane is a live process with a conversation in it; killing it because its+ menu entry was deleted would throw away work the user never asked to lose.+ It keeps running under its own name and simply cannot be started again.+ """+ entries = list_custom_clis()+ entry = next((e for e in entries if e.id == entry_id), None)+ if entry is None:+ raise CustomCliError("That CLI is not in the list any more.")+ _write([e for e in entries if e.id != entry_id])+ _remove_logo_files(entry_id)+ return entry+++# --------------------------------------------------------------------------+# Logos+# --------------------------------------------------------------------------+++def _remove_logo_files(entry_id: str) -> None:+ for suffix in LOGO_TYPES:+ candidate = logo_dir() / f"{entry_id}{suffix}"+ try:+ candidate.unlink(missing_ok=True)+ except OSError as exc: # noqa: PERF203 - one failure must not stop the rest+ log.warning("workspace-clis: could not remove %s: %s", candidate, exc)+++def _looks_like(suffix: str, data: bytes) -> bool:+ """Do these bytes match what the extension claims?++ The store hands this file back out over HTTP, so "the user said it was a+ PNG" is not enough to serve it as one. SVG is text and has no magic number,+ so it is checked for the one tag that has to be in it.+ """+ if suffix == ".svg":+ head = data[:4096].lstrip()+ try:+ text = head.decode("utf-8", errors="ignore").lower()+ except Exception: # noqa: BLE001 - undecodable is simply not an SVG+ return False+ return "<svg" in text+ return any(data.startswith(magic) for magic in _MAGIC.get(suffix, ()))+++def set_logo(entry_id: str, data: bytes, filename: str) -> CustomCli:+ """Store an image as this entry's mark and return the updated entry."""+ entries = list_custom_clis()+ index = next((i for i, e in enumerate(entries) if e.id == entry_id), -1)+ if index < 0:+ raise CustomCliError("That CLI is not in the list any more.")+ suffix = Path(filename or "").suffix.lower()+ if suffix not in LOGO_TYPES:+ readable = ", ".join(sorted(s.lstrip(".").upper() for s in LOGO_TYPES))+ raise CustomCliError(f"A logo has to be one of: {readable}.")+ if not data:+ raise CustomCliError("That file is empty.")+ if len(data) > MAX_LOGO_BYTES:+ raise CustomCliError(+ f"Keep the logo under {MAX_LOGO_BYTES // 1024} KB."+ )+ if not _looks_like(suffix, data):+ raise CustomCliError(f"That file is not really a {suffix.lstrip('.').upper()}.")++ # One logo per entry: the old file goes first, so a switch from PNG to SVG+ # does not leave a stale sibling that a later lookup could pick up.+ _remove_logo_files(entry_id)+ target = logo_dir() / f"{entry_id}{suffix}"+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_bytes(data)++ entries[index] = replace(entries[index], logo=target.name)+ _write(entries)+ return entries[index]+++def clear_logo(entry_id: str) -> CustomCli:+ """Drop the logo and fall back to the monogram the UI draws without one."""+ entries = list_custom_clis()+ index = next((i for i, e in enumerate(entries) if e.id == entry_id), -1)+ if index < 0:+ raise CustomCliError("That CLI is not in the list any more.")+ _remove_logo_files(entry_id)+ entries[index] = replace(entries[index], logo="")+ _write(entries)+ return entries[index]+++def logo_file(entry_id: str) -> tuple[Path, str] | None:+ """``(path, media type)`` of this entry's logo, or ``None`` if it has none.++ The file name is rebuilt from the id rather than trusted from the store, so+ a hand-edited ``"logo": "../../.env"`` reads as "no logo" instead of as a+ path traversal out of the logo directory.+ """+ entry = get_custom_cli(entry_id)+ if entry is None or not entry.logo:+ return None+ suffix = Path(entry.logo).suffix.lower()+ media = LOGO_TYPES.get(suffix)+ if media is None:+ return None+ path = logo_dir() / f"{entry_id}{suffix}"+ return (path, media) if path.is_file() else None+++def logo_url(entry: CustomCli) -> str:+ """Where the UI fetches this entry's mark, or empty when it has none."""+ return f"/api/workspace-clis/{entry.id}/logo" if entry.logo else ""+++__all__ = [+ "LOGO_TYPES",+ "MAX_COMMAND_LEN",+ "MAX_DESCRIPTION_LEN",+ "MAX_LOGO_BYTES",+ "MAX_NAME_LEN",+ "CustomCli",+ "CustomCliError",+ "clear_logo",+ "create_custom_cli",+ "delete_custom_cli",+ "get_custom_cli",+ "list_custom_clis",+ "logo_dir",+ "logo_file",+ "logo_url",+ "needs_shell",+ "revision",+ "set_logo",+ "split_command",+ "update_custom_cli",+]diff --git a/jarvis/workspace/launcher.py b/jarvis/workspace/launcher.pyindex 5f2181c9f4..fa2589951a 100644--- a/jarvis/workspace/launcher.py+++ b/jarvis/workspace/launcher.py@@ -17,7 +17,7 @@ from pathlib import Pathfrom jarvis.core.paths import repo_root-from .agents import AGENT_NAMES, get_agent, pty_available+from .agents import coding_agent_names, get_agent, pty_availablefrom .trust import TrustResult, ensure_trustedlog = logging.getLogger(__name__)@@ -57,7 +57,10 @@ def validate_split(layout: int, split: dict[str, int]) -> None:"""Raise ``ValueError`` if the request is malformed."""if layout not in LAYOUT_CHOICES:raise ValueError(f"layout must be one of {LAYOUT_CHOICES}, got {layout}")- unknown = set(split) - set(AGENT_NAMES)+ # The LIVE registry, not the import-time snapshot: the user can add a CLI of+ # their own while the app runs, and a plan naming it must not be rejected as+ # an unknown agent by the very layer that just offered it.+ unknown = set(split) - set(coding_agent_names())if unknown:raise ValueError(f"unknown agents: {sorted(unknown)}")if any(count < 0 for count in split.values()):@@ -73,7 +76,7 @@ def build_slots(split: dict[str, int]) -> list[Slot]:"""Expand the per-agent counts into one slot each (grouped, stable order)."""slots: list[Slot] = []idx = 0- for name in AGENT_NAMES:+ for name in coding_agent_names():count = split.get(name, 0)agent = get_agent(name)if agent is None or count <= 0:diff --git a/tests/integration/test_workspace_clis_routes.py b/tests/integration/test_workspace_clis_routes.pynew file mode 100644index 0000000000..adcf939166--- /dev/null+++ b/tests/integration/test_workspace_clis_routes.py@@ -0,0 +1,183 @@+"""REST routes for the terminal CLIs the user added themselves.++Every test gets its own scratch store, so nothing here can see or damage the+maintainer's own entries.+"""+from __future__ import annotations++from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.workspace import agents as registry+from jarvis.workspace import custom_clis++SVG = b'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"></svg>'+++def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):+ root = tmp_path / "workspace-clis"+ monkeypatch.setattr(custom_clis, "workspace_clis_dir", lambda: root)+ monkeypatch.setattr(+ custom_clis, "workspace_clis_path", lambda: root / "custom.json"+ )+ registry.refresh_custom_agents()++ from jarvis.ui.web import workspace_clis_routes++ app = FastAPI()+ app.include_router(workspace_clis_routes.router)+ yield TestClient(app)++ monkeypatch.undo()+ registry.refresh_custom_agents()+++def _create(client: TestClient, **overrides) -> dict:+ payload = {"display_name": "Antigravity", "command": "agy", **overrides}+ response = client.post("/api/workspace-clis", json=payload)+ assert response.status_code == 200, response.text+ return response.json()+++def test_the_empty_list_still_carries_the_form_limits(client: TestClient) -> None:+ """The form has to know what it may accept before anything exists."""+ body = client.get("/api/workspace-clis").json()+ assert body["clis"] == []+ assert body["max_name_length"] > 0+ assert body["max_command_length"] > 0+ assert ".svg" in body["logo_extensions"]+++def test_a_created_cli_is_immediately_openable(client: TestClient) -> None:+ """Stored, registered and offered — without a restart, which is the point."""+ entry = _create(client, description="Google's terminal coding CLI.")+ assert entry["id"] == "antigravity"+ assert entry["binary"] == "agy"+ assert entry["runs_through_shell"] is False+ assert entry["logo_url"] == ""++ assert "antigravity" in registry.coding_agent_names()+ agent = registry.get_agent("antigravity")+ assert agent is not None and agent.custom is True+++def test_a_shell_command_says_so_in_the_payload(client: TestClient) -> None:+ """It changes what "the pane exited" means, so the UI has to be able to say."""+ entry = _create(client, display_name="Piped", command="agy | tee log.txt")+ assert entry["runs_through_shell"] is True+++def test_a_blank_command_is_refused_with_a_readable_reason(+ client: TestClient,+) -> None:+ response = client.post(+ "/api/workspace-clis", json={"display_name": "Nothing", "command": " "}+ )+ assert response.status_code == 422+ # The message is meant to be read by the person looking at the form.+ assert "command" in response.json()["detail"].lower()+++def test_a_patch_leaves_untouched_fields_alone(client: TestClient) -> None:+ entry = _create(client, description="Original description.")+ updated = client.patch(+ f"/api/workspace-clis/{entry['id']}", json={"display_name": "Antigravity CLI"}+ ).json()+ assert updated["id"] == entry["id"]+ assert updated["display_name"] == "Antigravity CLI"+ assert updated["description"] == "Original description."+ assert updated["command"] == "agy"+++def test_patching_something_that_is_gone_says_so(client: TestClient) -> None:+ response = client.patch(+ "/api/workspace-clis/never-existed", json={"display_name": "X"}+ )+ assert response.status_code == 422+++def test_delete_removes_it_from_the_registry(client: TestClient) -> None:+ entry = _create(client)+ assert client.delete(f"/api/workspace-clis/{entry['id']}").json()["ok"] is True+ assert "antigravity" not in registry.coding_agent_names()+++def test_a_logo_round_trips_with_the_headers_that_make_it_safe(+ client: TestClient,+) -> None:+ entry = _create(client)+ uploaded = client.put(+ f"/api/workspace-clis/{entry['id']}/logo",+ files={"file": ("mark.svg", SVG, "image/svg+xml")},+ ).json()+ assert uploaded["logo_url"] == f"/api/workspace-clis/{entry['id']}/logo"++ served = client.get(uploaded["logo_url"])+ assert served.status_code == 200+ assert served.headers["content-type"].startswith("image/svg+xml")+ # SVG is a document format: the same URL opened in a tab could run script.+ assert "sandbox" in served.headers["content-security-policy"]+ assert served.headers["x-content-type-options"] == "nosniff"+ assert served.content == SVG+++def test_the_registry_learns_about_a_new_logo(client: TestClient) -> None:+ """A stored logo the registry has not re-read is one no picker can draw."""+ entry = _create(client)+ client.put(+ f"/api/workspace-clis/{entry['id']}/logo",+ files={"file": ("mark.svg", SVG, "image/svg+xml")},+ )+ agent = registry.get_agent(entry["id"])+ assert agent is not None+ assert agent.logo_url == f"/api/workspace-clis/{entry['id']}/logo"+++def test_a_file_pretending_to_be_an_image_is_refused(client: TestClient) -> None:+ entry = _create(client)+ response = client.put(+ f"/api/workspace-clis/{entry['id']}/logo",+ files={"file": ("mark.svg", b"PK\x03\x04 a zip file", "image/svg+xml")},+ )+ assert response.status_code == 422+++def test_asking_for_a_logo_that_is_not_there(client: TestClient) -> None:+ entry = _create(client)+ assert client.get(f"/api/workspace-clis/{entry['id']}/logo").status_code == 404+++def test_removing_a_logo_leaves_the_entry(client: TestClient) -> None:+ entry = _create(client)+ client.put(+ f"/api/workspace-clis/{entry['id']}/logo",+ files={"file": ("mark.svg", SVG, "image/svg+xml")},+ )+ cleared = client.delete(f"/api/workspace-clis/{entry['id']}/logo").json()+ assert cleared["logo_url"] == ""+ assert client.get("/api/workspace-clis").json()["clis"][0]["id"] == entry["id"]+++def test_the_write_routes_are_marked_dangerous() -> None:+ """A stored entry is a command line this app will start in a terminal.++ That is what the user is asking for when they type it into the form — and+ what must not happen because a model decided it would be helpful.+ """+ from jarvis.ui.web import workspace_clis_routes++ app = FastAPI()+ app.include_router(workspace_clis_routes.router)+ paths = app.openapi()["paths"]++ assert paths["/api/workspace-clis"]["post"].get("x-jarvis-dangerous") is True+ for method in ("patch", "delete"):+ entry = paths["/api/workspace-clis/{cli_id}"][method]+ assert entry.get("x-jarvis-dangerous") is True+ # Reading the list, and fetching a logo, are not.+ assert "x-jarvis-dangerous" not in paths["/api/workspace-clis"]["get"]+ assert "x-jarvis-dangerous" not in paths["/api/workspace-clis/{cli_id}/logo"]["get"]diff --git a/tests/unit/workspace/test_custom_clis.py b/tests/unit/workspace/test_custom_clis.pynew file mode 100644index 0000000000..3457b2909b--- /dev/null+++ b/tests/unit/workspace/test_custom_clis.py@@ -0,0 +1,401 @@+"""Terminal CLIs the user adds: storing them, and what the registry makes of them.++Every test runs against a temporary app-data directory, so nothing here can see+or damage the maintainer's own stored CLIs.+"""+from __future__ import annotations++import json+from pathlib import Path++import pytest++from jarvis.workspace import agents as registry+from jarvis.workspace import custom_clis++[email protected](autouse=True)+def isolated_store(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):+ """Point the store at a scratch directory and forget it again afterwards.++ The registry caches the store by revision number, so the cache has to be+ dropped on both sides of the test: on the way in, because a previous test's+ entries would still be registered, and on the way out, because these ones+ must not leak into the next.+ """+ root = tmp_path / "workspace-clis"+ monkeypatch.setattr(custom_clis, "workspace_clis_dir", lambda: root)+ monkeypatch.setattr(custom_clis, "workspace_clis_path", lambda: root / "custom.json")+ registry.refresh_custom_agents()+ yield root+ monkeypatch.undo()+ registry.refresh_custom_agents()+++# --------------------------------------------------------------------------+# Storing+# --------------------------------------------------------------------------+++def test_a_stored_cli_is_offered_like_a_built_in() -> None:+ """The whole point: one form, and every surface offers it."""+ entry = custom_clis.create_custom_cli(+ "Antigravity", "agy", description="Google's terminal coding CLI."+ )+ registry.refresh_custom_agents()++ assert entry.id == "antigravity"+ assert entry.id in registry.coding_agent_names()+ assert entry.id in registry.agent_names()++ agent = registry.get_agent(entry.id)+ assert agent is not None+ assert agent.display_name == "Antigravity"+ assert agent.is_coding_agent+ assert agent.custom is True+ assert agent.executable == "agy"+ # No trust file of ours to seed and no install command we could honestly+ # offer — both must degrade to "nothing", never to a guess.+ assert agent.needs_trust is False+ assert registry.install_command(entry.id) is None+++def test_the_plain_terminal_stays_last_in_the_menu() -> None:+ """A "no agent at all" choice buried among CLIs reads as one of them."""+ custom_clis.create_custom_cli("Antigravity", "agy")+ registry.refresh_custom_agents()+ assert registry.agent_names()[-1] == registry.PLAIN_TERMINAL+++def test_a_rename_keeps_the_id() -> None:+ """Panes, saved workspaces and resume offers all recorded the old id."""+ entry = custom_clis.create_custom_cli("Antigravity", "agy")+ renamed = custom_clis.update_custom_cli(entry.id, display_name="Antigravity CLI")+ assert renamed.id == entry.id+ assert renamed.display_name == "Antigravity CLI"+++def test_a_name_that_is_taken_gets_its_own_id() -> None:+ """Two entries answering to one name is a pane running the wrong tool."""+ first = custom_clis.create_custom_cli("Antigravity", "agy")+ second = custom_clis.create_custom_cli("Antigravity", "agy2")+ assert first.id != second.id+ assert second.id.startswith("antigravity")+++def test_a_built_in_name_cannot_be_claimed() -> None:+ entry = custom_clis.create_custom_cli("Codex", "not-really-codex")+ assert entry.id != "codex"+ assert registry.get_agent("codex") is not None+ assert registry.get_agent("codex").display_name == "Codex"+++def test_accents_survive_into_the_id() -> None:+ """An id built only from the ASCII that survived is unrecognisable."""+ entry = custom_clis.create_custom_cli("Café CLI", "cafe")+ assert entry.id == "cafe-cli"+++ ("name", "command"),+ [("", "agy"), (" ", "agy"), ("Antigravity", ""), ("Antigravity", " ")],+)+def test_a_blank_name_or_command_is_refused(name: str, command: str) -> None:+ with pytest.raises(custom_clis.CustomCliError):+ custom_clis.create_custom_cli(name, command)+++def test_a_multi_line_command_is_refused() -> None:+ """A command line, not a script — see MAX_COMMAND_LEN's neighbours."""+ with pytest.raises(custom_clis.CustomCliError):+ custom_clis.create_custom_cli("Two Things", "agy\nrm -rf /")+++def test_deleting_removes_it_from_the_registry() -> None:+ entry = custom_clis.create_custom_cli("Antigravity", "agy")+ registry.refresh_custom_agents()+ assert entry.id in registry.coding_agent_names()++ custom_clis.delete_custom_cli(entry.id)+ registry.refresh_custom_agents()+ assert entry.id not in registry.coding_agent_names()+ assert registry.get_agent(entry.id) is None+++def test_a_corrupt_store_does_not_hide_the_built_ins(isolated_store: Path) -> None:+ """One hand-edited file must not take the shipped CLIs down with it."""+ isolated_store.mkdir(parents=True, exist_ok=True)+ (isolated_store / "custom.json").write_text("{ not json", encoding="utf-8")+ registry.refresh_custom_agents()+ assert "claude" in registry.coding_agent_names()+ assert custom_clis.list_custom_clis() == []+++def test_an_incomplete_entry_is_skipped_not_fatal(isolated_store: Path) -> None:+ isolated_store.mkdir(parents=True, exist_ok=True)+ (isolated_store / "custom.json").write_text(+ json.dumps(+ {+ "entries": [+ {"id": "broken"}, # no name, no command+ {"id": "good", "display_name": "Good", "command": "good"},+ ]+ }+ ),+ encoding="utf-8",+ )+ stored = custom_clis.list_custom_clis()+ assert [entry.id for entry in stored] == ["good"]+++def test_a_hand_written_entry_cannot_shadow_a_built_in(isolated_store: Path) -> None:+ """The store refuses to CREATE one; this is the file being edited by hand."""+ isolated_store.mkdir(parents=True, exist_ok=True)+ (isolated_store / "custom.json").write_text(+ json.dumps(+ {+ "entries": [+ {"id": "codex", "display_name": "Impostor", "command": "impostor"}+ ]+ }+ ),+ encoding="utf-8",+ )+ registry.refresh_custom_agents()+ shipped = registry.get_agent("codex")+ assert shipped is not None+ assert shipped.display_name == "Codex"+ assert shipped.custom is False+++# --------------------------------------------------------------------------+# Commands+# --------------------------------------------------------------------------+++def test_a_windows_path_survives_the_split() -> None:+ """POSIX shlex would eat the backslashes and report a working CLI missing."""+ parts = custom_clis.split_command(r'C:\tools\agy.exe --flag "two words"')+ assert parts == (r"C:\tools\agy.exe", "--flag", "two words")+++ ("command", "through_shell"),+ [+ ("agy", False),+ ("npx -y some-cli", False),+ ("agy | tee log.txt", True),+ ("agy && echo done", True),+ ("FOO=1 agy", True),+ ("agy --model $MODEL", True),+ ],+)+def test_shell_source_is_told_apart_from_an_argv(+ command: str, through_shell: bool+) -> None:+ assert custom_clis.needs_shell(command) is through_shell+++def test_an_environment_prefix_does_not_become_the_binary() -> None:+ """`FOO=1 agy` must look for `agy`, not for a program called `FOO=1`."""+ entry = custom_clis.create_custom_cli("Prefixed", "FOO=1 agy --flag")+ assert entry.binary == "agy"+++def test_a_shell_entry_carries_no_half_parsed_argv() -> None:+ custom_clis.create_custom_cli("Piped", "agy | tee log.txt")+ registry.refresh_custom_agents()+ agent = registry.get_agent("piped")+ assert agent is not None+ assert agent.shell_launch is True+ assert agent.launch_args == ()+++def test_a_plain_entry_keeps_its_arguments() -> None:+ custom_clis.create_custom_cli("Npx Tool", "npx -y some-cli")+ registry.refresh_custom_agents()+ agent = registry.get_agent("npx-tool")+ assert agent is not None+ assert agent.shell_launch is False+ assert agent.executable == "npx"+ assert agent.launch_args == ("-y", "some-cli")+++def test_a_shell_launch_argv_exits_with_the_agent() -> None:+ """A surviving prompt reads as a live agent to every readiness check."""+ argv = registry.shell_run_argv("agy | tee log.txt")+ if argv is None: # a host with no shell at all+ pytest.skip("no shell on this host")+ assert "-NoExit" not in argv+ assert "/k" not in argv+++# --------------------------------------------------------------------------+# Detection+# --------------------------------------------------------------------------+++async def test_detection_never_runs_a_strangers_binary(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The sweep shares the event loop the wake microphone is delivered on."""+ custom_clis.create_custom_cli("Antigravity", "agy")+ registry.refresh_custom_agents()++ probed: list[str] = []++ class RecordingProber:+ async def probe_all(self, specs): # noqa: ANN001, ANN202+ from jarvis.clis.spec import CliStatus++ probed.extend(spec.name for spec in specs)+ return {spec.name: CliStatus(installed=False, version=None) for spec in specs}++ monkeypatch.setattr(registry, "_on_path", lambda binary: binary == "agy")+ infos = {i.name: i for i in await registry.detect_agents(RecordingProber())}++ assert "antigravity" not in probed+ assert infos["antigravity"].installed is True+ # No version, ever: asking would be the subprocess this path avoids.+ assert infos["antigravity"].version is None+ assert infos["antigravity"].install_command is None+ assert infos["antigravity"].custom is True+++async def test_a_missing_binary_is_reported_honestly(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ custom_clis.create_custom_cli("Nowhere", "definitely-not-installed-xyz")+ registry.refresh_custom_agents()++ class QuietProber:+ async def probe_all(self, specs): # noqa: ANN001, ANN202+ from jarvis.clis.spec import CliStatus++ return {spec.name: CliStatus(installed=False, version=None) for spec in specs}++ monkeypatch.setattr(registry, "_on_path", lambda binary: False)+ infos = {i.name: i for i in await registry.detect_agents(QuietProber())}+ assert infos["nowhere"].installed is False+++# --------------------------------------------------------------------------+# Logos+# --------------------------------------------------------------------------+++SVG = b'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"></svg>'+PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 32+++def test_a_logo_is_stored_and_served() -> None:+ entry = custom_clis.create_custom_cli("Antigravity", "agy")+ updated = custom_clis.set_logo(entry.id, SVG, "mark.svg")+ assert updated.logo == "antigravity.svg"+ assert custom_clis.logo_url(updated) == "/api/workspace-clis/antigravity/logo"++ found = custom_clis.logo_file(entry.id)+ assert found is not None+ path, media = found+ assert media == "image/svg+xml"+ assert path.read_bytes() == SVG+++def test_replacing_a_logo_leaves_no_stale_sibling() -> None:+ """A later lookup keyed on the id would otherwise pick up the old file."""+ entry = custom_clis.create_custom_cli("Antigravity", "agy")+ custom_clis.set_logo(entry.id, SVG, "mark.svg")+ updated = custom_clis.set_logo(entry.id, PNG, "mark.png")+ assert updated.logo == "antigravity.png"+ assert not (custom_clis.logo_dir() / "antigravity.svg").exists()+++def test_a_file_that_is_not_what_it_claims_is_refused() -> None:+ """These bytes get handed back out over HTTP."""+ entry = custom_clis.create_custom_cli("Antigravity", "agy")+ with pytest.raises(custom_clis.CustomCliError):+ custom_clis.set_logo(entry.id, b"PK\x03\x04 a zip file", "mark.svg")+ with pytest.raises(custom_clis.CustomCliError):+ custom_clis.set_logo(entry.id, b"not a png at all", "mark.png")+++def test_an_unknown_extension_is_refused() -> None:+ entry = custom_clis.create_custom_cli("Antigravity", "agy")+ with pytest.raises(custom_clis.CustomCliError):+ custom_clis.set_logo(entry.id, b"MZ binary", "mark.exe")+++def test_an_oversized_logo_is_refused() -> None:+ entry = custom_clis.create_custom_cli("Antigravity", "agy")+ huge = SVG + b" " * custom_clis.MAX_LOGO_BYTES+ with pytest.raises(custom_clis.CustomCliError):+ custom_clis.set_logo(entry.id, huge, "mark.svg")+++def test_a_hand_edited_logo_path_cannot_escape_the_logo_directory(+ isolated_store: Path,+) -> None:+ """The file name is rebuilt from the id rather than trusted from the store."""+ isolated_store.mkdir(parents=True, exist_ok=True)+ (isolated_store / "custom.json").write_text(+ json.dumps(+ {+ "entries": [+ {+ "id": "evil",+ "display_name": "Evil",+ "command": "evil",+ "logo": "../../../../.env",+ }+ ]+ }+ ),+ encoding="utf-8",+ )+ assert custom_clis.logo_file("evil") is None+++def test_deleting_an_entry_takes_its_logo_with_it() -> None:+ entry = custom_clis.create_custom_cli("Antigravity", "agy")+ custom_clis.set_logo(entry.id, SVG, "mark.svg")+ stored = custom_clis.logo_dir() / "antigravity.svg"+ assert stored.exists()++ custom_clis.delete_custom_cli(entry.id)+ assert not stored.exists()+++def test_clearing_a_logo_falls_back_to_the_monogram() -> None:+ entry = custom_clis.create_custom_cli("Antigravity", "agy")+ custom_clis.set_logo(entry.id, SVG, "mark.svg")+ cleared = custom_clis.clear_logo(entry.id)+ assert cleared.logo == ""+ assert custom_clis.logo_url(cleared) == ""+ assert custom_clis.logo_file(entry.id) is None+++# --------------------------------------------------------------------------+# Speech+# --------------------------------------------------------------------------+++def test_a_short_one_word_name_claims_no_spoken_alias() -> None:+ """An alias like "go" turns every sentence containing it into a spawn."""+ custom_clis.create_custom_cli("Go", "go-cli")+ registry.refresh_custom_agents()+ assert "go" not in registry.spoken_aliases()+++def test_a_real_name_is_addressable_by_voice() -> None:+ custom_clis.create_custom_cli("Antigravity", "agy")+ registry.refresh_custom_agents()+ assert registry.spoken_aliases().get("antigravity") == "antigravity"+++def test_a_custom_name_is_reserved_against_pane_call_signs() -> None:+ """Saying "Antigravity" must not be a coin flip between a pane and a CLI."""+ custom_clis.create_custom_cli("Antigravity", "agy")+ registry.refresh_custom_agents()+ assert "antigravity" in registry.reserved_call_signs()