Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(computers): run agents on Linux and Mac computers the way their own terminal does

rubenluetke10-beep28f2fdcfa531
diff --git a/docs/os-parity.md b/docs/os-parity.md
index 183261d7aa..6e26c953be 100644
--- a/docs/os-parity.md
+++ b/docs/os-parity.md
@@ -1,39 +1,73 @@
# OS Feature Parity — macOS / Linux Gap Register
-## Connected computers that run Windows (2026-09-30, T3)
+## Connected computers on Linux, macOS and Windows (2026-10-01, T3)
This one is about the REMOTE side: the machine Jarvis connects to under
-Computers, whatever OS Jarvis itself runs on. Linux and macOS computers take
-the POSIX paths they always took. A Windows computer with the OpenSSH server
-runs commands in `cmd.exe` (or PowerShell as its `DefaultShell`), which runs
-no POSIX shell and mangles its own command line: every non-ASCII letter
-arrived as two U+FFFD characters, a line break ends the command, and the line
-stops at 8 191 characters. `jarvis/computers/remote_os.py` asks each computer
-once (one `echo` that sh, cmd and PowerShell answer differently) and then:
-
-| Feature | Linux / macOS computer | Windows computer |
-|---|---|---|
-| Health check and facts | POSIX probe | PowerShell probe on stdin, same sections; no load average |
-| Planting the app's key (password login) | `~/.ssh/authorized_keys` | PowerShell: `administrators_authorized_keys` for admins, ACL by SID (works on a German Windows), UTF-8 without BOM |
-| Readiness and install | tmux, git, Node, CLIs; apt/dnf/yum/apk/pacman/brew | git (Git for Windows), Node, CLIs; winget and npm; "admin" instead of root |
-| Society agent's CLI turn | `exec env … <cli>` on the command line; cancel = hang up | system prompt uploaded as a file, CLI started by a Git Bash launcher uploaded over SFTP; cancel ends the launcher's process tree with `taskkill /T` first, because hanging up ends only cmd and bash and left the CLI running (measured) |
-| Society agent's shell tool | sh in `~/jarvis-agents/<id>` | Git Bash in the same folder; PowerShell when Git for Windows is missing |
-| IDE panes | tmux session; survives app close and network loss, re-attached | no tmux: the agent runs in the SSH terminal (ConPTY) and ends with the channel; a plain terminal is PowerShell |
-| IDE folder sync, conversation copy | POSIX scripts | the same scripts in Git Bash; SFTP paths as `/C:/…` |
-| Keep working when this PC closes | offered | not offered (and refused on quit): its agents would stop with the connection |
-
-Git for Windows is the one prerequisite beyond the SSH server, and every
-feature that needs it says so in one sentence. Verified live against a
-Windows 11 Pro VM (German locale): facts, readiness, a CLI start through the
-launcher, a cancelled turn leaving no process behind, an agent shell command
-with non-ASCII output, a PowerShell pane (closing it, or the app, ends its
-program there), and a git folder sent over and brought back with an edit made
-there. Covered
-by `tests/unit/computers/test_windows_remote.py` against a scripted Windows
-SSH server. Not verified live: planting the key with a password (unit-tested
-only; the VM already had the key), a Windows computer whose `DefaultShell` is
-PowerShell (handled by prefixing `&`, unit-tested only), the winget install
-leg, and a Windows Server install without winget.
+Computers, whatever OS Jarvis itself runs on. `jarvis/computers/remote_os.py`
+asks each computer once which shell it speaks (one `echo` that sh, cmd and
+PowerShell answer differently) and, on Linux and macOS, which `PATH` the
+user's own login shell builds (`$SHELL -ilc`, then `-lc`, between markers so
+rc-file chatter cannot leak in). Two rules then hold on every OS:
+
+- **Nothing of substance travels on the SSH command line.** The server hands
+ that line to the user's login shell — bash, zsh, fish, tcsh or `cmd.exe` —
+ and each parses it differently: fish has no `if …; then`, and `cmd.exe`
+ turned every non-ASCII letter into two U+FFFD characters, ends at a line
+ break and stops at 8 191 characters (measured). Scripts go on stdin to
+ `/bin/bash -s` (or `/bin/sh -s`); programs that need stdin or a terminal
+ start from a launcher file uploaded over SFTP (`/bin/sh <file>`, Git Bash on
+ Windows). The only lines a login shell ever parses are that `echo`, the two
+ script runners and a launcher's name (pinned by
+ `test_no_script_ever_reaches_the_login_shell`).
+- **Programs are found the way the user's own terminal finds them.** Over SSH
+ the search path is short: `~/.local/bin` (Claude Code's own installer) and
+ `/opt/homebrew/bin` (Homebrew on Apple silicon) were missing, so a turn said
+ "Install claude" while the readiness panel said it was installed. Every
+ script and launcher now starts with the login shell's `PATH`, plus the
+ well-known install folders that exist.
+
+| Feature | Linux | macOS | Windows |
+|---|---|---|---|
+| Health check and facts | POSIX probe | same probe; uptime from `kern.boottime`, memory from `vm_stat`, disk from the Data volume | PowerShell probe on stdin, same sections; no load average |
+| Planting the app's key (password login) | `~/.ssh/authorized_keys` | same | `administrators_authorized_keys` for admins, ACL by SID (works on a German Windows), UTF-8 without BOM |
+| Readiness: what counts as there | tmux, git, a CLI and its login; Node.js below 18 counts as missing (Ubuntu 22.04 ships 12) | Homebrew tools; Apple's placeholder `git` (no command-line tools) counts as missing and is never run — it opens an install dialog on the Mac's screen | git (Git for Windows), Node.js, CLIs; no tmux |
+| Install | tmux/git from the distribution (root or password-less sudo); Claude Code from its own installer into `~/.local/bin` (no Node.js, no root); Node.js from nodejs.org into `~/.local` (no root) when Codex needs it; Codex through npm into `~/.local` | everything through Homebrew, without root (it refuses root); without Homebrew the panel says to install it | winget and npm; needs an administrator login |
+| Claude Code login for the agents | `~/.claude/.credentials.json` or "Use my login" | the Keychain is locked in SSH sessions (documented by Anthropic): a `claude setup-token` token saved owner-only in `~/.config/jarvis/agent.env`, read by every launcher ("Use a token" in the readiness panel) | `~/.claude/.credentials.json`; the token works too |
+| Society agent's CLI turn | launcher + prompt file; cancel ends the process group the SSH server gave the command, then hangs up | same | Git Bash launcher; cancel ends the tree with `taskkill /T` — hanging up ends only cmd and bash and left the CLI running (measured) |
+| Society agent's shell tool | bash in `~/jarvis-agents/<id>`; each step stops on its own failure, so `cd x; ls` can no longer run half in the home folder; a timeout ends the command there | same | Git Bash in the same folder; PowerShell when Git for Windows is missing |
+| IDE panes | tmux, started by an uploaded launcher; survives app close and network loss, re-attached; a missing folder stops with a sentence instead of starting the agent in the home folder | same, tmux from Homebrew; a plain terminal is the user's zsh | no tmux: the agent runs in the SSH terminal (ConPTY) and ends with the channel; a plain terminal is PowerShell |
+| IDE folder sync, conversation copy | POSIX scripts on stdin | same | the same scripts in Git Bash; SFTP paths as `/C:/…` |
+| Keep working when this PC closes | offered | offered (keep the Mac awake: `pmset`, in the setup prompt) | not offered, and refused on quit |
+
+The SSH connect timeout is 20 s: a busy machine took longer than the old 12 s
+to log in. The setup prompt a coding agent runs on the target computer covers
+each OS: Remote Login and `pmset` on a Mac, Homebrew with tmux and git, and the
+Claude token saved straight into `~/.config/jarvis/agent.env`.
+
+Verified live:
+
+- **Windows 11 Pro** (German locale; this development PC reached over its LAN
+ address): facts, readiness, a CLI start through the launcher, a cancelled
+ turn leaving no process behind, an agent shell command with non-ASCII
+ output, a PowerShell pane (closing it, or the app, ends its program there),
+ and a git folder sent over and brought back with an edit made there.
+- **Linux** (Ubuntu 24.04 in Docker with a real OpenSSH server), as a zsh user
+ whose tmux lives in `/opt/homebrew/bin` and whose Claude Code lives in
+ `~/.local/bin` (both only on the rc files' `PATH`, as on a Mac) and as a
+ fish user: both found through the login `PATH`; readiness, an agent shell
+ command, a CLI turn with the runner's real argv and stream-json stdin, a
+ cancelled turn ending its process, a pane in the user's own shell that
+ survives the app quitting and is re-attached, a missing pane folder, and
+ the token file written with mode 600.
+
+Not verified live: a real Mac (the Keychain behaviour and `vm_stat`/
+`kern.boottime` parsing are covered by tests and Anthropic's documentation
+only), the install jobs on any OS (unit-tested scripts), planting a key with
+a password on Windows, a Windows `DefaultShell` of PowerShell, and Windows
+Server without winget. Covered by `tests/unit/computers/test_posix_remote.py`,
+`test_windows_remote.py`, `test_remote_terminal.py` and
+`tests/unit/society/test_remote_placement.py` against scripted SSH servers.
+
## Persistent Agentic IDE terminals (2026-09-28, T3)
diff --git a/jarvis/agent_chat/remote_cli.py b/jarvis/agent_chat/remote_cli.py
index e13bb1283f..4170d887a6 100644
--- a/jarvis/agent_chat/remote_cli.py
+++ b/jarvis/agent_chat/remote_cli.py
@@ -18,10 +18,13 @@ What does NOT travel:
and a remote CLI cannot reach it, so ``--mcp-config`` / the Codex
``mcp_servers`` overrides are dropped for remote turns.
-A Windows computer cannot take the turn on its command line (``cmd.exe``
-mangles non-ASCII text and line breaks, and stops at 8 191 characters), so
-there the system prompt is uploaded as a file and the CLI is started by a
-small Git Bash launcher uploaded next to it (``jarvis.computers.remote_os``).
+On every OS the turn is started by a small launcher uploaded first, with the
+system prompt as a file next to it (``jarvis.computers.remote_os``): the SSH
+command line goes through the user's login shell — fish re-reads it, and
+``cmd.exe`` mangles non-ASCII text and line breaks — and a prompt on argv
+hits Linux's 128 KiB limit for one argument. The launcher also puts the
+user's own ``PATH`` in front (a CLI in ``~/.local/bin`` or Homebrew is found)
+and reads the per-computer agent settings (a Claude token on a Mac).
"""
from __future__ import annotations
@@ -79,6 +82,15 @@ def _looks_like_launcher(part: str) -> bool:
return low.endswith((".exe", ".cmd", ".bat", ".ps1", ".js", ".mjs"))
+def _program_name(part: str) -> str:
+ """``claude`` for ``claude``, ``Claude.EXE`` or ``codex.cmd``."""
+ low = part.replace("\\", "/").rsplit("/", 1)[-1].lower()
+ for suffix in (".exe", ".cmd", ".bat", ".ps1"):
+ if low.endswith(suffix):
+ return low[: -len(suffix)]
+ return low
+
+
def remote_argv(
argv: Sequence[str],
*,
@@ -100,6 +112,11 @@ def remote_argv(
start = 0
while start < len(parts) and _looks_like_launcher(parts[start]):
start += 1
+ # A turn planned for another computer names its CLI bare ("claude"): the
+ # planner cannot resolve a path there. That name IS the program, not its
+ # first argument — kept, it ran as `claude claude --print …`.
+ if start == 0 and parts and _program_name(parts[0]) == _program_name(binary):
+ start = 1
rest = parts[start:]
out: list[str] = [binary]
skip = False
@@ -266,7 +283,7 @@ def placement_note(computer: Any, remote_cwd: str) -> str:
)
-async def _windows_launch(
+async def _launch(
opened: Any,
host: Any,
agent_id: str,
@@ -277,14 +294,19 @@ async def _windows_launch(
env: dict[str, str],
prompts: dict[str, str],
) -> str:
- """Upload the system prompt and a Git Bash launcher; the command that runs it."""
+ """Upload the system prompt and a launcher; the command line that runs it.
+
+ One path for every OS: the command line carries only the launcher's name,
+ so no login shell (fish, zsh, cmd) re-reads the turn, and no command-line
+ limit caps the system prompt.
+ """
from jarvis.computers import remote_os
uploaded: dict[str, str] = {}
for index, (local_path, text) in enumerate(prompts.items()):
name = remote_os.launcher_name(f"{agent_id}-prompt-{index}", ".md")
relative = f"{remote_os.LAUNCH_DIR}/{name}"
- await remote_os.upload_text(opened, host, relative, text)
+ await remote_os.upload_text(opened, host, relative, text, private=True)
uploaded[local_path] = f"{host.home}/{relative}"
command_argv = remote_argv(
argv,
@@ -295,9 +317,9 @@ async def _windows_launch(
)
launcher = f"{remote_os.LAUNCH_DIR}/{remote_os.launcher_name(agent_id)}"
script = remote_os.launcher_script(
- remote_cwd, command_argv, remote_env(env), pid_file=_pid_file(agent_id)
+ host, remote_cwd, command_argv, remote_env(env), pid_file=_pid_file(agent_id)
)
- await remote_os.upload_text(opened, host, launcher, script)
+ await remote_os.upload_text(opened, host, launcher, script, private=True)
return host.launcher_command(launcher)
@@ -321,7 +343,7 @@ async def spawn(
"""Start the CLI on ``computer_id`` inside the agent's remote workspace."""
from jarvis.computers import remote_os
from jarvis.computers.service import ComputerError, get_service
- from jarvis.computers.ssh import SshError, run_command
+ from jarvis.computers.ssh import SshError
from jarvis.society.remote import remote_workspace_expr
stack = contextlib.AsyncExitStack()
@@ -340,10 +362,7 @@ async def spawn(
f"mkdir -p {folder} && cd {folder} && {'pwd -W' if host.windows else 'pwd'} && "
f"(command -v {shlex.quote(binary)} >/dev/null 2>&1 && echo found || echo missing)"
)
- if host.windows:
- probe = await remote_os.run_bash(opened, host, check, timeout_s=30)
- else:
- probe = await run_command(opened, check, timeout_s=20)
+ probe = await remote_os.run_script(opened, host, check, timeout_s=30)
lines = [line.strip() for line in probe.stdout.splitlines() if line.strip()]
if len(lines) < 2:
said = (probe.stderr or probe.stdout).strip().splitlines()
@@ -354,27 +373,15 @@ async def spawn(
remote_cwd, presence = lines[-2], lines[-1]
if presence != "found":
raise RemoteCliUnavailable(
- f"Install {binary} on {computer.name} (and log in there once), "
- "or set the agent to run on this computer."
+ f"{binary} was not found on {computer.name}. Install it there (Computers, "
+ "Ready for coding agents) and log in once, or set the agent to run on "
+ "this computer."
)
note = placement_note(computer, remote_cwd)
prompts = {path: text + note for path, text in (system_prompt_files or {}).items()}
- if host.windows:
- command = await _windows_launch(
- opened, host, agent_id, argv, binary, local_cwd, remote_cwd, env, prompts
- )
- else:
- command_argv = remote_argv(
- argv,
- binary=binary,
- local_cwd=local_cwd,
- remote_cwd=remote_cwd,
- system_prompt_files=prompts,
- )
- assignments = " ".join(f"{k}={shlex.quote(v)}" for k, v in remote_env(env).items())
- command = (
- f"cd {shlex.quote(remote_cwd)} && exec env {assignments} {shlex.join(command_argv)}"
- )
+ command = await _launch(
+ opened, host, agent_id, argv, binary, local_cwd, remote_cwd, env, prompts
+ )
log.info("agent chat: %s turn for %s runs on %s", runner, agent_id, computer.name)
process = await opened.conn.create_process(command, encoding=None)
except (ComputerError, SshError) as exc:
@@ -383,11 +390,11 @@ async def spawn(
except BaseException:
await stack.aclose()
raise
- stop = None
- if host.windows:
- stop_command = remote_os.stop_script(_pid_file(agent_id))
+ stop_command = remote_os.stop_script(host, _pid_file(agent_id))
- async def stop() -> None:
- await remote_os.run_bash(opened, host, stop_command, timeout_s=30)
+ async def stop() -> None:
+ # Hanging up does not reliably end the CLI: on Windows it orphans it
+ # (measured), and a POSIX CLI may ignore the hang-up until it writes.
+ await remote_os.run_script(opened, host, stop_command, timeout_s=30)
return RemoteCliProcess(process, stack, stop=stop)
diff --git a/jarvis/computers/probe.py b/jarvis/computers/probe.py
index 0daefcd622..0ede036a8b 100644
--- a/jarvis/computers/probe.py
+++ b/jarvis/computers/probe.py
@@ -3,7 +3,9 @@
A check runs ONE script over SSH that prints labelled sections (hostname, OS,
cores, memory, disk, uptime, load). It only reads — nothing is installed or
changed. Linux answers every section of :data:`PROBE_SCRIPT`; macOS answers
-through its own tools; a Windows OpenSSH server gets
+through its own tools (``vm_stat`` for memory, ``kern.boottime`` for uptime,
+the Data volume for disk — ``/`` is the small sealed system volume there); a
+Windows OpenSSH server gets
:data:`WINDOWS_PROBE_SCRIPT` (PowerShell, sent on stdin), which prints the
same sections in the same shapes, so one parser reads all three. Windows has
no load average; that section stays empty.
@@ -22,10 +24,26 @@ echo "@@os"; cat /etc/os-release 2>/dev/null
echo "@@darwin"; sw_vers 2>/dev/null
echo "@@nproc"; nproc 2>/dev/null || getconf _NPROCESSORS_ONLN 2>/dev/null \
|| sysctl -n hw.ncpu 2>/dev/null
-echo "@@meminfo"; head -n 3 /proc/meminfo 2>/dev/null
+echo "@@meminfo"
+if [ -r /proc/meminfo ]; then head -n 3 /proc/meminfo
+elif command -v vm_stat >/dev/null 2>&1; then
+ vm_stat | awk -v page="$(sysctl -n hw.pagesize 2>/dev/null)" \
+ -v total="$(sysctl -n hw.memsize 2>/dev/null)" '
+ /Pages free/ {f=$3} /Pages inactive/ {i=$3} /Pages speculative/ {s=$3}
+ END { gsub(/\./, "", f); gsub(/\./, "", i); gsub(/\./, "", s)
+ if (total > 0 && page > 0) {
+ printf "MemTotal: %.0f kB\n", total / 1024
+ printf "MemAvailable: %.0f kB\n", (f + i + s) * page / 1024 } }'
+fi
echo "@@memsize"; sysctl -n hw.memsize 2>/dev/null
-echo "@@df"; df -Pk / 2>/dev/null | tail -n 1
-echo "@@uptime"; cat /proc/uptime 2>/dev/null
+echo "@@df"; d=/; [ -d /System/Volumes/Data ] && d=/System/Volumes/Data
+df -Pk "$d" 2>/dev/null | tail -n 1
+echo "@@uptime"
+if [ -r /proc/uptime ]; then cat /proc/uptime
+else
+ b=$(sysctl -n kern.boottime 2>/dev/null | sed -n 's/.*sec = \([0-9]*\).*/\1/p')
+ [ -n "$b" ] && echo $(( $(date +%s) - b ))
+fi
echo "@@loadavg"; cat /proc/loadavg 2>/dev/null || sysctl -n vm.loadavg 2>/dev/null
echo "@@end"
""".strip()
diff --git a/jarvis/computers/remote_os.py b/jarvis/computers/remote_os.py
index 9d95964f4a..4ae6fc5d1e 100644
--- a/jarvis/computers/remote_os.py
+++ b/jarvis/computers/remote_os.py
@@ -1,23 +1,27 @@
"""Which shell a connected computer answers in, and how to speak it.
-A POSIX machine (Linux, macOS, BSD) runs every command in ``sh`` — the
-original path, unchanged. A Windows machine with the OpenSSH server runs
-commands in ``cmd.exe`` (or PowerShell, when its ``DefaultShell`` says so),
-and three facts decide how Jarvis talks to it:
-
-* ``cmd.exe`` carries neither line breaks nor non-ASCII text on its command
- line intact (measured: each non-ASCII letter arrived as two U+FFFD
- replacement characters), and it caps the line at
- 8 191 characters. So nothing of substance travels there: a script goes on
- **stdin** and is read whole before it runs, and a program that needs stdin
- or a terminal itself (a coding CLI's turn, an IDE pane) is started by a
- small launcher file uploaded over SFTP (:func:`launcher_script`).
-* Windows PowerShell 5.1 ships with every Windows 10/11 and Server box: it
- reads the machine's facts, what is installed, and plants a login key
- (:data:`POWERSHELL_STDIN`).
-* Git for Windows' ``bash`` runs the same POSIX scripts the Linux path uses —
- code sync, conversation copies, the launchers. Claude Code on Windows needs
- Git for Windows anyway, and so does every git workspace.
+Every feature that runs something on a connected computer goes through this
+module, on Linux, macOS and Windows alike. Two rules make that work anywhere:
+
+* **Nothing of substance travels on the SSH command line.** The server hands
+ that line to the user's LOGIN shell, which may be bash, zsh, fish, tcsh or
+ ``cmd.exe`` — each parses it differently (fish has no ``if …; then``, cmd
+ turns every non-ASCII letter into two U+FFFD characters and stops at 8 191
+ characters). So a script goes on **stdin** to a known shell
+ (:meth:`RemoteHost.script_command`), and a program that needs stdin or a
+ terminal itself (a coding CLI's turn, an IDE pane) is started by a small
+ launcher file uploaded over SFTP (:meth:`RemoteHost.launcher_command`).
+* **Programs are found the way the user's own terminal finds them.** Over SSH
+ the search path is short: ``~/.local/bin`` (where Claude Code installs
+ itself) and ``/opt/homebrew/bin`` (Homebrew on Apple silicon) are missing.
+ Detection asks the user's login shell once for its full ``PATH``
+ (:func:`detect`), and :func:`env_preamble` puts it in front of every script
+ and launcher, plus the well-known install folders that exist.
+
+On Windows (``cmd`` or PowerShell as the OpenSSH ``DefaultShell``), machine
+facts, readiness and key planting run in Windows PowerShell 5.1
+(:data:`POWERSHELL_STDIN`); everything POSIX-shaped runs in Git for Windows'
+bash, which Claude Code on Windows needs anyway.
Detection is one ``echo`` that each shell answers differently
(:data:`DETECT_COMMAND`), cached per computer and server identity
@@ -38,7 +42,7 @@ RemoteOs = Literal["posix", "windows"]
RemoteShell = Literal["sh", "cmd", "powershell"]
#: ``cmd`` prints ``Windows_NT $env:OS``, PowerShell prints ``%OS%`` and
-#: ``Windows_NT`` on two lines, ``sh`` prints ``%OS% :OS``.
+#: ``Windows_NT`` on two lines, a POSIX shell prints ``%OS% :OS`` (or nothing).
DETECT_COMMAND: Final[str] = "echo %OS% $env:OS"
#: Runs the PowerShell script sent on stdin, whole (a multi-line block works),
@@ -51,13 +55,31 @@ POWERSHELL_STDIN: Final[str] = (
'& ([scriptblock]::Create([Console]::In.ReadToEnd()))"'
)
-#: Folder (relative to the remote home) for the launcher files of CLI turns
-#: and IDE panes on a Windows computer.
+#: Folder (relative to the remote home) for launcher, prompt and pid files.
LAUNCH_DIR: Final[str] = "jarvis-agents/.launch"
+#: Per-computer agent settings (relative to the remote home), sourced by every
+#: launcher: ``CLAUDE_CODE_OAUTH_TOKEN`` lives here on a Mac, whose Keychain
+#: is locked in SSH sessions.
+AGENT_ENV_FILE: Final[str] = ".config/jarvis/agent.env"
+
+#: The user's own install folders: put FIRST when present, so a Node.js the
+#: readiness panel installed there wins over an older one from the system.
+USER_BIN_DIRS: Final[tuple[str, ...]] = ("$HOME/.local/bin", "$HOME/bin")
+
+#: System install folders a login may not put on ``PATH`` over SSH; appended.
+WELL_KNOWN_BIN_DIRS: Final[tuple[str, ...]] = (
+ "/opt/homebrew/bin",
+ "/opt/homebrew/sbin",
+ "/usr/local/bin",
+ "/usr/local/sbin",
+ "/home/linuxbrew/.linuxbrew/bin",
+ "/snap/bin",
+)
+
#: Git Bash converts arguments and variables that look like POSIX paths when
#: it starts a Windows program ("/help" would become "C:/Program Files/Git/
-#: help"). A launcher hands its argv over untouched.
+#: help"). A Windows launcher hands its argv over untouched.
_NO_PATH_CONVERSION: Final[str] = "export MSYS_NO_PATHCONV=1 MSYS2_ARG_CONV_EXCL='*'"
_WINDOWS_FACTS: Final[str] = r"""
@@ -75,6 +97,19 @@ foreach ($path in $candidates) {
}
""".strip()
+#: Sent to ``/bin/sh -s``: works whatever the login shell is.
+_POSIX_FACTS: Final[str] = r"""
+printf 'home %s\n' "$HOME"
+printf 'shell %s\n' "${SHELL:-}"
+printf 'system %s\n' "$(uname -s 2>/dev/null)"
+for b in /bin/bash /usr/bin/bash /usr/local/bin/bash /opt/homebrew/bin/bash; do
+ if [ -x "$b" ]; then printf 'bash %s\n' "$b"; break; fi
+done
+""".strip()
+
+_PATH_MARK: Final[str] = "__JARVIS_PATH__"
+_PATH_RE = re.compile(rf"{_PATH_MARK}(.*?){_PATH_MARK}")
+
_DRIVE_PATH = re.compile(r"^[A-Za-z]:/")
_PLAIN_PATH = re.compile(r"^[A-Za-z]:/[A-Za-z0-9/._-]*$")
@@ -85,15 +120,26 @@ class RemoteHost:
os: RemoteOs = "posix"
default_shell: RemoteShell = "sh"
- #: Windows only: the home folder with forward slashes (``C:/Users/ada``).
+ #: The home folder: ``/home/ada``; on Windows ``C:/Users/ada``.
home: str = ""
- #: Windows only: Git for Windows' bash, ``None`` when it is not installed.
+ #: A bash to run scripts in: ``/bin/bash`` on POSIX (``None`` = plain sh),
+ #: Git for Windows' bash on Windows (``None`` = not installed).
bash: str | None = None
+ #: POSIX: the user's login shell (``$SHELL``) — a plain IDE terminal.
+ login_shell: str | None = None
+ #: POSIX: ``PATH`` as the user's own login shell builds it.
+ path: str | None = None
+ #: POSIX: ``uname -s`` (``Linux``, ``Darwin``, ``FreeBSD``).
+ system: str | None = None
@property
def windows(self) -> bool:
return self.os == "windows"
+ @property
+ def mac(self) -> bool:
+ return self.system == "Darwin"
+
def program(self, path: str, args: str = "") -> str:
"""The command line that starts ``path`` in this computer's default shell.
@@ -104,18 +150,27 @@ class RemoteHost:
return f'{call}"{path}" {args}'.rstrip()
def bash_script_command(self) -> str:
- """Git Bash reading a script from stdin, as a login shell."""
+ """Git Bash reading a script from stdin, as a login shell (Windows)."""
if not self.bash:
raise SshError("protocol", "Git for Windows is not installed on this computer.")
return self.program(self.bash, "-l -s")
+ def script_command(self) -> str:
+ """The command line that runs a POSIX script sent on stdin."""
+ if self.windows:
+ return self.bash_script_command()
+ return f"{self.bash} -s" if self.bash else "/bin/sh -s"
+
def launcher_command(self, relative_path: str) -> str:
- """Git Bash running an uploaded launcher (a path relative to the home folder).
+ """The command line that runs an uploaded launcher (relative to the home).
- The path goes absolute when the home folder needs no quoting; a home
- with spaces or umlauts stays relative, which the SSH server resolves
- from that same home — ``cmd`` gets one quoted part per line, never two.
+ POSIX: ``/bin/sh <path>`` — the SSH server starts in the home folder.
+ Windows: Git Bash; the path goes absolute when the home folder needs no
+ quoting, and stays relative otherwise — ``cmd`` gets one quoted part per
+ line, never two.
"""
+ if not self.windows:
+ return f"/bin/sh {relative_path}"
if not self.bash:
raise SshError("protocol", "Git for Windows is not installed on this computer.")
target = f"{self.home}/{relative_path}" if _PLAIN_PATH.match(self.home) else relative_path
@@ -145,6 +200,57 @@ def parse_windows_facts(stdout: str) -> tuple[str, str | None]:
return home, bash
+def parse_posix_facts(stdout: str) -> dict[str, str]:
+ facts: dict[str, str] = {}
+ for raw in stdout.splitlines():
+ key, _, value = raw.strip().partition(" ")
+ if key in ("home", "shell", "system", "bash") and value.strip():
+ facts[key] = value.strip()
+ return facts
+
+
+def parse_login_path(stdout: str) -> str | None:
+ """The ``PATH`` between the markers, when it looks like one."""
+ found = _PATH_RE.findall(stdout)
+ if not found:
+ return None
+ value = found[-1].strip()
+ parts = [p for p in value.split(":") if p]
+ if not parts or any(not p.startswith("/") or "\n" in p for p in parts):
+ return None
+ return ":".join(parts)
+
+
+def login_path_script(flags: str) -> str:
+ """Ask the login shell for its ``PATH``; rc-file chatter is cut by the markers."""
+ probe = shlex.quote(f'printf "\\n{_PATH_MARK}%s{_PATH_MARK}\\n" "$PATH"')
+ return (
+ 'cd "$HOME" 2>/dev/null\n'
+ f'"${{SHELL:-/bin/sh}}" {flags} {probe} </dev/null 2>/dev/null\n'
+ "exit 0\n"
+ )
+
+
+def env_preamble(host: RemoteHost) -> str:
+ """The lines that give a POSIX script the user's ``PATH`` ('' on Windows)."""
+ if host.windows:
+ return ""
+ lines = []
+ if host.path:
+ lines.append(f'PATH={shlex.quote(host.path)}:"$PATH"')
+ user = " ".join(f'"{d}"' for d in USER_BIN_DIRS)
+ lines.append(
+ f"for d in {user}; do "
+ 'case ":$PATH:" in *":$d:"*) ;; *) [ -d "$d" ] && PATH="$d:$PATH" ;; esac; done'
+ )
+ lines.append(
+ f"for d in {' '.join(WELL_KNOWN_BIN_DIRS)}; do "
+ 'case ":$PATH:" in *":$d:"*) ;; *) [ -d "$d" ] && PATH="$PATH:$d" ;; esac; done'
+ )
+ lines.append("export PATH")
+ return "\n".join(lines) + "\n"
+
+
async def run_powershell(session: Session, script: str, *, timeout_s: float) -> CommandResult:
"""One PowerShell script on a Windows computer, sent on stdin."""
return await run_command(session, POWERSHELL_STDIN, timeout_s=timeout_s, stdin=script)
@@ -157,29 +263,71 @@ async def run_bash(
return await run_command(session, host.bash_script_command(), timeout_s=timeout_s, stdin=script)
+async def run_script(
+ session: Session, host: RemoteHost, script: str, *, timeout_s: float
+) -> CommandResult:
+ """One POSIX script on any computer: sh/bash on POSIX, Git Bash on Windows.
+
+ The script is sent on stdin, after :func:`env_preamble`, so neither the
+ login shell's syntax nor its command-line limits can change it.
+ """
+ return await run_command(
+ session, host.script_command(), timeout_s=timeout_s, stdin=env_preamble(host) + script
+ )
+
+
+async def _login_path(session: Session) -> str | None:
+ """The login shell's ``PATH``: interactive first (zsh and bash put most in
+ their rc files), then login-only for an rc file that stalls without a
+ terminal, then nothing — the well-known folders still apply."""
+ for flags, timeout in (("-ilc", 20.0), ("-lc", 15.0)):
+ try:
+ answer = await run_command(
+ session, "/bin/sh -s", timeout_s=timeout, stdin=login_path_script(flags)
+ )
+ except SshError:
+ continue
+ path = parse_login_path(answer.stdout)
+ if path:
+ return path
+ return None
+
+
async def detect(session: Session) -> RemoteHost:
- """Ask the computer which shell it speaks (and, on Windows, where Git Bash is)."""
+ """Ask the computer which shell it speaks, where bash is, and its ``PATH``."""
answer = await run_command(session, DETECT_COMMAND, timeout_s=20)
os_name, shell = parse_detect(answer.stdout)
- if os_name == "posix":
- return RemoteHost()
- facts = await run_powershell(session, _WINDOWS_FACTS, timeout_s=45)
- home, bash = parse_windows_facts(facts.stdout)
- return RemoteHost(os="windows", default_shell=shell, home=home, bash=bash)
+ if os_name == "windows":
+ facts = await run_powershell(session, _WINDOWS_FACTS, timeout_s=45)
+ home, bash = parse_windows_facts(facts.stdout)
+ return RemoteHost(os="windows", default_shell=shell, home=home, bash=bash)
+ posix = parse_posix_facts(
+ (await run_command(session, "/bin/sh -s", timeout_s=30, stdin=_POSIX_FACTS)).stdout
+ )
+ return RemoteHost(
+ os="posix",
+ home=posix.get("home", ""),
+ bash=posix.get("bash"),
+ login_shell=posix.get("shell"),
+ path=await _login_path(session),
+ system=posix.get("system"),
+ )
#: computer id -> (pinned server identity, what it answered)
_CACHE: dict[str, tuple[str, RemoteHost]] = {}
-async def remote_host(computer_id: str, session: Session) -> RemoteHost:
+async def remote_host(computer_id: str, session: Session, *, refresh: bool = False) -> RemoteHost:
""":func:`detect`, remembered while the server keeps its identity.
- A Windows answer without Git Bash is asked again next time: installing
- Git for Windows must take effect without a restart of the app.
+ ``refresh`` asks again (a health check, the readiness panel), so a CLI
+ installed since into a new folder is found. A Windows answer without Git
+ Bash is asked again anyway: installing Git for Windows must take effect
+ without a restart of the app.
"""
cached = _CACHE.get(computer_id)
- if cached is not None and cached[0] == session.host_key:
+ if not refresh and cached is not None and cached[0] == session.host_key:
host = cached[1]
if not host.windows or host.bash:
return host
@@ -192,37 +340,109 @@ def forget(computer_id: str) -> None:
_CACHE.pop(computer_id, None)
+def pid_record(host: RemoteHost, pid_file: str) -> str:
+ """The script lines that note what :func:`stop_script` must end later.
+
+ POSIX: the process group the SSH server gave this command (``setsid``), so
+ the stop reaches everything the program started. Windows: the Git Bash
+ that becomes the program's parent; ``taskkill /T`` ends its tree.
+ """
+ target = f'"$HOME"/{shlex.quote(pid_file)}'
+ folder = f'"$HOME"/{shlex.quote(pid_file.rsplit("/", 1)[0])}' if "/" in pid_file else '"$HOME"'
+ make = f"mkdir -p {folder} 2>/dev/null\n"
+ if host.windows:
+ return make + f"cat /proc/$$/winpid > {target} 2>/dev/null || true\n"
+ return (
+ make
+ + "g=$(ps -o pgid= -p $$ 2>/dev/null | tr -d ' ')\n"
+ + f'echo "${{g:-$$}}" > {target} 2>/dev/null || true\n'
+ )
+
+
+def _source_agent_env() -> str:
+ return f'[ -f "$HOME/{AGENT_ENV_FILE}" ] && . "$HOME/{AGENT_ENV_FILE}"\n'
+
+
def launcher_script(
+ host: RemoteHost,
cwd: str,
argv: Sequence[str],
env: Mapping[str, str] | None = None,
*,
pid_file: str | None = None,
) -> str:
- """The Git Bash file that starts ``argv`` in ``cwd`` with stdin and terminal intact.
+ """The launcher file that starts ``argv`` in ``cwd`` with stdin and terminal intact.
- ``pid_file`` (relative to the home folder) receives the Windows id of the
- bash that becomes ``argv``'s parent: hanging up the SSH channel ends that
- bash but not the program below it, so :func:`stop_script` ends the tree.
+ ``pid_file`` (relative to the home folder) receives what :func:`stop_script`
+ needs to end the program with everything it started: hanging up the SSH
+ channel does not reliably do that (on Windows it ends only cmd and bash).
"""
- lines = [f"cd -- {shlex.quote(cwd)} || exit 97"]
+ lines = [env_preamble(host).rstrip("\n"), _source_agent_env().rstrip("\n")]
+ lines.append(f"cd -- {shlex.quote(cwd)} || exit 97")
if pid_file:
- lines.append(f'cat /proc/$$/winpid > "$HOME"/{shlex.quote(pid_file)} 2>/dev/null || true')
+ lines.append(pid_record(host, pid_file).rstrip("\n"))
for key, value in (env or {}).items():
lines.append(f"export {key}={shlex.quote(value)}")
- lines.append(_NO_PATH_CONVERSION)
+ if host.windows:
+ lines.append(_NO_PATH_CONVERSION)
lines.append("exec " + shlex.join(argv))
- return "\n".join(lines) + "\n"
+ return "\n".join(line for line in lines if line) + "\n"
-def stop_script(pid_file: str) -> str:
- """The Git Bash script that ends a launcher's whole process tree (Windows)."""
+def pane_launcher_script(
+ host: RemoteHost,
+ *,
+ name: str,
+ self_path: str,
+ cwd: str,
+ argv: Sequence[str],
+ cols: int,
+ rows: int,
+) -> str:
+ """A POSIX IDE pane: create-or-attach its tmux session, the agent inside.
+
+ The same file runs twice: first as the SSH command (it starts or re-joins
+ tmux), then with ``run`` as the session's own command (it starts the
+ agent). tmux hands its command to the login shell — fish included — so the
+ only thing on that line is ``sh "<this file>" run``. A missing folder stops
+ with a sentence instead of starting the agent in the home folder.
+ """
+ session = shlex.quote(name)
+ folder = shlex.quote(cwd)
return (
- f'f="$HOME"/{shlex.quote(pid_file)}\n'
- '[ -f "$f" ] || exit 0\n'
- 'p=$(cat "$f"); rm -f "$f"\n'
- '[ -n "$p" ] && MSYS_NO_PATHCONV=1 taskkill /PID "$p" /T /F >/dev/null 2>&1\n'
- "exit 0\n"
+ env_preamble(host)
+ + _source_agent_env()
+ + 'if [ "${1:-}" = run ]; then\n'
+ + f" cd -- {folder} || {{ printf 'The folder %s is missing on this computer.\\n' "
+ + f"{folder}; sleep 5; exit 97; }}\n"
+ + f" exec {shlex.join(argv)}\n"
+ + "fi\n"
+ + f'self="$HOME"/{shlex.quote(self_path)}\n'
+ + f"exec tmux -u new-session -A -s {session} -x {cols} -y {rows} -c {folder} "
+ + '"sh \\"$self\\" run" '
+ + f"\\; set-option -t {session} status off "
+ + f"\\; set-option -t {session} mouse off "
+ + f"\\; set-option -t {session} escape-time 0\n"
+ )
+
+
+def stop_script(host: RemoteHost, pid_file: str) -> str:
+ """The script that ends a launcher's program and everything it started."""
+ head = f'f="$HOME"/{shlex.quote(pid_file)}\n[ -f "$f" ] || exit 0\np=$(cat "$f"); rm -f "$f"\n'
+ if host.windows:
+ return (
+ head
+ + '[ -n "$p" ] && MSYS_NO_PATHCONV=1 taskkill /PID "$p" /T /F >/dev/null 2>&1\n'
+ + "exit 0\n"
+ )
+ return (
+ head
+ + 'case "$p" in ""|*[!0-9]*|0|1) exit 0 ;; esac\n'
+ + 'kill -TERM -- "-$p" 2>/dev/null || kill -TERM "$p" 2>/dev/null\n'
+ + "i=0\n"
+ + 'while [ "$i" -lt 5 ] && kill -0 -- "-$p" 2>/dev/null; do sleep 1; i=$((i + 1)); done\n'
+ + 'kill -KILL -- "-$p" 2>/dev/null\n'
+ + "exit 0\n"
)
@@ -231,8 +451,14 @@ def launcher_name(identity: str, suffix: str = ".sh") -> str:
return re.sub(r"[^A-Za-z0-9_.-]", "-", identity)[:64] + suffix
-async def upload_text(session: Session, host: RemoteHost, path: str, text: str) -> None:
- """Write ``text`` (UTF-8) to ``path`` on the computer, creating its folder."""
+async def upload_text(
+ session: Session, host: RemoteHost, path: str, text: str, *, private: bool = False
+) -> None:
+ """Write ``text`` (UTF-8) to ``path`` on the computer, creating its folder.
+
+ ``private`` makes the file readable by its owner only (POSIX; a Windows
+ profile folder already is).
+ """
import asyncssh
remote = host.sftp_path(path)
@@ -243,6 +469,8 @@ async def upload_text(session: Session, host: RemoteHost, path: str, text: str)
await sftp.makedirs(folder, exist_ok=True)
async with sftp.open(remote, "wb") as handle:
await handle.write(text.encode("utf-8"))
+ if private and not host.windows:
+ await sftp.chmod(remote, 0o600)
except (asyncssh.Error, OSError) as exc:
raise SshError("protocol", f"A file could not be written there: {exc}") from exc
diff --git a/jarvis/computers/remote_terminal.py b/jarvis/computers/remote_terminal.py
index 4dd8ad5edb..3ab0abf252 100644
--- a/jarvis/computers/remote_terminal.py
+++ b/jarvis/computers/remote_terminal.py
@@ -17,6 +17,12 @@ A dropped connection is not an exit: the pool reconnects with jittered backoff
(AP-33) and re-attaches to the still-running tmux session. Only a session that
is really gone on the server reports the pane closed.
+The pane is started by a launcher file uploaded first
+(``remote_os.pane_launcher_script``): the SSH command line holds only its
+name, so a fish or zsh login shell cannot re-read it, and the launcher puts
+the user's own ``PATH`` in front — tmux from Homebrew and a CLI in
+``~/.local/bin`` are found on a Mac and a Linux server alike.
+
A Windows computer has no tmux. There a pane runs its agent directly in the
SSH terminal (ConPTY), started by a small Git Bash launcher uploaded first
(``jarvis.computers.remote_os``), and non-interactive commands run in Git Bash
@@ -60,41 +66,17 @@ def tmux_session_name(identity: str) -> str:
return "jv-" + _NAME_RE.sub("-", identity)[:48]
-def tmux_command(
- name: str, argv: tuple[str, ...] | list[str], cwd: str, cols: int, rows: int
-) -> str:
- """Create-or-attach the pane's tmux session, quiet and full-screen.
+def pane_argv(host: remote_os.RemoteHost, argv: tuple[str, ...] | list[str]) -> tuple[str, ...]:
+ """A pane's argv on ``host``: a plain terminal is that computer's own shell.
- ``-A`` attaches when the session already exists, so the same command both
- starts a new agent and re-joins a running one; the agent's argv is only
- used for a new session. The status line and mouse capture are off — the
- pane is the agent's screen, not tmux's.
+ The IDE asks for ``bash -l``; a Mac user's shell is zsh, and Windows has
+ PowerShell.
"""
- agent = shlex.join(argv)
- session = shlex.quote(name)
- return (
- f"tmux -u new-session -A -s {session} -x {cols} -y {rows} -c {shlex.quote(cwd)} "
- f"{shlex.quote(agent)} "
- f"\\; set-option -t {session} status off "
- f"\\; set-option -t {session} mouse off "
- f"\\; set-option -t {session} escape-time 0"
- )
-
-
-def windows_pane_argv(argv: tuple[str, ...] | list[str]) -> tuple[str, ...]:
- """A pane's argv for a Windows computer: the login shell becomes PowerShell."""
- if tuple(argv) == ("bash", "-l"):
+ if tuple(argv) != ("bash", "-l"):
+ return tuple(argv)
+ if host.windows:
return ("powershell.exe", "-NoLogo")
- return tuple(argv)
-
-
-def login_shell(command: str) -> str:
- """Run through a login shell so user-installed CLIs (npm, nvm) are on PATH."""
- quoted = shlex.quote(command)
- return (
- "if command -v bash >/dev/null 2>&1; "
- f"then exec bash -lc {quoted}; else exec sh -lc {quoted}; fi"
- )
+ return (host.login_shell or host.bash or "sh", "-l")
@dataclass
@@ -172,12 +154,8 @@ class SshPtyPool:
"""
if self._home is None:
host = await self.host()
- if host.windows:
- self._home = host.home or "C:/Users/Public"
- else:
- session = await self.connection()
- result = await session.conn.run('printf %s "$HOME"', check=False)
- self._home = str(result.stdout or "").strip() or "/root"
+ fallback = "C:/Users/Public" if host.windows else "/root"
+ self._home = host.home or fallback
return self._home
async def sftp_path(self, path: str) -> str:
@@ -186,35 +164,27 @@ class SshPtyPool:
async def run(self, command: str, *, timeout_s: float = 60.0) -> tuple[int, str, str]:
"""One non-interactive command on the shared connection.
- A POSIX computer runs it in a login shell; a Windows one in Git Bash,
- from stdin.
+ Sent on stdin to sh/bash (Git Bash on Windows) behind the user's own
+ ``PATH`` — never to the login shell, which may be fish or cmd.
"""
host = await self.host()
session = await self.connection()
- if host.windows:
- if not host.bash:
- raise ComputerError(
- "This Windows computer needs Git for Windows first. "
- + remote_os.GIT_FOR_WINDOWS_HINT,
- status=409,
- )
- result = await asyncio.wait_for(
- session.conn.run(
- host.bash_script_command(),
- input=command,
- check=False,
- encoding="utf-8",
- errors="replace",
- ),
- timeout=timeout_s,
- )
- else:
- result = await asyncio.wait_for(
- session.conn.run(
- login_shell(command), check=False, encoding="utf-8", errors="replace"
- ),
- timeout=timeout_s,
+ if host.windows and not host.bash:
+ raise ComputerError(
+ "This Windows computer needs Git for Windows first. "
+ + remote_os.GIT_FOR_WINDOWS_HINT,
+ status=409,
)
+ result = await asyncio.wait_for(
+ session.conn.run(
+ host.script_command(),
+ input=remote_os.env_preamble(host) + command,
+ check=False,
+ encoding="utf-8",
+ errors="replace",
+ ),
+ timeout=timeout_s,
+ )
code = result.exit_status if result.exit_status is not None else -1
return code, str(result.stdout or ""), str(result.stderr or "")
@@ -244,10 +214,15 @@ class SshPtyPool:
identity = str((meta or {}).get("history_id") or shell_id)
name = tmux_session_name(identity)
host = await self.host()
- if host.windows:
- command = await self._windows_launcher(host, name, shell_argv, cwd)
- else:
- command = login_shell(tmux_command(name, tuple(shell_argv), cwd, cols, rows))
+ if not self._tmux_checked and not host.windows:
+ code, _out, _err = await self.run("command -v tmux >/dev/null", timeout_s=20)
+ if code != 0:
+ raise ComputerError(
+ "tmux is not installed on this computer. Open Computers, then Prepare.",
+ status=409,
+ )
+ self._tmux_checked = True
+ command = await self._launcher(host, name, pane_argv(host, shell_argv), cwd, cols, rows)
pane = _Pane(
terminal_id=uuid4().hex,
tmux_name=name,
@@ -258,14 +233,6 @@ class SshPtyPool:
on_closed=on_closed,
on_probe=on_probe,
)
- if not self._tmux_checked and not host.windows:
- code, _out, _err = await self.run("command -v tmux >/dev/null", timeout_s=20)
- if code != 0:
- raise ComputerError(
- "tmux is not installed on this computer. Open Computers, then Prepare.",
- status=409,
- )
- self._tmux_checked = True
# A new viewer of the SAME tmux session replaces the old channel; the
# agent inside is untouched (``tmux new-session -A`` re-joins it).
for other_id, other in list(self._panes.items()):
@@ -353,22 +320,33 @@ class SshPtyPool:
# -- internals ---------------------------------------------------------------
- async def _windows_launcher(
+ async def _launcher(
self,
host: remote_os.RemoteHost,
name: str,
- shell_argv: tuple[str, ...] | list[str],
+ argv: tuple[str, ...],
cwd: str,
+ cols: int,
+ rows: int,
) -> str:
- """Upload the pane's Git Bash launcher; the command that starts it."""
- if not host.bash:
+ """Upload the pane's launcher; the command line that starts it.
+
+ POSIX: create-or-attach the tmux session (re-used verbatim on every
+ re-attach). Windows: the agent itself, in Git Bash.
+ """
+ if host.windows and not host.bash:
raise ComputerError(
"This Windows computer needs Git for Windows first. "
+ remote_os.GIT_FOR_WINDOWS_HINT,
status=409,
)
relative = f"{remote_os.LAUNCH_DIR}/{remote_os.launcher_name(name)}"
- script = remote_os.launcher_script(cwd, windows_pane_argv(shell_argv))
+ if host.windows:
+ script = remote_os.launcher_script(host, cwd, argv)
+ else:
+ script = remote_os.pane_launcher_script(
+ host, name=name, self_path=relative, cwd=cwd, argv=argv, cols=cols, rows=rows
+ )
session = await self.connection()
try:
await remote_os.upload_text(session, host, relative, script)
diff --git a/jarvis/computers/service.py b/jarvis/computers/service.py
index 7227430b36..66993fc930 100644
--- a/jarvis/computers/service.py
+++ b/jarvis/computers/service.py
@@ -60,7 +60,7 @@ _PROBE_TIMEOUT_S = 25.0
async def _probe(opened: Session, host: remote_os.RemoteHost) -> CommandResult:
- """The health script in the language the computer speaks."""
+ """The health script in the language the computer speaks, sent on stdin."""
if host.windows:
return await remote_os.run_powershell(
# PowerShell alone took 6 s to start on a busy Windows VM.
@@ -68,7 +68,7 @@ async def _probe(opened: Session, host: remote_os.RemoteHost) -> CommandResult:
WINDOWS_PROBE_SCRIPT,
timeout_s=_PROBE_TIMEOUT_S * 2,
)
- return await run_command(opened, PROBE_SCRIPT, timeout_s=_PROBE_TIMEOUT_S)
+ return await remote_os.run_script(opened, host, PROBE_SCRIPT, timeout_s=_PROBE_TIMEOUT_S)
class ComputerError(Exception):
@@ -329,7 +329,9 @@ class ComputerService:
try:
async with self.session(computer_id) as opened:
try:
- host = await remote_os.remote_host(computer_id, opened)
+ # A check asks afresh: a CLI installed since may live in a
+ # folder the remembered PATH does not have yet.
+ host = await remote_os.remote_host(computer_id, opened, refresh=True)
result = await _probe(opened, host)
except SshError as exc:
# A probe that times out or loses the channel is a health
@@ -409,8 +411,8 @@ class ComputerService:
opened, authorize_key_script_windows(identity.public_key_line()), timeout_s=30
)
else:
- result = await run_command(
- opened, authorize_key_command(identity.public_key_line()), timeout_s=20
+ result = await remote_os.run_script(
+ opened, host, authorize_key_command(identity.public_key_line()), timeout_s=20
)
except SshError as exc:
raise ComputerError(exc.message, status=502, kind=exc.kind) from exc
diff --git a/jarvis/computers/ssh.py b/jarvis/computers/ssh.py
index f56e80ebf5..96261fab0b 100644
--- a/jarvis/computers/ssh.py
+++ b/jarvis/computers/ssh.py
@@ -27,7 +27,8 @@ log = logging.getLogger(__name__)
SshErrorKind = Literal["unreachable", "timeout", "auth", "host_key_changed", "protocol"]
-CONNECT_TIMEOUT_S = 12.0
+#: A busy machine (measured: a loaded Windows box) needed more than 12 s to log in.
+CONNECT_TIMEOUT_S = 20.0
#: Keepalive probes: a silent connection counts as dead after about 45 s.
KEEPALIVE_INTERVAL_S = 15
KEEPALIVE_COUNT_MAX = 3
diff --git a/jarvis/computers/toolbox.py b/jarvis/computers/toolbox.py
index 4f703b9260..bdbe4ab257 100644
--- a/jarvis/computers/toolbox.py
+++ b/jarvis/computers/toolbox.py
@@ -2,32 +2,43 @@
A remote IDE pane needs ``tmux`` (the server owns the agent), ``git`` (the
workspace travels as a git bundle) and the agent CLI itself, logged in. This
-module reads what is there in one command, installs what is missing ONLY when
+module reads what is there in one script, installs what is missing ONLY when
the user asks (herdr's rule: nothing is installed on a server unasked), and can
-copy this computer's CLI login to the server on an explicit click — never on
-its own.
+copy this computer's CLI login — or a Claude token — to the server on an
+explicit click, never on its own.
Installation is a background job with a log the UI polls, because a fresh VPS
-takes minutes to fetch Node and two npm packages.
-
-A Windows computer is read and served in PowerShell (``remote_os``): it needs
-Git for Windows instead of tmux (panes there run without a server-side
-session), installs through ``winget`` and ``npm``, and keeps the CLI logins in
-the same ``~/.claude`` / ``~/.codex`` files.
+takes minutes to fetch Node and the CLIs.
+
+Per OS, what the user's own terminal would do:
+
+* **Linux**: tmux and git from the distribution (root or password-less sudo);
+ Claude Code from its own installer into ``~/.local/bin`` (no Node, no
+ root); Node.js, only for Codex, from nodejs.org into ``~/.local`` when the
+ distribution's is missing or older than :data:`NODE_MIN_MAJOR` (Ubuntu
+ 22.04 ships 12); Codex through npm into ``~/.local``.
+* **macOS**: everything through Homebrew, which needs no root (and refuses
+ it). A Mac without the command-line tools has only a placeholder ``git``
+ that opens an install dialog on the Mac's screen when run — it counts as
+ missing and is never started. Claude Code's login sits in the Keychain,
+ which SSH sessions cannot open: :func:`save_claude_token` stores a
+ ``claude setup-token`` token for the agents instead.
+* **Windows**: read and served in PowerShell; Git for Windows instead of
+ tmux, installs through ``winget`` and ``npm``.
"""
from __future__ import annotations
import asyncio
import logging
+import re
import shlex
import time
from dataclasses import asdict, dataclass, field
from pathlib import Path
-from typing import Any, Literal
+from typing import Any, Final, Literal
from jarvis.computers import remote_os
-from jarvis.computers.remote_terminal import login_shell
from jarvis.computers.service import ComputerError, get_service
from jarvis.computers.ssh import SshError
@@ -40,24 +51,45 @@ TOOLS: tuple[ToolId, ...] = ("tmux", "git", "node", "claude", "codex")
#: Windows has no tmux; Git for Windows brings the bash agents run in.
WINDOWS_TOOLS: tuple[ToolId, ...] = ("git", "node", "claude", "codex")
+#: The oldest Node.js the coding CLIs run on.
+NODE_MIN_MAJOR: Final[int] = 18
+
_INSPECT = r"""
-for t in tmux git node npm claude codex; do
+clt=yes
+if [ "$(uname -s)" = Darwin ] && ! xcode-select -p >/dev/null 2>&1; then clt=no; fi
+for t in tmux git node claude codex; do
p=$(command -v "$t" 2>/dev/null)
- if [ -n "$p" ]; then
- v=$("$t" --version 2>/dev/null | head -n 1 | tr -d '\r')
- echo "tool $t ok $v"
+ if [ -z "$p" ]; then echo "tool $t missing"; continue; fi
+ # Apple's placeholder git opens an install dialog on the Mac's screen.
+ if [ "$t" = git ] && [ "$clt" = no ] && [ "$p" = /usr/bin/git ]; then
+ echo "tool git missing"; continue
+ fi
+ case "$t" in tmux) flag=-V ;; *) flag=--version ;; esac
+ if v=$("$t" "$flag" 2>/dev/null); then
+ echo "tool $t ok $(printf '%s\n' "$v" | head -n 1 | tr -d '\r')"
else
echo "tool $t missing"
fi
done
-[ -f "$HOME/.claude/.credentials.json" ] && echo "login claude ok" || echo "login claude missing"
+if [ -f "$HOME/.claude/.credentials.json" ] \
+ || grep -qs 'CLAUDE_CODE_OAUTH_TOKEN=' "$HOME/.config/jarvis/agent.env"; then
+ echo "login claude ok"
+else
+ echo "login claude missing"
+fi
[ -f "$HOME/.codex/auth.json" ] && echo "login codex ok" || echo "login codex missing"
-for m in apt-get dnf yum apk pacman brew; do
+managers="apt-get dnf yum zypper apk pacman brew"
+[ "$(uname -s)" = Darwin ] && managers=brew
+for m in $managers; do
command -v "$m" >/dev/null 2>&1 && { echo "pkg $m"; break; }
done
echo "uid $(id -u)"
-command -v sudo >/dev/null 2>&1 && echo "sudo yes" || echo "sudo no"
+sudo -n true >/dev/null 2>&1 && echo "sudo yes" || echo "sudo no"
echo "os $(uname -s)"
+echo "arch $(uname -m)"
+if command -v curl >/dev/null 2>&1; then echo "fetch curl"
+elif command -v wget >/dev/null 2>&1; then echo "fetch wget"; fi
+echo "clt $clt"
""".strip()
#: The same report from a Windows computer ("uid 0" = an administrator).
@@ -72,7 +104,10 @@ foreach ($t in 'git', 'node', 'claude', 'codex') {
"tool $t ok $v"
} else { "tool $t missing" }
}
-if (Test-Path (Join-Path $HOME '.claude\.credentials.json')) { 'login claude ok' }
+$envFile = Join-Path $HOME '.config\jarvis\agent.env'
+$token = (Test-Path $envFile) -and
+ (Select-String -Path $envFile -Pattern 'CLAUDE_CODE_OAUTH_TOKEN=' -Quiet)
+if ((Test-Path (Join-Path $HOME '.claude\.credentials.json')) -or $token) { 'login claude ok' }
else { 'login claude missing' }
if (Test-Path (Join-Path $HOME '.codex\auth.json')) { 'login codex ok' }
else { 'login codex missing' }
@@ -84,24 +119,17 @@ if ((whoami /groups) -match 'S-1-5-32-544') { 'uid 0' } else { 'uid 1000' }
_WINGET_IDS: dict[str, str] = {"git": "Git.Git", "node": "OpenJS.NodeJS.LTS"}
+#: Linux distribution packages: tmux and git only (their Node is often too old).
_PACKAGES: dict[str, dict[str, str]] = {
"apt-get": {
- "tmux": "tmux",
- "git": "git",
- "node": "nodejs npm",
"update": "apt-get update -qq",
"install": "DEBIAN_FRONTEND=noninteractive apt-get install -y -qq",
},
- "dnf": {"tmux": "tmux", "git": "git", "node": "nodejs npm", "install": "dnf install -y -q"},
- "yum": {"tmux": "tmux", "git": "git", "node": "nodejs npm", "install": "yum install -y -q"},
- "apk": {"tmux": "tmux", "git": "git", "node": "nodejs npm", "install": "apk add --no-cache"},
- "pacman": {
- "tmux": "tmux",
- "git": "git",
- "node": "nodejs npm",
- "install": "pacman -S --noconfirm",
- },
- "brew": {"tmux": "tmux", "git": "git", "node": "node", "install": "brew install"},
+ "dnf": {"install": "dnf install -y -q"},
+ "yum": {"install": "yum install -y -q"},
+ "zypper": {"install": "zypper --non-interactive install"},
+ "apk": {"install": "apk add --no-cache"},
+ "pacman": {"install": "pacman -S --noconfirm"},
}
_NPM_PACKAGES: dict[str, str] = {
@@ -114,12 +142,17 @@ _LOGIN_FILES: dict[str, str] = {
"codex": ".codex/auth.json",
}
+#: The current Node.js LTS line, fetched from nodejs.org on Linux.
+_NODE_DIST: Final[str] = "https://nodejs.org/dist/latest-v24.x"
+
@dataclass
class ToolState:
id: str
installed: bool
version: str | None = None
+ #: Installed but too old to use (Node.js below :data:`NODE_MIN_MAJOR`).
+ outdated: bool = False
@dataclass
@@ -133,17 +166,23 @@ class Readiness:
#: Ready for at least one coding agent: tmux + git + a logged-in CLI.
ready: bool
checked_at: float = field(default_factory=time.time)
+ arch: str | None = None
+ #: ``curl`` or ``wget``: how installers are downloaded (POSIX).
+ fetch: str | None = None
def to_dict(self) -> dict[str, Any]:
return asdict(self)
+def _node_major(version: str | None) -> int | None:
+ match = re.match(r"v?(\d+)\.", version or "")
+ return int(match.group(1)) if match else None
+
+
def parse_inspection(output: str) -> Readiness:
tools: dict[str, ToolState] = {}
logins: dict[str, bool] = {}
- pkg: str | None = None
- root = sudo = False
- os_name: str | None = None
+ facts: dict[str, str] = {}
for raw in output.splitlines():
parts = raw.strip().split(" ", 3)
if not parts or not parts[0]:
@@ -151,17 +190,16 @@ def parse_inspection(output: str) -> Readiness:
kind = parts[0]
if kind == "tool" and len(parts) >= 3:
version = parts[3].strip() if len(parts) > 3 else None
- tools[parts[1]] = ToolState(parts[1], parts[2] == "ok", version or None)
+ state = ToolState(parts[1], parts[2] == "ok", version or None)
+ major = _node_major(state.version) if state.id == "node" else None
+ if state.installed and major is not None and major < NODE_MIN_MAJOR:
+ state = ToolState(state.id, False, state.version, outdated=True)
+ tools[parts[1]] = state
elif kind == "login" and len(parts) >= 3:
logins[parts[1]] = parts[2] == "ok"
- elif kind == "pkg" and len(parts) >= 2:
- pkg = parts[1]
- elif kind == "uid" and len(parts) >= 2:
- root = parts[1] == "0"
- elif kind == "sudo" and len(parts) >= 2:
- sudo = parts[1] == "yes"
- elif kind == "os" and len(parts) >= 2:
- os_name = parts[1]
+ elif len(parts) >= 2:
+ facts[kind] = parts[1]
+ os_name = facts.get("os")
windows = os_name == "Windows"
ordered = [tools.get(t, ToolState(t, False)) for t in (WINDOWS_TOOLS if windows else TOOLS)]
have = {t.id for t in ordered if t.installed}
@@ -172,32 +210,29 @@ def parse_inspection(output: str) -> Readiness:
return Readiness(
tools=ordered,
logins={a: logins.get(a, False) for a in ("claude", "codex")},
- package_manager=pkg,
- root=root,
- sudo=sudo,
+ package_manager=facts.get("pkg"),
+ root=facts.get("uid") == "0",
+ sudo=facts.get("sudo") == "yes",
os=os_name,
ready=ready,
+ arch=facts.get("arch"),
+ fetch=facts.get("fetch"),
)
async def inspect(computer_id: str) -> Readiness:
- """Read what the computer has, in one round trip."""
+ """Read what the computer has, in one round trip (after asking its PATH afresh)."""
async with get_service().session(computer_id) as session:
try:
- host = await remote_os.remote_host(computer_id, session)
+ host = await remote_os.remote_host(computer_id, session, refresh=True)
if host.windows:
# PowerShell itself needs seconds to start on a busy machine.
answer = await remote_os.run_powershell(session, _INSPECT_WINDOWS, timeout_s=90)
- return parse_inspection(answer.stdout)
+ else:
+ answer = await remote_os.run_script(session, host, _INSPECT, timeout_s=60)
except SshError as exc:
raise ComputerError(exc.message, status=502, kind=exc.kind) from exc
- result = await asyncio.wait_for(
- session.conn.run(
- login_shell(_INSPECT), check=False, encoding="utf-8", errors="replace"
- ),
- timeout=45,
- )
- return parse_inspection(str(result.stdout or ""))
+ return parse_inspection(answer.stdout)
def install_script_windows(readiness: Readiness, wanted: list[str]) -> str:
@@ -207,6 +242,10 @@ def install_script_windows(readiness: Readiness, wanted: list[str]) -> str:
npm = [_NPM_PACKAGES[a] for a in _NPM_PACKAGES if a in wanted and a in missing]
if npm and "node" in missing and "node" not in system:
system.append("node")
+ if system and not readiness.root:
+ raise ComputerError(
+ "Installing Git and Node.js needs an administrator login on this computer."
+ )
lines = ["$ErrorActionPreference = 'Stop'"]
if system:
if readiness.package_manager != "winget":
@@ -234,31 +273,86 @@ def install_script_windows(readiness: Readiness, wanted: list[str]) -> str:
return "\n".join(lines)
+def _fetch(readiness: Readiness) -> str:
+ if readiness.fetch == "curl":
+ return "curl -fsSL"
+ if readiness.fetch == "wget":
+ return "wget -qO-"
+ raise ComputerError("This computer has neither curl nor wget to download installers.")
+
+
+def _node_from_nodejs_org(fetch: str) -> list[str]:
+ """Node.js LTS from nodejs.org into ``~/.local`` — no root, any glibc Linux."""
+ return [
+ 'case "$(uname -m)" in x86_64|amd64) na=x64 ;; aarch64|arm64) na=arm64 ;; '
+ "armv7l) na=armv7l ;; ppc64le) na=ppc64le ;; s390x) na=s390x ;; "
+ '*) echo "[jarvis] Node.js has no build for $(uname -m)."; exit 1 ;; esac',
+ f"file=$({fetch} {_NODE_DIST}/SHASUMS256.txt | awk '{{print $2}}' "
+ '| grep "^node-v[0-9.]*-linux-$na\\.tar\\.gz$" | head -n 1)',
+ '[ -n "$file" ] || { echo "[jarvis] The Node.js download was not found."; exit 1; }',
+ 'mkdir -p "$HOME/.local/lib/nodejs"',
+ f'{fetch} "{_NODE_DIST}/$file" | tar -xz -C "$HOME/.local/lib/nodejs"',
+ 'node_dir="$HOME/.local/lib/nodejs/${file%.tar.gz}"',
+ 'for b in node npm npx; do ln -sf "$node_dir/bin/$b" "$HOME/.local/bin/$b"; done',
+ "hash -r 2>/dev/null || true",
+ ]
+
+
def install_script(readiness: Readiness, wanted: list[str]) -> str:
- """The shell script that installs ``wanted`` on this computer."""
+ """The script that installs ``wanted`` on this computer (see the module notes)."""
if readiness.os == "Windows":
return install_script_windows(readiness, wanted)
+ mac = readiness.os == "Darwin"
missing = {t.id for t in readiness.tools if not t.installed}
- lines = ["set -e"]
- prefix = "" if readiness.root else ("sudo -n " if readiness.sudo else "")
+ want = [t for t in TOOLS if t in wanted and t in missing]
+ node = "node" in want or ("codex" in want and "node" in missing)
pkg = readiness.package_manager
- system = [t for t in ("tmux", "git", "node") if t in wanted and t in missing]
- needs_node = any(a in wanted and a in missing for a in _NPM_PACKAGES) and "node" in missing
- if needs_node and "node" not in system:
- system.append("node")
+ lines = ["set -e", 'mkdir -p "$HOME/.local/bin"', 'export PATH="$HOME/.local/bin:$PATH"']
+
+ system = [t for t in ("tmux", "git") if t in want]
+ if node and pkg in ("brew", "apk"):
+ system.append("node") # both ship a current Node.js
if system:
- if pkg is None or pkg not in _PACKAGES:
+ if pkg == "brew":
+ names = " ".join("node" if t == "node" else t for t in system)
+ lines.append(f"brew install {names}")
+ elif pkg in _PACKAGES:
+ if readiness.root:
+ prefix = ""
+ elif readiness.sudo:
+ prefix = "sudo -n "
+ else:
+ raise ComputerError(
+ "Installing tmux and git needs root or sudo without a password on "
+ "this login. Install them there by hand, or log in as root."
+ )
+ spec = _PACKAGES[pkg]
+ if "update" in spec:
+ lines.append(f"{prefix}{spec['update']}")
+ names = " ".join("nodejs npm" if t == "node" else t for t in system)
+ lines.append(f"{prefix}{spec['install']} {names}")
+ elif mac:
raise ComputerError(
- "No supported package manager was found. Install tmux, git and Node.js by hand."
+ "Install Homebrew on the Mac first (brew.sh); it also brings the "
+ "command-line tools git needs. Then check again."
)
- spec = _PACKAGES[pkg]
- if "update" in spec:
- lines.append(f"{prefix}{spec['update']}")
- names = " ".join(spec[t] for t in system)
- lines.append(f"{prefix}{spec['install']} {names}")
- npm = [_NPM_PACKAGES[a] for a in _NPM_PACKAGES if a in wanted and a in missing]
- if npm:
- lines.append(f"{prefix}npm install -g --silent {' '.join(npm)}")
+ else:
+ raise ComputerError(
+ "No supported package manager was found. Install tmux and git by hand."
+ )
+ if node and pkg not in ("brew", "apk"):
+ if mac:
+ raise ComputerError("Install Homebrew on the Mac first (brew.sh), then check again.")
+ lines += _node_from_nodejs_org(_fetch(readiness))
+ if "claude" in want:
+ # The native build needs no Node.js and updates itself in ~/.local.
+ lines.append(
+ 'command -v bash >/dev/null 2>&1 || { echo "[jarvis] The Claude Code installer '
+ 'needs bash."; exit 1; }'
+ )
+ lines.append(f"{_fetch(readiness)} https://claude.ai/install.sh | bash")
+ if "codex" in want:
+ lines.append(f'npm install -g --silent --prefix "$HOME/.local" {_NPM_PACKAGES["codex"]}')
lines.append("echo '[jarvis] done'")
return "\n".join(lines)
@@ -295,40 +389,30 @@ async def start_install(computer_id: str, items: list[str]) -> InstallJob:
if not wanted:
raise ComputerError("Choose at least one thing to install.")
readiness = await inspect(computer_id)
- windows = readiness.os == "Windows"
- if (
- not readiness.root
- and not readiness.sudo
- and any(t in wanted for t in ("tmux", "git", "node"))
- ):
- raise ComputerError(
- "Installing Git and Node.js needs an administrator login on this computer."
- if windows
- else "Installing system packages needs root or sudo without a password on this login."
- )
- script = install_script(readiness, wanted)
+ script = install_script(readiness, wanted) # refuses what this login cannot do
new_job = InstallJob(computer_id=computer_id, items=wanted)
_JOBS[computer_id] = new_job
_TASKS[computer_id] = asyncio.create_task(
- _run_install(new_job, script, windows=windows), name=f"computers-install-{computer_id}"
+ _run_install(new_job, script), name=f"computers-install-{computer_id}"
)
return new_job
-async def _run_install(current: InstallJob, script: str, *, windows: bool = False) -> None:
+async def _run_install(current: InstallJob, script: str) -> None:
try:
async with get_service().session(current.computer_id) as session:
import asyncssh
+ host = await remote_os.remote_host(current.computer_id, session)
+ if host.windows:
+ command, body = remote_os.POWERSHELL_STDIN, script
+ else:
+ command, body = host.script_command(), remote_os.env_preamble(host) + script
process = await session.conn.create_process(
- remote_os.POWERSHELL_STDIN if windows else login_shell(script),
- encoding="utf-8",
- errors="replace",
- stderr=asyncssh.STDOUT,
+ command, encoding="utf-8", errors="replace", stderr=asyncssh.STDOUT
)
- if windows:
- process.stdin.write(script)
- process.stdin.write_eof()
+ process.stdin.write(body)
+ process.stdin.write_eof()
async for line in process.stdout:
current.log.append(line.rstrip())
await asyncio.wait_for(process.wait(), timeout=1500)
@@ -338,7 +422,7 @@ async def _run_install(current: InstallJob, script: str, *, windows: bool = Fals
else:
current.state = "failed"
current.message = f"The installation stopped (exit {code}). See the log."
- except ComputerError as exc: # recorded on the job the UI polls
+ except (ComputerError, SshError) as exc: # recorded on the job the UI polls
current.state = "failed"
current.message = exc.message
except Exception as exc: # noqa: BLE001 — reported in the job, logged here
@@ -390,13 +474,13 @@ async def copy_login(computer_id: str, agent: AgentLogin) -> None:
async with get_service().session(computer_id) as session:
try:
host = await remote_os.remote_host(computer_id, session)
+ if not host.windows:
+ quoted = shlex.quote(folder)
+ await remote_os.run_script(
+ session, host, f"mkdir -p ~/{quoted} && chmod 700 ~/{quoted}\n", timeout_s=30
+ )
except SshError as exc:
raise ComputerError(exc.message, status=502, kind=exc.kind) from exc
- if not host.windows:
- remote_dir = shlex.quote(folder)
- await session.conn.run(
- f"mkdir -p ~/{remote_dir} && chmod 700 ~/{remote_dir}", check=False
- )
async with session.conn.start_sftp_client() as sftp:
if host.windows:
# Relative paths start in the home folder; Windows keeps its own
@@ -406,3 +490,33 @@ async def copy_login(computer_id: str, agent: AgentLogin) -> None:
if not host.windows:
await sftp.chmod(rel, 0o600)
log.info("computers: copied the %s login to %s at the user's request", agent, computer_id)
+
+
+#: What ``claude setup-token`` prints: one line of URL-safe characters.
+_TOKEN_RE = re.compile(r"^[A-Za-z0-9._~+/=-]{20,512}$")
+
+
+async def save_claude_token(computer_id: str, token: str) -> None:
+ """Log Claude Code in for the agents on this computer (explicit user action).
+
+ The token goes into :data:`remote_os.AGENT_ENV_FILE` (owner-only), which
+ every launcher reads — a login that works over SSH on a Mac, whose
+ Keychain stays locked there. It is never stored or logged on this PC.
+ """
+ value = token.strip()
+ if not _TOKEN_RE.match(value):
+ raise ComputerError(
+ "This does not look like a Claude token. Run claude setup-token and paste "
+ "the one line it prints."
+ )
+ body = (
+ "# Written by Personal Jarvis: the login Claude Code uses for agents here.\n"
+ f"export CLAUDE_CODE_OAUTH_TOKEN={shlex.quote(value)}\n"
+ )
+ async with get_service().session(computer_id) as session:
+ try:
+ host = await remote_os.remote_host(computer_id, session)
+ await remote_os.upload_text(session, host, remote_os.AGENT_ENV_FILE, body, private=True)
+ except SshError as exc:
+ raise ComputerError(exc.message, status=502, kind=exc.kind) from exc
+ log.info("computers: saved a Claude token for the agents on %s", computer_id)
diff --git a/jarvis/society/remote.py b/jarvis/society/remote.py
index 1df757d42b..40fa3d61b0 100644
--- a/jarvis/society/remote.py
+++ b/jarvis/society/remote.py
@@ -20,6 +20,7 @@ PowerShell in the same folder (``jarvis.computers.remote_os``).
from __future__ import annotations
+import contextlib
import logging
import shlex
import time
@@ -57,10 +58,23 @@ def remote_workspace_expr(agent_id: str, relative: str = "") -> str:
return '"$HOME"/' + shlex.quote(str(rel))
-def wrap_in_workspace(agent_id: str, command: str, *, relative: str = "") -> str:
- """``mkdir -p <ws> && cd <ws> && <command>`` with prompt-free defaults."""
+def wrap_in_workspace(
+ agent_id: str, command: str, *, relative: str = "", record_pid: str = ""
+) -> str:
+ """The script that runs ``command`` in the workspace, with prompt-free defaults.
+
+ Each step stands on its own line and exits when it fails: as one
+ ``mkdir && cd && <command>`` line, a command like ``cd x; ls`` ran its
+ second half in the home folder when the first steps failed. ``record_pid``
+ is a line from ``remote_os.pid_record`` that lets a timeout end the
+ command with everything it started.
+ """
folder = remote_workspace_expr(agent_id, relative)
- return f"mkdir -p {folder} && cd {folder} && export CI=1 NO_COLOR=1 && {command}"
+ lines = [f"mkdir -p {folder} || exit 97", f"cd {folder} || exit 97"]
+ if record_pid:
+ lines.append(record_pid.rstrip("\n"))
+ lines += ["export CI=1 NO_COLOR=1", command]
+ return "\n".join(lines) + "\n"
def _ps_quote(text: str) -> str:
@@ -102,40 +116,49 @@ class SshShellBackend:
return "" if text == "." else text
async def run(self, command: str, *, cwd: Path, timeout_s: float) -> ShellResult:
+ from jarvis.computers import remote_os
from jarvis.computers.service import ComputerError, get_service
+ from jarvis.computers.ssh import SshError
timeout = max(1.0, min(float(timeout_s or DEFAULT_TIMEOUT_S), MAX_TIMEOUT_S))
relative = self._relative(cwd)
started = time.perf_counter()
+ pid_file = f"{remote_os.LAUNCH_DIR}/{remote_os.launcher_name(self._agent_id, '.shell.pid')}"
try:
async with get_service().session(self._computer_id) as opened:
- from jarvis.computers import remote_os
- from jarvis.computers.ssh import SshError, run_command
-
+ host = await self._host(opened)
+ name = get_service().get(self._computer_id).name
+ posix_shell = not host.windows or bool(host.bash)
+ self.where = f"{name} ({_shell_label(host)})"
try:
- host = await remote_os.remote_host(self._computer_id, opened)
- name = get_service().get(self._computer_id).name
- if not host.windows:
- self.where = f"{name} (bash)"
- wrapped = wrap_in_workspace(self._agent_id, command, relative=relative)
- result = await run_command(opened, wrapped, timeout_s=timeout)
- elif host.bash:
- self.where = f"{name} (Windows, Git Bash)"
- wrapped = wrap_in_workspace(self._agent_id, command, relative=relative)
- result = await remote_os.run_bash(opened, host, wrapped, timeout_s=timeout)
+ if posix_shell:
+ wrapped = wrap_in_workspace(
+ self._agent_id,
+ command,
+ relative=relative,
+ record_pid=remote_os.pid_record(host, pid_file),
+ )
+ result = await remote_os.run_script(
+ opened, host, wrapped, timeout_s=timeout
+ )
else:
- self.where = f"{name} (Windows, PowerShell)"
script = powershell_in_workspace(self._agent_id, command, relative=relative)
result = await remote_os.run_powershell(opened, script, timeout_s=timeout)
except SshError as exc:
- if exc.kind == "timeout":
- return ShellResult(
- output=f"Command timed out after {int(timeout)} s",
- exit_code=None,
- seconds=time.perf_counter() - started,
- timed_out=True,
- )
- raise ComputerError(exc.message, status=502, kind=exc.kind) from exc
+ if exc.kind != "timeout":
+ raise ComputerError(exc.message, status=502, kind=exc.kind) from exc
+ if posix_shell:
+ # Giving up on the channel does not end the command there.
+ with contextlib.suppress(SshError):
+ await remote_os.run_script(
+ opened, host, remote_os.stop_script(host, pid_file), timeout_s=30
+ )
+ return ShellResult(
+ output=f"Command timed out after {int(timeout)} s",
+ exit_code=None,
+ seconds=time.perf_counter() - started,
+ timed_out=True,
+ )
except ComputerError as exc:
log.info("society: remote shell for %s failed: %s", self._agent_id, exc.message)
return ShellResult(
@@ -151,6 +174,24 @@ class SshShellBackend:
seconds=time.perf_counter() - started,
)
+ async def _host(self, opened: Any) -> Any:
+ from jarvis.computers import remote_os
+ from jarvis.computers.service import ComputerError
+ from jarvis.computers.ssh import SshError
+
+ try:
+ return await remote_os.remote_host(self._computer_id, opened)
+ except SshError as exc:
+ raise ComputerError(exc.message, status=502, kind=exc.kind) from exc
+
+
+def _shell_label(host: Any) -> str:
+ """ "Windows, Git Bash", "macOS, bash", "Linux, sh" — where a command ran."""
+ if host.windows:
+ return "Windows, Git Bash" if host.bash else "Windows, PowerShell"
+ system = "macOS" if host.mac else (host.system or "POSIX")
+ return f"{system}, {'bash' if host.bash else 'sh'}"
+
def backend_for(agent: Any, workspace: Path) -> ShellBackend:
"""The shell an agent's commands run in: remote when it is placed on a computer."""
diff --git a/jarvis/ui/web/computers_routes.py b/jarvis/ui/web/computers_routes.py
index b8a0871ca9..6f0749714a 100644
--- a/jarvis/ui/web/computers_routes.py
+++ b/jarvis/ui/web/computers_routes.py
@@ -116,6 +116,11 @@ class RunBody(BaseModel):
timeout_s: float = Field(default=60.0, ge=1, le=300)
+class ClaudeTokenBody(BaseModel):
+ #: What ``claude setup-token`` prints; passed through, never stored here.
+ token: str = Field(min_length=20, max_length=512)
+
+
class PasswordBody(BaseModel):
password: str = Field(min_length=1, max_length=1024)
@@ -450,3 +455,17 @@ async def copy_login(computer_id: str, body: CopyLoginBody) -> dict[str, Any]:
except ComputerError as exc:
raise _fail(exc) from exc
return {"copied": body.agent}
+
+
[email protected]("/{computer_id}/claude-token")
+async def save_claude_token(computer_id: str, body: ClaudeTokenBody) -> dict[str, Any]:
+ """Log Claude Code in for the agents there with a ``claude setup-token`` token.
+
+ The one login that works over SSH on a Mac (its Keychain stays locked in
+ SSH sessions). Written owner-only on that computer; nothing is kept here.
+ """
+ try:
+ await toolbox.save_claude_token(computer_id, body.token)
+ except ComputerError as exc:
+ raise _fail(exc) from exc
+ return {"saved": "claude"}
diff --git a/tests/fakes/fake_ssh_server.py b/tests/fakes/fake_ssh_server.py
index f590206d0f..b361e0b4b1 100644
--- a/tests/fakes/fake_ssh_server.py
+++ b/tests/fakes/fake_ssh_server.py
@@ -2,10 +2,15 @@
A real ``asyncssh`` server on 127.0.0.1 with a tiny scripted "shell": it
accepts one password, trusts the public keys it has been told about (and the
-ones an ``authorized_keys`` command appends), answers the health probe with a
+ones an ``authorized_keys`` script appends), answers the health probe with a
canned Linux reading, and echoes every other command. Nothing on disk, no
system ``sshd`` — the tests exercise the actual SSH handshake, host-key pinning
and key installation end to end on every OS.
+
+Like a real server it is handed scripts the way ``jarvis.computers.remote_os``
+sends them: on stdin to ``/bin/sh -s`` / ``/bin/bash -s``, or as a launcher
+file uploaded over SFTP and run with ``/bin/sh <file>`` (needs ``sftp_root``).
+Handlers and :attr:`FakeSshState.commands` see the SCRIPT, not the runner.
"""
from __future__ import annotations
@@ -45,6 +50,14 @@ MemAvailable: 6000000 kB
@@end
"""
+#: What ``remote_os`` learns about the fake Linux box.
+POSIX_FACTS_OUTPUT = "home /home/test\nshell /bin/bash\nsystem Linux\nbash /bin/bash\n"
+LOGIN_PATH_OUTPUT = "motd noise\n__JARVIS_PATH__/usr/local/bin:/usr/bin:/bin__JARVIS_PATH__\n"
+
+#: Command lines that read their script from stdin.
+SCRIPT_RUNNERS = ("/bin/sh -s", "/bin/bash -s")
+_LAUNCHER_RE = re.compile(r"^/bin/sh (\S+)$")
+
#: The one password the fake server accepts.
TEST_PASSWORD = "correct horse" # noqa: S105 — a fixture, not a credential
@@ -59,6 +72,8 @@ class FakeSshState:
password_login: bool = True
authorized: set[str] = field(default_factory=set)
commands: list[str] = field(default_factory=list)
+ #: The raw SSH command lines, as the user's login shell would parse them.
+ lines: list[str] = field(default_factory=list)
#: Optional scripted command handler: return True when it answered the
#: process (wrote output and called ``exit``); False falls through to the
#: built-in behaviour. Lets a test play a remote CLI or a shell.
@@ -107,15 +122,41 @@ class FakeSshServer:
#: in it); ``None`` serves no SFTP at all.
self.sftp_root = sftp_root
- async def _process(self, process: asyncssh.SSHServerProcess) -> None:
+ async def resolve(self, process: asyncssh.SSHServerProcess) -> str:
+ """What the client asked to run: the command line, the script it sent
+ on stdin, or the uploaded launcher a ``/bin/sh <file>`` line names."""
command = process.command or ""
+ self.state.lines.append(command)
+ if command in SCRIPT_RUNNERS:
+ return str(await process.stdin.read())
+ match = _LAUNCHER_RE.match(command)
+ if match is not None and self.sftp_root is not None:
+ launcher = self.sftp_root / match.group(1)
+ if launcher.is_file():
+ return launcher.read_text(encoding="utf-8")
+ return command
+
+ async def _process(self, process: asyncssh.SSHServerProcess) -> None:
+ command = await self.resolve(process)
self.state.commands.append(command)
if self.state.handler is not None and await self.state.handler(command, process):
return
- if command == PROBE_SCRIPT:
+ await self.answer(command, process)
+
+ async def answer(self, command: str, process: asyncssh.SSHServerProcess) -> None:
+ """The built-in behaviour for a resolved command."""
+ if PROBE_SCRIPT in command:
process.stdout.write(LINUX_PROBE_OUTPUT)
process.exit(0)
return
+ if "printf 'home %s\\n'" in command:
+ process.stdout.write(POSIX_FACTS_OUTPUT)
+ process.exit(0)
+ return
+ if "__JARVIS_PATH__" in command:
+ process.stdout.write(LOGIN_PATH_OUTPUT)
+ process.exit(0)
+ return
if "authorized_keys" in command:
match = _KEY_RE.search(command)
if match:
@@ -129,19 +170,20 @@ class FakeSshServer:
process.stdout.write(f"ran: {command}\n")
process.exit(0)
- async def start(self, port: int = 0) -> None:
+ def sftp_factory(self) -> Any:
root = self.sftp_root
+ if root is None:
+ return None
+ return lambda chan: asyncssh.SFTPServer(chan, chroot=str(root))
+
+ async def start(self, port: int = 0) -> None:
self._acceptor = await asyncssh.listen(
"127.0.0.1",
port,
server_host_keys=[self.host_key],
server_factory=lambda: _Server(self.state),
process_factory=self._process,
- sftp_factory=(
- (lambda chan: asyncssh.SFTPServer(chan, chroot=str(root)))
- if root is not None
- else None
- ),
+ sftp_factory=self.sftp_factory(),
)
self.port = self._acceptor.sockets[0].getsockname()[1]
diff --git a/tests/fakes/fake_tmux_server.py b/tests/fakes/fake_tmux_server.py
index 25ae44115a..809a79bbd4 100644
--- a/tests/fakes/fake_tmux_server.py
+++ b/tests/fakes/fake_tmux_server.py
@@ -1,15 +1,16 @@
"""An in-process SSH server that behaves like a VPS running tmux.
Built on :class:`tests.fakes.fake_ssh_server.FakeSshServer` (real asyncssh,
-127.0.0.1, random port). Only the handful of commands the IDE's remote panes
-send are understood:
+127.0.0.1, random port, SFTP into a folder that plays the home). Only the
+handful of commands the IDE's remote panes send are understood — read from the
+uploaded pane launcher or the script sent on stdin, as a real server would run
+them:
* ``tmux ... new-session -A -s NAME ...`` — creates (or re-joins) session NAME
and becomes its screen: prints ``ready NAME`` and echoes every keystroke back
as ``echo:<data>`` until the session is killed.
* ``tmux has-session -t NAME`` — exit 0 while NAME lives, 1 after.
* ``tmux kill-session -t NAME`` — ends NAME (and the screen attached to it).
-* ``printf %s "$HOME"`` — ``/home/test``.
``drop_connections()`` cuts every client connection WITHOUT ending the tmux
sessions, which is what a flaky network or a sleeping laptop does.
@@ -19,6 +20,7 @@ from __future__ import annotations
import re
from dataclasses import dataclass, field
+from pathlib import Path
from typing import Any
import asyncssh
@@ -40,8 +42,8 @@ class TmuxState:
class FakeTmuxServer(FakeSshServer):
- def __init__(self, state: FakeSshState | None = None) -> None:
- super().__init__(state)
+ def __init__(self, state: FakeSshState | None = None, *, sftp_root: Path) -> None:
+ super().__init__(state, sftp_root=sftp_root)
self.tmux = TmuxState()
self._connections: list[Any] = []
@@ -52,12 +54,13 @@ class FakeTmuxServer(FakeSshServer):
server_host_keys=[self.host_key],
server_factory=lambda: _Server(self.state),
process_factory=self._process,
+ sftp_factory=self.sftp_factory(),
line_editor=False,
)
self.port = self._acceptor.sockets[0].getsockname()[1]
async def _process(self, process: asyncssh.SSHServerProcess) -> None:
- command = process.command or ""
+ command = await self.resolve(process)
self.state.commands.append(command)
self._connections.append(process.channel.get_connection())
if (match := _NEW.search(command)) is not None:
@@ -73,11 +76,7 @@ class FakeTmuxServer(FakeSshServer):
screen.exit(0)
process.exit(0)
return
- if 'printf %s "$HOME"' in command:
- process.stdout.write("/home/test")
- process.exit(0)
- return
- await super()._process(process)
+ await self.answer(command, process)
async def _screen(self, process: asyncssh.SSHServerProcess, name: str) -> None:
if name in self.tmux.alive:
diff --git a/tests/unit/computers/test_posix_remote.py b/tests/unit/computers/test_posix_remote.py
new file mode 100644
index 0000000000..cc06ce91f5
--- /dev/null
+++ b/tests/unit/computers/test_posix_remote.py
@@ -0,0 +1,269 @@
+"""Linux and macOS computers: the user's own PATH, any login shell, a Mac's login.
+
+Over SSH the search path is short — ``~/.local/bin`` (Claude Code's own
+installer) and ``/opt/homebrew/bin`` (Homebrew on Apple silicon) are missing —
+and the login shell may be fish, which cannot parse a POSIX script on the
+command line. These tests pin the answers: detection asks the login shell for
+its PATH, every script travels on stdin to sh/bash behind that PATH, every
+program starts from an uploaded launcher, and a Mac's agents log in with a
+token because its Keychain is locked in SSH sessions.
+"""
+
+from __future__ import annotations
+
+import re
+import stat
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from jarvis.agent_chat import remote_cli
+from jarvis.computers import identity, remote_os, service, toolbox
+from jarvis.computers.service import ComputerError, ComputerService
+from jarvis.computers.store import ComputerStore
+from jarvis.society import remote
+from tests.fakes.fake_ssh_server import FakeSshServer
+
+MAC_INSPECT = (
+ "tool tmux ok tmux 3.5a\ntool git missing\ntool node ok v12.22.9\n"
+ "tool claude ok 2.1.284 (Claude Code)\ntool codex missing\n"
+ "login claude missing\nlogin codex missing\npkg brew\nuid 501\nsudo no\n"
+ "os Darwin\narch arm64\nfetch curl\nclt no\n"
+)
+
+LINUX_INSPECT = (
+ "tool tmux missing\ntool git ok git version 2.43.0\ntool node ok v12.22.9\n"
+ "tool claude missing\ntool codex missing\n"
+ "login claude missing\nlogin codex missing\npkg apt-get\nuid 1000\nsudo yes\n"
+ "os Linux\narch x86_64\nfetch curl\nclt yes\n"
+)
+
+#: The only command lines a login shell is ever asked to parse.
+_SAFE_LINE = re.compile(
+ r"^(echo %OS% \$env:OS|/bin/(ba)?sh -s|/bin/sh jarvis-agents/\.launch/\S+)$"
+)
+
+
+def computers(tmp_path: Path, secret_box, monkeypatch: pytest.MonkeyPatch) -> ComputerService: # noqa: ANN001
+ path = tmp_path / "computers.json"
+ monkeypatch.setattr("jarvis.computers.store.default_path", lambda: path)
+ svc = ComputerService(ComputerStore(path))
+ monkeypatch.setattr(service, "_SERVICE", svc)
+ return svc
+
+
+async def ssh_server(tmp_path: Path): # noqa: ANN201
+ home = tmp_path / "remote-home"
+ home.mkdir()
+ server = FakeSshServer(sftp_root=home)
+ server.state.authorized.add(identity.public_key_line())
+ await server.start()
+ try:
+ yield server
+ finally:
+ await server.stop()
+
+
+async def box(computers: ComputerService, ssh_server: FakeSshServer): # noqa: ANN201
+ return await computers.add_server(name="Box", host="127.0.0.1", port=ssh_server.port)
+
+
+# -- pure pieces ------------------------------------------------------------------
+
+
+def test_the_login_path_is_read_between_markers_and_checked() -> None:
+ path = "/opt/homebrew/bin:/Users/a/.local/bin:/usr/bin"
+ noisy = f"Welcome!\n__JARVIS_PATH__{path}__JARVIS_PATH__\n"
+ assert remote_os.parse_login_path(noisy) == path
+ assert remote_os.parse_login_path("no markers here") is None
+ assert remote_os.parse_login_path("__JARVIS_PATH__relative:bin__JARVIS_PATH__") is None
+ script = remote_os.login_path_script("-ilc")
+ assert '"${SHELL:-/bin/sh}" -ilc' in script and "</dev/null" in script
+
+
+def test_the_preamble_puts_the_users_path_and_the_install_folders_first() -> None:
+ host = remote_os.RemoteHost(path="/opt/homebrew/bin:/usr/bin")
+ preamble = remote_os.env_preamble(host)
+ assert preamble.startswith('PATH=/opt/homebrew/bin:/usr/bin:"$PATH"\n')
+ assert '"$HOME/.local/bin"' in preamble and "/opt/homebrew/bin" in preamble
+ assert preamble.rstrip().endswith("export PATH")
+ assert remote_os.env_preamble(remote_os.RemoteHost(os="windows")) == ""
+ assert remote_os.RemoteHost(bash="/bin/bash").script_command() == "/bin/bash -s"
+ assert remote_os.RemoteHost().script_command() == "/bin/sh -s"
+ assert remote_os.RemoteHost().launcher_command("jarvis-agents/.launch/x.sh") == (
+ "/bin/sh jarvis-agents/.launch/x.sh"
+ )
+
+
[email protected](sys.platform == "win32", reason="needs a POSIX /bin/sh")
+def test_the_preamble_runs_in_a_real_sh(tmp_path: Path) -> None:
+ import subprocess
+
+ host = remote_os.RemoteHost(path="/custom/bin:/usr/bin:/bin")
+ (tmp_path / ".local" / "bin").mkdir(parents=True)
+ script = remote_os.env_preamble(host) + 'printf %s "$PATH"\n'
+ result = subprocess.run( # noqa: S603 — fixed argv, script on stdin
+ ["/bin/sh", "-s"],
+ input=script.encode(),
+ capture_output=True,
+ env={"HOME": str(tmp_path), "PATH": "/usr/bin:/bin"},
+ check=True,
+ )
+ path = result.stdout.decode().split(":")
+ # The user's own folder wins over the system's (a newer Node.js lives there).
+ assert path[0] == f"{tmp_path}/.local/bin"
+ assert path[1] == "/custom/bin"
+
+
+def test_a_bare_cli_name_is_the_program_not_its_first_argument() -> None:
+ """Planned for another computer, argv starts with the bare name ("claude")."""
+ common = {"local_cwd": "/ws", "remote_cwd": "/home/u/jarvis-agents/a"}
+ out = remote_cli.remote_argv(["claude", "--print"], binary="claude", **common)
+ assert out == ["claude", "--print"]
+ out = remote_cli.remote_argv(["codex.cmd", "exec", "-"], binary="codex", **common)
+ assert out == ["codex", "exec", "-"]
+ # A real first argument that happens to differ stays.
+ out = remote_cli.remote_argv(["exec", "--json"], binary="codex", **common)
+ assert out == ["codex", "exec", "--json"]
+
+
+def test_a_macs_health_reading_has_memory_uptime_and_the_data_volume() -> None:
+ from jarvis.computers.probe import parse_probe
+
+ reading = parse_probe(
+ "@@hostname\nmac-mini\n@@uname\nDarwin 24.0.0 arm64\n@@os\n"
+ "@@darwin\nProductName:\t\tmacOS\nProductVersion:\t\t15.0\nBuildVersion:\t\t24A335\n"
+ "@@nproc\n10\n@@meminfo\nMemTotal: 16777216 kB\nMemAvailable: 4194304 kB\n"
+ "@@memsize\n17179869184\n"
+ "@@df\n/dev/disk3s5 482797652 241398826 241398826 50% /System/Volumes/Data\n"
+ "@@uptime\n3600\n@@loadavg\n{ 1.50 1.20 1.00 }\n@@end\n"
+ )
+ assert reading.facts.os_id == "macos" and reading.facts.os_name == "macOS 15.0"
+ assert reading.facts.mem_total_mb == 16384 and reading.mem_used_pct == 75.0
+ assert reading.disk_used_pct == 50.0 and reading.uptime_s == 3600
+ assert reading.load_1m == 1.5
+
+
+def test_a_mac_counts_the_git_placeholder_and_old_node_as_missing() -> None:
+ readiness = toolbox.parse_inspection(MAC_INSPECT)
+ by_id = {tool.id: tool for tool in readiness.tools}
+ assert not by_id["git"].installed
+ assert by_id["node"].outdated and not by_id["node"].installed
+ assert by_id["node"].version == "v12.22.9"
+ assert readiness.os == "Darwin" and readiness.package_manager == "brew"
+ assert not readiness.ready
+
+
+def test_a_mac_installs_through_homebrew_without_root() -> None:
+ readiness = toolbox.parse_inspection(MAC_INSPECT)
+ script = toolbox.install_script(readiness, ["git", "node", "codex"])
+ assert "brew install git node" in script
+ assert "sudo" not in script
+ assert 'npm install -g --silent --prefix "$HOME/.local" @openai/codex' in script
+ no_brew = toolbox.parse_inspection(MAC_INSPECT.replace("pkg brew\n", ""))
+ with pytest.raises(ComputerError) as caught:
+ toolbox.install_script(no_brew, ["git"])
+ assert "Homebrew" in caught.value.message
+
+
+def test_linux_installs_claude_natively_and_node_from_nodejs_org() -> None:
+ readiness = toolbox.parse_inspection(LINUX_INSPECT)
+ script = toolbox.install_script(readiness, ["tmux", "claude", "codex"])
+ assert "sudo -n DEBIAN_FRONTEND=noninteractive apt-get install -y -qq tmux" in script
+ assert "curl -fsSL https://claude.ai/install.sh | bash" in script
+ assert "@anthropic-ai/claude-code" not in script, "Claude Code needs no Node.js"
+ assert "https://nodejs.org/dist/latest-v24.x" in script
+ assert "nodejs npm" not in script, "the distribution's Node.js is too old"
+ assert 'ln -sf "$node_dir/bin/$b" "$HOME/.local/bin/$b"' in script
+ no_sudo = toolbox.parse_inspection(LINUX_INSPECT.replace("sudo yes", "sudo no"))
+ with pytest.raises(ComputerError):
+ toolbox.install_script(no_sudo, ["tmux"])
+ # Claude Code alone needs neither root nor Node.js.
+ assert "curl -fsSL" in toolbox.install_script(no_sudo, ["claude"])
+
+
+# -- over SSH -------------------------------------------------------------------------
+
+
+async def test_detection_reads_the_login_shells_path(box, ssh_server: FakeSshServer) -> None: # noqa: ANN001
+ async with service.get_service().session(box.id) as opened:
+ host = await remote_os.remote_host(box.id, opened)
+ assert host.os == "posix" and host.system == "Linux"
+ assert host.home == "/home/test" and host.bash == "/bin/bash"
+ assert host.login_shell == "/bin/bash"
+ assert host.path == "/usr/local/bin:/usr/bin:/bin"
+ assert any("-ilc" in c and "__JARVIS_PATH__" in c for c in ssh_server.state.commands)
+
+
+async def test_no_script_ever_reaches_the_login_shell(
+ box, # noqa: ANN001
+ ssh_server: FakeSshServer,
+ tmp_path: Path,
+) -> None:
+ """fish, tcsh or nu as login shell parse only these few fixed lines."""
+
+ async def handler(command: str, process: Any) -> bool:
+ if "command -v" in command and "pwd" in command:
+ process.stdout.write("/home/test/jarvis-agents/scout\nfound\n")
+ process.exit(0)
+ return True
+ if "exec claude" in command:
+ process.exit(0)
+ return True
+ return False
+
+ ssh_server.state.handler = handler
+ await service.get_service().check(box.id)
+ await toolbox.inspect(box.id)
+ backend = remote.backend_for(SimpleNamespace(agent_id="scout", computer_id=box.id), tmp_path)
+ await backend.run("echo hi; ls", cwd=tmp_path, timeout_s=30)
+ proc = await remote_cli.spawn(
+ box.id,
+ agent_id="scout",
+ runner="claude-cli",
+ binary="claude",
+ argv=["claude", "--print"],
+ local_cwd="/ws",
+ env={},
+ )
+ await proc.wait()
+ unsafe = [line for line in ssh_server.state.lines if not _SAFE_LINE.match(line)]
+ assert unsafe == []
+
+
+async def test_a_claude_token_is_saved_owner_only_on_that_computer(
+ box, # noqa: ANN001
+ ssh_server: FakeSshServer,
+) -> None:
+ token = "sk-ant-oat01-" + "a" * 40
+ await toolbox.save_claude_token(box.id, token)
+ saved = ssh_server.sftp_root / ".config" / "jarvis" / "agent.env"
+ assert f"export CLAUDE_CODE_OAUTH_TOKEN={token}\n" in saved.read_text()
+ if sys.platform != "win32":
+ assert stat.S_IMODE(saved.stat().st_mode) == 0o600
+ with pytest.raises(ComputerError):
+ await toolbox.save_claude_token(box.id, "not a token; rm -rf ~")
+
+
+async def test_readiness_on_a_mac_reads_brew_and_the_git_placeholder(
+ box, # noqa: ANN001
+ ssh_server: FakeSshServer,
+) -> None:
+ async def handler(command: str, process: Any) -> bool:
+ if "tool $t" in command:
+ assert "xcode-select -p" in command and "/usr/bin/git" in command
+ process.stdout.write(MAC_INSPECT)
+ process.exit(0)
+ return True
+ return False
+
+ ssh_server.state.handler = handler
+ readiness = await toolbox.inspect(box.id)
+ assert readiness.package_manager == "brew"
+ assert [t.id for t in readiness.tools if not t.installed] == ["git", "node", "codex"]
diff --git a/tests/unit/computers/test_remote_terminal.py b/tests/unit/computers/test_remote_terminal.py
index 5916e457b5..47b056d0d8 100644
--- a/tests/unit/computers/test_remote_terminal.py
+++ b/tests/unit/computers/test_remote_terminal.py
@@ -12,15 +12,17 @@ import asyncio
import pytest
-from jarvis.computers import identity, remote_terminal
+from jarvis.computers import identity, remote_os, remote_terminal
from jarvis.computers.remote_terminal import SshPtyPool, tmux_session_name
from jarvis.computers.service import ComputerService
from tests.fakes.fake_tmux_server import FakeTmuxServer
@pytest.fixture
-async def tmux_server(): # noqa: ANN201
- server = FakeTmuxServer()
+async def tmux_server(tmp_path): # noqa: ANN001, ANN201
+ home = tmp_path / "remote-home"
+ home.mkdir()
+ server = FakeTmuxServer(sftp_root=home)
await server.start()
try:
yield server
@@ -158,16 +160,35 @@ async def test_close_kills_the_session_and_a_server_side_end_reports_closed(
assert other.closed == [0]
-def test_tmux_command_is_create_or_attach_and_quiet() -> None:
- command = remote_terminal.tmux_command(
- "jv-x", ("claude", "--resume", "a b"), "/srv/my app", 80, 24
+def test_pane_launcher_is_create_or_attach_quiet_and_runs_the_agent_itself() -> None:
+ host = remote_os.RemoteHost(home="/home/u", path="/opt/homebrew/bin:/usr/bin")
+ script = remote_os.pane_launcher_script(
+ host,
+ name="jv-x",
+ self_path="jarvis-agents/.launch/jv-x.sh",
+ cwd="/srv/my app",
+ argv=("claude", "--resume", "a b"),
+ cols=80,
+ rows=24,
)
- assert "new-session -A -s jv-x" in command
- assert "status off" in command
- assert "'/srv/my app'" in command
+ assert 'PATH=/opt/homebrew/bin:/usr/bin:"$PATH"' in script
+ assert "new-session -A -s jv-x -x 80 -y 24 -c '/srv/my app'" in script
+ assert "status off" in script
+ # tmux hands its command to the login shell: only `sh <this file> run` goes there.
+ assert '"sh \\"$self\\" run"' in script
+ assert "exec claude --resume 'a b'" in script
+ assert "|| { printf 'The folder %s is missing" in script
assert remote_terminal.tmux_session_name("a/b c") == "jv-a-b-c"
+def test_a_plain_terminal_is_the_computers_own_shell() -> None:
+ mac = remote_os.RemoteHost(login_shell="/bin/zsh", system="Darwin")
+ assert remote_terminal.pane_argv(mac, ("bash", "-l")) == ("/bin/zsh", "-l")
+ windows = remote_os.RemoteHost(os="windows", bash="C:/Git/bin/bash.exe")
+ assert remote_terminal.pane_argv(windows, ("bash", "-l")) == ("powershell.exe", "-NoLogo")
+ assert remote_terminal.pane_argv(mac, ("claude",)) == ("claude",)
+
+
async def test_two_workspaces_same_call_sign_stay_apart(
pool: SshPtyPool, tmux_server: FakeTmuxServer
) -> None:
diff --git a/tests/unit/computers/test_windows_remote.py b/tests/unit/computers/test_windows_remote.py
index 8d64079c49..b98e850f4b 100644
--- a/tests/unit/computers/test_windows_remote.py
+++ b/tests/unit/computers/test_windows_remote.py
@@ -22,7 +22,7 @@ import pytest
from jarvis.agent_chat import remote_cli
from jarvis.computers import identity, remote_os, service, toolbox
from jarvis.computers.probe import WINDOWS_PROBE_SCRIPT, parse_probe
-from jarvis.computers.remote_terminal import SshPtyPool, windows_pane_argv
+from jarvis.computers.remote_terminal import SshPtyPool, pane_argv
from jarvis.computers.service import ComputerService
from jarvis.computers.ssh import authorize_key_script_windows
from jarvis.computers.store import ComputerStore
@@ -171,11 +171,15 @@ def test_command_lines_quote_the_program_once() -> None:
def test_launcher_keeps_every_argument_intact() -> None:
argv = ["claude", "--print", 'a "b" & c', "café Ω ✓", "multi\nline", "/help", "100%PATH%"]
- script = remote_os.launcher_script(f"{HOME}/jarvis-agents/scout", argv, {"CI": "1"})
+ host = remote_os.RemoteHost(os="windows", home=HOME, bash=GIT_BASH)
+ script = remote_os.launcher_script(host, f"{HOME}/jarvis-agents/scout", argv, {"CI": "1"})
lines = script.splitlines()
- assert lines[0] == f"cd -- {HOME}/jarvis-agents/scout || exit 97"
+ agent_env = '"$HOME/.config/jarvis/agent.env"'
+ assert lines[0] == f"[ -f {agent_env} ] && . {agent_env}"
+ assert lines[1] == f"cd -- {HOME}/jarvis-agents/scout || exit 97"
assert "export CI=1" in lines
assert "MSYS_NO_PATHCONV=1" in script
+ assert "PATH=" not in script, "Git Bash brings the Windows PATH itself"
exec_line = script.split("exec ", 1)[1]
assert shlex.split(exec_line) == argv
assert remote_os.launcher_name("society:scout/x") == "society-scout-x.sh"
@@ -226,8 +230,9 @@ def test_powershell_workspace_quotes_the_folder() -> None:
script = remote.powershell_in_workspace("scout", "Get-ChildItem", relative="it's/sub")
assert "Join-Path $HOME 'jarvis-agents\\scout\\it''s\\sub'" in script
assert "\nGet-ChildItem\n" in script
- assert windows_pane_argv(("bash", "-l")) == ("powershell.exe", "-NoLogo")
- assert windows_pane_argv(("claude", "--resume", "x")) == ("claude", "--resume", "x")
+ windows = remote_os.RemoteHost(os="windows", bash=GIT_BASH)
+ assert pane_argv(windows, ("bash", "-l")) == ("powershell.exe", "-NoLogo")
+ assert pane_argv(windows, ("claude", "--resume", "x")) == ("claude", "--resume", "x")
# -- over SSH -------------------------------------------------------------------------
@@ -344,7 +349,8 @@ async def test_agent_shell_runs_in_git_bash_or_powershell(
result = await backend.run("ls -la", cwd=tmp_path, timeout_s=30)
assert result.ok and "bash-ran" in result.output
kind, script = box.scripts[-1]
- assert kind == "bash" and script.endswith("&& ls -la")
+ assert kind == "bash" and script.rstrip().endswith("ls -la")
+ assert 'cd "$HOME"/jarvis-agents/scout || exit 97' in script
assert backend.where == "Desk (Windows, Git Bash)"
box.bash = False
diff --git a/tests/unit/society/test_remote_placement.py b/tests/unit/society/test_remote_placement.py
index 2b424ff33b..569fc2cdb4 100644
--- a/tests/unit/society/test_remote_placement.py
+++ b/tests/unit/society/test_remote_placement.py
@@ -8,6 +8,7 @@ started there with a rewritten argv and read back line by line.
from __future__ import annotations
+import asyncio
import json
from pathlib import Path
from types import SimpleNamespace
@@ -63,8 +64,10 @@ def computers(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> ComputerServic
@pytest.fixture
-async def ssh_server(): # noqa: ANN201
- server = FakeSshServer()
+async def ssh_server(tmp_path: Path): # noqa: ANN201
+ home = tmp_path / "remote-home"
+ home.mkdir()
+ server = FakeSshServer(sftp_root=home)
await server.start()
try:
yield server
@@ -149,7 +152,7 @@ async def test_shell_runs_inside_the_remote_workspace(
tmp_path: Path, vps, ssh_server: FakeSshServer
) -> None: # noqa: ANN001
async def handler(command: str, process: Any) -> bool:
- if command.startswith("mkdir -p"):
+ if "ls -la" in command:
process.stdout.write("hello from the vps\n")
process.stderr.write("a warning\n")
process.exit(0)
@@ -168,8 +171,12 @@ async def test_shell_runs_inside_the_remote_workspace(
assert result.ok
assert "hello from the vps" in result.output and "a warning" in result.output
sent = ssh_server.state.commands[-1]
- assert '"$HOME"/jarvis-agents/scout/sub' in sent
- assert sent.endswith("&& ls -la")
+ # The login shell's PATH comes first, then each step stops on its own failure:
+ # `cd x; ls` can no longer run its second half in the home folder.
+ assert sent.startswith("PATH=/usr/local/bin:/usr/bin:/bin:")
+ assert 'cd "$HOME"/jarvis-agents/scout/sub || exit 97' in sent
+ assert sent.rstrip().endswith("ls -la")
+ assert backend.where == "VPS (Linux, bash)"
async def test_shell_reports_an_unreachable_computer(tmp_path: Path, computers) -> None: # noqa: ANN001
@@ -239,7 +246,7 @@ async def test_cli_turn_streams_from_the_remote_process(vps, ssh_server: FakeSsh
process.stdout.write("/root/jarvis-agents/scout\nfound\n")
process.exit(0)
return True
- if "exec env" in command:
+ if "exec claude" in command:
prompt = await process.stdin.readline()
process.stdout.write(json.dumps({"type": "echo", "got": prompt.strip()}) + "\n")
process.stdout.write(json.dumps({"type": "result", "result": "done"}) + "\n")
@@ -253,9 +260,17 @@ async def test_cli_turn_streams_from_the_remote_process(vps, ssh_server: FakeSsh
agent_id="scout",
runner="claude-cli",
binary="claude",
- argv=[r"C:\bin\claude.exe", "--print", "--output-format", "stream-json"],
+ argv=[
+ r"C:\bin\claude.exe",
+ "--print",
+ "--output-format",
+ "stream-json",
+ "--append-system-prompt-file",
+ r"C:\tmp\identity.md",
+ ],
local_cwd=r"C:\ws",
env={"PATH": r"C:\secret-path"},
+ system_prompt_files={r"C:\tmp\identity.md": "You are Scout."},
)
proc.stdin.write(b"hello there\n")
await proc.stdin.drain()
@@ -267,9 +282,59 @@ async def test_cli_turn_streams_from_the_remote_process(vps, ssh_server: FakeSsh
assert first == {"type": "echo", "got": "hello there"}
assert second["type"] == "result"
assert code == 0
+ # Started by an uploaded launcher: the login shell never reads the turn.
launched = ssh_server.state.commands[-1]
- assert "cd /root/jarvis-agents/scout && exec env CI=1 NO_COLOR=1 claude --print" in launched
+ assert launched.startswith("PATH=/usr/local/bin:/usr/bin:/bin:")
+ assert '. "$HOME/.config/jarvis/agent.env"' in launched
+ assert "cd -- /root/jarvis-agents/scout || exit 97" in launched
+ assert "export CI=1" in launched and "export NO_COLOR=1" in launched
+ prompt_file = "/home/test/jarvis-agents/.launch/scout-prompt-0.md"
+ assert (
+ "exec claude --print --output-format stream-json "
+ f"--append-system-prompt-file {prompt_file}" in launched
+ )
assert "secret-path" not in launched
+ uploaded = (ssh_server.sftp_root / "jarvis-agents/.launch/scout-prompt-0.md").read_text()
+ assert uploaded.startswith("You are Scout.") and '"VPS"' in uploaded
+
+
+async def test_a_cancelled_turn_ends_its_process_group(vps, ssh_server: FakeSshServer) -> None: # noqa: ANN001
+ """Hanging up does not reliably end a CLI that never writes: stop it first."""
+ stopped = asyncio.Event()
+
+ async def handler(command: str, process: Any) -> bool:
+ if "command -v" in command:
+ process.stdout.write("/root/jarvis-agents/scout\nfound\n")
+ process.exit(0)
+ return True
+ if "exec claude" in command:
+ await stopped.wait()
+ process.exit(143)
+ return True
+ if "kill -TERM" in command:
+ stopped.set()
+ process.exit(0)
+ return True
+ return False
+
+ ssh_server.state.handler = handler
+ proc = await remote_cli.spawn(
+ vps.id,
+ agent_id="scout",
+ runner="claude-cli",
+ binary="claude",
+ argv=["claude", "--print"],
+ local_cwd="/ws",
+ env={},
+ )
+ launcher = next(c for c in ssh_server.state.commands if "exec claude" in c)
+ assert "ps -o pgid= -p $$" in launcher
+ assert 'echo "${g:-$$}" > "$HOME"/jarvis-agents/.launch/scout.pid' in launcher
+
+ proc.kill()
+ assert await asyncio.wait_for(proc.wait(), timeout=30) == 143
+ stop = next(c for c in ssh_server.state.commands if "kill -TERM" in c)
+ assert 'kill -TERM -- "-$p"' in stop and "jarvis-agents/.launch/scout.pid" in stop
async def test_missing_cli_on_the_remote_is_a_clear_sentence(
@@ -293,7 +358,7 @@ async def test_missing_cli_on_the_remote_is_a_clear_sentence(
local_cwd="/work",
env={},
)
- assert "Install codex on VPS" in str(caught.value)
+ assert "codex was not found on VPS" in str(caught.value)
async def test_placement_follows_the_society_roster(monkeypatch: pytest.MonkeyPatch) -> None: