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(sharing): guest machine sharing — a guest's own OS account, the owner's subscriptions, shared folders
bitcoinbuilderbc7f56ff9a2a
diff --git a/backend/src/lib/hub.test.ts b/backend/src/lib/hub.test.tsindex f4d5ed3a2..94ef392a6 100644--- a/backend/src/lib/hub.test.ts+++ b/backend/src/lib/hub.test.ts@@ -68,6 +68,24 @@ describe('hub fan-out backpressure', () => {})})+describe('a guest on a shared machine', () => {+ // A guest hears only what the machine addresses to it, never the owner's broadcasts+ // (docs/plans/2026-10-19-guest-machine-sharing-plan.md).+ it('is sent no broadcast, only the frames addressed to its own connection', () => {+ const machineId = `hub-guest-${Date.now()}`+ const ownerOut: string[] = []+ const guestOut: string[] = []+ const owner = attachHubClient(socket(ownerOut), machineId, 'web')+ const guest = attachHubClient(socket(guestOut), machineId, 'web', { guest: true })+ deliverUpLocal(machineId, { webEligible: true, commanderEligible: false, frame: { type: 'agent_synced', payload: { agent: { id: 'owners' } } } })+ deliverUpLocal(machineId, { webEligible: true, commanderEligible: false, targetConnId: guest.connId, frame: { type: 'agent_synced', payload: { sealed: true } } })+ expect(ownerOut).toHaveLength(1)+ expect(guestOut).toHaveLength(1)+ expect(guestOut[0]).toContain('sealed')+ owner.detach(); guest.detach()+ })+})+describe('sendClientsControl coalescing', () => {beforeEach(async () => {await flush() // let any attach/detach flush from the previous describe land firstdiff --git a/backend/src/lib/hub.ts b/backend/src/lib/hub.tsindex 57cfb1675..e884dae0f 100644--- a/backend/src/lib/hub.ts+++ b/backend/src/lib/hub.ts@@ -78,6 +78,7 @@ export function deliverUpLocal(machineId: string, msg: UpBusMsg): void {// frame is not a broadcast. Without this, `e2e_status_result` etc. never reach a paired device// (commanders are filtered by `!commanderEligible` and by the `_result` suppression).if (!msg.targetConnId) {+ if (c.guest) return // a guest hears only what is addressed to itif (c.kind === 'web' && msg.webEligible === false) return // device-only frame (forwardToCommander)if (c.kind === 'commander' && !msg.commanderEligible) return // preserve COMMANDER_FORWARD filter// RPC replies (`<x>_result`) are answered to the device directly by deviceWs (trimmed); the@@ -309,13 +310,13 @@ setTimeout(() => {}, Math.floor(Math.random() * 5_000)).unref?.()/** Register a client socket into the hub. The caller still owns the socket's 'message' handler. */-export function attachHubClient(socket: WebSocket, machineId: string, kind: ClientKind): HubClient {+export function attachHubClient(socket: WebSocket, machineId: string, kind: ClientKind, opts: { guest?: boolean } = {}): HubClient {const connId = randomUUID();(socket as Alive).__hubLastAlive = Date.now()// Wired ONCE per socket because a web socket re-attaches on every agent switch. Note this does NOT// touch __hubDeadlineMs: a device sets its own (shorter) deadline before any machine attaches.wireLiveness(socket)- const first = registry.addClient({ connId, machineId, kind, socket })+ const first = registry.addClient({ connId, machineId, kind, socket, ...(opts.guest ? { guest: true } : {}) })if (first) {void subscribeUp(machineId, (msg) => {diff --git a/backend/src/lib/registry.ts b/backend/src/lib/registry.tsindex 7c5bbd4b6..32f249202 100644--- a/backend/src/lib/registry.ts+++ b/backend/src/lib/registry.ts@@ -31,6 +31,10 @@ export interface ClientConn {// so the node/adapter streams full turn cards only to an actively-viewed machine, while still running the// (cheaper) recap for every attached commander. Always false/undefined for web + background machines.active?: boolean+ // A web client using a machine shared with its account as a GUEST (lib/machineAccess.ts): it is never+ // sent the machine's broadcasts — the owner's events — only the frames addressed to its own connection,+ // which the machine seals for it (docs/plans/2026-10-19-guest-machine-sharing-plan.md).+ guest?: boolean}export interface QueuedCommanderFrame {diff --git a/backend/src/lib/webWs.ts b/backend/src/lib/webWs.tsindex 6d1774fff..8f91edbb2 100644--- a/backend/src/lib/webWs.ts+++ b/backend/src/lib/webWs.ts@@ -359,7 +359,8 @@ function attachUserClient(ws: WebSocket, user: AuthUser, surface: 'mobile' | 'we// selecting a deliberately stopped machine wakes it before the readiness ack.if (client && machineId === currentAgentId) { currentBinding = binding; ack(machineId); return }client?.detach()- client = attachHubClient(ws, machineId, 'web')+ // A guest never hears the machine's broadcasts, only what the machine addresses to it (lib/hub.ts).+ client = attachHubClient(ws, machineId, 'web', { guest: !!shared })currentAgentId = machineIdcurrentBinding = bindingwatchShare(shared ? machineId : null)diff --git a/backend/src/types/productUsage.ts b/backend/src/types/productUsage.tsindex f1ec00673..8b6c51120 100644--- a/backend/src/types/productUsage.ts+++ b/backend/src/types/productUsage.ts@@ -103,6 +103,10 @@ export const LAUNCH_ERROR_CODES = ['restart_failed', 'restart_unsupported_backend', 'retarget_unsupported_backend', 'fork_on_grid_unsupported','no_active_process', 'opencode_sqlite_missing', 'unavailable', 'missing_name', 'missing_update','invalid_close_request', 'invalid_delete_request', 'close_failed', 'delete_failed',+ // A guest on a machine shared with it (core/guestPolicy.ts, core/agents/guestCreate.ts, services/guestLaunches.ts).+ 'guest_not_allowed', 'guest_unsupported', 'guest_harness', 'guest_unavailable', 'guest_helper_required',+ 'guest_engine_unsupported', 'guest_relay_failed', 'guest_folder_unavailable', 'guest_invalid', 'guest_helper_missing',+ 'guest_helper_not_authorized', 'guest_helper_failed','unlisted', 'none',] as constexport type LaunchErrorCode = typeof LAUNCH_ERROR_CODES[number]diff --git a/cli/assets/guest-helper/guest-helper.sh b/cli/assets/guest-helper/guest-helper.shnew file mode 100755index 000000000..b5d75b505--- /dev/null+++ b/cli/assets/guest-helper/guest-helper.sh@@ -0,0 +1,531 @@+#!/bin/sh+# Harness guest helper: the one privileged step of sharing a machine with a guest+# (docs/plans/2026-10-19-guest-machine-sharing-plan.md).+#+# Installed root-owned at /usr/local/libexec/harness/guest-helper by the owner's one-time admin+# prompt (cli/src/lib/guestHelperInstall.ts), and run by the owner's daemon through+# `sudo -n` (/etc/sudoers.d/harness-guests). A guest's harness runs as an OS user of its own, so+# it can read neither the owner's files nor another guest's.+#+# ensure <email> create the guest's user, home and workspace+# run <user> --cwd <dir> [--pass KEY]... [--env KEY=VALUE]... -- <argv>+# run argv as that user, in <dir>+# install <user> claude|codex|opencode install an engine into the guest's home+# share <user> [--read DIR]... [--write DIR]... give the guest exactly these of the owner's folders+# shared <user> the folders the guest has, one `read|write<TAB>DIR` a line+# remove <user> delete the user, its processes and its home+# version this helper's version+#+# Everything a caller passes is validated: users are hg_<12 hex> in the harnessguest group, a cwd+# resolves inside that user's home or a folder shared with it, a shared folder is the owner's own+# (never /, the owner's whole home or a guest's home), and only the keys in GUEST_ENV_KEYS reach the+# guest's process.+# `--pass KEY` hands over the value this helper was started with (the daemon sets it on the tmux+# pane, and the sudoers drop-in keeps exactly these keys): a token on the command line would be+# readable by every account on the machine in `ps`. `--env KEY=VALUE` is for values that are not+# secret.+# HARNESS_GUEST_HELPER_DRY_RUN=1 prints the commands instead of running them (tests); it, and the+# platform, home-root, state and owner-home overrides that go with it, are refused when running as root.+set -eu+# Wherever the caller stood, which a guest (and root's `cd` into a guest's folder) may not be able to read: every+# path here is absolute.+cd /++HELPER_VERSION=2+GROUP=harnessguest+# The variables a guest's harness may be given. Nothing of the owner's reaches it: `sudo -u ... env -i`.+GUEST_ENV_KEYS='TERM COLORTERM LANG ANTHROPIC_BASE_URL ANTHROPIC_AUTH_TOKEN ANTHROPIC_MODEL HARNESS_RELAY_TOKEN HARNESS_HOOK_TOKEN HARNESS_HOOK_URL HARNESS_AGENT_ID CODEX_HOME'+NODE_DIR=/usr/local/lib/harness/node++die() {+ printf 'guest-helper: %s\n' "$1" >&2+ exit "${2:-2}"+}++DRY=+if [ "${HARNESS_GUEST_HELPER_DRY_RUN:-}" = 1 ]; then+ [ "$(id -u)" != 0 ] || die 'dry run is refused as root'+ DRY=1+fi++PLATFORM=$(uname -s)+if [ -n "$DRY" ] && [ -n "${HARNESS_GUEST_HELPER_PLATFORM:-}" ]; then PLATFORM=$HARNESS_GUEST_HELPER_PLATFORM; fi+case $PLATFORM in+ Darwin) HOME_ROOT=/Users/Shared/HarnessGuests; GUEST_SHELL=/bin/zsh ;;+ Linux) HOME_ROOT=/home/harness-guests; GUEST_SHELL=/bin/bash ;;+ *) die "unsupported platform: $PLATFORM" ;;+esac+if [ -n "$DRY" ] && [ -n "${HARNESS_GUEST_HELPER_DRY_HOME_ROOT:-}" ]; then HOME_ROOT=$HARNESS_GUEST_HELPER_DRY_HOME_ROOT; fi+# Which of the owner's folders each guest has (`share`), one root-owned file per guest. The ACLs are the+# grant; this is what `run` and the next `share` read, so a share that has not changed changes nothing.+case $PLATFORM in+ Darwin) STATE_DIR=/var/db/harness-guests ;;+ Linux) STATE_DIR=/var/lib/harness-guests ;;+esac+if [ -n "$DRY" ] && [ -n "${HARNESS_GUEST_HELPER_DRY_STATE_DIR:-}" ]; then STATE_DIR=$HARNESS_GUEST_HELPER_DRY_STATE_DIR; fi+TAB=$(printf '\t')++# One shell word, quoted, for the dry-run transcript.+quote() {+ printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"+}++# Runs its arguments, or (dry run) prints them on one line after `+ `.+do_cmd() {+ if [ -n "$DRY" ]; then+ printf '+'+ for word do printf ' %s' "$(quote "$word")"; done+ printf '\n'+ return 0+ fi+ "$@"+}++# Like do_cmd, for the last command: replaces this process.+exec_cmd() {+ if [ -n "$DRY" ]; then+ do_cmd "$@"+ exit 0+ fi+ exec "$@"+}++valid_user() {+ printf '%s' "$1" | grep -Eq '^hg_[0-9a-f]{12}$'+}++sha256_hex() {+ if command -v shasum >/dev/null 2>&1; then+ printf '%s' "$1" | shasum -a 256 | cut -c1-64+ else+ printf '%s' "$1" | sha256sum | cut -c1-64+ fi+}++# The owner this helper acts for: the account sudo ran it from (the dry run's own account).+owner_name() {+ if [ -n "$DRY" ]; then id -un; return; fi+ owner=${SUDO_USER:-}+ printf '%s' "$owner" | grep -Eq '^[A-Za-z_][A-Za-z0-9_.-]{0,31}$' || die 'run through sudo by the owner'+ [ "$owner" != root ] || die 'run through sudo by the owner'+ valid_user "$owner" && die 'a guest cannot run the guest helper'+ printf '%s' "$owner"+}++# The guest's existence and group, checked before anything runs as them. A dry run takes a home+# under its home root as the user existing.+require_guest() {+ valid_user "$1" || die "not a guest user: $1"+ if [ -n "$DRY" ]; then+ [ -d "$HOME_ROOT/$1" ] || die "no such guest: $1" 3+ return 0+ fi+ id "$1" >/dev/null 2>&1 || die "no such guest: $1" 3+ [ "$(id -gn "$1")" = "$GROUP" ] || die "not in $GROUP: $1"+}++env_allowed() {+ key=$1+ case $key in+ LC_*) printf '%s' "$key" | grep -Eq '^LC_[A-Z_]+$'; return ;;+ esac+ for allowed in $GUEST_ENV_KEYS; do+ [ "$key" = "$allowed" ] && return 0+ done+ return 1+}++# The first free id at or above 600 among the given dscl listing's numbers.+free_id() {+ used=$1+ candidate=600+ while printf '%s\n' "$used" | grep -qx "$candidate"; do candidate=$((candidate + 1)); done+ printf '%s' "$candidate"+}++ensure_group_darwin() {+ if [ -z "$DRY" ] && dscl . -read "/Groups/$GROUP" PrimaryGroupID >/dev/null 2>&1; then+ dscl . -read "/Groups/$GROUP" PrimaryGroupID | awk '{print $2}'+ return+ fi+ if [ -n "$DRY" ]; then gid=600; else gid=$(free_id "$(dscl . -list /Groups PrimaryGroupID | awk '{print $2}')"); fi+ do_cmd dscl . -create "/Groups/$GROUP" >&2+ do_cmd dscl . -create "/Groups/$GROUP" PrimaryGroupID "$gid" >&2+ do_cmd dscl . -create "/Groups/$GROUP" RealName 'Harness guests' >&2+ do_cmd dscl . -create "/Groups/$GROUP" Password '*' >&2+ printf '%s' "$gid"+}++# The owner may read a guest's files (it is the owner's machine, and the daemon lists a guest's+# workspace for them); other guests may not.+grant_owner_read() {+ owner=$1 path=$2+ if [ "$PLATFORM" = Darwin ]; then+ do_cmd chmod +a "$owner allow list,search,readattr,readextattr,readsecurity,read,file_inherit,directory_inherit" "$path"+ elif command -v setfacl >/dev/null 2>&1 || [ -n "$DRY" ]; then+ do_cmd setfacl -m "u:$owner:rX" "$path"+ do_cmd setfacl -d -m "u:$owner:rX" "$path"+ else+ printf 'guest-helper: setfacl is missing: the owner cannot read %s\n' "$path" >&2+ fi+}++# The owner's home: never shared whole, since its dotfiles hold every sign-in on the machine.+owner_home() {+ if [ -n "$DRY" ]; then printf '%s' "${HARNESS_GUEST_HELPER_DRY_OWNER_HOME:-$HOME}"; return; fi+ if [ "$PLATFORM" = Darwin ]; then+ dscl . -read "/Users/$1" NFSHomeDirectory | awk '{print $2}'+ else+ getent passwd "$1" | cut -d: -f6+ fi+}++# The account that owns [path], read the way this system's stat reads it.+path_owner() {+ case $(uname -s) in+ Darwin | *BSD) stat -f %Su "$1" ;;+ *) stat -c %U "$1" ;;+ esac+}++# A folder the owner may share, resolved; or the reason it may not be.+shareable() {+ dir=$1+ case $dir in /*) ;; *) die "not an absolute path: $dir" ;; esac+ case $dir in *"$TAB"* | *'+'*) die "not a folder that can be shared: $dir" ;; esac+ real=$(cd "$dir" 2>/dev/null && pwd -P) || die "no such folder: $dir"+ [ "$real" != / ] || die 'not a folder that can be shared: /'+ owner=$(owner_name)+ home=$(owner_home "$owner")+ real_home=$(cd "$home" 2>/dev/null && pwd -P) || real_home=$home+ [ "$real" != "$real_home" ] || die "the owner's whole home cannot be shared: choose a folder in it"+ real_root=$(cd "$HOME_ROOT" 2>/dev/null && pwd -P) || real_root=$HOME_ROOT+ case $real in "$real_root" | "$real_root"/*) die "a guest's home cannot be shared: $dir" ;; esac+ [ "$(path_owner "$real")" = "$owner" ] || die "not the owner's folder: $dir"+ printf '%s' "$real"+}++FOLDER_READ='list,search,readattr,readextattr,readsecurity,read,execute'+FOLDER_WRITE='write,append,add_file,add_subdirectory,delete_child,delete,writeattr,writeextattr'++# The macOS entry a guest has on a shared folder and everything in it, now and created later.+folder_ace() {+ if [ "$2" = write ]; then+ printf '%s allow %s,%s,file_inherit,directory_inherit' "$1" "$FOLDER_READ" "$FOLDER_WRITE"+ else+ printf '%s allow %s,file_inherit,directory_inherit' "$1" "$FOLDER_READ"+ fi+}++grant_folder() {+ user=$1 mode=$2 dir=$3+ if [ "$PLATFORM" = Darwin ]; then+ do_cmd chmod -R +a "$(folder_ace "$user" "$mode")" "$dir"+ else+ perm=rX+ [ "$mode" = write ] && perm=rwX+ do_cmd setfacl -R -m "u:$user:$perm" "$dir"+ do_cmd find "$dir" -type d -exec setfacl -d -m "u:$user:$perm" {} ++ fi+}++# Taken back, as it was given: on macOS `chmod -a` also takes the entries files made since inherited.+revoke_folder() {+ user=$1 mode=$2 dir=$3+ [ -n "$DRY" ] || [ -d "$dir" ] || return 0+ if [ "$PLATFORM" = Darwin ]; then+ do_cmd chmod -R -a "$(folder_ace "$user" "$mode")" "$dir" || true+ else+ do_cmd setfacl -R -x "u:$user" "$dir" || true+ do_cmd find "$dir" -type d -exec setfacl -d -x "u:$user" {} + || true+ fi+}++# Whether every account may pass through [dir] already (its mode's last digit is odd).+open_to_all() {+ case $(uname -s) in+ Darwin | *BSD) bits=$(stat -f %Lp "$1") ;;+ *) bits=$(stat -c %a "$1") ;;+ esac+ [ $(( ${bits#"${bits%?}"} % 2 )) = 1 ]+}++# The folders above each shared one that the guest must pass through (and only pass through: no listing) to+# reach it: not those anyone may pass through already (/, /Users, …), nor those shared themselves.+ancestors() {+ printf '%s\n' "$1" | while IFS="$TAB" read -r mode path; do+ [ -n "$path" ] || continue+ d=$(dirname "$path")+ while [ "$d" != / ]; do+ if ! printf '%s\n' "$1" | cut -f2 | grep -Fxq "$d" && ! open_to_all "$d"; then printf '%s\n' "$d"; fi+ d=$(dirname "$d")+ done+ done | sort -u+}++grant_search() {+ if [ "$PLATFORM" = Darwin ]; then do_cmd chmod +a "$1 allow search" "$2"; else do_cmd setfacl -m "u:$1:x" "$2"; fi+}++revoke_search() {+ [ -n "$DRY" ] || [ -d "$2" ] || return 0+ if [ "$PLATFORM" = Darwin ]; then do_cmd chmod -a "$1 allow search" "$2" || true; else do_cmd setfacl -x "u:$1" "$2" || true; fi+}++# What [user] has now: `mode<TAB>path` lines.+shares_of() {+ [ -f "$STATE_DIR/$1" ] && cat "$STATE_DIR/$1" || true+}++# Gives [user] exactly the folders in [want] (`mode<TAB>path` lines): what changed, and nothing else.+apply_shares() {+ user=$1 want=$2+ have=$(shares_of "$user")+ printf '%s\n' "$have" | while IFS="$TAB" read -r mode path; do+ [ -n "$path" ] || continue+ printf '%s\n' "$want" | grep -Fxq "$mode$TAB$path" || revoke_folder "$user" "$mode" "$path"+ done+ printf '%s\n' "$want" | while IFS="$TAB" read -r mode path; do+ [ -n "$path" ] || continue+ printf '%s\n' "$have" | grep -Fxq "$mode$TAB$path" || grant_folder "$user" "$mode" "$path"+ done+ before=$(ancestors "$have")+ after=$(ancestors "$want")+ printf '%s\n' "$after" | while read -r dir; do+ [ -n "$dir" ] || continue+ printf '%s\n' "$before" | grep -Fxq "$dir" || grant_search "$user" "$dir"+ done+ printf '%s\n' "$before" | while read -r dir; do+ [ -n "$dir" ] || continue+ printf '%s\n' "$after" | grep -Fxq "$dir" || revoke_search "$user" "$dir"+ done+ mkdir -p "$STATE_DIR"+ chmod 700 "$STATE_DIR"+ if [ -n "$want" ]; then+ printf '%s\n' "$want" > "$STATE_DIR/$user.tmp"+ chmod 600 "$STATE_DIR/$user.tmp"+ mv "$STATE_DIR/$user.tmp" "$STATE_DIR/$user"+ else+ rm -f "$STATE_DIR/$user"+ fi+}++cmd_share() {+ [ $# -ge 1 ] || die 'usage: share <user> [--read DIR]... [--write DIR]...'+ user=$1+ shift+ require_guest "$user"+ want=''+ while [ $# -gt 0 ]; do+ case $1 in+ --read | --write)+ [ $# -ge 2 ] || die 'usage: share <user> [--read DIR]... [--write DIR]...'+ mode=${1#--}+ path=$(shareable "$2")+ if [ -n "$want" ] && printf '%s\n' "$want" | cut -f2 | grep -Fxq "$path"; then die "shared twice: $path"; fi+ want="$want${want:++}$mode$TAB$path"+ shift 2+ ;;+ *) die "unexpected argument: $1" ;;+ esac+ done+ apply_shares "$user" "$want"+}++cmd_shared() {+ [ $# -eq 1 ] || die 'usage: shared <user>'+ require_guest "$1"+ shares_of "$1"+}++# Whether [dir] is in one of the folders shared with [user].+in_shared() {+ [ -f "$STATE_DIR/$1" ] || return 1+ while IFS="$TAB" read -r mode path; do+ case $2 in "$path" | "$path"/*) return 0 ;; esac+ done < "$STATE_DIR/$1"+ return 1+}++cmd_ensure() {+ [ $# -eq 1 ] || die 'usage: ensure <email>'+ email=$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')+ [ "${#email}" -le 254 ] || die 'not an email address'+ printf '%s' "$email" | grep -Eq "^[a-z0-9._%+'-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*\\.[a-z]{2,}\$" \+ || die 'not an email address'+ user="hg_$(sha256_hex "$email" | cut -c1-12)"+ home="$HOME_ROOT/$user"+ owner=$(owner_name)+ exists=+ if [ -n "$DRY" ]; then+ [ -d "$home" ] && exists=1+ elif id "$user" >/dev/null 2>&1; then+ exists=1+ fi+ if [ -z "$exists" ]; then+ do_cmd mkdir -p "$HOME_ROOT" >&2+ do_cmd chmod 755 "$HOME_ROOT" >&2+ if [ "$PLATFORM" = Darwin ]; then+ gid=$(ensure_group_darwin)+ if [ -n "$DRY" ]; then uid=600; else uid=$(free_id "$(dscl . -list /Users UniqueID | awk '{print $2}')"); fi+ do_cmd dscl . -create "/Users/$user" >&2+ do_cmd dscl . -create "/Users/$user" UniqueID "$uid" >&2+ do_cmd dscl . -create "/Users/$user" PrimaryGroupID "$gid" >&2+ do_cmd dscl . -create "/Users/$user" UserShell "$GUEST_SHELL" >&2+ do_cmd dscl . -create "/Users/$user" RealName "Harness guest $email" >&2+ do_cmd dscl . -create "/Users/$user" NFSHomeDirectory "$home" >&2+ do_cmd dscl . -create "/Users/$user" IsHidden 1 >&2+ do_cmd dscl . -create "/Users/$user" Password '*' >&2+ do_cmd dscl . -append "/Groups/$GROUP" GroupMembership "$user" >&2+ do_cmd mkdir -p "$home" >&2+ else+ if [ -n "$DRY" ] || ! getent group "$GROUP" >/dev/null 2>&1; then do_cmd groupadd -r -f "$GROUP" >&2; fi+ do_cmd useradd -r -m -d "$home" -g "$GROUP" -s "$GUEST_SHELL" -c "Harness guest $email" "$user" >&2+ fi+ do_cmd chown "$user:$GROUP" "$home" >&2+ do_cmd chmod 700 "$home" >&2+ grant_owner_read "$owner" "$home" >&2+ fi+ if [ -n "$DRY" ] || [ ! -d "$home/work" ]; then+ do_cmd mkdir -p "$home/work" >&2+ do_cmd chown "$user:$GROUP" "$home/work" >&2+ do_cmd chmod 700 "$home/work" >&2+ fi+ printf '{"user":"%s","home":"%s","workspace":"%s"}\n' "$user" "$home" "$home/work"+}++cmd_run() {+ [ $# -ge 1 ] || die 'usage: run <user> --cwd <dir> [--pass KEY]... [--env KEY=VALUE]... -- <argv>'+ user=$1+ shift+ require_guest "$user"+ home="$HOME_ROOT/$user"++ # First pass: validate the options and find the command.+ cwd='' expect='' seen='' argc=0+ for arg do+ if [ -n "$seen" ]; then argc=$((argc + 1)); continue; fi+ case $expect in+ cwd) cwd=$arg; expect=; continue ;;+ env)+ key=${arg%%=*}+ [ "$key" != "$arg" ] || die "not KEY=VALUE: $arg"+ env_allowed "$key" || die "not allowed for a guest: $key"+ expect=+ continue+ ;;+ pass)+ env_allowed "$arg" || die "not allowed for a guest: $arg"+ expect=+ continue+ ;;+ esac+ case $arg in+ --cwd) expect='cwd' ;;+ --env) expect='env' ;;+ --pass) expect='pass' ;;+ --) seen=1 ;;+ *) die "unexpected argument: $arg" ;;+ esac+ done+ [ -z "$expect" ] && [ -n "$seen" ] || die 'usage: run <user> --cwd <dir> [--pass KEY]... [--env KEY=VALUE]... -- <argv>'+ [ "$argc" -gt 0 ] || die 'nothing to run'+ [ -n "$cwd" ] || die 'a --cwd is required'+ case $cwd in /*) ;; *) die "not an absolute path: $cwd" ;; esac+ real_home=$(cd "$home" && pwd -P) || die "no home for $user"+ real_cwd=$(cd "$cwd" 2>/dev/null && pwd -P) || die "no such folder: $cwd"+ case $real_cwd in+ "$real_home" | "$real_home"/*) ;;+ *) in_shared "$user" "$real_cwd" || die "outside the guest's home and shared folders: $cwd" ;;+ esac++ # Second pass: rebuild the arguments as the env pairs, the cd trampoline, then the command.+ count=$# expect='' seen=''+ # shellcheck disable=SC2016 # the trampoline's "$1" and "$@" are the guest shell's, not this one's+ for arg do+ if [ -n "$seen" ]; then set -- "$@" "$arg"; continue; fi+ case $expect in+ cwd) expect=; continue ;;+ env) set -- "$@" "$arg"; expect=; continue ;;+ pass)+ # (An unset key is left out, not passed empty.)+ if value=$(printenv "$arg"); then set -- "$@" "$arg=$value"; fi+ expect=+ continue+ ;;+ esac+ case $arg in+ --cwd) expect='cwd' ;;+ --env) expect='env' ;;+ --pass) expect='pass' ;;+ --) seen=1; set -- "$@" /bin/sh -c 'cd "$1" || exit 1; shift; exec "$@"' harness-guest "$real_cwd" ;;+ esac+ done+ shift "$count"+ exec_cmd sudo -u "$user" -H env -i "HOME=$home" "USER=$user" "LOGNAME=$user" "SHELL=$GUEST_SHELL" \+ "PATH=$home/.local/bin:$home/.opencode/bin:$NODE_DIR/bin:/usr/local/bin:/usr/bin:/bin" "$@"+}++cmd_install() {+ [ $# -eq 2 ] || die 'usage: install <user> claude|codex|opencode'+ user=$1 engine=$2+ require_guest "$user"+ home="$HOME_ROOT/$user"+ path="$home/.local/bin:$home/.opencode/bin:$NODE_DIR/bin:/usr/local/bin:/usr/bin:/bin"+ printf 'Installing %s for %s\n' "$engine" "$user"+ case $engine in+ claude)+ do_cmd sudo -u "$user" -H env -i "HOME=$home" "USER=$user" "PATH=$path" /bin/sh -c 'curl -fsSL https://claude.ai/install.sh | bash'+ ;;+ codex)+ [ -n "$DRY" ] || [ -x "$NODE_DIR/bin/npm" ] || die "no Node runtime at $NODE_DIR: install the guest helper again" 4+ do_cmd sudo -u "$user" -H env -i "HOME=$home" "USER=$user" "PATH=$path" "$NODE_DIR/bin/npm" install -g @openai/codex --prefix "$home/.local"+ ;;+ opencode)+ do_cmd sudo -u "$user" -H env -i "HOME=$home" "USER=$user" "PATH=$path" /bin/sh -c \+ "curl -fsSL https://opencode.ai/install | bash || '$NODE_DIR/bin/npm' install -g opencode-ai --prefix \"\$HOME/.local\""+ ;;+ *) die "not an engine a guest can install: $engine" ;;+ esac+ printf 'Installed %s for %s\n' "$engine" "$user"+}++cmd_remove() {+ [ $# -eq 1 ] || die 'usage: remove <user>'+ user=$1+ require_guest "$user"+ home="$HOME_ROOT/$user"+ do_cmd pkill -KILL -u "$user" || true+ # Its shares go first: an entry naming a deleted user would name whoever gets its id next.+ apply_shares "$user" ''+ if [ "$PLATFORM" = Darwin ]; then+ do_cmd dscl . -delete "/Groups/$GROUP" GroupMembership "$user" || true+ do_cmd dscl . -delete "/Users/$user"+ do_cmd rm -rf "$home"+ if [ -z "$DRY" ] && ! dscl . -list /Users | grep -Eq '^hg_[0-9a-f]{12}$'; then+ do_cmd dscl . -delete "/Groups/$GROUP" || true+ fi+ else+ do_cmd userdel -r "$user" || true+ do_cmd rm -rf "$home"+ if [ -z "$DRY" ] && ! getent passwd | cut -d: -f1 | grep -Eq '^hg_[0-9a-f]{12}$'; then+ do_cmd groupdel "$GROUP" || true+ fi+ fi+}++[ $# -ge 1 ] || die 'usage: guest-helper ensure|run|install|share|shared|remove|version ...'+command=$1+shift+case $command in+ ensure) cmd_ensure "$@" ;;+ run) cmd_run "$@" ;;+ install) cmd_install "$@" ;;+ share) cmd_share "$@" ;;+ shared) cmd_shared "$@" ;;+ remove) cmd_remove "$@" ;;+ version) printf '%s\n' "$HELPER_VERSION" ;;+ *) die "unknown command: $command" ;;+esacdiff --git a/cli/assets/guest-helper/sudoers b/cli/assets/guest-helper/sudoersnew file mode 100644index 000000000..651fd2a9c--- /dev/null+++ b/cli/assets/guest-helper/sudoers@@ -0,0 +1,7 @@+# Harness guest helper (cli/src/lib/guestHelperInstall.ts), installed at /etc/sudoers.d/harness-guests.+# Lets the machine's owner run the guest helper as root without a password, so the owner's daemon can+# create a guest's account and run that guest's harnesses as it. The helper validates every argument.+# The variables kept are the ones a guest's harness may be given (the helper's GUEST_ENV_KEYS): their+# values travel in the environment, never on a command line every account can read in `ps`.+Defaults!/usr/local/libexec/harness/guest-helper env_keep += "TERM COLORTERM LANG LC_* ANTHROPIC_BASE_URL ANTHROPIC_AUTH_TOKEN ANTHROPIC_MODEL HARNESS_RELAY_TOKEN HARNESS_HOOK_TOKEN HARNESS_HOOK_URL HARNESS_AGENT_ID CODEX_HOME"+{{OWNER}} ALL=(root) NOPASSWD: /usr/local/libexec/harness/guest-helper *diff --git a/cli/build-bundle.mjs b/cli/build-bundle.mjsindex 71db35c23..b8230d7ac 100644--- a/cli/build-bundle.mjs+++ b/cli/build-bundle.mjs@@ -64,6 +64,9 @@ const options = {__DEVICES_BUNDLE__: JSON.stringify(devicesBundle),__HARNESS_MONITOR_BUNDLE__: JSON.stringify(harnessMonitorBundle),__MEMORIES_BUNDLE__: JSON.stringify(memoriesBundle),+ // The guest helper and its sudoers drop-in (src/lib/guestHelperAssets.ts): the installed CLI is cli.js alone.+ __GUEST_HELPER__: JSON.stringify(readFileSync('assets/guest-helper/guest-helper.sh', 'utf8')),+ __GUEST_SUDOERS__: JSON.stringify(readFileSync('assets/guest-helper/sudoers', 'utf8')),__BUILTIN_REVISIONS__: JSON.stringify(builtinRevisions),__DARWIN_PROCESS_IMAGES__: processImages ? JSON.stringify(processImages) : 'undefined',},diff --git a/cli/build.mjs b/cli/build.mjsindex 41582b528..e98623fe3 100644--- a/cli/build.mjs+++ b/cli/build.mjs@@ -49,6 +49,9 @@ try {__DEVICES_BUNDLE__: JSON.stringify(devicesBundle),__HARNESS_MONITOR_BUNDLE__: JSON.stringify(harnessMonitorBundle),__MEMORIES_BUNDLE__: JSON.stringify(memoriesBundle),+ // The guest helper and its sudoers drop-in (src/lib/guestHelperAssets.ts): the installed CLI is cli.js alone.+ __GUEST_HELPER__: JSON.stringify(readFileSync('assets/guest-helper/guest-helper.sh', 'utf8')),+ __GUEST_SUDOERS__: JSON.stringify(readFileSync('assets/guest-helper/sudoers', 'utf8')),},logLevel: 'info',})diff --git a/cli/e2e/harness/daemon.ts b/cli/e2e/harness/daemon.tsindex a96ba5412..d5a8173e5 100644--- a/cli/e2e/harness/daemon.ts+++ b/cli/e2e/harness/daemon.ts@@ -260,6 +260,10 @@ export class IsolatedDaemon {// Engine probes and usage readers must not consult the person's macOS// Keychain merely because the fixture itself runs on a Mac.await writeFile(join(dirs.bin, 'security'), '#!/bin/sh\nexit 44\n', { mode: 0o755 })+ // Nor does it run anything as root or as another account: a guest's harness goes through `sudo -n` and the guest+ // helper (lib/guestAccounts.ts), which may be installed on the Mac the tests run on. Refused, as for an owner who+ // never turned guest access on.+ await writeFile(join(dirs.bin, 'sudo'), '#!/bin/sh\necho "sudo: a password is required" >&2\nexit 1\n', { mode: 0o755 })const env = daemonEnvironment(tmux.env, {NODE_ENV: 'test',HOME: dirs.home,diff --git a/cli/e2e/sharedMachines.e2e.ts b/cli/e2e/sharedMachines.e2e.tsindex 64716ea8e..f37bf5771 100644--- a/cli/e2e/sharedMachines.e2e.ts+++ b/cli/e2e/sharedMachines.e2e.ts@@ -5,10 +5,11 @@* Dee shares her machine with everyone at acme.io; Kim, at acme.io on another account, adds it. Kim's* daemon then pins Dee's machine and Dee's daemon trusts Kim's (services/sharedMachines.ts, through the* gateway: gateway/sharedTrust.ts), so a window on Kim's computer reaches Dee's machine through the relay,- * end to end encrypted, with the owner's rights. Neither joins the other's trust group. Dee stopping+ * end to end encrypted, as a guest (docs/plans/2026-10-19-guest-machine-sharing-plan.md): its own harnesses+ * and nothing of Dee's, not even her harnesses' events. Neither joins the other's trust group. Dee stopping* sharing ends the session and takes the trust back on both sides.*/-import { readFileSync } from 'node:fs'+import { mkdirSync, readFileSync } from 'node:fs'import { join } from 'node:path'import WebSocket from 'ws'import { afterEach, describe, expect, it, onTestFailed } from 'vitest'@@ -51,7 +52,7 @@ describe('a machine shared across accounts', () => {backend = null})- it('is reached from a colleague’s computer once shared and added, with the owner’s rights, and no longer once sharing stops', async () => {+ it('is reached from a colleague’s computer once shared and added, as a guest, and no longer once sharing stops', async () => {backend = await FakeBackend.start()const specs = [{ machineId: 'd1'.repeat(16), computerId: 'e2e-computer-0000-0000-0000000000d1', name: 'dee-studio', token: 'e2e-token-dee', account: 'dee', email: '[email protected]', identity: newIdentity() },@@ -93,15 +94,36 @@ describe('a machine shared across accounts', () => {await until('Kim’s machine trusted on Dee’s', () => e2eFile(dee, 'paired.json').some((p) => (p as { identityPub: string; shared?: boolean }).identityPub === b64e(kimSpec.identity.pub) && (p as { shared?: boolean }).shared === true) || null, 30_000)- // A window on Kim's computer works on Dee's machine, with the owner's rights: the sharing itself reads.+ // A window on Kim's computer reaches Dee's machine as a guest. Dee's own harness is there, and Kim sees none+ // of it: not in the list, not its terminal, not its events.const viaKim = await LocalClient.connect(kim, { machineId: deeSpec.machineId })clients.push(viaKim)- expect((await viaKim.request<{ agents?: unknown[] }>('agents_list', {}, 30_000)).agents).toEqual(expect.any(Array))- expect(await viaKim.request('shared_machines', { action: 'get' }, 30_000)).toMatchObject({- sameDomain: true, members: [{ email: '[email protected]', via: 'domain', machines: 1 }] })+ const deeHarness = await onDee.request<{ agent?: { id: string } }>('agent_create', { engine: 'terminal' }, 30_000)+ const deeAgent = deeHarness.agent!.id+ await onDee.request('agent_update', { agentId: deeAgent, name: 'Dee’s private notes' }, 30_000)+ expect((await viaKim.request<{ agents?: unknown[] }>('agents_list', {}, 30_000)).agents).toEqual([])+ expect(await viaKim.request('terminal_open', { agentId: deeAgent }, 30_000)).toMatchObject({ error: 'NOT_YOUR_HARNESS' })+ for (const [type, payload] of [['shared_machines', { action: 'get' }], ['e2ee_pairings_list', {}], ['fs_list_dir', { path: '/' }],+ ['sessions_list', {}], ['agent_resume', { agentId: deeAgent }]] as const) {+ expect(await viaKim.request(type, payload, 30_000), type).toMatchObject({ error: 'GUEST_NOT_ALLOWED' })+ }+ // A harness of its own runs as its own OS account, which this machine's owner has not allowed yet.+ expect(await viaKim.request('agent_create', { engine: 'claude', cwd: '/' }, 60_000)).toMatchObject({ error: 'GUEST_HELPER_REQUIRED' })+ expect(viaKim.frames.some((frame) => JSON.stringify(frame).includes(deeAgent))).toBe(false)+ // The owner reads that guest access is off, and who uses the machine now.+ expect(await onDee.request('shared_machines', { action: 'get' }, 30_000)).toMatchObject({+ sameDomain: true, members: [{ email: '[email protected]', via: 'domain', machines: 1 }], guestAccess: expect.any(String) })+ // She shares a folder of hers with guests; Kim reads where he may start: his workspace, and that folder.+ const project = join(dee.dataDir, 'shared-project')+ mkdirSync(project)+ expect(await onDee.request('shared_machines', { action: 'set_folders', folders: [{ path: project, write: false }] }, 30_000))+ .toMatchObject({ folders: [{ path: project, write: false }] })+ expect(await viaKim.request('guest_folders', {}, 30_000)).toEqual({ requestId: expect.any(String),+ workspace: expect.stringMatching(/\/hg_[0-9a-f]{12}\/work$/), folders: [{ path: project, write: false }] })// Sealed end to end: the relay saw the outer type and never what was in it.- const relayed = [...backend.webSent.values()].flat().filter((frame) => frame.type === 'agents_list' || frame.type === 'shared_machines')- expect(relayed.length).toBeGreaterThanOrEqual(2)+ const relayed = [...backend.webSent.values()].flat().filter((frame) => frame.type === 'agents_list' || frame.type === 'shared_machines' || frame.type === 'guest_folders')+ expect(relayed.some((frame) => frame.type === 'guest_folders')).toBe(true)+ expect(relayed.length).toBeGreaterThanOrEqual(3)expect(relayed.every((frame) => !!(frame.payload as { __e2e?: unknown } | undefined)?.__e2e)).toBe(true)// Neither account's trust group took in the other's machine.diff --git a/cli/src/agentClient/daemon.ts b/cli/src/agentClient/daemon.tsindex 5cc7e275f..6b29540b2 100644--- a/cli/src/agentClient/daemon.ts+++ b/cli/src/agentClient/daemon.ts@@ -6,6 +6,7 @@* the paired relay (`machine_select` naming it).*/import { randomUUID } from 'node:crypto'+import { localCredentialHeaders } from '../lib/localCredential.js'import { existsSync } from 'node:fs'import { WebSocket } from 'ws'import { env } from '../config/env.js'@@ -56,10 +57,13 @@ export function whereFor(pane: string | undefined, owner: typeof paneOwner = panreturn { port: found?.port ?? env.PORT, dataDir: found?.dataDir ?? env.ADAPTER_DATA_DIR, machineId, harnessPane: !!found }}-/** The Unix socket when the daemon has one (file permissions are its lock), else loopback TCP. */+/** The Unix socket when the daemon has one (file permissions are its lock), else loopback TCP with the+ * daemon's local credential (lib/localCredential.ts). */export const connectSocket: Connect = (where) => {const path = localSocketPath(where.dataDir, where.port)- return path && existsSync(path) ? new WebSocket(`ws+unix://${path}:/api/local-ws`) : new WebSocket(`ws://127.0.0.1:${where.port}/api/local-ws`)+ return path && existsSync(path)+ ? new WebSocket(`ws+unix://${path}:/api/local-ws`)+ : new WebSocket(`ws://127.0.0.1:${where.port}/api/local-ws`, { headers: localCredentialHeaders(where.dataDir) })}export const DEFAULT_TIMEOUT_MS = 20_000diff --git a/cli/src/agentClient/settings.spec.ts b/cli/src/agentClient/settings.spec.tsindex 49359a235..190313cd7 100644--- a/cli/src/agentClient/settings.spec.ts+++ b/cli/src/agentClient/settings.spec.ts@@ -1,4 +1,8 @@+import { mkdtempSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'import { describe, expect, it } from 'vitest'+import { loadOrCreateHookCredential } from '../lib/hookAuth.js'import { settingsCommand, SETTINGS_SIGNED_OUT, SETTINGS_USAGE } from './settings.js'/** This computer's daemon as `harness settings` meets it: its answers to `/api/agent-settings`, and what was asked. */@@ -100,4 +104,18 @@ describe('harness settings', () => {expect(d.out).toEqual([SETTINGS_USAGE])expect(d.asked).toEqual([])})++ it('shows the daemon this OS user\'s local credential, which its loopback port wants', async () => {+ const dataDir = mkdtempSync(join(tmpdir(), 'settings-cred-'))+ try {+ const credential = loadOrCreateHookCredential(dataDir)+ const asked: Record<string, string>[] = []+ const fetch = (async (_url: string, init: RequestInit) => {+ asked.push(init.headers as Record<string, string>)+ return new Response(JSON.stringify({ ...OFF, signedIn: true }))+ }) as unknown as typeof globalThis.fetch+ expect(await settingsCommand([], { port: 4321, dataDir, fetch, env: {}, out: () => {}, err: () => {} })).toBe(0)+ expect(asked).toEqual([{ 'x-adapter-local': '1', 'X-Harness-Local': credential }])+ } finally { rmSync(dataDir, { recursive: true, force: true }) }+ })})diff --git a/cli/src/agentClient/settings.ts b/cli/src/agentClient/settings.tsindex 302b4a426..364c90a53 100644--- a/cli/src/agentClient/settings.ts+++ b/cli/src/agentClient/settings.ts@@ -9,6 +9,8 @@* change through to the account (core/experiments.ts `createAgentSettingsSync`): the copy is the daemon's alone.*/import { AGENT_SETTING_NAMES, type AgentSettings } from '../lib/agentSettings.js'+import { localCredentialHeaders } from '../lib/localCredential.js'+import { env } from '../config/env.js'import { daemonUnreachableText } from '../lib/daemonState.js'import { outsideCaller } from './model.js'@@ -48,6 +50,8 @@ export const SETTINGS_SIGNED_OUT = 'Signed out: these are experiments of your acexport interface SettingsDeps {/** This computer's daemon's port (lib/daemonState.ts `daemonPort`). */port: number+ /** Its data dir, where its local credential is (lib/localCredential.ts). */+ dataDir?: string/** Who runs it, by what its shell says (model.ts `outsideCaller`): an agent may not turn a setting on. */env?: NodeJS.ProcessEnvfetch?: typeof fetch@@ -77,7 +81,7 @@ export async function settingsCommand(argv: readonly string[], deps: SettingsDepconst response = await (deps.fetch ?? fetch)(`http://127.0.0.1:${deps.port}/api/agent-settings`, {method: change ? 'PATCH' : 'GET',// The local API's CSRF gate: a write must say it comes from this computer.- headers: { 'x-adapter-local': '1', ...(change ? { 'content-type': 'application/json' } : {}) },+ headers: { 'x-adapter-local': '1', ...localCredentialHeaders(deps.dataDir ?? env.ADAPTER_DATA_DIR), ...(change ? { 'content-type': 'application/json' } : {}) },...(change ? { body: JSON.stringify(change) } : {}),signal: AbortSignal.timeout(20_000),})diff --git a/cli/src/backendSocket.guest.spec.ts b/cli/src/backendSocket.guest.spec.tsnew file mode 100644index 000000000..3a5189306--- /dev/null+++ b/cli/src/backendSocket.guest.spec.ts@@ -0,0 +1,133 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import type { BackendSocket } from './backendSocket.js'+import type { RemoteClient } from './core/api.js'+import { dispatchDown, gatewayOf, relaySocket, upstreamOf } from './testing/relaySocket.js'++// A guest: a session trusted only because this machine is shared with its account. Its own space, nothing+// of the owner's (docs/plans/2026-10-19-guest-machine-sharing-plan.md, core/guestPolicy.ts).+describe('a guest session', () => {+ const sockets: BackendSocket[] = []+ afterEach(async () => { for (const s of sockets.splice(0)) await s.stop(); vi.restoreAllMocks() })++ const sealed = (type: string, payload: Record<string, unknown> = {}) => ({ type, payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } }, clear: { type, payload: { requestId: 'one', ...payload } } })++ /** A relayed `web` session from `remote`: the owner's own app, or `guest`'s. */+ function session(guest?: string, sharedWith = guest) {+ const socket = relaySocket('fixture')+ sockets.push(socket)+ const gw = gatewayOf(socket)+ vi.spyOn(gw.e2ee, 'hasSession').mockReturnValue(true)+ vi.spyOn(gw.e2ee, 'sessionRole').mockReturnValue('web')+ vi.spyOn(gw.e2ee, 'sessionIdentity').mockReturnValue('identity')+ vi.spyOn(gw.e2ee, 'pairedPeers').mockReturnValue([{ identityPub: 'identity', label: 'Mac · kim', pairedAt: 1, role: 'web',+ ...(guest !== undefined ? { shared: true as const, ...(sharedWith ? { sharedWith } : {}) } : {}) }])+ const client: RemoteClient = { role: 'web', label: null, identity: 'identity', direct: false, accountOwner: guest === undefined,+ ...(guest !== undefined ? { guest } : {}) }+ ;(socket as unknown as { remoteClients: Map<string, RemoteClient> }).remoteClients.set('remote', client)+ const replies = vi.spyOn(gw, 'reply').mockImplementation(() => {})+ const ask = async (type: string, payload: Record<string, unknown> = {}) => {+ const frame = sealed(type, payload)+ vi.spyOn(gw.e2ee, 'unwrapDown').mockReturnValue(frame.clear)+ await dispatchDown(socket, { type: frame.type, payload: frame.payload }, 'remote')+ }+ const answered = () => replies.mock.calls.map(([, type, , payload]) => ({ type, payload: payload as Record<string, unknown> }))+ return { socket, gw, ask, answered }+ }++ it('is refused what is not its own, and the service never hears it', async () => {+ const { socket, ask, answered } = session('[email protected]')+ const routed = vi.fn(() => true)+ socket.serviceRouter = routed+ await ask('shell', { op: 'open' })+ await ask('fs_list_dir', { path: '/Users/owner' })+ expect(routed).not.toHaveBeenCalled()+ expect(answered()).toEqual([+ { type: 'shell', payload: expect.objectContaining({ error: 'GUEST_NOT_ALLOWED' }) },+ { type: 'fs_list_dir', payload: expect.objectContaining({ error: 'GUEST_NOT_ALLOWED' }) },+ ])+ })++ it('may ask what is allowed, as no owner, saying whose guest it is', async () => {+ const { socket, ask } = session('[email protected]')+ const askers: unknown[] = []+ socket.serviceRouter = (_type, _payload, asker, reply) => { askers.push(asker); reply({ ok: true }); return true }+ await ask('usage_read')+ expect(askers).toEqual([expect.objectContaining({ owner: false, guest: '[email protected]' })])+ })++ it('lists only its own harnesses, and opens only their terminals', async () => {+ const { socket, ask, answered } = session('[email protected]')+ const lists: unknown[] = []+ socket.agentsProvider = async (_payload, _role, reply, guest) => { lists.push(guest); reply({ agents: [] }) }+ socket.agentGuest = (agentId) => (agentId === 'mine' ? '[email protected]' : null)+ const opened = vi.fn(async () => true)+ ;(socket as unknown as { terminalStreams: unknown }).terminalStreams = { handleFrame: opened, stop: vi.fn() }+ await ask('agents_list')+ expect(lists).toEqual(['[email protected]'])+ await ask('terminal_open', { agentId: 'owners' })+ expect(opened).not.toHaveBeenCalled()+ expect(answered().at(-1)).toEqual({ type: 'terminal_open', payload: expect.objectContaining({ error: 'NOT_YOUR_HARNESS' }) })+ await ask('terminal_open', { agentId: 'mine' })+ expect(opened).toHaveBeenCalledWith('remote', 'terminal_open', expect.objectContaining({ agentId: 'mine' }))+ })++ it('the owner\'s own app is still the owner', async () => {+ const { socket, ask } = session()+ const lists: unknown[] = []+ const askers: unknown[] = []+ socket.agentsProvider = async (_payload, _role, reply, guest) => { lists.push(guest); reply({ agents: [] }) }+ socket.serviceRouter = (type, _payload, asker, reply) => { if (type !== 'shell') return false; askers.push(asker); reply({ ok: true }); return true }+ await ask('agents_list')+ await ask('shell')+ expect(lists).toEqual([undefined])+ expect(askers).toEqual([expect.objectContaining({ owner: true })])+ })++ it('manages none of the machine\'s pairings, and joins no trust group: the gateway refuses it', async () => {+ const { ask, answered } = session('[email protected]')+ await ask('e2ee_pairings_list')+ await ask('e2ee_pairing_unpair', { identityPub: 'owner-phone' })+ await ask('group_sync')+ expect(answered().map((a) => a.payload)).toEqual([+ expect.objectContaining({ error: 'GUEST_NOT_ALLOWED' }), expect.objectContaining({ error: 'GUEST_NOT_ALLOWED' }), expect.objectContaining({ error: 'GUEST_NOT_ALLOWED' }),+ ])+ })++ it('a share recorded before its account was is still a guest, which owns nothing', async () => {+ const { socket, ask, answered } = session('', '')+ socket.agentGuest = () => ''+ await ask('terminal_open', { agentId: 'any' })+ await ask('e2ee_pairings_list')+ expect(answered().map((a) => a.payload)).toEqual([+ expect.objectContaining({ error: 'NOT_YOUR_HARNESS' }), expect.objectContaining({ error: 'GUEST_NOT_ALLOWED' }),+ ])+ })++ it('the gateway sends a guest\'s event to the group, and sealed to each of that guest\'s sessions', () => {+ const { gw, socket } = session('[email protected]')+ vi.spyOn(gw.e2ee, 'guestSessions').mockImplementation((email) => (email === '[email protected]' ? ['g1', 'g2', 'gone'] : []))+ vi.spyOn(gw.e2ee, 'wrapFor').mockImplementation((connId, frame) => (connId === 'gone' ? null : { ...frame, payload: { sealedFor: connId } }))+ const queue = upstreamOf(socket).queue+ const before = queue.length+ gw.broadcast({ type: 'turn_started', agentId: 'mine', payload: {} }, '[email protected]')+ gw.broadcast({ type: 'turn_started', agentId: 'owners', payload: {} })+ const sent = queue.slice(before).map((q) => q.msg as { targetConnId?: string; frame: { payload: unknown } })+ expect(sent.map((m) => m.targetConnId ?? 'group')).toEqual(['group', 'g1', 'g2', 'group'])+ expect(sent[1].frame.payload).toEqual({ sealedFor: 'g1' })+ })++ it('hears its own harnesses\' events sealed for it alone; the owner\'s go to the group only', () => {+ const { socket, gw } = session('[email protected]')+ socket.agentGuest = (agentId) => (agentId === 'mine' ? '[email protected]' : null)+ const broadcast = vi.spyOn(gw, 'broadcast')+ socket.send({ type: 'agent_synced', payload: { agent: { id: 'mine' } } })+ socket.send({ type: 'turn_started', agentId: 'mine', payload: {} })+ socket.send({ type: 'agent_deleted', payload: { agentId: 'mine' } })+ socket.send({ type: 'agent_synced', payload: { agent: { id: 'owners' } } })+ socket.send({ type: 'machines_changed', payload: {} })+ expect(broadcast.mock.calls.map(([frame, guest]) => [frame.type, guest])).toEqual([+ ['agent_synced', '[email protected]'], ['turn_started', '[email protected]'], ['agent_deleted', '[email protected]'],+ ['agent_synced', undefined], ['machines_changed', undefined],+ ])+ })+})diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 91363a0c5..ad4d31d1d 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -42,6 +42,7 @@ import type { TerminalStreamManager } from './lib/terminalStreamManager.js'import { encodeTerminalLocal, type TerminalBinaryClear } from './lib/terminalBinary.js'import { BACKEND_ONLY_DOWN_TYPES, GATEWAY_REQUEST_TYPES, isLocalClientId, logSafeType, PAIR_REQUESTS, PLATE_REQUEST, rpcResultType, type DownTransport } from './lib/relayFrames.js'import { sid, logFrame } from './lib/log.js'+import { eventAgentId, GUEST_REFUSALS, guestVerdict } from './core/guestPolicy.js'export { isLocalClientId, type DownTransport }@@ -260,7 +261,10 @@ export class BackendSocket {* asked for (cli.ts binds core/agents/list.ts). The second argument reads the asker's paired role.* Null answers UNSUPPORTED. */agentsProvider: ((payload: Record<string, unknown>, sessionRole: () => string | null,- reply: (result: Record<string, unknown>) => void) => Promise<void>) | null = null+ reply: (result: Record<string, unknown>) => void, guest?: string) => Promise<void>) | null = null+ /** The guest (email) an agent was started for, or null for the owner's own (registry `guest`): what a+ * guest session may act on (core/guestPolicy.ts). Null treats every agent as the owner's. */+ agentGuest: ((agentId: string) => string | null) | null = null/** Answers `session_get` with the whole reply: a conversation's history, a page at a time (cli.ts binds* core/transcripts/history.ts). Null answers UNSUPPORTED. */historyProvider: ((payload: Record<string, unknown>) => Promise<Record<string, unknown>>) | null = null@@ -516,7 +520,17 @@ export class BackendSocket {for (const [connId, sink] of this.localClients) {if (!sink.sendFrame(frame)) void this.unregisterLocalClient(connId)}- if (!this.thisComputerOnly) this.toGateway('web', (gateway) => gateway.broadcast(frame))+ if (!this.thisComputerOnly) {+ const guest = this.frameGuest(frame)+ this.toGateway('web', (gateway) => gateway.broadcast(frame, guest ?? undefined))+ }+ }++ /** The guest whose harness a frame is about (registry `guest`, through `agentGuest`), or null for the+ * owner's own and for a frame about no harness. Its sessions are sent it sealed for each (gateway.ts). */+ private frameGuest(frame: Frame): string | null {+ const id = this.agentGuest ? eventAgentId(frame) : null+ return id ? this.agentGuest!(id) : null}/** Signed out: the cloud link is never dialed in this process's life (a sign-in restarts it), so nothing@@ -807,6 +821,8 @@ export class BackendSocket {// sending and being dispatched used to leave `localClients.has()` false, and its already-queued// frames were then read as the BACKEND's. The transport half closes that, because it is stamped// at enqueue by the caller that had just verified membership. Either one being true is local.+ // A local client is this OS user's: the Unix socket is 0600, and a TCP one showed the daemon's local+ // credential at the door (lib/localCredential.ts, hookServer.ts and localWsServer.ts).const local = transport === 'local' || this.localClients.has(connId)if (local) {// ⚠️ The backend's own instructions, refused from anywhere else. See BACKEND_ONLY_DOWN_TYPES.@@ -851,9 +867,11 @@ export class BackendSocket {}this.emitReply(connId, t, rid, p)}+ // A guest: a session trusted only because this machine is shared with its account (gateway/gateway.ts).+ const guest = local ? undefined : this.remoteClient(connId)?.guest// Who may act as this machine's owner: a process here, or the owner's own paired app or browser, whose- // session the gateway says is a `web` one. A device or an observer may not.- const owner = local || role === 'web'+ // session the gateway says is a `web` one. A device, an observer or a guest may not.+ const owner = local || (role === 'web' && guest === undefined)const lifecycleTarget = (frame.payload as { agentId?: unknown } | undefined)?.agentIdif (typeof lifecycleTarget === 'string' && this.purgeAgentService?.busy(lifecycleTarget)&& ['agent_close', 'agent_delete', 'agent_resume', 'agent_restart', 'agent_retarget', 'agent_update'].includes(type)) {@@ -863,6 +881,17 @@ export class BackendSocket {const requestId = payload.requestIdconst answer = (result: Record<string, unknown>): void => reply(type, requestId, result)+ // A guest gets its own space and nothing of the owner's: default-deny (core/guestPolicy.ts), before+ // anything else answers it — the services and the terminal streams included.+ if (guest !== undefined) {+ const verdict = guestVerdict(type, payload, guest, (agentId) => this.agentGuest?.(agentId) ?? null)+ if (!verdict.allow) {+ console.warn(`[guest] refused ${logSafeType(type)} from conn:${sid(connId)} — ${verdict.error}`)+ if (requestId !== undefined) reply(type, requestId, { error: verdict.error, message: GUEST_REFUSALS[verdict.error] })+ return+ }+ }+// A paired owner can run the machine's orchestrator; observers and device sessions cannot.// Both requests and replies are encrypted, including project artifacts.if (ROUTE_COMMAND_TYPES.has(type)) {@@ -915,6 +944,7 @@ export class BackendSocket {// SERVICE_UNAVAILABLE while it is off. Never waited on in line: the next frame is not held for it.// Who asked is established here, after the gates above, and the service trusts only that.const asker: Asker = { local, owner, ...(!local ? { accountOwner: this.remoteClient(connId)?.accountOwner === true } : {}),+ ...(guest !== undefined ? { guest } : {}),connection: connId, ...(typeof requestId === 'string' ? { requestId } : {}) }// A window that draws row state asks for the models list with `rowState`, and the list's changes are// pushed to it in that form (`pushGridModels`). Noted here, by connection: the models service answers@@ -944,7 +974,7 @@ export class BackendSocket {// The agents on this machine, live and, when asked, stopped (core/agents/list.ts, bound by cli.ts).case 'agents_list':- if (this.agentsProvider) await this.agentsProvider(payload, () => (local ? null : role), answer)+ if (this.agentsProvider) await this.agentsProvider(payload, () => (local ? null : role), answer, guest)else reply(type, requestId, { error: 'UNSUPPORTED' })returndiff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 0bb69d341..c75469342 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -65,6 +65,7 @@ import { remoteCommand } from './remoteCommand.js'import { tuiCommand } from './tui/index.js'import { machineChoices, newCommand, type MachineRow, type NewMachine } from './lib/newCommand.js'import { gridSetupCommand } from './lib/gridSetupCommand.js'+import { localCredentialHeaders } from './lib/localCredential.js'import { WebSocket as NewCommandSocket } from 'ws'import { describeMasterStatus, readStatusFile } from './harnessd/master.js'import { namedNode } from './harnessd/processName.js'@@ -1291,7 +1292,7 @@ async function runningDaemonStatus(): Promise<{} | null> {try {const body = await localDaemonStatus(env.ADAPTER_DATA_DIR, env.PORT)- ?? await legacyDaemonStatus(daemonPort(), readPid(), computerId())+ ?? await legacyDaemonStatus(daemonPort(), readPid(), computerId(), env.ADAPTER_DATA_DIR)if (!body) return nullconst status = body as {version?: unknown; sessions?: unknown; machineId?: unknown; connected?: unknown@@ -1606,12 +1607,18 @@ async function resetCommand(): Promise<void> {process.exit(0)}+/** What every call to this daemon's loopback API carries: the CSRF mark its writes want, and the local+ * credential every TCP call wants (lib/localCredential.ts). */+function daemonHeaders(extra: Record<string, string> = {}): Record<string, string> {+ return { 'x-adapter-local': '1', ...localCredentialHeaders(env.ADAPTER_DATA_DIR), ...extra }+}+/** Call the running daemon's localhost control API. Exits with a friendly message if it's not up. */async function daemonCall(method: 'GET' | 'POST', path: string, body?: unknown): Promise<{ res: Response; json: Record<string, unknown> }> {const url = `http://127.0.0.1:${daemonPort()}${path}`let res: Responsetry {- const headers: Record<string, string> = { 'x-adapter-local': '1' } // passes the local API's CSRF gate+ const headers: Record<string, string> = daemonHeaders() // the local API's CSRF gate and credentialif (body) headers['content-type'] = 'application/json'res = await fetch(url, { method, headers, body: body ? JSON.stringify(body) : undefined })} catch (error) {@@ -1792,7 +1799,7 @@ async function remotePasswordSetCommand(json: boolean, stdin: boolean): Promise<try {const res = await fetch(`http://127.0.0.1:${daemonPort()}/api/remote-password/set`, {method: 'POST',- headers: { 'x-adapter-local': '1', 'content-type': 'application/json' },+ headers: daemonHeaders({ 'content-type': 'application/json' }),body: JSON.stringify({ password }),})if (res.ok) {@@ -1821,7 +1828,7 @@ async function remotePasswordClearCommand(json: boolean): Promise<void> {try {const res = await fetch(`http://127.0.0.1:${daemonPort()}/api/remote-password/clear`, {method: 'POST',- headers: { 'x-adapter-local': '1' },+ headers: daemonHeaders(),})if (res.ok) cleared = true} catch { /* fall back to the disk-backed store below */ }@@ -1840,7 +1847,7 @@ async function remotePasswordClearCommand(json: boolean): Promise<void> {async function remotePasswordStatusCommand(json: boolean): Promise<void> {let status: { hasPassword: boolean; fingerprint: string | null; setAt: number | null } | null = nulltry {- const res = await fetch(`http://127.0.0.1:${daemonPort()}/api/remote-password/status`, { headers: { 'x-adapter-local': '1' } })+ const res = await fetch(`http://127.0.0.1:${daemonPort()}/api/remote-password/status`, { headers: daemonHeaders() })if (res.ok) {const body = (await res.json().catch(() => null)) as { hasPassword?: unknown; fingerprint?: unknown; setAt?: unknown } | nullif (typeof body?.hasPassword === 'boolean') {@@ -2004,7 +2011,7 @@ async function trustLinkedMachine(peer: LinkedPeer): Promise<void> {try {const res = await fetch(`http://127.0.0.1:${daemonPort()}/api/link/trust-peer`, {method: 'POST',- headers: { 'x-adapter-local': '1', 'content-type': 'application/json' },+ headers: daemonHeaders({ 'content-type': 'application/json' }),body: JSON.stringify(peer),})if (res.ok) return@@ -2053,7 +2060,7 @@ async function daemonGroupRemove(selector: string): Promise<boolean> {try {const res = await fetch(`http://127.0.0.1:${daemonPort()}/api/group/remove`, {method: 'POST',- headers: { 'x-adapter-local': '1', 'content-type': 'application/json' },+ headers: daemonHeaders({ 'content-type': 'application/json' }),body: JSON.stringify({ selector }),})return res.ok@@ -2081,7 +2088,7 @@ async function groupCommand(sub: string | undefined, arg: string | undefined, js}if (sub === 'sync') {try {- const res = await fetch(`http://127.0.0.1:${daemonPort()}/api/group/sync`, { method: 'POST', headers: { 'x-adapter-local': '1' } })+ const res = await fetch(`http://127.0.0.1:${daemonPort()}/api/group/sync`, { method: 'POST', headers: daemonHeaders() })if (!res.ok) throw new Error(String(res.status))} catch (error) {console.error(`\n ✗ ${daemonUnreachableText((error as { cause?: unknown }).cause ?? error)}\n`)@@ -2632,7 +2639,7 @@ switch (cmd) {runDevicesCommand(rest, {port: daemonPort(),machineId: async () => (await runningDaemonStatus())?.machineId ?? null,- connect: (url) => new NewCommandSocket(url),+ connect: (url, headers) => new NewCommandSocket(url, { headers }),}).then(code => { process.exitCode = code }).catch(onError)breakcase 'pair':@@ -2654,7 +2661,7 @@ switch (cmd) {port: daemonPort(),localMachineId: wantedDaemonIdentity(),daemonRunning: isDaemonRunning, unreachable: () => daemonUnreachableText(),- connect: (url) => new NewCommandSocket(url),+ connect: (url) => new NewCommandSocket(url, { headers: localCredentialHeaders(env.ADAPTER_DATA_DIR) }),output: (line) => console.log(line),error: (line) => console.error(line),}).then((code) => { process.exitCode = code }).catch(onError)@@ -2689,7 +2696,7 @@ switch (cmd) {localMachineId: wantedDaemonIdentity(),daemonRunning: isDaemonRunning, unreachable: () => daemonUnreachableText(),listMachines: usableMachines,- connect: (url) => new NewCommandSocket(url),+ connect: (url) => new NewCommandSocket(url, { headers: localCredentialHeaders(env.ADAPTER_DATA_DIR) }),output: (line) => console.log(line),error: (line) => console.error(line),origin: () => agentOrigin(),diff --git a/cli/src/core/agents/fork.spec.ts b/cli/src/core/agents/fork.spec.tsindex 5acd3756b..eb87b9e28 100644--- a/cli/src/core/agents/fork.spec.ts+++ b/cli/src/core/agents/fork.spec.ts@@ -12,6 +12,7 @@ import type { RegisteredSession } from '../../lib/registry.js'import { createAgentForker, type ForkAgentDeps } from './fork.js'import type { NativeLaunch } from '../../engines/nativeLaunch.js'import { createLaunchHelpers } from './launch.js'+import { GUEST_HARNESS_REFUSAL } from '../guestPolicy.js'vi.mock('../../dsh/installed.js', () => ({ installedDsh: vi.fn(() => undefined) }))@@ -193,6 +194,8 @@ describe('forking an agent', () => {it('refuses without tmux, an agent, a folder, or with a grid or a turn in progress', async () => {expect(await setup(source(), { tmuxBackend: null }).fork({ agentId: 'a1', name: null, prompt: null })).toEqual({ ok: false, error: 'TMUX_UNAVAILABLE' })expect(await setup(null).fork({ agentId: 'a1', name: null, prompt: null })).toEqual({ ok: false, error: 'AGENT_NOT_FOUND' })+ // A guest's harness: a fork would start as the owner, with the guest's conversation.+ expect(await setup(source({ guest: '[email protected]' })).fork({ agentId: 'a1', name: null, prompt: null })).toEqual(GUEST_HARNESS_REFUSAL)expect(await setup(source({ cwd: undefined })).fork({ agentId: 'a1', name: null, prompt: null })).toMatchObject({ error: 'CWD_NOT_FOUND', detail: expect.stringContaining('no working folder') })expect(await setup(source({ cwd: join(root, 'file') })).fork({ agentId: 'a1', name: null, prompt: null })).toEqual({ ok: false, error: 'CWD_NOT_FOUND' })expect(await setup(source({ cwd: join(root, 'gone') })).fork({ agentId: 'a1', name: null, prompt: null })).toEqual({ ok: false, error: 'CWD_NOT_FOUND' })diff --git a/cli/src/core/agents/fork.ts b/cli/src/core/agents/fork.tsindex 7c7f1f47a..8aa113b6e 100644--- a/cli/src/core/agents/fork.ts+++ b/cli/src/core/agents/fork.ts@@ -32,6 +32,7 @@ import type { LaunchAuthority, LaunchPreparation } from '../../lib/launchPreparaimport type { LaunchOverridesDeps } from '../../lib/launchOverrides.js'import type { AgentEngine } from '../../engines/types.js'import { nativeHookLocations } from '../../engines/kit/nativeLocations.js'+import { GUEST_HARNESS_REFUSAL } from '../guestPolicy.js'type ForkAgent = NonNullable<BackendSocket['onForkAgent']>@@ -67,6 +68,7 @@ export function createAgentForker({if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }const observed = registry.byAgent(agentId)if (!observed) return { ok: false, error: 'AGENT_NOT_FOUND' }+ if (observed.guest) return GUEST_HARNESS_REFUSALconst source = structuredClone(observed)const sourceName = projectDisplayName(source)if (!source.cwd) return { ok: false, error: 'CWD_NOT_FOUND', detail: `${sourceName} has no working folder on record.` }diff --git a/cli/src/core/agents/guestCreate.spec.ts b/cli/src/core/agents/guestCreate.spec.tsnew file mode 100644index 000000000..9494a8f1e--- /dev/null+++ b/cli/src/core/agents/guestCreate.spec.ts@@ -0,0 +1,104 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import type { GuestLaunch } from '../api.js'+import type { RegisteredSession } from '../../lib/registry.js'+import { createGuestCreate, type GuestCreateDeps } from './guestCreate.js'++// A guest's New Harness: the launch shared machines builds, opened as a pane and recorded as the guest's+// (docs/plans/2026-10-19-guest-machine-sharing-plan.md). The pane is a fake tmux's; nothing runs.+const runtime = { kind: 'tmux' as const, sessionName: 'harness-claude-1', paneId: '%7' }+const launched: GuestLaunch = { ok: true, workspace: '/Users/Shared/HarnessGuests/hg_0123456789ab/work', argv: ['/bin/sh', '-c', 'boot'], env: { TERM: 'xterm-256color' } }++function setup(over: Partial<GuestCreateDeps> & { answer?: GuestLaunch; spawn?: 'ok' | 'fail'; register?: boolean } = {}) {+ const session = { agentId: 'agent-1', sessionId: '', engine: 'claude', guest: '[email protected]' } as RegisteredSession+ const tmux = {+ create: vi.fn(async () => over.spawn === 'fail' ? { state: 'failed' as const, reason: 'no server' } : { state: 'succeeded' as const, runtime }),+ kill: vi.fn(async () => {}),+ }+ const deps: GuestCreateDeps = {+ launch: vi.fn(async () => over.answer ?? launched),+ tmuxBackend: () => tmux as never,+ registry: { openPendingAgent: vi.fn(() => over.register === false ? null : session) },+ announceSession: vi.fn(),+ watchNewPane: vi.fn(async () => {}) as never,+ ...over,+ }+ return { create: createGuestCreate(deps), deps, tmux, session }+}++describe('a guest\'s New Harness', () => {+ afterEach(() => vi.restoreAllMocks())+ const said = () => vi.spyOn(console, 'log').mockImplementation(() => {})+ const warned = () => vi.spyOn(console, 'warn').mockImplementation(() => {})++ it('opens the launch shared machines built, in the guest\'s workspace, and records it as the guest\'s', async () => {+ const log = said()+ const { create, deps, tmux, session } = setup()+ expect(await create({ engine: 'claude', name: ' Notes ', cwd: '/Users/owner/secret' }, '[email protected]')).toEqual({ ok: true, session })+ // The folder asked for goes to shared machines, which starts it there only when the owner shares it: here, not.+ // Auto-approve, a harness's default: the engine's own auto mode, never Skip all checks.+ expect(deps.launch).toHaveBeenCalledWith({ email: '[email protected]', engine: 'claude', bypassPermission: true,+ permissionFlags: ['--permission-mode', 'auto'], cwd: '/Users/owner/secret' })+ expect(tmux.create).toHaveBeenCalledWith(expect.objectContaining({ cwd: launched.ok && launched.workspace, command: ['/bin/sh', '-c', 'boot'], env: { TERM: 'xterm-256color' } }))+ expect(deps.registry.openPendingAgent).toHaveBeenCalledWith(expect.objectContaining({ engine: 'claude', cwd: launched.ok && launched.workspace,+ guest: '[email protected]', defaultName: 'Notes', bypassPermission: true, permissionMode: 'auto' }))+ expect(deps.announceSession).toHaveBeenCalledWith(session)+ // Watched as any pane, with no install: the pane installs a missing engine for the guest itself.+ expect(deps.watchNewPane).toHaveBeenCalledWith('claude', session, expect.objectContaining({ runtime }), ['/bin/sh', '-c', 'boot'], undefined)+ expect(log).toHaveBeenCalledWith('[agent] create guest pane open · claude · agent agent-1')+ })++ it('asks before each command when the guest says so, by mode or by the older flag', async () => {+ said()+ const { create, deps } = setup()+ await create({ engine: 'codex', permissionMode: 'ask' }, '[email protected]')+ await create({ engine: 'codex', permissionMode: 'full' }, '[email protected]')+ await create({ engine: 'codex', bypassPermission: false, name: ' ' }, '[email protected]')+ expect(vi.mocked(deps.launch).mock.calls.map(([input]) => [input.bypassPermission, input.permissionFlags])).toEqual([+ [false, []], [true, ['--dangerously-bypass-approvals-and-sandbox']], [false, []]])+ // A mode the engine does not have is refused, never approximated.+ expect(await create({ engine: 'codex', permissionMode: 'plan' }, '[email protected]'))+ .toEqual({ ok: false, error: 'INVALID_PERMISSION_MODE', detail: 'codex has no permission mode "plan"' })+ expect(deps.registry.openPendingAgent).toHaveBeenLastCalledWith(expect.objectContaining({ defaultName: null }))+ })++ it('refuses what would run the owner\'s way, before anything starts, saying why', async () => {+ const { create, deps } = setup()+ for (const [key, value] of [['dsh', 'acme/blender'], ['resumeSessionId', 'abc-123'], ['agent', 'reviewer']] as const) {+ expect(await create({ engine: 'claude', [key]: value }, '[email protected]'), key).toEqual({ ok: false, error: 'GUEST_UNSUPPORTED', detail: expect.any(String) })+ }+ expect(deps.launch).not.toHaveBeenCalled()+ // Empty is absent.+ said()+ expect((await create({ engine: 'claude', dsh: null, agent: '' }, '[email protected]')).ok).toBe(true)+ })++ it('starts on the guest\'s first message, bounded as the owner\'s are', async () => {+ said()+ const { create, deps } = setup()+ await create({ engine: 'claude', prompt: ' Fix the tests ' }, '[email protected]')+ await create({ engine: 'claude', prompt: ' ' }, '[email protected]')+ await create({ engine: 'claude', prompt: null }, '[email protected]')+ expect(vi.mocked(deps.launch).mock.calls.map(([input]) => input.prompt)).toEqual(['Fix the tests', undefined, undefined])+ // A folder to start in goes to shared machines, which starts there only when the owner shares it.+ await create({ engine: 'claude', cwd: '/Users/dee/docs' }, '[email protected]')+ await create({ engine: 'claude', cwd: 'docs' }, '[email protected]')+ expect(vi.mocked(deps.launch).mock.calls.slice(3).map(([input]) => input.cwd)).toEqual(['/Users/dee/docs', undefined])+ expect(await create({ engine: 'claude', prompt: 7 }, '[email protected]')).toEqual({ ok: false, error: 'INVALID_PROMPT', detail: 'prompt must be a string' })+ expect(await create({ engine: 'claude', prompt: 'x'.repeat(2001) }, '[email protected]')).toEqual({ ok: false, error: 'PROMPT_TOO_LONG', detail: expect.stringMatching(/2000/) })+ expect(deps.launch).toHaveBeenCalledTimes(5)+ })++ it('says what stopped it: no tmux, a launch refused, a pane that would not open or register', async () => {+ expect(await setup({ tmuxBackend: () => null }).create({ engine: 'claude' }, '[email protected]')).toEqual({ ok: false, error: 'TMUX_UNAVAILABLE' })+ expect(await setup({ answer: { ok: false, error: 'GUEST_HELPER_REQUIRED', detail: 'Turn it on.' } }).create({ engine: 'claude' }, '[email protected]'))+ .toEqual({ ok: false, error: 'GUEST_HELPER_REQUIRED', detail: 'Turn it on.' })+ expect(await setup({ answer: { ok: false, error: 'GUEST_UNAVAILABLE' } }).create({ engine: 'claude' }, '[email protected]')).toEqual({ ok: false, error: 'GUEST_UNAVAILABLE' })+ // No engine named: no mode of its to start in.+ expect(await setup().create({}, '[email protected]')).toMatchObject({ ok: false, error: 'INVALID_PERMISSION_MODE' })+ warned()+ expect(await setup({ spawn: 'fail' }).create({ engine: 'claude' }, '[email protected]')).toEqual({ ok: false, error: 'SPAWN_FAILED', detail: 'no server' })+ const unregistered = setup({ register: false })+ expect(await unregistered.create({ engine: 'claude' }, '[email protected]')).toEqual({ ok: false, error: 'REGISTRATION_FAILED', detail: expect.any(String) })+ expect(unregistered.deps.announceSession).not.toHaveBeenCalled()+ })+})diff --git a/cli/src/core/agents/guestCreate.ts b/cli/src/core/agents/guestCreate.tsnew file mode 100644index 000000000..1f425c4ce--- /dev/null+++ b/cli/src/core/agents/guestCreate.ts@@ -0,0 +1,98 @@+/**+ * A guest's New Harness (docs/plans/2026-10-19-guest-machine-sharing-plan.md): the engine run as the+ * guest's own OS user, in the guest's workspace, on the owner's subscription. Shared machines builds the+ * launch (core/api.ts `SharedMachinesCorePort.guestLaunch`: the account, a relay token, the pane's command);+ * the core opens the pane as any other and records whose it is (registry `guest`), which is what lets the+ * guest, and only the guest, list it and reach it (core/guestPolicy.ts).+ *+ * The guest gets its workspace, the folders the owner shares and its engine, and nothing else: a folder in the+ * request is where it starts only when the owner shares it, and what would run the owner's way — a harness from the Store, a+ * conversation to resume, an engine's named agent — is refused before anything starts, rather than+ * half-applied. A first message goes to the engine as its first prompt. A grid or a saved API never reaches here (the policy refuses it).+ */+import type { GuestLaunch, GuestLaunchInput } from '../api.js'+import type { AgentEngine } from '../../engines/types.js'+import { createAndRegisterPane, type CreateAgentPaneDeps } from '../../lib/createAgentPane.js'+import { MAX_FIRST_PROMPT_CHARS, permissionModeApproves, permissionModeFlags } from '../../lib/engineLaunch.js'+import { DEFAULT_HARNESS_PERMISSION } from '../../lib/harnessDefaults.js'+import { buildHarnessSessionLabel } from '../../lib/harnessSessionLabel.js'+import type { RegisteredSession } from '../../lib/registry.js'+import type { createPaneWatcher } from './newPane.js'++export type GuestCreateResult =+ | { ok: true; session: RegisteredSession }+ | { ok: false; error: string; detail?: string }++export interface GuestCreateDeps {+ launch: (input: GuestLaunchInput) => Promise<GuestLaunch>+ /** The tmux backend; null where the configuration lists no tmux. */+ tmuxBackend: () => CreateAgentPaneDeps['tmuxBackend'] | null+ registry: CreateAgentPaneDeps['registry']+ announceSession: (session: RegisteredSession) => void+ watchNewPane: ReturnType<typeof createPaneWatcher>+}++/** What a guest's New Harness may not ask for, each with why. */+const NOT_FOR_GUESTS: ReadonlyArray<readonly [string, string]> = [+ ['dsh', 'A guest starts Claude Code or Codex; harnesses from the Store are not available to guests.'],+ ['resumeSessionId', 'A guest starts a new conversation.'],+ ['agent', 'A guest starts the engine itself, not a named agent.'],+]++export function createGuestCreate(deps: GuestCreateDeps) {+ return async (payload: Record<string, unknown>, guest: string): Promise<GuestCreateResult> => {+ for (const [key, detail] of NOT_FOR_GUESTS) {+ const value = payload[key]+ if (value !== undefined && value !== null && value !== '') return { ok: false, error: 'GUEST_UNSUPPORTED', detail }+ }+ const tmuxBackend = deps.tmuxBackend()+ if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }+ const engine = typeof payload.engine === 'string' ? payload.engine : ''+ // The mode the guest chose, with the engine's own flags for it, as an owner's launch has (Auto-approve is the+ // engine's auto mode, never Skip all checks). A client that predates the choice sends only `bypassPermission`.+ const permissionMode = typeof payload.permissionMode === 'string' ? payload.permissionMode+ : payload.bypassPermission === false ? 'ask' : DEFAULT_HARNESS_PERMISSION+ const permissionFlags = permissionModeFlags(engine as AgentEngine, permissionMode)+ if (!permissionFlags) return { ok: false, error: 'INVALID_PERMISSION_MODE', detail: `${engine} has no permission mode ${JSON.stringify(permissionMode)}` }+ const bypassPermission = permissionModeApproves(permissionMode)+ // A first message, bounded as the owner's are (core/agents/launches.ts).+ if (payload.prompt !== undefined && payload.prompt !== null && typeof payload.prompt !== 'string') {+ return { ok: false, error: 'INVALID_PROMPT', detail: 'prompt must be a string' }+ }+ const prompt = typeof payload.prompt === 'string' ? payload.prompt.trim() : ''+ if (prompt.length > MAX_FIRST_PROMPT_CHARS) {+ return { ok: false, error: 'PROMPT_TOO_LONG', detail: `prompt is longer than ${MAX_FIRST_PROMPT_CHARS} characters` }+ }+ // A folder the owner shares, to start in (shared machines checks it is shared; the helper, that it may be).+ const cwd = typeof payload.cwd === 'string' && payload.cwd.startsWith('/') ? payload.cwd : null+ const launch = await deps.launch({ email: guest, engine, bypassPermission, permissionFlags: [...permissionFlags],+ ...(prompt ? { prompt } : {}), ...(cwd ? { cwd } : {}) })+ if (!launch.ok) return { ok: false, error: launch.error, ...(launch.detail ? { detail: launch.detail } : {}) }+ const name = typeof payload.name === 'string' && payload.name.trim() ? payload.name.trim().slice(0, 120) : null+ const label = buildHarnessSessionLabel(engine as AgentEngine)+ const result = await createAndRegisterPane({+ tmuxBackend,+ registry: deps.registry,+ engine: engine as AgentEngine,+ cwd: launch.workspace,+ // The owner's tmux starts the pane: in a folder the owner may enter (the guest's home gives the owner a+ // read ACL). The helper changes to the workspace as the guest.+ spawnCwd: launch.workspace,+ sessionLabel: label,+ argv: launch.argv,+ env: launch.env,+ bypassPermission,+ permissionMode,+ defaultName: name,+ guest,+ })+ if (!result.ok) return { ok: false, error: result.error, detail: result.detail }+ deps.announceSession(result.pending)+ // No install here: the pane installs a missing engine for the guest itself (lib/guestPaneCommand.ts).+ void deps.watchNewPane(engine as AgentEngine, result.pending, result.spawned, launch.argv, undefined)+ console.log(`[agent] create guest pane open · ${engine} · agent ${result.pending.agentId}`)+ return { ok: true, session: result.pending }+ }+}++export type GuestCreate = ReturnType<typeof createGuestCreate>diff --git a/cli/src/core/agents/launches.spec.ts b/cli/src/core/agents/launches.spec.tsindex ae36b4477..bab498eae 100644--- a/cli/src/core/agents/launches.spec.ts+++ b/cli/src/core/agents/launches.spec.ts@@ -984,3 +984,69 @@ describe('agent_fork', () => {await vi.waitFor(() => expect(frameless.replies).toStrictEqual([{ error: 'INTERNAL' }]))})})++describe('agent_create, from a guest', () => {+ // A guest's New Harness never reaches the owner's launch: it is built as the guest's own OS user+ // (core/agents/guestCreate.ts, docs/plans/2026-10-19-guest-machine-sharing-plan.md).+ const guestAsk = async (run: ReturnType<typeof setup>, payload: Record<string, unknown>, guest = '[email protected]') => {+ await run.requests.create(payload, { local: false, guest }, (result) => { run.replies.push(result) })+ return run.replies.at(-1)+ }++ it('is the guest\'s own launch, never the owner\'s, answered as the owner\'s are', async () => {+ const guestCreate = vi.fn(async () => ({ ok: true as const, session: session('guest-agent', { guest: '[email protected]' }) }))+ const run = setup({ guestCreate: () => guestCreate })+ expect(await guestAsk(run, { engine: 'claude', cwd: '/Users/owner' })).toEqual({ agent: { id: 'guest-agent' } })+ expect(guestCreate).toHaveBeenCalledWith({ engine: 'claude', cwd: '/Users/owner' }, '[email protected]')+ expect(run.create).not.toHaveBeenCalled()+ guestCreate.mockResolvedValueOnce({ ok: false, error: 'GUEST_HELPER_REQUIRED', detail: 'Turn it on.' } as never)+ expect(await guestAsk(run, { engine: 'claude' })).toEqual({ error: 'GUEST_HELPER_REQUIRED', detail: 'Turn it on.' })+ guestCreate.mockResolvedValueOnce({ ok: false, error: 'TMUX_UNAVAILABLE' } as never)+ expect(await guestAsk(run, { engine: 'claude' })).toEqual({ error: 'TMUX_UNAVAILABLE' })+ })++ it('keeps a receipt under its creationId, so a retry finds the same harness and a status check what became of it', async () => {+ const guestCreate = vi.fn(async () => ({ ok: true as const, session: session('guest-agent', { guest: '[email protected]' }) }))+ const run = setup({ guestCreate: () => guestCreate, byAgent: (id) => id === 'guest-agent' ? session('guest-agent') : undefined })+ await guestAsk(run, { creationId: CREATION, engine: 'claude' })+ await vi.waitFor(() => expect(run.replies.at(-1)).toEqual({ creationId: CREATION, state: 'created', agent: { id: 'guest-agent' } }))+ await guestAsk(run, { creationId: CREATION, engine: 'claude' })+ await vi.waitFor(() => expect(run.replies).toHaveLength(2))+ expect(guestCreate).toHaveBeenCalledTimes(1)+ // The same id for another launch is a conflict, not a second harness.+ await guestAsk(run, { creationId: CREATION, engine: 'codex' })+ await vi.waitFor(() => expect(run.replies.at(-1)).toEqual({ error: 'CREATION_CONFLICT' }))+ })++ it('records a refusal as the outcome, with its words', async () => {+ const guestCreate = vi.fn(async () => ({ ok: false as const, error: 'GUEST_UNSUPPORTED', detail: 'A guest starts a new conversation.' }))+ const run = setup({ guestCreate: () => guestCreate })+ await guestAsk(run, { creationId: CREATION, engine: 'claude' })+ await vi.waitFor(() => expect(run.replies.at(-1)).toEqual({ creationId: CREATION, state: 'failed', failure: { code: 'GUEST_UNSUPPORTED', detail: 'A guest starts a new conversation.' } }))+ guestCreate.mockResolvedValueOnce({ ok: false, error: 'TMUX_UNAVAILABLE' } as never)+ await guestAsk(run, { creationId: 'creation-fedcba9876543210', engine: 'claude' })+ await vi.waitFor(() => expect(run.replies.at(-1)).toEqual({ creationId: 'creation-fedcba9876543210', state: 'failed', failure: { code: 'TMUX_UNAVAILABLE' } }))+ })++ it('starts nothing on a machine that cannot start a guest\'s harness, or for an id that is not one', async () => {+ expect(await guestAsk(setup(), { engine: 'claude' })).toEqual({ error: 'GUEST_NOT_ALLOWED' })+ expect(await guestAsk(setup({ guestCreate: () => null }), { engine: 'claude' })).toEqual({ error: 'GUEST_NOT_ALLOWED' })+ const guestCreate = vi.fn()+ expect(await guestAsk(setup({ guestCreate: () => guestCreate }), { creationId: 'short', engine: 'claude' })).toEqual({ error: 'INVALID_CREATION_ID' })+ expect(guestCreate).not.toHaveBeenCalled()+ })++ it('answers INTERNAL when its receipt cannot be kept or its answer cannot be built', async () => {+ const guestCreate = vi.fn(async () => ({ ok: true as const, session: session('guest-agent') }))+ const broken = setup({ guestCreate: () => guestCreate })+ vi.spyOn(broken.deps.receipts, 'run').mockImplementation(() => { throw new Error('disk full') })+ expect(await guestAsk(broken, { creationId: CREATION, engine: 'claude' })).toEqual({ error: 'INTERNAL' })+ const conflict = setup({ guestCreate: () => guestCreate })+ vi.spyOn(conflict.deps.receipts, 'run').mockImplementation(() => { throw new AgentCreationReceiptError('CREATION_CONFLICT') })+ expect(await guestAsk(conflict, { creationId: CREATION, engine: 'claude' })).toEqual({ error: 'CREATION_CONFLICT' })+ const unbuilt = setup({ guestCreate: () => guestCreate, toProject: async () => { throw new Error('gone') }, byAgent: () => session('guest-agent') })+ vi.spyOn(unbuilt.deps.receipts, 'run').mockResolvedValue({ state: 'created', agentId: 'guest-agent' })+ await guestAsk(unbuilt, { creationId: CREATION, engine: 'claude' })+ await vi.waitFor(() => expect(unbuilt.replies.at(-1)).toEqual({ error: 'INTERNAL' }))+ })+})diff --git a/cli/src/core/agents/launches.ts b/cli/src/core/agents/launches.tsindex d932ad88f..c14630330 100644--- a/cli/src/core/agents/launches.ts+++ b/cli/src/core/agents/launches.ts@@ -33,6 +33,7 @@ import { parentAgentIdOf, type RegisteredSession } from '../../lib/registry.js'import { buildHarnessSessionLabel } from '../../lib/harnessSessionLabel.js'import type { LaunchAuthority, LaunchPreparation } from '../../lib/launchPreparation.js'import { createPendingLaunches } from './pendingLaunches.js'+import type { GuestCreate } from './guestCreate.js'/** Creates an agent (core/agents/create.ts). The orchestrator creates through the same one. */export type CreateAgent = NonNullable<BackendSocket['onCreateAgent']>@@ -69,12 +70,14 @@ export interface LaunchRequestDeps {* machine (core/api.ts `ModelsPort.launchTarget`). Null or a rejection holds a durable model request;* resolving the semantic choice may renew service-owned credentials, but never dispatches a launch. */modelTarget: (selection: NewAgentModel) => Promise<GridLaunchOverride | null>+ /** A guest's New Harness, as the guest's own OS user (core/agents/guestCreate.ts); null where there is none. */+ guestCreate?: () => GuestCreate | null}type Reply = (result: Record<string, unknown>) => voidtype CreateInput = Parameters<CreateAgent>[0]-export function createLaunchRequests({ receipts, createAgent, prepareCreate, prepareEngine, forkAgent, resumeAgent, restartAgent, byAgent, toProject, modelTarget }: LaunchRequestDeps) {+export function createLaunchRequests({ receipts, createAgent, prepareCreate, prepareEngine, forkAgent, resumeAgent, restartAgent, byAgent, toProject, modelTarget, guestCreate }: LaunchRequestDeps) {const validateInstalled = async (input: CreateInput, known?: ReturnType<typeof installedDsh>): Promise<{ error: string; detail: string } | null> => {if (input.dsh) {const installed = known ?? installedDsh(input.dsh)@@ -258,8 +261,36 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre}}- /** Answers `agent_create`. `asker.local` says the frame came from this machine. */- const create = async (payload: Record<string, unknown>, asker: { local: boolean }, reply: Reply): Promise<void> => {+ /** A guest's `agent_create`: its own launch, never the owner's (core/agents/guestCreate.ts). A `creationId` keeps a+ * receipt as the owner's launches do, so a status check or a retry finds the same harness. */+ const createForGuest = async (payload: Record<string, unknown>, guest: string, reply: Reply): Promise<void> => {+ const launch = guestCreate?.()+ if (!launch) { reply({ error: 'GUEST_NOT_ALLOWED' }); return }+ const creationId = payload.creationId+ if (creationId !== undefined && !validCreationId(creationId)) { reply({ error: 'INVALID_CREATION_ID' }); return }+ if (creationId === undefined) {+ const result = await launch(payload, guest)+ reply(result.ok ? { agent: await toProject(result.session) } : { error: result.error, ...(result.detail ? { detail: result.detail } : {}) })+ return+ }+ try {+ const fingerprint = creationFingerprint({ guest, engine: payload.engine, name: payload.name })+ void receipts.run(creationId, fingerprint, async () => {+ const result = await launch(payload, guest)+ return result.ok ? { state: 'created', agentId: result.session.agentId }+ : { state: 'failed', error: result.error, ...(result.detail ? { detail: result.detail } : {}) }+ }).then(async (status) => {+ reply({ creationId, ...await creationStatusPayload(status) })+ }).catch(() => reply({ error: 'INTERNAL' }))+ } catch (error) {+ reply({ error: error instanceof AgentCreationReceiptError ? error.code : 'INTERNAL' })+ }+ }++ /** Answers `agent_create`. `asker.local` says the frame came from this machine; `asker.guest`, that a guest+ * of a machine shared with them asks (core/guestPolicy.ts). */+ const create = async (payload: Record<string, unknown>, asker: { local: boolean; guest?: string }, reply: Reply): Promise<void> => {+ if (asker.guest !== undefined) { await createForGuest(payload, asker.guest, reply); return }const engine = payload.engine as AgentEngine | undefinedconst cwd = payload.cwdif (typeof engine !== 'string' || !ENGINES.includes(engine)) { reply({ error: 'INVALID_ENGINE' }); return }diff --git a/cli/src/core/agents/lifecycle.spec.ts b/cli/src/core/agents/lifecycle.spec.tsindex ced86ea01..476c73da7 100644--- a/cli/src/core/agents/lifecycle.spec.ts+++ b/cli/src/core/agents/lifecycle.spec.ts@@ -5,6 +5,7 @@ import { createResumeAgentService } from '../../lib/resumeAgentService.js'import { AgentStopError, createStopAgentService } from '../../lib/stopAgentService.js'import { createAgentLifecycle, createPurgeRequest, createStopRequest, type LifecycleDeps } from './lifecycle.js'import { IdentityReadUnavailable } from '../../engines/kit/identityScan.js'+import { GUEST_HARNESS_REFUSAL } from '../guestPolicy.js'vi.mock('../../lib/stopAgentService.js', async (real) => ({ ...await real<object>(), createStopAgentService: vi.fn(() => vi.fn(async () => {})) }))vi.mock('../../lib/resumeAgentService.js', async (real) => ({@@ -144,6 +145,15 @@ describe('stopping, purging and resuming an agent', () => {expect(deps.stoppedAgents.get).toHaveBeenCalledWith('a1')})+ it('resumes no guest\'s harness, stopped or running: it would run as the owner', async () => {+ const stopped = setup({ stoppedAgents: { list: () => [], get: vi.fn(() => row({ guest: '[email protected]' })) } as never })+ expect(await stopped.lifecycle.resumeAgent('a1')).toEqual(GUEST_HARNESS_REFUSAL)+ const running = setup({ stoppedAgents: { list: () => [], get: vi.fn(() => undefined) } as never })+ vi.spyOn(running.deps.registry, 'byAgent').mockReturnValue(row({ guest: '[email protected]' }))+ expect(await running.lifecycle.resumeAgent('a1')).toEqual(GUEST_HARNESS_REFUSAL)+ expect(vi.mocked(createResumeAgentService).mock.results.every((r) => !vi.mocked(r.value).mock.calls.length)).toBe(true)+ })+it('waits while the agent is being purged, or while a purge holds its folder', async () => {const busy = setup()vi.spyOn(busy.lifecycle.purgeAgentService, 'busy').mockReturnValue(true)diff --git a/cli/src/core/agents/lifecycle.ts b/cli/src/core/agents/lifecycle.tsindex b771444ae..d6fdfa629 100644--- a/cli/src/core/agents/lifecycle.ts+++ b/cli/src/core/agents/lifecycle.ts@@ -14,6 +14,7 @@ import { AgentStopError, createStopAgentService, type StopAgentServiceDeps } froimport { IdentityReadUnavailable } from '../../engines/kit/identityScan.js'import type { ResumeAgent } from './launches.js'+import { GUEST_HARNESS_REFUSAL } from '../guestPolicy.js'export interface LifecycleDeps {settlePane?: StopAgentServiceDeps['settlePane']@@ -87,8 +88,10 @@ export function createAgentLifecycle({retainExitedSession, announceSession, relaunchOverrides, prepareSessionResume,refreshGridWebSearch, clearDeleted, attachDsh, attachSession, relaunchMarks,})- const resumeAgent: ResumeAgent = (id, permissionMode) => purgeAgentService.busy(id) || purgeAgentService.blocksFolder(stoppedAgents.get(id)?.cwd)- ? Promise.resolve({ ok: false, error: 'AGENT_BUSY' }) : resume(id, permissionMode)+ const resumeAgent: ResumeAgent = (id, permissionMode) => (stoppedAgents.get(id) ?? registry.byAgent(id))?.guest+ ? Promise.resolve(GUEST_HARNESS_REFUSAL)+ : purgeAgentService.busy(id) || purgeAgentService.blocksFolder(stoppedAgents.get(id)?.cwd)+ ? Promise.resolve({ ok: false, error: 'AGENT_BUSY' }) : resume(id, permissionMode)return { stopJobs, stopAgent, purgeAgentService, resumeAgent }}diff --git a/cli/src/core/agents/list.spec.ts b/cli/src/core/agents/list.spec.tsindex 8db65e931..42cb86a9c 100644--- a/cli/src/core/agents/list.spec.ts+++ b/cli/src/core/agents/list.spec.ts@@ -33,6 +33,27 @@ function setup(live: RegisteredSession[], saved: RegisteredSession[] = [], over:return { deps, created, replies, ask }}+describe('the agents a guest asks for', () => {+ // A guest (a session of an account this machine is shared with) sees the harnesses it started and nothing+ // of the owner's (docs/plans/2026-10-19-guest-machine-sharing-plan.md).+ it('only its own harnesses, oldest first; never the owner\'s, the stopped, the cloud ones or the monitor\'s readings', async () => {+ const [mine, also, older, owners, theirs] = [session('mine', { guest: '[email protected]' }), session('also', { guest: '[email protected]' }), session('older', { guest: '[email protected]' }), session('owners'), session('theirs', { guest: '[email protected]' })]+ const cloud = vi.fn(() => [])+ const { created, replies, deps } = setup([mine, also, older, owners, theirs], [session('saved', { guest: '[email protected]' })], { cloudFrames: cloud })+ created.set('older', '2026-10-05T09:00:00.000Z')+ await createAgentList(deps).agentsList({ includeStopped: true, monitor: true }, () => 'web', (r) => { replies.push(r) }, '[email protected]')+ // Made at the same time, the id breaks the tie.+ expect(replies).toEqual([{ agents: [expect.objectContaining({ id: 'older' }), expect.objectContaining({ id: 'also' }), expect.objectContaining({ id: 'mine' })] }])+ expect(deps.stoppedAgents.available).not.toHaveBeenCalled()+ expect(cloud).not.toHaveBeenCalled()+ expect(deps.harnessResourcesReader).not.toHaveBeenCalled()+ // A share recorded before its account was: a guest that owns nothing.+ replies.length = 0+ await createAgentList(deps).agentsList({}, () => 'web', (r) => { replies.push(r) }, '')+ expect(replies).toEqual([{ agents: [] }])+ })+})+describe('the agents a window asks for', () => {it('every live agent\'s frame, oldest first, an id breaking a tie, and nothing stopped unless asked for', async () => {const [a, b, c] = [session('b-agent'), session('a-agent'), session('c-agent')]diff --git a/cli/src/core/agents/list.ts b/cli/src/core/agents/list.tsindex ecd6a361b..1d3f56820 100644--- a/cli/src/core/agents/list.ts+++ b/cli/src/core/agents/list.ts@@ -92,7 +92,17 @@ export function createAgentList({payload: Record<string, unknown>,sessionRole: () => string | null,reply: (result: Record<string, unknown>) => void,+ guest?: string,): Promise<void> => {+ // A guest sees the harnesses it started and nothing of the owner's (core/guestPolicy.ts): no stopped+ // conversations, no cloud harnesses, no monitor readings.+ if (guest !== undefined) {+ const own = registry.advertised().filter((s) => !!guest && s.guest === guest)+ const frames = await Promise.all(own.map((s) => toProject(s)))+ frames.sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt) || a.id.localeCompare(b.id))+ reply({ agents: frames })+ return+ }const sessions = registry.advertised()const projects: Array<AgentFrame | CloudAgentFrame> = await Promise.all(sessions.map((s) => toProject(s)))// Older clients/devices keep their live-only contract. The desktop pickerdiff --git a/cli/src/core/agents/restart.spec.ts b/cli/src/core/agents/restart.spec.tsindex ec2fce307..41c369241 100644--- a/cli/src/core/agents/restart.spec.ts+++ b/cli/src/core/agents/restart.spec.ts@@ -10,6 +10,7 @@ import { terminalRouteKey } from '../../lib/terminalRuntime.js'import { clearPaneRemainOnExit, processLaunchArgs } from '../../lib/tmux.js'import { workspaceMissing } from '../../lib/workspaceCheck.js'import { createAgentRestarter, type RestartDeps } from './restart.js'+import { GUEST_HARNESS_REFUSAL } from '../guestPolicy.js'vi.mock('../../lib/engineBin.js', async (real) => ({ ...await real<object>(), enginePathOverride: vi.fn(() => undefined) }))vi.mock('../../lib/engineLaunch.js', async (real) => ({@@ -144,6 +145,11 @@ describe('restarting an agent', () => {expect(await setup(null).restart('a1')).toEqual({ ok: false, error: 'AGENT_NOT_FOUND' })})+ it('for a guest\'s harness, which a relaunch would run as the owner', async () => {+ const run = setup(agent({ guest: '[email protected]' }))+ expect(await run.restart('a1')).toEqual(GUEST_HARNESS_REFUSAL)+ })+it('for an agent held for a service, its launch, now, with nothing of a swap touched', async () => {const launched = { ok: true as const, session: agent(), resumed: true }const run = setup(agent({ processIdentity: undefined, tmuxPane: '%4' } as Partial<RegisteredSession>), { restartHeld: vi.fn(() => Promise.resolve(launched)) })diff --git a/cli/src/core/agents/restart.ts b/cli/src/core/agents/restart.tsindex f3b891d72..5582b0d43 100644--- a/cli/src/core/agents/restart.ts+++ b/cli/src/core/agents/restart.ts@@ -23,6 +23,7 @@ import type { createLaunchHelpers } from './launch.js'import type { RestartAgent } from './launches.js'import type { PaneSwap } from './swap.js'import type { LaunchOverridesDeps } from '../../lib/launchOverrides.js'+import { GUEST_HARNESS_REFUSAL } from '../guestPolicy.js'type LaunchHelpers = ReturnType<typeof createLaunchHelpers>@@ -101,6 +102,7 @@ export function createAgentRestarter({if (purgeBusy(agentId) || stopJobs.has(agentId) || pinnedControls.has(agentId)) return { ok: false, error: 'AGENT_BUSY' }const session = registry.resolve(agentId)if (!session) return { ok: false, error: 'AGENT_NOT_FOUND' }+ if (session.guest) return GUEST_HARNESS_REFUSALif (!session.sessionId && (session.launch?.state === 'held' || session.launch?.state === 'starting') && session.launch.nativeToken) {return { ok: false, error: 'NATIVE_LAUNCH_HELD', detail: 'The original launch is held for recovery. Its first prompt or fork cannot be replaced by a fresh launch.' }}diff --git a/cli/src/core/agents/retarget.spec.ts b/cli/src/core/agents/retarget.spec.tsindex 9a4027d7d..c246f9c65 100644--- a/cli/src/core/agents/retarget.spec.ts+++ b/cli/src/core/agents/retarget.spec.ts@@ -13,6 +13,7 @@ import { TerminalAgentReconciler } from '../../lib/terminalAgentReconciler.js'import { terminalRouteKey } from '../../lib/terminalRuntime.js'import { createAgentRetargeter, type RetargetDeps } from './retarget.js'import type { NativeLaunch } from '../../engines/nativeLaunch.js'+import { GUEST_HARNESS_REFUSAL } from '../guestPolicy.js'vi.mock('../../engines/launchControl.js', async (real) => ({...await real<object>(),@@ -245,6 +246,8 @@ describe('retargeting an agent', () => {expect(await setup(agent(), { purgeBusy: () => true }).retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'AGENT_BUSY' })expect(await setup(agent(), { tmuxBackend: null }).retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'TMUX_UNAVAILABLE' })expect(await setup(null).retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'AGENT_NOT_FOUND' })+ // A guest's harness: re-exec'd here it would run as the owner, on the owner's keys.+ expect(await setup(agent({ guest: '[email protected]' })).retarget({ agentId: 'a1', grid })).toEqual(GUEST_HARNESS_REFUSAL)expect(await setup(agent({ runtimes: [] } as Partial<RegisteredSession>)).retarget({ agentId: 'a1', grid })).toMatchObject({ error: 'RETARGET_UNSUPPORTED_BACKEND' })expect(await setup(agent({ processIdentity: undefined } as Partial<RegisteredSession>)).retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'NO_ACTIVE_PROCESS' })})diff --git a/cli/src/core/agents/retarget.ts b/cli/src/core/agents/retarget.tsindex 3a1c25705..a74f66bae 100644--- a/cli/src/core/agents/retarget.ts+++ b/cli/src/core/agents/retarget.ts@@ -32,6 +32,7 @@ import type { createLaunchHelpers } from './launch.js'import type { PaneSwap } from './swap.js'import { createLaunchAuthority } from './launchAuthority.js'import { nativeOpencodeStore } from '../../engines/kit/nativeLocations.js'+import { GUEST_HARNESS_REFUSAL } from '../guestPolicy.js'type LaunchHelpers = ReturnType<typeof createLaunchHelpers>@@ -71,6 +72,7 @@ export function createAgentRetargeter({if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }const live = registry.resolve(agentId)if (!live) return { ok: false, error: 'AGENT_NOT_FOUND' }+ if (live.guest) return GUEST_HARNESS_REFUSAL// Registry observations can update a row in place while a service or pane// read waits. The request keeps its original conversation and exact process.const session = structuredClone(live)diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.tsindex 0635bae2b..ba5ac66ba 100644--- a/cli/src/core/api.spec.ts+++ b/cli/src/core/api.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it, vi } from 'vitest'import { projectDisplayName, type RegisteredSession } from '../lib/registry.js'-import { CLOUD_DOWN, CLOUD_FALLBACKS, CONNECTOR_VAULT_OFF, CONVERSATIONS_OFF, ACCOUNT_BACKEND_OFF, accountIdentity, AGENT_ACTIONS_OFF, AGENT_CLEANUP_FALLBACKS, createCoreApi, DAEMON_UNKNOWN, DELIVERIES_OFF, DEVICES_FALLBACKS, emptyPorts, LANE_OFF, LONG_ANSWERS, MODELS_OFF, STORE_OFF, MODELS_REQUESTS, MONITOR_OFF, OBSERVER_KEY_OFF, ORCHESTRATOR_FALLBACKS, RECAPS_FALLBACKS, resolveAgent, SHARING_FALLBACKS, MESSAGES_FALLBACKS, TAB_KEY_OFF, TAB_RELAY_OFF, TERMINALS_OFF, WIFI_FALLBACKS, WIFI_OFF, type CoreApiDeps } from './api.js'+import { CLOUD_DOWN, CLOUD_FALLBACKS, CONNECTOR_VAULT_OFF, CONVERSATIONS_OFF, ACCOUNT_BACKEND_OFF, accountIdentity, AGENT_ACTIONS_OFF, AGENT_CLEANUP_FALLBACKS, createCoreApi, DAEMON_UNKNOWN, DELIVERIES_OFF, DEVICES_FALLBACKS, emptyPorts, LANE_OFF, LONG_ANSWERS, MODELS_OFF, STORE_OFF, MODELS_REQUESTS, MONITOR_OFF, OBSERVER_KEY_OFF, ORCHESTRATOR_FALLBACKS, RECAPS_FALLBACKS, resolveAgent, SHARED_MACHINES_FALLBACKS, SHARED_MACHINES_OFF, SHARING_FALLBACKS, MESSAGES_FALLBACKS, TAB_KEY_OFF, TAB_RELAY_OFF, TERMINALS_OFF, WIFI_FALLBACKS, WIFI_OFF, type CoreApiDeps } from './api.js'import { FAIL, readFallback } from './serviceHost.js'const row = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/work/app' }) as RegisteredSession@@ -335,7 +335,7 @@ describe('the core API services stand on', () => {})it('starts with every port empty: a service fills its own when it starts', () => {- expect(emptyPorts()).toEqual({ usage: null, store: null, search: null, viewers: null, models: null, workspaces: null, messages: null, devices: null, wifi: null, monitor: null, orchestrator: null, sharing: null, recaps: null, agentCleanup: null, cloud: null, superTabs: null })+ expect(emptyPorts()).toEqual({ usage: null, store: null, search: null, viewers: null, models: null, workspaces: null, messages: null, devices: null, wifi: null, monitor: null, orchestrator: null, sharing: null, recaps: null, agentCleanup: null, cloud: null, superTabs: null, sharedMachines: null })expect(emptyPorts()).not.toBe(emptyPorts())})@@ -422,4 +422,12 @@ describe('the core API services stand on', () => {await expect(MONITOR_OFF.resources()).rejects.toThrow('the monitor service is unavailable')expect(await MONITOR_OFF.storage([], true)).toEqual(new Map())})++ it('answers a guest\'s New Harness while shared machines is off: guest access unavailable, in words, and nothing to stop', async () => {+ expect(await SHARED_MACHINES_OFF.guestLaunch({ email: '[email protected]', engine: 'claude', bypassPermission: true }))+ .toEqual({ ok: false, error: 'GUEST_UNAVAILABLE', detail: expect.stringMatching(/Guest access/) })+ expect(SHARED_MACHINES_OFF.stop()).toBeUndefined()+ expect(SHARED_MACHINES_FALLBACKS.stop).toBeUndefined()+ expect(LONG_ANSWERS.sharedMachines).toEqual({ guestLaunch: 2 * 60_000, shared_machines: 11 * 60_000 })+ })})diff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex 14634daa8..43b49f895 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -593,6 +593,8 @@ export interface Asker {* Established by the gateway's pairing record, never by the request payload.* Absent in older transports; a local owner remains authoritative. */accountOwner?: boolean+ /** A guest's session (RemoteClient.guest): the account it is shared with. Never `owner`. */+ guest?: string/** The connection it came over (a window's, a remote client's), as the core names it, and the id it* asked under: what a service keys work by that belongs to one connection (the Model Manager's grid* commands, which a cancel on the same connection stops; a limit on how many at once per connection).@@ -650,7 +652,38 @@ export const HANDOFF_REQUESTS = ['agent_handoff_prepare'] as constexport const CONNECTORS_REQUESTS = ['connectors'] as const/** Sharing this machine with other accounts, and adding machines shared with this one, in the edge host* (services/sharedMachines.ts). */-export const SHARED_MACHINES_REQUESTS = ['shared_machines'] as const+export const SHARED_MACHINES_REQUESTS = ['shared_machines', 'guest_folders'] as const++/** What the core asks to start a guest's harness: whose (the email the gateway named the session by), which+ * engine, and whether it works without asking for each command. */+export interface GuestLaunchInput { email: string; engine: string; bypassPermission: boolean; prompt?: string+ /** The engine's own flags for the permission mode asked for (lib/engineLaunch.ts `permissionModeFlags`), as an+ * owner's launch passes them; absent, `bypassPermission` alone decides. */+ permissionFlags?: string[]+ /** A folder the owner shares to start in; the guest's workspace when absent or not shared. */+ cwd?: string }+/** A guest's harness as shared machines builds it (services/guestLaunches.ts): the pane's command, which runs+ * the engine as the guest's own OS user on the owner's subscription, the variables to set on the pane, and+ * `workspace`, where it starts (the guest's workspace or a folder the owner shares). The core opens it and+ * records whose it is (core/agents/guestCreate.ts). */+export type GuestLaunch =+ | { ok: true; workspace: string; argv: string[]; env: Record<string, string> }+ | { ok: false; error: string; detail?: string }++/** The core's call into shared machines: a guest's launch (docs/plans/2026-10-19-guest-machine-sharing-plan.md). */+export interface SharedMachinesCorePort {+ guestLaunch(input: GuestLaunchInput): Promise<GuestLaunch>+ /** The service stopping: its subscription relay closes. */+ stop(): Promise<void> | void+}++/** What a guest's New Harness is told while shared machines is off or failing. */+export const GUEST_LAUNCH_UNAVAILABLE: GuestLaunch = {+ ok: false, error: 'GUEST_UNAVAILABLE', detail: 'Guest access is not running on this computer right now. Try again in a moment.',+}+export const SHARED_MACHINES_FALLBACKS: PortFallbacks<SharedMachinesCorePort> = { guestLaunch: later(GUEST_LAUNCH_UNAVAILABLE), stop: undefined }+/** What the core calls while `ports.sharedMachines` is null. */+export const SHARED_MACHINES_OFF: SharedMachinesCorePort = { guestLaunch: async () => GUEST_LAUNCH_UNAVAILABLE, stop: () => {} }/** A Harness OS computer managed from the owner's phone: whether it runs Harness OS, its update, and its Wi-Fi,* in the edge host (services/osDevice.ts). */export const OS_DEVICE_REQUESTS = ['os_device'] as const@@ -702,6 +735,9 @@ export const LONG_ANSWERS: Readonly<Record<string, Readonly<Record<string, numbe// A cloud agent's maker answers on its own time: Fo's reply waits 40 s, and a busy Fo is retried for half a// minute more. A wait shorter than that said "not running" of words that were then sent anyway.cloud: { create: 3 * MINUTE, deliver: 3 * MINUTE, answer: 3 * MINUTE, stopHarness: 2 * MINUTE, cloud_send: 3 * MINUTE },+ // A guest's first harness makes their OS account (`dscl`, a home); turning guest access on waits on the+ // owner at the admin prompt, which gives up after ten minutes (lib/guestHelperInstall.ts).+ sharedMachines: { guestLaunch: 2 * MINUTE, shared_machines: 11 * MINUTE },}/** The orchestrator (services/orchestrator.ts): its projects, for the apps and for the agents it runs. */@@ -1330,6 +1366,10 @@ export type RemoteRole = 'web' | 'device'export interface RemoteClient {role: RemoteRoleaccountOwner?: boolean+ /** Set for a session trusted only because this machine is shared with another account: that account's+ * email ('' when an older store did not record it). A guest uses its own space and nothing of the+ * owner's (docs/plans/2026-10-19-guest-machine-sharing-plan.md, core/guestPolicy.ts). */+ guest?: stringlabel: string | nullidentity: stringdirect: boolean@@ -1366,8 +1406,8 @@ export interface GatewayPort {/** Whether the backend link is up. */connected(): boolean/** A frame for the web audience: sealed under the group key when it carries content, queued while the- * link is down. */- broadcast(frame: Record<string, unknown>): void+ * link is down. [guest]: the guest whose harness it is about, whose sessions get it sealed for each. */+ broadcast(frame: Record<string, unknown>, guest?: string): void/** A frame for the devices (the commander audience), sealed the same way. */commander(frame: Record<string, unknown>): void/** A notification for every browser signed in to the account (the user audience). */@@ -1634,10 +1674,11 @@ export interface CorePorts {agentCleanup: AgentCleanupPort | nullcloud: CloudPort | nullsuperTabs: SuperTabsPort | null+ sharedMachines: SharedMachinesCorePort | null}export function emptyPorts(): CorePorts {- return { usage: null, store: null, search: null, viewers: null, models: null, workspaces: null, messages: null, devices: null, wifi: null, monitor: null, orchestrator: null, sharing: null, recaps: null, agentCleanup: null, cloud: null, superTabs: null }+ return { usage: null, store: null, search: null, viewers: null, models: null, workspaces: null, messages: null, devices: null, wifi: null, monitor: null, orchestrator: null, sharing: null, recaps: null, agentCleanup: null, cloud: null, superTabs: null, sharedMachines: null }}export interface CoreApiDeps {diff --git a/cli/src/core/gatewayLink.spec.ts b/cli/src/core/gatewayLink.spec.tsindex 95d2ca268..9b2ff3817 100644--- a/cli/src/core/gatewayLink.spec.ts+++ b/cli/src/core/gatewayLink.spec.ts@@ -124,6 +124,9 @@ describe('the gateway in its own process, as the core sees it', () => {link.port.usageLaunch?.({ id: 'creation-fixture-1', phase: 'start' })link.port.broadcast({ type: 'turn_started' })expect(kinds()).toEqual(['start', 'broadcast'])+ // About a guest's harness: the gateway is told whose, to seal it for that guest's sessions.+ link.port.broadcast({ type: 'turn_started', agentId: 'g' }, '[email protected]')+ expect(kinds().at(-1)).toBe('broadcast')setBuffered(0)link.port.usageCounter?.('create_requests')expect(kinds().at(-1)).toBe('usageCounter')diff --git a/cli/src/core/gatewayLink.ts b/cli/src/core/gatewayLink.tsindex f7c0c063d..c0897750d 100644--- a/cli/src/core/gatewayLink.ts+++ b/cli/src/core/gatewayLink.ts@@ -191,7 +191,7 @@ export function createGatewayLink(deps: GatewayLinkDeps) {holdRequests: () => { requestsOpen = false; send('hold') },openRequests: () => { requestsOpen = true; send('open') },connected: () => up && linkUp,- broadcast: (frame) => { bulk('broadcast', { frame }) },+ broadcast: (frame, guest) => { bulk('broadcast', guest ? { frame, guest } : { frame }) },commander: (frame) => { bulk('commander', { frame }) },user: (frame) => { send('user', { frame }) },reply: (connId, type, requestId, payload) => { send('reply', { connId, type, requestId, payload }) },diff --git a/cli/src/core/guestPolicy.spec.ts b/cli/src/core/guestPolicy.spec.tsnew file mode 100644index 000000000..af621bd0c--- /dev/null+++ b/cli/src/core/guestPolicy.spec.ts@@ -0,0 +1,69 @@+import { describe, expect, it } from 'vitest'+import { eventAgentId, GUEST_HARNESS_REFUSAL, GUEST_REFUSALS, guestVerdict } from './guestPolicy.js'++// A guest is a session of an account the owner shares this machine with: its own space, nothing of the+// owner's (docs/plans/2026-10-19-guest-machine-sharing-plan.md).+describe('what a guest may ask', () => {+ const owners: Record<string, string | null> = { mine: '[email protected]', theirs: '[email protected]', owner: null }+ const guestOf = (agentId: string) => owners[agentId]+ const verdict = (type: string, payload: Record<string, unknown> = {}, guest = '[email protected]') => guestVerdict(type, payload, guest, guestOf)++ it('may list and start its own harnesses, and use its terminals', () => {+ for (const type of ['agents_list', 'agent_create', 'agent_create_status', 'agent_create_cancel', 'engines_probe', 'theme_set', 'usage_read', 'guest_folders',+ 'terminal_capabilities', 'terminal_alive', 'terminal_ack', 'terminal_input', 'terminal_resize', 'terminal_paste', 'terminal_paste_image',+ 'terminal_paste_file', 'terminal_chunked_upload_begin', 'terminal_chunked_upload_cancel', 'terminal_scroll', 'terminal_resync', 'terminal_close']) {+ expect(verdict(type, type === 'agent_create' ? { engine: 'claude' } : {}), type).toEqual({ allow: true })+ }+ expect(verdict('agent_create', { engine: 'codex' })).toEqual({ allow: true })+ })++ it('starts nothing on the owner\'s grid, saved APIs or cloud accounts, nor an engine the relay cannot pay for', () => {+ expect(verdict('agent_create', { engine: 'claude', grid: { baseUrl: 'x' } })).toEqual({ allow: false, error: 'GUEST_NOT_ALLOWED' })+ expect(verdict('agent_create', { engine: 'claude', apiConnection: 'openrouter' })).toEqual({ allow: false, error: 'GUEST_NOT_ALLOWED' })+ for (const engine of ['devin-cloud', 'opencode', 'terminal', undefined]) {+ expect(verdict('agent_create', { engine }), String(engine)).toEqual({ allow: false, error: 'GUEST_NOT_ALLOWED' })+ }+ })++ it('acts on a harness only when it started it', () => {+ for (const type of ['terminal_open', 'terminal_info', 'agent_update', 'agent_close', 'agent_delete', 'message', 'cancel', 'question_response']) {+ expect(verdict(type, { agentId: 'mine' }), type).toEqual({ allow: true })+ expect(verdict(type, { agentId: 'owner' }), type).toEqual({ allow: false, error: 'NOT_YOUR_HARNESS' })+ expect(verdict(type, { agentId: 'theirs' }), type).toEqual({ allow: false, error: 'NOT_YOUR_HARNESS' })+ expect(verdict(type), type).toEqual({ allow: false, error: 'NOT_YOUR_HARNESS' })+ }+ })++ it('a guest whose account was never recorded owns nothing', () => {+ expect(guestVerdict('terminal_open', { agentId: 'unrecorded' }, '', () => '')).toEqual({ allow: false, error: 'NOT_YOUR_HARNESS' })+ })++ it('relaunches nothing, its own included: a relaunch is built the owner\'s way, as the owner', () => {+ for (const type of ['agent_resume', 'agent_restart', 'agent_retarget', 'agent_fork']) {+ expect(verdict(type, { agentId: 'mine' }), type).toEqual({ allow: false, error: 'GUEST_NOT_ALLOWED' })+ }+ expect(GUEST_HARNESS_REFUSAL).toEqual({ ok: false, error: 'GUEST_HARNESS', detail: expect.stringMatching(/Start a new one/) })+ })++ it('is refused everything else, including what is added later', () => {+ for (const type of ['e2ee_pairings_list', 'e2ee_pairing_unpair', 'device_e2ee_pair', 'phone_pair', 'group_sync', 'shared_machines',+ 'sessions_list', 'session_get', 'session_search', 'agent_recent', 'agent_fork', 'agent_purge', 'agents_cleanup_preview', 'fs_list_dir',+ 'agent_read_file', 'shell', 'connectors', 'memory', 'grid_models_list', 'api_connections', 'harness_devices_list', 'browser_open',+ 'claude_login_status', 'route_task', 'viewer_surface', 'a_request_added_next_year']) {+ expect(verdict(type), type).toEqual({ allow: false, error: 'GUEST_NOT_ALLOWED' })+ }+ })++ it('names the harness an event is about, wherever the event carries it', () => {+ expect(eventAgentId({ agentId: 'top', payload: { agentId: 'inner' } })).toBe('top')+ expect(eventAgentId({ payload: { agentId: 'inner' } })).toBe('inner')+ expect(eventAgentId({ payload: { agent: { id: 'carried' } } })).toBe('carried')+ expect(eventAgentId({ agentId: '', payload: { agent: { id: '' } } })).toBeNull()+ expect(eventAgentId({ payload: undefined })).toBeNull()+ })++ it('says why in words', () => {+ expect(GUEST_REFUSALS.GUEST_NOT_ALLOWED).toMatch(/guest/)+ expect(GUEST_REFUSALS.NOT_YOUR_HARNESS).toMatch(/not yours/)+ })+})diff --git a/cli/src/core/guestPolicy.ts b/cli/src/core/guestPolicy.tsnew file mode 100644index 000000000..c05e91ba4--- /dev/null+++ b/cli/src/core/guestPolicy.ts@@ -0,0 +1,91 @@+/**+ * What a GUEST may ask this machine (docs/plans/2026-10-19-guest-machine-sharing-plan.md).+ *+ * A guest is a session trusted only because the owner shares this machine with its account+ * (RemoteClient.guest, set by the gateway from the paired key's `sharedWith`). It gets its own space:+ * the harnesses it starts — which run as its own OS user — and nothing of the owner's. So this is a+ * DEFAULT-DENY list: a request type not named here is refused, including every one added later.+ *+ * Checked once per frame by the core (backendSocket.ts `dispatchDown`) before anything else answers it;+ * the gateway refuses its own pairing requests for a guest (gateway/gateway.ts).+ */++import { GUEST_LAUNCH_ENGINES } from '../lib/guestPaneCommand.js'++/** Answered for a guest as for anyone, scoped by the handler (`agents_list` lists only its agents). */+const ANY: ReadonlySet<string> = new Set([+ 'agents_list',+ 'agent_create', 'agent_create_status', 'agent_create_cancel',+ 'engines_probe',+ 'theme_set',+ // The owner's plan limits, which a guest's harness uses through the subscription relay.+ 'usage_read',+ // Where it may start a harness: its workspace and the folders the owner shares with guests.+ 'guest_folders',+ // Stream-scoped: a stream answers only the connection that opened it (lib/terminalStreamManager.ts), and+ // `terminal_open` below admits only the guest's own agents.+ 'terminal_capabilities', 'terminal_alive', 'terminal_ack', 'terminal_input', 'terminal_resize',+ 'terminal_paste', 'terminal_paste_image', 'terminal_paste_file',+ 'terminal_chunked_upload_begin', 'terminal_chunked_upload_cancel',+ 'terminal_scroll', 'terminal_resync', 'terminal_close',+])++/** Answered only for an agent the guest started (`payload.agentId`). Not resume, restart or retarget: those+ * relaunch a pane the owner's way, as the owner (GUEST_HARNESS_REFUSAL below). */+const OWN_AGENT: ReadonlySet<string> = new Set([+ 'terminal_open', 'terminal_info',+ 'agent_update', 'agent_close', 'agent_delete',+ 'message', 'cancel', 'question_response',+])++export type GuestVerdict = { allow: true } | { allow: false; error: 'GUEST_NOT_ALLOWED' | 'NOT_YOUR_HARNESS' }++/**+ * Whether a guest may send `type`. [guestOf]: the guest (email) an agent was started for, or null for+ * the owner's own — read from the registry, never from the payload.+ */+export function guestVerdict(type: string, payload: Record<string, unknown>, guest: string,+ guestOf: (agentId: string) => string | null | undefined): GuestVerdict {+ if (ANY.has(type)) {+ // A guest's harness is Claude Code or Codex on the owner's subscription (lib/guestPaneCommand.ts): never a+ // grid or a saved API, which are keys of the owner's, and never a cloud harness, which is the owner's account.+ if (type === 'agent_create' && (payload.grid !== undefined || payload.apiConnection !== undefined+ || typeof payload.engine !== 'string' || !GUEST_LAUNCH_ENGINES.includes(payload.engine))) {+ return { allow: false, error: 'GUEST_NOT_ALLOWED' }+ }+ return { allow: true }+ }+ if (OWN_AGENT.has(type)) {+ const agentId = typeof payload.agentId === 'string' ? payload.agentId : ''+ // Nothing of an unknown guest is its own: a store that did not record whom the machine is shared+ // with names the guest '', and '' owns nothing.+ if (!agentId || !guest || guestOf(agentId) !== guest) return { allow: false, error: 'NOT_YOUR_HARNESS' }+ return { allow: true }+ }+ return { allow: false, error: 'GUEST_NOT_ALLOWED' }+}++/** The harness an outgoing event is about (its top-level `agentId`, the payload's `agentId`, or the agent+ * it carries), or null: whose guest, if any, is sent it sealed for its sessions (gateway/gateway.ts). */+export function eventAgentId(frame: { agentId?: unknown; payload?: unknown }): string | null {+ const payload = frame.payload as { agentId?: unknown; agent?: { id?: unknown } } | undefined+ if (typeof frame.agentId === 'string' && frame.agentId) return frame.agentId+ if (typeof payload?.agentId === 'string' && payload.agentId) return payload.agentId+ if (typeof payload?.agent?.id === 'string' && payload.agent.id) return payload.agent.id+ return null+}++/**+ * What a relaunch of a guest's harness answers, whoever asks: restart, resume, retarget, fork and the boot's+ * restore all build an owner's launch, which would run the guest's harness as the owner, with the owner's+ * keys, in a folder the owner may only read. A guest starts a new harness instead.+ */+export const GUEST_HARNESS_REFUSAL = {+ ok: false, error: 'GUEST_HARNESS', detail: 'A guest\'s harness is not restarted, resumed, moved or forked. Start a new one.',+} as const++/** What a guest is told when it is refused. */+export const GUEST_REFUSALS: Record<'GUEST_NOT_ALLOWED' | 'NOT_YOUR_HARNESS', string> = {+ GUEST_NOT_ALLOWED: 'A guest on this computer cannot do that.',+ NOT_YOUR_HARNESS: 'That harness is not yours.',+}diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex faa7ff324..b7faa9413 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -171,7 +171,7 @@ import { createEngineHooks, installEngineHooks, installOpencodePluginBeforeSpawnimport { createCursorDiscovery } from './engines/cursorDiscovery.js'import { createCursorTaskHooks, loadPendingCursorTasks } from './engines/cursorTasks.js'import { databaseHistory, hermesDb } from './transcripts/databaseHistory.js'-import { CLOUD_FALLBACKS, CLOUD_REQUESTS, type CloudCore, CONNECTORS_REQUESTS, SHARED_MACHINES_REQUESTS, MEMORY_REQUESTS, ROUTER_REQUESTS, createCoreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS, emptyPorts, HANDOFF_REQUESTS, EXPERIMENTS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, OS_DEVICE_REQUESTS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_FALLBACKS, STORE_OFF, STORE_REQUESTS, MESSAGES_FALLBACKS, MESSAGES_REQUESTS, TURN_DELIVERERS, USAGE_FALLBACKS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WIFI_FALLBACKS, WINDOW_NAMES_REQUESTS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type WindowFocus } from './api.js'+import { CLOUD_FALLBACKS, CLOUD_REQUESTS, type CloudCore, CONNECTORS_REQUESTS, SHARED_MACHINES_FALLBACKS, SHARED_MACHINES_OFF, SHARED_MACHINES_REQUESTS, MEMORY_REQUESTS, ROUTER_REQUESTS, createCoreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS, emptyPorts, HANDOFF_REQUESTS, EXPERIMENTS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, OS_DEVICE_REQUESTS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_FALLBACKS, STORE_OFF, STORE_REQUESTS, MESSAGES_FALLBACKS, MESSAGES_REQUESTS, TURN_DELIVERERS, USAGE_FALLBACKS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WIFI_FALLBACKS, WINDOW_NAMES_REQUESTS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type WindowFocus } from './api.js'import { createServiceHost, testFaults } from './serviceHost.js'import { SUPER_TAB_REQUESTS, SUPER_TAB_FALLBACKS } from './api.js'import { startStalls } from './stall.js'@@ -180,6 +180,8 @@ import { createViewerStreams } from './viewerStreams.js'import { createViewersLink } from './viewersLink.js'import { createWorkspacesLink } from './workspacesLink.js'import { createMonitorLink } from './monitorLink.js'+import { createSharedMachinesLink } from './sharedMachinesLink.js'+import { createGuestCreate } from './agents/guestCreate.js'import { createStoreLink } from './storeLink.js'import { createModelsLink } from './modelsLink.js'import { createRecapsLink } from './recapsLink.js'@@ -213,6 +215,7 @@ import { createViewersWake, VIEWERS_ON_DEMAND, wakeViewers } from './viewersWakeimport { createWifiLink } from './wifiLink.js'import { wifiDoors } from './wifiAgents.js'import { autonomousDeviceLocalRequest } from '../lib/deviceManagementHttp.js'+import { loadOrCreateHookCredential } from '../lib/hookAuth.js'import { attachLocalWsServer, LOCAL_WS_PATH, LOCAL_WS_PROTOCOL_VERSION } from '../localWsServer.js'import { TERMINAL_BINARY_VERSION } from '../lib/terminalBinary.js'import { isLoopbackRequest, loopbackHosts } from '../lib/loopbackRequest.js'@@ -1280,6 +1283,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {harnessResourcesReader: () => (ports.monitor ?? MONITOR_OFF).resources(), harnessStorageReader: (agents, invalidate) => (ports.monitor ?? MONITOR_OFF).storage(agents, invalidate),cloudFrames: () => cloud.frames(),}).agentsList+ backend.agentGuest = (agentId) => registry.resolve(agentId)?.guest ?? nullconst questionWatcher = asking.questionWatcher@@ -1566,8 +1570,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Connected services' MCP bridge and the Connectors screen (services/connectors.ts): here, or in the edge host.if (!outOfProcess.has('connectors')) serviceHost.serve('connectors', inline!.startConnectors, coreApi, CONNECTORS_REQUESTS)// Sharing this machine with other accounts, and the machines shared with this one (services/sharedMachines.ts).- if (!outOfProcess.has('sharedMachines')) serviceHost.serve('sharedMachines', (core) => inline!.startSharedMachines(core,- { port: inlineSharedMachinesPort(sharedMachinesAccount, core.account.signedIn()) }), coreApi, SHARED_MACHINES_REQUESTS)+ // Its port builds a guest's harness (core/agents/guestCreate.ts), asked of the edge host (core/sharedMachinesLink.ts).+ if (outOfProcess.has('sharedMachines')) ports.sharedMachines = createSharedMachinesLink((type, payload) => serviceLinks.call('sharedMachines', type, payload))+ else serviceHost.start('sharedMachines', (core, staged) => inline!.startSharedMachines(core,+ { port: inlineSharedMachinesPort(sharedMachinesAccount, core.account.signedIn()), ports: staged }), coreApi, SHARED_MACHINES_FALLBACKS, SHARED_MACHINES_REQUESTS)// A Harness OS computer managed from the owner's phone: its update and its Wi-Fi (services/osDevice.ts): here, or in the edge host.if (!outOfProcess.has('osDevice')) serviceHost.serve('osDevice', inline!.startOsDevice, coreApi, OS_DEVICE_REQUESTS)// The recaps: in this process, or in the edge host (services/recapsProcess.ts), told each turn's lifecycle.@@ -2028,6 +2034,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {const localWsServer = attachLocalWsServer(hookServer, {localSocketServer: localSocket?.server ?? null,+ // Over TCP the window, the CLI or a tool shows this user's 0600 credential (lib/localCredential.ts).+ localCredential: loadOrCreateHookCredential(env.ADAPTER_DATA_DIR),services: serviceLinks,// A window's answer to a bridge's ask, and its comings and goings: the window bridges are the devices'.onSelectionReply: (connId, machineId, payload) => ports.devices?.windowReply('selection', connId, machineId, payload),@@ -2645,6 +2653,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {paneSwapDeps,restartHeld: (agentId) => heldLaunches.restartHeld(agentId),})+ const guestCreate = createGuestCreate({+ launch: (input) => (ports.sharedMachines ?? SHARED_MACHINES_OFF).guestLaunch(input),+ tmuxBackend: () => tmuxBackend, registry, announceSession, watchNewPane,+ })// The requests that start an agent's process, and the receipts of those asked with a creationId// (core/agents/launches.ts). The orchestrator and the cable create and fork through the socket's slots.const launches = createLaunchRequests({@@ -2654,6 +2666,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {resumeAgent: () => lifecycle.resumeAgent, restartAgent: () => restartAgent,byAgent: (id) => registry.byAgent(id), toProject: (s) => backend.toProject(s),modelTarget: (selection) => (ports.models ?? MODELS_OFF).launchTarget(selection),+ // A guest's New Harness: built by shared machines, as the guest's own OS user (core/agents/guestCreate.ts).+ guestCreate: () => guestCreate,})// A cloud agent is made by its service (core/agents/cloud.ts); every other engine launches here.// Answered when the service answers, never in the connection's line: the window's next requests go on.diff --git a/cli/src/core/sharedMachinesLink.spec.ts b/cli/src/core/sharedMachinesLink.spec.tsnew file mode 100644index 000000000..1d622197e--- /dev/null+++ b/cli/src/core/sharedMachinesLink.spec.ts@@ -0,0 +1,36 @@+import { describe, expect, it, vi } from 'vitest'+import { GUEST_LAUNCH_UNAVAILABLE } from './api.js'+import { createSharedMachinesLink } from './sharedMachinesLink.js'++describe('a guest\'s launch, asked of shared machines\' process', () => {+ const input = { email: '[email protected]', engine: 'claude', bypassPermission: true }++ it('asks under the port\'s member name, and takes a launch as it came', async () => {+ const call = vi.fn(async () => ({ ok: true, workspace: '/g/work', argv: ['/bin/sh', '-c', 'x'], env: { TERM: 'xterm' } }))+ const link = createSharedMachinesLink(call)+ expect(await link.guestLaunch(input)).toEqual({ ok: true, workspace: '/g/work', argv: ['/bin/sh', '-c', 'x'], env: { TERM: 'xterm' } })+ expect(call).toHaveBeenCalledWith('guestLaunch', input)+ link.stop()+ })++ it('passes on a refusal, with its words when it has them', async () => {+ expect(await createSharedMachinesLink(async () => ({ ok: false, error: 'GUEST_HELPER_REQUIRED', detail: 'Turn it on.' })).guestLaunch(input))+ .toEqual({ ok: false, error: 'GUEST_HELPER_REQUIRED', detail: 'Turn it on.' })+ expect(await createSharedMachinesLink(async () => ({ ok: false, error: 'GUEST_INVALID' })).guestLaunch(input)).toEqual({ ok: false, error: 'GUEST_INVALID' })+ })++ it('runs nothing it cannot trust the shape of: a process down, failing, or answering oddly', async () => {+ for (const answer of [+ { error: 'SERVICE_UNAVAILABLE' },+ { ok: true, workspace: '/g/work', argv: [], env: {} },+ { ok: true, workspace: '/g/work', argv: ['sh', 1], env: {} },+ { ok: true, workspace: '/g/work', argv: ['sh'], env: { TERM: 1 } },+ { ok: true, workspace: '/g/work', argv: ['sh'], env: ['x'] },+ { ok: true, workspace: '/g/work', argv: ['sh'], env: null },+ { ok: true, argv: ['sh'], env: {} },+ { ok: false },+ ]) {+ expect(await createSharedMachinesLink(async () => answer as Record<string, unknown>).guestLaunch(input), JSON.stringify(answer)).toEqual(GUEST_LAUNCH_UNAVAILABLE)+ }+ })+})diff --git a/cli/src/core/sharedMachinesLink.ts b/cli/src/core/sharedMachinesLink.tsnew file mode 100644index 000000000..9ed03aef8--- /dev/null+++ b/cli/src/core/sharedMachinesLink.ts@@ -0,0 +1,32 @@+/**+ * Shared machines in their own process (the edge host; services/sharedMachinesProcess.ts), as the core+ * reaches it: a guest's harness (`guestLaunch`), asked when a guest's New Harness arrives and never in a+ * connection's line. An answer that does not come (the process is down, or slower than its wait,+ * core/api.ts `LONG_ANSWERS`), or one not shaped as a launch, is the fallback: guest access unavailable.+ * The argv and the variables are checked here, as strings, because the core runs them in a pane.+ */+import { GUEST_LAUNCH_UNAVAILABLE, type GuestLaunch, type SharedMachinesCorePort } from './api.js'++/** Ask shared machines' process (core/serviceLinks.ts `call`, for `sharedMachines`): never rejects. */+export type CallSharedMachines = (type: string, payload: Record<string, unknown>) => Promise<Record<string, unknown>>++const strings = (value: unknown): value is string[] => Array.isArray(value) && value.length > 0 && value.every((v) => typeof v === 'string')+const stringMap = (value: unknown): value is Record<string, string> =>+ !!value && typeof value === 'object' && !Array.isArray(value) && Object.values(value).every((v) => typeof v === 'string')++export function createSharedMachinesLink(call: CallSharedMachines): SharedMachinesCorePort {+ return {+ guestLaunch: async (input): Promise<GuestLaunch> => {+ const answer = await call('guestLaunch', { ...input })+ if (answer.ok === true && typeof answer.workspace === 'string' && strings(answer.argv) && stringMap(answer.env)) {+ return { ok: true, workspace: answer.workspace, argv: answer.argv, env: answer.env }+ }+ if (answer.ok === false && typeof answer.error === 'string') {+ return { ok: false, error: answer.error, ...(typeof answer.detail === 'string' ? { detail: answer.detail } : {}) }+ }+ return GUEST_LAUNCH_UNAVAILABLE+ },+ // The process stops its own relay.+ stop: () => {},+ }+}diff --git a/cli/src/devices/client.spec.ts b/cli/src/devices/client.spec.tsindex 508026873..a00e9f519 100644--- a/cli/src/devices/client.spec.ts+++ b/cli/src/devices/client.spec.ts@@ -1,5 +1,9 @@import { describe, expect, it, vi } from 'vitest'import { EventEmitter } from 'node:events'+import { mkdtempSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { loadOrCreateHookCredential } from '../lib/hookAuth.js'import { devicesCommand, deviceRequest, type DevicesClientDeps } from './client.js'const snapshot = (brightness = 80) => ({ status: { devices: [{ id: 'usb', attached: true, settings: { brightness } }] } })@@ -67,4 +71,21 @@ describe('Devices DSH commands', () => {expect(await reply).toEqual(snapshot())expect(socket.close).toHaveBeenCalledOnce()})+ it('shows the daemon this OS user\'s local credential on its loopback socket and fetches', async () => {+ const dataDir = mkdtempSync(join(tmpdir(), 'devices-cred-'))+ try {+ const credential = loadOrCreateHookCredential(dataDir)+ const socket = Object.assign(new EventEmitter(), { send: vi.fn(), close: vi.fn() })+ const { deps } = fixture()+ const connect = vi.fn((_url: string, _headers?: Record<string, string>) => socket)+ Object.assign(deps, { dataDir, connect, request: undefined })+ const reply = deviceRequest(deps, 'remote', 'harness_devices_list')+ expect(connect).toHaveBeenCalledWith('ws://127.0.0.1:18473/api/local-ws', { 'X-Harness-Local': credential })+ socket.emit('close', 1000)+ await expect(reply).rejects.toThrow('The computer disconnected.')+ await devicesCommand(['list', '--json'], { ...deps, request: async () => snapshot() })+ const init = vi.mocked(deps.fetch!).mock.calls[0]![1] as RequestInit+ expect(init.headers).toMatchObject({ 'x-adapter-local': '1', 'X-Harness-Local': credential })+ } finally { rmSync(dataDir, { recursive: true, force: true }) }+ })})diff --git a/cli/src/devices/client.ts b/cli/src/devices/client.tsindex 9233deeb0..06e8b1a1f 100644--- a/cli/src/devices/client.ts+++ b/cli/src/devices/client.ts@@ -1,12 +1,17 @@/** Devices DSH tools use the same owned-machine bridge as Desktop. No serial or credential access. */import { randomUUID } from 'node:crypto'+import { env } from '../config/env.js'+import { localCredentialHeaders } from '../lib/localCredential.js'import type { ClientSocket } from '../lib/clientSocket.js'import { deviceSettingsPatchSchema } from '../lib/harnessDevices.js'export interface DevicesClientDeps {port: number+ /** The daemon's data dir, where its local credential is (lib/localCredential.ts). */+ dataDir?: stringmachineId(): Promise<string | null>- connect(url: string): ClientSocket+ /** A loopback socket to the daemon, carrying [headers] (its local credential). */+ connect(url: string, headers?: Record<string, string>): ClientSocketfetch?: typeof fetchrequest?: (machineId: string, type: string, payload?: Record<string, unknown>) => Promise<Record<string, unknown>>delay?: (ms: number) => Promise<void>@@ -14,7 +19,7 @@ export interface DevicesClientDeps {export function deviceRequest(deps: DevicesClientDeps, machineId: string, type: string, payload: Record<string, unknown> = {}): Promise<Record<string, unknown>> {return new Promise((resolve, reject) => {- const socket = deps.connect(`ws://127.0.0.1:${deps.port}/api/local-ws`)+ const socket = deps.connect(`ws://127.0.0.1:${deps.port}/api/local-ws`, localCredentialHeaders(deps.dataDir ?? env.ADAPTER_DATA_DIR))const requestId = randomUUID()let settled = false, sent = falseconst finish = (error: Error | null, reply?: Record<string, unknown>): void => {@@ -53,7 +58,7 @@ async function ownedHosts(deps: DevicesClientDeps): Promise<Host[]> {const localId = await deps.machineId()if (!localId) throw new Error('Start Harness on this computer first.')const response = await (deps.fetch ?? fetch)(`http://127.0.0.1:${deps.port}/api/machines`, {- headers: { 'x-adapter-local': '1' }, signal: AbortSignal.timeout(8000),+ headers: { 'x-adapter-local': '1', ...localCredentialHeaders(deps.dataDir ?? env.ADAPTER_DATA_DIR) }, signal: AbortSignal.timeout(8000),})if (!response.ok) throw new Error('Could not read the account’s computers. Sign in and try again.')const body = await response.json() as { data?: { machines?: Record<string, unknown>[] }; machines?: Record<string, unknown>[] }diff --git a/cli/src/gateway/gateway.spec.ts b/cli/src/gateway/gateway.spec.tsindex 01b0f0259..444eceae3 100644--- a/cli/src/gateway/gateway.spec.ts+++ b/cli/src/gateway/gateway.spec.ts@@ -104,12 +104,15 @@ describe('a remote client, as the core hears it', () => {// A field in the payload claiming the owner's role is the sender's word; the session is the gateway's.await dispatchDown(socket, phone.seal('dsh_list', { requestId: 'p', owner: false }), 'phone-1')await dispatchDown(socket, dial.seal('dsh_list', { requestId: 'd', owner: true, local: true, role: 'web', accountOwner: true }), 'dial-1')+ // A colleague the machine is shared with is a guest (core/guestPolicy.ts): never the owner, whatever it says. Its+ // `dsh_list` is refused before any service hears it; what a guest may ask is asked as that guest.await dispatchDown(socket, colleague.seal('dsh_list', { requestId: 'c', owner: true, local: true, accountOwner: true }), 'colleague')+ await dispatchDown(socket, colleague.seal('usage_read', { requestId: 'u', owner: true, local: true, accountOwner: true }), 'colleague')// With the connection and the request id it asked under, which a service keys a connection's own work by.expect(asked).toEqual([{ type: 'dsh_list', asker: { local: false, owner: true, accountOwner: true, connection: 'phone-1', requestId: 'p' } },{ type: 'dsh_list', asker: { local: false, owner: false, accountOwner: false, connection: 'dial-1', requestId: 'd' } },- { type: 'dsh_list', asker: { local: false, owner: true, accountOwner: false, connection: 'colleague', requestId: 'c' } },+ { type: 'usage_read', asker: expect.objectContaining({ local: false, owner: false, accountOwner: false, connection: 'colleague', requestId: 'u' }) },])await socket.stop()})diff --git a/cli/src/gateway/gateway.ts b/cli/src/gateway/gateway.tsindex c0275afa3..37dbb469a 100644--- a/cli/src/gateway/gateway.ts+++ b/cli/src/gateway/gateway.ts@@ -145,10 +145,15 @@ export class RelayGateway implements GatewayPort {isConnectionAvailable: connId => this.directDeviceSinks.has(connId) || this.connected(),onIdentityPaired: (connId, pub) => { if (this.directDeviceSinks.has(connId)) this.directDevicePins.set(connId, pub) },onIdentityRevoked: identity => { this.deviceUnpaired(identity); this.onDirectDeviceRevoked?.(fingerprint(b64d(identity))) },- onSessionOpened: (connId, role, identity) => this.core.client(connId, {- role, label: this.e2ee.sessionLabel(connId), identity, direct: this.directDeviceSinks.has(connId),- accountOwner: role === 'web' && this.e2ee.pairedPeers().some(peer => peer.identityPub === identity && !peer.shared),- }),+ onSessionOpened: (connId, role, identity) => {+ const peer = this.e2ee.pairedPeers().find(p => p.identityPub === identity)+ this.core.client(connId, {+ role, label: this.e2ee.sessionLabel(connId), identity, direct: this.directDeviceSinks.has(connId),+ accountOwner: role === 'web' && !!peer && !peer.shared,+ // Trusted only because this machine is shared: that account's guest, never the owner.+ ...(peer?.shared ? { guest: peer.sharedWith ?? '' } : {}),+ })+ },onSessionDropped: (connId) => this.core.client(connId, null),onPeerLinked: (peer) => {// The mutual half of a password link: a machine that proved this one's password is pinned back,@@ -243,8 +248,11 @@ export class RelayGateway implements GatewayPort {// ── out, to remote clients ───────────────────────────────────────────────────────────────────────- /** User-content events are group-encrypted (E2EE) here; system frames pass through as plaintext. */- broadcast(frame: Frame): void {+ /** User-content events are group-encrypted (E2EE) here; system frames pass through as plaintext.+ * [guest]: the guest whose harness the frame is about (the core reads it from the registry). The group+ * never reaches a guest (manager.ts `groupKeyFor`, backend/src/lib/hub.ts), so its sessions are sent+ * the frame sealed for each of them. */+ broadcast(frame: Frame, guest?: string): void {if ((frame.type === 'turn_started' || frame.type === 'turn_ended' || frame.type === 'text_delta' || frame.type === 'error') && typeof frame.agentId === 'string') {const interrupted = frame.type === 'turn_ended' && (frame.payload as { aborted?: unknown } | undefined)?.aborted === truetry { this.productUsage?.observe(frame.type, frame.agentId, frame.replay === true, interrupted) } catch { /* Work continues without metrics. */ }@@ -264,6 +272,21 @@ export class RelayGateway implements GatewayPort {}if (this.link.servesThisComputerOnly()) returnthis.link.enqueue({ t: 'up', frame: this.e2ee.wrapUp(frame) })+ if (guest) {+ for (const connId of this.e2ee.guestSessions(guest)) {+ const sealed = this.e2ee.wrapFor(connId, frame)+ if (sealed) this.link.enqueue({ t: 'up', targetConnId: connId, frame: sealed })+ }+ }+ }++ /** The guest a remote connection's session is (gateway/sharedTrust.ts), '' when its store did not+ * record the account; undefined for everyone else. */+ private guestOf(connId: string): string | undefined {+ const identity = this.e2ee.sessionIdentity(connId)+ if (!identity) return undefined+ const peer = this.e2ee.pairedPeers().find((p) => p.identityPub === identity)+ return peer?.shared ? (peer.sharedWith ?? '') : undefined}/** A DEVICE-audience frame (commanderEligible, not web). User/data frames are group-encrypted (E2EE)@@ -524,6 +547,13 @@ export class RelayGateway implements GatewayPort {return}const payload = (opened.payload ?? {}) as Record<string, unknown>+ // A guest manages none of this machine's pairings and is no member of its trust group+ // (docs/plans/2026-10-19-guest-machine-sharing-plan.md): the rest it asks, the core decides.+ if ((type === 'group_sync' || GATEWAY_REQUEST_TYPES.has(type)) && this.guestOf(connId) !== undefined) {+ this.logRequest(connId, opened)+ this.reply(connId, type, payload.requestId, { error: 'GUEST_NOT_ALLOWED' })+ return+ }// Trust-group roster exchange: only over an E2EE session, from the identity that session proved —// the roster carries the keys this machine trusts, and the peer's own entry must be that identity.if (type === 'group_sync') {diff --git a/cli/src/gateway/gatewayProcess.spec.ts b/cli/src/gateway/gatewayProcess.spec.tsindex 67fb4bee6..a93313d9b 100644--- a/cli/src/gateway/gatewayProcess.spec.ts+++ b/cli/src/gateway/gatewayProcess.spec.ts@@ -197,6 +197,8 @@ describe('the gateway\'s process, spoken to by the core', () => {w.link.notice({ kind: 'status', connected: true })w.link.notice({ kind: 'client', connId: 'phone-1', client: { role: 'web', label: null, identity: 'P', direct: false } })w.link.port.broadcast({ type: 'turn_started' })+ // A guest's harness's event, named for that guest's sessions (gateway/gateway.ts `broadcast`).+ w.link.port.broadcast({ type: 'turn_started', agentId: 'guests' }, '[email protected]')w.link.port.commander({ type: 'commander_event' })w.link.port.user({ type: 'notification' })w.link.port.reply('phone-1', 'agents_list', 'r-1', { agents: [] })@@ -215,6 +217,7 @@ describe('the gateway\'s process, spoken to by the core', () => {w.link.ops.wifiService(false)await w.link.stop()expect(port.broadcast).toHaveBeenCalledWith({ type: 'turn_started' })+ expect(port.broadcast).toHaveBeenCalledWith({ type: 'turn_started', agentId: 'guests' }, '[email protected]')expect(port.commander).toHaveBeenCalledWith({ type: 'commander_event' })expect(port.user).toHaveBeenCalledWith({ type: 'notification' })expect(port.reply).toHaveBeenCalledWith('phone-1', 'agents_list', 'r-1', { agents: [] })@@ -234,7 +237,7 @@ describe('the gateway\'s process, spoken to by the core', () => {// Stopped: what the core says after is for no gateway, and is dropped.expect(w.gateways[0].stop).toHaveBeenCalled()w.link.port.broadcast({ type: 'after' })- expect(port.broadcast).toHaveBeenCalledTimes(1)+ expect(port.broadcast).toHaveBeenCalledTimes(2)})it('tells the core everything the gateway says, as the same call', () => {diff --git a/cli/src/gateway/gatewayProcess.ts b/cli/src/gateway/gatewayProcess.tsindex 42ff0878e..5b6c520f7 100644--- a/cli/src/gateway/gatewayProcess.ts+++ b/cli/src/gateway/gatewayProcess.ts@@ -167,7 +167,13 @@ export function runGatewayService(options: GatewayServiceOptions): ServiceProcescase 'thisComputerOnly': port.serveThisComputerOnly(); returncase 'hold': port.holdRequests(); returncase 'open': port.openRequests(); return- case 'broadcast': port.broadcast(record(payload.frame)); return+ case 'broadcast': {+ // A guest's harness's event goes to the group (which cannot open it) and sealed to that guest's sessions.+ const guest = text(payload.guest)+ if (guest) port.broadcast(record(payload.frame), guest)+ else port.broadcast(record(payload.frame))+ return+ }case 'commander': port.commander(record(payload.frame)); returncase 'user': port.user(record(payload.frame)); returncase 'reply': port.reply(connId, text(payload.type), payload.requestId, record(payload.payload)); returndiff --git a/cli/src/gateway/sharedTrust.spec.ts b/cli/src/gateway/sharedTrust.spec.tsindex 422ed0c12..fa9f635e7 100644--- a/cli/src/gateway/sharedTrust.spec.ts+++ b/cli/src/gateway/sharedTrust.spec.ts@@ -22,7 +22,7 @@ function stores(pins: Pin[] = [], paired: PairedClient[] = []) {paired: () => [...trusted.values()],trust: vi.fn((peer: LinkedPeer) => {trusted.set(peer.pub, { identityPub: peer.pub, label: peer.label, pairedAt: 1, role: 'web', machineId: peer.machineId, kind: peer.kind,- ...(peer.shared ? { shared: true as const } : {}) })+ ...(peer.shared ? { shared: true as const } : {}), ...(peer.sharedWith ? { sharedWith: peer.sharedWith } : {}) })}),untrust: vi.fn((pub: string) => { trusted.delete(pub) }),dropSessions: vi.fn(),@@ -42,6 +42,24 @@ describe('sharedPeers', () => {})})+describe('whom a shared key is shared with', () => {+ // Its sessions are that account's guest (docs/plans/2026-10-19-guest-machine-sharing-plan.md).+ it('keeps a valid address, lowercased, and drops one that is not', () => {+ const peer = { machineId: id('a'), pub: key(1), label: 'Mac' }+ expect(sharedPeers([{ ...peer, email: ' [email protected] ' }])).toEqual([{ ...peer, email: '[email protected]' }])+ expect(sharedPeers([{ ...peer, email: 'not an address' }])).toEqual([peer])+ expect(sharedPeers([{ ...peer, email: 42 }])).toEqual([peer])+ })++ it('trusts each key with its account, and a key with none as a guest of no one', () => {+ const { deps, trusted } = stores()+ applySharedTrust(deps, { keys: [{ machineId: id('k'), pub: key(1), label: 'Mac · kim', email: '[email protected]' }, { machineId: id('n'), pub: key(2), label: 'Mac' }] })+ expect(trusted.get(key(1))).toMatchObject({ shared: true, sharedWith: '[email protected]' })+ expect(trusted.get(key(2))).toMatchObject({ shared: true })+ expect(trusted.get(key(2))?.sharedWith).toBeUndefined()+ })+})+describe('applySharedTrust', () => {it('pins the machines shared with this account, marked shared, and takes back only its own', () => {const { deps, held } = stores([diff --git a/cli/src/gateway/sharedTrust.ts b/cli/src/gateway/sharedTrust.tsindex dd1127cda..d33034f54 100644--- a/cli/src/gateway/sharedTrust.ts+++ b/cli/src/gateway/sharedTrust.ts@@ -6,8 +6,10 @@* - `pins`: the machines shared WITH this account, each under the key its owner's device key log names.* Pinned in machinePeers.json so a window here reaches one through the relay as it does the account's* own (lib/remoteRelay.ts).- * - `keys`: the machines of the accounts THIS machine is shared with. Trusted in paired.json as the- * account's own machines are (role `web`): the owner shares the machine with full rights.+ * - `keys`: the machines of the accounts THIS machine is shared with. Trusted in paired.json under role+ * `web`, each with the account it is shared with (`sharedWith`): its sessions are that GUEST's, which+ * the core lets use its own space and nothing of the owner's+ * (docs/plans/2026-10-19-guest-machine-sharing-plan.md).** Each is marked `shared`, which keeps it out of the trust group (lib/e2ee/groupSyncer.ts) and lets this* take back what it gave and nothing else. Something the account itself already trusts or pins is never@@ -19,7 +21,7 @@ import type { LinkedPeer } from '../lib/e2ee/manager.js'import type { PairedClient } from '../lib/e2ee/store.js'/** One machine and its key, as the service names it. */-export interface SharedPeer { machineId: string; pub: string; label: string }+export interface SharedPeer { machineId: string; pub: string; label: string; email?: string }/** What the service wants trusted; the most of each it may ask for. A part left out is left as it is:* the service says only what it could read this time. */@@ -39,6 +41,7 @@ export interface SharedTrustDeps {const PUB_RE = /^[A-Za-z0-9+/]{43}=$/const MACHINE_RE = /^[A-Za-z0-9_-]{1,128}$/+const EMAIL_RE = /^[^\s@]{1,128}@[^\s@]{1,128}$//** The valid peers of a list the service sent, at most SHARED_TRUST_MAX, each machine and key once. */export function sharedPeers(raw: unknown): SharedPeer[] {@@ -50,7 +53,8 @@ export function sharedPeers(raw: unknown): SharedPeer[] {if (!p || typeof p.pub !== 'string' || !PUB_RE.test(p.pub) || typeof p.machineId !== 'string' || !MACHINE_RE.test(p.machineId)) continueif (seen.has(p.machineId) || seen.has(p.pub)) continueseen.add(p.machineId); seen.add(p.pub)- out.push({ machineId: p.machineId, pub: p.pub, label: typeof p.label === 'string' ? p.label.slice(0, 120) : '' })+ const email = typeof p.email === 'string' && EMAIL_RE.test(p.email.trim()) ? p.email.trim().toLowerCase() : undefined+ out.push({ machineId: p.machineId, pub: p.pub, label: typeof p.label === 'string' ? p.label.slice(0, 120) : '', ...(email ? { email } : {}) })}return out}@@ -89,7 +93,7 @@ function applyKeys(deps: SharedTrustDeps, desired: SharedPeer[]): number {for (const want of keys.values()) {const held = paired.find((p) => p.identityPub === want.pub)if (held && !held.shared) continue // trusted as the account's own already- deps.trust({ pub: want.pub, machineId: want.machineId, kind: 'machine', label: want.label, shared: true })+ deps.trust({ pub: want.pub, machineId: want.machineId, kind: 'machine', label: want.label, shared: true, ...(want.email ? { sharedWith: want.email } : {}) })trusted++}return trusteddiff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.tsindex ead6f559a..37fa1f4f7 100644--- a/cli/src/hookServer.spec.ts+++ b/cli/src/hookServer.spec.ts@@ -12,6 +12,19 @@ import { engineHooks } from './engines/hooks.js'let server: Server | null = null+/** The fetch a test's calls go through: this OS user's process, so over the loopback port it shows the daemon's+ * local credential (lib/localCredential.ts) — unless the test names its own `x-harness-local`. */+const realFetch = globalThis.fetch+function credentialedFetch(base: string, credential: string): void {+ vi.spyOn(globalThis, 'fetch').mockImplementation((input: string | URL | Request, init?: RequestInit) => {+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url+ if (!url.startsWith(base)) return realFetch(input, init)+ const headers = new Headers(init?.headers)+ if (!headers.has('x-harness-local')) headers.set('x-harness-local', credential)+ return realFetch(input, { ...init, headers })+ })+}+afterEach(async () => {vi.restoreAllMocks()if (!server) return@@ -29,6 +42,7 @@ async function start(overrides: Partial<HookServerHandlers> = {}) {server = started.serverconst credential = readHookCredential(env.ADAPTER_DATA_DIR)if (!credential) throw new Error('hook credential was not created')+ credentialedFetch(`http://127.0.0.1:${started.port}`, credential)return {handlers,base: `http://127.0.0.1:${started.port}`,@@ -621,8 +635,10 @@ describe('requests must name this server', () => {// A page that re-points its hostname at 127.0.0.1 is same-origin to this port; only its Host gives it away.async function send(base: string, method: string, path: string, headers: Record<string, string>): Promise<number> {const url = new URL(path, base)+ // This OS user's process: it shows the local credential, as every route but liveness wants over the port.+ const credentialed = { 'x-harness-local': readHookCredential(env.ADAPTER_DATA_DIR) ?? '', ...headers }return new Promise((resolve, reject) => {- const r = request({ host: '127.0.0.1', port: url.port, path: url.pathname, method, headers }, (res) => { res.resume(); resolve(res.statusCode ?? 0) })+ const r = request({ host: '127.0.0.1', port: url.port, path: url.pathname, method, headers: credentialed }, (res) => { res.resume(); resolve(res.statusCode ?? 0) })r.on('error', reject)r.end()})@@ -788,8 +804,12 @@ describe('the daemon socket', () => {expect(await viaSocket(socketPath, 'POST', '/api/auth/handoff', local)).toBe(200)expect(await viaSocket(socketPath, 'POST', '/api/auth/handoff')).toBe(403)const port = (started.server.address() as { port: number }).port+ // Over the port: refused without the local credential, and still refused with it.const tcp = await fetch(`http://127.0.0.1:${port}/api/auth/handoff`, { method: 'POST', headers: local })- expect(tcp.status).toBe(403)+ expect(tcp.status).toBe(401)+ const credential = readHookCredential(env.ADAPTER_DATA_DIR) ?? ''+ const credentialed = await fetch(`http://127.0.0.1:${port}/api/auth/handoff`, { method: 'POST', headers: { ...local, 'x-harness-local': credential } })+ expect(credentialed.status).toBe(403)expect(onAuthHandoff).toHaveBeenCalledTimes(1)} finally {await started.localSocket?.close()@@ -879,3 +899,75 @@ it.each(['/api/hook/session-end', '/api/hook/turn-start', '/api/hook/tool-start'expect(mutation).not.toHaveBeenCalled()},)++describe('the loopback port wants this OS user\'s local credential', () => {+ // Another OS user's process reaches 127.0.0.1 too — a guest's harness running as its own user+ // (docs/plans/2026-10-19-guest-machine-sharing-plan.md). Only this user can read the 0600 credential.+ const raw = (port: number, method: string, path: string, headers: Record<string, string> = {}): Promise<{ status: number; body: string }> =>+ new Promise((resolve, reject) => {+ const r = request({ host: '127.0.0.1', port, path, method, headers }, (res) => {+ let body = ''+ res.setEncoding('utf8')+ res.on('data', (chunk: string) => { body += chunk })+ res.on('end', () => resolve({ status: res.statusCode ?? 0, body }))+ })+ r.on('error', reject)+ r.end()+ })++ it('refuses every route without it, takes it by header or bearer, and leaves liveness and the hook routes alone', async () => {+ const onMachinesList = vi.fn(async () => ({ status: 200, body: { success: true, data: { machines: [] } } }))+ const started = await startHookServer(0, {+ onRegistered: vi.fn(), onSessionEnd: vi.fn(), onMachinesList,+ onStatus: () => ({ version: '9.9.9', pid: 42, corePid: 43, computerId: 'c1', machineId: 'm1', dataDir: '/secret/data', signedIn: true, localWs: { path: '/api/local-ws' }, localSocket: null }),+ } as Partial<HookServerHandlers> as HookServerHandlers)+ server = started.server+ const port = started.port+ const credential = readHookCredential(env.ADAPTER_DATA_DIR)!+ // Without it: the account's routes, reads and writes alike, are refused.+ for (const [method, path] of [['GET', '/api/machines'], ['GET', '/api/pairs'], ['POST', '/api/revoke-all'], ['GET', '/api/agent-settings'], ['GET', '/nowhere']] as const) {+ const answer = await raw(port, method, path, { 'x-adapter-local': '1' })+ expect(answer.status, `${method} ${path}`).toBe(401)+ expect(JSON.parse(answer.body)).toEqual({ error: 'LOCAL_CREDENTIAL_REQUIRED' })+ }+ // A wrong one is no better.+ expect((await raw(port, 'GET', '/api/machines', { 'x-harness-local': 'x'.repeat(43) })).status).toBe(401)+ // With it, by its header or as a bearer.+ expect((await raw(port, 'GET', '/api/machines', { 'x-harness-local': credential })).status).toBe(200)+ expect((await raw(port, 'GET', '/api/machines', { authorization: `Bearer ${credential}` })).status).toBe(200)+ expect(onMachinesList).toHaveBeenCalledTimes(2)+ // Liveness answers anyone; the status, only who the daemon is and where its socket is.+ expect((await raw(port, 'GET', '/api/health')).status).toBe(200)+ const open = await raw(port, 'GET', '/api/status')+ expect(open.status).toBe(200)+ expect(JSON.parse(open.body)).toEqual({ credentialRequired: true, version: '9.9.9', pid: 42, corePid: 43, computerId: 'c1', localWs: { path: '/api/local-ws' }, localSocket: null })+ const whole = JSON.parse((await raw(port, 'GET', '/api/status', { 'x-harness-local': credential })).body)+ expect(whole).toMatchObject({ machineId: 'm1', dataDir: '/secret/data', signedIn: true })+ // A hook route keeps its own token: refused for want of it, not of the local credential.+ const hook = await raw(port, 'POST', '/api/hook/session-end')+ expect(hook.status).toBe(401)+ expect(JSON.parse(hook.body)).toEqual({ error: 'UNAUTHORIZED' })+ })++ const viaSocket = (socketPath: string, method: string, path: string): Promise<number> =>+ new Promise((resolve, reject) => {+ const r = request({ socketPath, path, method }, (res) => { res.resume(); resolve(res.statusCode ?? 0) })+ r.on('error', reject)+ r.end()+ })++ it('takes nothing over the daemon\'s own socket', async () => {+ const dir = mkdtempSync('/tmp/hsock-')+ const socketPath = join(dir, 'daemon.sock')+ const onMachinesList = vi.fn(async () => ({ status: 200, body: { success: true, data: { machines: [] } } }))+ const started = await startHookServer(0, { onRegistered: vi.fn(), onSessionEnd: vi.fn(), onMachinesList } as Partial<HookServerHandlers> as HookServerHandlers, { socketPath })+ server = started.server+ try {+ expect(await viaSocket(socketPath, 'GET', '/api/machines')).toBe(200)+ expect(onMachinesList).toHaveBeenCalledTimes(1)+ } finally {+ await started.localSocket?.close()+ rmSync(dir, { recursive: true, force: true })+ }+ })+})diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.tsindex 8527f0456..d718bbe48 100644--- a/cli/src/hookServer.ts+++ b/cli/src/hookServer.ts@@ -24,6 +24,7 @@ import { sid } from './lib/log.js'import { VERSION } from './version.js'import { env } from './config/env.js'import { hookCredentialMatches, loadOrCreateHookCredential } from './lib/hookAuth.js'+import { LOCAL_CREDENTIAL_REQUIRED, localCredentialMatches } from './lib/localCredential.js'import { routeStoreRequest, type StoreHandler } from './lib/storeProxy.js'import type { HookTerminalHint } from './lib/terminalTypes.js'import { ENGINES, type AgentEngine } from './engines/types.js'@@ -381,6 +382,17 @@ export interface HookServerOptions {admissionBytesCapacity?: number}+/** The `/api/status` fields a caller without the local credential is answered. */+// Which daemon this is (its pid and computer, as a takeover or a status check compares) and where its socket+// is — never the account, its folders or its connections.+const PUBLIC_STATUS_FIELDS = ['version', 'pid', 'corePid', 'computerId', 'localWs', 'localSocket', 'supported'] as const++function publicStatus(status: Record<string, unknown>): Record<string, unknown> {+ const out: Record<string, unknown> = { credentialRequired: true }+ for (const key of PUBLIC_STATUS_FIELDS) if (key in status) out[key] = status[key]+ return out+}+export function startHookServer(port: number,handlers: HookServerHandlers,@@ -443,7 +455,20 @@ export function startHookServer(// send it, can trigger actions. A local process could still call it — same trust level as the// CLI, which is acceptable on loopback.const localOk = req.headers['x-adapter-local'] === '1'- const hookOk = hookCredentialMatches(hookCredential, req.headers['x-harness-hook-token'])+ // An engine hook's token. Today the daemon's own credential; a guest's harness will carry a token+ // scoped to its own agent (docs/plans/2026-10-19-guest-machine-sharing-plan.md), checked here.+ const hookTokenMatches = (request: http.IncomingMessage): boolean =>+ hookCredentialMatches(hookCredential, request.headers['x-harness-hook-token'])+ const hookOk = hookTokenMatches(req)+ // The loopback port takes any local OS user's process, so over TCP every route but the few below+ // wants the daemon's local credential (lib/localCredential.ts): the 0600 file only this OS user can+ // read. Over the daemon's Unix socket the filesystem already said who this is.+ const credentialOk = trustedLocal || localCredentialMatches(hookCredential, req)+ // Open without it: liveness, the status a discovery reads (cut down, below), the hook routes (their+ // own token, above) and the native device routes (their own bearer, just below).+ const open = (req.method === 'GET' && (url === '/api/health' || url === '/api/status'))+ || url.startsWith('/api/hook/') || url.startsWith('/api/autonomous-device/')+ if (!credentialOk && !open) { json(401, { error: LOCAL_CREDENTIAL_REQUIRED }); return }if (url.startsWith('/api/autonomous-device/')) {const peer = req.socket.remoteAddress@@ -469,7 +494,10 @@ export function startHookServer(// it linked from retired with the browser setup links (#348). `harness stop` stops the daemon// through its pid, never through here.if (req.method === 'GET' && url === '/api/status') {- json(200, handlers.onStatus ? await handlers.onStatus() : { supported: false }); return+ const status = handlers.onStatus ? await handlers.onStatus() : { supported: false }+ // Without the credential, only what says a daemon is here and where its socket is: nothing about+ // the account, its folders or its connections.+ json(200, credentialOk ? status : publicStatus(status)); return}// SessionStart AND UserPromptSubmit both POST here (the catch hook re-registers so a sessiondiff --git a/cli/src/lib/accountUsage.ts b/cli/src/lib/accountUsage.tsindex 704bea13e..c3db7d51d 100644--- a/cli/src/lib/accountUsage.ts+++ b/cli/src/lib/accountUsage.ts@@ -24,13 +24,17 @@* Every failure here is an `outcome`, never a throw — the reply must go back either way.*/import { createHash } from 'node:crypto'-import { execFile } from 'node:child_process'-import { readFile } from 'node:fs/promises'import { homedir } from 'node:os'-import { join } from 'node:path'-import { promisify } from 'node:util'--const execFileAsync = promisify(execFile)+import {+ asRecord,+ claudeProfilePath,+ codexAuthPath,+ jwtClaims,+ parseJson,+ readClaudeStored,+ readText,+ stringField,+} from './agentCredentials.js'export type UsageProviderId = 'claude' | 'codex'@@ -95,15 +99,13 @@ export async function readAccountUsage(deps: AccountUsageDeps = {}): Promise<Accasync function readClaude(deps: AccountUsageDeps): Promise<AccountUsageReading> {const home = deps.home ?? homedir()- // The Keychain first and the file second, as the desktop reads its own: macOS keeps the token in- // the login Keychain and Linux in a file, and a Keychain that will not answer is a state, not the- // end of the road.- const stored = (await readKeychain(deps)) ?? (await readText(join(home, '.claude', '.credentials.json')))+ // The Keychain first and the file second (`agentCredentials.ts`).+ const stored = (await readClaudeStored(deps))?.raw ?? nullconst oauth = asRecord(asRecord(parseJson(stored))?.claudeAiOauth)const token = stringField(oauth?.accessToken)// The account lives beside the token rather than in it: `~/.claude.json` is where Claude Code// records who it is signed in as, on every platform.- const profile = asRecord(asRecord(parseJson(await readText(join(home, '.claude.json'))))?.oauthAccount)+ const profile = asRecord(asRecord(parseJson(await readText(claudeProfilePath(home))))?.oauthAccount)const accountId = stringField(profile?.accountUuid)const email = emailField(profile?.emailAddress)const account = accountId ? accountKey('claude', accountId) : null@@ -129,7 +131,7 @@ async function readClaude(deps: AccountUsageDeps): Promise<AccountUsageReading>async function readCodex(deps: AccountUsageDeps): Promise<AccountUsageReading> {const home = deps.home ?? homedir()- const tokens = asRecord(asRecord(parseJson(await readText(join(home, '.codex', 'auth.json'))))?.tokens)+ const tokens = asRecord(asRecord(parseJson(await readText(codexAuthPath(home))))?.tokens)const token = stringField(tokens?.access_token)const accountId = stringField(tokens?.account_id)const account = accountId ? accountKey('codex', accountId) : null@@ -161,61 +163,11 @@ async function ask(}}-/** The macOS Keychain item Claude Code writes — `security` rather than a native module, for one- * read of one generic password. */-async function readKeychain(deps: AccountUsageDeps): Promise<string | null> {- if (deps.readKeychain) return deps.readKeychain()- if ((deps.platform ?? process.platform) !== 'darwin') return null- try {- const { stdout } = await execFileAsync(- 'security',- ['find-generic-password', '-s', 'Claude Code-credentials', '-w'],- { timeout: 5_000 },- )- const out = stdout.trim()- return out.length > 0 ? out : null- } catch {- return null- }-}--async function readText(path: string): Promise<string | null> {- try {- return await readFile(path, 'utf8')- } catch {- return null- }-}--/** A half-written credentials file is not news — the CLI that owns it is mid-refresh, and the next- * poll a minute from now reads it whole. */-function parseJson(raw: string | null): unknown {- if (raw === null) return null- try {- return JSON.parse(raw) as unknown- } catch {- return null- }-}--function asRecord(value: unknown): Record<string, unknown> | null {- return typeof value === 'object' && value !== null && !Array.isArray(value)- ? (value as Record<string, unknown>)- : null-}--function stringField(value: unknown): string | null {- return typeof value === 'string' && value.length > 0 ? value : null-}-function emailField(value: unknown): string | null {return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null}/** ID-token claims supply a display label only, never an authentication decision. */function tokenEmail(value: unknown): string | null {- if (typeof value !== 'string') return null- const parts = value.split('.')- if (parts.length !== 3) return null- return emailField(asRecord(parseJson(Buffer.from(parts[1]!, 'base64url').toString('utf8')))?.email)+ return emailField(jwtClaims(value)?.email)}diff --git a/cli/src/lib/agentCredentials.ts b/cli/src/lib/agentCredentials.tsnew file mode 100644index 000000000..5299efb9a--- /dev/null+++ b/cli/src/lib/agentCredentials.ts@@ -0,0 +1,103 @@+/**+ * Where the agent CLIs on this computer keep their sign-ins, read the way they write them: Claude+ * Code's OAuth tokens in the macOS login Keychain (`Claude Code-credentials`) or, where there is no+ * Keychain, in `~/.claude/.credentials.json`; Codex's in `~/.codex/auth.json`.+ *+ * Shared by the two readers that need the OWNER's sign-in without asking it of the CLI that owns+ * it: the usage reading (`accountUsage.ts`, which only reads) and the guest subscription relay+ * (`ownerSubscriptions.ts`, which also refreshes and writes back). Nothing here logs or returns a+ * token anywhere but to its caller.+ */+import { execFile } from 'node:child_process'+import { readFile } from 'node:fs/promises'+import { homedir } from 'node:os'+import { join } from 'node:path'+import { promisify } from 'node:util'++const execFileAsync = promisify(execFile)++/** The Keychain service Claude Code stores its OAuth sign-in under (no `CLAUDE_CONFIG_DIR`). */+export const CLAUDE_KEYCHAIN_SERVICE = 'Claude Code-credentials'++/** Everything reading reaches outside for, so a spec never touches a real home or Keychain. */+export interface CredentialReadDeps {+ home?: string+ platform?: NodeJS.Platform+ /** The Keychain item's secret (its JSON), or null. Production asks `security`. */+ readKeychain?: () => Promise<string | null>+}++export type ClaudeCredentialSource = 'keychain' | 'file'++export const claudeCredentialsPath = (home: string): string => join(home, '.claude', '.credentials.json')+export const claudeProfilePath = (home: string): string => join(home, '.claude.json')+export const codexAuthPath = (home: string): string => join(home, '.codex', 'auth.json')++/**+ * Claude Code's stored sign-in as it was written, and where it came from — the Keychain first and+ * the file second, as the desktop reads its own: macOS keeps the token in the login Keychain and+ * Linux in a file, and a Keychain that will not answer is a state, not the end of the road.+ */+export async function readClaudeStored(+ deps: CredentialReadDeps = {},+): Promise<{ raw: string; source: ClaudeCredentialSource } | null> {+ const keychain = await readClaudeKeychain(deps)+ if (keychain !== null) return { raw: keychain, source: 'keychain' }+ const file = await readText(claudeCredentialsPath(deps.home ?? homedir()))+ return file !== null ? { raw: file, source: 'file' } : null+}++/** The macOS Keychain item Claude Code writes — `security` rather than a native module, for one+ * read of one generic password. */+export async function readClaudeKeychain(deps: CredentialReadDeps = {}): Promise<string | null> {+ if (deps.readKeychain) return deps.readKeychain()+ if ((deps.platform ?? process.platform) !== 'darwin') return null+ try {+ const { stdout } = await execFileAsync(+ 'security',+ ['find-generic-password', '-s', CLAUDE_KEYCHAIN_SERVICE, '-w'],+ { timeout: 5_000 },+ )+ const out = stdout.trim()+ return out.length > 0 ? out : null+ } catch {+ return null+ }+}++export async function readText(path: string): Promise<string | null> {+ try {+ return await readFile(path, 'utf8')+ } catch {+ return null+ }+}++/** A half-written credentials file is not news — the CLI that owns it is mid-refresh, and the next+ * read moments later finds it whole. */+export function parseJson(raw: string | null): unknown {+ if (raw === null) return null+ try {+ return JSON.parse(raw) as unknown+ } catch {+ return null+ }+}++export function asRecord(value: unknown): Record<string, unknown> | null {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : null+}++export function stringField(value: unknown): string | null {+ return typeof value === 'string' && value.length > 0 ? value : null+}++/** A JWT's claims, unverified: for display and expiry hints only, never an authentication decision. */+export function jwtClaims(token: unknown): Record<string, unknown> | null {+ if (typeof token !== 'string') return null+ const parts = token.split('.')+ if (parts.length !== 3) return null+ return asRecord(parseJson(Buffer.from(parts[1]!, 'base64url').toString('utf8')))+}diff --git a/cli/src/lib/createAgentPane.ts b/cli/src/lib/createAgentPane.tsindex 7d7b93ce7..baf07c57d 100644--- a/cli/src/lib/createAgentPane.ts+++ b/cli/src/lib/createAgentPane.ts@@ -47,6 +47,7 @@ export interface CreateAgentPaneDeps {externalResume?: ExternalResumeIntentstartedBy?: StartedBy | nullparentAgentId?: string | null+ guest?: string | null}) => RegisteredSession | null }nativeToken?: stringengine: AgentEngine@@ -87,6 +88,8 @@ export interface CreateAgentPaneDeps {/** The harness here whose agent started it (registry.ts `parentAgentId`), recorded on the row; null otherwise. */parentAgentId?: string | nullexternalResume?: ExternalResumeIntent+ /** The guest (an email) whose harness this is: it runs as their own OS user (core/agents/guestCreate.ts). */+ guest?: string | null/** Rechecked by the backend after its gates and immediately before process dispatch. */current?: () => booleanonDispatch?: () => void@@ -138,6 +141,7 @@ export async function createAndRegisterPane(deps: CreateAgentPaneDeps): Promise<...(deps.externalResume ? { externalResume: deps.externalResume } : {}),...(deps.startedBy ? { startedBy: deps.startedBy } : {}),...(deps.startedBy && deps.parentAgentId ? { parentAgentId: deps.parentAgentId } : {}),+ ...(deps.guest ? { guest: deps.guest } : {}),})if (pending) return { ok: true, spawned, pending }console.warn(`[agent] create ${deps.engine} registration failed · pane ${spawned.runtime.paneId} · `diff --git a/cli/src/lib/daemonEndpoint.spec.ts b/cli/src/lib/daemonEndpoint.spec.tsindex ac6712783..804616a12 100644--- a/cli/src/lib/daemonEndpoint.spec.ts+++ b/cli/src/lib/daemonEndpoint.spec.ts@@ -2,6 +2,7 @@ import { createServer } from 'node:http'import { chmodSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'import { join } from 'node:path'import { afterEach, describe, expect, it } from 'vitest'+import { loadOrCreateHookCredential } from './hookAuth.js'import { legacyDaemonStatus, localDaemonStatus, saveDaemonPort, savedDaemonPort } from './daemonEndpoint.js'import { listenLocalSocket, localSocketPath } from './localSocket.js'@@ -82,4 +83,18 @@ describe('per-user daemon discovery', () => {expect(await legacyDaemonStatus(port, 43210, 'other-user')).toBeNull()expect(await legacyDaemonStatus(port, 43210, 'this-user')).toEqual(status)})++ it('shows legacy status this OS user\'s local credential when it is given the data dir', async () => {+ const status = { pid: 43210, computerId: 'this-user' }+ const seen: Array<string | undefined> = []+ const server = createServer((req, res) => { seen.push(req.headers['x-harness-local'] as string | undefined); res.end(JSON.stringify(status)) })+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))+ cleanup.push(() => new Promise<void>((resolve) => { server.closeAllConnections(); server.close(() => resolve()) }))+ const port = (server.address() as { port: number }).port+ const dataDir = directory()+ const credential = loadOrCreateHookCredential(dataDir)+ expect(await legacyDaemonStatus(port, 43210, 'this-user', dataDir)).toEqual(status)+ expect(await legacyDaemonStatus(port, 43210, 'this-user')).toEqual(status)+ expect(seen).toEqual([credential, undefined])+ })})diff --git a/cli/src/lib/daemonEndpoint.ts b/cli/src/lib/daemonEndpoint.tsindex 4221563e8..3d44bd171 100644--- a/cli/src/lib/daemonEndpoint.ts+++ b/cli/src/lib/daemonEndpoint.ts@@ -1,4 +1,5 @@import { request } from 'node:http'+import { localCredentialHeaders } from './localCredential.js'import { lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'import { join } from 'node:path'import { localSocketPath } from './localSocket.js'@@ -62,10 +63,12 @@ export async function localDaemonStatus(dataDir: string, configuredPort: number)/** Read-only compatibility for CLI status on Windows and older daemons without a Unix socket.* Native hn connections must use localDaemonStatus instead. Never accept another daemon's status.*/-export async function legacyDaemonStatus(port: number, pid: number | null, computerId: string): Promise<Record<string, unknown> | null> {+export async function legacyDaemonStatus(port: number, pid: number | null, computerId: string, dataDir?: string): Promise<Record<string, unknown> | null> {if (!pid || !computerId) return nulltry {- const response = await fetch(`http://127.0.0.1:${port}/api/status`, { signal: AbortSignal.timeout(1_500) })+ // With the daemon's local credential, the whole status; without it, only who the daemon is.+ const headers = dataDir ? localCredentialHeaders(dataDir) : {}+ const response = await fetch(`http://127.0.0.1:${port}/api/status`, { headers, signal: AbortSignal.timeout(1_500) })if (!response.ok) return nullconst value: unknown = await response.json()if (value === null || typeof value !== 'object' || Array.isArray(value)) return nulldiff --git a/cli/src/lib/e2ee/applicationFrames.ts b/cli/src/lib/e2ee/applicationFrames.tsindex 93c38abf5..e9004ed0f 100644--- a/cli/src/lib/e2ee/applicationFrames.ts+++ b/cli/src/lib/e2ee/applicationFrames.ts@@ -32,8 +32,9 @@ const MACHINE_REQUESTS = new Set([...SHELL_REQUESTS, 'agent_purge', 'agent_workt'cloud_transcript', 'cloud_send', 'cloud_agents',// A Harness OS computer managed from the phone (services/osDevice.ts): a Wi-Fi join carries the network's password.'os_device',- // Sharing a machine across accounts (services/sharedMachines.ts): the addresses it is shared with.- 'shared_machines',+ // Sharing a machine across accounts (services/sharedMachines.ts): the addresses it is shared with, and where+ // a guest may start a harness (the owner's folders).+ 'shared_machines', 'guest_folders','super_tabs',// A sign-in a phone caught for a page a harness's program opened (core/terminals/browser.ts): it holds the code.'browser_callback', ...ROUTE_COMMAND_TYPES])diff --git a/cli/src/lib/e2ee/manager.test.ts b/cli/src/lib/e2ee/manager.test.tsindex 99f50d8b3..e0d5cc828 100644--- a/cli/src/lib/e2ee/manager.test.ts+++ b/cli/src/lib/e2ee/manager.test.ts@@ -807,3 +807,56 @@ describe('terminal bytes sealed for a session this process never had', () => {expect(h.mgr.terminalSessionGone('live', await keystrokes(4))).toBeNull()})})++// A guest: a key trusted only because this machine is shared with its account (gateway/sharedTrust.ts). It+// must not open the owner's broadcasts; what concerns its own harnesses is sealed for its session alone+// (docs/plans/2026-10-19-guest-machine-sharing-plan.md).+describe('E2eeManager guests', () => {+ type Wrapped = import('./core.js').WrappedPayload+ it('welcomes a guest without the machine\'s group key, seals its events for its session alone, and keeps it out of a rekey', () => {+ const h = machine()+ const adapterPub = (h.mgr as unknown as { store: { getIdentity(): { pub: Uint8Array } } }).store.getIdentity().pub+ const owner = new WebPeer(); const guest = new WebPeer(); const other = new WebPeer()+ h.mgr.trustPeer({ pub: C.b64e(owner.identity.pub), label: 'own' })+ h.mgr.trustPeer({ pub: C.b64e(guest.identity.pub), label: 'Mac · kim', kind: 'machine', machineId: 'a'.repeat(32), shared: true, sharedWith: '[email protected]' })+ h.mgr.trustPeer({ pub: C.b64e(other.identity.pub), label: 'Mac · lee', kind: 'machine', machineId: 'b'.repeat(32), shared: true, sharedWith: '[email protected]' })+ for (const [conn, peer] of [['o', owner], ['g', guest], ['l', other]] as const) {+ h.mgr.handleFrame(conn, peer.hello())+ peer.onWelcome(h.lastFor(conn, 'e2e_welcome')!, adapterPub)+ }+ const opens = (peer: WebPeer, frame: Frame) => C.unwrapPayload(peer.session!.groupKey, (frame.payload as Wrapped).__e2e, 'text_delta', 's')+ const up = h.mgr.wrapUp({ type: 'text_delta', dbSessionId: 's', payload: { content: 'the owner\'s' } })+ expect(opens(owner, up)).toEqual({ content: 'the owner\'s' })+ expect(opens(guest, up)).toBeNull()++ expect(h.mgr.guestSessions('[email protected]')).toEqual(['g'])+ expect(h.mgr.guestSessions('')).toEqual([])+ const mine = h.mgr.wrapFor('g', { type: 'text_delta', dbSessionId: 's', payload: { content: 'yours' } })!+ const env = (mine.payload as Wrapped).__e2e+ expect(env.k).toBe('p')+ expect(C.unwrapPayload(guest.session!.s2c, env, 'text_delta', 's')).toEqual({ content: 'yours' })+ expect(C.unwrapPayload(other.session!.s2c, env, 'text_delta', 's')).toBeNull()+ expect(h.mgr.wrapFor('gone', { type: 'text_delta', payload: {} })).toBeNull()+ // Nothing to seal: as wrapUp passes it.+ expect(h.mgr.wrapFor('g', { type: 'node_status', payload: { online: true } })).toEqual({ type: 'node_status', payload: { online: true } })++ // Sharing with lee ends: the key turns over, and the guest that stays is still handed a throwaway one.+ h.mgr.untrustPeer(C.b64e(other.identity.pub))+ owner.onRekey(h.lastFor('o', 'e2e_rekey')!)+ guest.onRekey(h.lastFor('g', 'e2e_rekey')!)+ const later = h.mgr.wrapUp({ type: 'text_delta', dbSessionId: 's', payload: { content: 'later' } })+ expect(opens(owner, later)).toEqual({ content: 'later' })+ expect(opens(guest, later)).toBeNull()+ })++ it('records whom a shared key is shared with, and a change of it', () => {+ const h = machine()+ const peer = new WebPeer()+ const pub = C.b64e(peer.identity.pub)+ h.mgr.trustPeer({ pub, label: 'Mac', kind: 'machine', machineId: 'c'.repeat(32), shared: true, sharedWith: '[email protected]' })+ expect(h.mgr.pairedPeers().find((p) => p.identityPub === pub)?.sharedWith).toBe('[email protected]')+ h.mgr.trustPeer({ pub, label: 'Mac', kind: 'machine', machineId: 'c'.repeat(32), shared: true, sharedWith: '[email protected]' })+ h.mgr.trustPeer({ pub, label: 'Mac', kind: 'machine', machineId: 'c'.repeat(32), shared: true, sharedWith: '[email protected]' })+ expect(h.mgr.pairedPeers().find((p) => p.identityPub === pub)?.sharedWith).toBe('[email protected]')+ })+})diff --git a/cli/src/lib/e2ee/manager.ts b/cli/src/lib/e2ee/manager.tsindex 4a048eae2..c86413be5 100644--- a/cli/src/lib/e2ee/manager.ts+++ b/cli/src/lib/e2ee/manager.ts@@ -139,6 +139,7 @@ export interface LinkedPeer {kind?: PeerKind // absent for an older joiner that did not saylabel: stringshared?: boolean // another account's machine this one is shared with (gateway/sharedTrust.ts)+ sharedWith?: string // with `shared`: the account (email) it is shared with — whose guest its sessions are}const MACHINE_ID_RE = /^[a-f0-9]{32}$/@@ -196,8 +197,8 @@ export class E2eeManager {trustPeer(peer: LinkedPeer, at = this.now()): void {const existing = this.store.pairedPeer(peer.pub)if (existing && existing.label === peer.label && existing.machineId === peer.machineId && existing.kind === peer.kind- && !!existing.shared === !!peer.shared) return- this.store.addPaired(peer.pub, peer.label, existing?.pairedAt ?? at, existing?.role ?? 'web', { machineId: peer.machineId, kind: peer.kind, shared: peer.shared })+ && !!existing.shared === !!peer.shared && existing.sharedWith === peer.sharedWith) return+ this.store.addPaired(peer.pub, peer.label, existing?.pairedAt ?? at, existing?.role ?? 'web', { machineId: peer.machineId, kind: peer.kind, shared: peer.shared, sharedWith: peer.sharedWith })}/** Stop trusting `pub` (a no-op when it is not paired): the same path as `harness unpair`. */untrustPeer(pub: string): boolean {@@ -342,11 +343,40 @@ export class E2eeManager {this.epoch = hex8()this.groupCounter = 0for (const [connId, s] of this.sessions.entries()) {- const enc = C.aeadSeal(s.s2c, s.s2cCounter++, C.utf8('e2e-rekey'), C.utf8(JSON.stringify({ groupKey: C.b64e(this.groupKey), epoch: this.epoch })))+ const enc = C.aeadSeal(s.s2c, s.s2cCounter++, C.utf8('e2e-rekey'), C.utf8(JSON.stringify({ groupKey: C.b64e(this.groupKeyFor(s.webIdentityPub)), epoch: this.epoch })))this.deps.sendTo(connId, { type: 'e2e_rekey', payload: { enc: C.b64e(enc), n: s.s2cCounter - 1 } })}}+ /** The group key a session is handed: the machine's, except for a GUEST (a key trusted only because the+ * machine is shared, gateway/sharedTrust.ts), which gets a throwaway one. A guest must not open the+ * owner's broadcasts; what concerns its own harnesses is sealed for its session alone (`wrapFor`),+ * and the backend sends it nothing else (backend/src/lib/hub.ts). */+ private groupKeyFor(identityPub: string): Uint8Array {+ return this.store.pairedPeer(identityPub)?.shared ? crypto32() : this.groupKey+ }++ /** The sessions of the guest `email` (docs/plans/2026-10-19-guest-machine-sharing-plan.md). */+ guestSessions(email: string): string[] {+ if (!email) return []+ const out: string[] = []+ for (const [connId, s] of this.sessions.entries()) {+ const peer = this.store.pairedPeer(s.webIdentityPub)+ if (peer?.shared && peer.sharedWith === email) out.push(connId)+ }+ return out+ }++ /** An `up` event sealed for ONE session: its content under that session's key, as a reply is. Null+ * without a session. A frame that carries no content passes through as `wrapUp` passes it. */+ wrapFor(connId: string, frame: Frame): Frame | null {+ const s = this.sessions.get(connId)+ if (!s) return null+ const type = frame.type as string | undefined+ if (!type || !C.isEncryptedUpType(type)) return frame+ return { ...frame, payload: C.wrapPayload(s.s2c, 'p', s.s2cCounter++, type, frame.dbSessionId as string | undefined, frame.payload) }+ }+// ── outbound wrapping ──────────────────────────────────────────────────────────────────────────/** Encrypt a broadcast `up` event under the group key if it carries user content; else pass through. */@@ -892,7 +922,7 @@ export class E2eeManager {this.deps.onSessionOpened?.(connId, role, identityPub)const id = this.store.getIdentity()const enc = C.aeadSeal(keys.s2c, 0, C.utf8('e2e-welcome'), C.utf8(JSON.stringify({- groupKey: C.b64e(this.groupKey),+ groupKey: C.b64e(this.groupKeyFor(identityPub)),epoch: this.epoch,// strictDown: this daemon opens a sealed frame of ANY type and refuses unsealed ones from the relay,// so a client may seal the types older daemons took in the clear (STRICT_DOWN_TYPES).diff --git a/cli/src/lib/e2ee/store.ts b/cli/src/lib/e2ee/store.tsindex 66c81138e..81c308507 100644--- a/cli/src/lib/e2ee/store.ts+++ b/cli/src/lib/e2ee/store.ts@@ -61,6 +61,9 @@ export interface PairedClient {/** A machine of another account this machine is shared with (gateway/sharedTrust.ts): trusted like the* account's own, but never a member of the trust group, and taken back when the sharing ends. */shared?: true+ /** With `shared`: the account (email) the machine is shared with. Its sessions are that account's guest+ * (docs/plans/2026-10-19-guest-machine-sharing-plan.md). */+ sharedWith?: string}/** What a password-linked peer is: another harness machine (which also serves, so it can be dialed back)@@ -159,12 +162,13 @@ export class E2eeStore {return this.paired.get(identityPubB64) ?? null}- addPaired(identityPubB64: string, label: string, at: number, role: PairRole = 'web', peer?: { machineId?: string; kind?: PeerKind; shared?: boolean }): void {+ addPaired(identityPubB64: string, label: string, at: number, role: PairRole = 'web', peer?: { machineId?: string; kind?: PeerKind; shared?: boolean; sharedWith?: string }): void {this.paired.set(identityPubB64, {identityPub: identityPubB64, label, pairedAt: at, role,...(peer?.machineId ? { machineId: peer.machineId } : {}),...(peer?.kind ? { kind: peer.kind } : {}),...(peer?.shared ? { shared: true as const } : {}),+ ...(peer?.shared && peer.sharedWith ? { sharedWith: peer.sharedWith } : {}),})writeSecure(PAIRED_FILE, [...this.paired.values()])}diff --git a/cli/src/lib/guestAccounts.spec.ts b/cli/src/lib/guestAccounts.spec.tsnew file mode 100644index 000000000..cc3057e87--- /dev/null+++ b/cli/src/lib/guestAccounts.spec.ts@@ -0,0 +1,389 @@+import { spawnSync } from 'node:child_process'+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { fileURLToPath } from 'node:url'+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'++import {+ createGuestAccounts, GUEST_ENV_KEYS, GUEST_HELPER_PATH, guestEnvAllowed, GuestHelperError, guestHelperFailure, guestHomeRoot,+ guestRunCommand, guestUserFor, guestWorkspaceFor, runGuestCommand, type GuestRunner,+} from './guestAccounts.js'+import { guestSudoersTemplate } from './guestHelperAssets.js'++const HELPER = fileURLToPath(new URL('../../assets/guest-helper/guest-helper.sh', import.meta.url))+const USER = guestUserFor('[email protected]')++describe('a guest\'s user and the command that runs as it', () => {+ it('names a guest by the hash of its lower-cased email', () => {+ expect(USER).toMatch(/^hg_[0-9a-f]{12}$/)+ expect(guestUserFor(' [email protected] ')).toBe(USER)+ expect(guestUserFor('[email protected]')).not.toBe(USER)+ })++ it('passes a guest\'s variables in the environment, never on the command line, and only the allowed ones', () => {+ const run = guestRunCommand(USER, '/Users/Shared/HarnessGuests/x/work', { ANTHROPIC_AUTH_TOKEN: 'relay-token', TERM: 'xterm' }, ['claude', '--resume', 'a b'])+ expect(run.argv).toEqual(['sudo', '-n', GUEST_HELPER_PATH, 'run', USER, '--cwd', '/Users/Shared/HarnessGuests/x/work',+ '--pass', 'ANTHROPIC_AUTH_TOKEN', '--pass', 'TERM', '--', 'claude', '--resume', 'a b'])+ expect(run.argv.join(' ')).not.toContain('relay-token')+ expect(run.env).toEqual({ ANTHROPIC_AUTH_TOKEN: 'relay-token', TERM: 'xterm' })+ expect(() => guestRunCommand(USER, '/w', { PATH: '/evil' }, ['x'])).toThrow(expect.objectContaining({ code: 'GUEST_ENV_NOT_ALLOWED' }))+ expect(() => guestRunCommand(USER, '/w', { GRID_API_KEY: 'k' }, ['x'])).toThrow(expect.objectContaining({ code: 'GUEST_ENV_NOT_ALLOWED' }))+ expect(() => guestRunCommand('hg_nothex', '/w', {}, ['x'])).toThrow(expect.objectContaining({ code: 'GUEST_INVALID' }))+ expect(() => guestRunCommand('owner', '/w', {}, ['x'])).toThrow(expect.objectContaining({ code: 'GUEST_INVALID' }))+ expect(() => guestRunCommand(USER, 'work', {}, ['x'])).toThrow(expect.objectContaining({ code: 'GUEST_INVALID' }))+ expect(() => guestRunCommand(USER, '/w', {}, [])).toThrow(expect.objectContaining({ code: 'GUEST_INVALID' }))+ expect(guestEnvAllowed('LC_ALL')).toBe(true)+ expect(guestEnvAllowed('LC_')).toBe(false)+ expect(guestEnvAllowed('HOME')).toBe(false)+ })++ it('keeps one list of a guest\'s variables in the helper, the sudoers drop-in and here', async () => {+ const { readFileSync } = await import('node:fs')+ const helperKeys = /^GUEST_ENV_KEYS='([^']+)'$/m.exec(readFileSync(HELPER, 'utf8'))?.[1].split(' ')+ expect(helperKeys).toEqual([...GUEST_ENV_KEYS])+ const kept = /env_keep \+= "([^"]+)"/.exec(guestSudoersTemplate())?.[1].split(' ')+ expect(kept).toEqual(['TERM', 'COLORTERM', 'LANG', 'LC_*', ...GUEST_ENV_KEYS.slice(3)])+ })+})++describe('the helper\'s answers, read', () => {+ it('tells a missing helper, a missing authorization and a refused argument apart', () => {+ expect(guestHelperFailure({ code: 1, stdout: '', stderr: 'sudo: a password is required\n' }).code).toBe('GUEST_HELPER_NOT_AUTHORIZED')+ expect(guestHelperFailure({ code: 1, stdout: '', stderr: 'sudo: a terminal is required to read the password' }).code).toBe('GUEST_HELPER_NOT_AUTHORIZED')+ expect(guestHelperFailure({ code: 1, stdout: '', stderr: 'Sorry, user ann is not allowed to execute \'/x\' as root' }).code).toBe('GUEST_HELPER_NOT_AUTHORIZED')+ expect(guestHelperFailure({ code: null, stdout: '', stderr: 'spawn sudo ENOENT' }).code).toBe('GUEST_HELPER_MISSING')+ expect(guestHelperFailure({ code: 1, stdout: '', stderr: 'sudo: /usr/local/libexec/harness/guest-helper: command not found' }).code).toBe('GUEST_HELPER_MISSING')+ const refused = guestHelperFailure({ code: 2, stdout: '', stderr: 'guest-helper: outside the guest\'s home: /tmp\n' })+ expect(refused).toMatchObject({ code: 'GUEST_INVALID', message: 'outside the guest\'s home: /tmp' })+ expect(guestHelperFailure({ code: 3, stdout: '', stderr: 'guest-helper: no such guest: hg_000000000000' }).code).toBe('GUEST_INVALID')+ expect(guestHelperFailure({ code: 4, stdout: '', stderr: '' })).toMatchObject({ code: 'GUEST_HELPER_FAILED', message: 'The guest helper failed (4).' })+ })+})++describe('a guest\'s account, through the helper', () => {+ const account = { user: USER, home: `/Users/Shared/HarnessGuests/${USER}`, workspace: `/Users/Shared/HarnessGuests/${USER}/work` }+ const answering = (stdout: string, code = 0): GuestRunner & ReturnType<typeof vi.fn> =>+ vi.fn(async () => ({ code, stdout, stderr: '' })) as never++ it('creates it once, by sudo -n, and remembers it', async () => {+ const runner = answering(`${JSON.stringify(account)}\n`)+ const guests = createGuestAccounts({ runner, installed: () => true })+ const [a, b] = await Promise.all([guests.ensureGuest('[email protected]'), guests.ensureGuest('[email protected]')])+ expect(a).toEqual(account)+ expect(b).toEqual(account)+ expect(runner).toHaveBeenCalledTimes(1)+ expect(runner).toHaveBeenCalledWith('sudo', ['-n', GUEST_HELPER_PATH, 'ensure', '[email protected]'], { timeoutMs: 60_000 })+ })++ it('refuses an answer that is not the account it asked for, and does not remember a failure', async () => {+ const wrong = createGuestAccounts({ runner: answering(JSON.stringify({ ...account, user: 'hg_000000000000' })), installed: () => true })+ await expect(wrong.ensureGuest('[email protected]')).rejects.toMatchObject({ code: 'GUEST_HELPER_FAILED' })+ const outside = createGuestAccounts({ runner: answering(JSON.stringify({ ...account, workspace: '/tmp/work' })), installed: () => true })+ await expect(outside.ensureGuest('[email protected]')).rejects.toMatchObject({ code: 'GUEST_HELPER_FAILED' })+ const garbled = createGuestAccounts({ runner: answering('not json'), installed: () => true })+ await expect(garbled.ensureGuest('[email protected]')).rejects.toMatchObject({ code: 'GUEST_HELPER_FAILED' })++ let answer = { code: 1, stdout: '', stderr: 'sudo: a password is required' }+ const runner = vi.fn(async () => answer)+ const guests = createGuestAccounts({ runner, installed: () => true })+ await expect(guests.ensureGuest('[email protected]')).rejects.toMatchObject({ code: 'GUEST_HELPER_NOT_AUTHORIZED' })+ answer = { code: 0, stdout: JSON.stringify(account), stderr: '' }+ await expect(guests.ensureGuest('[email protected]')).resolves.toEqual(account)+ expect(runner).toHaveBeenCalledTimes(2)+ })++ it('does not run sudo at all when the helper is not installed', async () => {+ const runner = answering('')+ const guests = createGuestAccounts({ runner, installed: () => false })+ await expect(guests.ensureGuest('[email protected]')).rejects.toMatchObject({ code: 'GUEST_HELPER_MISSING' })+ expect(runner).not.toHaveBeenCalled()+ })++ it('installs an engine as the guest with its progress, and removes a guest it forgets', async () => {+ const runner = answering(JSON.stringify(account))+ const guests = createGuestAccounts({ runner, installed: () => true, helperPath: '/opt/helper' })+ const onLine = vi.fn()+ await guests.installGuestEngine(USER, 'codex', onLine)+ expect(runner).toHaveBeenLastCalledWith('sudo', ['-n', '/opt/helper', 'install', USER, 'codex'], { timeoutMs: 600_000, onLine })+ await guests.installGuestEngine(USER, 'claude')+ expect(runner).toHaveBeenLastCalledWith('sudo', ['-n', '/opt/helper', 'install', USER, 'claude'], { timeoutMs: 600_000 })+ await expect(guests.installGuestEngine(USER, 'cursor' as never)).rejects.toMatchObject({ code: 'GUEST_INVALID' })+ await expect(guests.installGuestEngine('root', 'claude')).rejects.toMatchObject({ code: 'GUEST_INVALID' })++ await guests.ensureGuest('[email protected]')+ await guests.removeGuest(USER)+ expect(runner).toHaveBeenLastCalledWith('sudo', ['-n', '/opt/helper', 'remove', USER], { timeoutMs: 60_000 })+ const calls = runner.mock.calls.length+ await guests.ensureGuest('[email protected]')+ expect(runner.mock.calls.length).toBe(calls + 1)+ await expect(guests.removeGuest('hg_bad')).rejects.toMatchObject({ code: 'GUEST_INVALID' })+ expect(guests.runCommand(USER, '/w', {}, ['x']).argv[2]).toBe('/opt/helper')+ })++ it('shares the owner\'s folders with a guest through the helper, and lists the guests that have an account', async () => {+ const runner = answering('')+ const guests = createGuestAccounts({ runner, installed: () => true, helperPath: '/opt/helper', homes: () => [USER, 'notes.txt', 'hg_bad', 'hg_000000000001'] })+ await guests.shareFolders(USER, [{ path: '/Users/dee/code', write: true }, { path: '/Users/dee/docs', write: false }])+ // A first share of a large folder sets an entry on everything in it: it may take minutes.+ expect(runner).toHaveBeenLastCalledWith('sudo', ['-n', '/opt/helper', 'share', USER, '--write', '/Users/dee/code', '--read', '/Users/dee/docs'], { timeoutMs: 600_000 })+ await guests.shareFolders(USER, [])+ expect(runner).toHaveBeenLastCalledWith('sudo', ['-n', '/opt/helper', 'share', USER], { timeoutMs: 600_000 })+ await expect(guests.shareFolders('root', [])).rejects.toMatchObject({ code: 'GUEST_INVALID' })+ expect(guests.guests()).toEqual(['hg_000000000001', USER].sort())+ // The machine's own home root, which a test never has: no guests.+ expect(createGuestAccounts().guests()).toEqual(expect.any(Array))+ })++ it('keeps guests\' homes under one root per platform, a workspace in each', () => {+ expect(guestHomeRoot('darwin')).toBe('/Users/Shared/HarnessGuests')+ expect(guestHomeRoot('linux')).toBe('/home/harness-guests')+ expect(guestHomeRoot()).toBe(guestHomeRoot(process.platform))+ expect(guestWorkspaceFor('[email protected]', 'darwin')).toBe(`/Users/Shared/HarnessGuests/${USER}/work`)+ expect(guestWorkspaceFor('[email protected]')).toBe(`${guestHomeRoot()}/${USER}/work`)+ })++ it('runs a command and hears its lines; a command that is not there is code null', async () => {+ const lines: string[] = []+ const result = await runGuestCommand(process.execPath, ['-e', 'process.stdout.write("one\\ntwo\\nthree")'], { onLine: (line) => lines.push(line), timeoutMs: 10_000 })+ expect(result).toMatchObject({ code: 0, stdout: 'one\ntwo\nthree' })+ expect(lines).toEqual(['one', 'two', 'three'])+ expect((await runGuestCommand(process.execPath, ['-e', 'process.stderr.write("no");process.exit(3)'])).code).toBe(3)+ expect((await runGuestCommand('harness-no-such-command-anywhere', [])).code).toBeNull()+ })+})++// The helper itself, in its dry run: validation is real, the commands are printed instead of run.+// Never as root (the helper refuses a dry run there) and never with sudo: nothing here touches the machine.+describe.skipIf(process.getuid?.() === 0)('the guest helper, dry run', () => {+ let root: string+ // The owner's side: a home with a closed folder in it, and the helper's record of what it shared.+ let owner: string+ let state: string+ beforeAll(() => {+ root = realpathSync(mkdtempSync(join(tmpdir(), 'guest-helper-')))+ owner = realpathSync(mkdtempSync(join(tmpdir(), 'guest-owner-')))+ state = realpathSync(mkdtempSync(join(tmpdir(), 'guest-state-')))+ mkdirSync(join(owner, 'docs'))+ mkdirSync(join(owner, 'code', 'app', 'src'), { recursive: true })+ chmodSync(owner, 0o755)+ chmodSync(join(owner, 'code'), 0o750)+ })+ afterAll(() => { for (const dir of [root, owner, state]) rmSync(dir, { recursive: true, force: true }) })++ const helper = (args: string[], platform = 'Darwin', extra: Record<string, string> = {}) => {+ const result = spawnSync('sh', [HELPER, ...args], {+ encoding: 'utf8',+ env: { PATH: process.env.PATH ?? '/usr/bin:/bin', HARNESS_GUEST_HELPER_DRY_RUN: '1', HARNESS_GUEST_HELPER_DRY_HOME_ROOT: root,+ HARNESS_GUEST_HELPER_DRY_STATE_DIR: state, HARNESS_GUEST_HELPER_DRY_OWNER_HOME: owner, HARNESS_GUEST_HELPER_PLATFORM: platform, ...extra },+ })+ return { code: result.status, stdout: result.stdout, stderr: result.stderr }+ }++ it('parses, in sh and in dash', () => {+ expect(spawnSync('sh', ['-n', HELPER]).status).toBe(0)+ const dash = spawnSync('dash', ['-n', HELPER])+ if (!dash.error) expect(dash.status).toBe(0)+ })++ it('names the version this CLI ships', () => {+ expect(helper(['version']).stdout.trim()).toMatch(/^\d+$/)+ })++ it('creates a hidden macOS user in a group of its own, with a 0700 home the owner may read', () => {+ const made = helper(['ensure', '[email protected]'])+ expect(made.code).toBe(0)+ const answer = JSON.parse(made.stdout)+ expect(answer).toEqual({ user: USER, home: `${root}/${USER}`, workspace: `${root}/${USER}/work` })+ const said = made.stderr+ for (const line of [+ `+ 'dscl' '.' '-create' '/Groups/harnessguest' 'PrimaryGroupID' '600'`,+ `+ 'dscl' '.' '-create' '/Users/${USER}' 'PrimaryGroupID' '600'`,+ `+ 'dscl' '.' '-create' '/Users/${USER}' 'UserShell' '/bin/zsh'`,+ `+ 'dscl' '.' '-create' '/Users/${USER}' 'RealName' 'Harness guest [email protected]'`,+ `+ 'dscl' '.' '-create' '/Users/${USER}' 'NFSHomeDirectory' '${root}/${USER}'`,+ `+ 'dscl' '.' '-create' '/Users/${USER}' 'IsHidden' '1'`,+ `+ 'dscl' '.' '-create' '/Users/${USER}' 'Password' '*'`,+ `+ 'chmod' '700' '${root}/${USER}'`,+ `+ 'chown' '${USER}:harnessguest' '${root}/${USER}/work'`,+ ]) expect(said).toContain(line)+ // Never the staff group every standard account shares, which can enter the owner's home.+ expect(said).not.toContain("'PrimaryGroupID' '20'")+ expect(said).toMatch(/'chmod' '\+a' '[^']+ allow list,search,readattr,readextattr,readsecurity,read,file_inherit,directory_inherit'/)+ })++ it('creates a Linux system user with useradd, and a default ACL for the owner', () => {+ const made = helper(['ensure', '[email protected]'], 'Linux')+ expect(made.code).toBe(0)+ const bob = guestUserFor('[email protected]')+ expect(made.stderr).toContain(`+ 'groupadd' '-r' '-f' 'harnessguest'`)+ expect(made.stderr).toContain(`+ 'useradd' '-r' '-m' '-d' '${root}/${bob}' '-g' 'harnessguest' '-s' '/bin/bash' '-c' 'Harness guest [email protected]' '${bob}'`)+ expect(made.stderr).toMatch(/\+ 'setfacl' '-d' '-m' 'u:[^']+:rX'/)+ })++ it('refuses what is not an email address', () => {+ for (const bad of ['nope', 'a@b', '[email protected]', '[email protected]', 'a [email protected]', '"a"@x.com', '[email protected]']) {+ expect(helper(['ensure', bad]).code, bad).toBe(2)+ }+ expect(helper(['ensure']).code).toBe(2)+ expect(helper(['ensure', '[email protected]', '[email protected]']).code).toBe(2)+ })++ describe('run', () => {+ let work: string+ beforeAll(() => {+ work = join(root, USER, 'work')+ mkdirSync(join(work, 'project'), { recursive: true })+ symlinkSync('/', join(work, 'escape'))+ })++ it('runs the command as the guest, with only the allowed variables, in its folder', () => {+ const ran = helper(['run', USER, '--cwd', join(work, 'project'), '--pass', 'ANTHROPIC_AUTH_TOKEN', '--pass', 'HARNESS_HOOK_TOKEN',+ '--env', 'TERM=xterm-256color', '--', 'claude', '--resume', 'a b'], 'Darwin', { ANTHROPIC_AUTH_TOKEN: "relay token 'quoted'" })+ expect(ran).toMatchObject({ code: 0, stderr: '' })+ expect(ran.stdout.trim()).toBe(['+', ...[+ 'sudo', '-u', USER, '-H', 'env', '-i', `HOME=${root}/${USER}`, `USER=${USER}`, `LOGNAME=${USER}`, 'SHELL=/bin/zsh',+ `PATH=${root}/${USER}/.local/bin:${root}/${USER}/.opencode/bin:/usr/local/lib/harness/node/bin:/usr/local/bin:/usr/bin:/bin`,+ // (An unset --pass is left out.)+ "ANTHROPIC_AUTH_TOKEN=relay token 'quoted'", 'TERM=xterm-256color',+ '/bin/sh', '-c', 'cd "$1" || exit 1; shift; exec "$@"', 'harness-guest', join(work, 'project'),+ 'claude', '--resume', 'a b',+ ].map((word) => `'${word.replaceAll("'", `'\\''`)}'`)].join(' '))+ })++ it('refuses a variable the guest may not have, a folder outside its home, and an unknown or malformed user', () => {+ const refused = (args: string[], code = 2) => {+ const ran = helper(args)+ expect(ran.code, args.join(' ')).toBe(code)+ expect(ran.stdout).toBe('')+ return ran.stderr+ }+ expect(refused(['run', USER, '--cwd', work, '--env', 'PATH=/evil', '--', 'x'])).toContain('not allowed for a guest: PATH')+ expect(refused(['run', USER, '--cwd', work, '--pass', 'GRID_API_KEY', '--', 'x'])).toContain('not allowed for a guest: GRID_API_KEY')+ expect(refused(['run', USER, '--cwd', work, '--env', 'TERM', '--', 'x'])).toContain('not KEY=VALUE')+ expect(refused(['run', USER, '--cwd', '/tmp', '--', 'x'])).toContain('outside the guest\'s home and shared folders')+ // A folder of the owner's is the guest's only once it is shared with it.+ expect(refused(['run', USER, '--cwd', join(owner, 'docs'), '--', 'x'])).toContain('outside the guest\'s home and shared folders')+ expect(refused(['run', USER, '--cwd', join(work, 'escape'), '--', 'x'])).toContain('outside the guest\'s home')+ expect(refused(['run', USER, '--cwd', `${work}/../..`, '--', 'x'])).toContain('outside the guest\'s home')+ expect(refused(['run', USER, '--cwd', 'work', '--', 'x'])).toContain('not an absolute path')+ expect(refused(['run', USER, '--cwd', join(work, 'missing'), '--', 'x'])).toContain('no such folder')+ expect(refused(['run', USER, '--cwd', work, '--'])).toContain('nothing to run')+ expect(refused(['run', USER, '--', 'x'])).toContain('a --cwd is required')+ expect(refused(['run', USER, '--cwd', work, 'x'])).toContain('unexpected argument')+ expect(refused(['run', USER, '--cwd'])).toContain('usage')+ expect(refused(['run', 'hg_xyz', '--cwd', work, '--', 'x'])).toContain('not a guest user')+ expect(refused(['run', 'root', '--cwd', work, '--', 'x'])).toContain('not a guest user')+ expect(refused(['run', 'hg_000000000000', '--cwd', work, '--', 'x'], 3)).toContain('no such guest')+ })+ })++ describe('share', () => {+ const READ = 'list,search,readattr,readextattr,readsecurity,read,execute'+ const WRITE = `${READ},write,append,add_file,add_subdirectory,delete_child,delete,writeattr,writeextattr`+ const lines = (out: string) => out.trim().split('\n').filter(Boolean)+ const acl = (verb: '+a' | '-a', perms: string, dir: string) => `+ 'chmod' '-R' '${verb}' '${USER} allow ${perms},file_inherit,directory_inherit' '${dir}'`+ const search = (verb: '+a' | '-a', dir: string) => `+ 'chmod' '${verb}' '${USER} allow search' '${dir}'`+ // The folders above the owner's own that its tests' temporary folder sits in, closed or not, say nothing here.+ const ours = (out: string) => lines(out).filter((line) => !/allow search' '/.test(line) || line.includes(owner))++ it('gives the guest exactly the owner\'s folders it is given, and changes only what changed', () => {+ rmSync(join(state, USER), { force: true })+ const docs = join(owner, 'docs'), app = join(owner, 'code', 'app')+ const first = helper(['share', USER, '--read', docs, '--write', `${owner}/code/./app`])+ expect(first).toMatchObject({ code: 0, stderr: '' })+ // The folders and what is in them, and the one closed folder above them: the guest passes through it, never lists it.+ expect(ours(first.stdout)).toEqual([acl('+a', READ, docs), acl('+a', WRITE, app), search('+a', join(owner, 'code'))])+ expect(readFileSync(join(state, USER), 'utf8')).toBe(`read\t${docs}\nwrite\t${app}\n`)+ expect(helper(['shared', USER]).stdout).toBe(`read\t${docs}\nwrite\t${app}\n`)+ // The same again changes nothing: the daemon asks on every read of the sharing.+ expect(helper(['share', USER, '--read', docs, '--write', app]).stdout).toBe('')+ // A run may start in a shared folder.+ expect(helper(['run', USER, '--cwd', join(app, 'src'), '--', 'claude'])).toMatchObject({ code: 0, stderr: '' })++ // Read only now, and the documents no longer: each taken back as it was given.+ expect(ours(helper(['share', USER, '--read', app]).stdout)).toEqual([acl('-a', READ, docs), acl('-a', WRITE, app), acl('+a', READ, app)])+ // Nothing: the folder above goes with the last folder under it.+ expect(ours(helper(['share', USER]).stdout)).toEqual([acl('-a', READ, app), search('-a', join(owner, 'code'))])+ expect(helper(['shared', USER]).stdout).toBe('')+ expect(helper(['run', USER, '--cwd', app, '--', 'claude']).stderr).toContain('outside the guest\'s home and shared folders')+ })++ it('uses access lists on Linux: the folders, their defaults for what is made later, and passage above them', () => {+ rmSync(join(state, USER), { force: true })+ const app = join(owner, 'code', 'app')+ const out = lines(helper(['share', USER, '--write', app], 'Linux').stdout).filter((line) => !/'u:[^']+:x'/.test(line) || line.includes(owner))+ expect(out).toEqual([+ `+ 'setfacl' '-R' '-m' 'u:${USER}:rwX' '${app}'`,+ `+ 'find' '${app}' '-type' 'd' '-exec' 'setfacl' '-d' '-m' 'u:${USER}:rwX' '{}' '+'`,+ `+ 'setfacl' '-m' 'u:${USER}:x' '${join(owner, 'code')}'`,+ ])+ expect(lines(helper(['share', USER], 'Linux').stdout).filter((line) => !/'-x' 'u:[^']+' '\//.test(line) || line.includes(owner))).toEqual([+ `+ 'setfacl' '-R' '-x' 'u:${USER}' '${app}'`,+ `+ 'find' '${app}' '-type' 'd' '-exec' 'setfacl' '-d' '-x' 'u:${USER}' '{}' '+'`,+ `+ 'setfacl' '-x' 'u:${USER}' '${join(owner, 'code')}'`,+ ])+ })++ it('shares only the owner\'s own folders: never /, its whole home, a guest\'s home, or another account\'s', () => {+ const refused = (args: string[]) => {+ const ran = helper(['share', USER, ...args])+ expect(ran.code, args.join(' ')).toBe(2)+ expect(ran.stdout).toBe('')+ return ran.stderr+ }+ expect(refused(['--read', 'docs'])).toContain('not an absolute path')+ expect(refused(['--read', join(owner, 'missing')])).toContain('no such folder')+ expect(refused(['--read', '/'])).toContain('not a folder that can be shared: /')+ expect(refused(['--write', owner])).toContain('whole home cannot be shared')+ expect(refused(['--read', join(root, USER, 'work')])).toContain('a guest\'s home cannot be shared')+ expect(refused(['--read', '/usr/bin'])).toContain('not the owner\'s folder')+ expect(refused(['--read', join(owner, 'docs'), '--write', join(owner, 'docs')])).toContain('shared twice')+ expect(refused(['--read'])).toContain('usage')+ expect(refused(['docs'])).toContain('unexpected argument')+ // One folder a line in the helper's record: a tab or a newline in a name could forge another.+ expect(refused(['--read', `${owner}/doc\tx`])).toContain('not a folder that can be shared')+ expect(refused(['--read', `${owner}/doc\nx`])).toContain('not a folder that can be shared')+ expect(helper(['share']).code).toBe(2)+ expect(helper(['share', 'hg_bad']).code).toBe(2)+ expect(helper(['shared']).code).toBe(2)+ })+ })++ it('installs an engine as the guest, and only the engines it knows', () => {+ const claude = helper(['install', USER, 'claude'])+ expect(claude.code).toBe(0)+ expect(claude.stdout).toContain(`'sudo' '-u' '${USER}' '-H' 'env' '-i'`)+ expect(claude.stdout).toContain("'curl -fsSL https://claude.ai/install.sh | bash'")+ const codex = helper(['install', USER, 'codex'])+ expect(codex.stdout).toContain(`'/usr/local/lib/harness/node/bin/npm' 'install' '-g' '@openai/codex' '--prefix' '${root}/${USER}/.local'`)+ expect(helper(['install', USER, 'opencode']).stdout).toContain('https://opencode.ai/install')+ expect(helper(['install', USER, 'cursor']).code).toBe(2)+ expect(helper(['install', 'hg_bad', 'claude']).code).toBe(2)+ })++ it('removes a guest: its shares, its processes, its user and its home', () => {+ rmSync(join(state, USER), { force: true })+ helper(['share', USER, '--read', join(owner, 'docs')])+ const removed = helper(['remove', USER])+ expect(removed.code).toBe(0)+ expect(removed.stdout).toContain(`+ 'chmod' '-R' '-a' '${USER} allow`)+ expect(removed.stdout.indexOf("'chmod' '-R' '-a'")).toBeLessThan(removed.stdout.indexOf("'dscl' '.' '-delete'"))+ expect(removed.stdout).toContain(`+ 'pkill' '-KILL' '-u' '${USER}'`)+ expect(removed.stdout).toContain(`+ 'dscl' '.' '-delete' '/Users/${USER}'`)+ expect(removed.stdout).toContain(`+ 'rm' '-rf' '${root}/${USER}'`)+ expect(helper(['remove', USER], 'Linux').stdout).toContain(`+ 'userdel' '-r' '${USER}'`)+ })++ it('refuses an unknown command, and a platform it does not know', () => {+ expect(helper(['format-disk']).code).toBe(2)+ expect(helper([]).code).toBe(2)+ expect(helper(['version'], 'Windows').code).toBe(2)+ })+})++it('a GuestHelperError carries its code', () => {+ const error = new GuestHelperError('GUEST_INVALID', 'x')+ expect(error).toBeInstanceOf(Error)+ expect(error).toMatchObject({ name: 'GuestHelperError', code: 'GUEST_INVALID', message: 'x' })+})diff --git a/cli/src/lib/guestAccounts.ts b/cli/src/lib/guestAccounts.tsnew file mode 100644index 000000000..8c45aef2a--- /dev/null+++ b/cli/src/lib/guestAccounts.ts@@ -0,0 +1,234 @@+/**+ * A guest's OS account on this machine, through the guest helper (cli/assets/guest-helper/guest-helper.sh,+ * docs/plans/2026-10-19-guest-machine-sharing-plan.md): created on first use, and the command a tmux pane+ * runs to start a guest's harness as that account. Every call is `sudo -n <helper> …`, which the+ * owner's one-time install allowed (guestHelperInstall.ts); nothing here asks for a password.+ */+import { spawn } from 'node:child_process'+import { createHash } from 'node:crypto'+import { existsSync, readdirSync } from 'node:fs'+import { isAbsolute } from 'node:path'++export const GUEST_HELPER_PATH = '/usr/local/libexec/harness/guest-helper'++/** Where guests' homes are (the helper's HOME_ROOT): never the owner's own home or `staff`'s reach. */+export function guestHomeRoot(platform: NodeJS.Platform = process.platform): string {+ return platform === 'darwin' ? '/Users/Shared/HarnessGuests' : '/home/harness-guests'+}++/** A folder of the owner's shared with every guest (docs/plans/2026-10-19-guest-machine-sharing-plan.md,+ * "Shared folders"): read, or read and write. */+export interface SharedFolder { path: string; write: boolean }++/** The variables a guest's harness may be given: the helper's GUEST_ENV_KEYS and the sudoers drop-in's+ * env_keep, which a test keeps equal. `LC_*` is allowed beside them. */+export const GUEST_ENV_KEYS = [+ 'TERM', 'COLORTERM', 'LANG', 'ANTHROPIC_BASE_URL', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_MODEL',+ 'HARNESS_RELAY_TOKEN', 'HARNESS_HOOK_TOKEN', 'HARNESS_HOOK_URL', 'HARNESS_AGENT_ID', 'CODEX_HOME',+] as const++export type GuestEngine = 'claude' | 'codex' | 'opencode'+export const GUEST_ENGINES: readonly GuestEngine[] = ['claude', 'codex', 'opencode']++export type GuestErrorCode =+ | 'GUEST_HELPER_MISSING' // the helper is not installed: the owner has not turned sharing on here yet+ | 'GUEST_HELPER_NOT_AUTHORIZED' // sudo wants a password: the sudoers drop-in is missing or for another user+ | 'GUEST_INVALID' // the helper refused what it was given (a user, a folder, an email)+ | 'GUEST_ENV_NOT_ALLOWED' // a variable a guest's harness may not be given+ | 'GUEST_HELPER_FAILED' // anything else, in the helper's words++export class GuestHelperError extends Error {+ constructor(readonly code: GuestErrorCode, message: string) {+ super(message)+ this.name = 'GuestHelperError'+ }+}++export interface GuestAccount {+ /** The OS user, `hg_<12 hex>`. */+ user: string+ home: string+ /** Where a guest's harnesses start: `<home>/work`. */+ workspace: string+}++export interface GuestRunResult { code: number | null; stdout: string; stderr: string }+export interface GuestRunOptions {+ timeoutMs?: number+ /** The terminal's own stdin/stdout/stderr: a password prompt (Linux `sudo`) must reach the person. */+ interactive?: boolean+ /** Each line of stdout as it comes (an engine install's progress). */+ onLine?: (line: string) => void+}+export type GuestRunner = (command: string, args: readonly string[], options?: GuestRunOptions) => Promise<GuestRunResult>++/** Runs a command and collects its output; never rejects (a spawn error is `code: null`). */+export const runGuestCommand: GuestRunner = (command, args, options = {}) => new Promise((resolve) => {+ let stdout = '', stderr = '', pending = ''+ const child = spawn(command, [...args], { stdio: options.interactive ? 'inherit' : ['ignore', 'pipe', 'pipe'] })+ const timer = options.timeoutMs ? setTimeout(() => child.kill('SIGKILL'), options.timeoutMs) : null+ child.stdout?.on('data', (chunk: Buffer) => {+ const text = chunk.toString('utf8')+ stdout += text+ if (!options.onLine) return+ pending += text+ const lines = pending.split('\n')+ pending = lines.pop() ?? ''+ for (const line of lines) options.onLine(line)+ })+ child.stderr?.on('data', (chunk: Buffer) => { stderr += chunk.toString('utf8') })+ child.on('error', (error) => { if (timer) clearTimeout(timer); resolve({ code: null, stdout, stderr: stderr || error.message }) })+ child.on('close', (code) => {+ if (timer) clearTimeout(timer)+ if (pending && options.onLine) options.onLine(pending)+ resolve({ code, stdout, stderr })+ })+})++const GUEST_USER = /^hg_[0-9a-f]{12}$/++/** The OS user a guest gets: `hg_` and the first 12 hex of sha256(the lower-cased email). The helper+ * derives the same name itself; a test holds the two equal. */+export function guestUserFor(email: string): string {+ return `hg_${createHash('sha256').update(email.trim().toLowerCase()).digest('hex').slice(0, 12)}`+}++/** Where a guest's harnesses start unless it picks a shared folder: `<home>/work`, as the helper makes it. */+export function guestWorkspaceFor(email: string, platform: NodeJS.Platform = process.platform): string {+ return `${guestHomeRoot(platform)}/${guestUserFor(email)}/work`+}++export function isGuestUser(user: string): boolean {+ return GUEST_USER.test(user)+}++export function guestEnvAllowed(key: string): boolean {+ return (GUEST_ENV_KEYS as readonly string[]).includes(key) || /^LC_[A-Z_]+$/.test(key)+}++/**+ * What a tmux pane runs to start [argv] as the guest [user], in [cwd] (inside the guest's home), with+ * [env]: `argv` for the pane, `env` to set on it (`tmux new-session -e`). The values travel in the+ * environment and the helper takes them over with `--pass` (kept by the sudoers drop-in): a token on a+ * command line is readable by every account on the machine in `ps`.+ *+ * ⚠️ The pane's own working directory (tmux `-c`) must be one the owner can enter — the guest's home is+ * 0700 with an owner read ACL — and is not where the harness runs: the helper changes to [cwd] as the guest.+ */+export function guestRunCommand(+ user: string, cwd: string, env: Readonly<Record<string, string>>, argv: readonly string[], helperPath = GUEST_HELPER_PATH,+): { argv: string[]; env: Record<string, string> } {+ if (!isGuestUser(user)) throw new GuestHelperError('GUEST_INVALID', `not a guest user: ${user}`)+ if (!isAbsolute(cwd)) throw new GuestHelperError('GUEST_INVALID', `not an absolute folder: ${cwd}`)+ if (argv.length === 0) throw new GuestHelperError('GUEST_INVALID', 'nothing to run')+ const pass: string[] = []+ const paneEnv: Record<string, string> = {}+ for (const [key, value] of Object.entries(env)) {+ if (!guestEnvAllowed(key)) throw new GuestHelperError('GUEST_ENV_NOT_ALLOWED', `not allowed for a guest: ${key}`)+ pass.push('--pass', key)+ paneEnv[key] = value+ }+ return { argv: ['sudo', '-n', helperPath, 'run', user, '--cwd', cwd, ...pass, '--', ...argv], env: paneEnv }+}++/** The helper's answer as a GuestHelperError, by what sudo and the helper say. */+export function guestHelperFailure(result: GuestRunResult): GuestHelperError {+ const said = result.stderr.trim() || result.stdout.trim()+ if (/a password is required|a terminal is required|not allowed to execute|may not run sudo|no tty present/i.test(said)) {+ return new GuestHelperError('GUEST_HELPER_NOT_AUTHORIZED', 'This computer has not allowed Harness to run guests yet. Turn sharing on again to allow it.')+ }+ if (result.code === null || /command not found|No such file or directory/.test(said)) {+ return new GuestHelperError('GUEST_HELPER_MISSING', 'The guest helper is not installed on this computer.')+ }+ const message = said.replace(/^guest-helper: /, '') || `The guest helper failed (${result.code}).`+ // The helper exits 2 for a refused argument and 3 for a guest that does not exist.+ return new GuestHelperError(result.code === 2 || result.code === 3 ? 'GUEST_INVALID' : 'GUEST_HELPER_FAILED', message)+}++export interface GuestAccountsDeps {+ runner?: GuestRunner+ helperPath?: string+ /** Whether the helper is installed (a file check; no sudo). */+ installed?: (path: string) => boolean+ /** The names in the guests' home root (it is 0755: no sudo). */+ homes?: () => string[]+}++export interface GuestAccounts {+ /** The guest's account, created on first use; one call per email at a time. */+ ensureGuest(email: string): Promise<GuestAccount>+ /** Installs an engine into the guest's home, as the guest; [onLine] hears its progress. */+ installGuestEngine(user: string, engine: GuestEngine, onLine?: (line: string) => void): Promise<void>+ /** Deletes the guest's account, processes and files: sharing with them has ended. */+ removeGuest(user: string): Promise<void>+ /** Gives the guest exactly these of the owner's folders. The helper changes only what changed, so asking+ * again with the same folders costs one `sudo -n`. */+ shareFolders(user: string, folders: readonly SharedFolder[]): Promise<void>+ /** The guests that have an account here, by user. */+ guests(): string[]+ runCommand: typeof guestRunCommand+}++export function createGuestAccounts(deps: GuestAccountsDeps = {}): GuestAccounts {+ const runner = deps.runner ?? runGuestCommand+ const helperPath = deps.helperPath ?? GUEST_HELPER_PATH+ const installed = deps.installed ?? existsSync+ const homes = deps.homes ?? (() => { try { return readdirSync(guestHomeRoot()) } catch { return [] } })+ const accounts = new Map<string, Promise<GuestAccount>>()++ const helper = async (args: string[], options?: GuestRunOptions): Promise<string> => {+ if (!installed(helperPath)) throw new GuestHelperError('GUEST_HELPER_MISSING', 'The guest helper is not installed on this computer.')+ const result = await runner('sudo', ['-n', helperPath, ...args], options)+ if (result.code !== 0) throw guestHelperFailure(result)+ return result.stdout+ }++ const ensure = async (email: string): Promise<GuestAccount> => {+ const out = await helper(['ensure', email], { timeoutMs: 60_000 })+ let parsed: unknown+ try {+ parsed = JSON.parse(out.trim().split('\n').pop() ?? '')+ } catch {+ throw new GuestHelperError('GUEST_HELPER_FAILED', 'The guest helper answered something unexpected.')+ }+ const account = parsed as Partial<GuestAccount>+ if (typeof account.user !== 'string' || typeof account.home !== 'string' || typeof account.workspace !== 'string'+ || account.user !== guestUserFor(email) || !account.workspace.startsWith(`${account.home}/`)) {+ throw new GuestHelperError('GUEST_HELPER_FAILED', 'The guest helper answered something unexpected.')+ }+ return { user: account.user, home: account.home, workspace: account.workspace }+ }++ return {+ ensureGuest(email) {+ const key = email.trim().toLowerCase()+ const known = accounts.get(key)+ if (known) return known+ const pending = ensure(key)+ accounts.set(key, pending)+ // A failure is not remembered: the next call asks again (the helper may be installed by then).+ pending.catch(() => { if (accounts.get(key) === pending) accounts.delete(key) })+ return pending+ },+ async installGuestEngine(user, engine, onLine) {+ if (!isGuestUser(user)) throw new GuestHelperError('GUEST_INVALID', `not a guest user: ${user}`)+ if (!GUEST_ENGINES.includes(engine)) throw new GuestHelperError('GUEST_INVALID', `not an engine a guest can install: ${engine}`)+ await helper(['install', user, engine], { timeoutMs: 10 * 60_000, ...(onLine ? { onLine } : {}) })+ },+ async removeGuest(user) {+ if (!isGuestUser(user)) throw new GuestHelperError('GUEST_INVALID', `not a guest user: ${user}`)+ for (const [email, pending] of accounts) {+ const account = await pending.catch(() => null)+ if (account?.user === user) accounts.delete(email)+ }+ await helper(['remove', user], { timeoutMs: 60_000 })+ },+ async shareFolders(user, folders) {+ if (!isGuestUser(user)) throw new GuestHelperError('GUEST_INVALID', `not a guest user: ${user}`)+ // A first share of a large folder sets an entry on everything in it: minutes, not seconds.+ await helper(['share', user, ...folders.flatMap((f) => [f.write ? '--write' : '--read', f.path])], { timeoutMs: 10 * 60_000 })+ },+ guests: () => homes().filter(isGuestUser).sort(),+ runCommand: (user, cwd, env, argv) => guestRunCommand(user, cwd, env, argv, helperPath),+ }+}diff --git a/cli/src/lib/guestHelperAssets.ts b/cli/src/lib/guestHelperAssets.tsnew file mode 100644index 000000000..49bceceb3--- /dev/null+++ b/cli/src/lib/guestHelperAssets.ts@@ -0,0 +1,27 @@+import { readFileSync } from 'node:fs'++declare const __GUEST_HELPER__: string+declare const __GUEST_SUDOERS__: string++// The release bundle carries both files inside cli.js (build-bundle.mjs `define`): the installed CLI is+// cli.js and notify.mjs alone, with nothing beside them to read. A dev checkout and the tests read the+// files themselves, from cli/assets/guest-helper (src/lib/ and dist/lib/ are both two levels down).+function asset(bundled: string | undefined, name: string): string {+ return bundled ?? readFileSync(new URL(`../../assets/guest-helper/${name}`, import.meta.url), 'utf8')+}++/** The guest helper's script (cli/assets/guest-helper/guest-helper.sh). */+export function guestHelperScript(): string {+ return asset(typeof __GUEST_HELPER__ === 'string' ? __GUEST_HELPER__ : undefined, 'guest-helper.sh')+}++/** The sudoers drop-in's template, `{{OWNER}}` still in it (cli/assets/guest-helper/sudoers). */+export function guestSudoersTemplate(): string {+ return asset(typeof __GUEST_SUDOERS__ === 'string' ? __GUEST_SUDOERS__ : undefined, 'sudoers')+}++/** The helper script's own version (its `HELPER_VERSION=`), or null when it names none. */+export function helperScriptVersion(script: string): number | null {+ const match = /^HELPER_VERSION=(\d+)$/m.exec(script)+ return match ? Number(match[1]) : null+}diff --git a/cli/src/lib/guestHelperInstall.spec.ts b/cli/src/lib/guestHelperInstall.spec.tsnew file mode 100644index 000000000..f9582a136--- /dev/null+++ b/cli/src/lib/guestHelperInstall.spec.ts@@ -0,0 +1,183 @@+import { spawnSync } from 'node:child_process'+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, describe, expect, it, vi } from 'vitest'++import { GUEST_HELPER_PATH, type GuestRunner } from './guestAccounts.js'+import { guestHelperScript, helperScriptVersion } from './guestHelperAssets.js'+import {+ adminAppleScript, buildInstallScript, GUEST_HELPER_PROMPT, GUEST_HELPER_VERSION, GUEST_HOOK_DIR, GUEST_NODE_DIR,+ GUEST_SUDOERS_PATH, guestHelperStatus, installGuestHelper, sudoersFor,+} from './guestHelperInstall.js'++const temps: string[] = []+const temp = () => { const dir = mkdtempSync(join(tmpdir(), 'guest-install-')); temps.push(dir); return dir }+afterEach(() => { for (const dir of temps.splice(0)) rmSync(dir, { recursive: true, force: true }) })++describe('the sudoers drop-in', () => {+ it('lets the owner, and only the owner, run the helper without a password', () => {+ const drop = sudoersFor('ann')+ expect(drop).toContain(`ann ALL=(root) NOPASSWD: ${GUEST_HELPER_PATH} *`)+ expect(drop).toContain(`Defaults!${GUEST_HELPER_PATH} env_keep += "`)+ expect(drop).not.toContain('{{OWNER}}')+ for (const bad of ['root', 'hg_0123456789ab', 'ann ALL=(ALL) ALL', '', 'a'.repeat(40), '-x']) {+ expect(() => sudoersFor(bad), bad).toThrow()+ }+ })+})++describe('the install script', () => {+ const stageDir = '/tmp/harness-guest-AbC'++ it('checks the drop-in, puts the helper in place before the drop-in that names it, and refuses unsafe parents', () => {+ const script = buildInstallScript({ stageDir, nodeRuntimeDir: null, hookScript: false })+ const at = (text: string) => { const index = script.indexOf(text); expect(index, text).toBeGreaterThanOrEqual(0); return index }+ const check = at(`visudo -cf '${stageDir}'/sudoers`)+ const helper = at(`install -o 0 -g 0 -m 0755 '${stageDir}'/guest-helper '${GUEST_HELPER_PATH}'`)+ const drop = at(`install -o 0 -g 0 -m 0440 '${stageDir}'/sudoers '${GUEST_SUDOERS_PATH}'`)+ expect(check).toBeLessThan(helper)+ expect(helper).toBeLessThan(drop)+ expect(at('for dir in / /usr /usr/local /usr/local/libexec /usr/local/lib /etc /etc/sudoers.d; do owned_by_root "$dir"; done')).toBeLessThan(helper)+ expect(script).toContain('includedir')+ expect(script).not.toContain(GUEST_NODE_DIR)+ expect(script).not.toContain('notify.mjs')+ expect(script.startsWith('#!/bin/sh\n')).toBe(true)+ })++ it('copies the Node runtime and the hook script for guests\' engines when there are some', () => {+ const script = buildInstallScript({ stageDir, nodeRuntimeDir: "/Users/o'neil/.harness/runtime/node-v22", hookScript: true })+ expect(script).toContain(`for part in '/Users/o'\\''neil/.harness/runtime/node-v22/bin' '/Users/o'\\''neil/.harness/runtime/node-v22/lib' `+ + `'/Users/o'\\''neil/.harness/runtime/node-v22/include'; do`)+ expect(script).not.toContain('node-v22/libexec')+ expect(script).toContain(`chmod -R a+rX,go-w '${GUEST_NODE_DIR}.new'`)+ expect(script).toContain(`mv '${GUEST_NODE_DIR}.new' '${GUEST_NODE_DIR}'`)+ expect(script).toContain(`install -o 0 -g 0 -m 0644 '${stageDir}'/notify.mjs '${GUEST_HOOK_DIR}/notify.mjs'`)+ // The drop-in last, still.+ expect(script.trimEnd().split('\n').pop()).toBe(`install -o 0 -g 0 -m 0440 '${stageDir}'/sudoers '${GUEST_SUDOERS_PATH}'`)+ })++ it('copies node and npm for guests, never the daemon\'s own process images', () => {+ const dir = temp()+ const runtime = join(dir, 'node-v22')+ for (const [path, text] of [['bin/node', 'node'], ['lib/node_modules/npm/index.js', 'npm'], ['include/node/v8.h', 'h'], ['libexec/harnessd/harnessd-core', 'big']]) {+ mkdirSync(join(runtime, path, '..'), { recursive: true })+ writeFileSync(join(runtime, path), text)+ }+ const dest = join(dir, 'guest-node')+ const copy = buildInstallScript({ stageDir: dir, nodeRuntimeDir: runtime, hookScript: false }).split('\n')+ .filter((line) => line.startsWith('mkdir -p') && line.includes('.new') || line.startsWith('for part in'))+ .map((line) => line.replaceAll(`'${GUEST_NODE_DIR}.new'`, `'${dest}'`)).join('\n')+ expect(spawnSync('sh', ['-c', copy]).status).toBe(0)+ expect(readdirSync(dest).sort()).toEqual(['bin', 'include', 'lib'])+ expect(readFileSync(join(dest, 'lib/node_modules/npm/index.js'), 'utf8')).toBe('npm')+ // A runtime with no headers still copies the rest.+ rmSync(join(runtime, 'include'), { recursive: true })+ rmSync(dest, { recursive: true })+ expect(spawnSync('sh', ['-c', copy]).status).toBe(0)+ expect(readdirSync(dest).sort()).toEqual(['bin', 'lib'])+ })++ it('parses as a shell script', () => {+ const dir = temp()+ const file = join(dir, 'install.sh')+ writeFileSync(file, buildInstallScript({ stageDir: "/tmp/a dir'with quote", nodeRuntimeDir: '/x/node', hookScript: true }))+ expect(spawnSync('sh', ['-n', file]).status).toBe(0)+ })++ it('quotes the script\'s path and the prompt for AppleScript', () => {+ expect(adminAppleScript('/tmp/a"b\\c/install.sh', 'Say "yes"'))+ .toBe('do shell script "/bin/sh " & quoted form of "/tmp/a\\"b\\\\c/install.sh" with prompt "Say \\"yes\\"" with administrator privileges')+ })+})++describe('installing the helper', () => {+ const ok = { code: 0, stdout: '', stderr: '' }++ it('asks macOS once for an admin, with every file staged privately, and cleans up', async () => {+ const hook = join(temp(), 'notify.mjs')+ writeFileSync(hook, '// hook')+ let staged = ''+ const runner = vi.fn<GuestRunner>(async (command, args) => {+ expect(command).toBe('osascript')+ expect(args[0]).toBe('-e')+ expect(args[1]).toContain('with administrator privileges')+ expect(args[1]).toContain(GUEST_HELPER_PROMPT)+ const script = /quoted form of "([^"]+)"/.exec(args[1])![1]+ staged = join(script, '..')+ expect(statSync(staged).mode & 0o777).toBe(0o700)+ expect(readFileSync(join(staged, 'guest-helper'), 'utf8')).toBe(guestHelperScript())+ expect(readFileSync(join(staged, 'sudoers'), 'utf8')).toContain('ann ALL=(root) NOPASSWD:')+ expect(statSync(join(staged, 'sudoers')).mode & 0o777).toBe(0o600)+ expect(readFileSync(join(staged, 'notify.mjs'), 'utf8')).toBe('// hook')+ expect(readFileSync(script, 'utf8')).toContain('/usr/local/lib/harness/node')+ return ok+ })+ const result = await installGuestHelper({ owner: 'ann', runner, platform: 'darwin', nodeRuntimeDir: '/runtime/node', hookScript: hook })+ expect(result).toEqual({ ok: true })+ expect(runner).toHaveBeenCalledTimes(1)+ expect(existsSync(staged)).toBe(false)+ })++ it('tells a cancelled prompt from a failure, and says what failed', async () => {+ const cancelled = vi.fn<GuestRunner>(async () => ({ code: 1, stdout: '', stderr: '0:200: execution error: User canceled. (-128)' }))+ expect(await installGuestHelper({ owner: 'ann', runner: cancelled, platform: 'darwin', nodeRuntimeDir: null, hookScript: null }))+ .toMatchObject({ ok: false, code: 'CANCELLED' })+ const failed = vi.fn<GuestRunner>(async () => ({ code: 1, stdout: '', stderr: '0:1: execution error: harness: /usr/local is not owned by root (6)' }))+ expect(await installGuestHelper({ owner: 'ann', runner: failed, platform: 'darwin', nodeRuntimeDir: null, hookScript: null }))+ .toEqual({ ok: false, code: 'FAILED', message: '/usr/local is not owned by root (6)' })+ const silent = vi.fn<GuestRunner>(async () => ({ code: 1, stdout: '', stderr: '' }))+ expect(await installGuestHelper({ owner: 'ann', runner: silent, platform: 'darwin', nodeRuntimeDir: null, hookScript: null }))+ .toEqual({ ok: false, code: 'FAILED', message: 'The guest helper could not be installed.' })+ })++ it('uses pkexec on a Linux desktop and sudo in a terminal', async () => {+ const runner = vi.fn<GuestRunner>(async () => ok)+ expect(await installGuestHelper({ owner: 'ann', runner, platform: 'linux', graphical: true, nodeRuntimeDir: null, hookScript: null })).toEqual({ ok: true })+ expect(runner.mock.calls[0][0]).toBe('pkexec')+ expect(runner.mock.calls[0][1][0]).toBe('/bin/sh')+ await installGuestHelper({ owner: 'ann', runner, platform: 'linux', graphical: false, nodeRuntimeDir: null, hookScript: null })+ expect(runner.mock.calls[1][0]).toBe('sudo')+ expect(runner.mock.calls[1][2]).toMatchObject({ interactive: true })+ const dismissed = vi.fn<GuestRunner>(async () => ({ code: 126, stdout: '', stderr: '' }))+ expect(await installGuestHelper({ owner: 'ann', runner: dismissed, platform: 'linux', graphical: true, nodeRuntimeDir: null, hookScript: null }))+ .toMatchObject({ ok: false, code: 'CANCELLED' })+ })++ it('refuses a platform with no sudo, and an owner name it cannot write into the drop-in', async () => {+ const runner = vi.fn<GuestRunner>(async () => ok)+ expect(await installGuestHelper({ owner: 'ann', runner, platform: 'win32' })).toMatchObject({ ok: false, code: 'UNSUPPORTED' })+ expect(await installGuestHelper({ owner: 'root', runner, platform: 'darwin' })).toMatchObject({ ok: false, code: 'FAILED' })+ expect(runner).not.toHaveBeenCalled()+ })+})++describe('the helper\'s status', () => {+ const current = guestHelperScript()++ it('is the version the shipped script names', () => {+ expect(GUEST_HELPER_VERSION).toBe(helperScriptVersion(current))+ expect(GUEST_HELPER_VERSION).toBeGreaterThanOrEqual(1)+ expect(helperScriptVersion('#!/bin/sh\necho hi\n')).toBeNull()+ })++ it('is missing, outdated, not allowed, or ready', async () => {+ const runner = vi.fn<GuestRunner>(async () => ({ code: 0, stdout: '', stderr: '' }))+ expect(await guestHelperStatus({ read: () => null, runner })).toEqual({ state: 'missing', version: null })+ expect(await guestHelperStatus({ read: () => 'HELPER_VERSION=0\n', runner })).toEqual({ state: 'outdated', version: 0 })+ expect(await guestHelperStatus({ read: () => '#!/bin/sh\n', runner })).toEqual({ state: 'outdated', version: null })+ expect(runner).not.toHaveBeenCalled()+ expect(await guestHelperStatus({ read: () => current, runner })).toEqual({ state: 'ready', version: GUEST_HELPER_VERSION })+ expect(runner).toHaveBeenCalledWith('sudo', ['-n', '-l', GUEST_HELPER_PATH], { timeoutMs: 10_000 })+ const asks = vi.fn<GuestRunner>(async () => ({ code: 1, stdout: '', stderr: 'sudo: a password is required' }))+ expect(await guestHelperStatus({ read: () => current, runner: asks, helperPath: '/opt/h' })).toEqual({ state: 'not-authorized', version: GUEST_HELPER_VERSION })+ expect(asks).toHaveBeenCalledWith('sudo', ['-n', '-l', '/opt/h'], { timeoutMs: 10_000 })+ })++ it('reads an installed helper from disk without sudo', async () => {+ const file = join(temp(), 'guest-helper')+ writeFileSync(file, 'HELPER_VERSION=0\n')+ expect(await guestHelperStatus({ helperPath: file, runner: vi.fn<GuestRunner>() })).toEqual({ state: 'outdated', version: 0 })+ expect(await guestHelperStatus({ helperPath: join(temp(), 'none'), runner: vi.fn<GuestRunner>() })).toEqual({ state: 'missing', version: null })+ })+})diff --git a/cli/src/lib/guestHelperInstall.ts b/cli/src/lib/guestHelperInstall.tsnew file mode 100644index 000000000..8e7eddafe--- /dev/null+++ b/cli/src/lib/guestHelperInstall.ts@@ -0,0 +1,212 @@+/**+ * The owner's one-time step that lets guests run here (docs/plans/2026-10-19-guest-machine-sharing-plan.md):+ * one admin prompt installs the guest helper, the sudoers drop-in that lets the owner's daemon run it+ * without a password, a Node runtime guests' engines can use, and the hook script their engines report+ * through. Guests are never prompted.+ *+ * One privileged script does all of it, staged in a private temp folder and run once: on macOS through+ * `osascript … with administrator privileges` (the system's own password or Touch ID sheet), on Linux+ * through `pkexec`, else `sudo` in the terminal. It is idempotent: running it again replaces each piece.+ */+import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'+import { tmpdir, userInfo } from 'node:os'+import { dirname, join, sep } from 'node:path'++import { env } from '../config/env.js'+import { HOOK_SCRIPT } from '../engines/kit/notifyHooks.js'+import { GUEST_HELPER_PATH, runGuestCommand, type GuestRunner } from './guestAccounts.js'+import { guestHelperScript, guestSudoersTemplate, helperScriptVersion } from './guestHelperAssets.js'+import { managedNodePath } from './nodeRuntime.js'++export const GUEST_SUDOERS_PATH = '/etc/sudoers.d/harness-guests'+export const GUEST_NODE_DIR = '/usr/local/lib/harness/node'+export const GUEST_HOOK_DIR = '/usr/local/lib/harness/hook'++/** The helper version this CLI ships: an installed one older than it is installed again. */+export const GUEST_HELPER_VERSION = helperScriptVersion(guestHelperScript()) ?? 0++const OWNER = /^[A-Za-z_][A-Za-z0-9_.-]{0,31}$/++/** The sudoers drop-in for [owner]. */+export function sudoersFor(owner: string): string {+ if (!OWNER.test(owner) || owner === 'root' || owner.startsWith('hg_')) throw new Error(`not an owner account: ${owner}`)+ return guestSudoersTemplate().replaceAll('{{OWNER}}', owner)+}++/** POSIX single quotes. */+function sh(word: string): string {+ return `'${word.replaceAll("'", `'\\''`)}'`+}++/** The managed Node runtime's folder (`~/.harness/runtime/node-…`), or null on a machine with none. */+export function managedNodeRuntimeDir(): string | null {+ const node = managedNodePath()+ if (!node.startsWith(env.ADAPTER_RUNTIME_DIR + sep)) return null+ return dirname(dirname(node))+}++export interface InstallScriptInput {+ /** The private folder holding `guest-helper`, `sudoers` and, when there is one, `notify.mjs`. */+ stageDir: string+ /** The Node runtime to copy for guests' engines; null leaves the installed one as it is. */+ nodeRuntimeDir: string | null+ hookScript: boolean+}++/** The one script run as root. Every target's parent must be root's alone: a helper sudo runs without a+ * password, in a folder the owner (or anyone) could write, would be root for whatever replaced it. */+export function buildInstallScript(input: InstallScriptInput): string {+ const stage = sh(input.stageDir)+ const lines = [+ '#!/bin/sh',+ '# Harness guest helper install (cli/src/lib/guestHelperInstall.ts), run once as root.',+ 'set -eu',+ 'die() { printf "harness: %s\\n" "$1" >&2; exit "${2:-1}"; }',+ // A parent another account could write is refused, not repaired: chown-ing a system folder is not ours.+ 'owned_by_root() {',+ ' [ -e "$1" ] || return 0',+ // (GNU `stat -f` is the file system's status and answers anything: the platform decides.)+ ' if [ "$(uname -s)" = Darwin ]; then uid=$(stat -f %u "$1"); mode=$(stat -f %Lp "$1")',+ ' else uid=$(stat -c %u "$1"); mode=$(stat -c %a "$1"); fi',+ ' [ "$uid" = 0 ] || die "$1 is not owned by root" 6',+ ' [ $((0$mode & 022)) -eq 0 ] || die "$1 can be written by others" 6',+ '}',+ 'for dir in / /usr /usr/local /usr/local/libexec /usr/local/lib /etc /etc/sudoers.d; do owned_by_root "$dir"; done',+ // sudo must read drop-ins; editing /etc/sudoers itself is not ours to do either.+ "grep -Eq '^[#@]includedir[[:space:]]+(/private)?/etc/sudoers\\.d' /etc/sudoers || die 'sudo does not read /etc/sudoers.d on this computer' 5",+ `visudo -cf ${stage}/sudoers >/dev/null || die 'the sudoers drop-in is not valid' 5`,+ `mkdir -p ${sh(dirname(GUEST_HELPER_PATH))} ${sh(GUEST_HOOK_DIR)}`,+ `chown 0:0 ${sh(dirname(GUEST_HELPER_PATH))} ${sh(dirname(GUEST_HOOK_DIR))} ${sh(GUEST_HOOK_DIR)}`,+ `chmod 755 ${sh(dirname(GUEST_HELPER_PATH))} ${sh(dirname(GUEST_HOOK_DIR))} ${sh(GUEST_HOOK_DIR)}`,+ // The helper before the drop-in that names it: sudo never allows a path that is not in place yet.+ `install -o 0 -g 0 -m 0755 ${stage}/guest-helper ${sh(GUEST_HELPER_PATH)}`,+ ]+ if (input.nodeRuntimeDir) {+ const next = sh(`${GUEST_NODE_DIR}.new`)+ // Node and npm, which a guest's engine installs need: `bin`, `lib` and `include`, about 190 MB. Never the+ // runtime's `libexec`, the daemon's own process images (a renamed node per process, 1.2 GB on 2026-10-19).+ const parts = ['bin', 'lib', 'include'].map((part) => sh(`${input.nodeRuntimeDir}/${part}`)).join(' ')+ lines.push(+ `rm -rf ${next}`,+ `mkdir -p ${next}`,+ `for part in ${parts}; do [ ! -e "$part" ] || cp -R "$part" ${next}/; done`,+ `chown -R 0:0 ${next}`,+ `chmod -R a+rX,go-w ${next}`,+ `rm -rf ${sh(GUEST_NODE_DIR)}`,+ `mv ${next} ${sh(GUEST_NODE_DIR)}`,+ )+ }+ if (input.hookScript) lines.push(`install -o 0 -g 0 -m 0644 ${stage}/notify.mjs ${sh(`${GUEST_HOOK_DIR}/notify.mjs`)}`)+ lines.push(`install -o 0 -g 0 -m 0440 ${stage}/sudoers ${sh(GUEST_SUDOERS_PATH)}`, '')+ return lines.join('\n')+}++/** The osascript line that runs [scriptPath] as root behind the system's admin prompt. */+export function adminAppleScript(scriptPath: string, prompt: string): string {+ const quote = (text: string) => `"${text.replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"`+ return `do shell script "/bin/sh " & quoted form of ${quote(scriptPath)} with prompt ${quote(prompt)} with administrator privileges`+}++export const GUEST_HELPER_PROMPT =+ 'Harness wants to let people you share this computer with run their harnesses as separate accounts, so they cannot see your files.'++export type GuestHelperInstallResult =+ | { ok: true }+ | { ok: false; code: 'CANCELLED' | 'FAILED' | 'UNSUPPORTED'; message: string }++export interface GuestHelperInstallOptions {+ /** The account the drop-in allows: this one, by default. */+ owner?: string+ runner?: GuestRunner+ platform?: NodeJS.Platform+ nodeRuntimeDir?: string | null+ hookScript?: string | null+ /** Whether `pkexec` and a desktop session are there (Linux). */+ graphical?: boolean+}++export async function installGuestHelper(options: GuestHelperInstallOptions = {}): Promise<GuestHelperInstallResult> {+ const platform = options.platform ?? process.platform+ if (platform !== 'darwin' && platform !== 'linux') {+ return { ok: false, code: 'UNSUPPORTED', message: 'Sharing a computer with guests needs macOS or Linux.' }+ }+ const runner = options.runner ?? runGuestCommand+ const owner = options.owner ?? userInfo().username+ let sudoers: string+ try {+ sudoers = sudoersFor(owner)+ } catch (error) {+ return { ok: false, code: 'FAILED', message: (error as Error).message }+ }+ const nodeRuntimeDir = options.nodeRuntimeDir === undefined ? managedNodeRuntimeDir() : options.nodeRuntimeDir+ const hookScript = options.hookScript === undefined ? (existsSync(HOOK_SCRIPT) ? HOOK_SCRIPT : null) : options.hookScript++ // Private to this account until root copies it (mkdtemp is 0700): nobody else can swap a file in between.+ const stageDir = mkdtempSync(join(tmpdir(), 'harness-guest-'))+ try {+ writeFileSync(join(stageDir, 'guest-helper'), guestHelperScript(), { mode: 0o700 })+ writeFileSync(join(stageDir, 'sudoers'), sudoers, { mode: 0o600 })+ if (hookScript) writeFileSync(join(stageDir, 'notify.mjs'), readFileSync(hookScript), { mode: 0o600 })+ const script = join(stageDir, 'install.sh')+ writeFileSync(script, buildInstallScript({ stageDir, nodeRuntimeDir, hookScript: !!hookScript }), { mode: 0o700 })+ chmodSync(stageDir, 0o700)++ let result+ if (platform === 'darwin') {+ result = await runner('osascript', ['-e', adminAppleScript(script, GUEST_HELPER_PROMPT)], { timeoutMs: 10 * 60_000 })+ // -128 is the sheet's Cancel.+ if (result.code !== 0 && /-128|User canceled/i.test(result.stderr)) {+ return { ok: false, code: 'CANCELLED', message: 'Sharing was not turned on: the admin prompt was cancelled.' }+ }+ } else {+ const graphical = options.graphical ?? (existsSync('/usr/bin/pkexec') && !!(process.env.DISPLAY || process.env.WAYLAND_DISPLAY))+ result = graphical+ ? await runner('pkexec', ['/bin/sh', script], { timeoutMs: 10 * 60_000 })+ : await runner('sudo', ['/bin/sh', script], { interactive: true, timeoutMs: 10 * 60_000 })+ // pkexec: 126 is a dismissed dialog, 127 a refused authorization.+ if (graphical && (result.code === 126 || result.code === 127)) {+ return { ok: false, code: 'CANCELLED', message: 'Sharing was not turned on: the admin prompt was cancelled.' }+ }+ }+ if (result.code !== 0) {+ const said = result.stderr.trim().split('\n').pop()?.replace(/^.*harness: /, '') ?? ''+ return { ok: false, code: 'FAILED', message: said || 'The guest helper could not be installed.' }+ }+ return { ok: true }+ } finally {+ rmSync(stageDir, { recursive: true, force: true })+ }+}++export type GuestHelperState =+ | 'ready' // installed, current, and this account may run it without a password+ | 'missing'+ | 'outdated' // older than this CLI's: install again+ | 'not-authorized' // installed, but sudo asks this account for a password++export interface GuestHelperStatus { state: GuestHelperState; version: number | null }++export interface GuestHelperStatusDeps {+ runner?: GuestRunner+ helperPath?: string+ /** The installed helper's text, or null when there is none (no sudo needed: it is 0755). */+ read?: (path: string) => string | null+}++export async function guestHelperStatus(deps: GuestHelperStatusDeps = {}): Promise<GuestHelperStatus> {+ const helperPath = deps.helperPath ?? GUEST_HELPER_PATH+ const read = deps.read ?? ((path: string) => {+ try {+ return statSync(path).isFile() ? readFileSync(path, 'utf8') : null+ } catch {+ return null+ }+ })+ const text = read(helperPath)+ if (text === null) return { state: 'missing', version: null }+ const version = helperScriptVersion(text)+ if (version === null || version < GUEST_HELPER_VERSION) return { state: 'outdated', version }+ // `sudo -n -l <command>` answers 0 only when this account may run it without a password.+ const allowed = await (deps.runner ?? runGuestCommand)('sudo', ['-n', '-l', helperPath], { timeoutMs: 10_000 })+ return { state: allowed.code === 0 ? 'ready' : 'not-authorized', version }+}diff --git a/cli/src/lib/guestPaneCommand.spec.ts b/cli/src/lib/guestPaneCommand.spec.tsnew file mode 100644index 000000000..654aec5f8--- /dev/null+++ b/cli/src/lib/guestPaneCommand.spec.ts@@ -0,0 +1,112 @@+import { execFileSync } from 'node:child_process'+import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, describe, expect, it } from 'vitest'+import { GUEST_LAUNCH_ENGINES, GUEST_PANE_BOOTSTRAP, guestPaneCommand } from './guestPaneCommand.js'++const account = { user: 'hg_0123456789ab', home: '/Users/Shared/HarnessGuests/hg_0123456789ab', workspace: '/Users/Shared/HarnessGuests/hg_0123456789ab/work' }+const relay = 'http://127.0.0.1:41234'++describe('a guest\'s pane', () => {+ it('runs Claude Code as the guest, on the owner\'s subscription through the relay, with the token only in the environment', () => {+ const { argv, env } = guestPaneCommand({ account, engine: 'claude', relayUrl: relay, token: 'guest-token', bypassPermission: true, lang: 'vi_VN.UTF-8' })+ expect(argv.slice(0, 8)).toEqual(['/bin/sh', '-c', GUEST_PANE_BOOTSTRAP, 'harness-guest', '/usr/local/libexec/harness/guest-helper', account.user, account.workspace, 'claude'])+ expect(argv.slice(8)).toEqual(['sudo', '-n', '/usr/local/libexec/harness/guest-helper', 'run', account.user, '--cwd', account.workspace,+ '--pass', 'TERM', '--pass', 'COLORTERM', '--pass', 'LANG', '--pass', 'ANTHROPIC_BASE_URL', '--pass', 'ANTHROPIC_AUTH_TOKEN',+ '--', 'claude', '--dangerously-skip-permissions'])+ expect(argv.join(' ')).not.toContain('guest-token')+ expect(env).toEqual({ TERM: 'xterm-256color', COLORTERM: 'truecolor', LANG: 'vi_VN.UTF-8',+ ANTHROPIC_BASE_URL: `${relay}/claude`, ANTHROPIC_AUTH_TOKEN: 'guest-token' })+ })++ it('runs Codex on the relay\'s provider, asking before each command when the guest wants it to', () => {+ const { argv, env } = guestPaneCommand({ account, engine: 'codex', relayUrl: relay, token: 'guest-token', bypassPermission: false, helperPath: '/opt/helper' })+ const engine = argv.slice(argv.indexOf('--') + 1)+ expect(engine[0]).toBe('codex')+ expect(engine).toContain(`model_providers.harness_owner.base_url="${relay}/codex"`)+ expect(engine).not.toContain('--dangerously-bypass-approvals-and-sandbox')+ expect(argv[4]).toBe('/opt/helper')+ expect(env).toEqual({ TERM: 'xterm-256color', COLORTERM: 'truecolor', LANG: 'en_US.UTF-8', HARNESS_RELAY_TOKEN: 'guest-token' })+ expect(guestPaneCommand({ account, engine: 'codex', relayUrl: relay, token: 't', bypassPermission: true }).argv.at(-1)).toBe('--dangerously-bypass-approvals-and-sandbox')+ })++ it('starts on the guest\'s first message, which no option can be read from', () => {+ const tail = (prompt: string, engine: 'claude' | 'codex' = 'claude') =>+ guestPaneCommand({ account, engine, relayUrl: relay, token: 't', bypassPermission: false, prompt }).argv.slice(-2)+ expect(tail('Fix the tests')).toEqual(['claude', 'Fix the tests'])+ expect(tail('Fix the tests', 'codex')).toEqual(['model_providers.harness_owner.supports_websockets=false', 'Fix the tests'])+ expect(tail('--settings /tmp/x')).toEqual(['--', '--settings /tmp/x'])+ })++ it('starts in a folder the owner shares when it is given one, which the helper checks again', () => {+ const { argv } = guestPaneCommand({ account, engine: 'claude', relayUrl: relay, token: 't', bypassPermission: false, cwd: '/Users/dee/docs' })+ expect(argv[6]).toBe('/Users/dee/docs')+ expect(argv.slice(argv.indexOf('run'), argv.indexOf('run') + 4)).toEqual(['run', account.user, '--cwd', '/Users/dee/docs'])+ })++ it('takes the engine\'s own flags for the mode the guest chose, in place of all or nothing', () => {+ const { argv } = guestPaneCommand({ account, engine: 'claude', relayUrl: relay, token: 't', bypassPermission: true,+ permissionFlags: ['--permission-mode', 'auto'], prompt: 'hi' })+ expect(argv.slice(argv.indexOf('--') + 1)).toEqual(['claude', '--permission-mode', 'auto', 'hi'])+ expect(argv).not.toContain('--dangerously-skip-permissions')+ })++ it('is for the engines whose subscription the relay spends', () => {+ expect(GUEST_LAUNCH_ENGINES).toEqual(['claude', 'codex'])+ })+})++// The bootstrap runs for real, with a fake `sudo` on PATH that logs what it is asked and answers whether the+// guest has the engine as the test says.+describe('the pane\'s first moments', () => {+ const dirs: string[] = []+ afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })++ function run(has: boolean, installs = true): { log: string[]; out: string; code: number } {+ const dir = mkdtempSync(join(tmpdir(), 'guest-pane-'))+ dirs.push(dir)+ const log = join(dir, 'log')+ writeFileSync(join(dir, 'sudo'), [+ '#!/bin/sh',+ `printf '%s\\n' "$*" >> '${log}'`,+ 'case "$3" in',+ ` run) case "$*" in *"command -v"*) exit ${has ? 0 : 1} ;; esac; exit 0 ;;`,+ ` install) exit ${installs ? 0 : 1} ;;`,+ 'esac',+ ].join('\n'))+ chmodSync(join(dir, 'sudo'), 0o755)+ let out = '', code = 0+ try {+ out = execFileSync('/bin/sh', ['-c', GUEST_PANE_BOOTSTRAP, 'harness-guest', '/helper', 'hg_0123456789ab', '/work', 'claude',+ 'sudo', '-n', '/helper', 'run', 'hg_0123456789ab', '--cwd', '/work', '--', 'claude'], { env: { PATH: `${dir}:/usr/bin:/bin` }, encoding: 'utf8' })+ } catch (error) {+ const failed = error as { status: number; stdout: string }+ code = failed.status+ out = failed.stdout+ }+ return { log: readFileSync(log, 'utf8').trim().split('\n'), out, code }+ }++ it('hands straight over when the guest has the engine', () => {+ const { log, code } = run(true)+ expect(code).toBe(0)+ expect(log).toEqual([+ '-n /helper run hg_0123456789ab --cwd /work -- /bin/sh -c command -v "$0" >/dev/null claude',+ '-n /helper run hg_0123456789ab --cwd /work -- claude',+ ])+ })++ it('installs it for the guest first, in front of them', () => {+ const { log, code } = run(false)+ expect(code).toBe(0)+ expect(log.slice(1)).toEqual(['-n /helper install hg_0123456789ab claude', '-n /helper run hg_0123456789ab --cwd /work -- claude'])+ })++ it('says so and stops when the install fails', () => {+ const { log, out, code } = run(false, false)+ expect(code).toBe(1)+ expect(out).toContain('Could not install claude for this guest.')+ expect(log.at(-1)).toBe('-n /helper install hg_0123456789ab claude')+ })+})diff --git a/cli/src/lib/guestPaneCommand.ts b/cli/src/lib/guestPaneCommand.tsnew file mode 100644index 000000000..3d273adc6--- /dev/null+++ b/cli/src/lib/guestPaneCommand.ts@@ -0,0 +1,77 @@+/**+ * What a tmux pane runs for a guest's harness (docs/plans/2026-10-19-guest-machine-sharing-plan.md): the+ * engine as the guest's own OS user, through the guest helper (guestAccounts.ts), in the guest's workspace,+ * spending the owner's subscription through the relay (subscriptionRelay.ts). Nothing of the owner's goes+ * in: no launch script, no PATH, no HOME, no key — the helper starts the engine with `env -i` and only the+ * variables passed here.+ *+ * The pane itself is the owner's. Before it hands over it asks the helper whether the guest has the engine,+ * and when not installs it as the guest, in that pane, so the guest watches it happen the first time rather+ * than waiting on a create that says nothing for a minute.+ */+import { GUEST_HELPER_PATH, guestRunCommand, type GuestAccount } from './guestAccounts.js'+import { claudeRelayEnv, codexRelayArgs, codexRelayEnv } from './subscriptionRelay.js'++/** The engines a guest's harness runs: the two whose subscription the relay can spend. */+export type GuestLaunchEngine = 'claude' | 'codex'+export const GUEST_LAUNCH_ENGINES: readonly string[] = ['claude', 'codex'] satisfies readonly GuestLaunchEngine[]++/** Each engine's flag for "work without asking for each command", which a harness starts with by default. */+const APPROVE_ALL: Record<GuestLaunchEngine, string> = {+ claude: '--dangerously-skip-permissions',+ codex: '--dangerously-bypass-approvals-and-sandbox',+}++/**+ * The owner's side of the pane: $1 the helper, $2 the guest's user, $3 the workspace, $4 the engine, then the+ * helper's `run` command. The check runs `command -v` as the guest, on the guest's PATH (the helper's).+ */+export const GUEST_PANE_BOOTSTRAP = [+ 'helper=$1 user=$2 work=$3 engine=$4; shift 4',+ 'if ! sudo -n "$helper" run "$user" --cwd "$work" -- /bin/sh -c \'command -v "$0" >/dev/null\' "$engine" 2>/dev/null; then',+ ' sudo -n "$helper" install "$user" "$engine" || { printf \'\\nCould not install %s for this guest.\\n\' "$engine"; exit 1; }',+ 'fi',+ 'exec "$@"',+].join('\n')++export interface GuestPaneInput {+ account: GuestAccount+ engine: GuestLaunchEngine+ /** The relay's base, `http://127.0.0.1:<port>`, and this harness's token for it. */+ relayUrl: string+ token: string+ bypassPermission: boolean+ /** The engine's flags for the permission mode the guest chose (Ask first, Auto-approve, …), in place of the+ * all-or-nothing [bypassPermission]: Auto-approve is not Skip all checks. */+ permissionFlags?: readonly string[]+ /** The guest's first message, which both engines take as their last argument. It is on the engine's command+ * line, which `ps` shows every account on this computer: a guest's task, never a secret of the owner's. */+ prompt?: string+ /** Where it starts: the guest's workspace unless a folder the owner shares (the helper checks it is). */+ cwd?: string+ /** The owner's LANG, so the guest's terminal reads text as the owner's does. */+ lang?: string+ helperPath?: string+}++/** The pane's argv and the variables to set on it (`tmux new-session -e`), which the helper passes on. */+export function guestPaneCommand(input: GuestPaneInput): { argv: string[]; env: Record<string, string> } {+ const { account, engine, relayUrl, token } = input+ const helperPath = input.helperPath ?? GUEST_HELPER_PATH+ const approve = input.permissionFlags ? [...input.permissionFlags] : input.bypassPermission ? [APPROVE_ALL[engine]] : []+ // A message that starts with `-` is still a message, not one of the engine's options.+ const first = !input.prompt ? [] : input.prompt.startsWith('-') ? ['--', input.prompt] : [input.prompt]+ const engineArgv = engine === 'claude' ? ['claude', ...approve, ...first] : ['codex', ...codexRelayArgs(relayUrl), ...approve, ...first]+ const env = {+ TERM: 'xterm-256color',+ COLORTERM: 'truecolor',+ LANG: input.lang || 'en_US.UTF-8',+ ...(engine === 'claude' ? claudeRelayEnv(relayUrl, token) : codexRelayEnv(token)),+ }+ const cwd = input.cwd ?? account.workspace+ const run = guestRunCommand(account.user, cwd, env, engineArgv, helperPath)+ return {+ argv: ['/bin/sh', '-c', GUEST_PANE_BOOTSTRAP, 'harness-guest', helperPath, account.user, cwd, engine, ...run.argv],+ env: run.env,+ }+}diff --git a/cli/src/lib/localCredential.spec.ts b/cli/src/lib/localCredential.spec.tsnew file mode 100644index 000000000..220fec407--- /dev/null+++ b/cli/src/lib/localCredential.spec.ts@@ -0,0 +1,50 @@+import { chmodSync, mkdtempSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, describe, expect, it } from 'vitest'+import { hookCredentialPath, loadOrCreateHookCredential } from './hookAuth.js'+import { LOCAL_CREDENTIAL_HEADER, localCredentialHeaders, localCredentialMatches, readLocalCredential, suppliedLocalCredential } from './localCredential.js'++const dirs: string[] = []+afterEach(() => dirs.splice(0).forEach((dir) => rmSync(dir, { recursive: true, force: true })))+function dataDir(): string {+ const dir = mkdtempSync(join(tmpdir(), 'local-cred-'))+ dirs.push(dir)+ return dir+}++describe('the daemon\'s local credential', () => {+ it('is the hook credential, sent as X-Harness-Local by a process that can read it', () => {+ const dir = dataDir()+ const credential = loadOrCreateHookCredential(dir)+ expect(readLocalCredential(dir)).toBe(credential)+ expect(localCredentialHeaders(dir)).toEqual({ [LOCAL_CREDENTIAL_HEADER]: credential })+ })++ it('adds no header when there is no credential to read, or one another user could have written', () => {+ const dir = dataDir()+ expect(localCredentialHeaders(dir)).toEqual({})+ loadOrCreateHookCredential(dir)+ chmodSync(hookCredentialPath(dir), 0o644)+ expect(readLocalCredential(dir)).toBeNull()+ expect(localCredentialHeaders(dir)).toEqual({})+ })++ it('is read from the named header first, else from a bearer', () => {+ expect(suppliedLocalCredential({ headers: { 'x-harness-local': 'named', authorization: 'Bearer other' } })).toBe('named')+ expect(suppliedLocalCredential({ headers: { authorization: 'Bearer bearer' } })).toBe('bearer')+ expect(suppliedLocalCredential({ headers: { 'x-harness-local': '', authorization: 'Bearer bearer' } })).toBe('bearer')+ expect(suppliedLocalCredential({ headers: { authorization: 'Basic abc' } })).toBeUndefined()+ expect(suppliedLocalCredential({ headers: {} })).toBeUndefined()+ })++ it('matches only the exact credential', () => {+ const credential = loadOrCreateHookCredential(dataDir())+ expect(localCredentialMatches(credential, { headers: { 'x-harness-local': credential } })).toBe(true)+ expect(localCredentialMatches(credential, { headers: { authorization: `Bearer ${credential}` } })).toBe(true)+ const wrong = `${credential.slice(0, -1)}${credential.endsWith('x') ? 'y' : 'x'}`+ expect(localCredentialMatches(credential, { headers: { 'x-harness-local': wrong } })).toBe(false)+ expect(localCredentialMatches(credential, { headers: { 'x-harness-local': credential.slice(1) } })).toBe(false)+ expect(localCredentialMatches(credential, { headers: {} })).toBe(false)+ })+})diff --git a/cli/src/lib/localCredential.ts b/cli/src/lib/localCredential.tsnew file mode 100644index 000000000..459e63775--- /dev/null+++ b/cli/src/lib/localCredential.ts@@ -0,0 +1,42 @@+import type { IncomingMessage } from 'node:http'+import { hookCredentialMatches, readHookCredential } from './hookAuth.js'++/**+ * The daemon's local credential: what a process must show to use its loopback TCP API (REST and the+ * local WebSocket). It is the 0600, uid-checked `hook-credential` file in the data dir+ * (lib/hookAuth.ts), so a process of THIS OS user reads it and any other user's process cannot —+ * which is the whole point once another account's harnesses run as their own OS user on this machine+ * (docs/plans/2026-10-19-guest-machine-sharing-plan.md, "Loopback credential"). The daemon's Unix socket+ * (lib/localSocket.ts) needs none: the filesystem already says who is on it.+ *+ * Sent as `X-Harness-Local: <credential>`, or `Authorization: Bearer <credential>` for a client that+ * can only set that one.+ */+export const LOCAL_CREDENTIAL_HEADER = 'X-Harness-Local'++/** What a refused request is answered. */+export const LOCAL_CREDENTIAL_REQUIRED = 'LOCAL_CREDENTIAL_REQUIRED'++/** The credential as a client reads it, or null when this process may not (another OS user, no file). */+export function readLocalCredential(dataDir: string): string | null {+ return readHookCredential(dataDir)+}++/** The headers a client adds to every loopback TCP request: none when it cannot read the credential. */+export function localCredentialHeaders(dataDir: string): Record<string, string> {+ const credential = readLocalCredential(dataDir)+ return credential ? { [LOCAL_CREDENTIAL_HEADER]: credential } : {}+}++/** The credential a request carries, if any: the named header first, else a bearer. */+export function suppliedLocalCredential(req: Pick<IncomingMessage, 'headers'>): string | undefined {+ const named = req.headers[LOCAL_CREDENTIAL_HEADER.toLowerCase()]+ if (typeof named === 'string' && named) return named+ const auth = req.headers.authorization+ return typeof auth === 'string' && auth.startsWith('Bearer ') ? auth.slice(7) : undefined+}++/** Whether [req] carries [expected], compared in constant time. */+export function localCredentialMatches(expected: string, req: Pick<IncomingMessage, 'headers'>): boolean {+ return hookCredentialMatches(expected, suppliedLocalCredential(req))+}diff --git a/cli/src/lib/ownerSubscriptions.spec.ts b/cli/src/lib/ownerSubscriptions.spec.tsnew file mode 100644index 000000000..f428cf418--- /dev/null+++ b/cli/src/lib/ownerSubscriptions.spec.ts@@ -0,0 +1,150 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { dirname, join } from 'node:path'+import {+ CLAUDE_CLIENT_ID,+ CODEX_CLIENT_ID,+ createOwnerSubscriptions,+ type KeychainWriter,+ type OwnerSubscriptionDeps,+} from './ownerSubscriptions.js'++let home: string+beforeEach(() => { home = mkdtempSync(join(tmpdir(), 'owner-subscriptions-')) })+afterEach(() => { rmSync(home, { recursive: true, force: true }) })++function write(relative: string, value: unknown, mode = 0o600): string {+ const path = join(home, relative)+ mkdirSync(dirname(path), { recursive: true })+ writeFileSync(path, typeof value === 'string' ? value : JSON.stringify(value), { mode })+ return path+}++const NOW = 1_800_000_000_000+const jwt = (claims: Record<string, unknown>): string =>+ ['e30', Buffer.from(JSON.stringify(claims)).toString('base64url'), 'sig'].join('.')++interface TokenCall { url: string; body: Record<string, string> }++/** The vendor's token endpoint: answers [answer] (or [status]) and remembers each request. */+function tokenEndpoint(answer: Record<string, unknown>, status = 200) {+ const calls: TokenCall[] = []+ const fetchImpl = (async (url: string, init: RequestInit) => {+ calls.push({ url: String(url), body: JSON.parse(String(init.body)) as Record<string, string> })+ await new Promise((resolve) => setTimeout(resolve, 5))+ return new Response(JSON.stringify(answer), { status })+ }) as unknown as typeof fetch+ return { calls, fetchImpl }+}++function keychain(stored: string | null) {+ const writes: Array<{ account: string; secret: string }> = []+ let current = stored+ const writer: KeychainWriter = {+ account: async () => 'owner',+ write: async (account, secret) => { writes.push({ account, secret }); current = secret },+ }+ return { writes, writer, read: async () => current }+}++function deps(extra: OwnerSubscriptionDeps): OwnerSubscriptionDeps {+ return { home, now: () => NOW, lockDir: join(home, 'locks'), readKeychain: async () => null, ...extra }+}++const claudeFile = (oauth: Record<string, unknown>, extra: Record<string, unknown> = {}) =>+ ({ claudeAiOauth: { scopes: ['user:inference'], subscriptionType: 'max', ...oauth }, ...extra })++describe('reading the owner\'s sign-ins', () => {+ it('reads Claude from the Keychain before the file, and Codex with its account and JWT expiry', async () => {+ const k = keychain(JSON.stringify(claudeFile({ accessToken: 'from-keychain', expiresAt: NOW + 3_600_000 })))+ write('.claude/.credentials.json', claudeFile({ accessToken: 'from-file' }))+ write('.codex/auth.json', { tokens: { access_token: jwt({ exp: 1_900_000_000 }), refresh_token: 'r', account_id: 'acct-1' } })+ const owner = createOwnerSubscriptions(deps({ readKeychain: k.read }))+ expect(await owner.read('claude')).toMatchObject({ accessToken: 'from-keychain', expiresAt: NOW + 3_600_000 })+ expect(await owner.read('codex')).toMatchObject({ accountId: 'acct-1', expiresAt: 1_900_000_000_000 })+ })++ it('is null when the owner is not signed in', async () => {+ const owner = createOwnerSubscriptions(deps({}))+ expect(await owner.read('claude')).toBeNull()+ expect(await owner.read('codex')).toBeNull()+ })+})++describe('refreshing Claude', () => {+ it('posts the refresh token with Claude Code\'s client id and writes the answer back to the file, keeping its mode and fields', async () => {+ const path = write('.claude/.credentials.json', claudeFile({ accessToken: 'old', refreshToken: 'r-old', expiresAt: NOW - 1 }, { other: 'kept' }))+ const vendor = tokenEndpoint({ access_token: 'new', refresh_token: 'r-new', expires_in: 3600 })+ const owner = createOwnerSubscriptions(deps({ fetchImpl: vendor.fetchImpl, tokenUrls: { claude: 'https://token.test/claude' } }))+ const stale = await owner.read('claude')+ const fresh = await owner.refresh('claude', stale)+ expect(fresh).toMatchObject({ accessToken: 'new', expiresAt: NOW + 3_600_000 })+ expect(vendor.calls).toEqual([{ url: 'https://token.test/claude', body: { grant_type: 'refresh_token', refresh_token: 'r-old', client_id: CLAUDE_CLIENT_ID } }])+ const saved = JSON.parse(readFileSync(path, 'utf8'))+ expect(saved).toEqual(claudeFile({ accessToken: 'new', refreshToken: 'r-new', expiresAt: NOW + 3_600_000 }, { other: 'kept' }))+ expect(statSync(path).mode & 0o777).toBe(0o600)+ })++ it('writes a Keychain sign-in back to the Keychain item it came from', async () => {+ const k = keychain(JSON.stringify(claudeFile({ accessToken: 'old', refreshToken: 'r-old', expiresAt: NOW - 1 })))+ const vendor = tokenEndpoint({ access_token: 'new', expires_in: 60 })+ const owner = createOwnerSubscriptions(deps({ readKeychain: k.read, keychain: k.writer, fetchImpl: vendor.fetchImpl }))+ expect(await owner.refresh('claude', await owner.read('claude'))).toMatchObject({ accessToken: 'new' })+ expect(k.writes).toHaveLength(1)+ expect(k.writes[0]!.account).toBe('owner')+ // The refresh token is kept when the vendor does not rotate it.+ expect(JSON.parse(k.writes[0]!.secret).claudeAiOauth).toMatchObject({ accessToken: 'new', refreshToken: 'r-old', subscriptionType: 'max' })+ })++ it('refreshes once when several requests find the token expired at the same time', async () => {+ write('.claude/.credentials.json', claudeFile({ accessToken: 'old', refreshToken: 'r-old', expiresAt: NOW - 1 }))+ const vendor = tokenEndpoint({ access_token: 'new', refresh_token: 'r-new', expires_in: 3600 })+ const owner = createOwnerSubscriptions(deps({ fetchImpl: vendor.fetchImpl }))+ const stale = await owner.read('claude')+ const results = await Promise.all([owner.refresh('claude', stale), owner.refresh('claude', stale), owner.refresh('claude', stale)])+ expect(results.map((r) => r?.accessToken)).toEqual(['new', 'new', 'new'])+ expect(vendor.calls).toHaveLength(1)+ })++ it('uses a token someone else already refreshed instead of spending the refresh token again', async () => {+ write('.claude/.credentials.json', claudeFile({ accessToken: 'theirs', refreshToken: 'r-theirs', expiresAt: NOW + 3_600_000 }))+ const vendor = tokenEndpoint({ access_token: 'never' })+ const owner = createOwnerSubscriptions(deps({ fetchImpl: vendor.fetchImpl }))+ const fresh = await owner.refresh('claude', { provider: 'claude', accessToken: 'mine', expiresAt: NOW - 1, accountId: null })+ expect(fresh?.accessToken).toBe('theirs')+ expect(vendor.calls).toHaveLength(0)+ })++ it('leaves the store alone and answers null when the vendor refuses', async () => {+ const before = claudeFile({ accessToken: 'old', refreshToken: 'r-old', expiresAt: NOW - 1 })+ const path = write('.claude/.credentials.json', before)+ const vendor = tokenEndpoint({ error: 'invalid_grant' }, 400)+ const owner = createOwnerSubscriptions(deps({ fetchImpl: vendor.fetchImpl }))+ expect(await owner.refresh('claude', await owner.read('claude'))).toBeNull()+ expect(JSON.parse(readFileSync(path, 'utf8'))).toEqual(before)+ })+})++describe('refreshing Codex', () => {+ it('posts with the Codex client id and writes the tokens back with last_refresh, keeping other fields and the mode', async () => {+ const path = write('.codex/auth.json', {+ OPENAI_API_KEY: null,+ tokens: { access_token: jwt({ exp: 1 }), refresh_token: 'r-old', account_id: 'acct-1', id_token: 'id-old' },+ last_refresh: 'then',+ }, 0o640)+ const newAccess = jwt({ exp: 1_900_000_000 })+ const vendor = tokenEndpoint({ access_token: newAccess, refresh_token: 'r-new', id_token: 'id-new' })+ const owner = createOwnerSubscriptions(deps({ fetchImpl: vendor.fetchImpl, tokenUrls: { codex: 'https://token.test/codex' } }))+ const fresh = await owner.refresh('codex', await owner.read('codex'))+ expect(fresh).toMatchObject({ accessToken: newAccess, accountId: 'acct-1', expiresAt: 1_900_000_000_000 })+ expect(vendor.calls[0]!.body).toEqual({ client_id: CODEX_CLIENT_ID, grant_type: 'refresh_token', refresh_token: 'r-old', scope: 'openid profile email' })+ const saved = JSON.parse(readFileSync(path, 'utf8'))+ expect(saved).toEqual({+ OPENAI_API_KEY: null,+ tokens: { access_token: newAccess, refresh_token: 'r-new', account_id: 'acct-1', id_token: 'id-new' },+ last_refresh: new Date(NOW).toISOString(),+ })+ expect(statSync(path).mode & 0o777).toBe(0o640)+ })+})diff --git a/cli/src/lib/ownerSubscriptions.ts b/cli/src/lib/ownerSubscriptions.tsnew file mode 100644index 000000000..ff08a2a18--- /dev/null+++ b/cli/src/lib/ownerSubscriptions.ts@@ -0,0 +1,331 @@+/**+ * The machine owner's Claude and ChatGPT subscriptions, as the guest subscription relay spends them+ * (`subscriptionRelay.ts`, docs/plans/2026-10-19-guest-machine-sharing-plan.md).+ *+ * The owner's sign-in is read where the vendor's CLI keeps it (`agentCredentials.ts`) and, when its+ * access token has expired, refreshed and **written back to the same store** — the Keychain item it+ * came from, or the file, its mode kept — so the owner's own `claude` and `codex` keep working with+ * the rotated refresh token. Refreshes are single-flight in this process and serialised across+ * processes with a lock file, and every refresh first re-reads the store: when the owner's CLI (or+ * another daemon) has refreshed in the meantime, that token is used and nothing is spent.+ *+ * ⚠️ Nothing here ever logs, returns in an error, or puts in a child's argv a token: the Keychain+ * write goes through `security -i` on stdin, hex-encoded, so another local user's `ps` never sees it.+ *+ * ⚠️ Undocumented vendor contracts, see the constants below for what was verified and what is+ * assumed.+ */+import { execFile, spawn } from 'node:child_process'+import { open, rename, stat, unlink, mkdir, writeFile } from 'node:fs/promises'+import { homedir, userInfo } from 'node:os'+import { dirname, join } from 'node:path'+import { promisify } from 'node:util'+import {+ asRecord,+ CLAUDE_KEYCHAIN_SERVICE,+ claudeCredentialsPath,+ codexAuthPath,+ jwtClaims,+ parseJson,+ readClaudeStored,+ readText,+ stringField,+ type ClaudeCredentialSource,+} from './agentCredentials.js'++const execFileAsync = promisify(execFile)++/**+ * Claude Code's OAuth refresh. **Verified** against the Claude Code 2.1.283 binary on the author's+ * machine (2026-10-19): `TOKEN_URL: "https://platform.claude.com/v1/oauth/token"` and+ * `CLIENT_ID: "9d1c250a-e61b-44d9-88ed-5944d1962f5e"` in its prod OAuth config. **Assumed** (not+ * read from the bundle): the body is the standard JSON `{grant_type, refresh_token, client_id}` and+ * the answer `{access_token, refresh_token?, expires_in}`.+ */+export const CLAUDE_TOKEN_URL = 'https://platform.claude.com/v1/oauth/token'+export const CLAUDE_CLIENT_ID = '9d1c250a-e61b-44d9-88ed-5944d1962f5e'++/**+ * Codex's (ChatGPT sign-in) OAuth refresh. **Assumed, not verified** on this machine: the token URL,+ * the public client id and the scope are those the open-source Codex CLI is documented to use. Kept+ * behind constants so a change is one edit.+ */+export const CODEX_TOKEN_URL = 'https://auth.openai.com/oauth/token'+export const CODEX_CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann'+export const CODEX_REFRESH_SCOPE = 'openid profile email'++export type SubscriptionProvider = 'claude' | 'codex'++/** One owner sign-in, as the relay spends it. */+export interface OwnerCredential {+ provider: SubscriptionProvider+ accessToken: string+ /** Epoch ms, or null when the store does not say. */+ expiresAt: number | null+ /** Codex: the ChatGPT account the backend scopes requests to. */+ accountId: string | null+}++export interface OwnerSubscriptions {+ /** The owner's current sign-in for [provider], or null when the owner is not signed in. */+ read(provider: SubscriptionProvider): Promise<OwnerCredential | null>+ /**+ * A fresh sign-in, given the one that just failed or expired. Returns another process's newer+ * token when there is one, else refreshes and writes back. Null when there is no sign-in to+ * refresh or the vendor refused (the caller answers as it would without a sign-in).+ */+ refresh(provider: SubscriptionProvider, stale: OwnerCredential | null): Promise<OwnerCredential | null>+}++/** What a Keychain write needs: the item's account attribute and the secret, never in argv. */+export interface KeychainWriter {+ /** The `acct` attribute of the existing item, so the write replaces it rather than adding one. */+ account(): Promise<string | null>+ write(account: string, secret: string): Promise<void>+}++export interface OwnerSubscriptionDeps {+ home?: string+ platform?: NodeJS.Platform+ readKeychain?: () => Promise<string | null>+ keychain?: KeychainWriter+ fetchImpl?: typeof fetch+ now?: () => number+ /** Where the cross-process refresh lock lives. */+ lockDir?: string+ tokenUrls?: Partial<Record<SubscriptionProvider, string>>+}++/** A token that expires within this long is refreshed before it is spent. */+export const EXPIRY_SKEW_MS = 60_000+const REFRESH_TIMEOUT_MS = 15_000+const LOCK_WAIT_MS = 20_000+const LOCK_STALE_MS = 30_000++/** An error that is safe to show: it never carries a token or a vendor body. */+export class OwnerSubscriptionError extends Error {}++export function createOwnerSubscriptions(deps: OwnerSubscriptionDeps = {}): OwnerSubscriptions {+ const home = deps.home ?? homedir()+ const now = deps.now ?? Date.now+ const fetchImpl = deps.fetchImpl ?? fetch+ const lockDir = deps.lockDir ?? join(home, '.harness', 'cli', 'data', 'locks')+ const keychain = deps.keychain ?? securityKeychain()+ const readDeps = { home, platform: deps.platform, readKeychain: deps.readKeychain }+ const inFlight = new Map<SubscriptionProvider, Promise<OwnerCredential | null>>()++ const read = async (provider: SubscriptionProvider): Promise<OwnerCredential | null> =>+ provider === 'claude' ? (await readClaude(readDeps))?.credential ?? null : (await readCodex(home))?.credential ?? null++ const refreshNow = async (provider: SubscriptionProvider, stale: OwnerCredential | null): Promise<OwnerCredential | null> => {+ const release = await acquireLock(join(lockDir, `${provider}-refresh.lock`))+ try {+ // Someone else may have refreshed while this one waited: theirs wins, nothing is spent.+ const current = await read(provider)+ if (!current) return null+ if (current.accessToken !== stale?.accessToken && !expired(current, now())) return current+ return provider === 'claude' ? await refreshClaude() : await refreshCodex()+ } finally {+ await release()+ }+ }++ const refreshClaude = async (): Promise<OwnerCredential | null> => {+ const stored = await readClaude(readDeps)+ const refreshToken = stringField(stored?.oauth.refreshToken)+ if (!stored || !refreshToken) return null+ const answer = await postToken(fetchImpl, deps.tokenUrls?.claude ?? CLAUDE_TOKEN_URL, {+ grant_type: 'refresh_token', refresh_token: refreshToken, client_id: CLAUDE_CLIENT_ID,+ })+ if (!answer) return null+ const accessToken = stringField(answer.access_token)+ if (!accessToken) return null+ const expiresIn = typeof answer.expires_in === 'number' ? answer.expires_in : null+ const oauth = {+ ...stored.oauth,+ accessToken,+ refreshToken: stringField(answer.refresh_token) ?? refreshToken,+ ...(expiresIn !== null ? { expiresAt: now() + expiresIn * 1000 } : {}),+ }+ const root = JSON.stringify({ ...stored.root, claudeAiOauth: oauth })+ if (stored.source === 'keychain') {+ const account = (await keychain.account()) ?? userInfo().username+ await keychain.write(account, root)+ } else {+ await writeKeepingMode(claudeCredentialsPath(home), root)+ }+ return claudeCredential(oauth)+ }++ const refreshCodex = async (): Promise<OwnerCredential | null> => {+ const stored = await readCodex(home)+ const refreshToken = stringField(stored?.tokens.refresh_token)+ if (!stored || !refreshToken) return null+ const answer = await postToken(fetchImpl, deps.tokenUrls?.codex ?? CODEX_TOKEN_URL, {+ client_id: CODEX_CLIENT_ID, grant_type: 'refresh_token', refresh_token: refreshToken, scope: CODEX_REFRESH_SCOPE,+ })+ const accessToken = stringField(answer?.access_token)+ if (!answer || !accessToken) return null+ const tokens = {+ ...stored.tokens,+ access_token: accessToken,+ refresh_token: stringField(answer.refresh_token) ?? refreshToken,+ ...(stringField(answer.id_token) ? { id_token: answer.id_token } : {}),+ }+ await writeKeepingMode(codexAuthPath(home), JSON.stringify({+ ...stored.root, tokens, last_refresh: new Date(now()).toISOString(),+ }, null, 2))+ return codexCredential(tokens)+ }++ return {+ read,+ refresh(provider, stale) {+ const running = inFlight.get(provider)+ if (running) return running+ const attempt = refreshNow(provider, stale).finally(() => inFlight.delete(provider))+ inFlight.set(provider, attempt)+ return attempt+ },+ }+}++/** Whether [credential] is spent or about to be. */+export function expired(credential: OwnerCredential, at: number): boolean {+ return credential.expiresAt !== null && credential.expiresAt <= at + EXPIRY_SKEW_MS+}++interface StoredClaude {+ root: Record<string, unknown>+ oauth: Record<string, unknown>+ source: ClaudeCredentialSource+ credential: OwnerCredential+}++async function readClaude(deps: { home: string; platform?: NodeJS.Platform; readKeychain?: () => Promise<string | null> }): Promise<StoredClaude | null> {+ const stored = await readClaudeStored(deps)+ const root = asRecord(parseJson(stored?.raw ?? null))+ const oauth = asRecord(root?.claudeAiOauth)+ if (!stored || !root || !oauth || !stringField(oauth.accessToken)) return null+ return { root, oauth, source: stored.source, credential: claudeCredential(oauth) }+}++function claudeCredential(oauth: Record<string, unknown>): OwnerCredential {+ return {+ provider: 'claude',+ accessToken: String(oauth.accessToken),+ expiresAt: typeof oauth.expiresAt === 'number' ? oauth.expiresAt : null,+ accountId: null,+ }+}++interface StoredCodex {+ root: Record<string, unknown>+ tokens: Record<string, unknown>+ credential: OwnerCredential+}++async function readCodex(home: string): Promise<StoredCodex | null> {+ const root = asRecord(parseJson(await readText(codexAuthPath(home))))+ const tokens = asRecord(root?.tokens)+ if (!root || !tokens || !stringField(tokens.access_token)) return null+ return { root, tokens, credential: codexCredential(tokens) }+}++function codexCredential(tokens: Record<string, unknown>): OwnerCredential {+ // auth.json keeps no expiry of its own; the access token is a JWT that does.+ const exp = jwtClaims(tokens.access_token)?.exp+ return {+ provider: 'codex',+ accessToken: String(tokens.access_token),+ expiresAt: typeof exp === 'number' ? exp * 1000 : null,+ accountId: stringField(tokens.account_id),+ }+}++/** The vendor's token answer, or null when it refused or could not be reached. Never throws a+ * message that could carry the refresh token or the vendor's body. */+async function postToken(fetchImpl: typeof fetch, url: string, body: Record<string, string>): Promise<Record<string, unknown> | null> {+ try {+ const response = await fetchImpl(url, {+ method: 'POST',+ headers: { 'content-type': 'application/json', accept: 'application/json' },+ body: JSON.stringify(body),+ signal: AbortSignal.timeout(REFRESH_TIMEOUT_MS),+ })+ if (!response.ok) return null+ return asRecord(parseJson(await response.text()))+ } catch {+ return null+ }+}++/** Atomic replace in the same directory, keeping the file's mode (0600 when it had none). */+async function writeKeepingMode(path: string, content: string): Promise<void> {+ let mode = 0o600+ try { mode = (await stat(path)).mode & 0o777 } catch { /* a new file: 0600 */ }+ const temporary = `${path}.${process.pid}.${Date.now()}.tmp`+ try {+ await writeFile(temporary, content, { mode })+ await rename(temporary, path)+ } catch {+ await unlink(temporary).catch(() => {})+ throw new OwnerSubscriptionError(`Could not save the refreshed sign-in to ${path}.`)+ }+}++/**+ * An exclusive lock file. A lock older than LOCK_STALE_MS is a crashed holder's and is taken over;+ * one held longer than LOCK_WAIT_MS by a live holder is waited out no further (the refresh then+ * runs anyway: a second refresh is wasteful, never wrong, because each re-reads the store first).+ */+async function acquireLock(path: string): Promise<() => Promise<void>> {+ await mkdir(dirname(path), { recursive: true, mode: 0o700 })+ const deadline = Date.now() + LOCK_WAIT_MS+ for (;;) {+ try {+ const handle = await open(path, 'wx', 0o600)+ await handle.close()+ return async () => { await unlink(path).catch(() => {}) }+ } catch {+ try {+ const age = Date.now() - (await stat(path)).mtimeMs+ if (age > LOCK_STALE_MS) { await unlink(path).catch(() => {}); continue }+ } catch { continue }+ if (Date.now() > deadline) return async () => {}+ await new Promise((resolve) => setTimeout(resolve, 50))+ }+ }+}++/**+ * The login Keychain through `security`. The secret is written with `security -i`, which reads its+ * commands from stdin, hex-encoded (`-X`), so it is neither in argv (visible to every local user's+ * `ps`) nor in need of shell quoting.+ */+export function securityKeychain(): KeychainWriter {+ return {+ async account() {+ try {+ // Attributes only — no `-w`, so the secret is not printed.+ const { stdout } = await execFileAsync('security', ['find-generic-password', '-s', CLAUDE_KEYCHAIN_SERVICE], { timeout: 5_000 })+ const match = /"acct"<blob>="([^"]*)"/.exec(stdout)+ return match?.[1] || null+ } catch {+ return null+ }+ },+ write(account, secret) {+ return new Promise((resolve, reject) => {+ const child = spawn('security', ['-i'], { stdio: ['pipe', 'ignore', 'ignore'] })+ const quoted = (value: string): string => `"${value.replace(/(["\\])/g, '\\$1')}"`+ const hex = Buffer.from(secret, 'utf8').toString('hex')+ child.on('error', () => reject(new OwnerSubscriptionError('Could not save the refreshed sign-in to the Keychain.')))+ child.on('close', (code) => code === 0+ ? resolve()+ : reject(new OwnerSubscriptionError('Could not save the refreshed sign-in to the Keychain.')))+ child.stdin.end(`add-generic-password -U -s ${quoted(CLAUDE_KEYCHAIN_SERVICE)} -a ${quoted(account)} -X ${hex}\n`)+ })+ },+ }+}diff --git a/cli/src/lib/productUsageContract.ts b/cli/src/lib/productUsageContract.tsindex f1ec00673..8b6c51120 100644--- a/cli/src/lib/productUsageContract.ts+++ b/cli/src/lib/productUsageContract.ts@@ -103,6 +103,10 @@ export const LAUNCH_ERROR_CODES = ['restart_failed', 'restart_unsupported_backend', 'retarget_unsupported_backend', 'fork_on_grid_unsupported','no_active_process', 'opencode_sqlite_missing', 'unavailable', 'missing_name', 'missing_update','invalid_close_request', 'invalid_delete_request', 'close_failed', 'delete_failed',+ // A guest on a machine shared with it (core/guestPolicy.ts, core/agents/guestCreate.ts, services/guestLaunches.ts).+ 'guest_not_allowed', 'guest_unsupported', 'guest_harness', 'guest_unavailable', 'guest_helper_required',+ 'guest_engine_unsupported', 'guest_relay_failed', 'guest_folder_unavailable', 'guest_invalid', 'guest_helper_missing',+ 'guest_helper_not_authorized', 'guest_helper_failed','unlisted', 'none',] as constexport type LaunchErrorCode = typeof LAUNCH_ERROR_CODES[number]diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.tsindex ef536a497..1b9f0b081 100644--- a/cli/src/lib/registry.spec.ts+++ b/cli/src/lib/registry.spec.ts@@ -2280,6 +2280,22 @@ describe('who started it', () => {expect(registry.byAgent(pending.agentId)?.startedBy).toBe('agent')})+ it('keeps whose guest it was started for through the hook that rebuilds the row and a reload', async () => {+ const transcriptPath = join(dataDir, 'session-guest.jsonl')+ writeFileSync(transcriptPath, '{}\n')+ const { registry } = await loadRegistryModule()+ registry.load()+ const pending = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%31' }], cwd: '/tmp/g', guest: '[email protected]' })!+ expect(pending.guest).toBe('[email protected]')+ expect(registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%32' }], cwd: '/tmp/o', guest: null })).not.toHaveProperty('guest')+ registry.register({ sessionId: 'session-guest', transcriptPath, tmuxPane: '%31', cwd: '/tmp/g' })+ expect(registry.byAgent(pending.agentId)?.guest).toBe('[email protected]')+ registry.flush()+ const reloaded = await loadRegistryModule()+ reloaded.registry.load()+ expect(reloaded.registry.byAgent(pending.agentId)?.guest).toBe('[email protected]')+ })+it('keeps which harness here started it, beside startedBy, through a reload and the hook that rebuilds the row', async () => {const transcriptPath = join(dataDir, 'session-child.jsonl')writeFileSync(transcriptPath, '{}\n')diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex 7c270e8dd..1b0920d29 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -253,6 +253,13 @@ export interface RegisteredSession {* new harness beside the one that started it and say so in its header (docs/design/2026-10-11-agent-client.md).*/parentAgentId?: string+ /**+ * The guest (email) this harness was started for: a session of an account the owner shares this machine+ * with. Its process runs as that guest's OS user, and only that guest's sessions may see or drive it+ * (core/guestPolicy.ts, docs/plans/2026-10-19-guest-machine-sharing-plan.md). Absent for the owner's own.+ * Recorded once at creation and never changed.+ */+ guest?: string/** Legacy launcher-owned snapshots may still contain this field. New records never write it. */launcherId?: stringtranscriptPath: string | null@@ -1322,6 +1329,8 @@ class Registry {...(raw.terminalHost === true || engine === 'terminal' ? { terminalHost: true } : {}),...(raw.startedBy === 'agent' ? { startedBy: 'agent' as const } : {}),...normalizedParent(raw.startedBy, raw.parentAgentId),+ // Rehydrated explicitly (see above): dropped, a guest's harness would read as the owner's.+ ...(typeof raw.guest === 'string' && raw.guest ? { guest: raw.guest } : {}),transcriptPath,defaultName: normalizedDefaultName(raw.defaultName),title: titleDisplayName(typeof raw.title === 'string' ? raw.title : null),@@ -1629,6 +1638,8 @@ class Registry {startedBy?: StartedBy | null/** The harness here that started it — see RegisteredSession.parentAgentId. Kept only with `startedBy: 'agent'`. */parentAgentId?: string | null+ /** The guest it is started for — see RegisteredSession.guest. */+ guest?: string | null}): RegisteredSession | null {if (this.writeBlocked) return nullconst externalResume = input.externalResume === undefined ? undefined : parseExternalResume(input.externalResume)@@ -1667,6 +1678,7 @@ class Registry {...normalizedForkedFrom(input.forkedFrom),...(input.startedBy === 'agent' ? { startedBy: 'agent' as const } : {}),...normalizedParent(input.startedBy, input.parentAgentId),+ ...(input.guest ? { guest: input.guest } : {}),transcriptPath: null,projectDir: basename(input.cwd ?? '') || agentId,cwd: input.cwd ?? null,@@ -2014,6 +2026,8 @@ class Registry {...(existing?.startedBy ? { startedBy: existing.startedBy } : {}),// And who it was, for the same reason: dropped at the first hook, the windows lost which harness started it....(existing?.parentAgentId ? { parentAgentId: existing.parentAgentId } : {}),+ // Whose guest's it is: dropped at the first hook, the guest would lose its own harness to the owner.+ ...(existing?.guest ? { guest: existing.guest } : {}),...(existing?.bypassPermission ? { bypassPermission: true } : {}),...(existing?.permissionMode ? { permissionMode: existing.permissionMode } : {}),...(existing?.resumeOnly ? { resumeOnly: true, launch: { state: 'ready' as const } } : {}),diff --git a/cli/src/lib/restoreAgents.spec.ts b/cli/src/lib/restoreAgents.spec.tsindex d7f157c90..aced5a373 100644--- a/cli/src/lib/restoreAgents.spec.ts+++ b/cli/src/lib/restoreAgents.spec.ts@@ -646,6 +646,13 @@ describe('restoreAgents — which agents get a pane back', () => {expect(h.paneCreates).toBe(0)})+ it('leaves a guest\'s harness stopped: rebuilt here it would run as the owner, with the owner\'s keys', async () => {+ const h = harness([row({ agentId: 'guests', guest: '[email protected]' })])+ const summary = await restoreAgents(h.deps)+ expect(summary.skipped).toEqual([{ agentId: 'guests', reason: 'a guest\'s harness' }])+ expect(h.paneCreates).toBe(0); expect(h.respawns).toBe(0)+ })+it('puts a grid agent back on its grid, key and all, when the row kept its launch', async () => {const h = harness([row({ agentId: 'gridded', grid: { baseUrl: GRID.baseUrl, model: null }, gridLaunch: GRID })])h.probes.set('%0', [identity(7)])diff --git a/cli/src/lib/restoreAgents.ts b/cli/src/lib/restoreAgents.tsindex 1f5300003..764a3ded3 100644--- a/cli/src/lib/restoreAgents.ts+++ b/cli/src/lib/restoreAgents.ts@@ -392,6 +392,9 @@ export async function restoreAgents(input: RestoreAgentsDeps): Promise<RestoreSutry {const runtime = tmuxRuntime(entry)if (entry.externalResume?.phase === 'cancelled') { summary.skipped.push({ agentId: entry.agentId, reason: 'external adoption cancelled' }); continue }+ // A guest's harness ran as the guest's own OS user (core/agents/guestCreate.ts). Rebuilt here it would run+ // as the owner, with the owner's keys: it is left stopped, and the guest starts a new one.+ if (entry.guest) { summary.skipped.push({ agentId: entry.agentId, reason: 'a guest\'s harness' }); continue }if (!runtime) { summary.skipped.push({ agentId: entry.agentId, reason: 'no tmux pane' }); continue }if (entry.launch?.state === 'failed') { summary.skipped.push({ agentId: entry.agentId, reason: 'last launch failed' }); continue }// Held: its pane, alive, runs no engine on purpose, so it is neither a stopped engine nor a terminal. Itsdiff --git a/cli/src/lib/sharedMachinesPort.ts b/cli/src/lib/sharedMachinesPort.tsindex a0b886d6e..48af2ff3e 100644--- a/cli/src/lib/sharedMachinesPort.ts+++ b/cli/src/lib/sharedMachinesPort.ts@@ -15,7 +15,9 @@ export interface SharedMachinesAccount {trust(desired: { pins?: SharedTrustPeer[]; keys?: SharedTrustPeer[] }): Promise<{ pins: number; keys: number }>}-export interface SharedTrustPeer { machineId: string; pub: string; label: string }+/** A machine and its key, as sharing trusts or pins it. `email`: on a key this machine trusts, the account it+ * is shared with — the guest its sessions are (docs/plans/2026-10-19-guest-machine-sharing-plan.md). */+export interface SharedTrustPeer { machineId: string; pub: string; label: string; email?: string }const MACHINE_RE = /^[a-f0-9]{32}$/diff --git a/cli/src/lib/storeProxy.spec.ts b/cli/src/lib/storeProxy.spec.tsindex 1881bc4ad..4edfc333b 100644--- a/cli/src/lib/storeProxy.spec.ts+++ b/cli/src/lib/storeProxy.spec.ts@@ -2,6 +2,8 @@import http, { type Server } from 'node:http'import { afterEach, describe, expect, it, vi } from 'vitest'import { STORE_PATH_RE as FROM_HOOK_SERVER, startHookServer, type HookServerHandlers } from '../hookServer.js'+import { env } from '../config/env.js'+import { readHookCredential } from './hookAuth.js'import { routeStoreRequest, STORE_PATH_RE, type StoreHandler, type StoreRoute } from './storeProxy.js'describe('STORE_PATH_RE', () => {@@ -86,10 +88,12 @@ describe('the store proxy on the hook server', () => {server = started.serverreturn started.port}- /** A raw request: the path goes out exactly as written, `..` and all, which fetch would not do. */+ /** A raw request: the path goes out exactly as written, `..` and all, which fetch would not do. As this OS user's+ * process sends it over the port: with the daemon's local credential (lib/localCredential.ts). */const send = (port: number, method: string, path: string, headers: Record<string, string> = {}, body?: string): Promise<{ status: number; json: unknown }> =>new Promise((resolve, reject) => {- const req = http.request({ host: '127.0.0.1', port, method, path, headers }, (res) => {+ const credentialed = { 'x-harness-local': readHookCredential(env.ADAPTER_DATA_DIR) ?? '', ...headers }+ const req = http.request({ host: '127.0.0.1', port, method, path, headers: credentialed }, (res) => {let text = ''res.setEncoding('utf8')res.on('data', (chunk: string) => { text += chunk })diff --git a/cli/src/lib/subscriptionRelay.spec.ts b/cli/src/lib/subscriptionRelay.spec.tsnew file mode 100644index 000000000..ff5e136a2--- /dev/null+++ b/cli/src/lib/subscriptionRelay.spec.ts@@ -0,0 +1,257 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'+import type { AddressInfo } from 'node:net'+import type { OwnerCredential, OwnerSubscriptions, SubscriptionProvider } from './ownerSubscriptions.js'+import {+ CLAUDE_OAUTH_BETA,+ claudeRelayEnv,+ codexRelayArgs,+ codexRelayEnv,+ startSubscriptionRelay,+ type SubscriptionRelay,+} from './subscriptionRelay.js'++const OWNER_CLAUDE = 'sk-ant-oat01-OWNER-SECRET'+const OWNER_CLAUDE_FRESH = 'sk-ant-oat01-OWNER-FRESH'+const OWNER_CODEX = 'codex-OWNER-SECRET'++interface Seen { method: string; url: string; headers: IncomingMessage['headers']; body: string }++/** A vendor on a local port: records every request and answers with [answer]. */+async function vendor(answer: (req: IncomingMessage, res: ServerResponse, seen: Seen) => void | Promise<void>) {+ const seen: Seen[] = []+ const server: Server = createServer(async (req, res) => {+ const chunks: Buffer[] = []+ for await (const chunk of req) chunks.push(chunk as Buffer)+ const entry = { method: req.method ?? '', url: req.url ?? '', headers: req.headers, body: Buffer.concat(chunks).toString() }+ seen.push(entry)+ await answer(req, res, entry)+ })+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))+ const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`+ return { seen, url, close: () => new Promise<void>((r) => { server.closeAllConnections(); server.close(() => r()) }) }+}++/** The owner's sign-ins as the relay sees them, and how often it was asked to refresh. */+function owner(initial: Partial<Record<SubscriptionProvider, OwnerCredential | null>>) {+ const current = { claude: null, codex: null, ...initial } as Record<SubscriptionProvider, OwnerCredential | null>+ const refreshed: Array<{ provider: SubscriptionProvider; stale: string | null }> = []+ let next: Partial<Record<SubscriptionProvider, OwnerCredential | null>> = {}+ const subscriptions: OwnerSubscriptions = {+ read: async (provider) => current[provider],+ refresh: async (provider, stale) => {+ refreshed.push({ provider, stale: stale?.accessToken ?? null })+ if (provider in next) current[provider] = next[provider] ?? null+ return current[provider]+ },+ }+ return { subscriptions, refreshed, willRefreshTo: (value: typeof next) => { next = value } }+}++const claude = (accessToken: string, expiresAt: number | null = null): OwnerCredential =>+ ({ provider: 'claude', accessToken, expiresAt, accountId: null })+const codex = (accessToken: string, accountId = 'acct-owner'): OwnerCredential =>+ ({ provider: 'codex', accessToken, expiresAt: null, accountId })++let relay: SubscriptionRelay+let upstream: Awaited<ReturnType<typeof vendor>>+let lines: string[]++beforeEach(() => { lines = [] })+afterEach(async () => {+ await relay?.close()+ await upstream?.close()+})++async function start(answer: Parameters<typeof vendor>[0], subscriptions: OwnerSubscriptions, now = () => 1_000_000) {+ upstream = await vendor(answer)+ relay = await startSubscriptionRelay({+ owner: subscriptions,+ upstream: { claude: upstream.url, codex: `${upstream.url}/backend-api/codex` },+ now,+ log: (line) => lines.push(line),+ })+}++const ok = (_req: IncomingMessage, res: ServerResponse) => { res.writeHead(200, { 'content-type': 'application/json' }); res.end('{"ok":true}') }++describe('the guest token', () => {+ it('is required, must be one minted here, and stops working when the guest is revoked', async () => {+ await start(ok, owner({ claude: claude(OWNER_CLAUDE) }).subscriptions)+ const post = (headers: Record<string, string>) => fetch(`${relay.url}/claude/v1/messages`, { method: 'POST', headers, body: '{}' })+ expect((await post({})).status).toBe(401)+ expect((await post({ authorization: 'Bearer not-a-token' })).status).toBe(401)+ const token = relay.mintToken('[email protected]')+ expect((await post({ authorization: `Bearer ${token}` })).status).toBe(200)+ // Claude Code with an API key sends it as x-api-key; that works too.+ expect((await post({ 'x-api-key': token })).status).toBe(200)+ relay.revoke('[email protected]')+ expect((await post({ authorization: `Bearer ${token}` })).status).toBe(401)+ expect((await fetch(`${relay.url}/elsewhere`, { headers: { authorization: `Bearer ${token}` } })).status).toBe(404)+ expect(upstream.seen).toHaveLength(2)+ // Each refusal is in the owner's log too.+ expect(lines.filter((line) => line.includes('→ 401 · no guest'))).toHaveLength(3)+ })++ it('listens on loopback only', async () => {+ await start(ok, owner({}).subscriptions)+ expect(relay.url).toMatch(/^http:\/\/127\.0\.0\.1:\d+$/)+ })+})++describe('Claude', () => {+ it('goes upstream with the owner\'s bearer and the OAuth beta, and never the guest\'s token', async () => {+ await start(ok, owner({ claude: claude(OWNER_CLAUDE) }).subscriptions)+ const token = relay.mintToken('[email protected]')+ const response = await fetch(`${relay.url}/claude/v1/messages?beta=true`, {+ method: 'POST',+ headers: {+ authorization: `Bearer ${token}`,+ 'x-api-key': token,+ 'anthropic-version': '2023-06-01',+ 'anthropic-beta': 'claude-code-20250219,interleaved-thinking-2025-05-14',+ 'content-type': 'application/json',+ },+ body: '{"model":"claude-sonnet-4-5","messages":[]}',+ })+ expect(await response.json()).toEqual({ ok: true })+ const [request] = upstream.seen+ expect(request!.method).toBe('POST')+ expect(request!.url).toBe('/v1/messages?beta=true')+ expect(request!.body).toBe('{"model":"claude-sonnet-4-5","messages":[]}')+ expect(request!.headers.authorization).toBe(`Bearer ${OWNER_CLAUDE}`)+ expect(request!.headers['x-api-key']).toBeUndefined()+ expect(request!.headers['anthropic-version']).toBe('2023-06-01')+ expect(request!.headers['anthropic-beta']).toBe(`claude-code-20250219,interleaved-thinking-2025-05-14,${CLAUDE_OAUTH_BETA}`)+ expect(JSON.stringify(request!.headers)).not.toContain(token)+ })++ it('adds the beta once, even when the guest already sent it', async () => {+ await start(ok, owner({ claude: claude(OWNER_CLAUDE) }).subscriptions)+ const token = relay.mintToken('[email protected]')+ await fetch(`${relay.url}/claude/v1/messages`, { method: 'POST', headers: { authorization: `Bearer ${token}`, 'anthropic-beta': CLAUDE_OAUTH_BETA }, body: '{}' })+ expect(upstream.seen[0]!.headers['anthropic-beta']).toBe(CLAUDE_OAUTH_BETA)+ })++ it('streams the answer chunk by chunk, as the vendor sends it', async () => {+ let release!: () => void+ const second = new Promise<void>((resolve) => { release = resolve })+ await start(async (_req, res) => {+ res.writeHead(200, { 'content-type': 'text/event-stream' })+ res.write('event: message_start\ndata: {"n":1}\n\n')+ await second // the relay must deliver the first event before the vendor sends the second+ res.end('event: message_stop\ndata: {"n":2}\n\n')+ }, owner({ claude: claude(OWNER_CLAUDE) }).subscriptions)+ const token = relay.mintToken('[email protected]')+ const response = await fetch(`${relay.url}/claude/v1/messages`, { method: 'POST', headers: { authorization: `Bearer ${token}` }, body: '{}' })+ expect(response.headers.get('content-type')).toBe('text/event-stream')+ const reader = response.body!.getReader()+ const decoder = new TextDecoder()+ const first = decoder.decode((await reader.read()).value)+ expect(first).toContain('message_start')+ release()+ let rest = ''+ for (;;) { const { done, value } = await reader.read(); if (done) break; rest += decoder.decode(value) }+ expect(rest).toContain('message_stop')+ })++ it('refreshes an expired token before spending it', async () => {+ const o = owner({ claude: claude(OWNER_CLAUDE, 1_000) })+ o.willRefreshTo({ claude: claude(OWNER_CLAUDE_FRESH, 9_999_999) })+ await start(ok, o.subscriptions, () => 1_000_000)+ const token = relay.mintToken('[email protected]')+ await fetch(`${relay.url}/claude/v1/messages`, { method: 'POST', headers: { authorization: `Bearer ${token}` }, body: '{}' })+ expect(o.refreshed).toEqual([{ provider: 'claude', stale: OWNER_CLAUDE }])+ expect(upstream.seen.map((s) => s.headers.authorization)).toEqual([`Bearer ${OWNER_CLAUDE_FRESH}`])+ })++ it('refreshes once on a 401 and retries, then passes a second 401 through', async () => {+ const o = owner({ claude: claude(OWNER_CLAUDE) })+ o.willRefreshTo({ claude: claude(OWNER_CLAUDE_FRESH) })+ await start((_req, res) => { res.writeHead(401, { 'content-type': 'application/json' }); res.end('{"error":"nope"}') }, o.subscriptions)+ const token = relay.mintToken('[email protected]')+ const response = await fetch(`${relay.url}/claude/v1/messages`, { method: 'POST', headers: { authorization: `Bearer ${token}` }, body: '{"x":1}' })+ expect(response.status).toBe(401)+ expect(o.refreshed).toHaveLength(1)+ expect(upstream.seen.map((s) => s.headers.authorization)).toEqual([`Bearer ${OWNER_CLAUDE}`, `Bearer ${OWNER_CLAUDE_FRESH}`])+ expect(upstream.seen.map((s) => s.body)).toEqual(['{"x":1}', '{"x":1}'])+ })++ it('says the owner is not signed in rather than forwarding without a token', async () => {+ await start(ok, owner({ claude: null }).subscriptions)+ const token = relay.mintToken('[email protected]')+ const response = await fetch(`${relay.url}/claude/v1/messages`, { method: 'POST', headers: { authorization: `Bearer ${token}` }, body: '{}' })+ expect(response.status).toBe(503)+ expect(JSON.stringify(await response.json())).toContain('not signed in to Claude')+ expect(upstream.seen).toHaveLength(0)+ // The owner reads why a guest's harness keeps retrying: their own sign-in.+ expect(lines).toEqual([expect.stringMatching(/^claude POST \/claude\/v1\/messages → 503 · owner not signed in · guest [0-9a-f]+$/)])+ })+})++describe('Codex', () => {+ it('goes to the Codex backend with the owner\'s token and account, whatever account the guest named', async () => {+ await start(ok, owner({ codex: codex(OWNER_CODEX, 'acct-owner') }).subscriptions)+ const token = relay.mintToken('[email protected]')+ await fetch(`${relay.url}/codex/responses`, {+ method: 'POST',+ headers: { authorization: `Bearer ${token}`, 'chatgpt-account-id': 'acct-guest', 'content-type': 'application/json' },+ body: '{"model":"gpt-5-codex","stream":true}',+ })+ const [request] = upstream.seen+ expect(request!.url).toBe('/backend-api/codex/responses')+ expect(request!.headers.authorization).toBe(`Bearer ${OWNER_CODEX}`)+ expect(request!.headers['chatgpt-account-id']).toBe('acct-owner')+ expect(request!.headers['anthropic-beta']).toBeUndefined()+ })+})++describe('secrets', () => {+ it('never put a token in a log line or in an error a guest sees', async () => {+ const o = owner({ claude: claude(OWNER_CLAUDE) })+ upstream = await vendor(ok)+ relay = await startSubscriptionRelay({+ owner: o.subscriptions,+ // A network failure whose message carries everything it was given.+ fetchImpl: (async (url: string, init: RequestInit) => { throw new Error(`failed ${url} ${JSON.stringify(init.headers)}`) }) as unknown as typeof fetch,+ log: (line) => lines.push(line),+ })+ const token = relay.mintToken('[email protected]')+ const failed = await fetch(`${relay.url}/claude/v1/messages`, { method: 'POST', headers: { authorization: `Bearer ${token}` }, body: '{}' })+ expect(failed.status).toBe(502)+ const text = await failed.text()+ expect(text).not.toContain(OWNER_CLAUDE)+ expect(text).not.toContain(token)+ await relay.close()++ await start(ok, o.subscriptions)+ const second = relay.mintToken('[email protected]')+ await fetch(`${relay.url}/claude/v1/messages`, { method: 'POST', headers: { authorization: `Bearer ${second}` }, body: '{}' })+ expect(lines.length).toBeGreaterThan(0)+ for (const line of lines) {+ expect(line).not.toContain(OWNER_CLAUDE)+ expect(line).not.toContain(second)+ expect(line).not.toContain('[email protected]')+ }+ })+})++describe('the launch contract', () => {+ it('points Claude Code at the relay with the bearer variable', () => {+ expect(claudeRelayEnv('http://127.0.0.1:4242/', 'tok')).toEqual({ ANTHROPIC_BASE_URL: 'http://127.0.0.1:4242/claude', ANTHROPIC_AUTH_TOKEN: 'tok' })+ })++ it('points Codex at the relay through its own provider, the token in the environment, web search kept', () => {+ const args = codexRelayArgs('http://127.0.0.1:4242')+ expect(args).toEqual([+ '-c', 'model_provider="harness_owner"',+ '-c', 'model_providers.harness_owner.name="Owner subscription"',+ '-c', 'model_providers.harness_owner.base_url="http://127.0.0.1:4242/codex"',+ '-c', 'model_providers.harness_owner.env_key="HARNESS_RELAY_TOKEN"',+ '-c', 'model_providers.harness_owner.wire_api="responses"',+ '-c', 'model_providers.harness_owner.supports_websockets=false',+ ])+ expect(args.join(' ')).not.toContain('web_search')+ expect(codexRelayEnv('tok')).toEqual({ HARNESS_RELAY_TOKEN: 'tok' })+ })+})diff --git a/cli/src/lib/subscriptionRelay.ts b/cli/src/lib/subscriptionRelay.tsnew file mode 100644index 000000000..577ce1cd1--- /dev/null+++ b/cli/src/lib/subscriptionRelay.ts@@ -0,0 +1,281 @@+/**+ * The owner subscription relay: a guest's harness, running as the guest's own OS user on the+ * owner's machine, spends the OWNER's Claude or ChatGPT subscription without ever holding the+ * owner's token (docs/plans/2026-10-19-guest-machine-sharing-plan.md, "Owner subscription relay").+ *+ * - Loopback only (127.0.0.1, a random port). Every request carries a **guest token** minted here,+ * as `Authorization: Bearer` (what Claude Code sends for `ANTHROPIC_AUTH_TOKEN` and Codex for a+ * provider's `env_key`) or `x-api-key`. Tokens are random, held in memory, compared in constant+ * time, and revoked per guest the moment sharing with them ends.+ * - `/claude/*` goes to the Anthropic API with the owner's OAuth bearer and the OAuth beta.+ * `/codex/*` goes to the ChatGPT Codex backend with the owner's access token and account id.+ * - Bodies stream back as they come (SSE). An expired token is refreshed before it is spent; an+ * upstream 401 is refreshed and retried once (`ownerSubscriptions.ts`).+ *+ * Integration seams: `startSubscriptionRelay` (the daemon starts one and keeps it), and the launch+ * contract at the bottom (`claudeRelayEnv`, `codexRelayArgs`, `codexRelayEnv`), which a guest's+ * launch merges the way `gridLaunch.ts` merges a grid's.+ *+ * ⚠️ No token — the owner's or a guest's — is ever logged or put in an error a client sees.+ */+import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'+import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'+import type { AddressInfo } from 'node:net'+import {+ expired,+ type OwnerCredential,+ type OwnerSubscriptions,+ type SubscriptionProvider,+} from './ownerSubscriptions.js'++export const ANTHROPIC_UPSTREAM = 'https://api.anthropic.com'+/**+ * Where Codex's ChatGPT sign-in sends its Responses requests. **Assumed** (not verified on this+ * machine): `https://chatgpt.com/backend-api/codex`, with `Authorization: Bearer <access token>` and+ * `ChatGPT-Account-Id`. A Codex pointed at this relay through a custom provider asks+ * `<base_url>/responses`, which lands on `<upstream>/responses`.+ */+export const CODEX_UPSTREAM = 'https://chatgpt.com/backend-api/codex'+/** The beta Anthropic requires for a Claude Code OAuth token (verified in Claude Code 2.1.283). */+export const CLAUDE_OAUTH_BETA = 'oauth-2025-04-20'++/** The provider id a guest's Codex is pointed at, and the variable its relay token travels in. */+export const OWNER_CODEX_PROVIDER = 'harness_owner'+export const RELAY_TOKEN_VAR = 'HARNESS_RELAY_TOKEN'++/** A request body this large is not a model request. */+const MAX_BODY_BYTES = 32 * 1024 * 1024++const HOP_BY_HOP = new Set([+ 'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailer',+ 'transfer-encoding', 'upgrade', 'host', 'content-length',+])++export interface SubscriptionRelayDeps {+ owner: OwnerSubscriptions+ fetchImpl?: typeof fetch+ upstream?: Partial<Record<SubscriptionProvider, string>>+ now?: () => number+ /** One line per request: provider, status, a short guest fingerprint. Never a token. */+ log?: (line: string) => void+}++export interface SubscriptionRelay {+ port: number+ /** `http://127.0.0.1:<port>` — the base the launch contract builds on. */+ url: string+ /** A new token for [guestEmail]; a guest may hold several (one per harness). */+ mintToken(guestEmail: string): string+ /** Every token [guestEmail] holds stops working at once. */+ revoke(guestEmail: string): void+ close(): Promise<void>+}++export async function startSubscriptionRelay(deps: SubscriptionRelayDeps): Promise<SubscriptionRelay> {+ const fetchImpl = deps.fetchImpl ?? fetch+ const now = deps.now ?? Date.now+ const upstream = { claude: deps.upstream?.claude ?? ANTHROPIC_UPSTREAM, codex: deps.upstream?.codex ?? CODEX_UPSTREAM }+ // sha256(token) -> guest. Keyed by the digest so the secret itself is never a map key, and the+ // match is confirmed with timingSafeEqual on the digests.+ const tokens = new Map<string, { guest: string; digest: Buffer }>()++ const guestFor = (presented: string | null): string | null => {+ if (!presented) return null+ const digest = createHash('sha256').update(presented).digest()+ const entry = tokens.get(digest.toString('hex'))+ return entry && timingSafeEqual(entry.digest, digest) ? entry.guest : null+ }++ const server = createServer((req, res) => {+ handle(req, res).catch(() => {+ // Never the error's message: a fetch failure can carry a URL, and nothing here may echo a token.+ if (!res.headersSent) fail(res, 502, 'The subscription relay could not reach the vendor.')+ else res.destroy()+ })+ })++ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {+ const url = new URL(req.url ?? '/', 'http://relay')+ const [, first, ...rest] = url.pathname.split('/')+ const provider: SubscriptionProvider | null = first === 'claude' || first === 'codex' ? first : null+ if (!provider) return fail(res, 404, 'Unknown relay route.')+ const guest = guestFor(presentedToken(req))+ if (!guest) {+ deps.log?.(`${provider} ${req.method} ${url.pathname} → 401 · no guest`)+ return fail(res, 401, 'Not a valid guest token for this relay.')+ }++ const body = await readBody(req)+ if (body === null) return fail(res, 413, 'Request too large.')+ const target = `${upstream[provider].replace(/\/$/, '')}/${rest.join('/')}${url.search}`++ let credential = await deps.owner.read(provider)+ if (credential && expired(credential, now())) credential = await deps.owner.refresh(provider, credential)+ if (!credential) {+ // Said in the owner's log too: a guest's harness retrying this is the owner's sign-in to fix.+ deps.log?.(`${provider} ${req.method} ${url.pathname} → 503 · owner not signed in · guest ${fingerprint(guest)}`)+ return fail(res, 503, provider === 'claude'+ ? 'The owner of this computer is not signed in to Claude.'+ : 'The owner of this computer is not signed in to ChatGPT.')+ }++ const abort = new AbortController()+ res.on('close', () => { if (!res.writableFinished) abort.abort() })+ const send = (spend: OwnerCredential): Promise<Response> => fetchImpl(target, {+ method: req.method ?? 'GET',+ headers: upstreamHeaders(provider, req.headers, spend),+ body: body.length > 0 && req.method !== 'GET' && req.method !== 'HEAD' ? new Uint8Array(body) : undefined,+ signal: abort.signal,+ })++ let response = await send(credential)+ if (response.status === 401) {+ // Once: the owner's CLI may have rotated the token, or it lapsed early.+ const fresh = await deps.owner.refresh(provider, credential)+ if (fresh && fresh.accessToken !== credential.accessToken) {+ await response.body?.cancel().catch(() => {})+ response = await send(fresh)+ }+ }+ deps.log?.(`${provider} ${req.method} ${url.pathname} → ${response.status} · guest ${fingerprint(guest)}`)+ await pipe(response, res)+ }++ await new Promise<void>((resolve, reject) => {+ server.once('error', reject)+ server.listen(0, '127.0.0.1', () => resolve())+ })+ const port = (server.address() as AddressInfo).port++ return {+ port,+ url: `http://127.0.0.1:${port}`,+ mintToken(guestEmail) {+ const token = randomBytes(32).toString('base64url')+ const digest = createHash('sha256').update(token).digest()+ tokens.set(digest.toString('hex'), { guest: guestEmail.toLowerCase(), digest })+ return token+ },+ revoke(guestEmail) {+ const guest = guestEmail.toLowerCase()+ for (const [key, entry] of tokens) if (entry.guest === guest) tokens.delete(key)+ },+ close: () => new Promise<void>((resolve) => {+ server.closeAllConnections?.()+ server.close(() => resolve())+ }),+ }+}++/** The guest token, from a bearer or an API-key header. */+function presentedToken(req: IncomingMessage): string | null {+ const auth = req.headers.authorization+ if (typeof auth === 'string' && /^bearer\s+/i.test(auth)) return auth.replace(/^bearer\s+/i, '').trim() || null+ const key = req.headers['x-api-key']+ return typeof key === 'string' && key.trim() ? key.trim() : null+}++/** The guest's request headers with its token taken out and the owner's put in. */+export function upstreamHeaders(+ provider: SubscriptionProvider,+ incoming: IncomingMessage['headers'],+ owner: OwnerCredential,+): Record<string, string> {+ const headers: Record<string, string> = {}+ for (const [name, value] of Object.entries(incoming)) {+ const key = name.toLowerCase()+ if (HOP_BY_HOP.has(key) || key === 'authorization' || key === 'x-api-key' || value === undefined) continue+ if (provider === 'codex' && key === 'chatgpt-account-id') continue+ headers[key] = Array.isArray(value) ? value.join(', ') : value+ }+ // Uncompressed, so the stream can be passed through as it arrives.+ headers['accept-encoding'] = 'identity'+ headers.authorization = `Bearer ${owner.accessToken}`+ if (provider === 'claude') {+ const betas = (headers['anthropic-beta'] ?? '').split(',').map((b) => b.trim()).filter(Boolean)+ if (!betas.includes(CLAUDE_OAUTH_BETA)) betas.push(CLAUDE_OAUTH_BETA)+ headers['anthropic-beta'] = betas.join(',')+ } else if (owner.accountId) {+ headers['chatgpt-account-id'] = owner.accountId+ }+ return headers+}++async function readBody(req: IncomingMessage): Promise<Buffer | null> {+ const chunks: Buffer[] = []+ let size = 0+ for await (const chunk of req) {+ size += (chunk as Buffer).length+ if (size > MAX_BODY_BYTES) return null+ chunks.push(chunk as Buffer)+ }+ return Buffer.concat(chunks)+}++/** The vendor's answer, status and headers first, then each chunk as it arrives. */+async function pipe(response: Response, res: ServerResponse): Promise<void> {+ const headers: Record<string, string> = {}+ response.headers.forEach((value, name) => {+ const key = name.toLowerCase()+ if (!HOP_BY_HOP.has(key) && key !== 'content-encoding') headers[key] = value+ })+ res.writeHead(response.status, headers)+ res.flushHeaders()+ if (!response.body) { res.end(); return }+ const reader = response.body.getReader()+ try {+ for (;;) {+ const { done, value } = await reader.read()+ if (done) break+ if (!res.write(value)) await new Promise((resolve) => res.once('drain', resolve))+ }+ } finally {+ res.end()+ }+}++function fail(res: ServerResponse, status: number, message: string): void {+ res.writeHead(status, { 'content-type': 'application/json' })+ res.end(JSON.stringify({ type: 'error', error: { type: 'harness_relay_error', message } }))+}++/** A short, stable, non-reversible label for a guest in logs. */+function fingerprint(guest: string): string {+ return createHash('sha256').update(guest).digest('hex').slice(0, 8)+}++// ── The launch contract ───────────────────────────────────────────────────────────────────────++/**+ * Claude Code pointed at the relay: `ANTHROPIC_AUTH_TOKEN` is sent as `Authorization: Bearer`, the+ * variable `gridLaunch.ts` uses for the same reason. Unlike a grid launch, web tools stay on: the+ * relay reaches the real Anthropic API. The integrator must also clear the owner-side variables a+ * guest pane might inherit (`GRID_CONFLICTING_ENV_VARS`) — the guest helper's `env -i` does.+ */+export function claudeRelayEnv(relayUrl: string, token: string): Record<string, string> {+ return { ANTHROPIC_BASE_URL: `${relayUrl.replace(/\/$/, '')}/claude`, ANTHROPIC_AUTH_TOKEN: token }+}++/**+ * Codex pointed at the relay through a provider of its own, mirroring the grid contract+ * (`gridLaunch.ts`) but WITHOUT disabling web search. The token travels in the environment under+ * `env_key`, never in argv.+ *+ * ⚠️ Codex records the provider per thread; `engines/codex/launch.ts`'s `ownProvider` handling must+ * learn `harness_owner`, as it learned `grid`, or a resume names the wrong provider.+ */+export function codexRelayArgs(relayUrl: string): string[] {+ const p = OWNER_CODEX_PROVIDER+ return [+ '-c', `model_provider="${p}"`,+ '-c', `model_providers.${p}.name="Owner subscription"`,+ '-c', `model_providers.${p}.base_url="${relayUrl.replace(/\/$/, '')}/codex"`,+ '-c', `model_providers.${p}.env_key="${RELAY_TOKEN_VAR}"`,+ '-c', `model_providers.${p}.wire_api="responses"`,+ '-c', `model_providers.${p}.supports_websockets=false`,+ ]+}++export function codexRelayEnv(token: string): Record<string, string> {+ return { [RELAY_TOKEN_VAR]: token }+}diff --git a/cli/src/localWsServer.spec.ts b/cli/src/localWsServer.spec.tsindex 2d12dc3b0..0f5321209 100644--- a/cli/src/localWsServer.spec.ts+++ b/cli/src/localWsServer.spec.ts@@ -168,6 +168,46 @@ describe('local CLI WebSocket', () => {}})+ // The port takes any OS user's process — a guest's harness running as its own user+ // (docs/plans/2026-10-19-guest-machine-sharing-plan.md); only this user can read the 0600 credential.+ it('takes a TCP upgrade only with the daemon\'s local credential, by header or bearer', async () => {+ const credential = 'c'.repeat(43)+ const url = await start(new FakeBackend(), { localCredential: credential })+ const refused = async (headers: Record<string, string>): Promise<number> => {+ const ws = new WebSocket(url, { headers })+ return new Promise<number>((resolve) => ws.once('unexpected-response', (_req, res) => resolve(res.statusCode ?? 0)))+ }+ expect(await refused({})).toBe(401)+ expect(await refused({ 'x-harness-local': 'w'.repeat(43) })).toBe(401)+ for (const headers of [{ 'x-harness-local': credential }, { authorization: `Bearer ${credential}` }]) {+ const ws = new WebSocket(url, { headers })+ await onceOpen(ws)+ const connected = onceMessage(ws)+ ws.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1 } }))+ expect(await connected).toMatchObject({ type: 'connected', payload: { machineId } })+ ws.close()+ }+ })++ it('takes an upgrade over the daemon\'s socket with no credential, the TCP port still wanting one', async () => {+ const dir = mkdtempSync('/tmp/lws-cred-')+ const socketPath = join(dir, 'daemon.sock')+ const unix = await listenLocalSocket((_req, res) => { res.statusCode = 404; res.end() }, socketPath)+ const tcp = await start(new FakeBackend(), { localSocketServer: unix.server, localCredential: 'c'.repeat(43) })+ try {+ const ws = new WebSocket(`ws+unix://${socketPath}:/api/local-ws`)+ await onceOpen(ws)+ ws.close()+ const refused = new WebSocket(tcp)+ expect(await new Promise<number>((resolve) => refused.once('unexpected-response', (_req, res) => resolve(res.statusCode ?? 0)))).toBe(401)+ } finally {+ await local?.close()+ local = null+ await unix.close()+ rmSync(dir, { recursive: true, force: true })+ }+ })+it('refuses an upgrade whose Host is not a loopback name for this port', async () => {const url = await start(new FakeBackend())const ws = new WebSocket(url, { headers: { host: 'rebind.evil.example:' + new URL(url).port } })diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.tsindex 83c9224b3..33d536b1a 100644--- a/cli/src/localWsServer.ts+++ b/cli/src/localWsServer.ts@@ -7,6 +7,7 @@ import { WebSocket, WebSocketServer, type RawData } from 'ws'import { watchSocketLiveness } from './lib/wsLiveness.js'import { isLoopbackRequest, loopbackHosts } from './lib/loopbackRequest.js'import { isTrustedLocal } from './lib/localSocket.js'+import { localCredentialMatches } from './lib/localCredential.js'import type { Frame, LocalClientSink } from './backendSocket.js'import {decodeTerminalLocal,@@ -51,6 +52,9 @@ export interface LocalWsServerOptions {backend: LocalWsBackend/** The daemon's Unix-socket server (lib/localSocket.ts), served the same endpoint beside TCP. */localSocketServer?: http.Server | null+ /** The daemon's local credential (lib/localCredential.ts). Given, a TCP upgrade must carry it: the+ * loopback port takes any local OS user's process, the Unix socket only this user's. */+ localCredential?: string/** Serves a `machine_select` for any OTHER machine this signed-in user owns, by relaying to* backend's `/api/web-ws` — see lib/remoteRelay.ts — and one for a harness shared with this account* (`shareId`, sharing/relay.ts). Both are the gateway's. Omit to keep today's own-machine-only behavior. */@@ -281,9 +285,10 @@ function withLocalClient(frame: Frame, localClient: LocalWsServerOptions['localC}/**- * Add an internal loopback WebSocket endpoint to the CLI's existing HTTP server. It intentionally has- * no credential: loopback-only, no Origin header, and the desktop computer-id validation identify the- * local process without placing SSO credentials on this transport.+ * Add an internal loopback WebSocket endpoint to the CLI's existing HTTP server. Over the daemon's Unix+ * socket it takes no credential: the filesystem says who the peer is. Over TCP it takes the daemon's+ * local credential (lib/localCredential.ts) — never an SSO credential — besides being loopback-only with+ * no Origin header: any OS user's process can reach the loopback port.*//** How long a closing server waits for its clients to answer the close before it drops them. */export const LOCAL_WS_CLOSE_GRACE_MS = 1_000@@ -292,8 +297,8 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerOconst wss = new WebSocketServer({noServer: true,maxPayload: MAX_WS_MESSAGE_BYTES,- // The loopback endpoint deliberately has no credential. Echo a protocol only for generic WS- // clients that insist on proposing one; it carries no authority and is never inspected.+ // The local credential travels in a header, never a subprotocol. Echo a protocol only for generic+ // WS clients that insist on proposing one; it carries no authority and is never inspected.handleProtocols: (protocols) => [...protocols][0] ?? false,})// One desktop can have a connection per machine. Once a live window reports its selected pane,@@ -326,6 +331,12 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerOrejectUpgrade(socket, 403, 'Forbidden')return}+ // Another OS user's process reaches this port too (a guest's harness, say): only this user's carries+ // the credential.+ if (options.localCredential !== undefined && !localCredentialMatches(options.localCredential, req)) {+ rejectUpgrade(socket, 401, 'Unauthorized')+ return+ }wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req))}const servers = [server, ...(options.localSocketServer ? [options.localSocketServer] : [])]diff --git a/cli/src/messages/rpc.ts b/cli/src/messages/rpc.tsindex 66dc761ae..5c6bb8e94 100644--- a/cli/src/messages/rpc.ts+++ b/cli/src/messages/rpc.ts@@ -4,6 +4,8 @@* send` reaches its own daemon the same way.*/import { randomBytes } from 'node:crypto'+import { env } from '../config/env.js'+import { localCredentialHeaders } from '../lib/localCredential.js'import { existsSync } from 'node:fs'import { WebSocket } from 'ws'import { localSocketPath } from '../lib/localSocket.js'@@ -22,7 +24,7 @@ export const messagesRpc: Rpc = (target, payload, timeoutMs = 20_000) => new Proconst socketPath = target.dataDir ? localSocketPath(target.dataDir, target.port) : nullconst ws = socketPath && existsSync(socketPath)? new WebSocket(`ws+unix://${socketPath}:/api/local-ws`)- : new WebSocket(`ws://127.0.0.1:${target.port}/api/local-ws`)+ : new WebSocket(`ws://127.0.0.1:${target.port}/api/local-ws`, { headers: localCredentialHeaders(target.dataDir ?? env.ADAPTER_DATA_DIR) })const requestId = randomBytes(16).toString('hex')let finished = false, selected = falseconst finish = (error: Error | null, value?: Record<string, unknown>): void => {diff --git a/cli/src/orchestrator/command.ts b/cli/src/orchestrator/command.tsindex eb8f8ccbb..eb34fe486 100644--- a/cli/src/orchestrator/command.ts+++ b/cli/src/orchestrator/command.ts@@ -1,4 +1,5 @@import { randomBytes } from 'node:crypto'+import { localCredentialHeaders } from '../lib/localCredential.js'import { WebSocket } from 'ws'import { env } from '../config/env.js'import { readAuthSession } from '../lib/authSession.js'@@ -6,7 +7,7 @@ import { readAuthSession } from '../lib/authSession.js'export function localOrchestratorRequest(port: number, machineId: string, payload: Record<string, unknown>, timeoutMs = 30_000): Promise<Record<string, unknown>> {return new Promise((resolve, reject) => {const requestId = randomBytes(16).toString('hex')- const ws = new WebSocket(`ws://127.0.0.1:${port}/api/local-ws`)+ const ws = new WebSocket(`ws://127.0.0.1:${port}/api/local-ws`, { headers: localCredentialHeaders(env.ADAPTER_DATA_DIR) })let settled = falseconst finish = (error?: Error, reply?: Record<string, unknown>): void => {if (settled) returndiff --git a/cli/src/remoteCommand.ts b/cli/src/remoteCommand.tsindex 471368d62..a725836a2 100644--- a/cli/src/remoteCommand.ts+++ b/cli/src/remoteCommand.ts@@ -14,6 +14,8 @@* an offline machine is listed but cannot be taken: there is nothing there to open a shell on.*/import { randomUUID } from 'node:crypto'+import { localCredentialHeaders } from './lib/localCredential.js'+import { env } from './config/env.js'import { emitKeypressEvents } from 'node:readline'import { WebSocket } from 'ws'import { TMUX_PANE_RE } from './lib/terminalHandoff.js'@@ -146,7 +148,8 @@ export class LoopbackClient {private readonly socket: LoopbackSocketprivate readonly opened: Promise<void>- constructor(url: string, connect: (url: string) => LoopbackSocket = (target) => new WebSocket(target) as unknown as LoopbackSocket) {+ constructor(url: string, connect: (url: string) => LoopbackSocket = (target) =>+ new WebSocket(target, { headers: localCredentialHeaders(env.ADAPTER_DATA_DIR) }) as unknown as LoopbackSocket) {this.socket = connect(url)this.opened = new Promise((resolve, reject) => {this.socket.on('open', () => resolve())diff --git a/cli/src/services/guestLaunches.spec.ts b/cli/src/services/guestLaunches.spec.tsnew file mode 100644index 000000000..ad302911f--- /dev/null+++ b/cli/src/services/guestLaunches.spec.ts@@ -0,0 +1,198 @@+import { describe, expect, it, vi } from 'vitest'+import { GuestHelperError, guestUserFor, type GuestAccounts, type SharedFolder } from '../lib/guestAccounts.js'+import type { GuestHelperState } from '../lib/guestHelperInstall.js'+import type { SubscriptionRelay } from '../lib/subscriptionRelay.js'+import { createGuestLaunches } from './guestLaunches.js'++const KIM = guestUserFor('[email protected]')+const LEE = guestUserFor('[email protected]')+const OLD = guestUserFor('[email protected]')++// Never a real OS account, helper or relay: each is a fake the test controls.+function setup(over: {+ state?: GuestHelperState; ensure?: GuestAccounts['ensureGuest']; relay?: () => Promise<SubscriptionRelay>+ folders?: SharedFolder[]; share?: GuestAccounts['shareFolders']; guests?: string[]+} = {}) {+ const revoked: string[] = []+ let n = 0+ const relay: SubscriptionRelay = {+ port: 41234, url: 'http://127.0.0.1:41234',+ mintToken: vi.fn((guest: string) => `token-${guest}-${++n}`),+ revoke: vi.fn((guest: string) => { revoked.push(guest) }),+ close: vi.fn(async () => {}),+ }+ const accounts = {+ ensureGuest: over.ensure ?? vi.fn(async () => ({ user: KIM, home: `/g/${KIM}`, workspace: `/g/${KIM}/work` })),+ installGuestEngine: vi.fn(), removeGuest: vi.fn(), runCommand: vi.fn(),+ shareFolders: vi.fn(over.share ?? (async () => {})),+ guests: vi.fn(() => over.guests ?? []),+ }+ const startRelay = vi.fn(over.relay ?? (async () => relay))+ const lines: string[] = []+ const helperState = vi.fn(async () => over.state ?? 'ready')+ const launches = createGuestLaunches({ accounts: accounts as GuestAccounts, helperState, startRelay, lang: 'en_GB.UTF-8',+ helperPath: '/opt/helper', folders: () => over.folders ?? [], log: (line) => { lines.push(line) } })+ return { launches, relay, accounts, startRelay, revoked, lines, helperState }+}++const flush = () => new Promise((resolve) => setTimeout(resolve, 0))+const input = { email: '[email protected]', engine: 'claude', bypassPermission: true }++describe('a guest\'s harness, as shared machines builds it', () => {+ it('runs as the guest\'s own account, in its workspace, on a token of its own; one relay for every harness', async () => {+ const { launches, accounts, startRelay, lines } = setup()+ const first = await launches.launch({ ...input, email: ' [email protected] ' })+ expect(accounts.ensureGuest).toHaveBeenCalledWith('[email protected]')+ expect(first).toEqual({ ok: true, workspace: `/g/${KIM}/work`, argv: expect.arrayContaining(['/opt/helper', KIM, 'claude']),+ env: expect.objectContaining({ ANTHROPIC_AUTH_TOKEN: '[email protected]', ANTHROPIC_BASE_URL: 'http://127.0.0.1:41234/claude', LANG: 'en_GB.UTF-8' }) })+ const second = await launches.launch({ ...input, engine: 'codex', bypassPermission: true, permissionFlags: ['--approve-for-me'], prompt: 'Fix the tests' })+ expect(second.ok && second.argv.slice(-2)).toEqual(['--approve-for-me', 'Fix the tests'])+ expect(second.ok && second.argv.at(-1)).toBe('Fix the tests')+ expect(second.ok && second.env.HARNESS_RELAY_TOKEN).toBe('[email protected]')+ expect(startRelay).toHaveBeenCalledTimes(1)+ expect(lines).toEqual([`launch · claude · ${KIM}`, `launch · codex · ${KIM}`])+ })++ it('works with the defaults: no log, the machine\'s helper and LANG, no folders', async () => {+ const relay = { port: 1, url: 'http://127.0.0.1:1', mintToken: () => 't', revoke: () => {}, close: async () => {} }+ const shareFolders = vi.fn(async () => {})+ const launches = createGuestLaunches({ accounts: { ensureGuest: async () => ({ user: KIM, home: '/g', workspace: '/g/work' }), shareFolders, guests: () => [KIM] } as unknown as GuestAccounts,+ helperState: async () => 'ready', startRelay: async () => relay })+ const launched = await launches.launch({ ...input, bypassPermission: false })+ expect(launched.ok && launched.argv[4]).toBe('/usr/local/libexec/harness/guest-helper')+ expect(launched.ok && launched.env.LANG).toBe('en_US.UTF-8')+ expect(shareFolders).toHaveBeenCalledWith(KIM, [])+ await launches.sync(() => false, [])+ await launches.stop()+ })++ it('starts nothing for a session whose guest it cannot name, or an engine whose subscription it cannot spend', async () => {+ const { launches, accounts } = setup()+ expect(await launches.launch({ ...input, email: ' ' })).toEqual({ ok: false, error: 'NOT_YOUR_HARNESS', detail: expect.any(String) })+ expect(await launches.launch({ ...input, engine: 'opencode' })).toEqual({ ok: false, error: 'GUEST_ENGINE_UNSUPPORTED', detail: expect.stringMatching(/Claude Code or Codex/) })+ expect(accounts.ensureGuest).not.toHaveBeenCalled()+ })++ it('asks the owner to turn guest access on, in words, until the helper is ready', async () => {+ for (const [state, words] of [['missing', /not turned guest access on/], ['outdated', /after an update/], ['not-authorized', /on again/]] as const) {+ const { launches } = setup({ state })+ expect(await launches.launch(input)).toEqual({ ok: false, error: 'GUEST_HELPER_REQUIRED', detail: expect.stringMatching(words) })+ }+ })++ it('says what the helper said when the account could not be made', async () => {+ const { launches } = setup({ ensure: async () => { throw new GuestHelperError('GUEST_INVALID', 'not an email') } })+ expect(await launches.launch(input)).toEqual({ ok: false, error: 'GUEST_INVALID', detail: 'not an email' })+ const odd = setup({ ensure: async () => { throw new Error('boom') } })+ expect(await odd.launches.launch(input)).toEqual({ ok: false, error: 'GUEST_HELPER_FAILED', detail: 'The guest helper failed.' })+ })++ it('starts the relay again for the next harness when it could not start', async () => {+ let fails = true+ const relay = { port: 1, url: 'http://127.0.0.1:1', mintToken: () => 't', revoke: () => {}, close: async () => {} }+ const { launches, startRelay } = setup({ relay: async () => { if (fails) throw new Error('EADDRINUSE'); return relay } })+ expect(await launches.launch(input)).toEqual({ ok: false, error: 'GUEST_RELAY_FAILED', detail: expect.any(String) })+ await flush()+ fails = false+ expect((await launches.launch(input)).ok).toBe(true)+ expect(startRelay).toHaveBeenCalledTimes(2)+ })++ describe('the owner\'s shared folders', () => {+ const folders = [{ path: '/Users/dee/code/app', write: true }, { path: '/Users/dee/docs/', write: false }]++ it('are the guest\'s on every harness, which starts in one when the guest asks, and in its workspace otherwise', async () => {+ const { launches, accounts } = setup({ folders })+ const inApp = await launches.launch({ ...input, cwd: '/Users/dee/code/app/src/../src' })+ expect(accounts.shareFolders).toHaveBeenCalledWith(KIM, folders)+ expect(inApp).toMatchObject({ ok: true, workspace: '/Users/dee/code/app/src', argv: expect.arrayContaining(['--cwd', '/Users/dee/code/app/src']) })+ expect(await launches.launch({ ...input, cwd: '/Users/dee/docs' })).toMatchObject({ ok: true, workspace: '/Users/dee/docs' })+ // Not shared, a neighbour that only starts the same, relative, or absent: its workspace.+ for (const cwd of ['/Users/dee/secret', '/Users/dee/code/application', 'code/app', undefined]) {+ expect(await launches.launch({ ...input, ...(cwd ? { cwd } : {}) }), String(cwd)).toMatchObject({ ok: true, workspace: `/g/${KIM}/work` })+ }+ })++ it('a share that failed stops a harness meant for that folder, and no other', async () => {+ const { launches, lines } = setup({ folders, share: async () => { throw new GuestHelperError('GUEST_INVALID', 'no such folder: /Users/dee/docs') } })+ expect(await launches.launch({ ...input, cwd: '/Users/dee/docs' })).toEqual({ ok: false, error: 'GUEST_FOLDER_UNAVAILABLE',+ detail: 'That folder could not be shared with you: no such folder: /Users/dee/docs' })+ expect(await launches.launch(input)).toMatchObject({ ok: true, workspace: `/g/${KIM}/work` })+ expect(lines.filter((l) => l.startsWith('could not share'))).toHaveLength(2)+ const odd = setup({ folders, share: async () => { throw 'helper gone' } })+ expect(await odd.launches.launch({ ...input, cwd: '/Users/dee/docs' })).toMatchObject({ detail: 'That folder could not be shared with you: helper gone' })+ })++ it('are shared one at a time: two shares never read the helper\'s record at once', async () => {+ const order: string[] = []+ let release: () => void = () => {}+ const { launches } = setup({ folders, guests: [KIM, LEE], share: async (user) => {+ order.push(`start ${user}`)+ if (order.length === 1) await new Promise<void>((resolve) => { release = resolve })+ order.push(`end ${user}`)+ } })+ const launched = launches.launch(input)+ await flush()+ const synced = launches.sync(() => true, ['[email protected]', '[email protected]'])+ await flush()+ expect(order).toEqual([`start ${KIM}`])+ release()+ await Promise.all([launched, synced])+ expect(order).toEqual([`start ${KIM}`, `end ${KIM}`, `start ${KIM}`, `end ${KIM}`, `start ${LEE}`, `end ${LEE}`])+ })+ })++ describe('sharing kept true', () => {+ it('revokes the tokens of whoever sharing no longer names, once', async () => {+ const { launches, revoked, lines } = setup()+ await launches.sync(() => false, []) // nothing minted, no relay: nothing to do+ await launches.launch(input)+ await launches.launch({ ...input, email: '[email protected]' })+ await launches.sync((email) => email === '[email protected]', [])+ await launches.sync((email) => email === '[email protected]', [])+ await flush()+ expect(revoked).toEqual(['[email protected]'])+ expect(lines.at(-1)).toBe('revoked · [email protected]')+ })++ it('gives every guest still named the owner\'s folders, and takes them from every other account', async () => {+ const folders = [{ path: '/Users/dee/docs', write: false }]+ const { launches, accounts, lines } = setup({ folders, guests: [KIM, LEE, OLD] })+ await launches.sync((email) => email !== '[email protected]', ['[email protected]', '[email protected]'])+ expect(accounts.shareFolders.mock.calls).toEqual([[KIM, folders], [LEE, []], [OLD, []]])+ // One that fails is said, and the rest go on.+ accounts.shareFolders.mockRejectedValueOnce(new Error('EPERM')).mockRejectedValueOnce('gone')+ await launches.sync(() => true, ['[email protected]'])+ expect(lines.filter((l) => l.startsWith('could not share'))).toEqual([`could not share folders with ${KIM}: EPERM`, `could not share folders with ${LEE}: gone`])+ })++ it('asks nothing of the helper while there are no guests, or guest access is off', async () => {+ const none = setup({ folders: [{ path: '/x', write: false }] })+ await none.launches.sync(() => true, ['[email protected]'])+ expect(none.helperState).not.toHaveBeenCalled()+ const off = setup({ state: 'missing', guests: [KIM] })+ await off.launches.sync(() => true, ['[email protected]'])+ expect(off.accounts.shareFolders).not.toHaveBeenCalled()+ })+ })++ it('closes the relay when it stops; one that never started, or fails as it stops, has nothing to close', async () => {+ const { launches, relay } = setup()+ await launches.launch(input)+ await launches.stop()+ expect(relay.close).toHaveBeenCalledTimes(1)+ await launches.stop()+ const never = setup({ relay: async () => { throw new Error('no') } })+ await never.launches.launch(input)+ await never.launches.sync(() => false, [])+ await never.launches.stop()+ let fail: (error: Error) => void = () => {}+ const stopping = setup({ relay: () => new Promise((_resolve, reject) => { fail = reject }) })+ const launched = stopping.launches.launch(input)+ await flush()+ const stopped = stopping.launches.stop()+ fail(new Error('stopped'))+ await stopped+ expect((await launched).ok).toBe(false)+ })+})diff --git a/cli/src/services/guestLaunches.ts b/cli/src/services/guestLaunches.tsnew file mode 100644index 000000000..0607dd5d9--- /dev/null+++ b/cli/src/services/guestLaunches.ts@@ -0,0 +1,139 @@+/**+ * Guests' harnesses, as shared machines builds them (docs/plans/2026-10-19-guest-machine-sharing-plan.md):+ * a guest's own OS account, made on their first harness (lib/guestAccounts.ts), a token for the owner's+ * subscription relay (lib/subscriptionRelay.ts), started on the first harness and kept, the owner's shared+ * folders, and the pane's command (lib/guestPaneCommand.ts). The core opens the pane (core/agents/guestCreate.ts).+ *+ * What sharing says is kept true on each read of it (`sync`): a guest no longer named spends nothing more of+ * the owner's subscriptions, even from a harness still running, and keeps none of the owner's folders; every+ * guest still named has exactly the folders the owner shares.+ */+import { isAbsolute, resolve } from 'node:path'+import type { GuestLaunch, GuestLaunchInput } from '../core/api.js'+import { GuestHelperError, guestUserFor, type GuestAccounts, type SharedFolder } from '../lib/guestAccounts.js'+import type { GuestHelperState } from '../lib/guestHelperInstall.js'+import { GUEST_LAUNCH_ENGINES, guestPaneCommand, type GuestLaunchEngine } from '../lib/guestPaneCommand.js'+import type { SubscriptionRelay } from '../lib/subscriptionRelay.js'++export interface GuestLaunchesDeps {+ accounts: GuestAccounts+ /** Whether the owner turned guest access on here: the helper installed, current and allowed. */+ helperState: () => Promise<GuestHelperState>+ startRelay: () => Promise<SubscriptionRelay>+ /** The owner's folders shared with every guest, as the owner last set them. */+ folders?: () => SharedFolder[]+ helperPath?: string+ lang?: string+ log?: (line: string) => void+}++export interface GuestLaunches {+ launch(input: GuestLaunchInput): Promise<GuestLaunch>+ /**+ * Makes sharing so: [still] says whether the machine is still shared with an address, and [shared] lists the+ * addresses it may be shared with (the policy's and the backend's members). A guest it no longer names loses+ * its relay tokens and the owner's folders; every guest it names has the folders the owner shares.+ */+ sync(still: (email: string) => boolean, shared: readonly string[]): Promise<void>+ stop(): Promise<void>+}++const HELPER_REQUIRED: Record<Exclude<GuestHelperState, 'ready'>, string> = {+ missing: 'The owner of this computer has not turned guest access on yet.',+ outdated: 'The owner of this computer has to turn guest access on again after an update.',+ 'not-authorized': 'The owner of this computer has to turn guest access on again.',+}++/** Whether [path] (resolved) is [folder] or inside it. */+const within = (path: string, folder: string): boolean => {+ const root = resolve(folder)+ return path === root || path.startsWith(`${root}/`)+}++export function createGuestLaunches(deps: GuestLaunchesDeps): GuestLaunches {+ const log = deps.log ?? (() => {})+ const folders = deps.folders ?? (() => [])+ let relay: Promise<SubscriptionRelay> | null = null+ /** Whom tokens were minted for, to revoke when sharing with them ends. */+ const minted = new Set<string>()+ // One share at a time: two at once would each read the helper's record of a guest's folders before the+ // other wrote it, and leave entries neither meant.+ let sharing: Promise<unknown> = Promise.resolve()+ const share = (user: string, owned: readonly SharedFolder[]): Promise<void> => {+ const next = sharing.then(() => deps.accounts.shareFolders(user, owned))+ sharing = next.catch(() => {})+ return next+ }++ const relayOnce = (): Promise<SubscriptionRelay> => {+ if (relay) return relay+ relay = deps.startRelay()+ // A relay that could not start is started again by the next harness.+ relay.catch(() => { relay = null })+ return relay+ }++ return {+ async launch({ email, engine, bypassPermission, prompt, cwd, permissionFlags }) {+ const guest = email.trim().toLowerCase()+ if (!guest) return { ok: false, error: 'NOT_YOUR_HARNESS', detail: 'This computer does not know whom it is shared with here.' }+ if (!GUEST_LAUNCH_ENGINES.includes(engine)) {+ return { ok: false, error: 'GUEST_ENGINE_UNSUPPORTED', detail: 'A guest can start Claude Code or Codex on this computer.' }+ }+ const state = await deps.helperState()+ if (state !== 'ready') return { ok: false, error: 'GUEST_HELPER_REQUIRED', detail: HELPER_REQUIRED[state] }+ let account+ try {+ account = await deps.accounts.ensureGuest(guest)+ } catch (error) {+ const failed = error instanceof GuestHelperError ? error : new GuestHelperError('GUEST_HELPER_FAILED', 'The guest helper failed.')+ return { ok: false, error: failed.code, detail: failed.message }+ }+ // It starts in a folder the owner shares when it asks for one, and in its own workspace otherwise: a+ // folder from an older client, or one of the owner's that is not shared, is not where it runs.+ const shared = folders()+ const start = cwd && isAbsolute(cwd) ? resolve(cwd) : null+ const folder = start ? shared.find((f) => within(start, f.path)) : undefined+ try {+ await share(account.user, shared)+ } catch (error) {+ const detail = error instanceof Error ? error.message : String(error)+ log(`could not share folders with ${account.user}: ${detail}`)+ if (folder) return { ok: false, error: 'GUEST_FOLDER_UNAVAILABLE', detail: `That folder could not be shared with you: ${detail}` }+ }+ const running = await relayOnce().catch(() => null)+ if (!running) return { ok: false, error: 'GUEST_RELAY_FAILED', detail: 'The subscription relay could not start on this computer.' }+ const token = running.mintToken(guest)+ minted.add(guest)+ const where = folder && start ? start : account.workspace+ const command = guestPaneCommand({+ account, engine: engine as GuestLaunchEngine, relayUrl: running.url, token, bypassPermission, cwd: where,+ ...(permissionFlags ? { permissionFlags } : {}),+ ...(prompt ? { prompt } : {}), ...(deps.lang ? { lang: deps.lang } : {}), ...(deps.helperPath ? { helperPath: deps.helperPath } : {}),+ })+ log(`launch · ${engine} · ${account.user}`)+ return { ok: true, workspace: where, argv: command.argv, env: command.env }+ },+ async sync(still, shared) {+ for (const guest of [...minted]) {+ if (still(guest)) continue+ minted.delete(guest)+ // Minted only from a relay that started: it is there, unless the service stopped it.+ void relay?.then((r) => { r.revoke(guest); log(`revoked · ${guest}`) })+ }+ const accounts = deps.accounts.guests()+ if (accounts.length === 0 || await deps.helperState() !== 'ready') return+ const named = new Set(shared.filter(still).map(guestUserFor))+ const owned = folders()+ for (const user of accounts) {+ await share(user, named.has(user) ? owned : [])+ .catch((error: unknown) => log(`could not share folders with ${user}: ${error instanceof Error ? error.message : String(error)}`))+ }+ },+ async stop() {+ const running = await relay?.catch(() => null)+ relay = null+ await running?.close()+ },+ }+}diff --git a/cli/src/services/process.spec.ts b/cli/src/services/process.spec.tsindex 07612e5fb..fa4d1aa45 100644--- a/cli/src/services/process.spec.ts+++ b/cli/src/services/process.spec.ts@@ -215,12 +215,16 @@ describe('a service in its own process', () => {socket().say({ type: 'session_search', payload: { requestId: 'r6', accountOwner: true }, asker: { local: false, owner: true, accountOwner: false } })socket().say({ type: 'session_search', payload: { requestId: 'r7' }, asker: { local: false, owner: true, accountOwner: true } })socket().say({ type: 'session_search', payload: { requestId: 'r8', accountOwner: true }, asker: { local: false, owner: true, accountOwner: 'yes' } })- await vi.waitFor(() => expect(asked).toHaveLength(8))+ // A guest's session, whose guest it is: never anything a payload says.+ socket().say({ type: 'session_search', payload: { requestId: 'r9', guest: '[email protected]' }, asker: { local: false, owner: false, guest: '[email protected]' } })+ socket().say({ type: 'session_search', payload: { requestId: 'r10', guest: '[email protected]' }, asker: { local: false, owner: false, guest: 7 } })+ await vi.waitFor(() => expect(asked).toHaveLength(10))expect(asked).toEqual([{ local: true, owner: true }, { local: false, owner: false }, { local: false, owner: false },{ local: true, owner: true, connection: 'local:1', requestId: 'cmd-1' }, { local: true, owner: true },{ local: false, owner: true, accountOwner: false }, { local: false, owner: true, accountOwner: true },{ local: false, owner: true },+ { local: false, owner: false, guest: '[email protected]' }, { local: false, owner: false },])})diff --git a/cli/src/services/process.ts b/cli/src/services/process.tsindex b12557c7d..a77f3f44e 100644--- a/cli/src/services/process.ts+++ b/cli/src/services/process.ts@@ -228,7 +228,7 @@ export function runServiceProcess(options: ServiceProcessOptions): ServiceProcescatch (error) { log(`[service ${options.name}] binary frame failed · ${describe(error)}`) }return}- let frame: { type?: unknown; payload?: Payload; asker?: { local?: unknown; owner?: unknown; accountOwner?: unknown; connection?: unknown; requestId?: unknown } }+ let frame: { type?: unknown; payload?: Payload; asker?: { local?: unknown; owner?: unknown; accountOwner?: unknown; guest?: unknown; connection?: unknown; requestId?: unknown } }try { frame = JSON.parse(raw.toString()) as typeof frame } catch { return }const payload = frame.payload ?? {}if (frame.type === 'connected') {@@ -271,6 +271,8 @@ export function runServiceProcess(options: ServiceProcessOptions): ServiceProceslocal: frame.asker?.local === true,owner: frame.asker?.owner === true,...(typeof frame.asker?.accountOwner === 'boolean' ? { accountOwner: frame.asker.accountOwner } : {}),+ // A guest's session (core/guestPolicy.ts): whose guest it is, for the few requests a guest may make here.+ ...(typeof frame.asker?.guest === 'string' ? { guest: frame.asker.guest } : {}),...(typeof frame.asker?.connection === 'string' ? { connection: frame.asker.connection } : {}),...(typeof frame.asker?.requestId === 'string' ? { requestId: frame.asker.requestId } : {}),}diff --git a/cli/src/services/sharedMachines.spec.ts b/cli/src/services/sharedMachines.spec.tsindex 28ef57862..ab4c630ef 100644--- a/cli/src/services/sharedMachines.spec.ts+++ b/cli/src/services/sharedMachines.spec.ts@@ -1,11 +1,34 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { fakeCore } from '../testing/fakeCore.js'-import type { Asker, BackendNotice } from '../core/api.js'+import { emptyPorts, type Asker, type BackendNotice } from '../core/api.js'+import type { GuestHelperState } from '../lib/guestHelperInstall.js'import type { PortFailure, SharedMachine, SharedMachinesPort, SharePolicy } from '../lib/sharedMachinesPort.js'-import { normalizeEmails, readPolicy, SHARE_EMAILS_MAX, SHARED_MACHINES_REQUESTS, startSharedMachines, trustedKeys } from './sharedMachines.js'+import type { GuestLaunches } from './guestLaunches.js'+import { guestLaunchInput, normalizeEmails, normalizeFolders, ownerFolderProblem, readPolicy, SHARE_EMAILS_MAX, SHARED_FOLDERS_MAX,+ SHARED_MACHINES_REQUESTS, startSharedMachines, stillShared, trustedKeys } from './sharedMachines.js'++// The real guests reach the machine (the helper, sudo, the owner's sign-ins, a loopback relay): never in a test. The+// defaults are proven against these fakes, which say what they were asked.+const machine = vi.hoisted(() => ({ state: 'missing' as string, relayLog: null as ((line: string) => void) | null }))+vi.mock('../lib/guestHelperInstall.js', () => ({+ guestHelperStatus: vi.fn(async () => ({ state: machine.state, version: null })),+ installGuestHelper: vi.fn(async () => ({ ok: false, code: 'CANCELLED', message: 'cancelled' })),+}))+vi.mock('../lib/guestAccounts.js', async (actual) => ({+ ...await actual<typeof import('../lib/guestAccounts.js')>(),+ createGuestAccounts: () => ({ ensureGuest: async () => ({ user: 'hg_0123456789ab', home: '/g', workspace: '/g/work' }) }),+}))+vi.mock('../lib/ownerSubscriptions.js', () => ({ createOwnerSubscriptions: () => ({}) }))+vi.mock('../lib/subscriptionRelay.js', async (actual) => ({+ ...await actual<typeof import('../lib/subscriptionRelay.js')>(),+ startSubscriptionRelay: vi.fn(async (deps: { log: (line: string) => void }) => {+ machine.relayLog = deps.log+ return { port: 1, url: 'http://127.0.0.1:1', mintToken: () => 'token', revoke: () => {}, close: async () => {} }+ }),+}))const owner: Asker = { local: true, owner: true }const key = (n: number) => Buffer.alloc(32, n).toString('base64')@@ -44,22 +67,30 @@ describe('shared machines', () => {const live = () => timers.filter((t) => !t.cancelled)const fire = async () => { const t = live().at(-1)!; t.cancelled = true; t.fn(); await vi.waitFor(() => expect(live().length).toBe(1)) }const log = vi.fn()+ let guests: { [K in keyof GuestLaunches]: ReturnType<typeof vi.fn> }+ let guestAccess: ReturnType<typeof vi.fn<() => Promise<GuestHelperState>>>+ let enableGuests: ReturnType<typeof vi.fn>beforeEach(() => {dir = mkdtempSync(join(tmpdir(), 'shared-machines-'))file = join(dir, 'shared-machines.json')timers = []log.mockReset()+ guests = { launch: vi.fn(async () => ({ ok: true, workspace: '/g/work', argv: ['sh'], env: {} })), sync: vi.fn(async () => {}), stop: vi.fn(async () => {}) }+ guestAccess = vi.fn(async () => 'ready' as const)+ enableGuests = vi.fn(async () => ({ ok: true }))})afterEach(() => rmSync(dir, { recursive: true, force: true }))- const start = (port: ReturnType<typeof fakePort> | null, notices?: Array<(n: BackendNotice) => void>) => {+ const start = (port: ReturnType<typeof fakePort> | null, notices?: Array<(n: BackendNotice) => void>, ports?: ReturnType<typeof emptyPorts>) => {const core = fakeCore({ dataDir: dir, account: { onNotice: vi.fn((listener) => { notices?.push(listener); return () => {} }) } })- return startSharedMachines(core, { port: port as SharedMachinesPort | null, file, setTimer, log }).shared_machines!+ return startSharedMachines(core, { port: port as SharedMachinesPort | null, file, setTimer, log, guests: guests as never, guestAccess,+ enableGuests: enableGuests as never, folderProblem: (path) => (path.includes('secret') ? `Only your own folders can be shared: ${path}` : null),+ ...(ports ? { ports } : {}) }).shared_machines!}- it('declares its one request', () => {- expect(SHARED_MACHINES_REQUESTS).toEqual(['shared_machines'])+ it('declares its requests: the owner\'s, and where a guest may start a harness', () => {+ expect(SHARED_MACHINES_REQUESTS).toEqual(['shared_machines', 'guest_folders'])})it('is the owner’s alone', async () => {@@ -70,7 +101,7 @@ describe('shared machines', () => {describe('this machine’s sharing', () => {it('is off by default, and offers the owner’s domain', async () => {- expect(await start(fakePort())({ action: 'get' }, owner)).toEqual({ emails: [], sameDomain: false, domain: 'acme.io', members: [] })+ expect(await start(fakePort())({ action: 'get' }, owner)).toEqual({ emails: [], sameDomain: false, folders: [], domain: 'acme.io', members: [], guestAccess: 'ready' })})it('shares with addresses and the domain: published, kept here, and the machines it names trusted', async () => {@@ -78,16 +109,17 @@ describe('shared machines', () => {{ email: '[email protected]', name: null, via: 'email', machines: [] }] })) })const view = await start(port)({ action: 'set', emails: [' [email protected] ', '[email protected]'], sameDomain: true }, owner)expect(port.publish).toHaveBeenCalledWith(['[email protected]'], true)- expect(JSON.parse(readFileSync(file, 'utf-8'))).toEqual({ emails: ['[email protected]'], sameDomain: true })+ expect(JSON.parse(readFileSync(file, 'utf-8'))).toEqual({ emails: ['[email protected]'], sameDomain: true, folders: [] })expect(port.trust).toHaveBeenCalledWith({ pins: [], keys: [- { machineId: 'a'.repeat(32), pub: key(2), label: 'Machine · [email protected]' },- { machineId: 'k'.repeat(32), pub: key(1), label: 'Kim’s Mac · [email protected]' },+ // Each key with the account it is shared with: whose guest its sessions are.+ { machineId: 'a'.repeat(32), pub: key(2), label: 'Machine · [email protected]', email: '[email protected]' },+ { machineId: 'k'.repeat(32), pub: key(1), label: 'Kim’s Mac · [email protected]', email: '[email protected]' },] })// Who uses it: those this machine's own policy names, never one the backend alone lists.- expect(view).toEqual({ emails: ['[email protected]'], sameDomain: true, domain: 'acme.io', members: [+ expect(view).toEqual({ emails: ['[email protected]'], sameDomain: true, folders: [], domain: 'acme.io', members: [{ email: '[email protected]', name: null, via: 'email', machines: 1 },{ email: '[email protected]', name: 'Kim', via: 'domain', machines: 1 },- ] })+ ], guestAccess: 'ready' })})it('refuses what is not a list of addresses, and says why the backend did', async () => {@@ -101,13 +133,13 @@ describe('shared machines', () => {expect(await handle({ action: 'set', ...payload }, owner)).toMatchObject({ error: 'BAD_REQUEST' })}expect(await handle({ action: 'set', emails: [], sameDomain: true }, owner)).toEqual({ error: 'PUBLIC_DOMAIN', message: 'It is a public email domain.' })- expect(readPolicy(file)).toEqual({ emails: [], sameDomain: false })+ expect(readPolicy(file)).toEqual({ emails: [], sameDomain: false, folders: [] })})it('reads as kept here when the backend cannot say, and signed out', async () => {writeFileSync(file, JSON.stringify({ emails: ['[email protected]'], sameDomain: true }))expect(await start(fakePort({ policy: vi.fn(async () => down) }))({ action: 'get' }, owner)).toEqual({- emails: ['[email protected]'], sameDomain: true, domain: null, members: [], error: 'BACKEND_UNREACHABLE', message: down.failed.message })+ emails: ['[email protected]'], sameDomain: true, folders: [], domain: null, members: [], error: 'BACKEND_UNREACHABLE', message: down.failed.message })const before = timers.lengthconst signedOut = start(null)expect(await signedOut({ action: 'get' }, owner)).toMatchObject({ emails: ['[email protected]'], error: 'NOT_SIGNED_IN' })@@ -172,13 +204,13 @@ describe('shared machines', () => {start(port)await fire()expect(port.publish).toHaveBeenCalledWith(['[email protected]'], false)- expect(readPolicy(file)).toEqual({ emails: ['[email protected]'], sameDomain: false })+ expect(readPolicy(file)).toEqual({ emails: ['[email protected]'], sameDomain: false, folders: [] })// Held the same way on both sides: nothing to tell.port.publish.mockClear()port.policy.mockResolvedValue(policy({ emails: ['[email protected]'], members: [ann] }))await fire()expect(port.publish).not.toHaveBeenCalled()- expect(port.trust).toHaveBeenLastCalledWith({ pins: [], keys: [{ ...ann.machines[0], label: 'Machine · [email protected]' }] })+ expect(port.trust).toHaveBeenLastCalledWith({ pins: [], keys: [{ ...ann.machines[0], label: 'Machine · [email protected]', email: '[email protected]' }] })})it('changes only what it could read, and nothing when it read nothing', async () => {@@ -232,23 +264,203 @@ describe('shared machines', () => {})it('reads a policy file that is missing, broken or holds what is not an address as off', () => {- expect(readPolicy(join(dir, 'missing.json'))).toEqual({ emails: [], sameDomain: false })+ expect(readPolicy(join(dir, 'missing.json'))).toEqual({ emails: [], sameDomain: false, folders: [] })writeFileSync(file, '{')- expect(readPolicy(file)).toEqual({ emails: [], sameDomain: false })+ expect(readPolicy(file)).toEqual({ emails: [], sameDomain: false, folders: [] })writeFileSync(file, JSON.stringify({ emails: ['nope'], sameDomain: 'yes' }))- expect(readPolicy(file)).toEqual({ emails: [], sameDomain: false })+ expect(readPolicy(file)).toEqual({ emails: [], sameDomain: false, folders: [] })expect(normalizeEmails([7])).toBeNull()expect(normalizeEmails([`${'x'.repeat(250)}@a.io`])).toBeNull()})it('trusts only the members its own policy names', () => {- expect(trustedKeys({ emails: [], sameDomain: true }, policy({ domain: null, members: [kim] }))).toEqual([])- expect(trustedKeys({ emails: [], sameDomain: false }, policy({ members: [kim, ann] }))).toEqual([])- expect(trustedKeys({ emails: [], sameDomain: true }, policy({ members: [{ ...kim, email: '[email protected]' }] }))).toEqual([])+ expect(trustedKeys({ emails: [], sameDomain: true, folders: [] }, policy({ domain: null, members: [kim] }))).toEqual([])+ expect(trustedKeys({ emails: [], sameDomain: false, folders: [] }, policy({ members: [kim, ann] }))).toEqual([])+ expect(trustedKeys({ emails: [], sameDomain: true, folders: [] }, policy({ members: [{ ...kim, email: '[email protected]' }] }))).toEqual([])+ })++ describe('guests', () => {+ // A guest's harness runs as their own OS account, on the owner's subscription+ // (docs/plans/2026-10-19-guest-machine-sharing-plan.md).+ const input = { email: '[email protected]', engine: 'claude', bypassPermission: true }++ it('says whether guest access is on, and turns it on behind the owner\'s one admin prompt', async () => {+ const handle = start(fakePort())+ guestAccess.mockResolvedValueOnce('missing')+ expect(await handle({ action: 'get' }, owner)).toMatchObject({ guestAccess: 'missing' })+ expect(await handle({ action: 'enable_guests' }, owner)).toEqual({ ok: true, guestAccess: 'ready' })+ expect(enableGuests).toHaveBeenCalledTimes(1)+ enableGuests.mockResolvedValueOnce({ ok: false, code: 'CANCELLED', message: 'Sharing was not turned on: the admin prompt was cancelled.' })+ expect(await handle({ action: 'enable_guests' }, owner)).toEqual({ error: 'CANCELLED', message: 'Sharing was not turned on: the admin prompt was cancelled.' })+ expect(await handle({ action: 'enable_guests' }, { local: false, owner: false })).toEqual({ error: 'OWNER_REQUIRED' })+ // A helper that cannot be read is off.+ guestAccess.mockRejectedValue(new Error('EACCES'))+ expect(await handle({ action: 'get' }, owner)).toMatchObject({ guestAccess: 'missing' })+ expect(await handle({ action: 'enable_guests' }, owner)).toEqual({ ok: true, guestAccess: 'missing' })+ })++ it('builds a guest\'s harness for the core, and stops its relay and its reads when the service stops', async () => {+ const ports = emptyPorts()+ start(fakePort(), undefined, ports)+ expect(await ports.sharedMachines!.guestLaunch(input)).toEqual({ ok: true, workspace: '/g/work', argv: ['sh'], env: {} })+ expect(guests.launch).toHaveBeenCalledWith(input)+ expect(live()).toHaveLength(1)+ await ports.sharedMachines!.stop()+ expect(live()).toHaveLength(0)+ expect(guests.stop).toHaveBeenCalledTimes(1)+ // Stopped before its first read was scheduled: nothing to cancel.+ const early = emptyPorts()+ const core = fakeCore({ dataDir: dir })+ startSharedMachines(core, { port: null, file, setTimer, log, guests: guests as never, guestAccess, enableGuests: enableGuests as never, ports: early })+ await early.sharedMachines!.stop()+ })++ it('keeps sharing true at each read: the guests it names, and every address it may name', async () => {+ writeFileSync(file, JSON.stringify({ emails: ['[email protected]', '[email protected]'], sameDomain: true }))+ const port = fakePort({ policy: vi.fn(async () => policy({ emails: ['[email protected]', '[email protected]'], sameDomain: true, members: [ann, kim] })) })+ start(port)+ await fire()+ const [still, shared] = guests.sync.mock.calls[0] as [(email: string) => boolean, string[]]+ expect(['[email protected]', '[email protected]', '[email protected]'].map(still)).toEqual([true, true, false])+ // The policy's addresses, and the backend's members: each once.+ // A read that could not say whom it is shared with changes nothing.+ guests.sync.mockClear()+ port.policy.mockResolvedValue(down)+ await fire()+ expect(guests.sync).not.toHaveBeenCalled()+ })++ describe('folders', () => {+ it('shares the owner\'s folders with every guest, read or read-write, and takes them back', async () => {+ const port = fakePort()+ const handle = start(port)+ const view = await handle({ action: 'set_folders', folders: [{ path: '/Users/dee/code/app/', write: true }, { path: '/Users/dee/docs', write: false }] }, owner)+ expect(view).toMatchObject({ folders: [{ path: '/Users/dee/code/app', write: true }, { path: '/Users/dee/docs', write: false }] })+ expect(readPolicy(file).folders).toEqual([{ path: '/Users/dee/code/app', write: true }, { path: '/Users/dee/docs', write: false }])+ // Given to the guests now, by a read of the sharing.+ expect(guests.sync).toHaveBeenCalled()+ // Sharing with someone keeps the folders.+ await handle({ action: 'set', emails: ['[email protected]'], sameDomain: false }, owner)+ expect(readPolicy(file)).toMatchObject({ emails: ['[email protected]'], folders: [{ path: '/Users/dee/code/app', write: true }, { path: '/Users/dee/docs', write: false }] })+ expect(await handle({ action: 'set_folders', folders: [] }, owner)).toMatchObject({ folders: [] })+ })++ it('signed out, gives them to the guests at once all the same', async () => {+ const handle = start(null)+ await handle({ action: 'set_folders', folders: [{ path: '/Users/dee/docs', write: false }] }, owner)+ const [still, shared] = guests.sync.mock.calls[0] as [(email: string) => boolean, string[]]+ expect(shared).toEqual([])+ expect(still('[email protected]')).toBe(false)+ })++ it('refuses what is not a folder of the owner\'s, by name, and changes nothing', async () => {+ const handle = start(fakePort())+ expect(await handle({ action: 'set_folders', folders: [{ path: '/Users/kim/secret', write: false }] }, owner))+ .toEqual({ error: 'BAD_REQUEST', message: 'Only your own folders can be shared: /Users/kim/secret' })+ for (const folders of ['/x', [{ path: 'relative', write: false }], [{ path: '/x' }], [{ path: '/', write: true }],+ [{ path: '/x', write: true }, { path: '/x/', write: false }], [{ path: '/a\tb', write: true }], [null],+ Array.from({ length: SHARED_FOLDERS_MAX + 1 }, (_, i) => ({ path: `/f${i}`, write: false }))]) {+ expect(await handle({ action: 'set_folders', folders }, owner), JSON.stringify(folders)).toMatchObject({ error: 'BAD_REQUEST' })+ }+ expect(await handle({ action: 'set_folders', folders: [] }, { local: false, owner: false })).toEqual({ error: 'OWNER_REQUIRED' })+ expect(readPolicy(file).folders).toEqual([])+ })++ it('tells a guest where it may start a harness: its workspace and the folders shared with it', async () => {+ writeFileSync(file, JSON.stringify({ emails: ['[email protected]'], sameDomain: false, folders: [{ path: '/Users/dee/docs', write: false }] }))+ const core = fakeCore({ dataDir: dir })+ const requests = startSharedMachines(core, { port: null, file, setTimer, log, guests: guests as never, guestAccess, enableGuests: enableGuests as never })+ const folders = requests.guest_folders!+ expect(await folders({}, { local: false, owner: false, guest: '[email protected]' })).toEqual({+ workspace: expect.stringMatching(/\/hg_[0-9a-f]{12}\/work$/), folders: [{ path: '/Users/dee/docs', write: false }] })+ expect(await folders({}, owner)).toEqual({ workspace: null, folders: [{ path: '/Users/dee/docs', write: false }] })+ // A session that is neither: nothing.+ expect(await folders({}, { local: false, owner: false })).toEqual({ error: 'OWNER_REQUIRED' })+ expect(await folders({}, { local: false, owner: false, guest: '' })).toEqual({ error: 'OWNER_REQUIRED' })+ })++ it('reads folders as full paths, each once, never /, and nothing from a file that holds otherwise', () => {+ expect(normalizeFolders([{ path: '/a/b/../c/', write: true }])).toEqual([{ path: '/a/c', write: true }])+ expect(normalizeFolders([{ path: `/${'x'.repeat(4096)}`, write: true }])).toBeNull()+ expect(normalizeFolders([{ path: '/a\nb', write: true }])).toBeNull()+ writeFileSync(file, JSON.stringify({ emails: [], sameDomain: false, folders: [{ path: 'nope', write: true }] }))+ expect(readPolicy(file).folders).toEqual([])+ })++ it('says in words why a folder cannot be shared, before the helper would', () => {+ const home = mkdtempSync(join(tmpdir(), 'owner-home-'))+ try {+ mkdirSync(join(home, 'code'))+ writeFileSync(join(home, 'notes.txt'), 'x')+ const guests = join(home, 'guests')+ mkdirSync(join(guests, 'hg_0123456789ab'), { recursive: true })+ const uid = process.getuid!()+ expect(ownerFolderProblem(join(home, 'code'), home, guests, uid)).toBeNull()+ expect(ownerFolderProblem(join(home, 'missing'), home, guests, uid)).toMatch(/^No such folder on this computer/)+ expect(ownerFolderProblem(join(home, 'notes.txt'), home, guests, uid)).toMatch(/^Not a folder/)+ expect(ownerFolderProblem(home, home, guests, uid)).toMatch(/whole home folder/)+ expect(ownerFolderProblem(join(guests, 'hg_0123456789ab'), home, guests, uid)).toMatch(/guest's home/)+ expect(ownerFolderProblem(guests, home, guests, uid)).toMatch(/guest's home/)+ expect(ownerFolderProblem(join(home, 'code'), home, guests, uid + 1)).toMatch(/your own folders/)+ // A platform with no uids checks the rest; the defaults are this account's.+ expect(ownerFolderProblem(join(home, 'code'), home, guests, undefined)).toBeNull()+ expect(ownerFolderProblem(join(home, 'missing'))).toMatch(/^No such folder/)+ } finally { rmSync(home, { recursive: true, force: true }) }+ })+ })++ it('reads a launch the core asked for, and nothing else as one', () => {+ expect(guestLaunchInput({ ...input, extra: 1 })).toEqual(input)+ expect(guestLaunchInput({ ...input, prompt: 'Fix the tests' })).toEqual({ ...input, prompt: 'Fix the tests' })+ expect(guestLaunchInput({ ...input, prompt: '' })).toEqual(input)+ expect(guestLaunchInput({ ...input, cwd: '/Users/dee/docs' })).toEqual({ ...input, cwd: '/Users/dee/docs' })+ expect(guestLaunchInput({ ...input, cwd: '' })).toEqual(input)+ expect(guestLaunchInput({ ...input, permissionFlags: ['--permission-mode', 'auto'] })).toEqual({ ...input, permissionFlags: ['--permission-mode', 'auto'] })+ for (const permissionFlags of ['--x', [7], ['; rm -rf /'], ['a', 'b', 'c', 'd', 'e'], ['--model=x']]) {+ expect(guestLaunchInput({ ...input, permissionFlags }), JSON.stringify(permissionFlags)).toBeNull()+ }+ for (const payload of [{}, { ...input, email: 1 }, { ...input, engine: null }, { ...input, bypassPermission: 'yes' }, { ...input, prompt: 7 }, { ...input, cwd: 7 }]) {+ expect(guestLaunchInput(payload as Record<string, unknown>)).toBeNull()+ }+ })++ it('shares with whom the policy names: by address, or by the owner\'s domain while it has one', () => {+ expect(stillShared({ emails: ['[email protected]'], sameDomain: false, folders: [] }, 'acme.io', '[email protected]')).toBe(true)+ expect(stillShared({ emails: [], sameDomain: true, folders: [] }, 'acme.io', '[email protected]')).toBe(true)+ expect(stillShared({ emails: [], sameDomain: true, folders: [] }, null, '[email protected]')).toBe(false)+ expect(stillShared({ emails: [], sameDomain: false, folders: [] }, 'acme.io', '[email protected]')).toBe(false)+ expect(stillShared({ emails: [], sameDomain: true, folders: [] }, 'acme.io', '[email protected]')).toBe(false)+ })+ })++ it('keeps its own guests, helper check and install by default, on the machine\'s helper and the owner\'s sign-ins', async () => {+ const said = vi.spyOn(console, 'log').mockImplementation(() => {})+ vi.stubEnv('LANG', 'vi_VN.UTF-8')+ try {+ const ports = emptyPorts()+ const handle = startSharedMachines(fakeCore({ dataDir: dir }), { port: fakePort() as never, file, setTimer, ports }).shared_machines!+ machine.state = 'missing'+ expect(await handle({ action: 'get' }, owner)).toMatchObject({ guestAccess: 'missing' })+ expect(await handle({ action: 'enable_guests' }, owner)).toEqual({ error: 'CANCELLED', message: 'cancelled' })+ // Folders are checked on this computer as they are shared.+ expect(await handle({ action: 'set_folders', folders: [{ path: join(dir, 'missing'), write: false }] }, owner))+ .toEqual({ error: 'BAD_REQUEST', message: `No such folder on this computer: ${join(dir, 'missing')}` })+ expect(await ports.sharedMachines!.guestLaunch({ email: '[email protected]', engine: 'claude', bypassPermission: true })).toMatchObject({ ok: false, error: 'GUEST_HELPER_REQUIRED' })+ machine.state = 'ready'+ expect(await ports.sharedMachines!.guestLaunch({ email: '[email protected]', engine: 'claude', bypassPermission: true }))+ .toMatchObject({ ok: true, workspace: '/g/work', env: expect.objectContaining({ LANG: 'vi_VN.UTF-8' }) })+ machine.relayLog!('claude · 200')+ expect(said).toHaveBeenCalledWith('[shared-machines] guest launch · claude · hg_0123456789ab')+ expect(said).toHaveBeenCalledWith('[shared-machines] relay · claude · 200')+ await ports.sharedMachines!.stop()+ } finally { said.mockRestore(); vi.unstubAllEnvs() }})it('keeps its own timer, file and log by default', async () => {vi.useFakeTimers()+ // No LANG of the owner's: a guest's harness gets the default (lib/guestPaneCommand.ts).+ vi.stubEnv('LANG', '')const said = vi.spyOn(console, 'log').mockImplementation(() => {})try {const notices: Array<(n: BackendNotice) => void> = []@@ -260,6 +472,6 @@ describe('shared machines', () => {expect(port.shared).toHaveBeenCalledTimes(1)expect(said).toHaveBeenCalledWith(expect.stringContaining('[shared-machines] could not update the trust stores'))startSharedMachines(core)- } finally { said.mockRestore(); vi.useRealTimers() }+ } finally { said.mockRestore(); vi.useRealTimers(); vi.unstubAllEnvs() }})})diff --git a/cli/src/services/sharedMachines.ts b/cli/src/services/sharedMachines.tsindex 793fda65d..de2ba515b 100644--- a/cli/src/services/sharedMachines.ts+++ b/cli/src/services/sharedMachines.ts@@ -9,7 +9,10 @@* Empty and false is "not shared".* - `add` {machineId}: add a machine shared with this account's domain to its machines; `remove` takes it* back out.- * Owner only, like every request that changes this machine.+ * - `enable_guests`: turn guest access on (the helper, behind one admin prompt on this computer).+ * - `set_folders` {folders: [{path, write}]}: the owner's folders every guest may work in, read or read-write.+ * Owner only, like every request that changes this machine. `guest_folders` is a guest's: where it may start a+ * harness, its own workspace and the folders shared with it (docs/plans/2026-10-19-guest-machine-sharing-plan.md).** The policy is kept here, on the machine (`shared-machines.json`), and published to the backend, which* lists the machine to the people it names and lets their relay sessions through. Whom to trust is still@@ -22,17 +25,25 @@* sharing of one shared with this account changed), after each change made here, and every few minutes* while anything is shared either way.*/-import { join } from 'node:path'-import { readFileSync, renameSync, writeFileSync } from 'node:fs'-import type { CoreApi, ServiceRequests } from '../core/api.js'+import { homedir } from 'node:os'+import { isAbsolute, join, resolve } from 'node:path'+import { readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'+import type { CoreApi, CorePorts, GuestLaunchInput, ServiceRequests } from '../core/api.js'+import { createGuestAccounts, guestHomeRoot, guestWorkspaceFor, type SharedFolder } from '../lib/guestAccounts.js'+import { guestHelperStatus, installGuestHelper, type GuestHelperInstallResult, type GuestHelperState } from '../lib/guestHelperInstall.js'+import { createOwnerSubscriptions } from '../lib/ownerSubscriptions.js'import { failed, type PortFailure, type ShareMember, type SharedMachinesPort, type SharePolicy,type SharedTrustPeer } from '../lib/sharedMachinesPort.js'+import { startSubscriptionRelay } from '../lib/subscriptionRelay.js'+import { createGuestLaunches, type GuestLaunches } from './guestLaunches.js'/** The request shared machines answers for the apps, declared in core/api.ts for the core to route. */export { SHARED_MACHINES_REQUESTS } from '../core/api.js'/** The most addresses one machine is shared with (the backend's `SHARE_EMAILS_MAX`). */export const SHARE_EMAILS_MAX = 100+/** The most folders the owner shares with guests. */+export const SHARED_FOLDERS_MAX = 20/** How often the sharing is read again while anything is shared either way, and while nothing is. */const BUSY_MS = 2 * 60_000const IDLE_MS = 15 * 60_000@@ -44,8 +55,8 @@ const NOTICE_MS = 1_000* rather than failing the whole list there (an address typed `name@!gmail.com`, 2026-10-15). */const EMAIL_RE = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/-/** This machine's sharing as its owner set it. */-export interface LocalPolicy { emails: string[]; sameDomain: boolean }+/** This machine's sharing as its owner set it. `folders` stay here: the backend never hears of them. */+export interface LocalPolicy { emails: string[]; sameDomain: boolean; folders: SharedFolder[] }export interface SharedMachinesDeps {/** The core's `shared_machines` answers, or null signed out: nothing is shared or read. */@@ -53,17 +64,53 @@ export interface SharedMachinesDeps {file: stringsetTimer: (fn: () => void, ms: number) => { cancel(): void }log: (line: string) => void+ /** Guests' harnesses (services/guestLaunches.ts): their OS accounts and the owner's subscription relay. */+ guests: GuestLaunches+ /** Whether guest access is on here (lib/guestHelperInstall.ts), and turning it on: the owner's one admin prompt. */+ guestAccess: () => Promise<GuestHelperState>+ enableGuests: () => Promise<GuestHelperInstallResult>+ /** Where the core's port goes (serviceHost `start`); absent where only the requests are wanted. */+ ports?: CorePorts+ /** Why the owner may not share [path] with guests, or null when it may (the helper checks it again). */+ folderProblem: (path: string) => string | null}-const OFF: LocalPolicy = { emails: [], sameDomain: false }+const OFF: LocalPolicy = { emails: [], sameDomain: false, folders: [] }export function readPolicy(file: string): LocalPolicy {try {const raw = JSON.parse(readFileSync(file, 'utf-8')) as Partial<LocalPolicy>- return { emails: normalizeEmails(raw.emails) ?? [], sameDomain: raw.sameDomain === true }+ return { emails: normalizeEmails(raw.emails) ?? [], sameDomain: raw.sameDomain === true, folders: normalizeFolders(raw.folders) ?? [] }} catch { return OFF }}+/** Folders as the owner shares them: full paths, each once, never /; null when one is not. One a line in the+ * helper's record, so a name may hold no tab or newline. */+export function normalizeFolders(raw: unknown): SharedFolder[] | null {+ if (!Array.isArray(raw) || raw.length > SHARED_FOLDERS_MAX) return null+ const folders: SharedFolder[] = []+ for (const folder of raw) {+ const { path, write } = (folder ?? {}) as { path?: unknown; write?: unknown }+ if (typeof path !== 'string' || !isAbsolute(path) || path.length > 4096 || /[\t\n\r\0]/.test(path) || typeof write !== 'boolean') return null+ const resolved = resolve(path)+ if (resolved === '/' || folders.some((f) => f.path === resolved)) return null+ folders.push({ path: resolved, write })+ }+ return folders+}++/** The helper's own rules, said here first in words: a folder of the owner's, on this computer, never its whole+ * home or a guest's. */+export function ownerFolderProblem(path: string, home = homedir(), guests = guestHomeRoot(), uid = process.getuid?.()): string | null {+ let info+ try { info = statSync(path) } catch { return `No such folder on this computer: ${path}` }+ if (!info.isDirectory()) return `Not a folder: ${path}`+ if (resolve(path) === resolve(home)) return 'Your whole home folder cannot be shared. Choose a folder in it.'+ if (path === guests || path.startsWith(`${guests}/`)) return `A guest's home cannot be shared: ${path}`+ if (uid !== undefined && info.uid !== uid) return `Only your own folders can be shared: ${path}`+ return null+}+function writePolicy(file: string, policy: LocalPolicy): void {const temp = `${file}.${process.pid}.tmp`writeFileSync(temp, JSON.stringify(policy, null, 2), { mode: 0o600 })@@ -78,8 +125,9 @@ export function normalizeEmails(raw: unknown): string[] | null {return emails}-const shares = (policy: LocalPolicy): boolean => policy.emails.length > 0 || policy.sameDomain-const samePolicy = (a: LocalPolicy, b: LocalPolicy): boolean =>+type Sharing = Pick<LocalPolicy, 'emails' | 'sameDomain'>+const shares = (policy: Sharing): boolean => policy.emails.length > 0 || policy.sameDomain+const samePolicy = (a: Sharing, b: Sharing): boolean =>a.sameDomain === b.sameDomain && a.emails.length === b.emails.length && a.emails.every((e) => b.emails.includes(e))/** Whether this machine's own policy names someone the backend says uses it. */@@ -87,23 +135,66 @@ const names = (local: LocalPolicy, domain: string | null, member: ShareMember):? local.emails.includes(member.email): local.sameDomain && !!domain && member.email.endsWith(`@${domain}`)+/** Whether this machine's own policy still shares it with [email]: by address, or by the owner's domain. */+export function stillShared(local: LocalPolicy, domain: string | null, email: string): boolean {+ return local.emails.includes(email) || (local.sameDomain && !!domain && email.endsWith(`@${domain}`))+}+/** The machines of those the backend says use this one, those this machine's own policy names. */export function trustedKeys(local: LocalPolicy, remote: SharePolicy): SharedTrustPeer[] {return remote.members.filter((m) => names(local, remote.domain, m))- .flatMap((m) => m.machines.map((machine) => ({ ...machine, label: `${machine.label || 'Machine'} · ${m.email}` })))+ .flatMap((m) => m.machines.map((machine) => ({ ...machine, label: `${machine.label || 'Machine'} · ${m.email}`, email: m.email })))}const answerFailure = (f: PortFailure): Record<string, unknown> => ({ error: f.failed.code, message: f.failed.message })+/** The real guests: OS accounts through the helper, the owner's sign-ins read where the engines keep them. */+function machineGuests(log: (line: string) => void, file: string): GuestLaunches {+ return createGuestLaunches({+ accounts: createGuestAccounts(),+ helperState: async () => (await guestHelperStatus()).state,+ folders: () => readPolicy(file).folders,+ startRelay: () => startSubscriptionRelay({ owner: createOwnerSubscriptions(), log: (line) => log(`relay · ${line}`) }),+ ...(process.env.LANG ? { lang: process.env.LANG } : {}),+ log: (line) => log(`guest ${line}`),+ })+}++/** A guest launch as the core asks for it; null when it is not one. */+export function guestLaunchInput(payload: Record<string, unknown>): GuestLaunchInput | null {+ if (typeof payload.email !== 'string' || typeof payload.engine !== 'string' || typeof payload.bypassPermission !== 'boolean') return null+ if (payload.prompt !== undefined && typeof payload.prompt !== 'string') return null+ if (payload.cwd !== undefined && typeof payload.cwd !== 'string') return null+ // Flags as an engine takes them (`--permission-mode`, `auto`): never a word that is not one.+ const flags = payload.permissionFlags+ if (flags !== undefined && (!Array.isArray(flags) || flags.length > 4 || !flags.every((f) => typeof f === 'string' && /^-{0,2}[A-Za-z][A-Za-z0-9-]*$/.test(f)))) return null+ return { email: payload.email, engine: payload.engine, bypassPermission: payload.bypassPermission,+ ...(payload.prompt ? { prompt: payload.prompt } : {}), ...(payload.cwd ? { cwd: payload.cwd } : {}),+ ...(flags ? { permissionFlags: flags as string[] } : {}) }+}+export function startSharedMachines(core: CoreApi, overrides: Partial<SharedMachinesDeps> = {}): ServiceRequests {+ const log = overrides.log ?? ((line: string) => console.log(`[shared-machines] ${line}`))+ const file = overrides.file ?? join(core.dataDir, 'shared-machines.json')const deps: SharedMachinesDeps = {port: overrides.port !== undefined ? overrides.port : null,- file: overrides.file ?? join(core.dataDir, 'shared-machines.json'),+ file,setTimer: overrides.setTimer ?? ((fn, ms) => { const t = setTimeout(fn, ms).unref(); return { cancel: () => clearTimeout(t) } }),- log: overrides.log ?? ((line) => console.log(`[shared-machines] ${line}`)),+ log,+ guests: overrides.guests ?? machineGuests(log, file),+ folderProblem: overrides.folderProblem ?? ((path) => ownerFolderProblem(path)),+ guestAccess: overrides.guestAccess ?? (async () => (await guestHelperStatus()).state),+ enableGuests: overrides.enableGuests ?? (() => installGuestHelper()),}const port = deps.port+ const guests = deps.guests+ if (overrides.ports) {+ overrides.ports.sharedMachines = {+ guestLaunch: (input) => guests.launch(input),+ stop: async () => { timer?.cancel(); await guests.stop() },+ }+ }let timer: { cancel(): void } | null = nulllet reading: Promise<void> | null = nulllet again = false@@ -130,11 +221,18 @@ export function startSharedMachines(core: CoreApi, overrides: Partial<SharedMachif (!failed(remote) && sameDomain !== local.sameDomain) writePolicy(deps.file, { ...local, sameDomain })}if (!failed(remote)) desired.keys = shares(local) ? trustedKeys(local, remote) : []- if (!desired.pins && !desired.keys) return- const held = await port.trust(desired)- if (failed(held)) deps.log(`could not update the trust stores: ${held.failed.message}`)+ if (desired.pins || desired.keys) {+ const held = await port.trust(desired)+ if (failed(held)) deps.log(`could not update the trust stores: ${held.failed.message}`)+ }+ // A guest sharing no longer names spends nothing more of the owner's subscriptions and keeps none of the+ // owner's folders; every guest it names has the folders the owner shares.+ if (!failed(remote)) await syncGuests(local, remote.domain, remote.members.map((m) => m.email))}+ const syncGuests = (local: LocalPolicy, domain: string | null, members: string[]): Promise<void> =>+ guests.sync((email) => stillShared(local, domain, email), [...new Set([...local.emails, ...members])])+/** One read at a time; one asked for while another runs follows it. Then the next round. */const read = (port: SharedMachinesPort): Promise<void> => {if (reading) { again = true; return reading }@@ -168,7 +266,8 @@ export function startSharedMachines(core: CoreApi, overrides: Partial<SharedMach}return { ...local, sameDomain: local.sameDomain && !!remote.domain, domain: remote.domain,members: remote.members.filter((m) => names(local, remote.domain, m))- .map((m) => ({ email: m.email, name: m.name, via: m.via, machines: m.machines.length })) }+ .map((m) => ({ email: m.email, name: m.name, via: m.via, machines: m.machines.length })),+ guestAccess: await deps.guestAccess().catch(() => 'missing' as const) }}return {@@ -186,7 +285,7 @@ export function startSharedMachines(core: CoreApi, overrides: Partial<SharedMachif (!port) return { error: 'NOT_SIGNED_IN', message: 'Sign in to share this machine.' }const published = await port.publish(emails, payload.sameDomain)if (failed(published)) return answerFailure(published)- writePolicy(deps.file, { emails: published.emails, sameDomain: published.sameDomain })+ writePolicy(deps.file, { ...readPolicy(deps.file), emails: published.emails, sameDomain: published.sameDomain })await read(port)return view()}@@ -199,8 +298,32 @@ export function startSharedMachines(core: CoreApi, overrides: Partial<SharedMachawait read(port)return { ok: true }}+ // Guest access: the helper that runs guests' harnesses as their own OS accounts, installed behind+ // one admin prompt on this computer (lib/guestHelperInstall.ts). Sharing turns it on first.+ case 'enable_guests': {+ const installed = await deps.enableGuests()+ if (!installed.ok) return { error: installed.code, message: installed.message }+ return { ok: true, guestAccess: await deps.guestAccess().catch(() => 'missing' as const) }+ }+ case 'set_folders': {+ const folders = normalizeFolders(payload.folders)+ if (!folders) return { error: 'BAD_REQUEST', message: `Choose up to ${SHARED_FOLDERS_MAX} folders, each by its full path.` }+ const problem = folders.map((f) => deps.folderProblem(f.path)).find((p) => p !== null)+ if (problem) return { error: 'BAD_REQUEST', message: problem }+ const local = { ...readPolicy(deps.file), folders }+ writePolicy(deps.file, local)+ // Given to every guest now (or taken back), not at their next harness.+ if (port) await read(port)+ else await syncGuests(local, null, [])+ return view()+ }default: return { error: 'UNKNOWN_ACTION' }}},+ // A guest's: where it may start a harness. Its workspace, and the folders the owner shares with guests.+ guest_folders: async (_payload, asker) => {+ if (!asker.guest && !asker.owner) return { error: 'OWNER_REQUIRED' }+ return { workspace: asker.guest ? guestWorkspaceFor(asker.guest) : null, folders: readPolicy(deps.file).folders }+ },}}diff --git a/cli/src/services/sharedMachinesProcess.spec.ts b/cli/src/services/sharedMachinesProcess.spec.tsindex 081ea660a..5c4fa475c 100644--- a/cli/src/services/sharedMachinesProcess.spec.ts+++ b/cli/src/services/sharedMachinesProcess.spec.ts@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'import { runServiceProcess, type ServiceProcessOptions } from './process.js'import { runSharedMachinesService } from './sharedMachinesProcess.js'import type { SharedMachinesDeps } from './sharedMachines.js'-import type { CoreApi } from '../core/api.js'+import { GUEST_LAUNCH_UNAVAILABLE, type CoreApi } from '../core/api.js'// The real default reaches a real socket: never in a test.vi.mock('./process.js', () => ({ runServiceProcess: vi.fn(() => ({ stop: vi.fn() })) }))@@ -53,12 +53,34 @@ describe('shared machines in their own process', () => {expect(await port.shared()).toMatchObject({ failed: expect.any(Object) })})+ it('builds a guest\'s harness when the core asks, from the port its service filled, and nothing from what is not one', async () => {+ let options: ServiceProcessOptions | null = null+ const guestLaunch = vi.fn(async () => ({ ok: true as const, workspace: '/g/work', argv: ['sh'], env: {} }))+ runSharedMachinesService({+ dataDir: '/data', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't',+ run: (o) => { options = o; return { stop: vi.fn() } },+ start: (_api, overrides = {}) => { overrides.ports!.sharedMachines = { guestLaunch, stop: vi.fn() }; return { shared_machines: async () => ({}) } },+ })+ const core = { local: false, owner: false }+ const input = { email: '[email protected]', engine: 'claude', bypassPermission: true }+ expect(await options!.requests.guestLaunch!(input, core)).toEqual({ ok: true, workspace: '/g/work', argv: ['sh'], env: {} })+ expect(guestLaunch).toHaveBeenCalledWith(input)+ expect(await options!.requests.guestLaunch!({ email: '[email protected]' }, core)).toEqual(GUEST_LAUNCH_UNAVAILABLE)+ // A service that filled no port builds nothing.+ runSharedMachinesService({+ dataDir: '/data', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't',+ run: (o) => { options = o; return { stop: vi.fn() } },+ start: () => ({ shared_machines: async () => ({}) }),+ })+ expect(await options!.requests.guestLaunch!(input, core)).toEqual(GUEST_LAUNCH_UNAVAILABLE)+ })+it('runs as a real service by default', () => {const stopTimers = vi.useFakeTimers()runSharedMachinesService({ dataDir: '/nonexistent', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })expect(runServiceProcess).toHaveBeenCalledWith(expect.objectContaining({ name: 'sharedMachines' }))const requests = vi.mocked(runServiceProcess).mock.calls[0][0].requests- expect(Object.keys(requests)).toEqual(['shared_machines'])+ expect(Object.keys(requests)).toEqual(['shared_machines', 'guest_folders', 'guestLaunch'])stopTimers.useRealTimers()})})diff --git a/cli/src/services/sharedMachinesProcess.ts b/cli/src/services/sharedMachinesProcess.tsindex 452cf261a..dfbfda0b9 100644--- a/cli/src/services/sharedMachinesProcess.ts+++ b/cli/src/services/sharedMachinesProcess.ts@@ -4,11 +4,14 @@* thing, `shared_machines` (core/sharedMachinesQueries.ts): this machine's sharing and the machines shared* with this account, read and written through the core's sign-in, and the gateway's trust stores, which* only the gateway holds. The core tells it `machines_changed` (`service_event` kind `notice`).+ *+ * The core asks it one thing, a guest's harness (`guestLaunch`, core/sharedMachinesLink.ts), named as its+ * port's member so that a test's fault names the same member whichever process it runs in.*/-import type { BackendNotice } from '../core/api.js'+import { emptyPorts, GUEST_LAUNCH_UNAVAILABLE, type BackendNotice } from '../core/api.js'import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'import { processCoreApi } from './processCoreApi.js'-import { startSharedMachines } from './sharedMachines.js'+import { guestLaunchInput, startSharedMachines } from './sharedMachines.js'import { sharedMachinesPortOf } from '../lib/sharedMachinesPort.js'export interface SharedMachinesServiceOptions {@@ -32,12 +35,22 @@ export function runSharedMachinesService(options: SharedMachinesServiceOptions):})// A refusal or no core reads as the backend unreachable: the next round tries again.const port = sharedMachinesPortOf((op, payload = {}) => ask('shared_machines', { ...payload, op }).catch((error: unknown) => ({ error: String(error) })))+ const ports = emptyPorts()+ const requests = (options.start ?? startSharedMachines)(api, { port, ports })+ const guests = ports.sharedMachinesreturn (options.run ?? runServiceProcess)({name: 'sharedMachines',socketPath: options.socketPath,machineId: options.machineId,token: options.token,- requests: (options.start ?? startSharedMachines)(api, { port }),+ requests: {+ ...requests,+ // Asked only by the core (core/sharedMachinesLink.ts): never a type an app's request is routed by.+ guestLaunch: async (payload) => {+ const input = guestLaunchInput(payload)+ return input && guests ? guests.guestLaunch(input) : GUEST_LAUNCH_UNAVAILABLE+ },+ },onEvent: (payload) => {if (payload.kind !== 'notice' || !payload.notice || typeof payload.notice !== 'object') returnfor (const listener of listeners) listener(payload.notice as BackendNotice)diff --git a/companions/src/companion/client.spec.ts b/companions/src/companion/client.spec.tsindex 639f9c1b2..5237f9a77 100644--- a/companions/src/companion/client.spec.ts+++ b/companions/src/companion/client.spec.ts@@ -80,8 +80,11 @@ describe('pairRequest: one request, settled once', () => {})const reply = await pairRequest(base(d.connect), { verb: 'status' })expect(reply).toEqual({ ok: true, n: 1 })- expect(d.connect).toHaveBeenCalledWith('ws://127.0.0.1:4242/api/local-ws')+ expect(d.connect).toHaveBeenCalledWith('ws://127.0.0.1:4242/api/local-ws', {})expect(d.sockets[0].closes).toBe(1)+ // Given the daemon's local credential, the loopback socket shows it: TCP upgrades without it are refused.+ await pairRequest(base(d.connect, { localCredential: 'c'.repeat(43) }), { verb: 'status' })+ expect(d.connect).toHaveBeenLastCalledWith('ws://127.0.0.1:4242/api/local-ws', { 'X-Harness-Local': 'c'.repeat(43) })})it('an error rejects with it; a close after it changes nothing and closes once', async () => {diff --git a/companions/src/companion/client.ts b/companions/src/companion/client.tsindex ac2659b66..65ff19e70 100644--- a/companions/src/companion/client.ts+++ b/companions/src/companion/client.ts@@ -27,7 +27,11 @@ export interface PairClientDeps {port: number/** This computer's machine id, as its daemon knows it; resolved from /api/status when absent. */machineId: () => Promise<string | null>- connect: (url: string) => PairSocket+ /** A loopback socket to the daemon carrying [headers]: its local credential, which a TCP connection+ * must show (cli/src/lib/localCredential.ts). */+ connect: (url: string, headers: Record<string, string>) => PairSocket+ /** The daemon's local credential, read by the caller from its data dir (`hook-credential`). */+ localCredential?: string | nullenv: NodeJS.ProcessEnvtokenFile?: string | nulltimeoutMs?: number@@ -39,7 +43,7 @@ export async function pairRequest(deps: PairClientDeps, payload: Record<string,if (!machineId) throw new Error('Harness is not running on this computer. Start it with `harness start`.')const token = presentedToken(deps.env, deps.tokenFile)return new Promise((resolve, reject) => {- const socket = deps.connect(`ws://127.0.0.1:${deps.port}/api/local-ws`)+ const socket = deps.connect(`ws://127.0.0.1:${deps.port}/api/local-ws`, deps.localCredential ? { 'X-Harness-Local': deps.localCredential } : {})const requestId = randomUUID()let settled = falseconst finish = (error: Error | null, reply?: Record<string, unknown>): void => {diff --git a/desktop/lib/core/guest_folders.dart b/desktop/lib/core/guest_folders.dartnew file mode 100644index 000000000..e677fe22a--- /dev/null+++ b/desktop/lib/core/guest_folders.dart@@ -0,0 +1,39 @@+/// Where a guest may start a harness on a machine shared with it (CLI services/sharedMachines.ts+/// `guest_folders`, docs/plans/2026-10-19-guest-machine-sharing-plan.md): its own workspace, and the+/// folders the machine's owner shares with guests, read only or editable.+library;++import 'package:flutter/foundation.dart';++@immutable+class GuestFolder {+ const GuestFolder({required this.path, required this.write});+ final String path;++ /// Whether the guest may change what is in it, not only read it.+ final bool write;+}++@immutable+class GuestFolders {+ const GuestFolders({this.workspace, this.folders = const []});++ /// The guest's own folder there, where a harness starts unless it picks a shared one.+ final String? workspace;+ final List<GuestFolder> folders;++ /// The machine's answer; what is not a folder in it is left out.+ factory GuestFolders.fromJson(Map<String, dynamic> json) => GuestFolders(+ workspace: json['workspace'] is String ? json['workspace'] as String : null,+ folders: [+ for (final folder in json['folders'] as List? ?? const [])+ if (folder is Map &&+ folder['path'] is String &&+ (folder['path'] as String).startsWith('/'))+ GuestFolder(+ path: folder['path'] as String,+ write: folder['write'] == true,+ ),+ ],+ );+}diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dartindex 232798885..ca9b096ad 100644--- a/desktop/lib/core/models.dart+++ b/desktop/lib/core/models.dart@@ -104,8 +104,9 @@ bool sameMachineId(String a, String b) =>/// A whole machine another account shares with this one (backend lib/machineAccess.ts): its owner/// named this account's address ([via] `email`), or shared it with everyone at their domain and this-/// account added it ([via] `domain`, [added]). Used with the owner's own rights, unlike [Machine.isShared],-/// one harness shared to watch.+/// account added it ([via] `domain`, [added]). This account is a guest there: a space of its own, its+/// own harnesses on the owner's plans, nothing of the owner's (docs/plans/2026-10-19-guest-machine-sharing-plan.md);+/// unlike [Machine.isShared], one harness shared to watch.class MachineShare {final String ownerName;final String ownerEmail;@@ -165,8 +166,8 @@ class Machine {this.machineShare,});- /// Another account's machine, shared whole with this one: used as the account's own, managed (renamed,- /// removed, shared on) by its owner alone.+ /// Another account's machine, shared with this one: this account is a guest there, with its own space and+ /// harnesses; the machine is managed (renamed, removed, shared on) by its owner alone.bool get isSharedMachine => machineShare != null;String get displayName => (name != null && name!.isNotEmpty)diff --git a/desktop/lib/e2ee/envelope.dart b/desktop/lib/e2ee/envelope.dartindex 09c91ab5a..55f8f342c 100644--- a/desktop/lib/e2ee/envelope.dart+++ b/desktop/lib/e2ee/envelope.dart@@ -36,8 +36,10 @@ const Set<String> encryptedDownTypes = {'viewer_surface','api_connections','connectors',- // Sharing a machine across accounts (CLI services/sharedMachines.ts): the addresses it is shared with.+ // Sharing a machine across accounts (CLI services/sharedMachines.ts): the addresses it is shared with,+ // and where a guest may start a harness (the owner's folders).'shared_machines',+ 'guest_folders','super_tabs','orchestrator','route_task',diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 1273ea226..bca2703ee 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -7330,9 +7330,12 @@ class _SwarmScreenState extends State<SwarmScreen> {if (id == 'agent.share' || id == 'pane.toggle_viewer') {final focused = WorkspacePaneContext.focused(app);final agent = focused?.agent;+ final machine = app.stateOf(focused?.pane.machineId ?? '')?.machine;return focused != null &&agent != null &&- app.stateOf(focused.pane.machineId)?.machine.isShared == false &&+ machine?.isShared == false &&+ // A guest shares nothing of a machine shared with it.+ (id != 'agent.share' || !machine!.isSharedMachine) &&(id == 'agent.share' ||agent.viewerUrl != null ||agent.viewerError != null);@@ -7373,6 +7376,10 @@ class _SwarmScreenState extends State<SwarmScreen> {// again, only a fork needs the engine to carry a conversation over.return machine != null &&!machine.machine.isShared &&+ // A guest's harness is never relaunched or forked: either would run the+ // owner's way, as the owner (docs/plans/2026-10-19-guest-machine-sharing-plan.md).+ (!machine.machine.isSharedMachine ||+ (id != 'agent.fork' && id != 'agent.restart')) &&(id != 'agent.fork' || _focusedAgent?.canFork == true) &&(id != 'agent.clone' || _focusedAgent?.canClone == true) &&((id != 'agent.restart' && id != 'agent.clone') ||diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 8a8af57e7..74bed2b23 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -2,6 +2,7 @@ import '../measurement/product_measurement.dart';import '../measurement/product_runtime_health.dart';import '../measurement/product_connections.dart';import '../core/crash_log.dart';+import '../core/guest_folders.dart';import '../measurement/desktop_setup_report.dart';import 'attached_task_delivery.dart';import 'harness_attachments.dart';@@ -979,6 +980,8 @@ class AppNotifier extends ChangeNotifier {if (_disposed || (_pool == null && connectionForTest == null)) return false;final machine = machineStates[key.machineId];return machine != null &&+ // A guest is read no conversation there (`agent_recent` is the owner's).+ !machine.machine.isSharedMachine &&machine.nodeOnline != false &&!machine.needsLink &&(machine.connectionStatus == ConnectionStatus.connected ||@@ -7778,6 +7781,44 @@ class AppNotifier extends ChangeNotifier {'sameDomain': sameDomain,});+ /// Turn guest access on at [machineId]: the helper that runs each guest's harnesses as their own+ /// account there (CLI lib/guestHelperInstall.ts), installed behind one admin prompt on that+ /// computer. Waits for the person at the prompt. `{ok, guestAccess}`, or `{error, message}`+ /// (`CANCELLED` when the prompt was dismissed).+ Future<Map<String, dynamic>> enableMachineGuests(String machineId) =>+ _sharedMachines(machineId, {+ 'action': 'enable_guests',+ }, timeout: const Duration(minutes: 11));++ /// The folders guests may work in on [machineId], read only or editable (CLI services/sharedMachines.ts+ /// `set_folders`). The view as it is now, or `{error, message}`.+ Future<Map<String, dynamic>> setMachineGuestFolders(+ String machineId,+ List<GuestFolder> folders,+ ) => _sharedMachines(machineId, {+ 'action': 'set_folders',+ 'folders': [+ for (final folder in folders)+ {'path': folder.path, 'write': folder.write},+ ],+ });++ /// Where this account, a guest on [machineId], may start a harness: its workspace and the folders+ /// the machine's owner shares (`guest_folders`). Null when the machine cannot say (an older CLI).+ Future<GuestFolders?> guestFolders(String machineId) async {+ try {+ return GuestFolders.fromJson(+ await _conn(machineId).request(+ 'guest_folders',+ payload: const {},+ timeout: const Duration(seconds: 15),+ ),+ );+ } catch (_) {+ return null;+ }+ }+/// Add a machine shared with this account's domain to its machines, or take one back out/// ([remove]). Asked of this computer's daemon, which pins the machine's key; null when done, else/// what went wrong.@@ -7811,14 +7852,12 @@ class AppNotifier extends ChangeNotifier {/// never got one is "could not reach".Future<Map<String, dynamic>> _sharedMachines(String machineId,- Map<String, dynamic> payload,- ) async {+ Map<String, dynamic> payload, {+ Duration timeout = const Duration(seconds: 30),+ }) async {try {- return await _conn(machineId).request(- 'shared_machines',- payload: payload,- timeout: const Duration(seconds: 30),- );+ return await _conn(machineId)+ .request('shared_machines', payload: payload, timeout: timeout);} on WsRequestFailure catch (failure) {return {...failure.payload, 'error': failure.code};}@@ -13260,6 +13299,17 @@ class AppNotifier extends ChangeNotifier {// fix is the same one the other UNSUPPORTED codes ask for.'INVALID_ENGINE' =>'Update the harness CLI on $machine to open this kind of pane.',+ // A guest's harness: its owner turns guest access on, and only Claude Code or Codex start.+ 'GUEST_NOT_ALLOWED' =>+ 'As a guest on $machine you can start Claude Code or Codex.',+ 'GUEST_UNSUPPORTED' ||+ 'GUEST_HELPER_REQUIRED' ||+ 'GUEST_UNAVAILABLE' ||+ 'GUEST_ENGINE_UNSUPPORTED' ||+ 'GUEST_INVALID' ||+ 'GUEST_HELPER_MISSING' ||+ 'GUEST_HELPER_NOT_AUTHORIZED' ||+ 'GUEST_RELAY_FAILED' => detail ?? 'Could not start a harness on $machine.',_ => 'Could not start harness: ${detail ?? code}',};@@ -13563,6 +13613,17 @@ class AppNotifier extends ChangeNotifier {'SESSION_BUSY_IN_TERMINAL','SESSION_STOP_FAILED','INVALID_SESSION',+ // A guest on a machine shared with this account, refused before anything starts+ // (docs/plans/2026-10-19-guest-machine-sharing-plan.md).+ 'GUEST_NOT_ALLOWED',+ 'GUEST_UNSUPPORTED',+ 'GUEST_HELPER_REQUIRED',+ 'GUEST_UNAVAILABLE',+ 'GUEST_ENGINE_UNSUPPORTED',+ 'GUEST_INVALID',+ 'GUEST_HELPER_MISSING',+ 'GUEST_HELPER_NOT_AUTHORIZED',+ 'GUEST_RELAY_FAILED',};// A cloud agent's service refuses in words a person reads ("Add your// Devin API key…"), and a retry of the same New Harness gets the same@@ -14396,6 +14457,14 @@ class AppNotifier extends ChangeNotifier {/// Attach to a running harness or resume its saved conversation immediately.Future<RestartAgentResult> resumeAgent(String machineId, String agentId) {+ if (stateOf(machineId)?.machine.isSharedMachine == true) {+ return Future.value(+ const RestartAgentResult(+ error: 'A guest’s harness is not restarted, resumed or forked. Start a new one.',+ retryable: false,+ ),+ );+ }if (pendingAgentPause(machineId, agentId) != null) {return Future.value(const RestartAgentResult(@@ -14466,6 +14535,13 @@ class AppNotifier extends ChangeNotifier {retryable: false,);}+ // Relaunched, a guest's harness would run the owner's way, as the owner: the daemon refuses it.+ if (machine.machine.isSharedMachine) {+ return const RestartAgentResult(+ error: 'A guest’s harness is not restarted, resumed or forked. Start a new one.',+ retryable: false,+ );+ }if (pendingAgentStop(machineId, agentId) != null) {return const RestartAgentResult(error: 'The harness is stopping.',@@ -14859,6 +14935,11 @@ class AppNotifier extends ChangeNotifier {if (stateOf(machineId)?.machine.isShared != false) {return Future.value('Shared harnesses are view-only.');}+ if (stateOf(machineId)?.machine.isSharedMachine == true) {+ return Future.value(+ 'A guest’s harness keeps the agent it started with. Start a new one.',+ );+ }if (!agentSwitchEngines(machineId, source).contains(engine)) {return Future.value('This agent is not supported by the installed harness.',@@ -15249,6 +15330,11 @@ class AppNotifier extends ChangeNotifier {if (machine.machine.isShared) {return const ForkAgentResult(error: 'Shared harnesses are view-only.');}+ if (machine.machine.isSharedMachine) {+ return const ForkAgentResult(+ error: 'A guest’s harness is not restarted, resumed or forked. Start a new one.',+ );+ }if (!attempt.awaitingConfirmation) {if (!_forkSourceCurrent(attempt)) {return const ForkAgentResult(diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dartindex 1e524b000..0286e526e 100644--- a/desktop/lib/state/new_harness.dart+++ b/desktop/lib/state/new_harness.dart@@ -16,6 +16,7 @@ import '../core/launch_setup.dart';import '../core/dsh_catalog.dart';import '../core/harness_catalog.dart';import '../core/first_task.dart';+import '../core/guest_folders.dart';import '../core/models.dart';import '../usage/models_menu_controller.dart';import '../core/fuzzy_match.dart';@@ -547,27 +548,32 @@ class NewHarnessController extends ChangeNotifier {.then((_) => _adoptAccountAgent()),);final initialMachine = _machineId;- unawaited(- app.probeDsh(initialMachine, force: true).then((_) {- // Store and remembered choices can open before the machine's catalog- // arrives. Resolve their preferred engine once compatibility is known.- // An inherited session, draft, or explicit user choice keeps its engine.- if (_disposed ||- locked ||- _selectionTouched ||- draft != null ||- (engine != null && !isHarnessId(engine)) ||- _machineId != initialMachine ||- _harnessId == null) {- return;- }- _engine = _initialEngine(null);- _restorePermissionMode();- _refresh();- }),- );- unawaited(_ensureHome(_machineId));- unawaited(_refreshGeneratedProject());+ // A guest is listed no harnesses or folders there (asGuest): nothing to ask.+ if (!asGuest) {+ unawaited(+ app.probeDsh(initialMachine, force: true).then((_) {+ // Store and remembered choices can open before the machine's catalog+ // arrives. Resolve their preferred engine once compatibility is known.+ // An inherited session, draft, or explicit user choice keeps its engine.+ if (_disposed ||+ locked ||+ _selectionTouched ||+ draft != null ||+ (engine != null && !isHarnessId(engine)) ||+ _machineId != initialMachine ||+ _harnessId == null) {+ return;+ }+ _engine = _initialEngine(null);+ _restorePermissionMode();+ _refresh();+ }),+ );+ unawaited(_ensureHome(_machineId));+ unawaited(_refreshGeneratedProject());+ } else {+ _startAsGuest();+ }}final AppNotifier app;@@ -636,7 +642,58 @@ class NewHarnessController extends ChangeNotifier {_machine?.dsh.entries ?? const <DshEntry>[],_harnessId!,);- List<String> get compatibleEngines => _harnessId == null++ /// A machine shared with this account: this person is a guest there, with a space of+ /// their own (docs/plans/2026-10-19-guest-machine-sharing-plan.md). Its daemon starts+ /// Claude Code or Codex in that space, on its owner's plans, and lists a guest no+ /// folders, harnesses, models or profiles, so none are asked for or offered.+ bool get asGuest => _machine?.machine.isSharedMachine == true;++ /// Where a guest may start there (asGuest): its workspace and the folders the owner shares, as the+ /// machine last said; null until it has.+ GuestFolders? _guestFolders;++ /// A guest starts in its workspace until it picks a folder the owner shares.+ void _startAsGuest() {+ _project = const NewHarnessProject.fresh();+ // An agent a guest cannot start there (OpenCode, a Store harness) gives way to Claude Code.+ if (_harnessId != null || !compatibleEngines.contains(_engine)) {+ _harnessId = null;+ _engine = compatibleEngines.first;+ _restorePermissionMode();+ }+ _guestFolders = null;+ final id = _machineId;+ unawaited(+ app.guestFolders(id).then((folders) {+ if (_disposed || id != _machineId) return;+ _guestFolders = folders;+ _refresh();+ }),+ );+ }++ /// A guest's Project: its workspace, or one of the folders the owner shares.+ List<NewHarnessOption> _guestPlaces() => [+ NewHarnessOption(+ id: guestWorkspaceId,+ title: 'My workspace',+ detail: 'Your own folder on $machineLabel',+ project: const NewHarnessProject.fresh(),+ ),+ for (final folder in _guestFolders?.folders ?? const <GuestFolder>[])+ NewHarnessOption(+ id: '$guestFolderId${folder.path}',+ title: p.basename(folder.path),+ detail:+ '${folder.path} · ${folder.write ? 'you can edit it' : 'read only'}',+ project: NewHarnessProject.folder(folder.path, exact: true),+ ),+ ];++ List<String> get compatibleEngines => asGuest+ ? const ['claude', 'codex']+ : _harnessId == null? [for (final engine in allEngines) engine.id,for (final agent in cloudAgents) agent.id,@@ -952,7 +1009,8 @@ class NewHarnessController extends ChangeNotifier {branchRefreshError = null;_branchesCheckedAt = null;_gitFuture = null;- if (key.$2 != null && !key.$3 && !checking) {+ // A guest's harness starts in its own space: no folder of theirs to read Git in (asGuest).+ if (key.$2 != null && !key.$3 && !checking && !asGuest) {_gitFuture = _readGitProject(key);}}@@ -1077,7 +1135,8 @@ class NewHarnessController extends ChangeNotifier {}Future<void> refreshModels() async {- if (_disposed) return;+ // A guest's harness runs on its owner's plans: no grid or saved API to pick.+ if (_disposed || asGuest) return;final request = ++_modelRequest;final machine = _machineId;_loadingModels = true;@@ -1319,8 +1378,9 @@ class NewHarnessController extends ChangeNotifier {_modes.any((mode) => mode.id == _mode) ? _mode : kDefaultPermissionMode;String get modeLabel =>_modes.where((m) => m.id == mode).firstOrNull?.label ?? mode;- bool get usesProfile => _base == 'codex' && _model == null;- bool get hasProfile => _baseOf(_settingsEngine) == 'codex';+ // A guest's Codex runs on its owner's subscription, through the relay: no CODEX_HOME of its own to pick (asGuest).+ bool get usesProfile => !asGuest && _base == 'codex' && _model == null;+ bool get hasProfile => !asGuest && _baseOf(_settingsEngine) == 'codex';bool get supportsProfiles =>hasProfile && _machine?.engines['codex']?.supportsCodexHome == true;String? get profileHelp => supportsProfiles@@ -1378,11 +1438,13 @@ class NewHarnessController extends ChangeNotifier {List<NewHarnessField> get fields => [NewHarnessField.harness,NewHarnessField.agent,- if (!isTerminal) NewHarnessField.model,+ if (!isTerminal && !asGuest) NewHarnessField.model,NewHarnessField.machine,- NewHarnessField.projectMenu,+ // A guest picks only among the folders the owner shares, when there are any.+ if (!asGuest || (_guestFolders?.folders.isNotEmpty ?? false))+ NewHarnessField.projectMenu,if (advancedOpen) ...[- if (isGitProject) NewHarnessField.branch,+ if (isGitProject && !asGuest) NewHarnessField.branch,if (hasModes) NewHarnessField.mode,if (usesProfile) NewHarnessField.profile,],@@ -1460,6 +1522,7 @@ class NewHarnessController extends ChangeNotifier {}bool get needsProject =>+ !asGuest &&!isTerminal &&!isCloud &&_project.folder == null &&@@ -1504,6 +1567,7 @@ class NewHarnessController extends ChangeNotifier {final engineState = machine.engines[_engine];if (!compatibleEngines.contains(_engine) ||(_rememberedAgent &&+ !asGuest &&!_selectionTouched &&engineState?.installed == false &&// The product default installs on Create; one that cannot be@@ -1571,6 +1635,7 @@ class NewHarnessController extends ChangeNotifier {String get projectLabel {final project = _project;+ if (asGuest) return project.folder ?? 'My workspace';if (project.folder case final folder?) return tildePath(folder);if (project.repository case final repo?) return '~/harnesses/${repo.name}';if (isTerminal) return '~';@@ -1877,6 +1942,8 @@ class NewHarnessController extends ChangeNotifier {static const newProjectId = 'project:name';static const createBranchId = 'branch:create:';static const existingProjectId = 'project:existing';+ static const guestWorkspaceId = 'project:guest-workspace';+ static const guestFolderId = 'project:guest-folder:';static const repositoryId = 'project:repository';static const storeId = 'agent:store';static const codingId = 'harness:coding';@@ -1941,35 +2008,37 @@ class NewHarnessController extends ChangeNotifier {}}- List<NewHarnessOption> _projectMenu() => [- if (!_desktopChoices)- const NewHarnessOption(- id: repositoryId,- synthetic: true,- title: 'Clone Repository',- detail: 'Paste a GitHub repository URL',- ),- const NewHarnessOption(- id: existingProjectId,- synthetic: true,- title: 'Open Folder',- detail: 'Enter a path or browse folders',- ),- const NewHarnessOption(- id: newProjectId,- synthetic: true,- title: 'New Folder',- detail: 'Name a new folder',- ),- if (_desktopChoices)- const NewHarnessOption(- id: repositoryId,- synthetic: true,- title: 'GitHub',- detail: 'Clone a GitHub repository',- ),- ..._ranked(_recentProjects()),- ];+ List<NewHarnessOption> _projectMenu() => asGuest+ ? _guestPlaces()+ : [+ if (!_desktopChoices)+ const NewHarnessOption(+ id: repositoryId,+ synthetic: true,+ title: 'Clone Repository',+ detail: 'Paste a GitHub repository URL',+ ),+ const NewHarnessOption(+ id: existingProjectId,+ synthetic: true,+ title: 'Open Folder',+ detail: 'Enter a path or browse folders',+ ),+ const NewHarnessOption(+ id: newProjectId,+ synthetic: true,+ title: 'New Folder',+ detail: 'Name a new folder',+ ),+ if (_desktopChoices)+ const NewHarnessOption(+ id: repositoryId,+ synthetic: true,+ title: 'GitHub',+ detail: 'Clone a GitHub repository',+ ),+ ..._ranked(_recentProjects()),+ ];/// Takes the highlighted row as this field's answer and moves along.void accept([NewHarnessOption? row]) {@@ -2226,6 +2295,10 @@ class NewHarnessController extends ChangeNotifier {_listing = null;_pathKey = null;unawaited(app.probeEngines(id, force: true));+ // A guest is listed no harnesses or folders there, only where it may start (asGuest).+ if (app.stateOf(id)?.machine.isSharedMachine == true) {+ return _startAsGuest();+ }unawaited(app.probeDsh(id, force: true));unawaited(_ensureHome(id));unawaited(_refreshGeneratedProject());@@ -2680,7 +2753,8 @@ class NewHarnessController extends ChangeNotifier {options = switch (field) {NewHarnessField.harness => [..._harnessOptions(),- if (offersStore) _store,+ // A guest starts nothing from the Store there (asGuest).+ if (offersStore && !asGuest) _store,],NewHarnessField.launch ||NewHarnessField.task ||@@ -2926,6 +3000,13 @@ class NewHarnessController extends ChangeNotifier {}List<NewHarnessOption> _harnessOptions() {+ // A guest there starts Claude Code or Codex, nothing from the Store (asGuest).+ if (asGuest) {+ return _ranked([+ for (final id in compatibleEngines)+ NewHarnessOption(id: id, title: labelOf(id), engine: id),+ ]);+ }final machine = _machine;final harnesses = machine != null && machine.dsh.loaded? [@@ -3696,7 +3777,9 @@ class NewHarnessController extends ChangeNotifier {return NewHarnessOutcome.failed;}final choice = _engine;- var harness = _harnessId;+ // A guest starts the engine itself, in its own space, on the owner's plans (asGuest).+ var harness = asGuest ? null : _harnessId;+ final model = asGuest ? null : _model;final terminal = isTerminalEngine(choice);final base = choice;// The daemon's launch installs a missing engine inside its new terminal.@@ -3718,10 +3801,10 @@ class NewHarnessController extends ChangeNotifier {status = recheck ? 'Checking on the harness…' : 'Starting harness…';notifyListeners();}- if (_model != null && !recheck) {+ if (model != null && !recheck) {await refreshModels();if (_disposed) return NewHarnessOutcome.failed;- if (!_modelAvailable(_model!)) {+ if (!_modelAvailable(model)) {return _fail('The selected model is unavailable for $agentLabel on $machineLabel. Choose a model or use your subscription.',);@@ -3801,8 +3884,8 @@ class NewHarnessController extends ChangeNotifier {engine: base,harnessId: harness,permissionMode: permissionMode ?? kDefaultPermissionMode,- model: _model,- profile: base == 'codex' && _model == null ? _profile : null,+ model: model,+ profile: base == 'codex' && model == null && !asGuest ? _profile : null,profileMachineId: _machineId,);// Working in a picked worktree says nothing about the next harness's.@@ -3812,15 +3895,20 @@ class NewHarnessController extends ChangeNotifier {final failure = await app.createAgent(_machineId,engine: base,- folder: terminal ? folder : folder ?? '',- projectFolder: projectFolderRequest,+ // A guest's harness starts in its workspace, or a folder the owner shares (asGuest).+ folder: asGuest+ ? (_project.folder ?? '')+ : (terminal ? folder : folder ?? ''),+ projectFolder: asGuest ? null : projectFolderRequest,swarmId: _targetId,split: split,placement: effectivePlacement,bypassPermission: bypass,permissionMode: permissionMode,- codexHome: base == 'codex' && _model == null ? _profile?.path : null,- model: _model,+ codexHome: base == 'codex' && model == null && !asGuest+ ? _profile?.path+ : null,+ model: model,dsh: harness,// Sent exactly as written; an agent that cannot take one is never sent it.prompt: takesTask && files.isEmpty && launchMessage.isNotEmptydiff --git a/desktop/lib/state/retarget_refusal.dart b/desktop/lib/state/retarget_refusal.dartindex ab630f13b..4b5912d5d 100644--- a/desktop/lib/state/retarget_refusal.dart+++ b/desktop/lib/state/retarget_refusal.dart@@ -54,6 +54,9 @@ String retargetRefusalMessage("This machine's Local models could not be resolved. Sign in again on it.",'UNSUPPORTED_ON_REMOTE' ||'UNSUPPORTED' => 'Update the harness CLI on this machine to change models.',+ // A guest's harness runs on its owner's plans and is never relaunched+ // (docs/plans/2026-10-19-guest-machine-sharing-plan.md).+ 'GUEST_NOT_ALLOWED' || 'GUEST_HARNESS' => 'A guest’s harness keeps the model it started with. Start a new one to use another.',_ => "Couldn't change this harness's model.",};}diff --git a/desktop/lib/state/swarm_navigation.dart b/desktop/lib/state/swarm_navigation.dartindex f82e37409..d7510548c 100644--- a/desktop/lib/state/swarm_navigation.dart+++ b/desktop/lib/state/swarm_navigation.dart@@ -602,7 +602,7 @@ class SwarmSearchCatalog {detail: ['Machine',if (machine.machine.machineShare case final share?)- 'Shared by ${share.owner}',+ 'Guest · shared by ${share.owner}',_countLabel(members.length, 'harness'),if (machine.needsLink)'Link required'diff --git a/desktop/lib/widgets/machine_sharing_form.dart b/desktop/lib/widgets/machine_sharing_form.dartindex c482d8c5a..c92d33fd6 100644--- a/desktop/lib/widgets/machine_sharing_form.dart+++ b/desktop/lib/widgets/machine_sharing_form.dart@@ -3,6 +3,7 @@ import 'dart:async';import 'package:flutter/material.dart';import 'package:flutter/services.dart';+import '../core/guest_folders.dart';import '../shared/theme/app_icons.dart';import '../shared/theme/app_theme.dart' as grid;import '../shared/widgets/app_icon_button.dart';@@ -19,6 +20,9 @@ import 'terminal_text_action.dart';/// The most addresses one machine is shared with (CLI services/sharedMachines.ts `SHARE_EMAILS_MAX`).const int machineShareEmailsMax = 100;+/// The most folders guests may use there (CLI services/sharedMachines.ts `SHARED_FOLDERS_MAX`).+const int machineSharedFoldersMax = 20;+/// The backend's own rule for an address (zod's `email()`): one it would refuse is refused as it is/// typed, by name, never as a failed save of the whole list.final _emailPattern = RegExp(@@ -58,8 +62,10 @@ class MachineSharingForm extends StatefulWidget {class MachineSharingFormState extends State<MachineSharingForm> {final _scope = FocusNode(debugLabel: 'Machine sharing');final _input = FocusNode(debugLabel: 'Share email');+ final _folderInput = FocusNode(debugLabel: 'Share folder');final _buttons = <String, FocusNode>{};final _value = TextEditingController();+ final _folderValue = TextEditingController();bool _loading = true, _busy = false;/// Why the sharing could not be read at all; the form offers Retry instead of its controls.@@ -80,7 +86,30 @@ class MachineSharingFormState extends State<MachineSharingForm> {String? _domain;List<Map<String, dynamic>> _members = const [];+ /// Whether guests can start harnesses there (`ready`), or what turning it on takes (`missing`,+ /// `outdated`, `not-authorized`); null from a CLI that predates guests.+ String? _guestAccess;++ /// Waiting on the admin prompt on that computer, which the first share shows.+ bool _approving = false;++ /// The owner's folders guests may work in there, read only or editable.+ List<GuestFolder> _folders = const [];++ /// What is wrong with the folder typed, said under its field.+ String? _folderError;+AppNotifier get app => widget.app;++ /// Whether it is shared with anyone now.+ bool get _sharing => _emails.isNotEmpty || _sameDomain;++ /// What a guest gets, and, until it is on, what sharing will ask of the owner.+ String get _guestNote => _approving+ ? 'Approve the prompt on $_name: it lets each guest run as their own account there.'+ : 'Guests get their own space on $_name and can use your Claude and ChatGPT plans. '+ 'They cannot see your files or harnesses.'+ '${_guestAccess == null || _guestAccess == 'ready' ? '' : ' Sharing asks for an admin password on $_name once.'}';String get _name =>app.stateOf(widget.machineId)?.machine.displayName ?? 'this machine';bool get _composing =>@@ -90,14 +119,18 @@ class MachineSharingFormState extends State<MachineSharingForm> {void initState() {super.initState();_value.addListener(_typed);+ _folderValue.addListener(_typed);unawaited(_load());}@overridevoid dispose() {_value.removeListener(_typed);+ _folderValue.removeListener(_typed);_scope.dispose();_input.dispose();+ _folderInput.dispose();+ _folderValue.dispose();for (final node in _buttons.values) {node.dispose();}@@ -110,6 +143,7 @@ class MachineSharingFormState extends State<MachineSharingForm> {if (!mounted) return;setState(() {_fieldError = null;+ _folderError = null;});}@@ -151,6 +185,8 @@ class MachineSharingFormState extends State<MachineSharingForm> {];_sameDomain = answer['sameDomain'] == true;_domain = answer['domain'] as String?;+ _guestAccess = answer['guestAccess'] as String? ?? _guestAccess;+ _folders = GuestFolders.fromJson(answer).folders;_members = [for (final member in answer['members'] as List? ?? const [])if (member is Map) Map<String, dynamic>.from(member),@@ -191,12 +227,17 @@ class MachineSharingFormState extends State<MachineSharingForm> {/// Make the machine's sharing [emails] and [sameDomain], at once. While it is written nothing else/// can change; a refusal leaves the sharing as it was and says why.+ ///+ /// The first share turns guest access on first: each guest's harnesses run as their own account+ /// there, which takes one admin prompt on that computer (docs/plans/2026-10-19-guest-machine-sharing-plan.md).Future<bool> _apply(List<String> emails, bool sameDomain) async {if (_busy) return false;setState(() {_busy = true;_status = null;});+ final sharing = emails.isNotEmpty || sameDomain;+ if (sharing && _guestsOff && !await _enableGuests()) return false;Map<String, dynamic> answer;try {answer = await app.setMachineSharing(@@ -226,6 +267,49 @@ class MachineSharingFormState extends State<MachineSharingForm> {return true;}+ /// Guest access is off there: the helper is missing, or older than this CLI's (an update), or no longer+ /// allowed. Null (a CLI from before guests) is not off.+ bool get _guestsOff => _guestAccess != null && _guestAccess != 'ready';++ /// Turn guest access on there, behind its admin prompt; false, with the reason said, when it was not.+ /// Called with the form busy, or busies it while it waits.+ Future<bool> _enableGuests() async {+ setState(() {+ _busy = true;+ _status = null;+ _approving = true;+ });+ Map<String, dynamic> enabled;+ try {+ enabled = await app.enableMachineGuests(widget.machineId);+ } catch (error) {+ enabled = {+ 'error': 'UNAVAILABLE',+ 'message': 'Could not reach $_name. Nothing changed.',+ };+ }+ if (!mounted) return false;+ final refused = enabled['error'];+ setState(() {+ _approving = false;+ if (refused != null) {+ _busy = false;+ _status =+ enabled['message'] as String? ??+ 'Guest access was not turned on ($refused).';+ } else {+ _guestAccess = enabled['guestAccess'] as String? ?? 'ready';+ }+ });+ return refused == null;+ }++ /// Turn on, on its own: shared already, but guests cannot start harnesses until it is on again.+ Future<void> _turnGuestsOn() async {+ if (_busy) return;+ if (await _enableGuests() && mounted) setState(() => _busy = false);+ }+/// Done: closes, and says where the sharing now stands when it changed here.void _done() {if (!_changed) return widget.onClose(null);@@ -291,6 +375,88 @@ class MachineSharingFormState extends State<MachineSharingForm> {await _apply(_emails, !_sameDomain);}+ /// Make the folders guests may use [folders], at once; a refusal (a folder that is not the owner's,+ /// or not there) leaves them as they were and says why.+ Future<bool> _applyFolders(List<GuestFolder> folders) async {+ if (_busy) return false;+ setState(() {+ _busy = true;+ _status = null;+ });+ Map<String, dynamic> answer;+ try {+ answer = await app.setMachineGuestFolders(widget.machineId, folders);+ } catch (error) {+ answer = {+ 'error': 'UNAVAILABLE',+ 'message': 'Could not reach $_name. Nothing changed.',+ };+ }+ if (!mounted) return false;+ final error = answer['error'];+ setState(() {+ _busy = false;+ if (error == null) {+ _show(answer);+ } else {+ _status =+ answer['message'] as String? ??+ 'Could not share the folder ($error).';+ }+ });+ if (error != null) return false;+ _changed = true;+ return true;+ }++ /// The folder typed, shared read only: a guest's harness may read it, and the switch lets it edit.+ Future<void> _addFolder() async {+ if (_busy || _loading) return;+ final typed = _folderValue.text.trim();+ if (typed.isEmpty) {+ _folderInput.requestFocus();+ return;+ }+ final path = typed.length > 1 && typed.endsWith('/')+ ? typed.substring(0, typed.length - 1)+ : typed;+ String? problem;+ if (!path.startsWith('/')) {+ problem =+ 'Enter the folder’s full path on $_name, like /Users/you/project.';+ } else if (_folders.any((folder) => folder.path == path)) {+ problem = 'Guests can already use $path.';+ } else if (_folders.length >= machineSharedFoldersMax) {+ problem = 'Guests can use up to $machineSharedFoldersMax folders.';+ }+ if (problem != null) {+ setState(() => _folderError = problem);+ _folderInput.requestFocus();+ return;+ }+ final added = await _applyFolders([+ ..._folders,+ GuestFolder(path: path, write: false),+ ]);+ if (added) _folderValue.clear();+ if (mounted) _folderInput.requestFocus();+ }++ Future<void> _toggleFolderWrite(String path) => _applyFolders([+ for (final folder in _folders)+ folder.path == path+ ? GuestFolder(path: path, write: !folder.write)+ : folder,+ ]);++ Future<void> _removeFolder(String path) async {+ await _applyFolders([+ for (final folder in _folders)+ if (folder.path != path) folder,+ ]);+ if (mounted) focus();+ }+// ── keys ──────────────────────────────────────────────────────────────────────────────────────/// The editor's stops, in reading order: Back, the domain switch, (the field,) Share, each person's@@ -304,6 +470,8 @@ class MachineSharingFormState extends State<MachineSharingForm> {}return [(id: 'back', run: _done),+ if (_guestsOff && _sharing)+ (id: 'guests-on', run: _busy ? null : () => unawaited(_turnGuestsOn())),if (_domain != null)(id: 'domain', run: _busy ? null : () => unawaited(_toggleDomain())),(@@ -317,6 +485,22 @@ class MachineSharingFormState extends State<MachineSharingForm> {id: 'remove:${person.email}',run: _busy ? null : () => unawaited(_remove(person.email)),),+ (+ id: 'folder-add',+ run: _busy || _folderValue.text.trim().isEmpty+ ? null+ : () => unawaited(_addFolder()),+ ),+ for (final folder in _folders) ...[+ (+ id: 'folder-write:${folder.path}',+ run: _busy ? null : () => unawaited(_toggleFolderWrite(folder.path)),+ ),+ (+ id: 'folder-remove:${folder.path}',+ run: _busy ? null : () => unawaited(_removeFolder(folder.path)),+ ),+ ],];}@@ -326,13 +510,17 @@ class MachineSharingFormState extends State<MachineSharingForm> {List<FocusNode> get _nodes {final stops = _stops.where((stop) => stop.run != null).toList();final field = !_loading && _unavailable == null && !_busy;- const beforeField = {'back', 'domain'};+ const beforeField = {'back', 'guests-on', 'domain'};+ bool folders(String id) => id.startsWith('folder-');return [for (final stop in stops)if (beforeField.contains(stop.id)) _node(stop.id),if (field) _input,for (final stop in stops)- if (!beforeField.contains(stop.id)) _node(stop.id),+ if (!beforeField.contains(stop.id) && !folders(stop.id)) _node(stop.id),+ if (field) _folderInput,+ for (final stop in stops)+ if (folders(stop.id)) _node(stop.id),];}@@ -367,6 +555,10 @@ class MachineSharingFormState extends State<MachineSharingForm> {unawaited(_add());return;}+ if (_folderInput.hasFocus) {+ unawaited(_addFolder());+ return;+ }final stop = _stops.where((s) => _buttons[s.id]?.hasFocus == true).firstOrNull;@@ -513,7 +705,7 @@ class MachineSharingFormState extends State<MachineSharingForm> {),);- // What sharing gives, said once and plainly: these people get the owner's own rights.+ // What sharing gives, said once and plainly: guests get a space of their own, never the owner's.final access = Row(crossAxisAlignment: CrossAxisAlignment.start,children: [@@ -526,12 +718,7 @@ class MachineSharingFormState extends State<MachineSharingForm> {),),const SizedBox(width: 8),- Expanded(- child: Text(- 'People you share it with get full access: they can run harnesses, open terminals and read files on it.',- style: muted13,- ),- ),+ Expanded(child: Text(_guestNote, style: muted13)),],);@@ -650,6 +837,123 @@ class MachineSharingFormState extends State<MachineSharingForm> {],);+ final folderAddRow = Row(+ children: [+ Expanded(+ child: ReadlineKeys(+ controller: _folderValue,+ enabled: !_busy,+ onChanged: (_) {},+ child: TextField(+ key: const ValueKey('machine-sharing-folder'),+ controller: _folderValue,+ focusNode: _folderInput,+ readOnly: _busy,+ onTapOutside: (_) {},+ enableSuggestions: false,+ autocorrect: false,+ style: DesktopChrome.text(size: 13),+ cursorColor: DesktopChrome.accent,+ decoration: InputDecoration(+ hintText: 'Add a folder by its full path',+ hintStyle: muted13,+ prefixIcon: Icon(+ AppIcons.folder,+ size: AppIcons.inlineSize,+ color: DesktopChrome.muted,+ ),+ prefixIconConstraints: const BoxConstraints(minWidth: 36),+ border: fieldBorder,+ enabledBorder: _folderError == null+ ? fieldBorder+ : fieldBorder.copyWith(+ borderSide: BorderSide(color: error),+ ),+ disabledBorder: fieldBorder,+ focusedBorder: fieldBorder.copyWith(+ borderSide: BorderSide(+ color: _folderError == null+ ? DesktopChrome.focusRing+ : error,+ width: grid.AppDesktop.focusWidth,+ ),+ ),+ filled: true,+ fillColor: DesktopChrome.field,+ isDense: true,+ contentPadding: const EdgeInsets.symmetric(+ horizontal: 10,+ vertical: 11,+ ),+ ),+ onEditingComplete: () {},+ ),+ ),+ ),+ const SizedBox(width: DesktopChrome.controlGap),+ FilledButton(+ key: const ValueKey('machine-sharing:folder-add'),+ focusNode: _node('folder-add'),+ onPressed: !_busy && _folderValue.text.trim().isNotEmpty+ ? () => unawaited(_addFolder())+ : null,+ child: const Text('Add'),+ ),+ ],+ );++ Widget folderRow(GuestFolder folder) => Padding(+ key: ValueKey('machine-sharing-folder:${folder.path}'),+ padding: const EdgeInsets.symmetric(vertical: 4),+ child: Row(+ children: [+ Icon(+ AppIcons.folder,+ size: AppIcons.inlineSize,+ color: DesktopChrome.muted,+ ),+ const SizedBox(width: 12),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ folder.path,+ style: DesktopChrome.control(medium: true),+ overflow: TextOverflow.ellipsis,+ ),+ const SizedBox(height: 2),+ Text(+ folder.write ? 'Guests can edit it' : 'Read only',+ style: DesktopChrome.metadata(),+ ),+ ],+ ),+ ),+ Text('Can edit', style: DesktopChrome.metadata()),+ const SizedBox(width: 6),+ Switch(+ key: ValueKey('machine-sharing:folder-write:${folder.path}'),+ focusNode: _node('folder-write:${folder.path}'),+ value: folder.write,+ onChanged: _busy+ ? null+ : (_) => unawaited(_toggleFolderWrite(folder.path)),+ ),+ AppIconButton(+ key: ValueKey('machine-sharing:folder-remove:${folder.path}'),+ icon: AppIcons.close,+ tooltip: 'Stop sharing ${folder.path}',+ destructive: true,+ focusNode: _node('folder-remove:${folder.path}'),+ onPressed: _busy+ ? null+ : () => unawaited(_removeFolder(folder.path)),+ ),+ ],+ ),+ );+Widget personRow(_Person person) => Padding(key: ValueKey('machine-sharing-person:${person.email}'),padding: const EdgeInsets.symmetric(vertical: 4),@@ -787,6 +1091,28 @@ class MachineSharingFormState extends State<MachineSharingForm> {heading,small,access,+ if (_guestsOff && _sharing) ...[+ small,+ Row(+ children: [+ Expanded(+ child: Text(+ _guestAccess == 'outdated'+ ? 'Guests cannot start harnesses until you turn guest access on again after the update.'+ : 'Guests cannot start harnesses until you turn guest access on.',+ style: DesktopChrome.text(size: 13),+ ),+ ),+ const SizedBox(width: DesktopChrome.controlGap),+ FilledButton(+ key: const ValueKey('machine-sharing:guests-on'),+ focusNode: _node('guests-on'),+ onPressed: _busy ? null : () => unawaited(_turnGuestsOn()),+ child: const Text('Turn on'),+ ),+ ],+ ),+ ],gap,if (_domain case final domain?) ...[domainRow(domain), gap],Text('People', style: DesktopChrome.control(medium: true)),@@ -808,6 +1134,28 @@ class MachineSharingFormState extends State<MachineSharingForm> {),),if (people.isNotEmpty) ...[small, ...people.map(personRow)],+ gap,+ Text('Folders', style: DesktopChrome.control(medium: true)),+ small,+ Text(+ 'Guests can open these in their harnesses. They can read anything inside, secrets too.',+ style: muted13,+ ),+ small,+ folderAddRow,+ if (_folderError case final problem?)+ Padding(+ padding: const EdgeInsets.only(top: 6, left: 2),+ child: Semantics(+ liveRegion: true,+ child: Text(+ problem,+ key: const ValueKey('machine-sharing:folder-error'),+ style: DesktopChrome.text(size: 12, color: error),+ ),+ ),+ ),+ if (_folders.isNotEmpty) ...[small, ..._folders.map(folderRow)],];}@@ -868,10 +1216,13 @@ class MachineSharingFormState extends State<MachineSharingForm> {gap,action('retry', 'Retry', () => unawaited(_load())),] else ...[- line(- 'People you share it with get full access: harnesses, terminals and files.',- color: theme.muted,- ),+ line(_guestNote, color: theme.muted),+ if (_guestsOff && _sharing)+ action(+ 'guests-on',+ 'Turn guest access on',+ _busy ? null : () => unawaited(_turnGuestsOn()),+ ),gap,if (_domain case final domain?) ...[action(@@ -933,6 +1284,68 @@ class MachineSharingFormState extends State<MachineSharingForm> {),],),+ gap,+ line(+ 'Folders guests can open. They can read anything inside, secrets too.',+ color: theme.muted,+ ),+ Row(+ children: [+ SizedBox(+ width: cell.width * 8,+ child: Text(+ 'folder >',+ style: terminalContentStyle(color: theme.muted),+ ),+ ),+ Expanded(+ child: ReadlineKeys(+ controller: _folderValue,+ enabled: !_busy,+ onChanged: (_) {},+ child: TextField(+ key: const ValueKey('machine-sharing-folder'),+ controller: _folderValue,+ focusNode: _folderInput,+ readOnly: _busy,+ onTapOutside: (_) {},+ enableSuggestions: false,+ autocorrect: false,+ style: terminalContentStyle(color: theme.foreground),+ cursorColor: theme.foreground,+ decoration: const InputDecoration(+ border: InputBorder.none,+ isDense: true,+ isCollapsed: true,+ contentPadding: EdgeInsets.zero,+ ),+ onEditingComplete: () {},+ ),+ ),+ ),+ ],+ ),+ for (final folder in _folders)+ Row(+ children: [+ Expanded(child: line(folder.path)),+ action(+ 'folder-write:${folder.path}',+ '[${folder.write ? 'x' : ' '}] can edit',+ _busy+ ? null+ : () => unawaited(_toggleFolderWrite(folder.path)),+ ),+ SizedBox(width: cell.width),+ action(+ 'folder-remove:${folder.path}',+ 'Remove',+ _busy ? null : () => unawaited(_removeFolder(folder.path)),+ ),+ ],+ ),+ if (_folderError case final problem?)+ line(problem, color: theme.yellow),],if (_fieldError case final problem?)line(problem, color: _fieldIsError ? theme.yellow : theme.muted),diff --git a/desktop/lib/widgets/new_harness_form.dart b/desktop/lib/widgets/new_harness_form.dartindex 83ccc9bb4..0c71f3274 100644--- a/desktop/lib/widgets/new_harness_form.dart+++ b/desktop/lib/widgets/new_harness_form.dart@@ -132,7 +132,7 @@ class NewHarnessFormState extends State<NewHarnessForm> {!_advancedRows.contains(row) ||box.advancedOpen) &&(row != _Row.profile || box.usesProfile) &&- (row != _Row.model || !box.isTerminal) &&+ (row != _Row.model || (!box.isTerminal && !box.asGuest)) &&(row != _Row.approvals || box.hasModes))row,];@@ -1777,11 +1777,17 @@ class NewHarnessFormState extends State<NewHarnessForm> {Widget _desktopHeader() {final folder = box.project.folder;- final projectName =- box.project.name ??- folder?.split(RegExp(r'[/\\]')).where((p) => p.isNotEmpty).lastOrNull ??- box.project.repository?.name ??- 'Choose repo';+ final lastPart = folder+ ?.split(RegExp(r'[/\\]'))+ .where((p) => p.isNotEmpty)+ .lastOrNull;+ // A guest starts in its workspace or a folder the owner shares (NewHarnessController.asGuest).+ final projectName = box.asGuest+ ? lastPart ?? 'My workspace'+ : box.project.name ??+ lastPart ??+ box.project.repository?.name ??+ 'Choose repo';return Row(crossAxisAlignment: CrossAxisAlignment.start,children: [@@ -1848,7 +1854,9 @@ class NewHarnessFormState extends State<NewHarnessForm> {),// Fo takes no repository; a cloud coding agent works on the chosen// repository's GitHub copy, never on this computer's folder.- if (!box.isCloud || cloudAgentTakesRepository(box.engine))+ if ((!box.isCloud || cloudAgentTakesRepository(box.engine)) &&+ (!box.asGuest ||+ box.fields.contains(NewHarnessField.projectMenu)))_desktopField(order: 3,anchor: _desktopAnchors[_Row.project]!,@@ -2048,7 +2056,9 @@ class NewHarnessFormState extends State<NewHarnessForm> {mainAxisSize: MainAxisSize.min,spacing: 2,children: [- if (!box.isTerminal && !box.isCloud)+ // A guest's harness runs on the owner's subscription: no model or+ // account of its own to pick.+ if (!box.isTerminal && !box.isCloud && !box.asGuest)_desktopField(order: 5,anchor: _desktopAnchors[_Row.model]!,diff --git a/desktop/lib/widgets/swarm_resource_preview.dart b/desktop/lib/widgets/swarm_resource_preview.dartindex 0a612beb6..8b7d09f58 100644--- a/desktop/lib/widgets/swarm_resource_preview.dart+++ b/desktop/lib/widgets/swarm_resource_preview.dart@@ -1689,11 +1689,14 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {if (machine.isLocalMachine) 'This computer',if (machine.machine.isShared) 'View only',if (machine.machine.machineShare case final share?)- 'Shared by ${share.owner}',+ 'Guest · shared by ${share.owner}',].join(' · '),'',+ // A guest's harnesses run as their own account there, on the owner's plans+ // (docs/plans/2026-10-19-guest-machine-sharing-plan.md).if (machine.machine.machineShare case final share?) ...[- 'You use it as your own. Only ${share.owner} can rename, remove or share it.',+ 'You have your own space on it and use ${share.owner}’s Claude and ChatGPT plans. '+ 'You see only the harnesses you start there.','',],if (resources?.cpuPercent case final cpu?) 'CPU ${cpu.round()}%',diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dartindex d3aecf728..989c2049b 100644--- a/desktop/lib/widgets/terminal_panel.dart+++ b/desktop/lib/widgets/terminal_panel.dart@@ -2761,7 +2761,10 @@ class _TerminalHeader extends StatelessWidget {].join('\n');// Reserve space for the pane-local model selector.// Engines without a picker keep their existing header width.- final showModelPicker = modelPickerSupports(session.engineId);+ // A guest's harness runs on its owner's plans: no model to move it to.+ final showModelPicker =+ modelPickerSupports(session.engineId) &&+ notifier.stateOf(session.machineId)?.machine.isSharedMachine != true;// Both text selectors keep their natural width until the title has yielded.final pickerWidth =(showModelPicker ? 232.0 : 0.0) + (agent != null ? 140.0 : 0.0);diff --git a/desktop/lib/ws/local_cli_discovery.dart b/desktop/lib/ws/local_cli_discovery.dartindex cd342a26b..fb74bab5e 100644--- a/desktop/lib/ws/local_cli_discovery.dart+++ b/desktop/lib/ws/local_cli_discovery.dart@@ -575,7 +575,13 @@ class LocalCliDiscovery {}) async {final Map<String, dynamic>? body;try {- final response = await dio.getUri<Map<String, dynamic>>(statusUri);+ final response = await dio.getUri<Map<String, dynamic>>(+ statusUri,+ // Over the port, the whole status wants the daemon's local credential.+ options: socketPath == null+ ? Options(headers: transport.tcpHeaders())+ : null,+ );body = response.data;} on DioException catch (error) {switch (error.type) {diff --git a/desktop/lib/ws/local_daemon_transport.dart b/desktop/lib/ws/local_daemon_transport.dartindex 2b76cb4f2..177a34dcd 100644--- a/desktop/lib/ws/local_daemon_transport.dart+++ b/desktop/lib/ws/local_daemon_transport.dart@@ -26,6 +26,15 @@ String daemonSocketName(int port) => 'daemon-$port.sock';/// the app look for one.const _maxSocketPathBytes = 96;+/// The daemon's data folder: `$ADAPTER_DATA_DIR`, by default+/// `~/.harness/cli/data` — or null with no home to put it in.+String? defaultDaemonDataDir({Map<String, String>? environment}) {+ final env = environment ?? Platform.environment;+ final home = env['HOME'] ?? env['USERPROFILE'];+ return env['ADAPTER_DATA_DIR'] ??+ (home == null || home.isEmpty ? null : '$home/.harness/cli/data');+}+/// Where the socket of the daemon on [port] would be —/// `$ADAPTER_DATA_DIR/daemon-<port>.sock`, by default/// `~/.harness/cli/data/daemon-<port>.sock` — or null where there is none@@ -36,16 +45,32 @@ String? defaultDaemonSocketPath(bool? isWindows,}) {if (isWindows ?? Platform.isWindows) return null;- final env = environment ?? Platform.environment;- final home = env['HOME'];- final dataDir =- env['ADAPTER_DATA_DIR'] ??- (home == null || home.isEmpty ? null : '$home/.harness/cli/data');+ final dataDir = defaultDaemonDataDir(environment: environment);if (dataDir == null) return null;final path = '$dataDir/${daemonSocketName(port)}';return utf8.encode(path).length <= _maxSocketPathBytes ? path : null;}+/// The header a call to the daemon's loopback PORT carries its local+/// credential in (CLI `lib/localCredential.ts`).+const daemonCredentialHeader = 'X-Harness-Local';++/// The daemon's local credential: its `hook-credential` file, 0600 and this+/// user's, in [defaultDaemonDataDir]. The loopback port takes any OS user's+/// process — another account's harness running as its own user on this+/// computer included — so every call over the port shows it; the socket needs+/// none. Null where it cannot be read.+String? readDaemonCredential({Map<String, String>? environment}) {+ final dataDir = defaultDaemonDataDir(environment: environment);+ if (dataDir == null) return null;+ try {+ final value = File('$dataDir/hook-credential').readAsStringSync().trim();+ return RegExp(r'^[A-Za-z0-9_-]{43}$').hasMatch(value) ? value : null;+ } on FileSystemException {+ return null;+ }+}+/// An [HttpClient] whose every connection goes to the socket at [path],/// whatever host the URL names.HttpClient unixHttpClient(String path) => HttpClient()@@ -57,18 +82,32 @@ HttpClient unixHttpClient(String path) => HttpClient()/// Which way the app currently reaches the daemon. One instance is shared by/// discovery, REST and the local WebSocket so they agree.class LocalDaemonTransport {- LocalDaemonTransport({this.candidate});+ LocalDaemonTransport({this.candidate, this.credential});/// The transport to the daemon at [daemonBase] (the loopback address the app- /// would otherwise dial): the socket named for its port, except under- /// `flutter test`, where a real daemon's socket must never be reached.+ /// would otherwise dial): the socket named for its port, and the credential+ /// the port wants — except under `flutter test`, where a real daemon must+ /// never be reached.factory LocalDaemonTransport.detect(Uri daemonBase) => LocalDaemonTransport(candidate: kUnderTest ? null : defaultDaemonSocketPath(daemonBase.port),+ credential: kUnderTest ? null : readDaemonCredential,);/// Where the socket would be, or null when this app never uses one.final String? candidate;+ /// Reads the daemon's local credential, or null when this app never shows+ /// one (tests).+ final String? Function()? credential;++ /// What a call over the loopback PORT adds: the daemon's local credential,+ /// read each time so a daemon that made a new one is not refused. Empty when+ /// there is none to read.+ Map<String, String> tcpHeaders() {+ final value = credential?.call();+ return value == null ? const {} : {daemonCredentialHeader: value};+ }+String? _active;/// The socket to use now, or null for the loopback port. Set by discovery@@ -138,9 +177,13 @@ class LocalDaemonHttpAdapter implements HttpClientAdapter {uri.scheme == daemonBase.scheme &&uri.host == daemonBase.host &&uri.port == daemonBase.port;- if (path == null || !toDaemon) {+ // Over the port, the daemon wants its local credential.+ Future<ResponseBody> overPort() {+ if (toDaemon) options.headers.addAll(transport.tcpHeaders());return _tcp.fetch(options, requestStream, cancelFuture);}++ if (path == null || !toDaemon) return overPort();try {return await _unixFor(path).fetch(options, requestStream, cancelFuture);} catch (error) {@@ -148,7 +191,7 @@ class LocalDaemonHttpAdapter implements HttpClientAdapter {// Nothing was sent: the socket could not be opened. The port can still// serve this request, and discovery will find the socket again later.transport.useTcp();- return _tcp.fetch(options, requestStream, cancelFuture);+ return overPort();}}diff --git a/desktop/lib/ws/ws_conn.dart b/desktop/lib/ws/ws_conn.dartindex a8a6c36ec..577e2c6a9 100644--- a/desktop/lib/ws/ws_conn.dart+++ b/desktop/lib/ws/ws_conn.dart@@ -8,6 +8,7 @@ import 'package:web_socket_channel/io.dart';import 'package:web_socket_channel/web_socket_channel.dart';import '../core/sleep_aware.dart';+import '../core/test_run.dart';import '../logging/app_log.dart';import '../logging/redact.dart';import '../core/models.dart';@@ -247,6 +248,17 @@ class WsConn {}}+ /// The local WebSocket over the daemon's loopback port, showing its local+ /// credential: the port takes any OS user's process, the socket only ours.+ WebSocketChannel _connectLocalPort(Uri uri) {+ final transport =+ localTransport ??+ LocalDaemonTransport(+ credential: kUnderTest ? null : readDaemonCredential,+ );+ return IOWebSocketChannel.connect(uri, headers: transport.tcpHeaders());+ }+Future<void> connect() async {if (_closing || _connecting) return;_connecting = true;@@ -318,9 +330,8 @@ class WsConn {protocols: token == null || token.isEmpty ? null : [token],): socket != null- ? await _connectLocalSocket(uri, socket) ??- WebSocketChannel.connect(uri)- : WebSocketChannel.connect(uri);+ ? await _connectLocalSocket(uri, socket) ?? _connectLocalPort(uri)+ : _connectLocalPort(uri);if (_closing) {await channel.sink.close();return;diff --git a/desktop/test/local_daemon_transport_test.dart b/desktop/test/local_daemon_transport_test.dartindex 7cc0573e3..9b0d2a55d 100644--- a/desktop/test/local_daemon_transport_test.dart+++ b/desktop/test/local_daemon_transport_test.dart@@ -18,6 +18,7 @@ class _Daemon {_Daemon(this.server, this.name) {server.listen((request) async {hits.add(request.uri.path);+ credentials.add(request.headers.value(daemonCredentialHeader));if (WebSocketTransformer.isUpgradeRequest(request)) {final ws = await WebSocketTransformer.upgrade(request);ws.listen((data) {@@ -57,6 +58,7 @@ class _Daemon {final HttpServer server;final String name;final List<String> hits = [];+ final List<String?> credentials = [];int selects = 0;static Future<_Daemon> tcp() async =>@@ -133,6 +135,78 @@ void main() {});});+ group('local credential', () {+ final credential = 'A' * 42 + '_';++ test('is the hook-credential file in the daemon data directory', () {+ final env = {'ADAPTER_DATA_DIR': scratch.path};+ expect(readDaemonCredential(environment: env), isNull);+ File('${scratch.path}/hook-credential').writeAsStringSync('$credential\n');+ expect(readDaemonCredential(environment: env), credential);+ // Anything that is not a credential the CLI made is not sent.+ File('${scratch.path}/hook-credential').writeAsStringSync('short');+ expect(readDaemonCredential(environment: env), isNull);+ });++ test('is never read under flutter test', () {+ expect(+ LocalDaemonTransport.detect(Uri.parse('http://127.0.0.1:18473')).tcpHeaders(),+ isEmpty,+ );+ });++ test('goes with REST over the port, never down the socket', () async {+ final tcp = await start(_Daemon.tcp());+ final unix = await start(_Daemon.unix(socketPath));+ final transport = LocalDaemonTransport(+ candidate: socketPath,+ credential: () => credential,+ )..useSocket();+ final api = ApiClient(+ config: configFor(tcp),+ session: AuthSession(),+ localTransport: transport,+ );++ expect(await api.me(), {'via': 'unix'});+ expect(unix.credentials, [null]);++ await unix.close();+ daemons.remove(unix);+ if (File(socketPath).existsSync()) File(socketPath).deleteSync();+ expect(await api.me(), {'via': 'tcp'});+ expect(tcp.credentials.last, credential);+ });++ test('goes with the local WebSocket over the port', () async {+ final tcp = await start(_Daemon.tcp());+ final transport = LocalDaemonTransport(+ candidate: socketPath,+ credential: () => credential,+ )..useTcp();+ final conn = WsConn(+ wsBaseUrl: 'wss://unused.example',+ autonomousEnv: 'prod',+ machineId: 'm1',+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ transportKind: WsTransportKind.localPlaintext,+ localWsUri: Uri.parse('ws://127.0.0.1:${tcp.server.port}/api/local-ws'),+ localTransport: transport,+ );+ addTearDown(conn.close);+ await conn.connect();+ for (var i = 0; i < 100 && tcp.selects == 0; i++) {+ await Future<void>.delayed(const Duration(milliseconds: 10));+ }++ expect(tcp.selects, 1);+ expect(tcp.credentials, [credential]);+ });+ });+group('discovery', () {test('asks the socket first and keeps the port untouched', () async {final tcp = await start(_Daemon.tcp());diff --git a/desktop/test/machine_sharing_form_test.dart b/desktop/test/machine_sharing_form_test.dartindex c665a7b48..4fa75c41e 100644--- a/desktop/test/machine_sharing_form_test.dart+++ b/desktop/test/machine_sharing_form_test.dart@@ -7,6 +7,7 @@ import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/auth/auth_session.dart';import 'package:harness/core/config.dart';+import 'package:harness/core/guest_folders.dart';import 'package:harness/shared/theme/app_theme.dart' as grid;import 'package:harness/state/app_state.dart';import 'package:harness/widgets/desktop_chrome.dart';@@ -33,6 +34,41 @@ class _SharingApp extends AppNotifier {Map<String, dynamic>? refusal;final sets = <({List<String> emails, bool sameDomain})>[];+ /// Turning guest access on: how often it was asked, and what the admin prompt came to.+ int enables = 0;+ Map<String, dynamic>? enableRefusal;++ /// The folders guests may use, as the daemon keeps them; [folderRefusal] answers instead when set.+ final folderSets = <List<({String path, bool write})>>[];+ Map<String, dynamic>? folderRefusal;++ @override+ Future<Map<String, dynamic>> setMachineGuestFolders(+ String machineId,+ List<GuestFolder> folders,+ ) async {+ folderSets.add([+ for (final folder in folders) (path: folder.path, write: folder.write),+ ]);+ if (folderRefusal != null) return folderRefusal!;+ policy = {+ ...policy,+ 'folders': [+ for (final folder in folders)+ {'path': folder.path, 'write': folder.write},+ ],+ };+ return policy;+ }++ @override+ Future<Map<String, dynamic>> enableMachineGuests(String machineId) async {+ enables++;+ if (enableRefusal != null) return enableRefusal!;+ policy = {...policy, 'guestAccess': 'ready'};+ return {'ok': true, 'guestAccess': 'ready'};+ }+@overrideFuture<Map<String, dynamic>> machineSharing(String machineId) async =>unreadable ?? policy;@@ -251,6 +287,187 @@ void main() {},);+ testWidgets(+ 'says what a guest gets, and turns guest access on before the first share, behind one admin prompt',+ (tester) async {+ final app = _SharingApp()+ ..policy = {+ 'emails': <String>[],+ 'sameDomain': false,+ 'domain': 'autonomous.ai',+ 'members': <Map<String, dynamic>>[],+ 'guestAccess': 'missing',+ };+ await open(tester, app);+ // Guest is the only level (docs/plans/2026-10-19-guest-machine-sharing-plan.md).+ expect(find.textContaining('full access'), findsNothing);+ expect(+ find.textContaining(+ 'Guests get their own space on this machine and can use your Claude and ChatGPT plans.',+ ),+ findsOneWidget,+ );+ expect(+ find.textContaining(+ 'Sharing asks for an admin password on this machine once.',+ ),+ findsOneWidget,+ );++ // Cancelled at the prompt: nothing is shared, and the form says why.+ app.enableRefusal = {+ 'error': 'CANCELLED',+ 'message': 'Sharing was not turned on: the admin prompt was cancelled.',+ };+ await tester.tap(find.byKey(const ValueKey('machine-sharing:domain')));+ await tester.pumpAndSettle();+ expect(app.enables, 1);+ expect(app.sets, isEmpty);+ expect(+ find.text('Sharing was not turned on: the admin prompt was cancelled.'),+ findsOneWidget,+ );++ // Approved: guest access first, then the share; the next share asks nothing more.+ app.enableRefusal = null;+ await tester.tap(find.byKey(const ValueKey('machine-sharing:domain')));+ await tester.pumpAndSettle();+ expect(app.enables, 2);+ expect(app.sets.single.sameDomain, isTrue);+ expect(find.textContaining('admin password'), findsNothing);+ await tester.enterText(+ find.byKey(const ValueKey('machine-sharing-email')),+ '[email protected]',+ );+ await tester.pump();+ await tester.tap(find.byKey(const ValueKey('machine-sharing:add')));+ await tester.pumpAndSettle();+ expect(app.enables, 2);+ expect(app.sets.last.emails, ['[email protected]']);+ },+ );++ testWidgets(+ 'shares folders with guests, read only until the switch lets them edit, and says why one cannot be',+ (tester) async {+ final app = _SharingApp();+ final (closed, _) = await open(tester, app);+ expect(+ find.textContaining('They can read anything inside, secrets too.'),+ findsOneWidget,+ );+ final field = find.byKey(const ValueKey('machine-sharing-folder'));+ final add = find.byKey(const ValueKey('machine-sharing:folder-add'));++ // A path that is not a full one is named, and nothing is sent.+ await tester.enterText(field, 'code/app');+ await tester.pump();+ await tester.tap(add);+ await tester.pumpAndSettle();+ expect(+ find.text(+ 'Enter the folder’s full path on this machine, like /Users/you/project.',+ ),+ findsOneWidget,+ );+ expect(app.folderSets, isEmpty);++ // Shared read only.+ await tester.enterText(field, '/Users/dee/code/app/');+ await tester.pump();+ await tester.tap(add);+ await tester.pumpAndSettle();+ expect(app.folderSets.last, [+ (path: '/Users/dee/code/app', write: false),+ ]);+ expect(find.text('/Users/dee/code/app'), findsOneWidget);+ expect(find.text('Read only'), findsOneWidget);++ // Once is enough.+ await tester.enterText(field, '/Users/dee/code/app');+ await tester.pump();+ await tester.tap(add);+ await tester.pumpAndSettle();+ expect(+ find.text('Guests can already use /Users/dee/code/app.'),+ findsOneWidget,+ );+ expect(app.folderSets, hasLength(1));++ // The switch lets them edit it.+ await tester.tap(+ find.byKey(+ const ValueKey('machine-sharing:folder-write:/Users/dee/code/app'),+ ),+ );+ await tester.pumpAndSettle();+ expect(app.folderSets.last, [(path: '/Users/dee/code/app', write: true)]);+ expect(find.text('Guests can edit it'), findsOneWidget);++ // The machine refuses one that is not the owner's, in words, and nothing changes.+ app.folderRefusal = {+ 'error': 'BAD_REQUEST',+ 'message': 'Only your own folders can be shared: /Users/kim',+ };+ await tester.enterText(field, '/Users/kim');+ await tester.pump();+ await tester.tap(add);+ await tester.pumpAndSettle();+ expect(+ find.text('Only your own folders can be shared: /Users/kim'),+ findsOneWidget,+ );+ // Kept in the field to correct, never listed.+ expect(+ find.byKey(const ValueKey('machine-sharing-folder:/Users/kim')),+ findsNothing,+ );+ app.folderRefusal = null;++ // Taken back.+ await tester.tap(+ find.byKey(+ const ValueKey('machine-sharing:folder-remove:/Users/dee/code/app'),+ ),+ );+ await tester.pumpAndSettle();+ expect(app.folderSets.last, isEmpty);+ expect(find.text('/Users/dee/code/app'), findsNothing);+ await tester.tap(find.byKey(const ValueKey('machine-sharing:back')));+ await tester.pump();+ expect(closed(), 'Not shared.');+ },+ );++ testWidgets(+ 'shared already, it says when guests are stopped until guest access is on, and turns it on',+ (tester) async {+ final app = _SharingApp()+ ..policy = {+ 'emails': ['[email protected]'],+ 'sameDomain': false,+ 'domain': 'autonomous.ai',+ 'members': <Map<String, dynamic>>[],+ 'guestAccess': 'outdated',+ };+ await open(tester, app);+ expect(+ find.text(+ 'Guests cannot start harnesses until you turn guest access on again after the update.',+ ),+ findsOneWidget,+ );+ await tester.tap(find.byKey(const ValueKey('machine-sharing:guests-on')));+ await tester.pumpAndSettle();+ expect(app.enables, 1);+ expect(app.sets, isEmpty);+ expect(+ find.byKey(const ValueKey('machine-sharing:guests-on')),+ findsNothing,+ );+ },+ );+testWidgets('Back with nothing changed closes quietly; light appearance; the domain is not listed person by person',(tester) async {diff --git a/desktop/test/new_harness_guest_test.dart b/desktop/test/new_harness_guest_test.dartnew file mode 100644index 000000000..d706aa85d--- /dev/null+++ b/desktop/test/new_harness_guest_test.dart@@ -0,0 +1,293 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/core/config.dart';+import 'package:harness/core/engine_availability.dart';+import 'package:harness/core/guest_folders.dart';+import 'package:harness/core/models.dart';+import 'package:harness/core/project_folder.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/app_state.dart';+import 'package:harness/state/harness_placement.dart';+import 'package:harness/state/new_harness.dart';+import 'package:harness/state/pane_arrangement.dart';+import 'package:harness/state/retarget_refusal.dart';+import 'package:harness/widgets/new_harness_form.dart';++/// A machine another account shares with this one: this person is a guest there+/// (docs/plans/2026-10-19-guest-machine-sharing-plan.md). Its daemon starts Claude Code or Codex in+/// the guest's own space, on its owner's plans, and answers a guest nothing of the owner's.+class _GuestApp extends AppNotifier {+ _GuestApp()+ : super(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ ) {+ final state = MachineState(+ const Machine(+ machineId: 'dee',+ name: 'Dee’s Studio',+ authMode: MachineAuthMode.remote,+ machineShare: MachineShare(+ ownerName: 'Dee',+ ownerEmail: '[email protected]',+ via: 'email',+ added: true,+ ),+ ),+ )..nodeOnline = true;+ // What the owner has installed says nothing of the guest's own space.+ state.engines.replace(const [+ EngineAvailability(engine: 'claude', installed: false),+ EngineAvailability(engine: 'codex', installed: true),+ EngineAvailability(engine: 'opencode', installed: true),+ ]);+ machineStates['dee'] = state;+ }++ /// Everything asked of the machine that a guest would be refused.+ final refusedAsks = <String>[];++ /// Where the machine says this guest may start: its workspace, and the folders its owner shares.+ GuestFolders? places = const GuestFolders(+ workspace: '/Users/Shared/HarnessGuests/hg_0/work',+ );++ @override+ Future<GuestFolders?> guestFolders(String machineId) async => places;+ final launches = <Map<String, Object?>>[];++ @override+ Future<void> probeEngines(String machineId, {bool force = false}) async {}++ @override+ Future<void> probeDsh(+ String machineId, {+ bool force = false,+ bool userAction = false,+ }) async => refusedAsks.add('dsh_list');++ @override+ Future<Map<String, dynamic>> listRemoteFolder(+ String machineId,+ String? path,+ ) async {+ refusedAsks.add('fs_list_dir');+ return {'error': 'GUEST_NOT_ALLOWED'};+ }++ @override+ Future<String?> createAgent(+ String machineId, {+ required String engine,+ required String? folder,+ bool bypassPermission = false,+ String? permissionMode,+ String? codexHome,+ String? dsh,+ GridModel? model,+ String? prompt,+ String? name,+ String? agent,+ ProjectFolderRequest? projectFolder,+ String? swarmId,+ PaneSplitRequest? split,+ AgentCreationAttempt? attempt,+ HarnessPlacement? placement,+ }) async {+ launches.add({+ 'machine': machineId,+ 'engine': engine,+ 'folder': folder,+ 'projectFolder': projectFolder,+ 'dsh': dsh,+ 'model': model,+ 'codexHome': codexHome,+ 'prompt': prompt,+ });+ return null;+ }+}++void main() {+ test('a guest starts Claude Code or Codex in its own space: no project, harness, model or folder to choose', () async {+ final app = _GuestApp();+ addTearDown(app.dispose);+ final box = NewHarnessController(+ app,+ machineId: 'dee',+ engine: 'claude',+ folder: '/Users/dee/secret',+ task: 'Fix the tests',+ // Offered to the owner's own machines; never to a guest.+ offersStore: true,+ );+ addTearDown(box.dispose);+ await pumpEventQueue();++ expect(box.asGuest, isTrue);+ expect(box.compatibleEngines, ['claude', 'codex']);+ // Nothing shared: no Project to pick, the workspace.+ expect(box.fields, isNot(contains(NewHarnessField.projectMenu)));+ expect(box.projectLabel, 'My workspace');+ // The agent menu offers what a guest can start: Claude Code and Codex.+ box.focusField(NewHarnessField.harness);+ expect(box.options.map((option) => option.id), ['claude', 'codex']);+ box.focusField(NewHarnessField.launch);+ expect(box.fields, isNot(contains(NewHarnessField.model)));+ expect(box.needsProject, isFalse);+ // Claude Code is missing among the owner's engines: the guest's own installs on Create.+ expect(box.requiredChoice, isNull);+ // Nothing of the owner's is asked for: no harnesses from the Store, no folders.+ expect(app.refusedAsks, isEmpty);++ final outcome = await box.create();+ expect(box.error, isNull);+ expect(outcome, isNot(NewHarnessOutcome.failed));+ expect(app.launches.single, {+ 'machine': 'dee',+ 'engine': 'claude',+ // The daemon starts it in the guest's workspace: no folder of the owner's is named.+ 'folder': '',+ 'projectFolder': null,+ 'dsh': null,+ 'model': null,+ 'codexHome': null,+ 'prompt': 'Fix the tests',+ });+ });++ testWidgets(+ 'a guest\'s Codex shows no model or account to choose: it runs on the owner\'s subscription',+ (tester) async {+ final app = _GuestApp();+ addTearDown(app.dispose);+ final box = NewHarnessController(app, machineId: 'dee', engine: 'codex');+ addTearDown(box.dispose);+ await tester.pumpWidget(+ MaterialApp(+ theme: grid+ .buildAppTheme(brightness: Brightness.dark)+ .copyWith(platform: TargetPlatform.macOS),+ home: Scaffold(+ body: NewHarnessForm(+ controller: box,+ desktop: true,+ onClose: () {},+ onCreated: () => fail('A guest fixture starts nothing'),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();++ expect(box.engine, 'codex');+ expect(+ find.byKey(const ValueKey('new-harness-field-approvals')),+ findsOneWidget,+ );+ // Each opened an empty menu on a shared machine ("No matches").+ expect(+ find.byKey(const ValueKey('new-harness-field-model')),+ findsNothing,+ );+ expect(+ find.byKey(const ValueKey('new-harness-field-profile')),+ findsNothing,+ );+ },+ );++ test('a guest picks among the folders the owner shares, which the daemon starts it in', () async {+ final app = _GuestApp()+ ..places = const GuestFolders(+ workspace: '/Users/Shared/HarnessGuests/hg_0/work',+ folders: [+ GuestFolder(path: '/Users/dee/code/app', write: true),+ GuestFolder(path: '/Users/dee/docs', write: false),+ ],+ );+ addTearDown(app.dispose);+ final box = NewHarnessController(app, machineId: 'dee', engine: 'codex');+ addTearDown(box.dispose);+ await pumpEventQueue();+ expect(box.fields, contains(NewHarnessField.projectMenu));+ expect(box.projectLabel, 'My workspace');+ box.focusField(NewHarnessField.projectMenu);+ expect(box.options.map((option) => (option.title, option.detail)), [+ ('My workspace', 'Your own folder on Dee’s Studio'),+ ('app', '/Users/dee/code/app · you can edit it'),+ ('docs', '/Users/dee/docs · read only'),+ ]);+ box.accept(box.options[2]);+ expect(box.projectLabel, '/Users/dee/docs');+ final outcome = await box.create();+ expect(box.error, isNull);+ expect(outcome, isNot(NewHarnessOutcome.failed));+ expect(app.launches.single['folder'], '/Users/dee/docs');+ expect(app.launches.single['projectFolder'], isNull);+ expect(app.refusedAsks, isEmpty);+ });++ test(+ 'an agent a guest cannot start there gives way to Claude Code',+ () async {+ for (final (engine, harness) in [+ ('opencode', null),+ ('claude', 'autonomous/blender'),+ ]) {+ final app = _GuestApp();+ addTearDown(app.dispose);+ final box = NewHarnessController(+ app,+ machineId: 'dee',+ engine: engine,+ harnessId: harness,+ );+ addTearDown(box.dispose);+ await pumpEventQueue();+ expect(box.engine, 'claude', reason: '$engine $harness');+ // Codex there runs on the owner's subscription: no profile to choose.+ box.focusField(NewHarnessField.harness);+ box.accept(box.options.firstWhere((option) => option.id == 'codex'));+ expect(box.engine, 'codex');+ expect(box.usesProfile, isFalse);+ expect(box.hasProfile, isFalse);+ expect(box.fields, isNot(contains(NewHarnessField.profile)));+ expect(box.harnessId, isNull);+ expect(box.requiredChoice, isNull);+ }+ },+ );++ test('the app says in words what a guest cannot do to its harness', () {+ for (final code in ['GUEST_NOT_ALLOWED', 'GUEST_HARNESS']) {+ expect(+ retargetRefusalMessage(code, engineLabel: 'Claude Code'),+ 'A guest’s harness keeps the model it started with. Start a new one to use another.',+ );+ }+ });++ test('a guest\'s harness is never resumed, restarted, forked or moved to another agent', () async {+ final app = _GuestApp();+ addTearDown(app.dispose);+ app.machineStates['dee']!.agents.add(+ Agent.fromJson({+ 'id': 'mine',+ 'name': 'Mine',+ 'engine': 'claude',+ 'status': 'stopped',+ 'createdAt': '2026-10-19T00:00:00.000Z',+ }),+ );+ final resumed = await app.resumeAgent('dee', 'mine');+ expect(resumed.error, contains('Start a new one'));+ expect(resumed.retryable, isFalse);+ expect(+ await app.changeAgent('dee', 'mine', 'codex'),+ 'A guest’s harness keeps the agent it started with. Start a new one.',+ );+ });+}diff --git a/docs/plans/2026-10-19-guest-machine-sharing-plan.md b/docs/plans/2026-10-19-guest-machine-sharing-plan.mdnew file mode 100644index 000000000..47dac4ef7--- /dev/null+++ b/docs/plans/2026-10-19-guest-machine-sharing-plan.md@@ -0,0 +1,217 @@+# Guest machine sharing — plan++Replaces the "full owner rights" model of [2026-10-15-share-machine-plan.md](2026-10-15-share-machine-plan.md).+People were not comfortable sharing a whole machine. Decided with the owner on 2026-10-19:++- **Guest is the only level.** It applies to email and domain shares alike. There is no Full level.+ Existing (test) shares are cleaned up, not migrated.+- A guest's harnesses **run as a separate OS user**, one per guest, so they cannot read the+ owner's files, logins or other harnesses.+- **Guests can use the owner's Claude and ChatGPT subscriptions** through a relay in the+ owner's daemon. The owner's token never leaves the owner's account. Subscriptions first;+ saved API keys later.+- Out of scope: owner controls (per-person limits, approval, activity view, notifications).++⚠️ Personal plans (Claude Pro/Max, ChatGPT Plus/Pro) are single-user under the vendors' terms,+and the subscription endpoints are undocumented. The owner accepted both risks.++## What a guest can do++| Can | Cannot |+|---|---|+| Start harnesses in their own workspace on the machine (and later, in folders the owner shares) | See the owner's files, harnesses, terminals, transcripts, settings or devices |+| See, open, type into, stop and resume **their own** harnesses | Pair or unpair devices, change the remote password, share the machine |+| Use the owner's Claude/ChatGPT subscription for those harnesses | Read the owner's credentials or keys |+| Use the machine's CPU/GPU and local models | Reach the owner's daemon API or other machines through it |++## Today's gaps (from a code survey, 2026-10-19)++1. **A shared key is a full owner in the core.** It opens as role `web`, and+ `owner = local || role === 'web'` (`cli/src/backendSocket.ts:856`). No email reaches the core;+ the only trace is the paired-key label (`<machine> · <email>`, `services/sharedMachines.ts:91`).+2. **The gateway answers pairing management before the core** (`e2ee_pairings_list/unpair/unpair_all`,+ `gateway/gateway.ts:536`, `lib/e2ee/manager.ts:291-328`), with no shared check. A guest can unpair+ the owner's devices.+3. **Broadcasts reach guests.** Every session gets the machine's group key in its welcome+ (`manager.ts:894`), and the backend sends broadcasts to every `web` client (`backend/src/lib/hub.ts:80`).+4. **The loopback API has no credential.** HTTP on `127.0.0.1:<port>` has only a CSRF header+ (`hookServer.ts:441-446`). The local WS on TCP "deliberately has no credential"+ (`localWsServer.ts:283`), and a TCP client can even drive the owner's other machines+ (`localWsServer.ts:448`). Any local process — a guest OS user included — is the owner.+5. **Launches run as the owner** in the owner's tmux, from a 0600 launch script+ (`lib/engineLaunch.ts:508`), with grid and API keys in the environment (`lib/gridLaunch.ts`).+ Agents carry no record of who started them (`lib/registry.ts`).+6. **Engines live in the owner's home.** `~/.local/share/claude` and `~/.harness/runtime` are 700.+ The home itself is `drwxr-x---` group `staff`, so any user in `staff` can traverse it.++## Design++### Identity: who a session is+- `sharedTrust` passes each trusted key's **member email** (from the backend's `shareMembers`).+ `PairedClient` stores it as `sharedWith` in `paired.json`.+- The gateway reports `guest: <email>` on `core.client(connId, …)` for a shared key+ (`RemoteClient.guest`).+- The core treats a session as owner only if `local` (trusted socket or authenticated loopback),+ or `role === 'web'` and not a guest.++### Policy: what a guest may ask+A **default-deny allowlist**, checked once per frame in the core (`backendSocket.ts` dispatch) and+in the gateway for gateway-only types:+- **`agents_list`, `sessions_list`:** only agents whose `guest` is this email.+- **`agent_create`:** forced into the guest's workspace, run as the guest's OS user, on the+ owner's subscription or the guest's own login. No grid or saved-API keys.+- **Own agents only:** `agent_close`, `agent_delete`, `agent_resume`, `agent_restart`,+ `agent_retarget` (subscription only), `message`, `cancel`, `question_response`,+ `terminal_*` (JSON and binary).+- **Allowed:** `engines_probe` (the guest's engines), `usage_read` (the owner's plan limits,+ for the picker), `theme_set`.+- **`fs_list_dir`:** inside the guest's workspace only.+- **Everything else** is answered `GUEST_NOT_ALLOWED`. That covers pairing, devices, shared machines,+ settings, search, memory, connectors, store, models management, shell, handoff, orchestrator+ and cloud.+- **Gateway:** no pairing management, no `device_e2ee_pair`, no `phone_pair`, no `group_sync`+ for a guest.++### Broadcasts+- A guest's welcome carries **no group key** (a random throwaway key).+- The gateway delivers what concerns that guest's own agents (`agent_*`, `turn_*`,+ `node_status`, `agents_changed`) to the guest's connId, sealed with its session key+ (`sendTo`).+- Clients must accept a welcome whose group key never opens a broadcast.++### Loopback credential+- The daemon's existing 0600, uid-checked `hook-credential` (`lib/hookAuth.ts`) becomes the+ **local credential**:+ - TCP HTTP requires `X-Harness-Local: <credential>` (or `Authorization: Bearer`). Only+ `/api/status` and the hook routes keep their own checks.+ - The TCP local WS requires the credential in the upgrade.+ - The Unix socket stays credential-free (0600, owner-only).+- Every owner-side TCP client reads the file and sends it: CLI commands, engine hooks,+ companions, devices, orchestrator, `harness new`/`remote`, and the desktop's TCP fallback.+ hn and the service processes already use the socket.+- Guest harnesses get a **guest-scoped hook token** in their environment, valid only for+ `/api/hook/*` on their own agent.++### Running as the guest's OS user+- **Install (once, by the owner).** Turning sharing on installs+ `/usr/local/libexec/harness/guest-helper` (root-owned, 0755) and+ `/etc/sudoers.d/harness-guests`, which lets the owner's user run that helper without a+ password. On macOS this goes through one standard admin prompt (`osascript … with administrator+ privileges`); on Linux, `sudo` once. Guests are never prompted. An owner who is not an admin+ cannot share; the form says so.+- **Helper commands.** Each validates every argument: user names `hg_<hex>`, the group+ `harnessguest`, paths under `/Users/Shared/HarnessGuests` (Linux: `/home/harness-guests`).+ - `ensure <email>` creates the hidden user, its own primary group (not `staff`), a 0700 home+ and `<home>/work`.+ - `run <user> --cwd <dir> --env K=V… -- <argv>` runs `sudo -u <user> env -i …` with an+ allowlisted environment.+ - `install <user> <engine>` installs the engine into the guest's home, as the guest.+ - `remove <user>` deletes the user and its files when sharing with them ends.+- **The pane.** The guest's pane still lives in the owner's tmux. Its command is+ `sudo -n guest-helper run …`, so the engine process is the guest while the daemon keeps the pty.+- **The launch.** It is inline, with no sourced 0600 launch script and no owner `PATH`, `HOME`+ or keys. Engines come from the guest's home.+- **Hook script.** It is copied to `/usr/local/lib/harness/hook` at install time, so the guest's+ engine can report turns with its scoped token.++### Owner subscription relay+- **The server.** A loopback HTTP relay in the owner's daemon, with **per-guest bearer+ tokens** minted by the daemon. A token is revoked when sharing with that person ends.+- **Claude Code.** The guest's harness gets `ANTHROPIC_BASE_URL=http://127.0.0.1:<relay>/claude`+ and `ANTHROPIC_AUTH_TOKEN=<guest token>`. The relay swaps in the owner's OAuth bearer, adds+ `anthropic-beta: oauth-2025-04-20` and streams the response from `api.anthropic.com`.+- **Codex.** The guest's harness gets a provider `harness_owner`:+ `base_url=http://127.0.0.1:<relay>/codex`, `env_key=HARNESS_RELAY_TOKEN`, `wire_api=responses`.+ The relay forwards to the ChatGPT Codex backend with the owner's access token and+ `ChatGPT-Account-Id`.+- **Owner's tokens.** They are read the way `lib/accountUsage.ts` reads them (Keychain or+ `~/.claude`, `~/.codex/auth.json`). Refresh: when the access token has expired, the relay+ refreshes it and writes the result back where it came from, under a lock, so the owner's own+ engine keeps working.+- **Picker.** The guest's picker shows "Anthropic · <owner>'s subscription", from `usage_read`+ (already per machine).++### Clients+- **Desktop and hn, as a guest.** A shared machine says "Guest · shared by <owner>". It lists+ the guest's harnesses only (the daemon enforces this). New Harness opens in the guest+ workspace. Rename, share, remove and folder browsing outside the workspace are hidden.+- **Owner's Share form.** It explains Guest ("They get their own space on this computer and+ can use your Claude and ChatGPT plans. They cannot see your files or harnesses."). It runs the+ one-time install the first time sharing is turned on.++### Shared folders (phase 3)+- The owner picks folders, read-only or read-write.+- The helper grants the guest's user a macOS ACL (`chmod +a`) or a Linux ACL (`setfacl`).+- The guest's New Harness offers those folders beside the workspace.+- The form warns that anything inside a shared folder, secrets included, is readable.++## Phases+1. **Isolation.**+ - identity and policy;+ - gateway gating;+ - broadcasts;+ - loopback credential;+ - the guest helper with install, ensure, run and engine install;+ - guest launches;+ - client wording and guest view;+ - remove the Full wording, clean up test shares.+2. **Subscription relay.**+ - Claude, then Codex;+ - token refresh;+ - picker label.+3. **Shared folders.**++## Status (2026-10-19)++**All three phases are built** on `feat/guest-machine-sharing`. Where the build differs from the design above:++- **Where it lives.** Guest launches are part of the existing `sharedMachines` service in the edge host+ (`services/guestLaunches.ts`), not a new service. It already knows who the machine is shared with, so it+ revokes a guest's relay tokens on the read after sharing with them ends (`sync`). The core reaches it+ through the port `ports.sharedMachines.guestLaunch` (`core/sharedMachinesLink.ts`) and opens the pane itself+ (`core/agents/guestCreate.ts`), recording `guest` on the registry row.+- **No relaunch of a guest's harness.** Restart, resume, retarget, fork and the boot's restore all build an+ owner's launch, which would run the guest's harness as the owner. All of them refuse a row with `guest`+ (`GUEST_HARNESS_REFUSAL`), and the policy refuses them to a guest. The guest starts a new harness instead.+- **Engines: Claude Code and Codex only** (the two whose subscription the relay spends). Each is installed into+ the guest's home on first use, in the pane itself (`lib/guestPaneCommand.ts`), so the guest sees the+ install. A first message goes to the engine as its first prompt.+- **Turning guest access on** is the `shared_machines` action `enable_guests`. The Share form (desktop and+ hn) runs it before the first share, when `get` says `guestAccess` is not `ready`. When the machine is+ already shared and guest access is off (an update made the helper `outdated`), the form says so and offers+ Turn on.+- **Shared folders.** The owner lists folders, each read only or editable (`set_folders`, kept in+ `shared-machines.json`; the backend never hears of them). The helper's `share <user> [--read DIR]...+ [--write DIR]...` gives a guest exactly those folders: an ACL on each folder and everything in it, and+ search-only entries on the closed folders above it. It keeps a root-owned record of what it gave+ (`/var/db/harness-guests/<user>`), changes only what differs, and `run` may start in a shared folder.+ On each read of the sharing, every guest still named gets the folders and every other guest account+ loses them (`sync`). A guest asks `guest_folders` for its workspace and the folders; New Harness offers+ them (desktop and hn), and a harness starts in a shared folder only when the daemon finds it shared.+- **Loopback credential.** TCP HTTP and the TCP local WS require the 0600 credential (`lib/localCredential.ts`);+ the Unix socket does not. Every owner-side TCP client sends it.+- **Clients.** A shared machine reads "Guest · shared by <owner>". New Harness there offers only Claude Code+ and Codex, with no harness, model or profile; its Project is the guest's workspace or a shared folder, and+ it never browses the owner's folders or asks for Store harnesses. Restart, fork, share, model and agent+ switches are hidden or refused with a sentence.++**Known gaps:**+- **Turn status.** A guest's engine has no Harness hooks, so a guest harness's working/idle state is+ limited. The guest-scoped hook token is left at the `hookTokenMatches` seam (`lib/hookServer.ts`).+- **Relay restarts.** Relay tokens live in memory. If the edge host restarts, the relay starts on a new+ port, and a guest's running harness loses its subscription until the guest starts a new one.+- **Unverified upstreams.** The Codex upstream's headers have not been checked against a real ChatGPT+ sign-in, and Anthropic may refuse relayed OAuth requests. Codex keyring storage is not read.+- **A large first share.** Sharing a folder sets an entry on everything in it, which can take minutes+ for a folder with `node_modules`. The read of the sharing waits for it.+- **Verified only by hand.** The real admin prompt, `dscl` and the sudo `env_keep` need the owner's Mac.+++## Testing+- **CLI unit tests:** the policy allowlist, per-agent ownership, gateway gating, broadcast+ filtering, the loopback credential on every route, the helper's argument validation+ (helper commands run through an injected runner), and the relay (against a fake upstream).+- **Two-account e2e** (`cli/e2e/sharedMachines.e2e.ts`): a guest lists only its agents, is refused+ pairing and settings, and cannot read broadcasts.+- **Manual, owner's Mac.** The admin prompt and the real OS user are checked by hand: the+ owner approves the one-time prompt. Automated tests never create OS users.diff --git a/tui/src/app.rs b/tui/src/app.rsindex 71c2b7ec9..f6580924e 100644--- a/tui/src/app.rs+++ b/tui/src/app.rs@@ -619,6 +619,9 @@ pub struct App {/// Each machine's last measured round trip (the live roster request), for `@`.pub rtt: HashMap<String, Duration>,pub homes: HashMap<String, String>,+ /// On a machine shared with this account, the folders its owner shares with guests (path, editable),+ /// as it last said (`guest_folders`); the guest's workspace stands as its home in [homes].+ pub guest_folders: HashMap<String, Vec<(String, bool)>>,last_focus_sent: Option<(String, String)>,/// The mouse event of the key whose commands are running (tmux's item event): `-t =`, the/// commands' target, send-keys -M and the mouse_* formats read it.@@ -1105,6 +1108,7 @@ impl App {shell_context: crate::shell_context::State::load(),rtt: HashMap::new(),homes: HashMap::new(),+ guest_folders: HashMap::new(),last_focus_sent: None,mouse_ev: None,mouse_state: Default::default(),@@ -1508,8 +1512,12 @@ impl App {if machine_id == self.fleet.local_id && !crate::local::is_local(&machine_id) { self.daemon_down = false; crate::dial::reconnected(self) }self.relist(&machine_id);self.push_theme();- // Its home folder, so its paths read `~/…` like this machine's do.- if !self.homes.contains_key(&machine_id) {+ // A guest there has no home of the owner's to read: its workspace stands for it, beside the+ // folders the owner shares (docs/plans/2026-10-19-guest-machine-sharing-plan.md).+ if self.fleet.shares.contains_key(&machine_id) {+ crate::input::load_guest_folders(self, machine_id.clone());+ } else if !self.homes.contains_key(&machine_id) {+ // Its home folder, so its paths read `~/…` like this machine's do.if let Some(link) = self.link(&machine_id) {let id = machine_id.clone();let generation = link.generation;diff --git a/tui/src/devices.rs b/tui/src/devices.rsindex aa64cc31d..bcce87d32 100644--- a/tui/src/devices.rs+++ b/tui/src/devices.rs@@ -42,7 +42,8 @@ pub const INSTALL: &str = "curl -fsSL https://cdn.autonomous.ai/harness/cli/instpub const LOGIN: &str = "harness login";pub const START: &str = "harness start && harness remote-password set";/// What sharing this computer gives (machine_sharing_form.dart's intro).-const SHARE_ACCESS: &str = "People you share it with get full access: they can run harnesses, open terminals and read files on it.";+/// What a guest gets (docs/plans/2026-10-19-guest-machine-sharing-plan.md): Guest is the only level.+const SHARE_ACCESS: &str = "Guests get their own space here and can use your Claude and ChatGPT plans. They cannot see your files or harnesses.";/// Where the Add Phone QR points (add_phone_dialog.dart `phonePairLink`): the phone parses exactly/// this, so the TUI's code is the app's, byte for byte.@@ -131,6 +132,8 @@ pub enum Entry {Rename { machine: String, name: String },/// An address to share this computer with (services/sharedMachines.ts).ShareEmail,+ /// A folder of this computer's for guests to open in their harnesses; [write]: they may change it.+ ShareFolder { write: bool },}/// What a yes does.@@ -149,6 +152,8 @@ pub enum Act {Share { emails: Vec<String>, same_domain: bool, said: String },/// A machine shared with this account's domain added to its machines (an older backend lists one to add).AddShared { machine: String, name: String },+ /// The folders guests may open here, each read only or editable (`set_folders`); [said] as for Share.+ ShareFolders { folders: Vec<(String, bool)>, said: String },}/// The panel is asking, in a dialog over it: a line to type (a password shown as dots; the caret@@ -271,7 +276,9 @@ pub fn ask(app: &mut App, req: Req, line: Option<fn(&mut App, &str)>, then: implReq::Rpc { ty, payload } => {let here = app.fleet.local_id.clone();let Some(link) = app.link(&here) else { return then(app, Reply::Rpc(Err(("DAEMON_DOWN".into(), "Harness is not running on this computer.".into())))) };- app.spawn(async move { Reply::Rpc(link.rpc(ty, payload, Duration::from_secs(30)).await.map_err(|e| (e.code, e.detail))) }, then)+ // Turning guest access on waits on the person at this computer's admin prompt, which gives up after ten minutes.+ let wait = Duration::from_secs(if payload.get("action").and_then(Value::as_str) == Some("enable_guests") { 660 } else { 30 });+ app.spawn(async move { Reply::Rpc(link.rpc(ty, payload, wait).await.map_err(|e| (e.code, e.detail))) }, then)}Req::Copy(text) => { crate::clipboard::store(&text); then(app, Reply::Done) }Req::Wait(d) => app.spawn(async move { tokio::time::sleep(d).await; Reply::Done }, then),@@ -803,6 +810,22 @@ fn run_act(app: &mut App, act: Act) {});}Act::Share { emails, same_domain, said } => {+ // The first share turns guest access on: each guest runs as their own account here, which takes one+ // admin prompt on this computer. A CLI from before guests says nothing of it, and is not asked.+ let access = app.devices.sharing.as_ref().and_then(|s| s.as_ref().ok()).and_then(|v| v.get("guestAccess")).and_then(Value::as_str).map(str::to_string);+ if (!emails.is_empty() || same_domain) && access.as_deref().is_some_and(|a| a != "ready") {+ note(app, "Approve the prompt on this computer: it lets each guest run as their own account.");+ ask(app, Req::Rpc { ty: "shared_machines", payload: json!({ "action": "enable_guests" }) }, None, move |app, reply| {+ match shared_answer(reply) {+ Ok(v) => {+ if let Some(Ok(sharing)) = app.devices.sharing.as_mut() { sharing["guestAccess"] = v.get("guestAccess").cloned().unwrap_or(json!("ready")) }+ run_act(app, Act::Share { emails, same_domain, said })+ }+ Err(message) => { fail(app, message); again(app) }+ }+ });+ return;+ }note(app, "Saving…");let payload = json!({ "action": "set", "emails": emails, "sameDomain": same_domain });ask(app, Req::Rpc { ty: "shared_machines", payload }, None, move |app, reply| {@@ -813,6 +836,17 @@ fn run_act(app: &mut App, act: Act) {again(app);});}+ Act::ShareFolders { folders, said } => {+ note(app, "Saving…");+ let folders: Vec<Value> = folders.into_iter().map(|(path, write)| json!({ "path": path, "write": write })).collect();+ ask(app, Req::Rpc { ty: "shared_machines", payload: json!({ "action": "set_folders", "folders": folders }) }, None, move |app, reply| {+ match shared_answer(reply) {+ Ok(v) => { app.devices.sharing = Some(Ok(v)); note(app, said) }+ Err(message) => fail(app, message),+ }+ again(app);+ });+ }// Only an older backend lists a team's machine to add first; a machine shared with you, by email// or with your domain, is never taken off your list (owner, 2026-10-16).Act::AddShared { machine, name } => {@@ -986,9 +1020,22 @@ fn submit(app: &mut App, what: Entry, value: String) {if new.is_empty() { return note(app, "Already shared with them") }emails.extend(new.iter().cloned());let here = app.fleet.local_machine_name();- confirm(app, format!("Share {here} with {}? They use it as their own: its harnesses, terminals and files.", new.join(", ")),+ confirm(app, format!("Share {here} with {}? They get their own space, as guests, and use your Claude and ChatGPT plans.", new.join(", ")),Act::Share { emails, same_domain, said: format!("Shared with {}", new.join(", ")) });}+ Entry::ShareFolder { write } => {+ let typed = value.trim();+ let path = if typed.len() > 1 { typed.trim_end_matches('/') } else { typed }.to_string();+ if path.is_empty() { return note(app, "Nothing changed") }+ let label = if write { "Folder guests can edit" } else { "Folder guests can read" };+ if !path.starts_with('/') { entry(app, Entry::ShareFolder { write }, label, &value, false); return fail(app, "Enter the folder's full path, like /Users/you/project") }+ let mut folders = sharing_folders(app);+ if folders.iter().any(|(p, _)| *p == path) { return note(app, format!("Guests can already use {path}")) }+ folders.push((path.clone(), write));+ let what = if write { "read and change" } else { "read" };+ confirm(app, format!("Let guests {what} {path}? They can read anything in it, secrets too."),+ Act::ShareFolders { folders, said: format!("Guests can use {path}") });+ }Entry::Rename { machine, name } => {let new = value.trim().to_string();if new.is_empty() { entry(app, Entry::Rename { machine, name: name.clone() }, "Machine name", &name, false); return fail(app, "Name cannot be empty") }@@ -1221,7 +1268,7 @@ fn share_action(app: &mut App, rest: &str) {if same_domain {run_act(app, Act::Share { emails, same_domain: false, said: format!("No longer shared with everyone at @{domain}") })} else {- confirm(app, format!("Share {here} with everyone at @{domain}? They use it as their own: its harnesses, terminals and files."),+ confirm(app, format!("Share {here} with everyone at @{domain}? They get their own space, as guests, and use your Claude and ChatGPT plans."),Act::Share { emails, same_domain: true, said: format!("Shared with everyone at @{domain}") })}}@@ -1229,10 +1276,40 @@ fn share_action(app: &mut App, rest: &str) {let rest: Vec<String> = emails.into_iter().filter(|e| e != email).collect();confirm(app, format!("Stop sharing {here} with {email}?"), Act::Share { emails: rest, same_domain, said: format!("No longer shared with {email}") })}+ ("guests-on", _) => {+ note(app, "Approve the prompt on this computer: it lets each guest run as their own account.");+ ask(app, Req::Rpc { ty: "shared_machines", payload: json!({ "action": "enable_guests" }) }, None, move |app, reply| {+ match shared_answer(reply) {+ Ok(v) => {+ if let Some(Ok(sharing)) = app.devices.sharing.as_mut() { sharing["guestAccess"] = v.get("guestAccess").cloned().unwrap_or(json!("ready")) }+ note(app, "Guest access is on")+ }+ Err(message) => fail(app, message),+ }+ again(app);+ });+ }+ ("folder-read", _) => entry(app, Entry::ShareFolder { write: false }, "Folder guests can read", "", false),+ ("folder-write", _) => entry(app, Entry::ShareFolder { write: true }, "Folder guests can edit", "", false),+ ("folder", path) => {+ let rest: Vec<(String, bool)> = sharing_folders(app).into_iter().filter(|(p, _)| p != path).collect();+ confirm(app, format!("Stop sharing {path} with guests?"), Act::ShareFolders { folders: rest, said: format!("Guests can no longer use {path}") })+ }_ => {}}}+/// Whether guests may start harnesses here (`ready`), or what turning it on takes; None from a CLI before guests.+fn guest_access(app: &App) -> Option<String> {+ app.devices.sharing.as_ref().and_then(|s| s.as_ref().ok()).and_then(|v| v.get("guestAccess")).and_then(Value::as_str).map(str::to_string)+}++/// The folders guests may open here, as this computer last said: (path, whether they may change it).+fn sharing_folders(app: &App) -> Vec<(String, bool)> {+ app.devices.sharing.as_ref().and_then(|s| s.as_ref().ok()).and_then(|v| v.get("folders")).and_then(Value::as_array).into_iter().flatten()+ .filter_map(|f| Some((f.get("path")?.as_str()?.to_string(), f.get("write") == Some(&Value::Bool(true))))).collect()+}+/// Whether [text] is an address the backend takes (zod's `email()`, by hand: this regex has no/// lookahead): one it would refuse is refused as it is typed, by name, never as a failed save.fn is_email(text: &str) -> bool {@@ -1378,7 +1455,7 @@ fn machines_rows(app: &App) -> Vec<Row> {_ => "…".into(),};rows.push(Row::new("share:", "Share this computer…").group(here).extra("share sharing people team domain").lead(dot("⇆", theme::TEAL))- .detail(vec![span("with people you choose; they use it as their own", fg(theme::MUTED))]).right(state));+ .detail(vec![span("with people you choose, as guests", fg(theme::MUTED))]).right(state));}let yours = "Your machines";@@ -1397,7 +1474,7 @@ fn machines_rows(app: &App) -> Vec<Row> {let (glyph, color, word) = reach(app, m);let rtt = app.rtt.get(&m.id).filter(|_| m.usable()).map(|d| format!("{}ms ", d.as_millis())).unwrap_or_default();rows.push(Row::new(format!("m:{}", m.id), m.name.clone()).group(with_you).extra(format!("{} {} {}", m.id, share.owner, share.email)).lead(dot(glyph, color))- .detail(vec![span(format!("shared by {} · ", share.owner), fg(theme::MUTED)), span(word, fg(color))]).right(format!("{rtt}{}", counts(app, &m.id))));+ .detail(vec![span(format!("guest · shared by {} · ", share.owner), fg(theme::MUTED)), span(word, fg(color))]).right(format!("{rtt}{}", counts(app, &m.id))));}// Shared with this account's domain: Enter adds one.let team = "Shared with your team";@@ -1456,7 +1533,7 @@ fn action_rows(app: &App, id: &str) -> Vec<Row> {/// This computer's sharing: everyone at its domain, the addresses, and who uses it now.fn share_rows(app: &App) -> Vec<Row> {let here = format!("Share {}", app.fleet.local_machine_name());- let mut rows = vec![info("share-what", "People you share it with get full access.", &here)];+ let mut rows = vec![info("share-what", "Guests get their own space here.", &here)];let Some((emails, same_domain, domain)) = sharing_now(app) else {match &app.devices.sharing {Some(Err(message)) => {@@ -1467,9 +1544,15 @@ fn share_rows(app: &App) -> Vec<Row> {}return rows;};+ // Shared already, but guests start nothing until guest access is on (again, after an update).+ let access = guest_access(app);+ if (!emails.is_empty() || same_domain) && access.as_deref().is_some_and(|a| a != "ready") {+ rows.push(Row::new("shr:guests-on", "Turn guest access on…").group(here.clone()).extra("guest access admin").lead(dot("!", theme::WARN))+ .detail(vec![span(if access.as_deref() == Some("outdated") { "again, after the update" } else { "guests cannot start harnesses yet" }, fg(theme::MUTED))]));+ }if let Some(domain) = &domain {rows.push(Row::new("shr:domain", format!("Everyone at @{domain}")).group(here.clone()).extra("domain team company").lead(dot(if same_domain { "✓" } else { "·" }, if same_domain { theme::ONLINE } else { theme::MUTED }))- .detail(vec![span("they use it as their own", fg(theme::MUTED))]).right(if same_domain { "on" } else { "off" }));+ .detail(vec![span("as guests", fg(theme::MUTED))]).right(if same_domain { "on" } else { "off" }));}rows.push(Row::new("shr:add", "Add an email…").group(here.clone()).extra("add email person").lead(dot("+", theme::TEAL)).detail(vec![span("they see it in their Machines", fg(theme::MUTED))]));for email in &emails {@@ -1477,6 +1560,14 @@ fn share_rows(app: &App) -> Vec<Row> {}let using = using_by_email(app);if !using.is_empty() { rows.push(info("share-using", format!("Using it now: {}", using.join(", ")), &here)) }+ // The folders guests may open in their harnesses (docs/plans/2026-10-19-guest-machine-sharing-plan.md).+ let folders = "Folders guests can open";+ rows.push(Row::new("shr:folder-read", "Share a folder (read only)…").group(folders).extra("folder share read").lead(dot("+", theme::TEAL)));+ rows.push(Row::new("shr:folder-write", "Share a folder guests can edit…").group(folders).extra("folder share edit write").lead(dot("+", theme::TEAL)));+ for (path, write) in sharing_folders(app) {+ rows.push(Row::new(format!("shr:folder:{path}"), path.clone()).group(folders).extra("folder remove").lead(dot("·", theme::MUTED))+ .right(if write { "can edit" } else { "read only" }));+ }rows}@@ -1589,7 +1680,7 @@ pub fn preview(app: &App, view: View, id: &str) -> Vec<Line<'static>> {"addshared" => {let Some((_, name, share)) = app.fleet.to_add.iter().find(|(id, ..)| id == rest) else { return vec![] };let mut out = vec![bold(name.clone()).into(), Line::raw(""), kv("shared by", owner_of(share)), Line::raw(""),- Line::raw(format!("{} shared it with everyone at your company. Added, it is one of your machines: its harnesses, terminals and files.", share.owner))];+ Line::raw(format!("{} shared it with everyone at your company. Added, you get your own space on it and use their Claude and ChatGPT plans.", share.owner))];out.extend(enter_does("adds it to your machines"));out}@@ -1672,13 +1763,13 @@ fn share_preview(app: &App, rest: &str) -> Vec<Line<'static>> {("domain", _) => {let Some(d) = domain else { return vec![] };let mut out = vec![bold(format!("Everyone at @{d}")).into(), Line::raw(""),- Line::raw(format!("Anyone with an @{d} address can use it as their own: its harnesses, terminals and files.")), Line::raw(""),+ Line::raw(format!("Anyone with an @{d} address can use it as a guest: their own space, on your Claude and ChatGPT plans.")), Line::raw(""),kv("now", if same_domain { "on" } else { "off" })];out.extend(enter_does(if same_domain { format!("stops sharing with everyone at @{d}; people you added by email keep it") } else { "asks y/n, then shares it with them".into() }));out}("add", _) => {- let mut out = vec![bold("Add people").into(), Line::raw(""), Line::raw("They see it in their Machines and use it as their own: its harnesses, terminals and files."),+ let mut out = vec![bold("Add people").into(), Line::raw(""), Line::raw("They see it in their Machines and use it as guests: their own space, on your Claude and ChatGPT plans."),Line::raw(""), dim("Several at once: separate the addresses with commas or spaces.").into()];out.extend(enter_does("asks for their email addresses, then y/n"));out@@ -1689,6 +1780,26 @@ fn share_preview(app: &App, rest: &str) -> Vec<Line<'static>> {out.extend(enter_does("asks y/n, then stops sharing with them — they lose access at once"));out}+ ("guests-on", _) => {+ let mut out = vec![bold("Turn guest access on").into(), Line::raw(""),+ Line::raw("Each guest's harnesses run as their own account on this computer, so they cannot see your files. That takes one admin password here.")];+ out.extend(enter_does("shows this computer's admin prompt"));+ out+ }+ ("folder-read" | "folder-write", _) => {+ let write = rest == "folder-write";+ let mut out = vec![bold(if write { "Share a folder guests can edit" } else { "Share a folder" }).into(), Line::raw(""),+ Line::raw(if write { "Guests' harnesses can open it, and read and change what is in it." } else { "Guests' harnesses can open it and read what is in it." }),+ Line::raw(""), Line::styled("They can read anything inside, secrets too.", fg(theme::WARN))];+ out.extend(enter_does("asks for the folder's full path, then y/n"));+ out+ }+ ("folder", path) => {+ let write = sharing_folders(app).iter().any(|(p, w)| p == path && *w);+ let mut out = vec![bold(path.to_string()).into(), Line::raw(""), kv("guests", if write { "can read and change it" } else { "can read it" })];+ out.extend(enter_does("asks y/n, then stops sharing it with guests"));+ out+ }_ => vec![],}}@@ -1823,7 +1934,8 @@ fn ask_title(app: &App, ask: &Ask) -> String {Ask::Confirm { act: Act::Remove { name, .. }, .. } => format!("Remove from Account · {name}"),Ask::Confirm { act: Act::Unpair { name, .. }, .. } => format!("Remove Access · {name}"),Ask::Confirm { act: Act::ArmPhone, .. } => "Add Your Phone".into(),- Ask::Entry { what: Entry::ShareEmail, .. } | Ask::Confirm { act: Act::Share { .. }, .. } => format!("Share · {}", app.fleet.local_machine_name()),+ Ask::Entry { what: Entry::ShareEmail | Entry::ShareFolder { .. }, .. } | Ask::Confirm { act: Act::Share { .. } | Act::ShareFolders { .. }, .. } =>+ format!("Share · {}", app.fleet.local_machine_name()),Ask::Confirm { act: Act::AddShared { name, .. }, .. } => format!("Add to My Machines · {name}"),}}@@ -1835,7 +1947,7 @@ fn action(ask: &Ask, room: u16) -> &'static str {Ask::Confirm { .. } => return "Yes",Ask::Entry { what: Entry::Link { .. }, .. } => "Connect",Ask::Entry { what: Entry::Rename { .. }, .. } => "Save",- Ask::Entry { what: Entry::ShareEmail, .. } => "Add",+ Ask::Entry { what: Entry::ShareEmail | Entry::ShareFolder { .. }, .. } => "Add",Ask::Entry { .. } => "Continue",};if "[ Cancel ] [ ]".width() + word.width() > room as usize { "Next" } else { word }@@ -2079,11 +2191,38 @@ mod tests {p["sameDomain"] = payload["sameDomain"].clone();p.clone()}+ Some("set_folders") => {+ let mut p = policy.lock().unwrap();+ p["folders"] = payload["folders"].clone();+ p.clone()+ }_ => json!({ "ok": true }),})))}));log}+ /// Guest access off at first: the first share turns it on behind this computer's admin prompt, unless the+ /// person cancels it there ([cancel]).+ fn guest_world(app: &mut App, cancel: bool) -> Arc<Mutex<Vec<Req>>> {+ guest_world_from(app, cancel, json!({ "emails": [], "sameDomain": false, "domain": "acme.io", "members": [], "guestAccess": "missing" }))+ }+ fn guest_world_from(app: &mut App, cancel: bool, policy: Value) -> Arc<Mutex<Vec<Req>>> {+ let log = Arc::new(Mutex::new(Vec::new()));+ let seen = log.clone();+ let policy = Arc::new(Mutex::new(policy));+ app.devices.runner = Some(Box::new(move |req: &Req| {+ seen.lock().unwrap().push(req.clone());+ let Req::Rpc { ty: "shared_machines", payload } = req else { return world(req) };+ let mut p = policy.lock().unwrap();+ Some(Reply::Rpc(Ok(match payload["action"].as_str() {+ Some("enable_guests") if cancel => json!({ "error": "CANCELLED", "message": "Sharing was not turned on: the admin prompt was cancelled." }),+ Some("enable_guests") => { p["guestAccess"] = json!("ready"); json!({ "ok": true, "guestAccess": "ready" }) }+ Some("set") => { p["emails"] = payload["emails"].clone(); p["sameDomain"] = payload["sameDomain"].clone(); p.clone() }+ _ => p.clone(),+ })))+ }));+ log+ }fn rpc(action: &str, rest: Value) -> Req {let mut payload = json!({ "action": action });for (k, v) in rest.as_object().unwrap() { payload[k] = v.clone() }@@ -2138,14 +2277,14 @@ mod tests {assert_eq!(row_of(&app, "share:").map(|r| r.right.clone()), Some("off".into()));go_to(&mut app, "share:");press(&mut app, KeyCode::Enter);- assert_eq!(ids(&app)[1..], ["shr:domain", "shr:add"]);+ assert_eq!(ids(&app)[1..], ["shr:domain", "shr:add", "shr:folder-read", "shr:folder-write"]);go_to(&mut app, "shr:domain");press(&mut app, KeyCode::Enter);assert!(app.devices.ask.is_some(), "everyone at the domain is asked first");// They use it straight away, as people named by email do: nothing to add first.assert!(matches!(&app.devices.ask, Some(Ask::Confirm { question, .. })- if question.ends_with("with everyone at @acme.io? They use it as their own: its harnesses, terminals and files.")), "{:?}", app.devices.ask);+ if question.ends_with("with everyone at @acme.io? They get their own space, as guests, and use your Claude and ChatGPT plans.")), "{:?}", app.devices.ask);press(&mut app, KeyCode::Char('Y'));assert!(has(&log, &rpc("set", json!({ "emails": [], "sameDomain": true }))));assert_eq!(row_of(&app, "shr:domain").map(|r| r.right.clone()), Some("on".into()));@@ -2177,6 +2316,115 @@ mod tests {assert_eq!(match &app.modal { Some(Modal::Picker { picker, .. }) => picker.current_id(), _ => None }.as_deref(), Some("share:"));}+ #[test]+ fn the_first_share_turns_guest_access_on_behind_this_computers_admin_prompt_and_a_cancel_shares_nothing() {+ let mut cancelled = app((150, 42));+ let log = guest_world(&mut cancelled, true);+ open(&mut cancelled, View::Machines);+ go_to(&mut cancelled, "share:");+ press(&mut cancelled, KeyCode::Enter);+ go_to(&mut cancelled, "shr:domain");+ press(&mut cancelled, KeyCode::Enter);+ press(&mut cancelled, KeyCode::Char('Y'));+ assert!(has(&log, &rpc("enable_guests", json!({}))));+ assert!(!log.lock().unwrap().iter().any(|r| matches!(r, Req::Rpc { payload, .. } if payload["action"] == "set")), "nothing shared without it");+ assert!(cancelled.devices.footer.as_ref().is_some_and(|(t, err, _)| *err && t.contains("admin prompt was cancelled")));++ let mut app = app((150, 42));+ let log = guest_world(&mut app, false);+ open(&mut app, View::Machines);+ go_to(&mut app, "share:");+ press(&mut app, KeyCode::Enter);+ go_to(&mut app, "shr:domain");+ press(&mut app, KeyCode::Enter);+ press(&mut app, KeyCode::Char('Y'));+ let asked: Vec<String> = log.lock().unwrap().iter().filter_map(|r| match r { Req::Rpc { payload, .. } => payload["action"].as_str().map(str::to_string), _ => None }).collect();+ assert_eq!(asked.iter().filter(|a| *a != "get").cloned().collect::<Vec<_>>(), ["enable_guests", "set"]);+ assert_eq!(row_of(&app, "shr:domain").map(|r| r.right.clone()), Some("on".into()));+ // On now: the next share asks nothing more of the person.+ go_to(&mut app, "shr:add");+ press(&mut app, KeyCode::Enter);+ typed(&mut app, "[email protected]");+ press(&mut app, KeyCode::Enter);+ press(&mut app, KeyCode::Char('Y'));+ assert_eq!(log.lock().unwrap().iter().filter(|r| matches!(r, Req::Rpc { payload, .. } if payload["action"] == "enable_guests")).count(), 1);+ assert!(has(&log, &rpc("set", json!({ "emails": ["[email protected]"], "sameDomain": true }))));+ }++ #[test]+ fn shared_already_it_says_guests_wait_on_guest_access_and_turns_it_on() {+ // Not shared yet: nothing to say.+ let mut app = app((150, 42));+ guest_world(&mut app, false);+ open(&mut app, View::Machines);+ go_to(&mut app, "share:");+ press(&mut app, KeyCode::Enter);+ assert!(row_of(&app, "shr:guests-on").is_none());++ let mut app = self::app((150, 42));+ let log = guest_world_from(&mut app, false, json!({ "emails": ["[email protected]"], "sameDomain": false, "domain": "acme.io", "members": [], "guestAccess": "outdated" }));+ open(&mut app, View::Machines);+ go_to(&mut app, "share:");+ press(&mut app, KeyCode::Enter);+ assert!(row_of(&app, "shr:guests-on").is_some_and(|r| r.detail.iter().any(|s| s.content.contains("after the update"))));+ go_to(&mut app, "shr:guests-on");+ press(&mut app, KeyCode::Enter);+ assert!(has(&log, &rpc("enable_guests", json!({}))));+ assert!(app.devices.footer.as_ref().is_some_and(|(t, err, _)| !err && t == "Guest access is on"));+ assert!(row_of(&app, "shr:guests-on").is_none());+ }++ #[test]+ fn folders_are_shared_with_guests_read_only_or_editable_each_after_a_yes_and_taken_back_the_same_way() {+ let mut app = app((150, 42));+ let log = sharing_world(&mut app);+ open(&mut app, View::Machines);+ go_to(&mut app, "share:");+ press(&mut app, KeyCode::Enter);++ // A path that is not a full one is refused, by name, and nothing is sent.+ go_to(&mut app, "shr:folder-read");+ press(&mut app, KeyCode::Enter);+ typed(&mut app, "code/app");+ press(&mut app, KeyCode::Enter);+ assert!(app.devices.footer.as_ref().is_some_and(|(t, err, _)| *err && t.contains("full path")));+ press(&mut app, KeyCode::Esc);++ go_to(&mut app, "shr:folder-read");+ press(&mut app, KeyCode::Enter);+ typed(&mut app, "/Users/dee/docs/");+ press(&mut app, KeyCode::Enter);+ assert!(matches!(&app.devices.ask, Some(Ask::Confirm { question, .. }) if question.contains("secrets too")), "{:?}", app.devices.ask);+ press(&mut app, KeyCode::Char('Y'));+ assert!(has(&log, &rpc("set_folders", json!({ "folders": [{ "path": "/Users/dee/docs", "write": false }] }))));+ assert_eq!(row_of(&app, "shr:folder:/Users/dee/docs").map(|r| r.right.clone()), Some("read only".into()));++ go_to(&mut app, "shr:folder-write");+ press(&mut app, KeyCode::Enter);+ typed(&mut app, "/Users/dee/code/app");+ press(&mut app, KeyCode::Enter);+ press(&mut app, KeyCode::Char('Y'));+ assert!(has(&log, &rpc("set_folders", json!({ "folders": [{ "path": "/Users/dee/docs", "write": false }, { "path": "/Users/dee/code/app", "write": true }] }))));+ assert_eq!(row_of(&app, "shr:folder:/Users/dee/code/app").map(|r| r.right.clone()), Some("can edit".into()));++ // Once is enough.+ go_to(&mut app, "shr:folder-read");+ press(&mut app, KeyCode::Enter);+ typed(&mut app, "/Users/dee/docs");+ press(&mut app, KeyCode::Enter);+ assert!(app.devices.footer.as_ref().is_some_and(|(t, err, _)| !err && t.contains("already")));++ // Taken back after a yes.+ go_to(&mut app, "shr:folder:/Users/dee/docs");+ press(&mut app, KeyCode::Enter);+ press(&mut app, KeyCode::Char('Y'));+ assert!(has(&log, &rpc("set_folders", json!({ "folders": [{ "path": "/Users/dee/code/app", "write": true }] }))));+ assert!(row_of(&app, "shr:folder:/Users/dee/docs").is_none());+ let text = |id: &str| preview(&app, View::Machines, id).iter().map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect::<String>()).collect::<Vec<_>>().join("\n");+ assert!(text("shr:folder-write").contains("secrets too"));+ assert!(text("shr:folder:/Users/dee/code/app").contains("can read and change it"));+ }+// Seen 2026-10-16: the list is about fifty columns, so the sharing rows were cut short, and// the side beside them, where a row says the rest, was empty.#[test]@@ -2197,11 +2445,11 @@ mod tests {assert!(text("account").starts_with("Signed in as [email protected]."), "{}", text("account"));let share = text("share:");- for said in ["get full access", "everyone at @acme.io · on", "[email protected]", "[email protected]", "using it [email protected]"] { assert!(share.contains(said), "{said}: {share}") }+ for said in ["Guests get their own space", "everyone at @acme.io · on", "[email protected]", "[email protected]", "using it [email protected]"] { assert!(share.contains(said), "{said}: {share}") }// Everyone at the domain may use it, and is the domain row: nobody at it is named one by one.assert!(!share.contains("[email protected]"), "{share}");let domain = text("shr:domain");- assert!(domain.contains("Anyone with an @acme.io address can use it as their own: its harnesses, terminals and files."), "{domain}");+ assert!(domain.contains("Anyone with an @acme.io address can use it as a guest: their own space, on your Claude and ChatGPT plans."), "{domain}");assert!(!domain.contains("[email protected]") && !domain.contains("add it from"), "{domain}");assert!(domain.contains("people you added by email keep it"));assert!(text("shr:rm:[email protected]").contains("using it") && text("shr:rm:[email protected]").contains("invited · not using it yet"));@@ -2215,7 +2463,7 @@ mod tests {go_to(&mut app, "share:");press(&mut app, KeyCode::Enter);assert!(row_of(&app, "share-what").is_some_and(|r| r.label.chars().count() <= 44));- assert!(row_of(&app, "shr:domain").is_some_and(|r| r.detail.iter().any(|s| s.content == "they use it as their own")));+ assert!(row_of(&app, "shr:domain").is_some_and(|r| r.detail.iter().any(|s| s.content == "as guests")));assert_eq!(row_of(&app, "share-using").map(|r| r.label.as_str()), Some("Using it now: [email protected]"));}diff --git a/tui/src/input.rs b/tui/src/input.rsindex d6725115a..6c75ff465 100644--- a/tui/src/input.rs+++ b/tui/src/input.rs@@ -1261,7 +1261,24 @@ fn agent_rpc_on(app: &mut App, machine: String, agent: String, ty: &'static str,/// The Store's catalog from [machine]. [user_action]: a person opened the Store, the one read that/// counts toward its reach; a refresh after an install or a form's own read is automatic.+/// Where a guest may start on a machine shared with this account: its workspace (kept as that machine's+/// home) and the folders the owner shares (`guest_folders`).+pub(crate) fn load_guest_folders(app: &mut App, machine: String) {+ let Some(link) = app.link(&machine) else { return };+ let generation = link.generation;+ app.spawn(async move { link.rpc("guest_folders", json!({}), Duration::from_secs(20)).await }, move |app, reply| {+ if app.connection_generation(&machine) != Some(generation) { return }+ let Ok(reply) = reply else { return };+ if let Some(workspace) = reply.get("workspace").and_then(Value::as_str).filter(|w| w.starts_with('/')) { app.homes.insert(machine.clone(), workspace.to_string()); }+ let folders = reply.get("folders").and_then(Value::as_array).into_iter().flatten()+ .filter_map(|f| Some((f.get("path")?.as_str().filter(|p| p.starts_with('/'))?.to_string(), f.get("write") == Some(&Value::Bool(true))))).collect();+ app.guest_folders.insert(machine, folders);+ });+}+pub(crate) fn load_dsh(app: &mut App, machine: String, user_action: bool) {+ // A guest is listed no harnesses or folders of the owner's there (load_guest_folders says where it may start).+ if app.fleet.shares.contains_key(&machine) { return }let Some(link) = app.link(&machine) else { return };let id = machine.clone();let mark = loading(format!("dsh {machine}"), true);diff --git a/tui/src/new_harness.rs b/tui/src/new_harness.rsindex 3ff6e0890..2de64804c 100644--- a/tui/src/new_harness.rs+++ b/tui/src/new_harness.rs@@ -675,6 +675,11 @@ fn resolve_launch_machine(app: &mut App, form: &mut Form) {}}fn agent_rows(app: &App, machine: &str) -> Vec<Row> {+ // A guest on a machine shared with this account starts Claude Code or Codex there, on its owner's plans, in+ // a space of its own: nothing from the Store, no other engine (docs/plans/2026-10-19-guest-machine-sharing-plan.md).+ if app.fleet.shares.contains_key(machine) {+ return modal::new_what_rows(&[]).into_iter().filter(|r| matches!(r.id.as_str(), "engine:claude" | "engine:codex")).collect();+ }modal::new_what_rows(app.dsh.get(machine).map(Vec::as_slice).unwrap_or(&[]))}fn compatible_rows(app: &App, machine: &str, dsh: &str) -> Vec<Row> {@@ -697,6 +702,20 @@ fn compatible_rows(app: &App, machine: &str, dsh: &str) -> Vec<Row> {}fn project_rows(app: &App, draft: &Draft, show_machine: bool) -> Vec<Row> {const PER_MACHINE: usize = 50;+ // A guest on a machine shared with this account starts in its workspace or a folder the owner shares, and+ // browses, makes or clones nothing of the owner's (docs/plans/2026-10-19-guest-machine-sharing-plan.md).+ let chosen = app.fleet.launch_machine_id(&draft.machine);+ if app.fleet.shares.contains_key(chosen) {+ let mut rows = vec![];+ if let Some(workspace) = app.homes.get(chosen) {+ rows.push(Row::new(format!("home:{chosen}\t{workspace}"), "My workspace").extra("home workspace").group("Yours"));+ }+ for (path, write) in app.guest_folders.get(chosen).into_iter().flatten() {+ rows.push(Row::new(format!("at:{chosen}\t{path}"), path.clone()).extra("shared folder").group("Shared with you")+ .right(if *write { "you can edit it" } else { "read only" }));+ }+ return rows;+ }let mut rows = vec![];if draft.what.engine != "terminal" {rows.push(Row::new("clone", "Clone Repository"));@@ -707,7 +726,6 @@ fn project_rows(app: &App, draft: &Draft, show_machine: bool) -> Vec<Row> {}// The chosen machine's home first, as the composer offers "this folder": a machine whose recent// agents all ran in scratch folders otherwise offered nothing else.- let chosen = app.fleet.launch_machine_id(&draft.machine);if let Some(home) = app.homes.get(chosen).filter(|h| h.starts_with('/')) {let label = if show_machine { format!("~ @ {}", machine_label(app, chosen)) } else { "~".into() };// (Its own id, not a recent project's "at:": chosen the same way, never counted among them.)@@ -775,7 +793,8 @@ fn sync_git(app: &mut App, form: &mut Form, force: bool) {} else {None};- if form.draft.what.engine == "terminal" || form.local_only || path.is_none() {+ // (A guest reads no Git of the owner's: a shared folder is opened as it is.)+ if form.draft.what.engine == "terminal" || form.local_only || path.is_none() || app.fleet.shares.contains_key(&form.draft.machine) {form.git = Value::Null;form.git_key = None;form.git_loading = false;@@ -2001,6 +2020,38 @@ mod tests {assert_eq!(rows.iter().map(|row| row.id.as_str()).collect::<Vec<_>>(), vec!["engine:codex"]);}+ #[test]+ fn a_guest_starts_in_its_workspace_or_a_folder_the_owner_shares_and_browses_nothing_of_the_owners() {+ let mut app = app();+ app.fleet.shares.insert("dee".into(), crate::fleet::MachineShare { owner: "Dee".into(), email: "[email protected]".into(), team: false });+ app.homes.insert("dee".into(), "/Users/Shared/HarnessGuests/hg_0/work".into());+ app.guest_folders.insert("dee".into(), vec![("/Users/dee/code/app".into(), true), ("/Users/dee/docs".into(), false)]);+ let draft = |machine: &str| Draft {+ machine: machine.into(), what: saved_agent(&Value::Null), project: Project::New(String::new()), task: String::new(),+ permission: "auto".into(), worktree: None, branch: None, new_branch: None, model: None, profile: None,+ };+ let rows = project_rows(&app, &draft("dee"), false);+ assert_eq!(rows.iter().map(|r| (r.id.as_str(), r.label.as_str(), r.right.as_str())).collect::<Vec<_>>(), [+ ("home:dee\t/Users/Shared/HarnessGuests/hg_0/work", "My workspace", ""),+ ("at:dee\t/Users/dee/code/app", "/Users/dee/code/app", "you can edit it"),+ ("at:dee\t/Users/dee/docs", "/Users/dee/docs", "read only"),+ ]);+ // This account's own machine still opens, makes and clones folders.+ let own = project_rows(&app, &draft("local"), false);+ assert!(own.iter().any(|r| r.id == "folder"));+ }++ #[test]+ fn a_guest_starts_claude_code_or_codex_on_a_machine_shared_with_it_and_nothing_from_its_store() {+ let mut app = app();+ app.dsh.insert("dee".into(), vec![json!({"id":"example/blender", "engine":"codex", "name":"Blender"})]);+ app.fleet.shares.insert("dee".into(), crate::fleet::MachineShare { owner: "Dee".into(), email: "[email protected]".into(), team: false });+ let ids = |rows: Vec<Row>| rows.into_iter().map(|row| row.id).collect::<Vec<_>>();+ assert_eq!(ids(agent_rows(&app, "dee")), ["engine:claude", "engine:codex"]);+ // This account's own machines still offer every engine.+ assert!(agent_rows(&app, "local").len() > 2);+ }+fn app() -> App {let (sink, _) = tokio::sync::mpsc::unbounded_channel();let mut app = App::new(19789, sink, (150, 42));