The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat: add remote-machine support for testing across multiple harness instances
Dev jacob5b2e80133faa
diff --git a/Makefile b/Makefileindex f9fd6b7e0..9c05275cf 100644--- a/Makefile+++ b/Makefile@@ -4,7 +4,7 @@# make install-cli ARGS="--no-restart"# make upload-cli ARGS="0.1.0"-.PHONY: cli-test install-cli upload-cli+.PHONY: cli-test install-cli upload-cli remote-machine## cli-test: typecheck + run the CLI test suite.cli-test:@@ -22,3 +22,15 @@ install-cli:## Running daemons pick the new version up within ~1 min.upload-cli:bash cli/scripts/upload-cli.sh $(ARGS)++## remote-machine: drive a SECOND harness machine in Docker, so the app's remote path (relay ->+## another machine's daemon) can be tested from one laptop. ARGS picks the step:+## make remote-machine ARGS=build -> bundle this tree + build the image+## make remote-machine ARGS=up -> start the box+## make remote-machine ARGS=login -> SSO on the box (interactive)+## make remote-machine ARGS=link -> let this Mac's relay reach it+## make remote-machine ARGS=verify -> what each remote agent is ACTUALLY running on+## make remote-machine ARGS=destroy -> throw it away (prints how to drop the machine record)+## See cli/docker/remote-machine/README.md.+remote-machine:+ bash cli/scripts/remote-machine.sh $(ARGS)diff --git a/cli/.gitignore b/cli/.gitignoreindex d369c55f9..f6fc48fa4 100644--- a/cli/.gitignore+++ b/cli/.gitignore@@ -3,3 +3,5 @@ dist/.env*.tsbuildinfo.DS_Store+# The Docker rig's pinned computer id — local to this checkout.+docker/remote-machine/.rig.envdiff --git a/cli/docker/remote-machine/Dockerfile b/cli/docker/remote-machine/Dockerfilenew file mode 100644index 000000000..924a9d979--- /dev/null+++ b/cli/docker/remote-machine/Dockerfile@@ -0,0 +1,96 @@+# A second harness machine, in a box.+#+# This exists to exercise the ONE path a single laptop cannot reach on its own: the app talking to a+# machine that is not the machine it is running on. Frames leave the desktop's local daemon, cross the+# backend relay (`cli/src/lib/remoteRelay.ts`), and are handled by the daemon in here. Nothing is+# stubbed — this container is a real machine on a real account, and the app cannot tell it apart from+# a second laptop.+#+# ## Two things about this image are load-bearing+#+# 1. **It carries the bundle from YOUR working tree, and self-update is off.** A container that+# updated itself would pull the published release, and a feature that has not shipped yet — the+# grid launch this rig was built to test, for one — would simply not be in it. The test would then+# fail for a reason that has nothing to do with the code under test, which is the worst kind of+# red. `ADAPTER_UPDATE_DISABLE=true` lives in the launcher, exactly as `install-cli.sh --no-updates`+# writes it on a real box.+#+# 2. **Code and state are deliberately on opposite sides of the volume.** The CLI is baked at+# `/opt/harness/cli`; the mutable state — computer id, SSO session, session registry — lives under+# `$HOME/.harness`, which is where the volume mounts. Putting the code in its default home instead+# would mean the volume SHADOWS `cli.js` on the second run, and the container would come up empty+# with no obvious cause.+#+# Runs as the unprivileged `node` user (uid 1000, already in the base image) rather than root, because+# Claude Code refuses `--dangerously-skip-permissions` when it is root — and that flag is reachable+# from the app's New agent dialog, so a root container would quietly take a testable option away.+FROM node:22-bookworm-slim++# tmux: the daemon discovers and drives agents through it, so there is no agent without it.+# procps: `ps` — the CLI reads a live engine's environment to answer "which grid is this agent on?"+# (`lib/processEnv.ts`). On Linux it reads /proc directly, but ps is what makes the same question+# answerable by hand when a test disagrees with the daemon.+# git + ca-certificates + curl: what an engine expects to find on a developer box.+# socat: the SSO callback listener binds the container's LOOPBACK (as it should — see+# ADAPTER_LOGIN_CALLBACK_PORT), but Docker publishes a port to the container's eth0, so nothing+# from the host can ever reach a loopback bind. socat bridges exactly that gap, on the container+# side, for the duration of a sign-in. Doing it here rather than teaching the CLI to bind 0.0.0.0+# keeps a real computer's SSO callback on its own loopback, where it belongs.+RUN apt-get update \+ && apt-get install -y --no-install-recommends \+ tmux procps git curl ca-certificates less socat \+ && rm -rf /var/lib/apt/lists/*++# The engine under test. Pinned by the build so a rebuild is reproducible; bump it deliberately.+ARG CLAUDE_CODE_VERSION=2.1.260+RUN npm install -g "@anthropic-ai/claude-code@${CLAUDE_CODE_VERSION}" \+ && npm cache clean --force++# ── The CLI, in the same shape `install-cli.sh` produces on a real box ────────────────────────────+# Built from the working tree by scripts/remote-machine.sh; see that script for the version label.+ENV ADAPTER_CLI_DIR=/opt/harness/cli+RUN mkdir -p /opt/harness/cli && printf '{"type":"module"}\n' > /opt/harness/cli/package.json+COPY dist/cli.js dist/notify.mjs /opt/harness/cli/++# The launcher, copied from `install-cli.sh --no-updates`. The pin is the point: see note 1 above.+RUN printf '%s\n' \+ '#!/bin/sh' \+ '# Container install, PINNED. Self-update is off so this box keeps the bytes it was built with;' \+ '# see cli/docker/remote-machine/Dockerfile for why that is not optional here.' \+ 'ADAPTER_UPDATE_DISABLE=true' \+ 'export ADAPTER_UPDATE_DISABLE' \+ 'exec node /opt/harness/cli/cli.js "$@"' \+ > /usr/local/bin/harness \+ && chmod 755 /usr/local/bin/harness++# State lives under the volume; code does not. Both halves of note 2.+ENV ADAPTER_DATA_DIR=/home/node/.harness/data+RUN mkdir -p /home/node/.harness/data && chown -R node:node /home/node/.harness++# Get Claude Code past the two first-run prompts, and nothing else.+#+# A box with no `~/.claude.json` opens on the theme picker, and then on "do you trust this folder?".+# Either one leaves the engine sitting at a prompt, which the daemon correctly reads as an agent that+# is BUSY — so `agent_retarget` refuses it and the rig cannot test the one thing it was built to test.+#+# This is the container standing in for a developer's already-used machine, not a decision being made+# on anyone's behalf. The trust entry covers exactly ONE directory: /home/node/work, which this image+# created and which only ever holds what a test puts there. That is deliberately narrower than what+# `gridLaunch.ts` refuses to do on a real computer — pre-trusting whatever folder a person happens to+# open an agent in — and the difference is the whole justification.+#+# It carries NO credential. An agent in here can reach a model only through the grid environment the+# daemon hands it at launch, which is precisely what makes this rig's answer trustworthy.+RUN mkdir -p /home/node/work \+ && printf '%s\n' '{"hasCompletedOnboarding":true,"theme":"dark","projects":{"/home/node/work":{"hasTrustDialogAccepted":true}}}' \+ > /home/node/.claude.json \+ && chown -R node:node /home/node/.claude.json /home/node/work++COPY --chown=node:node docker/remote-machine/entrypoint.sh /usr/local/bin/entrypoint.sh+RUN chmod 755 /usr/local/bin/entrypoint.sh++USER node+WORKDIR /home/node+VOLUME ["/home/node/.harness"]++ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]diff --git a/cli/docker/remote-machine/entrypoint.sh b/cli/docker/remote-machine/entrypoint.shnew file mode 100755index 000000000..d8f5e2fd2--- /dev/null+++ b/cli/docker/remote-machine/entrypoint.sh@@ -0,0 +1,29 @@+#!/bin/sh+# Keep the box alive, and bring the daemon up when — and only when — it has a session to come up with.+#+# The container is a BOX, not a daemon supervisor. `harness start` self-daemonizes on a real machine+# and does the same here, so pid 1 is this script rather than the adapter: that way a `harness stop`+# from a test, or a daemon that exits on its own, does not take the whole container down and strand+# the SSO session and computer id that the next step needs.+#+# First run has no session at all — SSO is interactive and cannot be automated, so there is nothing to+# do but say so and wait. `scripts/remote-machine.sh login` is what drives the sign-in from outside.+set -eu++echo "[entrypoint] harness $(harness version 2>/dev/null || echo '(version unavailable)')"+echo "[entrypoint] computer id: ${ADAPTER_COMPUTER_ID:-<from volume>}"++if harness auth status --json 2>/dev/null | grep -q '"loggedIn":[[:space:]]*true'; then+ echo "[entrypoint] session found — starting the adapter"+ # Never fatal: a backend that is briefly unreachable must leave the box up and retryable, not kill+ # it and take the volume's session out of reach with it.+ harness start || echo "[entrypoint] WARNING: 'harness start' failed; the box stays up — retry from the host"+else+ echo "[entrypoint] no SSO session yet — sign in with:"+ echo "[entrypoint] bash cli/scripts/remote-machine.sh login"+fi++echo "[entrypoint] ready; holding the container open"+# `exec` so this becomes pid 1 and a `docker stop` reaches it as SIGTERM rather than waiting out the+# 10s grace period on a shell that is ignoring it.+exec tail -f /dev/nulldiff --git a/cli/scripts/install-cli.sh b/cli/scripts/install-cli.shindex 70d67c32e..dd1ca3a7c 100755--- a/cli/scripts/install-cli.sh+++ b/cli/scripts/install-cli.sh@@ -36,12 +36,8 @@ BIN_DIR="${HARNESS_BIN_DIR:-$HOME/.local/bin}"LAUNCHER="$BIN_DIR/harness"PID_FILE="$DATA_DIR/adapter.pid"-# Source of truth for the *core* X.Y.Z, same as upload-cli.sh: whatever is published. Only used to-# label the build (see step 1) — this script never publishes.-GCS_BUCKET="${GCS_BUCKET:-s3-autonomous-upgrade-3}"-GCS_PUBLIC_BASE_URL="${GCS_PUBLIC_BASE_URL:-https://storage.googleapis.com/${GCS_BUCKET}}"-METADATA_PATH="${METADATA_PATH:-harness/cli/metadata.json}"-OTA_KEY="${OTA_KEY:-cli}" # must match ADAPTER_UPDATE_KEY in src/config/env.ts+# The build's version label — and the GCS_BUCKET / METADATA_PATH / OTA_KEY overrides that steer it —+# belong to scripts/lib/build-label.sh, sourced at step 1. This script never publishes.# --- Parse args ---DO_BUILD=1@@ -72,21 +68,11 @@ fi# launcher's disable: even with updates on, the computer sits still until the next real release# instead of oscillating.if [ "$DO_BUILD" -eq 1 ]; then- META_URL="${GCS_PUBLIC_BASE_URL%/}/${METADATA_PATH#/}"- CORE="$(curl -fsSL --max-time 6 "$META_URL" 2>/dev/null | node -e '-let s=""; process.stdin.on("data",d=>s+=d).on("end",()=>{- try { process.stdout.write(String((JSON.parse(s)[process.argv[1]]||{}).version||"")) } catch { process.stdout.write("") }-})' "$OTA_KEY" 2>/dev/null || true)"- if [ -z "$CORE" ]; then- CORE="$(node -p "require('$ADAPTER_DIR/package.json').version" 2>/dev/null || echo '0.0.0')"- echo ">> manifest unreachable — labelling against package.json: $CORE" >&2- fi- SHA="$(git -C "$ADAPTER_DIR" rev-parse --short HEAD 2>/dev/null || echo nogit)"- DIRTY=""- # --porcelain, not `diff --quiet`: an UNTRACKED new source file changes the bundle too. dist/ is- # gitignored, so bundling never makes the next run look dirty by itself.- [ -z "$(git -C "$ADAPTER_DIR" status --porcelain -- "$ADAPTER_DIR" 2>/dev/null)" ] || DIRTY=".dirty"- LABEL="${CORE}-dev.${SHA}${DIRTY}"+ # Shared with the Docker remote-machine rig, so both boxes report the SAME version for the same+ # tree — see scripts/lib/build-label.sh.+ # shellcheck source=lib/build-label.sh+ . "$ADAPTER_DIR/scripts/lib/build-label.sh"+ LABEL="$(harness_build_label "$ADAPTER_DIR")"echo ">> bundling ${LABEL}…" # braces required: bash 3.2 swallows the following UTF-8 byte into the name( cd "$ADAPTER_DIR" && ADAPTER_VERSION="$LABEL" npm run bundle )fidiff --git a/cli/scripts/lib/build-label.sh b/cli/scripts/lib/build-label.shnew file mode 100644index 000000000..453751186--- /dev/null+++ b/cli/scripts/lib/build-label.sh@@ -0,0 +1,47 @@+#!/usr/bin/env bash+# The version label a LOCAL, unpublished build wears — shared by every script that makes one.+#+# `<published-core>-dev.<sha>[.dirty]`. Two properties, both deliberate:+#+# * The core matches the current release, so `harness version` and `harness status` read sensibly+# next to a production install, and semverGt() (lib/selfUpdate.ts) — which compares the X.Y.Z core+# only and is false on equality — can never let the release you are level with overwrite your+# build. The NEXT real release still lands, which is the behaviour you want.+# * The `-dev.<sha>` suffix makes it unmistakably local, and `.dirty` says the tree had uncommitted+# changes when it was bundled — the difference between "this is commit abc123" and "this is+# something only my disk has ever seen".+#+# It lives here rather than inside install-cli.sh because more than one script now builds the same+# bytes: the local install and the Docker remote-machine rig. Two copies of this would drift, and the+# symptom would be two boxes reporting different versions for identical code — precisely the+# confusion a two-machine test cannot afford.++# Print the label for the adapter package at $1. Never fails: every lookup degrades to something+# printable, because refusing to name a build is worse than naming it conservatively.+harness_build_label() {+ local adapter_dir="$1"+ local bucket="${GCS_BUCKET:-s3-autonomous-upgrade-3}"+ local base_url="${GCS_PUBLIC_BASE_URL:-https://storage.googleapis.com/${bucket}}"+ local metadata_path="${METADATA_PATH:-harness/cli/metadata.json}"+ local ota_key="${OTA_KEY:-cli}" # must match ADAPTER_UPDATE_KEY in src/config/env.ts+ local meta_url="${base_url%/}/${metadata_path#/}"++ # The published core, straight from the release manifest the self-updater reads.+ local core+ core="$(curl -fsSL --max-time 6 "$meta_url" 2>/dev/null | node -e '+let s=""; process.stdin.on("data",d=>s+=d).on("end",()=>{+ try { process.stdout.write(String((JSON.parse(s)[process.argv[1]]||{}).version||"")) } catch { process.stdout.write("") }+})' "$ota_key" 2>/dev/null || true)"+ if [ -z "$core" ]; then+ core="$(node -p "require('$adapter_dir/package.json').version" 2>/dev/null || echo '0.0.0')"+ echo ">> manifest unreachable — labelling against package.json: $core" >&2+ fi++ local sha dirty=""+ sha="$(git -C "$adapter_dir" rev-parse --short HEAD 2>/dev/null || echo nogit)"+ # --porcelain, not `diff --quiet`: an UNTRACKED new source file changes the bundle too. dist/ is+ # gitignored, so bundling never makes the next run look dirty by itself.+ [ -z "$(git -C "$adapter_dir" status --porcelain -- "$adapter_dir" 2>/dev/null)" ] || dirty=".dirty"++ printf '%s-dev.%s%s' "$core" "$sha" "$dirty"+}diff --git a/cli/scripts/remote-machine.sh b/cli/scripts/remote-machine.shnew file mode 100755index 000000000..eee844258--- /dev/null+++ b/cli/scripts/remote-machine.sh@@ -0,0 +1,298 @@+#!/usr/bin/env bash+# Drive a second harness machine in Docker — the one thing a single laptop cannot test.+#+# The desktop app reaches another of your machines through the backend relay+# (`src/lib/remoteRelay.ts`): frames leave the local daemon, cross the cloud, and are handled by the+# daemon on the far side. Every interesting behaviour on that path — creating an agent, moving one+# onto a grid, reading back which grid it landed on — is code that never runs when the app and the+# agent share a computer. This rig gives you the far side.+#+# bash cli/scripts/remote-machine.sh build # bundle THIS tree + build the image+# bash cli/scripts/remote-machine.sh up # start the box+# bash cli/scripts/remote-machine.sh login # SSO (interactive — opens a URL you approve)+# bash cli/scripts/remote-machine.sh link # let this Mac's relay reach the box+# bash cli/scripts/remote-machine.sh verify # what each remote agent is ACTUALLY running on+# bash cli/scripts/remote-machine.sh sh # a shell inside the box+# bash cli/scripts/remote-machine.sh down # stop + remove the container (keeps the session)+# bash cli/scripts/remote-machine.sh destroy # ...and throw the session away+#+# `verify` is the instrument the rig exists for. It prints, per agent, BOTH the environment of the+# live engine process (read from /proc, which is the only thing that decides where inference goes)+# AND what the daemon reports about it. Those two disagreeing is a real class of bug — the daemon can+# be right about a process and still describe it wrongly to the app — so the rig refuses to collapse+# them into one number.+set -euo pipefail++ADAPTER_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" # the cli package+RIG_DIR="$ADAPTER_DIR/docker/remote-machine"+RIG_ENV="$RIG_DIR/.rig.env" # gitignored; holds the pinned computer id, nothing secret++IMAGE="${HARNESS_RIG_IMAGE:-harness-remote-machine}"+CONTAINER="${HARNESS_RIG_CONTAINER:-harness-remote-machine}"+VOLUME="${HARNESS_RIG_VOLUME:-harness-remote-machine-state}"+# The Mac's own CLI — the side that has to be told how to reach the box.+HOST_HARNESS="${HARNESS_BIN:-$HOME/.local/bin/harness}"+# The SSO redirect lands on the HOST's browser but must reach a listener inside the box, so the port+# cannot be the ephemeral one `harness login` would otherwise pick — it has to be known in advance to+# be published. Pinned here and honoured by ADAPTER_LOGIN_CALLBACK_PORT on the far side.+LOGIN_PORT="${HARNESS_RIG_LOGIN_PORT:-46789}"++die() { echo "error: $*" >&2; exit 1; }+note() { echo ">> $*"; }++require_docker() {+ command -v docker >/dev/null 2>&1 || die "docker not found"+ docker info >/dev/null 2>&1 || die "the Docker daemon is not running — start Docker Desktop first"+}++running() { [ "$(docker inspect -f '{{.State.Running}}' "$CONTAINER" 2>/dev/null || echo false)" = "true" ]; }+require_running() { running || die "the box is not up — run: bash cli/scripts/remote-machine.sh up"; }++# The container's identity, pinned OUTSIDE the volume.+#+# A machine is bound to its computer id on the backend, so an id that regenerates does not reconnect —+# it mints a SECOND machine on your account and leaves the first as a tombstone. The volume normally+# carries the id, but `destroy` (or any stray `docker volume rm`) takes it with it, and the cost of+# that lands on a real account. Keeping it here means even a wiped volume comes back as the same+# machine.+ensure_computer_id() {+ if [ -f "$RIG_ENV" ]; then+ # shellcheck source=/dev/null+ . "$RIG_ENV"+ fi+ if [ -z "${ADAPTER_COMPUTER_ID:-}" ]; then+ # A UUID, because the backend validates the shape and rejects anything else with+ # "Invalid computer id" — a readable prefix like `docker-...` does not survive registration.+ ADAPTER_COMPUTER_ID="$(node -e 'process.stdout.write(require("crypto").randomUUID())')"+ mkdir -p "$RIG_DIR"+ printf 'ADAPTER_COMPUTER_ID=%s\n' "$ADAPTER_COMPUTER_ID" > "$RIG_ENV"+ note "minted a computer id for the box: $ADAPTER_COMPUTER_ID (kept in docker/remote-machine/.rig.env)"+ fi+ export ADAPTER_COMPUTER_ID+}++cmd_build() {+ require_docker+ # Bundle from the working tree, labelled exactly as a local install is, so `harness version` on the+ # box and on this Mac read identically for the same code. See scripts/lib/build-label.sh.+ # shellcheck source=lib/build-label.sh+ . "$ADAPTER_DIR/scripts/lib/build-label.sh"+ local label+ label="$(harness_build_label "$ADAPTER_DIR")"+ note "bundling ${label}…"+ ( cd "$ADAPTER_DIR" && ADAPTER_VERSION="$label" npm run bundle )+ [ -f "$ADAPTER_DIR/dist/cli.js" ] || die "dist/cli.js missing after the bundle step"++ note "building image ${IMAGE}…" # braces required: bash swallows the following UTF-8 byte into the name+ docker build \+ -f "$RIG_DIR/Dockerfile" \+ -t "$IMAGE" \+ "$ADAPTER_DIR"+ note "built $IMAGE ($label)"+}++cmd_up() {+ require_docker+ ensure_computer_id+ docker image inspect "$IMAGE" >/dev/null 2>&1 \+ || die "image $IMAGE not built — run: bash cli/scripts/remote-machine.sh build"+ if running; then note "already up"; cmd_status; return; fi+ docker rm -f "$CONTAINER" >/dev/null 2>&1 || true+ docker volume create "$VOLUME" >/dev/null+ note "starting ${CONTAINER}…"+ docker run -d \+ --name "$CONTAINER" \+ --hostname harness-remote-box \+ -e ADAPTER_COMPUTER_ID="$ADAPTER_COMPUTER_ID" \+ -e ADAPTER_LOGIN_CALLBACK_PORT="$LOGIN_PORT" \+ -p "127.0.0.1:${LOGIN_PORT}:${LOGIN_PORT}" \+ -v "$VOLUME:/home/node/.harness" \+ "$IMAGE" >/dev/null+ sleep 1+ docker logs "$CONTAINER" 2>&1 | sed 's/^/ /'+}++signed_in() {+ docker exec "$CONTAINER" harness auth status --json 2>/dev/null | grep -q '"loggedIn":[[:space:]]*true'+}++cmd_login() {+ require_running+ if signed_in; then+ note "the box is already signed in"+ else+ # `--json` rather than the human flow, and deliberately so: this is the same NDJSON stream the+ # desktop app drives (`lib/auth/cli_login.dart`), so it needs no TTY and works the same whether a+ # person or a script is watching. The browser step itself cannot be automated — SSO is a person+ # approving something — so the URL is surfaced as loudly as possible and then we wait.+ # Bridge the published port to the callback's loopback bind, for this sign-in only.+ #+ # `harness login` listens on 127.0.0.1:$LOGIN_PORT INSIDE the box — correct everywhere, and+ # unreachable from here, because Docker forwards a published port to the container's eth0 address+ # rather than its loopback. socat listens on that eth0 address (NOT 0.0.0.0: the CLI already owns+ # the same port on loopback, and this way the two cannot collide) and hands the connection across.+ # It exits with the sign-in; nothing is left listening.+ note "bridging the callback port inside the box…"+ docker exec -d "$CONTAINER" sh -c \+ "socat TCP-LISTEN:${LOGIN_PORT},bind=\$(hostname -i),fork,reuseaddr TCP:127.0.0.1:${LOGIN_PORT}"++ note "signing the box in — approve the URL below, then come back"+ docker exec -i "$CONTAINER" harness login --json | node -e '+const rl = require("readline").createInterface({ input: process.stdin })+rl.on("line", (line) => {+ let e; try { e = JSON.parse(line) } catch { return }+ if (e.type === "authorize_url") {+ console.log("")+ console.log(" ┌─ approve the box in your browser ─────────────────────────────")+ console.log(" │ " + e.url)+ console.log(" └───────────────────────────────────────────────────────────────")+ console.log("")+ return+ }+ if (e.type === "result") {+ if (e.status === "success") console.log(e.alreadySignedIn ? " already signed in" : " signed in")+ else { console.error(` sign-in failed: ${e.code} ${e.message || ""}`); process.exitCode = 1 }+ }+})'+ docker exec "$CONTAINER" pkill -f "socat TCP-LISTEN:${LOGIN_PORT}" >/dev/null 2>&1 || true+ signed_in || die "the box is still not signed in"+ fi+ note "starting the adapter on the box…"+ docker exec "$CONTAINER" harness start || true+ cmd_status+}++# The box's own machine id, straight from the backend's answer rather than anything we guessed.+box_machine_id() {+ docker exec "$CONTAINER" harness machines --json 2>/dev/null \+ | node -e '+let s=""; process.stdin.on("data",d=>s+=d).on("end",()=>{+ for (const line of s.split("\n")) {+ if (!line.trim()) continue+ try { const m = JSON.parse(line); if (m.current) { process.stdout.write(String(m.machineId||"")); return } } catch {}+ }+})'+}++cmd_link() {+ require_running+ [ -x "$HOST_HARNESS" ] || die "this Mac's harness CLI not found at $HOST_HARNESS (set HARNESS_BIN)"+ local id+ id="$(box_machine_id)"+ [ -n "$id" ] || die "the box has no machine id yet — run: bash cli/scripts/remote-machine.sh login"+ note "box machine id: $id"++ # A fresh password per run, held only in this shell and passed on stdin to BOTH sides. It is never+ # written to disk and never appears in argv — `ps` is world-readable, and a rig that taught the+ # habit of putting credentials on a command line would be teaching the wrong habit.+ local password+ password="$(node -e 'process.stdout.write(require("crypto").randomBytes(24).toString("base64url"))')"++ note "setting the box's remote password…"+ printf '%s\n' "$password" | docker exec -i "$CONTAINER" harness remote-password set --stdin+ note "connecting this Mac to it…"+ printf '%s\n' "$password" | "$HOST_HARNESS" link connect "$id" --stdin+ note "linked — the box should now appear as a machine in the desktop app"+}++cmd_status() {+ require_docker+ if ! running; then echo "box: not running"; return; fi+ echo "box: running ($CONTAINER)"+ docker exec "$CONTAINER" harness status 2>&1 | sed 's/^/ /' || true+ if [ -x "$HOST_HARNESS" ]; then+ echo "this Mac's linked machines:"+ "$HOST_HARNESS" link list 2>&1 | sed 's/^/ /' || true+ fi+}++# What is each remote agent ACTUALLY running on, and does the daemon agree?+cmd_verify() {+ require_running+ docker exec "$CONTAINER" node -e '+const fs = require("fs")+const path = require("path")++const dataDir = process.env.ADAPTER_DATA_DIR || "/home/node/.harness/data"+const registryPath = path.join(dataDir, "registry.json")++// Only the variables that decide where inference goes. The rest of a process environment is the+// user'"'"'s business and this rig has no reason to print it.+const INTERESTING = ["ANTHROPIC_BASE_URL", "ANTHROPIC_MODEL", "OPENAI_BASE_URL", "GROK_MODELS_BASE_URL", "COPILOT_PROVIDER_BASE_URL"]++function processEnv(pid) {+ try {+ const out = {}+ for (const entry of fs.readFileSync(`/proc/${pid}/environ`, "utf8").split("\0")) {+ const eq = entry.indexOf("=")+ if (eq > 0 && INTERESTING.includes(entry.slice(0, eq))) out[entry.slice(0, eq)] = entry.slice(eq + 1)+ }+ return out+ } catch { return null }+}++let agents = []+try {+ const raw = JSON.parse(fs.readFileSync(registryPath, "utf8"))+ agents = Array.isArray(raw) ? raw : (raw.agents ? (Array.isArray(raw.agents) ? raw.agents : Object.values(raw.agents)) : [])+} catch (err) {+ console.log(`no registry at ${registryPath} (${err.code || err.message}) — has an agent been created on this box yet?`)+ process.exit(0)+}++if (!agents.length) { console.log("the box has no agents yet — create one on this machine from the app"); process.exit(0) }++for (const a of agents) {+ const pid = a.processIdentity && a.processIdentity.pid+ const env = pid ? processEnv(pid) : null+ console.log(`agent ${String(a.agentId).slice(0, 8)} engine=${a.engine} pid=${pid ?? "-"} cwd=${a.cwd ?? "-"}`)+ // The process is the truth: an environment is fixed at exec, so this is where the requests go.+ if (env === null) console.log(" process env : UNREADABLE (process gone?)")+ else if (!Object.keys(env).length) console.log(" process env : no endpoint override — the engine is on its OWN login")+ else for (const [k, v] of Object.entries(env)) console.log(` process env : ${k}=${v}`)+ // What the daemon would tell the app. Printed separately ON PURPOSE — see the header of this file.+ console.log(` daemon says : grid=${JSON.stringify(a.grid ?? null)}`)+}+' 2>&1+}++cmd_sh() { require_running; docker exec -it "$CONTAINER" bash; }++cmd_down() {+ require_docker+ docker rm -f "$CONTAINER" >/dev/null 2>&1 || true+ note "container removed (volume $VOLUME kept — the box keeps its session and id)"+}++cmd_destroy() {+ require_docker+ local id=""+ running && id="$(box_machine_id || true)"+ docker rm -f "$CONTAINER" >/dev/null 2>&1 || true+ docker volume rm "$VOLUME" >/dev/null 2>&1 || true+ rm -f "$RIG_ENV"+ note "container, volume and pinned id removed"+ # The machine record lives on the ACCOUNT, and nothing local can remove it. Say so plainly rather+ # than leaving a tombstone the user finds weeks later in their machine list.+ if [ -n "$id" ]; then+ echo " the machine record is still on your account. Remove it with:"+ echo " harness machines delete $id"+ else+ echo " if the box was ever signed in, remove its machine record with:"+ echo " harness machines # find it"+ echo " harness machines delete <id>"+ fi+}++case "${1:-}" in+ build) cmd_build ;;+ up) cmd_up ;;+ login) cmd_login ;;+ link) cmd_link ;;+ status) cmd_status ;;+ verify) cmd_verify ;;+ sh) cmd_sh ;;+ down) cmd_down ;;+ destroy) cmd_destroy ;;+ *) sed -n '2,20p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; exit 1 ;;+esacdiff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 592817d62..d41a86544 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -421,7 +421,9 @@ async function loginCommand(foreground: boolean, force: boolean, json: boolean):const callback = createServer()await new Promise<void>((resolve, reject) => {callback.once('error', reject)- callback.listen(0, '127.0.0.1', () => resolve())+ // 0 = whatever the OS gives, which is what a real computer wants. Pinned only where the browser+ // and this listener are not on the same loopback — see ADAPTER_LOGIN_CALLBACK_PORT.+ callback.listen(env.ADAPTER_LOGIN_CALLBACK_PORT, '127.0.0.1', () => resolve())})const address = callback.address()if (!address || typeof address === 'string') throw new Error('Could not start the SSO callback server')diff --git a/cli/src/config/env.ts b/cli/src/config/env.tsindex 8a2df2809..9f0d0a7e4 100644--- a/cli/src/config/env.ts+++ b/cli/src/config/env.ts@@ -116,6 +116,15 @@ const envSchema = z.object({// value (below the OS ephemeral range, outside the project's 80xx/8100-8999/9001-9999 ranges). No// free-port fallback — if it's taken, the adapter reports it (another adapter is likely running).PORT: z.string().default('18473').transform(Number),+ // The loopback port `harness login` listens on for the SSO redirect. 0 (the default) takes whatever+ // the OS gives, which is right on a real computer: the browser and the listener are the same+ // loopback, so the port never has to be known in advance.+ //+ // It has to be PINNABLE for a login that happens inside a container. There the browser is on the+ // host and the listener is not, so the only way the redirect ever arrives is a published port — and+ // a port cannot be published before it is known. Set this, publish the same number, and the real+ // SSO flow works from a box with no browser of its own. See cli/docker/remote-machine/.+ ADAPTER_LOGIN_CALLBACK_PORT: z.string().default('0').transform(Number),// The backend the CLI dials (`/api/adapter-ws`). Local dev: ws://localhost:8090.BACKEND_WS_URL: z.string().default('wss://harness-api.autonomous.ai'),// SSO account plane used by native-loopback login and the adapter WebSocket.