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.

fix(missions): contain portable API worker commands

Ruben Lütkef41501fe80ae
diff --git a/jarvis/missions/isolation/job_object.py b/jarvis/missions/isolation/job_object.py
index 7dc2b524c0..27eae826e2 100644
--- a/jarvis/missions/isolation/job_object.py
+++ b/jarvis/missions/isolation/job_object.py
@@ -1,8 +1,9 @@
"""Windows Job Object wrapper for worker subprocess reaping.
ADR-0009 §3 + Research-Doc §C: every worker subprocess is assigned to a
-per-mission Windows Job Object with the limit flags
-`JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_BREAKAWAY_OK`.
+per-mission Windows Job Object with `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`.
+Long-running mission-worker jobs allow explicit child breakaway; strict local
+command jobs disable breakaway so their descendants cannot detach.
When the orchestrator crashes (or closes the handle), the OS atomically
reaps the entire descendant tree of the mission — no zombies, no orphans.
@@ -18,10 +19,12 @@ with SIGTERM→SIGKILL on close (workers are spawned with `start_new_session=Tru
from __future__ import annotations
import asyncio
+import ctypes
import logging
import os
import signal
import sys
+from ctypes import wintypes
from types import TracebackType
from typing import Any
@@ -35,10 +38,11 @@ _SIGKILL = getattr(signal, "SIGKILL", 9)
class _NoOpJobObject:
- """No-op implementation for non-Windows platforms.
+ """Explicit no-op used by tests and last-resort Windows degradation.
- Exposes the same API as `WindowsJobObject` but does nothing, so
- Linux CI and unit tests can run without pywin32 or Windows.
+ Normal POSIX runs use ``_PosixProcessGroupJobObject``. API-worker local
+ commands detect this no-op through ``handle is None`` and fail closed before
+ starting a Windows target.
"""
def __init__(self, name: str | None = None) -> None:
@@ -53,7 +57,7 @@ class _NoOpJobObject:
def handle(self) -> Any: # noqa: ANN401 — opaque on purpose
return None
- async def __aenter__(self) -> "_NoOpJobObject":
+ async def __aenter__(self) -> _NoOpJobObject:
return self
async def __aexit__(
@@ -65,9 +69,9 @@ class _NoOpJobObject:
await self.close()
def assign(self, pid: int) -> None:
- # Non-Windows has no Job Objects — we only log; the Win32 test
- # verifies real semantics via psutil.
- logger.debug("NoOpJobObject.assign(pid=%d) — no-op (non-Windows)", pid)
+ # This explicit test/degradation implementation deliberately records
+ # no ownership. Security-sensitive callers must reject ``handle=None``.
+ logger.debug("NoOpJobObject.assign(pid=%d) — no-op", pid)
async def close(self) -> None:
self._closed = True
@@ -79,13 +83,14 @@ class _Win32JobObjectImpl:
Limit flags:
- `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`: closing the last handle kills all
assigned processes atomically, even on orchestrator crash.
- - `JOB_OBJECT_LIMIT_BREAKAWAY_OK`: allows children to detach from the job
- when spawned with `CREATE_BREAKAWAY_FROM_JOB`. This is needed so a
- worker subprocess (itself a job member) can still be explicitly assigned
- without inheritance (pattern from Research-Doc §C line 167).
+ - `JOB_OBJECT_LIMIT_BREAKAWAY_OK` is optional. Mission-worker jobs enable it
+ for explicit nested ownership; strict local-command jobs disable it so a
+ descendant cannot request detachment.
"""
- def __init__(self, name: str | None = None) -> None:
+ def __init__(
+ self, name: str | None = None, *, allow_breakaway: bool = True
+ ) -> None:
# Lazy import — Windows only.
import win32job # type: ignore[import-not-found] # noqa: PLC0415
@@ -99,8 +104,11 @@ class _Win32JobObjectImpl:
)
info["BasicLimitInformation"]["LimitFlags"] |= (
win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
- | win32job.JOB_OBJECT_LIMIT_BREAKAWAY_OK
)
+ if allow_breakaway:
+ info["BasicLimitInformation"]["LimitFlags"] |= (
+ win32job.JOB_OBJECT_LIMIT_BREAKAWAY_OK
+ )
win32job.SetInformationJobObject(
self._handle, win32job.JobObjectExtendedLimitInformation, info
)
@@ -113,7 +121,7 @@ class _Win32JobObjectImpl:
def handle(self) -> Any: # noqa: ANN401
return self._handle
- async def __aenter__(self) -> "_Win32JobObjectImpl":
+ async def __aenter__(self) -> _Win32JobObjectImpl:
return self
async def __aexit__(
@@ -168,6 +176,154 @@ class _Win32JobObjectImpl:
)
+class _JobObjectBasicLimitInformation(ctypes.Structure):
+ _fields_ = [
+ ("PerProcessUserTimeLimit", ctypes.c_longlong),
+ ("PerJobUserTimeLimit", ctypes.c_longlong),
+ ("LimitFlags", wintypes.DWORD),
+ ("MinimumWorkingSetSize", ctypes.c_size_t),
+ ("MaximumWorkingSetSize", ctypes.c_size_t),
+ ("ActiveProcessLimit", wintypes.DWORD),
+ ("Affinity", ctypes.c_size_t),
+ ("PriorityClass", wintypes.DWORD),
+ ("SchedulingClass", wintypes.DWORD),
+ ]
+
+
+class _IoCounters(ctypes.Structure):
+ _fields_ = [
+ ("ReadOperationCount", ctypes.c_ulonglong),
+ ("WriteOperationCount", ctypes.c_ulonglong),
+ ("OtherOperationCount", ctypes.c_ulonglong),
+ ("ReadTransferCount", ctypes.c_ulonglong),
+ ("WriteTransferCount", ctypes.c_ulonglong),
+ ("OtherTransferCount", ctypes.c_ulonglong),
+ ]
+
+
+class _JobObjectExtendedLimitInformation(ctypes.Structure):
+ _fields_ = [
+ ("BasicLimitInformation", _JobObjectBasicLimitInformation),
+ ("IoInfo", _IoCounters),
+ ("ProcessMemoryLimit", ctypes.c_size_t),
+ ("JobMemoryLimit", ctypes.c_size_t),
+ ("PeakProcessMemoryUsed", ctypes.c_size_t),
+ ("PeakJobMemoryUsed", ctypes.c_size_t),
+ ]
+
+
+class _Win32CtypesJobObjectImpl:
+ """Dependency-free Win32 Job Object fallback for base installations.
+
+ ``pywin32`` belongs to the desktop extra, but mission process containment
+ must remain available in a base Windows install. These are stable Kernel32
+ APIs, called lazily only on Windows. The API mirrors the pywin32-backed
+ implementation exactly.
+ """
+
+ _JOB_OBJECT_EXTENDED_LIMIT_INFORMATION = 9
+ _JOB_OBJECT_LIMIT_BREAKAWAY_OK = 0x00000800
+ _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000
+ _PROCESS_TERMINATE = 0x0001
+ _PROCESS_SET_QUOTA = 0x0100
+
+ def __init__(
+ self, name: str | None = None, *, allow_breakaway: bool = True
+ ) -> None:
+ if sys.platform != "win32":
+ raise OSError("Win32 Job Objects are unavailable on this platform")
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ self._kernel32 = kernel32
+ self._closed = False
+
+ kernel32.CreateJobObjectW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR]
+ kernel32.CreateJobObjectW.restype = wintypes.HANDLE
+ kernel32.SetInformationJobObject.argtypes = [
+ wintypes.HANDLE,
+ ctypes.c_int,
+ ctypes.c_void_p,
+ wintypes.DWORD,
+ ]
+ kernel32.SetInformationJobObject.restype = wintypes.BOOL
+ kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
+ kernel32.OpenProcess.restype = wintypes.HANDLE
+ kernel32.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]
+ kernel32.AssignProcessToJobObject.restype = wintypes.BOOL
+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
+ kernel32.CloseHandle.restype = wintypes.BOOL
+
+ handle = kernel32.CreateJobObjectW(None, name or None)
+ if not handle:
+ raise ctypes.WinError(ctypes.get_last_error())
+ self._handle = handle
+ try:
+ info = _JobObjectExtendedLimitInformation()
+ info.BasicLimitInformation.LimitFlags = (
+ self._JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
+ )
+ if allow_breakaway:
+ info.BasicLimitInformation.LimitFlags |= (
+ self._JOB_OBJECT_LIMIT_BREAKAWAY_OK
+ )
+ ok = kernel32.SetInformationJobObject(
+ handle,
+ self._JOB_OBJECT_EXTENDED_LIMIT_INFORMATION,
+ ctypes.byref(info),
+ ctypes.sizeof(info),
+ )
+ if not ok:
+ raise ctypes.WinError(ctypes.get_last_error())
+ except BaseException:
+ kernel32.CloseHandle(handle)
+ self._closed = True
+ raise
+
+ @property
+ def closed(self) -> bool:
+ return self._closed
+
+ @property
+ def handle(self) -> Any: # noqa: ANN401
+ return self._handle
+
+ async def __aenter__(self) -> _Win32CtypesJobObjectImpl:
+ return self
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc: BaseException | None,
+ tb: TracebackType | None,
+ ) -> None:
+ await self.close()
+
+ def assign(self, pid: int) -> None:
+ if self._closed:
+ raise RuntimeError("WindowsJobObject is already closed")
+ process = self._kernel32.OpenProcess(
+ self._PROCESS_TERMINATE | self._PROCESS_SET_QUOTA,
+ False,
+ pid,
+ )
+ if not process:
+ raise ctypes.WinError(ctypes.get_last_error())
+ try:
+ if not self._kernel32.AssignProcessToJobObject(self._handle, process):
+ raise ctypes.WinError(ctypes.get_last_error())
+ finally:
+ self._kernel32.CloseHandle(process)
+
+ async def close(self) -> None:
+ if self._closed:
+ return
+ self._closed = True
+ if not self._kernel32.CloseHandle(self._handle):
+ logger.warning(
+ "WindowsJobObject.close() failed — handle may leak: %s",
+ ctypes.WinError(ctypes.get_last_error()),
+ )
+
+
class _PosixProcessGroupJobObject:
"""POSIX kill-on-close containment via session/process-group signalling.
@@ -228,7 +384,7 @@ class _PosixProcessGroupJobObject:
def assign(self, pid: int) -> None:
"""Record a worker's process group so ``close()`` can reap the tree."""
if self._closed:
- raise RuntimeError("PosixProcessGroupJobObject ist schon geschlossen") # noqa: E501 i18n-allow: owning session's German message; its test asserts this string
+ raise RuntimeError("PosixProcessGroupJobObject is already closed")
getpgid = self._getpgid or os.getpgid
try:
pgid = getpgid(pid)
@@ -238,6 +394,17 @@ class _PosixProcessGroupJobObject:
pgid = pid
self._pgids.add(pgid)
+ def release(self, pid: int) -> None:
+ """Forget a fully reaped short-lived group before its id can be reused.
+
+ Long-running CLI workers remain registered until mission close. The
+ in-process API worker, however, starts a fresh process group for every
+ local command and reaps it immediately. Retaining that dead numeric pgid
+ for the rest of a long mission could later signal an unrelated process
+ group after kernel id reuse.
+ """
+ self._pgids.discard(pid)
+
async def close(self) -> None:
"""SIGTERM, brief grace, then SIGKILL every recorded process group."""
if self._closed:
@@ -260,8 +427,10 @@ class _PosixProcessGroupJobObject:
)
-def WindowsJobObject(name: str | None = None) -> Any: # noqa: ANN401, N802
- """Factory: returns a real Win32 wrapper on Windows, otherwise a no-op.
+def WindowsJobObject( # noqa: ANN401, N802
+ name: str | None = None, *, allow_breakaway: bool = True
+) -> Any:
+ """Return kernel-backed Win32 containment or POSIX process-group reaping.
A function (not a class) so the mandatory constructor resolves to the
platform-appropriate implementation type. The API is identical:
@@ -271,18 +440,28 @@ def WindowsJobObject(name: str | None = None) -> Any: # noqa: ANN401, N802
job.assign(proc.pid)
... # exit kills all assigned procs
- Sentinel via `sys.platform != 'win32'` — no `os.name` polling, because
+ ``allow_breakaway=False`` creates the stricter command-job form. Sentinel
+ via `sys.platform != 'win32'` — no `os.name` polling, because
PyOxidizer/PyInstaller can set `os.name` to nt while pywin32 is absent.
"""
if sys.platform == "win32":
try:
- return _Win32JobObjectImpl(name)
- except ImportError:
- logger.warning(
- "pywin32 missing — WindowsJobObject falls back to a no-op. "
- "Worker crash reaping is NOT guaranteed."
- )
- return _NoOpJobObject(name)
+ return _Win32JobObjectImpl(name, allow_breakaway=allow_breakaway)
+ except Exception: # noqa: BLE001 - fall through to dependency-free kernel API
+ try:
+ logger.info(
+ "pywin32 Job Object setup is unavailable; using the Kernel32 "
+ "fallback",
+ exc_info=True,
+ )
+ return _Win32CtypesJobObjectImpl(
+ name, allow_breakaway=allow_breakaway
+ )
+ except (OSError, AttributeError):
+ logger.exception(
+ "Windows Job Object setup failed; process containment is unavailable"
+ )
+ return _NoOpJobObject(name)
# macOS / Linux: real session/process-group reaping (SIGTERM→SIGKILL on close).
return _PosixProcessGroupJobObject(name)
diff --git a/jarvis/missions/workers/api_agent_tools.py b/jarvis/missions/workers/api_agent_tools.py
index e99946e546..287b71bf07 100644
--- a/jarvis/missions/workers/api_agent_tools.py
+++ b/jarvis/missions/workers/api_agent_tools.py
@@ -1,26 +1,86 @@
-"""Worktree-scoped file/shell tools for the in-process API-agent worker.
+"""Worktree-scoped file and process tools for the in-process API worker.
These are the hands of :class:`ApiAgentWorker` — the worker that drives an
OpenAI-compatible brain (openai / openrouter) in a tool-use loop. The
-CLI workers (claude / codex / agy) get Write/Edit/Read/Bash from their own
+CLI workers (claude / codex / agy) get file and process tools 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.
+Safety boundary: file-tool paths are confined to the disposable mission
+worktree. RunCommand reduces accidental path escape and secret exposure by
+using structured argv, rejecting obvious wrappers/escape arguments, and giving
+the child a reduced environment with mission-scoped HOME and temporary paths.
+Cancellation, timeout, and normal completion reap the ordinary command process
+tree. Deliberately detached POSIX code remains outside this misuse guard.
+
+This is explicitly NOT a filesystem or code-execution sandbox. A workspace
+Python/Node script, test suite, compiler, or package script is arbitrary code
+running with the Jarvis OS user's rights and can access anything that user can.
+The policy is a misuse guard plus secret reduction; the controller's disposable
+worktree, process containment, and post-run diff/path review remain mandatory.
"""
from __future__ import annotations
+import asyncio
+import json
+import logging
+import os
+import re
+import shutil
import subprocess
-from pathlib import Path
+import sys
+import uuid
+from collections.abc import Callable, Mapping, Sequence
+from contextlib import suppress as contextlib_suppress
+from pathlib import Path, PureWindowsPath
from typing import Any
+from urllib.parse import urlsplit
+
+from jarvis.missions.isolation.job_object import WindowsJobObject
-from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+from .process_utils import create_worker_subprocess, resolve_node_executable
+
+logger = logging.getLogger(__name__)
+
+_WINDOWS_GATE_SCRIPT = """param(
+ [Parameter(Mandatory=$true)][string]$GatePath,
+ [Parameter(Mandatory=$true)][string]$PayloadPath
+)
+$deadline = [DateTime]::UtcNow.AddSeconds(30)
+while (-not (Test-Path -LiteralPath $GatePath -PathType Leaf)) {
+ if ([DateTime]::UtcNow -ge $deadline) {
+ Write-Error "Containment gate did not open before its deadline."
+ exit 125
+ }
+ Start-Sleep -Milliseconds 10
+}
+try {
+ $payload = Get-Content -LiteralPath $PayloadPath -Raw | ConvertFrom-Json
+ $commandArgs = @()
+ foreach ($item in $payload.arguments) { $commandArgs += [string]$item }
+ & ([string]$payload.executable) @commandArgs
+ if ($null -eq $LASTEXITCODE) { exit 1 }
+ exit [int]$LASTEXITCODE
+} catch {
+ Write-Error $_
+ exit 1
+}
+"""
+
+_POSIX_GATE_SCRIPT = """#!/bin/sh
+gate_path=$1
+shift
+gate_attempts=0
+while [ ! -f "$gate_path" ]; do
+ gate_attempts=$((gate_attempts + 1))
+ if [ "$gate_attempts" -ge 3000 ]; then
+ echo "Containment gate did not open before its deadline." >&2
+ exit 125
+ fi
+ sleep 0.01
+done
+exec "$@"
+"""
# Anthropic-style tool specs (name / description / input_schema). `_openai_base.
# _tools_openai_format` translates these to OpenAI function specs, so the same
@@ -69,18 +129,31 @@ WORKER_TOOL_SPECS: tuple[dict[str, Any], ...] = (
},
},
{
- "name": "Bash",
+ "name": "RunCommand",
"description": (
- "Run a shell command in the workspace directory and return stdout+stderr. "
- "Use for builds, tests, listing files, git, etc."
+ "Run one program directly in the workspace and return stdout and stderr. "
+ "This is not a shell: provide the executable name and each argument "
+ "separately. Shell chaining, redirection, inline code, absolute paths "
+ "outside the workspace, and parent traversal are unsupported."
),
"input_schema": {
"type": "object",
"properties": {
- "command": {"type": "string"},
- "timeout_s": {"type": "number", "description": "Optional timeout (default 120)."},
+ "program": {
+ "type": "string",
+ "description": "Executable name from PATH, without a directory.",
+ },
+ "args": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": "Argument vector. Do not combine arguments into a shell string.",
+ },
+ "timeout_s": {
+ "type": "number",
+ "description": "Optional timeout in seconds (default 120, maximum 600).",
+ },
},
- "required": ["command"],
+ "required": ["program"],
},
},
{
@@ -96,13 +169,121 @@ WORKER_TOOL_SPECS: tuple[dict[str, Any], ...] = (
_MAX_READ_CHARS = 60_000
_MAX_OUTPUT_CHARS = 16_000
-_DEFAULT_BASH_TIMEOUT = 120.0
+_DEFAULT_COMMAND_TIMEOUT = 120.0
+_MAX_COMMAND_TIMEOUT = 600.0
+_MIN_COMMAND_TIMEOUT = 0.1
+_COMMAND_STOP_GRACE_S = 0.25
+_MAX_COMMAND_ARGS = 256
+_MAX_COMMAND_ARG_CHARS = 8_192
+_MAX_COMMAND_TOTAL_CHARS = 65_536
+
+# A direct process runner has no reason to launch a shell. Blocking every common
+# spelling also keeps a model from reintroducing shell evaluation indirectly.
+_SHELL_PROGRAMS = frozenset(
+ {
+ "bash",
+ "busybox",
+ "cmd",
+ "cmd.exe",
+ "command",
+ "csh",
+ "dash",
+ "env",
+ "env.exe",
+ "fish",
+ "ksh",
+ "powershell",
+ "powershell.exe",
+ "pwsh",
+ "pwsh.exe",
+ "pythonw",
+ "pythonw.exe",
+ "sh",
+ "setsid",
+ "tcsh",
+ "wsl",
+ "wsl.exe",
+ "zsh",
+ }
+)
+
+# Inline program flags turn an interpreter into another unreviewable command
+# string. Script files and ``python -m <module>`` remain available for tests and
+# builds, but the script/module must be named explicitly in argv.
+_INLINE_PROGRAM_FLAGS: dict[str, frozenset[str]] = {
+ "node": frozenset({"-e", "--eval", "-p", "--print"}),
+ "node.exe": frozenset({"-e", "--eval", "-p", "--print"}),
+ "perl": frozenset({"-e", "-E"}),
+ "py": frozenset({"-c"}),
+ "py.exe": frozenset({"-c"}),
+ "python": frozenset({"-c"}),
+ "python.exe": frozenset({"-c"}),
+ "python3": frozenset({"-c"}),
+ "python3.exe": frozenset({"-c"}),
+ "ruby": frozenset({"-e"}),
+}
+
+_PATH_VALUE_OPTION = re.compile(
+ r"^(?:--?(?:chdir|cwd|directory|git-dir|output|prefix|root|target|work-tree))=(.*)$",
+ re.IGNORECASE,
+)
+_COMPACT_PATH_OPTION = re.compile(r"^(?:-[ILo]|/F[deo])(.+)$", re.IGNORECASE)
+
+# Only process-launch essentials cross into a local command. In particular no
+# provider/API credential, keyring selector, cloud token, or user PYTHONPATH is
+# inherited from the worker/provider environment.
+_SAFE_ENV_KEYS = frozenset(
+ {
+ "COMSPEC",
+ "CC",
+ "CXX",
+ "AR",
+ "CI",
+ "GOROOT",
+ "JAVA_HOME",
+ "LANG",
+ "LC_ALL",
+ "LIB",
+ "LIBPATH",
+ "NUMBER_OF_PROCESSORS",
+ "OS",
+ "PATH",
+ "PATHEXT",
+ "PKG_CONFIG_PATH",
+ "PROCESSOR_ARCHITECTURE",
+ "PROCESSOR_ARCHITEW6432",
+ "RUSTUP_HOME",
+ "SYSTEMDRIVE",
+ "SYSTEMROOT",
+ "TERM",
+ "TZ",
+ "VIRTUAL_ENV",
+ "WINDIR",
+ }
+)
+
+_PROXY_ENV_KEYS = frozenset({"ALL_PROXY", "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY"})
+_CA_FILE_ENV_KEYS = frozenset(
+ {
+ "CURL_CA_BUNDLE",
+ "GIT_SSL_CAINFO",
+ "NODE_EXTRA_CA_CERTS",
+ "PIP_CERT",
+ "REQUESTS_CA_BUNDLE",
+ "SSL_CERT_FILE",
+ }
+)
+_MAX_CA_BUNDLE_BYTES = 16 * 1024 * 1024
class WorktreeEscapeError(ValueError):
"""Raised when a tool path resolves outside the worktree."""
+class CommandPolicyError(ValueError):
+ """Raised when a requested process cannot cross the worker boundary."""
+
+
def _safe_path(worktree: Path, rel: str) -> Path:
"""Resolve ``rel`` inside ``worktree``; reject any escape.
@@ -119,6 +300,650 @@ def _safe_path(worktree: Path, rel: str) -> Path:
return target
+def _validate_command_path(value: str, *, worktree: Path) -> None:
+ """Reject direct and option-embedded paths that can leave ``worktree``."""
+ if not value:
+ return
+ if "\x00" in value or "\r" in value or "\n" in value:
+ raise CommandPolicyError("command arguments must not contain control lines")
+
+ candidate = value
+ option_match = _PATH_VALUE_OPTION.match(value)
+ if option_match:
+ candidate = option_match.group(1)
+ elif value.startswith("-") and "=" in value:
+ # Treat every GNU-style ``--option=/path`` value as a possible path,
+ # not only the common names above. Unknown tools invent option names.
+ candidate = value.split("=", 1)[1]
+ else:
+ compact_match = _COMPACT_PATH_OPTION.match(value)
+ if compact_match:
+ candidate = compact_match.group(1)
+
+ embedded_windows_absolute = re.search(r"(?i)(?:^|[=:])([a-z]:[\\/].*)", candidate)
+ if embedded_windows_absolute:
+ candidate = embedded_windows_absolute.group(1)
+
+ # Tilde and environment forms can be expanded by programs even without a
+ # shell. Reject path-position expansions instead of pretending they are
+ # confined to the mission workspace.
+ upper = candidate.upper()
+ if candidate.startswith("~") or upper.startswith(("$HOME", "${HOME}", "%USERPROFILE%")):
+ raise WorktreeEscapeError(f"path escapes the workspace: {value!r}")
+
+ segments = re.split(r"[\\/]", candidate)
+ if ".." in segments:
+ raise WorktreeEscapeError(f"path escapes the workspace: {value!r}")
+
+ native = Path(candidate)
+ windows = PureWindowsPath(candidate)
+ if native.is_absolute() or windows.is_absolute() or bool(windows.drive):
+ _safe_path(worktree, candidate)
+ return
+
+ # Resolve every relative token as a potential path. Harmless flags and
+ # literals simply map to a nonexistent name under the workspace, while an
+ # existing single-component symlink to a host directory is caught here.
+ _safe_path(worktree, candidate)
+
+
+def _validated_command(
+ program: Any,
+ args: Any,
+ *,
+ worktree: Path,
+) -> tuple[str, tuple[str, ...]]:
+ """Return a policy-checked executable name and argument vector."""
+ executable = str(program or "").strip()
+ if not executable:
+ raise CommandPolicyError("program must be a non-empty executable name")
+ if len(executable) > 255:
+ raise CommandPolicyError("program name is too long")
+ if any(char in executable for char in ("\x00", "\r", "\n")):
+ raise CommandPolicyError("program must not contain control lines")
+ if (
+ Path(executable).is_absolute()
+ or PureWindowsPath(executable).drive
+ or "/" in executable
+ or "\\" in executable
+ or executable in {".", ".."}
+ ):
+ raise CommandPolicyError("program must be an executable name from PATH, not a path")
+
+ normalized = executable.casefold()
+ if normalized in _SHELL_PROGRAMS:
+ raise CommandPolicyError(
+ f"unsupported command {executable!r}: shell and command-wrapper "
+ "programs are not available; "
+ "use one RunCommand call with a program and args"
+ )
+
+ if args is None:
+ argv: tuple[str, ...] = ()
+ elif (
+ isinstance(args, Sequence)
+ and not isinstance(args, (str, bytes, bytearray))
+ and all(isinstance(item, str) for item in args)
+ ):
+ argv = tuple(args)
+ else:
+ raise CommandPolicyError("args must be an array of strings")
+ if len(argv) > _MAX_COMMAND_ARGS:
+ raise CommandPolicyError(f"args must contain at most {_MAX_COMMAND_ARGS} items")
+ if any(len(arg) > _MAX_COMMAND_ARG_CHARS for arg in argv):
+ raise CommandPolicyError(
+ f"each command argument must be at most {_MAX_COMMAND_ARG_CHARS} characters"
+ )
+ if sum(len(arg) for arg in argv) > _MAX_COMMAND_TOTAL_CHARS:
+ raise CommandPolicyError(
+ f"command arguments must total at most {_MAX_COMMAND_TOTAL_CHARS} characters"
+ )
+
+ inline_flags = _INLINE_PROGRAM_FLAGS.get(normalized, frozenset())
+ if any(arg in inline_flags for arg in argv):
+ raise CommandPolicyError(
+ f"unsupported command {executable!r}: inline program text is disabled; "
+ "run a workspace script or module instead"
+ )
+ command_name = Path(normalized).stem
+ if command_name == "find" and any(
+ arg.casefold() in {"-exec", "-execdir", "--exec"} for arg in argv
+ ):
+ raise CommandPolicyError("unsupported command: find execution actions are disabled")
+ if command_name == "git":
+ lowered = tuple(arg.casefold() for arg in argv)
+ if "config" in lowered or "-c" in lowered or any(
+ arg.startswith("--config-env")
+ or (arg.startswith("-c") and "=" in arg)
+ or arg.startswith("--exec-path")
+ or arg.startswith("alias.")
+ or "=!" in arg
+ for arg in lowered
+ ):
+ raise CommandPolicyError(
+ "unsupported command: git configuration and executable aliases are disabled"
+ )
+ if command_name in {"npm", "npx"}:
+ subcommand = argv[0].casefold() if argv else ""
+ if command_name == "npx" or subcommand in {"exec", "x"}:
+ raise CommandPolicyError(
+ "unsupported command: package-exec wrappers are disabled; use a "
+ "reviewed workspace package script"
+ )
+ if command_name in {"curl", "wget"}:
+ lowered = tuple(arg.casefold() for arg in argv)
+ blocked_options = {"--config", "-k", "--input-file", "-i"}
+ blocked_indirection = any(
+ arg in blocked_options
+ or arg.startswith(("--config=", "--input-file=", "-k", "-i"))
+ or "file:" in arg
+ or "@/" in arg
+ or "@\\" in arg
+ or "@.." in arg
+ or re.search(r"(?i)@[a-z]:[\\/]", arg) is not None
+ for arg in lowered
+ )
+ if blocked_indirection:
+ raise CommandPolicyError(
+ "unsupported command: local-file/config indirection is disabled for "
+ f"{command_name}"
+ )
+
+ for arg in argv:
+ _validate_command_path(arg, worktree=worktree)
+ return executable, argv
+
+
+def _command_timeout(value: Any) -> float:
+ """Return a finite timeout inside the worker command budget."""
+ try:
+ timeout_s = float(value if value is not None else _DEFAULT_COMMAND_TIMEOUT)
+ except (TypeError, ValueError, OverflowError) as exc:
+ raise CommandPolicyError("timeout_s must be a finite number") from exc
+ if not (_MIN_COMMAND_TIMEOUT <= timeout_s <= _MAX_COMMAND_TIMEOUT):
+ raise CommandPolicyError(
+ f"timeout_s must be between {_MIN_COMMAND_TIMEOUT:g} and "
+ f"{_MAX_COMMAND_TIMEOUT:g} seconds"
+ )
+ return timeout_s
+
+
+def _safe_proxy_value(key: str, value: str) -> str | None:
+ """Keep proxy routing only when it carries no embedded credentials."""
+ stripped = value.strip()
+ if not stripped:
+ return None
+ if key == "NO_PROXY":
+ return stripped
+ try:
+ parsed = urlsplit(stripped if "://" in stripped else f"http://{stripped}")
+ if (
+ parsed.username is not None
+ or parsed.password is not None
+ or parsed.query
+ or parsed.fragment
+ ):
+ return None
+ except ValueError:
+ return None
+ if "@" in stripped:
+ return None
+ return stripped
+
+
+def _copy_ca_environment(
+ raw_env: Mapping[str, str], *, runtime_dir: Path
+) -> dict[str, str]:
+ """Copy public CA bundles into mission state without exposing host paths."""
+ copied: dict[str, str] = {}
+ cert_dir = runtime_dir / "certificates"
+ for key in _CA_FILE_ENV_KEYS:
+ raw_path = raw_env.get(key)
+ if not raw_path:
+ continue
+ source = Path(raw_path).expanduser()
+ try:
+ if not source.is_file() or source.stat().st_size > _MAX_CA_BUNDLE_BYTES:
+ continue
+ content = source.read_bytes()
+ if b"PRIVATE KEY" in content.upper():
+ logger.warning("Refusing to stage %s because it contains private key data", key)
+ continue
+ cert_dir.mkdir(parents=True, exist_ok=True)
+ target = cert_dir / f"{key.casefold()}.pem"
+ target.write_bytes(content)
+ copied[key] = str(target)
+ except OSError:
+ logger.debug("Could not stage %s for RunCommand", key, exc_info=True)
+ return copied
+
+
+def _command_environment(
+ source: Mapping[str, str] | None,
+ *,
+ runtime_dir: Path,
+) -> dict[str, str]:
+ """Build a credential-reduced, mission-scoped subprocess environment."""
+ source_env = source if source is not None else os.environ
+ raw_env = {str(key).upper(): str(value) for key, value in source_env.items()}
+ host_env = {str(key).upper(): str(value) for key, value in os.environ.items()}
+ for key in _SAFE_ENV_KEYS | _PROXY_ENV_KEYS | _CA_FILE_ENV_KEYS:
+ if key not in raw_env and key in host_env:
+ raw_env[key] = host_env[key]
+ env = {
+ key: value for key, value in raw_env.items() if key in _SAFE_ENV_KEYS
+ }
+ # Tests and direct WorkerProtocol callers may pass an intentionally sparse
+ # mapping. Fill only non-secret process essentials from the host; never fall
+ # back to the complete host environment.
+ env.setdefault("PATH", os.environ.get("PATH", os.defpath))
+ runtime_dir.mkdir(parents=True, exist_ok=True)
+ home = runtime_dir / "home"
+ temp = runtime_dir / "tmp"
+ home.mkdir(parents=True, exist_ok=True)
+ temp.mkdir(parents=True, exist_ok=True)
+ env.update(
+ {
+ "HOME": str(home),
+ "USERPROFILE": str(home),
+ "TMP": str(temp),
+ "TEMP": str(temp),
+ "TMPDIR": str(temp),
+ "XDG_CACHE_HOME": str(home / ".cache"),
+ "XDG_CONFIG_HOME": str(home / ".config"),
+ "GIT_CONFIG_GLOBAL": os.devnull,
+ "GIT_CONFIG_NOSYSTEM": "1",
+ "NO_COLOR": "1",
+ "PYTHONIOENCODING": "utf-8",
+ "PYTHONNOUSERSITE": "1",
+ }
+ )
+ for key in _PROXY_ENV_KEYS:
+ safe_value = _safe_proxy_value(key, raw_env.get(key, ""))
+ if safe_value is not None:
+ env[key] = safe_value
+ env[key.casefold()] = safe_value
+ env.update(_copy_ca_environment(raw_env, runtime_dir=runtime_dir))
+ return env
+
+
+def _resolve_program(program: str, env: Mapping[str, str]) -> tuple[str, tuple[str, ...]]:
+ """Resolve a policy-checked program without invoking a platform shell.
+
+ npm is a batch shim on Windows. It is mapped to its documented JavaScript
+ entry point and the native ``node.exe`` instead of handing the shim to
+ ``cmd.exe``. Other batch files fail honestly.
+ """
+ normalized = program.casefold()
+ if normalized in {"python", "python.exe", "python3", "python3.exe"}:
+ if not bool(getattr(sys, "frozen", False)):
+ return sys.executable, ()
+ candidates = tuple(
+ dict.fromkeys((program, "python3", "python", "py" if os.name == "nt" else ""))
+ )
+ for candidate in candidates:
+ if not candidate:
+ continue
+ interpreter = shutil.which(candidate, path=env.get("PATH"))
+ if not interpreter:
+ continue
+ try:
+ launches_frozen_jarvis = os.path.samefile(interpreter, sys.executable)
+ except OSError:
+ launches_frozen_jarvis = os.path.normcase(
+ os.path.realpath(interpreter)
+ ) == os.path.normcase(os.path.realpath(sys.executable))
+ if launches_frozen_jarvis:
+ continue
+ if Path(interpreter).suffix.casefold() in {".bat", ".cmd"}:
+ continue
+ return interpreter, ()
+ raise CommandPolicyError(
+ "Python is unavailable in this packaged Jarvis build. Install a real "
+ "Python interpreter on PATH or use another supported build tool; "
+ "Jarvis.exe will never be launched as Python."
+ )
+ resolved = shutil.which(program, path=env.get("PATH"))
+ if not resolved:
+ raise CommandPolicyError(f"program is not available on PATH: {program!r}")
+ suffix = Path(resolved).suffix.casefold()
+ if suffix in {".bat", ".cmd"}:
+ bare_name = Path(program).stem.casefold()
+ if bare_name == "npm":
+ node = resolve_node_executable() or shutil.which(
+ "node", path=env.get("PATH")
+ )
+ script = Path(resolved).parent / "node_modules" / "npm" / "bin" / "npm-cli.js"
+ if node and script.is_file():
+ return node, (str(script),)
+ raise CommandPolicyError(
+ f"unsupported command {program!r}: Windows batch shims require cmd.exe; "
+ "install a native executable or use a supported module runner"
+ )
+ return resolved, ()
+
+
+def _prepare_windows_gated_launch(
+ executable: str,
+ args: Sequence[str],
+ *,
+ env: Mapping[str, str],
+ runtime_dir: Path,
+) -> tuple[list[str], Path]:
+ """Build a trusted launcher that cannot start the target before assignment.
+
+ ``asyncio.create_subprocess_exec`` does not retain the primary thread handle
+ needed to safely resume a ``CREATE_SUSPENDED`` child. A fixed PowerShell
+ launcher therefore waits on a random gate file. Jarvis assigns that waiting
+ launcher to a non-breakaway Job Object first and creates the gate only after
+ assignment succeeds. The trusted launcher self-exits after 30 seconds if
+ Jarvis crashes in that narrow pre-assignment window. Target argv is JSON
+ data, never interpolated into PowerShell source.
+ """
+ powershell = (
+ shutil.which("powershell.exe", path=env.get("PATH"))
+ or shutil.which("pwsh.exe", path=env.get("PATH"))
+ or shutil.which("pwsh", path=env.get("PATH"))
+ )
+ if not powershell:
+ system_root = env.get("SYSTEMROOT") or env.get("WINDIR")
+ if system_root:
+ candidate = (
+ Path(system_root)
+ / "System32"
+ / "WindowsPowerShell"
+ / "v1.0"
+ / "powershell.exe"
+ )
+ if candidate.is_file():
+ powershell = str(candidate)
+ if not powershell:
+ raise CommandPolicyError(
+ "RunCommand is unavailable on Windows because the trusted containment "
+ "launcher (PowerShell) is not installed. No target process was started."
+ )
+
+ launch_dir = runtime_dir / "windows-launch"
+ launch_dir.mkdir(parents=True, exist_ok=True)
+ token = uuid.uuid4().hex
+ script_path = launch_dir / "contained-command.ps1"
+ payload_path = launch_dir / f"payload-{token}.json"
+ gate_path = launch_dir / f"gate-{token}"
+ with contextlib_suppress(FileNotFoundError):
+ gate_path.unlink()
+ script_path.write_text(_WINDOWS_GATE_SCRIPT, encoding="utf-8")
+ payload_path.write_text(
+ json.dumps(
+ {"executable": executable, "arguments": list(args)},
+ ensure_ascii=True,
+ ),
+ encoding="utf-8",
+ )
+ command = [
+ powershell,
+ "-NoLogo",
+ "-NoProfile",
+ "-NonInteractive",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-File",
+ str(script_path),
+ "-GatePath",
+ str(gate_path),
+ "-PayloadPath",
+ str(payload_path),
+ ]
+ return command, gate_path
+
+
+def _prepare_posix_gated_launch(
+ executable: str,
+ args: Sequence[str],
+ *,
+ runtime_dir: Path,
+) -> tuple[list[str], Path]:
+ """Gate direct POSIX exec until its process group is registered.
+
+ The fixed script consumes only positional argv and uses ``exec \"$@\"``;
+ model text is never evaluated as shell source. The waiting launcher
+ self-exits after approximately 30 seconds if Jarvis crashes before process-
+ group registration. ``/bin/sh`` is part of the supported Linux/macOS floor;
+ an unusual host without it fails honestly.
+ """
+ shell = Path("/bin/sh")
+ if not shell.is_file():
+ raise CommandPolicyError(
+ "RunCommand is unavailable because /bin/sh is missing; no target "
+ "process was started."
+ )
+ launch_dir = runtime_dir / "posix-launch"
+ launch_dir.mkdir(parents=True, exist_ok=True)
+ token = uuid.uuid4().hex
+ script_path = launch_dir / "contained-command.sh"
+ gate_path = launch_dir / f"gate-{token}"
+ with contextlib_suppress(FileNotFoundError):
+ gate_path.unlink()
+ script_path.write_text(_POSIX_GATE_SCRIPT, encoding="ascii")
+ return [str(shell), str(script_path), str(gate_path), executable, *args], gate_path
+
+
+async def _read_limited(stream: asyncio.StreamReader | None) -> str:
+ """Drain a process stream while retaining only bounded UTF-8 output."""
+ if stream is None:
+ return ""
+ kept = bytearray()
+ while True:
+ chunk = await stream.read(4096)
+ if not chunk:
+ break
+ if len(kept) < _MAX_OUTPUT_CHARS:
+ kept.extend(chunk[: _MAX_OUTPUT_CHARS - len(kept)])
+ return bytes(kept).decode("utf-8", errors="replace")
+
+
+async def _wait_for_exit(proc: asyncio.subprocess.Process, timeout_s: float = 2.0) -> None:
+ with contextlib_suppress(TimeoutError, ProcessLookupError):
+ await asyncio.wait_for(proc.wait(), timeout=timeout_s)
+
+
+async def _terminate_windows_tree(proc: asyncio.subprocess.Process) -> None:
+ """Best-effort psutil fallback when a Windows Job Object is unavailable."""
+ try:
+ import psutil # noqa: PLC0415
+
+ parent = psutil.Process(proc.pid)
+ processes = parent.children(recursive=True) + [parent]
+ for process in reversed(processes):
+ with contextlib_suppress(psutil.Error):
+ process.terminate()
+ _, alive = await asyncio.to_thread(psutil.wait_procs, processes, timeout=0.25)
+ for process in alive:
+ with contextlib_suppress(psutil.Error):
+ process.kill()
+ except Exception: # noqa: BLE001 - final fallback below still runs
+ logger.debug("RunCommand psutil tree cleanup failed", exc_info=True)
+ if proc.returncode is None:
+ with contextlib_suppress(ProcessLookupError):
+ proc.kill()
+ await _wait_for_exit(proc)
+
+
+async def _terminate_posix_group(proc: asyncio.subprocess.Process) -> None:
+ """Terminate the process session created by ``create_worker_subprocess``."""
+ import signal # noqa: PLC0415
+
+ with contextlib_suppress(ProcessLookupError, PermissionError, OSError):
+ os.killpg(proc.pid, signal.SIGTERM)
+ try:
+ await asyncio.wait_for(proc.wait(), timeout=_COMMAND_STOP_GRACE_S)
+ except TimeoutError:
+ pass
+ # The leader may already have exited while a background grandchild still
+ # owns the group, so always attempt the final group kill.
+ with contextlib_suppress(ProcessLookupError, PermissionError, OSError):
+ os.killpg(proc.pid, signal.SIGKILL)
+ await _wait_for_exit(proc)
+
+
+async def _terminate_process_tree(proc: asyncio.subprocess.Process) -> None:
+ if sys.platform == "win32":
+ await _terminate_windows_tree(proc)
+ else:
+ await _terminate_posix_group(proc)
+
+
+async def _run_command(
+ tool_input: Mapping[str, Any],
+ *,
+ worktree: Path,
+ env: Mapping[str, str] | None,
+ job: Any | None,
+ runtime_dir: Path,
+ on_spawn: Callable[[int], None] | None,
+) -> tuple[str, bool]:
+ """Run one direct command with cancellation-safe tree containment."""
+ root = worktree.resolve() # noqa: ASYNC240 - one fast boundary check before spawn
+ if not root.is_dir(): # noqa: ASYNC240 - one fast boundary check before spawn
+ return (f"Workspace is not a directory: {worktree}", True)
+ program, args = _validated_command(
+ tool_input.get("program"), tool_input.get("args"), worktree=root
+ )
+ timeout_s = _command_timeout(tool_input.get("timeout_s"))
+ command_env = _command_environment(env, runtime_dir=runtime_dir)
+ executable, launcher_args = _resolve_program(program, command_env)
+
+ # Windows must never start a model-selected target until a strict,
+ # non-breakaway Job Object owns the trusted waiting launcher. A no-op Job is
+ # an honest capability failure, not permission to run uncontained.
+ command_job = (
+ WindowsJobObject(
+ f"api-command-{uuid.uuid4().hex}", allow_breakaway=False
+ )
+ if sys.platform == "win32"
+ else None
+ )
+ if command_job is not None and command_job.handle is None:
+ await command_job.close()
+ return (
+ "RunCommand is unavailable because strict Windows process-tree "
+ "containment could not be created. No target process was started.",
+ True,
+ )
+
+ spawn_command = [executable, *launcher_args, *args]
+ gate_path: Path | None = None
+ if sys.platform == "win32":
+ try:
+ spawn_command, gate_path = _prepare_windows_gated_launch(
+ executable,
+ (*launcher_args, *args),
+ env=command_env,
+ runtime_dir=runtime_dir,
+ )
+ except BaseException:
+ if command_job is not None:
+ await command_job.close()
+ raise
+ else:
+ spawn_command, gate_path = _prepare_posix_gated_launch(
+ executable,
+ (*launcher_args, *args),
+ runtime_dir=runtime_dir,
+ )
+ proc: asyncio.subprocess.Process | None = None
+ stdout_task: asyncio.Task[str] | None = None
+ stderr_task: asyncio.Task[str] | None = None
+ timed_out = False
+ try:
+ proc = await create_worker_subprocess(
+ spawn_command,
+ cwd=str(root),
+ env=command_env,
+ stdin=subprocess.DEVNULL,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ )
+ if on_spawn is not None:
+ on_spawn(proc.pid)
+ if command_job is not None:
+ try:
+ command_job.assign(proc.pid)
+ except Exception as exc: # noqa: BLE001 - fail closed before target gate
+ await _terminate_windows_tree(proc)
+ raise CommandPolicyError(
+ "RunCommand is unavailable because strict Windows process-tree "
+ "assignment failed. No target process was started."
+ ) from exc
+
+ # The mission container is a second ownership layer. Failure is
+ # non-fatal only when the dedicated strict command Job already owns the
+ # Windows launcher; POSIX uses the mission process-group registry.
+ if job is not None:
+ try:
+ job.assign(proc.pid)
+ except Exception as exc: # noqa: BLE001
+ if command_job is None:
+ await _terminate_posix_group(proc)
+ raise CommandPolicyError(
+ "RunCommand process-group assignment failed; the command was "
+ "stopped and no result was accepted."
+ ) from exc
+ logger.warning(
+ "RunCommand pid=%d is strictly command-contained but could not "
+ "join the additional mission container",
+ proc.pid,
+ exc_info=True,
+ )
+
+ if gate_path is not None:
+ # The fixed launcher cannot start the target before this exact line.
+ gate_path.write_text("go", encoding="ascii") # noqa: ASYNC240
+
+ stdout_task = asyncio.create_task(_read_limited(proc.stdout))
+ stderr_task = asyncio.create_task(_read_limited(proc.stderr))
+ try:
+ await asyncio.wait_for(proc.wait(), timeout=timeout_s)
+ except TimeoutError:
+ timed_out = True
+ await _terminate_process_tree(proc)
+ except asyncio.CancelledError:
+ await _terminate_process_tree(proc)
+ raise
+ finally:
+ # Reap background descendants even when their command leader already
+ # returned successfully. On Windows the dedicated Job Object is the
+ # atomic path; POSIX uses the command's private process group.
+ if command_job is not None:
+ await command_job.close()
+ elif proc is not None:
+ await _terminate_posix_group(proc)
+
+ stdout = await stdout_task
+ stderr = await stderr_task
+ output = (stdout + stderr)[:_MAX_OUTPUT_CHARS]
+ if timed_out:
+ return (f"Command timed out after {timeout_s:g}s", True)
+ returncode = proc.returncode
+ is_error = returncode not in (0, None)
+ tag = f"[exit {returncode}] " if is_error else ""
+ return (f"{tag}{output}".strip() or "(no output)", is_error)
+ finally:
+ if proc is not None and proc.returncode is None:
+ await _terminate_process_tree(proc)
+ if command_job is not None and not command_job.closed:
+ await command_job.close()
+ if proc is not None and proc.returncode is not None and job is not None:
+ release = getattr(job, "release", None)
+ if callable(release):
+ with contextlib_suppress(Exception):
+ release(proc.pid)
+ for task in (stdout_task, stderr_task):
+ if task is not None and not task.done():
+ task.cancel()
+ with contextlib_suppress(asyncio.CancelledError):
+ await task
+
+
def execute_worker_tool(
name: str, tool_input: dict[str, Any], *, worktree: Path
) -> tuple[str, bool]:
@@ -155,23 +980,17 @@ def execute_worker_tool(
path.write_text(text.replace(old, new, 1), encoding="utf-8")
return (f"Edited {tool_input['file_path']}", False)
+ if name == "RunCommand":
+ return (
+ "RunCommand requires the async worker executor; no process was started.",
+ True,
+ )
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,
+ return (
+ "Bash is unsupported in API workers. Use RunCommand with separate "
+ "program and args fields.",
+ True,
)
- 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 "."))
@@ -188,8 +1007,43 @@ def execute_worker_tool(
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)
+
+
+async def execute_worker_tool_async(
+ name: str,
+ tool_input: dict[str, Any],
+ *,
+ worktree: Path,
+ env: Mapping[str, str] | None = None,
+ job: Any | None = None,
+ runtime_dir: Path | None = None,
+ on_spawn: Callable[[int], None] | None = None,
+) -> tuple[str, bool]:
+ """Execute a local worker tool without blocking the event loop.
+
+ Cancellation deliberately propagates to the caller after the active command
+ tree is reaped. Policy and operating-system failures are ordinary tool
+ errors so the model can select a supported command or correct its arguments.
+ """
+ try:
+ if name == "RunCommand":
+ return await _run_command(
+ tool_input,
+ worktree=worktree,
+ env=env,
+ job=job,
+ runtime_dir=runtime_dir or worktree / ".jarvis-agent-runtime",
+ on_spawn=on_spawn,
+ )
+ return await asyncio.to_thread(
+ execute_worker_tool, name, tool_input, worktree=worktree
+ )
+ except (CommandPolicyError, WorktreeEscapeError) as exc:
+ return (str(exc), True)
except KeyError as exc:
return (f"Missing required argument: {exc}", True)
except OSError as exc:
@@ -206,7 +1060,9 @@ def tool_writes_file(name: str) -> bool:
__all__ = [
"WORKER_TOOL_SPECS",
+ "CommandPolicyError",
"WorktreeEscapeError",
"execute_worker_tool",
+ "execute_worker_tool_async",
"tool_writes_file",
]
diff --git a/jarvis/missions/workers/api_agent_worker.py b/jarvis/missions/workers/api_agent_worker.py
index bd627d272a..96f40e77dd 100644
--- a/jarvis/missions/workers/api_agent_worker.py
+++ b/jarvis/missions/workers/api_agent_worker.py
@@ -14,11 +14,17 @@ 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.
+Isolation note: unlike the CLI workers the provider loop runs IN the app event
+loop. Its local ``RunCommand`` tool uses structured argv and an asynchronous
+subprocess, assigns that PID to process-tree containment, reduces the child
+environment, and reaps the whole tree on completion, timeout, or cancellation.
+Fixed POSIX and Windows gate launchers ensure no model-selected target starts
+before process-group/Job assignment; argv remains positional data, never shell
+source. File tools are dispatched off the event loop. Cancellation is honored
+while a command is active as well as at turn boundaries. This containment is
+not a filesystem or code-execution sandbox: workspace scripts retain the
+Jarvis user's OS rights and intentionally detached POSIX code can escape a
+userspace process group.
"""
from __future__ import annotations
@@ -35,7 +41,7 @@ from typing import Any, Literal
from jarvis.core.protocols import BrainMessage, BrainRequest
-from .api_agent_tools import WORKER_TOOL_SPECS, execute_worker_tool
+from .api_agent_tools import WORKER_TOOL_SPECS, execute_worker_tool_async
from .capabilities import WorkerCapabilityInventory
from .stream_consumer import (
ClaudeAssistantMessage,
@@ -147,7 +153,7 @@ def _resolve_worker_model(provider: str, explicit: str) -> str:
picked = (getattr(pc, "model", "") or "").strip()
if picked:
return picked
- except Exception: # noqa: BLE001 — config read must never crash the worker
+ except Exception: # noqa: BLE001, S110 — config read must never crash the worker
pass
return _DEFAULT_MODEL.get(prov, "")
@@ -159,7 +165,7 @@ _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, plus any mission-scoped connected tools — "
+ "Write, Edit, Read, RunCommand, Ls, plus any mission-scoped connected tools — "
"with file paths relative to the workspace root. Connected tools are "
"executed by the supervisor and may honestly require human approval. "
"Actually CREATE and EDIT the files the task needs; never just describe what "
@@ -184,7 +190,7 @@ def _build_brain(provider: str, model: str) -> Any:
def _tool_incapable_message(model: str, provider: str, *, detail: str = "") -> str:
"""Shared honest-failure text for a worker model that cannot call tools.
- Missions deliver ALL work through tool calls (Write/Edit/Bash/...); a
+ Missions deliver ALL work through tool calls (Write/Edit/RunCommand/...); a
text-only reply produces an empty diff and the mission dies 3 critic
loops later with an inscrutable ``critic_loop_exhausted`` (forensics
Bug 10). Fail fast and actionably instead.
@@ -226,8 +232,8 @@ class ApiAgentWorker:
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)
+ env: dict[str, str],
+ job: Any,
worker_id: str,
log_dir: Path,
model: str = "",
@@ -269,8 +275,8 @@ class ApiAgentWorker:
prompt: str,
*,
worktree: Path,
- env: dict[str, str], # noqa: ARG002 - in-process brain reads credentials via config
- job: Any, # noqa: ARG002 - no child PID to assign (in-process)
+ env: dict[str, str],
+ job: Any,
worker_id: str,
log_dir: Path,
model: str = "",
@@ -279,6 +285,7 @@ class ApiAgentWorker:
**_unused: Any,
) -> AsyncIterator[Any]:
session_id = str(uuid.uuid4())
+ self.last_pid = None
self.last_session_id = session_id
resolved_model = _resolve_worker_model(self.provider, model)
log_dir.mkdir(parents=True, exist_ok=True) # noqa: ASYNC240 — trivial sync mkdir (mirrors sibling workers)
@@ -355,7 +362,6 @@ class ApiAgentWorker:
)
messages: list[BrainMessage] = [BrainMessage(role="user", content=prompt)]
- loop = asyncio.get_running_loop()
t0 = time.perf_counter()
final_text = ""
turns = 0
@@ -452,7 +458,9 @@ class ApiAgentWorker:
messages.append(BrainMessage(role="assistant", content=content_blocks))
- # Execute each tool call off the event loop, emit tool_result.
+ # Execute each local tool through its async boundary. File I/O
+ # is sent to a thread; RunCommand remains cancellable and owns
+ # its whole subprocess tree through the mission job.
result_blocks: list[dict[str, Any]] = []
for block in content_blocks:
if block.get("type") != "tool_use":
@@ -460,11 +468,14 @@ class ApiAgentWorker:
name = block["name"]
tool_input = block["input"] if isinstance(block["input"], dict) else {}
if name in local_names:
- result_text, is_error = await loop.run_in_executor(
- None,
- lambda n=name, i=tool_input: execute_worker_tool(
- n, i, worktree=worktree
- ),
+ result_text, is_error = await execute_worker_tool_async(
+ name,
+ tool_input,
+ worktree=worktree,
+ env=env,
+ job=job,
+ runtime_dir=log_dir / "command-runtime",
+ on_spawn=lambda pid: setattr(self, "last_pid", pid),
)
elif broker_binding is not None:
broker_result = await broker_binding.execute(name, tool_input)
diff --git a/tests/missions/test_job_object.py b/tests/missions/test_job_object.py
index c26634f786..68dbc6c46f 100644
--- a/tests/missions/test_job_object.py
+++ b/tests/missions/test_job_object.py
@@ -13,6 +13,7 @@ import time
import pytest
+from jarvis.missions.isolation import job_object as job_module
from jarvis.missions.isolation.job_object import (
AlwaysOpenJobObject,
WindowsJobObject,
@@ -68,7 +69,7 @@ async def test_close_kills_assigned_process() -> None:
psutil = pytest.importorskip("psutil")
# Long-lived sleeper — runs 60s if not killed.
- proc = subprocess.Popen( # noqa: S603 — controlled args
+ proc = subprocess.Popen( # noqa: ASYNC220, S603 — controlled args
[sys.executable, "-c", "import time; time.sleep(60)"],
creationflags=(
_CREATE_BREAKAWAY_FROM_JOB | _CREATE_NO_WINDOW | _CREATE_NEW_PROCESS_GROUP
@@ -120,8 +121,8 @@ async def test_close_is_idempotent() -> None:
@pytest.mark.skipif(not _IS_WIN, reason="Job objects are Windows-only")
async def test_async_context_manager_closes_on_exit() -> None:
- psutil = pytest.importorskip("psutil")
- proc = subprocess.Popen( # noqa: S603
+ pytest.importorskip("psutil")
+ proc = subprocess.Popen( # noqa: ASYNC220, S603
[sys.executable, "-c", "import time; time.sleep(60)"],
creationflags=(
_CREATE_BREAKAWAY_FROM_JOB | _CREATE_NO_WINDOW | _CREATE_NEW_PROCESS_GROUP
@@ -144,3 +145,60 @@ async def test_async_context_manager_closes_on_exit() -> None:
if proc.poll() is None:
proc.kill()
proc.wait(timeout=2)
+
+
[email protected](not _IS_WIN, reason="Job objects are Windows-only")
+async def test_ctypes_fallback_kills_assigned_process_without_pywin32() -> None:
+ """Base Windows installs retain kernel-enforced tree containment."""
+ proc = subprocess.Popen( # noqa: ASYNC220, S603 - controlled test argv
+ [sys.executable, "-c", "import time; time.sleep(60)"],
+ creationflags=(
+ _CREATE_BREAKAWAY_FROM_JOB | _CREATE_NO_WINDOW | _CREATE_NEW_PROCESS_GROUP
+ ),
+ )
+ try:
+ job = job_module._Win32CtypesJobObjectImpl(
+ "ctypes-fallback-test", allow_breakaway=False
+ )
+ job.assign(proc.pid)
+ await job.close()
+ deadline = time.monotonic() + 2.0
+ while time.monotonic() < deadline and proc.poll() is None: # noqa: ASYNC110
+ await asyncio.sleep(0.05)
+ assert proc.poll() is not None
+ finally:
+ if proc.poll() is None:
+ proc.kill()
+ proc.wait(timeout=2)
+
+
[email protected](not _IS_WIN, reason="Job objects are Windows-only")
+async def test_strict_job_disables_descendant_breakaway() -> None:
+ win32job = pytest.importorskip("win32job")
+
+ job = WindowsJobObject("strict-flags-test", allow_breakaway=False)
+ try:
+ info = win32job.QueryInformationJobObject(
+ job.handle, win32job.JobObjectExtendedLimitInformation
+ )
+ flags = info["BasicLimitInformation"]["LimitFlags"]
+ assert flags & win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
+ assert not flags & win32job.JOB_OBJECT_LIMIT_BREAKAWAY_OK
+ finally:
+ await job.close()
+
+
[email protected](not _IS_WIN, reason="Job objects are Windows-only")
+async def test_factory_uses_ctypes_when_pywin32_is_missing(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ def _missing_pywin32(*_args, **_kwargs): # noqa: ANN002, ANN003, ANN202
+ raise ImportError("simulated missing pywin32")
+
+ monkeypatch.setattr(job_module, "_Win32JobObjectImpl", _missing_pywin32)
+ job = WindowsJobObject("ctypes-factory-test", allow_breakaway=False)
+ try:
+ assert type(job).__name__ == "_Win32CtypesJobObjectImpl"
+ assert job.handle is not None
+ finally:
+ await job.close()
diff --git a/tests/missions/test_posix_containment.py b/tests/missions/test_posix_containment.py
index b67bdb9637..04547c60d6 100644
--- a/tests/missions/test_posix_containment.py
+++ b/tests/missions/test_posix_containment.py
@@ -97,6 +97,15 @@ async def test_posix_job_assign_after_close_raises() -> None:
job.assign(1)
+async def test_posix_job_can_release_a_reaped_short_lived_group() -> None:
+ killer = _FakeKiller()
+ job = _make_job(killer)
+ job.assign(77)
+ job.release(77)
+ await job.close()
+ assert killer.calls == []
+
+
async def test_posix_job_async_context_manager_reaps_on_exit() -> None:
killer = _FakeKiller()
async with _make_job(killer) as job:
diff --git a/tests/missions/workers/test_api_agent_tools.py b/tests/missions/workers/test_api_agent_tools.py
index 80d6955cdc..9346e130e9 100644
--- a/tests/missions/workers/test_api_agent_tools.py
+++ b/tests/missions/workers/test_api_agent_tools.py
@@ -1,18 +1,26 @@
-"""Tests for the worktree-scoped tools of the in-process API-agent worker."""
+"""Tests for the worktree-scoped tools of the in-process API worker."""
from __future__ import annotations
+import asyncio
+import os
+import sys
+import time
from pathlib import Path
+import pytest
+
+from jarvis.missions.workers import api_agent_tools as aat
from jarvis.missions.workers.api_agent_tools import (
WORKER_TOOL_SPECS,
execute_worker_tool,
+ execute_worker_tool_async,
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"}
+ assert names == {"Write", "Read", "Edit", "RunCommand", "Ls"}
# every spec is OpenAI/Anthropic-translatable
for t in WORKER_TOOL_SPECS:
assert t["description"]
@@ -20,7 +28,9 @@ def test_specs_cover_the_core_tools() -> None:
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)
+ 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)
@@ -58,14 +68,30 @@ def test_ls_lists_entries(tmp_path: Path) -> None:
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)
+async def test_command_runs_directly_in_worktree(tmp_path: Path) -> None:
+ (tmp_path / "show_cwd.py").write_text(
+ "from pathlib import Path\nprint(Path.cwd().name)\n", encoding="utf-8"
+ )
+ out, err = await execute_worker_tool_async(
+ "RunCommand",
+ {"program": "python", "args": ["show_cwd.py"]},
+ worktree=tmp_path,
+ )
assert err is False
- assert "hello-from-bash" in out
+ assert tmp_path.name 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)
+async def test_command_nonzero_exit_is_error(tmp_path: Path) -> None:
+ (tmp_path / "fail.py").write_text(
+ "raise SystemExit(3)\n", encoding="utf-8"
+ )
+ out, err = await execute_worker_tool_async(
+ "RunCommand",
+ {"program": "python", "args": ["fail.py"]},
+ worktree=tmp_path,
+ )
assert err is True
assert "exit 3" in out
@@ -94,4 +120,395 @@ def test_unknown_tool_is_error(tmp_path: Path) -> None:
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")
+ assert not tool_writes_file("Read") and not tool_writes_file("RunCommand")
+
+
+ ("tool_input", "message"),
+ [
+ ({"program": "python", "args": ["../outside.py"]}, "escapes"),
+ ({"program": "../python", "args": []}, "executable name"),
+ ({"program": "python", "args": ["-c", "print('x')"]}, "inline"),
+ ({"program": "py", "args": ["-c", "print('x')"]}, "inline"),
+ ({"program": "bash", "args": ["-c", "echo x"]}, "shell"),
+ ({"program": "env", "args": ["python", "build.py"]}, "shell"),
+ ({"program": "pythonw", "args": ["build.py"]}, "shell"),
+ ({"program": "npx", "args": ["vite"]}, "package-exec"),
+ ({"program": "npm", "args": ["exec", "vite"]}, "package-exec"),
+ ({"program": "git", "args": ["config", "alias.x", "!cmd"]}, "git"),
+ ({"program": "git", "args": ["-c", "alias.x=!cmd", "x"]}, "git"),
+ ({"program": "curl", "args": ["file:///etc/passwd"]}, "local-file"),
+ ({"program": "curl", "args": ["--data", "@../secret"]}, "local-file"),
+ ({"program": "python", "args": "script.py"}, "array"),
+ ],
+)
+async def test_command_policy_rejects_unsafe_shapes(
+ tmp_path: Path, tool_input: dict[str, object], message: str
+) -> None:
+ out, err = await execute_worker_tool_async(
+ "RunCommand", tool_input, worktree=tmp_path
+ )
+ assert err is True
+ assert message in out.lower()
+
+
+def test_command_policy_keeps_reviewable_build_and_network_shapes(tmp_path: Path) -> None:
+ assert aat._validated_command(
+ "git", ["--no-pager", "status"], worktree=tmp_path
+ ) == ("git", ("--no-pager", "status"))
+ assert aat._validated_command(
+ "npm", ["run", "build"], worktree=tmp_path
+ ) == ("npm", ("run", "build"))
+ assert aat._validated_command(
+ "curl", ["https://example.com/status"], worktree=tmp_path
+ ) == ("curl", ("https://example.com/status",))
+
+
+async def test_command_rejects_absolute_path_outside_worktree(tmp_path: Path) -> None:
+ out, err = await execute_worker_tool_async(
+ "RunCommand",
+ {"program": "python", "args": [str(tmp_path.parent / "outside.py")]},
+ worktree=tmp_path,
+ )
+ assert err is True
+ assert "escapes" in out.lower()
+
+ out, err = await execute_worker_tool_async(
+ "RunCommand",
+ {
+ "program": "python",
+ "args": [f"--unknown-output={tmp_path.parent / 'outside.txt'}"],
+ },
+ worktree=tmp_path,
+ )
+ assert err is True
+ assert "escapes" in out.lower()
+
+
+async def test_command_environment_does_not_forward_credentials(tmp_path: Path) -> None:
+ (tmp_path / "show_env.py").write_text(
+ "import os\n"
+ "print(os.environ.get('OPENAI_API_KEY', 'missing'))\n"
+ "print(os.environ.get('HOME', ''))\n",
+ encoding="utf-8",
+ )
+ runtime_dir = tmp_path / "runtime"
+ out, err = await execute_worker_tool_async(
+ "RunCommand",
+ {"program": "python", "args": ["show_env.py"]},
+ worktree=tmp_path,
+ env={"PATH": os.environ.get("PATH", ""), "OPENAI_API_KEY": "secret"},
+ runtime_dir=runtime_dir,
+ )
+ assert err is False
+ assert out.splitlines()[0] == "missing"
+ assert str(runtime_dir / "home") in out
+
+
+def test_command_environment_keeps_safe_portability_without_proxy_credentials(
+ tmp_path: Path,
+) -> None:
+ ca_bundle = tmp_path / "corporate-ca.pem"
+ ca_bundle.write_text("PUBLIC CA\n", encoding="ascii")
+ unsafe_bundle = tmp_path / "unsafe-ca.pem"
+ unsafe_bundle.write_text("PRIVATE KEY\n", encoding="ascii")
+ runtime_dir = tmp_path / "runtime"
+ env = aat._command_environment(
+ {
+ "PATH": os.environ.get("PATH", ""),
+ "JAVA_HOME": str(tmp_path / "jdk"),
+ "HTTPS_PROXY": "http://proxy.example:8080",
+ "HTTP_PROXY": "http://user:[email protected]:8080",
+ "ALL_PROXY": "http://proxy.example:8080?token=secret",
+ "REQUESTS_CA_BUNDLE": str(ca_bundle),
+ "CURL_CA_BUNDLE": str(unsafe_bundle),
+ "OPENAI_API_KEY": "must-not-cross",
+ },
+ runtime_dir=runtime_dir,
+ )
+ assert env["JAVA_HOME"] == str(tmp_path / "jdk")
+ assert env["HTTPS_PROXY"] == "http://proxy.example:8080"
+ assert "HTTP_PROXY" not in env
+ assert "ALL_PROXY" not in env
+ assert "OPENAI_API_KEY" not in env
+ assert "CURL_CA_BUNDLE" not in env
+ staged_ca = Path(env["REQUESTS_CA_BUNDLE"])
+ assert staged_ca.parent == runtime_dir / "certificates"
+ assert staged_ca.read_text(encoding="ascii") == "PUBLIC CA\n"
+
+
+def test_frozen_python_never_resolves_to_jarvis_executable(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ jarvis_exe = str(Path("C:/Program Files/Jarvis/Jarvis.exe"))
+ monkeypatch.setattr(aat.sys, "frozen", True, raising=False)
+ monkeypatch.setattr(aat.sys, "executable", jarvis_exe)
+ monkeypatch.setattr(aat.shutil, "which", lambda *_args, **_kwargs: jarvis_exe)
+
+ with pytest.raises(aat.CommandPolicyError, match="Jarvis.exe will never"):
+ aat._resolve_program("python", {"PATH": "unused"})
+
+
+def test_frozen_python_uses_a_distinct_path_interpreter(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ jarvis_exe = str(Path("C:/Program Files/Jarvis/Jarvis.exe"))
+ real_python = str(Path("C:/Python311/python.exe"))
+ monkeypatch.setattr(aat.sys, "frozen", True, raising=False)
+ monkeypatch.setattr(aat.sys, "executable", jarvis_exe)
+
+ def _which(candidate: str, **_kwargs: object) -> str | None:
+ if candidate == "python":
+ return jarvis_exe
+ if candidate == "python3":
+ return real_python
+ return None
+
+ monkeypatch.setattr(aat.shutil, "which", _which)
+ assert aat._resolve_program("python", {"PATH": "unused"}) == (real_python, ())
+
+
+def test_command_timeout_allows_long_builds_but_remains_bounded() -> None:
+ assert aat._command_timeout(None) == 120.0
+ assert aat._command_timeout(600) == 600.0
+ with pytest.raises(aat.CommandPolicyError, match="600"):
+ aat._command_timeout(601)
+
+
+async def test_command_pid_is_assigned_to_mission_container(tmp_path: Path) -> None:
+ (tmp_path / "ok.py").write_text("print('ok')\n", encoding="utf-8")
+
+ class _Job:
+ def __init__(self) -> None:
+ self.assigned: list[int] = []
+
+ def assign(self, pid: int) -> None:
+ self.assigned.append(pid)
+
+ job = _Job()
+ out, err = await execute_worker_tool_async(
+ "RunCommand",
+ {"program": "python", "args": ["ok.py"]},
+ worktree=tmp_path,
+ job=job,
+ )
+ assert err is False and out == "ok"
+ assert len(job.assigned) == 1
+ assert job.assigned[0] > 0
+
+
+def _tree_script(tmp_path: Path, *, fast_leader: bool = False) -> Path:
+ script = tmp_path / "spawn_tree.py"
+ script.write_text(
+ "import subprocess, sys, time\n"
+ "from pathlib import Path\n"
+ "flags = getattr(subprocess, 'CREATE_NO_WINDOW', 0)\n"
+ "child = subprocess.Popen(\n"
+ " [sys.executable, str(Path(__file__).with_name('sleep.py'))],\n"
+ " creationflags=flags,\n"
+ ")\n"
+ "Path('child.pid').write_text(str(child.pid), encoding='utf-8')\n"
+ + ("pass\n" if fast_leader else "time.sleep(60)\n"),
+ encoding="utf-8",
+ )
+ (tmp_path / "sleep.py").write_text("import time\ntime.sleep(60)\n", encoding="utf-8")
+ return script
+
+
+async def _wait_for_pid_file(path: Path) -> int:
+ deadline = time.monotonic() + 5.0
+ while time.monotonic() < deadline:
+ if path.is_file(): # noqa: ASYNC240 - tiny test synchronization probe
+ return int(
+ path.read_text(encoding="utf-8") # noqa: ASYNC240 - tiny pid file
+ )
+ await asyncio.sleep(0.02)
+ raise AssertionError("child pid file was not created")
+
+
+async def _assert_pid_gone(pid: int) -> None:
+ psutil = pytest.importorskip("psutil")
+ deadline = time.monotonic() + 5.0
+ while time.monotonic() < deadline:
+ if not psutil.pid_exists(pid):
+ return
+ await asyncio.sleep(0.05)
+ with pytest.raises(psutil.NoSuchProcess):
+ process = psutil.Process(pid)
+ if process.is_running():
+ raise AssertionError(f"descendant process {pid} survived command cleanup")
+
+
+async def test_command_timeout_reaps_descendant_tree(tmp_path: Path) -> None:
+ _tree_script(tmp_path)
+ out, err = await execute_worker_tool_async(
+ "RunCommand",
+ {"program": "python", "args": ["spawn_tree.py"], "timeout_s": 2.0},
+ worktree=tmp_path,
+ )
+ child_pid = await _wait_for_pid_file(tmp_path / "child.pid")
+ assert err is True
+ assert "timed out" in out.lower()
+ await _assert_pid_gone(child_pid)
+
+
+async def test_command_cancellation_reaps_descendant_tree(tmp_path: Path) -> None:
+ _tree_script(tmp_path)
+ task = asyncio.create_task(
+ execute_worker_tool_async(
+ "RunCommand",
+ {"program": "python", "args": ["spawn_tree.py"]},
+ worktree=tmp_path,
+ )
+ )
+ child_pid = await _wait_for_pid_file(tmp_path / "child.pid")
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ await _assert_pid_gone(child_pid)
+
+
[email protected](sys.platform != "win32", reason="Windows Job Object guarantee")
+async def test_windows_fast_leader_cannot_leave_descendant(tmp_path: Path) -> None:
+ _tree_script(tmp_path, fast_leader=True)
+ out, err = await execute_worker_tool_async(
+ "RunCommand",
+ {"program": "python", "args": ["spawn_tree.py"]},
+ worktree=tmp_path,
+ )
+ child_pid = await _wait_for_pid_file(tmp_path / "child.pid")
+ assert err is False, out
+ await _assert_pid_gone(child_pid)
+
+
[email protected](sys.platform != "win32", reason="Windows Job Object guarantee")
+async def test_windows_noop_job_fails_before_target_start(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ marker = tmp_path / "started.txt"
+ (tmp_path / "target.py").write_text(
+ "from pathlib import Path\nPath('started.txt').write_text('bad')\n",
+ encoding="utf-8",
+ )
+ from jarvis.missions.isolation.job_object import AlwaysOpenJobObject
+
+ monkeypatch.setattr(
+ aat,
+ "WindowsJobObject",
+ lambda name, **_kwargs: AlwaysOpenJobObject(name),
+ )
+ out, err = await execute_worker_tool_async(
+ "RunCommand",
+ {"program": "python", "args": ["target.py"]},
+ worktree=tmp_path,
+ )
+ assert err is True
+ assert "containment" in out.lower()
+ assert not marker.exists()
+
+
[email protected](sys.platform != "win32", reason="Windows Job Object guarantee")
+async def test_windows_assignment_failure_never_opens_target_gate(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ marker = tmp_path / "started.txt"
+ (tmp_path / "target.py").write_text(
+ "from pathlib import Path\nPath('started.txt').write_text('bad')\n",
+ encoding="utf-8",
+ )
+
+ class _FailingJob:
+ handle = object()
+ closed = False
+
+ def assign(self, _pid: int) -> None:
+ raise OSError("simulated assignment failure")
+
+ async def close(self) -> None:
+ self.closed = True
+
+ monkeypatch.setattr(aat, "WindowsJobObject", lambda *_args, **_kwargs: _FailingJob())
+ out, err = await execute_worker_tool_async(
+ "RunCommand",
+ {"program": "python", "args": ["target.py"]},
+ worktree=tmp_path,
+ )
+ assert err is True
+ assert "assignment failed" in out.lower()
+ assert not marker.exists()
+
+
[email protected](sys.platform != "win32", reason="Windows Job Object guarantee")
+async def test_windows_breakaway_retry_is_contained_or_fails_before_target(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """The generic worker retry cannot bypass the strict command gate."""
+ from jarvis.missions.workers import process_utils
+
+ marker = tmp_path / "started.txt"
+ (tmp_path / "target.py").write_text(
+ "from pathlib import Path\nPath('started.txt').write_text('ok')\n",
+ encoding="utf-8",
+ )
+ breakaway = 0x01000000
+ original_create = asyncio.create_subprocess_exec
+ seen_flags: list[int] = []
+
+ async def _deny_first_breakaway(*cmd: str, **kwargs: object): # noqa: ANN202
+ flags = int(kwargs.get("creationflags", 0))
+ seen_flags.append(flags)
+ if len(seen_flags) == 1 and flags & breakaway:
+ raise PermissionError(5, "simulated parent Job breakaway denial")
+ return await original_create(*cmd, **kwargs)
+
+ monkeypatch.setattr(process_utils.asyncio, "create_subprocess_exec", _deny_first_breakaway)
+ out, err = await execute_worker_tool_async(
+ "RunCommand",
+ {"program": "python", "args": ["target.py"]},
+ worktree=tmp_path,
+ )
+
+ assert len(seen_flags) == 2
+ assert seen_flags[0] & breakaway
+ assert not seen_flags[1] & breakaway
+ if err:
+ # Some ambient Windows jobs reject nested assignment. The trusted
+ # launcher still cannot open its target gate in that case.
+ assert "assignment failed" in out.lower()
+ assert not marker.exists()
+ else:
+ assert marker.read_text(encoding="utf-8") == "ok"
+
+
[email protected](sys.platform == "win32", reason="POSIX process-group guarantee")
+async def test_posix_assignment_failure_never_opens_target_gate(tmp_path: Path) -> None:
+ marker = tmp_path / "started.txt"
+ (tmp_path / "target.py").write_text(
+ "from pathlib import Path\nPath('started.txt').write_text('bad')\n",
+ encoding="utf-8",
+ )
+
+ class _FailingJob:
+ def assign(self, _pid: int) -> None:
+ raise OSError("simulated assignment failure")
+
+ out, err = await execute_worker_tool_async(
+ "RunCommand",
+ {"program": "python", "args": ["target.py"]},
+ worktree=tmp_path,
+ job=_FailingJob(),
+ )
+ assert err is True
+ assert "assignment failed" in out.lower()
+ assert not marker.exists()
diff --git a/tests/missions/workers/test_api_agent_worker.py b/tests/missions/workers/test_api_agent_worker.py
index 6921bb9ecb..9880f30a7d 100644
--- a/tests/missions/workers/test_api_agent_worker.py
+++ b/tests/missions/workers/test_api_agent_worker.py
@@ -102,7 +102,7 @@ async def test_worker_writes_file_and_emits_critic_readable_stream(
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
+ assert "Write" in fake.seen_tools and "RunCommand" 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
@@ -113,6 +113,59 @@ async def test_worker_writes_file_and_emits_critic_readable_stream(
assert "out.txt" in extract_write_targets(stream_text)
+async def test_worker_run_command_is_async_and_mission_contained(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """The provider loop uses direct argv and assigns the process to its job."""
+ (tmp_path / "build.py").write_text("print('build-ok')\n", encoding="utf-8")
+ turns = [
+ [
+ BrainDelta(
+ tool_call={
+ "id": "run-1",
+ "name": "RunCommand",
+ "input": {"program": "python", "args": ["build.py"]},
+ }
+ ),
+ BrainDelta(finish_reason="tool_use"),
+ ],
+ [BrainDelta(content="Build complete."), BrainDelta(finish_reason="end_turn")],
+ ]
+ fake = FakeBrain(turns)
+ _patch_brain(monkeypatch, fake)
+
+ class _Job:
+ def __init__(self) -> None:
+ self.assigned: list[int] = []
+
+ def assign(self, pid: int) -> None:
+ self.assigned.append(pid)
+
+ job = _Job()
+ events = await _drain(
+ ApiAgentWorker("openai"),
+ prompt="run the build",
+ worktree=tmp_path,
+ env={},
+ job=job,
+ worker_id="m::0",
+ log_dir=tmp_path / "_logs",
+ model="gpt-5.5",
+ )
+
+ tool_results = [
+ block
+ for event in events
+ if type(event).__name__ == "ClaudeUserMessage"
+ for block in event.message["content"]
+ ]
+ assert tool_results[0]["content"] == "build-ok"
+ assert tool_results[0]["is_error"] is False
+ assert len(job.assigned) == 1
+ assert events[-1].is_error is False
+
+
class _RaisingBrain:
"""A brain whose complete() dies with a provider error (429/401/...)."""