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(missions): real subagent worker for grok/openai/openrouter (run ON the picked provider)
Ruben Lütke85b52cb6f68e
diff --git a/jarvis/missions/init.py b/jarvis/missions/init.pyindex c2c6ef716a..1f7043e3a0 100644--- a/jarvis/missions/init.py+++ b/jarvis/missions/init.py@@ -48,6 +48,7 @@ from .worker_runtime.provider_map import (ANTIGRAVITY_SUBAGENT_SLUGS,CODEX_SUBAGENT_SLUGS,)+from .workers.api_agent_worker import ApiAgentWorkerfrom .workers.claude_direct_worker import ClaudeDirectWorkerfrom .workers.codex_direct_worker import CodexDirectWorkerfrom .workers.gemini_worker import GeminiWorker@@ -55,6 +56,12 @@ from .workers.google_cli_worker import GoogleCliWorkerlogger = logging.getLogger(__name__)+# Pure-API providers that run on THEIR OWN provider via the in-process+# ApiAgentWorker (OpenAI-compatible chat API + tool-use loop), instead of the+# legacy silent ClaudeDirectWorker fallback. Single source for the routing+# decision so the UI "runs on Claude" badge can never drift from reality.+_API_AGENT_SLUGS: frozenset[str] = frozenset({"grok", "openai", "openrouter"})+# Type aliasesTTSSpeakFn = Callable[[str, str], Awaitable[None]]@@ -176,6 +183,14 @@ def _select_subagent_worker_kind(# stripped from the worker env (the OAuth login then bills the subscription).if sub_jarvis_provider in ANTIGRAVITY_SUBAGENT_SLUGS:return "antigravity"+ # grok / openai / openrouter run ON their own provider via the in-process+ # ApiAgentWorker (OpenAI-compatible chat API + tool-use loop writing files+ # into the worktree). Before 2026-06-22 they fell through to "subjarvis" ->+ # ClaudeDirectWorker, so picking "Grok" silently ran the mission on Claude+ # (violates the "selected provider must run" mandate). A HARD LOCK like+ # claude-api/antigravity: no per-step model can divert it.+ if sub_jarvis_provider in _API_AGENT_SLUGS:+ return "api_agent"# Explicitly selecting "gemini" routes to the direct GeminiWorker so the# sub-agent actually runs on Gemini (the user's "selected provider must run"# mandate). This is NOT the anti-silent-Gemini case (2026-05-29) — that@@ -197,16 +212,20 @@ def subagent_runs_on_claude_fallback(sub_jarvis_provider: str | None) -> bool:"""True when picking this subagent provider does NOT run heavy missions onTHAT provider but silently falls back to the ClaudeDirectWorker (Opus).- ``grok`` / ``openai`` / ``openrouter`` resolve to the legacy ``"subjarvis"``- kind, whose dedicated worker (the OpenClaw subprocess) was removed after the- ~92% nested-claude hang — so ``_worker_factory`` falls them through to the- proven direct Claude worker. The UI reads this to flag those provider cards- honestly instead of pretending the selection runs on the chosen LLM.+ As of 2026-06-22 grok/openai/openrouter resolve to the ``"api_agent"`` kind+ (the in-process ApiAgentWorker runs them on their OWN provider), so they no+ longer report a Claude fallback here — provided an API key is configured. The+ only remaining always-Claude case is the legacy ``"subjarvis"`` kind+ (openclaw-claude / unknown provider), whose dedicated OpenClaw worker was+ removed after the ~92% nested-claude hang.++ NOTE: this is the ROUTING truth, not a credential check — an api_agent+ provider with NO key still falls back to Claude at run time (``_worker_+ factory`` honest gate), which the provider card surfaces separately via its+ key-present state.Derived from the SINGLE routing source of truth (``_select_subagent_worker_- kind``) so the badge can never drift from the worker that actually runs:- the day a real grok/openrouter worker is wired, the kind stops being- ``"subjarvis"`` and this returns ``False`` automatically.+ kind``) so the badge can never drift from the worker that actually runs."""return _select_subagent_worker_kind(sub_jarvis_provider, "") == "subjarvis"@@ -639,6 +658,34 @@ async def bootstrap_missions("(agy over PTY, OAuth login, no API key) — billed against Antigravity.")return GoogleCliWorker()+ if kind == "api_agent":+ # grok / openai / openrouter: run ON the selected provider via the+ # in-process ApiAgentWorker. Honest credential gate — if no API key+ # is configured the provider CANNOT run, so fall back to Claude Max+ # (mission still completes) instead of spawning a guaranteed-fail+ # worker (e.g. openai/openrouter with no key).+ provider = live_provider or ""+ try:+ from jarvis.core import config as _cfg++ ep = _cfg.resolve_provider_endpoint(provider, vendor_default_base_url="")+ has_key = bool(getattr(ep, "credential", None))+ except Exception: # noqa: BLE001 — any resolve failure => no usable key+ has_key = False+ if has_key:+ logger.info(+ "Mission worker -> ApiAgentWorker on %r (in-process tool-use "+ "loop over the provider's own API, writes files in the worktree).",+ provider,+ )+ return ApiAgentWorker(provider)+ logger.warning(+ "Mission worker -> ClaudeDirectWorker: subagent provider %r has no "+ "API key configured, so it cannot run — completing on Claude Max "+ "instead of failing the mission.",+ provider,+ )+ return ClaudeDirectWorker(mcp_servers=_assemble_worker_mcp_servers())if kind == "gemini":# Reached when [brain.sub_jarvis].provider == "gemini" was selected# (the user's "selected provider must run" mandate) OR, legacy, whendiff --git a/jarvis/missions/workers/api_agent_tools.py b/jarvis/missions/workers/api_agent_tools.pynew file mode 100644index 0000000000..7d5ccdaf2c--- /dev/null+++ b/jarvis/missions/workers/api_agent_tools.py@@ -0,0 +1,212 @@+"""Worktree-scoped file/shell tools for the in-process API-agent worker.++These are the hands of :class:`ApiAgentWorker` — the worker that drives an+OpenAI-compatible brain (grok / openai / openrouter) in a tool-use loop. The+CLI workers (claude / codex / agy) get Write/Edit/Read/Bash from their own+binary; an in-process brain has none, so we supply a minimal, deliberately+small set here.++Security model: every path is resolved INSIDE the per-mission git worktree and+rejected if it escapes (``..`` / absolute path outside the tree). The worker is+already isolated in a worktree + Job Object (AD-OE4), so these tools run with no+risk-tier confirmation — but they must never let the model touch the user's real+tree. Tool names match the claude-CLI vocabulary (Write/Edit/Read/Bash/Ls) so+the Critic's evidence extractors (`stream_evidence._WRITE_TOOL_NAMES`,+`_SHELL_TOOL_NAMES`) credit them with zero changes.+"""+from __future__ import annotations++import subprocess+from pathlib import Path+from typing import Any++from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS++# Anthropic-style tool specs (name / description / input_schema). `_openai_base.+# _tools_openai_format` translates these to OpenAI function specs, so the same+# list works for grok / openai / openrouter.+WORKER_TOOL_SPECS: tuple[dict[str, Any], ...] = (+ {+ "name": "Write",+ "description": (+ "Create or overwrite a file in the workspace with the given content. "+ "Use a path relative to the workspace root."+ ),+ "input_schema": {+ "type": "object",+ "properties": {+ "file_path": {"type": "string", "description": "Path relative to workspace root."},+ "content": {"type": "string", "description": "Full file content to write."},+ },+ "required": ["file_path", "content"],+ },+ },+ {+ "name": "Read",+ "description": "Read a file from the workspace and return its text content.",+ "input_schema": {+ "type": "object",+ "properties": {+ "file_path": {"type": "string", "description": "Path relative to workspace root."},+ },+ "required": ["file_path"],+ },+ },+ {+ "name": "Edit",+ "description": (+ "Replace the first occurrence of old_string with new_string in a file. "+ "old_string must match exactly and be unique enough to identify the spot."+ ),+ "input_schema": {+ "type": "object",+ "properties": {+ "file_path": {"type": "string"},+ "old_string": {"type": "string"},+ "new_string": {"type": "string"},+ },+ "required": ["file_path", "old_string", "new_string"],+ },+ },+ {+ "name": "Bash",+ "description": (+ "Run a shell command in the workspace directory and return stdout+stderr. "+ "Use for builds, tests, listing files, git, etc."+ ),+ "input_schema": {+ "type": "object",+ "properties": {+ "command": {"type": "string"},+ "timeout_s": {"type": "number", "description": "Optional timeout (default 120)."},+ },+ "required": ["command"],+ },+ },+ {+ "name": "Ls",+ "description": "List the files and directories at a workspace path (default: root).",+ "input_schema": {+ "type": "object",+ "properties": {"path": {"type": "string", "description": "Relative path, default '.'"}},+ "required": [],+ },+ },+)++_MAX_READ_CHARS = 60_000+_MAX_OUTPUT_CHARS = 16_000+_DEFAULT_BASH_TIMEOUT = 120.0+++class WorktreeEscapeError(ValueError):+ """Raised when a tool path resolves outside the worktree."""+++def _safe_path(worktree: Path, rel: str) -> Path:+ """Resolve ``rel`` inside ``worktree``; reject any escape.++ Absolute paths and ``..`` traversals that land outside the tree raise+ :class:`WorktreeEscapeError`. An absolute path that already points INSIDE+ the worktree is allowed (the model sometimes echoes the full cwd path).+ """+ root = worktree.resolve()+ candidate = Path(rel)+ target = candidate if candidate.is_absolute() else root / candidate+ target = target.resolve()+ if target != root and root not in target.parents:+ raise WorktreeEscapeError(f"path escapes the workspace: {rel!r}")+ return target+++def execute_worker_tool(+ name: str, tool_input: dict[str, Any], *, worktree: Path+) -> tuple[str, bool]:+ """Execute one worker tool. Returns ``(result_text, is_error)``.++ Never raises — every failure (bad args, escape, OS error, non-zero command)+ comes back as ``(message, True)`` so the loop can feed it to the brain as a+ tool_result and let it correct course.+ """+ try:+ if name == "Write":+ path = _safe_path(worktree, str(tool_input["file_path"]))+ path.parent.mkdir(parents=True, exist_ok=True)+ content = str(tool_input.get("content", ""))+ path.write_text(content, encoding="utf-8")+ return (f"Wrote {len(content)} chars to {tool_input['file_path']}", False)++ if name == "Read":+ path = _safe_path(worktree, str(tool_input["file_path"]))+ if not path.is_file():+ return (f"File not found: {tool_input['file_path']}", True)+ text = path.read_text(encoding="utf-8", errors="replace")+ return (text[:_MAX_READ_CHARS], False)++ if name == "Edit":+ path = _safe_path(worktree, str(tool_input["file_path"]))+ if not path.is_file():+ return (f"File not found: {tool_input['file_path']}", True)+ text = path.read_text(encoding="utf-8", errors="replace")+ old = str(tool_input["old_string"])+ new = str(tool_input["new_string"])+ if old not in text:+ return ("old_string not found in file; nothing changed.", True)+ path.write_text(text.replace(old, new, 1), encoding="utf-8")+ return (f"Edited {tool_input['file_path']}", False)++ if name == "Bash":+ command = str(tool_input["command"])+ timeout_s = float(tool_input.get("timeout_s") or _DEFAULT_BASH_TIMEOUT)+ proc = subprocess.run( # noqa: S602 — a Bash tool intentionally runs shell commands; the worker is sandboxed in a worktree + Job Object+ command,+ shell=True,+ cwd=str(worktree),+ capture_output=True,+ text=True,+ timeout=timeout_s,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ out = (proc.stdout or "") + (proc.stderr or "")+ out = out[:_MAX_OUTPUT_CHARS]+ is_error = proc.returncode != 0+ tag = "" if not is_error else f"[exit {proc.returncode}] "+ return (f"{tag}{out}".strip() or "(no output)", is_error)++ if name == "Ls":+ path = _safe_path(worktree, str(tool_input.get("path") or "."))+ if not path.exists():+ return (f"Path not found: {tool_input.get('path', '.')}", True)+ if path.is_file():+ return (path.name, False)+ entries = sorted(+ (e.name + ("/" if e.is_dir() else "")) for e in path.iterdir()+ )+ return ("\n".join(entries) or "(empty)", False)++ return (f"Unknown tool: {name}", True)++ except WorktreeEscapeError as exc:+ return (str(exc), True)+ except subprocess.TimeoutExpired:+ return (f"Command timed out after {_DEFAULT_BASH_TIMEOUT:.0f}s", True)+ except KeyError as exc:+ return (f"Missing required argument: {exc}", True)+ except OSError as exc:+ return (f"OS error: {exc}", True)+++_WRITE_TOOLS = frozenset({"Write", "Edit"})+++def tool_writes_file(name: str) -> bool:+ """True if a successful call to this tool materialises a worktree file."""+ return name in _WRITE_TOOLS+++__all__ = [+ "WORKER_TOOL_SPECS",+ "WorktreeEscapeError",+ "execute_worker_tool",+ "tool_writes_file",+]diff --git a/jarvis/missions/workers/api_agent_worker.py b/jarvis/missions/workers/api_agent_worker.pynew file mode 100644index 0000000000..b23ea8a6fd--- /dev/null+++ b/jarvis/missions/workers/api_agent_worker.py@@ -0,0 +1,279 @@+"""ApiAgentWorker — an in-process agentic Phase-6 worker for API brains.++The CLI workers (claude / codex / agy) wrap a vendor binary that ships its own+agent loop + file tools. The pure-API providers — **grok**, **openai**,+**openrouter** — have no such CLI, so picking them as the subagent provider used+to fall through to the Claude worker ("Grok" silently ran on Claude). This worker+closes that gap: it drives the selected provider's own chat API+(`jarvis.plugins.brain.*`) in a tool-use loop, writing real files into the git+worktree via :mod:`api_agent_tools`, and emits the same claude-shaped stream the+Kontrollierer + Critic already read (so NO orchestrator change is needed).++Provider-agnostic by design (multi-provider mandate / AP-21): the provider slug+selects the Brain class via a capability-style map; nothing branches on a model+id. A missing API key degrades to a clean error result so the orchestrator's+fallback chain takes over instead of crashing.++Isolation note: unlike the subprocess workers this runs IN the app event loop —+there is no child PID to hand the Job Object, so ``job`` is accepted but unused;+the only spawned processes are short-lived ``Bash`` tool subprocesses (run off+the loop via ``run_in_executor`` so the voice pipeline never blocks). Cancel is+honored cooperatively at each turn boundary.+"""+from __future__ import annotations++import asyncio+import json+import logging+import time+import uuid+from collections.abc import AsyncIterator+from contextlib import suppress+from pathlib import Path+from typing import Any, Literal++from jarvis.core.protocols import BrainMessage, BrainRequest++from .api_agent_tools import WORKER_TOOL_SPECS, execute_worker_tool+from .stream_consumer import (+ ClaudeAssistantMessage,+ ClaudeResult,+ ClaudeSystemInit,+ ClaudeUserMessage,+)++logger = logging.getLogger(__name__)++# Provider slug -> (module, class). Lazy-imported so a worker for one provider+# never imports another's SDK path. Slugs match jarvis provider ids.+_BRAIN_BY_PROVIDER: dict[str, tuple[str, str]] = {+ "grok": ("jarvis.plugins.brain.grok", "GrokBrain"),+ "openai": ("jarvis.plugins.brain.openai", "OpenAIBrain"),+ "openrouter": ("jarvis.plugins.brain.openrouter", "OpenRouterBrain"),+}++# Per-provider default deep model when the step carries none. Documented+# defaults only — never a gate (AP-21).+_DEFAULT_MODEL: dict[str, str] = {+ "grok": "grok-4.3",+ "openai": "gpt-5.5",+ "openrouter": "anthropic/claude-opus-4.8",+}++_WORKER_TIMEOUT_S: float = 1200.0 # 20 min hard cap, mirrors the other workers+_MAX_TURNS: int = 25+_MAX_TOKENS: int = 8192++_SYSTEM_PROMPT = (+ "You are an autonomous software worker running inside an isolated git "+ "workspace. Your ONLY way to deliver work is to call the provided tools — "+ "Write, Edit, Read, Bash, Ls — with paths relative to the workspace root. "+ "Actually CREATE and EDIT the files the task needs; never just describe what "+ "you would do (a text description is not a deliverable and will be rejected). "+ "Work autonomously without asking questions: if a detail is unspecified, pick "+ "a sensible default and build the finished artefact. When the task is fully "+ "done, reply with a one-line summary and stop calling tools."+)+++def supports_api_agent_worker(provider: str | None) -> bool:+ """True if ``provider`` has an in-process API-agent worker."""+ return (provider or "").strip().lower() in _BRAIN_BY_PROVIDER+++def _build_brain(provider: str, model: str) -> Any:+ mod_name, cls_name = _BRAIN_BY_PROVIDER[provider]+ mod = __import__(mod_name, fromlist=[cls_name])+ return getattr(mod, cls_name)(model=model)+++class ApiAgentWorker:+ """Phase-6 worker that drives an OpenAI-compatible API brain in a tool loop.++ ``cli`` is declared ``"claude"`` so the telemetry schema needs no migration;+ the synthetic init event's ``model`` field carries ``<provider>/<model>`` so+ debugging stays unambiguous.+ """++ cli: Literal["claude"] = "claude"++ def __init__(self, provider: str) -> None:+ self.provider = (provider or "").strip().lower()+ self.last_pid: int | None = None+ self.last_session_id: str | None = None++ async def spawn(+ self,+ prompt: str,+ *,+ worktree: Path,+ env: dict[str, str], # noqa: ARG002 — in-process brain reads creds via cfg+ job: Any, # noqa: ARG002 — no child PID to assign (in-process)+ worker_id: str,+ log_dir: Path,+ model: str = "",+ max_turns: int = _MAX_TURNS,+ **_unused: Any,+ ) -> AsyncIterator[Any]:+ session_id = str(uuid.uuid4())+ self.last_session_id = session_id+ resolved_model = model or _DEFAULT_MODEL.get(self.provider, "")+ log_dir.mkdir(parents=True, exist_ok=True) # noqa: ASYNC240 — trivial sync mkdir (mirrors sibling workers)+ stream_path = log_dir / "stream.jsonl"+ written: list[str] = []++ def _emit_line(event: Any) -> None:+ with suppress(OSError):+ with stream_path.open("a", encoding="utf-8") as fh:+ fh.write(json.dumps(event.model_dump(), default=str) + "\n")++ init = ClaudeSystemInit(+ session_id=session_id,+ model=f"{self.provider}/{resolved_model}",+ tools=[t["name"] for t in WORKER_TOOL_SPECS],+ cwd=str(worktree),+ )+ _emit_line(init)+ yield init++ # Build the brain (provider-agnostic). A missing key / unknown provider+ # → clean error result so the orchestrator's fallback chain takes over.+ try:+ if self.provider not in _BRAIN_BY_PROVIDER:+ raise RuntimeError(f"no API-agent worker for provider {self.provider!r}")+ brain = _build_brain(self.provider, resolved_model)+ except Exception as exc: # noqa: BLE001+ res = ClaudeResult(+ subtype="error_during_execution", is_error=True, session_id=session_id,+ duration_ms=0, result=f"ApiAgentWorker init failed: {exc}",+ )+ _emit_line(res)+ yield res+ return++ logger.info(+ "ApiAgentWorker[%s] spawn in-process: provider=%s model=%s cwd=%s",+ worker_id, self.provider, resolved_model, worktree,+ )++ messages: list[BrainMessage] = [BrainMessage(role="user", content=prompt)]+ loop = asyncio.get_running_loop()+ t0 = time.perf_counter()+ final_text = ""+ turns = 0++ try:+ for turn in range(max_turns):+ if time.perf_counter() - t0 > _WORKER_TIMEOUT_S:+ res = ClaudeResult(+ subtype="error_during_execution", is_error=True,+ session_id=session_id, timed_out=True,+ duration_ms=int((time.perf_counter() - t0) * 1000),+ result=f"{final_text}\n[timeout after {_WORKER_TIMEOUT_S:.0f}s]".strip(),+ )+ _emit_line(res)+ yield res+ return++ turns = turn + 1+ req = BrainRequest(+ messages=tuple(messages),+ tools=WORKER_TOOL_SPECS,+ system=_SYSTEM_PROMPT,+ max_tokens=_MAX_TOKENS,+ stream=True,+ )+ text_parts: list[str] = []+ tool_calls: list[dict[str, Any]] = []+ async for delta in brain.complete(req):+ if delta.content:+ text_parts.append(delta.content)+ if delta.tool_call:+ tool_calls.append(delta.tool_call)++ assistant_text = "".join(text_parts).strip()+ if assistant_text:+ final_text = assistant_text++ content_blocks: list[dict[str, Any]] = []+ if assistant_text:+ content_blocks.append({"type": "text", "text": assistant_text})+ for tc in tool_calls:+ content_blocks.append({+ "type": "tool_use",+ "id": str(tc.get("id") or uuid.uuid4().hex),+ "name": str(tc.get("name") or ""),+ "input": tc.get("input") or {},+ })+ assistant_event = ClaudeAssistantMessage(+ message={"role": "assistant", "content": content_blocks},+ session_id=session_id,+ )+ _emit_line(assistant_event)+ yield assistant_event++ if not tool_calls:+ break # model finished — no more tool calls++ messages.append(BrainMessage(role="assistant", content=content_blocks))++ # Execute each tool call off the event loop, emit tool_result.+ result_blocks: list[dict[str, Any]] = []+ for block in content_blocks:+ if block.get("type") != "tool_use":+ continue+ name = block["name"]+ tool_input = block["input"] if isinstance(block["input"], dict) else {}+ result_text, is_error = await loop.run_in_executor(+ None,+ lambda n=name, i=tool_input: execute_worker_tool(+ n, i, worktree=worktree+ ),+ )+ if name in ("Write", "Edit") and not is_error:+ fp = str(tool_input.get("file_path", ""))+ if fp:+ written.append(fp)+ result_blocks.append({+ "type": "tool_result",+ "tool_use_id": block["id"],+ "content": result_text,+ "is_error": is_error,+ })+ messages.append(BrainMessage(+ role="tool", content=result_text, tool_call_id=block["id"], name=name,+ ))++ user_event = ClaudeUserMessage(+ message={"role": "user", "content": result_blocks},+ session_id=session_id,+ )+ _emit_line(user_event)+ yield user_event++ wall_ms = int((time.perf_counter() - t0) * 1000)+ summary = final_text or (+ f"Completed {len(written)} file change(s): {', '.join(written[:10])}"+ if written else "Worker finished with no output."+ )+ res = ClaudeResult(+ subtype="success", is_error=False, session_id=session_id,+ num_turns=turns, duration_ms=wall_ms, result=summary[:4000],+ )+ _emit_line(res)+ yield res+ except asyncio.CancelledError:+ raise+ except Exception as exc: # noqa: BLE001+ wall_ms = int((time.perf_counter() - t0) * 1000)+ logger.warning("ApiAgentWorker[%s] failed: %s", worker_id, exc, exc_info=True)+ res = ClaudeResult(+ subtype="error_during_execution", is_error=True, session_id=session_id,+ num_turns=turns, duration_ms=wall_ms,+ result=f"{final_text}\n[worker error: {exc}]".strip(),+ )+ _emit_line(res)+ yield res+++__all__ = ["ApiAgentWorker", "supports_api_agent_worker"]diff --git a/tests/missions/test_subagent_worker_routing.py b/tests/missions/test_subagent_worker_routing.pyindex 778b3d2c0f..67e06ffae1 100644--- a/tests/missions/test_subagent_worker_routing.py+++ b/tests/missions/test_subagent_worker_routing.py@@ -42,10 +42,24 @@ def test_codex_providers_route_codex(provider: str) -> None:@pytest.mark.parametrize("provider", ["grok", "openai", "openrouter"])-def test_other_providers_route_subjarvis(provider: str) -> None:- """Even with a gemini step model, a non-empty provider goes via OpenClaw,- never directly to the Gemini API worker."""- assert _select_subagent_worker_kind(provider, "gemini-3.1-pro") == "subjarvis"[email protected]("step_model", ["", "gemini-3.1-pro", "sonnet", "claude-opus-4-8"])+def test_api_agent_providers_route_to_api_agent(provider: str, step_model: str) -> None:+ """grok/openai/openrouter run ON their own provider via the in-process+ ApiAgentWorker (2026-06-22). A HARD LOCK like claude-api/antigravity: no step+ model can divert them — and they must NOT silently route to Claude (subjarvis)+ or to the Gemini API worker. The credential gate (no key -> Claude) lives in+ the worker factory, not in this pure routing decision."""+ assert _select_subagent_worker_kind(provider, step_model) == "api_agent"+++def test_api_agent_providers_are_not_a_claude_fallback() -> None:+ """The UI badge must stop pretending grok/openai/openrouter run on Claude."""+ from jarvis.missions.init import subagent_runs_on_claude_fallback++ for provider in ("grok", "openai", "openrouter"):+ assert subagent_runs_on_claude_fallback(provider) is False+ # the genuine always-Claude case stays True+ assert subagent_runs_on_claude_fallback("openclaw-claude") is True@pytest.mark.parametrize("step_model", ["", "claude-opus-4-8", "gemini-3.1-pro"])@@ -172,19 +186,27 @@ def test_live_provider_survives_registry_refresh_failure(monkeypatch: pytest.Mon# --- Honesty surface: which selections silently fall back to Claude ----------#-# grok / openai / openrouter map to the removed-OpenClaw ``"subjarvis"`` kind,-# so picking them runs the ClaudeDirectWorker (Opus) — NOT the picked provider.-# The UI reads ``subagent_runs_on_claude_fallback`` (derived from the SAME-# routing function) to flag those cards instead of silently lying.+# As of 2026-06-22 grok/openai/openrouter run on their OWN provider via the+# in-process ApiAgentWorker, so they are NO LONGER routing-level Claude+# fallbacks. Only the legacy ``"subjarvis"`` kind (openclaw-claude / unknown)+# still always runs Claude. The UI reads ``subagent_runs_on_claude_fallback``+# (derived from the SAME routing function) so the badge never lies.[email protected]("provider", ["grok", "openai", "openrouter"])-def test_fallback_providers_flagged_as_claude(provider: str) -> None:[email protected]("provider", ["openclaw-claude"])+def test_subjarvis_kind_flagged_as_claude(provider: str) -> None:from jarvis.missions.init import subagent_runs_on_claude_fallbackassert subagent_runs_on_claude_fallback(provider) is True[email protected]("provider", ["grok", "openai", "openrouter"])+def test_api_agent_providers_no_longer_flagged_as_claude(provider: str) -> None:+ from jarvis.missions.init import subagent_runs_on_claude_fallback++ assert subagent_runs_on_claude_fallback(provider) is False++@pytest.mark.parametrize("provider", ["openai-codex", "chatgpt", "gemini", "claude-api", "antigravity"])diff --git a/tests/missions/workers/test_api_agent_tools.py b/tests/missions/workers/test_api_agent_tools.pynew file mode 100644index 0000000000..80d6955cdc--- /dev/null+++ b/tests/missions/workers/test_api_agent_tools.py@@ -0,0 +1,97 @@+"""Tests for the worktree-scoped tools of the in-process API-agent worker."""+from __future__ import annotations++from pathlib import Path++from jarvis.missions.workers.api_agent_tools import (+ WORKER_TOOL_SPECS,+ execute_worker_tool,+ tool_writes_file,+)+++def test_specs_cover_the_core_tools() -> None:+ names = {t["name"] for t in WORKER_TOOL_SPECS}+ assert names == {"Write", "Read", "Edit", "Bash", "Ls"}+ # every spec is OpenAI/Anthropic-translatable+ for t in WORKER_TOOL_SPECS:+ assert t["description"]+ assert t["input_schema"]["type"] == "object"+++def test_write_then_read_roundtrip(tmp_path: Path) -> None:+ out, err = execute_worker_tool("Write", {"file_path": "a/b.txt", "content": "hi"}, worktree=tmp_path)+ assert err is False+ assert (tmp_path / "a" / "b.txt").read_text(encoding="utf-8") == "hi"+ out, err = execute_worker_tool("Read", {"file_path": "a/b.txt"}, worktree=tmp_path)+ assert err is False and out == "hi"+++def test_edit_replaces_first_occurrence(tmp_path: Path) -> None:+ (tmp_path / "f.txt").write_text("foo bar foo", encoding="utf-8")+ out, err = execute_worker_tool(+ "Edit", {"file_path": "f.txt", "old_string": "foo", "new_string": "X"}, worktree=tmp_path+ )+ assert err is False+ assert (tmp_path / "f.txt").read_text(encoding="utf-8") == "X bar foo"+++def test_edit_missing_old_string_is_error(tmp_path: Path) -> None:+ (tmp_path / "f.txt").write_text("abc", encoding="utf-8")+ out, err = execute_worker_tool(+ "Edit", {"file_path": "f.txt", "old_string": "zzz", "new_string": "X"}, worktree=tmp_path+ )+ assert err is True+ assert (tmp_path / "f.txt").read_text(encoding="utf-8") == "abc" # unchanged+++def test_read_missing_file_is_error(tmp_path: Path) -> None:+ out, err = execute_worker_tool("Read", {"file_path": "nope.txt"}, worktree=tmp_path)+ assert err is True+++def test_ls_lists_entries(tmp_path: Path) -> None:+ (tmp_path / "x.txt").write_text("1", encoding="utf-8")+ (tmp_path / "sub").mkdir()+ out, err = execute_worker_tool("Ls", {}, worktree=tmp_path)+ assert err is False+ assert "x.txt" in out and "sub/" in out+++def test_bash_runs_in_worktree(tmp_path: Path) -> None:+ out, err = execute_worker_tool("Bash", {"command": "echo hello-from-bash"}, worktree=tmp_path)+ assert err is False+ assert "hello-from-bash" in out+++def test_bash_nonzero_exit_is_error(tmp_path: Path) -> None:+ out, err = execute_worker_tool("Bash", {"command": "exit 3"}, worktree=tmp_path)+ assert err is True+ assert "exit 3" in out+++def test_path_escape_is_rejected_on_write(tmp_path: Path) -> None:+ """The model must never write outside the worktree (../ escape)."""+ out, err = execute_worker_tool(+ "Write", {"file_path": "../escape.txt", "content": "x"}, worktree=tmp_path+ )+ assert err is True+ assert "escape" in out.lower()+ assert not (tmp_path.parent / "escape.txt").exists()+++def test_absolute_path_outside_worktree_rejected(tmp_path: Path) -> None:+ out, err = execute_worker_tool(+ "Write", {"file_path": str(tmp_path.parent / "x.txt"), "content": "x"}, worktree=tmp_path+ )+ assert err is True+++def test_unknown_tool_is_error(tmp_path: Path) -> None:+ out, err = execute_worker_tool("Frobnicate", {}, worktree=tmp_path)+ assert err is True+++def test_tool_writes_file_predicate() -> None:+ assert tool_writes_file("Write") and tool_writes_file("Edit")+ assert not tool_writes_file("Read") and not tool_writes_file("Bash")diff --git a/tests/missions/workers/test_api_agent_worker.py b/tests/missions/workers/test_api_agent_worker.pynew file mode 100644index 0000000000..9a6fa6b6cd--- /dev/null+++ b/tests/missions/workers/test_api_agent_worker.py@@ -0,0 +1,154 @@+"""Tests for ApiAgentWorker — the in-process agentic worker for grok/openai/+openrouter. Uses a scripted FakeBrain so no network call is made; the real+provider is exercised by the live probe, not the unit suite."""+from __future__ import annotations++import json+from collections.abc import AsyncIterator+from pathlib import Path++import pytest++from jarvis.core.protocols import BrainDelta, BrainRequest+from jarvis.missions.stream_evidence import extract_write_targets+from jarvis.missions.workers.api_agent_worker import (+ ApiAgentWorker,+ supports_api_agent_worker,+)+++class FakeBrain:+ """Yields a scripted sequence of BrainDelta lists, one per complete() turn."""++ def __init__(self, turns: list[list[BrainDelta]]) -> None:+ self._turns = turns+ self.calls = 0+ self.seen_tools: list[str] = []++ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:+ # record that the worker passed the tool specs through+ self.seen_tools = [t["name"] for t in req.tools]+ turn = self._turns[min(self.calls, len(self._turns) - 1)]+ self.calls += 1+ for d in turn:+ yield d+++def _patch_brain(monkeypatch: pytest.MonkeyPatch, brain: FakeBrain) -> None:+ monkeypatch.setattr(+ "jarvis.missions.workers.api_agent_worker._build_brain",+ lambda provider, model: brain,+ )+++async def _drain(worker: ApiAgentWorker, **kw): # noqa: ANN003+ events = []+ async for ev in worker.spawn(**kw):+ events.append(ev)+ return events+++def test_supports_api_agent_worker() -> None:+ assert supports_api_agent_worker("grok")+ assert supports_api_agent_worker("openai")+ assert supports_api_agent_worker("openrouter")+ assert not supports_api_agent_worker("claude-api")+ assert not supports_api_agent_worker("antigravity")+ assert not supports_api_agent_worker(None)+++async def test_worker_writes_file_and_emits_critic_readable_stream(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """A Write tool_call is executed (real file on disk), the frames are emitted+ in the claude shape, and the stream.jsonl is credited by extract_write_targets."""+ turns = [+ # turn 0: model asks to Write a file+ [+ BrainDelta(tool_call={"id": "c1", "name": "Write",+ "input": {"file_path": "out.txt", "content": "RESULT"}}),+ BrainDelta(finish_reason="tool_use"),+ ],+ # turn 1: model is satisfied, finishes with text, no tool_call+ [BrainDelta(content="Created out.txt."), BrainDelta(finish_reason="end_turn")],+ ]+ fake = FakeBrain(turns)+ _patch_brain(monkeypatch, fake)+ worker = ApiAgentWorker("grok")+ log_dir = tmp_path / "_logs"++ events = await _drain(+ worker, prompt="make out.txt", worktree=tmp_path, env={}, job=None,+ worker_id="m::0", log_dir=log_dir, model="grok-4.3",+ )++ kinds = [type(e).__name__ for e in events]+ assert kinds[0] == "ClaudeSystemInit"+ assert kinds[-1] == "ClaudeResult"+ assert "ClaudeAssistantMessage" in kinds and "ClaudeUserMessage" in kinds+ # the worker forwarded the worker tool specs to the brain+ assert "Write" in fake.seen_tools and "Bash" in fake.seen_tools+ # GROUND TRUTH: the file is really on disk+ assert (tmp_path / "out.txt").read_text(encoding="utf-8") == "RESULT"+ # terminal result is success+ result = events[-1]+ assert result.is_error is False+ # stream.jsonl is Critic-readable: the write is credited+ stream_text = (log_dir / "stream.jsonl").read_text(encoding="utf-8")+ assert "out.txt" in extract_write_targets(stream_text)+++async def test_worker_tool_error_is_fed_back_not_fatal(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """A failing tool_call (read missing file) becomes a tool_result with+ is_error, the loop continues, and the worker still finishes."""+ turns = [+ [BrainDelta(tool_call={"id": "c1", "name": "Read", "input": {"file_path": "nope.txt"}}),+ BrainDelta(finish_reason="tool_use")],+ [BrainDelta(content="Could not read; done."), BrainDelta(finish_reason="end_turn")],+ ]+ _patch_brain(monkeypatch, FakeBrain(turns))+ worker = ApiAgentWorker("grok")+ events = await _drain(+ worker, prompt="x", worktree=tmp_path, env={}, job=None,+ worker_id="m::0", log_dir=tmp_path / "_logs",+ )+ user_msgs = [e for e in events if type(e).__name__ == "ClaudeUserMessage"]+ assert user_msgs+ block = user_msgs[0].message["content"][0]+ assert block["type"] == "tool_result" and block["is_error"] is True+ assert events[-1].is_error is False # mission still finishes+++async def test_unknown_provider_returns_clean_error(tmp_path: Path) -> None:+ """An unsupported provider yields an error ClaudeResult (so the orchestrator+ can fall back) instead of raising."""+ worker = ApiAgentWorker("definitely-not-a-provider")+ events = await _drain(+ worker, prompt="x", worktree=tmp_path, env={}, job=None,+ worker_id="m::0", log_dir=tmp_path / "_logs",+ )+ assert events[-1].is_error is True+++async def test_stream_jsonl_is_valid_ndjson(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ turns = [+ [BrainDelta(tool_call={"id": "c1", "name": "Write",+ "input": {"file_path": "a.txt", "content": "x"}}),+ BrainDelta(finish_reason="tool_use")],+ [BrainDelta(content="done"), BrainDelta(finish_reason="end_turn")],+ ]+ _patch_brain(monkeypatch, FakeBrain(turns))+ worker = ApiAgentWorker("grok")+ log_dir = tmp_path / "_logs"+ await _drain(worker, prompt="x", worktree=tmp_path, env={}, job=None,+ worker_id="m::0", log_dir=log_dir)+ for line in (log_dir / "stream.jsonl").read_text(encoding="utf-8").splitlines():+ json.loads(line) # every line is valid JSON