Skip to content

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.

@ feat(workspace): make a coding CLI a registry entry instead of a code path

Ruben Lütkee4e7a4b850a2
diff --git a/jarvis/agentic_ide/prompt_blueprint.py b/jarvis/agentic_ide/prompt_blueprint.py
index 3a28115cf5..30989ffa16 100644
--- a/jarvis/agentic_ide/prompt_blueprint.py
+++ b/jarvis/agentic_ide/prompt_blueprint.py
@@ -1,24 +1,41 @@
"""What a composed prompt looks like, and what it is allowed to say.
-Every rule here is traceable to the Claude 5 prompting documentation, because
-the thing this module replaces was a plausible-sounding prompt that made the
-receiving agent behave *worse*:
-
-* **Full specification up front.** Opus 5 "performs best when given the
- complete task specification up front and left to run" — the old 1200-char
- cap worked directly against that.
-* **The reason, not only the request.** Fable 5 connects a task to the right
+Every rule here is traceable to the vendors' own prompting documentation,
+because the thing this module replaces was a plausible-sounding prompt that
+made the receiving agent behave *worse*:
+
+* **Goal and constraints, never the implementation.** The single most
+ load-bearing rule, and the one the first version got backwards. Measured
+ live 2026-07-27: asked to make composition faster, the composer wrote "use
+ non-blocking background tasks for writer resolution" — it handed the agent a
+ solution that was *already implemented*, so the agent's task became
+ re-doing finished work. Every current frontier guide converges here: state
+ what good looks like and the bounds, and let the model choose the route.
+ Enumerated steps measurably REDUCE output quality on Fable 5, and leaner
+ system prompts score higher on agentic coding evaluations while costing a
+ fraction of the tokens.
+* **Full specification up front.** Complete does not mean prescriptive: the
+ agent should not have to come back with questions, which is a statement
+ about the CONTEXT it was handed, not about how many steps were dictated.
+* **The reason, not only the request.** A model connects a task to the right
context when it knows the intent behind it, so ``## Why this matters`` earns
its place whenever the intent is actually known.
-* **An explicit scope bound.** Both models widen tasks — surrounding
- refactors, unrequested abstractions, defensive code for impossible cases —
- unless told not to.
+* **Scope as intent, not as a prohibition list.** The first version listed
+ what the agent must not do (no surrounding cleanup, no unrequested
+ refactors, no speculative abstractions, no defensive handling). Anthropic's
+ own measured replacement for exactly that failure mode is an intent
+ instruction — deliver what was asked at the scope intended, make routine
+ judgement calls, flag rather than silently widen — which in testing cut
+ scope drift to near zero without producing extra clarifying questions.
* **No verification ritual.** "If your prompt contains explicit verification
instructions … remove them: instructions like these cause over-verification
… and removing them reduces wasted tokens with no loss in quality." Success
*criteria* stay; "double-check afterwards" is banned.
* **No reasoning echo.** Asking an agent to reproduce its internal reasoning
can trigger the ``reasoning_extraction`` refusal category on Fable 5.
+* **Say each thing exactly once.** A rule repeated in two sections is not
+ twice as followed; it is noise that dilutes the rules that matter, and it is
+ paid for on every composition in latency the user waits through.
* **Per-kind guardrails.** The clearest case: on a review, "only report
high-severity issues" is followed literally and suppresses real findings. On
an investigation the opposite steer is right — report, do not fix. One
@@ -44,41 +61,50 @@ from .task_kind import (
)
# The hard ceiling. MAX_PROMPT_CHARS is the transport cap above this.
-# Set above what real briefs measure (2865-3713 across three live runs) rather
-# than at it: a limit the writer breaches on every ordinary composition teaches
-# it that the limits in this prompt are approximate, and the ones that matter —
-# invent nothing, never end on a reference — are not.
-MAX_BODY_CHARS = 4500
+# Set above what real briefs measure rather than at it: a limit the writer
+# breaches on every ordinary composition teaches it that the limits in this
+# prompt are approximate, and the ones that matter — invent nothing, never end
+# on a reference — are not.
+MAX_BODY_CHARS = 3600
# What a GOOD prompt weighs, which is a different question from what is allowed.
-# The first version stated only the ceiling, and three live compositions came
-# back at 549 / 865 / 904 characters — under a third of the budget. A model
-# reads "keep it under N" as "be brief", so the target has to be said out loud.
-# The floor is the load-bearing half: below it, context the agent will have to
-# rediscover for itself has almost certainly been left out.
-TARGET_MIN_CHARS = 1800
-TARGET_MAX_CHARS = 3200
+# Both bounds were learned the hard way and BOTH are load-bearing:
+#
+# * Without a stated target the writer is brief — three live compositions came
+# back at 549 / 865 / 904 characters, and a lean-prompt A/B on 2026-07-27
+# produced a `## Done when` reading "the time taken is reduced", which is not
+# an acceptance criterion at all. A model reads "keep it under N" as "be
+# brief", so the target has to be said out loud.
+# * The old 1800-3200 target then bought length from the wrong place. The brief
+# it produced measured 3801 characters — over its own ceiling — and spent the
+# surplus dictating an implementation the agent should have chosen itself.
+#
+# So the target came down and the rules changed what the words are spent ON:
+# describing the code that exists, not prescribing the code to write. Every
+# character also costs the user real waiting time — 3801 characters took 21.8 s
+# against 16.0 s for a leaner brief on the same writer.
+TARGET_MIN_CHARS = 1400
+TARGET_MAX_CHARS = 2400
_SKELETON = """\
## Task
-<what to do, in the imperative - two to five sentences. Name the concrete
-symbols, files and behaviours involved; do not compress it to a headline>
+<what must be achieved, in the imperative - two to four sentences naming the
+concrete symbols, files and behaviours involved>
## Why this matters
<the intent behind the request, and what breaks or improves for the user -
-ONLY when it is known or clearly derivable>
+ONLY when known or clearly derivable>
## How it works today
-<the current behaviour of the code being changed, in real symbol names: which
-function does what, who calls it, which state it keeps. This is the part that
-saves the agent an entire round of rediscovery>
+<the current behaviour in real symbol names: which function does what, who
+calls it, which state it keeps>
## Key files
-- `@path/to/file` - what lives here and which part of it matters, named
+- `@path/to/file` - what lives here and which symbol in it matters
- `@path/to/other` - same, specifically
## Scope
-<what is in, what is explicitly out, and the constraints that apply>
+<the bound the user actually drew>
## Done when
- <an observable outcome>
@@ -86,54 +112,45 @@ saves the agent an entire round of rediscovery>
"""
_SHARED_RULES = f"""\
-You turn a spoken instruction into a prompt for a coding agent (Claude Code or \
-Codex) that is already running inside the user's repository. The agent will act \
-on what you write, so write the brief you would want to receive.
+You turn a spoken instruction into a brief for a coding agent (Claude Code or \
+Codex) already running inside the user's repository. The agent will act on what \
+you write, so write the brief you would want to receive.
-Output format - Markdown, using exactly this skeleton:
+Give the agent the GOAL, the CONTEXT and the CONSTRAINTS - never the \
+implementation. Which approach, which mechanism, which order are its decisions, \
+made against code it can see and you cannot; a solution you guess at gets built \
+even when it is wrong or already there. Say what must be true when it is done, \
+and leave the route open.
+
+Markdown, exactly this skeleton:
{_SKELETON}
-Rules for the skeleton:
-- Output ONLY the prompt. No preamble, no commentary, no surrounding code \
-fence, no quotes.
-- `## Task` is mandatory. Every other section is OPTIONAL: omit a section \
-entirely when you have nothing grounded to put in it. Never pad a section to \
-fill the shape.
-
-DESCRIBING is not INVENTING, and the difference decides how good this prompt \
-is. Keep these apart:
-- INVENTING is forbidden: a requirement, a constraint, a scope boundary or a \
-success criterion the user did not state and the workspace does not establish. \
-`## Done when` may only contain what the user asked for or what the repository \
-itself determines (its test command, its lint gate). If neither gives you \
-anything, omit the section.
-- DESCRIBING is wanted, in detail: what the code in the file outlines actually \
-does, which function is called from where, what the workspace profile says \
-about the stack and conventions, which constraint the repository's own house \
-rules impose. None of that is invention - it is context you were given and the \
-agent would otherwise spend its first minutes rediscovering. Spend words here.
-
-Be thorough. Aim for {TARGET_MIN_CHARS}-{TARGET_MAX_CHARS} characters. A prompt \
-under 800 characters has almost certainly dropped context you were handed: go \
-back and say what the relevant code does today, name the symbols involved, and \
-state the constraints that apply. Length must come from substance - concrete \
-file, symbol and behaviour detail - never from filler, restating the task in \
-other words, or hedging.
-- Reference files with `@path` inside a `## Key files` list item, using ONLY \
-paths from the candidate list you are given. Say what each file holds and \
-which function or class in it is the relevant one - "the ranking pipeline" is \
-worth far less to the agent than "`_fuse_ranked()`, which merges the ranked \
-lists before the relevance gate". Omit the section when no candidate is \
-clearly relevant.
-- Never end the prompt on an `@path` or a `/command`: a trailing reference \
-leaves the agent's completion popup open and the prompt is never submitted.
-- Write in ENGLISH, whatever language the user spoke. The agent works in a \
-repository whose code, comments and commits are English.
-- Preserve every constraint, file, symbol and intent the user expressed. \
-Remove speech artefacts: filler words, false starts, self-corrections, and the \
-clause addressing the agent by name.
-- Never exceed {MAX_BODY_CHARS} characters.
+- Output ONLY the brief: no preamble, no code fence, no quotes.
+- `## Task` is mandatory; every other section is OPTIONAL. Omit any you cannot \
+ground rather than padding it.
+
+DESCRIBING is not INVENTING, and the difference decides how good this brief is:
+- INVENTING is forbidden: a requirement, constraint, boundary or success \
+criterion the user did not state and the workspace does not establish. `## Done \
+when` holds only what the user asked for or what the repository itself \
+determines (its test command, its lint gate); `## Scope` only a line the user \
+actually drew. Omit either otherwise.
+- DESCRIBING is wanted, in detail: what the code in the outlines does, which \
+function is called from where, what the workspace profile and house rules \
+impose. That is context you were handed and the agent would otherwise rediscover.
+- Aim for {TARGET_MIN_CHARS}-{TARGET_MAX_CHARS} characters, never over \
+{MAX_BODY_CHARS}. Under 800 you have dropped context you were given. Length \
+comes from concrete file, symbol and behaviour detail - never from filler, \
+restatement, hedging or dictated steps.
+- `@path` references only inside `## Key files`, only from the candidate list, \
+each naming the symbol that matters ("`_fuse_ranked()`, which merges the ranked \
+lists before the relevance gate" beats "the ranking pipeline"). Never end the \
+prompt on an `@path` or `/command` - a trailing reference holds the agent's \
+completion popup open and the prompt is never submitted.
+- ENGLISH, whatever language the user spoke.
+- Preserve every constraint, file, symbol and intent expressed; drop speech \
+artefacts and the clause addressing the agent by name.
Two subjects must not appear in the prompt AT ALL - not as a requirement and \
not as a prohibition. Say nothing about either; the agent handles both \
@@ -151,17 +168,18 @@ prompt is this rule being LEAKED instead of followed - it is a defect.)\
_KIND_RULES: dict[str, str] = {
KIND_IMPLEMENT: """\
This is an IMPLEMENTATION task. Specific to it:
-- Give the COMPLETE specification up front, so the agent can work start to \
-finish without coming back with questions. This is the kind that most deserves \
-length: describe the behaviour that must exist afterwards, the shape it should \
-take, where it belongs in the existing code, and how it should behave when \
-things go wrong.
-- `## How it works today` is close to mandatory here. Name the function the \
-change lands in, what it currently does, and who calls it - the agent cannot \
-fit a change into code it has to find first.
-- `## Scope` matters here. Bound the work: name what is out of scope, and say \
-that surrounding cleanup, unrequested refactors, speculative abstractions and \
-defensive handling for impossible cases are not wanted.
+- Specify the OUTCOME completely, so the agent can work start to finish without \
+coming back with questions: the behaviour that must exist afterwards, how it \
+should behave when things go wrong, and any constraint it has to respect. \
+Complete means the agent lacks no context - not that you dictated the steps.
+- `## How it works today` is close to mandatory here: the function the change \
+lands in, what it currently does, and who calls it - the agent cannot fit a \
+change into code it has to find first. Give it the MAP, not every path; the \
+helpers it will meet on its own do not need listing.
+- `## Scope` only when the user actually drew a line. Do not fill it with \
+generic don'ts - "no unrequested refactors", "no speculative abstractions", "no \
+surrounding cleanup" are things the agent already gets right, and spending the \
+section on them costs the place a real boundary would have gone.
- `## Done when` states observable outcomes, not activities.\
""",
KIND_REVIEW: """\
@@ -203,8 +221,9 @@ user set a real boundary.\
""",
KIND_NEUTRAL: """\
The kind of work is not clearly determined. Stay with what the user said:
-- State the task as they framed it, and bound the scope to it - no \
-surrounding cleanup, no unrequested refactors.
+- State the task as they framed it, at the scope they framed it. Do not \
+sharpen an open request into a specific one - if they were broad, the agent \
+gets to decide where to start.
- Still describe the relevant code as it stands today. Being unsure which KIND \
of work this is is no reason to hand over less context.
- If they described a problem rather than asking for a change, say that the \
@@ -218,6 +237,57 @@ def system_prompt(kind: str) -> str:
return f"{_SHARED_RULES}\n\n{_KIND_RULES.get(kind, _KIND_RULES[KIND_NEUTRAL])}"
+def attachment_block(attachments: list) -> str:
+ """The dropped files' contents, laid out for the writer. ``""`` when none.
+
+ Each entry is a ``drop_analysis.DropAnalysis``. The description of a
+ screenshot and the text of a document are the whole reason the drop was
+ analysed: without them the writer can only say "the file the user dropped",
+ which is exactly the empty prompt this feature exists to prevent.
+
+ The reference travels WITH the content so the writer can cite the file the
+ agent will open, rather than inventing a path for a picture that only exists
+ as a description.
+ """
+ usable = [a for a in attachments or [] if getattr(a, "name", "")]
+ if not usable:
+ return ""
+ parts: list[str] = []
+ for item in usable:
+ kind = getattr(item, "kind", "") or "file"
+ header = f'<attachment name="{item.name}" kind="{kind}" reference="{item.reference}">'
+ if item.detail and getattr(item, "described_by", "") == "vision":
+ body = f"Description of what this image shows:\n{item.detail}"
+ elif item.detail:
+ body = f"Contents:\n{item.detail}"
+ else:
+ body = item.note or "No content could be read from this file."
+ parts.append(f"{header}\n{body}\n</attachment>")
+ return "\n\n".join(parts)
+
+
+# What the writer must do with a dropped file, appended only when there is one.
+# Stated as its own rule set rather than folded into the shared rules: on a
+# prompt with no attachment these lines are noise, and a rule that applies to
+# nothing teaches the model that the rules are approximate.
+_ATTACHMENT_RULES = """\
+The user DROPPED one or more files into this instruction, and their contents \
+are given above. Specific to that:
+- Carry the substance across. The agent may not be able to open an image at \
+all, so the description is its only view of it: put what the image actually \
+shows into `## How it works today` or `## Task`, in detail, rather than \
+writing "the screenshot the user dropped".
+- Quote the exact strings. Error messages, stack traces, labels and code from \
+an attachment go into the prompt VERBATIM — those are what the agent will \
+search the repository for, and a paraphrase cannot be grepped.
+- Reference the file as well, using the reference given in its attachment tag, \
+so an agent that CAN open it does. The description is the floor, not a \
+replacement.
+- The attachment is context, not the task. What the user asked for still \
+decides what the prompt asks the agent to do.\
+"""
+
+
def user_block(
*,
utterance: str,
diff --git a/jarvis/clis/installer.py b/jarvis/clis/installer.py
index 5dd63bcdb3..c6922755e0 100644
--- a/jarvis/clis/installer.py
+++ b/jarvis/clis/installer.py
@@ -11,6 +11,7 @@ from __future__ import annotations
import asyncio
import logging
+import sys
import time
from collections.abc import Callable
from dataclasses import dataclass, field
@@ -63,17 +64,35 @@ _PS_FETCH = "i" + "wr -useb"
_PS_PIPE = " | i" + "ex"
-def _build_ps_download_command(url: str) -> list[str]:
- """PowerShell wrapper that downloads and executes an install script.
+def _build_script_download_command(url: str) -> list[str]:
+ """Download-and-run wrapper for an official install script, per platform.
- Follows the official installer pattern used by many CLIs (Fly.io, Bun, etc.).
- The PowerShell one-liner is assembled here from fragments.
+ Follows the installer pattern most CLIs publish (Fly.io, Bun, OpenCode, ...):
+ fetch a script over HTTPS and execute it. The two worlds spell that
+ differently and neither spelling runs on the other, so the platform decides —
+ a PowerShell one-liner on Windows, a POSIX pipeline everywhere else.
+
+ That branch is not a nicety. Until it existed, ``script`` was the ONLY
+ install method a CLI could declare whose command was PowerShell-only, so a
+ tool whose official installer is ``curl -fsSL … | sh`` had no install path at
+ all on macOS or Linux — the CLI was simply unofferable there, which is
+ exactly the "the maintainer's OS is the baseline" failure the project
+ forbids.
+
+ The Windows one-liner stays assembled from fragments: written out whole it
+ matches the ``iwr … | iex`` pattern that anti-virus heuristics flag on sight.
"""
- inner = f"{_PS_FETCH} '{url}'{_PS_PIPE}"
- return [
- "powershell", "-NoProfile", "-ExecutionPolicy", "Bypass",
- "-Command", inner,
- ]
+ if sys.platform == "win32":
+ inner = f"{_PS_FETCH} '{url}'{_PS_PIPE}"
+ return [
+ "powershell", "-NoProfile", "-ExecutionPolicy", "Bypass",
+ "-Command", inner,
+ ]
+ # POSIX: curl if present, otherwise wget — a slim container often has only
+ # one of the two, and failing over inside the shell keeps this a single
+ # command rather than a probe plus a decision.
+ fetch = f"(curl -fsSL '{url}' || wget -qO- '{url}')"
+ return ["sh", "-c", f"{fetch} | sh"]
class CliInstaller:
@@ -96,7 +115,7 @@ class CliInstaller:
if method == "cargo" and i.cargo_package:
return ["cargo", "install", i.cargo_package]
if method == "script" and i.script_url:
- return _build_ps_download_command(i.script_url)
+ return _build_script_download_command(i.script_url)
return None
def start(
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index d6dd1bd7d9..3cab957905 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -2530,12 +2530,73 @@ class Phase6Config(BaseModel):
safety: Phase6SafetyConfig = Field(default_factory=Phase6SafetyConfig)
+class GlmCodingPlanConfig(BaseModel):
+ """Where a GLM pane sends its traffic, and which model ids it asks for.
+
+ The GLM Coding Plan has no CLI of its own: the vendor's own instructions are
+ to run the ordinary Claude Code binary against a different endpoint. So a
+ "GLM" pane is that binary plus this environment — which makes every value
+ here load-bearing, and every one of them a *setting* rather than a constant.
+
+ Why nothing is hardcoded:
+
+ * ``base_url`` — accounts registered in mainland China use a different host
+ from the international ones, and the two are not interchangeable. A fixed
+ URL simply locks out whichever half of the world it is not.
+ * the model ids — vendor documentation disagrees with itself about the
+ current names, and a wrong id fails at request time in a way that reads
+ like our bug. Empty means "send no model override at all" and let the
+ endpoint apply its own mapping, which is the only default that cannot be
+ wrong. Fill them in to pin a specific model.
+ * ``request_timeout_ms`` — the CLI's stock timeout is tuned for a different
+ backend and expires mid-answer here, which surfaces as a hang rather than
+ as an error.
+
+ The API key is deliberately NOT in this model: it lives in the credential
+ store under ``zai_api_key`` (ENV fallback ``ZAI_API_KEY``), because a key in
+ ``jarvis.toml`` is a key in a file that gets copied, shared and pasted into
+ bug reports (AP-12).
+ """
+
+ model_config = ConfigDict(extra="allow")
+
+ base_url: str = Field(
+ default="https://api.z.ai/api/anthropic",
+ description=(
+ "Anthropic-compatible endpoint a GLM pane talks to. Use "
+ "https://open.bigmodel.cn/api/anthropic for a mainland-China account."
+ ),
+ )
+ opus_model: str = Field(
+ default="",
+ description="Model id for the CLI's 'opus' tier. Empty = let the endpoint decide.",
+ )
+ sonnet_model: str = Field(
+ default="",
+ description="Model id for the CLI's 'sonnet' tier. Empty = let the endpoint decide.",
+ )
+ haiku_model: str = Field(
+ default="",
+ description="Model id for the CLI's 'haiku' tier. Empty = let the endpoint decide.",
+ )
+ request_timeout_ms: int = Field(
+ default=3_000_000,
+ ge=60_000,
+ description=(
+ "Per-request timeout handed to the CLI. The stock value is far too "
+ "short for this backend's long agentic runs and expires mid-answer."
+ ),
+ )
+
+
class AgenticIdeConfig(BaseModel):
"""Agentic IDE behaviour that is not per-workspace state."""
# AP-16: a key written by a NEWER install must not fail this one's boot.
model_config = ConfigDict(extra="allow")
+ glm: GlmCodingPlanConfig = Field(default_factory=GlmCodingPlanConfig)
+
prompt_writer: str = Field(
default="auto",
description=(
diff --git a/jarvis/workspace/agents.py b/jarvis/workspace/agents.py
index efbe4ab950..0f0cc1e4e6 100644
--- a/jarvis/workspace/agents.py
+++ b/jarvis/workspace/agents.py
@@ -29,7 +29,9 @@ rather than handing the PTY an argv that cannot start.
from __future__ import annotations
import logging
+from collections.abc import Callable
from dataclasses import dataclass
+from typing import Any, Literal
from jarvis.clis.prober import CliStatusProber
from jarvis.clis.spec import AuthConfig, CliSpec, InstallMethods, RiskConfig
@@ -41,12 +43,109 @@ log = logging.getLogger(__name__)
# "2.1.195 (Claude Code)" and "codex-cli 0.142.3".
_SEMVER_RE = r"(\d+\.\d+\.\d+)"
+# The same, with the patch component optional. Not every CLI ships three parts:
+# the Python-generation Kimi answers ``kimi, version 1.3``, which the strict
+# pattern above misses entirely — and a missed version is not a cosmetic loss.
+# It reads downstream as ``version=None``, which the wizard and the resume offer
+# render as a blank field next to an installed binary, i.e. exactly what a
+# broken install looks like. Entries whose CLI numbers itself in two parts opt
+# into this instead.
+_LOOSE_SEMVER_RE = r"(\d+\.\d+(?:\.\d+)?)"
+
# The registry key of the plain-shell entry. A name rather than a literal
# everywhere, because several layers (the IDE session registry, the pane split
# menu, the tests) have to agree on it.
PLAIN_TERMINAL = "shell"
+@dataclass(frozen=True, slots=True)
+class TrustSpec:
+ """Where and how one CLI records "this folder is trusted".
+
+ Every CLI that shows a trust dialog also writes the answer somewhere, and
+ writing it ourselves BEFORE launch is the only way to skip a dialog inside a
+ PTY we cannot answer programmatically. The shape of that write is the only
+ thing that differs between CLIs, so it is data here rather than a branch in
+ :mod:`jarvis.workspace.trust`.
+
+ ``home_env`` is the CLI's own "move my whole config elsewhere" variable; when
+ it is set in the environment the file lives under THAT directory instead of
+ ``~/<subdir>``. ``both_path_forms`` exists because some CLIs key the entry on
+ the cwd string exactly as they saw it, so a Windows path stored with
+ backslashes does not match the same folder written with forward slashes —
+ seeding both costs one extra key and removes a whole class of "the dialog
+ appeared anyway".
+ """
+
+ filename: str
+ fmt: Literal["json", "toml"]
+ # Key path to the table of per-project entries inside the file.
+ section: tuple[str, ...] = ("projects",)
+ # The key/value inside a project's entry that means "trusted".
+ key: str = "trust_level"
+ value: Any = "trusted"
+ # Keys written only when absent — never used to decide "already trusted".
+ extra_defaults: tuple[tuple[str, Any], ...] = ()
+ home_env: str | None = None
+ # Where the file lives relative to home. "" means home itself.
+ subdir: str = ""
+ both_path_forms: bool = False
+ # Take a one-time copy before the first mutation. Worth it for a file the
+ # user's own CLI configuration shares; pointless for one we created.
+ backup: bool = False
+
+
+@dataclass(frozen=True, slots=True)
+class AccountSpec:
+ """How one CLI's entire identity moves to a different directory.
+
+ The mechanism behind several subscriptions of the same CLI
+ (:mod:`jarvis.agent_accounts`): the CLI resolves credentials, settings and
+ conversation history from ONE directory, and publishes a variable that moves
+ it. Deliberately a mapping and not a single variable — OpenCode needs two
+ (its data root and its config root), and modelling that as one variable is
+ how a "switched" account keeps spending the previous login.
+
+ ``shared_env`` names the variables that are NOT dedicated overrides but
+ general-purpose ones the CLI happens to honour (``XDG_DATA_HOME``).
+ Redirecting those also redirects any other tool the agent spawns inside that
+ pane, so an entry that can only be moved through a shared variable is
+ offered as single-login until that blast radius has been measured.
+ """
+
+ #: ``{VAR: "{dir}"}`` — the value template gets the account directory.
+ env: tuple[tuple[str, str], ...]
+ #: Where the CLI looks when no override is set, e.g. ``~/.claude``.
+ native_dir: str
+ #: Subset of ``env`` whose variables are shared with other tools.
+ shared_env: tuple[str, ...] = ()
+
+ @property
+ def dedicated(self) -> bool:
+ """True when every variable that moves this CLI is its own."""
+ return not self.shared_env
+
+
+@dataclass(frozen=True, slots=True)
+class WinShim:
+ """How to reach the real executable behind a Windows ``.cmd`` shim.
+
+ ConPTY cannot exec a batch file, so a pane whose CLI installed itself as
+ ``<name>.cmd`` has to be launched some other way. ``cmd /c <shim>`` works and
+ is the fallback, but it puts a second process between the pane and the agent,
+ which costs signal delivery and a clean exit. When the package layout is
+ known we skip the shim entirely and launch what it would have launched.
+
+ ``kind`` says what sits at the end of the path: a Node script that needs
+ ``node.exe`` in front of it (Codex), or a native executable that is simply
+ run (OpenCode's Bun-compiled binary).
+ """
+
+ #: Path components relative to the directory the shim lives in.
+ relative_path: tuple[str, ...]
+ kind: Literal["node", "exe"] = "node"
+
+
@dataclass(frozen=True, slots=True)
class WorkspaceAgent:
"""One thing a workspace terminal can run.
@@ -61,6 +160,13 @@ class WorkspaceAgent:
``needs_trust`` says whether the folder has to be pre-marked as trusted for
this entry before a pane opens (``jarvis.workspace.trust``). A shell has no
trust dialog to skip, and neither does a CLI that never asks.
+
+ Everything below ``description`` is what a SECOND, THIRD or SIXTH coding CLI
+ turned out to need. Each field defaults to the behaviour the two original
+ entries already had, so adding them changed nothing for Claude Code and
+ Codex — and each one exists because the alternative was another
+ ``if agent == "<name>"`` branch in a layer that has no business knowing
+ product names (AP-21).
"""
name: str
@@ -76,11 +182,81 @@ class WorkspaceAgent:
# One line the UI can show under the name in a picker.
description: str = ""
+ # --- What to actually execute -------------------------------------------
+ #: The executable to look up on PATH. Split from ``launch_command`` because
+ #: a multi-token command ("uv tool run kimi") is not something
+ #: ``shutil.which`` can find, and feeding it one used to fail as "not
+ #: installed" rather than as the configuration error it is.
+ binary: str = ""
+ #: Arguments that always precede the per-pane ones.
+ launch_args: tuple[str, ...] = ()
+ win_shim: WinShim | None = None
+ #: Directories to add to PATH before looking, for CLIs that install outside
+ #: the usual places (Kimi's installer drops into ``~/.local/bin``).
+ extra_path_dirs: tuple[str, ...] = ()
+ #: Fixed environment for every pane of this entry — e.g. switching off an
+ #: auto-updater that would otherwise swap the binary under a live pane.
+ spawn_env: tuple[tuple[str, str], ...] = ()
+ #: Resolved per spawn AND per resume, for an entry whose environment depends
+ #: on user configuration (a key, an endpoint). Returning ``None`` means "not
+ #: configured" and must stop the launch — never a half-set environment,
+ #: which is how a pane silently talks to the wrong vendor.
+ spawn_env_factory: Callable[[], dict[str, str] | None] | None = None
+ #: Answers which GENERATION of the CLI is installed, when a vendor ships two
+ #: under one binary name. ``None`` when there is only ever one.
+ generation_probe: Callable[[], str | None] | None = None
+
+ # --- How it behaves once it is running ----------------------------------
+ trust: TrustSpec | None = None
+ account: AccountSpec | None = None
+ #: Which session adapter reopens this CLI's conversations. Empty means "the
+ #: one named after this entry"; naming another entry's adapter is how a
+ #: launch profile over an existing binary (GLM over Claude Code) inherits
+ #: resume for free instead of duplicating it.
+ resume_adapter: str = ""
+ #: How a dropped file is written into the prompt: ``@path`` or ``"path"``.
+ file_reference: Literal["at", "quoted"] = "quoted"
+ #: True when a pane must show its input line before a prompt may be typed.
+ #: Every CLI observed so far swallows a paste that arrives while it is still
+ #: booting, so this defaults on; an entry proven not to needs it off.
+ needs_input_line_wait: bool = True
+ #: The prompt sigils this CLI's input line starts with. Empty means "the
+ #: shared default set", which covers every TUI observed so far.
+ input_markers: tuple[str, ...] = ()
+ #: TUI furniture to strip before a transcript is summarised — banners,
+ #: status bars, key hints. Additive to the shared set.
+ chrome_fragments: tuple[str, ...] = ()
+ #: The per-project instructions file this CLI reads (CLAUDE.md, AGENTS.md).
+ instruction_filename: str = ""
+
+ # --- 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
+ #: word costs the whole spawn group it appeared in.
+ spoken_aliases: tuple[str, ...] = ()
+ #: Spellings that are ordinary words on their own ("cloud", "open") and only
+ #: mean the product with its second word behind them.
+ spoken_aliases_needing_suffix: tuple[str, ...] = ()
+ #: The word those aliases need behind them.
+ alias_suffix: str = "code"
+
@property
def is_coding_agent(self) -> bool:
"""True for an entry that runs an agent rather than a bare shell."""
return self.kind == "cli"
+ @property
+ def executable(self) -> str:
+ """The name to resolve on PATH — explicit, else the spec's, else empty."""
+ if self.binary:
+ return self.binary
+ return self.spec.binary_name if self.spec is not None else ""
+
+ @property
+ def adapter_key(self) -> str:
+ """Which session adapter this entry resumes through."""
+ return self.resume_adapter or self.name
+
def make_cli_agent(
name: str,
@@ -91,15 +267,24 @@ def make_cli_agent(
homepage: str = "",
launch_command: str | None = None,
description: str = "",
+ install: InstallMethods | None = None,
+ version_regex: str = _SEMVER_RE,
+ needs_trust: bool = True,
+ **extra: Any,
) -> WorkspaceAgent:
"""Build a registrable entry for an interactive CLI.
The convenience path for plugging in a new coding agent: give it a name, a
binary and (optionally) the npm package that installs it, and detection,
the install command and the launch argv all follow. A CLI installed some
- other way simply passes no package — it is then detected and launched, and
- reports "not installed" without offering an install command it does not
- have.
+ other way passes ``install=`` with whatever methods it does have — or
+ nothing at all, and is then detected and launched while honestly reporting
+ "not installed" rather than offering a command that cannot work.
+
+ ``extra`` forwards the behavioural fields of :class:`WorkspaceAgent`
+ (``trust``, ``resume_adapter``, ``spawn_env``, ``spoken_aliases``, ...) so a
+ new provider stays one call rather than a constructor plus a pile of
+ ``dataclasses.replace``.
"""
spec = CliSpec(
name=name,
@@ -108,8 +293,10 @@ def make_cli_agent(
homepage=homepage,
binary_name=binary,
check_command=(binary, "--version"),
- version_parse_regex=_SEMVER_RE,
- install=InstallMethods(npm_package=npm_package or None, recommended="npm"),
+ version_parse_regex=version_regex,
+ install=install or InstallMethods(
+ npm_package=npm_package or None, recommended="npm"
+ ),
# We only care whether the binary is installed; the agent handles its
# own login interactively on first launch in the terminal.
auth=AuthConfig(type="none"),
@@ -122,10 +309,127 @@ def make_cli_agent(
kind="cli",
spec=spec,
launch_command=launch_command or binary,
+ needs_trust=needs_trust,
description=description,
+ binary=binary,
+ **extra,
)
+#: Claude Code keeps per-project trust in ``~/.claude.json``. Named rather than
+#: inlined because a launch PROFILE over the same binary (the GLM entry) has to
+#: seed the very same file — a second descriptor saying the same thing is a
+#: second thing to keep in step.
+CLAUDE_TRUST = TrustSpec(
+ filename=".claude.json",
+ fmt="json",
+ section=("projects",),
+ key="hasTrustDialogAccepted",
+ value=True,
+ extra_defaults=(("hasCompletedProjectOnboarding", True),),
+ # Deliberately no ``home_env``. ``CLAUDE_CONFIG_DIR`` moves the ``.claude``
+ # DIRECTORY, while this file sits beside it in the home directory, and the
+ # per-account copies are seeded through the caller's explicit ``config_dirs``
+ # instead. Naming the variable here would silently relocate the machine's
+ # default trust file whenever an account happens to be active.
+ home_env=None,
+ subdir="",
+ both_path_forms=True,
+ backup=True,
+)
+
+#: Codex keeps it in ``$CODEX_HOME/config.toml`` under a per-project table.
+CODEX_TRUST = TrustSpec(
+ filename="config.toml",
+ fmt="toml",
+ section=("projects",),
+ key="trust_level",
+ value="trusted",
+ home_env="CODEX_HOME",
+ subdir=".codex",
+)
+
+#: Kimi ships under two generations that both install a binary called ``kimi``.
+KIMI_CURRENT = "kimi-code"
+KIMI_LEGACY = "kimi-cli"
+
+
+def kimi_generation() -> str | None:
+ """Which Kimi is installed: the current CLI, the wound-down one, or unknown.
+
+ Moonshot AI replaced its Python ``kimi-cli`` with a TypeScript ``kimi-code``
+ and BOTH put a binary named ``kimi`` on PATH. They do not share a data
+ directory and they do not share every flag — the short forms differ, so an
+ argv built for one silently means something else to the other, and
+ ``kimi --version`` succeeds either way. Detecting the generation is
+ therefore not polish: it is the difference between resuming a conversation
+ and opening a stranger's.
+
+ Decided on the data directory, which is the thing that actually differs and
+ the one signal that costs no subprocess. ``None`` means neither has been run
+ yet on this machine — a fresh install, where the honest answer is "whatever
+ the installer just put there", and the caller falls back to the current
+ generation's behaviour because that is what a fresh install gets.
+ """
+ from pathlib import Path
+
+ home = Path.home()
+ if (home / ".kimi-code").is_dir():
+ return KIMI_CURRENT
+ if (home / ".kimi").is_dir():
+ return KIMI_LEGACY
+ return None
+
+
+def glm_spawn_env() -> dict[str, str] | None:
+ """Environment that turns a Claude Code process into a GLM one.
+
+ Returns ``None`` when no key is configured, which stops the launch. That is
+ deliberate and is the whole safety property of this function: the CLI reads
+ its endpoint ONCE at process start and never mentions which backend it got,
+ so a pane launched with a half-set environment would answer perfectly well —
+ from, and billed to, the wrong vendor, with nothing anywhere saying so.
+ Refusing to start is recoverable; a silent wrong-vendor pane is not.
+
+ ``ANTHROPIC_API_KEY`` is blanked on purpose. This host may well have one set
+ for other reasons, it outranks the token we are passing, and the result
+ would be exactly the silent fallback above. An empty value means "remove
+ this variable from the child" — see :attr:`WorkspaceAgent.spawn_env`.
+ """
+ from jarvis.core.config import get_secret, load_config
+
+ token = (get_secret("zai_api_key", "ZAI_API_KEY") or "").strip()
+ if not token:
+ return None
+ try:
+ settings = load_config().agentic_ide.glm
+ except Exception as exc: # noqa: BLE001 - a broken config must not brick the pane
+ log.warning("GLM pane: falling back to default endpoint settings: %s", exc)
+ settings = None
+
+ def _setting(field: str, fallback: str) -> str:
+ value = getattr(settings, field, "") if settings is not None else ""
+ return str(value or fallback).strip()
+
+ env = {
+ "ANTHROPIC_BASE_URL": _setting("base_url", "https://api.z.ai/api/anthropic"),
+ "ANTHROPIC_AUTH_TOKEN": token,
+ "API_TIMEOUT_MS": _setting("request_timeout_ms", "3000000"),
+ "ANTHROPIC_API_KEY": "",
+ }
+ # Only pin a model when the user actually chose one: vendor documentation
+ # disagrees with itself about the current ids, and a wrong id fails at
+ # request time in a way that reads like a bug in this app.
+ for field, var in (
+ ("opus_model", "ANTHROPIC_DEFAULT_OPUS_MODEL"),
+ ("sonnet_model", "ANTHROPIC_DEFAULT_SONNET_MODEL"),
+ ("haiku_model", "ANTHROPIC_DEFAULT_HAIKU_MODEL"),
+ ):
+ if chosen := _setting(field, ""):
+ env[var] = chosen
+ return env
+
+
_AGENTS: dict[str, WorkspaceAgent] = {
"claude": make_cli_agent(
"claude",
@@ -133,6 +437,20 @@ _AGENTS: dict[str, WorkspaceAgent] = {
binary="claude",
npm_package="@anthropic-ai/claude-code",
homepage="https://claude.com/claude-code",
+ trust=CLAUDE_TRUST,
+ account=AccountSpec(
+ env=(("CLAUDE_CONFIG_DIR", "{dir}"),), native_dir="~/.claude"
+ ),
+ # Verified live: an ``@path`` is resolved into the file's contents and
+ # the file-picker popup does not eat an injected reference.
+ file_reference="at",
+ # The measured exception, not the rule: this CLI has a stable
+ # launch-and-prompt path, so waiting for its input line to appear would
+ # only slow down behaviour that already works.
+ needs_input_line_wait=False,
+ instruction_filename="CLAUDE.md",
+ spoken_aliases=("claude", "cloude", "claud", "clode", "klaude", "kloude"),
+ spoken_aliases_needing_suffix=("cloud", "clawed", "clod", "loud"),
),
"codex": make_cli_agent(
"codex",
@@ -140,6 +458,92 @@ _AGENTS: dict[str, WorkspaceAgent] = {
binary="codex",
npm_package="@openai/codex",
homepage="https://github.com/openai/codex",
+ trust=CODEX_TRUST,
+ account=AccountSpec(env=(("CODEX_HOME", "{dir}"),), native_dir="~/.codex"),
+ win_shim=WinShim(
+ relative_path=("node_modules", "@openai", "codex", "bin", "codex.js"),
+ kind="node",
+ ),
+ instruction_filename="AGENTS.md",
+ spoken_aliases=("codex", "kodex", "codecs", "codeks"),
+ ),
+ "opencode": make_cli_agent(
+ "opencode",
+ "OpenCode",
+ binary="opencode",
+ homepage="https://opencode.ai",
+ description="Open-source terminal coding agent — bring your own model.",
+ install=InstallMethods(
+ npm_package="opencode-ai",
+ script_url="https://opencode.ai/install",
+ # npm rather than the script: it is the one method that behaves the
+ # same on all three OSes, and this app installs by running a command
+ # in a terminal the user is watching.
+ recommended="npm",
+ ),
+ # No trust dialog exists — the folder is simply opened. What gates
+ # execution here is its permission system, which is a config file the
+ # user owns rather than a prompt in the way.
+ needs_trust=False,
+ win_shim=WinShim(
+ relative_path=("node_modules", "opencode-ai", "bin", "opencode.exe"),
+ kind="exe",
+ ),
+ # Its updater is ON by default and would swap the binary underneath a
+ # pane that is mid-conversation.
+ spawn_env=(("OPENCODE_DISABLE_AUTOUPDATE", "1"),),
+ file_reference="at",
+ instruction_filename="AGENTS.md",
+ spoken_aliases=("opencode",),
+ # "open" is the verb half of "open a terminal", so on its own it means
+ # nothing here — only "open code" is unmistakable, and even that needs
+ # the guard in the intent parser that keeps a sentence from matching its
+ # own opening verb.
+ spoken_aliases_needing_suffix=("open",),
+ ),
+ "kimi": make_cli_agent(
+ "kimi",
+ "Kimi Code",
+ binary="kimi",
+ npm_package="@moonshot-ai/kimi-code",
+ homepage="https://moonshotai.github.io/kimi-code/en/",
+ description="Moonshot AI's terminal coding agent.",
+ # Measured: the wound-down generation answers "kimi, version 1.3", which
+ # the strict three-part pattern drops to None — and a blank version next
+ # to an installed binary reads as a broken install.
+ version_regex=_LOOSE_SEMVER_RE,
+ needs_trust=False,
+ # Its update preflight can check, install and PROMPT mid-session.
+ spawn_env=(("KIMI_CODE_NO_AUTO_UPDATE", "1"),),
+ account=AccountSpec(
+ env=(("KIMI_CODE_HOME", "{dir}"),), native_dir="~/.kimi-code"
+ ),
+ # Its own installer drops the binary here, which is not on the PATH a
+ # GUI-launched process inherits on macOS or Linux.
+ extra_path_dirs=("~/.local/bin",),
+ generation_probe=kimi_generation,
+ spoken_aliases=("kimi", "kimmy", "kimmi", "kimme", "kimmie"),
+ ),
+ "glm": make_cli_agent(
+ "glm",
+ "GLM Coding Plan",
+ # The whole design of this entry: the binary IS Claude Code. Z.ai ships
+ # no CLI of its own — its own documentation says to run Anthropic's
+ # binary against a different endpoint — so detection, the install
+ # command, trust seeding and conversation resume are all INHERITED
+ # rather than re-implemented against an executable that cannot exist.
+ binary="claude",
+ npm_package="@anthropic-ai/claude-code",
+ homepage="https://docs.z.ai/devpack/tool/claude",
+ description="Z.ai's GLM models, driven through the Claude Code CLI.",
+ trust=CLAUDE_TRUST,
+ resume_adapter="claude",
+ file_reference="at",
+ needs_input_line_wait=False,
+ instruction_filename="CLAUDE.md",
+ # Resolved fresh on every spawn AND every resume — see the docstring.
+ spawn_env_factory=glm_spawn_env,
+ spoken_aliases=("glm", "g l m", "gee ell em", "jlm"),
),
PLAIN_TERMINAL: WorkspaceAgent(
name=PLAIN_TERMINAL,
@@ -163,9 +567,28 @@ def register_agent(agent: WorkspaceAgent, *, replace: bool = False) -> Workspace
if agent.name in _AGENTS and not replace:
raise ValueError(f"A workspace agent called {agent.name!r} is already registered.")
_AGENTS[agent.name] = agent
+ _forget_command_catalog()
return agent
+def _forget_command_catalog() -> None:
+ """Drop the cached command catalog, which spells this registry out.
+
+ The voice/LLM schema for "open a pane running X" lists the registered
+ coding CLIs by name, and that catalog is built once and cached. An agent
+ registered after the first build would therefore be openable from the UI,
+ resumable, promptable — and invisible to the one surface meant to drive it.
+ Never raises: the catalog is optional to this module, and a registration
+ that fails because of it would be the worse outcome.
+ """
+ try:
+ from jarvis.commands.registry import get_registry
+
+ get_registry.cache_clear()
+ except Exception: # noqa: BLE001 - the catalog is not this module's job
+ return
+
+
def list_agents() -> list[WorkspaceAgent]:
"""Every registered entry, in registration order."""
return list(_AGENTS.values())
@@ -203,12 +626,99 @@ AGENT_NAMES: tuple[str, ...] = coding_agent_names()
def install_command(name: str) -> str | None:
- """The shell command that installs the agent (for display + terminal run)."""
+ """The shell command that installs the agent (for display + terminal run).
+
+ Delegates to the shared installer rather than assembling an npm line here.
+ Not every coding CLI is an npm package — some ship a winget id, a scoop
+ package or their own install script — and hardcoding one package manager
+ meant every other kind of CLI reported "no install command" while its spec
+ carried a perfectly good one.
+
+ ``None`` stays an honest answer: an entry that declares no reachable install
+ method for THIS platform is shown as not installed without being offered a
+ command that cannot work.
+ """
agent = _AGENTS.get(name)
if agent is None or agent.spec is None:
return None
- pkg = agent.spec.install.npm_package
- return f"npm install -g {pkg}" if pkg else None
+ methods = agent.spec.install
+ chosen = methods.recommended
+ available = methods.available_methods()
+ if chosen not in available:
+ chosen = available[0] if available else None
+ if chosen in (None, "manual"):
+ return None
+ from jarvis.clis.installer import CliInstaller
+
+ argv = CliInstaller().build_command(agent.spec, chosen) # type: ignore[arg-type]
+ if not argv:
+ return None
+ return " ".join(argv)
+
+
+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]
+
+
+def generation_of(name: str) -> str | None:
+ """Which generation of ``name``'s CLI this machine has, when that differs.
+
+ ``None`` for every entry whose vendor ships exactly one thing under one
+ binary name — which is all of them but Kimi.
+ """
+ agent = _AGENTS.get(name)
+ if agent is None or agent.generation_probe is None:
+ return None
+ try:
+ return agent.generation_probe()
+ except Exception as exc: # noqa: BLE001 - a probe must never block a launch
+ log.warning("generation probe for %s failed: %s", name, exc)
+ return None
+
+
+def spoken_aliases() -> dict[str, str]:
+ """Every spelling a transcript may carry, mapped to the entry it names.
+
+ Includes the spellings that are ordinary words on their own — the caller
+ decides what to do with those (see :func:`aliases_needing_suffix`), because
+ only the caller knows whether the product's second word followed.
+ """
+ out: dict[str, str] = {}
+ for agent in _AGENTS.values():
+ for spelling in (*agent.spoken_aliases, *agent.spoken_aliases_needing_suffix):
+ out.setdefault(spelling, agent.name)
+ return out
+
+
+def aliases_needing_suffix() -> dict[str, tuple[str, str]]:
+ """Ambiguous spellings → ``(entry name, the word that must follow)``.
+
+ "cloud" is not a request for a Claude Code pane and "open" is not a request
+ for an OpenCode one; "cloud code" and "open code" are. Keeping the required
+ word beside the spelling means a new entry can pick its own without every
+ caller learning about it.
+ """
+ return {
+ spelling: (agent.name, agent.alias_suffix)
+ for agent in _AGENTS.values()
+ for spelling in agent.spoken_aliases_needing_suffix
+ }
+
+
+def reserved_call_signs() -> frozenset[str]:
+ """Names a pane may never carry, because a product already answers to them.
+
+ Addressing a pane called "Kimi" by saying "Kimi" is a coin flip once a CLI
+ is also called that, so the pool of call-signs excludes every registered
+ product name and every spelling of one.
+ """
+ names: set[str] = set()
+ for agent in _AGENTS.values():
+ names.add(agent.name.lower())
+ names.update(part.lower() for part in agent.display_name.split())
+ names.update(spelling.lower() for spelling in agent.spoken_aliases)
+ return frozenset(n for n in names if n.isalpha())
@dataclass(slots=True)
@@ -335,20 +845,34 @@ def pty_available() -> bool:
__all__ = [
"AGENT_NAMES",
+ "CLAUDE_TRUST",
+ "CODEX_TRUST",
+ "KIMI_CURRENT",
+ "KIMI_LEGACY",
"PLAIN_TERMINAL",
+ "AccountSpec",
"AgentInfo",
+ "TrustSpec",
+ "WinShim",
"WorkspaceAgent",
"agent_names",
+ "aliases_needing_suffix",
"build_agent_argv",
"build_install_argv",
"coding_agent_names",
+ "coding_agents",
"detect_agents",
+ "generation_of",
"get_agent",
+ "glm_spawn_env",
"install_command",
+ "kimi_generation",
"list_agents",
"make_cli_agent",
"needs_trust",
"plain_terminal_argv",
"pty_available",
"register_agent",
+ "reserved_call_signs",
+ "spoken_aliases",
]
diff --git a/jarvis/workspace/trust.py b/jarvis/workspace/trust.py
index a286166ed2..5f93d06d95 100644
--- a/jarvis/workspace/trust.py
+++ b/jarvis/workspace/trust.py
@@ -3,19 +3,28 @@
Detached external terminals can't be answered programmatically, so the robust
way to "skip the trust prompt" is to mark the project folder as trusted in each
CLI's own config BEFORE launching — exactly what the CLI writes when the user
-clicks "trust" once:
-
-- **Claude Code** keeps per-project trust in ``~/.claude.json`` under
- ``projects[<path>].hasTrustDialogAccepted = true``. Claude keys by the cwd
- string, and the form (drive case / slash style) matters, so we seed both the
- native and forward-slash variants.
-- **Codex** keeps it in ``$CODEX_HOME/config.toml`` (default ``~/.codex``) under
+clicks "trust" once.
+
+**Which file, and what to put in it, is registry data** — a
+:class:`~jarvis.workspace.agents.TrustSpec` on the agent entry — not a chain of
+``if name == ...`` here. Two things fall out of that. A CLI whose config happens
+to have the same shape as another's (a launch profile over the same binary)
+reuses the writer instead of earning a fourth branch, and a newly registered CLI
+gets trust seeding by declaring where its file lives, with no edit to this
+module at all. Only two *shapes* exist, and they are the two file formats:
+
+- a **JSON** object with a per-project entry — Claude Code's ``~/.claude.json``,
+ ``projects[<path>].hasTrustDialogAccepted = true``. It keys by the cwd string
+ as it saw it, and the form (drive case / slash style) matters, so a spec may
+ ask for both the native and forward-slash variants to be seeded.
+- a **TOML** table — Codex's ``$CODEX_HOME/config.toml``,
``[projects.'<path>'] trust_level = "trusted"``.
Both writes are atomic (temp file + ``os.replace``) and idempotent, and never
-clobber unrelated keys. ``~/.claude.json`` is backed up once before the first
-mutation. If a write fails we report it honestly — we never claim "skipped"
-when it wasn't.
+clobber unrelated keys. A spec may ask for a one-time backup before the first
+mutation — worth it for a file the user's own CLI configuration shares, and
+pointless for one we created. If a write fails we report it honestly — we never
+claim "skipped" when it wasn't.
``config_dirs`` covers the second place a CLI reads that file from. A terminal
running on an ADDED subscription resolves its whole configuration from the
@@ -31,9 +40,12 @@ from __future__ import annotations
import json
import logging
import os
-from collections.abc import Iterable, Mapping
+from collections.abc import Callable, Iterable, Mapping
from dataclasses import dataclass
from pathlib import Path
+from typing import Any
+
+from .agents import TrustSpec
log = logging.getLogger(__name__)
@@ -60,35 +72,66 @@ def ensure_trusted(
subscriptions run from (see the module docstring). Each of them is seeded in
addition to the machine's default, and contributes its own result, so a
caller can see per directory whether the dialog will really be skipped."""
+ from .agents import get_agent
+
test_mode = home is not None
home = home or Path.home()
- claude_cfg = home / ".claude.json"
- if test_mode:
- codex_home = home / ".codex"
- else:
- codex_home = Path(os.environ.get("CODEX_HOME") or (home / ".codex"))
- codex_cfg = codex_home / "config.toml"
results: list[TrustResult] = []
for name in agents:
- if name == "claude":
- results.append(_trust_claude(repo_root, claude_cfg))
- for extra in _extra_configs(name, ".claude.json", claude_cfg, config_dirs):
- results.append(_trust_claude(repo_root, extra))
- elif name == "codex":
- results.append(_trust_codex(repo_root, codex_cfg))
- for extra in _extra_configs(name, "config.toml", codex_cfg, config_dirs):
- results.append(_trust_codex(repo_root, extra))
- elif not _needs_trust(name):
- # A registered entry with no trust dialog to skip — a plain shell,
- # or a CLI that simply never asks. Nothing to write, and saying so
- # is not the same answer as "I do not know this agent".
- results.append(TrustResult(name, True, "noop", "nothing to pre-trust"))
- else: # pragma: no cover - guarded upstream
- results.append(TrustResult(name, False, "error", f"unknown agent: {name}"))
+ entry = get_agent(name)
+ spec = entry.trust if entry is not None else None
+ if spec is None:
+ if entry is None: # pragma: no cover - guarded upstream
+ results.append(
+ TrustResult(name, False, "error", f"unknown agent: {name}")
+ )
+ elif entry.needs_trust:
+ # The entry says a dialog exists but never said where the answer
+ # goes. The pane still opens — the user just answers the dialog
+ # once — but this must be loud rather than indistinguishable
+ # from "nothing to do": a silent noop here is exactly how a
+ # provider ships looking finished and greets every new folder
+ # with a prompt nobody expected.
+ log.warning(
+ "%s wants folder trust but declares no trust spec; "
+ "the CLI will ask in the pane.", name,
+ )
+ results.append(
+ TrustResult(name, True, "noop", "no trust spec — CLI will ask")
+ )
+ else:
+ # A registered entry with no trust dialog to skip — a plain
+ # shell, or a CLI that simply never asks. Nothing to write, and
+ # saying so is not the same answer as "I do not know this agent".
+ results.append(
+ TrustResult(name, True, "noop", "nothing to pre-trust")
+ )
+ continue
+ cfg = _config_path(spec, home, test_mode=test_mode)
+ write = _WRITERS[spec.fmt]
+ results.append(write(name, repo_root, cfg, spec))
+ for extra in _extra_configs(name, spec.filename, cfg, config_dirs):
+ results.append(write(name, repo_root, extra, spec))
return results
+def _config_path(spec: TrustSpec, home: Path, *, test_mode: bool) -> Path:
+ """Where this CLI's trust file lives on this machine.
+
+ The CLI's own "move my config elsewhere" variable wins when it is set, which
+ is the whole reason the variable is on the spec: seeding the default
+ location for a CLI the user has redirected writes a file nothing reads, and
+ the dialog this module exists to skip appears anyway. Tests pass an explicit
+ home and are deliberately kept away from the real environment.
+ """
+ if spec.home_env and not test_mode:
+ if raw := os.environ.get(spec.home_env):
+ return Path(raw).expanduser() / spec.filename
+ base = home / spec.subdir if spec.subdir else home
+ return base / spec.filename
+
+
def _extra_configs(
agent: str,
filename: str,
@@ -117,14 +160,6 @@ def _extra_configs(
return extras
-def _needs_trust(name: str) -> bool:
- """Does the registry know this entry, and does it want folder trust seeded?"""
- from .agents import get_agent
-
- agent = get_agent(name)
- return agent is None or agent.needs_trust
-
-
def _atomic_write_text(path: Path, text: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(f"{path.name}.tmp-{os.getpid()}")
@@ -132,46 +167,63 @@ def _atomic_write_text(path: Path, text: str) -> None:
os.replace(tmp, path)
-def _trust_claude(repo_root: Path, cfg: Path) -> TrustResult:
+def _project_keys(repo_root: Path, spec: TrustSpec) -> set[str]:
+ """The cwd spellings to seed — one, or both slash forms when asked."""
+ native = str(repo_root)
+ if not spec.both_path_forms:
+ return {native}
+ return {native, repo_root.as_posix()}
+
+
+def _trust_json(
+ agent: str, repo_root: Path, cfg: Path, spec: TrustSpec
+) -> TrustResult:
+ """Seed trust into a JSON config with a per-project object."""
native = str(repo_root)
- forward = repo_root.as_posix()
try:
if cfg.exists():
raw = cfg.read_text(encoding="utf-8")
data = json.loads(raw) # dup keys: last wins, no error
- backup = cfg.with_name(cfg.name + ".jarvis-bak")
- if not backup.exists():
- backup.write_text(raw, encoding="utf-8")
+ if spec.backup:
+ backup = cfg.with_name(cfg.name + ".jarvis-bak")
+ if not backup.exists():
+ backup.write_text(raw, encoding="utf-8")
else:
data = {}
if not isinstance(data, dict):
- return TrustResult("claude", False, "error", "config root is not an object")
+ return TrustResult(agent, False, "error", "config root is not an object")
- projects = data.setdefault("projects", {})
- if not isinstance(projects, dict):
- return TrustResult("claude", False, "error", "'projects' is not an object")
+ projects: Any = data
+ for step in spec.section:
+ nested = projects.setdefault(step, {})
+ if not isinstance(nested, dict):
+ return TrustResult(
+ agent, False, "error", f"{step!r} is not an object"
+ )
+ projects = nested
changed = False
- for key in {native, forward}:
+ for key in _project_keys(repo_root, spec):
entry = projects.get(key)
if not isinstance(entry, dict):
entry = {}
- if entry.get("hasTrustDialogAccepted") is not True:
- entry["hasTrustDialogAccepted"] = True
+ if entry.get(spec.key) != spec.value:
+ entry[spec.key] = spec.value
changed = True
- entry.setdefault("hasCompletedProjectOnboarding", True)
+ for extra_key, extra_value in spec.extra_defaults:
+ entry.setdefault(extra_key, extra_value)
projects[key] = entry
if changed or not cfg.exists():
_atomic_write_text(cfg, json.dumps(data, indent=2, ensure_ascii=False))
- return TrustResult("claude", True, "config", f"trusted {native}")
- return TrustResult("claude", True, "noop", "already trusted")
+ return TrustResult(agent, True, "config", f"trusted {native}")
+ return TrustResult(agent, True, "noop", "already trusted")
except Exception as exc: # noqa: BLE001
- log.warning("claude trust pre-seed failed: %s", exc)
- return TrustResult("claude", False, "error", str(exc))
+ log.warning("%s trust pre-seed failed: %s", agent, exc)
+ return TrustResult(agent, False, "error", str(exc))
-def _already_trusted_by_codex(text: str, native: str) -> bool:
+def _already_trusted_in_toml(text: str, native: str, spec: TrustSpec) -> bool:
"""Read-only "is this folder already trusted?" — the fast path.
Deliberately ``tomllib`` and not ``tomlkit``. Both parse the same file, but
@@ -189,21 +241,28 @@ def _already_trusted_by_codex(text: str, native: str) -> bool:
import tomllib
try:
- projects = tomllib.loads(text).get("projects")
+ section: Any = tomllib.loads(text)
except (ValueError, TypeError):
return False
- if not isinstance(projects, dict):
+ for step in spec.section:
+ if not isinstance(section, dict):
+ return False
+ section = section.get(step)
+ if not isinstance(section, dict):
return False
- entry = projects.get(native)
- return isinstance(entry, dict) and entry.get("trust_level") == "trusted"
+ entry = section.get(native)
+ return isinstance(entry, dict) and entry.get(spec.key) == spec.value
-def _trust_codex(repo_root: Path, cfg: Path) -> TrustResult:
+def _trust_toml(
+ agent: str, repo_root: Path, cfg: Path, spec: TrustSpec
+) -> TrustResult:
+ """Seed trust into a TOML config with a per-project table."""
native = str(repo_root)
try:
existing_text = cfg.read_text(encoding="utf-8") if cfg.exists() else ""
- if existing_text and _already_trusted_by_codex(existing_text, native):
- return TrustResult("codex", True, "noop", "already trusted")
+ if existing_text and _already_trusted_in_toml(existing_text, native, spec):
+ return TrustResult(agent, True, "noop", "already trusted")
# Only now, when something actually has to change, is the
# formatting-preserving parser worth its cost.
@@ -215,24 +274,36 @@ def _trust_codex(repo_root: Path, cfg: Path) -> TrustResult:
cfg.parent.mkdir(parents=True, exist_ok=True)
doc = tomlkit.document()
- projects = doc.get("projects")
- if projects is None:
- projects = tomlkit.table()
- doc["projects"] = projects
+ section: Any = doc
+ for step in spec.section:
+ nested = section.get(step)
+ if nested is None:
+ nested = tomlkit.table()
+ section[step] = nested
+ section = nested
- existing = projects.get(native)
- already = existing is not None and dict(existing).get("trust_level") == "trusted"
- if already:
- return TrustResult("codex", True, "noop", "already trusted")
+ existing = section.get(native)
+ if existing is not None and dict(existing).get(spec.key) == spec.value:
+ return TrustResult(agent, True, "noop", "already trusted")
entry = tomlkit.table()
- entry["trust_level"] = "trusted"
- projects[native] = entry
+ entry[spec.key] = spec.value
+ for extra_key, extra_value in spec.extra_defaults:
+ entry.setdefault(extra_key, extra_value)
+ section[native] = entry
_atomic_write_text(cfg, tomlkit.dumps(doc))
- return TrustResult("codex", True, "config", f"trusted {native}")
+ return TrustResult(agent, True, "config", f"trusted {native}")
except Exception as exc: # noqa: BLE001
- log.warning("codex trust pre-seed failed: %s", exc)
- return TrustResult("codex", False, "error", str(exc))
+ log.warning("%s trust pre-seed failed: %s", agent, exc)
+ return TrustResult(agent, False, "error", str(exc))
+
+
+#: One writer per FILE FORMAT — never per product. A CLI that stores trust the
+#: way another already does reuses the writer by declaring the same ``fmt``.
+_WRITERS: dict[str, Callable[[str, Path, Path, TrustSpec], TrustResult]] = {
+ "json": _trust_json,
+ "toml": _trust_toml,
+}
__all__ = ["TrustResult", "ensure_trusted"]
diff --git a/tests/unit/agentic_ide/test_prompt_blueprint.py b/tests/unit/agentic_ide/test_prompt_blueprint.py
index 44fbb0d543..58ee171345 100644
--- a/tests/unit/agentic_ide/test_prompt_blueprint.py
+++ b/tests/unit/agentic_ide/test_prompt_blueprint.py
@@ -109,11 +109,25 @@ def test_investigate_makes_the_diagnosis_the_deliverable():
assert "not apply a fix" in text.lower()
-def test_implement_demands_a_scope_bound():
+def test_implement_specifies_the_outcome_without_dictating_the_route():
+ """Complete is a statement about CONTEXT, not about enumerated steps.
+
+ The first version paired "give the COMPLETE specification" with a list of
+ generic prohibitions to put in `## Scope` — no surrounding cleanup, no
+ unrequested refactors, no speculative abstractions. Measured live
+ 2026-07-27, that combination produced a brief telling the agent to "use
+ non-blocking background tasks for writer resolution": a solution the
+ composer had ALREADY implemented, so the agent's task became re-doing
+ finished work. Specify the outcome; leave the route to the agent, which can
+ read the code the writer only saw an outline of.
+ """
text = system_prompt(KIND_IMPLEMENT)
assert "IMPLEMENTATION task" in text
- assert "out of scope" in text.lower()
- assert "complete specification" in text.lower()
+ assert "Specify the OUTCOME completely" in text
+ # Complete must be defined as context, not as dictated steps.
+ assert "not that you dictated the steps" in text
+ # And the generic prohibition list must stay OUT of `## Scope`.
+ assert "only when the user actually drew a line" in text
def test_question_forbids_changing_anything():
@@ -233,10 +247,17 @@ def test_the_target_length_sits_inside_the_hard_ceiling():
@pytest.mark.parametrize("kind", _ALL_KINDS)
def test_every_kind_states_the_target_length_not_only_the_ceiling(kind):
+ """Both bounds, and a floor that names what a too-short brief dropped.
+
+ "Be thorough" used to carry the floor and it bought length from the wrong
+ place — the writer padded with dictated implementation steps rather than
+ with description. The floor is now stated as the thing actually missing
+ from a thin brief: context the writer was handed and did not pass on.
+ """
text = system_prompt(kind)
assert str(TARGET_MIN_CHARS) in text
assert str(TARGET_MAX_CHARS) in text
- assert "Be thorough" in text
+ assert "Under 800 you have dropped context you were given" in text
@pytest.mark.parametrize("kind", _ALL_KINDS)
@@ -248,6 +269,22 @@ def test_every_kind_separates_describing_from_inventing(kind):
assert "DESCRIBING is wanted" in text
[email protected]("kind", _ALL_KINDS)
+def test_every_kind_asks_for_the_goal_and_not_the_implementation(kind):
+ """The rule the whole blueprint turns on, so it is pinned for every kind.
+
+ The writer sees bounded file OUTLINES; the agent sees the code. A route
+ chosen from the outline is a guess, and a guessed route gets built even
+ when it is wrong or already there — measured live 2026-07-27, a brief
+ asked for concurrency that the target module already had. Every current
+ frontier prompting guide converges on the same instruction: state the
+ goal and the bounds, leave the route to the model.
+ """
+ text = system_prompt(kind)
+ assert "never the implementation" in text
+ assert "leave the route open" in text
+
+
@pytest.mark.parametrize("kind", _ALL_KINDS)
def test_every_kind_offers_the_current_behaviour_section(kind):
"""Describing today's code is what saves the agent a discovery round."""
diff --git a/tests/unit/workspace/test_agents.py b/tests/unit/workspace/test_agents.py
index 1f8cf09a47..53739e872c 100644
--- a/tests/unit/workspace/test_agents.py
+++ b/tests/unit/workspace/test_agents.py
@@ -27,11 +27,21 @@ from jarvis.workspace.agents import (
)
-def test_coding_agents_are_claude_and_codex() -> None:
- assert set(coding_agent_names()) == {"claude", "codex"}
+# The entries this build promises. A SUPERSET assertion, deliberately: pinning
+# the exact set is what froze the registry at two providers and turned every
+# later addition into a test edit, which is the opposite of what an open
+# registry is for. What must not break is that a shipped provider silently
+# disappears.
+REQUIRED_CODING_AGENTS = frozenset({"claude", "codex", "opencode", "kimi", "glm"})
+
+
+def test_every_promised_coding_agent_is_registered() -> None:
+ assert REQUIRED_CODING_AGENTS <= set(coding_agent_names())
# The historical constant keeps meaning "the coding agents": every existing
# caller (the Make-It-Yours launcher, its PTY route) reads it that way.
- assert set(AGENT_NAMES) == {"claude", "codex"}
+ assert set(AGENT_NAMES) == set(coding_agent_names())
+ # The plain terminal is not one of them.
+ assert PLAIN_TERMINAL not in coding_agent_names()
def test_the_registry_also_holds_a_plain_terminal() -> None:
@@ -48,23 +58,46 @@ def test_the_registry_also_holds_a_plain_terminal() -> None:
def test_cli_specs_are_valid_clispecs() -> None:
+ """A property every coding entry must hold — not a list of the two we had.
+
+ The binary is deliberately NOT compared against a fixed set: one entry (the
+ GLM coding plan) is a launch PROFILE over another entry's binary, which is
+ the whole reason a provider with no CLI of its own can be offered at all.
+ """
for agent in list_agents():
if not agent.is_coding_agent:
continue
assert isinstance(agent.spec, CliSpec)
- assert agent.spec.binary_name in ("claude", "codex")
+ assert agent.spec.binary_name
assert agent.spec.check_command[-1] == "--version"
-
-
-def test_install_commands_use_npm() -> None:
+ # The name to resolve on PATH always agrees with what detection probed;
+ # a disagreement means a pane launches something the status card never
+ # checked.
+ assert agent.executable == agent.spec.binary_name
+
+
+def test_install_commands_are_runnable_or_honestly_absent() -> None:
+ """Every entry either yields a usable command or says it has none."""
+ for name in coding_agent_names():
+ command = install_command(name)
+ assert command is None or command.strip()
+ # The built-ins keep their exact commands: these are what the user is shown
+ # and what gets run in a terminal, so a silent change is a real change.
assert install_command("claude") == "npm install -g @anthropic-ai/claude-code"
assert install_command("codex") == "npm install -g @openai/codex"
+ assert install_command("opencode") == "npm install -g opencode-ai"
+ assert install_command("kimi") == "npm install -g @moonshot-ai/kimi-code"
+ # A launch profile installs the binary it borrows.
+ assert install_command("glm") == "npm install -g @anthropic-ai/claude-code"
assert install_command("nope") is None
def test_launch_command_is_bare_binary() -> None:
assert get_agent("claude").launch_command == "claude"
assert get_agent("codex").launch_command == "codex"
+ assert get_agent("opencode").launch_command == "opencode"
+ # The profile runs the borrowed binary, not a command named after itself.
+ assert get_agent("glm").launch_command == "claude"
def test_build_agent_argv_wraps_command_in_a_shell() -> None:
@@ -103,11 +136,22 @@ def test_pty_available_is_true_on_a_host_with_a_shell() -> None:
class FakeProber:
+ """A prober that answers for the entries a test names and no others.
+
+ Missing names default to "not installed" rather than raising. A test about
+ Claude Code has no business failing because a THIRD provider was registered
+ since it was written — that turned every new entry into an edit of unrelated
+ tests, which is exactly the friction an open registry is meant to remove.
+ """
+
def __init__(self, statuses: dict[str, CliStatus]) -> None:
self._statuses = statuses
async def probe_all(self, specs) -> dict[str, CliStatus]: # noqa: ANN001
- return {s.name: self._statuses[s.name] for s in specs}
+ return {
+ s.name: self._statuses.get(s.name, CliStatus(installed=False))
+ for s in specs
+ }
@pytest.mark.asyncio