diff --git a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts index 833d12b1214..1835974ee9d 100644 --- a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts +++ b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts @@ -3,9 +3,9 @@ import type { BuildInputs, GoldenImageManifest } from './golden-image' export const MANIFEST: GoldenImageManifest = {"imageVersion":"2026-11-09.1","image":"vercel/sandbox/node:24","region":"iad1","vcpus":4,"orcad":{"bundleUrl":null,"sha256":null},"gh":{"version":"2.103.3","sha256":"4c806978ffce1cec70853302a56d70ac6da4f19bae7adca4e1a8ab00633dd91d"},"chrome":{"version":"157.0.8103.38-1","sha256":"a62b277dc03da2cff50cc04589deb66f6875be339c066d46adb49b49eedb629d"},"agentCliPackages":["@anthropic-ai/claude-code@2.1.319","@openai/codex@0.166.0","opencode-ai@1.19.5","@google/gemini-cli@0.67.0","@github/copilot@1.0.108"],"cursorAgent":{"version":"2026.11.05-86047df","sha256":"170b77786cbf4c93064d64fff12b71a178b968730561c64afc2e8e752535442e"},"desktop":{"novnc":{"version":"1.6.0","sha256":"5066103959ef4e9b10f37e5a148627360dd8414e4cf8a7db92bdbd022e728aaa"},"websockify":{"version":"0.13.0","sha256":"b6413e364efd04f3c92ec8c17747e3c4adc20157c2ef1c5d019a26d944a46df8"}}} export const PROVISION_SCRIPT: string = "#!/usr/bin/env bash\n# Runs once inside the build sandbox (as the sandbox user, with sudo). Installs the pinned orcad\n# bundle, agent CLIs and Orca's VM entry points into /opt/orca, then smoke-tests orcad.\n# Inputs (env, from image/golden-image.manifest.json via build-golden-image.ts):\n# ORCAD_BUNDLE_URL ORCAD_BUNDLE_SHA256 [GH_VERSION GH_SHA256] [CHROME_VERSION CHROME_SHA256]\n# AGENT_NPM_PACKAGES (space-separated\n# name@version), [CURSOR_AGENT_VERSION CURSOR_AGENT_SHA256], [NOVNC_VERSION NOVNC_SHA256 WEBSOCKIFY_VERSION WEBSOCKIFY_SHA256] and ORCA_VM_SCRIPT_ (base64) for each /opt/orca/bin entry point.\n# [ORCA_VM_SCRIPTS_STAMP] (VM_SCRIPTS_STAMP of those scripts; written to /opt/orca/bin/.scripts-stamp).\nset -euo pipefail\nORCA_HOME=/opt/orca\nlog() { printf '[golden] %s\\n' \"$*\" >&2; }\n\nsudo mkdir -p \"$ORCA_HOME/bin\" \"$ORCA_HOME/runtime\" \"$ORCA_HOME/tools\"\nsudo chown -R \"$(id -u):$(id -g)\" \"$ORCA_HOME\"\n\nlog 'system packages'\nif command -v apt-get >/dev/null; then\n # Transient mirror errors and dpkg lock contention made apt exit 100 (2 of ~10 golden builds):\n # retry downloads and wait for the lock instead of failing the build.\n printf 'Acquire::Retries \"5\";\\nDPkg::Lock::Timeout \"180\";\\n' | sudo tee /etc/apt/apt.conf.d/80-orca-retries >/dev/null\n # Sandbox egress is TLS-only: plain-http apt mirrors time out at runtime (W2, wake on SSH).\n sudo sed -i 's#http://#https://#g' /etc/apt/sources.list.d/*.sources /etc/apt/sources.list 2>/dev/null || true\n sudo DEBIAN_FRONTEND=noninteractive apt-get update -qq\n # Developer basics agents expect (Conductor parity): rg, tmux, vim, git-lfs alongside the build tools.\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \\\n ca-certificates curl git git-lfs jq ripgrep tmux vim-nox less openssh-client openssh-server build-essential python3 \\\n unzip zip util-linux procps >/dev/null\n git lfs install --system --skip-repo >/dev/null\n # sshd is started on demand by the wake-on-SSH bridge (key-only, loopback); never at boot.\n sudo systemctl disable ssh.service ssh.socket >/dev/null 2>&1 || true\n # A locked password field (\"!\") makes sshd refuse even key logins; '*' = no password, not locked.\n sudo usermod -p '*' \"$(id -un)\"\nelif command -v dnf >/dev/null; then\n sudo dnf install -y -q ca-certificates curl-minimal git git-lfs jq tmux vim-enhanced gcc gcc-c++ make python3 \\\n unzip util-linux procps-ng >/dev/null\nelse\n log 'no supported package manager'; exit 1\nfi\n\n# Managed images have no /vercel/sandbox; the project lives at /vercel/sandbox/project on every image.\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" /vercel/sandbox\n\nfetch_verified() { # url sha256 dest\n curl -fsSL --retry 3 -o \"$3\" \"$1\"\n echo \"$2 $3\" | sha256sum -c --quiet -\n}\n\nlog 'orcad bundle'\nbundle=\"$(mktemp -d)/orcad.tgz\"\nfetch_verified \"$ORCAD_BUNDLE_URL\" \"$ORCAD_BUNDLE_SHA256\" \"$bundle\"\ntar -xzf \"$bundle\" -C \"$ORCA_HOME/runtime\"\nrm -rf \"$(dirname \"$bundle\")\"\n# Release tarballs (orca-server-linux-*) may nest the server; normalize to runtime/orcad + runtime/runtimes.\nif [ ! -s \"$ORCA_HOME/runtime/orcad/orcad-server.js\" ]; then\n server=\"$(find \"$ORCA_HOME/runtime\" -name orcad-server.js -type f | head -n 1)\"\n [ -n \"$server\" ] || { log 'bundle has no orcad-server.js'; exit 1; }\n root=\"$(dirname \"$(dirname \"$server\")\")\"\n # Move the tree up rather than linking to it: every VM script finds node with\n # `find .../runtime/runtimes -type f`, and find doesn't descend into a symlinked start point\n # (a linked release bundle left the build with no node). orcad's ../runtimes still resolves.\n for entry in \"$root\"/*; do mv \"$entry\" \"$ORCA_HOME/runtime/\"; done\n rmdir \"$root\"\nfi\ntest -s \"$ORCA_HOME/runtime/orcad/orcad-server.js\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ntest -x \"$node\"\n\nif [ -n \"${GH_VERSION:-}\" ]; then\n log \"gh $GH_VERSION\"\n fetch_verified \"https://github.com/cli/cli/releases/download/v${GH_VERSION}/gh_${GH_VERSION}_linux_amd64.tar.gz\" \\\n \"$GH_SHA256\" /tmp/gh.tgz\n tar -xzf /tmp/gh.tgz -C /tmp\n # The real gh lives off PATH; tools/bin/gh (first on agent PATHs) is the GH-AS-MEMBER wrapper (bin/gh).\n mkdir -p \"$ORCA_HOME/tools/bin\" \"$ORCA_HOME/tools/gh/bin\"\n install -m 0755 \"/tmp/gh_${GH_VERSION}_linux_amd64/bin/gh\" \"$ORCA_HOME/tools/gh/bin/gh\"\n ln -sfn ../../bin/gh \"$ORCA_HOME/tools/bin/gh\"\n rm -rf /tmp/gh.tgz \"/tmp/gh_${GH_VERSION}_linux_amd64\"\nfi\n\nif [ -n \"${CHROME_VERSION:-}\" ] && command -v apt-get >/dev/null; then\n log \"google-chrome $CHROME_VERSION (headless browser for agents and Orca browser automation)\"\n deb=\"$(mktemp -d)/chrome.deb\"\n fetch_verified \"https://dl.google.com/linux/chrome/deb/pool/main/g/google-chrome-stable/google-chrome-stable_${CHROME_VERSION}_amd64.deb\" \\\n \"$CHROME_SHA256\" \"$deb\"\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \"$deb\" >/dev/null\n rm -rf \"$(dirname \"$deb\")\"\n # The .deb adds Google's apt source; the image stays pinned, so drop it.\n sudo rm -f /etc/apt/sources.list.d/google-chrome.list /etc/cron.daily/google-chrome\n google-chrome --headless=new --no-sandbox --disable-gpu --dump-dom 'data:text/html,

ok

' 2>/dev/null | grep -q '

ok

'\nfi\n\nlog 'agent CLIs'\n# The image's system npm installs them; agents later run on whatever node orcad puts on PATH.\n# shellcheck disable=SC2086 # word splitting is the package list\nnpm install --global --no-fund --no-audit --prefix \"$ORCA_HOME/tools\" $AGENT_NPM_PACKAGES\n# opencode-ai installs every linux-x64 build variant (~205 MB each) and hardlinks the one its\n# postinstall picked into bin/opencode.exe, a standalone binary: drop the variants it did not pick.\nopencode_pkg=\"$ORCA_HOME/tools/lib/node_modules/opencode-ai\"\nif [ -x \"$opencode_pkg/bin/opencode.exe\" ]; then\n picked=\"$(stat -c %i \"$opencode_pkg/bin/opencode.exe\")\"\n for variant in \"$opencode_pkg\"/node_modules/opencode-*; do\n [ -d \"$variant\" ] || continue\n [ \"$(stat -c %i \"$variant/bin/opencode\" 2>/dev/null)\" = \"$picked\" ] || rm -rf \"$variant\"\n done\n \"$opencode_pkg/bin/opencode.exe\" --version >/dev/null\n # OpenCode installs @opencode-ai/plugin (its own version) into ~/.config/opencode on every start\n # until that dir has node_modules and a lock listing it, and draws nothing until that install ends\n # once a plugin is configured (Orca's is): with a slow or unreachable registry the first launch\n # sat blank ~85 s (n73). Install it here once; orca-sandbox-start copies it into a fresh home.\n oc_seed=\"$ORCA_HOME/opencode-config-seed\"\n mkdir -p \"$oc_seed\"\n printf '{\\n \"dependencies\": {\\n \"@opencode-ai/plugin\": \"%s\"\\n }\\n}\\n' \\\n \"$(\"$opencode_pkg/bin/opencode.exe\" --version)\" >\"$oc_seed/package.json\"\n (cd \"$oc_seed\" && npm install --no-fund --no-audit --ignore-scripts >/dev/null)\n test -s \"$oc_seed/package-lock.json\" && test -d \"$oc_seed/node_modules/@opencode-ai/plugin\"\nfi\n\n# Copilot CLI prefers GH_TOKEN/GITHUB_TOKEN over the user's own /login. In Orca Cloud those hold the\n# workspace's GitHub App placeholder, which Copilot can't use (\"Resource not accessible by\n# integration\"), so a signed-in user could never get past it. The wrapper drops them for Copilot\n# only (COPILOT_GITHUB_TOKEN, a /login and BYOK still work), unless BYOK is set up, which needs no\n# GitHub sign-in and keeps them so `gh` in Copilot's shell still works.\ncopilot_loader=\"$ORCA_HOME/tools/lib/node_modules/@github/copilot/npm-loader.js\"\nif [ -f \"$copilot_loader\" ]; then\n rm -f \"$ORCA_HOME/tools/bin/copilot\"\n cat >\"$ORCA_HOME/tools/bin/copilot\" </dev/null; fi\ndone\n\nif [ -n \"${CURSOR_AGENT_VERSION:-}\" ]; then\n # Cursor's agent CLI is a pinned tarball (its own node + bundle), not an npm package. The image\n # copy lives under /opt/orca (root-owned) and its release channel is set to \"static\" at boot\n # (orca-sandbox-env), so it never replaces itself mid-session.\n log \"cursor-agent $CURSOR_AGENT_VERSION\"\n tgz=\"$(mktemp -d)/cursor-agent.tgz\"\n fetch_verified \"https://downloads.cursor.com/lab/${CURSOR_AGENT_VERSION}/linux/x64/agent-cli-package.tar.gz\" \\\n \"$CURSOR_AGENT_SHA256\" \"$tgz\"\n rm -rf \"$ORCA_HOME/tools/cursor-agent\"\n mkdir -p \"$ORCA_HOME/tools/cursor-agent\" \"$ORCA_HOME/tools/bin\"\n tar --strip-components=1 -xzf \"$tgz\" -C \"$ORCA_HOME/tools/cursor-agent\"\n rm -rf \"$(dirname \"$tgz\")\"\n ln -sfn ../cursor-agent/cursor-agent \"$ORCA_HOME/tools/bin/cursor-agent\"\n \"$ORCA_HOME/tools/bin/cursor-agent\" --version >/dev/null\nfi\n\nlog 'openssh server (binaries only)'\n# For `orca ssh`: an unprivileged sshd on loopback (see vm/orca-sshd). Only the server binaries,\n# kept out of /usr: the packages would pull in systemd units, SELinux policy (~38 MB on AL2023) and\n# system host keys a user-run sshd never uses. Its libraries are already in the base image, except\n# tcp-wrappers on Ubuntu.\nmkdir -p \"$ORCA_HOME/openssh\"\npkgs=\"$(mktemp -d)\"\nif command -v dnf >/dev/null; then\n sudo dnf install -y -q --setopt=install_weak_deps=False cpio >/dev/null\n sudo dnf install -y -q --downloadonly --downloaddir=\"$pkgs\" openssh-server >/dev/null\n (cd \"$pkgs\" && rpm2cpio openssh-server-[0-9]*.rpm | cpio -idm --quiet)\n sudo dnf clean all -q >/dev/null 2>&1 || true\n libexec=\"$pkgs/usr/libexec/openssh\"\nelse\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends libwrap0 >/dev/null\n (cd \"$pkgs\" && apt-get download -qq openssh-server openssh-sftp-server >/dev/null)\n for deb in \"$pkgs\"/*.deb; do dpkg-deb -x \"$deb\" \"$pkgs\"; done\n libexec=\"$pkgs/usr/lib/openssh\"\nfi\ninstall -m 0755 \"$pkgs/usr/sbin/sshd\" \"$libexec/sshd-session\" \"$libexec/sftp-server\" \"$ORCA_HOME/openssh/\"\n# OpenSSH 10 splits authentication into its own binary.\nif [ -x \"$libexec/sshd-auth\" ]; then install -m 0755 \"$libexec/sshd-auth\" \"$ORCA_HOME/openssh/\"; fi\nsudo rm -rf \"$pkgs\"\n\"$ORCA_HOME/openssh/sshd\" -V 2>&1 | head -n 1 >&2 || true\n# sshd refuses a locked account ('!') even for key logins; '*' unlocks it with no usable password.\nsudo usermod -p '*' \"$(id -un)\"\n\ninstall_desktop() {\n # Remote desktop (~80 MB): Xvnc + openbox + xterm from the distro, noVNC + websockify pinned\n # tarballs. Only orca-desktop-start runs it, on demand; nothing starts at boot. Every step says\n # `|| return 1`: errexit does not apply inside an `if` condition.\n command -v apt-get >/dev/null || { log 'remote desktop: apt only'; return 1; }\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \\\n tigervnc-standalone-server tigervnc-tools openbox xterm x11-xserver-utils >/dev/null || return 1\n local tmp dir=\"$ORCA_HOME/desktop\"\n tmp=\"$(mktemp -d)\" || return 1\n fetch_verified \"https://github.com/novnc/noVNC/archive/refs/tags/v${NOVNC_VERSION}.tar.gz\" \\\n \"$NOVNC_SHA256\" \"$tmp/novnc.tgz\" || return 1\n fetch_verified \"https://github.com/novnc/websockify/archive/refs/tags/v${WEBSOCKIFY_VERSION}.tar.gz\" \\\n \"$WEBSOCKIFY_SHA256\" \"$tmp/websockify.tgz\" || return 1\n rm -rf \"$dir\" && mkdir -p \"$dir/novnc\" \"$dir/websockify\" || return 1\n tar -xzf \"$tmp/novnc.tgz\" -C \"$dir/novnc\" --strip-components 1 || return 1\n tar -xzf \"$tmp/websockify.tgz\" -C \"$dir/websockify\" --strip-components 1 || return 1\n # Orca tab fit: title \"Remote desktop\" (Xvnc's -desktop name), no noVNC favicon, control bar on\n # the right (away from Orca's sidebar edge); a stale per-boot password ends the session with one\n # plain message instead of a reconnect loop. \"Unencrypted\" is noVNC's view of plain ws:// to\n # localhost; the hop to the sandbox rides the end-to-end encrypted runtime connection.\n sed -i -e 's/document.title = e.detail.name + \" - \" + PAGE_TITLE;/document.title = e.detail.name;/' \\\n -e \"s/WebUtil.readSetting('controlbar_pos') === 'right'/WebUtil.readSetting('controlbar_pos', 'right') === 'right'/\" \\\n -e 's/securityFailed(e) {/securityFailed(e) { UI.inhibitReconnect = true; UI.showStatus(\"This remote desktop session ended. Reopen it from the workspace menu.\", \"error\"); return;/' \\\n -e 's/_(\"Connected (unencrypted) to \")/_(\"Connected to \")/' \\\n \"$dir/novnc/app/ui.js\" || return 1\n sed -i '/rel=\"icon\"/d; /rel=\"apple-touch-icon\"/d' \"$dir/novnc/vnc.html\" || return 1\n rm -rf \"$tmp\"\n PYTHONPATH=\"$dir/websockify\" python3 -P -c 'import websockify' >/dev/null || return 1\n command -v Xvnc >/dev/null && test -s \"$dir/novnc/vnc.html\"\n}\ndesktop=false\nif [ -n \"${NOVNC_VERSION:-}\" ]; then\n log 'remote desktop'\n # Optional: a failure leaves an image without the desktop, never a failed build.\n if install_desktop; then\n desktop=true\n else\n log 'remote desktop install failed; continuing without it'\n rm -rf \"$ORCA_HOME/desktop\"\n fi\nfi\n\nlog 'Orca entry points'\nfor name in orca-sandbox-start orca-sandbox-drain orca-memguard orca-sandbox-env orca-session-env.sh orca-env orca-egress-probe orca-image-wipe orca-agent-signout orca-share-proxy orca-sshd orca-ssh-keys orca-desktop-start orca-desktop-proxy orca-desktop-page.js orca-sandbox-grant orca-sandbox-revoke orca-sandbox-members orca-sandbox-read-snapshot orca-read-snapshot.cjs orca-git-as orca-git-identity orcad-boot git gh docker; do\n var=\"ORCA_VM_SCRIPT_${name//[-.]/_}\"\n printf '%s' \"${!var}\" | base64 -d >\"$ORCA_HOME/bin/$name\"\n chmod 0755 \"$ORCA_HOME/bin/$name\"\ndone\n# Which entry points this image carries (VM_SCRIPTS_STAMP): a Worker with older scripts never\n# reinstalls over them. Absent (old callers) reads as 0, so any Worker may still update the image.\nrm -f \"$ORCA_HOME/bin/.scripts-stamp\" \"$ORCA_HOME\"/bin/.entry-points-*\nif [[ \"${ORCA_VM_SCRIPTS_STAMP:-}\" =~ ^[0-9]+$ ]]; then\n printf '%s\\n' \"$ORCA_VM_SCRIPTS_STAMP\" >\"$ORCA_HOME/bin/.scripts-stamp\"\nfi\n# The orca CLI (agents drive worktrees, terminals and the browser through it) talks to this VM's orcad.\ncli=\"$(find \"$ORCA_HOME/runtime\" -name orca-cli.cjs -type f | head -n 1)\"\nif [ -n \"$cli\" ]; then\n printf '#!/usr/bin/env bash\\nexport ORCA_USER_DATA_PATH=\"${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}\"\\nexec \"%s\" \"%s\" \"$@\"\\n' \"$node\" \"$cli\" >\"$ORCA_HOME/bin/orca\"\n chmod 0755 \"$ORCA_HOME/bin/orca\"\nelse\n log 'bundle has no orca CLI (orca-cli.cjs): agents will not have `orca` on PATH'\nfi\n# The image's node/npm/npx live only on the build command's PATH; append them so agents (codex's\n# `env node` shebang) and stdio MCP servers launched with npx resolve them in Orca's login shells.\nsystem_node=\"$(command -v npx || command -v node || true)\"\nif [ -z \"$system_node\" ]; then\n echo 'no node/npx on the build PATH' >&2\n exit 1\nfi\nprintf 'export PATH=%s/tools/bin:%s/bin:$PATH:%s\\n' \"$ORCA_HOME\" \"$ORCA_HOME\" \"$(dirname \"$system_node\")\" |\n sudo tee /etc/profile.d/orca.sh >/dev/null\n# Every new shell (login or not: /etc/bashrc sources profile.d) re-reads the session env file.\nsudo install -m 0644 \"$ORCA_HOME/bin/orca-session-env.sh\" /etc/profile.d/zz-orca-session-env.sh\nif [ -f /etc/bash.bashrc ]; then\n # Ubuntu's bash.bashrc does not source profile.d for non-login interactive shells (AL2023's bashrc does).\n grep -q zz-orca-session-env /etc/bash.bashrc ||\n echo '[ -r /etc/profile.d/zz-orca-session-env.sh ] && . /etc/profile.d/zz-orca-session-env.sh' | sudo tee -a /etc/bash.bashrc >/dev/null\nfi\nif [ -f /etc/bash.bashrc ]; then\n # Ubuntu: zsh reads /etc/zsh/zshenv for every shell, so new zsh shells match bash (`orca-env` covers\n # shells that were already open).\n sudo install -d -m 0755 /etc/zsh\n sudo touch /etc/zsh/zshenv\n grep -q zz-orca-session-env /etc/zsh/zshenv ||\n echo '[ -r /etc/profile.d/zz-orca-session-env.sh ] && . /etc/profile.d/zz-orca-session-env.sh' | sudo tee -a /etc/zsh/zshenv >/dev/null\nfi\nsudo chown -R root:root \"$ORCA_HOME\"\n\nlog 'smoke: orcad reaches ready on loopback (and warms the V8 compile cache: ~1.5 s off every boot)'\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" \"$ORCA_HOME/compile-cache\"\n# The runtime is root-owned, so its startup-qualified marker lives here. The smoke run leaves one,\n# so every boot from the image skips orcad's disposable startup preflight (~0.6 s of wake).\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" \"$ORCA_HOME/startup-qualification\"\nsmoke_data=\"$(mktemp -d)\"\n# orcad-boot also writes orcad's full code cache as the smoke run exits (~0.3 s more off every boot).\nNODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_USER_DATA=\"$smoke_data\" timeout 60 \"$node\" \"$ORCA_HOME/bin/orcad-boot\" \\\n --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" --write-code-cache \"$ORCA_HOME/runtime/orcad/orcad-server.js\" \\\n --port 6799 --json >/tmp/orcad-smoke.out 2>/tmp/orcad-smoke.err &\nsmoke_pid=$!\nready=0\nfor _ in $(seq 1 600); do\n if grep -q '\"orca_server_ready\"' /tmp/orcad-smoke.out 2>/dev/null; then ready=1; break; fi\n sleep 0.1\ndone\n# orcad writes the marker just after readiness; best effort, a boot without one only re-qualifies.\nfor _ in $(seq 1 30); do\n [ \"$ready\" = 1 ] && [ ! -s \"$ORCA_HOME/startup-qualification/.orcad-startup-qualified\" ] || break\n sleep 0.1\ndone\nkill \"$smoke_pid\" 2>/dev/null || true\nwait \"$smoke_pid\" 2>/dev/null || true\nrm -rf \"$smoke_data\" /tmp/orcad-smoke.out\nif [ \"$ready\" != 1 ]; then\n tail -n 40 /tmp/orcad-smoke.err >&2; exit 1\nfi\n# Best effort: without it every boot loads orcad as before.\nif [ -s \"$ORCA_HOME/compile-cache/orcad-server.v8\" ]; then\n log \"orcad code cache: $(stat -c %s \"$ORCA_HOME/compile-cache/orcad-server.v8\") bytes\"\nelse\n log 'orcad code cache was not written; boots compile orcad without it'\n grep 'orcad-boot' /tmp/orcad-smoke.err >&2 || true\nfi\n\nlog 'versions'\nversions=\"{}\"\nfor bin in claude codex opencode gemini cursor-agent copilot gh; do\n if [ -x \"$ORCA_HOME/tools/bin/$bin\" ]; then\n v=\"$(\"$ORCA_HOME/tools/bin/$bin\" --version 2>/dev/null | head -n 1 || echo unknown)\"\n versions=\"$(jq -c --arg k \"$bin\" --arg v \"$v\" '. + {($k): $v}' <<<\"$versions\")\"\n fi\ndone\nfor sys in rg vim git-lfs google-chrome; do\n if command -v \"$sys\" >/dev/null; then\n v=\"$(\"$sys\" --version 2>/dev/null | head -n 1 || echo unknown)\"\n versions=\"$(jq -c --arg k \"$sys\" --arg v \"$v\" '. + {($k): $v}' <<<\"$versions\")\"\n fi\ndone\ncommand -v tmux >/dev/null && versions=\"$(jq -c --arg v \"$(tmux -V)\" '. + {tmux: $v}' <<<\"$versions\")\"\n[ -x \"$ORCA_HOME/bin/orca\" ] && versions=\"$(jq -c '. + {orca: \"bundled\"}' <<<\"$versions\")\"\njq -c --arg node \"$(\"$node\" --version)\" --arg disk \"$(df -h / | awk 'NR==2{print $2}')\" \\\n --argjson desktop \"$desktop\" '{node: $node, disk: $disk, tools: ., desktop: $desktop}' <<<\"$versions\"\n" -export const VM_SCRIPT_SOURCES: BuildInputs['vmScripts'] = {"orca-sandbox-start":"#!/usr/bin/env bash\n# Starts orcad for this boot (idempotent) and prints its recipe line:\n# {\"schemaVersion\":1,\"pairingCode\":\"orca://pair?...\",\"projectRoot\":\"/vercel/sandbox/project\"}\n# Env from the control plane: ORCA_SANDBOX_ID, ORCA_PUBLIC_WSS, optional ORCA_REPO_URL/ORCA_REPO_REF,\n# ORCA_GITHUB_PLACEHOLDER, ORCA_SECRET_ENV (`NAME=` lines: org/personal/repo secrets for\n# orcad and its agents), ORCA_SHARE_PROXY_KEY (this session's share-link proxy key, port 6769),\n# ORCA_DOCKER (on|off: the control plane's Docker switch for the `docker` shim).\n# Never prints anything else on stdout's last line.\n# With ORCA_READY_VIA=file it prints {\"schemaVersion\":1,\"readyFile\":\"\"} instead and the control\n# plane reads the offer with the files API: the provider keeps command stdout as logs, not files.\n# With ORCA_READY_KEY too (64 hex chars, this call's key; env is not kept) the pointer also carries\n# \"sealedOffer\": \".\", which saves that round trip.\n# Managed env for every process orcad starts: ORCA_IS_CLOUD=1, ORCA_SANDBOX_ID, ORCA_ROOT_PATH,\n# ORCA_WORKTREE_PATH, ORCA_WORKSPACE_PATH, ORCA_WORKSPACE_NAME, ORCA_DEFAULT_BRANCH, ORCA_PORT and the\n# CONDUCTOR_* names imported Conductor scripts read.\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nPROJECT=/vercel/sandbox/project\nmkdir -p \"$STATE\"\n# Only print_ready uses the key; nothing this script starts inherits it.\nready_key=\"${ORCA_READY_KEY:-}\"\nunset ORCA_READY_KEY\n[[ \"$ready_key\" =~ ^[0-9a-f]{64}$ ]] || ready_key=''\nexec 9>\"$STATE/start.lock\"\nflock -w 60 9\n# Background children close fd 9 (`9>&-`): an orcad that inherited it would hold the lock for its whole\n# life and every later start (resume of a running sandbox, a retried create) would wait out the 60 s.\n\n# orcad only lists a project once a client registers it (the desktop does on connect), so API, MCP,\n# routine and phone sessions saw no repo. Register the workspace project at every start, in the\n# background (ready is not delayed); `repo add` of an already-registered path is a no-op error.\nregister_project() {\n [ -x \"$ORCA_HOME/bin/orca\" ] && [ -d \"$PROJECT\" ] || return 0\n local kind=() name=()\n [ -e \"$PROJECT/.git\" ] || kind=(--kind folder)\n # The checkout lives at .../project; name it after the repository (owner/name.git -> name).\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n local base=\"${ORCA_REPO_URL%/}\"\n base=\"${base##*/}\"\n base=\"${base%.git}\"\n [ -n \"$base\" ] && name=(--display-name \"$base\")\n fi\n setsid \"$ORCA_HOME/bin/orca\" repo add --path \"$PROJECT\" \"${kind[@]}\" \"${name[@]}\" --json \\\n >\"$STATE/register-project.log\" 2>&1 &- &\n}\n\nprint_ready() {\n if [ \"${ORCA_READY_VIA:-}\" = file ]; then\n local sealed='' iv\n if [ -n \"$ready_key\" ] && command -v openssl >/dev/null; then\n iv=\"$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')\"\n # Best effort: without it the control plane reads the file, as before.\n sealed=\"$(tail -n 1 \"$STATE/ready.json\" | openssl enc -aes-256-ctr -K \"$ready_key\" -iv \"$iv\" -nosalt | base64 -w0)\" &&\n sealed=\"$iv.$sealed\" || sealed=''\n fi\n printf '{\"schemaVersion\":1,\"readyFile\":\"%s\"%s}\\n' \"$STATE/ready.json\" \"${sealed:+,\\\"sealedOffer\\\":\\\"$sealed\\\"}\"\n else\n tail -n 1 \"$STATE/ready.json\"\n fi\n}\n# Command stderr is kept by the provider: strip injected values and credential shapes from log tails.\nredact_log() {\n local text kv value\n text=\"$(cat)\"\n for kv in ${agent_env[@]+\"${agent_env[@]}\"}; do\n value=\"${kv#*=}\"\n if [ \"${#value}\" -ge 8 ]; then\n text=\"${text//\"$value\"/[REDACTED]}\"\n fi\n done\n printf '%s\\n' \"$text\" | sed -E \\\n -e 's#orca://[^[:space:]]+#[REDACTED_PAIRING]#g' \\\n -e 's#(gh[pousr]_|github_pat_|sk-|vc[kpiar]_)[A-Za-z0-9._-]{16,}#[REDACTED_TOKEN]#g' \\\n -e 's#eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}#[REDACTED_JWT]#g' \\\n -e 's#(Authorization|authorization):[[:space:]]*[A-Za-z]+[[:space:]]+[^[:space:]]+#\\1: [REDACTED]#g'\n}\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n\n# Share-link proxy (port 6769): answers only requests the control plane signed with this session's\n# key, so its public route is useless on its own. The key goes in on stdin (printf is a builtin), so\n# it never appears in any argv or in the proxy's /proc//environ.\nstart_share_proxy() {\n [ -n \"${ORCA_SHARE_PROXY_KEY:-}\" ] && [ -x \"$ORCA_HOME/bin/orca-share-proxy\" ] || return 0\n if [ \"$(cat \"$STATE/share-proxy.boot\" 2>/dev/null || true)\" = \"$boot_id\" ] \\\n && kill -0 \"$(cat \"$STATE/share-proxy.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n return 0\n fi\n printf '%s' \"$ORCA_SHARE_PROXY_KEY\" | env -i HOME=\"$HOME\" LANG=C.UTF-8 PATH=/usr/bin:/bin \\\n setsid \"$node\" \"$ORCA_HOME/bin/orca-share-proxy\" >\"$STATE/share-proxy.log\" 2>&1 9>&- &\n echo $! >\"$STATE/share-proxy.pid\"\n printf '%s' \"$boot_id\" >\"$STATE/share-proxy.boot\"\n}\n\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\n# CREATE-GIT-ASYNC: a create answers before member identities are installed; `git` holds commits and\n# pushes until orca-sandbox-members (or the control plane) marks this setup ready or failed. Marked\n# before the already-started exit below: a pooled VM's orcad may be up before its create claims it.\nif [ \"${ORCA_GIT_SETUP:-}\" = pending ]; then\n rm -f \"$STATE/git-setup.ready\" \"$STATE/git-setup.failed\"\n date +%s >\"$STATE/git-setup.pending\"\nfi\n# PARITY-DOCKER: the control plane's Docker switch (SANDBOX_DOCKER) for the `docker` shim. Only a\n# start that says so changes it; a retried or repair start (no ORCA_DOCKER) keeps the last answer.\ncase \"${ORCA_DOCKER:-}\" in\n off) : >\"$STATE/docker.off\" ;;\n on) rm -f \"$STATE/docker.off\" ;;\nesac\nstart_share_proxy\nunset ORCA_SHARE_PROXY_KEY\n# MEMGUARD: OOM-killer ranks that spare orcad and terminals, a guard that stops the largest build or\n# test before the VM stalls, on-demand swap and a /dev/shm sized for browsers. Before the\n# already-started exit so a repair start brings a dead guard back; it returns at once.\nsudo -n \"$ORCA_HOME/bin/orca-memguard\" start /dev/null 2>&1 9>&- || true\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" = \"$boot_id\" ] && [ -s \"$STATE/ready.json\" ] \\\n && kill -0 \"$(cat \"$STATE/orcad.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n print_ready\n exit 0\nfi\n# Resume = reboot from disk: locks and pids from the previous session name dead processes.\nrm -f \"$STATE/ready.json\" \"$STATE/orcad.pid\"\nprintf '%s' \"$boot_id\" >\"$STATE/boot-id\"\n# Any other boot (wake, restart) installs identities before it answers: a resumed disk's marks are stale.\n[ \"${ORCA_GIT_SETUP:-}\" = pending ] || rm -f \"$STATE/git-setup.pending\" \"$STATE/git-setup.ready\" \"$STATE/git-setup.failed\"\n\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n # Every github.com request carries the placeholder; the egress policy swaps in a 1h repo token.\n git config --global http.https://github.com/.extraheader \"$ORCA_GIT_EXTRAHEADER\"\nfi\n# Commits outside a teammate's turn (or before any member connected GitHub) need an author too.\n# The fallback is noreply@orca.dev (DOMAIN-1); a workspace still on an earlier default follows it.\ncase \"$(git config --global user.email 2>/dev/null || true)\" in\n cloud@users.noreply.onorca.dev | cloud@users.noreply.orca.dev)\n git config --global user.email 'noreply@orca.dev' ;;\nesac\ngit config --global user.email >/dev/null 2>&1 || git config --global user.email 'noreply@orca.dev'\n# The fallback name is \"Orca\" (DOMAIN-1); a workspace still on the earlier default follows it.\n[ \"$(git config --global user.name 2>/dev/null || true)\" = 'Orca Cloud' ] \\\n && git config --global user.name 'Orca'\ngit config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca'\n# First boot clones while orcad starts (orcad only needs the directory to exist); ready waits for both.\nclone_pid=''\nif [ ! -d \"$PROJECT\" ]; then\n mkdir -p \"$PROJECT\"\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n git clone --quiet ${ORCA_REPO_REF:+--branch \"$ORCA_REPO_REF\"} -- \"$ORCA_REPO_URL\" \"$PROJECT\" 2>\"$STATE/clone.log\" 9>&- &\n clone_pid=$!\n fi\nfi\n\n# The clone may still be running here, so the name comes from the URL; the default branch is\n# filled in lazily by the session-env shell hook once the clone exists.\nif [ -n \"${ORCA_REPO_URL:-}\" ]; then\n workspace_name=\"$(basename \"${ORCA_REPO_URL%/}\" .git)\"\nelse\n workspace_name=\"$(basename \"$(git -C \"$PROJECT\" remote get-url origin 2>/dev/null || echo \"$PROJECT\")\" .git)\"\nfi\n# One workspace per VM: its preview ports start at 3000 (Conductor allots CONDUCTOR_PORT..+9).\nmanaged_env=(\n ORCA_IS_CLOUD=1\n ORCA_ROOT_PATH=\"$PROJECT\" ORCA_WORKTREE_PATH=\"$PROJECT\" ORCA_WORKSPACE_PATH=\"$PROJECT\"\n ORCA_WORKSPACE_NAME=\"$workspace_name\" ORCA_PORT=3000\n CONDUCTOR_IS_CLOUD=1\n # Agent CLIs are pinned by the image (smoke-tested); a self-update mid-session can break a running agent.\n DISABLE_AUTOUPDATER=1 OPENCODE_DISABLE_AUTOUPDATE=1 COPILOT_AUTO_UPDATE=false\n CONDUCTOR_ROOT_PATH=\"$PROJECT\" CONDUCTOR_WORKSPACE_PATH=\"$PROJECT\"\n CONDUCTOR_WORKSPACE_NAME=\"$workspace_name\" CONDUCTOR_PORT=3000\n)\n\nagent_env=()\nif command -v google-chrome >/dev/null; then\n # Orca's browser automation and agent browser tools use the image's headless Chrome.\n agent_env+=(\"ORCA_BROWSER_EXECUTABLE=$(command -v google-chrome)\")\nfi\nif [ -n \"${ORCA_GITHUB_PLACEHOLDER:-}\" ]; then\n # The egress layer swaps the placeholder for a short-lived GitHub token; none lives in the VM.\n agent_env+=(\"GH_TOKEN=$ORCA_GITHUB_PLACEHOLDER\" \"GITHUB_TOKEN=$ORCA_GITHUB_PLACEHOLDER\")\n # GH-AS-MEMBER: gh (image/vm/gh) acts as the attested sender with their own placeholder.\n [ \"${ORCA_GH_AS_MEMBER:-}\" = on ] && agent_env+=(\"ORCA_GH_AS_MEMBER=on\")\nfi\n\nsecret_names=()\nif [ -n \"${ORCA_SECRET_ENV:-}\" ]; then\n # Secrets live only in memory: orcad's process env and a tmpfs file new shells re-read\n # (orca-sandbox-env), never under $HOME or the project, so the stop snapshot never carries them.\n # Resolved per start (and per edit) by the control plane: no image rebuild, no restart.\n while IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\" # not IFS='=': read would strip base64 padding\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n agent_env+=(\"$name=$(printf '%s' \"$b64\" | base64 -d)\")\n secret_names+=(\"$name\")\n done < <(printf '%s\\n' \"$ORCA_SECRET_ENV\") # a pipe, not a here-string temp file\nfi\n# Always rewrite the file, so a resume with fewer secrets drops the old names too.\n\"$ORCA_HOME/bin/orca-sandbox-env\" >/dev/null || echo 'session env file unavailable; secrets apply at boot only' >&2\nunset ORCA_SECRET_ENV\n\n# OpenCode installs @opencode-ai/plugin into ~/.config/opencode and, with Orca's plugin configured,\n# draws nothing until that install ends (blank ~85 s on a slow registry, n73). The image carries the\n# install (provision-golden.sh): copy it into a home that has neither node_modules nor a package.json\n# of its own, so the first launch never fetches.\noc_seed=\"$ORCA_HOME/opencode-config-seed\"\noc_dir=\"$HOME/.config/opencode\"\nif [ -d \"$oc_seed/node_modules\" ] && [ ! -e \"$oc_dir/node_modules\" ] && [ ! -e \"$oc_dir/package.json\" ]; then\n mkdir -p \"$oc_dir\" \\\n && cp -R \"$oc_seed/node_modules\" \"$oc_dir/node_modules\" \\\n && cp \"$oc_seed/package.json\" \"$oc_seed/package-lock.json\" \"$oc_dir/\" \\\n || echo 'opencode config seed not copied' >&2\nfi\n# The rest of OpenCode's first run (its database, the model list): ~2.5 s on the first launch\n# (5.2 s vs 2.7 s warm, n72). Done now in the background at low priority with no credentials\n# (`opencode models` does it and exits). Skipped once it has run on this disk. An image without the\n# seed (an environment snapshot from an older golden) still needs the install: then the first run\n# waits for orcad to put Orca's plugin in ~/.config/opencode/plugins (~10 s), since OpenCode only\n# finishes that install when a plugin is configured.\nif [ -x \"$ORCA_HOME/tools/bin/opencode\" ] && { [ ! -e \"$HOME/.local/share/opencode/opencode.db\" ] || [ ! -e \"$oc_dir/node_modules\" ]; }; then\n (\n cd \"$HOME\" || exit 0\n # shellcheck disable=SC2016 # expanded by the inner shell\n env -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 PATH=\"$ORCA_HOME/tools/bin:/usr/local/bin:/usr/bin:/bin\" \\\n OPENCODE_DISABLE_AUTOUPDATE=1 setsid nohup nice -n 19 bash -c '\n if [ ! -e \"$HOME/.config/opencode/node_modules\" ]; then\n for _ in $(seq 1 120); do [ -d \"$HOME/.config/opencode/plugins\" ] && break; sleep 0.5; done\n fi\n exec timeout 120 \"$1\" models\n ' opencode-first-run \"$ORCA_HOME/tools/bin/opencode\" /dev/null 2>&1 9>&- &\n )\nfi\n\n# Agent CLIs installed with the image's npm (codex, gemini, ...) are `#!/usr/bin/env node` scripts:\n# terminals need that node on PATH, not only orcad's bundled runtime.\nsystem_node=\"$(command -v node 2>/dev/null || echo \"$node\")\"\n# The egress proxy answers for hosts with credential rules (model APIs, api.github.com) with a\n# certificate from Vercel's CA, which this command's env trusts (Vercel sets these). Pure-Node clients\n# use Node's bundled roots otherwise: Gemini CLI retried forever (\"taking a bit longer\") in every\n# terminal while the same call worked here. Pass the provider's CA settings on to orcad and its shells.\nca_env=(NODE_USE_SYSTEM_CA=\"${NODE_USE_SYSTEM_CA:-1}\")\nfor name in NODE_EXTRA_CA_CERTS SSL_CERT_FILE; do\n if [ -n \"${!name:-}\" ]; then ca_env+=(\"$name=${!name}\"); fi\ndone\n# N-02: the host is a cloud terminal's source of truth across app reopens, so orcad and its\n# daemon keep a local terminal's depth (5000 rows) instead of the desktop daemon's 1000-row live\n# window. Scoped to the VM: local desktop daemons keep their default.\n# Ports panel: programs under $ORCA_HOME are the image's own services, and 23456 is Vercel's\n# sandbox-init (root, pid invisible to this user); neither is listed as the user's port.\nenv -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 TERM=xterm-256color \"${ca_env[@]}\" \\\n PATH=\"$ORCA_HOME/tools/bin:$ORCA_HOME/bin:$(dirname \"$system_node\"):/usr/local/bin:/usr/bin:/bin\" \\\n ORCA_USER_DATA=\"$HOME/.orcad-data\" ORCA_SANDBOX_ID=\"$ORCA_SANDBOX_ID\" \"${managed_env[@]}\" \\\n ORCA_HOST_MANAGED_LISTENER_PATHS=\"$ORCA_HOME\" ORCA_HOST_MANAGED_UNOWNED_PORTS=23456 \\\n NODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_DAEMON_SESSION_SCROLLBACK_ROWS=5000 \\\n ORCA_SESSION_ENV_NAMES=\"${secret_names[*]}\" \"${agent_env[@]}\" \\\n setsid nohup \"$node\" \"$ORCA_HOME/bin/orcad-boot\" --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" \\\n \"$ORCA_HOME/runtime/orcad/orcad-server.js\" --port 6768 --bind 0.0.0.0 --pairing-address \"$ORCA_PUBLIC_WSS\" \\\n --recipe-json --project-root \"$PROJECT\" \\\n >\"$STATE/ready.json\" 2>\"$STATE/orcad.log\" &- &\necho $! >\"$STATE/orcad.pid\"\n\n# sshd for `orca ssh` (loopback only). Best effort: a workspace without it still serves orcad.\n\"$ORCA_HOME/bin/orca-sshd\" >/dev/null 2>\"$STATE/sshd-start.err\" || true\n\n# The agent CLIs are large and a fresh VM pages them in lazily from the snapshot, so the first agent\n# launch paid for it (OpenCode 11 s cold vs 3.75 s warm, n71). Read them into the page cache in the\n# background at idle IO priority, after orcad is starting. Best effort; detached so it outlives this\n# script, and never on the ready path.\nprefetch_dirs=()\nfor dir in @anthropic-ai @openai opencode-ai; do\n if [ -d \"$ORCA_HOME/tools/lib/node_modules/$dir\" ]; then\n prefetch_dirs+=(\"$ORCA_HOME/tools/lib/node_modules/$dir\")\n fi\ndone\nif [ \"${#prefetch_dirs[@]}\" -gt 0 ]; then\n # shellcheck disable=SC2016 # expanded by the inner shell\n setsid nohup nice -n 19 bash -c '\n command -v ionice >/dev/null && ionice -c 3 -p $$ 2>/dev/null\n find \"$@\" -type f -size +256k -print0 2>/dev/null | xargs -0 -r cat >/dev/null 2>&1\n ' agent-prefetch \"${prefetch_dirs[@]}\" /dev/null 2>&1 9>&- &\nfi\n\n# Polled every 10 ms (at least 60 s in all): ready is on the wake path, so detect it promptly.\nfor _ in $(seq 1 6000); do\n if grep -q '\"pairingCode\"' \"$STATE/ready.json\" 2>/dev/null; then\n if [ -n \"$clone_pid\" ] && ! wait \"$clone_pid\"; then\n echo 'repository clone failed' >&2\n tail -n 5 \"$STATE/clone.log\" | redact_log >&2\n exit 1\n fi\n register_project\n print_ready\n exit 0\n fi\n if ! kill -0 \"$(cat \"$STATE/orcad.pid\")\" 2>/dev/null; then\n echo 'orcad exited before ready' >&2\n tail -n 40 \"$STATE/orcad.log\" | redact_log >&2\n exit 1\n fi\n sleep 0.01\ndone\necho 'orcad start timed out' >&2\nexit 1\n","orca-sandbox-drain":"#!/usr/bin/env bash\n# Asks orcad to quit before the VM stops: its shutdown turns working agent chats into durable\n# restart offers and flushes terminal restore hints, which the desktop continues after resume.\nset -euo pipefail\nSTATE=\"$HOME/.orca-sandbox\"\nWAIT_SECONDS=\"${1:-280}\"\npid=\"$(cat \"$STATE/orcad.pid\" 2>/dev/null || true)\"\nif [ -z \"$pid\" ] || ! kill -0 \"$pid\" 2>/dev/null; then\n exit 0\nfi\nkill -TERM \"$pid\"\nfor _ in $(seq 1 $((WAIT_SECONDS * 10))); do\n if ! kill -0 \"$pid\" 2>/dev/null; then\n rm -f \"$STATE/orcad.pid\" \"$STATE/ready.json\"\n # On-demand swap files would ride the stop snapshot (2 GiB each). Best effort, bounded.\n [ -x /opt/orca/bin/orca-memguard ] && sudo -n timeout 20 /opt/orca/bin/orca-memguard release-swap >/dev/null 2>&1 || true\n exit 0\n fi\n sleep 0.1\ndone\n# Leave it running: the provider stop ends it, and the drain already had its window.\necho 'orcad still draining at deadline' >&2\nexit 0\n","orca-memguard":"#!/usr/bin/env bash\n# Memory guard for the workspace VM (runs as root: `sudo -n orca-memguard start`). A build or test\n# that eats the VM's memory must cost that process, never the workspace: without this the kernel\n# thrashes for minutes before its OOM killer picks something, and the VM looks dead meanwhile.\n# start start the guard for this boot unless it already runs (returns at once)\n# run the guard loop itself (start runs it detached)\n# release-swap turn off and delete on-demand swap (before a stop, so the snapshot stays small)\n# sweep apply OOM-killer priorities once and exit (tests, diagnostics)\n# victim print \" \" of the process the guard would stop now (no kill)\n# Every few seconds it ranks processes for the kernel's OOM killer (oom_score_adj):\n# -900 Orca's own runtime: orcad, its terminal daemon, the share proxy (Orca's bundled Node)\n# -500 terminal shells (children of the terminal daemon) and agent CLIs\n# 500 everything else (builds, tests, dev servers, browsers); never lowered\n# When MemAvailable falls under KILL_PCT (8%) of RAM it kills the largest process ranked 0 or more,\n# records it in $RUN/kills and $RUN/state, and waits for memory to return. The kernel's OOM killer\n# stays the backstop for allocations faster than the guard's 200 ms look, with the same ranks.\n# Swap is added on demand (2 GiB files up to 1.5x RAM) when memory runs low, if the kernel takes it,\n# and dropped after 10 quiet minutes. It also sizes /dev/shm to half of RAM (the provider mounts\n# 64 MB, which crashes Chrome and Electron renderers).\n# $RUN/state (key=value, world-readable) is what the control plane's status probe reads.\nset -uo pipefail\nRUN=/run/orca-memguard\n# Tests point it at a fake process table.\nPROC=\"${ORCA_MEMGUARD_PROC:-/proc}\"\nSWAP_DIR=/var/lib/orca-memguard\nORCA_HOME=/opt/orca\nKILL_PCT=\"${ORCA_MEMGUARD_KILL_PCT:-8}\"\nHIGH_PCT=15\nSWAP_ADD_PCT=20\nQUIET_PCT=50\nQUIET_SECONDS=600\nTICK=1\nFAST_TICK=0.2\nSWEEP_EVERY=3\nSTATE_EVERY=15\nSWAP_CHUNK_KIB=$((2 * 1024 * 1024))\n\nboot_id() { local id; read -r id >\"$RUN/memguard.log\"; }\n\n# Name of a process for people: the script a node/python/... runs, else its command name.\nproc_name() {\n local pid=\"$1\" comm arg name='' skip=0 module=0 args=()\n read -r comm 2>/dev/null <\"$PROC/$pid/comm\" || comm=''\n mapfile -d '' -t args 2>/dev/null <\"$PROC/$pid/cmdline\" || true\n case \"${args[0]##*/}\" in\n node | nodejs | bun | deno | python* | ruby | perl | java | sh | bash | dash | zsh)\n for arg in \"${args[@]:1}\"; do\n if [ \"$skip\" -eq 1 ]; then skip=0; continue; fi\n if [ \"$module\" -eq 1 ]; then name=\"${arg##*/}\"; break; fi\n case \"$arg\" in\n # Inline code is no name (and may hold anything): the interpreter's name it is.\n -e | -p | -c | --eval | --print) break ;;\n -m | -jar) module=1 ;; # python -m pytest, java -jar gradle.jar: the module or jar\n -r | --require | --import | --loader | -X | -W | -cp | -classpath) skip=1 ;;\n -*) ;;\n *) name=\"${arg##*/}\"; break ;;\n esac\n done ;;\n esac\n [ -n \"$name\" ] || name=\"${args[0]##*/}\"\n [ -n \"$name\" ] || name=\"$comm\"\n name=\"${name%.js}\"\n name=\"${name%.mjs}\"\n name=\"${name%.cjs}\"\n name=\"${name%.jar}\"\n name=\"${name//[^A-Za-z0-9._+-]/}\"\n printf '%s' \"${name:0:40}\"\n}\n\n# The terminal daemon's pid(s): Orca-runtime node processes running the daemon entry.\ndaemon_pids=' '\n# Sets RANK to the oom_score_adj a process should have; returns 1 for a kernel thread or a gone pid.\nRANK=500\nrank() {\n local pid=\"$1\" args=() stat ppid\n mapfile -d '' -t -n 3 args 2>/dev/null <\"$PROC/$pid/cmdline\" || return 1\n [ \"${#args[@]}\" -gt 0 ] || return 1\n RANK=-900\n case \"${args[0]}\" in \"$ORCA_HOME\"/runtime/runtimes/*) return 0 ;; esac\n RANK=-500\n read -r stat 2>/dev/null <\"$PROC/$pid/stat\" || return 1\n stat=\"${stat##*) }\"\n ppid=\"${stat#* }\"\n ppid=\"${ppid%% *}\"\n case \"$daemon_pids\" in *\" $ppid \"*) return 0 ;; esac\n case \"${args[0]}/${args[1]:-}/${args[2]:-}\" in \"$ORCA_HOME\"/tools/* | */\"$ORCA_HOME\"/tools/*) return 0 ;; esac\n case \"${args[0]##*/}\" in claude | codex | opencode | gemini | cursor-agent | copilot | amp | droid) return 0 ;; esac\n RANK=500\n}\n\nsweep() {\n local p pid want adj args=()\n daemon_pids=' '\n for p in \"$PROC\"/[0-9]*; do\n pid=\"${p#\"$PROC\"/}\"\n mapfile -d '' -t -n 3 args 2>/dev/null <\"$p/cmdline\" || continue\n [ \"${#args[@]}\" -ge 2 ] || continue\n case \"${args[0]}\" in \"$ORCA_HOME\"/runtime/runtimes/*) ;; *) continue ;; esac\n case \"${args[*]:1}\" in *\"$ORCA_HOME\"/runtime/orcad/daemon*) daemon_pids+=\"$pid \" ;; esac\n done\n for p in \"$PROC\"/[0-9]*; do\n pid=\"${p#\"$PROC\"/}\"\n [ \"$pid\" -gt 1 ] && [ \"$pid\" != \"$$\" ] || continue\n read -r adj 2>/dev/null <\"$p/oom_score_adj\" || continue\n # -1000 is a process that asked for it as root (sshd): leave it alone.\n [ \"$adj\" -gt -1000 ] || continue\n rank \"$pid\" || continue\n want=\"$RANK\"\n # Never lower what a process raised for itself (Chrome ranks its renderers above its browser).\n if [ \"$want\" -eq 500 ]; then\n [ \"$adj\" -lt 500 ] || continue\n fi\n [ \"$adj\" -ne \"$want\" ] || continue\n printf '%s\\n' \"$want\" 2>/dev/null >\"$p/oom_score_adj\" || true\n done\n}\n\nmem_total=0 mem_avail=0 swap_total=0 swap_free=0\nread_mem() {\n local key value _\n while read -r key value _; do\n case \"$key\" in\n MemTotal:) mem_total=\"$value\" ;;\n MemAvailable:) mem_avail=\"$value\" ;;\n SwapTotal:) swap_total=\"$value\" ;;\n SwapFree:) swap_free=\"$value\" ;;\n esac\n done <\"$PROC/meminfo\"\n}\n\n# PSI percentages (avg10, integer part); 0 when the kernel doesn't report them.\npsi_some=0 psi_full=0\nread_psi() {\n local kind avg _\n psi_some=0 psi_full=0\n [ -r \"$PROC/pressure/memory\" ] || return 0\n while read -r kind avg _; do\n avg=\"${avg#avg10=}\"\n avg=\"${avg%%.*}\"\n case \"$kind\" in some) psi_some=\"$avg\" ;; full) psi_full=\"$avg\" ;; esac\n done 2>/dev/null <\"$PROC/pressure/memory\" || true\n}\n\nkills=0 last_kill_name='' last_kill_at=0 swap_mode=on-demand level=ok\nwrite_state() {\n local pct=\"$1\"\n {\n printf 'bootId=%s\\nat=%s\\npid=%s\\nlevel=%s\\navailPct=%s\\nmemTotalKiB=%s\\nmemAvailKiB=%s\\n' \\\n \"$BOOT\" \"$(now_ms)\" \"$$\" \"$level\" \"$pct\" \"$mem_total\" \"$mem_avail\"\n printf 'swapTotalKiB=%s\\nswapFreeKiB=%s\\nswap=%s\\npsiSome10=%s\\npsiFull10=%s\\n' \\\n \"$swap_total\" \"$swap_free\" \"$swap_mode\" \"$psi_some\" \"$psi_full\"\n printf 'kills=%s\\nlastKillName=%s\\nlastKillAt=%s\\n' \"$kills\" \"$last_kill_name\" \"$last_kill_at\"\n } >\"$RUN/state.tmp\" && mv -f \"$RUN/state.tmp\" \"$RUN/state\"\n}\n\n# Sets VICTIM/VICTIM_RSS (pages) to the largest process ranked 0 or more; returns 1 when there is none.\nVICTIM=0 VICTIM_RSS=0\nchoose_victim() {\n local p pid adj rss _ best=0 best_rss=0 args=()\n sweep\n for p in \"$PROC\"/[0-9]*; do\n pid=\"${p#\"$PROC\"/}\"\n [ \"$pid\" -gt 1 ] && [ \"$pid\" != \"$$\" ] || continue\n read -r adj 2>/dev/null <\"$p/oom_score_adj\" || continue\n [ \"$adj\" -ge 0 ] || continue\n read -r _ rss _ 2>/dev/null <\"$p/statm\" || continue\n # Kernel threads have no command line (and /proc sizes read 0, so `-s` can't tell).\n mapfile -d '' -t -n 1 args 2>/dev/null <\"$p/cmdline\" || continue\n [ \"${#args[@]}\" -gt 0 ] || continue\n if [ \"$rss\" -gt \"$best_rss\" ]; then\n best=\"$pid\" best_rss=\"$rss\"\n fi\n done\n # Nothing big enough to matter (64 MiB): what fills memory is protected, so leave it to the kernel.\n [ \"$best\" -gt 1 ] && [ \"$best_rss\" -ge 16384 ] || return 1\n VICTIM=\"$best\" VICTIM_RSS=\"$best_rss\"\n}\n\n# Kills the largest process ranked 0 or more ($1: MemAvailable %). Returns 1 when there is none.\nkill_largest() {\n choose_victim || return 1\n local best=\"$VICTIM\" best_rss=\"$VICTIM_RSS\" name at\n name=\"$(proc_name \"$best\")\"\n kill -KILL \"$best\" 2>/dev/null || return 1\n at=\"$(now_ms)\"\n kills=$((kills + 1)) last_kill_name=\"${name:-process}\" last_kill_at=\"$at\"\n printf '%s %s %s %s %s\\n' \"$at\" \"$best\" \"$((best_rss * 4))\" \"$1\" \"$last_kill_name\" >>\"$RUN/kills\"\n tail -n 50 \"$RUN/kills\" >\"$RUN/kills.tmp\" && mv -f \"$RUN/kills.tmp\" \"$RUN/kills\"\n log \"killed pid=$best name=$last_kill_name rssKiB=$((best_rss * 4)) availPct=$1\"\n # Shells hear it like a kernel OOM kill (exit 137); this says why where someone may look.\n logger -t orca-memguard \"stopped $last_kill_name (pid $best, $((best_rss * 4)) KiB) at $1% memory available\" 2>/dev/null || true\n return 0\n}\n\nswap_files() { compgen -G \"$SWAP_DIR/swap-*\" || true; }\nadd_swap() {\n [ \"$swap_mode\" = on-demand ] || return 1\n [ $((swap_total + SWAP_CHUNK_KIB)) -le $((mem_total * 3 / 2)) ] || return 1\n local free_kib file\n free_kib=\"$(df -k --output=avail \"$SWAP_DIR\" 2>/dev/null | tail -n 1 | tr -d ' ')\"\n # Keep 4 GiB of the disk for the workspace itself.\n [ \"${free_kib:-0}\" -gt $((SWAP_CHUNK_KIB + 4 * 1024 * 1024)) ] || return 1\n file=\"$SWAP_DIR/swap-$(now_ms)\"\n if fallocate -l \"$((SWAP_CHUNK_KIB))K\" \"$file\" 2>/dev/null && chmod 600 \"$file\" \\\n && mkswap -q \"$file\" >/dev/null 2>&1 && swapon \"$file\" 2>/dev/null; then\n log \"swap on $file\"\n return 0\n fi\n rm -f \"$file\"\n # One refusal means this kernel or disk won't swap: don't retry every tick.\n swap_mode=unsupported\n log 'swap unavailable; guard kills only'\n return 1\n}\nrelease_swap() {\n local file\n for file in $(swap_files | sort -r); do\n swapoff \"$file\" 2>/dev/null && rm -f \"$file\" && log \"swap off $file\"\n done\n}\n\nrun() {\n BOOT=\"$(boot_id)\"\n mkdir -p \"$RUN\" \"$SWAP_DIR\"\n chmod 0755 \"$RUN\"\n chmod 0700 \"$SWAP_DIR\"\n # A resumed disk carries the last session's files: its kills and swap belong to that boot.\n rm -f \"$RUN/kills\" \"$RUN/state\" \"$RUN\"/*.tmp\n for file in $(swap_files); do\n grep -q \"^$file \" /proc/swaps 2>/dev/null || rm -f \"$file\"\n done\n printf '%s %s\\n' \"$BOOT\" \"$$\" >\"$RUN/pid\"\n echo -1000 >/proc/self/oom_score_adj\n read_mem\n # Half of RAM for /dev/shm (tmpfs only takes pages that are written).\n mount -o remount,size=50% /dev/shm 2>/dev/null && log \"/dev/shm $(df -h --output=size /dev/shm | tail -n 1 | tr -d ' ')\"\n log \"start mem=${mem_total}KiB\"\n local tick=0 pct quiet_since=0 prev='' now\n while :; do\n read_mem\n read_psi\n pct=$((mem_total > 0 ? mem_avail * 100 / mem_total : 100))\n if [ $((tick % SWEEP_EVERY)) -eq 0 ]; then\n sweep\n fi\n if [ \"$pct\" -lt \"$SWAP_ADD_PCT\" ] && { [ \"$swap_total\" -eq 0 ] || [ $((swap_free * 4)) -lt \"$swap_total\" ]; }; then\n add_swap && read_mem\n fi\n # Swap only raises MemAvailable by paging idle memory out: a fast allocator outruns it (the\n # kernel OOM-killed a 300 MB/s hog with 1.7 GB of swap free), so the threshold ignores swap.\n if [ \"$pct\" -lt \"$KILL_PCT\" ]; then\n level=critical\n if kill_largest \"$pct\"; then\n write_state \"$pct\"\n prev=\"$level:$kills\"\n sleep 1 # let the kernel reclaim the victim's memory before judging again\n tick=$((tick + 1))\n continue\n fi\n elif [ \"$psi_full\" -ge 10 ]; then\n level=critical\n elif [ \"$pct\" -lt \"$HIGH_PCT\" ] || [ \"$psi_some\" -ge 20 ]; then\n level=high\n else\n level=ok\n fi\n now=\"${EPOCHSECONDS}\"\n if [ \"$pct\" -ge \"$QUIET_PCT\" ] && [ \"$swap_total\" -gt 0 ]; then\n [ \"$quiet_since\" -gt 0 ] || quiet_since=\"$now\"\n if [ $((now - quiet_since)) -ge \"$QUIET_SECONDS\" ] && [ $(((swap_total - swap_free) * 2)) -lt \"$mem_avail\" ]; then\n release_swap\n quiet_since=0\n fi\n else\n quiet_since=0\n fi\n if [ \"$level:$kills\" != \"$prev\" ] || [ $((tick % STATE_EVERY)) -eq 0 ]; then\n write_state \"$pct\"\n prev=\"$level:$kills\"\n fi\n tick=$((tick + 1))\n # Memory can go from 15% to nothing in two seconds: look five times as often when it is low.\n if [ \"$level\" = ok ]; then sleep \"$TICK\"; else sleep \"$FAST_TICK\"; fi\n done\n}\n\nrunning() {\n local boot pid\n read -r boot pid <\"$RUN/pid\" 2>/dev/null || return 1\n [ \"$boot\" = \"$(boot_id)\" ] && [ -n \"$pid\" ] && kill -0 \"$pid\" 2>/dev/null \\\n && grep -qa orca-memguard \"/proc/$pid/cmdline\" 2>/dev/null\n}\n\ncase \"${1:-}\" in\n start)\n [ \"$(id -u)\" -eq 0 ] || { echo 'orca-memguard: needs root' >&2; exit 1; }\n running && exit 0\n mkdir -p \"$RUN\"\n setsid nohup \"$0\" run /dev/null 2>>\"$RUN/memguard.log\" &\n exit 0 ;;\n run) run ;;\n sweep) sweep ;;\n victim) choose_victim && printf '%s %s %s\\n' \"$VICTIM\" \"$((VICTIM_RSS * 4))\" \"$(proc_name \"$VICTIM\")\" ;;\n release-swap) release_swap ;;\n *) echo 'usage: orca-memguard start|run|sweep|victim|release-swap' >&2; exit 2 ;;\nesac\n","orca-sandbox-env":"#!/usr/bin/env bash\n# Writes this session's secret env where new shells and agent launches read it (orca-session-env.sh).\n# Input: ORCA_SECRET_ENV (`NAME=` lines) from the control plane, at boot (orca-sandbox-start)\n# and whenever a secret changes (POST /v1/sandboxes/:id/env/refresh). The file lives on tmpfs only:\n# never on the sandbox disk, so the stop snapshot never carries it. Prints {\"names\":N} on success.\n# Also keeps Codex pointed at a configured OpenAI-compatible provider (OPENAI_BASE_URL), since Codex\n# does not read that variable: a managed block in ~/.codex/config.toml naming only the env var.\nset -euo pipefail\numask 077\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\n# ORCA_SESSION_ENV_DIR: tests only (a scratch dir off tmpfs); the control plane never sets it.\ndir=\"${ORCA_SESSION_ENV_DIR:-/dev/shm/orca-env-$(id -u)}\"\nif [ -z \"${ORCA_SESSION_ENV_DIR:-}\" ] && [ \"$(stat -f -c %T /dev/shm 2>/dev/null || true)\" != tmpfs ]; then\n # No memory-only place to keep it: refuse rather than write secrets to disk.\n echo 'no tmpfs for the session env' >&2\n exit 3\nfi\nmkdir -p \"$dir\"\nchmod 700 \"$dir\"\n# Writes are ordered by the control plane's resolve time: an older refresh that lost a race is dropped.\ngeneration=\"${ORCA_ENV_GENERATION:-0}\"\ncase \"$generation\" in '' | *[!0-9]*) generation=0 ;; esac\ncurrent=\"$(cat \"$dir/generation\" 2>/dev/null || echo 0)\"\ncase \"$current\" in '' | *[!0-9]*) current=0 ;; esac\nif [ \"$generation\" -lt \"$current\" ]; then\n printf '{\"stale\":true}\\n'\n exit 0\nfi\ntmp=\"$(mktemp \"$dir/.session.env.XXXXXX\")\"\ncount=0\nopenai_base_url=''\nopenai_model=''\nanthropic_model=''\nanthropic_key_tail=''\nanthropic_key_scrub=''\ngateway_key=''\ngemini_key=''\ncodex_placeholder=''\nsign_in_inside=''\nwhile IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\"\n # Not for shells: the Codex account placeholder becomes ~/.codex/auth.json below.\n # Not for shells: the agents the person signs in inside this workspace (e.g. `claude,codex`).\n if [ \"$name\" = ORCA_SIGN_IN_INSIDE ]; then\n sign_in_inside=\"$(printf '%s' \"$b64\" | base64 -d)\"\n case \"$sign_in_inside\" in *[!a-z,]*) sign_in_inside='' ;; esac\n fi\n if [ \"$name\" = ORCA_CODEX_AUTH_PLACEHOLDER ]; then\n codex_placeholder=\"$(printf '%s' \"$b64\" | base64 -d)\"\n case \"$codex_placeholder\" in *[!A-Za-z0-9._-]*) codex_placeholder='' ;; esac\n fi\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n # Values stay base64 in the file; the shell hook decodes them.\n printf '%s=%s\\n' \"$name\" \"$b64\" >>\"$tmp\"\n count=$((count + 1))\n case \"$name\" in\n OPENAI_BASE_URL) openai_base_url=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n OPENAI_MODEL) openai_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n ANTHROPIC_MODEL) anthropic_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n AI_GATEWAY_API_KEY) gateway_key=1 ;;\n GEMINI_API_KEY | GOOGLE_API_KEY) gemini_key=\"${gemini_key:-gemini-api-key}\" ;;\n GOOGLE_GENAI_USE_VERTEXAI) case \"$(printf '%s' \"$b64\" | base64 -d)\" in true | 1) gemini_key=vertex-ai ;; esac ;;\n # Claude Code asks once per key whether to use ANTHROPIC_API_KEY; it remembers the last 20 chars.\n # G9: pre-approve only an Orca placeholder. A real key (placeholders off) is never written, not even its\n # tail: Claude Code asks once instead, and a tail an older image wrote is scrubbed.\n ANTHROPIC_API_KEY)\n case \"$(printf '%s' \"$b64\" | base64 -d)\" in\n orca-ph-*) anthropic_key_tail=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n *) anthropic_key_scrub=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n esac\n ;;\n esac\ndone < <(printf '%s\\n' \"${ORCA_SECRET_ENV:-}\")\nmv -f \"$tmp\" \"$dir/session.env\"\nprintf '%s' \"$generation\" >\"$dir/generation\"\n\n# ---- Codex: trust the workspace and use the configured provider (no secret values) ----\nPROJECT=/vercel/sandbox/project\ncodex_config=\"$HOME/.codex/config.toml\"\ntoml_string() { # TOML basic string; the control plane only accepts https URLs and plain model ids\n local value=\"${1//\\\\/\\\\\\\\}\"\n printf '\"%s\"' \"${value//\\\"/\\\\\\\"}\"\n}\nstrip_managed() { # drop the managed blocks and the blank lines written before them (no growth per refresh)\n awk '/^# >>> orca-cloud managed/{skip=1; blank=\"\"} skip{if (/^# <<< orca-cloud managed/) skip=0; next}\n /^[[:space:]]*$/{blank=blank $0 \"\\n\"; next} {printf \"%s\", blank; blank=\"\"; print}' \"$1\"\n}\n# Always managed: an agent launched from the phone or the API has no one to answer Codex's\n# \"trust this folder?\" screen, so the workspace project is trusted up front.\nif true; then\n mkdir -p \"$HOME/.codex\"\n user_part=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n if [ -f \"$codex_config\" ]; then strip_managed \"$codex_config\" >\"$user_part\"; fi\n next=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n openai_host=\"${openai_base_url#https://}\"\n openai_host=\"${openai_host%%/*}\"\n custom_provider=''\n if [ -n \"$openai_base_url\" ] && [ \"$openai_host\" != api.openai.com ]; then custom_provider=1; fi\n # Top-level keys must precede every table; each is skipped when the user already set it.\n head_keys=\"$(awk '/^\\[/{exit} {print}' \"$user_part\")\"\n has_key() { grep -Eq \"^[[:space:]]*$1[[:space:]]*=\" <<<\"$head_keys\"; }\n {\n printf '# >>> orca-cloud managed (Orca Cloud; edit in Orca settings)\\n'\n # The sandbox is the isolation boundary: Codex's own bwrap sandbox can't start in it (\"Unexpected\n # capabilities\"), and a prompt delivered from the phone or the API has no one to approve commands.\n has_key sandbox_mode || printf 'sandbox_mode = \"danger-full-access\"\\n'\n has_key approval_policy || printf 'approval_policy = \"never\"\\n'\n if [ -n \"$custom_provider\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_cloud\"\\n'\n if [ -n \"$openai_model\" ] && ! has_key model; then\n printf 'model = %s\\n' \"$(toml_string \"$openai_model\")\"\n fi\n elif [ -n \"$codex_placeholder\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_chatgpt\"\\n'\n fi\n printf '# <<< orca-cloud managed\\n'\n cat \"$user_part\"\n if [ -n \"$custom_provider\" ]; then\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_cloud]\\nname = \"Orca Cloud\"\\n'\n printf 'base_url = %s\\nenv_key = \"OPENAI_API_KEY\"\\nwire_api = \"responses\"\\n' \"$(toml_string \"$openai_base_url\")\"\n printf '# <<< orca-cloud managed\\n'\n elif [ -n \"$codex_placeholder\" ]; then\n # Codex via the Orca account: the ChatGPT backend over HTTPS. Its default Responses WebSocket can't\n # pass the egress proxy, where the placeholder becomes the real token (found live, Codex 0.166).\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_chatgpt]\\nname = \"OpenAI\"\\n'\n printf 'base_url = \"https://chatgpt.com/backend-api/codex\"\\nwire_api = \"responses\"\\nrequires_openai_auth = true\\nsupports_websockets = false\\n'\n printf '# <<< orca-cloud managed\\n'\n # CODEX-PS-CALLS: Codex's plugin catalog made ~170 chatgpt.com calls per session start through the\n # account swap. Off unless the person's own config says otherwise (a [features] table of theirs is\n # left alone: TOML can't define it twice).\n if ! grep -Eq '^[[:space:]]*(\\[features\\]|features[.[:space:]=])' \"$user_part\"; then\n printf '\\n# >>> orca-cloud managed features\\n[features]\\nplugins = false\\n# <<< orca-cloud managed\\n'\n fi\n fi\n } >\"$next\"\n if ! grep -qF \"[projects.\\\"$PROJECT\\\"]\" \"$user_part\"; then\n printf '\\n# >>> orca-cloud managed trust\\n[projects.\"%s\"]\\ntrust_level = \"trusted\"\\n# <<< orca-cloud managed\\n' \"$PROJECT\" >>\"$next\"\n fi\n chmod 600 \"$next\"\n mv -f \"$next\" \"$codex_config\"\n rm -f \"$user_part\"\nfi\n# CODEX-WS-OFF: the same provider at the system layer (/etc/codex/config.toml), so Codex keeps HTTPS for it\n# even when the person's own config drops ours: header-swapping firewalls refuse WebSocket upgrades\n# (Codex then retries for ~10 s per session). Best effort: no passwordless sudo, no system file.\nif [ -n \"$codex_placeholder\" ] && [ -z \"$custom_provider\" ]; then\n sys_cfg='# >>> orca-cloud managed (Orca Cloud)\\n[model_providers.orca_chatgpt]\\nname = \"OpenAI\"\\nbase_url = \"https://chatgpt.com/backend-api/codex\"\\nwire_api = \"responses\"\\nrequires_openai_auth = true\\nsupports_websockets = false\\n# <<< orca-cloud managed\\n'\n if [ -n \"${ORCA_CODEX_SYSTEM_CONFIG:-}\" ]; then\n # Tests: a scratch path, written directly.\n mkdir -p \"$(dirname \"$ORCA_CODEX_SYSTEM_CONFIG\")\" && printf \"$sys_cfg\" >\"$ORCA_CODEX_SYSTEM_CONFIG\"\n else\n # shellcheck disable=SC2059\n printf \"$sys_cfg\" | sudo -n sh -c 'mkdir -p /etc/codex && cat >/etc/codex/config.toml.orca-new && mv -f /etc/codex/config.toml.orca-new /etc/codex/config.toml' 2>/dev/null || true\n fi\nfi\n# ---- Codex via the person's Orca account (contract D11): a placeholder ChatGPT login, no refresh token.\n# The egress proxy swaps the real access token on chatgpt.com; the real tokens never reach this VM. The\n# marker remembers which placeholder Orca wrote (a clone gets its own), so a login of the person's own\n# (kill-switch fallback, or `codex login` run here) is set aside while the account applies and put back after.\ncodex_auth=\"$HOME/.codex/auth.json\"\ncodex_saved=\"$HOME/.codex/auth.json.orca-saved\"\ncodex_marker=\"$HOME/.codex/.orca-account-placeholder\"\ncodex_ours=''\n# Ours: the marker's placeholder, or any Orca placeholder (all end in `.orca-placeholder`; a real token never does).\nif [ -f \"$codex_auth\" ] && { { [ -f \"$codex_marker\" ] && grep -qF \"\\\"$(cat \"$codex_marker\")\\\"\" \"$codex_auth\"; } || grep -q '\\.orca-placeholder\"' \"$codex_auth\"; }; then\n codex_ours=1\nfi\nif [ -n \"$codex_placeholder\" ]; then\n mkdir -p \"$HOME/.codex\"\n if [ -f \"$codex_auth\" ] && [ -z \"$codex_ours\" ]; then\n # Never overwrite a login already set aside: a second one gets its own name.\n if [ -e \"$codex_saved\" ]; then mv -f \"$codex_auth\" \"$codex_saved.$(date -u +%Y%m%d%H%M%S)\"; else mv -f \"$codex_auth\" \"$codex_saved\"; fi\n fi\n # Marker first: a run cut short after the swap still recognises the file as Orca's.\n printf '%s' \"$codex_placeholder\" >\"$codex_marker\"\n codex_tmp=\"$(mktemp \"$HOME/.codex/.auth.XXXXXX\")\"\n # last_refresh far ahead: Codex never refreshes this login itself (Orca refreshes the real one centrally).\n printf '{\\n \"OPENAI_API_KEY\": null,\\n \"tokens\": {\\n \"id_token\": \"%s\",\\n \"access_token\": \"%s\",\\n \"refresh_token\": \"\",\\n \"account_id\": null\\n },\\n \"last_refresh\": \"2099-01-01T00:00:00Z\"\\n}\\n' \\\n \"$codex_placeholder\" \"$codex_placeholder\" >\"$codex_tmp\"\n chmod 600 \"$codex_tmp\"\n mv -f \"$codex_tmp\" \"$codex_auth\"\nelif [ -f \"$codex_marker\" ] || [ -n \"$codex_ours\" ]; then\n if [ -n \"$codex_ours\" ]; then rm -f \"$codex_auth\"; fi\n rm -f \"$codex_marker\"\n if [ -f \"$codex_saved\" ] && [ ! -f \"$codex_auth\" ]; then mv -f \"$codex_saved\" \"$codex_auth\"; fi\nfi\n# ---- Claude Code, Gemini CLI, Cursor agent, Copilot CLI, OpenCode: first-run screens answered once\n# (Claude: theme picker, folder trust, bypass-mode warning, the \"use this API key?\" question; others:\n# folder trust, auth-method picker, self-update). A prompt delivered from the phone or the API has no one to click\n# through them, and the agent would sit there doing nothing. Merges; never touches credentials.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nif [ -n \"$node_bin\" ]; then\n claude_inside=''\n case \",$sign_in_inside,\" in *,claude,*) claude_inside=1 ;; esac\n ORCA_CLAUDE_INSIDE=\"$claude_inside\" ORCA_PROJECT=\"$PROJECT\" ORCA_KEY_TAIL=\"$anthropic_key_tail\" ORCA_KEY_SCRUB=\"$anthropic_key_scrub\" ORCA_GEMINI_KEY=\"$gemini_key\" \\\n ORCA_GATEWAY_MODEL=\"${gateway_key:+${anthropic_model:-$openai_model}}\" \"$node_bin\" -e '\nconst fs = require(\"fs\"), path = require(\"path\"), os = require(\"os\")\nconst home = os.homedir()\nconst readJson = (file) => { try { const v = JSON.parse(fs.readFileSync(file, \"utf8\")); return v && typeof v === \"object\" && !Array.isArray(v) ? v : {} } catch { return {} } }\nconst write = (file, value) => {\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\nconst claudeFile = path.join(process.env.CLAUDE_CONFIG_DIR || home, \".claude.json\")\nconst c = readJson(claudeFile)\nconst before = JSON.stringify(c)\n// Signed in inside this workspace and no login here yet: leave first-run onboarding to Claude, so it opens\n// on its own sign-in screens instead of \"Not logged in\". Once a login exists, onboarding is done as usual.\nconst claudeCredentials = path.join(process.env.CLAUDE_CONFIG_DIR || path.join(home, \".claude\"), \".credentials.json\")\nif (process.env.ORCA_CLAUDE_INSIDE === \"1\" && !fs.existsSync(claudeCredentials)) delete c.hasCompletedOnboarding\nelse c.hasCompletedOnboarding = true\nc.theme = c.theme || \"dark\"\nc.bypassPermissionsModeAccepted = true\nc.projects = c.projects && typeof c.projects === \"object\" ? c.projects : {}\nconst p = process.env.ORCA_PROJECT\nc.projects[p] = { ...(c.projects[p] || {}), hasTrustDialogAccepted: true, hasCompletedProjectOnboarding: true }\nconst tail = process.env.ORCA_KEY_TAIL\nconst scrub = process.env.ORCA_KEY_SCRUB\nif (scrub && c.customApiKeyResponses && typeof c.customApiKeyResponses === \"object\") {\n const r = c.customApiKeyResponses\n for (const list of [\"approved\", \"rejected\"]) if (Array.isArray(r[list])) r[list] = r[list].filter((t) => t !== scrub)\n}\nif (tail) {\n const r = c.customApiKeyResponses && typeof c.customApiKeyResponses === \"object\" ? c.customApiKeyResponses : {}\n const approved = Array.isArray(r.approved) ? r.approved : []\n const rejected = Array.isArray(r.rejected) ? r.rejected.filter((t) => t !== tail) : []\n c.customApiKeyResponses = { ...r, approved: approved.includes(tail) ? approved : [...approved, tail], rejected }\n}\nif (JSON.stringify(c) !== before) write(claudeFile, c)\nconst settingsFile = path.join(home, \".claude\", \"settings.json\")\nconst s = readJson(settingsFile)\nif (s.skipDangerousModePermissionPrompt !== true) write(settingsFile, { ...s, skipDangerousModePermissionPrompt: true })\n\n// Each block below only fills in what is unset and leaves a file it cannot parse alone.\nconst readStrict = (file) => { try { return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, \"utf8\")) : {} } catch { return null } }\nconst isObject = (v) => v !== null && typeof v === \"object\" && !Array.isArray(v)\nconst section = (o, key) => (isObject(o[key]) ? o[key] : (o[key] = {}))\n\n// Gemini CLI: folder trust and the auth-method picker (only when a Gemini key is configured; a\n// Google sign-in picks its own method), no self-update, no usage stats (its host is not on the\n// egress allowlist, so every send would fail).\nconst geminiTrustFile = path.join(home, \".gemini\", \"trustedFolders.json\")\nconst geminiTrust = readStrict(geminiTrustFile)\nif (isObject(geminiTrust) && !geminiTrust[p]) write(geminiTrustFile, { ...geminiTrust, [p]: \"TRUST_FOLDER\" })\nconst geminiSettingsFile = path.join(home, \".gemini\", \"settings.json\")\nconst g = readStrict(geminiSettingsFile)\nif (isObject(g)) {\n const gBefore = JSON.stringify(g)\n const general = section(g, \"general\")\n general.disableAutoUpdate ??= true\n general.disableUpdateNag ??= true\n section(g, \"privacy\").usageStatisticsEnabled ??= false\n // gemini-api-key or vertex-ai (GOOGLE_GENAI_USE_VERTEXAI=true with an API key): headless runs\n // refuse to start without a method (\"Invalid auth method selected\").\n if (process.env.ORCA_GEMINI_KEY) section(section(g, \"security\"), \"auth\").selectedType ??= process.env.ORCA_GEMINI_KEY\n if (JSON.stringify(g) !== gBefore) write(geminiSettingsFile, g)\n}\n\n// Cursor agent: trust the workspace (cursor-agent keys trust by a slug of the path) and pin the\n// release channel to \"static\", which turns off its background self-update.\nconst cursorTrust = path.join(home, \".cursor\", \"projects\", p.replace(/^\\/+/, \"\").replace(/[^A-Za-z0-9]+/g, \"-\"), \".workspace-trusted\")\nif (!fs.existsSync(cursorTrust)) {\n fs.mkdirSync(path.dirname(cursorTrust), { recursive: true, mode: 0o700 })\n fs.writeFileSync(cursorTrust, JSON.stringify({ trustedAt: new Date().toISOString(), workspacePath: p }, null, 2) + \"\\n\", { mode: 0o600 })\n}\nconst cursorConfigFile = path.join(home, \".cursor\", \"cli-config.json\")\nconst cc = readStrict(cursorConfigFile)\nif (isObject(cc) && cc.channel === undefined) write(cursorConfigFile, { version: 1, ...cc, channel: \"static\" })\n\n// GitHub Copilot CLI: trusted folders live in ~/.copilot/config.json, which Copilot prefixes with\n// \"//\" comment lines; keep them.\nconst copilotFile = path.join(home, \".copilot\", \"config.json\")\nlet copilotHead = \"\"\nlet co = {}\ntry {\n const raw = fs.existsSync(copilotFile) ? fs.readFileSync(copilotFile, \"utf8\") : \"\"\n const lines = raw.split(\"\\n\")\n let i = 0\n while (i < lines.length && /^\\s*\\/\\//.test(lines[i])) i++\n copilotHead = lines.slice(0, i).map((l) => l + \"\\n\").join(\"\")\n const body = lines.slice(i).join(\"\\n\").trim()\n co = body ? JSON.parse(body) : {}\n} catch { co = null }\nif (isObject(co)) {\n const folders = Array.isArray(co.trustedFolders) ? co.trustedFolders : []\n if (!folders.includes(p)) {\n fs.mkdirSync(path.dirname(copilotFile), { recursive: true, mode: 0o700 })\n const tmp = `${copilotFile}.orca-${process.pid}`\n fs.writeFileSync(tmp, copilotHead + JSON.stringify({ ...co, trustedFolders: [...folders, p] }, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, copilotFile)\n }\n}\n\n// OpenCode: with the AI Gateway preset and a model secret (ANTHROPIC_MODEL, else OPENAI_MODEL), use\n// that model through the gateway unless the user picked one. A ledger remembers what Orca wrote, so a\n// changed model secret updates it and a model the user set is never touched.\nconst ocDir = path.join(home, \".config\", \"opencode\")\nconst ocFile = path.join(ocDir, \"opencode.json\")\nconst ocLedger = path.join(ocDir, \".orca-managed-model\")\nconst managedModel = process.env.ORCA_GATEWAY_MODEL ? `vercel/${process.env.ORCA_GATEWAY_MODEL}` : \"\"\nconst oc = readStrict(ocFile)\nlet jsoncHasModel = false\ntry { jsoncHasModel = /\"model\"\\s*:/.test(fs.readFileSync(path.join(ocDir, \"opencode.jsonc\"), \"utf8\")) } catch {}\nif (isObject(oc) && !jsoncHasModel) {\n let ours = \"\"\n try { ours = fs.readFileSync(ocLedger, \"utf8\").trim() } catch {}\n const userModel = typeof oc.model === \"string\" && oc.model !== ours\n if (!userModel && (oc.model ?? \"\") !== managedModel) {\n const next = { $schema: \"https://opencode.ai/config.json\", ...oc }\n if (managedModel) next.model = managedModel\n else delete next.model\n write(ocFile, next)\n }\n if (!userModel) {\n if (managedModel) fs.writeFileSync(ocLedger, managedModel + \"\\n\", { mode: 0o600 })\n else fs.rmSync(ocLedger, { force: true })\n }\n}\n\n// OpenCode: two built-in providers cannot work in Orca Cloud, and with no other credential OpenCode\n// picks one and fails (\"Authorization header is badly formatted\" / opencode.ai unreachable) instead\n// of showing \"Connect a provider\". GitHub Copilot reads GITHUB_TOKEN, which here is the stand-in for the\n// GitHub App token of the workspace, never a Copilot token; OpenCode Zen needs opencode.ai, which is not on the\n// egress allowlist. Both stay off unless the user connected them in OpenCode itself (auth.json).\nconst ocAuth = readStrict(path.join(process.env.XDG_DATA_HOME || path.join(home, \".local\", \"share\"), \"opencode\", \"auth.json\"))\nconst connected = new Set(isObject(ocAuth) ? Object.keys(ocAuth) : [])\nconst ocDisabledLedger = path.join(ocDir, \".orca-managed-disabled-providers\")\nconst ocNow = readStrict(ocFile)\nif (isObject(ocNow) && !/\"disabled_providers\"\\s*:/.test((() => { try { return fs.readFileSync(path.join(ocDir, \"opencode.jsonc\"), \"utf8\") } catch { return \"\" } })())) {\n let ours = []\n try { ours = fs.readFileSync(ocDisabledLedger, \"utf8\").split(\"\\n\").filter(Boolean) } catch {}\n const userList = (Array.isArray(ocNow.disabled_providers) ? ocNow.disabled_providers : []).filter((id) => typeof id === \"string\" && !ours.includes(id))\n const managed = [\"github-copilot\", \"opencode\"].filter((id) => !connected.has(id) && !userList.includes(id))\n const next = [...userList, ...managed]\n const before = JSON.stringify(ocNow.disabled_providers ?? [])\n if (JSON.stringify(next) !== before) {\n const updated = { $schema: \"https://opencode.ai/config.json\", ...ocNow }\n if (next.length > 0) updated.disabled_providers = next\n else delete updated.disabled_providers\n write(ocFile, updated)\n }\n if (managed.length > 0) fs.writeFileSync(ocDisabledLedger, managed.join(\"\\n\") + \"\\n\", { mode: 0o600 })\n else fs.rmSync(ocDisabledLedger, { force: true })\n}\n' || echo 'agent first-run state not seeded' >&2\nfi\nprintf '{\"names\":%d}\\n' \"$count\"\n","orca-session-env.sh":"# Orca Cloud: sourced by every new bash/zsh (via /etc/profile.d) so terminals and agents started\n# after a secret edit get the current values with no restart. The file is written by\n# /opt/orca/bin/orca-sandbox-env on tmpfs; names it no longer lists are unset. Cloud secrets win\n# over same-named values already in the environment.\n__orca_env_file=\"/dev/shm/orca-env-$(id -u 2>/dev/null)/session.env\"\nif [ -r \"$__orca_env_file\" ]; then\n # $(...) word-splits in both bash and zsh.\n for __orca_n in $(printf '%s' \"${ORCA_SESSION_ENV_NAMES-}\"); do\n unset \"$__orca_n\" 2>/dev/null || true\n done\n __orca_names=''\n while IFS= read -r __orca_line || [ -n \"$__orca_line\" ]; do\n __orca_n=\"${__orca_line%%=*}\"\n case \"$__orca_n\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n export \"$__orca_n=$(printf '%s' \"${__orca_line#*=}\" | base64 -d 2>/dev/null)\"\n __orca_names=\"$__orca_names $__orca_n\"\n done <\"$__orca_env_file\"\n export ORCA_SESSION_ENV_NAMES=\"${__orca_names# }\"\nfi\n# Default branch of the cloud workspace repo, once its first-boot clone exists (computed once per shell tree).\nif [ -n \"${ORCA_WORKSPACE_PATH-}\" ] && [ -z \"${ORCA_DEFAULT_BRANCH-}\" ]; then\n __orca_branch=\"$(git -C \"$ORCA_WORKSPACE_PATH\" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)\"\n if [ -n \"$__orca_branch\" ]; then\n export ORCA_DEFAULT_BRANCH=\"${__orca_branch#origin/}\" CONDUCTOR_DEFAULT_BRANCH=\"${__orca_branch#origin/}\"\n fi\nfi\n# CR-cmd-quiet: Orca's staged agent launch (` . '/tmp/orca-launch-….sh'`) stays out of zsh history.\n# zsh records a line before running it, so the hook must exist first; the staged script itself\n# drops the line from bash's history. eval: bash parses this file too.\nif [ -n \"${ZSH_VERSION-}\" ]; then\n eval '__orca_skip_launch_history() { [[ $1 == *orca-launch-* ]] && return 1; return 0 }\n (( ${zshaddhistory_functions[(Ie)__orca_skip_launch_history]} )) || zshaddhistory_functions+=(__orca_skip_launch_history)'\nfi\nunset __orca_env_file __orca_line __orca_n __orca_names __orca_branch\n","orca-env":"#!/usr/bin/env bash\n# Prints shell lines that bring the current shell up to date with this session's cloud env (secrets\n# saved after the shell started): eval \"$(orca-env)\" or, in fish: orca-env --fish | source\n# Reads /dev/shm/orca-env-/session.env (written by orca-sandbox-env, `NAME=` lines) and\n# prints an export for each name, plus an unset for each name in $ORCA_SESSION_ENV_NAMES that is gone.\n# Never writes a file. Values are single-quoted, so quotes, newlines and $ in them stay literal.\nset -euo pipefail\nfish=''\ncase \"${1-}\" in\n '') ;;\n --fish) fish=1 ;;\n -h | --help)\n printf 'usage: eval \"$(orca-env)\" (fish: orca-env --fish | source)\\n'\n exit 0\n ;;\n *)\n printf 'orca-env: unknown option %s\\n' \"$1\" >&2\n exit 2\n ;;\nesac\n# ORCA_SESSION_ENV_FILE is for tests; secrets can't set ORCA_* names.\nfile=\"${ORCA_SESSION_ENV_FILE:-/dev/shm/orca-env-$(id -u)/session.env}\"\nset -f # names are split below, never globbed\n# Not written yet (or not a cloud VM): nothing to change, like the shell hook.\n[ -r \"$file\" ] || exit 0\n\n# 'it'\\''s' for POSIX shells; fish single quotes escape only \\ and '.\nquote() {\n local v=\"$1\"\n if [ -n \"$fish\" ]; then\n v=\"${v//\\\\/\\\\\\\\}\"\n v=\"${v//\\'/\\\\\\'}\"\n printf \"'%s'\" \"$v\"\n else\n printf \"'%s'\" \"${v//\\'/\\'\\\\\\'\\'}\"\n fi\n}\n\n# The control plane's reserved names and prefixes (cloud/apps/sandbox-control/src/secrets.ts; a test\n# keeps this in sync): a session file never sets what would hijack the shell or Orca's own processes.\nskip_name() {\n case \"$1\" in\n '' | *[!A-Z0-9_]* | [0-9]*) return 0 ;;\n LD_* | DYLD_* | ORCA_* | VERCEL_* | BASH_FUNC_* | GIT_CONFIG*) return 0 ;;\n PATH | HOME | USER | LOGNAME | SHELL | PWD | OLDPWD | LANG | TERM | TMPDIR | IFS | ENV | \\\n BASH_ENV | PS4 | PROMPT_COMMAND | SHELLOPTS | BASHOPTS | NODE_OPTIONS | NODE_PATH | \\\n NODE_EXTRA_CA_CERTS | NODE_TLS_REJECT_UNAUTHORIZED | SSL_CERT_FILE | SSL_CERT_DIR | \\\n CURL_CA_BUNDLE | REQUESTS_CA_BUNDLE | HTTP_PROXY | HTTPS_PROXY | ALL_PROXY | NO_PROXY | \\\n PYTHONPATH | PYTHONSTARTUP | PERL5OPT | RUBYOPT | JAVA_TOOL_OPTIONS | GIT_SSH | \\\n GIT_SSH_COMMAND | GIT_ASKPASS | GIT_EXEC_PATH | GIT_PROXY_COMMAND | SSH_AUTH_SOCK | \\\n GH_TOKEN | GITHUB_TOKEN) return 0 ;;\n # CLAUDE_CODE_OAUTH_TOKEN is reserved for users but set by the control plane itself: only ever the\n # Orca-account placeholder (contract D10), never a stored value.\n esac\n return 1\n}\n\nnames=' '\nwhile IFS= read -r line || [ -n \"$line\" ]; do\n name=\"${line%%=*}\"\n skip_name \"$name\" && continue\n # $(...) drops trailing newlines; the x keeps them.\n value=\"$(printf '%s' \"${line#*=}\" | base64 -d 2>/dev/null; printf x)\"\n value=\"${value%x}\"\n if [ -n \"$fish\" ]; then\n printf 'set -gx %s %s\\n' \"$name\" \"$(quote \"$value\")\"\n else\n printf 'export %s=%s\\n' \"$name\" \"$(quote \"$value\")\"\n fi\n names=\"$names$name \"\ndone <\"$file\"\nfor name in ${ORCA_SESSION_ENV_NAMES-}; do\n skip_name \"$name\" && continue\n case \"$names\" in *\" $name \"*) continue ;; esac\n if [ -n \"$fish\" ]; then\n printf 'set -e %s\\n' \"$name\"\n else\n printf 'unset %s\\n' \"$name\"\n fi\ndone\nnames=\"${names# }\"\nnames=\"${names% }\"\nif [ -n \"$fish\" ]; then\n printf 'set -gx ORCA_SESSION_ENV_NAMES %s\\n' \"$(quote \"$names\")\"\nelse\n printf 'export ORCA_SESSION_ENV_NAMES=%s\\n' \"$(quote \"$names\")\"\nfi\n","orca-egress-probe":"#!/usr/bin/env bash\n# Bounded Node fetch against each credential host. Vercel transform rules have made undici hang on\n# response bodies (no content-length / transfer-encoding); report it instead of letting agents hang.\n# Prints one JSON line: {\"host\":\"api.github.com\",\"status\":\"ok\"|\"egress_framing_hang\"|\"error\"}.\nset -euo pipefail\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\nfor host in \"$@\"; do\n \"$node\" -e '\n const host = process.argv[1]\n const timer = setTimeout(() => { console.log(JSON.stringify({ host, status: \"egress_framing_hang\" })); process.exit(0) }, 8000)\n fetch(`https://${host}/`, { headers: { authorization: process.env.ORCA_PROBE_AUTHORIZATION ?? \"\" } })\n .then((r) => r.arrayBuffer())\n .then(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"ok\" })) })\n .catch(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"error\" })) })\n ' \"$host\"\ndone\n","orca-image-wipe":"#!/usr/bin/env bash\n# Runs last before the golden snapshot. Every sandbox cloned from the image must start without an\n# orcad identity, device registry, agent sign-in or shell history (clone-safe identity, risk #1).\nset -euo pipefail\npkill -f orcad-server.js 2>/dev/null || true\nfor path in \\\n \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\" \"$HOME/.orca-desktop\" \"$HOME/.config/orca\" \"$HOME/.config/orca-dev\" \\\n \"$HOME/.claude\" \"$HOME/.claude.json\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.gemini\" \\\n \"$HOME/.local/share/opencode\" \"$HOME/.config/opencode\" \"$HOME/.cursor\" \"$HOME/.config/cursor\" \\\n \"$HOME/.local/share/cursor-agent\" \"$HOME/.copilot\" \"$HOME/.npm\" \"$HOME/.cache\" \"$HOME/.config/google-chrome\" \"$HOME/.bash_history\" \\\n /vercel/sandbox/project; do\n rm -rf -- \"$path\"\ndone\nsudo rm -rf /tmp/* /var/tmp/* 2>/dev/null || true\nfor leftover in \"$HOME/.orcad-data\" \"$HOME/.claude\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.cursor\" \"$HOME/.copilot\" \"$HOME/.gemini\"; do\n if [ -e \"$leftover\" ]; then\n echo \"identity survived wipe: $leftover\" >&2\n exit 1\n fi\ndone\necho '{\"wiped\":true}'\n","orca-agent-signout":"#!/usr/bin/env bash\n# Signs every agent out on this sandbox before Orca deletes it (A9): each agent's own logout, then\n# its credential files. Covers logins made inside the sandbox (the kill-switch fallback path).\n# Never fails: the sandbox is deleted next whatever happens. Values are never printed.\nset -u\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\nexport PATH=\"/opt/orca/tools/bin:$HOME/.local/bin:$HOME/.npm-global/bin:/usr/local/bin:/usr/bin:/bin:/opt/orca/bin:${PATH:-}\"\nclaude_dir=\"${CLAUDE_CONFIG_DIR:-$HOME/.claude}\"\nclaude_json=\"${CLAUDE_CONFIG_DIR:-$HOME}/.claude.json\"\ncodex_dir=\"${CODEX_HOME:-$HOME/.codex}\"\n\nlogged_out=0\n# Each logout gets a few seconds; a hung CLI must not hold up the delete.\nif command -v claude >/dev/null 2>&1 && timeout 8 claude auth logout /dev/null 2>&1; then\n logged_out=$((logged_out + 1))\nfi\nif command -v codex >/dev/null 2>&1 && timeout 8 codex logout /dev/null 2>&1; then\n logged_out=$((logged_out + 1))\nfi\n\n# The files go whether or not a logout ran: an older CLI, a missing binary or no network leaves them.\nrm -f -- \"$claude_dir\"/.credentials* \"$HOME/.claude\"/.credentials* \"$codex_dir/auth.json\" \"$HOME/.codex/auth.json\" 2>/dev/null\n# Orca-managed Codex homes keep their own auth.json under orcad's data dir.\nif [ -d \"$HOME/.orcad-data\" ]; then\n find \"$HOME/.orcad-data\" -path '*codex*' -type f -name auth.json -delete 2>/dev/null\nfi\n# ~/.claude.json keeps settings Orca wrote (onboarding, trust); only the sign-in fields go.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nfor file in \"$claude_json\" \"$HOME/.claude.json\"; do\n [ -f \"$file\" ] || continue\n if [ -n \"$node_bin\" ]; then\n ORCA_FILE=\"$file\" \"$node_bin\" -e '\nconst fs = require(\"fs\")\nconst file = process.env.ORCA_FILE\nlet c\ntry { c = JSON.parse(fs.readFileSync(file, \"utf8\")) } catch { process.exit(2) }\nif (!c || typeof c !== \"object\" || Array.isArray(c)) process.exit(2)\nlet changed = false\nfor (const key of Object.keys(c)) {\n if (/oauth/i.test(key) || key === \"primaryApiKey\") { delete c[key]; changed = true }\n}\nif (changed) {\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(c, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\n' 2>/dev/null || rm -f -- \"$file\"\n else\n # No node to edit it safely: losing Orca's settings beats leaving a sign-in behind.\n rm -f -- \"$file\"\n fi\ndone\n\nleft=0\nfor file in \"$claude_dir\"/.credentials* \"$HOME/.claude\"/.credentials* \"$codex_dir/auth.json\" \"$HOME/.codex/auth.json\"; do\n [ -e \"$file\" ] && left=$((left + 1))\ndone\nprintf '{\"loggedOut\":%d,\"left\":%d}\\n' \"$logged_out\" \"$left\"\n","orca-share-proxy":"#!/usr/bin/env node\n// Share-link proxy for this VM. Listens on 0.0.0.0:6769 (its public *.vercel.run route) and only\n// serves requests the control plane's share gateway signed with this session's key:\n// x-orca-share: v2.....\n// A request must start before `expiresAt` (60s windows); its response or WebSocket is closed at\n// `until` (the link's expiry, at most 30 minutes out), so a revoked or expired link also loses open\n// streams. Signed requests are reverse-proxied to 127.0.0.1:: streaming both ways, no\n// buffering, WebSocket upgrades piped raw. Anything unsigned gets a bare 404.\n// Vercel closes a WebSocket on a *.vercel.run route after ~340 s with no traffic (1006). A preview\n// app's socket can sit silent that long, so once an upgrade is a WebSocket the proxy watches the app's\n// frames and, after KEEPALIVE_MS with nothing either way, sends the visitor a ping control frame\n// between two frames (never inside one). The visitor's pong reaches the app, which RFC 6455 says to\n// ignore (an unsolicited pong needs no answer).\n// The key arrives on stdin (orca-sandbox-start pipes it), so it is never in this process's\n// environment or argv; ORCA_SHARE_PROXY_KEY in the env is accepted for tests. Optional\n// ORCA_SHARE_PROXY_PORT (default 6769). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst crypto = process.getBuiltinModule('node:crypto')\nconst fs = process.getBuiltinModule('node:fs')\nconst http = process.getBuiltinModule('node:http')\nconst net = process.getBuiltinModule('node:net')\n\nconst LISTEN_PORT = Number(process.env.ORCA_SHARE_PROXY_PORT || 6769)\nconst KEY = Buffer.from((process.env.ORCA_SHARE_PROXY_KEY || fs.readFileSync(0, 'utf8')).trim(), 'base64url')\ndelete process.env.ORCA_SHARE_PROXY_KEY\n// Never proxy to the VM's sshd, orcad or this proxy itself.\n// 6080: the remote desktop (VNC behind a password) is for its owner's forward only.\nconst BLOCKED_PORTS = new Set([2222, 6080, 6768, LISTEN_PORT])\nconst MAX_SKEW_SECONDS = 300\nconst MAX_CONNECTION_SECONDS = 3600\n// Well under Vercel's ~340 s idle cut. ORCA_SHARE_PROXY_KEEPALIVE_MS is for tests.\nconst KEEPALIVE_MS = Number(process.env.ORCA_SHARE_PROXY_KEEPALIVE_MS || 30_000)\n// FIN + ping opcode, empty payload, unmasked (server to client).\nconst PING_FRAME = Buffer.from([0x89, 0x00])\nconst HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-connection', 'transfer-encoding', 'te', 'trailer', 'upgrade']\n\nif (KEY.length < 32) {\n console.error('orca-share-proxy: share proxy key missing or short')\n process.exit(2)\n}\n\n/** The target port and close-by time (ms) for a validly signed request, else null. */\nfunction verify(header, nowMs) {\n if (typeof header !== 'string') {\n return null\n }\n const match = /^v2\\.(\\d{1,5})\\.(\\d{1,12})\\.(\\d{1,12})\\.([0-9a-f]{32})\\.([A-Za-z0-9_-]{43})$/.exec(header)\n if (!match) {\n return null\n }\n const now = Math.floor(nowMs / 1000)\n const port = Number(match[1])\n const expiresAt = Number(match[2])\n const until = Number(match[3])\n if (port < 1 || port > 65535 || BLOCKED_PORTS.has(port)) {\n return null\n }\n if (expiresAt < now || expiresAt > now + MAX_SKEW_SECONDS || until <= now || until > now + MAX_CONNECTION_SECONDS) {\n return null\n }\n const signed = header.slice(0, header.lastIndexOf('.'))\n const expected = crypto.createHmac('sha256', KEY).update(signed).digest()\n const given = Buffer.from(match[5], 'base64url')\n return given.length === expected.length && crypto.timingSafeEqual(given, expected) ? { port, untilMs: until * 1000 } : null\n}\n\nfunction upstreamHeaders(raw, port) {\n const headers = { ...raw }\n const connectionTokens = String(raw.connection || '')\n .split(',')\n .map((token) => token.trim().toLowerCase())\n for (const name of [...HOP_BY_HOP, ...connectionTokens, 'x-orca-share']) {\n delete headers[name]\n }\n // Dev servers (Vite, Next) allow localhost hosts by default; the public host rides x-forwarded-host.\n headers.host = `localhost:${port}`\n return headers\n}\n\nfunction refuse(res) {\n res.writeHead(404, { 'content-type': 'text/plain', 'cache-control': 'no-store' })\n res.end('not found')\n}\n\n/**\n * Follows the app's WebSocket frames (server to client: header, then payload) just closely enough to\n * know when the stream sits between two frames, where a control frame may be inserted.\n */\nfunction frameBoundaries() {\n let header = []\n let remaining = 0\n return {\n push(chunk) {\n let i = 0\n while (i < chunk.length) {\n if (remaining > 0) {\n const take = Math.min(remaining, chunk.length - i)\n remaining -= take\n i += take\n continue\n }\n header.push(chunk[i++])\n if (header.length < 2) {\n continue\n }\n const len7 = header[1] & 0x7f\n const need = 2 + (len7 === 126 ? 2 : len7 === 127 ? 8 : 0) + (header[1] & 0x80 ? 4 : 0)\n if (header.length < need) {\n continue\n }\n const bytes = Buffer.from(header)\n remaining = len7 === 126 ? bytes.readUInt16BE(2) : len7 === 127 ? Number(bytes.readBigUInt64BE(2)) : len7\n header = []\n }\n },\n atBoundary: () => header.length === 0 && remaining === 0\n }\n}\n\n/** The app's answer to the upgrade: its head is passed through; only a 101 to `websocket` gets keepalives. */\nfunction upgradeAnswer() {\n let head = Buffer.alloc(0)\n let state = 'head'\n const frames = frameBoundaries()\n return {\n push(chunk) {\n if (state === 'head') {\n head = Buffer.concat([head, chunk])\n const end = head.indexOf('\\r\\n\\r\\n')\n if (end === -1) {\n if (head.length > 64 * 1024) {\n state = 'raw'\n }\n return\n }\n const text = head.subarray(0, end).toString('latin1')\n state = /^HTTP\\/1\\.1 101/.test(text) && /^upgrade:\\s*websocket\\s*$/im.test(text) ? 'ws' : 'raw'\n chunk = head.subarray(end + 4)\n head = Buffer.alloc(0)\n }\n if (state === 'ws') {\n frames.push(chunk)\n }\n },\n canPing: () => state === 'ws' && frames.atBoundary()\n }\n}\n\n/** Ends `close` at the grant's deadline; the timer goes away with the connection. */\nfunction deadline(untilMs, close, ...emitters) {\n const timer = setTimeout(close, Math.max(0, untilMs - Date.now()))\n for (const emitter of emitters) {\n emitter.once('close', () => clearTimeout(timer))\n }\n}\n\nconst server = http.createServer((req, res) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n return refuse(res)\n }\n const { port } = grant\n const upstream = http.request(\n { host: '127.0.0.1', port, method: req.method, path: req.url, headers: upstreamHeaders(req.headers, port) },\n (answer) => {\n const headers = { ...answer.headers }\n for (const name of HOP_BY_HOP) {\n delete headers[name]\n }\n // Marks the answer as the app's, so the gateway can tell it from a route with no proxy behind it.\n headers['x-orca-share-proxy'] = '1'\n res.writeHead(answer.statusCode || 502, answer.statusMessage, headers)\n answer.pipe(res)\n }\n )\n deadline(grant.untilMs, () => {\n upstream.destroy()\n res.destroy()\n }, res)\n upstream.on('error', (error) => {\n if (res.headersSent) {\n res.destroy()\n return\n }\n // The gateway renders its own page for this; the code tells it why. Status 200 on purpose: a 5xx\n // from the VM reaches a Worker as Vercel's own 502 with our headers gone (found live).\n res.writeHead(200, { 'content-type': 'text/plain', 'x-orca-share-proxy': '1', 'x-orca-share-error': error.code === 'ECONNREFUSED' ? 'no_listener' : 'upstream_failed' })\n res.end('upstream unavailable')\n })\n req.on('aborted', () => upstream.destroy())\n req.pipe(upstream)\n})\n\nserver.on('upgrade', (req, socket, head) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n socket.end('HTTP/1.1 404 Not Found\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n return\n }\n const { port } = grant\n const headers = upstreamHeaders(req.headers, port)\n const target = net.connect(port, '127.0.0.1', () => {\n const lines = [`${req.method} ${req.url} HTTP/1.1`, `connection: upgrade`, `upgrade: ${req.headers.upgrade || 'websocket'}`]\n for (const [name, value] of Object.entries(headers)) {\n for (const item of Array.isArray(value) ? value : [value]) {\n lines.push(`${name}: ${item}`)\n }\n }\n target.write(`${lines.join('\\r\\n')}\\r\\n\\r\\n`)\n if (head && head.length > 0) {\n target.write(head)\n }\n socket.pipe(target)\n // App to visitor by hand (with backpressure) so the keepalive knows where frames start and end.\n const answer = upgradeAnswer()\n let lastTraffic = Date.now()\n socket.on('data', () => {\n lastTraffic = Date.now()\n })\n target.on('data', (chunk) => {\n lastTraffic = Date.now()\n answer.push(chunk)\n if (!socket.write(chunk)) {\n target.pause()\n socket.once('drain', () => target.resume())\n }\n })\n target.on('end', () => socket.end())\n const keepalive = setInterval(() => {\n if (Date.now() - lastTraffic >= KEEPALIVE_MS && answer.canPing() && socket.writable) {\n socket.write(PING_FRAME)\n lastTraffic = Date.now()\n }\n }, Math.max(50, Math.floor(KEEPALIVE_MS / 3)))\n socket.once('close', () => clearInterval(keepalive))\n })\n const close = () => {\n socket.destroy()\n target.destroy()\n }\n deadline(grant.untilMs, close, socket)\n target.on('error', () => {\n if (socket.writable) {\n socket.end('HTTP/1.1 200 OK\\r\\nx-orca-share-proxy: 1\\r\\nx-orca-share-error: no_listener\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n }\n close()\n })\n socket.on('error', close)\n target.on('close', () => socket.destroy())\n socket.on('close', () => target.destroy())\n})\n\nserver.keepAliveTimeout = 65_000\nserver.headersTimeout = 70_000\n// No request timeout: previews can stream (SSE, long polls) until the grant's deadline.\nserver.requestTimeout = 0\nserver.listen(LISTEN_PORT, '0.0.0.0', () => {\n console.log(`orca-share-proxy listening on ${LISTEN_PORT}`)\n})\n","orca-sshd":"#!/usr/bin/env bash\n# Starts this boot's unprivileged sshd on 127.0.0.1:2222 (idempotent). Nothing outside the VM can\n# reach that port: the desktop tunnels to it over orcad's runtime connection (`orca ssh-proxy`).\n# Key-only, single user (the sandbox user), no root. Its host key and authorized_keys live under\n# ~/.orca-sandbox/ssh on the persistent disk, so the host key stays the same across stop/resume;\n# orca-image-wipe removes that directory, so every VM cloned from the golden image makes its own.\n# Prints {\"port\":2222,\"user\":\"\",\"hostKey\":\"ssh-ed25519 AAAA...\"} on success.\nset -euo pipefail\numask 077\nOPENSSH=/opt/orca/openssh\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\nPORT=2222\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 8>\"$SSH_DIR/sshd.lock\"\nflock -w 30 8\n\nif [ ! -x \"$OPENSSH/sshd\" ]; then\n echo 'sshd is not installed in this image' >&2\n exit 3\nfi\nif [ ! -s \"$SSH_DIR/ssh_host_ed25519_key\" ]; then\n rm -f \"$SSH_DIR/ssh_host_ed25519_key\" \"$SSH_DIR/ssh_host_ed25519_key.pub\"\n ssh-keygen -q -t ed25519 -N '' -C \"orca-cloud-host\" -f \"$SSH_DIR/ssh_host_ed25519_key\"\nfi\ntouch \"$SSH_DIR/authorized_keys\"\nchmod 0600 \"$SSH_DIR/authorized_keys\"\n\n# Rewritten every start so an image update's settings apply to existing workspaces. PAM stays at\n# its compiled-in default (off): an unprivileged sshd cannot use it, and this build warns on `no`.\ncat >\"$SSH_DIR/sshd_config\" </dev/null || echo 0)\"\n# Resume reboots from disk, so a recorded pid can name a dead process or an unrelated one.\nif ! { kill -0 \"$pid\" 2>/dev/null && grep -q sshd \"/proc/$pid/cmdline\" 2>/dev/null; }; then\n rm -f \"$SSH_DIR/sshd.pid\"\n : >\"$SSH_DIR/sshd.log\"\n \"$OPENSSH/sshd\" -t -f \"$SSH_DIR/sshd_config\"\n \"$OPENSSH/sshd\" -f \"$SSH_DIR/sshd_config\" -E \"$SSH_DIR/sshd.log\"\n for _ in $(seq 1 100); do\n [ -s \"$SSH_DIR/sshd.pid\" ] && break\n sleep 0.02\n done\n [ -s \"$SSH_DIR/sshd.pid\" ] || { echo 'sshd did not start' >&2; tail -n 20 \"$SSH_DIR/sshd.log\" >&2; exit 1; }\nfi\n\nhost_key=\"$(cut -d' ' -f1-2 \"$SSH_DIR/ssh_host_ed25519_key.pub\")\"\nprintf '{\"port\":%s,\"user\":\"%s\",\"hostKey\":\"%s\"}\\n' \"$PORT\" \"$(id -un)\" \"$host_key\"\n","orca-ssh-keys":"#!/usr/bin/env bash\n# `orca-ssh-keys add|remove`: adds or removes one desktop's key in the Orca-managed authorized_keys\n# of this VM's sshd, then makes sure sshd runs. The control plane passes the key in\n# ORCA_SSH_PUBLIC_KEY (`ssh-ed25519 `), never on the command line. Keys are\n# matched by their base64 blob, so a renamed comment cannot keep a revoked key alive.\n# Prints orca-sshd's {\"port\":...,\"user\":...,\"hostKey\":...} line on success.\nset -euo pipefail\numask 077\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\naction=\"${1:-}\"\nkey=\"${ORCA_SSH_PUBLIC_KEY:-}\"\n# grep matches per line: a second line could carry key options past the check below.\ncase \"$key\" in *$'\\n'* | *$'\\r'*) echo 'invalid public key' >&2; exit 2 ;; esac\n# One line, ed25519 only, a plain comment: nothing that sshd would read as key options.\nif ! printf '%s' \"$key\" | grep -Eq '^ssh-ed25519 [A-Za-z0-9+/]{68} [A-Za-z0-9@._:+-]{1,200}$'; then\n echo 'invalid public key' >&2\n exit 2\nfi\nblob=\"$(printf '%s' \"$key\" | cut -d' ' -f2)\"\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 7>\"$SSH_DIR/keys.lock\"\nflock -w 30 7\ntouch \"$SSH_DIR/authorized_keys\"\nnext=\"$(mktemp \"$SSH_DIR/authorized_keys.XXXXXX\")\"\n# Drop the key wherever it appears (with or without options), then append it on add.\nawk -v blob=\"$blob\" '{ for (i = 1; i <= NF; i++) if ($i == blob) next; print }' \\\n \"$SSH_DIR/authorized_keys\" >\"$next\"\ncase \"$action\" in\n add) printf '%s\\n' \"$key\" >>\"$next\" ;;\n remove) ;;\n *) rm -f \"$next\"; echo 'usage: orca-ssh-keys add|remove' >&2; exit 2 ;;\nesac\nchmod 0600 \"$next\"\nmv -f \"$next\" \"$SSH_DIR/authorized_keys\"\nexec /opt/orca/bin/orca-sshd\n","orca-desktop-start":"#!/usr/bin/env bash\n# Starts the on-demand remote desktop (idempotent) and mints one connection ticket. Prints one line:\n# {\"schemaVersion\":2,\"port\":6080,\"display\":\":1\",\"path\":\"vnc.html\",\"ticket\":\"<43 chars>\",\"expiresInMs\":60000}\n# Xvnc (X server + VNC in one) listens on a 0600 unix socket only, with no VNC auth: only this uid\n# can open it. orca-desktop-proxy (websockify + a ticket gate) serves noVNC on 127.0.0.1 and\n# bridges WebSockets to that socket. Nothing is reachable from outside the VM: the desktop app\n# reaches it through Orca's port forward, a localhost port on the user's computer that any local\n# process or web page can reach, so each WebSocket needs a ticket from here: 32 random bytes,\n# single use, valid for 60 s, stored only as its sha256 (the file name; its content is the expiry).\n# The ticket goes to stdout only (the control plane hands it to the desktop app). Never started at boot.\nset -euo pipefail\numask 077\nDESKTOP=/opt/orca/desktop\nSTATE=\"$HOME/.orca-desktop\"\nPORT=\"${ORCA_DESKTOP_PORT:-6080}\"\nDISPLAY_NUM=\"${ORCA_DESKTOP_DISPLAY:-1}\"\nGEOMETRY=\"${ORCA_DESKTOP_GEOMETRY:-1280x800}\"\nSOCKET=\"$STATE/vnc.sock\"\n# The parent's DISPLAY must not leak into the WM/xterm below; they use ours.\nexport DISPLAY=\":$DISPLAY_NUM\"\n\n# Exit 3 = this image has no desktop (built before it, or its optional install failed).\nfail() { printf 'orca-desktop: %s\\n' \"$1\" >&2; exit \"${2:-1}\"; }\ncase \"$PORT\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_PORT must be a number' ;; esac\ncase \"$DISPLAY_NUM\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_DISPLAY must be a number' ;; esac\ncase \"$GEOMETRY\" in [0-9]*x[0-9]*) ;; *) fail 'ORCA_DESKTOP_GEOMETRY must look like 1280x800' ;; esac\ncommand -v Xvnc >/dev/null || fail 'not installed in this image (Xvnc missing)' 3\n[ -s \"$DESKTOP/novnc/vnc.html\" ] || fail 'not installed in this image (noVNC missing)' 3\nPROXY=\"$(dirname \"$(readlink -f \"$0\")\")/orca-desktop-proxy\"\n[ -x \"$PROXY\" ] || fail 'orca-desktop-proxy missing next to this script'\nTICKETS=\"$STATE/tickets\"\nTICKET_TTL_S=60\n# Xvnc's mode: a previous version of this script ran it with VncAuth; restart it in this mode.\nMODE=ticket-v1\n\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/start.lock\"\nflock -w 30 9 || fail 'another start is in progress'\n\npid_of() { # never \"0\": kill 0 targets our own process group\n local pid\n pid=\"$(cat \"$STATE/$1.pid\" 2>/dev/null || true)\"\n case \"$pid\" in '' | 0 | *[!0-9]*) return 1 ;; esac\n printf '%s' \"$pid\"\n}\nalive() { local pid; pid=\"$(pid_of \"$1\")\" && kill -0 \"$pid\" 2>/dev/null; }\nmint_ticket() { # prints the ticket; stores only its sha256, with the expiry as content\n local ticket now digest\n mkdir -p \"$TICKETS\"\n now=\"$(date +%s)\"\n # Expired or spent-but-unswept tickets; keep at most 16 live ones (oldest go first).\n for file in \"$TICKETS\"/*; do\n [ -f \"$file\" ] || continue\n [ \"$(cat \"$file\" 2>/dev/null || echo 0)\" -ge \"$now\" ] 2>/dev/null || rm -f \"$file\"\n done\n # shellcheck disable=SC2012 # names are hex digests\n ls -1t \"$TICKETS\" 2>/dev/null | tail -n +16 | while read -r old; do rm -f \"$TICKETS/$old\"; done\n ticket=\"$(head -c 32 /dev/urandom | base64 | tr '+/' '-_' | tr -d '=\\n')\"\n [ \"${#ticket}\" = 43 ] || fail 'could not generate a ticket'\n digest=\"$(printf '%s' \"$ticket\" | sha256sum | cut -d' ' -f1)\"\n printf '%s' \"$((now + TICKET_TTL_S))\" >\"$TICKETS/.$digest\" && mv \"$TICKETS/.$digest\" \"$TICKETS/$digest\"\n printf '%s' \"$ticket\"\n}\nready_line() {\n local ticket\n ticket=\"$(mint_ticket)\" || exit 1\n printf '{\"schemaVersion\":2,\"port\":%s,\"display\":\":%s\",\"path\":\"vnc.html\",\"ticket\":\"%s\",\"expiresInMs\":%s}\\n' \\\n \"$PORT\" \"$DISPLAY_NUM\" \"$ticket\" \"$((TICKET_TTL_S * 1000))\"\n}\nlistening() { # the proxy answers HTTP on loopback\n curl -fsS -o /dev/null --max-time 1 \"http://127.0.0.1:$PORT/vnc.html\" 2>/dev/null\n}\n\n# Pids from a previous boot (resume = reboot from disk) name dead or unrelated processes.\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" != \"$boot_id\" ]; then\n rm -rf \"$STATE\"/*.pid \"$SOCKET\" \"$STATE/password\" \"$STATE/passwd\" \"$STATE/mode\" \"$TICKETS\"\n printf '%s' \"$boot_id\" >\"$STATE/boot-id\"\nfi\n\n# Same boot, older script: its websockify had no ticket gate and its Xvnc wanted a VNC password.\nrm -f \"$STATE/password\" \"$STATE/passwd\"\nif alive websockify; then kill \"$(pid_of websockify)\" 2>/dev/null || true; fi\nrm -f \"$STATE/websockify.pid\"\ncurrent_mode() { cat \"$STATE/mode\" 2>/dev/null || true; }\n\nif alive xvnc && alive proxy && listening && [ \"$(current_mode)\" = \"$MODE\" ]; then\n ready_line\n exit 0\nfi\n\nstart() { # name cmd... — detached, logs in $STATE/.log\n local name=$1; shift\n # 9>&-: children must not inherit the start lock, or the next call waits for them to exit.\n setsid nohup \"$@\" >\"$STATE/$name.log\" 2>&1 &- &\n echo $! >\"$STATE/$name.pid\"\n}\n\nif ! alive xvnc || [ \"$(current_mode)\" != \"$MODE\" ]; then\n if alive xvnc; then kill \"$(pid_of xvnc)\" 2>/dev/null || true; sleep 0.2; fi\n rm -f \"$SOCKET\"\n # -rfbport -1: no TCP VNC port at all, only a 0600 unix socket (in the 0700 state dir) for the\n # proxy. SecurityTypes None is safe only because of that: the ticket gate is in the proxy.\n # SendPrimary=0: only explicit copies (xterm copies its selection, below) leave the sandbox.\n # The X display itself takes a cookie from ~/.Xauthority (Xlib's default for this user), so only\n # this uid's processes (agents, apps they start on DISPLAY=:1) can open it.\n auth=()\n if command -v xauth >/dev/null && command -v mcookie >/dev/null; then\n xauth -q -f \"$HOME/.Xauthority\" add \":$DISPLAY_NUM\" . \"$(mcookie)\" 9>&- && auth=(-auth \"$HOME/.Xauthority\")\n fi\n start xvnc Xvnc \":$DISPLAY_NUM\" \"${auth[@]}\" -geometry \"$GEOMETRY\" -depth 24 -nolisten tcp \\\n -rfbport -1 -rfbunixpath \"$SOCKET\" -rfbunixmode 0600 \\\n -SecurityTypes None -SendPrimary=0 \\\n -AlwaysShared -AcceptSetDesktopSize -desktop 'Remote desktop'\n printf '%s' \"$MODE\" >\"$STATE/mode\"\n for _ in $(seq 1 100); do\n [ -S \"$SOCKET\" ] && break\n alive xvnc || { tail -n 20 \"$STATE/xvnc.log\" >&2; fail 'Xvnc exited'; }\n sleep 0.05\n done\n [ -S \"$SOCKET\" ] || fail 'Xvnc did not create its socket'\n if command -v xsetroot >/dev/null; then xsetroot -solid '#1e1f22' 9>&- || true; fi\n if command -v openbox >/dev/null; then\n # Dark, flat theme to match Orca; the first terminal stays maximized as the tab resizes the screen.\n printf '%s\\n' '' \\\n 'Onyx' \\\n 'yes' \\\n '' >\"$STATE/openbox.xml\"\n start wm openbox --config-file \"$STATE/openbox.xml\"\n # Let it manage the screen before the terminal maps, so its maximize rule applies.\n sleep 0.2\n elif command -v twm >/dev/null; then\n start wm twm\n fi\n if command -v xterm >/dev/null; then\n # selectToClipboard: a selection is a copy (to CLIPBOARD, which reaches this computer).\n start xterm xterm -maximized -bg '#1e1f22' -fg '#d4d4d4' -fa 'Liberation Mono,Monospace' -fs 11 \\\n -xrm 'XTerm*selectToClipboard: true'\n fi\nfi\n\nif ! alive proxy || ! listening; then\n if alive proxy; then kill \"$(pid_of proxy)\" 2>/dev/null || true; sleep 0.1; fi\n mkdir -p \"$TICKETS\"\n PYTHONPATH=\"$DESKTOP/websockify\" start proxy python3 -P -W ignore::UserWarning \"$PROXY\" \\\n --listen \"$PORT\" --web \"$DESKTOP/novnc\" --unix-target \"$SOCKET\" --tickets \"$TICKETS\"\n for _ in $(seq 1 100); do\n listening && break\n alive proxy || { tail -n 20 \"$STATE/proxy.log\" >&2; fail 'orca-desktop-proxy exited'; }\n sleep 0.05\n done\n listening || fail \"orca-desktop-proxy is not answering on 127.0.0.1:$PORT\"\nfi\nready_line\n","orca-desktop-proxy":"#!/usr/bin/env python3\n# Remote desktop gateway, started by orca-desktop-start: serves noVNC on 127.0.0.1 and bridges one\n# WebSocket per single-use ticket to Xvnc's 0600 unix socket (Xvnc itself has no VNC auth: only this\n# uid can open the socket). The port is reached only through Orca's localhost forward on the user's\n# computer, where any local process or web page could knock, so every WebSocket must carry an\n# unused, unexpired ticket minted by orca-desktop-start (see consume_ticket), from a page on the same\n# localhost origin. Tickets never reach a log: paths are scrubbed before websockify logs them.\n# orca-desktop-proxy --listen PORT --web DIR --unix-target SOCKET --tickets DIR\n# stdlib + websockify (pinned tarball in /opt/orca/desktop/websockify, on PYTHONPATH) only.\nimport argparse\nimport hashlib\nimport hmac\nimport logging\nimport os\nimport re\nimport sys\nimport time\nfrom urllib.parse import parse_qs, urlsplit\n\nfrom websockify import websocketproxy\n\nTICKET_RE = re.compile(r'^[A-Za-z0-9_-]{43}$') # 32 random bytes, base64url without padding\nSCRUB_RE = re.compile(r'([?&]ticket=)[^&\\s\\'\"]*')\nLOOPBACK_HOST_RE = re.compile(r'^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:[0-9]{1,5})?$')\nWS_PATH = '/websockify'\nPAGE_SCRIPT = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'orca-desktop-page.js')\n# The page may only talk to its own origin (its WebSocket included): even a URL that tries to point\n# noVNC elsewhere cannot carry a ticket or the user's keys off this forward.\nPAGE_CSP = \"connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'\"\nPAGE_TAG = b'\\n'\n\n\ndef scrub(text):\n return SCRUB_RE.sub(r'\\1', str(text))\n\n\ndef ticket_digest(ticket):\n return hashlib.sha256(ticket.encode('ascii')).hexdigest()\n\n\ndef consume_ticket(directory, ticket, now=None):\n \"\"\"True once per minted ticket, within its lifetime. The ticket file (named by the ticket's\n sha256, holding its expiry) is unlinked on first use, so a replay or a racing second\n connection finds nothing; each request runs in its own forked process, so state is on disk.\"\"\"\n if not isinstance(ticket, str) or not TICKET_RE.match(ticket):\n return False\n digest = ticket_digest(ticket)\n match = None\n try:\n names = os.listdir(directory)\n except OSError:\n return False\n for name in names:\n # Compare every entry in constant time; never short-circuit on a prefix.\n if hmac.compare_digest(name.encode('ascii', 'replace'), digest.encode('ascii')):\n match = name\n if match is None:\n return False\n path = os.path.join(directory, match)\n try:\n with open(path, 'r', encoding='ascii') as handle:\n expires_at = int(handle.read().strip() or '0')\n except (OSError, ValueError):\n expires_at = 0\n try:\n os.unlink(path) # the consume: only one caller can win this\n except FileNotFoundError:\n return False\n return (now if now is not None else time.time()) <= expires_at\n\n\ndef same_loopback_origin(headers):\n \"\"\"The page and the WebSocket share one localhost origin (blocks other local sites and DNS\n rebinding). The port is the user's local forward, which may differ from ours, so compare the\n Origin with the Host the browser dialed rather than with a fixed port.\"\"\"\n host = (headers.get('Host') or '').strip().lower()\n origin = (headers.get('Origin') or '').strip().lower()\n return loopback_host(host) and origin == 'http://' + host\n\n\ndef loopback_host(host):\n return bool(LOOPBACK_HOST_RE.match(host or ''))\n\n\nclass TicketedProxyHandler(websocketproxy.ProxyRequestHandler):\n \"\"\"websockify's proxy handler plus the ticket + origin gate. Module level (not a closure) so\n websockify's per-connection multiprocessing can pickle it under any start method.\"\"\"\n\n def log_message(self, format, *args): # noqa: A002 (websockify's signature)\n super().log_message('%s', scrub(format % args if args else format))\n\n def reject(self, code, reason):\n self.send_response(code)\n self.send_header('Content-Length', '0')\n self.send_header('Connection', 'close')\n self.end_headers()\n self.close_connection = True\n raise self.server.EClose('desktop: websocket refused (%s)' % reason)\n\n def validate_connection(self):\n parts = urlsplit(self.path)\n ticket = (parse_qs(parts.query).get('ticket') or [''])[0]\n # Drop it before anything below (websockify's own logging included) can see self.path.\n self.path = parts.path\n if parts.path != WS_PATH:\n self.reject(404, 'path')\n if not same_loopback_origin(self.headers):\n self.reject(403, 'origin')\n if not consume_ticket(self.server.orca_tickets_dir, ticket):\n self.reject(403, 'ticket')\n\n def loopback_request(self):\n if loopback_host((self.headers.get('Host') or '').strip().lower()):\n return True\n self.send_error(403)\n return False\n\n def do_GET(self):\n if not self.loopback_request():\n return None\n path = urlsplit(self.path).path\n if path == '/orca-desktop-page.js':\n return self.send_bytes(read_file(PAGE_SCRIPT), 'text/javascript; charset=utf-8')\n if path == '/vnc.html':\n page = read_file(os.path.join(self.server.web, 'vnc.html'))\n return self.send_bytes(page.replace(b'', PAGE_TAG, 1), 'text/html; charset=utf-8', PAGE_CSP)\n return super().do_GET()\n\n def do_HEAD(self):\n if not self.loopback_request():\n return None\n return super().do_HEAD()\n\n def send_bytes(self, body, content_type, csp=None):\n self.send_response(200)\n self.send_header('Content-Type', content_type)\n if csp:\n self.send_header('Content-Security-Policy', csp)\n self.send_header('Content-Length', str(len(body)))\n self.send_header('Cache-Control', 'no-store')\n self.send_header('Referrer-Policy', 'no-referrer')\n self.end_headers()\n self.wfile.write(body)\n return None\n\n\ndef read_file(path):\n with open(path, 'rb') as handle:\n return handle.read()\n\n\ndef main(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('--listen', type=int, required=True)\n parser.add_argument('--web', required=True)\n parser.add_argument('--unix-target', required=True)\n parser.add_argument('--tickets', required=True)\n args = parser.parse_args(argv)\n logging.basicConfig(level=logging.INFO, format='%(message)s')\n server = websocketproxy.WebSocketProxy(\n RequestHandlerClass=TicketedProxyHandler,\n listen_host='127.0.0.1',\n listen_port=args.listen,\n web=args.web,\n file_only=True,\n unix_target=args.unix_target,\n )\n server.orca_tickets_dir = os.path.abspath(args.tickets)\n server.start_server()\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","orca-desktop-page.js":"// Orca's glue for noVNC, injected into vnc.html by orca-desktop-proxy. Orca (the desktop app's\n// main process) drives it through window.orcaDesktop:\n// - tickets: the page never connects by itself. Each WebSocket needs a fresh single-use ticket,\n// which Orca hands over with connect(ticket) after nextTicketRequest() resolves: 'ticket' on\n// load or after a session dropped, 'retry' after an attempt that never connected. Tickets live\n// only in memory here: never in the URL, storage or noVNC's settings.\n// - pause(message, label): Orca stopped retrying; show why, with a Reconnect button. resume()\n// (Orca reopened the desktop) or the button asks for a ticket again.\n// - fit: resize=remote makes Xvnc follow the tab; a server without SetDesktopSize gets scaling.\n// - clipboard: a copy inside the desktop right after user input there goes to this computer's\n// clipboard; paste(text, chord) sets the sandbox's clipboard first, then replays the paste key.\nimport UI from './app/ui.js';\nimport * as WebUtil from './app/webutil.js';\n\nconst WS_PATH = 'websockify';\nconst RESIZE_FALLBACK_MS = 1500;\n// A copy inside the desktop follows a copy key or a selection (drag or double-click) there; other\n// clipboard changes (an agent in the sandbox running xclip) must not overwrite this computer's\n// clipboard. Plain typing does not open the window.\nconst USER_COPY_WINDOW_MS = 1500;\nconst DRAG_PX = 4;\nconst MAX_CLIPBOARD_CHARS = 1 << 20;\nconst TICKET_RE = /^[A-Za-z0-9_-]{43}$/;\nconst XK = { v: 0x0076, V: 0x0056, Insert: 0xff63, Shift_L: 0xffe1, Super_L: 0xffeb, Super_R: 0xffec };\n\nlet state = 'idle'; // idle | connecting | connected | disconnected | paused\nlet attemptConnected = true;\nlet ticketWaiters = [];\nlet lastCopyIntent = 0;\nlet pointerStart = null;\n\nconst style = document.createElement('style');\n// Orca owns connecting and the chrome: noVNC's Connect button would only try without a ticket,\n// and its control bar duplicates what the Orca tab does (fit, clipboard, keyboard release).\n// The pause card follows Orca's theme: Orca sets Electron's theme source from its own setting, so\n// prefers-color-scheme here is Orca's light or dark, and it follows a switch while paused. The\n// page cannot read Orca's tokens, so these mirror them (popover, border, focus ring).\nstyle.textContent = `\n#noVNC_connect_dlg, #noVNC_control_bar_anchor { display: none !important; }\n#orca_pause { --orca-scrim: rgb(10 10 10 / 0.88); --orca-card: #171717; --orca-text: #f0f0f0;\n --orca-border: rgb(255 255 255 / 0.1); --orca-control: rgb(255 255 255 / 0.25);\n --orca-control-hover: rgb(255 255 255 / 0.08); --orca-focus: color-mix(in oklab, #f0f0f0 65%, #0a0a0a);\n color-scheme: dark; position: fixed; inset: 0; display: none; align-items: center;\n justify-content: center; padding: 16px; background: var(--orca-scrim); z-index: 1000;\n font: 13px/1.5 system-ui, sans-serif; }\n@media (prefers-color-scheme: light) {\n #orca_pause { --orca-scrim: rgb(255 255 255 / 0.88); --orca-card: #fff; --orca-text: #0a0a0a;\n --orca-border: #e5e5e5; --orca-control: #a3a3a3; --orca-control-hover: #f5f5f5;\n --orca-focus: color-mix(in oklab, #0a0a0a 55%, #fff); color-scheme: light; }\n}\n#orca_pause.open { display: flex; }\n#orca_pause > div { max-width: 360px; padding: 16px; border: 1px solid var(--orca-border);\n border-radius: 8px; background: var(--orca-card); color: var(--orca-text); text-align: center;\n box-shadow: 0 8px 24px rgb(0 0 0 / 0.16); }\n#orca_pause p { margin: 0; }\n#orca_pause button { margin-top: 12px; padding: 4px 12px; border: 1px solid var(--orca-control);\n border-radius: 6px; background: transparent; color: var(--orca-text); font: inherit; cursor: pointer; }\n#orca_pause button:hover { background: var(--orca-control-hover); }\n#orca_pause button:focus-visible { outline: 2px solid var(--orca-focus); outline-offset: 2px; }\n@media (prefers-reduced-motion: no-preference) {\n #orca_pause.open > div { animation: orca-pause-in 120ms ease-out; }\n}\n@keyframes orca-pause-in { from { opacity: 0; transform: translateY(4px); } }\n`;\ndocument.head.appendChild(style);\n\nconst overlay = document.createElement('div');\noverlay.id = 'orca_pause';\noverlay.innerHTML = '

';\noverlay.querySelector('button').addEventListener('click', () => resume());\ndocument.addEventListener('DOMContentLoaded', () => document.body.appendChild(overlay));\n\nwindow.addEventListener('keydown', (event) => {\n if ((event.ctrlKey || event.metaKey) && !event.altKey && (event.key === 'c' || event.key === 'C' || event.key === 'Insert')) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerdown', (event) => {\n pointerStart = { x: event.clientX, y: event.clientY };\n}, true);\n// A double- or triple-click selects a word or line (pointer events carry no click count).\nwindow.addEventListener('mousedown', (event) => {\n if (event.detail >= 2) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerup', (event) => {\n if (pointerStart && Math.hypot(event.clientX - pointerStart.x, event.clientY - pointerStart.y) >= DRAG_PX) {\n lastCopyIntent = Date.now();\n }\n pointerStart = null;\n}, true);\n\nfunction requestTicket() {\n const answer = attemptConnected ? 'ticket' : 'retry';\n const waiters = ticketWaiters;\n ticketWaiters = [];\n waiters.forEach((resolve) => resolve(answer));\n}\n\nasync function whenStarted() {\n while (document.documentElement.classList.contains('noVNC_loading')) {\n await new Promise((resolve) => setTimeout(resolve, 25));\n }\n}\n\nfunction onConnect() {\n state = 'connected';\n attemptConnected = true;\n UI.hideStatus();\n setTimeout(() => {\n // Xvnc answers SetDesktopSize; anything that does not gets scaled into the tab instead.\n if (UI.rfb && state === 'connected' && !UI.rfb._supportsSetDesktopSize) {\n UI.rfb.scaleViewport = true;\n }\n }, RESIZE_FALLBACK_MS);\n}\n\nfunction onDisconnect() {\n if (state === 'paused') {\n return;\n }\n state = 'disconnected';\n // The ticket is spent: ask Orca for a new one (a dropped forward, a restart of the desktop).\n requestTicket();\n}\n\nfunction onClipboard(event) {\n const text = event.detail && event.detail.text;\n if (typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return;\n }\n if (Date.now() - lastCopyIntent > USER_COPY_WINDOW_MS || !document.hasFocus()) {\n return;\n }\n navigator.clipboard.writeText(text).catch(() => {});\n}\n\nasync function connect(ticket) {\n if (typeof ticket !== 'string' || !TICKET_RE.test(ticket)) {\n return 'invalid';\n }\n if (state === 'connecting' || state === 'connected' || state === 'paused') {\n return state;\n }\n await whenStarted();\n if (UI.rfb) {\n return 'connecting';\n }\n state = 'connecting';\n attemptConnected = false;\n // UI.connect reads the path setting synchronously and opens the WebSocket in RFB's constructor;\n // the in-memory setting is restored right after, so the ticket is never kept or shown.\n // Only ever this page's own origin: noVNC also reads host, port, encrypt, repeater and logging\n // from the URL, which must never send a ticketed session (and the user's keys) elsewhere.\n WebUtil.setSetting('host', '');\n WebUtil.setSetting('port', '');\n WebUtil.setSetting('encrypt', false);\n WebUtil.setSetting('repeaterID', '');\n WebUtil.setSetting('path', `${WS_PATH}?ticket=${ticket}`);\n try {\n UI.connect();\n } finally {\n WebUtil.setSetting('path', WS_PATH);\n }\n const rfb = UI.rfb;\n if (!rfb) {\n state = 'disconnected';\n requestTicket();\n return 'failed';\n }\n rfb.addEventListener('connect', onConnect);\n rfb.addEventListener('disconnect', onDisconnect);\n rfb.addEventListener('clipboard', onClipboard);\n return 'connecting';\n}\n\n/** Pastes this computer's clipboard: the sandbox's clipboard first, then the paste key itself. */\nfunction paste(text, chord) {\n const rfb = UI.rfb;\n if (!rfb || state !== 'connected' || typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return false;\n }\n rfb.clipboardPasteFrom(text);\n if (chord && chord.kind === 'mac') {\n // Cmd+V: Linux apps do not paste on Super+V, so release Super and send Shift+Insert.\n rfb.sendKey(XK.Super_L, 'MetaLeft', false);\n rfb.sendKey(XK.Super_R, 'MetaRight', false);\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', true);\n rfb.sendKey(XK.Insert, 'Insert');\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', false);\n } else if (chord && chord.kind === 'replay') {\n // Ctrl+V, Ctrl+Shift+V, Shift+Insert: the held modifiers already reached the sandbox.\n const insert = chord.key === 'Insert';\n rfb.sendKey(insert ? XK.Insert : chord.key === 'V' ? XK.V : XK.v, insert ? 'Insert' : 'KeyV');\n }\n return true;\n}\n\nfunction pause(message, label, tone) {\n state = 'paused';\n if (UI.rfb) {\n UI.rfb.disconnect();\n }\n UI.hideStatus();\n overlay.querySelector('p').textContent = String(message || '');\n overlay.querySelector('button').textContent = String(label || 'Reconnect');\n // Asleep and starting are states, not errors: announce them politely.\n overlay.firstElementChild.setAttribute('role', tone === 'neutral' ? 'status' : 'alert');\n overlay.classList.add('open');\n overlay.querySelector('button').focus();\n return true;\n}\n\nfunction resume() {\n if (state !== 'paused') {\n return false;\n }\n overlay.classList.remove('open');\n state = 'disconnected';\n attemptConnected = true; // a person asked: start the retry budget over\n requestTicket();\n return true;\n}\n\nObject.defineProperty(window, 'orcaDesktop', {\n value: Object.freeze({\n version: 1,\n state: () => state,\n /** Resolves when the page needs a ticket: now if it is not connected, else after a drop. */\n nextTicketRequest: () => new Promise((resolve) => {\n ticketWaiters.push(resolve);\n if (state === 'idle' || state === 'disconnected') {\n requestTicket();\n }\n }),\n connect,\n paste,\n pause,\n resume\n })\n});\n","orca-sandbox-grant":"#!/usr/bin/env bash\n# Mints a fresh, single-device orcad pairing offer for one org member's device and seals it to that\n# device's X25519 key, so the control plane relays only ciphertext (the VM owner's E2EE model holds:\n# every member device gets its own revocable orcad credential, nobody else can read it).\n# Env from the control plane: ORCA_GRANT_ID, ORCA_GRANT_RECIPIENT_KEY (base64 raw X25519 public\n# key), ORCA_GRANT_KIND (desktop|mobile), ORCA_PUBLIC_WSS. Prints one JSON line:\n# {\"deviceId\":\"…\",\"sealed\":{\"v\":1,\"ephemeralPublicKeyB64\":\"…\",\"nonceB64\":\"…\",\"ciphertextB64\":\"…\"}}\n# Sealing: ECDH(ephemeral, recipient) -> HKDF-SHA256(salt = eph||recipient, info\n# \"orca-cloud-grant-v1\") -> AES-256-GCM, AAD \"orca-cloud-grant-v1:\".\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nDATA=\"$HOME/.orcad-data\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\n# One mint at a time: --rotate retires unredeemed offers, so two members never share a credential.\nflock -w 30 9\n\ncase \"${ORCA_GRANT_ID:-}\" in '' | *[!A-Za-z0-9_-]*) echo 'bad grant id' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_KIND:-}\" in desktop) scope=() ;; mobile) scope=(--mobile) ;; *) echo 'bad kind' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_RECIPIENT_KEY:-}\" in '' | *[!A-Za-z0-9+/=]*) echo 'bad key' >&2; exit 2 ;; esac\ncase \"${ORCA_PUBLIC_WSS:-}\" in wss://*) ;; *) echo 'bad endpoint' >&2; exit 2 ;; esac\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\n# The workspace's project must exist on this orcad before a phone opens it: phones may not add\n# projects themselves (mobile RPC scope), and a phone may be the first client this VM ever sees.\nproject=/vercel/sandbox/project\nif [ -d \"$project\" ]; then\n kind=folder\n [ -d \"$project/.git\" ] && kind=git\n ORCA_USER_DATA_PATH=\"$DATA\" timeout 20 \"$node\" \"$cli\" repo add --path \"$project\" --kind \"$kind\" --json \\\n >/dev/null 2>&1 || true\nfi\noffer=\"$(ORCA_USER_DATA_PATH=\"$DATA\" timeout 30 \"$node\" \"$cli\" pair --json --rotate \"${scope[@]}\" \\\n --address \"$ORCA_PUBLIC_WSS\" 2>/dev/null)\" || { echo 'pair failed' >&2; exit 1; }\n# This workspace's read-snapshot signer (public half), so the paired device pins it; best effort.\nsigner=\"$(\"$node\" \"$ORCA_HOME/bin/orca-read-snapshot.cjs\" --signer-public-key 2>/dev/null || true)\"\n# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.\n# Granted devices are listed so orcad can keep owner-only features (local commands) from them.\nprintf '%s' \"$offer\" | ORCA_GRANT_ID=\"$ORCA_GRANT_ID\" ORCA_GRANT_RECIPIENT_KEY=\"$ORCA_GRANT_RECIPIENT_KEY\" ORCA_READ_SIGNER=\"$signer\" \\\n ORCA_GRANT_LEDGER=\"$STATE/grant-devices\" \"$node\" -e '\nconst crypto = require(\"node:crypto\")\nlet input = \"\"\nprocess.stdin.on(\"data\", (c) => (input += c)).on(\"end\", () => {\n const res = JSON.parse(input).result\n if (!res || res.available !== true || !res.pairingUrl || !res.deviceId) {\n console.error(\"offer unavailable\")\n process.exit(1)\n }\n if (process.env.ORCA_GRANT_LEDGER) require(\"node:fs\").appendFileSync(process.env.ORCA_GRANT_LEDGER, res.deviceId + \"\\n\", { mode: 0o600 })\n const recipient = Buffer.from(process.env.ORCA_GRANT_RECIPIENT_KEY, \"base64\")\n if (recipient.length !== 32) { console.error(\"bad key length\"); process.exit(2) }\n const recipientKey = crypto.createPublicKey({ key: { kty: \"OKP\", crv: \"X25519\", x: recipient.toString(\"base64url\") }, format: \"jwk\" })\n const eph = crypto.generateKeyPairSync(\"x25519\")\n const ephRaw = Buffer.from(eph.publicKey.export({ format: \"jwk\" }).x, \"base64url\")\n const shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: recipientKey })\n const key = Buffer.from(crypto.hkdfSync(\"sha256\", shared, Buffer.concat([ephRaw, recipient]), \"orca-cloud-grant-v1\", 32))\n const nonce = crypto.randomBytes(12)\n const cipher = crypto.createCipheriv(\"aes-256-gcm\", key, nonce)\n cipher.setAAD(Buffer.from(\"orca-cloud-grant-v1:\" + process.env.ORCA_GRANT_ID))\n const signer = /^[A-Za-z0-9+/]{43}=$/.test(process.env.ORCA_READ_SIGNER || \"\") ? process.env.ORCA_READ_SIGNER : undefined\n const body = Buffer.from(JSON.stringify({ pairingUrl: res.pairingUrl, deviceId: res.deviceId, scope: res.scope, ...(signer ? { readSignerPublicKeyB64: signer } : {}) }))\n const ct = Buffer.concat([cipher.update(body), cipher.final(), cipher.getAuthTag()])\n process.stdout.write(JSON.stringify({ deviceId: res.deviceId, sealed: { v: 1, ephemeralPublicKeyB64: ephRaw.toString(\"base64\"), nonceB64: nonce.toString(\"base64\"), ciphertextB64: ct.toString(\"base64\") } }) + \"\\n\")\n})'\n","orca-sandbox-revoke":"#!/usr/bin/env bash\n# Revokes member devices from orcad's device registry. orcad adopts on-disk removals at every auth\n# (an admin revoke, device-registry-store.ts), so this works whether or not orcad is running; the\n# control plane also runs it at boot, before orcad starts, for revokes queued while suspended.\n# Env: ORCA_REVOKE_DEVICE_IDS (comma list of orcad device ids). Prints {\"revoked\":,\"live\":}.\nset -euo pipefail\numask 077\nSTATE=\"$HOME/.orca-sandbox\"\nREGISTRY=\"$HOME/.orcad-data/orca-devices.json\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\nflock -w 30 9\n\nids=\"${ORCA_REVOKE_DEVICE_IDS:-}\"\ncase \"$ids\" in '' | *[!A-Za-z0-9,_-]*) echo 'bad device ids' >&2; exit 2 ;; esac\n# Live orcad first: `orca pair --revoke` also closes the device's open sockets now. Older orcad\n# builds lack it; the on-disk removal below still blocks their next sign-in.\nORCA_HOME=/opt/orca\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node 2>/dev/null | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\nlive=0\nif [ -n \"$node\" ] && [ -f \"$cli\" ] && [ -s \"$HOME/.orcad-data/orca-runtime.json\" ]; then\n for id in ${ids//,/ }; do\n if ORCA_USER_DATA_PATH=\"$HOME/.orcad-data\" timeout 15 \"$node\" \"$cli\" pair --revoke \"$id\" --json 2>/dev/null \\\n | jq -e '.ok == true and .result.revoked == true' >/dev/null 2>&1; then\n live=$((live + 1))\n fi\n done\nfi\nif [ ! -s \"$REGISTRY\" ]; then\n echo \"{\\\"revoked\\\":$live,\\\"live\\\":$live}\"\n exit 0\nfi\nids_json=\"$(jq -cn --arg ids \"$ids\" '$ids | split(\",\") | map(select(length > 0))')\"\nbefore=\"$(jq 'length' \"$REGISTRY\")\"\ntmp=\"$(mktemp \"$REGISTRY.revoke.XXXXXX\")\"\n# Removes the rows and any phones delegated through them (parentDeviceId), like orcad's own revoke.\njq --argjson ids \"$ids_json\" \\\n '[.[] | select((.deviceId as $d | $ids | index($d)) == null and ((.parentDeviceId // \"\") as $p | $ids | index($p)) == null)]' \\\n \"$REGISTRY\" >\"$tmp\"\nchmod 0600 \"$tmp\"\nsync \"$tmp\" 2>/dev/null || true\nmv -f \"$tmp\" \"$REGISTRY\"\nafter=\"$(jq 'length' \"$REGISTRY\")\"\necho \"{\\\"revoked\\\":$((live + before - after)),\\\"live\\\":$live}\"\n","orca-sandbox-members":"#!/usr/bin/env bash\n# Runs as root (control plane, sudo). Installs who-may-push-as-whom for `orca-git-as`:\n# /etc/orca/members/.gitconfig egress placeholder header + GitHub author identity\n# /etc/orca/members/devices.json {\"\": \"\"} (each member's paired devices)\n# Both root-only: agents never read another member's placeholder. `orca-git-identity` (root, via a\n# sudoers rule) hands an agent only the identity of the member whose device drove its turn, as orcad\n# attests it. No token lives here: the placeholder is swapped at egress, for this repository only.\n# Env: ORCA_MEMBERS_B64 = base64 JSON [{userId, name, email, authorization, deviceIds:[...]}]\n# The VM user agents run as is orcad's own user (detected). Prints {\"members\":,\"devices\":}.\nset -euo pipefail\numask 077\nDIR=/etc/orca/members\norcad_pid=\"$(pgrep -f orcad-server.js | head -n 1 || true)\"\nUSER_NAME=\"$( [ -n \"$orcad_pid\" ] && ps -o user= -p \"$orcad_pid\" | tr -d ' ' || true)\"\nUSER_NAME=\"${USER_NAME:-${ORCA_SANDBOX_USER:-${SUDO_USER:-}}}\"\ncase \"$USER_NAME\" in '' | *[!a-z0-9_-]*) echo 'bad user' >&2; exit 2 ;; esac\nmkdir -p /etc/orca\njson=\"$(printf '%s' \"${ORCA_MEMBERS_B64:-W10=}\" | base64 -d)\"\ntmp=\"$(mktemp -d /etc/orca/members.XXXXXX)\"\ncount=0\nwhile IFS= read -r row; do\n user=\"$(jq -r '.userId' <<<\"$row\")\"\n case \"$user\" in '' | *[!A-Za-z0-9_.:-]*) continue ;; esac\n file=\"$tmp/$(printf '%s' \"$user\" | tr ':' '_').gitconfig\"\n # An empty extraheader first resets the image-wide (app identity) header for this member's git.\n git config -f \"$file\" --add http.https://github.com/.extraheader ''\n git config -f \"$file\" --add http.https://github.com/.extraheader \"Authorization: $(jq -r '.authorization' <<<\"$row\")\"\n git config -f \"$file\" user.name \"$(jq -r '.name' <<<\"$row\")\"\n git config -f \"$file\" user.email \"$(jq -r '.email' <<<\"$row\")\"\n # GH-AS-MEMBER: the member's placeholder for gh (a placeholder, never a token).\n gh_token=\"$(jq -r '.ghToken // empty' <<<\"$row\")\"\n case \"$gh_token\" in orca-ph-* | orca-mph-*) git config -f \"$file\" orca.ghtoken \"$gh_token\" ;; esac\n count=$((count + 1))\ndone < <(jq -c '.[]' <<<\"$json\")\n# GIT-COAUTHOR: members whose GitHub identity can't be used right now get only a co-author line (no header,\n# no author: their commits fall back to the workspace identity, with a Co-authored-by trailer for them).\n# Env: ORCA_COAUTHORS_B64 = base64 JSON [{userId, coauthor: \"Name \", deviceIds}]\ncoauthors=\"$(printf '%s' \"${ORCA_COAUTHORS_B64:-W10=}\" | base64 -d)\"\njq -e 'type == \"array\"' <<<\"$coauthors\" >/dev/null 2>&1 || coauthors='[]'\nwhile IFS= read -r row; do\n user=\"$(jq -r '.userId' <<<\"$row\")\"\n case \"$user\" in '' | *[!A-Za-z0-9_.:-]*) continue ;; esac\n file=\"$tmp/$(printf '%s' \"$user\" | tr ':' '_').gitconfig\"\n [ -e \"$file\" ] && continue\n line=\"$(jq -r '.coauthor' <<<\"$row\")\"\n [[ \"$line\" =~ ^[^\\<\\>[:cntrl:]]{1,80}\\ \\<[0-9]{1,20}\\+[A-Za-z0-9-]{1,39}@users\\.noreply\\.github\\.com\\>$ ]] || continue\n git config -f \"$file\" orca.coauthor \"$line\"\ndone < <(jq -c '.[]' <<<\"$coauthors\")\n# A device id claimed by more than one member maps to nobody (never \"last wins\": one member's device must\n# never attest as another's). Both lists.\nDEVICES_JQ='add | [.[] | select(.userId | test(\"^[A-Za-z0-9_.:-]+$\")) | .userId as $u | (.deviceIds // [])[] | select(test(\"^[A-Za-z0-9_-]{1,128}$\")) | {key: ., value: $u}] | group_by(.key) | map(select((map(.value) | unique | length) == 1) | .[0]) | from_entries'\njq -c -s \"$DEVICES_JQ\" <(printf '%s' \"$json\") <(printf '%s' \"$coauthors\") >\"$tmp/devices.json\"\ndevices=\"$(jq 'length' \"$tmp/devices.json\")\"\nchmod 0700 \"$tmp\" && chmod 0600 \"$tmp\"/*\nrm -rf \"$DIR.old\"\n[ -d \"$DIR\" ] && mv \"$DIR\" \"$DIR.old\"\nmv \"$tmp\" \"$DIR\"\nrm -rf \"$DIR.old\"\n# Agents may ask for their own sender's identity, and only that (the helper checks with orcad).\nrule=\"$USER_NAME ALL=(root) NOPASSWD:SETENV: /opt/orca/bin/orca-git-identity\"\nprintf '%s\\n' \"$rule\" >/etc/sudoers.d/orca-git-identity.new\nchmod 0440 /etc/sudoers.d/orca-git-identity.new\nif visudo -cf /etc/sudoers.d/orca-git-identity.new >/dev/null; then\n mv -f /etc/sudoers.d/orca-git-identity.new /etc/sudoers.d/orca-git-identity\nelse\n rm -f /etc/sudoers.d/orca-git-identity.new\n echo 'sudoers rule rejected' >&2\n exit 1\nfi\n# Pre-attestation layout (agent-readable member files) must not linger.\nuser_home=\"$(getent passwd \"$USER_NAME\" | cut -d: -f6)\"\n[ -n \"$orcad_pid\" ] && user_home=\"$(tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n 's/^HOME=//p' | head -n 1)\"\n[ -n \"$user_home\" ] && rm -rf \"$user_home/.orca-sandbox/members\"\n# Commits outside a teammate's turn still need an author (images older than orca-sandbox-start's default).\nif [ -n \"$user_home\" ]; then\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email 'noreply@orca.dev'\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name 'Orca'\nfi\n# CREATE-GIT-ASYNC: identities are in place, so `git` stops holding commits and pushes for this boot.\nif [ -n \"$user_home\" ] && [ -d \"$user_home/.orca-sandbox\" ]; then\n sudo -u \"$USER_NAME\" sh -c 'rm -f \"$1/git-setup.pending\" \"$1/git-setup.failed\" && date +%s >\"$1/git-setup.ready\"' \\\n _ \"$user_home/.orca-sandbox\" || true\nfi\necho \"{\\\"members\\\":$count,\\\"devices\\\":$devices}\"\n","orca-sandbox-read-snapshot":"#!/usr/bin/env bash\n# Seals a read-only snapshot of this workspace (chats, agent status, git, PR) to the reader keys the\n# control plane passes, right before the drain. Only ciphertext is printed (one JSON line); see\n# orca-read-snapshot.cjs. Exit 3: orcad isn't running (nothing to read).\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nexport ORCA_USER_DATA_PATH=\"${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n[ -n \"$node\" ] || { echo 'node not found' >&2; exit 1; }\nexec timeout 35 \"$node\" \"$ORCA_HOME/bin/orca-read-snapshot.cjs\"\n","orca-read-snapshot.cjs":"#!/usr/bin/env node\n// Gathers what a sleeping workspace should still show (recent chats per agent session, agent\n// status, git status/diff summary, PR link) from the running orcad over its local socket, then seals\n// it to the reader keys the control plane passed, so only ciphertext leaves the VM.\n// Run by orca-sandbox-read-snapshot right before the drain. Env:\n// ORCA_READ_SNAPSHOT_ID rsn_<24 hex> ORCA_READ_WORKSPACE_ID sbx_<24 hex>\n// ORCA_READ_RECIPIENTS JSON [{keyId, publicKeyB64}] ORCA_READ_REASON sleep|rollover\n// ORCA_USER_DATA_PATH orcad's data dir (orca-runtime.json lives there)\n// Prints one JSON line: {v:1, snapshotId, workspaceId, nonceB64, ciphertextB64, recipients[], stats}.\n// Construction (keep in sync with src/shared/cloud-workspaces/read-snapshot.ts in the app):\n// body = AES-256-GCM(dek, nonce, JSON, AAD \"orca-cloud-read-v1::\")\n// wrapped = AES-256-GCM(HKDF-SHA256(X25519(eph, reader), eph||reader, \"orca-cloud-read-wrap-v1\"),\n// nonce_i, dek, AAD \"orca-cloud-read-wrap-v1:::\")\n'use strict'\nconst crypto = require('node:crypto')\nconst fs = require('node:fs')\nconst net = require('node:net')\nconst path = require('node:path')\n\nconst INFO = 'orca-cloud-read-v1'\nconst WRAP_INFO = 'orca-cloud-read-wrap-v1'\nconst PROJECT = '/vercel/sandbox/project'\nconst LIMITS = { sessions: 12, messagesPerSession: 60, messageChars: 4000, changes: 200, commits: 10 }\n/** Plaintext budget: sealed + base64 it stays under the control plane's 220 kB and the 256 kB stdout cap. */\nconst MAX_PLAIN_BYTES = 150_000\nconst CALL_TIMEOUT_MS = 5_000\nconst TOTAL_BUDGET_MS = 20_000\n\nfunction b64(bytes) {\n return Buffer.from(bytes).toString('base64')\n}\n\nfunction x25519PublicKey(raw) {\n return crypto.createPublicKey({ key: { kty: 'OKP', crv: 'X25519', x: Buffer.from(raw).toString('base64url') }, format: 'jwk' })\n}\n\nfunction gcmSeal(key, nonce, plain, aad) {\n const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce)\n cipher.setAAD(Buffer.from(aad))\n return Buffer.concat([cipher.update(plain), cipher.final(), cipher.getAuthTag()])\n}\n\nconst SIG_INFO = 'orca-cloud-read-sig-v1'\n\n/**\n * This VM's snapshot signing key (Ed25519), created once and kept on the VM's own disk (0600, never\n * printed). Devices pin its public half per workspace, so a snapshot the control plane forged or\n * swapped doesn't verify. Same file for the grant script, which hands the public half to pairing devices.\n */\nfunction signingKey(stateDir) {\n if (!path.isAbsolute(stateDir)) {\n throw new Error('no state dir')\n }\n const file = path.join(stateDir, 'read-signing-key.pem')\n const load = () => {\n try {\n const privateKey = crypto.createPrivateKey(fs.readFileSync(file, 'utf8'))\n return privateKey.asymmetricKeyType === 'ed25519' ? privateKey : null\n } catch {\n return null\n }\n }\n let privateKey = load()\n if (!privateKey) {\n fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 })\n // Written whole to a temp file, then linked into place: atomic, and a concurrent first run\n // (grant + capture) keeps whichever key landed first. A broken file is replaced (devices that\n // pinned the old signer then see \"signer changed\" until they trust the new one).\n const temp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}`\n fs.writeFileSync(temp, crypto.generateKeyPairSync('ed25519').privateKey.export({ format: 'pem', type: 'pkcs8' }), { mode: 0o600 })\n try {\n fs.linkSync(temp, file)\n } catch {\n if (!load()) {\n fs.renameSync(temp, file)\n }\n } finally {\n fs.rmSync(temp, { force: true })\n }\n privateKey = load()\n if (!privateKey) {\n throw new Error('signing key unavailable')\n }\n }\n const publicKeyB64 = Buffer.from(crypto.createPublicKey(privateKey).export({ format: 'jwk' }).x, 'base64url').toString('base64')\n return { privateKey, publicKeyB64 }\n}\n\n/** Signs the sealed body: \"orca-cloud-read-sig-v1::::\" || ciphertext bytes. */\nfunction sign(out, key) {\n const message = Buffer.concat([\n Buffer.from(`${SIG_INFO}:${out.workspaceId}:${out.snapshotId}:${out.nonceB64}:`),\n Buffer.from(out.ciphertextB64, 'base64')\n ])\n return { publicKeyB64: key.publicKeyB64, signatureB64: crypto.sign(null, message, key.privateKey).toString('base64') }\n}\n\n/** Seals `payload` (an object) to every recipient; a malformed key is skipped, not fatal. */\nfunction seal(payload, recipients, workspaceId, snapshotId) {\n const scope = `${workspaceId}:${snapshotId}`\n const dek = crypto.randomBytes(32)\n const nonce = crypto.randomBytes(12)\n const ciphertext = gcmSeal(dek, nonce, Buffer.from(JSON.stringify(payload)), `${INFO}:${scope}`)\n const sealedTo = []\n for (const recipient of recipients) {\n const reader = Buffer.from(String(recipient.publicKeyB64 || ''), 'base64')\n if (reader.length !== 32 || !/^rk_[0-9a-f]{24}$/.test(String(recipient.keyId || ''))) {\n continue\n }\n let shared\n const eph = crypto.generateKeyPairSync('x25519')\n try {\n shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: x25519PublicKey(reader) })\n } catch {\n continue\n }\n if (shared.every((byte) => byte === 0)) {\n continue\n }\n const ephRaw = Buffer.from(eph.publicKey.export({ format: 'jwk' }).x, 'base64url')\n const kek = Buffer.from(crypto.hkdfSync('sha256', shared, Buffer.concat([ephRaw, reader]), WRAP_INFO, 32))\n const wrapNonce = crypto.randomBytes(12)\n const wrapped = gcmSeal(kek, wrapNonce, dek, `${WRAP_INFO}:${scope}:${recipient.keyId}`)\n sealedTo.push({ keyId: recipient.keyId, ephemeralPublicKeyB64: b64(ephRaw), nonceB64: b64(wrapNonce), wrappedKeyB64: b64(wrapped) })\n }\n dek.fill(0)\n return { v: 1, snapshotId, workspaceId, nonceB64: b64(nonce), ciphertextB64: b64(ciphertext), recipients: sealedTo }\n}\n\n// --- gathering -------------------------------------------------------------------------------\n\n/** One request per connection, like the CLI. A streaming method resolves on its first frame. */\nfunction rpc(metadata, method, params, timeoutMs = CALL_TIMEOUT_MS) {\n return new Promise((resolve) => {\n const transport = (metadata.transports || [metadata.transport]).find((t) => t && (t.kind === 'unix' || t.kind === 'named-pipe'))\n if (!transport) {\n resolve(null)\n return\n }\n const socket = net.createConnection(transport.endpoint)\n const id = crypto.randomUUID()\n let buffer = ''\n let done = false\n const finish = (value) => {\n if (!done) {\n done = true\n clearTimeout(timer)\n socket.destroy()\n resolve(value)\n }\n }\n const timer = setTimeout(() => finish(null), timeoutMs)\n socket.setEncoding('utf8')\n socket.on('error', () => finish(null))\n socket.on('close', () => finish(null))\n socket.on('connect', () => socket.write(`${JSON.stringify({ id, authToken: metadata.authToken, method, params })}\\n`))\n socket.on('data', (chunk) => {\n buffer += chunk\n let newline\n while ((newline = buffer.indexOf('\\n')) !== -1) {\n const line = buffer.slice(0, newline)\n buffer = buffer.slice(newline + 1)\n let frame\n try {\n frame = JSON.parse(line)\n } catch {\n continue\n }\n if (!frame || frame.id !== id) {\n continue\n }\n finish(frame.ok === true ? frame.result : null)\n return\n }\n })\n })\n}\n\nconst isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v)\nconst str = (v, max) => (typeof v === 'string' ? v.slice(0, max) : null)\nconst num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null)\n\nfunction messagesOf(history) {\n const items = isObj(history) && isObj(history.page) && Array.isArray(history.page.items) ? history.page.items : []\n const out = []\n for (const item of items) {\n const body = isObj(item) && isObj(item.body) ? item.body : null\n if (!body || body.kind !== 'message' || !Array.isArray(body.blocks)) {\n continue\n }\n const role = body.role\n if (role !== 'user' && role !== 'assistant' && role !== 'system') {\n continue\n }\n const text = body.blocks\n .filter((b) => isObj(b) && b.type === 'text' && typeof b.text === 'string')\n .map((b) => b.text)\n .join('\\n')\n .trim()\n if (text) {\n out.push({ itemId: String(item.itemId).slice(0, 200), role, text: text.slice(0, LIMITS.messageChars), at: num(item.observedAt) ?? 0 })\n }\n }\n return { messages: out, hasOlder: isObj(history) && isObj(history.page) && history.page.hasOlder === true }\n}\n\nfunction gitOf(status, log) {\n if (!isObj(status) && !isObj(log)) {\n return null\n }\n const entries = isObj(status) && Array.isArray(status.entries) ? status.entries.filter(isObj) : []\n let added = 0\n let removed = 0\n let counted = false\n const changes = entries.slice(0, LIMITS.changes).map((e) => {\n const a = num(e.added)\n const r = num(e.removed)\n if (a !== null || r !== null) {\n counted = true\n }\n return { path: String(e.path).slice(0, 1024), status: str(e.status, 20) || 'modified', area: str(e.area, 20) || 'unstaged', added: a, removed: r }\n })\n for (const e of entries) {\n added += num(e.added) || 0\n removed += num(e.removed) || 0\n }\n const items = isObj(log) && Array.isArray(log.items) ? log.items.filter(isObj) : []\n return {\n branch: isObj(status) && typeof status.branch === 'string' ? status.branch.replace(/^refs\\/heads\\//, '') : null,\n head: isObj(status) ? str(status.head, 64) : null,\n changes,\n changeCount: entries.length,\n added: counted ? added : null,\n removed: counted ? removed : null,\n commits: items.slice(0, LIMITS.commits).map((c) => ({\n id: String(c.id).slice(0, 64),\n subject: String(c.subject ?? '').slice(0, 300),\n author: str(c.author, 120),\n at: num(c.timestamp)\n }))\n }\n}\n\nfunction prOf(linked) {\n if (!isObj(linked) || num(linked.number) === null || typeof linked.url !== 'string' || !linked.url.startsWith('https://')) {\n return null\n }\n return {\n number: linked.number,\n title: String(linked.title ?? '').slice(0, 300),\n state: str(linked.state, 20) || 'open',\n url: linked.url.slice(0, 500),\n checksStatus: str(linked.checksStatus, 20),\n checksSummary: str(linked.checksSummary, 200)\n }\n}\n\nconst STATUSES = new Set(['working', 'attention', 'idle'])\nconst PANE_PREFIX = 'structured-agent-session-'\n\n/**\n * Chats as orcad stores them (agent-session-journal.db, read-only): every session's provider, name\n * and last turn, open tabs first. The local socket can't stream agentSession.subscribeStatus, and\n * worktree.ps lists only agents that are live right now, so this is the complete list.\n */\nfunction storedSessions(dataDir) {\n let db\n try {\n const { DatabaseSync } = require('node:sqlite')\n db = new DatabaseSync(path.join(dataDir, 'agent-session-journal.db'), { readOnly: true })\n const open = new Set(db.prepare('SELECT session_id FROM agent_session_tabs').all().map((r) => r.session_id))\n const out = []\n for (const row of db.prepare('SELECT session_id, record_json FROM agent_session_records').all()) {\n let record\n try {\n record = JSON.parse(row.record_json)\n } catch {\n continue\n }\n const last = isObj(record.lastTurn) ? record.lastTurn : {}\n out.push({\n sessionId: row.session_id,\n agent: str(record.provider, 40),\n title: str(record.conversationName, 200) || str(last.prompt, 200),\n status: last.state === 'running' || last.state === 'submitted' ? 'working' : last.state === 'settled' ? 'idle' : 'unknown',\n turnOutcome: str(last.outcome, 40),\n updatedAt: num(record.updatedAt),\n open: open.has(row.session_id),\n lastPrompt: str(last.prompt, LIMITS.messageChars),\n lastReply: str(last.reply, LIMITS.messageChars),\n lastAt: num(last.at),\n // \"::\": which checkout this chat works in.\n worktreePath: isObj(record.location) && typeof record.location.workspaceId === 'string' ? record.location.workspaceId.split('::').pop() : null\n })\n }\n return out\n } catch {\n return []\n } finally {\n try {\n db && db.close()\n } catch {}\n }\n}\n\n/** Live agent rows from worktree.ps, keyed by session id (their status wins over the stored one). */\nfunction liveAgents(worktrees) {\n const out = new Map()\n for (const w of worktrees) {\n for (const a of Array.isArray(w.agents) ? w.agents.filter(isObj) : []) {\n const tab = typeof a.paneKey === 'string' ? a.paneKey.split(':')[0] : ''\n if (!tab.startsWith(PANE_PREFIX)) {\n continue\n }\n const state = a.mainAgent && typeof a.mainAgent.state === 'string' ? a.mainAgent.state : a.state\n out.set(tab.slice(PANE_PREFIX.length), {\n agent: str(a.agentType, 40),\n title: str(a.conversationName, 200) || str(a.taskTitle, 200) || str(a.displayName, 200),\n status: state === 'working' ? 'working' : state === 'blocked' || state === 'waiting' || state === 'attention' ? 'attention' : 'idle',\n updatedAt: num(a.updatedAt)\n })\n }\n }\n return out\n}\n\n/**\n * The checkout this workspace is about: the one its newest chat works in, else the most recently\n * active one (a workspace on its own branch is a separate worktree, not the base clone at\n * /vercel/sandbox/project), else the base clone.\n */\nfunction workspaceCheckout(worktrees, sessions) {\n const byPath = new Map(worktrees.filter((w) => typeof w.path === 'string').map((w) => [w.path, w]))\n const newest = sessions\n .filter((s) => s.worktreePath && byPath.has(s.worktreePath))\n .sort((a, b) => (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0))[0]\n if (newest) {\n return byPath.get(newest.worktreePath)\n }\n const activity = (w) => Math.max(num(w.lastActivityAt) || 0, num(w.sortOrder) || 0)\n const ranked = [...byPath.values()].sort(\n (a, b) => activity(b) - activity(a) || Number(a.isMainWorktree === true) - Number(b.isMainWorktree === true)\n )\n return ranked[0] || null\n}\n\n/** `call(method, params)` -> result | null. Never throws: a missing piece is left out. */\nasync function gather(call, { workspaceId, snapshotId, reason, now, deadline, listSessions = () => [] }) {\n const timeLeft = () => deadline - Date.now()\n const ps = await call('worktree.ps', { limit: 20 })\n const worktrees = isObj(ps) && Array.isArray(ps.worktrees) ? ps.worktrees.filter(isObj) : []\n const stored = listSessions()\n const project = workspaceCheckout(worktrees, stored)\n const selector = project && typeof project.path === 'string' ? `path:${project.path}` : `path:${PROJECT}`\n const [status, log] = await Promise.all([\n call('git.status', { worktree: selector, includeLineStats: true }),\n call('git.history', { worktree: selector, limit: LIMITS.commits })\n ])\n const live = liveAgents(worktrees)\n const byId = new Map()\n for (const s of stored) {\n byId.set(s.sessionId, s)\n }\n for (const [sessionId, a] of live) {\n byId.set(sessionId, { ...(byId.get(sessionId) || { sessionId, open: true }), ...Object.fromEntries(Object.entries(a).filter(([, v]) => v !== null)) })\n }\n // Open chats first, then newest activity.\n const picked = [...byId.values()]\n .filter((s) => typeof s.sessionId === 'string')\n .sort((a, b) => Number(Boolean(b.open)) - Number(Boolean(a.open)) || (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0))\n .slice(0, LIMITS.sessions)\n const sessions = []\n for (const s of picked) {\n const history = timeLeft() > 1_000 ? await call('agentSession.history', { sessionId: s.sessionId, direction: 'tail', limit: LIMITS.messagesPerSession }) : null\n let { messages, hasOlder } = messagesOf(history)\n if (messages.length === 0) {\n // No readable history (or out of time): the stored last turn still says what happened.\n const at = s.lastAt || s.updatedAt || 0\n messages = [\n ...(s.lastPrompt ? [{ itemId: `${s.sessionId}:last-prompt`, role: 'user', text: s.lastPrompt, at }] : []),\n ...(s.lastReply ? [{ itemId: `${s.sessionId}:last-reply`, role: 'assistant', text: s.lastReply, at }] : [])\n ]\n hasOlder = hasOlder || messages.length > 0\n }\n sessions.push({\n sessionId: s.sessionId.slice(0, 200),\n agent: s.agent || null,\n title: s.title || null,\n status: STATUSES.has(s.status) ? s.status : 'unknown',\n turnOutcome: s.turnOutcome || null,\n updatedAt: num(s.updatedAt),\n messages: messages.slice(-LIMITS.messagesPerSession),\n truncated: hasOlder || messages.length > LIMITS.messagesPerSession\n })\n }\n return {\n v: 1,\n workspaceId,\n snapshotId,\n capturedAt: now,\n reason,\n git: gitOf(status, log),\n pr: prOf(project && project.linkedPR),\n sessions\n }\n}\n\n/** Cuts the oldest messages (then long texts, then sessions) until the JSON fits the budget. */\nfunction fitToBudget(payload, maxBytes = MAX_PLAIN_BYTES) {\n const size = () => Buffer.byteLength(JSON.stringify(payload))\n let guard = 0\n while (size() > maxBytes && guard++ < 10_000) {\n const longest = payload.sessions.reduce((best, s) => (!best || s.messages.length > best.messages.length ? s : best), null)\n if (longest && longest.messages.length > 4) {\n longest.messages.shift()\n longest.truncated = true\n continue\n }\n const longText = payload.sessions.flatMap((s) => s.messages).find((m) => m.text.length > 500)\n if (longText) {\n longText.text = `${longText.text.slice(0, 500)}…`\n continue\n }\n if (payload.git && payload.git.changes.length > 20) {\n payload.git.changes = payload.git.changes.slice(0, 20)\n continue\n }\n if (payload.sessions.length > 1) {\n payload.sessions.pop()\n continue\n }\n payload.sessions = []\n break\n }\n return payload\n}\n\n// Fails closed without HOME (signingKey refuses a relative path).\nconst stateDir = process.env.HOME ? path.join(process.env.HOME, '.orca-sandbox') : ''\n\nasync function main() {\n const started = Date.now()\n const env = process.env\n if (process.argv[2] === '--signer-public-key') {\n // For orca-sandbox-grant: pairing devices learn (and pin) this workspace's signer.\n process.stdout.write(`${signingKey(stateDir).publicKeyB64}\\n`)\n return\n }\n const snapshotId = env.ORCA_READ_SNAPSHOT_ID || ''\n const workspaceId = env.ORCA_READ_WORKSPACE_ID || ''\n if (!/^rsn_[0-9a-f]{24}$/.test(snapshotId) || !/^sbx_[0-9a-f]{24}$/.test(workspaceId)) {\n process.stderr.write('bad ids\\n')\n process.exit(2)\n }\n let recipients\n try {\n recipients = JSON.parse(env.ORCA_READ_RECIPIENTS || '[]')\n } catch {\n recipients = null\n }\n if (!Array.isArray(recipients) || recipients.length === 0) {\n process.stderr.write('no recipients\\n')\n process.exit(2)\n }\n const dataDir = env.ORCA_USER_DATA_PATH || path.join(env.HOME || '', '.orcad-data')\n let metadata\n try {\n metadata = JSON.parse(fs.readFileSync(path.join(dataDir, 'orca-runtime.json'), 'utf8'))\n } catch {\n metadata = null\n }\n if (!metadata || !metadata.authToken) {\n process.stderr.write('orcad not running\\n')\n process.exit(3)\n }\n const deadline = started + TOTAL_BUDGET_MS\n const call = (method, params) => rpc(metadata, method, params, Math.max(250, Math.min(CALL_TIMEOUT_MS, deadline - Date.now())))\n const payload = fitToBudget(\n await gather(call, { workspaceId, snapshotId, reason: (env.ORCA_READ_REASON || 'sleep').slice(0, 20), now: Date.now(), deadline, listSessions: () => storedSessions(dataDir) })\n )\n const out = seal(payload, recipients, workspaceId, snapshotId)\n out.signature = sign(out, signingKey(stateDir))\n // Timing only: counts and sizes would describe the plaintext to the control plane's logs.\n out.stats = { collectMs: Date.now() - started }\n process.stdout.write(`${JSON.stringify(out)}\\n`)\n}\n\nmodule.exports = { workspaceCheckout, seal, sign, signingKey, gather, fitToBudget, messagesOf, gitOf, prOf, rpc, storedSessions, liveAgents }\n\nif (require.main === module) {\n // A fixed message: an error text could carry workspace content into the control plane's logs.\n main().catch(() => {\n process.stderr.write('read snapshot failed\\n')\n process.exit(1)\n })\n}\n","orca-git-as":"#!/usr/bin/env bash\n# Runs git as the teammate whose message started this agent's turn: their GitHub identity for\n# pushes/PRs (this repository only) and their commit author.\n# orca-git-as e.g. orca-git-as push origin HEAD\n# orca-git-as --as refuses unless that member really sent the message\n# Orca attests the sender from the paired device that sent the message, never from arguments or\n# message text. Without an attested sender (not run from an agent, or the owner's local session) it\n# runs plain git with the workspace identity.\nset -euo pipefail\nexpect=''\nif [ \"${1:-}\" = '--as' ]; then\n expect=\"${2:-}\"\n shift 2 || { echo 'usage: orca-git-as [--as ] ' >&2; exit 2; }\n case \"$expect\" in '' | *[!A-Za-z0-9_.:-]*) echo 'orca-git-as: bad member id' >&2; exit 2 ;; esac\nfi\nset +e\nfile=\"$(ORCA_GIT_AS=\"$expect\" sudo -n --preserve-env=ORCA_GIT_AS,ORCA_TERMINAL_HANDLE,ORCA_PANE_KEY,ORCA_AGENT_LAUNCH_TOKEN,ORCA_AGENT_SESSION_ID \\\n /opt/orca/bin/orca-git-identity)\"\nstatus=$?\nset -e\ncase \"$status\" in\n 0)\n trap 'rm -f \"$file\"' EXIT\n # GIT-COAUTHOR: a member whose GitHub identity can't be used right now: the workspace identity commits, with\n # them as co-author (the trailer goes right after the `commit` subcommand). Never for any other command.\n coauthor=\"$(git config -f \"$file\" orca.coauthor 2>/dev/null || true)\"\n if [ -n \"$coauthor\" ] && [ -z \"$(git config -f \"$file\" user.email 2>/dev/null || true)\" ]; then\n if [ -n \"$expect\" ]; then\n echo \"orca-git-as: $expect's GitHub connection can't be used right now; refusing to act as them. Reconnect GitHub in Settings → Account.\" >&2\n exit 4\n fi\n echo 'orca-git-as: no teammate identity for this turn; using the workspace identity' >&2\n args=()\n skip=0\n placed=0\n for arg in \"$@\"; do\n args+=(\"$arg\")\n [ \"$placed\" = 0 ] || continue\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n -*) ;;\n commit) args+=(--trailer \"Co-authored-by: $coauthor\"); placed=1 ;;\n *) placed=1 ;;\n esac\n done\n git -c \"include.path=$file\" \"${args[@]}\"\n exit\n fi\n git -c \"include.path=$file\" \"$@\"\n ;;\n 3)\n echo 'orca-git-as: no teammate identity for this turn; using the workspace identity' >&2\n exec git \"$@\"\n ;;\n *) exit 4 ;;\nesac\n","orca-git-identity":"#!/usr/bin/env bash\n# Root helper behind `orca-git-as` (sudoers: the VM user may run only this). Asks orcad, as the\n# calling agent, which paired device sent the message that started the agent's latest turn\n# (`orca sender`: orcad identifies the agent from its launch evidence, never from arguments), maps\n# that device to a workspace member, and prints that member's git config file for the caller to\n# include. Optional ORCA_GIT_AS: the member the agent expects; any other answer is refused.\n# Exit codes: 0 printed a config path; 3 no member identity (use the workspace identity); 4 refused.\nset -euo pipefail\nDIR=/etc/orca/members\ncaller=\"${SUDO_USER:-}\"\ncase \"$caller\" in '' | root | *[!a-z0-9_-]*) echo 'orca-git-identity: run through orca-git-as' >&2; exit 4 ;; esac\n# orcad's own data dir and HOME (the agent's user may not use its passwd home, e.g. HOME=/vercel).\norcad_pid=\"$(pgrep -u \"$caller\" -f orcad-server.js | head -n 1 || true)\"\n[ -n \"$orcad_pid\" ] || exit 3\norcad_env() { tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n \"s/^$1=//p\" | head -n 1; }\nhome=\"$(orcad_env HOME)\"\ndata=\"$(orcad_env ORCA_USER_DATA)\"\ndata=\"${data:-$home/.orcad-data}\"\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\ncli=/opt/orca/runtime/orcad/out/cli/index.js\n# Only the evidence variables orcad needs reach the query, which runs as the caller, not root.\nanswer=\"$(sudo -u \"$caller\" env -i HOME=\"$home\" PATH=/usr/bin:/bin ORCA_USER_DATA_PATH=\"$data\" \\\n ${ORCA_TERMINAL_HANDLE:+ORCA_TERMINAL_HANDLE=\"$ORCA_TERMINAL_HANDLE\"} \\\n ${ORCA_PANE_KEY:+ORCA_PANE_KEY=\"$ORCA_PANE_KEY\"} \\\n ${ORCA_AGENT_LAUNCH_TOKEN:+ORCA_AGENT_LAUNCH_TOKEN=\"$ORCA_AGENT_LAUNCH_TOKEN\"} \\\n ${ORCA_AGENT_SESSION_ID:+ORCA_AGENT_SESSION_ID=\"$ORCA_AGENT_SESSION_ID\"} \\\n timeout 15 \"$node\" \"$cli\" sender --json 2>/dev/null || true)\"\ndevice=\"$(jq -r '.result.sender.deviceId // empty' <<<\"$answer\" 2>/dev/null || true)\"\nif [ -z \"$device\" ] || [ ! -s \"$DIR/devices.json\" ]; then\n if [ -n \"${ORCA_GIT_AS:-}\" ]; then\n echo \"orca-git-as: Orca cannot confirm that $ORCA_GIT_AS sent this agent's latest message; refusing to push as them.\" >&2\n exit 4\n fi\n exit 3\nfi\nmember=\"$(jq -r --arg d \"$device\" '.[$d] // empty' \"$DIR/devices.json\")\"\nif [ -z \"$member\" ]; then\n [ -n \"${ORCA_GIT_AS:-}\" ] && { echo \"orca-git-as: the sender's device is not linked to a workspace member; refusing.\" >&2; exit 4; }\n exit 3\nfi\nif [ -n \"${ORCA_GIT_AS:-}\" ] && [ \"$ORCA_GIT_AS\" != \"$member\" ]; then\n echo \"orca-git-as: this agent's latest message came from $member, not $ORCA_GIT_AS; refusing to push as someone else.\" >&2\n exit 4\nfi\nfile=\"$DIR/$(printf '%s' \"$member\" | tr ':' '_').gitconfig\"\n[ -s \"$file\" ] || exit 3\n# The caller reads the identity through this one-shot copy (owned by them, removed by orca-git-as).\nout=\"$(sudo -u \"$caller\" mktemp)\"\ncat \"$file\" >\"$out\"\necho \"$out\"\n","orcad-boot":"#!/usr/bin/env node\n// Starts orcad from a V8 code cache taken after a full startup, so a boot skips compiling the\n// functions startup runs. NODE_COMPILE_CACHE only stores what V8 compiles before the bundle runs\n// (about 5 of its 15 MB); every other function compiled lazily on every boot (~300 ms of wake).\n// orcad-boot --code-cache [--write-code-cache] [orcad args...]\n// orcad sees the argv `node [orcad args...]`, as if started directly.\n// --write-code-cache (the image's smoke run) writes the cache when orcad exits. The cache is used\n// only when its header matches this bundle's bytes and this Node; otherwise orcad loads exactly as\n// before (plain require, which NODE_COMPILE_CACHE still serves). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst fs = process.getBuiltinModule('node:fs')\nconst path = process.getBuiltinModule('node:path')\nconst vm = process.getBuiltinModule('node:vm')\nconst zlib = process.getBuiltinModule('node:zlib')\nconst { Module, createRequire } = process.getBuiltinModule('node:module')\n\nconst MAGIC = 'orcad-code-cache-v1'\n\nconst args = process.argv.slice(2)\nlet cacheFile = null\nlet writeCache = false\nwhile (args[0] === '--code-cache' || args[0] === '--write-code-cache') {\n if (args[0] === '--code-cache') {\n cacheFile = args[1]\n args.splice(0, 2)\n } else {\n writeCache = true\n args.shift()\n }\n}\nconst entry = args.shift()\nif (!entry || !cacheFile) {\n console.error('usage: orcad-boot --code-cache [--write-code-cache] [args...]')\n process.exit(2)\n}\n// As for `node `: argv[1] is the resolved path, __filename the real one.\nprocess.argv = [process.argv[0], path.resolve(entry), ...args]\nlet file = process.argv[1]\ntry {\n file = fs.realpathSync(file)\n} catch {\n // A missing bundle fails in require below, as it would under plain node.\n}\n\n// One line of identity: a cache from another bundle or Node must never run (V8 only checks length).\nfunction cacheHeader(bytes) {\n return `${MAGIC} ${process.version} ${process.arch} ${bytes.length} ${zlib.crc32(bytes)}\\n`\n}\n\nfunction readCache(header) {\n let data\n try {\n data = fs.readFileSync(cacheFile)\n } catch {\n return null\n }\n const headerLength = Buffer.byteLength(header)\n if (data.length <= headerLength || data.toString('latin1', 0, headerLength) !== header) {\n console.error('orcad-boot: code cache is for another orcad build; loading without it')\n return null\n }\n return data.subarray(headerLength)\n}\n\nfunction runCompiled(header, source, cachedData) {\n // A vm.Script can serialize what startup compiled; the CommonJS loader cannot. Same wrapper,\n // filename and require as the loader, and import() resolves from the bundle like it does there.\n const options = {\n filename: file,\n cachedData: cachedData ?? undefined,\n importModuleDynamically: vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER\n }\n // Node flags the loader option experimental once, on the first import() through it. Spend that\n // one-time warning here, unprinted, so orcad's stderr stays as it was.\n const emitWarning = process.emitWarning\n process.emitWarning = (warning, ...rest) => {\n if (!String(warning?.message ?? warning).includes('USE_MAIN_CONTEXT_DEFAULT_LOADER')) {\n emitWarning.call(process, warning, ...rest)\n }\n }\n let script\n try {\n new vm.Script('import(\"node:path\")', {\n filename: file,\n importModuleDynamically: options.importModuleDynamically\n })\n .runInThisContext()\n .catch(() => {})\n script = new vm.Script(Module.wrap(source), options)\n } finally {\n process.emitWarning = emitWarning\n }\n if (cachedData && script.cachedDataRejected) {\n console.error('orcad-boot: V8 rejected the code cache (other V8 flags?); compiled without it')\n }\n if (writeCache) {\n process.on('exit', () => {\n try {\n const data = script.createCachedData()\n const temporary = `${cacheFile}.${process.pid}.tmp`\n fs.writeFileSync(temporary, Buffer.concat([Buffer.from(header, 'latin1'), data]))\n fs.renameSync(temporary, cacheFile)\n console.error(`orcad-boot: wrote ${data.length} bytes of code cache`)\n } catch (error) {\n console.error(`orcad-boot: could not write the code cache: ${error.message}`)\n }\n })\n }\n const module = new Module(file, null)\n module.filename = file\n module.paths = Module._nodeModulePaths(path.dirname(file))\n const compiled = script.runInThisContext()\n compiled.call(module.exports, module.exports, createRequire(file), module, file, path.dirname(file))\n}\n\n// Locals, so neither the bundle bytes nor the cache outlive the compile.\nfunction boot() {\n // Older Node (no crc32 or main-context import()) loads as before.\n if (typeof zlib.crc32 === 'function' && vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER) {\n let bytes = null\n try {\n bytes = fs.readFileSync(file)\n } catch {\n // Missing or unreadable: require reports it as plain node would.\n }\n if (bytes) {\n const header = cacheHeader(bytes)\n const cachedData = readCache(header)\n if (cachedData || writeCache) {\n runCompiled(header, bytes.toString('utf8'), cachedData)\n return\n }\n }\n }\n createRequire(file)(file)\n}\n\nboot()\n","git":"#!/usr/bin/env bash\n# git for agents in Orca Cloud workspaces (first on orcad's PATH). Commands that author or publish\n# work run as the teammate whose message started this agent's turn (orca-git-as: orcad attests the\n# sender's paired device; root-only member identities). Everything else is plain git, untouched.\nreal=\"${ORCA_REAL_GIT:-/usr/bin/git}\"\nsub=''\nskip=0\nfor arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n -*) ;;\n *) sub=\"$arg\"; break ;;\n esac\ndone\n# CREATE-GIT-ASYNC: a new workspace answers before teammates' GitHub identities are installed. Until\n# they are (orca-sandbox-members writes git-setup.ready), commits and pushes wait up to 15 s rather\n# than go out under the workspace identity; a failed or stalled setup stops them with what to do.\n# Read-only git and fetches never wait (they use the workspace's own credentials, set before ready).\nhold_for_member_setup() {\n local state=\"${HOME:-/nonexistent}/.orca-sandbox\" ticks=0 since\n # A failed install on any boot (create or a later restart) refuses even with nothing pending.\n [ -f \"$state/git-setup.pending\" ] || [ -f \"$state/git-setup.failed\" ] || return 0\n since=\"$(cat \"$state/git-setup.pending\" 2>/dev/null || echo 0)\"\n case \"$since\" in '' | *[!0-9]*) since=0 ;; esac\n while [ -f \"$state/git-setup.pending\" ] && [ ! -f \"$state/git-setup.ready\" ] && [ ! -f \"$state/git-setup.failed\" ]; do\n # 15 s per command; a mark older than 2 min is a setup that died, not one still running.\n if [ \"$ticks\" -ge \"${ORCA_GIT_SETUP_WAIT_TICKS:-150}\" ] || [ $(($(date +%s) - since)) -gt 120 ]; then\n break\n fi\n sleep 0.1\n ticks=$((ticks + 1))\n done\n if [ -f \"$state/git-setup.ready\" ] || { [ ! -f \"$state/git-setup.pending\" ] && [ ! -f \"$state/git-setup.failed\" ]; }; then\n return 0\n fi\n if [ -f \"$state/git-setup.failed\" ]; then\n printf '%s\\n' \"orca: Orca couldn't set up your GitHub identity in this sandbox, so it stopped \\`git $sub\\` rather than use the wrong identity. Restart this workspace (right-click it in the sidebar > Restart), then try again.\" >&2\n else\n printf '%s\\n' \"orca: Orca is still setting up your GitHub identity in this sandbox, so it stopped \\`git $sub\\` rather than use the wrong identity. Try again in a few seconds. If this keeps happening, restart this workspace (right-click it in the sidebar > Restart).\" >&2\n fi\n exit 1\n}\n# A commit under the workspace identity (Orca ) says once per session how to use your own\n# (design-squad). /dev/shm is per boot: a wake or restart says it again.\nnudge_once() {\n [ \"$sub\" = commit ] || return 0\n local mark=\"${ORCA_GIT_NUDGE_DIR:-/dev/shm}/orca-git-nudge-$(id -u)\"\n [ -e \"$mark\" ] && return 0\n : >\"$mark\" 2>/dev/null || return 0\n printf '%s\\n' \"orca: This commit is authored as Orca . Connect GitHub in Settings → Account to commit as yourself.\" >&2\n}\n# PUSH-RAW-PROMPT: a push, pull or fetch to github.com that no credential covers (neither the person's\n# connected GitHub nor the App installation) must never fall through to git's own \"Username for\n# 'https://github.com':\" prompt. Prompts are off for that remote, and git's auth failure becomes one\n# plain line saying what to do.\ngithub_slug=''\ngithub_remote_slug() {\n local arg skip=0 seen=0 remote='' url\n for arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n if [ \"$seen\" = 0 ]; then\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n \"$sub\") seen=1 ;;\n esac\n continue\n fi\n case \"$arg\" in\n --repo=*) remote=\"${arg#--repo=}\"; break ;;\n -o | --push-option | --receive-pack | --upload-pack | --exec | --depth | --deepen | --shallow-since | --shallow-exclude | --refmap | --recurse-submodules-default | -j | --jobs) skip=1 ;;\n -*) ;;\n *) remote=\"$arg\"; break ;;\n esac\n done\n [ -n \"$remote\" ] || remote=\"$(\"$real\" config --get \"branch.$(\"$real\" symbolic-ref --short -q HEAD 2>/dev/null).remote\" 2>/dev/null || true)\"\n [ -n \"$remote\" ] || remote=origin\n case \"$remote\" in\n *://*) url=\"$remote\" ;;\n *) url=\"$(\"$real\" remote get-url \"$remote\" 2>/dev/null || printf '%s' \"$remote\")\" ;;\n esac\n case \"$url\" in\n https://github.com/* | https://*@github.com/*) url=\"${url#*github.com/}\" ;;\n *) return 0 ;;\n esac\n url=\"${url%.git}\"\n url=\"${url%/}\"\n case \"$url\" in */*/*) url=\"${url%%/*}/$(printf '%s' \"${url#*/}\" | cut -d/ -f1)\" ;; esac\n case \"$url\" in [A-Za-z0-9_.-]*/[A-Za-z0-9_.-]*) github_slug=\"$url\" ;; esac\n}\nno_access_line() {\n local owner=\"${github_slug%%/*}\" verb='push to'\n [ \"$sub\" = push ] || verb='read'\n printf '%s\\n' \"orca: Orca Cloud can't $verb $github_slug. Install the Orca GitHub App on $owner, or connect GitHub in Settings → Account.\" >&2\n}\n# GitHub's \"not found\" is a typo'd name or a private repo it won't confirm: say which half fits whom.\nnot_found_line() {\n printf '%s\\n' \"orca: Orca Cloud can't find $github_slug. Check the name, or install the Orca GitHub App on ${github_slug%%/*} if it's private.\" >&2\n}\n# PUSH-CAP (E3): git to github.com goes through Orca's egress proxy, whose edge refuses request bodies over\n# ~100 MB with a bare 413. Say what happened and how to split the push instead.\ntoo_large_line() {\n printf '%s\\n' \"orca: This push is over Orca Cloud's limit of about 100 MB per push. Push fewer commits at a time, for example git push origin HEAD~5:refs/heads/, then run git push again.\" >&2\n}\n# orca-git-as's own fallback line is replaced by the nudge; GitHub auth failures by the plain line.\nfallback_filter() {\n local line said=0 said413=0\n while IFS= read -r line || [ -n \"$line\" ]; do\n case \"$line\" in\n 'orca-git-as: no teammate identity'*) nudge_once ;;\n 'remote: Repository not found.'* | \"fatal: repository 'https://github.com/\"*\"' not found\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said\" = 1 ] || not_found_line\n said=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *\"could not read Username for 'https://github.com'\"* | *\"could not read Password for 'https://\"*\"github.com'\"* | \\\n *\"Authentication failed for 'https://github.com/\"* | 'remote: Permission to '*' denied to '* | \\\n *\"The requested URL returned error: 403\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said\" = 1 ] || no_access_line\n said=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *\"RPC failed; HTTP 413\"* | *\"The requested URL returned error: 413\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said413\" = 1 ] || too_large_line\n said413=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *) printf '%s\\n' \"$line\" ;;\n esac\n done\n}\ncase \"$sub\" in\n push | pull | fetch)\n github_remote_slug \"$@\"\n if [ -n \"$github_slug\" ]; then\n export GIT_TERMINAL_PROMPT=0 GCM_INTERACTIVE=never\n fi\n ;;\nesac\ngit_as=\"${ORCA_GIT_AS:-/opt/orca/bin/orca-git-as}\"\ncase \"$sub\" in\n commit | push | merge | rebase | cherry-pick | revert | am | pull | tag)\n hold_for_member_setup\n # Outside an agent turn (no attested sender) orca-git-as falls back to the workspace identity.\n if [ -n \"${ORCA_TERMINAL_HANDLE:-}${ORCA_AGENT_SESSION_ID:-}\" ] && [ -x \"$git_as\" ]; then\n PATH=\"/usr/bin:/bin:$PATH\" exec \"$git_as\" \"$@\" 2> >(fallback_filter >&2)\n fi\n # No terminal or agent turn to attribute it to: the workspace identity.\n nudge_once\n ;;\nesac\nif [ -n \"$github_slug\" ]; then\n exec \"$real\" \"$@\" 2> >(fallback_filter >&2)\nfi\nexec \"$real\" \"$@\"\n","gh":"#!/usr/bin/env bash\n# gh for agents in Orca Cloud workspaces: GitHub actions an agent takes in a teammate's turn (gh pr create,\n# comments, reviews) act as that teammate, through their own placeholder, swapped at egress for their GitHub\n# user token (never in the VM). Orcad attests the sender exactly as for git (orca-git-identity). With no\n# attested teammate, or before the control plane turns this on (ORCA_GH_AS_MEMBER=on), gh runs as before:\n# the workspace identity.\n# Layout: the real gh is /opt/orca/tools/gh/bin/gh (off PATH); /opt/orca/tools/bin/gh, first on every agent\n# PATH, is a link to this script. Symlinks are resolved so the link never finds itself.\nself=\"$(readlink -f \"$0\" 2>/dev/null || echo \"$0\")\"\nreal=\"${ORCA_REAL_GH:-}\"\nif [ -z \"$real\" ] && [ -x \"${ORCA_HOME:-/opt/orca}/tools/gh/bin/gh\" ]; then\n real=\"${ORCA_HOME:-/opt/orca}/tools/gh/bin/gh\"\nfi\nif [ -z \"$real\" ]; then\n IFS=: read -r -a dirs <<<\"${PATH:-/usr/bin:/bin}\"\n for dir in \"${dirs[@]}\" /usr/local/bin /usr/bin; do\n if [ -x \"$dir/gh\" ] && [ \"$(readlink -f \"$dir/gh\" 2>/dev/null || echo \"$dir/gh\")\" != \"$self\" ]; then\n real=\"$dir/gh\"\n break\n fi\n done\nfi\n[ -n \"$real\" ] || { echo 'gh: not installed in this sandbox' >&2; exit 127; }\nif [ \"${ORCA_GH_AS_MEMBER:-}\" = on ] && [ -n \"${ORCA_TERMINAL_HANDLE:-}${ORCA_AGENT_SESSION_ID:-}\" ]; then\n file=\"$(sudo -n --preserve-env=ORCA_TERMINAL_HANDLE,ORCA_PANE_KEY,ORCA_AGENT_LAUNCH_TOKEN,ORCA_AGENT_SESSION_ID \\\n /opt/orca/bin/orca-git-identity 2>/dev/null)\" && [ -n \"$file\" ] && {\n token=\"$(git config -f \"$file\" orca.ghtoken 2>/dev/null || true)\"\n rm -f \"$file\"\n case \"$token\" in\n orca-ph-* | orca-mph-*) exec env GH_TOKEN=\"$token\" GITHUB_TOKEN=\"$token\" \"$real\" \"$@\" ;;\n esac\n }\nfi\nexec \"$real\" \"$@\"\n","docker":"#!/usr/bin/env bash\n# docker for Orca Cloud workspaces (first on orcad's PATH; PARITY-DOCKER). The golden image does not\n# ship Docker (it made every create ~5 s slower): the first docker command in a workspace installs\n# Ubuntu's pinned packages, then starts dockerd as root inside this workspace's own VM, then everything\n# is plain docker. Running containers stop when the workspace sleeps; images and the install stay.\n# The control plane can turn Docker off (SANDBOX_DOCKER=off): orca-sandbox-start then leaves\n# ~/.orca-sandbox/docker.off and this refuses with a plain message instead.\n# The Worker installs this script into every workspace on start, so changing the pins below is a\n# Worker deploy, not a golden rotation.\nreal=\"${ORCA_REAL_DOCKER:-/usr/bin/docker}\"\nstate=\"${HOME:-/nonexistent}/.orca-sandbox\"\nlog=\"${ORCA_DOCKERD_LOG:-/tmp/orca-dockerd.log}\"\nsudo_cmd=\"${ORCA_DOCKER_SUDO-sudo -n}\"\npackages=\"${ORCA_DOCKER_PACKAGES:-docker.io=29.1.3-0ubuntu4.1 docker-compose-v2=2.40.3+ds1-0ubuntu1 docker-buildx=0.30.1-0ubuntu1}\"\n\n# fd 3 is the caller's stderr even while apt's output goes to the log.\nexec 3>&2\nsay() { printf '%s\\n' \"$@\" >&3; }\n\nif [ -f \"$state/docker.off\" ]; then\n say \"orca: Docker is turned off for Orca Cloud workspaces right now.\"\n exit 1\nfi\n\n# Only commands that need the daemon start it; `docker --version`, `docker help` and the like don't.\nneeds_daemon=1\ncase \"${1:-}\" in '' | -v | --version | help | -h | --help) needs_daemon=0 ;; esac\n# A DOCKER_HOST pointing elsewhere is the user's choice: never start a local daemon for it.\n[ -n \"${DOCKER_HOST:-}\" ] && needs_daemon=0\n\ndaemon_up() { \"$real\" info >/dev/null 2>&1; }\n\nif [ -x \"$real\" ] && { [ \"$needs_daemon\" = 0 ] || daemon_up; }; then\n exec \"$real\" \"$@\"\nfi\n\n# First use (install) or a stopped daemon (start): two first commands at once must not run apt twice\n# or start two daemons.\nexec 8>\"${ORCA_DOCKER_LOCK:-/tmp/orca-dockerd.lock}\"\nflock -w 600 8 || true\n\nif [ ! -x \"$real\" ]; then\n say \"orca: Setting up Docker in this workspace (first use, about 10 seconds)...\"\n apt=\"${ORCA_DOCKER_APT:-apt-get}\"\n if ! $sudo_cmd env DEBIAN_FRONTEND=noninteractive \"$apt\" update -qq >>\"$log\" 2>&1; then\n say \"orca: Couldn't set up Docker in this workspace because the Ubuntu package archive couldn't be reached. Run docker again to retry. Details: $log\"\n exit 1\n fi\n say \"orca: Downloading and installing Docker (about 110 MB)...\"\n # shellcheck disable=SC2086 # $packages is one word per package\n if ! $sudo_cmd env DEBIAN_FRONTEND=noninteractive \"$apt\" install -y -qq --no-install-recommends $packages >>\"$log\" 2>&1 ||\n [ ! -x \"$real\" ]; then\n say \"orca: Couldn't set up Docker in this workspace. Run docker again to retry. Details: $log\"\n exit 1\n fi\n # overlay2; capped local logs; the mirror first (Docker Hub's anonymous limit is per IP, and\n # sandboxes share egress IPs). Left alone if the user already has a config.\n config=\"${ORCA_DOCKER_CONFIG:-/etc/docker/daemon.json}\"\n if [ ! -e \"$config\" ]; then\n $sudo_cmd mkdir -p \"$(dirname \"$config\")\" &&\n printf '%s\\n' '{\"storage-driver\":\"overlay2\",\"log-driver\":\"local\",\"log-opts\":{\"max-size\":\"10m\",\"max-file\":\"3\"},\"registry-mirrors\":[\"https://mirror.gcr.io\"]}' |\n $sudo_cmd tee \"$config\" >/dev/null\n fi\n say \"orca: Docker is set up.\"\nfi\n\nif [ \"$needs_daemon\" = 1 ] && ! daemon_up; then\n # The socket belongs to this user's group, so docker works in this shell without a new login.\n $sudo_cmd \"${ORCA_DOCKERD:-/usr/bin/dockerd}\" --group \"$(id -gn)\" >>\"$log\" 2>&1 3>&- 8>&- /dev/null || true\n ticks=0\n until daemon_up; do\n if [ \"$ticks\" -ge \"${ORCA_DOCKER_WAIT_TICKS:-150}\" ]; then\n say \"orca: Docker couldn't start in this workspace. Run docker again to retry. Details: $log\"\n exit 1\n fi\n sleep 0.1\n ticks=$((ticks + 1))\n done\n # Said where agents and people see it: what differs from a laptop. Containers stopping on sleep is\n # said on every start; the proxy certificate only on the workspace's first.\n say \"orca: Docker started in this workspace. Running containers stop when the workspace sleeps (images stay).\"\n if [ ! -e \"$state/docker.ca-noticed\" ]; then\n say \"orca: Containers that call github.com or an agent's API need to trust this workspace's proxy certificate. Mount it:\" \\\n \" -v /etc/pki/ca-trust/source/anchors/vercel-proxy-ca.pem:/usr/local/share/ca-certificates/orca-proxy.crt:ro\" \\\n \"then run update-ca-certificates in the container, or point NODE_EXTRA_CA_CERTS or SSL_CERT_FILE at it.\"\n mkdir -p \"$state\" 2>/dev/null && : >\"$state/docker.ca-noticed\"\n fi\nfi\nexec 8>&-\nexec \"$real\" \"$@\"\n"} -export const VM_SCRIPTS_HASH: string = "2dc4bcdb" -export const VM_SCRIPTS_STAMP: number = 1794811929 +export const VM_SCRIPT_SOURCES: BuildInputs['vmScripts'] = {"orca-sandbox-start":"#!/usr/bin/env bash\n# Starts orcad for this boot (idempotent) and prints its recipe line:\n# {\"schemaVersion\":1,\"pairingCode\":\"orca://pair?...\",\"projectRoot\":\"/vercel/sandbox/project\"}\n# Env from the control plane: ORCA_SANDBOX_ID, ORCA_PUBLIC_WSS, optional ORCA_REPO_URL/ORCA_REPO_REF,\n# ORCA_GITHUB_PLACEHOLDER, ORCA_SECRET_ENV (`NAME=` lines: org/personal/repo secrets for\n# orcad and its agents), ORCA_SHARE_PROXY_KEY (this session's share-link proxy key, port 6769),\n# ORCA_DOCKER (on|off: the control plane's Docker switch for the `docker` shim).\n# Never prints anything else on stdout's last line.\n# With ORCA_READY_VIA=file it prints {\"schemaVersion\":1,\"readyFile\":\"\"} instead and the control\n# plane reads the offer with the files API: the provider keeps command stdout as logs, not files.\n# With ORCA_READY_KEY too (64 hex chars, this call's key; env is not kept) the pointer also carries\n# \"sealedOffer\": \".\", which saves that round trip.\n# Managed env for every process orcad starts: ORCA_IS_CLOUD=1, ORCA_SANDBOX_ID, ORCA_ROOT_PATH,\n# ORCA_WORKTREE_PATH, ORCA_WORKSPACE_PATH, ORCA_WORKSPACE_NAME, ORCA_DEFAULT_BRANCH, ORCA_PORT and the\n# CONDUCTOR_* names imported Conductor scripts read.\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nPROJECT=/vercel/sandbox/project\nmkdir -p \"$STATE\"\n# Only print_ready uses the key; nothing this script starts inherits it.\nready_key=\"${ORCA_READY_KEY:-}\"\nunset ORCA_READY_KEY\n[[ \"$ready_key\" =~ ^[0-9a-f]{64}$ ]] || ready_key=''\nexec 9>\"$STATE/start.lock\"\nflock -w 60 9\n# Background children close fd 9 (`9>&-`): an orcad that inherited it would hold the lock for its whole\n# life and every later start (resume of a running sandbox, a retried create) would wait out the 60 s.\n\n# orcad only lists a project once a client registers it (the desktop does on connect), so API, MCP,\n# routine and phone sessions saw no repo. Register the workspace project at every start, in the\n# background (ready is not delayed); `repo add` of an already-registered path is a no-op error.\nregister_project() {\n [ -x \"$ORCA_HOME/bin/orca\" ] && [ -d \"$PROJECT\" ] || return 0\n local kind=() name=()\n [ -e \"$PROJECT/.git\" ] || kind=(--kind folder)\n # The checkout lives at .../project; name it after the repository (owner/name.git -> name).\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n local base=\"${ORCA_REPO_URL%/}\"\n base=\"${base##*/}\"\n base=\"${base%.git}\"\n [ -n \"$base\" ] && name=(--display-name \"$base\")\n fi\n setsid \"$ORCA_HOME/bin/orca\" repo add --path \"$PROJECT\" \"${kind[@]}\" \"${name[@]}\" --json \\\n >\"$STATE/register-project.log\" 2>&1 &- &\n}\n\nprint_ready() {\n if [ \"${ORCA_READY_VIA:-}\" = file ]; then\n local sealed='' iv\n if [ -n \"$ready_key\" ] && command -v openssl >/dev/null; then\n iv=\"$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')\"\n # Best effort: without it the control plane reads the file, as before.\n sealed=\"$(tail -n 1 \"$STATE/ready.json\" | openssl enc -aes-256-ctr -K \"$ready_key\" -iv \"$iv\" -nosalt | base64 -w0)\" &&\n sealed=\"$iv.$sealed\" || sealed=''\n fi\n printf '{\"schemaVersion\":1,\"readyFile\":\"%s\"%s}\\n' \"$STATE/ready.json\" \"${sealed:+,\\\"sealedOffer\\\":\\\"$sealed\\\"}\"\n else\n tail -n 1 \"$STATE/ready.json\"\n fi\n}\n# Command stderr is kept by the provider: strip injected values and credential shapes from log tails.\nredact_log() {\n local text kv value\n text=\"$(cat)\"\n for kv in ${agent_env[@]+\"${agent_env[@]}\"}; do\n value=\"${kv#*=}\"\n if [ \"${#value}\" -ge 8 ]; then\n text=\"${text//\"$value\"/[REDACTED]}\"\n fi\n done\n printf '%s\\n' \"$text\" | sed -E \\\n -e 's#orca://[^[:space:]]+#[REDACTED_PAIRING]#g' \\\n -e 's#(gh[pousr]_|github_pat_|sk-|vc[kpiar]_)[A-Za-z0-9._-]{16,}#[REDACTED_TOKEN]#g' \\\n -e 's#eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}#[REDACTED_JWT]#g' \\\n -e 's#(Authorization|authorization):[[:space:]]*[A-Za-z]+[[:space:]]+[^[:space:]]+#\\1: [REDACTED]#g'\n}\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n\n# Share-link proxy (port 6769): answers only requests the control plane signed with this session's\n# key, so its public route is useless on its own. The key goes in on stdin (printf is a builtin), so\n# it never appears in any argv or in the proxy's /proc//environ.\nstart_share_proxy() {\n [ -n \"${ORCA_SHARE_PROXY_KEY:-}\" ] && [ -x \"$ORCA_HOME/bin/orca-share-proxy\" ] || return 0\n if [ \"$(cat \"$STATE/share-proxy.boot\" 2>/dev/null || true)\" = \"$boot_id\" ] \\\n && kill -0 \"$(cat \"$STATE/share-proxy.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n return 0\n fi\n printf '%s' \"$ORCA_SHARE_PROXY_KEY\" | env -i HOME=\"$HOME\" LANG=C.UTF-8 PATH=/usr/bin:/bin \\\n setsid \"$node\" \"$ORCA_HOME/bin/orca-share-proxy\" >\"$STATE/share-proxy.log\" 2>&1 9>&- &\n echo $! >\"$STATE/share-proxy.pid\"\n printf '%s' \"$boot_id\" >\"$STATE/share-proxy.boot\"\n}\n\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\n# CREATE-GIT-ASYNC: a create answers before member identities are installed; `git` holds commits and\n# pushes until orca-sandbox-members (or the control plane) marks this setup ready or failed. Marked\n# before the already-started exit below: a pooled VM's orcad may be up before its create claims it.\nif [ \"${ORCA_GIT_SETUP:-}\" = pending ]; then\n rm -f \"$STATE/git-setup.ready\" \"$STATE/git-setup.failed\"\n date +%s >\"$STATE/git-setup.pending\"\nfi\n# PARITY-DOCKER: the control plane's Docker switch (SANDBOX_DOCKER) for the `docker` shim. Only a\n# start that says so changes it; a retried or repair start (no ORCA_DOCKER) keeps the last answer.\ncase \"${ORCA_DOCKER:-}\" in\n off) : >\"$STATE/docker.off\" ;;\n on) rm -f \"$STATE/docker.off\" ;;\nesac\nstart_share_proxy\nunset ORCA_SHARE_PROXY_KEY\n# MEMGUARD: OOM-killer ranks that spare orcad and terminals, a guard that stops the largest build or\n# test before the VM stalls, on-demand swap and a /dev/shm sized for browsers. Before the\n# already-started exit so a repair start brings a dead guard back; it returns at once.\nsudo -n \"$ORCA_HOME/bin/orca-memguard\" start /dev/null 2>&1 9>&- || true\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" = \"$boot_id\" ] && [ -s \"$STATE/ready.json\" ] \\\n && kill -0 \"$(cat \"$STATE/orcad.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n print_ready\n exit 0\nfi\n# Resume = reboot from disk: locks and pids from the previous session name dead processes.\nrm -f \"$STATE/ready.json\" \"$STATE/orcad.pid\"\nprintf '%s' \"$boot_id\" >\"$STATE/boot-id\"\n# Any other boot (wake, restart) installs identities before it answers: a resumed disk's marks are stale.\n[ \"${ORCA_GIT_SETUP:-}\" = pending ] || rm -f \"$STATE/git-setup.pending\" \"$STATE/git-setup.ready\" \"$STATE/git-setup.failed\"\n\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n # Every github.com request carries the placeholder; the egress policy swaps in a 1h repo token.\n git config --global http.https://github.com/.extraheader \"$ORCA_GIT_EXTRAHEADER\"\nfi\n# Commits outside a teammate's turn (or before any member connected GitHub) need an author too.\n# The fallback is noreply@orca.dev (DOMAIN-1); a workspace still on an earlier default follows it.\ncase \"$(git config --global user.email 2>/dev/null || true)\" in\n cloud@users.noreply.onorca.dev | cloud@users.noreply.orca.dev)\n git config --global user.email 'noreply@orca.dev' ;;\nesac\ngit config --global user.email >/dev/null 2>&1 || git config --global user.email 'noreply@orca.dev'\n# The fallback name is \"Orca\" (DOMAIN-1); a workspace still on the earlier default follows it.\n[ \"$(git config --global user.name 2>/dev/null || true)\" = 'Orca Cloud' ] \\\n && git config --global user.name 'Orca'\ngit config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca'\n# First boot clones while orcad starts (orcad only needs the directory to exist); ready waits for both.\nclone_pid=''\nif [ ! -d \"$PROJECT\" ]; then\n mkdir -p \"$PROJECT\"\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n git clone --quiet ${ORCA_REPO_REF:+--branch \"$ORCA_REPO_REF\"} -- \"$ORCA_REPO_URL\" \"$PROJECT\" 2>\"$STATE/clone.log\" 9>&- &\n clone_pid=$!\n fi\nfi\n\n# The clone may still be running here, so the name comes from the URL; the default branch is\n# filled in lazily by the session-env shell hook once the clone exists.\nif [ -n \"${ORCA_REPO_URL:-}\" ]; then\n workspace_name=\"$(basename \"${ORCA_REPO_URL%/}\" .git)\"\nelse\n workspace_name=\"$(basename \"$(git -C \"$PROJECT\" remote get-url origin 2>/dev/null || echo \"$PROJECT\")\" .git)\"\nfi\n# One workspace per VM: its preview ports start at 3000 (Conductor allots CONDUCTOR_PORT..+9).\nmanaged_env=(\n ORCA_IS_CLOUD=1\n ORCA_ROOT_PATH=\"$PROJECT\" ORCA_WORKTREE_PATH=\"$PROJECT\" ORCA_WORKSPACE_PATH=\"$PROJECT\"\n ORCA_WORKSPACE_NAME=\"$workspace_name\" ORCA_PORT=3000\n CONDUCTOR_IS_CLOUD=1\n # Agent CLIs are pinned by the image (smoke-tested); a self-update mid-session can break a running agent.\n DISABLE_AUTOUPDATER=1 OPENCODE_DISABLE_AUTOUPDATE=1 COPILOT_AUTO_UPDATE=false\n CONDUCTOR_ROOT_PATH=\"$PROJECT\" CONDUCTOR_WORKSPACE_PATH=\"$PROJECT\"\n CONDUCTOR_WORKSPACE_NAME=\"$workspace_name\" CONDUCTOR_PORT=3000\n)\n\nagent_env=()\nif command -v google-chrome >/dev/null; then\n # Orca's browser automation and agent browser tools use the image's headless Chrome.\n agent_env+=(\"ORCA_BROWSER_EXECUTABLE=$(command -v google-chrome)\")\nfi\nif [ -n \"${ORCA_GITHUB_PLACEHOLDER:-}\" ]; then\n # The egress layer swaps the placeholder for a short-lived GitHub token; none lives in the VM.\n agent_env+=(\"GH_TOKEN=$ORCA_GITHUB_PLACEHOLDER\" \"GITHUB_TOKEN=$ORCA_GITHUB_PLACEHOLDER\")\n # GH-AS-MEMBER: gh (image/vm/gh) acts as the attested sender with their own placeholder.\n [ \"${ORCA_GH_AS_MEMBER:-}\" = on ] && agent_env+=(\"ORCA_GH_AS_MEMBER=on\")\nfi\n\nsecret_names=()\nif [ -n \"${ORCA_SECRET_ENV:-}\" ]; then\n # Secrets live only in memory: orcad's process env and a tmpfs file new shells re-read\n # (orca-sandbox-env), never under $HOME or the project, so the stop snapshot never carries them.\n # Resolved per start (and per edit) by the control plane: no image rebuild, no restart.\n while IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\" # not IFS='=': read would strip base64 padding\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n agent_env+=(\"$name=$(printf '%s' \"$b64\" | base64 -d)\")\n secret_names+=(\"$name\")\n done < <(printf '%s\\n' \"$ORCA_SECRET_ENV\") # a pipe, not a here-string temp file\nfi\n# Always rewrite the file, so a resume with fewer secrets drops the old names too.\n\"$ORCA_HOME/bin/orca-sandbox-env\" >/dev/null || echo 'session env file unavailable; secrets apply at boot only' >&2\nunset ORCA_SECRET_ENV\n\n# OpenCode installs @opencode-ai/plugin into ~/.config/opencode and, with Orca's plugin configured,\n# draws nothing until that install ends (blank ~85 s on a slow registry, n73). The image carries the\n# install (provision-golden.sh): copy it into a home that has neither node_modules nor a package.json\n# of its own, so the first launch never fetches.\noc_seed=\"$ORCA_HOME/opencode-config-seed\"\noc_dir=\"$HOME/.config/opencode\"\nif [ -d \"$oc_seed/node_modules\" ] && [ ! -e \"$oc_dir/node_modules\" ] && [ ! -e \"$oc_dir/package.json\" ]; then\n mkdir -p \"$oc_dir\" \\\n && cp -R \"$oc_seed/node_modules\" \"$oc_dir/node_modules\" \\\n && cp \"$oc_seed/package.json\" \"$oc_seed/package-lock.json\" \"$oc_dir/\" \\\n || echo 'opencode config seed not copied' >&2\nfi\n# The rest of OpenCode's first run (its database, the model list): ~2.5 s on the first launch\n# (5.2 s vs 2.7 s warm, n72). Done now in the background at low priority with no credentials\n# (`opencode models` does it and exits). Skipped once it has run on this disk. An image without the\n# seed (an environment snapshot from an older golden) still needs the install: then the first run\n# waits for orcad to put Orca's plugin in ~/.config/opencode/plugins (~10 s), since OpenCode only\n# finishes that install when a plugin is configured.\nif [ -x \"$ORCA_HOME/tools/bin/opencode\" ] && { [ ! -e \"$HOME/.local/share/opencode/opencode.db\" ] || [ ! -e \"$oc_dir/node_modules\" ]; }; then\n (\n cd \"$HOME\" || exit 0\n # shellcheck disable=SC2016 # expanded by the inner shell\n env -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 PATH=\"$ORCA_HOME/tools/bin:/usr/local/bin:/usr/bin:/bin\" \\\n OPENCODE_DISABLE_AUTOUPDATE=1 setsid nohup nice -n 19 bash -c '\n if [ ! -e \"$HOME/.config/opencode/node_modules\" ]; then\n for _ in $(seq 1 120); do [ -d \"$HOME/.config/opencode/plugins\" ] && break; sleep 0.5; done\n fi\n exec timeout 120 \"$1\" models\n ' opencode-first-run \"$ORCA_HOME/tools/bin/opencode\" /dev/null 2>&1 9>&- &\n )\nfi\n\n# Agent CLIs installed with the image's npm (codex, gemini, ...) are `#!/usr/bin/env node` scripts:\n# terminals need that node on PATH, not only orcad's bundled runtime.\nsystem_node=\"$(command -v node 2>/dev/null || echo \"$node\")\"\n# The egress proxy answers for hosts with credential rules (model APIs, api.github.com) with a\n# certificate from Vercel's CA, which this command's env trusts (Vercel sets these). Pure-Node clients\n# use Node's bundled roots otherwise: Gemini CLI retried forever (\"taking a bit longer\") in every\n# terminal while the same call worked here. Pass the provider's CA settings on to orcad and its shells.\nca_env=(NODE_USE_SYSTEM_CA=\"${NODE_USE_SYSTEM_CA:-1}\")\nfor name in NODE_EXTRA_CA_CERTS SSL_CERT_FILE; do\n if [ -n \"${!name:-}\" ]; then ca_env+=(\"$name=${!name}\"); fi\ndone\n# N-02: the host is a cloud terminal's source of truth across app reopens, so orcad and its\n# daemon keep a local terminal's depth (5000 rows) instead of the desktop daemon's 1000-row live\n# window. Scoped to the VM: local desktop daemons keep their default.\n# Ports panel: programs under $ORCA_HOME are the image's own services, and 23456 is Vercel's\n# sandbox-init (root, pid invisible to this user); neither is listed as the user's port.\nenv -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 TERM=xterm-256color \"${ca_env[@]}\" \\\n PATH=\"$ORCA_HOME/tools/bin:$ORCA_HOME/bin:$(dirname \"$system_node\"):/usr/local/bin:/usr/bin:/bin\" \\\n ORCA_USER_DATA=\"$HOME/.orcad-data\" ORCA_SANDBOX_ID=\"$ORCA_SANDBOX_ID\" \"${managed_env[@]}\" \\\n ORCA_HOST_MANAGED_LISTENER_PATHS=\"$ORCA_HOME\" ORCA_HOST_MANAGED_UNOWNED_PORTS=23456 \\\n NODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_DAEMON_SESSION_SCROLLBACK_ROWS=5000 \\\n ORCA_SESSION_ENV_NAMES=\"${secret_names[*]}\" \"${agent_env[@]}\" \\\n setsid nohup \"$node\" \"$ORCA_HOME/bin/orcad-boot\" --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" \\\n \"$ORCA_HOME/runtime/orcad/orcad-server.js\" --port 6768 --bind 0.0.0.0 --pairing-address \"$ORCA_PUBLIC_WSS\" \\\n --recipe-json --project-root \"$PROJECT\" \\\n >\"$STATE/ready.json\" 2>\"$STATE/orcad.log\" &- &\necho $! >\"$STATE/orcad.pid\"\n\n# sshd for `orca ssh` (loopback only). Best effort: a workspace without it still serves orcad.\n\"$ORCA_HOME/bin/orca-sshd\" >/dev/null 2>\"$STATE/sshd-start.err\" || true\n\n# The agent CLIs are large and a fresh VM pages them in lazily from the snapshot, so the first agent\n# launch paid for it (OpenCode 11 s cold vs 3.75 s warm, n71). Read them into the page cache in the\n# background at idle IO priority, after orcad is starting. Best effort; detached so it outlives this\n# script, and never on the ready path.\nprefetch_dirs=()\nfor dir in @anthropic-ai @openai opencode-ai; do\n if [ -d \"$ORCA_HOME/tools/lib/node_modules/$dir\" ]; then\n prefetch_dirs+=(\"$ORCA_HOME/tools/lib/node_modules/$dir\")\n fi\ndone\nif [ \"${#prefetch_dirs[@]}\" -gt 0 ]; then\n # shellcheck disable=SC2016 # expanded by the inner shell\n setsid nohup nice -n 19 bash -c '\n command -v ionice >/dev/null && ionice -c 3 -p $$ 2>/dev/null\n find \"$@\" -type f -size +256k -print0 2>/dev/null | xargs -0 -r cat >/dev/null 2>&1\n ' agent-prefetch \"${prefetch_dirs[@]}\" /dev/null 2>&1 9>&- &\nfi\n\n# Polled every 10 ms (at least 60 s in all): ready is on the wake path, so detect it promptly.\nfor _ in $(seq 1 6000); do\n if grep -q '\"pairingCode\"' \"$STATE/ready.json\" 2>/dev/null; then\n if [ -n \"$clone_pid\" ] && ! wait \"$clone_pid\"; then\n echo 'repository clone failed' >&2\n tail -n 5 \"$STATE/clone.log\" | redact_log >&2\n exit 1\n fi\n register_project\n print_ready\n exit 0\n fi\n if ! kill -0 \"$(cat \"$STATE/orcad.pid\")\" 2>/dev/null; then\n echo 'orcad exited before ready' >&2\n tail -n 40 \"$STATE/orcad.log\" | redact_log >&2\n exit 1\n fi\n sleep 0.01\ndone\necho 'orcad start timed out' >&2\nexit 1\n","orca-sandbox-drain":"#!/usr/bin/env bash\n# Asks orcad to quit before the VM stops: its shutdown turns working agent chats into durable\n# restart offers and flushes terminal restore hints, which the desktop continues after resume.\nset -euo pipefail\nSTATE=\"$HOME/.orca-sandbox\"\nWAIT_SECONDS=\"${1:-280}\"\npid=\"$(cat \"$STATE/orcad.pid\" 2>/dev/null || true)\"\nif [ -z \"$pid\" ] || ! kill -0 \"$pid\" 2>/dev/null; then\n exit 0\nfi\nkill -TERM \"$pid\"\nfor _ in $(seq 1 $((WAIT_SECONDS * 10))); do\n if ! kill -0 \"$pid\" 2>/dev/null; then\n rm -f \"$STATE/orcad.pid\" \"$STATE/ready.json\"\n # On-demand swap files would ride the stop snapshot (2 GiB each). Best effort, bounded.\n [ -x /opt/orca/bin/orca-memguard ] && sudo -n timeout 20 /opt/orca/bin/orca-memguard release-swap >/dev/null 2>&1 || true\n exit 0\n fi\n sleep 0.1\ndone\n# Leave it running: the provider stop ends it, and the drain already had its window.\necho 'orcad still draining at deadline' >&2\nexit 0\n","orca-memguard":"#!/usr/bin/env bash\n# Memory guard for the workspace VM (runs as root: `sudo -n orca-memguard start`). A build or test\n# that eats the VM's memory must cost that process, never the workspace: without this the kernel\n# thrashes for minutes before its OOM killer picks something, and the VM looks dead meanwhile.\n# start start the guard for this boot unless it already runs (returns at once)\n# run the guard loop itself (start runs it detached)\n# release-swap turn off and delete on-demand swap (before a stop, so the snapshot stays small)\n# sweep apply OOM-killer priorities once and exit (tests, diagnostics)\n# victim print \" \" of the process the guard would stop now (no kill)\n# Every few seconds it ranks processes for the kernel's OOM killer (oom_score_adj):\n# -900 Orca's own runtime: orcad, its terminal daemon, the share proxy (Orca's bundled Node)\n# -500 terminal shells (children of the terminal daemon) and agent CLIs\n# 500 everything else (builds, tests, dev servers, browsers); never lowered\n# When MemAvailable falls under KILL_PCT (8%) of RAM it kills the largest process ranked 0 or more,\n# records it in $RUN/kills and $RUN/state, and waits for memory to return. The kernel's OOM killer\n# stays the backstop for allocations faster than the guard's 200 ms look, with the same ranks.\n# Swap is added on demand (2 GiB files up to 1.5x RAM) when memory runs low, if the kernel takes it,\n# and dropped after 10 quiet minutes. It also sizes /dev/shm to half of RAM (the provider mounts\n# 64 MB, which crashes Chrome and Electron renderers).\n# $RUN/state (key=value, world-readable) is what the control plane's status probe reads.\nset -uo pipefail\nRUN=/run/orca-memguard\n# Tests point it at a fake process table.\nPROC=\"${ORCA_MEMGUARD_PROC:-/proc}\"\nSWAP_DIR=/var/lib/orca-memguard\nORCA_HOME=/opt/orca\nKILL_PCT=\"${ORCA_MEMGUARD_KILL_PCT:-8}\"\nHIGH_PCT=15\nSWAP_ADD_PCT=20\nQUIET_PCT=50\nQUIET_SECONDS=600\nTICK=1\nFAST_TICK=0.2\nSWEEP_EVERY=3\nSTATE_EVERY=15\nSWAP_CHUNK_KIB=$((2 * 1024 * 1024))\n\nboot_id() { local id; read -r id >\"$RUN/memguard.log\"; }\n\n# Name of a process for people: the script a node/python/... runs, else its command name.\nproc_name() {\n local pid=\"$1\" comm arg name='' skip=0 module=0 args=()\n read -r comm 2>/dev/null <\"$PROC/$pid/comm\" || comm=''\n mapfile -d '' -t args 2>/dev/null <\"$PROC/$pid/cmdline\" || true\n case \"${args[0]##*/}\" in\n node | nodejs | bun | deno | python* | ruby | perl | java | sh | bash | dash | zsh)\n for arg in \"${args[@]:1}\"; do\n if [ \"$skip\" -eq 1 ]; then skip=0; continue; fi\n if [ \"$module\" -eq 1 ]; then name=\"${arg##*/}\"; break; fi\n case \"$arg\" in\n # Inline code is no name (and may hold anything): the interpreter's name it is.\n -e | -p | -c | --eval | --print) break ;;\n -m | -jar) module=1 ;; # python -m pytest, java -jar gradle.jar: the module or jar\n -r | --require | --import | --loader | -X | -W | -cp | -classpath) skip=1 ;;\n -*) ;;\n *) name=\"${arg##*/}\"; break ;;\n esac\n done ;;\n esac\n [ -n \"$name\" ] || name=\"${args[0]##*/}\"\n [ -n \"$name\" ] || name=\"$comm\"\n name=\"${name%.js}\"\n name=\"${name%.mjs}\"\n name=\"${name%.cjs}\"\n name=\"${name%.jar}\"\n name=\"${name//[^A-Za-z0-9._+-]/}\"\n printf '%s' \"${name:0:40}\"\n}\n\n# The terminal daemon's pid(s): Orca-runtime node processes running the daemon entry.\ndaemon_pids=' '\n# Sets RANK to the oom_score_adj a process should have; returns 1 for a kernel thread or a gone pid.\nRANK=500\nrank() {\n local pid=\"$1\" args=() stat ppid\n mapfile -d '' -t -n 3 args 2>/dev/null <\"$PROC/$pid/cmdline\" || return 1\n [ \"${#args[@]}\" -gt 0 ] || return 1\n RANK=-900\n case \"${args[0]}\" in \"$ORCA_HOME\"/runtime/runtimes/*) return 0 ;; esac\n RANK=-500\n read -r stat 2>/dev/null <\"$PROC/$pid/stat\" || return 1\n stat=\"${stat##*) }\"\n ppid=\"${stat#* }\"\n ppid=\"${ppid%% *}\"\n case \"$daemon_pids\" in *\" $ppid \"*) return 0 ;; esac\n case \"${args[0]}/${args[1]:-}/${args[2]:-}\" in \"$ORCA_HOME\"/tools/* | */\"$ORCA_HOME\"/tools/*) return 0 ;; esac\n case \"${args[0]##*/}\" in claude | codex | opencode | gemini | cursor-agent | copilot | amp | droid) return 0 ;; esac\n RANK=500\n}\n\nsweep() {\n local p pid want adj args=()\n daemon_pids=' '\n for p in \"$PROC\"/[0-9]*; do\n pid=\"${p#\"$PROC\"/}\"\n mapfile -d '' -t -n 3 args 2>/dev/null <\"$p/cmdline\" || continue\n [ \"${#args[@]}\" -ge 2 ] || continue\n case \"${args[0]}\" in \"$ORCA_HOME\"/runtime/runtimes/*) ;; *) continue ;; esac\n case \"${args[*]:1}\" in *\"$ORCA_HOME\"/runtime/orcad/daemon*) daemon_pids+=\"$pid \" ;; esac\n done\n for p in \"$PROC\"/[0-9]*; do\n pid=\"${p#\"$PROC\"/}\"\n [ \"$pid\" -gt 1 ] && [ \"$pid\" != \"$$\" ] || continue\n read -r adj 2>/dev/null <\"$p/oom_score_adj\" || continue\n # -1000 is a process that asked for it as root (sshd): leave it alone.\n [ \"$adj\" -gt -1000 ] || continue\n rank \"$pid\" || continue\n want=\"$RANK\"\n # Never lower what a process raised for itself (Chrome ranks its renderers above its browser).\n if [ \"$want\" -eq 500 ]; then\n [ \"$adj\" -lt 500 ] || continue\n fi\n [ \"$adj\" -ne \"$want\" ] || continue\n printf '%s\\n' \"$want\" 2>/dev/null >\"$p/oom_score_adj\" || true\n done\n}\n\nmem_total=0 mem_avail=0 swap_total=0 swap_free=0\nread_mem() {\n local key value _\n while read -r key value _; do\n case \"$key\" in\n MemTotal:) mem_total=\"$value\" ;;\n MemAvailable:) mem_avail=\"$value\" ;;\n SwapTotal:) swap_total=\"$value\" ;;\n SwapFree:) swap_free=\"$value\" ;;\n esac\n done <\"$PROC/meminfo\"\n}\n\n# PSI percentages (avg10, integer part); 0 when the kernel doesn't report them.\npsi_some=0 psi_full=0\nread_psi() {\n local kind avg _\n psi_some=0 psi_full=0\n [ -r \"$PROC/pressure/memory\" ] || return 0\n while read -r kind avg _; do\n avg=\"${avg#avg10=}\"\n avg=\"${avg%%.*}\"\n case \"$kind\" in some) psi_some=\"$avg\" ;; full) psi_full=\"$avg\" ;; esac\n done 2>/dev/null <\"$PROC/pressure/memory\" || true\n}\n\nkills=0 last_kill_name='' last_kill_at=0 swap_mode=on-demand level=ok\nwrite_state() {\n local pct=\"$1\"\n {\n printf 'bootId=%s\\nat=%s\\npid=%s\\nlevel=%s\\navailPct=%s\\nmemTotalKiB=%s\\nmemAvailKiB=%s\\n' \\\n \"$BOOT\" \"$(now_ms)\" \"$$\" \"$level\" \"$pct\" \"$mem_total\" \"$mem_avail\"\n printf 'swapTotalKiB=%s\\nswapFreeKiB=%s\\nswap=%s\\npsiSome10=%s\\npsiFull10=%s\\n' \\\n \"$swap_total\" \"$swap_free\" \"$swap_mode\" \"$psi_some\" \"$psi_full\"\n printf 'kills=%s\\nlastKillName=%s\\nlastKillAt=%s\\n' \"$kills\" \"$last_kill_name\" \"$last_kill_at\"\n } >\"$RUN/state.tmp\" && mv -f \"$RUN/state.tmp\" \"$RUN/state\"\n}\n\n# Sets VICTIM/VICTIM_RSS (pages) to the largest process ranked 0 or more; returns 1 when there is none.\nVICTIM=0 VICTIM_RSS=0\nchoose_victim() {\n local p pid adj rss _ best=0 best_rss=0 args=()\n sweep\n for p in \"$PROC\"/[0-9]*; do\n pid=\"${p#\"$PROC\"/}\"\n [ \"$pid\" -gt 1 ] && [ \"$pid\" != \"$$\" ] || continue\n read -r adj 2>/dev/null <\"$p/oom_score_adj\" || continue\n [ \"$adj\" -ge 0 ] || continue\n read -r _ rss _ 2>/dev/null <\"$p/statm\" || continue\n # Kernel threads have no command line (and /proc sizes read 0, so `-s` can't tell).\n mapfile -d '' -t -n 1 args 2>/dev/null <\"$p/cmdline\" || continue\n [ \"${#args[@]}\" -gt 0 ] || continue\n if [ \"$rss\" -gt \"$best_rss\" ]; then\n best=\"$pid\" best_rss=\"$rss\"\n fi\n done\n # Nothing big enough to matter (64 MiB): what fills memory is protected, so leave it to the kernel.\n [ \"$best\" -gt 1 ] && [ \"$best_rss\" -ge 16384 ] || return 1\n VICTIM=\"$best\" VICTIM_RSS=\"$best_rss\"\n}\n\n# Kills the largest process ranked 0 or more ($1: MemAvailable %). Returns 1 when there is none.\nkill_largest() {\n choose_victim || return 1\n local best=\"$VICTIM\" best_rss=\"$VICTIM_RSS\" name at\n name=\"$(proc_name \"$best\")\"\n kill -KILL \"$best\" 2>/dev/null || return 1\n at=\"$(now_ms)\"\n kills=$((kills + 1)) last_kill_name=\"${name:-process}\" last_kill_at=\"$at\"\n printf '%s %s %s %s %s\\n' \"$at\" \"$best\" \"$((best_rss * 4))\" \"$1\" \"$last_kill_name\" >>\"$RUN/kills\"\n tail -n 50 \"$RUN/kills\" >\"$RUN/kills.tmp\" && mv -f \"$RUN/kills.tmp\" \"$RUN/kills\"\n log \"killed pid=$best name=$last_kill_name rssKiB=$((best_rss * 4)) availPct=$1\"\n # Shells hear it like a kernel OOM kill (exit 137); this says why where someone may look.\n logger -t orca-memguard \"stopped $last_kill_name (pid $best, $((best_rss * 4)) KiB) at $1% memory available\" 2>/dev/null || true\n return 0\n}\n\nswap_files() { compgen -G \"$SWAP_DIR/swap-*\" || true; }\nadd_swap() {\n [ \"$swap_mode\" = on-demand ] || return 1\n [ $((swap_total + SWAP_CHUNK_KIB)) -le $((mem_total * 3 / 2)) ] || return 1\n local free_kib file\n free_kib=\"$(df -k --output=avail \"$SWAP_DIR\" 2>/dev/null | tail -n 1 | tr -d ' ')\"\n # Keep 4 GiB of the disk for the workspace itself.\n [ \"${free_kib:-0}\" -gt $((SWAP_CHUNK_KIB + 4 * 1024 * 1024)) ] || return 1\n file=\"$SWAP_DIR/swap-$(now_ms)\"\n if fallocate -l \"$((SWAP_CHUNK_KIB))K\" \"$file\" 2>/dev/null && chmod 600 \"$file\" \\\n && mkswap -q \"$file\" >/dev/null 2>&1 && swapon \"$file\" 2>/dev/null; then\n log \"swap on $file\"\n return 0\n fi\n rm -f \"$file\"\n # One refusal means this kernel or disk won't swap: don't retry every tick.\n swap_mode=unsupported\n log 'swap unavailable; guard kills only'\n return 1\n}\nrelease_swap() {\n local file\n for file in $(swap_files | sort -r); do\n swapoff \"$file\" 2>/dev/null && rm -f \"$file\" && log \"swap off $file\"\n done\n}\n\nrun() {\n BOOT=\"$(boot_id)\"\n mkdir -p \"$RUN\" \"$SWAP_DIR\"\n chmod 0755 \"$RUN\"\n chmod 0700 \"$SWAP_DIR\"\n # A resumed disk carries the last session's files: its kills and swap belong to that boot.\n rm -f \"$RUN/kills\" \"$RUN/state\" \"$RUN\"/*.tmp\n for file in $(swap_files); do\n grep -q \"^$file \" /proc/swaps 2>/dev/null || rm -f \"$file\"\n done\n printf '%s %s\\n' \"$BOOT\" \"$$\" >\"$RUN/pid\"\n echo -1000 >/proc/self/oom_score_adj\n read_mem\n # Half of RAM for /dev/shm (tmpfs only takes pages that are written).\n mount -o remount,size=50% /dev/shm 2>/dev/null && log \"/dev/shm $(df -h --output=size /dev/shm | tail -n 1 | tr -d ' ')\"\n log \"start mem=${mem_total}KiB\"\n local tick=0 pct quiet_since=0 prev='' now\n while :; do\n read_mem\n read_psi\n pct=$((mem_total > 0 ? mem_avail * 100 / mem_total : 100))\n if [ $((tick % SWEEP_EVERY)) -eq 0 ]; then\n sweep\n fi\n if [ \"$pct\" -lt \"$SWAP_ADD_PCT\" ] && { [ \"$swap_total\" -eq 0 ] || [ $((swap_free * 4)) -lt \"$swap_total\" ]; }; then\n add_swap && read_mem\n fi\n # Swap only raises MemAvailable by paging idle memory out: a fast allocator outruns it (the\n # kernel OOM-killed a 300 MB/s hog with 1.7 GB of swap free), so the threshold ignores swap.\n if [ \"$pct\" -lt \"$KILL_PCT\" ]; then\n level=critical\n if kill_largest \"$pct\"; then\n write_state \"$pct\"\n prev=\"$level:$kills\"\n sleep 1 # let the kernel reclaim the victim's memory before judging again\n tick=$((tick + 1))\n continue\n fi\n elif [ \"$psi_full\" -ge 10 ]; then\n level=critical\n elif [ \"$pct\" -lt \"$HIGH_PCT\" ] || [ \"$psi_some\" -ge 20 ]; then\n level=high\n else\n level=ok\n fi\n now=\"${EPOCHSECONDS}\"\n if [ \"$pct\" -ge \"$QUIET_PCT\" ] && [ \"$swap_total\" -gt 0 ]; then\n [ \"$quiet_since\" -gt 0 ] || quiet_since=\"$now\"\n if [ $((now - quiet_since)) -ge \"$QUIET_SECONDS\" ] && [ $(((swap_total - swap_free) * 2)) -lt \"$mem_avail\" ]; then\n release_swap\n quiet_since=0\n fi\n else\n quiet_since=0\n fi\n if [ \"$level:$kills\" != \"$prev\" ] || [ $((tick % STATE_EVERY)) -eq 0 ]; then\n write_state \"$pct\"\n prev=\"$level:$kills\"\n fi\n tick=$((tick + 1))\n # Memory can go from 15% to nothing in two seconds: look five times as often when it is low.\n if [ \"$level\" = ok ]; then sleep \"$TICK\"; else sleep \"$FAST_TICK\"; fi\n done\n}\n\nrunning() {\n local boot pid\n read -r boot pid <\"$RUN/pid\" 2>/dev/null || return 1\n [ \"$boot\" = \"$(boot_id)\" ] && [ -n \"$pid\" ] && kill -0 \"$pid\" 2>/dev/null \\\n && grep -qa orca-memguard \"/proc/$pid/cmdline\" 2>/dev/null\n}\n\ncase \"${1:-}\" in\n start)\n [ \"$(id -u)\" -eq 0 ] || { echo 'orca-memguard: needs root' >&2; exit 1; }\n running && exit 0\n mkdir -p \"$RUN\"\n setsid nohup \"$0\" run /dev/null 2>>\"$RUN/memguard.log\" &\n exit 0 ;;\n run) run ;;\n sweep) sweep ;;\n victim) choose_victim && printf '%s %s %s\\n' \"$VICTIM\" \"$((VICTIM_RSS * 4))\" \"$(proc_name \"$VICTIM\")\" ;;\n release-swap) release_swap ;;\n *) echo 'usage: orca-memguard start|run|sweep|victim|release-swap' >&2; exit 2 ;;\nesac\n","orca-sandbox-env":"#!/usr/bin/env bash\n# Writes this session's secret env where new shells and agent launches read it (orca-session-env.sh).\n# Input: ORCA_SECRET_ENV (`NAME=` lines) from the control plane, at boot (orca-sandbox-start)\n# and whenever a secret changes (POST /v1/sandboxes/:id/env/refresh). The file lives on tmpfs only:\n# never on the sandbox disk, so the stop snapshot never carries it. Prints {\"names\":N} on success.\n# Also keeps Codex pointed at a configured OpenAI-compatible provider (OPENAI_BASE_URL), since Codex\n# does not read that variable: a managed block in ~/.codex/config.toml naming only the env var.\nset -euo pipefail\numask 077\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\n# ORCA_SESSION_ENV_DIR: tests only (a scratch dir off tmpfs); the control plane never sets it.\ndir=\"${ORCA_SESSION_ENV_DIR:-/dev/shm/orca-env-$(id -u)}\"\nif [ -z \"${ORCA_SESSION_ENV_DIR:-}\" ] && [ \"$(stat -f -c %T /dev/shm 2>/dev/null || true)\" != tmpfs ]; then\n # No memory-only place to keep it: refuse rather than write secrets to disk.\n echo 'no tmpfs for the session env' >&2\n exit 3\nfi\nmkdir -p \"$dir\"\nchmod 700 \"$dir\"\n# Writes are ordered by the control plane's resolve time: an older refresh that lost a race is dropped.\ngeneration=\"${ORCA_ENV_GENERATION:-0}\"\ncase \"$generation\" in '' | *[!0-9]*) generation=0 ;; esac\ncurrent=\"$(cat \"$dir/generation\" 2>/dev/null || echo 0)\"\ncase \"$current\" in '' | *[!0-9]*) current=0 ;; esac\nif [ \"$generation\" -lt \"$current\" ]; then\n printf '{\"stale\":true}\\n'\n exit 0\nfi\ntmp=\"$(mktemp \"$dir/.session.env.XXXXXX\")\"\ncount=0\nopenai_base_url=''\nopenai_model=''\nanthropic_model=''\nanthropic_key_tail=''\nanthropic_key_scrub=''\ngateway_key=''\ngemini_key=''\ncodex_placeholder=''\nsign_in_inside=''\nwhile IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\"\n # Not for shells: the Codex account placeholder becomes ~/.codex/auth.json below.\n # Not for shells: the agents the person signs in inside this workspace (e.g. `claude,codex`).\n if [ \"$name\" = ORCA_SIGN_IN_INSIDE ]; then\n sign_in_inside=\"$(printf '%s' \"$b64\" | base64 -d)\"\n case \"$sign_in_inside\" in *[!a-z,]*) sign_in_inside='' ;; esac\n fi\n if [ \"$name\" = ORCA_CODEX_AUTH_PLACEHOLDER ]; then\n codex_placeholder=\"$(printf '%s' \"$b64\" | base64 -d)\"\n case \"$codex_placeholder\" in *[!A-Za-z0-9._-]*) codex_placeholder='' ;; esac\n fi\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n # Values stay base64 in the file; the shell hook decodes them.\n printf '%s=%s\\n' \"$name\" \"$b64\" >>\"$tmp\"\n count=$((count + 1))\n case \"$name\" in\n OPENAI_BASE_URL) openai_base_url=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n OPENAI_MODEL) openai_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n ANTHROPIC_MODEL) anthropic_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n AI_GATEWAY_API_KEY) gateway_key=1 ;;\n GEMINI_API_KEY | GOOGLE_API_KEY) gemini_key=\"${gemini_key:-gemini-api-key}\" ;;\n GOOGLE_GENAI_USE_VERTEXAI) case \"$(printf '%s' \"$b64\" | base64 -d)\" in true | 1) gemini_key=vertex-ai ;; esac ;;\n # Claude Code asks once per key whether to use ANTHROPIC_API_KEY; it remembers the last 20 chars.\n # G9: pre-approve only an Orca placeholder. A real key (placeholders off) is never written, not even its\n # tail: Claude Code asks once instead, and a tail an older image wrote is scrubbed.\n ANTHROPIC_API_KEY)\n case \"$(printf '%s' \"$b64\" | base64 -d)\" in\n orca-ph-*) anthropic_key_tail=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n *) anthropic_key_scrub=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n esac\n ;;\n esac\ndone < <(printf '%s\\n' \"${ORCA_SECRET_ENV:-}\")\nmv -f \"$tmp\" \"$dir/session.env\"\nprintf '%s' \"$generation\" >\"$dir/generation\"\n\n# ---- Codex: trust the workspace and use the configured provider (no secret values) ----\nPROJECT=/vercel/sandbox/project\ncodex_config=\"$HOME/.codex/config.toml\"\ntoml_string() { # TOML basic string; the control plane only accepts https URLs and plain model ids\n local value=\"${1//\\\\/\\\\\\\\}\"\n printf '\"%s\"' \"${value//\\\"/\\\\\\\"}\"\n}\nstrip_managed() { # drop the managed blocks and the blank lines written before them (no growth per refresh)\n awk '/^# >>> orca-cloud managed/{skip=1; blank=\"\"} skip{if (/^# <<< orca-cloud managed/) skip=0; next}\n /^[[:space:]]*$/{blank=blank $0 \"\\n\"; next} {printf \"%s\", blank; blank=\"\"; print}' \"$1\"\n}\n# Always managed: an agent launched from the phone or the API has no one to answer Codex's\n# \"trust this folder?\" screen, so the workspace project is trusted up front.\nif true; then\n mkdir -p \"$HOME/.codex\"\n user_part=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n if [ -f \"$codex_config\" ]; then strip_managed \"$codex_config\" >\"$user_part\"; fi\n next=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n openai_host=\"${openai_base_url#https://}\"\n openai_host=\"${openai_host%%/*}\"\n custom_provider=''\n if [ -n \"$openai_base_url\" ] && [ \"$openai_host\" != api.openai.com ]; then custom_provider=1; fi\n # Top-level keys must precede every table; each is skipped when the user already set it.\n head_keys=\"$(awk '/^\\[/{exit} {print}' \"$user_part\")\"\n has_key() { grep -Eq \"^[[:space:]]*$1[[:space:]]*=\" <<<\"$head_keys\"; }\n {\n printf '# >>> orca-cloud managed (Orca Cloud; edit in Orca settings)\\n'\n # The sandbox is the isolation boundary: Codex's own bwrap sandbox can't start in it (\"Unexpected\n # capabilities\"), and a prompt delivered from the phone or the API has no one to approve commands.\n has_key sandbox_mode || printf 'sandbox_mode = \"danger-full-access\"\\n'\n has_key approval_policy || printf 'approval_policy = \"never\"\\n'\n if [ -n \"$custom_provider\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_cloud\"\\n'\n if [ -n \"$openai_model\" ] && ! has_key model; then\n printf 'model = %s\\n' \"$(toml_string \"$openai_model\")\"\n fi\n elif [ -n \"$codex_placeholder\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_chatgpt\"\\n'\n fi\n printf '# <<< orca-cloud managed\\n'\n cat \"$user_part\"\n if [ -n \"$custom_provider\" ]; then\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_cloud]\\nname = \"Orca Cloud\"\\n'\n printf 'base_url = %s\\nenv_key = \"OPENAI_API_KEY\"\\nwire_api = \"responses\"\\n' \"$(toml_string \"$openai_base_url\")\"\n printf '# <<< orca-cloud managed\\n'\n elif [ -n \"$codex_placeholder\" ]; then\n # Codex via the Orca account: the ChatGPT backend over HTTPS. Its default Responses WebSocket can't\n # pass the egress proxy, where the placeholder becomes the real token (found live, Codex 0.166).\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_chatgpt]\\nname = \"OpenAI\"\\n'\n printf 'base_url = \"https://chatgpt.com/backend-api/codex\"\\nwire_api = \"responses\"\\nrequires_openai_auth = true\\nsupports_websockets = false\\n'\n printf '# <<< orca-cloud managed\\n'\n # CODEX-PS-CALLS: Codex's plugin catalog made ~170 chatgpt.com calls per session start through the\n # account swap. Off unless the person's own config says otherwise (a [features] table of theirs is\n # left alone: TOML can't define it twice).\n if ! grep -Eq '^[[:space:]]*(\\[features\\]|features[.[:space:]=])' \"$user_part\"; then\n printf '\\n# >>> orca-cloud managed features\\n[features]\\nplugins = false\\n# <<< orca-cloud managed\\n'\n fi\n fi\n } >\"$next\"\n if ! grep -qF \"[projects.\\\"$PROJECT\\\"]\" \"$user_part\"; then\n printf '\\n# >>> orca-cloud managed trust\\n[projects.\"%s\"]\\ntrust_level = \"trusted\"\\n# <<< orca-cloud managed\\n' \"$PROJECT\" >>\"$next\"\n fi\n chmod 600 \"$next\"\n mv -f \"$next\" \"$codex_config\"\n rm -f \"$user_part\"\nfi\n# CODEX-WS-OFF: the same provider at the system layer (/etc/codex/config.toml), so Codex keeps HTTPS for it\n# even when the person's own config drops ours: header-swapping firewalls refuse WebSocket upgrades\n# (Codex then retries for ~10 s per session). Best effort: no passwordless sudo, no system file.\nif [ -n \"$codex_placeholder\" ] && [ -z \"$custom_provider\" ]; then\n sys_cfg='# >>> orca-cloud managed (Orca Cloud)\\n[model_providers.orca_chatgpt]\\nname = \"OpenAI\"\\nbase_url = \"https://chatgpt.com/backend-api/codex\"\\nwire_api = \"responses\"\\nrequires_openai_auth = true\\nsupports_websockets = false\\n# <<< orca-cloud managed\\n'\n if [ -n \"${ORCA_CODEX_SYSTEM_CONFIG:-}\" ]; then\n # Tests: a scratch path, written directly.\n mkdir -p \"$(dirname \"$ORCA_CODEX_SYSTEM_CONFIG\")\" && printf \"$sys_cfg\" >\"$ORCA_CODEX_SYSTEM_CONFIG\"\n else\n # shellcheck disable=SC2059\n printf \"$sys_cfg\" | sudo -n sh -c 'mkdir -p /etc/codex && cat >/etc/codex/config.toml.orca-new && mv -f /etc/codex/config.toml.orca-new /etc/codex/config.toml' 2>/dev/null || true\n fi\nfi\n# ---- Codex via the person's Orca account (contract D11): a placeholder ChatGPT login, no refresh token.\n# The egress proxy swaps the real access token on chatgpt.com; the real tokens never reach this VM. The\n# marker remembers which placeholder Orca wrote (a clone gets its own), so a login of the person's own\n# (kill-switch fallback, or `codex login` run here) is set aside while the account applies and put back after.\ncodex_auth=\"$HOME/.codex/auth.json\"\ncodex_saved=\"$HOME/.codex/auth.json.orca-saved\"\ncodex_marker=\"$HOME/.codex/.orca-account-placeholder\"\ncodex_ours=''\n# Ours: the marker's placeholder, or any Orca placeholder (all end in `.orca-placeholder`; a real token never does).\nif [ -f \"$codex_auth\" ] && { { [ -f \"$codex_marker\" ] && grep -qF \"\\\"$(cat \"$codex_marker\")\\\"\" \"$codex_auth\"; } || grep -q '\\.orca-placeholder\"' \"$codex_auth\"; }; then\n codex_ours=1\nfi\nif [ -n \"$codex_placeholder\" ]; then\n mkdir -p \"$HOME/.codex\"\n if [ -f \"$codex_auth\" ] && [ -z \"$codex_ours\" ]; then\n # Never overwrite a login already set aside: a second one gets its own name.\n if [ -e \"$codex_saved\" ]; then mv -f \"$codex_auth\" \"$codex_saved.$(date -u +%Y%m%d%H%M%S)\"; else mv -f \"$codex_auth\" \"$codex_saved\"; fi\n fi\n # Marker first: a run cut short after the swap still recognises the file as Orca's.\n printf '%s' \"$codex_placeholder\" >\"$codex_marker\"\n codex_tmp=\"$(mktemp \"$HOME/.codex/.auth.XXXXXX\")\"\n # last_refresh far ahead: Codex never refreshes this login itself (Orca refreshes the real one centrally).\n printf '{\\n \"OPENAI_API_KEY\": null,\\n \"tokens\": {\\n \"id_token\": \"%s\",\\n \"access_token\": \"%s\",\\n \"refresh_token\": \"\",\\n \"account_id\": null\\n },\\n \"last_refresh\": \"2099-01-01T00:00:00Z\"\\n}\\n' \\\n \"$codex_placeholder\" \"$codex_placeholder\" >\"$codex_tmp\"\n chmod 600 \"$codex_tmp\"\n mv -f \"$codex_tmp\" \"$codex_auth\"\nelif [ -f \"$codex_marker\" ] || [ -n \"$codex_ours\" ]; then\n if [ -n \"$codex_ours\" ]; then rm -f \"$codex_auth\"; fi\n rm -f \"$codex_marker\"\n if [ -f \"$codex_saved\" ] && [ ! -f \"$codex_auth\" ]; then mv -f \"$codex_saved\" \"$codex_auth\"; fi\nfi\n# ---- Claude Code, Gemini CLI, Cursor agent, Copilot CLI, OpenCode: first-run screens answered once\n# (Claude: theme picker, folder trust, bypass-mode warning, the \"use this API key?\" question; others:\n# folder trust, auth-method picker, self-update). A prompt delivered from the phone or the API has no one to click\n# through them, and the agent would sit there doing nothing. Merges; never touches credentials.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nif [ -n \"$node_bin\" ]; then\n claude_inside=''\n case \",$sign_in_inside,\" in *,claude,*) claude_inside=1 ;; esac\n ORCA_CLAUDE_INSIDE=\"$claude_inside\" ORCA_PROJECT=\"$PROJECT\" ORCA_KEY_TAIL=\"$anthropic_key_tail\" ORCA_KEY_SCRUB=\"$anthropic_key_scrub\" ORCA_GEMINI_KEY=\"$gemini_key\" \\\n ORCA_GATEWAY_MODEL=\"${gateway_key:+${anthropic_model:-$openai_model}}\" \"$node_bin\" -e '\nconst fs = require(\"fs\"), path = require(\"path\"), os = require(\"os\")\nconst home = os.homedir()\nconst readJson = (file) => { try { const v = JSON.parse(fs.readFileSync(file, \"utf8\")); return v && typeof v === \"object\" && !Array.isArray(v) ? v : {} } catch { return {} } }\nconst write = (file, value) => {\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\nconst claudeFile = path.join(process.env.CLAUDE_CONFIG_DIR || home, \".claude.json\")\nconst c = readJson(claudeFile)\nconst before = JSON.stringify(c)\n// Signed in inside this workspace and no login here yet: leave first-run onboarding to Claude, so it opens\n// on its own sign-in screens instead of \"Not logged in\". Once a login exists, onboarding is done as usual.\nconst claudeCredentials = path.join(process.env.CLAUDE_CONFIG_DIR || path.join(home, \".claude\"), \".credentials.json\")\nif (process.env.ORCA_CLAUDE_INSIDE === \"1\" && !fs.existsSync(claudeCredentials)) delete c.hasCompletedOnboarding\nelse c.hasCompletedOnboarding = true\nc.theme = c.theme || \"dark\"\nc.bypassPermissionsModeAccepted = true\nc.projects = c.projects && typeof c.projects === \"object\" ? c.projects : {}\nconst p = process.env.ORCA_PROJECT\nc.projects[p] = { ...(c.projects[p] || {}), hasTrustDialogAccepted: true, hasCompletedProjectOnboarding: true }\nconst tail = process.env.ORCA_KEY_TAIL\nconst scrub = process.env.ORCA_KEY_SCRUB\nif (scrub && c.customApiKeyResponses && typeof c.customApiKeyResponses === \"object\") {\n const r = c.customApiKeyResponses\n for (const list of [\"approved\", \"rejected\"]) if (Array.isArray(r[list])) r[list] = r[list].filter((t) => t !== scrub)\n}\nif (tail) {\n const r = c.customApiKeyResponses && typeof c.customApiKeyResponses === \"object\" ? c.customApiKeyResponses : {}\n const approved = Array.isArray(r.approved) ? r.approved : []\n const rejected = Array.isArray(r.rejected) ? r.rejected.filter((t) => t !== tail) : []\n c.customApiKeyResponses = { ...r, approved: approved.includes(tail) ? approved : [...approved, tail], rejected }\n}\nif (JSON.stringify(c) !== before) write(claudeFile, c)\nconst settingsFile = path.join(home, \".claude\", \"settings.json\")\nconst s = readJson(settingsFile)\nif (s.skipDangerousModePermissionPrompt !== true) write(settingsFile, { ...s, skipDangerousModePermissionPrompt: true })\n\n// Each block below only fills in what is unset and leaves a file it cannot parse alone.\nconst readStrict = (file) => { try { return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, \"utf8\")) : {} } catch { return null } }\nconst isObject = (v) => v !== null && typeof v === \"object\" && !Array.isArray(v)\nconst section = (o, key) => (isObject(o[key]) ? o[key] : (o[key] = {}))\n\n// Gemini CLI: folder trust and the auth-method picker (only when a Gemini key is configured; a\n// Google sign-in picks its own method), no self-update, no usage stats (its host is not on the\n// egress allowlist, so every send would fail).\nconst geminiTrustFile = path.join(home, \".gemini\", \"trustedFolders.json\")\nconst geminiTrust = readStrict(geminiTrustFile)\nif (isObject(geminiTrust) && !geminiTrust[p]) write(geminiTrustFile, { ...geminiTrust, [p]: \"TRUST_FOLDER\" })\nconst geminiSettingsFile = path.join(home, \".gemini\", \"settings.json\")\nconst g = readStrict(geminiSettingsFile)\nif (isObject(g)) {\n const gBefore = JSON.stringify(g)\n const general = section(g, \"general\")\n general.disableAutoUpdate ??= true\n general.disableUpdateNag ??= true\n section(g, \"privacy\").usageStatisticsEnabled ??= false\n // gemini-api-key or vertex-ai (GOOGLE_GENAI_USE_VERTEXAI=true with an API key): headless runs\n // refuse to start without a method (\"Invalid auth method selected\").\n if (process.env.ORCA_GEMINI_KEY) section(section(g, \"security\"), \"auth\").selectedType ??= process.env.ORCA_GEMINI_KEY\n if (JSON.stringify(g) !== gBefore) write(geminiSettingsFile, g)\n}\n\n// Cursor agent: trust the workspace (cursor-agent keys trust by a slug of the path) and pin the\n// release channel to \"static\", which turns off its background self-update.\nconst cursorTrust = path.join(home, \".cursor\", \"projects\", p.replace(/^\\/+/, \"\").replace(/[^A-Za-z0-9]+/g, \"-\"), \".workspace-trusted\")\nif (!fs.existsSync(cursorTrust)) {\n fs.mkdirSync(path.dirname(cursorTrust), { recursive: true, mode: 0o700 })\n fs.writeFileSync(cursorTrust, JSON.stringify({ trustedAt: new Date().toISOString(), workspacePath: p }, null, 2) + \"\\n\", { mode: 0o600 })\n}\nconst cursorConfigFile = path.join(home, \".cursor\", \"cli-config.json\")\nconst cc = readStrict(cursorConfigFile)\nif (isObject(cc) && cc.channel === undefined) write(cursorConfigFile, { version: 1, ...cc, channel: \"static\" })\n\n// GitHub Copilot CLI: trusted folders live in ~/.copilot/config.json, which Copilot prefixes with\n// \"//\" comment lines; keep them.\nconst copilotFile = path.join(home, \".copilot\", \"config.json\")\nlet copilotHead = \"\"\nlet co = {}\ntry {\n const raw = fs.existsSync(copilotFile) ? fs.readFileSync(copilotFile, \"utf8\") : \"\"\n const lines = raw.split(\"\\n\")\n let i = 0\n while (i < lines.length && /^\\s*\\/\\//.test(lines[i])) i++\n copilotHead = lines.slice(0, i).map((l) => l + \"\\n\").join(\"\")\n const body = lines.slice(i).join(\"\\n\").trim()\n co = body ? JSON.parse(body) : {}\n} catch { co = null }\nif (isObject(co)) {\n const folders = Array.isArray(co.trustedFolders) ? co.trustedFolders : []\n if (!folders.includes(p)) {\n fs.mkdirSync(path.dirname(copilotFile), { recursive: true, mode: 0o700 })\n const tmp = `${copilotFile}.orca-${process.pid}`\n fs.writeFileSync(tmp, copilotHead + JSON.stringify({ ...co, trustedFolders: [...folders, p] }, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, copilotFile)\n }\n}\n\n// OpenCode: with the AI Gateway preset and a model secret (ANTHROPIC_MODEL, else OPENAI_MODEL), use\n// that model through the gateway unless the user picked one. A ledger remembers what Orca wrote, so a\n// changed model secret updates it and a model the user set is never touched.\nconst ocDir = path.join(home, \".config\", \"opencode\")\nconst ocFile = path.join(ocDir, \"opencode.json\")\nconst ocLedger = path.join(ocDir, \".orca-managed-model\")\nconst managedModel = process.env.ORCA_GATEWAY_MODEL ? `vercel/${process.env.ORCA_GATEWAY_MODEL}` : \"\"\nconst oc = readStrict(ocFile)\nlet jsoncHasModel = false\ntry { jsoncHasModel = /\"model\"\\s*:/.test(fs.readFileSync(path.join(ocDir, \"opencode.jsonc\"), \"utf8\")) } catch {}\nif (isObject(oc) && !jsoncHasModel) {\n let ours = \"\"\n try { ours = fs.readFileSync(ocLedger, \"utf8\").trim() } catch {}\n const userModel = typeof oc.model === \"string\" && oc.model !== ours\n if (!userModel && (oc.model ?? \"\") !== managedModel) {\n const next = { $schema: \"https://opencode.ai/config.json\", ...oc }\n if (managedModel) next.model = managedModel\n else delete next.model\n write(ocFile, next)\n }\n if (!userModel) {\n if (managedModel) fs.writeFileSync(ocLedger, managedModel + \"\\n\", { mode: 0o600 })\n else fs.rmSync(ocLedger, { force: true })\n }\n}\n\n// OpenCode: two built-in providers cannot work in Orca Cloud, and with no other credential OpenCode\n// picks one and fails (\"Authorization header is badly formatted\" / opencode.ai unreachable) instead\n// of showing \"Connect a provider\". GitHub Copilot reads GITHUB_TOKEN, which here is the stand-in for the\n// GitHub App token of the workspace, never a Copilot token; OpenCode Zen needs opencode.ai, which is not on the\n// egress allowlist. Both stay off unless the user connected them in OpenCode itself (auth.json).\nconst ocAuth = readStrict(path.join(process.env.XDG_DATA_HOME || path.join(home, \".local\", \"share\"), \"opencode\", \"auth.json\"))\nconst connected = new Set(isObject(ocAuth) ? Object.keys(ocAuth) : [])\nconst ocDisabledLedger = path.join(ocDir, \".orca-managed-disabled-providers\")\nconst ocNow = readStrict(ocFile)\nif (isObject(ocNow) && !/\"disabled_providers\"\\s*:/.test((() => { try { return fs.readFileSync(path.join(ocDir, \"opencode.jsonc\"), \"utf8\") } catch { return \"\" } })())) {\n let ours = []\n try { ours = fs.readFileSync(ocDisabledLedger, \"utf8\").split(\"\\n\").filter(Boolean) } catch {}\n const userList = (Array.isArray(ocNow.disabled_providers) ? ocNow.disabled_providers : []).filter((id) => typeof id === \"string\" && !ours.includes(id))\n const managed = [\"github-copilot\", \"opencode\"].filter((id) => !connected.has(id) && !userList.includes(id))\n const next = [...userList, ...managed]\n const before = JSON.stringify(ocNow.disabled_providers ?? [])\n if (JSON.stringify(next) !== before) {\n const updated = { $schema: \"https://opencode.ai/config.json\", ...ocNow }\n if (next.length > 0) updated.disabled_providers = next\n else delete updated.disabled_providers\n write(ocFile, updated)\n }\n if (managed.length > 0) fs.writeFileSync(ocDisabledLedger, managed.join(\"\\n\") + \"\\n\", { mode: 0o600 })\n else fs.rmSync(ocDisabledLedger, { force: true })\n}\n' || echo 'agent first-run state not seeded' >&2\nfi\nprintf '{\"names\":%d}\\n' \"$count\"\n","orca-session-env.sh":"# Orca Cloud: sourced by every new bash/zsh (via /etc/profile.d) so terminals and agents started\n# after a secret edit get the current values with no restart. The file is written by\n# /opt/orca/bin/orca-sandbox-env on tmpfs; names it no longer lists are unset. Cloud secrets win\n# over same-named values already in the environment.\n__orca_env_file=\"/dev/shm/orca-env-$(id -u 2>/dev/null)/session.env\"\nif [ -r \"$__orca_env_file\" ]; then\n # $(...) word-splits in both bash and zsh.\n for __orca_n in $(printf '%s' \"${ORCA_SESSION_ENV_NAMES-}\"); do\n unset \"$__orca_n\" 2>/dev/null || true\n done\n __orca_names=''\n while IFS= read -r __orca_line || [ -n \"$__orca_line\" ]; do\n __orca_n=\"${__orca_line%%=*}\"\n case \"$__orca_n\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n export \"$__orca_n=$(printf '%s' \"${__orca_line#*=}\" | base64 -d 2>/dev/null)\"\n __orca_names=\"$__orca_names $__orca_n\"\n done <\"$__orca_env_file\"\n export ORCA_SESSION_ENV_NAMES=\"${__orca_names# }\"\nfi\n# Default branch of the cloud workspace repo, once its first-boot clone exists (computed once per shell tree).\nif [ -n \"${ORCA_WORKSPACE_PATH-}\" ] && [ -z \"${ORCA_DEFAULT_BRANCH-}\" ]; then\n __orca_branch=\"$(git -C \"$ORCA_WORKSPACE_PATH\" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)\"\n if [ -n \"$__orca_branch\" ]; then\n export ORCA_DEFAULT_BRANCH=\"${__orca_branch#origin/}\" CONDUCTOR_DEFAULT_BRANCH=\"${__orca_branch#origin/}\"\n fi\nfi\n# CR-cmd-quiet: Orca's staged agent launch (` . '/tmp/orca-launch-….sh'`) stays out of zsh history.\n# zsh records a line before running it, so the hook must exist first; the staged script itself\n# drops the line from bash's history. eval: bash parses this file too.\nif [ -n \"${ZSH_VERSION-}\" ]; then\n eval '__orca_skip_launch_history() { [[ $1 == *orca-launch-* ]] && return 1; return 0 }\n (( ${zshaddhistory_functions[(Ie)__orca_skip_launch_history]} )) || zshaddhistory_functions+=(__orca_skip_launch_history)'\nfi\nunset __orca_env_file __orca_line __orca_n __orca_names __orca_branch\n","orca-env":"#!/usr/bin/env bash\n# Prints shell lines that bring the current shell up to date with this session's cloud env (secrets\n# saved after the shell started): eval \"$(orca-env)\" or, in fish: orca-env --fish | source\n# Reads /dev/shm/orca-env-/session.env (written by orca-sandbox-env, `NAME=` lines) and\n# prints an export for each name, plus an unset for each name in $ORCA_SESSION_ENV_NAMES that is gone.\n# Never writes a file. Values are single-quoted, so quotes, newlines and $ in them stay literal.\nset -euo pipefail\nfish=''\ncase \"${1-}\" in\n '') ;;\n --fish) fish=1 ;;\n -h | --help)\n printf 'usage: eval \"$(orca-env)\" (fish: orca-env --fish | source)\\n'\n exit 0\n ;;\n *)\n printf 'orca-env: unknown option %s\\n' \"$1\" >&2\n exit 2\n ;;\nesac\n# ORCA_SESSION_ENV_FILE is for tests; secrets can't set ORCA_* names.\nfile=\"${ORCA_SESSION_ENV_FILE:-/dev/shm/orca-env-$(id -u)/session.env}\"\nset -f # names are split below, never globbed\n# Not written yet (or not a cloud VM): nothing to change, like the shell hook.\n[ -r \"$file\" ] || exit 0\n\n# 'it'\\''s' for POSIX shells; fish single quotes escape only \\ and '.\nquote() {\n local v=\"$1\"\n if [ -n \"$fish\" ]; then\n v=\"${v//\\\\/\\\\\\\\}\"\n v=\"${v//\\'/\\\\\\'}\"\n printf \"'%s'\" \"$v\"\n else\n printf \"'%s'\" \"${v//\\'/\\'\\\\\\'\\'}\"\n fi\n}\n\n# The control plane's reserved names and prefixes (cloud/apps/sandbox-control/src/secrets.ts; a test\n# keeps this in sync): a session file never sets what would hijack the shell or Orca's own processes.\nskip_name() {\n case \"$1\" in\n '' | *[!A-Z0-9_]* | [0-9]*) return 0 ;;\n LD_* | DYLD_* | ORCA_* | VERCEL_* | BASH_FUNC_* | GIT_CONFIG*) return 0 ;;\n PATH | HOME | USER | LOGNAME | SHELL | PWD | OLDPWD | LANG | TERM | TMPDIR | IFS | ENV | \\\n BASH_ENV | PS4 | PROMPT_COMMAND | SHELLOPTS | BASHOPTS | NODE_OPTIONS | NODE_PATH | \\\n NODE_EXTRA_CA_CERTS | NODE_TLS_REJECT_UNAUTHORIZED | SSL_CERT_FILE | SSL_CERT_DIR | \\\n CURL_CA_BUNDLE | REQUESTS_CA_BUNDLE | HTTP_PROXY | HTTPS_PROXY | ALL_PROXY | NO_PROXY | \\\n PYTHONPATH | PYTHONSTARTUP | PERL5OPT | RUBYOPT | JAVA_TOOL_OPTIONS | GIT_SSH | \\\n GIT_SSH_COMMAND | GIT_ASKPASS | GIT_EXEC_PATH | GIT_PROXY_COMMAND | SSH_AUTH_SOCK | \\\n GH_TOKEN | GITHUB_TOKEN) return 0 ;;\n # CLAUDE_CODE_OAUTH_TOKEN is reserved for users but set by the control plane itself: only ever the\n # Orca-account placeholder (contract D10), never a stored value.\n esac\n return 1\n}\n\nnames=' '\nwhile IFS= read -r line || [ -n \"$line\" ]; do\n name=\"${line%%=*}\"\n skip_name \"$name\" && continue\n # $(...) drops trailing newlines; the x keeps them.\n value=\"$(printf '%s' \"${line#*=}\" | base64 -d 2>/dev/null; printf x)\"\n value=\"${value%x}\"\n if [ -n \"$fish\" ]; then\n printf 'set -gx %s %s\\n' \"$name\" \"$(quote \"$value\")\"\n else\n printf 'export %s=%s\\n' \"$name\" \"$(quote \"$value\")\"\n fi\n names=\"$names$name \"\ndone <\"$file\"\nfor name in ${ORCA_SESSION_ENV_NAMES-}; do\n skip_name \"$name\" && continue\n case \"$names\" in *\" $name \"*) continue ;; esac\n if [ -n \"$fish\" ]; then\n printf 'set -e %s\\n' \"$name\"\n else\n printf 'unset %s\\n' \"$name\"\n fi\ndone\nnames=\"${names# }\"\nnames=\"${names% }\"\nif [ -n \"$fish\" ]; then\n printf 'set -gx ORCA_SESSION_ENV_NAMES %s\\n' \"$(quote \"$names\")\"\nelse\n printf 'export ORCA_SESSION_ENV_NAMES=%s\\n' \"$(quote \"$names\")\"\nfi\n","orca-egress-probe":"#!/usr/bin/env bash\n# Bounded Node fetch against each credential host. Vercel transform rules have made undici hang on\n# response bodies (no content-length / transfer-encoding); report it instead of letting agents hang.\n# Prints one JSON line: {\"host\":\"api.github.com\",\"status\":\"ok\"|\"egress_framing_hang\"|\"error\"}.\nset -euo pipefail\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\nfor host in \"$@\"; do\n \"$node\" -e '\n const host = process.argv[1]\n const timer = setTimeout(() => { console.log(JSON.stringify({ host, status: \"egress_framing_hang\" })); process.exit(0) }, 8000)\n fetch(`https://${host}/`, { headers: { authorization: process.env.ORCA_PROBE_AUTHORIZATION ?? \"\" } })\n .then((r) => r.arrayBuffer())\n .then(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"ok\" })) })\n .catch(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"error\" })) })\n ' \"$host\"\ndone\n","orca-image-wipe":"#!/usr/bin/env bash\n# Runs last before the golden snapshot. Every sandbox cloned from the image must start without an\n# orcad identity, device registry, agent sign-in or shell history (clone-safe identity, risk #1).\nset -euo pipefail\npkill -f orcad-server.js 2>/dev/null || true\nfor path in \\\n \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\" \"$HOME/.orca-desktop\" \"$HOME/.config/orca\" \"$HOME/.config/orca-dev\" \\\n \"$HOME/.claude\" \"$HOME/.claude.json\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.gemini\" \\\n \"$HOME/.local/share/opencode\" \"$HOME/.config/opencode\" \"$HOME/.cursor\" \"$HOME/.config/cursor\" \\\n \"$HOME/.local/share/cursor-agent\" \"$HOME/.copilot\" \"$HOME/.npm\" \"$HOME/.cache\" \"$HOME/.config/google-chrome\" \"$HOME/.bash_history\" \\\n /vercel/sandbox/project; do\n rm -rf -- \"$path\"\ndone\nsudo rm -rf /tmp/* /var/tmp/* 2>/dev/null || true\nfor leftover in \"$HOME/.orcad-data\" \"$HOME/.claude\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.cursor\" \"$HOME/.copilot\" \"$HOME/.gemini\"; do\n if [ -e \"$leftover\" ]; then\n echo \"identity survived wipe: $leftover\" >&2\n exit 1\n fi\ndone\necho '{\"wiped\":true}'\n","orca-agent-signout":"#!/usr/bin/env bash\n# Signs every agent out on this sandbox before Orca deletes it (A9): each agent's own logout, then\n# its credential files. Covers logins made inside the sandbox (the kill-switch fallback path).\n# Never fails: the sandbox is deleted next whatever happens. Values are never printed.\nset -u\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\nexport PATH=\"/opt/orca/tools/bin:$HOME/.local/bin:$HOME/.npm-global/bin:/usr/local/bin:/usr/bin:/bin:/opt/orca/bin:${PATH:-}\"\nclaude_dir=\"${CLAUDE_CONFIG_DIR:-$HOME/.claude}\"\nclaude_json=\"${CLAUDE_CONFIG_DIR:-$HOME}/.claude.json\"\ncodex_dir=\"${CODEX_HOME:-$HOME/.codex}\"\n\nlogged_out=0\n# Each logout gets a few seconds; a hung CLI must not hold up the delete.\nif command -v claude >/dev/null 2>&1 && timeout 8 claude auth logout /dev/null 2>&1; then\n logged_out=$((logged_out + 1))\nfi\nif command -v codex >/dev/null 2>&1 && timeout 8 codex logout /dev/null 2>&1; then\n logged_out=$((logged_out + 1))\nfi\n\n# The files go whether or not a logout ran: an older CLI, a missing binary or no network leaves them.\nrm -f -- \"$claude_dir\"/.credentials* \"$HOME/.claude\"/.credentials* \"$codex_dir/auth.json\" \"$HOME/.codex/auth.json\" 2>/dev/null\n# Orca-managed Codex homes keep their own auth.json under orcad's data dir.\nif [ -d \"$HOME/.orcad-data\" ]; then\n find \"$HOME/.orcad-data\" -path '*codex*' -type f -name auth.json -delete 2>/dev/null\nfi\n# ~/.claude.json keeps settings Orca wrote (onboarding, trust); only the sign-in fields go.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nfor file in \"$claude_json\" \"$HOME/.claude.json\"; do\n [ -f \"$file\" ] || continue\n if [ -n \"$node_bin\" ]; then\n ORCA_FILE=\"$file\" \"$node_bin\" -e '\nconst fs = require(\"fs\")\nconst file = process.env.ORCA_FILE\nlet c\ntry { c = JSON.parse(fs.readFileSync(file, \"utf8\")) } catch { process.exit(2) }\nif (!c || typeof c !== \"object\" || Array.isArray(c)) process.exit(2)\nlet changed = false\nfor (const key of Object.keys(c)) {\n if (/oauth/i.test(key) || key === \"primaryApiKey\") { delete c[key]; changed = true }\n}\nif (changed) {\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(c, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\n' 2>/dev/null || rm -f -- \"$file\"\n else\n # No node to edit it safely: losing Orca's settings beats leaving a sign-in behind.\n rm -f -- \"$file\"\n fi\ndone\n\nleft=0\nfor file in \"$claude_dir\"/.credentials* \"$HOME/.claude\"/.credentials* \"$codex_dir/auth.json\" \"$HOME/.codex/auth.json\"; do\n [ -e \"$file\" ] && left=$((left + 1))\ndone\nprintf '{\"loggedOut\":%d,\"left\":%d}\\n' \"$logged_out\" \"$left\"\n","orca-share-proxy":"#!/usr/bin/env node\n// Share-link proxy for this VM. Listens on 0.0.0.0:6769 (its public *.vercel.run route) and only\n// serves requests the control plane's share gateway signed with this session's key:\n// x-orca-share: v2.....\n// A request must start before `expiresAt` (60s windows); its response or WebSocket is closed at\n// `until` (the link's expiry, at most 30 minutes out), so a revoked or expired link also loses open\n// streams. Signed requests are reverse-proxied to 127.0.0.1:: streaming both ways, no\n// buffering, WebSocket upgrades piped raw. Anything unsigned gets a bare 404.\n// Vercel closes a WebSocket on a *.vercel.run route after ~340 s with no traffic (1006). A preview\n// app's socket can sit silent that long, so once an upgrade is a WebSocket the proxy watches the app's\n// frames and, after KEEPALIVE_MS with nothing either way, sends the visitor a ping control frame\n// between two frames (never inside one). The visitor's pong reaches the app, which RFC 6455 says to\n// ignore (an unsolicited pong needs no answer).\n// The key arrives on stdin (orca-sandbox-start pipes it), so it is never in this process's\n// environment or argv; ORCA_SHARE_PROXY_KEY in the env is accepted for tests. Optional\n// ORCA_SHARE_PROXY_PORT (default 6769). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst crypto = process.getBuiltinModule('node:crypto')\nconst fs = process.getBuiltinModule('node:fs')\nconst http = process.getBuiltinModule('node:http')\nconst net = process.getBuiltinModule('node:net')\n\nconst LISTEN_PORT = Number(process.env.ORCA_SHARE_PROXY_PORT || 6769)\nconst KEY = Buffer.from((process.env.ORCA_SHARE_PROXY_KEY || fs.readFileSync(0, 'utf8')).trim(), 'base64url')\ndelete process.env.ORCA_SHARE_PROXY_KEY\n// Never proxy to the VM's sshd, orcad or this proxy itself.\n// 6080: the remote desktop (VNC behind a password) is for its owner's forward only.\nconst BLOCKED_PORTS = new Set([2222, 6080, 6768, LISTEN_PORT])\nconst MAX_SKEW_SECONDS = 300\nconst MAX_CONNECTION_SECONDS = 3600\n// Well under Vercel's ~340 s idle cut. ORCA_SHARE_PROXY_KEEPALIVE_MS is for tests.\nconst KEEPALIVE_MS = Number(process.env.ORCA_SHARE_PROXY_KEEPALIVE_MS || 30_000)\n// FIN + ping opcode, empty payload, unmasked (server to client).\nconst PING_FRAME = Buffer.from([0x89, 0x00])\nconst HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-connection', 'transfer-encoding', 'te', 'trailer', 'upgrade']\n\nif (KEY.length < 32) {\n console.error('orca-share-proxy: share proxy key missing or short')\n process.exit(2)\n}\n\n/** The target port and close-by time (ms) for a validly signed request, else null. */\nfunction verify(header, nowMs) {\n if (typeof header !== 'string') {\n return null\n }\n const match = /^v2\\.(\\d{1,5})\\.(\\d{1,12})\\.(\\d{1,12})\\.([0-9a-f]{32})\\.([A-Za-z0-9_-]{43})$/.exec(header)\n if (!match) {\n return null\n }\n const now = Math.floor(nowMs / 1000)\n const port = Number(match[1])\n const expiresAt = Number(match[2])\n const until = Number(match[3])\n if (port < 1 || port > 65535 || BLOCKED_PORTS.has(port)) {\n return null\n }\n if (expiresAt < now || expiresAt > now + MAX_SKEW_SECONDS || until <= now || until > now + MAX_CONNECTION_SECONDS) {\n return null\n }\n const signed = header.slice(0, header.lastIndexOf('.'))\n const expected = crypto.createHmac('sha256', KEY).update(signed).digest()\n const given = Buffer.from(match[5], 'base64url')\n return given.length === expected.length && crypto.timingSafeEqual(given, expected) ? { port, untilMs: until * 1000 } : null\n}\n\nfunction upstreamHeaders(raw, port) {\n const headers = { ...raw }\n const connectionTokens = String(raw.connection || '')\n .split(',')\n .map((token) => token.trim().toLowerCase())\n for (const name of [...HOP_BY_HOP, ...connectionTokens, 'x-orca-share']) {\n delete headers[name]\n }\n // Dev servers (Vite, Next) allow localhost hosts by default; the public host rides x-forwarded-host.\n headers.host = `localhost:${port}`\n return headers\n}\n\nfunction refuse(res) {\n res.writeHead(404, { 'content-type': 'text/plain', 'cache-control': 'no-store' })\n res.end('not found')\n}\n\n/**\n * Follows the app's WebSocket frames (server to client: header, then payload) just closely enough to\n * know when the stream sits between two frames, where a control frame may be inserted.\n */\nfunction frameBoundaries() {\n let header = []\n let remaining = 0\n return {\n push(chunk) {\n let i = 0\n while (i < chunk.length) {\n if (remaining > 0) {\n const take = Math.min(remaining, chunk.length - i)\n remaining -= take\n i += take\n continue\n }\n header.push(chunk[i++])\n if (header.length < 2) {\n continue\n }\n const len7 = header[1] & 0x7f\n const need = 2 + (len7 === 126 ? 2 : len7 === 127 ? 8 : 0) + (header[1] & 0x80 ? 4 : 0)\n if (header.length < need) {\n continue\n }\n const bytes = Buffer.from(header)\n remaining = len7 === 126 ? bytes.readUInt16BE(2) : len7 === 127 ? Number(bytes.readBigUInt64BE(2)) : len7\n header = []\n }\n },\n atBoundary: () => header.length === 0 && remaining === 0\n }\n}\n\n/** The app's answer to the upgrade: its head is passed through; only a 101 to `websocket` gets keepalives. */\nfunction upgradeAnswer() {\n let head = Buffer.alloc(0)\n let state = 'head'\n const frames = frameBoundaries()\n return {\n push(chunk) {\n if (state === 'head') {\n head = Buffer.concat([head, chunk])\n const end = head.indexOf('\\r\\n\\r\\n')\n if (end === -1) {\n if (head.length > 64 * 1024) {\n state = 'raw'\n }\n return\n }\n const text = head.subarray(0, end).toString('latin1')\n state = /^HTTP\\/1\\.1 101/.test(text) && /^upgrade:\\s*websocket\\s*$/im.test(text) ? 'ws' : 'raw'\n chunk = head.subarray(end + 4)\n head = Buffer.alloc(0)\n }\n if (state === 'ws') {\n frames.push(chunk)\n }\n },\n canPing: () => state === 'ws' && frames.atBoundary()\n }\n}\n\n/** Ends `close` at the grant's deadline; the timer goes away with the connection. */\nfunction deadline(untilMs, close, ...emitters) {\n const timer = setTimeout(close, Math.max(0, untilMs - Date.now()))\n for (const emitter of emitters) {\n emitter.once('close', () => clearTimeout(timer))\n }\n}\n\nconst server = http.createServer((req, res) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n return refuse(res)\n }\n const { port } = grant\n const upstream = http.request(\n { host: '127.0.0.1', port, method: req.method, path: req.url, headers: upstreamHeaders(req.headers, port) },\n (answer) => {\n const headers = { ...answer.headers }\n for (const name of HOP_BY_HOP) {\n delete headers[name]\n }\n // Marks the answer as the app's, so the gateway can tell it from a route with no proxy behind it.\n headers['x-orca-share-proxy'] = '1'\n res.writeHead(answer.statusCode || 502, answer.statusMessage, headers)\n answer.pipe(res)\n }\n )\n deadline(grant.untilMs, () => {\n upstream.destroy()\n res.destroy()\n }, res)\n upstream.on('error', (error) => {\n if (res.headersSent) {\n res.destroy()\n return\n }\n // The gateway renders its own page for this; the code tells it why. Status 200 on purpose: a 5xx\n // from the VM reaches a Worker as Vercel's own 502 with our headers gone (found live).\n res.writeHead(200, { 'content-type': 'text/plain', 'x-orca-share-proxy': '1', 'x-orca-share-error': error.code === 'ECONNREFUSED' ? 'no_listener' : 'upstream_failed' })\n res.end('upstream unavailable')\n })\n req.on('aborted', () => upstream.destroy())\n req.pipe(upstream)\n})\n\nserver.on('upgrade', (req, socket, head) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n socket.end('HTTP/1.1 404 Not Found\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n return\n }\n const { port } = grant\n const headers = upstreamHeaders(req.headers, port)\n const target = net.connect(port, '127.0.0.1', () => {\n const lines = [`${req.method} ${req.url} HTTP/1.1`, `connection: upgrade`, `upgrade: ${req.headers.upgrade || 'websocket'}`]\n for (const [name, value] of Object.entries(headers)) {\n for (const item of Array.isArray(value) ? value : [value]) {\n lines.push(`${name}: ${item}`)\n }\n }\n target.write(`${lines.join('\\r\\n')}\\r\\n\\r\\n`)\n if (head && head.length > 0) {\n target.write(head)\n }\n socket.pipe(target)\n // App to visitor by hand (with backpressure) so the keepalive knows where frames start and end.\n const answer = upgradeAnswer()\n let lastTraffic = Date.now()\n socket.on('data', () => {\n lastTraffic = Date.now()\n })\n target.on('data', (chunk) => {\n lastTraffic = Date.now()\n answer.push(chunk)\n if (!socket.write(chunk)) {\n target.pause()\n socket.once('drain', () => target.resume())\n }\n })\n target.on('end', () => socket.end())\n const keepalive = setInterval(() => {\n if (Date.now() - lastTraffic >= KEEPALIVE_MS && answer.canPing() && socket.writable) {\n socket.write(PING_FRAME)\n lastTraffic = Date.now()\n }\n }, Math.max(50, Math.floor(KEEPALIVE_MS / 3)))\n socket.once('close', () => clearInterval(keepalive))\n })\n const close = () => {\n socket.destroy()\n target.destroy()\n }\n deadline(grant.untilMs, close, socket)\n target.on('error', () => {\n if (socket.writable) {\n socket.end('HTTP/1.1 200 OK\\r\\nx-orca-share-proxy: 1\\r\\nx-orca-share-error: no_listener\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n }\n close()\n })\n socket.on('error', close)\n target.on('close', () => socket.destroy())\n socket.on('close', () => target.destroy())\n})\n\nserver.keepAliveTimeout = 65_000\nserver.headersTimeout = 70_000\n// No request timeout: previews can stream (SSE, long polls) until the grant's deadline.\nserver.requestTimeout = 0\nserver.listen(LISTEN_PORT, '0.0.0.0', () => {\n console.log(`orca-share-proxy listening on ${LISTEN_PORT}`)\n})\n","orca-sshd":"#!/usr/bin/env bash\n# Starts this boot's unprivileged sshd on 127.0.0.1:2222 (idempotent). Nothing outside the VM can\n# reach that port: the desktop tunnels to it over orcad's runtime connection (`orca ssh-proxy`).\n# Key-only, single user (the sandbox user), no root. Its host key and authorized_keys live under\n# ~/.orca-sandbox/ssh on the persistent disk, so the host key stays the same across stop/resume;\n# orca-image-wipe removes that directory, so every VM cloned from the golden image makes its own.\n# Prints {\"port\":2222,\"user\":\"\",\"hostKey\":\"ssh-ed25519 AAAA...\"} on success.\nset -euo pipefail\numask 077\nOPENSSH=/opt/orca/openssh\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\nPORT=2222\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 8>\"$SSH_DIR/sshd.lock\"\nflock -w 30 8\n\nif [ ! -x \"$OPENSSH/sshd\" ]; then\n echo 'sshd is not installed in this image' >&2\n exit 3\nfi\nif [ ! -s \"$SSH_DIR/ssh_host_ed25519_key\" ]; then\n rm -f \"$SSH_DIR/ssh_host_ed25519_key\" \"$SSH_DIR/ssh_host_ed25519_key.pub\"\n ssh-keygen -q -t ed25519 -N '' -C \"orca-cloud-host\" -f \"$SSH_DIR/ssh_host_ed25519_key\"\nfi\ntouch \"$SSH_DIR/authorized_keys\"\nchmod 0600 \"$SSH_DIR/authorized_keys\"\n\n# Rewritten every start so an image update's settings apply to existing workspaces. PAM stays at\n# its compiled-in default (off): an unprivileged sshd cannot use it, and this build warns on `no`.\ncat >\"$SSH_DIR/sshd_config\" </dev/null || echo 0)\"\n# Resume reboots from disk, so a recorded pid can name a dead process or an unrelated one.\nif ! { kill -0 \"$pid\" 2>/dev/null && grep -q sshd \"/proc/$pid/cmdline\" 2>/dev/null; }; then\n rm -f \"$SSH_DIR/sshd.pid\"\n : >\"$SSH_DIR/sshd.log\"\n \"$OPENSSH/sshd\" -t -f \"$SSH_DIR/sshd_config\"\n \"$OPENSSH/sshd\" -f \"$SSH_DIR/sshd_config\" -E \"$SSH_DIR/sshd.log\"\n for _ in $(seq 1 100); do\n [ -s \"$SSH_DIR/sshd.pid\" ] && break\n sleep 0.02\n done\n [ -s \"$SSH_DIR/sshd.pid\" ] || { echo 'sshd did not start' >&2; tail -n 20 \"$SSH_DIR/sshd.log\" >&2; exit 1; }\nfi\n\nhost_key=\"$(cut -d' ' -f1-2 \"$SSH_DIR/ssh_host_ed25519_key.pub\")\"\nprintf '{\"port\":%s,\"user\":\"%s\",\"hostKey\":\"%s\"}\\n' \"$PORT\" \"$(id -un)\" \"$host_key\"\n","orca-ssh-keys":"#!/usr/bin/env bash\n# `orca-ssh-keys add|remove`: adds or removes one desktop's key in the Orca-managed authorized_keys\n# of this VM's sshd, then makes sure sshd runs. The control plane passes the key in\n# ORCA_SSH_PUBLIC_KEY (`ssh-ed25519 `), never on the command line. Keys are\n# matched by their base64 blob, so a renamed comment cannot keep a revoked key alive.\n# Prints orca-sshd's {\"port\":...,\"user\":...,\"hostKey\":...} line on success.\nset -euo pipefail\numask 077\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\naction=\"${1:-}\"\nkey=\"${ORCA_SSH_PUBLIC_KEY:-}\"\n# grep matches per line: a second line could carry key options past the check below.\ncase \"$key\" in *$'\\n'* | *$'\\r'*) echo 'invalid public key' >&2; exit 2 ;; esac\n# One line, ed25519 only, a plain comment: nothing that sshd would read as key options.\nif ! printf '%s' \"$key\" | grep -Eq '^ssh-ed25519 [A-Za-z0-9+/]{68} [A-Za-z0-9@._:+-]{1,200}$'; then\n echo 'invalid public key' >&2\n exit 2\nfi\nblob=\"$(printf '%s' \"$key\" | cut -d' ' -f2)\"\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 7>\"$SSH_DIR/keys.lock\"\nflock -w 30 7\ntouch \"$SSH_DIR/authorized_keys\"\nnext=\"$(mktemp \"$SSH_DIR/authorized_keys.XXXXXX\")\"\n# Drop the key wherever it appears (with or without options), then append it on add.\nawk -v blob=\"$blob\" '{ for (i = 1; i <= NF; i++) if ($i == blob) next; print }' \\\n \"$SSH_DIR/authorized_keys\" >\"$next\"\ncase \"$action\" in\n add) printf '%s\\n' \"$key\" >>\"$next\" ;;\n remove) ;;\n *) rm -f \"$next\"; echo 'usage: orca-ssh-keys add|remove' >&2; exit 2 ;;\nesac\nchmod 0600 \"$next\"\nmv -f \"$next\" \"$SSH_DIR/authorized_keys\"\nexec /opt/orca/bin/orca-sshd\n","orca-desktop-start":"#!/usr/bin/env bash\n# Starts the on-demand remote desktop (idempotent) and mints one connection ticket. Prints one line:\n# {\"schemaVersion\":2,\"port\":6080,\"display\":\":1\",\"path\":\"vnc.html\",\"ticket\":\"<43 chars>\",\"expiresInMs\":60000}\n# Xvnc (X server + VNC in one) listens on a 0600 unix socket only, with no VNC auth: only this uid\n# can open it. orca-desktop-proxy (websockify + a ticket gate) serves noVNC on 127.0.0.1 and\n# bridges WebSockets to that socket. Nothing is reachable from outside the VM: the desktop app\n# reaches it through Orca's port forward, a localhost port on the user's computer that any local\n# process or web page can reach, so each WebSocket needs a ticket from here: 32 random bytes,\n# single use, valid for 60 s, stored only as its sha256 (the file name; its content is the expiry).\n# The ticket goes to stdout only (the control plane hands it to the desktop app). Never started at boot.\nset -euo pipefail\numask 077\nDESKTOP=/opt/orca/desktop\nSTATE=\"$HOME/.orca-desktop\"\nPORT=\"${ORCA_DESKTOP_PORT:-6080}\"\nDISPLAY_NUM=\"${ORCA_DESKTOP_DISPLAY:-1}\"\nGEOMETRY=\"${ORCA_DESKTOP_GEOMETRY:-1280x800}\"\nSOCKET=\"$STATE/vnc.sock\"\n# The parent's DISPLAY must not leak into the WM/xterm below; they use ours.\nexport DISPLAY=\":$DISPLAY_NUM\"\n\n# Exit 3 = this image has no desktop (built before it, or its optional install failed).\nfail() { printf 'orca-desktop: %s\\n' \"$1\" >&2; exit \"${2:-1}\"; }\ncase \"$PORT\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_PORT must be a number' ;; esac\ncase \"$DISPLAY_NUM\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_DISPLAY must be a number' ;; esac\ncase \"$GEOMETRY\" in [0-9]*x[0-9]*) ;; *) fail 'ORCA_DESKTOP_GEOMETRY must look like 1280x800' ;; esac\ncommand -v Xvnc >/dev/null || fail 'not installed in this image (Xvnc missing)' 3\n[ -s \"$DESKTOP/novnc/vnc.html\" ] || fail 'not installed in this image (noVNC missing)' 3\nPROXY=\"$(dirname \"$(readlink -f \"$0\")\")/orca-desktop-proxy\"\n[ -x \"$PROXY\" ] || fail 'orca-desktop-proxy missing next to this script'\nTICKETS=\"$STATE/tickets\"\nTICKET_TTL_S=60\n# Xvnc's mode: a previous version of this script ran it with VncAuth; restart it in this mode.\nMODE=ticket-v1\n\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/start.lock\"\nflock -w 30 9 || fail 'another start is in progress'\n\npid_of() { # never \"0\": kill 0 targets our own process group\n local pid\n pid=\"$(cat \"$STATE/$1.pid\" 2>/dev/null || true)\"\n case \"$pid\" in '' | 0 | *[!0-9]*) return 1 ;; esac\n printf '%s' \"$pid\"\n}\nalive() { local pid; pid=\"$(pid_of \"$1\")\" && kill -0 \"$pid\" 2>/dev/null; }\nmint_ticket() { # prints the ticket; stores only its sha256, with the expiry as content\n local ticket now digest\n mkdir -p \"$TICKETS\"\n now=\"$(date +%s)\"\n # Expired or spent-but-unswept tickets; keep at most 16 live ones (oldest go first).\n for file in \"$TICKETS\"/*; do\n [ -f \"$file\" ] || continue\n [ \"$(cat \"$file\" 2>/dev/null || echo 0)\" -ge \"$now\" ] 2>/dev/null || rm -f \"$file\"\n done\n # shellcheck disable=SC2012 # names are hex digests\n ls -1t \"$TICKETS\" 2>/dev/null | tail -n +16 | while read -r old; do rm -f \"$TICKETS/$old\"; done\n ticket=\"$(head -c 32 /dev/urandom | base64 | tr '+/' '-_' | tr -d '=\\n')\"\n [ \"${#ticket}\" = 43 ] || fail 'could not generate a ticket'\n digest=\"$(printf '%s' \"$ticket\" | sha256sum | cut -d' ' -f1)\"\n printf '%s' \"$((now + TICKET_TTL_S))\" >\"$TICKETS/.$digest\" && mv \"$TICKETS/.$digest\" \"$TICKETS/$digest\"\n printf '%s' \"$ticket\"\n}\nready_line() {\n local ticket\n ticket=\"$(mint_ticket)\" || exit 1\n printf '{\"schemaVersion\":2,\"port\":%s,\"display\":\":%s\",\"path\":\"vnc.html\",\"ticket\":\"%s\",\"expiresInMs\":%s}\\n' \\\n \"$PORT\" \"$DISPLAY_NUM\" \"$ticket\" \"$((TICKET_TTL_S * 1000))\"\n}\nlistening() { # the proxy answers HTTP on loopback\n curl -fsS -o /dev/null --max-time 1 \"http://127.0.0.1:$PORT/vnc.html\" 2>/dev/null\n}\n\n# Pids from a previous boot (resume = reboot from disk) name dead or unrelated processes.\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" != \"$boot_id\" ]; then\n rm -rf \"$STATE\"/*.pid \"$SOCKET\" \"$STATE/password\" \"$STATE/passwd\" \"$STATE/mode\" \"$TICKETS\"\n printf '%s' \"$boot_id\" >\"$STATE/boot-id\"\nfi\n\n# Same boot, older script: its websockify had no ticket gate and its Xvnc wanted a VNC password.\nrm -f \"$STATE/password\" \"$STATE/passwd\"\nif alive websockify; then kill \"$(pid_of websockify)\" 2>/dev/null || true; fi\nrm -f \"$STATE/websockify.pid\"\ncurrent_mode() { cat \"$STATE/mode\" 2>/dev/null || true; }\n\nif alive xvnc && alive proxy && listening && [ \"$(current_mode)\" = \"$MODE\" ]; then\n ready_line\n exit 0\nfi\n\nstart() { # name cmd... — detached, logs in $STATE/.log\n local name=$1; shift\n # 9>&-: children must not inherit the start lock, or the next call waits for them to exit.\n setsid nohup \"$@\" >\"$STATE/$name.log\" 2>&1 &- &\n echo $! >\"$STATE/$name.pid\"\n}\n\nif ! alive xvnc || [ \"$(current_mode)\" != \"$MODE\" ]; then\n if alive xvnc; then kill \"$(pid_of xvnc)\" 2>/dev/null || true; sleep 0.2; fi\n rm -f \"$SOCKET\"\n # -rfbport -1: no TCP VNC port at all, only a 0600 unix socket (in the 0700 state dir) for the\n # proxy. SecurityTypes None is safe only because of that: the ticket gate is in the proxy.\n # SendPrimary=0: only explicit copies (xterm copies its selection, below) leave the sandbox.\n # The X display itself takes a cookie from ~/.Xauthority (Xlib's default for this user), so only\n # this uid's processes (agents, apps they start on DISPLAY=:1) can open it.\n auth=()\n if command -v xauth >/dev/null && command -v mcookie >/dev/null; then\n xauth -q -f \"$HOME/.Xauthority\" add \":$DISPLAY_NUM\" . \"$(mcookie)\" 9>&- && auth=(-auth \"$HOME/.Xauthority\")\n fi\n start xvnc Xvnc \":$DISPLAY_NUM\" \"${auth[@]}\" -geometry \"$GEOMETRY\" -depth 24 -nolisten tcp \\\n -rfbport -1 -rfbunixpath \"$SOCKET\" -rfbunixmode 0600 \\\n -SecurityTypes None -SendPrimary=0 \\\n -AlwaysShared -AcceptSetDesktopSize -desktop 'Remote desktop'\n printf '%s' \"$MODE\" >\"$STATE/mode\"\n for _ in $(seq 1 100); do\n [ -S \"$SOCKET\" ] && break\n alive xvnc || { tail -n 20 \"$STATE/xvnc.log\" >&2; fail 'Xvnc exited'; }\n sleep 0.05\n done\n [ -S \"$SOCKET\" ] || fail 'Xvnc did not create its socket'\n if command -v xsetroot >/dev/null; then xsetroot -solid '#1e1f22' 9>&- || true; fi\n if command -v openbox >/dev/null; then\n # Dark, flat theme to match Orca; the first terminal stays maximized as the tab resizes the screen.\n printf '%s\\n' '' \\\n 'Onyx' \\\n 'yes' \\\n '' >\"$STATE/openbox.xml\"\n start wm openbox --config-file \"$STATE/openbox.xml\"\n # Let it manage the screen before the terminal maps, so its maximize rule applies.\n sleep 0.2\n elif command -v twm >/dev/null; then\n start wm twm\n fi\n if command -v xterm >/dev/null; then\n # selectToClipboard: a selection is a copy (to CLIPBOARD, which reaches this computer).\n start xterm xterm -maximized -bg '#1e1f22' -fg '#d4d4d4' -fa 'Liberation Mono,Monospace' -fs 11 \\\n -xrm 'XTerm*selectToClipboard: true'\n fi\nfi\n\nif ! alive proxy || ! listening; then\n if alive proxy; then kill \"$(pid_of proxy)\" 2>/dev/null || true; sleep 0.1; fi\n mkdir -p \"$TICKETS\"\n PYTHONPATH=\"$DESKTOP/websockify\" start proxy python3 -P -W ignore::UserWarning \"$PROXY\" \\\n --listen \"$PORT\" --web \"$DESKTOP/novnc\" --unix-target \"$SOCKET\" --tickets \"$TICKETS\"\n for _ in $(seq 1 100); do\n listening && break\n alive proxy || { tail -n 20 \"$STATE/proxy.log\" >&2; fail 'orca-desktop-proxy exited'; }\n sleep 0.05\n done\n listening || fail \"orca-desktop-proxy is not answering on 127.0.0.1:$PORT\"\nfi\nready_line\n","orca-desktop-proxy":"#!/usr/bin/env python3\n# Remote desktop gateway, started by orca-desktop-start: serves noVNC on 127.0.0.1 and bridges one\n# WebSocket per single-use ticket to Xvnc's 0600 unix socket (Xvnc itself has no VNC auth: only this\n# uid can open the socket). The port is reached only through Orca's localhost forward on the user's\n# computer, where any local process or web page could knock, so every WebSocket must carry an\n# unused, unexpired ticket minted by orca-desktop-start (see consume_ticket), from a page on the same\n# localhost origin. Tickets never reach a log: paths are scrubbed before websockify logs them.\n# orca-desktop-proxy --listen PORT --web DIR --unix-target SOCKET --tickets DIR\n# stdlib + websockify (pinned tarball in /opt/orca/desktop/websockify, on PYTHONPATH) only.\nimport argparse\nimport hashlib\nimport hmac\nimport logging\nimport os\nimport re\nimport sys\nimport time\nfrom urllib.parse import parse_qs, urlsplit\n\nfrom websockify import websocketproxy\n\nTICKET_RE = re.compile(r'^[A-Za-z0-9_-]{43}$') # 32 random bytes, base64url without padding\nSCRUB_RE = re.compile(r'([?&]ticket=)[^&\\s\\'\"]*')\nLOOPBACK_HOST_RE = re.compile(r'^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:[0-9]{1,5})?$')\nWS_PATH = '/websockify'\nPAGE_SCRIPT = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'orca-desktop-page.js')\n# The page may only talk to its own origin (its WebSocket included): even a URL that tries to point\n# noVNC elsewhere cannot carry a ticket or the user's keys off this forward.\nPAGE_CSP = \"connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'\"\nPAGE_TAG = b'\\n'\n\n\ndef scrub(text):\n return SCRUB_RE.sub(r'\\1', str(text))\n\n\ndef ticket_digest(ticket):\n return hashlib.sha256(ticket.encode('ascii')).hexdigest()\n\n\ndef consume_ticket(directory, ticket, now=None):\n \"\"\"True once per minted ticket, within its lifetime. The ticket file (named by the ticket's\n sha256, holding its expiry) is unlinked on first use, so a replay or a racing second\n connection finds nothing; each request runs in its own forked process, so state is on disk.\"\"\"\n if not isinstance(ticket, str) or not TICKET_RE.match(ticket):\n return False\n digest = ticket_digest(ticket)\n match = None\n try:\n names = os.listdir(directory)\n except OSError:\n return False\n for name in names:\n # Compare every entry in constant time; never short-circuit on a prefix.\n if hmac.compare_digest(name.encode('ascii', 'replace'), digest.encode('ascii')):\n match = name\n if match is None:\n return False\n path = os.path.join(directory, match)\n try:\n with open(path, 'r', encoding='ascii') as handle:\n expires_at = int(handle.read().strip() or '0')\n except (OSError, ValueError):\n expires_at = 0\n try:\n os.unlink(path) # the consume: only one caller can win this\n except FileNotFoundError:\n return False\n return (now if now is not None else time.time()) <= expires_at\n\n\ndef same_loopback_origin(headers):\n \"\"\"The page and the WebSocket share one localhost origin (blocks other local sites and DNS\n rebinding). The port is the user's local forward, which may differ from ours, so compare the\n Origin with the Host the browser dialed rather than with a fixed port.\"\"\"\n host = (headers.get('Host') or '').strip().lower()\n origin = (headers.get('Origin') or '').strip().lower()\n return loopback_host(host) and origin == 'http://' + host\n\n\ndef loopback_host(host):\n return bool(LOOPBACK_HOST_RE.match(host or ''))\n\n\nclass TicketedProxyHandler(websocketproxy.ProxyRequestHandler):\n \"\"\"websockify's proxy handler plus the ticket + origin gate. Module level (not a closure) so\n websockify's per-connection multiprocessing can pickle it under any start method.\"\"\"\n\n def log_message(self, format, *args): # noqa: A002 (websockify's signature)\n super().log_message('%s', scrub(format % args if args else format))\n\n def reject(self, code, reason):\n self.send_response(code)\n self.send_header('Content-Length', '0')\n self.send_header('Connection', 'close')\n self.end_headers()\n self.close_connection = True\n raise self.server.EClose('desktop: websocket refused (%s)' % reason)\n\n def validate_connection(self):\n parts = urlsplit(self.path)\n ticket = (parse_qs(parts.query).get('ticket') or [''])[0]\n # Drop it before anything below (websockify's own logging included) can see self.path.\n self.path = parts.path\n if parts.path != WS_PATH:\n self.reject(404, 'path')\n if not same_loopback_origin(self.headers):\n self.reject(403, 'origin')\n if not consume_ticket(self.server.orca_tickets_dir, ticket):\n self.reject(403, 'ticket')\n\n def loopback_request(self):\n if loopback_host((self.headers.get('Host') or '').strip().lower()):\n return True\n self.send_error(403)\n return False\n\n def do_GET(self):\n if not self.loopback_request():\n return None\n path = urlsplit(self.path).path\n if path == '/orca-desktop-page.js':\n return self.send_bytes(read_file(PAGE_SCRIPT), 'text/javascript; charset=utf-8')\n if path == '/vnc.html':\n page = read_file(os.path.join(self.server.web, 'vnc.html'))\n return self.send_bytes(page.replace(b'', PAGE_TAG, 1), 'text/html; charset=utf-8', PAGE_CSP)\n return super().do_GET()\n\n def do_HEAD(self):\n if not self.loopback_request():\n return None\n return super().do_HEAD()\n\n def send_bytes(self, body, content_type, csp=None):\n self.send_response(200)\n self.send_header('Content-Type', content_type)\n if csp:\n self.send_header('Content-Security-Policy', csp)\n self.send_header('Content-Length', str(len(body)))\n self.send_header('Cache-Control', 'no-store')\n self.send_header('Referrer-Policy', 'no-referrer')\n self.end_headers()\n self.wfile.write(body)\n return None\n\n\ndef read_file(path):\n with open(path, 'rb') as handle:\n return handle.read()\n\n\ndef main(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('--listen', type=int, required=True)\n parser.add_argument('--web', required=True)\n parser.add_argument('--unix-target', required=True)\n parser.add_argument('--tickets', required=True)\n args = parser.parse_args(argv)\n logging.basicConfig(level=logging.INFO, format='%(message)s')\n server = websocketproxy.WebSocketProxy(\n RequestHandlerClass=TicketedProxyHandler,\n listen_host='127.0.0.1',\n listen_port=args.listen,\n web=args.web,\n file_only=True,\n unix_target=args.unix_target,\n )\n server.orca_tickets_dir = os.path.abspath(args.tickets)\n server.start_server()\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","orca-desktop-page.js":"// Orca's glue for noVNC, injected into vnc.html by orca-desktop-proxy. Orca (the desktop app's\n// main process) drives it through window.orcaDesktop:\n// - tickets: the page never connects by itself. Each WebSocket needs a fresh single-use ticket,\n// which Orca hands over with connect(ticket) after nextTicketRequest() resolves: 'ticket' on\n// load or after a session dropped, 'retry' after an attempt that never connected. Tickets live\n// only in memory here: never in the URL, storage or noVNC's settings.\n// - pause(message, label): Orca stopped retrying; show why, with a Reconnect button. resume()\n// (Orca reopened the desktop) or the button asks for a ticket again.\n// - fit: resize=remote makes Xvnc follow the tab; a server without SetDesktopSize gets scaling.\n// - clipboard: a copy inside the desktop right after user input there goes to this computer's\n// clipboard; paste(text, chord) sets the sandbox's clipboard first, then replays the paste key.\nimport UI from './app/ui.js';\nimport * as WebUtil from './app/webutil.js';\n\nconst WS_PATH = 'websockify';\nconst RESIZE_FALLBACK_MS = 1500;\n// A copy inside the desktop follows a copy key or a selection (drag or double-click) there; other\n// clipboard changes (an agent in the sandbox running xclip) must not overwrite this computer's\n// clipboard. Plain typing does not open the window.\nconst USER_COPY_WINDOW_MS = 1500;\nconst DRAG_PX = 4;\nconst MAX_CLIPBOARD_CHARS = 1 << 20;\nconst TICKET_RE = /^[A-Za-z0-9_-]{43}$/;\nconst XK = { v: 0x0076, V: 0x0056, Insert: 0xff63, Shift_L: 0xffe1, Super_L: 0xffeb, Super_R: 0xffec };\n\nlet state = 'idle'; // idle | connecting | connected | disconnected | paused\nlet attemptConnected = true;\nlet ticketWaiters = [];\nlet lastCopyIntent = 0;\nlet pointerStart = null;\n\nconst style = document.createElement('style');\n// Orca owns connecting and the chrome: noVNC's Connect button would only try without a ticket,\n// and its control bar duplicates what the Orca tab does (fit, clipboard, keyboard release).\n// The pause card follows Orca's theme: Orca sets Electron's theme source from its own setting, so\n// prefers-color-scheme here is Orca's light or dark, and it follows a switch while paused. The\n// page cannot read Orca's tokens, so these mirror them (popover, border, focus ring).\nstyle.textContent = `\n#noVNC_connect_dlg, #noVNC_control_bar_anchor { display: none !important; }\n#orca_pause { --orca-scrim: rgb(10 10 10 / 0.88); --orca-card: #171717; --orca-text: #f0f0f0;\n --orca-border: rgb(255 255 255 / 0.1); --orca-control: rgb(255 255 255 / 0.25);\n --orca-control-hover: rgb(255 255 255 / 0.08); --orca-focus: color-mix(in oklab, #f0f0f0 65%, #0a0a0a);\n color-scheme: dark; position: fixed; inset: 0; display: none; align-items: center;\n justify-content: center; padding: 16px; background: var(--orca-scrim); z-index: 1000;\n font: 13px/1.5 system-ui, sans-serif; }\n@media (prefers-color-scheme: light) {\n #orca_pause { --orca-scrim: rgb(255 255 255 / 0.88); --orca-card: #fff; --orca-text: #0a0a0a;\n --orca-border: #e5e5e5; --orca-control: #a3a3a3; --orca-control-hover: #f5f5f5;\n --orca-focus: color-mix(in oklab, #0a0a0a 55%, #fff); color-scheme: light; }\n}\n#orca_pause.open { display: flex; }\n#orca_pause > div { max-width: 360px; padding: 16px; border: 1px solid var(--orca-border);\n border-radius: 8px; background: var(--orca-card); color: var(--orca-text); text-align: center;\n box-shadow: 0 8px 24px rgb(0 0 0 / 0.16); }\n#orca_pause p { margin: 0; }\n#orca_pause button { margin-top: 12px; padding: 4px 12px; border: 1px solid var(--orca-control);\n border-radius: 6px; background: transparent; color: var(--orca-text); font: inherit; cursor: pointer; }\n#orca_pause button:hover { background: var(--orca-control-hover); }\n#orca_pause button:focus-visible { outline: 2px solid var(--orca-focus); outline-offset: 2px; }\n@media (prefers-reduced-motion: no-preference) {\n #orca_pause.open > div { animation: orca-pause-in 120ms ease-out; }\n}\n@keyframes orca-pause-in { from { opacity: 0; transform: translateY(4px); } }\n`;\ndocument.head.appendChild(style);\n\nconst overlay = document.createElement('div');\noverlay.id = 'orca_pause';\noverlay.innerHTML = '

';\noverlay.querySelector('button').addEventListener('click', () => resume());\ndocument.addEventListener('DOMContentLoaded', () => document.body.appendChild(overlay));\n\nwindow.addEventListener('keydown', (event) => {\n if ((event.ctrlKey || event.metaKey) && !event.altKey && (event.key === 'c' || event.key === 'C' || event.key === 'Insert')) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerdown', (event) => {\n pointerStart = { x: event.clientX, y: event.clientY };\n}, true);\n// A double- or triple-click selects a word or line (pointer events carry no click count).\nwindow.addEventListener('mousedown', (event) => {\n if (event.detail >= 2) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerup', (event) => {\n if (pointerStart && Math.hypot(event.clientX - pointerStart.x, event.clientY - pointerStart.y) >= DRAG_PX) {\n lastCopyIntent = Date.now();\n }\n pointerStart = null;\n}, true);\n\nfunction requestTicket() {\n const answer = attemptConnected ? 'ticket' : 'retry';\n const waiters = ticketWaiters;\n ticketWaiters = [];\n waiters.forEach((resolve) => resolve(answer));\n}\n\nasync function whenStarted() {\n while (document.documentElement.classList.contains('noVNC_loading')) {\n await new Promise((resolve) => setTimeout(resolve, 25));\n }\n}\n\nfunction onConnect() {\n state = 'connected';\n attemptConnected = true;\n UI.hideStatus();\n setTimeout(() => {\n // Xvnc answers SetDesktopSize; anything that does not gets scaled into the tab instead.\n if (UI.rfb && state === 'connected' && !UI.rfb._supportsSetDesktopSize) {\n UI.rfb.scaleViewport = true;\n }\n }, RESIZE_FALLBACK_MS);\n}\n\nfunction onDisconnect() {\n if (state === 'paused') {\n return;\n }\n state = 'disconnected';\n // The ticket is spent: ask Orca for a new one (a dropped forward, a restart of the desktop).\n requestTicket();\n}\n\nfunction onClipboard(event) {\n const text = event.detail && event.detail.text;\n if (typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return;\n }\n if (Date.now() - lastCopyIntent > USER_COPY_WINDOW_MS || !document.hasFocus()) {\n return;\n }\n navigator.clipboard.writeText(text).catch(() => {});\n}\n\nasync function connect(ticket) {\n if (typeof ticket !== 'string' || !TICKET_RE.test(ticket)) {\n return 'invalid';\n }\n if (state === 'connecting' || state === 'connected' || state === 'paused') {\n return state;\n }\n await whenStarted();\n if (UI.rfb) {\n return 'connecting';\n }\n state = 'connecting';\n attemptConnected = false;\n // UI.connect reads the path setting synchronously and opens the WebSocket in RFB's constructor;\n // the in-memory setting is restored right after, so the ticket is never kept or shown.\n // Only ever this page's own origin: noVNC also reads host, port, encrypt, repeater and logging\n // from the URL, which must never send a ticketed session (and the user's keys) elsewhere.\n WebUtil.setSetting('host', '');\n WebUtil.setSetting('port', '');\n WebUtil.setSetting('encrypt', false);\n WebUtil.setSetting('repeaterID', '');\n WebUtil.setSetting('path', `${WS_PATH}?ticket=${ticket}`);\n try {\n UI.connect();\n } finally {\n WebUtil.setSetting('path', WS_PATH);\n }\n const rfb = UI.rfb;\n if (!rfb) {\n state = 'disconnected';\n requestTicket();\n return 'failed';\n }\n rfb.addEventListener('connect', onConnect);\n rfb.addEventListener('disconnect', onDisconnect);\n rfb.addEventListener('clipboard', onClipboard);\n return 'connecting';\n}\n\n/** Pastes this computer's clipboard: the sandbox's clipboard first, then the paste key itself. */\nfunction paste(text, chord) {\n const rfb = UI.rfb;\n if (!rfb || state !== 'connected' || typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return false;\n }\n rfb.clipboardPasteFrom(text);\n if (chord && chord.kind === 'mac') {\n // Cmd+V: Linux apps do not paste on Super+V, so release Super and send Shift+Insert.\n rfb.sendKey(XK.Super_L, 'MetaLeft', false);\n rfb.sendKey(XK.Super_R, 'MetaRight', false);\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', true);\n rfb.sendKey(XK.Insert, 'Insert');\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', false);\n } else if (chord && chord.kind === 'replay') {\n // Ctrl+V, Ctrl+Shift+V, Shift+Insert: the held modifiers already reached the sandbox.\n const insert = chord.key === 'Insert';\n rfb.sendKey(insert ? XK.Insert : chord.key === 'V' ? XK.V : XK.v, insert ? 'Insert' : 'KeyV');\n }\n return true;\n}\n\nfunction pause(message, label, tone) {\n state = 'paused';\n if (UI.rfb) {\n UI.rfb.disconnect();\n }\n UI.hideStatus();\n overlay.querySelector('p').textContent = String(message || '');\n overlay.querySelector('button').textContent = String(label || 'Reconnect');\n // Asleep and starting are states, not errors: announce them politely.\n overlay.firstElementChild.setAttribute('role', tone === 'neutral' ? 'status' : 'alert');\n overlay.classList.add('open');\n overlay.querySelector('button').focus();\n return true;\n}\n\nfunction resume() {\n if (state !== 'paused') {\n return false;\n }\n overlay.classList.remove('open');\n state = 'disconnected';\n attemptConnected = true; // a person asked: start the retry budget over\n requestTicket();\n return true;\n}\n\nObject.defineProperty(window, 'orcaDesktop', {\n value: Object.freeze({\n version: 1,\n state: () => state,\n /** Resolves when the page needs a ticket: now if it is not connected, else after a drop. */\n nextTicketRequest: () => new Promise((resolve) => {\n ticketWaiters.push(resolve);\n if (state === 'idle' || state === 'disconnected') {\n requestTicket();\n }\n }),\n connect,\n paste,\n pause,\n resume\n })\n});\n","orca-sandbox-grant":"#!/usr/bin/env bash\n# Mints a fresh, single-device orcad pairing offer for one org member's device and seals it to that\n# device's X25519 key, so the control plane relays only ciphertext (the VM owner's E2EE model holds:\n# every member device gets its own revocable orcad credential, nobody else can read it).\n# Env from the control plane: ORCA_GRANT_ID, ORCA_GRANT_RECIPIENT_KEY (base64 raw X25519 public\n# key), ORCA_GRANT_KIND (desktop|mobile), ORCA_PUBLIC_WSS. Prints one JSON line:\n# {\"deviceId\":\"…\",\"sealed\":{\"v\":1,\"ephemeralPublicKeyB64\":\"…\",\"nonceB64\":\"…\",\"ciphertextB64\":\"…\"}}\n# Sealing: ECDH(ephemeral, recipient) -> HKDF-SHA256(salt = eph||recipient, info\n# \"orca-cloud-grant-v1\") -> AES-256-GCM, AAD \"orca-cloud-grant-v1:\".\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nDATA=\"$HOME/.orcad-data\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\n# One mint at a time: --rotate retires unredeemed offers, so two members never share a credential.\nflock -w 30 9\n\ncase \"${ORCA_GRANT_ID:-}\" in '' | *[!A-Za-z0-9_-]*) echo 'bad grant id' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_KIND:-}\" in desktop) scope=() ;; mobile) scope=(--mobile) ;; *) echo 'bad kind' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_RECIPIENT_KEY:-}\" in '' | *[!A-Za-z0-9+/=]*) echo 'bad key' >&2; exit 2 ;; esac\ncase \"${ORCA_PUBLIC_WSS:-}\" in wss://*) ;; *) echo 'bad endpoint' >&2; exit 2 ;; esac\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\n# The workspace's project must exist on this orcad before a phone opens it: phones may not add\n# projects themselves (mobile RPC scope), and a phone may be the first client this VM ever sees.\nproject=/vercel/sandbox/project\nif [ -d \"$project\" ]; then\n kind=folder\n [ -d \"$project/.git\" ] && kind=git\n ORCA_USER_DATA_PATH=\"$DATA\" timeout 20 \"$node\" \"$cli\" repo add --path \"$project\" --kind \"$kind\" --json \\\n >/dev/null 2>&1 || true\nfi\noffer=\"$(ORCA_USER_DATA_PATH=\"$DATA\" timeout 30 \"$node\" \"$cli\" pair --json --rotate \"${scope[@]}\" \\\n --address \"$ORCA_PUBLIC_WSS\" 2>/dev/null)\" || { echo 'pair failed' >&2; exit 1; }\n# This workspace's read-snapshot signer (public half), so the paired device pins it; best effort.\nsigner=\"$(\"$node\" \"$ORCA_HOME/bin/orca-read-snapshot.cjs\" --signer-public-key 2>/dev/null || true)\"\n# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.\n# Granted devices are listed so orcad can keep owner-only features (local commands) from them.\nprintf '%s' \"$offer\" | ORCA_GRANT_ID=\"$ORCA_GRANT_ID\" ORCA_GRANT_RECIPIENT_KEY=\"$ORCA_GRANT_RECIPIENT_KEY\" ORCA_READ_SIGNER=\"$signer\" \\\n ORCA_GRANT_LEDGER=\"$STATE/grant-devices\" \"$node\" -e '\nconst crypto = require(\"node:crypto\")\nlet input = \"\"\nprocess.stdin.on(\"data\", (c) => (input += c)).on(\"end\", () => {\n const res = JSON.parse(input).result\n if (!res || res.available !== true || !res.pairingUrl || !res.deviceId) {\n console.error(\"offer unavailable\")\n process.exit(1)\n }\n if (process.env.ORCA_GRANT_LEDGER) require(\"node:fs\").appendFileSync(process.env.ORCA_GRANT_LEDGER, res.deviceId + \"\\n\", { mode: 0o600 })\n const recipient = Buffer.from(process.env.ORCA_GRANT_RECIPIENT_KEY, \"base64\")\n if (recipient.length !== 32) { console.error(\"bad key length\"); process.exit(2) }\n const recipientKey = crypto.createPublicKey({ key: { kty: \"OKP\", crv: \"X25519\", x: recipient.toString(\"base64url\") }, format: \"jwk\" })\n const eph = crypto.generateKeyPairSync(\"x25519\")\n const ephRaw = Buffer.from(eph.publicKey.export({ format: \"jwk\" }).x, \"base64url\")\n const shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: recipientKey })\n const key = Buffer.from(crypto.hkdfSync(\"sha256\", shared, Buffer.concat([ephRaw, recipient]), \"orca-cloud-grant-v1\", 32))\n const nonce = crypto.randomBytes(12)\n const cipher = crypto.createCipheriv(\"aes-256-gcm\", key, nonce)\n cipher.setAAD(Buffer.from(\"orca-cloud-grant-v1:\" + process.env.ORCA_GRANT_ID))\n const signer = /^[A-Za-z0-9+/]{43}=$/.test(process.env.ORCA_READ_SIGNER || \"\") ? process.env.ORCA_READ_SIGNER : undefined\n const body = Buffer.from(JSON.stringify({ pairingUrl: res.pairingUrl, deviceId: res.deviceId, scope: res.scope, ...(signer ? { readSignerPublicKeyB64: signer } : {}) }))\n const ct = Buffer.concat([cipher.update(body), cipher.final(), cipher.getAuthTag()])\n process.stdout.write(JSON.stringify({ deviceId: res.deviceId, sealed: { v: 1, ephemeralPublicKeyB64: ephRaw.toString(\"base64\"), nonceB64: nonce.toString(\"base64\"), ciphertextB64: ct.toString(\"base64\") } }) + \"\\n\")\n})'\n","orca-sandbox-revoke":"#!/usr/bin/env bash\n# Revokes member devices from orcad's device registry. orcad adopts on-disk removals at every auth\n# (an admin revoke, device-registry-store.ts), so this works whether or not orcad is running; the\n# control plane also runs it at boot, before orcad starts, for revokes queued while suspended.\n# Env: ORCA_REVOKE_DEVICE_IDS (comma list of orcad device ids). Prints {\"revoked\":,\"live\":}.\nset -euo pipefail\numask 077\nSTATE=\"$HOME/.orca-sandbox\"\nREGISTRY=\"$HOME/.orcad-data/orca-devices.json\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\nflock -w 30 9\n\nids=\"${ORCA_REVOKE_DEVICE_IDS:-}\"\ncase \"$ids\" in '' | *[!A-Za-z0-9,_-]*) echo 'bad device ids' >&2; exit 2 ;; esac\n# Live orcad first: `orca pair --revoke` also closes the device's open sockets now. Older orcad\n# builds lack it; the on-disk removal below still blocks their next sign-in.\nORCA_HOME=/opt/orca\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node 2>/dev/null | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\nlive=0\nif [ -n \"$node\" ] && [ -f \"$cli\" ] && [ -s \"$HOME/.orcad-data/orca-runtime.json\" ]; then\n for id in ${ids//,/ }; do\n if ORCA_USER_DATA_PATH=\"$HOME/.orcad-data\" timeout 15 \"$node\" \"$cli\" pair --revoke \"$id\" --json 2>/dev/null \\\n | jq -e '.ok == true and .result.revoked == true' >/dev/null 2>&1; then\n live=$((live + 1))\n fi\n done\nfi\nif [ ! -s \"$REGISTRY\" ]; then\n echo \"{\\\"revoked\\\":$live,\\\"live\\\":$live}\"\n exit 0\nfi\nids_json=\"$(jq -cn --arg ids \"$ids\" '$ids | split(\",\") | map(select(length > 0))')\"\nbefore=\"$(jq 'length' \"$REGISTRY\")\"\ntmp=\"$(mktemp \"$REGISTRY.revoke.XXXXXX\")\"\n# Removes the rows and any phones delegated through them (parentDeviceId), like orcad's own revoke.\njq --argjson ids \"$ids_json\" \\\n '[.[] | select((.deviceId as $d | $ids | index($d)) == null and ((.parentDeviceId // \"\") as $p | $ids | index($p)) == null)]' \\\n \"$REGISTRY\" >\"$tmp\"\nchmod 0600 \"$tmp\"\nsync \"$tmp\" 2>/dev/null || true\nmv -f \"$tmp\" \"$REGISTRY\"\nafter=\"$(jq 'length' \"$REGISTRY\")\"\necho \"{\\\"revoked\\\":$((live + before - after)),\\\"live\\\":$live}\"\n","orca-sandbox-members":"#!/usr/bin/env bash\n# Runs as root (control plane, sudo). Installs who-may-push-as-whom for `orca-git-as`:\n# /etc/orca/members/.gitconfig egress placeholder header + GitHub author identity\n# /etc/orca/members/devices.json {\"\": \"\"} (each member's paired devices)\n# Both root-only: agents never read another member's placeholder. `orca-git-identity` (root, via a\n# sudoers rule) hands an agent only the identity of the member whose device drove its turn, as orcad\n# attests it. No token lives here: the placeholder is swapped at egress, for this repository only.\n# Env: ORCA_MEMBERS_B64 = base64 JSON [{userId, name, email, authorization, deviceIds:[...]}]\n# The VM user agents run as is orcad's own user (detected). Prints {\"members\":,\"devices\":}.\nset -euo pipefail\numask 077\nDIR=/etc/orca/members\norcad_pid=\"$(pgrep -f orcad-server.js | head -n 1 || true)\"\nUSER_NAME=\"$( [ -n \"$orcad_pid\" ] && ps -o user= -p \"$orcad_pid\" | tr -d ' ' || true)\"\nUSER_NAME=\"${USER_NAME:-${ORCA_SANDBOX_USER:-${SUDO_USER:-}}}\"\ncase \"$USER_NAME\" in '' | *[!a-z0-9_-]*) echo 'bad user' >&2; exit 2 ;; esac\nmkdir -p /etc/orca\njson=\"$(printf '%s' \"${ORCA_MEMBERS_B64:-W10=}\" | base64 -d)\"\ntmp=\"$(mktemp -d /etc/orca/members.XXXXXX)\"\ncount=0\nwhile IFS= read -r row; do\n user=\"$(jq -r '.userId' <<<\"$row\")\"\n case \"$user\" in '' | *[!A-Za-z0-9_.:-]*) continue ;; esac\n file=\"$tmp/$(printf '%s' \"$user\" | tr ':' '_').gitconfig\"\n # An empty extraheader first resets the image-wide (app identity) header for this member's git.\n git config -f \"$file\" --add http.https://github.com/.extraheader ''\n git config -f \"$file\" --add http.https://github.com/.extraheader \"Authorization: $(jq -r '.authorization' <<<\"$row\")\"\n git config -f \"$file\" user.name \"$(jq -r '.name' <<<\"$row\")\"\n git config -f \"$file\" user.email \"$(jq -r '.email' <<<\"$row\")\"\n # GH-AS-MEMBER: the member's placeholder for gh (a placeholder, never a token).\n gh_token=\"$(jq -r '.ghToken // empty' <<<\"$row\")\"\n case \"$gh_token\" in orca-ph-* | orca-mph-*) git config -f \"$file\" orca.ghtoken \"$gh_token\" ;; esac\n count=$((count + 1))\ndone < <(jq -c '.[]' <<<\"$json\")\n# GIT-COAUTHOR: members whose GitHub identity can't be used right now get only a co-author line (no header,\n# no author: their commits fall back to the workspace identity, with a Co-authored-by trailer for them).\n# Env: ORCA_COAUTHORS_B64 = base64 JSON [{userId, coauthor: \"Name \", deviceIds}]\ncoauthors=\"$(printf '%s' \"${ORCA_COAUTHORS_B64:-W10=}\" | base64 -d)\"\njq -e 'type == \"array\"' <<<\"$coauthors\" >/dev/null 2>&1 || coauthors='[]'\nwhile IFS= read -r row; do\n user=\"$(jq -r '.userId' <<<\"$row\")\"\n case \"$user\" in '' | *[!A-Za-z0-9_.:-]*) continue ;; esac\n file=\"$tmp/$(printf '%s' \"$user\" | tr ':' '_').gitconfig\"\n [ -e \"$file\" ] && continue\n line=\"$(jq -r '.coauthor' <<<\"$row\")\"\n [[ \"$line\" =~ ^[^\\<\\>[:cntrl:]]{1,80}\\ \\<[0-9]{1,20}\\+[A-Za-z0-9-]{1,39}@users\\.noreply\\.github\\.com\\>$ ]] || continue\n git config -f \"$file\" orca.coauthor \"$line\"\ndone < <(jq -c '.[]' <<<\"$coauthors\")\n# A device id claimed by more than one member maps to nobody (never \"last wins\": one member's device must\n# never attest as another's). Both lists.\nDEVICES_JQ='add | [.[] | select(.userId | test(\"^[A-Za-z0-9_.:-]+$\")) | .userId as $u | (.deviceIds // [])[] | select(test(\"^[A-Za-z0-9_-]{1,128}$\")) | {key: ., value: $u}] | group_by(.key) | map(select((map(.value) | unique | length) == 1) | .[0]) | from_entries'\njq -c -s \"$DEVICES_JQ\" <(printf '%s' \"$json\") <(printf '%s' \"$coauthors\") >\"$tmp/devices.json\"\ndevices=\"$(jq 'length' \"$tmp/devices.json\")\"\n# GH-SOLO: ORCA_SOLO_MEMBER = the only person who can use this workspace (absent when shared). orca-git-identity\n# then acts as them without an attested sender, matching the control plane.\nsolo=\"${ORCA_SOLO_MEMBER:-}\"\nsolo_file=''\ncase \"$solo\" in '' | *[!A-Za-z0-9_.:-]*) solo='' ;; esac\nif [ -n \"$solo\" ]; then\n solo_file=\"$tmp/$(printf '%s' \"$solo\" | tr ':' '_').gitconfig\"\n if [ -s \"$solo_file\" ]; then printf '%s\\n' \"$solo\" >\"$tmp/solo\"; else solo=''; solo_file=''; fi\nfi\nchmod 0700 \"$tmp\" && chmod 0600 \"$tmp\"/*\nrm -rf \"$DIR.old\"\n[ -d \"$DIR\" ] && mv \"$DIR\" \"$DIR.old\"\nmv \"$tmp\" \"$DIR\"\nrm -rf \"$DIR.old\"\n# Agents may ask for their own sender's identity, and only that (the helper checks with orcad).\nrule=\"$USER_NAME ALL=(root) NOPASSWD:SETENV: /opt/orca/bin/orca-git-identity\"\nprintf '%s\\n' \"$rule\" >/etc/sudoers.d/orca-git-identity.new\nchmod 0440 /etc/sudoers.d/orca-git-identity.new\nif visudo -cf /etc/sudoers.d/orca-git-identity.new >/dev/null; then\n mv -f /etc/sudoers.d/orca-git-identity.new /etc/sudoers.d/orca-git-identity\nelse\n rm -f /etc/sudoers.d/orca-git-identity.new\n echo 'sudoers rule rejected' >&2\n exit 1\nfi\n# Pre-attestation layout (agent-readable member files) must not linger.\nuser_home=\"$(getent passwd \"$USER_NAME\" | cut -d: -f6)\"\n[ -n \"$orcad_pid\" ] && user_home=\"$(tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n 's/^HOME=//p' | head -n 1)\"\n[ -n \"$user_home\" ] && rm -rf \"$user_home/.orca-sandbox/members\"\n# GH-SOLO: in a one-person workspace a plain `git commit` (no turn at all) is theirs too: the default author is\n# the member's GitHub noreply identity. Marked, so a workspace that becomes shared goes back to Orca's.\nif [ -n \"$user_home\" ]; then\n as_user() { sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global \"$@\"; }\n solo_email=\"$( [ -n \"$solo\" ] && git config -f \"$DIR/$(printf '%s' \"$solo\" | tr ':' '_').gitconfig\" user.email 2>/dev/null || true)\"\n if [ -n \"$solo_email\" ]; then\n as_user user.name \"$(git config -f \"$DIR/$(printf '%s' \"$solo\" | tr ':' '_').gitconfig\" user.name)\"\n as_user user.email \"$solo_email\"\n as_user orca.soloauthor true\n elif [ \"$(as_user --get orca.soloauthor 2>/dev/null || true)\" = true ]; then\n as_user user.name 'Orca'\n as_user user.email 'noreply@orca.dev'\n as_user --unset orca.soloauthor || true\n fi\nfi\n# Commits outside a teammate's turn still need an author (images older than orca-sandbox-start's default).\nif [ -n \"$user_home\" ]; then\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email 'noreply@orca.dev'\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name 'Orca'\nfi\n# CREATE-GIT-ASYNC: identities are in place, so `git` stops holding commits and pushes for this boot.\nif [ -n \"$user_home\" ] && [ -d \"$user_home/.orca-sandbox\" ]; then\n sudo -u \"$USER_NAME\" sh -c 'rm -f \"$1/git-setup.pending\" \"$1/git-setup.failed\" && date +%s >\"$1/git-setup.ready\"' \\\n _ \"$user_home/.orca-sandbox\" || true\nfi\necho \"{\\\"members\\\":$count,\\\"devices\\\":$devices}\"\n","orca-sandbox-read-snapshot":"#!/usr/bin/env bash\n# Seals a read-only snapshot of this workspace (chats, agent status, git, PR) to the reader keys the\n# control plane passes, right before the drain. Only ciphertext is printed (one JSON line); see\n# orca-read-snapshot.cjs. Exit 3: orcad isn't running (nothing to read).\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nexport ORCA_USER_DATA_PATH=\"${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n[ -n \"$node\" ] || { echo 'node not found' >&2; exit 1; }\nexec timeout 35 \"$node\" \"$ORCA_HOME/bin/orca-read-snapshot.cjs\"\n","orca-read-snapshot.cjs":"#!/usr/bin/env node\n// Gathers what a sleeping workspace should still show (recent chats per agent session, agent\n// status, git status/diff summary, PR link) from the running orcad over its local socket, then seals\n// it to the reader keys the control plane passed, so only ciphertext leaves the VM.\n// Run by orca-sandbox-read-snapshot right before the drain. Env:\n// ORCA_READ_SNAPSHOT_ID rsn_<24 hex> ORCA_READ_WORKSPACE_ID sbx_<24 hex>\n// ORCA_READ_RECIPIENTS JSON [{keyId, publicKeyB64}] ORCA_READ_REASON sleep|rollover\n// ORCA_USER_DATA_PATH orcad's data dir (orca-runtime.json lives there)\n// Prints one JSON line: {v:1, snapshotId, workspaceId, nonceB64, ciphertextB64, recipients[], stats}.\n// Construction (keep in sync with src/shared/cloud-workspaces/read-snapshot.ts in the app):\n// body = AES-256-GCM(dek, nonce, JSON, AAD \"orca-cloud-read-v1::\")\n// wrapped = AES-256-GCM(HKDF-SHA256(X25519(eph, reader), eph||reader, \"orca-cloud-read-wrap-v1\"),\n// nonce_i, dek, AAD \"orca-cloud-read-wrap-v1:::\")\n'use strict'\nconst crypto = require('node:crypto')\nconst fs = require('node:fs')\nconst net = require('node:net')\nconst path = require('node:path')\n\nconst INFO = 'orca-cloud-read-v1'\nconst WRAP_INFO = 'orca-cloud-read-wrap-v1'\nconst PROJECT = '/vercel/sandbox/project'\nconst LIMITS = { sessions: 12, messagesPerSession: 60, messageChars: 4000, changes: 200, commits: 10 }\n/** Plaintext budget: sealed + base64 it stays under the control plane's 220 kB and the 256 kB stdout cap. */\nconst MAX_PLAIN_BYTES = 150_000\nconst CALL_TIMEOUT_MS = 5_000\nconst TOTAL_BUDGET_MS = 20_000\n\nfunction b64(bytes) {\n return Buffer.from(bytes).toString('base64')\n}\n\nfunction x25519PublicKey(raw) {\n return crypto.createPublicKey({ key: { kty: 'OKP', crv: 'X25519', x: Buffer.from(raw).toString('base64url') }, format: 'jwk' })\n}\n\nfunction gcmSeal(key, nonce, plain, aad) {\n const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce)\n cipher.setAAD(Buffer.from(aad))\n return Buffer.concat([cipher.update(plain), cipher.final(), cipher.getAuthTag()])\n}\n\nconst SIG_INFO = 'orca-cloud-read-sig-v1'\n\n/**\n * This VM's snapshot signing key (Ed25519), created once and kept on the VM's own disk (0600, never\n * printed). Devices pin its public half per workspace, so a snapshot the control plane forged or\n * swapped doesn't verify. Same file for the grant script, which hands the public half to pairing devices.\n */\nfunction signingKey(stateDir) {\n if (!path.isAbsolute(stateDir)) {\n throw new Error('no state dir')\n }\n const file = path.join(stateDir, 'read-signing-key.pem')\n const load = () => {\n try {\n const privateKey = crypto.createPrivateKey(fs.readFileSync(file, 'utf8'))\n return privateKey.asymmetricKeyType === 'ed25519' ? privateKey : null\n } catch {\n return null\n }\n }\n let privateKey = load()\n if (!privateKey) {\n fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 })\n // Written whole to a temp file, then linked into place: atomic, and a concurrent first run\n // (grant + capture) keeps whichever key landed first. A broken file is replaced (devices that\n // pinned the old signer then see \"signer changed\" until they trust the new one).\n const temp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}`\n fs.writeFileSync(temp, crypto.generateKeyPairSync('ed25519').privateKey.export({ format: 'pem', type: 'pkcs8' }), { mode: 0o600 })\n try {\n fs.linkSync(temp, file)\n } catch {\n if (!load()) {\n fs.renameSync(temp, file)\n }\n } finally {\n fs.rmSync(temp, { force: true })\n }\n privateKey = load()\n if (!privateKey) {\n throw new Error('signing key unavailable')\n }\n }\n const publicKeyB64 = Buffer.from(crypto.createPublicKey(privateKey).export({ format: 'jwk' }).x, 'base64url').toString('base64')\n return { privateKey, publicKeyB64 }\n}\n\n/** Signs the sealed body: \"orca-cloud-read-sig-v1::::\" || ciphertext bytes. */\nfunction sign(out, key) {\n const message = Buffer.concat([\n Buffer.from(`${SIG_INFO}:${out.workspaceId}:${out.snapshotId}:${out.nonceB64}:`),\n Buffer.from(out.ciphertextB64, 'base64')\n ])\n return { publicKeyB64: key.publicKeyB64, signatureB64: crypto.sign(null, message, key.privateKey).toString('base64') }\n}\n\n/** Seals `payload` (an object) to every recipient; a malformed key is skipped, not fatal. */\nfunction seal(payload, recipients, workspaceId, snapshotId) {\n const scope = `${workspaceId}:${snapshotId}`\n const dek = crypto.randomBytes(32)\n const nonce = crypto.randomBytes(12)\n const ciphertext = gcmSeal(dek, nonce, Buffer.from(JSON.stringify(payload)), `${INFO}:${scope}`)\n const sealedTo = []\n for (const recipient of recipients) {\n const reader = Buffer.from(String(recipient.publicKeyB64 || ''), 'base64')\n if (reader.length !== 32 || !/^rk_[0-9a-f]{24}$/.test(String(recipient.keyId || ''))) {\n continue\n }\n let shared\n const eph = crypto.generateKeyPairSync('x25519')\n try {\n shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: x25519PublicKey(reader) })\n } catch {\n continue\n }\n if (shared.every((byte) => byte === 0)) {\n continue\n }\n const ephRaw = Buffer.from(eph.publicKey.export({ format: 'jwk' }).x, 'base64url')\n const kek = Buffer.from(crypto.hkdfSync('sha256', shared, Buffer.concat([ephRaw, reader]), WRAP_INFO, 32))\n const wrapNonce = crypto.randomBytes(12)\n const wrapped = gcmSeal(kek, wrapNonce, dek, `${WRAP_INFO}:${scope}:${recipient.keyId}`)\n sealedTo.push({ keyId: recipient.keyId, ephemeralPublicKeyB64: b64(ephRaw), nonceB64: b64(wrapNonce), wrappedKeyB64: b64(wrapped) })\n }\n dek.fill(0)\n return { v: 1, snapshotId, workspaceId, nonceB64: b64(nonce), ciphertextB64: b64(ciphertext), recipients: sealedTo }\n}\n\n// --- gathering -------------------------------------------------------------------------------\n\n/** One request per connection, like the CLI. A streaming method resolves on its first frame. */\nfunction rpc(metadata, method, params, timeoutMs = CALL_TIMEOUT_MS) {\n return new Promise((resolve) => {\n const transport = (metadata.transports || [metadata.transport]).find((t) => t && (t.kind === 'unix' || t.kind === 'named-pipe'))\n if (!transport) {\n resolve(null)\n return\n }\n const socket = net.createConnection(transport.endpoint)\n const id = crypto.randomUUID()\n let buffer = ''\n let done = false\n const finish = (value) => {\n if (!done) {\n done = true\n clearTimeout(timer)\n socket.destroy()\n resolve(value)\n }\n }\n const timer = setTimeout(() => finish(null), timeoutMs)\n socket.setEncoding('utf8')\n socket.on('error', () => finish(null))\n socket.on('close', () => finish(null))\n socket.on('connect', () => socket.write(`${JSON.stringify({ id, authToken: metadata.authToken, method, params })}\\n`))\n socket.on('data', (chunk) => {\n buffer += chunk\n let newline\n while ((newline = buffer.indexOf('\\n')) !== -1) {\n const line = buffer.slice(0, newline)\n buffer = buffer.slice(newline + 1)\n let frame\n try {\n frame = JSON.parse(line)\n } catch {\n continue\n }\n if (!frame || frame.id !== id) {\n continue\n }\n finish(frame.ok === true ? frame.result : null)\n return\n }\n })\n })\n}\n\nconst isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v)\nconst str = (v, max) => (typeof v === 'string' ? v.slice(0, max) : null)\nconst num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null)\n\nfunction messagesOf(history) {\n const items = isObj(history) && isObj(history.page) && Array.isArray(history.page.items) ? history.page.items : []\n const out = []\n for (const item of items) {\n const body = isObj(item) && isObj(item.body) ? item.body : null\n if (!body || body.kind !== 'message' || !Array.isArray(body.blocks)) {\n continue\n }\n const role = body.role\n if (role !== 'user' && role !== 'assistant' && role !== 'system') {\n continue\n }\n const text = body.blocks\n .filter((b) => isObj(b) && b.type === 'text' && typeof b.text === 'string')\n .map((b) => b.text)\n .join('\\n')\n .trim()\n if (text) {\n out.push({ itemId: String(item.itemId).slice(0, 200), role, text: text.slice(0, LIMITS.messageChars), at: num(item.observedAt) ?? 0 })\n }\n }\n return { messages: out, hasOlder: isObj(history) && isObj(history.page) && history.page.hasOlder === true }\n}\n\nfunction gitOf(status, log) {\n if (!isObj(status) && !isObj(log)) {\n return null\n }\n const entries = isObj(status) && Array.isArray(status.entries) ? status.entries.filter(isObj) : []\n let added = 0\n let removed = 0\n let counted = false\n const changes = entries.slice(0, LIMITS.changes).map((e) => {\n const a = num(e.added)\n const r = num(e.removed)\n if (a !== null || r !== null) {\n counted = true\n }\n return { path: String(e.path).slice(0, 1024), status: str(e.status, 20) || 'modified', area: str(e.area, 20) || 'unstaged', added: a, removed: r }\n })\n for (const e of entries) {\n added += num(e.added) || 0\n removed += num(e.removed) || 0\n }\n const items = isObj(log) && Array.isArray(log.items) ? log.items.filter(isObj) : []\n return {\n branch: isObj(status) && typeof status.branch === 'string' ? status.branch.replace(/^refs\\/heads\\//, '') : null,\n head: isObj(status) ? str(status.head, 64) : null,\n changes,\n changeCount: entries.length,\n added: counted ? added : null,\n removed: counted ? removed : null,\n commits: items.slice(0, LIMITS.commits).map((c) => ({\n id: String(c.id).slice(0, 64),\n subject: String(c.subject ?? '').slice(0, 300),\n author: str(c.author, 120),\n at: num(c.timestamp)\n }))\n }\n}\n\nfunction prOf(linked) {\n if (!isObj(linked) || num(linked.number) === null || typeof linked.url !== 'string' || !linked.url.startsWith('https://')) {\n return null\n }\n return {\n number: linked.number,\n title: String(linked.title ?? '').slice(0, 300),\n state: str(linked.state, 20) || 'open',\n url: linked.url.slice(0, 500),\n checksStatus: str(linked.checksStatus, 20),\n checksSummary: str(linked.checksSummary, 200)\n }\n}\n\nconst STATUSES = new Set(['working', 'attention', 'idle'])\nconst PANE_PREFIX = 'structured-agent-session-'\n\n/**\n * Chats as orcad stores them (agent-session-journal.db, read-only): every session's provider, name\n * and last turn, open tabs first. The local socket can't stream agentSession.subscribeStatus, and\n * worktree.ps lists only agents that are live right now, so this is the complete list.\n */\nfunction storedSessions(dataDir) {\n let db\n try {\n const { DatabaseSync } = require('node:sqlite')\n db = new DatabaseSync(path.join(dataDir, 'agent-session-journal.db'), { readOnly: true })\n const open = new Set(db.prepare('SELECT session_id FROM agent_session_tabs').all().map((r) => r.session_id))\n const out = []\n for (const row of db.prepare('SELECT session_id, record_json FROM agent_session_records').all()) {\n let record\n try {\n record = JSON.parse(row.record_json)\n } catch {\n continue\n }\n const last = isObj(record.lastTurn) ? record.lastTurn : {}\n out.push({\n sessionId: row.session_id,\n agent: str(record.provider, 40),\n title: str(record.conversationName, 200) || str(last.prompt, 200),\n status: last.state === 'running' || last.state === 'submitted' ? 'working' : last.state === 'settled' ? 'idle' : 'unknown',\n turnOutcome: str(last.outcome, 40),\n updatedAt: num(record.updatedAt),\n open: open.has(row.session_id),\n lastPrompt: str(last.prompt, LIMITS.messageChars),\n lastReply: str(last.reply, LIMITS.messageChars),\n lastAt: num(last.at),\n // \"::\": which checkout this chat works in.\n worktreePath: isObj(record.location) && typeof record.location.workspaceId === 'string' ? record.location.workspaceId.split('::').pop() : null\n })\n }\n return out\n } catch {\n return []\n } finally {\n try {\n db && db.close()\n } catch {}\n }\n}\n\n/** Live agent rows from worktree.ps, keyed by session id (their status wins over the stored one). */\nfunction liveAgents(worktrees) {\n const out = new Map()\n for (const w of worktrees) {\n for (const a of Array.isArray(w.agents) ? w.agents.filter(isObj) : []) {\n const tab = typeof a.paneKey === 'string' ? a.paneKey.split(':')[0] : ''\n if (!tab.startsWith(PANE_PREFIX)) {\n continue\n }\n const state = a.mainAgent && typeof a.mainAgent.state === 'string' ? a.mainAgent.state : a.state\n out.set(tab.slice(PANE_PREFIX.length), {\n agent: str(a.agentType, 40),\n title: str(a.conversationName, 200) || str(a.taskTitle, 200) || str(a.displayName, 200),\n status: state === 'working' ? 'working' : state === 'blocked' || state === 'waiting' || state === 'attention' ? 'attention' : 'idle',\n updatedAt: num(a.updatedAt)\n })\n }\n }\n return out\n}\n\n/**\n * The checkout this workspace is about: the one its newest chat works in, else the most recently\n * active one (a workspace on its own branch is a separate worktree, not the base clone at\n * /vercel/sandbox/project), else the base clone.\n */\nfunction workspaceCheckout(worktrees, sessions) {\n const byPath = new Map(worktrees.filter((w) => typeof w.path === 'string').map((w) => [w.path, w]))\n const newest = sessions\n .filter((s) => s.worktreePath && byPath.has(s.worktreePath))\n .sort((a, b) => (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0))[0]\n if (newest) {\n return byPath.get(newest.worktreePath)\n }\n const activity = (w) => Math.max(num(w.lastActivityAt) || 0, num(w.sortOrder) || 0)\n const ranked = [...byPath.values()].sort(\n (a, b) => activity(b) - activity(a) || Number(a.isMainWorktree === true) - Number(b.isMainWorktree === true)\n )\n return ranked[0] || null\n}\n\n/** `call(method, params)` -> result | null. Never throws: a missing piece is left out. */\nasync function gather(call, { workspaceId, snapshotId, reason, now, deadline, listSessions = () => [] }) {\n const timeLeft = () => deadline - Date.now()\n const ps = await call('worktree.ps', { limit: 20 })\n const worktrees = isObj(ps) && Array.isArray(ps.worktrees) ? ps.worktrees.filter(isObj) : []\n const stored = listSessions()\n const project = workspaceCheckout(worktrees, stored)\n const selector = project && typeof project.path === 'string' ? `path:${project.path}` : `path:${PROJECT}`\n const [status, log] = await Promise.all([\n call('git.status', { worktree: selector, includeLineStats: true }),\n call('git.history', { worktree: selector, limit: LIMITS.commits })\n ])\n const live = liveAgents(worktrees)\n const byId = new Map()\n for (const s of stored) {\n byId.set(s.sessionId, s)\n }\n for (const [sessionId, a] of live) {\n byId.set(sessionId, { ...(byId.get(sessionId) || { sessionId, open: true }), ...Object.fromEntries(Object.entries(a).filter(([, v]) => v !== null)) })\n }\n // Open chats first, then newest activity.\n const picked = [...byId.values()]\n .filter((s) => typeof s.sessionId === 'string')\n .sort((a, b) => Number(Boolean(b.open)) - Number(Boolean(a.open)) || (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0))\n .slice(0, LIMITS.sessions)\n const sessions = []\n for (const s of picked) {\n const history = timeLeft() > 1_000 ? await call('agentSession.history', { sessionId: s.sessionId, direction: 'tail', limit: LIMITS.messagesPerSession }) : null\n let { messages, hasOlder } = messagesOf(history)\n if (messages.length === 0) {\n // No readable history (or out of time): the stored last turn still says what happened.\n const at = s.lastAt || s.updatedAt || 0\n messages = [\n ...(s.lastPrompt ? [{ itemId: `${s.sessionId}:last-prompt`, role: 'user', text: s.lastPrompt, at }] : []),\n ...(s.lastReply ? [{ itemId: `${s.sessionId}:last-reply`, role: 'assistant', text: s.lastReply, at }] : [])\n ]\n hasOlder = hasOlder || messages.length > 0\n }\n sessions.push({\n sessionId: s.sessionId.slice(0, 200),\n agent: s.agent || null,\n title: s.title || null,\n status: STATUSES.has(s.status) ? s.status : 'unknown',\n turnOutcome: s.turnOutcome || null,\n updatedAt: num(s.updatedAt),\n messages: messages.slice(-LIMITS.messagesPerSession),\n truncated: hasOlder || messages.length > LIMITS.messagesPerSession\n })\n }\n return {\n v: 1,\n workspaceId,\n snapshotId,\n capturedAt: now,\n reason,\n git: gitOf(status, log),\n pr: prOf(project && project.linkedPR),\n sessions\n }\n}\n\n/** Cuts the oldest messages (then long texts, then sessions) until the JSON fits the budget. */\nfunction fitToBudget(payload, maxBytes = MAX_PLAIN_BYTES) {\n const size = () => Buffer.byteLength(JSON.stringify(payload))\n let guard = 0\n while (size() > maxBytes && guard++ < 10_000) {\n const longest = payload.sessions.reduce((best, s) => (!best || s.messages.length > best.messages.length ? s : best), null)\n if (longest && longest.messages.length > 4) {\n longest.messages.shift()\n longest.truncated = true\n continue\n }\n const longText = payload.sessions.flatMap((s) => s.messages).find((m) => m.text.length > 500)\n if (longText) {\n longText.text = `${longText.text.slice(0, 500)}…`\n continue\n }\n if (payload.git && payload.git.changes.length > 20) {\n payload.git.changes = payload.git.changes.slice(0, 20)\n continue\n }\n if (payload.sessions.length > 1) {\n payload.sessions.pop()\n continue\n }\n payload.sessions = []\n break\n }\n return payload\n}\n\n// Fails closed without HOME (signingKey refuses a relative path).\nconst stateDir = process.env.HOME ? path.join(process.env.HOME, '.orca-sandbox') : ''\n\nasync function main() {\n const started = Date.now()\n const env = process.env\n if (process.argv[2] === '--signer-public-key') {\n // For orca-sandbox-grant: pairing devices learn (and pin) this workspace's signer.\n process.stdout.write(`${signingKey(stateDir).publicKeyB64}\\n`)\n return\n }\n const snapshotId = env.ORCA_READ_SNAPSHOT_ID || ''\n const workspaceId = env.ORCA_READ_WORKSPACE_ID || ''\n if (!/^rsn_[0-9a-f]{24}$/.test(snapshotId) || !/^sbx_[0-9a-f]{24}$/.test(workspaceId)) {\n process.stderr.write('bad ids\\n')\n process.exit(2)\n }\n let recipients\n try {\n recipients = JSON.parse(env.ORCA_READ_RECIPIENTS || '[]')\n } catch {\n recipients = null\n }\n if (!Array.isArray(recipients) || recipients.length === 0) {\n process.stderr.write('no recipients\\n')\n process.exit(2)\n }\n const dataDir = env.ORCA_USER_DATA_PATH || path.join(env.HOME || '', '.orcad-data')\n let metadata\n try {\n metadata = JSON.parse(fs.readFileSync(path.join(dataDir, 'orca-runtime.json'), 'utf8'))\n } catch {\n metadata = null\n }\n if (!metadata || !metadata.authToken) {\n process.stderr.write('orcad not running\\n')\n process.exit(3)\n }\n const deadline = started + TOTAL_BUDGET_MS\n const call = (method, params) => rpc(metadata, method, params, Math.max(250, Math.min(CALL_TIMEOUT_MS, deadline - Date.now())))\n const payload = fitToBudget(\n await gather(call, { workspaceId, snapshotId, reason: (env.ORCA_READ_REASON || 'sleep').slice(0, 20), now: Date.now(), deadline, listSessions: () => storedSessions(dataDir) })\n )\n const out = seal(payload, recipients, workspaceId, snapshotId)\n out.signature = sign(out, signingKey(stateDir))\n // Timing only: counts and sizes would describe the plaintext to the control plane's logs.\n out.stats = { collectMs: Date.now() - started }\n process.stdout.write(`${JSON.stringify(out)}\\n`)\n}\n\nmodule.exports = { workspaceCheckout, seal, sign, signingKey, gather, fitToBudget, messagesOf, gitOf, prOf, rpc, storedSessions, liveAgents }\n\nif (require.main === module) {\n // A fixed message: an error text could carry workspace content into the control plane's logs.\n main().catch(() => {\n process.stderr.write('read snapshot failed\\n')\n process.exit(1)\n })\n}\n","orca-git-as":"#!/usr/bin/env bash\n# Runs git as the teammate whose message started this agent's turn: their GitHub identity for\n# pushes/PRs (this repository only) and their commit author.\n# orca-git-as e.g. orca-git-as push origin HEAD\n# orca-git-as --as refuses unless that member really sent the message\n# Orca attests the sender from the paired device that sent the message, never from arguments or\n# message text. Without an attested sender (not run from an agent, or the owner's local session) it\n# runs plain git with the workspace identity.\nset -euo pipefail\nexpect=''\nif [ \"${1:-}\" = '--as' ]; then\n expect=\"${2:-}\"\n shift 2 || { echo 'usage: orca-git-as [--as ] ' >&2; exit 2; }\n case \"$expect\" in '' | *[!A-Za-z0-9_.:-]*) echo 'orca-git-as: bad member id' >&2; exit 2 ;; esac\nfi\nset +e\nfile=\"$(ORCA_GIT_AS=\"$expect\" sudo -n --preserve-env=ORCA_GIT_AS,ORCA_TERMINAL_HANDLE,ORCA_PANE_KEY,ORCA_AGENT_LAUNCH_TOKEN,ORCA_AGENT_SESSION_ID \\\n /opt/orca/bin/orca-git-identity)\"\nstatus=$?\nset -e\ncase \"$status\" in\n 0)\n trap 'rm -f \"$file\"' EXIT\n # GIT-COAUTHOR: a member whose GitHub identity can't be used right now: the workspace identity commits, with\n # them as co-author (the trailer goes right after the `commit` subcommand). Never for any other command.\n coauthor=\"$(git config -f \"$file\" orca.coauthor 2>/dev/null || true)\"\n if [ -n \"$coauthor\" ] && [ -z \"$(git config -f \"$file\" user.email 2>/dev/null || true)\" ]; then\n if [ -n \"$expect\" ]; then\n echo \"orca-git-as: $expect's GitHub connection can't be used right now; refusing to act as them. Reconnect GitHub in Settings → Account.\" >&2\n exit 4\n fi\n echo 'orca-git-as: no teammate identity for this turn; using the workspace identity' >&2\n args=()\n skip=0\n placed=0\n for arg in \"$@\"; do\n args+=(\"$arg\")\n [ \"$placed\" = 0 ] || continue\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n -*) ;;\n commit) args+=(--trailer \"Co-authored-by: $coauthor\"); placed=1 ;;\n *) placed=1 ;;\n esac\n done\n git -c \"include.path=$file\" \"${args[@]}\"\n exit\n fi\n git -c \"include.path=$file\" \"$@\"\n ;;\n 3)\n echo 'orca-git-as: no teammate identity for this turn; using the workspace identity' >&2\n exec git \"$@\"\n ;;\n *) exit 4 ;;\nesac\n","orca-git-identity":"#!/usr/bin/env bash\n# Root helper behind `orca-git-as` (sudoers: the VM user may run only this). Asks orcad, as the\n# calling agent, which paired device sent the message that started the agent's latest turn\n# (`orca sender`: orcad identifies the agent from its launch evidence, never from arguments), maps\n# that device to a workspace member, and prints that member's git config file for the caller to\n# include. Optional ORCA_GIT_AS: the member the agent expects; any other answer is refused.\n# Exit codes: 0 printed a config path; 3 no member identity (use the workspace identity); 4 refused.\nset -euo pipefail\nDIR=/etc/orca/members\ncaller=\"${SUDO_USER:-}\"\ncase \"$caller\" in '' | root | *[!a-z0-9_-]*) echo 'orca-git-identity: run through orca-git-as' >&2; exit 4 ;; esac\n# Hands the caller a one-shot copy of a member's git config (owned by them, removed by orca-git-as).\nemit() {\n local file\n file=\"$DIR/$(printf '%s' \"$1\" | tr ':' '_').gitconfig\"\n [ -s \"$file\" ] || exit 3\n out=\"$(sudo -u \"$caller\" mktemp)\"\n cat \"$file\" >\"$out\"\n echo \"$out\"\n exit 0\n}\n# GH-SOLO: a workspace only one person can use (the control plane's rule, member-git.ts pickActing) acts as that\n# person whoever typed: a TUI typed into directly has no attested sender. The control plane writes `solo` only\n# while that holds, and removes it before any other member's device is paired (grants.ts).\nif [ -s \"$DIR/solo\" ]; then\n solo=\"$(cat \"$DIR/solo\")\"\n case \"$solo\" in '' | *[!A-Za-z0-9_.:-]*) exit 3 ;; esac\n if [ -n \"${ORCA_GIT_AS:-}\" ] && [ \"$ORCA_GIT_AS\" != \"$solo\" ]; then\n echo \"orca-git-as: only $solo uses this workspace, not $ORCA_GIT_AS; refusing to push as someone else.\" >&2\n exit 4\n fi\n emit \"$solo\"\nfi\n# orcad's own data dir and HOME (the agent's user may not use its passwd home, e.g. HOME=/vercel).\norcad_pid=\"$(pgrep -u \"$caller\" -f orcad-server.js | head -n 1 || true)\"\n[ -n \"$orcad_pid\" ] || exit 3\norcad_env() { tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n \"s/^$1=//p\" | head -n 1; }\nhome=\"$(orcad_env HOME)\"\ndata=\"$(orcad_env ORCA_USER_DATA)\"\ndata=\"${data:-$home/.orcad-data}\"\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\ncli=/opt/orca/runtime/orcad/out/cli/index.js\n# Only the evidence variables orcad needs reach the query, which runs as the caller, not root.\nanswer=\"$(sudo -u \"$caller\" env -i HOME=\"$home\" PATH=/usr/bin:/bin ORCA_USER_DATA_PATH=\"$data\" \\\n ${ORCA_TERMINAL_HANDLE:+ORCA_TERMINAL_HANDLE=\"$ORCA_TERMINAL_HANDLE\"} \\\n ${ORCA_PANE_KEY:+ORCA_PANE_KEY=\"$ORCA_PANE_KEY\"} \\\n ${ORCA_AGENT_LAUNCH_TOKEN:+ORCA_AGENT_LAUNCH_TOKEN=\"$ORCA_AGENT_LAUNCH_TOKEN\"} \\\n ${ORCA_AGENT_SESSION_ID:+ORCA_AGENT_SESSION_ID=\"$ORCA_AGENT_SESSION_ID\"} \\\n timeout 15 \"$node\" \"$cli\" sender --json 2>/dev/null || true)\"\ndevice=\"$(jq -r '.result.sender.deviceId // empty' <<<\"$answer\" 2>/dev/null || true)\"\nif [ -z \"$device\" ] || [ ! -s \"$DIR/devices.json\" ]; then\n if [ -n \"${ORCA_GIT_AS:-}\" ]; then\n echo \"orca-git-as: Orca cannot confirm that $ORCA_GIT_AS sent this agent's latest message; refusing to push as them.\" >&2\n exit 4\n fi\n exit 3\nfi\nmember=\"$(jq -r --arg d \"$device\" '.[$d] // empty' \"$DIR/devices.json\")\"\nif [ -z \"$member\" ]; then\n [ -n \"${ORCA_GIT_AS:-}\" ] && { echo \"orca-git-as: the sender's device is not linked to a workspace member; refusing.\" >&2; exit 4; }\n exit 3\nfi\nif [ -n \"${ORCA_GIT_AS:-}\" ] && [ \"$ORCA_GIT_AS\" != \"$member\" ]; then\n echo \"orca-git-as: this agent's latest message came from $member, not $ORCA_GIT_AS; refusing to push as someone else.\" >&2\n exit 4\nfi\nemit \"$member\"\n","orcad-boot":"#!/usr/bin/env node\n// Starts orcad from a V8 code cache taken after a full startup, so a boot skips compiling the\n// functions startup runs. NODE_COMPILE_CACHE only stores what V8 compiles before the bundle runs\n// (about 5 of its 15 MB); every other function compiled lazily on every boot (~300 ms of wake).\n// orcad-boot --code-cache [--write-code-cache] [orcad args...]\n// orcad sees the argv `node [orcad args...]`, as if started directly.\n// --write-code-cache (the image's smoke run) writes the cache when orcad exits. The cache is used\n// only when its header matches this bundle's bytes and this Node; otherwise orcad loads exactly as\n// before (plain require, which NODE_COMPILE_CACHE still serves). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst fs = process.getBuiltinModule('node:fs')\nconst path = process.getBuiltinModule('node:path')\nconst vm = process.getBuiltinModule('node:vm')\nconst zlib = process.getBuiltinModule('node:zlib')\nconst { Module, createRequire } = process.getBuiltinModule('node:module')\n\nconst MAGIC = 'orcad-code-cache-v1'\n\nconst args = process.argv.slice(2)\nlet cacheFile = null\nlet writeCache = false\nwhile (args[0] === '--code-cache' || args[0] === '--write-code-cache') {\n if (args[0] === '--code-cache') {\n cacheFile = args[1]\n args.splice(0, 2)\n } else {\n writeCache = true\n args.shift()\n }\n}\nconst entry = args.shift()\nif (!entry || !cacheFile) {\n console.error('usage: orcad-boot --code-cache [--write-code-cache] [args...]')\n process.exit(2)\n}\n// As for `node `: argv[1] is the resolved path, __filename the real one.\nprocess.argv = [process.argv[0], path.resolve(entry), ...args]\nlet file = process.argv[1]\ntry {\n file = fs.realpathSync(file)\n} catch {\n // A missing bundle fails in require below, as it would under plain node.\n}\n\n// One line of identity: a cache from another bundle or Node must never run (V8 only checks length).\nfunction cacheHeader(bytes) {\n return `${MAGIC} ${process.version} ${process.arch} ${bytes.length} ${zlib.crc32(bytes)}\\n`\n}\n\nfunction readCache(header) {\n let data\n try {\n data = fs.readFileSync(cacheFile)\n } catch {\n return null\n }\n const headerLength = Buffer.byteLength(header)\n if (data.length <= headerLength || data.toString('latin1', 0, headerLength) !== header) {\n console.error('orcad-boot: code cache is for another orcad build; loading without it')\n return null\n }\n return data.subarray(headerLength)\n}\n\nfunction runCompiled(header, source, cachedData) {\n // A vm.Script can serialize what startup compiled; the CommonJS loader cannot. Same wrapper,\n // filename and require as the loader, and import() resolves from the bundle like it does there.\n const options = {\n filename: file,\n cachedData: cachedData ?? undefined,\n importModuleDynamically: vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER\n }\n // Node flags the loader option experimental once, on the first import() through it. Spend that\n // one-time warning here, unprinted, so orcad's stderr stays as it was.\n const emitWarning = process.emitWarning\n process.emitWarning = (warning, ...rest) => {\n if (!String(warning?.message ?? warning).includes('USE_MAIN_CONTEXT_DEFAULT_LOADER')) {\n emitWarning.call(process, warning, ...rest)\n }\n }\n let script\n try {\n new vm.Script('import(\"node:path\")', {\n filename: file,\n importModuleDynamically: options.importModuleDynamically\n })\n .runInThisContext()\n .catch(() => {})\n script = new vm.Script(Module.wrap(source), options)\n } finally {\n process.emitWarning = emitWarning\n }\n if (cachedData && script.cachedDataRejected) {\n console.error('orcad-boot: V8 rejected the code cache (other V8 flags?); compiled without it')\n }\n if (writeCache) {\n process.on('exit', () => {\n try {\n const data = script.createCachedData()\n const temporary = `${cacheFile}.${process.pid}.tmp`\n fs.writeFileSync(temporary, Buffer.concat([Buffer.from(header, 'latin1'), data]))\n fs.renameSync(temporary, cacheFile)\n console.error(`orcad-boot: wrote ${data.length} bytes of code cache`)\n } catch (error) {\n console.error(`orcad-boot: could not write the code cache: ${error.message}`)\n }\n })\n }\n const module = new Module(file, null)\n module.filename = file\n module.paths = Module._nodeModulePaths(path.dirname(file))\n const compiled = script.runInThisContext()\n compiled.call(module.exports, module.exports, createRequire(file), module, file, path.dirname(file))\n}\n\n// Locals, so neither the bundle bytes nor the cache outlive the compile.\nfunction boot() {\n // Older Node (no crc32 or main-context import()) loads as before.\n if (typeof zlib.crc32 === 'function' && vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER) {\n let bytes = null\n try {\n bytes = fs.readFileSync(file)\n } catch {\n // Missing or unreadable: require reports it as plain node would.\n }\n if (bytes) {\n const header = cacheHeader(bytes)\n const cachedData = readCache(header)\n if (cachedData || writeCache) {\n runCompiled(header, bytes.toString('utf8'), cachedData)\n return\n }\n }\n }\n createRequire(file)(file)\n}\n\nboot()\n","git":"#!/usr/bin/env bash\n# git for agents in Orca Cloud workspaces (first on orcad's PATH). Commands that author or publish\n# work run as the teammate whose message started this agent's turn (orca-git-as: orcad attests the\n# sender's paired device; root-only member identities). Everything else is plain git, untouched.\nreal=\"${ORCA_REAL_GIT:-/usr/bin/git}\"\nsub=''\nskip=0\nfor arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n -*) ;;\n *) sub=\"$arg\"; break ;;\n esac\ndone\n# CREATE-GIT-ASYNC: a new workspace answers before teammates' GitHub identities are installed. Until\n# they are (orca-sandbox-members writes git-setup.ready), commits and pushes wait up to 15 s rather\n# than go out under the workspace identity; a failed or stalled setup stops them with what to do.\n# Read-only git and fetches never wait (they use the workspace's own credentials, set before ready).\nhold_for_member_setup() {\n local state=\"${HOME:-/nonexistent}/.orca-sandbox\" ticks=0 since\n # A failed install on any boot (create or a later restart) refuses even with nothing pending.\n [ -f \"$state/git-setup.pending\" ] || [ -f \"$state/git-setup.failed\" ] || return 0\n since=\"$(cat \"$state/git-setup.pending\" 2>/dev/null || echo 0)\"\n case \"$since\" in '' | *[!0-9]*) since=0 ;; esac\n while [ -f \"$state/git-setup.pending\" ] && [ ! -f \"$state/git-setup.ready\" ] && [ ! -f \"$state/git-setup.failed\" ]; do\n # 15 s per command; a mark older than 2 min is a setup that died, not one still running.\n if [ \"$ticks\" -ge \"${ORCA_GIT_SETUP_WAIT_TICKS:-150}\" ] || [ $(($(date +%s) - since)) -gt 120 ]; then\n break\n fi\n sleep 0.1\n ticks=$((ticks + 1))\n done\n if [ -f \"$state/git-setup.ready\" ] || { [ ! -f \"$state/git-setup.pending\" ] && [ ! -f \"$state/git-setup.failed\" ]; }; then\n return 0\n fi\n if [ -f \"$state/git-setup.failed\" ]; then\n printf '%s\\n' \"orca: Orca couldn't set up your GitHub identity in this sandbox, so it stopped \\`git $sub\\` rather than use the wrong identity. Restart this workspace (right-click it in the sidebar > Restart), then try again.\" >&2\n else\n printf '%s\\n' \"orca: Orca is still setting up your GitHub identity in this sandbox, so it stopped \\`git $sub\\` rather than use the wrong identity. Try again in a few seconds. If this keeps happening, restart this workspace (right-click it in the sidebar > Restart).\" >&2\n fi\n exit 1\n}\n# A commit under the workspace identity (Orca ) says once per session how to use your own\n# (design-squad). /dev/shm is per boot: a wake or restart says it again.\nnudge_once() {\n [ \"$sub\" = commit ] || return 0\n local mark=\"${ORCA_GIT_NUDGE_DIR:-/dev/shm}/orca-git-nudge-$(id -u)\"\n [ -e \"$mark\" ] && return 0\n : >\"$mark\" 2>/dev/null || return 0\n printf '%s\\n' \"orca: This commit is authored as Orca . Connect GitHub in Settings → Account to commit as yourself.\" >&2\n}\n# PUSH-RAW-PROMPT: a push, pull or fetch to github.com that no credential covers (neither the person's\n# connected GitHub nor the App installation) must never fall through to git's own \"Username for\n# 'https://github.com':\" prompt. Prompts are off for that remote, and git's auth failure becomes one\n# plain line saying what to do.\ngithub_slug=''\ngithub_remote_slug() {\n local arg skip=0 seen=0 remote='' url\n for arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n if [ \"$seen\" = 0 ]; then\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n \"$sub\") seen=1 ;;\n esac\n continue\n fi\n case \"$arg\" in\n --repo=*) remote=\"${arg#--repo=}\"; break ;;\n -o | --push-option | --receive-pack | --upload-pack | --exec | --depth | --deepen | --shallow-since | --shallow-exclude | --refmap | --recurse-submodules-default | -j | --jobs) skip=1 ;;\n -*) ;;\n *) remote=\"$arg\"; break ;;\n esac\n done\n [ -n \"$remote\" ] || remote=\"$(\"$real\" config --get \"branch.$(\"$real\" symbolic-ref --short -q HEAD 2>/dev/null).remote\" 2>/dev/null || true)\"\n [ -n \"$remote\" ] || remote=origin\n case \"$remote\" in\n *://*) url=\"$remote\" ;;\n *) url=\"$(\"$real\" remote get-url \"$remote\" 2>/dev/null || printf '%s' \"$remote\")\" ;;\n esac\n case \"$url\" in\n https://github.com/* | https://*@github.com/*) url=\"${url#*github.com/}\" ;;\n *) return 0 ;;\n esac\n url=\"${url%.git}\"\n url=\"${url%/}\"\n case \"$url\" in */*/*) url=\"${url%%/*}/$(printf '%s' \"${url#*/}\" | cut -d/ -f1)\" ;; esac\n case \"$url\" in [A-Za-z0-9_.-]*/[A-Za-z0-9_.-]*) github_slug=\"$url\" ;; esac\n}\nno_access_line() {\n local owner=\"${github_slug%%/*}\" verb='push to'\n [ \"$sub\" = push ] || verb='read'\n printf '%s\\n' \"orca: Orca Cloud can't $verb $github_slug. Install the Orca GitHub App on $owner, or connect GitHub in Settings → Account.\" >&2\n}\n# GitHub's \"not found\" is a typo'd name or a private repo it won't confirm: say which half fits whom.\nnot_found_line() {\n printf '%s\\n' \"orca: Orca Cloud can't find $github_slug. Check the name, or install the Orca GitHub App on ${github_slug%%/*} if it's private.\" >&2\n}\n# PUSH-CAP (E3): git to github.com goes through Orca's egress proxy, whose edge refuses request bodies over\n# ~100 MB with a bare 413. Say what happened and how to split the push instead.\ntoo_large_line() {\n printf '%s\\n' \"orca: This push is over Orca Cloud's limit of about 100 MB per push. Push fewer commits at a time, for example git push origin HEAD~5:refs/heads/, then run git push again.\" >&2\n}\n# orca-git-as's own fallback line is replaced by the nudge; GitHub auth failures by the plain line.\nfallback_filter() {\n local line said=0 said413=0\n while IFS= read -r line || [ -n \"$line\" ]; do\n case \"$line\" in\n 'orca-git-as: no teammate identity'*) nudge_once ;;\n 'remote: Repository not found.'* | \"fatal: repository 'https://github.com/\"*\"' not found\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said\" = 1 ] || not_found_line\n said=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *\"could not read Username for 'https://github.com'\"* | *\"could not read Password for 'https://\"*\"github.com'\"* | \\\n *\"Authentication failed for 'https://github.com/\"* | 'remote: Permission to '*' denied to '* | \\\n *\"The requested URL returned error: 403\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said\" = 1 ] || no_access_line\n said=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *\"RPC failed; HTTP 413\"* | *\"The requested URL returned error: 413\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said413\" = 1 ] || too_large_line\n said413=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *) printf '%s\\n' \"$line\" ;;\n esac\n done\n}\ncase \"$sub\" in\n push | pull | fetch)\n github_remote_slug \"$@\"\n if [ -n \"$github_slug\" ]; then\n export GIT_TERMINAL_PROMPT=0 GCM_INTERACTIVE=never\n fi\n ;;\nesac\ngit_as=\"${ORCA_GIT_AS:-/opt/orca/bin/orca-git-as}\"\ncase \"$sub\" in\n commit | push | merge | rebase | cherry-pick | revert | am | pull | tag)\n hold_for_member_setup\n # Outside an agent turn (no attested sender) orca-git-as falls back to the workspace identity.\n if [ -n \"${ORCA_TERMINAL_HANDLE:-}${ORCA_AGENT_SESSION_ID:-}\" ] && [ -x \"$git_as\" ]; then\n PATH=\"/usr/bin:/bin:$PATH\" exec \"$git_as\" \"$@\" 2> >(fallback_filter >&2)\n fi\n # No terminal or agent turn to attribute it to: the workspace identity.\n nudge_once\n ;;\nesac\nif [ -n \"$github_slug\" ]; then\n exec \"$real\" \"$@\" 2> >(fallback_filter >&2)\nfi\nexec \"$real\" \"$@\"\n","gh":"#!/usr/bin/env bash\n# gh for agents in Orca Cloud workspaces: GitHub actions an agent takes in a teammate's turn (gh pr create,\n# comments, reviews) act as that teammate, through their own placeholder, swapped at egress for their GitHub\n# user token (never in the VM). Orcad attests the sender exactly as for git (orca-git-identity). With no\n# attested teammate, or before the control plane turns this on (ORCA_GH_AS_MEMBER=on), gh runs as before:\n# the workspace identity.\n# Layout: the real gh is /opt/orca/tools/gh/bin/gh (off PATH); /opt/orca/tools/bin/gh, first on every agent\n# PATH, is a link to this script. Symlinks are resolved so the link never finds itself.\nself=\"$(readlink -f \"$0\" 2>/dev/null || echo \"$0\")\"\nreal=\"${ORCA_REAL_GH:-}\"\nif [ -z \"$real\" ] && [ -x \"${ORCA_HOME:-/opt/orca}/tools/gh/bin/gh\" ]; then\n real=\"${ORCA_HOME:-/opt/orca}/tools/gh/bin/gh\"\nfi\nif [ -z \"$real\" ]; then\n IFS=: read -r -a dirs <<<\"${PATH:-/usr/bin:/bin}\"\n for dir in \"${dirs[@]}\" /usr/local/bin /usr/bin; do\n if [ -x \"$dir/gh\" ] && [ \"$(readlink -f \"$dir/gh\" 2>/dev/null || echo \"$dir/gh\")\" != \"$self\" ]; then\n real=\"$dir/gh\"\n break\n fi\n done\nfi\n[ -n \"$real\" ] || { echo 'gh: not installed in this sandbox' >&2; exit 127; }\nif [ \"${ORCA_GH_AS_MEMBER:-}\" = on ] && [ -n \"${ORCA_TERMINAL_HANDLE:-}${ORCA_AGENT_SESSION_ID:-}\" ]; then\n file=\"$(sudo -n --preserve-env=ORCA_TERMINAL_HANDLE,ORCA_PANE_KEY,ORCA_AGENT_LAUNCH_TOKEN,ORCA_AGENT_SESSION_ID \\\n /opt/orca/bin/orca-git-identity 2>/dev/null)\" && [ -n \"$file\" ] && {\n token=\"$(git config -f \"$file\" orca.ghtoken 2>/dev/null || true)\"\n rm -f \"$file\"\n case \"$token\" in\n orca-ph-* | orca-mph-*) exec env GH_TOKEN=\"$token\" GITHUB_TOKEN=\"$token\" \"$real\" \"$@\" ;;\n esac\n }\nfi\nexec \"$real\" \"$@\"\n","docker":"#!/usr/bin/env bash\n# docker for Orca Cloud workspaces (first on orcad's PATH; PARITY-DOCKER). The golden image does not\n# ship Docker (it made every create ~5 s slower): the first docker command in a workspace installs\n# Ubuntu's pinned packages, then starts dockerd as root inside this workspace's own VM, then everything\n# is plain docker. Running containers stop when the workspace sleeps; images and the install stay.\n# The control plane can turn Docker off (SANDBOX_DOCKER=off): orca-sandbox-start then leaves\n# ~/.orca-sandbox/docker.off and this refuses with a plain message instead.\n# The Worker installs this script into every workspace on start, so changing the pins below is a\n# Worker deploy, not a golden rotation.\nreal=\"${ORCA_REAL_DOCKER:-/usr/bin/docker}\"\nstate=\"${HOME:-/nonexistent}/.orca-sandbox\"\nlog=\"${ORCA_DOCKERD_LOG:-/tmp/orca-dockerd.log}\"\nsudo_cmd=\"${ORCA_DOCKER_SUDO-sudo -n}\"\npackages=\"${ORCA_DOCKER_PACKAGES:-docker.io=29.1.3-0ubuntu4.1 docker-compose-v2=2.40.3+ds1-0ubuntu1 docker-buildx=0.30.1-0ubuntu1}\"\n\n# fd 3 is the caller's stderr even while apt's output goes to the log.\nexec 3>&2\nsay() { printf '%s\\n' \"$@\" >&3; }\n\nif [ -f \"$state/docker.off\" ]; then\n say \"orca: Docker is turned off for Orca Cloud workspaces right now.\"\n exit 1\nfi\n\n# Only commands that need the daemon start it; `docker --version`, `docker help` and the like don't.\nneeds_daemon=1\ncase \"${1:-}\" in '' | -v | --version | help | -h | --help) needs_daemon=0 ;; esac\n# A DOCKER_HOST pointing elsewhere is the user's choice: never start a local daemon for it.\n[ -n \"${DOCKER_HOST:-}\" ] && needs_daemon=0\n\ndaemon_up() { \"$real\" info >/dev/null 2>&1; }\n\nif [ -x \"$real\" ] && { [ \"$needs_daemon\" = 0 ] || daemon_up; }; then\n exec \"$real\" \"$@\"\nfi\n\n# First use (install) or a stopped daemon (start): two first commands at once must not run apt twice\n# or start two daemons.\nexec 8>\"${ORCA_DOCKER_LOCK:-/tmp/orca-dockerd.lock}\"\nflock -w 600 8 || true\n\nif [ ! -x \"$real\" ]; then\n say \"orca: Setting up Docker in this workspace (first use, about 10 seconds)...\"\n apt=\"${ORCA_DOCKER_APT:-apt-get}\"\n if ! $sudo_cmd env DEBIAN_FRONTEND=noninteractive \"$apt\" update -qq >>\"$log\" 2>&1; then\n say \"orca: Couldn't set up Docker in this workspace because the Ubuntu package archive couldn't be reached. Run docker again to retry. Details: $log\"\n exit 1\n fi\n say \"orca: Downloading and installing Docker (about 110 MB)...\"\n # shellcheck disable=SC2086 # $packages is one word per package\n if ! $sudo_cmd env DEBIAN_FRONTEND=noninteractive \"$apt\" install -y -qq --no-install-recommends $packages >>\"$log\" 2>&1 ||\n [ ! -x \"$real\" ]; then\n say \"orca: Couldn't set up Docker in this workspace. Run docker again to retry. Details: $log\"\n exit 1\n fi\n # overlay2; capped local logs; the mirror first (Docker Hub's anonymous limit is per IP, and\n # sandboxes share egress IPs). Left alone if the user already has a config.\n config=\"${ORCA_DOCKER_CONFIG:-/etc/docker/daemon.json}\"\n if [ ! -e \"$config\" ]; then\n $sudo_cmd mkdir -p \"$(dirname \"$config\")\" &&\n printf '%s\\n' '{\"storage-driver\":\"overlay2\",\"log-driver\":\"local\",\"log-opts\":{\"max-size\":\"10m\",\"max-file\":\"3\"},\"registry-mirrors\":[\"https://mirror.gcr.io\"]}' |\n $sudo_cmd tee \"$config\" >/dev/null\n fi\n say \"orca: Docker is set up.\"\nfi\n\nif [ \"$needs_daemon\" = 1 ] && ! daemon_up; then\n # The socket belongs to this user's group, so docker works in this shell without a new login.\n $sudo_cmd \"${ORCA_DOCKERD:-/usr/bin/dockerd}\" --group \"$(id -gn)\" >>\"$log\" 2>&1 3>&- 8>&- /dev/null || true\n ticks=0\n until daemon_up; do\n if [ \"$ticks\" -ge \"${ORCA_DOCKER_WAIT_TICKS:-150}\" ]; then\n say \"orca: Docker couldn't start in this workspace. Run docker again to retry. Details: $log\"\n exit 1\n fi\n sleep 0.1\n ticks=$((ticks + 1))\n done\n # Said where agents and people see it: what differs from a laptop. Containers stopping on sleep is\n # said on every start; the proxy certificate only on the workspace's first.\n say \"orca: Docker started in this workspace. Running containers stop when the workspace sleeps (images stay).\"\n if [ ! -e \"$state/docker.ca-noticed\" ]; then\n say \"orca: Containers that call github.com or an agent's API need to trust this workspace's proxy certificate. Mount it:\" \\\n \" -v /etc/pki/ca-trust/source/anchors/vercel-proxy-ca.pem:/usr/local/share/ca-certificates/orca-proxy.crt:ro\" \\\n \"then run update-ca-certificates in the container, or point NODE_EXTRA_CA_CERTS or SSL_CERT_FILE at it.\"\n mkdir -p \"$state\" 2>/dev/null && : >\"$state/docker.ca-noticed\"\n fi\nfi\nexec 8>&-\nexec \"$real\" \"$@\"\n"} +export const VM_SCRIPTS_HASH: string = "bdcc6c09" +export const VM_SCRIPTS_STAMP: number = 1794819210 export const SOURCE_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Golden build from source, run by the Worker inside the build sandbox: orcad + the orca CLI from one\n# commit of the Orca repo (cloud/integration carries host RPCs no upstream release has), then the same\n# provision-golden.sh every image uses. Inputs (env):\n# ORCA_SRC_SHA (40-hex) and either ORCA_SRC_DIR (source already uploaded) or ORCA_SRC_REPO\n# (https://github.com//) + ORCA_SRC_AUTH (an\n# `Authorization: Basic …` header value for a 1 h read-only installation token; never printed),\n# ORCA_PROVISION_SCRIPT (base64 of provision-golden.sh) + everything provision-golden.sh reads.\nset -euo pipefail\n# Vercel can report a detached build command as still running after it exits, so the outcome is also\n# a file the caller polls: /tmp/source-build.exit (exit code), /tmp/source-build.report (the\n# provision report line).\nrm -f /tmp/source-build.exit /tmp/source-build.report\ntrap 'echo $? >/tmp/source-build.exit' EXIT\nlog() { printf '[source-build] %s\\n' \"$*\" >&2; }\nstart=$(date +%s)\n[[ \"$ORCA_SRC_SHA\" =~ ^[0-9a-f]{40}$ ]] || { log 'ORCA_SRC_SHA must be a full commit sha'; exit 2; }\n\nlog 'build tools'\nif command -v apt-get >/dev/null; then\n # Transient mirror errors and dpkg lock contention made apt exit 100 (2 of ~10 golden builds):\n # retry downloads and wait for the lock instead of failing the build.\n printf 'Acquire::Retries \"5\";\\nDPkg::Lock::Timeout \"180\";\\n' | sudo tee /etc/apt/apt.conf.d/80-orca-retries >/dev/null\n sudo apt-get update -qq\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends build-essential python3 git ca-certificates >/dev/null\nelse\n sudo dnf install -y -q gcc gcc-c++ make tar gzip python3 git >/dev/null\nfi\nsudo corepack enable >/dev/null 2>&1 || true\n\nsrc=\"$HOME/orca-src\"\nif [ -n \"${ORCA_SRC_DIR:-}\" ]; then\n # Operator rotation (image/rotate-golden-from-source.ts) uploaded `git archive ` here already.\n log \"uploaded source for $ORCA_SRC_SHA\"\n src=\"$ORCA_SRC_DIR\"\n cd \"$src\" && test -f package.json\n git init -q && git add -A && git -c user.email=build@orca -c user.name=build commit -qm \"$ORCA_SRC_SHA\"\nelse\n log \"fetch $ORCA_SRC_SHA\"\n rm -rf \"$src\" && mkdir -p \"$src\" && cd \"$src\"\n git init -q\n # The header lives only in this one command's config, not in .git/config.\n git -c \"http.https://github.com/.extraheader=$ORCA_SRC_AUTH\" fetch -q --depth 1 \"$ORCA_SRC_REPO\" \"$ORCA_SRC_SHA\"\n unset ORCA_SRC_AUTH\n git -c advice.detachedHead=false checkout -q FETCH_HEAD\n test \"$(git rev-parse HEAD)\" = \"$ORCA_SRC_SHA\"\nfi\n\n# The image files come from this commit too (VM scripts, provision, manifest pins). The env the\n# caller passed is only a fallback for commits from before commit-provision-env.mjs existed.\nimage_dir=\"$src/cloud/apps/sandbox-control/image\"\nif [ -f \"$image_dir/commit-provision-env.mjs\" ]; then\n # The stamp must describe this commit's scripts, never the Worker's: a commit from before stamps\n # leaves it unset (the image then reads as stamp 0).\n unset ORCA_VM_SCRIPTS_STAMP\n node \"$image_dir/commit-provision-env.mjs\" \"$image_dir\" >/tmp/commit-provision.env\n # shellcheck disable=SC1091\n . /tmp/commit-provision.env\n rm -f /tmp/commit-provision.env\n log \"image files from $ORCA_SRC_SHA\"\nfi\n\nlog 'build orcad + CLI'\nexport CI=1 ELECTRON_SKIP_BINARY_DOWNLOAD=1 PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1\ncorepack pnpm install --frozen-lockfile >/tmp/src-install.log 2>&1 || { tail -40 /tmp/src-install.log >&2; exit 1; }\ncorepack pnpm -C mobile install --frozen-lockfile >/tmp/src-mobile.log 2>&1 || { tail -40 /tmp/src-mobile.log >&2; exit 1; }\ncorepack pnpm build:mobile-web >/tmp/src-mobile-web.log 2>&1 || { tail -40 /tmp/src-mobile-web.log >&2; exit 1; }\ncorepack pnpm build:orcad >/tmp/src-orcad.log 2>&1 || { tail -60 /tmp/src-orcad.log >&2; exit 1; }\ncorepack pnpm build:cli >/tmp/src-cli.log 2>&1 || { tail -40 /tmp/src-cli.log >&2; exit 1; }\nmkdir -p out/orca-cli\nnode_modules/.bin/esbuild out/cli/index.js --bundle --platform=node --target=node22 --format=cjs \\\n --outfile=out/orca-cli/orca-cli.cjs --log-level=error\nprintf '%s\\n' \"$ORCA_SRC_SHA\" >out/orcad/SOURCE_COMMIT\ntar czf /tmp/orcad.tgz -C out orcad runtimes orca-cli\nlog \"built in $(( $(date +%s) - start ))s\"\n\nexport ORCAD_BUNDLE_URL=file:///tmp/orcad.tgz\nORCAD_BUNDLE_SHA256=\"$(sha256sum /tmp/orcad.tgz | cut -d' ' -f1)\"\nexport ORCAD_BUNDLE_SHA256\ncd \"$HOME\"\nprintf '%s' \"$ORCA_PROVISION_SCRIPT\" | base64 -d >/tmp/provision-golden.sh\nunset ORCA_PROVISION_SCRIPT\nbash /tmp/provision-golden.sh | tee /tmp/source-build.report\n# Build leftovers stay out of the image.\nrm -rf \"$src\" \"$HOME/.local/share/pnpm\" \"$HOME/.cache/pnpm\" /tmp/orcad.tgz /tmp/provision-golden.sh /tmp/src-*.log\nlog \"done in $(( $(date +%s) - start ))s\"\n" export const ENVIRONMENT_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Environment build (\"Cloud Computer\"), run by the control plane in a VM booted from the golden image.\n# Clones every repo, runs the org's install script once with `set -euo pipefail`, then records what it\n# built from (commit + lockfile blob ids per repo) so the control plane can tell when a rebuild is due.\n# Everything printed here streams live to the desktop build log.\n#\n# Env from the control plane (validated there): ORCA_BUILD_REPOS (`|||\n# ` lines: each private repo gets its own placeholder the egress swaps), ORCA_INSTALL_SCRIPT_B64, ORCA_LOCKFILES (space list), optional ORCA_GIT_EXTRAHEADER and ORCA_CLONE_FILTER, plus\n# ORCA_BUILD_SECRET_NAMES (space list of the team secrets the environment names; each value rides in\n# the variable of that name) and ORCA_BUILD_WITHHELD_SECRETS (names it lists that builds never get).\n# `::orca-step:: ` lines mark progress.\n# Exit codes: 10 clone, 20 install script, 30 recording the result, 40 a secret's value left on disk.\n# ORCA_AUTO_INSTALL=1 (automatic environments, no install script): install from the lockfile, never failing.\nset -uo pipefail\numask 022\n# One stream: the provider replays stdout and stderr separately after the fact, so a failed build's\n# log would read out of order. `::orca-error::` lines carry Orca's own failure explanations.\nexec 2>&1\nOUT=/tmp/orca-build\nROOT=/vercel/sandbox/repos\nmkdir -p \"$OUT\" \"$ROOT\"\n\n# SEC-2: the snapshot of this VM is the team's saved environment, booted by every member's workspace,\n# so a secret's value must never be in it. Secrets are for the install script alone: take_secrets\n# moves them out of this script's environment (clones and Orca's own steps never see them), the\n# install step hands them to that one child, and scan_secrets searches the disk before the build\n# may succeed.\nsecret_names=()\nsecret_values=()\ntake_secrets() {\n local name\n for name in ${ORCA_BUILD_SECRET_NAMES:-}; do\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n [ -n \"${!name:-}\" ] || continue\n secret_names+=(\"$name\")\n secret_values+=(\"${!name}\")\n unset \"$name\"\n done\n unset ORCA_BUILD_SECRET_NAMES\n # Only a file that changes after this marker can hold a value: the base image never saw one.\n : >\"$OUT/.scan-since\"\n}\n\n# Fails (non-zero) when a secret's value is in a file the build created or changed, anywhere on the\n# disk the snapshot captures. Plain text only: a value the script encoded, encrypted or compressed is\n# not found, and neither is one shorter than 8 characters (it would match ordinary text). A search\n# that cannot run fails too. Prints names and paths, never a value.\n# ORCA_SCAN_ROOT: tests only (a scratch tree); the control plane never sets it.\nscan_secrets() {\n [ \"${#secret_names[@]}\" -gt 0 ] || return 0\n local root=\"${ORCA_SCAN_ROOT:-/}\" i line pattern hit named=0\n local names=() patterns=() args=() newer=() sudo=()\n for i in \"${!secret_names[@]}\"; do\n # grep -F reads a newline as \"or\": a multi-line value (a PEM key) is searched by its longest line.\n pattern=\"\"\n while IFS= read -r line; do\n case \"$line\" in -----*) continue ;; esac\n if [ \"${#line}\" -gt \"${#pattern}\" ]; then pattern=\"$line\"; fi\n done < <(printf '%s\\n' \"${secret_values[$i]}\") # a pipe, not a here-string temp file\n [ \"${#pattern}\" -ge 8 ] || continue\n names+=(\"${secret_names[$i]}\")\n patterns+=(\"$pattern\")\n args+=(-e \"$pattern\")\n done\n [ \"${#patterns[@]}\" -gt 0 ] || return 0\n if ! command -v find >/dev/null 2>&1 || ! command -v grep >/dev/null 2>&1 || ! command -v xargs >/dev/null 2>&1; then\n echo \"::orca-error:: Orca couldn’t check the build for secrets, so the environment wasn’t saved.\"\n return 1\n fi\n # Root-owned files count too (`sudo npm config set` writes /root/.npmrc).\n if sudo -n true 2>/dev/null; then sudo=(sudo -n); fi\n # A missing marker (the install script removed it) means every file is searched.\n if [ -f \"$OUT/.scan-since\" ]; then newer=(-cnewer \"$OUT/.scan-since\"); fi\n changed_files() {\n ${sudo[@]+\"${sudo[@]}\"} find \"$root\" \\( -path /proc -o -path /sys -o -path /dev -o -path /run \\) -prune \\\n -o -type f ${newer[@]+\"${newer[@]}\"} -print0 2>/dev/null\n }\n # One pass for every value; the per-secret passes only run on a build that is about to fail.\n if [ -z \"$(changed_files | ${sudo[@]+\"${sudo[@]}\"} xargs -0 grep -lsF \"${args[@]}\" -- 2>/dev/null | head -n 1)\" ]; then\n return 0\n fi\n for i in \"${!names[@]}\"; do\n while IFS= read -r hit; do\n [ -n \"$hit\" ] || continue\n named=1\n echo \"::orca-error:: ${names[$i]} was left in $hit. Saved environments are shared with your team, so remove it before the install script ends.\"\n done < <(changed_files | ${sudo[@]+\"${sudo[@]}\"} xargs -0 grep -lsF -e \"${patterns[$i]}\" -- 2>/dev/null | head -n 5)\n done\n if [ \"$named\" -eq 0 ]; then\n # The file moved between the two passes: still a build that held a value on disk.\n echo \"::orca-error:: The install script left a secret on disk, so the environment wasn’t saved. Remove it before the script ends, then save again.\"\n fi\n return 1\n}\n\n# PARITY-AUTO-ENV-DEPS: an automatic environment (ORCA_AUTO_INSTALL=1, no install script) installs the\n# first repo's JavaScript dependencies from its lockfile, so new workspaces start with them (the deps\n# step below carries node_modules into each worktree). Soft by design: a failure, a lockfile out of date\n# or the time cap leaves the clone as it was (no half-installed node_modules) and the build goes on.\n# Package managers the image doesn't have (bun, uv, bundler, go, cargo) are only named in the log.\n# ORCA_AUTO_INSTALL_TIMEOUT: tests only.\nauto_install() {\n local dir=\"$1\" pm=\"\" declared=\"\" rc=0 started f\n local cmd=() others=()\n for f in bun.lock bun.lockb uv.lock poetry.lock Pipfile.lock Gemfile.lock go.sum Cargo.lock; do\n [ -f \"$dir/$f\" ] && others+=(\"$f\")\n done\n if [ -f \"$dir/package.json\" ]; then\n # package.json's packageManager (\"pnpm@9.1.0\") wins over the lockfile guess.\n declared=$(sed -n 's/.*\"packageManager\"[[:space:]]*:[[:space:]]*\"\\([a-z]*\\)@.*/\\1/p' \"$dir/package.json\" | head -n 1)\n case \"$declared\" in\n pnpm | yarn | npm) pm=\"$declared\" ;;\n *)\n if [ -f \"$dir/pnpm-lock.yaml\" ]; then pm=pnpm\n elif [ -f \"$dir/yarn.lock\" ]; then pm=yarn\n elif [ -f \"$dir/package-lock.json\" ] || [ -f \"$dir/npm-shrinkwrap.json\" ]; then pm=npm\n fi\n ;;\n esac\n fi\n if [ \"${#others[@]}\" -gt 0 ]; then\n echo \"Not installed automatically: ${others[*]}. Add an install script to the environment to install these.\"\n fi\n if [ -z \"$pm\" ]; then\n [ \"${#others[@]}\" -gt 0 ] || echo \"No lockfile found; the build keeps the cloned repos.\"\n return 0\n fi\n # Through corepack, so pnpm and yarn come at the version the repo pins (Node ships corepack).\n case \"$pm\" in\n pnpm) cmd=(corepack pnpm install --frozen-lockfile) ;;\n yarn)\n if [ -f \"$dir/.yarnrc.yml\" ]; then cmd=(corepack yarn install --immutable)\n else cmd=(corepack yarn install --frozen-lockfile)\n fi\n ;;\n npm) cmd=(npm ci) ;;\n esac\n echo \"Installing dependencies automatically: ${cmd[*]}\"\n started=$(date +%s)\n (cd \"$dir\" && COREPACK_ENABLE_DOWNLOAD_PROMPT=0 timeout \"${ORCA_AUTO_INSTALL_TIMEOUT:-900}\" \"${cmd[@]}\") /dev/null || true\n return 0\n fi\n echo \"Installed dependencies in $(($(date +%s) - started))s.\"\n}\n\ntake_secrets\nstep() { printf '\\n::orca-step:: %s\\n' \"$1\"; }\nstarted=$(date +%s)\nexport PATH=\"/opt/orca/tools/bin:/opt/orca/bin:$PATH\"\nexport ORCA_REPOS_ROOT=\"$ROOT\" ORCA_ENVIRONMENT_BUILD=1 CI=1 GIT_TERMINAL_PROMPT=0\nrepos() { printf '%s\\n' \"$ORCA_BUILD_REPOS\"; }\n\n# Tell the script author (often an agent) what they are installing onto.\npm=$(for c in apt-get dnf yum apk; do command -v \"$c\" >/dev/null 2>&1 && { echo \"$c\"; break; }; done)\necho \"Base image: $(. /etc/os-release 2>/dev/null && echo \"$PRETTY_NAME\"), $(nproc) vCPU, package manager: ${pm:-none} (with sudo)\"\n\nstep clone\nfirst=\"\"\nwhile IFS='|' read -r url branch dir header; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n [ -n \"$first\" ] || first=\"$dest\"\n # The egress layer swaps the placeholder for a short-lived repo token; nothing real is on disk,\n # and the header is never written to the repo's config.\n git_auth=()\n [ -z \"${header:-}\" ] || git_auth=(-c \"http.https://github.com/.extraheader=$header\")\n echo \"Cloning $url${branch:+ ($branch)}\"\n rm -rf -- \"$dest\"\n # The clone's own error shows only when it really failed (an empty repo is recovered below).\n # ORCA_CLONE_FILTER (automatic environments: blob:none) keeps history and trees, not every old blob.\n if ! git \"${git_auth[@]}\" clone --quiet ${ORCA_CLONE_FILTER:+--filter=\"$ORCA_CLONE_FILTER\"} ${branch:+--branch \"$branch\"} -- \"$url\" \"$dest\" 2>\"$OUT/clone.err\"; then\n refs=0\n git \"${git_auth[@]}\" ls-remote --exit-code -- \"$url\" >/dev/null 2>&1 || refs=$?\n if [ -n \"$branch\" ] && [ \"$refs\" -eq 2 ]; then\n # Reachable but no refs at all (ls-remote exits 2): a repo with no commits yet.\n echo \"$url has no commits yet; starting it empty on $branch.\"\n rm -rf -- \"$dest\"\n { git \"${git_auth[@]}\" clone --quiet -- \"$url\" \"$dest\" 2>/dev/null && git -C \"$dest\" checkout --quiet -b \"$branch\"; } || exit 10\n else\n cat \"$OUT/clone.err\"\n echo \"::orca-error:: Could not clone $url${branch:+ at $branch}. Check that the branch exists and Orca Cloud can reach the repository.\" \n exit 10\n fi\n fi\n git -C \"$dest\" log -1 --format=' at %h %s' 2>/dev/null || echo ' (no commits yet)'\ndone < <(repos)\n\nstep install\nprintf '%s' \"${ORCA_INSTALL_SCRIPT_B64:-}\" | base64 -d >\"$OUT/install.sh\"\nif [ -s \"$OUT/install.sh\" ]; then\n echo \"Running the install script in ${first:-$ROOT}\"\n for name in ${ORCA_BUILD_WITHHELD_SECRETS:-}; do\n echo \"$name is a model key, so environment builds don’t get it. Agents in workspaces still do.\"\n done\n (\n cd \"${first:-$ROOT}\" || exit 1\n if [ \"${#secret_names[@]}\" -gt 0 ]; then\n for i in \"${!secret_names[@]}\"; do export \"${secret_names[$i]}=${secret_values[$i]}\"; done\n fi\n exec bash -euo pipefail \"$OUT/install.sh\"\n ) /dev/null)\" || continue\n git -C \"$dest\" ls-files --others --ignored --exclude-standard --directory 2>/dev/null \\\n | sed 's#/$##' | grep -E \"$deps_re\" | head -n 500 >\"$common/orca-env-deps\" || true\n if [ -n \"${ORCA_DEPS_HOOK_B64:-}\" ]; then\n # A relative core.hooksPath (husky: .husky/_) names a gitignored folder a new worktree lacks; pin\n # it to the primary checkout so every worktree runs the same hooks, ours included.\n rel=\"$(git -C \"$dest\" config --get core.hooksPath 2>/dev/null || true)\"\n case \"$rel\" in '' | /*) ;; *) git -C \"$dest\" config core.hooksPath \"$dest/$rel\" ;; esac\n hooks=\"$(git -C \"$dest\" rev-parse --path-format=absolute --git-path hooks)\"\n mkdir -p \"$hooks\"\n if [ -e \"$hooks/post-checkout\" ] && ! grep -q 'orca-env-deps' \"$hooks/post-checkout\"; then\n mv -- \"$hooks/post-checkout\" \"$hooks/post-checkout.orca-chained\"\n fi\n printf '%s' \"$ORCA_DEPS_HOOK_B64\" | base64 -d >\"$hooks/post-checkout\" && chmod 0755 \"$hooks/post-checkout\"\n fi\n n=$(wc -l <\"$common/orca-env-deps\" | tr -d ' ')\n [ \"$n\" -gt 0 ] && echo \"$dir: $n installed folder(s) carried into new workspaces.\"\ndone < <(repos)\n{\n printf '{\"durationSec\":%d,\"repos\":[' \"$(( $(date +%s) - started ))\"\n sep=\"\"\n while IFS='|' read -r url branch dir _; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n commit=$(git -C \"$dest\" rev-parse --verify --quiet HEAD 2>/dev/null || true)\n head=$(git -C \"$dest\" symbolic-ref --quiet --short HEAD 2>/dev/null || true)\n printf '%s{\"url\":\"%s\",\"dir\":\"%s\",\"branch\":\"%s\",\"commit\":\"%s\",\"lockfiles\":{' \"$sep\" \"$url\" \"$dir\" \"$head\" \"$commit\"\n lsep=\"\"\n if [ -n \"$commit\" ]; then\n for f in ${ORCA_LOCKFILES:-}; do\n blob=$(git -C \"$dest\" rev-parse --verify --quiet \"HEAD:$f\" 2>/dev/null || true)\n if [ -n \"$blob\" ]; then printf '%s\"%s\":\"%s\"' \"$lsep\" \"$f\" \"$blob\"; lsep=\",\"; fi\n done\n fi\n printf '}}'\n sep=\",\"\n done < <(repos)\n printf '],\"diskUsedBytes\":%s,\"diskTotalBytes\":%s}\\n' \\\n \"$(df -B1 --output=used / | tail -n 1 | tr -d ' ')\" \"$(df -B1 --output=size / | tail -n 1 | tr -d ' ')\"\n} >\"$OUT/result.json\" || exit 30\n# Nothing from this VM's own session belongs in the image, only what the script installed.\nrm -rf -- \"$OUT/install.sh\" \"$OUT/.scan-since\" \"$HOME/.bash_history\" \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\"\necho \"Disk used: $(df -h --output=used / | tail -n 1 | tr -d ' ') of $(df -h --output=size / | tail -n 1 | tr -d ' ')\"\n" export const ENVIRONMENT_DEPS_HOOK: string = "#!/usr/bin/env bash\n# Installed by Orca environment builds as the repo's post-checkout hook. When git creates a new linked\n# worktree (`git worktree add` passes the null commit as the previous HEAD), give it the dependency\n# folders the build installed in the primary checkout, as hard links: near-instant, real paths (not\n# symlinks, so bundlers and native modules behave). Hard links share file contents: tools that rewrite\n# a file in place inside these folders change it for every worktree on this VM (one workspace per VM).\n# Any post-checkout hook the repo already had runs afterwards, unchanged.\nprev=\"${1:-}\"\nhere=\"$(dirname \"$0\")\"\nif [ \"$prev\" = \"0000000000000000000000000000000000000000\" ] && [ \"${ORCA_SKIP_DEPS_LINK:-}\" != 1 ]; then\n common=\"$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null || true)\"\n top=\"$(git rev-parse --show-toplevel 2>/dev/null || true)\"\n primary=\"$(dirname \"$common\")\"\n list=\"$common/orca-env-deps\"\n if [ -n \"$top\" ] && [ \"$top\" != \"$primary\" ] && [ -f \"$list\" ]; then\n started=$(date +%s%N)\n linked=0\n while IFS= read -r rel; do\n case \"$rel\" in '' | /* | *..*) continue ;; esac\n [ -e \"$primary/$rel\" ] && [ ! -e \"$top/$rel\" ] || continue\n mkdir -p \"$(dirname \"$top/$rel\")\"\n if [ -d \"$primary/$rel\" ]; then\n if ! cp -al -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null; then\n # A partial hard-link copy would make the fallback nest inside it: start clean.\n rm -rf -- \"$top/$rel\"\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || { rm -rf -- \"$top/$rel\"; continue; }\n fi\n else\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || continue\n fi\n linked=$((linked + 1))\n done <\"$list\"\n if [ \"$linked\" -gt 0 ]; then\n echo \"Orca: reused $linked installed dependency folder(s) from the environment build ($(( ($(date +%s%N) - started) / 1000000 )) ms).\" >&2\n fi\n fi\nfi\nif [ -x \"$here/post-checkout.orca-chained\" ]; then\n if head -n 1 \"$here/post-checkout.orca-chained\" | grep -Eq '^#!.*(ba|da|z)?sh'; then\n # Sourced, so $0 still names `post-checkout` (husky v9 finds the user's hook by basename \"$0\").\n ( . \"$here/post-checkout.orca-chained\" \"$@\" )\n exit $?\n fi\n exec \"$here/post-checkout.orca-chained\" \"$@\"\nfi\nexit 0\n" diff --git a/cloud/apps/sandbox-control/image/vm/orca-git-identity b/cloud/apps/sandbox-control/image/vm/orca-git-identity index a6cded392f5..8800576753f 100755 --- a/cloud/apps/sandbox-control/image/vm/orca-git-identity +++ b/cloud/apps/sandbox-control/image/vm/orca-git-identity @@ -9,6 +9,28 @@ set -euo pipefail DIR=/etc/orca/members caller="${SUDO_USER:-}" case "$caller" in '' | root | *[!a-z0-9_-]*) echo 'orca-git-identity: run through orca-git-as' >&2; exit 4 ;; esac +# Hands the caller a one-shot copy of a member's git config (owned by them, removed by orca-git-as). +emit() { + local file + file="$DIR/$(printf '%s' "$1" | tr ':' '_').gitconfig" + [ -s "$file" ] || exit 3 + out="$(sudo -u "$caller" mktemp)" + cat "$file" >"$out" + echo "$out" + exit 0 +} +# GH-SOLO: a workspace only one person can use (the control plane's rule, member-git.ts pickActing) acts as that +# person whoever typed: a TUI typed into directly has no attested sender. The control plane writes `solo` only +# while that holds, and removes it before any other member's device is paired (grants.ts). +if [ -s "$DIR/solo" ]; then + solo="$(cat "$DIR/solo")" + case "$solo" in '' | *[!A-Za-z0-9_.:-]*) exit 3 ;; esac + if [ -n "${ORCA_GIT_AS:-}" ] && [ "$ORCA_GIT_AS" != "$solo" ]; then + echo "orca-git-as: only $solo uses this workspace, not $ORCA_GIT_AS; refusing to push as someone else." >&2 + exit 4 + fi + emit "$solo" +fi # orcad's own data dir and HOME (the agent's user may not use its passwd home, e.g. HOME=/vercel). orcad_pid="$(pgrep -u "$caller" -f orcad-server.js | head -n 1 || true)" [ -n "$orcad_pid" ] || exit 3 @@ -42,9 +64,4 @@ if [ -n "${ORCA_GIT_AS:-}" ] && [ "$ORCA_GIT_AS" != "$member" ]; then echo "orca-git-as: this agent's latest message came from $member, not $ORCA_GIT_AS; refusing to push as someone else." >&2 exit 4 fi -file="$DIR/$(printf '%s' "$member" | tr ':' '_').gitconfig" -[ -s "$file" ] || exit 3 -# The caller reads the identity through this one-shot copy (owned by them, removed by orca-git-as). -out="$(sudo -u "$caller" mktemp)" -cat "$file" >"$out" -echo "$out" +emit "$member" diff --git a/cloud/apps/sandbox-control/image/vm/orca-sandbox-members b/cloud/apps/sandbox-control/image/vm/orca-sandbox-members index b91038787bf..218eabe8ba7 100755 --- a/cloud/apps/sandbox-control/image/vm/orca-sandbox-members +++ b/cloud/apps/sandbox-control/image/vm/orca-sandbox-members @@ -51,6 +51,15 @@ done < <(jq -c '.[]' <<<"$coauthors") DEVICES_JQ='add | [.[] | select(.userId | test("^[A-Za-z0-9_.:-]+$")) | .userId as $u | (.deviceIds // [])[] | select(test("^[A-Za-z0-9_-]{1,128}$")) | {key: ., value: $u}] | group_by(.key) | map(select((map(.value) | unique | length) == 1) | .[0]) | from_entries' jq -c -s "$DEVICES_JQ" <(printf '%s' "$json") <(printf '%s' "$coauthors") >"$tmp/devices.json" devices="$(jq 'length' "$tmp/devices.json")" +# GH-SOLO: ORCA_SOLO_MEMBER = the only person who can use this workspace (absent when shared). orca-git-identity +# then acts as them without an attested sender, matching the control plane. +solo="${ORCA_SOLO_MEMBER:-}" +solo_file='' +case "$solo" in '' | *[!A-Za-z0-9_.:-]*) solo='' ;; esac +if [ -n "$solo" ]; then + solo_file="$tmp/$(printf '%s' "$solo" | tr ':' '_').gitconfig" + if [ -s "$solo_file" ]; then printf '%s\n' "$solo" >"$tmp/solo"; else solo=''; solo_file=''; fi +fi chmod 0700 "$tmp" && chmod 0600 "$tmp"/* rm -rf "$DIR.old" [ -d "$DIR" ] && mv "$DIR" "$DIR.old" @@ -71,6 +80,21 @@ fi user_home="$(getent passwd "$USER_NAME" | cut -d: -f6)" [ -n "$orcad_pid" ] && user_home="$(tr '\0' '\n' <"/proc/$orcad_pid/environ" | sed -n 's/^HOME=//p' | head -n 1)" [ -n "$user_home" ] && rm -rf "$user_home/.orca-sandbox/members" +# GH-SOLO: in a one-person workspace a plain `git commit` (no turn at all) is theirs too: the default author is +# the member's GitHub noreply identity. Marked, so a workspace that becomes shared goes back to Orca's. +if [ -n "$user_home" ]; then + as_user() { sudo -u "$USER_NAME" env HOME="$user_home" git config --global "$@"; } + solo_email="$( [ -n "$solo" ] && git config -f "$DIR/$(printf '%s' "$solo" | tr ':' '_').gitconfig" user.email 2>/dev/null || true)" + if [ -n "$solo_email" ]; then + as_user user.name "$(git config -f "$DIR/$(printf '%s' "$solo" | tr ':' '_').gitconfig" user.name)" + as_user user.email "$solo_email" + as_user orca.soloauthor true + elif [ "$(as_user --get orca.soloauthor 2>/dev/null || true)" = true ]; then + as_user user.name 'Orca' + as_user user.email 'noreply@orca.dev' + as_user --unset orca.soloauthor || true + fi +fi # Commits outside a teammate's turn still need an author (images older than orca-sandbox-start's default). if [ -n "$user_home" ]; then sudo -u "$USER_NAME" env HOME="$user_home" git config --global user.email >/dev/null 2>&1 \ diff --git a/cloud/apps/sandbox-control/package.json b/cloud/apps/sandbox-control/package.json index a41ba540e7f..f252b756f57 100644 --- a/cloud/apps/sandbox-control/package.json +++ b/cloud/apps/sandbox-control/package.json @@ -4,7 +4,7 @@ "version": "0.0.0", "type": "module", "scripts": { - "dev": "wrangler dev -c wrangler.jsonc -c wrangler.build-runner.jsonc --port 8791 --ip 127.0.0.1", + "dev": "wrangler dev -c wrangler.jsonc -c wrangler.build-runner.jsonc --var SANDBOX_ENV:local --port 8791 --ip 127.0.0.1", "db:migrate:local": "wrangler d1 migrations apply SANDBOX_DB --local", "golden-image": "tsx image/build-golden-image.ts", "typecheck": "node scripts/typecheck.mjs", diff --git a/cloud/apps/sandbox-control/scripts/launch-smoke.mjs b/cloud/apps/sandbox-control/scripts/launch-smoke.mjs new file mode 100644 index 00000000000..b8e33aaa062 --- /dev/null +++ b/cloud/apps/sandbox-control/scripts/launch-smoke.mjs @@ -0,0 +1,21 @@ +#!/usr/bin/env node +// Launch smoke for a deployed sandbox-control Worker: its public /v1/health must say ok, model keys swapped at +// egress (keySwap "on"), and the environment it was deployed as (default "prod"). A prod Worker missing +// SANDBOX_ENV=prod reports something else and fails here, before anything else runs against it. +// node scripts/launch-smoke.mjs [expected environment, default prod] +const [base, expected = 'prod'] = process.argv.slice(2) +if (!base) { + console.error('usage: launch-smoke.mjs [expected environment]') + process.exit(2) +} +const response = await fetch(new URL('/v1/health', base), { signal: AbortSignal.timeout(15_000) }) +const body = await response.json().catch(() => null) +const problems = [] +if (response.status !== 200 || body?.ok !== true) problems.push(`health ${response.status} ${JSON.stringify(body)}`) +if (body?.keySwap !== 'on') problems.push(`keySwap is ${JSON.stringify(body?.keySwap)}, expected "on"`) +if (body?.environment !== expected) problems.push(`environment is ${JSON.stringify(body?.environment)}, expected ${JSON.stringify(expected)}`) +if (problems.length > 0) { + console.error(`launch smoke FAILED for ${base}:\n- ${problems.join('\n- ')}`) + process.exit(1) +} +console.log(`launch smoke OK: ${base} is ${expected}, keySwap on`) diff --git a/cloud/apps/sandbox-control/src/agent-sources.ts b/cloud/apps/sandbox-control/src/agent-sources.ts index ed5764361e8..df29b5aaa56 100644 --- a/cloud/apps/sandbox-control/src/agent-sources.ts +++ b/cloud/apps/sandbox-control/src/agent-sources.ts @@ -15,7 +15,8 @@ import { memberNamesFor } from './member-names' import { effectiveSecrets } from './secrets' import { getSandbox, type SandboxRow } from './store' import { agentCredentialState, isUsable } from './agent-credentials' -import { accountProvider, isSharedWorkspace } from './account-providers' +import { accountProvider } from './account-providers' +import { sharedWorkspaceMode } from './shared-workspace' export type AgentSource = 'sign-in' | 'key' type OfferAnswer = 'unanswered' | 'accepted' | 'declined' @@ -157,7 +158,7 @@ export async function agentSourcesView( owner = { userId: row.user_id, displayName: names.get(row.user_id) ?? null, isCaller: row.user_id === caller.userId } } // D13: personal accounts never apply in a workspace shared with teammates. - const sharedWorkspace = row ? isSharedWorkspace(row) : false + const sharedWorkspace = row ? await sharedWorkspaceMode(db, row) : false return { defaults, inWorkspace, workspace, effective: resolved, coveredByKey: covered, signInOffer, owner, sharedWorkspace } } @@ -236,6 +237,7 @@ export async function agentModesFor( const inWorkspace = inWorkspaceAgents(rows) const covered = coveredByKey(new Set(Object.keys(env))) const modes = {} as Record + const shared = await sharedWorkspaceMode(db, row) for (const agent of CREDENTIAL_AGENTS) { if (!workspace[agent] && inWorkspace[agent]) { // Nothing of Orca's for this agent: no placeholder, no key, no egress route, so the login the person @@ -255,7 +257,7 @@ export async function agentModesFor( } else if (!enabled) { // Kill switch (or no provider yet): the agent signs in inside the sandbox; keys stay out (Rule 3). modes[agent] = 'omit' - } else if (usable && options.accountsUsable && !isSharedWorkspace(row)) { + } else if (usable && options.accountsUsable && !shared) { modes[agent] = 'account' } else { // Expired/revoked, placeholders off, or a shared workspace (D13): the winning key, if any. diff --git a/cloud/apps/sandbox-control/src/auth.ts b/cloud/apps/sandbox-control/src/auth.ts index e9ef8be3954..ce11ebf65cc 100644 --- a/cloud/apps/sandbox-control/src/auth.ts +++ b/cloud/apps/sandbox-control/src/auth.ts @@ -1,5 +1,6 @@ // Desktop callers present a short-lived ES256 JWT minted by Orca Cloud auth (aud=orca-sandbox, // purpose=sandbox), verified against the auth JWKS — the billing Worker's pattern. +import { devOnly } from './dev-only' import { createLocalJWKSet, jwtVerify, @@ -114,7 +115,7 @@ let stagingKeys: { source: string; keys: JWTVerifyGetKey } | null = null /** Staging auth's keys and issuer; never honored in prod. Same accounts as billing dev (it trusts staging too). */ function stagingKeysFor(env: Env): { keys: JWTVerifyGetKey; issuer: string[] | undefined } | null { const source = env.SANDBOX_STAGING_JWKS_URL ?? (env.SANDBOX_STAGING_JWKS ? `inline:${env.SANDBOX_STAGING_JWKS}` : null) - if (env.SANDBOX_ENV === 'prod' || !source || !env.SANDBOX_STAGING_AUTH_ISSUER) { + if (!devOnly(env) || !source || !env.SANDBOX_STAGING_AUTH_ISSUER) { return null } if (stagingKeys?.source !== source) { @@ -177,7 +178,7 @@ export async function authenticateDesktop( const caller = (await verify(token, keysFor(env), env, issuerList(env.SANDBOX_AUTH_ISSUER), now)) ?? (staging ? await verify(token, staging.keys, env, staging.issuer, now) : null) - if (caller || !env.SANDBOX_DEV_JWKS || env.SANDBOX_ENV === 'prod') { + if (caller || !env.SANDBOX_DEV_JWKS || !devOnly(env)) { if (!caller || (await tokenPredatesRemoval(env.SANDBOX_DB, caller))) { return null } diff --git a/cloud/apps/sandbox-control/src/dev-only.ts b/cloud/apps/sandbox-control/src/dev-only.ts new file mode 100644 index 00000000000..b1acece073a --- /dev/null +++ b/cloud/apps/sandbox-control/src/dev-only.ts @@ -0,0 +1,7 @@ +// Dev-only routes and behaviors (operator/seed/dev-sign-in/debug): an allowlist of environment names, so an +// unset SANDBOX_ENV, staging, prod or a typo all leave them off. Never `!== 'prod'`. +import type { Env } from './env' + +export function devOnly(env: Pick): boolean { + return env.SANDBOX_ENV === 'dev' || env.SANDBOX_ENV === 'local' || env.SANDBOX_ENV === 'test' +} diff --git a/cloud/apps/sandbox-control/src/entitlements.ts b/cloud/apps/sandbox-control/src/entitlements.ts index 93570bac08f..88be95ef6c0 100644 --- a/cloud/apps/sandbox-control/src/entitlements.ts +++ b/cloud/apps/sandbox-control/src/entitlements.ts @@ -1,5 +1,6 @@ // Billing Worker client (cloud/apps/billing on nwparker/billing-worker): start checks and usage. // Fails closed: without a configured billing URL no sandbox starts, except the local-dev stub. +import { devOnly } from './dev-only' import { z } from 'zod' import type { Env } from './env' @@ -95,7 +96,7 @@ export const STOP_RUNNING_REASONS: ReadonlySet = new Set([ /** Dev operator test accounts (`dev:*`, see auth.ts) never reach billing outside prod. */ export function withDevAccountBypass(env: Env, client: EntitlementClient): EntitlementClient { // SANDBOX_DEV_BILLING_PASSTHROUGH=true sends dev accounts to billing too (live smoke of the internal routes). - if (env.SANDBOX_ENV === 'prod' || env.SANDBOX_DEV_BILLING_PASSTHROUGH === 'true') { + if (!devOnly(env) || env.SANDBOX_DEV_BILLING_PASSTHROUGH === 'true') { return client } const enforced = devBillingEnforcePrefix(env) @@ -135,8 +136,8 @@ export function createEntitlementClient( doFetch: typeof fetch = env.BILLING ? (input, init) => env.BILLING!.fetch(input, init) : fetch ): EntitlementClient { if (env.ENTITLEMENTS_MODE === 'stub') { - if (env.SANDBOX_ENV === 'prod') { - throw new BillingUnavailableError('stub entitlements refused in prod') + if (!devOnly(env)) { + throw new BillingUnavailableError('stub entitlements refused outside dev') } return { checkStart: async () => ({ allow: true, reason: null, suspendRunning: false }), diff --git a/cloud/apps/sandbox-control/src/env.ts b/cloud/apps/sandbox-control/src/env.ts index 9f346eed413..36aecdc7638 100644 --- a/cloud/apps/sandbox-control/src/env.ts +++ b/cloud/apps/sandbox-control/src/env.ts @@ -41,6 +41,8 @@ export type Env = { /** GH-AS-MEMBER: how long a shared workspace's latest sender keeps acting after their last send (default 60; `0`: no cap). */ MEMBER_GIT_SHARED_MAX_MINUTES?: string /** GH-AS-MEMBER: `on` lets gh in workspaces act as the attested sender (off by default). */ + /** TEAM-SHARING hold (team-sharing.ts): `on` lets workspaces be shared with the team; anything else holds it. */ + TEAM_SHARING?: string GH_AS_MEMBER?: string /** * Who sees a member's daily activity heatmap on their profile. `opt_in` (default): only members diff --git a/cloud/apps/sandbox-control/src/grants.ts b/cloud/apps/sandbox-control/src/grants.ts index 34ad6b27db7..caf51748d01 100644 --- a/cloud/apps/sandbox-control/src/grants.ts +++ b/cloud/apps/sandbox-control/src/grants.ts @@ -7,11 +7,12 @@ // DELETE /v1/team/workspaces/:id/grants/:grantId grantee, workspace owner or org admin // Revocation removes the device from orcad's registry (orca-sandbox-revoke); while the sandbox is // not running it is queued and applied at the next boot before orcad starts. +import { teamSharingEnabled } from './team-sharing' import { z } from 'zod' import type { SandboxCaller } from './auth' import { isDeviceSessionLive } from './device-sessions' import { markRevoked, runVmRevoke, type GrantRow } from './grant-revokes' -import { LifecycleError, settleMemberGit, resumeSandbox, syncMemberGit, type LifecycleDeps, type Ready } from './lifecycle' +import { DROP_SOLO_SCRIPT, LifecycleError, settleMemberGit, resumeSandbox, syncMemberGit, type LifecycleDeps, type Ready } from './lifecycle' import { ensureEntryPoints } from './golden-images' import type { CommandResult } from './sandbox-provider' import { ORCAD_PORT } from './sandbox-vm-commands' @@ -133,6 +134,14 @@ export async function issueGrant( .run() let output: z.infer try { + // GH-SOLO: anyone but a still-untransferred owner makes it (possibly) shared: drop the VM's one-person mark + // first, and refuse the grant if that fails (lifecycle.ts DROP_SOLO_SCRIPT). + if (caller.userId !== row.user_id || row.ownership_transferred_at != null) { + const dropped = await deps.provider.runCommand(live.sessionId, { command: 'bash', args: ['-c', DROP_SOLO_SCRIPT], sudo: true, timeoutMs: 15_000 }) + if (dropped.exitCode !== 0) { + throw new Error(`drop_solo_exit_${dropped.exitCode}`) + } + } const result = await withEntryPoints(deps, live.sessionId, GRANT_COMMAND, () => deps.provider.runCommand(live.sessionId, { command: GRANT_COMMAND, @@ -260,6 +269,40 @@ export async function revokeForAccessChange( return revokeGrants(deps, row, results, { by, reason: mode === 'non_owner' ? 'workspace_private' : 'owner_changed' }) } +/** + * TEAM-SHARING hold (team-sharing.ts): while sharing is held, a workspace stored as `team` acts private, so + * every device grant but its owner's goes, the way making it private revokes them (reason team_sharing_held). + * Transferred workspaces keep their own rules. Bounded per run; the next run takes the rest. + */ +export async function sweepHeldTeamGrants(deps: LifecycleDeps): Promise<{ workspaces: number; revoked: number; queued: number }> { + const out = { workspaces: 0, revoked: 0, queued: 0 } + if (teamSharingEnabled()) { + return out + } + const { results } = await deps.db + .prepare( + `SELECT g.* FROM workspace_grants g JOIN sandboxes s ON s.id = g.sandbox_id + WHERE g.status IN ('issuing', 'active') AND g.user_id <> s.user_id AND s.visibility = 'team' AND s.ownership_transferred_at IS NULL AND s.status <> 'destroyed' + ORDER BY g.sandbox_id LIMIT 500` + ) + .all() + const bySandbox = new Map() + for (const grant of results) { + bySandbox.set(grant.sandbox_id, [...(bySandbox.get(grant.sandbox_id) ?? []), grant]) + } + for (const [sandboxId, grants] of bySandbox) { + const row = await getSandbox(deps.db, sandboxId) + if (!row) { + continue + } + const result = await revokeGrants(deps, row, grants, { by: 'system', reason: 'team_sharing_held' }).catch(() => ({ revoked: 0, queued: 0 })) + out.workspaces++ + out.revoked += result.revoked + out.queued += result.queued + } + return out +} + /** A member left the org (auth push) or a phone session ended (W8): revoke everywhere. */ async function revokeWhere(deps: LifecycleDeps, where: string, binds: (string | number)[], audit: { by: string; reason: string }) { const { results } = await deps.db diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index 9640ce772b2..fb158e9811e 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -39,6 +39,8 @@ // Operator (OPERATOR_TOKEN): /v1/internal/* (see operator.ts) // Public share links (src/share-gateway.ts): /s//*, plus the root-path cookie fallback // Vercel network-policy forwardURL target (Vercel sandbox OIDC): /v1/egress/proxy +import { devOnly } from './dev-only' +import { configureTeamSharing, teamSharingEnabled } from './team-sharing' import { purgeTeamSecrets, teamDeleteRoute, teamWorkspaceCount } from './team-delete' import { ReadSnapshotRouteError, getReadSnapshot, handleReaderKeysRoute, pruneReadSnapshotToOwner, revokeDeviceSessionReaderKeys } from './read-snapshots' import { refreshEnvironment, refreshStaleEnvironments, type GoldenRefreshOptions } from './environment-golden-refresh' @@ -137,7 +139,8 @@ import { pushCredentialToSandbox, refreshAfterSecretChange, refreshSandboxEnv } import { credentialPushTargets, markCredentialChanged, pushCredentialChange, pushPendingCredentialChanges, type CredentialChange, type PushDeps } from './credential-outbox' import { markExpiredAccountCredentials, refreshGitHubUserTokens } from './credential-refresh' import type { CredentialAgent } from './agent-credential-names' -import { ACCOUNT_PROVIDERS, accountProvider, claudeAccount, isSharedWorkspace } from './account-providers' +import { ACCOUNT_PROVIDERS, accountProvider, claudeAccount } from './account-providers' +import { sharedWorkspaceMode } from './shared-workspace' import { handleAccountRequestSucceeded, handleAccountUnauthorized, runScheduledAccountChecks, verifyAccountCredential } from './agent-credential-checks' import { codexBrokerTick, handleCodexBrokerRoute, type BrokerDeps } from './codex-broker' import { codexAccount, parseStoredCodex, refreshCodexLeases, storeCodexLogin } from './codex-credentials' @@ -207,7 +210,8 @@ import { recordOwnerDeviceForCreate, revokeForAccessChange, revokeGrantsForDeviceSession, - revokeOne + revokeOne, + sweepHeldTeamGrants } from './grants' import { getOrgPrompts, putOrgPrompts } from './org-prompts' import { @@ -475,7 +479,7 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) => scheduleEnvRefresh(env, deps, row) return signedOut('account_owner_changed') } - if (isSharedWorkspace(row)) { + if (await sharedWorkspaceMode(env.SANDBOX_DB, row)) { scheduleEnvRefresh(env, deps, row) return signedOut('account_not_shared') } @@ -888,7 +892,7 @@ function githubManifestStart(url: URL): Response { /** GitHub App manifest flow redirect: the operator's exchange script reads the one-time code from logs. */ function githubManifestCallback(env: Env, url: URL): Response { - if (env.SANDBOX_ENV === 'prod') { + if (!devOnly(env)) { return fail('not_found', 404) } const code = url.searchParams.get('code') ?? '' @@ -923,7 +927,7 @@ async function configureAppWebhook(env: Env, deps: Deps, body: unknown): Promise function devCredentials(env: Env): CredentialBroker { const value = env.EGRESS_DEV_STATIC_AUTHORIZATION - if (!value || env.SANDBOX_ENV === 'prod') { + if (!value || !devOnly(env)) { return NO_CREDENTIALS } return { authorizationFor: async (_row, host) => (host === 'api.github.com' ? value : null) } @@ -1061,7 +1065,7 @@ export async function lifecycleDeps(env: Env, deps: Deps): Promise { + configureTeamSharing(env) try { return await routeRequest(request, env, deps) } catch (error) { @@ -1443,7 +1448,7 @@ async function routeRequest(request: Request, env: Env, deps: Deps): Promise // account (desktop builds call POST /v1/github/connect instead). const connect = githubConnect(env, deps) @@ -1644,7 +1650,7 @@ async function routeRequest(request: Request, env: Env, deps: Deps): Promise member ; desktop builds call POST /v1/github/user/connect instead. const connect = githubConnect(env, deps) @@ -2435,7 +2441,8 @@ async function workspaceRoute(request: Request, url: URL, env: Env, deps: Deps, const route = `${request.method} ${action ?? ''}${grantId ? ' :grant' : ''}` const view = async (r = row) => (await workspaceViews(db, caller, [r], clock(), githubActingOptions(env)))[0] if (route === 'GET ') { - return json({ workspace: await view() }) + // TEAM-SHARING hold: the capability rides on the single-workspace answer too (panels and link opens read it). + return json({ workspace: await view(), teamSharing: teamSharingEnabled() }) } if (route === 'GET read-snapshot') { try { @@ -2799,11 +2806,15 @@ function errorResponse(error: unknown): Response { return fail('internal_error', 500) } +/** TEAM-SHARING hold: whether this isolate has run the held-grants sweep yet (a value, never a promise). */ +let heldSweepRan = false + export default { fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { return handleRequest(request, env, { waitUntil: (work) => ctx.waitUntil(work.catch(() => undefined)) }) }, async scheduled(controller: ScheduledController, env: Env, ctx: ExecutionContext): Promise { + configureTeamSharing(env) // Every minute: routines (schedule slots, run polling). Every fifth minute: everything else. ctx.waitUntil( lifecycleDeps(env, {}).then(async (life) => { @@ -2834,6 +2845,17 @@ export default { ) const fifthMinute = new Date(controller.scheduledTime).getUTCMinutes() % 5 === 0 ctx.waitUntil(credentialTick(env, fifthMinute)) + // TEAM-SHARING hold: every fifth minute, and on an isolate's first run (so right after a deploy). + if (!teamSharingEnabled() && (fifthMinute || !heldSweepRan)) { + heldSweepRan = true + ctx.waitUntil( + lifecycleDeps(env, {}).then(async (life) => { + const swept = life ? await sweepHeldTeamGrants(life).catch(() => null) : null + // Counts only. + console.log(JSON.stringify({ event: 'team_sharing_held_sweep', ...(swept ?? { failed: true }) })) + }) + ) + } if (env.AGENT_ACCOUNTS_CODEX === 'on') { ctx.waitUntil(codexTick(env, fifthMinute)) } diff --git a/cloud/apps/sandbox-control/src/lifecycle.ts b/cloud/apps/sandbox-control/src/lifecycle.ts index aaa6aa6b0c3..b9d1d179132 100644 --- a/cloud/apps/sandbox-control/src/lifecycle.ts +++ b/cloud/apps/sandbox-control/src/lifecycle.ts @@ -1,5 +1,6 @@ // Sandbox lifecycle: one persistent provider sandbox per Orca workspace, with an Orca-owned lease, // a forced stop before the provider's 24h cap, usage metering and write-ahead rows. +import { teamSharingEnabled } from './team-sharing' import { accountProvider } from './account-providers' import { readUsableAgentCredential } from './agent-credentials' import { CODEX_FIREWALL_ALL_PATHS, CODEX_FIREWALL_PATHS } from './codex-paths' @@ -7,7 +8,7 @@ import { codexPlaceholder } from './codex-credentials' /** Where Codex refreshes its ChatGPT login. */ export const CODEX_AUTH_HOST = 'auth.openai.com' import { parseStoredCodex } from './codex-credentials' -import { isSharedWorkspace } from './shared-workspace' +import { sharedWorkspaceMode } from './shared-workspace' import { deleteAgentSourcesForSandbox } from './agent-sources' import { signOutAgentsBeforeDelete } from './agent-signout' import type { EntitlementClient, MachineSize } from './entitlements' @@ -25,7 +26,7 @@ import { applyQueuedRevokes } from './grant-revokes' import { ENTRY_POINTS_PROBE, ensureEntryPoints, entryPointsBehind, installEntryPoints, parseEntryPointsProbe } from './golden-images' import { RUNTIME_REFRESH_SCRIPT, type RuntimeBundle } from './runtime-bundles' import { memberPlaceholder, type MemberGitIdentity } from './github-user-tokens' -import { connectedMembers, memberCoauthors, memberGitConfigs } from './member-git' +import { connectedMembers, memberCoauthors, memberGitConfigs, soloMember } from './member-git' import type { RetentionConfig } from './retention' import { ProviderError, type ProviderSandboxState, type SandboxProviderApi } from './sandbox-provider' import { egressAccountRoutes, egressSecretHosts, placeholderValues, secretPlaceholder, type SecretEgressHost } from './secret-egress' @@ -428,11 +429,12 @@ export async function firewallInputsFor(deps: LifecycleDeps, row: SandboxRow): P } const keyring = deps.secrets.keyring const accounts: FirewallAccount[] = [] + const shared = await sharedWorkspaceMode(deps.db, row) for (const route of egressAccountRoutes(row)) { if (!classes.has(route.agent)) { continue } - const applies = route.owner === row.user_id && !isSharedWorkspace(row) && Boolean(deps.secrets.accountProviders?.[route.agent]) + const applies = route.owner === row.user_id && !shared && Boolean(deps.secrets.accountProviders?.[route.agent]) const stored = applies ? await readUsableAgentCredential(deps.db, keyring, row.user_id, route.agent, deps.now()).catch(() => null) : null if (route.agent === 'codex') { const tokens = stored ? parseStoredCodex(stored) : null @@ -1245,23 +1247,41 @@ export async function syncMemberGit(deps: LifecycleDeps, row: SandboxRow, sessio } } +/** + * GH-SOLO: before another person's device is paired, the VM stops treating the workspace as one person's + * (orca-git-identity would otherwise act as the owner for that device's agents too). The members sync after + * the grant writes it back if it still holds. + */ +export const DROP_SOLO_SCRIPT = 'rm -f /etc/orca/members/solo' + /** Throws when the VM did not take the identities; on success the VM's setup reads ready. */ async function installMemberGit(deps: LifecycleDeps, row: SandboxRow, sessionId: string): Promise { await ensureEntryPoints(deps, sessionId) await refreshGitCredentials(deps, row, sessionId) const configs = await memberGitConfigs({ db: deps.db, identity: deps.memberIdentity! }, row) const coauthors = await memberCoauthors(deps.db, row, new Set(configs.map((config) => config.userId))) + // GH-SOLO: the only person who can use the workspace acts as themselves in the VM with no attested sender + // (a TUI typed into directly has none), as the egress proxy already allows (memberMayAct). + const solo = await soloMember(deps.db, row) const encode = (value: unknown) => btoa(String.fromCharCode(...new TextEncoder().encode(JSON.stringify(value)))) const result = await deps.provider.runCommand(sessionId, { command: MEMBERS_COMMAND, // GIT-COAUTHOR: a separate variable, which an image's older members script simply ignores. - env: { ORCA_MEMBERS_B64: encode(configs), ORCA_COAUTHORS_B64: encode(coauthors) }, + env: { ORCA_MEMBERS_B64: encode(configs), ORCA_COAUTHORS_B64: encode(coauthors), ...(solo ? { ORCA_SOLO_MEMBER: solo } : {}) }, sudo: true, timeoutMs: 30_000 }) if (result.exitCode !== 0) { throw new Error(`members_exit_${result.exitCode}`) } + // GH-SOLO: a grant may have started between the read above and the VM write (it drops the mark first, and + // this write could have put it back). Re-check now; if it no longer holds, drop it, failing closed. + if (solo && (await soloMember(deps.db, row)) !== solo) { + const dropped = await deps.provider.runCommand(sessionId, { command: 'bash', args: ['-c', DROP_SOLO_SCRIPT], sudo: true, timeoutMs: 15_000 }) + if (dropped.exitCode !== 0) { + throw new Error(`drop_solo_exit_${dropped.exitCode}`) + } + } if (row.git_setup_failed_at) { await deps.db.prepare('UPDATE sandboxes SET git_setup_failed_at = NULL WHERE id = ?').bind(row.id).run() } @@ -1438,8 +1458,9 @@ export async function createSandbox( source_snapshot_id: bootSnapshotId, repo_branch: request.repo?.ref ?? null, name: request.title ?? null, - // A personal account has no team: its workspaces are always private. - visibility: request.visibility === 'team' && caller.accountId.includes('org:') ? 'team' : 'private', + // A personal account has no team: its workspaces are always private. So is every one while team sharing + // is held (team-sharing.ts). + visibility: request.visibility === 'team' && caller.accountId.includes('org:') && teamSharingEnabled() ? 'team' : 'private', section: request.section ?? null, ownership_transferred_at: request.ownershipTransferredAt ?? null }, diff --git a/cloud/apps/sandbox-control/src/member-git.ts b/cloud/apps/sandbox-control/src/member-git.ts index 9f5b5893a7f..d98c93cc733 100644 --- a/cloud/apps/sandbox-control/src/member-git.ts +++ b/cloud/apps/sandbox-control/src/member-git.ts @@ -82,6 +82,30 @@ export async function actingMember(db: D1Database, row: SandboxRow, now: number, return pickActing(row, grantees, latest, now, sharedMaxMs) } +/** + * GH-SOLO: the one person who can use this workspace, or null. From the people set itself (active grantees, plus + * the untransferred owner, who may have no grant row: the create's own pairing code), never from "no expiry". + * Someone else's grant still being issued or revoked (their device may be pairing, or not yet unpaired) means not + * solo. + */ +export async function soloMember(db: D1Database, row: SandboxRow): Promise { + const { results } = await db + .prepare(`SELECT DISTINCT user_id, status FROM workspace_grants WHERE sandbox_id = ? AND status IN ('issuing', 'active', 'revoking')`) + .bind(row.id) + .all<{ user_id: string; status: string }>() + const pick = pickActing( + row, + results.filter((r) => r.status === 'active').map((r) => r.user_id), + null, + 0, + null + ) + if (!('userId' in pick)) { + return null + } + return results.some((r) => r.user_id !== pick.userId) ? null : pick.userId +} + export type ActingMember = { userId: string; until: number | null } | { none: 'no_send' | 'stale' } /** The rule itself, on already-read rows (the workspace list reads them for every row in one go). */ diff --git a/cloud/apps/sandbox-control/src/read-snapshots.ts b/cloud/apps/sandbox-control/src/read-snapshots.ts index f422767f59a..3b2cedae064 100644 --- a/cloud/apps/sandbox-control/src/read-snapshots.ts +++ b/cloud/apps/sandbox-control/src/read-snapshots.ts @@ -9,6 +9,7 @@ // the control plane at runtime chooses the recipient keys and drives the VM, so it is trusted not to // add its own key (same as relaying grant keys). Access mirrors canOpen at read time, and pruning // (removal, private, revoke) deletes wrapped keys at once, without the VM. +import { effectiveVisibility } from './team-sharing' import { z } from 'zod' import type { SandboxCaller } from './auth' import { ensureEntryPoints } from './golden-images' @@ -202,7 +203,7 @@ export async function readerKeysFor(db: D1Database, row: SandboxRow, now: number if (row.archived_at !== null) { return [] } - const team = row.visibility === 'team' + const team = effectiveVisibility(row) === 'team' const { results } = await db .prepare( `SELECT k.id, k.public_key FROM reader_keys k @@ -340,7 +341,7 @@ export async function captureReadSnapshot(deps: LifecycleDeps, row: SandboxRow, await deps.db.batch(statements) // The workspace may have been made private while sealing: re-apply the current rule. const current = await deps.db.prepare('SELECT * FROM sandboxes WHERE id = ?').bind(row.id).first() - if (current && current.visibility !== 'team') { + if (current && effectiveVisibility(current) !== 'team') { await pruneReadSnapshotToOwner(deps.db, current) } return done({ @@ -387,7 +388,7 @@ export async function readSnapshotTimes(db: D1Database, ids: readonly string[]): export async function getReadSnapshot(db: D1Database, caller: SandboxCaller, row: SandboxRow, keyId: string | null, now: number) { // Belt and braces over canOpen: a private workspace's snapshot opens only for its owner. - if (!canOpen(caller, row) || (row.visibility !== 'team' && !isOwner(caller, row))) { + if (!canOpen(caller, row) || (effectiveVisibility(row) !== 'team' && !isOwner(caller, row))) { throw new WorkspaceError('not_found') } if (!keyId || !KEY_ID.test(keyId)) { diff --git a/cloud/apps/sandbox-control/src/secrets.ts b/cloud/apps/sandbox-control/src/secrets.ts index 2d15240032f..b3c3f575638 100644 --- a/cloud/apps/sandbox-control/src/secrets.ts +++ b/cloud/apps/sandbox-control/src/secrets.ts @@ -13,7 +13,7 @@ import { createKeyring, type Keyring, type SealFormat, type SecretBinding } from import { createKekUnwrapper, SecretsKmsError } from './secrets-kms' import { AUTH_IAT_BACKDATE_MS } from './member-changes' import { BASE_URL_NAMES, baseUrlHost } from './provider-env' -import { isSharedWorkspace } from './shared-workspace' +import { isSharedWorkspace, sharedWorkspaceMode } from './shared-workspace' import type { SandboxRow } from './store' import { secretLog } from './secret-log' import { @@ -196,12 +196,15 @@ function repoOwner(accountId: string, repo: string): string { * never its owner's personal ones, the same rule as personal accounts (D13). Fails closed: only a row * known to be private counts as unshared. */ -export function ownersForSandbox(row: Pick) { +export function ownersForSandbox( + row: Pick, + shared: boolean = isSharedWorkspace(row) +) { const repo = normalizeRepo(row.repo_url) return { org: ORG_ACCOUNT.test(row.account_id) ? row.account_id : null, // The one definition of "shared" (visibility, or ever transferred to another owner). - personal: isSharedWorkspace(row) ? null : personalOwner(row.user_id, row.account_id.startsWith('dev:')), + personal: shared ? null : personalOwner(row.user_id, row.account_id.startsWith('dev:')), repo: repo ? repoOwner(row.account_id, repo) : null } } @@ -362,7 +365,7 @@ export async function resolveSandboxSecrets( keyring: Keyring, row: Pick ): Promise { - const owners = ownersForSandbox(row) + const owners = ownersForSandbox(row, await sharedWorkspaceMode(db, row)) const pairs: [SecretScope, string][] = [] if (owners.personal) { pairs.push(['personal', owners.personal]) diff --git a/cloud/apps/sandbox-control/src/share-links.ts b/cloud/apps/sandbox-control/src/share-links.ts index 014a7feb970..b0cdc510564 100644 --- a/cloud/apps/sandbox-control/src/share-links.ts +++ b/cloud/apps/sandbox-control/src/share-links.ts @@ -5,6 +5,7 @@ // DELETE /v1/sandboxes/:id/shares/:shareId -> {share} // POST /v1/shares/:token/visit -> {url} (team-only: a one-time sign-in URL for this viewer) // The public side is src/share-gateway.ts. +import { devOnly } from './dev-only' import { auditSession } from './api/audit' import { z } from 'zod' import type { SandboxCaller } from './auth' @@ -77,7 +78,7 @@ export function shareSecrets(env: Env): string[] | null { * from SHARE_HOST_SUFFIX (a separate registrable domain). */ export function sharePathMode(env: Env): boolean { - return env.SHARE_PATH_MODE === 'on' || (env.SHARE_PATH_MODE !== 'off' && env.SANDBOX_ENV !== 'prod') + return env.SHARE_PATH_MODE === 'on' || (env.SHARE_PATH_MODE !== 'off' && devOnly(env)) } export function shareState(link: ShareLinkRow, now: number): ShareState { diff --git a/cloud/apps/sandbox-control/src/shared-workspace.ts b/cloud/apps/sandbox-control/src/shared-workspace.ts index 8fc679ec56d..be2ff1e910d 100644 --- a/cloud/apps/sandbox-control/src/shared-workspace.ts +++ b/cloud/apps/sandbox-control/src/shared-workspace.ts @@ -1,6 +1,7 @@ // What counts as a shared workspace when deciding whose credentials a session may carry. One // definition, used by secrets, agent accounts, the egress proxy and the member git rules. import type { SandboxRow } from './store' +import { teamSharingEnabled } from './team-sharing' /** * D13: a workspace shared with teammates never uses a personal account. Fails closed: only a row @@ -12,3 +13,43 @@ import type { SandboxRow } from './store' export function isSharedWorkspace(row: Pick): boolean { return row.visibility !== 'private' || row.ownership_transferred_at != null } + +/** + * The rule above, precisely, for callers that can read the database (all of them today). TEAM-SHARING hold: a + * workspace stored as `team` acts private while sharing is held, but keeps shared mode until no one but its + * owner holds a device grant on it (the hold's sweep revokes them, grants.ts sweepHeldTeamGrants), and none was + * revoked during the current session (what a teammate started there may still run): personal credentials never + * reach a VM a teammate may still be paired to or running in. Fails closed on a failed read. + */ +export async function sharedWorkspaceMode( + db: D1Database, + row: Pick +): Promise { + if (row.ownership_transferred_at != null) { + return true + } + if (row.visibility !== 'private' && (teamSharingEnabled() || row.visibility !== 'team')) { + return true + } + // Private, or `team` while held: shared only while a teammate's grant is live or was revoked this session + // (Make private and the hold's sweep alike). + // Review M1: a revoke closes a teammate's connections, not what they left running in this session's + // terminals. A grant revoked during the current session keeps it shared until the next boot. + // The session start is read here, not from the caller's row (which may be a partial or older copy). A revoke + // queued while the workspace slept (no session) counts for nothing: the next boot applies it before orcad + // accepts a sign-in, and that boot's processes are all new, so its session can be private. Its revoked_at + // is when it was queued (revokeGrants; markRevoked keeps it), so it never reads as "revoked this session". + // Unknown (null) falls back to the apply time there. + const others = await db + .prepare( + `SELECT COUNT(*) AS n FROM workspace_grants g JOIN sandboxes s ON s.id = g.sandbox_id WHERE g.sandbox_id = ? AND g.user_id <> ? + AND (g.status IN ('issuing', 'active') + OR (g.status = 'revoking' AND s.session_started_at IS NOT NULL) + OR (s.session_started_at IS NOT NULL AND g.revoked_at IS NOT NULL AND g.revoked_at >= s.session_started_at))` + ) + .bind(row.id, row.user_id) + .first<{ n: number }>() + .catch(() => null) + return !others || others.n > 0 +} + diff --git a/cloud/apps/sandbox-control/src/team-sharing.ts b/cloud/apps/sandbox-control/src/team-sharing.ts new file mode 100644 index 00000000000..6b83a46c540 --- /dev/null +++ b/cloud/apps/sandbox-control/src/team-sharing.ts @@ -0,0 +1,21 @@ +// TEAM-SHARING hold: team workspace sharing ships in a later release. TEAM_SHARING=on turns it on; anything else +// (the default) holds it. While held, a workspace stored as `team` acts private everywhere access is decided +// (owner only, plus org admins' metadata as before): the column and its data stay, so turning it on restores +// each workspace's own setting. Set from the Worker's env at the start of every request and scheduled run (the +// same value for the whole isolate: no per-request state). +import type { SandboxRow } from './store' + +let enabled = false + +export function configureTeamSharing(env: { TEAM_SHARING?: string }): void { + enabled = env.TEAM_SHARING === 'on' +} + +export function teamSharingEnabled(): boolean { + return enabled +} + +/** The visibility access rules use: the stored one with sharing on, else always private. */ +export function effectiveVisibility(row: Pick): 'private' | 'team' { + return enabled && row.visibility === 'team' ? 'team' : 'private' +} diff --git a/cloud/apps/sandbox-control/src/workspace-follows.ts b/cloud/apps/sandbox-control/src/workspace-follows.ts index 77c494d0716..aec5435a764 100644 --- a/cloud/apps/sandbox-control/src/workspace-follows.ts +++ b/cloud/apps/sandbox-control/src/workspace-follows.ts @@ -6,6 +6,7 @@ // visible to the whole team). A private workspace's only viewer is its owner, so a teammate's old // follow of a workspace that turned private is never shown and never counts. Archived workspaces // may still be followed: they stay browsable. +import { effectiveVisibility } from './team-sharing' import type { SandboxCaller } from './auth' import type { SandboxRow } from './store' @@ -42,7 +43,7 @@ export function visibleFollowers( if (!seen) { return [] } - return row.visibility === 'team' ? [...followers] : followers.filter((id) => id === row.user_id) + return effectiveVisibility(row) === 'team' ? [...followers] : followers.filter((id) => id === row.user_id) } /** The caller must be able to see the row (the route checks canSee first). */ diff --git a/cloud/apps/sandbox-control/src/workspaces.ts b/cloud/apps/sandbox-control/src/workspaces.ts index 11e593c4ea1..84a92810ccc 100644 --- a/cloud/apps/sandbox-control/src/workspaces.ts +++ b/cloud/apps/sandbox-control/src/workspaces.ts @@ -9,6 +9,7 @@ // Access rule: a workspace is visible to its owner, and to every member of the owning org when // visibility is `team`. Org owners/admins additionally see private rows' metadata (scope=all) so a // departed member's workspaces can be reassigned or archived — metadata only, never access. +import { effectiveVisibility, teamSharingEnabled } from './team-sharing' import { githubActingViews, type GithubActingOptions, type GithubActingView } from './git-actor' import type { TeamMembershipCheck } from './team-membership' import { z } from 'zod' @@ -63,7 +64,7 @@ export function canSee(caller: SandboxCaller, row: SandboxRow): boolean { if (row.account_id !== caller.accountId || row.status === 'destroyed') { return false } - return row.user_id === caller.userId || (row.visibility === 'team' && caller.orgId !== undefined) + return row.user_id === caller.userId || (effectiveVisibility(row) === 'team' && caller.orgId !== undefined) } /** Can the caller pair a device with it (grant) or keep it awake (lease)? */ @@ -231,7 +232,8 @@ export async function workspaceViews( // The link to copy: org slug + number when both exist, else the sandbox id form. link: workspaceLink(row, slug), repo: repoView(row), - visibility: row.visibility, + // TEAM-SHARING hold: what access actually follows (stored `team` reads private while held). + visibility: effectiveVisibility(row), section: row.section, archivedAt: row.archived_at, createdBy: row.created_by ?? row.user_id, @@ -315,6 +317,8 @@ export async function listWorkspaces(db: D1Database, caller: SandboxCaller, url: ]) return { workspaces: views.map((view, i) => ({ ...view, routineName: routineNames.get(rows[i]!.id) ?? null })), + // TEAM-SHARING hold: whether workspaces can be shared with the team on this control plane (older ones omit it). + teamSharing: teamSharingEnabled(), // Home: offer the Routine runs switch only when the team has routines, and say what it hides // (its count and hours still belong in the team's totals). routineRuns: { @@ -393,6 +397,10 @@ export async function patchWorkspace( if (patch.archived === true) { throw new WorkspaceError('invalid_request', 'archive_via_lifecycle') } + if (patch.visibility === 'team' && !teamSharingEnabled()) { + // TEAM-SHARING hold (team-sharing.ts): sharing with the team isn't available yet. + throw new WorkspaceError('invalid_request', 'team_sharing_unavailable') + } if (patch.visibility === 'team' && !row.account_id.includes('org:')) { // A personal account has no team to share with. throw new WorkspaceError('invalid_request', 'personal_account') diff --git a/cloud/apps/sandbox-control/test/dev-billing-enforce.test.ts b/cloud/apps/sandbox-control/test/dev-billing-enforce.test.ts index cb6fe0cce19..1aa8d4d5f13 100644 --- a/cloud/apps/sandbox-control/test/dev-billing-enforce.test.ts +++ b/cloud/apps/sandbox-control/test/dev-billing-enforce.test.ts @@ -42,12 +42,12 @@ describe('SANDBOX_DEV_BILLING_ENFORCE_PREFIX', () => { expect(devBillingEnforcePrefix({ SANDBOX_ENV: 'dev', SANDBOX_DEV_BILLING_ENFORCE_PREFIX: 'dev:billing-test-' })).toBe('dev:billing-test-') }) - it('outside dev, dev accounts keep the plain bypass even with the prefix set (prod sends everything to billing anyway)', async () => { + it('outside dev/local/test (staging, prod) there is no dev-account bypass at all: everything goes to billing', async () => { const { client, seen } = billing() const staging = withDevAccountBypass({ SANDBOX_ENV: 'staging', SANDBOX_DEV_BILLING_ENFORCE_PREFIX: 'dev:billing-test-' } as Env, client) - expect(await staging.checkStart(start('dev:billing-test-alice'))).toMatchObject({ allow: true }) + await staging.checkStart(start('dev:billing-test-alice')) const prod = withDevAccountBypass({ SANDBOX_ENV: 'prod', SANDBOX_DEV_BILLING_ENFORCE_PREFIX: 'dev:billing-test-' } as Env, client) expect(await prod.checkStart(start('user:bob'))).toMatchObject({ allow: false }) - expect(seen).toEqual(['user:bob']) + expect(seen).toEqual(['dev:billing-test-alice', 'user:bob']) }) }) diff --git a/cloud/apps/sandbox-control/test/dev-seed-gate.test.ts b/cloud/apps/sandbox-control/test/dev-seed-gate.test.ts new file mode 100644 index 00000000000..8c540ea37f2 --- /dev/null +++ b/cloud/apps/sandbox-control/test/dev-seed-gate.test.ts @@ -0,0 +1,43 @@ +// The dev GitHub seed route stores any installation token as a member's GitHub user token: it must not exist +// outside dev/local/test, whatever else is configured. +import { describe, expect, it } from 'vitest' +import { devOnly } from '../src/dev-only' +import { createHarness } from './harness' + +const OP = 'o'.repeat(40) + +describe('dev member-github seed route gate', () => { + it('is an allowlist: only dev, local and test', () => { + for (const env of ['dev', 'local', 'test']) { + expect(devOnly({ SANDBOX_ENV: env })).toBe(true) + } + for (const env of ['prod', 'staging', '', 'Dev', 'production', 'dev ', undefined as unknown as string]) { + expect(devOnly({ SANDBOX_ENV: env })).toBe(false) + } + }) + + it('answers 404 in staging and prod even with the operator token, and stores nothing', async () => { + for (const SANDBOX_ENV of ['staging', 'prod']) { + const h = await createHarness({ SANDBOX_ENV, OPERATOR_TOKEN: OP, SECRETS_KEK: Buffer.alloc(32, 7).toString('base64') }) + const seeded = await h.call('POST', '/v1/internal/dev/member-github', { + bearer: OP, + body: { accountId: 'org:acme', userId: 'alice', repoUrl: 'https://github.com/acme/app', login: 'alice-gh', githubUserId: 11, name: 'A' } + }) + expect(seeded.status).toBe(404) + expect(h.raw.prepare('SELECT COUNT(*) AS n FROM github_user_tokens').get()).toEqual({ n: 0 }) + } + }) + + it('the other dev-only routes are gone in staging too (seed, dev connect, codex login, manifest)', async () => { + const h = await createHarness({ SANDBOX_ENV: 'staging', OPERATOR_TOKEN: OP }) + for (const [method, path] of [ + ['POST', '/v1/internal/dev/codex-login'], + ['GET', '/v1/github/dev-connect'], + ['GET', '/v1/github/dev-user-connect'], + ['GET', '/v1/github/manifest-start'] + ] as const) { + expect((await h.call(method, path, { bearer: OP, body: method === 'POST' ? {} : undefined })).status, path).toBe(404) + } + }) +}) + diff --git a/cloud/apps/sandbox-control/test/egress-swap-fail-closed.test.ts b/cloud/apps/sandbox-control/test/egress-swap-fail-closed.test.ts index ba3d696efae..6721dd73711 100644 --- a/cloud/apps/sandbox-control/test/egress-swap-fail-closed.test.ts +++ b/cloud/apps/sandbox-control/test/egress-swap-fail-closed.test.ts @@ -142,9 +142,9 @@ describe('EGRESS-SWAP-FAIL-CLOSED', () => { const missing = await setup({ SANDBOX_ENV: 'staging' }) expect(await missing.h.call('GET', '/v1/health')).toEqual({ status: 503, body: { error: 'egress_proxy_missing', keySwap: 'off' } }) const present = await setup({ SANDBOX_ENV: 'staging', EGRESS_PROXY_URL: 'https://sandbox.test/v1/egress/proxy' }) - expect(await present.h.call('GET', '/v1/health')).toEqual({ status: 200, body: { ok: true, keySwap: 'on' } }) + expect(await present.h.call('GET', '/v1/health')).toEqual({ status: 200, body: { ok: true, keySwap: 'on', environment: 'staging' } }) const local = await setup({ SANDBOX_ENV: 'test' }) - expect(await local.h.call('GET', '/v1/health')).toEqual({ status: 200, body: { ok: true, keySwap: 'off' } }) + expect(await local.h.call('GET', '/v1/health')).toEqual({ status: 200, body: { ok: true, keySwap: 'off', environment: 'test' } }) }) it('a respond route compiles to a matched direct response, before the trailing deny', () => { diff --git a/cloud/apps/sandbox-control/test/fake-vercel.ts b/cloud/apps/sandbox-control/test/fake-vercel.ts index 1a9d242373f..e0ba48aff0b 100644 --- a/cloud/apps/sandbox-control/test/fake-vercel.ts +++ b/cloud/apps/sandbox-control/test/fake-vercel.ts @@ -1,5 +1,6 @@ // In-memory Vercel Sandbox with the behaviours the bake-off measured: stop = reboot from an automatic // snapshot, resume keeps the name and route, and delete leaves automatic snapshots behind. +import { DROP_SOLO_SCRIPT } from '../src/lifecycle' import { createCipheriv, createPublicKey, diffieHellman, generateKeyPairSync, hkdfSync, randomBytes } from 'node:crypto' import { GRANT_COMMAND } from '../src/grants' import { REVOKE_COMMAND } from '../src/grant-revokes' @@ -408,6 +409,10 @@ export function createFakeVercel(now: () => number): FakeVercel { } return { exitCode: 0, stdout: 'synced\n', stderr: '' } } + // GH-SOLO: dropping the one-person mark before a grant (rm -f: always succeeds in a VM). + if (script === DROP_SOLO_SCRIPT) { + return { exitCode: 0, stdout: '', stderr: '' } + } if (params.command === DRAIN_COMMAND) { return { exitCode: 0, stdout: '', stderr: '' } } diff --git a/cloud/apps/sandbox-control/test/gh-solo-member.test.ts b/cloud/apps/sandbox-control/test/gh-solo-member.test.ts new file mode 100644 index 00000000000..eefc020fa8d --- /dev/null +++ b/cloud/apps/sandbox-control/test/gh-solo-member.test.ts @@ -0,0 +1,148 @@ +// GH-SOLO regression (orca-plugins#89): in a workspace only one person can use, the server acts as that person +// (memberMayAct), but the VM picked a member only from an attested sender. Codex typed into directly in a +// terminal has none, so gh and git went out as the bot. Now the VM acts as the solo member with no sender too. +import { execFileSync, spawnSync } from 'node:child_process' +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterEach, describe, expect, it } from 'vitest' +import { generateGrantRecipientKey } from '../../../../src/main/cloud-workspaces/sealed-grant-node' +import { GRANT_COMMAND } from '../src/grants' +import { DROP_SOLO_SCRIPT, MEMBERS_COMMAND } from '../src/lifecycle' +import { soloMember } from '../src/member-git' +import { getSandbox } from '../src/store' +import { createHarness } from './harness' + +const IDENTITY = fileURLToPath(new URL('../image/vm/orca-git-identity', import.meta.url).href) +const dirs: string[] = [] +afterEach(() => dirs.splice(0).forEach((dir) => rmSync(dir, { recursive: true, force: true }))) + +/** orca-git-identity as root would run it, against a scratch members dir, with no orcad (so no attested sender). */ +function identity(members: { solo?: string; files: Record }, env: Record = {}) { + const root = mkdtempSync(join(tmpdir(), 'orca-git-solo-')) + dirs.push(root) + const dir = join(root, 'members') + mkdirSync(dir) + mkdirSync(join(root, 'bin')) + for (const [name, email] of Object.entries(members.files)) { + execFileSync('git', ['config', '-f', join(dir, `${name}.gitconfig`), 'user.email', email]) + } + if (members.solo) { + writeFileSync(join(dir, 'solo'), `${members.solo}\n`) + } + // `sudo -u mktemp` and `pgrep` stand-ins: no orcad runs here. + writeFileSync(join(root, 'bin/sudo'), '#!/usr/bin/env bash\nshift 2\nexec "$@"\n') + writeFileSync(join(root, 'bin/pgrep'), '#!/usr/bin/env bash\nexit 1\n') + chmodSync(join(root, 'bin/sudo'), 0o755) + chmodSync(join(root, 'bin/pgrep'), 0o755) + const script = join(root, 'orca-git-identity') + writeFileSync(script, readFileSync(IDENTITY, 'utf8').replace('DIR=/etc/orca/members', `DIR=${dir}`)) + const run = spawnSync('bash', [script], { env: { PATH: `${join(root, 'bin')}:/usr/bin:/bin`, SUDO_USER: 'vercel-sandbox', ...env }, encoding: 'utf8' }) + const out = run.stdout.trim() + return { status: run.status, stderr: run.stderr, email: run.status === 0 ? execFileSync('git', ['config', '-f', out, 'user.email'], { encoding: 'utf8' }).trim() : null } +} + +describe('orca-git-identity in a one-person workspace', () => { + it('acts as the solo member with no attested sender (a TUI typed into directly)', () => { + expect(identity({ solo: 'user_neil', files: { user_neil: '1+neil@users.noreply.github.com' } })).toMatchObject({ status: 0, email: '1+neil@users.noreply.github.com' }) + expect(identity({ solo: 'user_neil', files: { user_neil: '1+neil@users.noreply.github.com' } }, { ORCA_GIT_AS: 'user_neil' }).status).toBe(0) + }) + + it('never for anyone else, and not at all once the workspace is shared (no solo mark)', () => { + const other = identity({ solo: 'user_neil', files: { user_neil: '1+neil@users.noreply.github.com' } }, { ORCA_GIT_AS: 'user_bob' }) + expect(other.status).toBe(4) + expect(identity({ files: { user_neil: '1+neil@users.noreply.github.com' } }).status).toBe(3) + // A mark naming someone with no identity installed: the workspace identity. + expect(identity({ solo: 'user_ghost', files: {} }).status).toBe(3) + }) +}) + +const OP = 'o'.repeat(40) +const REPO = 'https://github.com/acme/app' + +async function workspace(extra: Record = {}) { + const h = await createHarness( + { EGRESS_PROXY_URL: 'https://sandbox.test/v1/egress/proxy', SECRETS_KEK: Buffer.alloc(32, 7).toString('base64'), OPERATOR_TOKEN: OP, ...extra }, + { + credentials: { authorizationFor: async () => 'Bearer ghs_app' }, + github: { tokenForRepo: async () => ({ token: 'ghs_repo', expiresAt: h.now() + 3_600_000 }), installationForRepo: async () => null } as never + } + ) + const as = (sub: string) => h.token(sub, 'acme', 'sandbox', { org_role: 'member' }) + const created = await h.call('POST', '/v1/sandboxes', { bearer: await as('alice'), body: { workspaceId: 'ws-1', machineSize: 'standard', repo: { url: REPO }, visibility: 'team' } }) + const id = created.body.sandbox.id as string + const connect = (userId: string, githubUserId: number) => + h.call('POST', '/v1/internal/dev/member-github', { bearer: OP, body: { accountId: 'org:acme', userId, repoUrl: REPO, login: `${userId}-gh`, githubUserId, name: userId } }) + const grant = async (userId: string) => + h.call('POST', `/v1/team/workspaces/${id}/grants`, { + bearer: await as(userId), + body: { recipientPublicKeyB64: generateGrantRecipientKey().publicKeyB64, deviceLabel: userId, deviceKind: 'desktop' } + }) + const syncs = () => h.vercel.commands.filter((c) => c.command === MEMBERS_COMMAND) + const restart = async () => expect((await h.call('POST', `/v1/sandboxes/${id}/restart`, { bearer: await as('alice') })).status).toBe(200) + return { h, as, id, connect, grant, syncs, restart } +} + +describe('the control plane marks a workspace solo only while one person can use it', () => { + it('sends ORCA_SOLO_MEMBER for the owner alone; drops the mark before pairing anyone else, then sends none', async () => { + const t = await workspace() + await t.connect('alice', 11) + await t.restart() + expect(t.syncs().at(-1)!.env.ORCA_SOLO_MEMBER).toBe('alice') + const before = t.h.vercel.commands.length + expect((await t.grant('bob')).status).toBe(200) + const after = t.h.vercel.commands.slice(before) + const drop = after.findIndex((c) => c.command === 'bash' && c.args?.includes(DROP_SOLO_SCRIPT)) + const pair = after.findIndex((c) => c.command === GRANT_COMMAND) + expect(drop).toBeGreaterThanOrEqual(0) + expect(drop).toBeLessThan(pair) + expect(t.syncs().at(-1)!.env.ORCA_SOLO_MEMBER).toBeUndefined() + }) + + it('review HIGH: shared with the cap off, a grantee who sent last is never marked solo (the owner has no grant row)', async () => { + const t = await workspace({ MEMBER_GIT_SHARED_MAX_MINUTES: '0' }) + await t.connect('alice', 11) + await t.connect('bob', 22) + expect((await t.grant('bob')).status).toBe(200) + expect((await t.h.call('POST', `/v1/team/workspaces/${t.id}/sent`, { bearer: await t.as('bob') })).status).toBe(200) + await t.restart() + expect(t.syncs().at(-1)!.env.ORCA_SOLO_MEMBER).toBeUndefined() + expect(await soloMember(t.h.env.SANDBOX_DB, (await getSandbox(t.h.env.SANDBOX_DB, t.id))!)).toBeNull() + }) + + it('review medium: a grant that starts while the members write is in flight drops the mark again after it', async () => { + const t = await workspace() + await t.connect('alice', 11) + // Bob's grant row appears (issuing) between the sync's read and its VM write. + t.h.vercel.commandHandler = (params) => { + if (params.command === MEMBERS_COMMAND) { + t.h.raw + .prepare(`INSERT INTO workspace_grants (id, sandbox_id, account_id, user_id, device_kind, device_label, status, created_at) VALUES ('grt_race', ?, 'org:acme', 'bob', 'desktop', 'b', 'issuing', 1)`) + .run(t.id) + return { exitCode: 0, stdout: '{"members":1,"devices":0}\n', stderr: '' } + } + return undefined + } + const before = t.h.vercel.commands.length + await t.restart() + const after = t.h.vercel.commands.slice(before) + const write = after.findIndex((c) => c.command === MEMBERS_COMMAND && c.env.ORCA_SOLO_MEMBER === 'alice') + const drop = after.findIndex((c, i) => i > write && c.command === 'bash' && c.args?.includes(DROP_SOLO_SCRIPT)) + expect(write).toBeGreaterThanOrEqual(0) + expect(drop).toBeGreaterThan(write) + }) + + it('a teammate whose grant is still being revoked (device not yet unpaired) keeps it from being solo', async () => { + const t = await workspace() + await t.connect('alice', 11) + t.h.raw + .prepare(`INSERT INTO workspace_grants (id, sandbox_id, account_id, user_id, device_kind, device_label, status, created_at) VALUES ('grt_out', ?, 'org:acme', 'bob', 'desktop', 'b', 'revoking', 1)`) + .run(t.id) + const row = (await getSandbox(t.h.env.SANDBOX_DB, t.id))! + expect(await soloMember(t.h.env.SANDBOX_DB, row)).toBeNull() + t.h.raw.prepare(`UPDATE workspace_grants SET status = 'revoked' WHERE id = 'grt_out'`).run() + expect(await soloMember(t.h.env.SANDBOX_DB, row)).toBe('alice') + }) +}) + diff --git a/cloud/apps/sandbox-control/test/harness.ts b/cloud/apps/sandbox-control/test/harness.ts index 82f28179479..cf1a90fad23 100644 --- a/cloud/apps/sandbox-control/test/harness.ts +++ b/cloud/apps/sandbox-control/test/harness.ts @@ -61,6 +61,8 @@ export async function createHarness(overrides: Partial = {}, extraDeps: Par VERCEL_PROJECT_ID: 'prj_orca', // Off unless a test turns it on (auto-environments.test.ts): it starts builds behind creates. AUTO_ENVIRONMENTS: 'off', + // Team sharing is on for the suite (its behavior is what most team tests cover); test/team-sharing-hold.test.ts holds it. + TEAM_SHARING: 'on', ...overrides } // No live github.com from tests: repos count as public unless a test says otherwise. diff --git a/cloud/apps/sandbox-control/test/member-git.test.ts b/cloud/apps/sandbox-control/test/member-git.test.ts index bf36f109e56..365ac39dabb 100644 --- a/cloud/apps/sandbox-control/test/member-git.test.ts +++ b/cloud/apps/sandbox-control/test/member-git.test.ts @@ -240,7 +240,7 @@ describe('GIT-ACTOR: githubActing and you on the workspace view (list and detail }) as D1Database const row = (await getSandbox(db, t.id))! // Four rows of the same owner (ids differ): a list of any size. - const results = [row, ...[1, 2, 3].map((n) => ({ ...row, id: `${row.id.slice(0, -1)}${n}` }))] + const results = [row, ...[1, 2, 3].map((n) => ({ ...row, id: `${row.id}-copy${n}` }))] const options = { enabled: () => true, sharedMaxMs: 60 * 60_000 } const views = await githubActingViews(counting, results as never, 'alice', t.h.now(), options) expect([...views.values()].map((v) => v.githubActing)).toEqual(Array(4).fill({ actingAs: 'member', userId: 'alice', login: 'alice-gh' })) diff --git a/cloud/apps/sandbox-control/test/team-sharing-hold.test.ts b/cloud/apps/sandbox-control/test/team-sharing-hold.test.ts new file mode 100644 index 00000000000..b22a34ae84c --- /dev/null +++ b/cloud/apps/sandbox-control/test/team-sharing-hold.test.ts @@ -0,0 +1,212 @@ +// TEAM-SHARING hold (team-sharing.ts): with TEAM_SHARING off, nothing can be shared with the team, and a +// workspace already stored as `team` acts private everywhere (owner only, plus org admins' metadata). +import { describe, expect, it } from 'vitest' +import { generateGrantRecipientKey } from '../../../../src/main/cloud-workspaces/sealed-grant-node' +import { sweepHeldTeamGrants } from '../src/grants' +import { lifecycleDeps } from '../src/index' +import { resolveSandboxSecrets } from '../src/secrets' +import { sharedWorkspaceMode } from '../src/shared-workspace' +import { getSandbox } from '../src/store' +import { configureTeamSharing } from '../src/team-sharing' +import { createHarness } from './harness' + +async function held(teamSharing: 'off' | undefined = 'off') { + const h = await createHarness({ PUBLIC_API_URL: 'https://api.test', ...(teamSharing ? { TEAM_SHARING: teamSharing } : { TEAM_SHARING: undefined }) }) + const token = (sub: string, role: 'member' | 'admin' = 'member') => h.token(sub, 'acme', 'sandbox', { org_role: role }) + const created = await h.call('POST', '/v1/sandboxes', { + bearer: await token('alice'), + body: { workspaceId: 'ws-1', machineSize: 'standard', title: 'Fix login', repo: { url: 'https://github.com/acme/app' }, visibility: 'team' } + }) + expect(created.status).toBe(200) + return { h, token, id: created.body.sandbox.id as string } +} + +describe('TEAM_SHARING held (the default)', () => { + it('a create asking for team is private, a PATCH to team is refused, and the list says sharing is off', async () => { + for (const setting of ['off', undefined] as const) { + const t = await held(setting) + expect(t.h.raw.prepare('SELECT visibility FROM sandboxes WHERE id = ?').get(t.id)).toEqual({ visibility: 'private' }) + const patch = await t.h.call('PATCH', `/v1/team/workspaces/${t.id}`, { bearer: await t.token('alice'), body: { visibility: 'team' } }) + expect(patch.status).toBe(400) + expect(patch.body).toEqual({ error: 'invalid_request', reason: 'team_sharing_unavailable' }) + const list = await t.h.call('GET', '/v1/team/workspaces', { bearer: await t.token('alice') }) + expect(list.body.teamSharing).toBe(false) + // Other edits still work, and making it private is always allowed. + expect((await t.h.call('PATCH', `/v1/team/workspaces/${t.id}`, { bearer: await t.token('alice'), body: { visibility: 'private', section: 'Auth' } })).status).toBe(200) + } + }) + + it('a workspace already stored as team acts private: owner only, admins see metadata, teammates nothing', async () => { + const t = await held() + t.h.raw.prepare("UPDATE sandboxes SET visibility = 'team' WHERE id = ?").run(t.id) + const bob = await t.token('bob') + // Team registry: not listed, not addressable, no grant, no follow. + expect((await t.h.call('GET', '/v1/team/workspaces?scope=team', { bearer: bob })).body.workspaces).toEqual([]) + expect((await t.h.call('GET', `/v1/team/workspaces/${t.id}`, { bearer: bob })).status).toBe(404) + const grant = await t.h.call('POST', `/v1/team/workspaces/${t.id}/grants`, { + bearer: bob, + body: { recipientPublicKeyB64: generateGrantRecipientKey().publicKeyB64, deviceLabel: 'b', deviceKind: 'desktop' } + }) + expect(grant.status).toBe(404) + expect((await t.h.call('PUT', `/v1/team/workspaces/${t.id}/follow`, { bearer: bob })).status).toBe(404) + // Public API and MCP's rule (api/access.ts): nothing for a teammate. + expect((await t.h.call('GET', '/v1/workspaces', { bearer: bob })).body.workspaces).toEqual([]) + expect((await t.h.call('GET', `/v1/workspaces/${t.id}`, { bearer: bob })).status).toBe(404) + expect((await t.h.call('POST', `/v1/workspaces/${t.id}/messages`, { bearer: bob, body: { text: 'hi' } })).status).toBe(404) + // The owner sees it as private (what access follows); the stored value is kept for when sharing ships. + const own = await t.h.call('GET', `/v1/team/workspaces/${t.id}`, { bearer: await t.token('alice') }) + expect(own.body.workspace).toMatchObject({ visibility: 'private', access: 'owner' }) + expect(own.body.teamSharing).toBe(false) + expect(t.h.raw.prepare('SELECT visibility FROM sandboxes WHERE id = ?').get(t.id)).toEqual({ visibility: 'team' }) + // An admin keeps today's management view (scope=all metadata), not the teammate view. + const admin = await t.token('carol', 'admin') + const all = await t.h.call('GET', '/v1/team/workspaces?scope=all', { bearer: admin }) + expect(all.body.workspaces.map((w: { id: string; visibility: string; access: string }) => [w.id, w.visibility, w.access])).toEqual([[t.id, 'private', 'none']]) + expect((await t.h.call('GET', '/v1/team/workspaces?scope=team', { bearer: admin })).body.workspaces).toEqual([]) + }) + + it('TEAM_SHARING=on restores each workspace’s own setting', async () => { + const h = await createHarness() + const alice = await h.token('alice', 'acme', 'sandbox', { org_role: 'member' }) + const created = await h.call('POST', '/v1/sandboxes', { + bearer: alice, + body: { workspaceId: 'ws-1', machineSize: 'standard', repo: { url: 'https://github.com/acme/app' }, visibility: 'team' } + }) + const bob = await h.token('bob', 'acme', 'sandbox', { org_role: 'member' }) + const list = await h.call('GET', '/v1/team/workspaces?scope=team', { bearer: bob }) + expect(list.body.teamSharing).toBe(true) + expect(list.body.workspaces.map((w: { id: string; visibility: string }) => [w.id, w.visibility])).toEqual([[created.body.sandbox.id, 'team']]) + }) + + it('the sweep revokes teammates’ grants on a held team workspace; credentials stay shared until it has', async () => { + // Shared while sharing was on: Bob holds a device grant. + const h = await createHarness({ SECRETS_KEK: Buffer.alloc(32, 7).toString('base64') }) + const alice = await h.token('alice', 'acme', 'sandbox', { org_role: 'member' }) + const created = await h.call('POST', '/v1/sandboxes', { + bearer: alice, + body: { workspaceId: 'ws-1', machineSize: 'standard', repo: { url: 'https://github.com/acme/app' }, visibility: 'team' } + }) + const id = created.body.sandbox.id as string + const grant = await h.call('POST', `/v1/team/workspaces/${id}/grants`, { + bearer: await h.token('bob', 'acme', 'sandbox', { org_role: 'member' }), + body: { recipientPublicKeyB64: generateGrantRecipientKey().publicKeyB64, deviceLabel: 'b', deviceKind: 'desktop' } + }) + expect(grant.status).toBe(200) + // Now held. + h.env.TEAM_SHARING = undefined + configureTeamSharing(h.env) + const db = h.env.SANDBOX_DB + const row = (await getSandbox(db, id))! + // Bob's grant is still active: shared mode (no personal credentials), though it acts private. + expect(await sharedWorkspaceMode(db, row)).toBe(true) + expect((await h.call('PUT', '/v1/secrets/personal/MY_TOKEN', { bearer: alice, body: { value: 'personal-value' } })).status).toBe(200) + const life = (await lifecycleDeps(h.env, h.deps))! + const keyring = await life.secrets!.keyring + expect((await resolveSandboxSecrets(db, keyring, row)).env.MY_TOKEN).toBeUndefined() + expect(await sweepHeldTeamGrants(life)).toEqual({ workspaces: 1, revoked: 1, queued: 0 }) + expect(h.raw.prepare('SELECT status, revoke_reason FROM workspace_grants WHERE user_id = ?').get('bob')).toEqual({ status: 'revoked', revoke_reason: 'team_sharing_held' }) + // Review M1: revoked during this session, so what Bob started may still run: shared until the next boot. + expect(await sharedWorkspaceMode(db, row)).toBe(true) + expect((await resolveSandboxSecrets(db, keyring, row)).env.MY_TOKEN).toBeUndefined() + // A new session (restart): the owner's alone, so it acts private for credentials too. + h.advance(1_000) + expect((await h.call('POST', `/v1/sandboxes/${id}/restart`, { bearer: alice })).status).toBe(200) + expect(await sharedWorkspaceMode(db, row)).toBe(false) + expect((await resolveSandboxSecrets(db, keyring, row)).env.MY_TOKEN).toBe('personal-value') + // Nothing left to sweep; and with sharing on again, nothing is swept at all. + expect(await sweepHeldTeamGrants(life)).toEqual({ workspaces: 0, revoked: 0, queued: 0 }) + configureTeamSharing({ TEAM_SHARING: 'on' }) + expect(await sharedWorkspaceMode(db, row)).toBe(true) + }) + + it('review L1: the sweep leaves private workspaces alone', async () => { + const t = await held() + t.h.raw + .prepare(`INSERT INTO workspace_grants (id, sandbox_id, account_id, user_id, device_kind, device_label, status, created_at) VALUES ('grt_p', ?, 'org:acme', 'bob', 'desktop', 'b', 'active', 1)`) + .run(t.id) + expect(await sweepHeldTeamGrants((await lifecycleDeps(t.h.env, t.h.deps))!)).toEqual({ workspaces: 0, revoked: 0, queued: 0 }) + }) + + it('review L2: concurrent sweeps revoke each grant once and agree on the end state', async () => { + const h = await createHarness() + const alice = await h.token('alice', 'acme', 'sandbox', { org_role: 'member' }) + const created = await h.call('POST', '/v1/sandboxes', { + bearer: alice, + body: { workspaceId: 'ws-1', machineSize: 'standard', repo: { url: 'https://github.com/acme/app' }, visibility: 'team' } + }) + const id = created.body.sandbox.id as string + for (const who of ['bob', 'dan']) { + const g = await h.call('POST', `/v1/team/workspaces/${id}/grants`, { + bearer: await h.token(who, 'acme', 'sandbox', { org_role: 'member' }), + body: { recipientPublicKeyB64: generateGrantRecipientKey().publicKeyB64, deviceLabel: who, deviceKind: 'desktop' } + }) + expect(g.status).toBe(200) + } + h.env.TEAM_SHARING = undefined + configureTeamSharing(h.env) + const life = (await lifecycleDeps(h.env, h.deps))! + const [a, b] = await Promise.all([sweepHeldTeamGrants(life), sweepHeldTeamGrants(life)]) + expect(a.revoked + a.queued + b.revoked + b.queued).toBeGreaterThanOrEqual(2) + expect(h.raw.prepare(`SELECT user_id, status, revoke_reason FROM workspace_grants WHERE user_id <> 'alice' ORDER BY user_id`).all()).toEqual([ + { user_id: 'bob', status: 'revoked', revoke_reason: 'team_sharing_held' }, + { user_id: 'dan', status: 'revoked', revoke_reason: 'team_sharing_held' } + ]) + expect(await sweepHeldTeamGrants(life)).toEqual({ workspaces: 0, revoked: 0, queued: 0 }) + }) +}) + +describe('Make private keeps shared credential mode until the next boot (same rule as the sweep)', () => { + it('a teammate revoked by Make private leaves this session shared; a fresh boot is private', async () => { + const h = await createHarness({ SECRETS_KEK: Buffer.alloc(32, 7).toString('base64') }) + const alice = await h.token('alice', 'acme', 'sandbox', { org_role: 'member' }) + const created = await h.call('POST', '/v1/sandboxes', { + bearer: alice, + body: { workspaceId: 'ws-1', machineSize: 'standard', repo: { url: 'https://github.com/acme/app' }, visibility: 'team' } + }) + const id = created.body.sandbox.id as string + const g = await h.call('POST', `/v1/team/workspaces/${id}/grants`, { + bearer: await h.token('bob', 'acme', 'sandbox', { org_role: 'member' }), + body: { recipientPublicKeyB64: generateGrantRecipientKey().publicKeyB64, deviceLabel: 'b', deviceKind: 'desktop' } + }) + expect(g.status).toBe(200) + expect((await h.call('PATCH', `/v1/team/workspaces/${id}`, { bearer: alice, body: { visibility: 'private' } })).status).toBe(200) + const db = h.env.SANDBOX_DB + expect(h.raw.prepare('SELECT status FROM workspace_grants WHERE user_id = ?').get('bob')).toEqual({ status: 'revoked' }) + const row = (await getSandbox(db, id))! + expect(row.visibility).toBe('private') + expect(await sharedWorkspaceMode(db, row)).toBe(true) + h.advance(1_000) + expect((await h.call('POST', `/v1/sandboxes/${id}/restart`, { bearer: alice })).status).toBe(200) + expect(await sharedWorkspaceMode(db, (await getSandbox(db, id))!)).toBe(false) + }) + + it('a revoke queued while the workspace slept leaves its next session private (no lost sign-in after the deploy sweep)', async () => { + const h = await createHarness({ SECRETS_KEK: Buffer.alloc(32, 7).toString('base64') }) + const alice = await h.token('alice', 'acme', 'sandbox', { org_role: 'member' }) + const created = await h.call('POST', '/v1/sandboxes', { + bearer: alice, + body: { workspaceId: 'ws-1', machineSize: 'standard', repo: { url: 'https://github.com/acme/app' }, visibility: 'team' } + }) + const id = created.body.sandbox.id as string + const g = await h.call('POST', `/v1/team/workspaces/${id}/grants`, { + bearer: await h.token('bob', 'acme', 'sandbox', { org_role: 'member' }), + body: { recipientPublicKeyB64: generateGrantRecipientKey().publicKeyB64, deviceLabel: 'b', deviceKind: 'desktop' } + }) + expect(g.status).toBe(200) + expect((await h.call('POST', `/v1/sandboxes/${id}/suspend`, { bearer: alice })).status).toBe(200) + h.env.TEAM_SHARING = undefined + configureTeamSharing(h.env) + const life = (await lifecycleDeps(h.env, h.deps))! + // Asleep: queued, not applied. + expect(await sweepHeldTeamGrants(life)).toEqual({ workspaces: 1, revoked: 0, queued: 1 }) + const db = h.env.SANDBOX_DB + const queuedAt = (h.raw.prepare('SELECT revoked_at FROM workspace_grants WHERE user_id = ?').get('bob') as { revoked_at: number }).revoked_at + expect(await sharedWorkspaceMode(db, (await getSandbox(db, id))!)).toBe(false) + h.advance(60_000) + expect((await h.call('POST', `/v1/sandboxes/${id}/resume`, { bearer: alice })).status).toBe(200) + // Applied at boot, still stamped with the queue time; the new session is private. + expect(h.raw.prepare('SELECT status, revoked_at FROM workspace_grants WHERE user_id = ?').get('bob')).toEqual({ status: 'revoked', revoked_at: queuedAt }) + expect(await sharedWorkspaceMode(db, (await getSandbox(db, id))!)).toBe(false) + }) +}) + diff --git a/cloud/apps/sandbox-control/wrangler.jsonc b/cloud/apps/sandbox-control/wrangler.jsonc index 327708bb86c..950ce833820 100644 --- a/cloud/apps/sandbox-control/wrangler.jsonc +++ b/cloud/apps/sandbox-control/wrangler.jsonc @@ -24,7 +24,8 @@ }, "triggers": { "crons": ["*/5 * * * *"] }, "vars": { - "SANDBOX_ENV": "local", + // No SANDBOX_ENV here: a config copied from this one that forgets to set it leaves every dev-only route and + // behavior off (dev-only.ts). `pnpm dev` passes SANDBOX_ENV=local itself. "SANDBOX_JWT_AUDIENCE": "orca-sandbox", "VERCEL_REGION": "pdx1", "VERCEL_FALLBACK_REGIONS": "iad1", diff --git a/src/main/cloud-sync/cloud-sync-fake-vm.test-support.ts b/src/main/cloud-sync/cloud-sync-fake-vm.test-support.ts index d86923f54f2..c57650dabc0 100644 --- a/src/main/cloud-sync/cloud-sync-fake-vm.test-support.ts +++ b/src/main/cloud-sync/cloud-sync-fake-vm.test-support.ts @@ -6,8 +6,6 @@ import type { SyncCall } from './cloud-sync-remote' const ParamsSchema = z.looseObject({ relativePath: z.string().optional(), relativePaths: z.array(z.string()).optional(), - candidatePaths: z.array(z.string()).optional(), - includeIgnored: z.boolean().optional(), offset: z.number().optional(), length: z.number().optional() }) @@ -17,7 +15,6 @@ export const VM_ROOT = '/vercel/sandbox/project' export type FakeVm = { files: Map - ignored: Set calls: string[] statManySupported: boolean asleep: boolean @@ -36,13 +33,11 @@ function codeError(code: string, message = code): Error { export function createFakeVm(): FakeVm { const files = new Map() - const ignored = new Set() const calls: string[] = [] const watches = new Set<(event: unknown) => void>() let clock = 1_000 const vm: FakeVm = { files, - ignored, calls, statManySupported: true, asleep: false, @@ -92,16 +87,6 @@ export function createFakeVm(): FakeVm { } return [...names].map(([name, isDirectory]) => ({ name, isDirectory, isSymlink: false })) } - case 'files.listAll': { - const candidates = p.candidatePaths - return [...files.keys()].filter( - (path) => - // Like orcad: gitignored files are listed unless includeIgnored is false. - (p.includeIgnored !== false || !ignored.has(path)) && - !path.startsWith('.context/') && - (!candidates || candidates.includes(path)) - ) - } case 'files.statMany': { if (!vm.statManySupported) { throw codeError('method_not_found', 'Unknown method: files.statMany') diff --git a/src/main/cloud-sync/cloud-sync-ipc.ts b/src/main/cloud-sync/cloud-sync-ipc.ts index 111bbf6cfd1..30df68d0ba2 100644 --- a/src/main/cloud-sync/cloud-sync-ipc.ts +++ b/src/main/cloud-sync/cloud-sync-ipc.ts @@ -125,18 +125,15 @@ export function installCloudSync( ipcMain.handle(CH.getState, (_event, workspaceId: unknown) => typeof workspaceId === 'string' ? sync.getState(workspaceId) : null ) - ipcMain.handle( - CH.setChoice, - (_event, args: { workspaceId?: unknown; context?: unknown; mirror?: unknown }) => { - if (typeof args?.workspaceId !== 'string') { - return null - } - return sync.setChoice(args.workspaceId, { - ...(typeof args.context === 'boolean' ? { context: args.context } : {}), - ...(typeof args.mirror === 'boolean' ? { mirror: args.mirror } : {}) - }) + ipcMain.handle(CH.setChoice, (_event, args: { workspaceId?: unknown; context?: unknown }) => { + if (typeof args?.workspaceId !== 'string') { + return null } - ) + return sync.setChoice( + args.workspaceId, + typeof args.context === 'boolean' ? { context: args.context } : {} + ) + }) ipcMain.handle(CH.openFolder, (_event, workspaceId: unknown) => typeof workspaceId === 'string' ? sync.openFolder(workspaceId) : { ok: false } ) diff --git a/src/main/cloud-sync/cloud-sync-local-copy.ts b/src/main/cloud-sync/cloud-sync-local-copy.ts index 0aa26661193..4436ec2af9a 100644 --- a/src/main/cloud-sync/cloud-sync-local-copy.ts +++ b/src/main/cloud-sync/cloud-sync-local-copy.ts @@ -1,12 +1,12 @@ // A workspace's copy on this computer as a whole: where it is (from the runtime record), what -// removing it would take with it, and removing it (archive, delete, both rows off). +// removing it would take with it, and removing it (archive, delete, sync turned off). import { rm, rmdir } from 'node:fs/promises' import { basename, join } from 'node:path' import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes' import { getEphemeralVmRecipeResultConnection } from '../../shared/ephemeral-vm-recipes' import type { CloudSyncRemovalPreview } from '../../shared/cloud-sync/cloud-sync-contract' import { localStatAt, removeCopies } from './cloud-sync-local-writes' -import { SYNC_TEMP_DIR, cloudSyncFolder, isContextPath } from './cloud-sync-paths' +import { SYNC_TEMP_DIR, cloudSyncFolder } from './cloud-sync-paths' import { isLocalCopyEdited } from './cloud-sync-plan' import type { CloudSyncStore } from './cloud-sync-store' @@ -74,20 +74,6 @@ export async function removeLocalCopy( await store.removeIndex(workspaceId) } -/** Mirror turned off while asleep: the mirrored files go now (they'd only get staler). */ -export async function removeMirroredFiles( - store: CloudSyncStore, - workspaceId: string, - folder: string -): Promise { - const index = await store.readIndex(workspaceId, folder) - const outside = Object.keys(index.entries).filter((path) => !isContextPath(path)) - if (outside.length > 0) { - await removeCopies(folder, outside, index.entries) - await store.writeIndex(workspaceId, index) - } -} - export async function previewRemoval( store: CloudSyncStore, workspaceId: string, diff --git a/src/main/cloud-sync/cloud-sync-paths.ts b/src/main/cloud-sync/cloud-sync-paths.ts index 9fe0630749e..baa46d579a9 100644 --- a/src/main/cloud-sync/cloud-sync-paths.ts +++ b/src/main/cloud-sync/cloud-sync-paths.ts @@ -48,7 +48,7 @@ export function displayPath(path: string, home: string = homedir()): string { } /** - * A cloud-relative path that is safe to mirror: forward slashes, no empty/`.`/`..` segments, no + * A cloud-relative path that is safe to copy here: forward slashes, no empty/`.`/`..` segments, no * absolute or drive paths, no control characters, never inside `.git` or this sync's temp dir. */ export function isSafeSyncPath(path: string): boolean { diff --git a/src/main/cloud-sync/cloud-sync-plan.ts b/src/main/cloud-sync/cloud-sync-plan.ts index 1566af16d5d..18e6f00853e 100644 --- a/src/main/cloud-sync/cloud-sync-plan.ts +++ b/src/main/cloud-sync/cloud-sync-plan.ts @@ -21,8 +21,8 @@ export type IndexEntry = { export type LocalStat = { size: number; mtimeMs: number } | null -/** Which rows are on for a workspace (this member's choice on this computer). */ -export type CloudSyncChoice = { context: boolean; mirror: boolean } +/** Whether `.context` sync is on for a workspace (this member's choice on this computer). */ +export type CloudSyncChoice = { context: boolean } export type SyncLimits = { maxFiles: number @@ -30,25 +30,16 @@ export type SyncLimits = { maxFileBytes: number } -// Decimal units, as the window shows them ("2.0 GB", "100 MB"). +// Decimal units, as the window shows them ("250 MB", "50 MB"). export const CONTEXT_LIMITS: SyncLimits = { maxFiles: 5_000, maxBytes: 250_000_000, maxFileBytes: 50_000_000 } -export const MIRROR_LIMITS: SyncLimits = { - maxFiles: 100_000, - maxBytes: 2_000_000_000, - maxFileBytes: 100_000_000 -} -export function limitsFor(choice: CloudSyncChoice): SyncLimits { - return choice.mirror ? MIRROR_LIMITS : CONTEXT_LIMITS -} - -export function limitsInfo(choice: CloudSyncChoice): CloudSyncLimitsInfo { - const limits = limitsFor(choice) - return { maxBytes: limits.maxBytes, maxFileBytes: limits.maxFileBytes } +export const CONTEXT_LIMITS_INFO: CloudSyncLimitsInfo = { + maxBytes: CONTEXT_LIMITS.maxBytes, + maxFileBytes: CONTEXT_LIMITS.maxFileBytes } export function emptySyncState( @@ -69,7 +60,7 @@ export function emptySyncState( editedHere: 0, skippedLarge: 0, overLimit: 0, - limits: limitsInfo(choice), + limits: CONTEXT_LIMITS_INFO, error: null } } @@ -164,7 +155,7 @@ export function planSync(input: { /** * Safety net for anything the watch missed. The VM's watcher can miss a directory created along * with its parent (`mkdir -p .context/shots`), so small folders are re-checked often (a few - * calls each) and large mirrors less often: 30 ms per file, between 30 s and 10 min, and never + * calls each) and large ones less often: 30 ms per file, between 30 s and 10 min, and never * more than 5% of the time (a slow pass, e.g. on an image without files.statMany, waits longer). */ export const SAFETY_TICK_MS = 30_000 diff --git a/src/main/cloud-sync/cloud-sync-remote.ts b/src/main/cloud-sync/cloud-sync-remote.ts index 1da48c426a8..025d8a1241e 100644 --- a/src/main/cloud-sync/cloud-sync-remote.ts +++ b/src/main/cloud-sync/cloud-sync-remote.ts @@ -1,9 +1,9 @@ -// The cloud half of a sync pass, over the workspace's E2EE orcad connection: list what is in -// scope (gitignore-aware), stat it in batches, and page files down. Replies are validated, never +// The cloud half of a sync pass, over the workspace's E2EE orcad connection: walk `.context`, +// stat it in batches, and page files down. Replies are validated, never // trusted: the VM is not this process. import { z } from 'zod' import { FILE_STAT_MANY_MAX } from '../../shared/file-access/file-stat-many' -import { CONTEXT_DIR, isContextPath, isSafeSyncPath } from './cloud-sync-paths' +import { CONTEXT_DIR, isSafeSyncPath } from './cloud-sync-paths' import type { RemoteEntry } from './cloud-sync-plan' export type SyncCall = ( @@ -12,11 +12,8 @@ export type SyncCall = ( options?: { timeoutMs?: number; signal?: AbortSignal } ) => Promise -export type SyncScope = 'context' | 'workspace' - const LIST_TIMEOUT_MS = 60_000 const STAT_TIMEOUT_MS = 60_000 -const CANDIDATE_BATCH = 100 const FALLBACK_STAT_CONCURRENCY = 12 const CONTEXT_MAX_DEPTH = 8 @@ -66,7 +63,6 @@ const WorktreeRows = z.looseObject({ const DirEntries = z.array( z.looseObject({ name: z.string(), isDirectory: z.boolean(), isSymlink: z.boolean().optional() }) ) -const PathList = z.array(z.string()) const StatMany = z.object({ entries: z.array( z.union([ @@ -108,12 +104,12 @@ export async function resolveCloudWorktree( } /** Every regular file under `.context` (it is usually gitignored, so it is walked, not listed). */ -async function listContext( +export async function listContext( call: SyncCall, selector: string, maxFiles: number, signal?: AbortSignal -): Promise { +): Promise<{ paths: string[]; truncated: boolean }> { const out: string[] = [] const walk = async (dir: string, depth: number): Promise => { if (depth > CONTEXT_MAX_DEPTH || out.length >= maxFiles) { @@ -151,83 +147,7 @@ async function listContext( } } await walk(CONTEXT_DIR, 0) - return out -} - -/** Paths in scope: `.context` always; the whole workspace (minus .gitignore) for a mirror. */ -export async function listScope( - call: SyncCall, - selector: string, - scope: SyncScope, - maxFiles: number, - signal?: AbortSignal -): Promise<{ paths: string[]; truncated: boolean }> { - const context = await listContext(call, selector, maxFiles, signal) - if (scope === 'context') { - return { paths: context, truncated: context.length >= maxFiles } - } - const listed = PathList.parse( - await call( - 'files.listAll', - // Quick-open listing adds gitignored files unless told not to. - { worktree: selector, includeIgnored: false, maxResults: maxFiles + 1 }, - { timeoutMs: LIST_TIMEOUT_MS, signal } - ) - ) - const paths = new Set(context) - for (const path of listed) { - if (isSafeSyncPath(path) && !isContextPath(path)) { - paths.add(path) - } - } - const all = [...paths] - return { paths: all.slice(0, maxFiles), truncated: all.length > maxFiles } -} - -/** - * Of the changed paths a watch reported, the ones a mirror includes: `.context` always, others - * only when the cloud's listing (which honours .gitignore) still has them. - */ -export async function filterIncluded( - call: SyncCall, - selector: string, - scope: SyncScope, - paths: readonly string[], - signal?: AbortSignal -): Promise> { - const included = new Set() - const others: string[] = [] - for (const path of paths) { - if (!isSafeSyncPath(path)) { - continue - } - if (isContextPath(path)) { - included.add(path) - } else if (scope === 'workspace') { - others.push(path) - } - } - for (let i = 0; i < others.length; i += CANDIDATE_BATCH) { - const batch = others.slice(i, i + CANDIDATE_BATCH) - const listed = PathList.parse( - await call( - 'files.listAll', - { - worktree: selector, - includeIgnored: false, - candidatePaths: batch, - maxResults: batch.length - }, - { timeoutMs: LIST_TIMEOUT_MS, signal } - ) - ) - for (const path of listed) { - if (batch.includes(path)) { - included.add(path) - } - } - } - return included + return { paths: out, truncated: out.length >= maxFiles } } /** Hosts whose orcad predates `files.statMany` (an older sandbox image). */ diff --git a/src/main/cloud-sync/cloud-sync-service.test.ts b/src/main/cloud-sync/cloud-sync-service.test.ts index b4b32f432ce..6b1abf922df 100644 --- a/src/main/cloud-sync/cloud-sync-service.test.ts +++ b/src/main/cloud-sync/cloud-sync-service.test.ts @@ -1,4 +1,4 @@ -import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises' +import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' @@ -61,6 +61,7 @@ async function setup() { return { vm, service, + userData, folder, views, opened, @@ -82,7 +83,7 @@ describe('cloud sync service', () => { expect(await readFile(join(t.folder, '.context/plan.md'), 'utf8')).toBe('plan') const view = await t.service.getState('ws') expect(view).toMatchObject({ - choice: { context: true, mirror: false }, + choice: { context: true }, displayPath: '~/orca/cloud/Hello-World/my-ws/.context' }) await t.service.openFolder('ws') @@ -90,15 +91,21 @@ describe('cloud sync service', () => { await t.service.dispose() }) - it('opens the workspace folder once the mirror is on', async () => { + it('loads a choice saved by an older build that also had a mirror field', async () => { const t = await setup() - await t.service.reconcile() - await t.synced() - const view = await t.service.setChoice('ws', { mirror: true }) - expect(view?.displayPath).toBe('~/orca/cloud/Hello-World/my-ws') - await vi.waitFor(async () => - expect(await readFile(join(t.folder, 'src/a.ts'), 'utf8')).toBe('a') + await mkdir(join(t.userData, 'orca-cloud-sync'), { recursive: true }) + await writeFile( + join(t.userData, 'orca-cloud-sync', 'choices.json'), + JSON.stringify({ version: 1, workspaces: { ws: { context: false, mirror: true } } }) ) + expect(await t.service.getState('ws')).toMatchObject({ + choice: { context: false }, + phase: 'off' + }) + const view = await t.service.setChoice('ws', { context: true }) + expect(view?.choice).toEqual({ context: true }) + await t.synced() + expect(await readFile(join(t.folder, '.context/plan.md'), 'utf8')).toBe('plan') await t.service.dispose() }) @@ -149,7 +156,7 @@ describe('cloud sync service', () => { await t.service.dispose() }) - it('turning both off removes the copy', async () => { + it('turning sync off removes the copy', async () => { const t = await setup() await t.service.reconcile() await t.synced() diff --git a/src/main/cloud-sync/cloud-sync-service.ts b/src/main/cloud-sync/cloud-sync-service.ts index 50aadbc7878..9ad1b06e053 100644 --- a/src/main/cloud-sync/cloud-sync-service.ts +++ b/src/main/cloud-sync/cloud-sync-service.ts @@ -13,11 +13,10 @@ import { cloudRuntimesFrom, previewRemoval, removeLocalCopy, - removeMirroredFiles, type CloudRuntime } from './cloud-sync-local-copy' import { CONTEXT_DIR, displayPath } from './cloud-sync-paths' -import { limitsInfo, type CloudSyncChoice } from './cloud-sync-plan' +import { CONTEXT_LIMITS_INFO, type CloudSyncChoice } from './cloud-sync-plan' import type { SyncCall } from './cloud-sync-remote' import { createCloudSyncSession, @@ -51,7 +50,7 @@ function idleState( workspaceId: runtime.workspaceId, choice, folder: runtime.folder, - phase: !choice.context && !choice.mirror ? 'off' : 'waiting', + phase: choice.context ? 'waiting' : 'off', files: previous?.files ?? 0, bytes: previous?.bytes ?? 0, progress: null, @@ -59,7 +58,7 @@ function idleState( editedHere: previous?.editedHere ?? 0, skippedLarge: previous?.skippedLarge ?? 0, overLimit: previous?.overLimit ?? 0, - limits: limitsInfo(choice), + limits: CONTEXT_LIMITS_INFO, error: null } } @@ -77,8 +76,7 @@ export function createCloudSyncService(deps: CloudSyncServiceDeps) { let disposed = false const viewOf = (state: CloudSyncState): CloudSyncView => { - const openPath = - state.choice.mirror || !state.choice.context ? state.folder : join(state.folder, CONTEXT_DIR) + const openPath = join(state.folder, CONTEXT_DIR) return { ...state, openPath, displayPath: displayPath(openPath, deps.home) } } @@ -175,7 +173,7 @@ export function createCloudSyncService(deps: CloudSyncServiceDeps) { continue } const choice = await deps.store.choice(runtime.workspaceId) - if (!runtime.running || (!choice.context && !choice.mirror)) { + if (!runtime.running || !choice.context) { await reconcileIdle(runtime, choice) continue } @@ -269,17 +267,12 @@ export function createCloudSyncService(deps: CloudSyncServiceDeps) { return null } const choice = await deps.store.setChoice(workspaceId, patch) - const session = sessions.get(workspaceId) - if (!choice.context && !choice.mirror) { + if (!choice.context) { await stopSession(workspaceId) await removeLocalCopy(deps.store, workspaceId, runtime.folder) - states.delete(workspaceId) - } else if (session) { - void session.session.setChoice(choice) - } else { - if (!choice.mirror) { - await removeMirroredFiles(deps.store, workspaceId, runtime.folder) - } + } + // A running session's state stands; otherwise the reconcile below starts one (or goes idle). + if (!sessions.has(workspaceId)) { states.delete(workspaceId) } await reconcile() diff --git a/src/main/cloud-sync/cloud-sync-session.test.ts b/src/main/cloud-sync/cloud-sync-session.test.ts index b0ccb436e98..1d61253b44d 100644 --- a/src/main/cloud-sync/cloud-sync-session.test.ts +++ b/src/main/cloud-sync/cloud-sync-session.test.ts @@ -14,7 +14,7 @@ afterEach(async () => { await Promise.all(dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))) }) -async function setup(vm: FakeVm, choice: CloudSyncChoice = { context: true, mirror: false }) { +async function setup(vm: FakeVm, choice: CloudSyncChoice = { context: true }) { const folder = await mkdtemp(join(tmpdir(), 'cloud-sync-folder-')) const userData = await mkdtemp(join(tmpdir(), 'cloud-sync-userdata-')) dirs.push(folder, userData) @@ -38,7 +38,7 @@ const settle = async (session: { resync: () => Promise }): Promise = } describe('cloud sync session', () => { - it('copies .context (gitignored, walked) read-only and leaves other files alone by default', async () => { + it('copies .context (gitignored, walked) read-only and nothing outside it', async () => { const vm = createFakeVm() vm.write('.context/plan.md', '# Plan') vm.write('.context/shots/one.png', 'PNG') @@ -53,21 +53,23 @@ describe('cloud sync session', () => { await session.stop() }) - it('mirrors the workspace minus .gitignore, then removes it when the mirror is turned off', async () => { + it('removes files outside .context that an older build copied', async () => { const vm = createFakeVm() vm.write('.context/plan.md', 'p') vm.write('src/index.ts', 'code') - vm.write('dist/bundle.js', 'built') - vm.ignored.add('dist/bundle.js') - const { folder, session, last } = await setup(vm, { context: true, mirror: true }) + const { folder, store, session } = await setup(vm) + const { mkdir } = await import('node:fs/promises') + await mkdir(join(folder, 'src')) + await writeFile(join(folder, 'src/index.ts'), 'code') + const copied = await stat(join(folder, 'src/index.ts')) + await store.writeIndex('ws', { + version: 1, + folder, + lastSyncedAt: 1, + entries: { 'src/index.ts': { rs: 4, rm: 1, ls: copied.size, lm: copied.mtimeMs } } + }) await session.start() - expect(await readFile(join(folder, 'src/index.ts'), 'utf8')).toBe('code') - await expect(stat(join(folder, 'dist/bundle.js'))).rejects.toThrow() - expect(last()).toMatchObject({ phase: 'synced', files: 2 }) - await session.setChoice({ context: true, mirror: false }) await expect(stat(join(folder, 'src/index.ts'))).rejects.toThrow() - // The emptied directory goes too; .context stays. - await expect(stat(join(folder, 'src'))).rejects.toThrow() expect(await readFile(join(folder, '.context/plan.md'), 'utf8')).toBe('p') await session.stop() }) @@ -75,16 +77,16 @@ describe('cloud sync session', () => { it('second pass is incremental: only changed files are read again', async () => { const vm = createFakeVm() for (let i = 0; i < 50; i++) { - vm.write(`src/f${i}.ts`, `v${i}`) + vm.write(`.context/f${i}.md`, `v${i}`) } - const { folder, session } = await setup(vm, { context: true, mirror: true }) + const { folder, session } = await setup(vm) await session.start() vm.calls.length = 0 - vm.write('src/f7.ts', 'changed') + vm.write('.context/f7.md', 'changed') await settle(session) expect(vm.calls.filter((method) => method === 'files.readChunk')).toHaveLength(1) expect(vm.calls.filter((method) => method === 'files.statMany')).toHaveLength(1) - expect(await readFile(join(folder, 'src/f7.ts'), 'utf8')).toBe('changed') + expect(await readFile(join(folder, '.context/f7.md'), 'utf8')).toBe('changed') await session.stop() }) @@ -220,7 +222,7 @@ describe('cloud sync session', () => { }) describe('safetyIntervalMs', () => { - it('re-checks small folders every 30 s and large mirrors at most every 10 min', () => { + it('re-checks small folders every 30 s and large ones at most every 10 min', () => { expect(safetyIntervalMs(0)).toBe(30_000) expect(safetyIntervalMs(21)).toBe(30_000) expect(safetyIntervalMs(2_000)).toBe(60_000) diff --git a/src/main/cloud-sync/cloud-sync-session.ts b/src/main/cloud-sync/cloud-sync-session.ts index 22cb63449e8..fbf1d59eb49 100644 --- a/src/main/cloud-sync/cloud-sync-session.ts +++ b/src/main/cloud-sync/cloud-sync-session.ts @@ -12,23 +12,21 @@ import { } from './cloud-sync-local-writes' import { isContextPath, isSafeSyncPath } from './cloud-sync-paths' import { + CONTEXT_LIMITS, + CONTEXT_LIMITS_INFO, emptySyncState, safetyIntervalMs, SAFETY_TICK_MS, - limitsFor, - limitsInfo, planSync, type LocalStat, type RemoteEntry } from './cloud-sync-plan' import { - filterIncluded, isWaitingError, - listScope, + listContext, resolveCloudWorktree, statFiles, - type SyncCall, - type SyncScope + type SyncCall } from './cloud-sync-remote' import type { CloudSyncChoice, CloudSyncIndex, CloudSyncStore } from './cloud-sync-store' import { @@ -59,7 +57,7 @@ export type CloudSyncSessionDeps = { export function createCloudSyncSession(deps: CloudSyncSessionDeps) { const now = deps.now ?? Date.now const log = (line: string): void => deps.log?.(`[cloud-sync] ${deps.workspaceId}: ${line}`) - let choice = deps.choice + const choice = deps.choice let stopped = false let worktree: { selector: string; root: string } | null = null let index: CloudSyncIndex | null = null @@ -80,12 +78,10 @@ export function createCloudSyncSession(deps: CloudSyncSessionDeps) { }) const publish = (patch: Partial): void => { - state = { ...state, ...patch, choice, limits: limitsInfo(choice) } + state = { ...state, ...patch, choice, limits: CONTEXT_LIMITS_INFO } deps.emit(state) } - const scope = (): SyncScope => (choice.mirror ? 'workspace' : 'context') - async function loadIndex(): Promise { index ??= await deps.store.readIndex(deps.workspaceId, deps.folder) if (index.lastSyncedAt !== null && state.lastSyncedAt === null) { @@ -141,11 +137,10 @@ export function createCloudSyncSession(deps: CloudSyncSessionDeps) { lastFullPassAt = now() const { selector } = await ensureWorktree() const current = await loadIndex() - const limits = limitsFor(choice) if (state.lastSyncedAt === null) { publish({ phase: 'starting', error: null }) } - const listed = await listScope(deps.call, selector, scope(), limits.maxFiles, abort.signal) + const listed = await listContext(deps.call, selector, CONTEXT_LIMITS.maxFiles, abort.signal) const remote = await statFiles(deps.call, selector, listed.paths, abort.signal) const paths = new Set([...remote.keys(), ...Object.keys(current.entries)]) // Manifest cost only (listing + stat), not the copying a first pass does. @@ -156,8 +151,8 @@ export function createCloudSyncSession(deps: CloudSyncSessionDeps) { async function incrementalPass(paths: string[]): Promise { const { selector } = await ensureWorktree() await loadIndex() - const included = await filterIncluded(deps.call, selector, scope(), paths, abort.signal) - const remote = await statFiles(deps.call, selector, [...included], abort.signal) + const included = paths.filter((path) => isSafeSyncPath(path) && isContextPath(path)) + const remote = await statFiles(deps.call, selector, included, abort.signal) await apply({ remote, paths: new Set(paths), scoped: new Set(paths), truncated: 0 }) } @@ -168,7 +163,7 @@ export function createCloudSyncSession(deps: CloudSyncSessionDeps) { truncated: number }): Promise { const current = index! - const limits = limitsFor(choice) + const limits = CONTEXT_LIMITS await mkdir(deps.folder, { recursive: true }) const local = new Map() for (const path of input.paths) { @@ -176,11 +171,9 @@ export function createCloudSyncSession(deps: CloudSyncSessionDeps) { local.set(path, await localStatAt(deps.folder, path)) } } - // Paths that left scope (mirror turned off) are removed like cloud deletions. + // Anything outside `.context` (copied by an older build) is removed like a cloud deletion. const remote = new Map( - [...input.remote].filter( - ([path]) => isSafeSyncPath(path) && (choice.mirror || isContextPath(path)) - ) + [...input.remote].filter(([path]) => isSafeSyncPath(path) && isContextPath(path)) ) const plan = planSync({ remote, @@ -232,7 +225,7 @@ export function createCloudSyncSession(deps: CloudSyncSessionDeps) { if (!worktree) { return } - const batch = readWatchEvent(event, worktree.root, choice.mirror) + const batch = readWatchEvent(event, worktree.root) if (batch.kind === 'ready') { watchRetryMs = WATCH_RETRY_MIN_MS } else if (batch.kind === 'rescan') { @@ -308,11 +301,6 @@ export function createCloudSyncSession(deps: CloudSyncSessionDeps) { void openWatch() return requestFullPass() }, - setChoice(next: CloudSyncChoice): Promise { - choice = next - publish({}) - return requestFullPass() - }, /** Stops syncing; the files stay (asleep). */ stop(): Promise { stopped = true diff --git a/src/main/cloud-sync/cloud-sync-store.ts b/src/main/cloud-sync/cloud-sync-store.ts index ce302beae7e..be26814ab66 100644 --- a/src/main/cloud-sync/cloud-sync-store.ts +++ b/src/main/cloud-sync/cloud-sync-store.ts @@ -9,14 +9,12 @@ import type { CloudSyncChoice, IndexEntry } from './cloud-sync-plan' export type { CloudSyncChoice } /** `.context` is small and holds what people come back for (plans, screenshots): on by default. */ -export const DEFAULT_SYNC_CHOICE: CloudSyncChoice = { context: true, mirror: false } +export const DEFAULT_SYNC_CHOICE: CloudSyncChoice = { context: true } const ChoicesSchema = z.object({ version: z.literal(1), - workspaces: z.record( - z.string(), - z.object({ context: z.boolean().optional(), mirror: z.boolean().optional() }) - ) + // z.object drops keys it doesn't name, so records saved by older builds still load. + workspaces: z.record(z.string(), z.object({ context: z.boolean().optional() })) }) const IndexEntrySchema = z.object({ @@ -66,10 +64,7 @@ export function createCloudSyncStore(userDataPath: string) { dir, async choice(workspaceId: string): Promise { const saved = (await loadChoices()).workspaces[workspaceId] - return { - context: saved?.context ?? DEFAULT_SYNC_CHOICE.context, - mirror: saved?.mirror ?? DEFAULT_SYNC_CHOICE.mirror - } + return { context: saved?.context ?? DEFAULT_SYNC_CHOICE.context } }, async setChoice( workspaceId: string, diff --git a/src/main/cloud-sync/cloud-sync-watch.ts b/src/main/cloud-sync/cloud-sync-watch.ts index e9c29e5408b..02d0bde2f76 100644 --- a/src/main/cloud-sync/cloud-sync-watch.ts +++ b/src/main/cloud-sync/cloud-sync-watch.ts @@ -1,4 +1,4 @@ -// The cloud's file watch, read for sync: which workspace paths changed, or that a rescan is +// The cloud's file watch, read for sync: which `.context` paths changed, or that a rescan is // needed (overflow, or a directory event that can stand for many files). Events come from the VM // and are validated like any other reply. import { z } from 'zod' @@ -28,7 +28,7 @@ export type WatchBatch = | { kind: 'paths'; paths: string[] } | { kind: 'none' } -export function readWatchEvent(event: unknown, root: string, mirror: boolean): WatchBatch { +export function readWatchEvent(event: unknown, root: string): WatchBatch { const parsed = WatchEventSchema.safeParse(event) if (!parsed.success) { return { kind: 'none' } @@ -50,7 +50,7 @@ export function readWatchEvent(event: unknown, root: string, mirror: boolean): W } for (const candidate of [change.data.absolutePath, change.data.oldAbsolutePath]) { const rel = relativeToRoot(root, candidate) - if (rel && isSafeSyncPath(rel) && (mirror || isContextPath(rel))) { + if (rel && isSafeSyncPath(rel) && isContextPath(rel)) { paths.push(rel) } } diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 9ab7dd93fad..41456890679 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -187,7 +187,7 @@ export type PreloadApi = { plainSsh?: PlainSshTerminalApi /** Desktop only: streams files and folders from a paired runtime host to this machine. */ runtimeDownloads?: RuntimeDownloadsApi - /** Desktop only: Orca Cloud workspace files synced to this computer (.context and the mirror). */ + /** Desktop only: an Orca Cloud workspace's `.context` folder synced to this computer. */ cloudSync?: CloudSyncApi /** Desktop only: the API keys Orca hands to agent launches. */ agentApiKeys?: AgentApiKeysApi diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacePeople.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacePeople.tsx index e0cd229b8fa..df98d083ffa 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacePeople.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacePeople.tsx @@ -1,6 +1,7 @@ // PARITY-FOLLOW: the people on the cloud workspace in front, beside its W-123 chip: its creator, // its followers and who is here now, then Follow. Nothing for a local workspace, a personal // account, or a workspace only you are on and nobody else could follow. +import { useCloudTeamSharingEnabled } from '@/lib/orca-cloud/cloud-team-sharing-flag' import React, { useState } from 'react' import { toast } from 'sonner' import { useAppStore } from '@/store' @@ -47,7 +48,9 @@ export function CloudWorkspacePeople({ const { directory } = useMemberDirectory(orgId ?? undefined, workspace ? [workspace] : []) // The live list row carries githubActing / you already. const actingLine = gitActingLine(workspace, t) - if (!workspace) { + // TEAM-SHARING-HOLD: followers and who's here only exist on a shared workspace. + const teamSharing = useCloudTeamSharingEnabled() + if (!workspace || !teamSharing) { return null } const following = followOffer(workspace, selfId) diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacePicker.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacePicker.tsx index cfba49b2cef..14870de4321 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacePicker.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacePicker.tsx @@ -1,5 +1,6 @@ // "Open cloud workspace…": cloud workspaces this computer's sidebar doesn't show, as the same rows // (and ⋯ menu) the team list had. Open goes through openCloudWorkspace and closes the picker. +import { cloudTeamSharingEnabled } from '@/lib/orca-cloud/cloud-team-sharing-flag' import React, { useCallback, useEffect, useMemo, useState } from 'react' import { RefreshCw, Search } from 'lucide-react' import { Button } from '@/components/ui/button' @@ -55,10 +56,16 @@ function pickerCopy( case 'open': return { title: t('components.cloudWorkspaces.picker.title', 'Open cloud workspace'), - description: t( - 'components.cloudWorkspaces.picker.description', - 'Cloud workspaces that aren’t in your sidebar: shared by teammates, or started on another computer.' - ) + // TEAM-SHARING-HOLD: nothing is shared by teammates while sharing is held. + description: cloudTeamSharingEnabled() + ? t( + 'components.cloudWorkspaces.picker.description', + 'Cloud workspaces that aren’t in your sidebar: shared by teammates, or started on another computer.' + ) + : t( + 'components.cloudWorkspaces.picker.descriptionOwn', + 'Your cloud workspaces that aren’t in your sidebar, such as ones started on another computer.' + ) } case 'teammate': return { diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.tsx index 450d133bab8..1970cc8c5c2 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.tsx @@ -1,5 +1,8 @@ import { CloudStatusGlyph } from '@/components/orca-cloud/CloudStatusGlyph' -import { cloudShareLinksEnabled } from '@/lib/orca-cloud/cloud-share-links-flag' +import { + cloudTeamSharingEnabled, + useCloudTeamSharingEnabled +} from '@/lib/orca-cloud/cloud-team-sharing-flag' import React, { useId, useState } from 'react' import { GitBranch, Loader2 } from 'lucide-react' import { Button } from '@/components/ui/button' @@ -113,6 +116,7 @@ export function CloudWorkspaceRow({ hours, defaultValue_one: '{{hours}} sandbox hour' }) + const teamSharing = useCloudTeamSharingEnabled() const lastActive = formatRelative(w.lastActivityAt, now, t, intlLocale) const presence = presenceSummary( presentMembers(w.presence, selfId), @@ -151,7 +155,7 @@ export function CloudWorkspaceRow({ return } if ( - cloudShareLinksEnabled() && + cloudTeamSharingEnabled() && keybindingMatchesAction( 'cloudWorkspace.copyLink', event.nativeEvent, @@ -272,12 +276,15 @@ export function CloudWorkspaceRow({ - actions.goToChat(w, member) : undefined} - /> + {/* TEAM-SHARING-HOLD: who's here only exists on a shared workspace. */} + {teamSharing ? ( + actions.goToChat(w, member) : undefined} + /> + ) : null} diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRowBadges.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRowBadges.tsx index f2f9528d2d8..05db2c73863 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRowBadges.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRowBadges.tsx @@ -1,5 +1,6 @@ // The small marks after a cloud workspace's title in Open cloud workspace…: private, started by a // routine, and its W-number (shown on hover or focus; its space is held so nothing shifts). +import { useCloudTeamSharingEnabled } from '@/lib/orca-cloud/cloud-team-sharing-flag' import React from 'react' import { CalendarClock, Lock } from 'lucide-react' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' @@ -23,9 +24,11 @@ export function CloudWorkspaceRowBadges({ }): React.JSX.Element { const t = useTranslate() const revealOpen = revealNumber + // TEAM-SHARING-HOLD: every workspace is private while sharing is held; no badge says so. + const teamSharing = useCloudTeamSharingEnabled() return ( <> - {w.visibility === 'private' && ( + {teamSharing && w.visibility === 'private' && ( state.keybindings) const copyShortcut = formatOptionalPrimaryShortcutLabel('cloudWorkspace.copyLink', keybindings) - const shareLinks = useCloudShareLinksEnabled() + const teamSharing = useCloudTeamSharingEnabled() // Read when the menu renders (it re-renders on open), not kept: focus moves between opens. const focused = open ? (actions.focusedItem?.(w) ?? null) : null const teammatesHere = canOpen @@ -187,8 +187,8 @@ export function CloudWorkspaceRowMenu({ ↵ )} - {/* SHARE-LINKS-HOLD: the Copy link items only while share links are on. */} - {shareLinks ? ( + {/* TEAM-SHARING-HOLD: share links only while team sharing is on. */} + {teamSharing ? ( actions.copyLink(w)}> {w.number @@ -199,7 +199,7 @@ export function CloudWorkspaceRowMenu({ {copyShortcut ? {copyShortcut} : null} ) : null} - {shareLinks && focused ? ( + {teamSharing && focused ? ( actions.copyWorkspaceLink(w)}> {focused === 'terminal' ? : } {focused === 'terminal' @@ -248,7 +248,8 @@ export function CloudWorkspaceRowMenu({ {canManage && ( <> - {w.visibility === 'private' ? ( + {/* TEAM-SHARING-HOLD: no Share with team / Make private while sharing is held. */} + {!teamSharing ? null : w.visibility === 'private' ? ( actions.patch(w, { visibility: 'team' })}> {t('auto.components.cloudWorkspaces.shareWithTeam', 'Share with team')} diff --git a/src/renderer/src/components/cloud-workspaces/cloud-workspace-action-groups.test.ts b/src/renderer/src/components/cloud-workspaces/cloud-workspace-action-groups.test.ts index bc9be09f8e6..6a385e44572 100644 --- a/src/renderer/src/components/cloud-workspaces/cloud-workspace-action-groups.test.ts +++ b/src/renderer/src/components/cloud-workspaces/cloud-workspace-action-groups.test.ts @@ -1,4 +1,10 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' +const teamSharing = vi.hoisted(() => ({ on: true })) +vi.mock('@/lib/orca-cloud/cloud-team-sharing-flag', () => ({ + CLOUD_SHARE_LINK_ACTION_ID: 'cloudWorkspace.copyLink', + cloudTeamSharingEnabled: () => teamSharing.on, + useCloudTeamSharingEnabled: () => teamSharing.on +})) import { cloudWorkspaceActionGroups, type CloudWorkspaceActionInput @@ -51,4 +57,20 @@ describe('one action list for every surface (JA-14)', () => { it('a teammate who cannot manage it only opens and copies links', () => { expect(flat({ canManage: false })).toEqual(['open:open,copyLink,copyWorkspaceLink']) }) + + it('TEAM-SHARING-HOLD: no Share with team or Make private while sharing is held', () => { + teamSharing.on = false + try { + for (const visibility of ['private', 'team'] as const) { + const actions = cloudWorkspaceActionGroups({ ...base, visibility }).flatMap( + (g) => g.actions + ) + expect(actions).not.toContain('share') + expect(actions).not.toContain('makePrivate') + expect(actions).toContain('archive') + } + } finally { + teamSharing.on = true + } + }) }) diff --git a/src/renderer/src/components/cloud-workspaces/cloud-workspace-action-groups.ts b/src/renderer/src/components/cloud-workspaces/cloud-workspace-action-groups.ts index 74745a7e3a0..1c952033d36 100644 --- a/src/renderer/src/components/cloud-workspaces/cloud-workspace-action-groups.ts +++ b/src/renderer/src/components/cloud-workspaces/cloud-workspace-action-groups.ts @@ -2,6 +2,7 @@ // workspace…" list's ⋯ menu and the sidebar's context menu both render these groups, in this order: // Open, Share, Lifecycle, Danger. Each surface leaves out only what it already shows elsewhere (the // sidebar row *is* the open workspace; the list has no local-only items) and never invents its own. +import { cloudTeamSharingEnabled } from '@/lib/orca-cloud/cloud-team-sharing-flag' import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' export type CloudWorkspaceAction = @@ -37,6 +38,8 @@ export type CloudWorkspaceActionInput = Pick< canRestart: boolean /** Teammates to hand it to (the list only). */ hasMembers?: boolean + /** TEAM-SHARING-HOLD: Share with team / Make private offered (default: the account's capability). */ + teamSharing?: boolean } export function cloudWorkspaceActionGroups( @@ -54,8 +57,10 @@ export function cloudWorkspaceActionGroups( open.push('copyWorkspaceLink') const share: CloudWorkspaceAction[] = [] - if (input.canManage) { + if (input.canManage && (input.teamSharing ?? cloudTeamSharingEnabled())) { share.push(input.visibility === 'private' ? 'share' : 'makePrivate') + } + if (input.canManage) { if (list && input.hasMembers) { share.push('reassignOwner') } diff --git a/src/renderer/src/components/cloud-workspaces/cloud-workspace-links.ts b/src/renderer/src/components/cloud-workspaces/cloud-workspace-links.ts index c94f69cc47f..bd67061be99 100644 --- a/src/renderer/src/components/cloud-workspaces/cloud-workspace-links.ts +++ b/src/renderer/src/components/cloud-workspaces/cloud-workspace-links.ts @@ -1,6 +1,6 @@ // App-level wiring for team cloud workspaces: orca://cloud links, presence for the workspace in // front, and the copy-link shortcut. Installed once from main.tsx; no React tree needed. -import { cloudShareLinksEnabled } from '@/lib/orca-cloud/cloud-share-links-flag' +import { cloudTeamSharingEnabled } from '@/lib/orca-cloud/cloud-team-sharing-flag' import { toast } from 'sonner' import { useAppStore } from '@/store' import { getShortcutPlatform } from '@/lib/keyboard/shortcut-platform' @@ -233,7 +233,7 @@ export function installCloudWorkspaceLinks(): () => void { const target = event.target instanceof HTMLElement ? event.target : null if ( !event.defaultPrevented && - cloudShareLinksEnabled() && + cloudTeamSharingEnabled() && !shortcutOwnedElsewhere(target) && keybindingMatchesAction( 'cloudWorkspace.copyLink', diff --git a/src/renderer/src/components/cloud-workspaces/cloud-workspace-picker-model.test.ts b/src/renderer/src/components/cloud-workspaces/cloud-workspace-picker-model.test.ts index a595804bdff..23f7deed7da 100644 --- a/src/renderer/src/components/cloud-workspaces/cloud-workspace-picker-model.test.ts +++ b/src/renderer/src/components/cloud-workspaces/cloud-workspace-picker-model.test.ts @@ -1,4 +1,10 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' +const teamSharing = vi.hoisted(() => ({ on: true })) +vi.mock('@/lib/orca-cloud/cloud-team-sharing-flag', () => ({ + CLOUD_SHARE_LINK_ACTION_ID: 'cloudWorkspace.copyLink', + cloudTeamSharingEnabled: () => teamSharing.on, + useCloudTeamSharingEnabled: () => teamSharing.on +})) import { initialPickerControls, pickerListQuery, @@ -110,4 +116,18 @@ describe('what the picker lists', () => { expect(rows(`W-${mine.number}`)).toEqual(['Mine here']) expect(rows('nothing like this')).toEqual([]) }) + + it('TEAM-SHARING-HOLD: no Team scope on a team while sharing is held; Open lists your own', () => { + teamSharing.on = false + try { + expect(initialPickerControls(true).scope).toBe('mine') + expect(pickerShowsScope({ kind: 'open' }, true)).toBe(false) + expect( + pickerListQuery({ kind: 'open' }, { scope: 'team', archived: false, search: '' }, true) + .scope + ).toBe('mine') + } finally { + teamSharing.on = true + } + }) }) diff --git a/src/renderer/src/components/cloud-workspaces/cloud-workspace-picker-model.ts b/src/renderer/src/components/cloud-workspaces/cloud-workspace-picker-model.ts index e8df9f74c0b..4a55f171a27 100644 --- a/src/renderer/src/components/cloud-workspaces/cloud-workspace-picker-model.ts +++ b/src/renderer/src/components/cloud-workspaces/cloud-workspace-picker-model.ts @@ -1,5 +1,6 @@ // What "Open cloud workspace…" reads and lists for each focus. Pure, so the rules are tested apart // from the dialog. +import { cloudTeamSharingEnabled } from '@/lib/orca-cloud/cloud-team-sharing-flag' import type { CloudWorkspace, CloudWorkspaceListQuery @@ -14,14 +15,22 @@ export type CloudWorkspacePickerControls = { search: string } +/** + * TEAM-SHARING-HOLD: with sharing held there is nothing of a teammate's to open, so "Open cloud + * workspace…" has no Team scope and lists your own. + */ +function teamScope(hasOrg: boolean): boolean { + return hasOrg && cloudTeamSharingEnabled() +} + export function initialPickerControls(hasOrg: boolean): CloudWorkspacePickerControls { // On a team, what you can't open from the sidebar is mostly what teammates shared. - return { scope: hasOrg ? 'team' : 'mine', archived: false, search: '' } + return { scope: teamScope(hasOrg) ? 'team' : 'mine', archived: false, search: '' } } /** Which controls the picker offers: a focused list (limit, teammate, team delete) is fixed. */ export function pickerShowsScope(focus: CloudWorkspacePickerFocus, hasOrg: boolean): boolean { - return focus.kind === 'open' && hasOrg + return focus.kind === 'open' && teamScope(hasOrg) } export function pickerShowsArchived(focus: CloudWorkspacePickerFocus): boolean { @@ -36,7 +45,7 @@ export function pickerListQuery( switch (focus.kind) { case 'open': return { - scope: hasOrg ? controls.scope : 'mine', + scope: teamScope(hasOrg) ? controls.scope : 'mine', archived: controls.archived ? 'only' : 'exclude' } case 'teammate': diff --git a/src/renderer/src/components/cloud-workspaces/cloud-workspace-share-link.test.ts b/src/renderer/src/components/cloud-workspaces/cloud-workspace-share-link.test.ts index 5c0737bc6a2..bbea34f22c5 100644 --- a/src/renderer/src/components/cloud-workspaces/cloud-workspace-share-link.test.ts +++ b/src/renderer/src/components/cloud-workspaces/cloud-workspace-share-link.test.ts @@ -5,8 +5,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const toasts = vi.hoisted(() => ({ success: vi.fn(), warning: vi.fn(), error: vi.fn() })) vi.mock('sonner', () => ({ toast: toasts })) const shareLinks = vi.hoisted(() => ({ on: true })) -vi.mock('@/lib/orca-cloud/cloud-share-links-flag', () => ({ - cloudShareLinksEnabled: () => shareLinks.on +vi.mock('@/lib/orca-cloud/cloud-team-sharing-flag', () => ({ + cloudTeamSharingEnabled: () => shareLinks.on })) import { copyCloudWorkspaceLink } from './cloud-workspace-share-link' diff --git a/src/renderer/src/components/cloud-workspaces/cloud-workspace-share-link.ts b/src/renderer/src/components/cloud-workspaces/cloud-workspace-share-link.ts index d488375eb9a..e29280b8e2e 100644 --- a/src/renderer/src/components/cloud-workspaces/cloud-workspace-share-link.ts +++ b/src/renderer/src/components/cloud-workspaces/cloud-workspace-share-link.ts @@ -1,5 +1,5 @@ // A cloud workspace's share link: the org slug + W-number link when known, else the sandbox-id form. -import { cloudShareLinksEnabled } from '@/lib/orca-cloud/cloud-share-links-flag' +import { cloudTeamSharingEnabled } from '@/lib/orca-cloud/cloud-team-sharing-flag' import { toast } from 'sonner' import { translate } from '@/i18n/i18n' import { @@ -49,7 +49,7 @@ export async function copyCloudWorkspaceLink( options: { quiet?: boolean } = {} ): Promise { // SHARE-LINKS-HOLD: nothing is copied while share links are held. - if (!cloudShareLinksEnabled()) { + if (!cloudTeamSharingEnabled()) { return false } const link = await shareLinkFor(id, chatId) diff --git a/src/renderer/src/components/cloud-workspaces/open-cloud-workspace-copy-link.test.ts b/src/renderer/src/components/cloud-workspaces/open-cloud-workspace-copy-link.test.ts index b0fc7e11ef4..2f9aa360039 100644 --- a/src/renderer/src/components/cloud-workspaces/open-cloud-workspace-copy-link.test.ts +++ b/src/renderer/src/components/cloud-workspaces/open-cloud-workspace-copy-link.test.ts @@ -3,8 +3,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const toast = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() })) vi.mock('sonner', () => ({ toast })) const shareLinks = vi.hoisted(() => ({ on: true })) -vi.mock('@/lib/orca-cloud/cloud-share-links-flag', () => ({ - cloudShareLinksEnabled: () => shareLinks.on +vi.mock('@/lib/orca-cloud/cloud-team-sharing-flag', () => ({ + cloudTeamSharingEnabled: () => shareLinks.on })) import { copyCloudWorkspaceLink, shareLinkFor } from './open-cloud-workspace' diff --git a/src/renderer/src/components/local-commands/LocalCommandApprovalDialog.tsx b/src/renderer/src/components/local-commands/LocalCommandApprovalDialog.tsx index 93718c828fa..26523be47aa 100644 --- a/src/renderer/src/components/local-commands/LocalCommandApprovalDialog.tsx +++ b/src/renderer/src/components/local-commands/LocalCommandApprovalDialog.tsx @@ -1,4 +1,5 @@ import { useCallback, useEffect, useRef, useState } from 'react' +import { useCloudTeamSharingEnabled } from '@/lib/orca-cloud/cloud-team-sharing-flag' import { TriangleAlert } from 'lucide-react' import { toast } from 'sonner' import { Button } from '@/components/ui/button' @@ -54,6 +55,7 @@ export function LocalCommandApprovalDialogView({ /** Denies this request and turns local commands off for the workspace. */ onTurnOff: () => void }): React.JSX.Element { + const teamSharing = useCloudTeamSharingEnabled() const t = useTranslate() // A long command must be scrolled to its end before it can be allowed: nothing stays out of view. const [readToEnd, setReadToEnd] = useState(false) @@ -164,7 +166,8 @@ export function LocalCommandApprovalDialogView({ )}

) : null} - {prompt.shared ? ( + {/* TEAM-SHARING-HOLD: no teammates can message while sharing is held. */} + {prompt.shared && teamSharing ? (

{t( 'localCommands.prompt.shared', diff --git a/src/renderer/src/components/local-commands/local-command-sharing-hold.test.tsx b/src/renderer/src/components/local-commands/local-command-sharing-hold.test.tsx new file mode 100644 index 00000000000..0c9e3ce2426 --- /dev/null +++ b/src/renderer/src/components/local-commands/local-command-sharing-hold.test.tsx @@ -0,0 +1,67 @@ +// @vitest-environment happy-dom +// TEAM-SHARING-HOLD: the approval dialog says nothing about teammates while team sharing is held. +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, describe, expect, it, vi } from 'vitest' + +const teamSharing = vi.hoisted(() => ({ on: false })) +vi.mock('@/lib/orca-cloud/cloud-team-sharing-flag', () => ({ + cloudTeamSharingEnabled: () => teamSharing.on, + useCloudTeamSharingEnabled: () => teamSharing.on +})) + +import { Dialog } from '@/components/ui/dialog' +import { TooltipProvider } from '@/components/ui/tooltip' +import { LocalCommandApprovalDialogView } from './LocalCommandApprovalDialog' + +globalThis.IS_REACT_ACT_ENVIRONMENT = true +let root: Root | null = null +afterEach(async () => { + await act(async () => root?.unmount()) + root = null + document.body.innerHTML = '' +}) + +async function show(): Promise { + const container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) + const prompt = { + requestId: 'r1', + workspace: 'web', + command: 'ls -la', + cwd: '/tmp', + shared: true, + timeoutSeconds: 120 + } + await act(async () => + root!.render( + +

+ {}} + onTurnOff={() => {}} + /> + + + ) + ) + return document.body.textContent ?? '' +} + +describe('the teammates note on a local command request', () => { + it('held: no mention of teammates', async () => { + teamSharing.on = false + expect(await show()).not.toContain('Teammates share this workspace') + }) + + it('sharing on: says a teammate may have led to it', async () => { + teamSharing.on = true + expect(await show()).toContain('Teammates share this workspace') + }) +}) diff --git a/src/renderer/src/components/orca-cloud/CloudWorkspaceCard.fixture.tsx b/src/renderer/src/components/orca-cloud/CloudWorkspaceCard.fixture.tsx index 62bcb3e81e4..952d25f7bb4 100644 --- a/src/renderer/src/components/orca-cloud/CloudWorkspaceCard.fixture.tsx +++ b/src/renderer/src/components/orca-cloud/CloudWorkspaceCard.fixture.tsx @@ -78,21 +78,21 @@ const entry = (status: HostedWorkspaceStatus): CloudStatusEntry => ({ }) const FOLDER = '/Users/me/orca/cloud/Hello-World/fix-login-redirect' -function syncView(id: string, mirror: boolean, empty = false): CloudSyncView { - const openPath = mirror ? FOLDER : `${FOLDER}/.context` +function syncView(id: string, empty = false): CloudSyncView { + const openPath = `${FOLDER}/.context` return { workspaceId: id, - choice: { context: true, mirror }, + choice: { context: true }, folder: FOLDER, phase: 'synced', - files: empty ? 0 : mirror ? 1_204 : 12, - bytes: empty ? 0 : mirror ? 38_400_000 : 640_000, + files: empty ? 0 : 12, + bytes: empty ? 0 : 640_000, progress: null, lastSyncedAt: Date.now() - 2 * 60_000, editedHere: 0, skippedLarge: 0, overLimit: 0, - limits: { maxBytes: 2_000_000_000, maxFileBytes: 100_000_000 }, + limits: { maxBytes: 250_000_000, maxFileBytes: 50_000_000 }, error: null, openPath, displayPath: openPath.replace('/Users/me', '~') @@ -105,7 +105,6 @@ const AS_OF = new Date(new Date().setHours(14, 31, 0, 0)).getTime() function card({ id, state = 'running', - mirror = false, emptyContext = false, attention = null, layer = 'main', @@ -114,7 +113,6 @@ function card({ }: { id: string state?: CloudDotState - mirror?: boolean emptyContext?: boolean attention?: CloudCardAttention | null layer?: CloudCardLayer @@ -122,7 +120,7 @@ function card({ paired?: boolean }) { // Seeded once, outside render: the card reads it through the same store as the live app. - seedCloudSyncView(syncView(id, mirror, emptyContext)) + seedCloudSyncView(syncView(id, emptyContext)) return defineFixture({ width: 320, // A paired card is registered as paired (PAIRED-STATUS), as the app does for its row. @@ -168,10 +166,8 @@ export const runningNotStarted = card({ }) /** Details open: the bars, uptime and sandbox hours. */ export const detailsOpen = card({ id: 'card-details', details: true }) -/** The sub-panel with the mirror off: the two switches and the .context status. */ -export const onComputerMirrorOff = card({ id: 'card-sync-off', layer: 'onComputer' }) -/** The sub-panel with the mirror on: where the files are, Open folder and Copy path. */ -export const onComputerMirrorOn = card({ id: 'card-sync-on', layer: 'onComputer', mirror: true }) +/** The sub-panel: the .context switch, its status, where the files are, Open folder and Copy path. */ +export const onComputer = card({ id: 'card-sync', layer: 'onComputer' }) /** The ⋯ menu open: Details, Restart, Move to this computer; Archive and Delete after a separator. */ export const menuOpen = defineFixture({ @@ -320,7 +316,7 @@ export const besideSidebar = defineFixture({ idsLoaded: true, status: { [PLACEMENT_ID]: entry(running) } }) - seedCloudSyncView(syncView(PLACEMENT_ID, false)) + seedCloudSyncView(syncView(PLACEMENT_ID)) }, render: () => (
diff --git a/src/renderer/src/components/orca-cloud/CloudWorkspaceMark.tsx b/src/renderer/src/components/orca-cloud/CloudWorkspaceMark.tsx index ee266b8857d..6b743e2ca04 100644 --- a/src/renderer/src/components/orca-cloud/CloudWorkspaceMark.tsx +++ b/src/renderer/src/components/orca-cloud/CloudWorkspaceMark.tsx @@ -10,7 +10,6 @@ import { useIsWorktreeGoingToSleep } from '@/lib/worktree-sleep-view' import { CloudWorkspaceStatusPanel } from './CloudWorkspaceStatusPanel' import { useCloudStatusPolling, useCloudWorkspaceView } from './use-cloud-workspace-view' import { useCloudPanelActions } from './use-cloud-panel-actions' -import { onCloudSyncFocusRequest } from '@/lib/orca-cloud/cloud-sync-store' const PANEL_POLL_MS = 5_000 const HOVER_OPEN_MS = 250 @@ -104,15 +103,6 @@ function CloudWorkspaceMarkInner({ timer.current = setTimeout(() => setOpen(null), HOVER_CLOSE_MS) } } - // "Mirror to this computer…" in the workspace menu opens this panel on its sync section. - useEffect( - () => - onCloudSyncFocusRequest(workspaceId, () => { - clearTimer() - setOpen('pinned') - }), - [workspaceId, clearTimer] - ) useCloudStatusPolling(workspaceId, PANEL_POLL_MS, open !== null) const close = useCallback(() => setOpen(null), []) const actions = useCloudPanelActions(workspaceId, close) diff --git a/src/renderer/src/components/orca-cloud/CloudWorkspaceMenuItems.tsx b/src/renderer/src/components/orca-cloud/CloudWorkspaceMenuItems.tsx index e69d9b5f5a3..119b91f27a4 100644 --- a/src/renderer/src/components/orca-cloud/CloudWorkspaceMenuItems.tsx +++ b/src/renderer/src/components/orca-cloud/CloudWorkspaceMenuItems.tsx @@ -1,20 +1,11 @@ import React, { useContext } from 'react' -import { useCloudShareLinksEnabled } from '@/lib/orca-cloud/cloud-share-links-flag' +import { useCloudTeamSharingEnabled } from '@/lib/orca-cloud/cloud-team-sharing-flag' import { ArchiveSnapshotTooltip } from './ArchiveSnapshotTooltip' import { toast } from 'sonner' -import { - Archive, - ArchiveRestore, - HardDriveDownload, - Link2, - Lock, - RotateCw, - Users -} from 'lucide-react' +import { Archive, ArchiveRestore, Link2, Lock, RotateCw, Users } from 'lucide-react' import { DropdownMenuItem, DropdownMenuSeparator } from '@/components/ui/dropdown-menu' import { useTranslate } from '@/i18n/use-translate' import { toastSharedWithTeam } from '@/components/cloud-workspaces/shared-with-team-toast' -import { isCloudSyncAvailable, requestCloudSyncFocus } from '@/lib/orca-cloud/cloud-sync-store' import { ConfirmationDialogContext, type ConfirmationDialogContextValue @@ -32,8 +23,6 @@ import { type CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' import { useCloudWorkspaceView } from './use-cloud-workspace-view' -import { useCloudWorkspace } from '@/lib/orca-cloud/orca-cloud-workspace-store' -import { isPairedCloudStatusRow } from '@/lib/orca-cloud/orca-cloud-workspace-rows' import { useCloudPanelActions } from './use-cloud-panel-actions' import { useCloudWorkspaceRecord } from './use-cloud-workspace-record' @@ -70,11 +59,9 @@ function CloudMenuRows({ }): React.JSX.Element { const t = useTranslate() const actions = useCloudPanelActions(worktreeId, noop) - const { workspace, reload } = useCloudWorkspaceRecord(worktreeId, hostId) + const { workspace, loaded, reload } = useCloudWorkspaceRecord(worktreeId, hostId) const confirm = useContext(ConfirmationDialogContext) const busy = view.pending !== undefined - // Mirroring syncs this desktop's own cloud workspaces; a paired one has no synced copy here. - const paired = useCloudWorkspace((state) => isPairedCloudStatusRow(state, worktreeId)) const archived = view.state === 'archived' const groups = cloudWorkspaceActionGroups({ surface: 'sidebar', @@ -97,12 +84,6 @@ function CloudMenuRows({ {t('orcaCloudWorkspace.restart', 'Restart')} ) : null} - {isCloudSyncAvailable() && view.state !== 'archived' && !paired ? ( - requestCloudSyncFocus(worktreeId)}> - - {t('orcaCloudSync.menuItem', 'Mirror to this computer…')} - - ) : null} {has('archive') && actions.onArchive ? ( @@ -117,12 +98,17 @@ function CloudMenuRows({ {t('orcaCloudWorkspace.unarchive', 'Unarchive')} ) : null} - {workspace && (has('share') || has('makePrivate')) ? ( + {/* Before the first answer for this row (it's fetched on row hover, so rarely), the rows + show disabled instead of appearing under the pointer a moment later. */} + {(workspace || !loaded) && (has('share') || has('makePrivate')) ? ( <> {has('share') ? ( void setVisibility(workspace, 'team', { reload, t, confirm })} + disabled={!workspace} + onSelect={() => + workspace && void setVisibility(workspace, 'team', { reload, t, confirm }) + } > {t('auto.components.cloudWorkspaces.shareWithTeam', 'Share with team')} @@ -130,7 +116,10 @@ function CloudMenuRows({ ) : null} {has('makePrivate') ? ( void setVisibility(workspace, 'private', { reload, t, confirm })} + disabled={!workspace} + onSelect={() => + workspace && void setVisibility(workspace, 'private', { reload, t, confirm }) + } > {t('auto.components.cloudWorkspaces.makePrivate', 'Make private')} @@ -202,16 +191,20 @@ export function CloudCopyWorkspaceLinkItem({ hostId?: string | null }): React.JSX.Element | null { const t = useTranslate() - const { workspace } = useCloudWorkspaceRecord(worktreeId, hostId ?? null) + const { workspace, loaded } = useCloudWorkspaceRecord(worktreeId, hostId ?? null) // SHARE-LINKS-HOLD: no way to produce a share link while it's held. - const shareLinks = useCloudShareLinksEnabled() - if (!workspace || !shareLinks) { + const shareLinks = useCloudTeamSharingEnabled() + // Not asked yet: disabled in place rather than appearing a moment later. + if ((!workspace && loaded) || !shareLinks) { return null } return ( - void copyCloudWorkspaceLink(workspace.id)}> + workspace && void copyCloudWorkspaceLink(workspace.id)} + > - {workspace.number + {workspace?.number ? t('auto.components.cloudWorkspaces.linkToNumber', 'Link to {{number}}', { number: formatWorkspaceNumber(workspace.number) }) diff --git a/src/renderer/src/components/orca-cloud/CloudWorkspaceStatusPanel.tsx b/src/renderer/src/components/orca-cloud/CloudWorkspaceStatusPanel.tsx index 2e681b67713..829f5c33264 100644 --- a/src/renderer/src/components/orca-cloud/CloudWorkspaceStatusPanel.tsx +++ b/src/renderer/src/components/orca-cloud/CloudWorkspaceStatusPanel.tsx @@ -312,8 +312,8 @@ export function CloudWorkspaceStatusPanel({

) : null} - {/* ARCHIVED-DEAD-ACTIONS: .context sync and mirroring run for this desktop's own cloud - workspaces only, so a paired card doesn't offer them. */} + {/* ARCHIVED-DEAD-ACTIONS: .context sync runs for this desktop's own cloud workspaces only, + so a paired card doesn't offer it. */} {state === 'archived' || paired ? null : ( setLayer('onComputer')} /> )} diff --git a/src/renderer/src/components/orca-cloud/CloudWorkspaceSyncSection.fixture.tsx b/src/renderer/src/components/orca-cloud/CloudWorkspaceSyncSection.fixture.tsx index ad0bc4be04a..f0320a49d77 100644 --- a/src/renderer/src/components/orca-cloud/CloudWorkspaceSyncSection.fixture.tsx +++ b/src/renderer/src/components/orca-cloud/CloudWorkspaceSyncSection.fixture.tsx @@ -49,11 +49,10 @@ const entry = (status: HostedWorkspaceStatus): CloudStatusEntry => ({ const FOLDER = '/Users/me/orca/cloud/Hello-World/fix-login-redirect' function view(id: string, over: Partial): CloudSyncView { - const choice = over.choice ?? { context: true, mirror: false } - const openPath = choice.mirror ? FOLDER : `${FOLDER}/.context` + const openPath = `${FOLDER}/.context` return { workspaceId: id, - choice, + choice: { context: true }, folder: FOLDER, phase: 'synced', files: 12, @@ -63,9 +62,7 @@ function view(id: string, over: Partial): CloudSyncView { editedHere: 0, skippedLarge: 0, overLimit: 0, - limits: choice.mirror - ? { maxBytes: 2_000_000_000, maxFileBytes: 100_000_000 } - : { maxBytes: 250_000_000, maxFileBytes: 50_000_000 }, + limits: { maxBytes: 250_000_000, maxFileBytes: 50_000_000 }, error: null, openPath, displayPath: openPath.replace('/Users/me', '~'), @@ -99,7 +96,7 @@ function panel( }) } -/** Default: `.context` on, mirror off. */ +/** Default: `.context` on. */ export const contextSynced = panel('fx-context', {}) export const contextSyncing = panel('fx-context-start', { phase: 'starting', @@ -107,47 +104,31 @@ export const contextSyncing = panel('fx-context-start', { bytes: 0, lastSyncedAt: null }) -export const mirrorCopying = panel('fx-mirror-copying', { - choice: { context: true, mirror: true }, +export const contextCopying = panel('fx-context-copying', { phase: 'copying', - progress: { done: 120, total: 1_204 } -}) -export const mirrorSynced = panel('fx-mirror', { - choice: { context: true, mirror: true }, - files: 1_204, - bytes: 38_400_000, - lastSyncedAt: Date.now() - 2 * 60_000 + progress: { done: 12, total: 48 } }) export const asleepWaiting = panel( 'fx-asleep', { - choice: { context: true, mirror: true }, phase: 'waiting', - files: 1_204, - bytes: 38_400_000, lastSyncedAt: Date.now() - 63 * 60_000 }, 'sleeping' ) -export const editedHere = panel('fx-edited', { - choice: { context: true, mirror: true }, - files: 1_204, - bytes: 38_400_000, - editedHere: 3 -}) +export const editedHere = panel('fx-edited', { editedHere: 3 }) export const overLimit = panel('fx-limit', { - choice: { context: true, mirror: true }, - files: 61_000, - bytes: 1_990_000_000, - overLimit: 812, + files: 4_820, + bytes: 249_000_000, + overLimit: 180, skippedLarge: 2 }) export const syncError = panel('fx-error', { phase: 'error', error: 'worktree_not_found' }) -export const bothOff = panel('fx-off', { - choice: { context: false, mirror: false }, +export const syncOff = panel('fx-off', { + choice: { context: false }, phase: 'off', files: 0, bytes: 0, diff --git a/src/renderer/src/components/orca-cloud/CloudWorkspaceSyncSection.tsx b/src/renderer/src/components/orca-cloud/CloudWorkspaceSyncSection.tsx index 1ddb238b80c..2bd84283c85 100644 --- a/src/renderer/src/components/orca-cloud/CloudWorkspaceSyncSection.tsx +++ b/src/renderer/src/components/orca-cloud/CloudWorkspaceSyncSection.tsx @@ -1,6 +1,6 @@ -// The card's "On this computer" sub-panel: `.context` sync (on by default) and the read-only mirror -// (off by default); with the mirror on, where the files are and how current they are. Quiet by -// design: no toasts; progress is announced politely and at most every ~10 s. +// The card's "On this computer" sub-panel: `.context` sync (on by default), where the files are +// and how current they are. Quiet by design: no toasts; progress is announced politely and at +// most every ~10 s. import React, { useContext, useEffect, useId, useRef, useState } from 'react' import { ConfirmationDialogContext } from '@/components/confirmation-dialog-context' import { Copy, FolderOpen } from 'lucide-react' @@ -14,9 +14,7 @@ import { openCloudSyncFolder, retryCloudSync, setCloudSyncChoice, - takeCloudSyncFocus, - useCloudSync, - useCloudSyncFocusRequest + useCloudSync } from '@/lib/orca-cloud/cloud-sync-store' import type { CloudSyncView } from '../../../../shared/cloud-sync/cloud-sync-contract' @@ -74,7 +72,7 @@ function ago(t: T, at: number, now: number): string { : t('orcaCloudSync.hoursAgo', '{{count}} h ago', { count: Math.floor(minutes / 60) }) } -/** The status line under the switches. */ +/** The status line under the switch. */ export function cloudSyncStatusLine(view: CloudSyncView, t: T, now: number): string | null { if (view.phase === 'off') { return null @@ -127,14 +125,12 @@ function SyncRow({ label, description, checked, - onCheckedChange, - switchRef + onCheckedChange }: { label: string description: string checked: boolean onCheckedChange: (next: boolean) => void - switchRef?: React.Ref }): React.JSX.Element { const id = useId() return ( @@ -148,7 +144,6 @@ function SyncRow({

(null) - const mirrorSwitch = useRef(null) - const focusRequested = useCloudSyncFocusRequest(workspaceId) const [copied, setCopied] = useState(false) const announcement = useAnnouncement(view, t) const confirm = useContext(ConfirmationDialogContext) - /** Turning a row off removes copies; changed ones are only removed after asking (as archive/delete). */ - const choose = async (patch: { context?: boolean; mirror?: boolean }): Promise => { + /** Turning sync off removes copies; changed ones are only removed after asking (as archive/delete). */ + const choose = async (context: boolean): Promise => { if (!view) { return } - const next = { ...view.choice, ...patch } - const removes = (view.choice.mirror && !next.mirror) || (!next.context && !next.mirror) - if (removes && view.editedHere > 0 && confirm) { + if (!context && view.choice.context && view.editedHere > 0 && confirm) { const ok = await confirm({ title: t('orcaCloudSync.removeConfirmTitle', 'Remove the copy on this computer?'), description: t( @@ -234,35 +224,19 @@ export function CloudWorkspaceSyncSection({ return } } - await setCloudSyncChoice(workspaceId, patch) + await setCloudSyncChoice(workspaceId, { context }) } - useEffect(() => { - if (!focusRequested || !view) { - return - } - // After the popover's own open-focus, which runs once this effect has. - const frame = requestAnimationFrame(() => { - if (takeCloudSyncFocus(workspaceId)) { - section.current?.scrollIntoView({ block: 'nearest' }) - mirrorSwitch.current?.focus() - } - }) - return () => cancelAnimationFrame(frame) - }, [focusRequested, view, workspaceId]) - if (!view) { return null } - const on = view.choice.context || view.choice.mirror - const mirror = view.choice.mirror + const on = view.choice.context const status = cloudSyncStatusLine(view, t, now) const tooLarge = view.skippedLarge > 0 const overLimit = view.overLimit > 0 return (
void choose({ context: next })} + onCheckedChange={(next) => void choose(next)} /> - {on && !mirror && status ? ( -

+ {on && status ? ( +

{status}

) : null} - void choose({ mirror: next })} - /> - - {mirror && status ? ( -

- {status} -

- ) : null} - {mirror ? ( + {on ? (
{ it('sums up On this computer in a few words', () => { expect(cloudCardOnComputerStatus(null, t)).toBe('Off') - expect(cloudCardOnComputerStatus(sync({ context: false, mirror: false }, 'off'), t)).toBe('Off') - expect(cloudCardOnComputerStatus(sync({ context: true, mirror: false }), t)).toBe( - '.context synced' - ) - expect(cloudCardOnComputerStatus(sync({ context: true, mirror: true }), t)).toBe( - 'Mirroring · .context synced' - ) - expect(cloudCardOnComputerStatus(sync({ context: true, mirror: true }, 'error'), t)).toBe( - 'Couldn’t sync' - ) + expect(cloudCardOnComputerStatus(sync({ context: false }, 'off'), t)).toBe('Off') + expect(cloudCardOnComputerStatus(sync({ context: true }), t)).toBe('.context synced') + expect(cloudCardOnComputerStatus(sync({ context: true }, 'copying'), t)).toBe('Syncing…') + expect(cloudCardOnComputerStatus(sync({ context: true }, 'error'), t)).toBe('Couldn’t sync') }) it('keeps one footer action per state; Restart only where it is the fix', () => { diff --git a/src/renderer/src/components/orca-cloud/cloud-workspace-card-model.ts b/src/renderer/src/components/orca-cloud/cloud-workspace-card-model.ts index d67303f5b94..f58085e2c2e 100644 --- a/src/renderer/src/components/orca-cloud/cloud-workspace-card-model.ts +++ b/src/renderer/src/components/orca-cloud/cloud-workspace-card-model.ts @@ -124,7 +124,7 @@ export function cloudCardAttentionLabel(item: CloudCardAttention, t: Translate): /** The "On this computer ›" row's short status. */ export function cloudCardOnComputerStatus(view: CloudSyncView | null, t: Translate): string { - if (!view || (!view.choice.context && !view.choice.mirror)) { + if (!view || !view.choice.context) { return t('orcaCloudWorkspace.card.syncOff', 'Off') } if (view.phase === 'error') { @@ -133,12 +133,7 @@ export function cloudCardOnComputerStatus(view: CloudSyncView | null, t: Transla if (view.phase === 'starting' || view.phase === 'copying') { return t('orcaCloudSync.syncing', 'Syncing…') } - if (view.choice.mirror && view.choice.context) { - return t('orcaCloudWorkspace.card.mirroringAndContext', 'Mirroring · .context synced') - } - return view.choice.mirror - ? t('orcaCloudWorkspace.card.mirroring', 'Mirroring') - : t('orcaCloudWorkspace.card.contextSynced', '.context synced') + return t('orcaCloudWorkspace.card.contextSynced', '.context synced') } export type CloudCardPrimary = 'sleep' | 'wake' | 'restart' | 'unarchive' | null diff --git a/src/renderer/src/components/orca-cloud/use-cloud-workspace-record.test.ts b/src/renderer/src/components/orca-cloud/use-cloud-workspace-record.test.ts new file mode 100644 index 00000000000..cf99e2e3c02 --- /dev/null +++ b/src/renderer/src/components/orca-cloud/use-cloud-workspace-record.test.ts @@ -0,0 +1,59 @@ +// @vitest-environment happy-dom +// Menu rows that need the team's record are there on the menu's first paint: the record is kept +// per row and fetched on row hover, not first asked for when the menu opens. +import { act, renderHook } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + prefetchCloudWorkspaceRecord, + RECORD_FRESH_MS, + resetCloudWorkspaceRecordsForTests, + useCloudWorkspaceRecord +} from './use-cloud-workspace-record' + +const T0 = 1_700_000_000_000 + +const bridge = { + localWorkspaces: vi.fn(async () => [{ worktreeId: 'w', sandboxId: 'sbx' }]), + environmentBindings: vi.fn(async () => ({})), + get: vi.fn(async () => ({ ok: true, value: { id: 'sbx', visibility: 'private' } })) +} + +beforeEach(() => { + vi.useFakeTimers({ now: T0, toFake: ['Date'] }) + resetCloudWorkspaceRecordsForTests() + vi.clearAllMocks() + Object.assign(window, { api: { cloudWorkspaces: bridge } }) +}) +afterEach(() => { + vi.useRealTimers() + Object.assign(window, { api: undefined }) +}) + +describe('useCloudWorkspaceRecord', () => { + it('a menu opened after row hover has the record on its first render', async () => { + await prefetchCloudWorkspaceRecord('w', null) + const { result } = renderHook(() => useCloudWorkspaceRecord('w', null)) + expect(result.current.loaded).toBe(true) + expect(result.current.workspace?.id).toBe('sbx') + }) + + it('says not loaded until the first answer, then updates in place', async () => { + const { result } = renderHook(() => useCloudWorkspaceRecord('w', null)) + expect(result.current.loaded).toBe(false) + await act(() => prefetchCloudWorkspaceRecord('w', null)) + expect(result.current.loaded).toBe(true) + expect(result.current.workspace?.id).toBe('sbx') + }) + + it('hovering again while fresh asks nothing; a stale record is refreshed', async () => { + await Promise.all([ + prefetchCloudWorkspaceRecord('w', null, T0), + prefetchCloudWorkspaceRecord('w', null, T0) + ]) + expect(bridge.get).toHaveBeenCalledOnce() + await prefetchCloudWorkspaceRecord('w', null, T0 + 1) + expect(bridge.get).toHaveBeenCalledOnce() + await prefetchCloudWorkspaceRecord('w', null, T0 + RECORD_FRESH_MS) + expect(bridge.get).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/renderer/src/components/orca-cloud/use-cloud-workspace-record.ts b/src/renderer/src/components/orca-cloud/use-cloud-workspace-record.ts index 71139424c75..fd632223ccd 100644 --- a/src/renderer/src/components/orca-cloud/use-cloud-workspace-record.ts +++ b/src/renderer/src/components/orca-cloud/use-cloud-workspace-record.ts @@ -1,37 +1,94 @@ -import { useCallback, useEffect, useState } from 'react' +import { useCallback, useEffect, useSyncExternalStore } from 'react' import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' import { toRuntimeExecutionHostId } from '../../../../shared/execution-host' /** * The team's record of the cloud workspace behind a sidebar row (visibility, access), so the * sidebar menu can offer the same Share actions as Home. Owned workspaces are found through this - * desktop's runtime; paired ones through their pairing. Null until loaded or when there is none. + * desktop's runtime; paired ones through their pairing. + * + * Kept per row across menu openings (last known), and fetched before the menu opens (row hover), + * so the menu's rows are there on its first paint instead of appearing a second later. A record + * older than RECORD_FRESH_MS is shown and refreshed in the background. + */ +export const RECORD_FRESH_MS = 30_000 + +type Entry = { workspace: CloudWorkspace | null; at: number } + +const records = new Map() +const inFlight = new Map>() +const listeners = new Set<() => void>() + +function key(worktreeId: string, hostId: string | null | undefined): string { + return `${worktreeId}\0${hostId ?? ''}` +} + +function api(): NonNullable['cloudWorkspaces'] | undefined { + return typeof window !== 'undefined' ? window.api?.cloudWorkspaces : undefined +} + +function fetchRecord(worktreeId: string, hostId: string | null | undefined): Promise { + const bridge = api() + const k = key(worktreeId, hostId) + if (!bridge) { + return Promise.resolve() + } + const running = inFlight.get(k) + if (running) { + return running + } + const run = (async () => { + const sandboxId = await resolveSandboxId(bridge, worktreeId, hostId) + const result = sandboxId ? await bridge.get(sandboxId).catch(() => null) : null + records.set(k, { workspace: result?.ok ? result.value : null, at: Date.now() }) + for (const listener of listeners) { + listener() + } + })().finally(() => inFlight.delete(k)) + inFlight.set(k, run) + return run +} + +/** Loads the record unless a fresh one is known; for row hover, before any menu opens. Resolves + * when that load (or the one already running) is done. */ +export function prefetchCloudWorkspaceRecord( + worktreeId: string, + hostId: string | null | undefined, + now = Date.now() +): Promise { + const known = records.get(key(worktreeId, hostId)) + if (!known || now - known.at >= RECORD_FRESH_MS) { + return fetchRecord(worktreeId, hostId) + } + return Promise.resolve() +} + +/** + * `workspace`: the last known record, null when there is none. `loaded`: false only until the + * first answer for this row, the one time a caller can't yet tell "none" from "not asked". */ export function useCloudWorkspaceRecord( worktreeId: string, hostId: string | null | undefined -): { workspace: CloudWorkspace | null; reload: () => void } { - const [workspace, setWorkspace] = useState(null) - const [generation, setGeneration] = useState(0) +): { workspace: CloudWorkspace | null; loaded: boolean; reload: () => void } { + const entry = useSyncExternalStore( + (listener) => { + listeners.add(listener) + return () => listeners.delete(listener) + }, + () => records.get(key(worktreeId, hostId)) + ) useEffect(() => { - const api = typeof window !== 'undefined' ? window.api?.cloudWorkspaces : undefined - if (!api) { - return - } - let cancelled = false - void (async () => { - const sandboxId = await resolveSandboxId(api, worktreeId, hostId) - const result = sandboxId ? await api.get(sandboxId).catch(() => null) : null - if (!cancelled) { - setWorkspace(result?.ok ? result.value : null) - } - })() - return () => { - cancelled = true - } - }, [worktreeId, hostId, generation]) - const reload = useCallback(() => setGeneration((value) => value + 1), []) - return { workspace, reload } + void prefetchCloudWorkspaceRecord(worktreeId, hostId) + }, [worktreeId, hostId]) + const reload = useCallback(() => void fetchRecord(worktreeId, hostId), [worktreeId, hostId]) + return { workspace: entry?.workspace ?? null, loaded: entry !== undefined, reload } +} + +/** Tests: forget every record. */ +export function resetCloudWorkspaceRecordsForTests(): void { + records.clear() + inFlight.clear() } async function resolveSandboxId( diff --git a/src/renderer/src/components/settings/cloud-workspaces/TeamWorkspacesSettings.test.tsx b/src/renderer/src/components/settings/cloud-workspaces/TeamWorkspacesSettings.test.tsx index 06be031a494..ba03c99cfac 100644 --- a/src/renderer/src/components/settings/cloud-workspaces/TeamWorkspacesSettings.test.tsx +++ b/src/renderer/src/components/settings/cloud-workspaces/TeamWorkspacesSettings.test.tsx @@ -29,6 +29,12 @@ const mocks = vi.hoisted(() => { return { state, open: vi.fn(), sleep: vi.fn(), archive: vi.fn() } }) +const teamSharing = vi.hoisted(() => ({ on: true })) +vi.mock('@/lib/orca-cloud/cloud-team-sharing-flag', () => ({ + CLOUD_SHARE_LINK_ACTION_ID: 'cloudWorkspace.copyLink', + cloudTeamSharingEnabled: () => teamSharing.on, + useCloudTeamSharingEnabled: () => teamSharing.on +})) vi.mock('@/store', () => ({ useAppStore: Object.assign( (selector: (s: typeof mocks.state) => unknown) => selector(mocks.state), diff --git a/src/renderer/src/components/settings/cloud-workspaces/TeamWorkspacesSettings.tsx b/src/renderer/src/components/settings/cloud-workspaces/TeamWorkspacesSettings.tsx index 55bc20629d9..5e23fd2bdaf 100644 --- a/src/renderer/src/components/settings/cloud-workspaces/TeamWorkspacesSettings.tsx +++ b/src/renderer/src/components/settings/cloud-workspaces/TeamWorkspacesSettings.tsx @@ -1,6 +1,7 @@ // Settings › Workspaces: every cloud workspace on the team, for owners and admins to manage // (Neil, HOME-1: the listing comes back only here). Open, Sleep and Archive use the same flows as // the sidebar and "Open cloud workspace…"; an action the control plane would refuse is not shown. +import { useCloudTeamSharingEnabled } from '@/lib/orca-cloud/cloud-team-sharing-flag' import React, { useEffect, useMemo, useState } from 'react' import { toast } from 'sonner' import { Lock, RefreshCw, Users } from 'lucide-react' @@ -49,6 +50,7 @@ const TEAM_QUERY = { scope: 'team', archived: 'include' } as const export function TeamWorkspacesSettings({ orgId }: { orgId: string | null }): React.JSX.Element { const t = useTranslate() + const teamSharing = useCloudTeamSharingEnabled() const intlLocale = useIntlLocale() const cloud = useAppStore((s) => s.orcaProfileAuthStatus?.cloud) const signIn = useAppStore((s) => s.connectCurrentOrcaProfile) @@ -147,7 +149,7 @@ export function TeamWorkspacesSettings({ orgId }: { orgId: string | null }): Rea - + {teamSharing ? : null} @@ -167,9 +169,12 @@ export function TeamWorkspacesSettings({ orgId }: { orgId: string | null }): Rea {t('settings.teamWorkspaces.colLastActive', 'Last active')} - - {t('settings.teamWorkspaces.colAccess', 'Access')} - + {/* TEAM-SHARING-HOLD: no Access column while sharing is held (all private). */} + {teamSharing ? ( + + {t('settings.teamWorkspaces.colAccess', 'Access')} + + ) : null} {t('settings.teamWorkspaces.colActions', 'Actions')} @@ -219,18 +224,20 @@ export function TeamWorkspacesSettings({ orgId }: { orgId: string | null }): Rea {formatRelative(w.lastActivityAt, now, t, intlLocale)} - - - {w.visibility === 'private' ? ( - - ) : ( - - )} - {w.visibility === 'private' - ? t('auto.components.cloudWorkspaces.private', 'Private') - : t('settings.teamWorkspaces.shared', 'Shared')} - - + {teamSharing ? ( + + + {w.visibility === 'private' ? ( + + ) : ( + + )} + {w.visibility === 'private' + ? t('auto.components.cloudWorkspaces.private', 'Private') + : t('settings.teamWorkspaces.shared', 'Shared')} + + + ) : null} () diff --git a/src/renderer/src/components/settings/shortcuts/shortcut-share-link-hold.test.ts b/src/renderer/src/components/settings/shortcuts/shortcut-share-link-hold.test.ts index 81e4db4f363..89d0a54e701 100644 --- a/src/renderer/src/components/settings/shortcuts/shortcut-share-link-hold.test.ts +++ b/src/renderer/src/components/settings/shortcuts/shortcut-share-link-hold.test.ts @@ -3,9 +3,9 @@ import { describe, expect, it, vi } from 'vitest' const shareLinks = vi.hoisted(() => ({ on: false })) -vi.mock('@/lib/orca-cloud/cloud-share-links-flag', () => ({ +vi.mock('@/lib/orca-cloud/cloud-team-sharing-flag', () => ({ CLOUD_SHARE_LINK_ACTION_ID: 'cloudWorkspace.copyLink', - cloudShareLinksEnabled: () => shareLinks.on + cloudTeamSharingEnabled: () => shareLinks.on })) import { groupDefinitions } from './shortcut-groups' diff --git a/src/renderer/src/components/settings/shortcuts/shortcuts-search.ts b/src/renderer/src/components/settings/shortcuts/shortcuts-search.ts index d8f05637a18..cc65cc4809b 100644 --- a/src/renderer/src/components/settings/shortcuts/shortcuts-search.ts +++ b/src/renderer/src/components/settings/shortcuts/shortcuts-search.ts @@ -1,8 +1,8 @@ import { KEYBINDING_DEFINITIONS } from '../../../../../shared/keybindings/definitions' import { CLOUD_SHARE_LINK_ACTION_ID, - cloudShareLinksEnabled -} from '@/lib/orca-cloud/cloud-share-links-flag' + cloudTeamSharingEnabled +} from '@/lib/orca-cloud/cloud-team-sharing-flag' import type { SettingsSearchEntry } from '../search/settings-search' import { translate } from '@/i18n/i18n' import { translateSearchKeyword } from '../search/settings-search-keywords' @@ -67,7 +67,7 @@ export function getShortcutsPaneSearchEntries(options?: { (includeManagedBrowser || (actionId !== 'tab.newBrowser' && actionId !== 'tab.newBrowserSplitRight')) && (includeMobileEmulator || actionId !== 'tab.newSimulator') && - (actionId !== CLOUD_SHARE_LINK_ACTION_ID || cloudShareLinksEnabled()) + (actionId !== CLOUD_SHARE_LINK_ACTION_ID || cloudTeamSharingEnabled()) ) .map(({ searchEntry }) => searchEntry), getTerminalShortcutPolicySearchEntry() diff --git a/src/renderer/src/components/sidebar/workspace-actions/context-menu/WorktreeCloudTransferMenuItem.tsx b/src/renderer/src/components/sidebar/workspace-actions/context-menu/WorktreeCloudTransferMenuItem.tsx index 694b9584bf4..a28db9b3d5f 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/context-menu/WorktreeCloudTransferMenuItem.tsx +++ b/src/renderer/src/components/sidebar/workspace-actions/context-menu/WorktreeCloudTransferMenuItem.tsx @@ -1,34 +1,25 @@ -import React, { useEffect, useState } from 'react' +import React from 'react' import { Monitor } from 'lucide-react' import { DropdownMenuItem } from '@/components/ui/dropdown-menu' import { useTranslate } from '@/i18n/use-translate' import { openMoveToThisComputer } from '@/lib/orca-cloud/orca-cloud-move-store' +import { useIsCloudWorkspace } from '@/lib/orca-cloud/orca-cloud-workspace-store' import { useAppStore } from '@/store' import { findWorktreeById } from '@/store/github/refresh/worktree-refresh' -/** "Move to this computer" for Orca Cloud workspaces. Mounted only inside the open menu. */ +/** + * "Move to this computer" for this desktop's own Orca Cloud workspaces. Reads the cloud workspace + * store (the same list main serves, loaded before any menu opens), so it is there on the menu's + * first paint instead of popping in after an IPC round trip. + */ export function WorktreeCloudTransferMenuItem({ worktreeId }: { worktreeId: string }): React.JSX.Element | null { const t = useTranslate() - const [isCloud, setIsCloud] = useState(false) - useEffect(() => { - let live = true - const api = window.api?.orcaCloudWorkspace - if (!api?.prepareTransferToLocal) { - return - } - void api - .listCloudWorkspaceIds() - .then((ids) => live && setIsCloud(ids.includes(worktreeId))) - .catch(() => undefined) - return () => { - live = false - } - }, [worktreeId]) - if (!isCloud) { + const isCloud = useIsCloudWorkspace(worktreeId) + if (!isCloud || !window.api?.orcaCloudWorkspace?.prepareTransferToLocal) { return null } return ( diff --git a/src/renderer/src/components/sidebar/workspace-actions/context-menu/WorktreeContextMenuCloudFirstPaint.fixture.tsx b/src/renderer/src/components/sidebar/workspace-actions/context-menu/WorktreeContextMenuCloudFirstPaint.fixture.tsx new file mode 100644 index 00000000000..f4fba56e36a --- /dev/null +++ b/src/renderer/src/components/sidebar/workspace-actions/context-menu/WorktreeContextMenuCloudFirstPaint.fixture.tsx @@ -0,0 +1,142 @@ +// MENU-FIRST-PAINT (Neil): a cloud workspace's right-click menu is whole when it opens; nothing +// appears a second later. The answers this menu used to wait for take 900 ms here (a slow link): +// the cloud workspace list and the team's record. Running and asleep (one Sleep or Wake item). +import { defineFixture } from '../../../../component-fixtures/component-fixture' +import type { Repo } from '../../../../../../shared/repo-types' +import type { Worktree } from '../../../../../../shared/worktree/types' +import type { HostedWorkspaceStatus } from '../../../../../../shared/hosted-sandbox/hosted-sandbox-wire' +import { seedCloudWorkspaceSnapshot } from '@/lib/orca-cloud/orca-cloud-workspace-store' +import WorktreeContextMenu from './WorktreeContextMenu' + +const SLOW_MS = 900 +const slow = (value: T): Promise => + new Promise((resolve) => setTimeout(() => resolve(value), SLOW_MS)) + +const repo: Repo = { + id: 'cloud-repo', + path: '/workspace/hello-world', + displayName: 'hello-world', + badgeColor: '', + addedAt: 1 +} + +function cloudWorktree(id: string, name: string): Worktree { + return { + id, + repoId: repo.id, + hostId: 'runtime:env-cloud', + instanceId: `${id}-instance`, + path: '/workspace/hello-world', + displayName: name, + branch: 'refs/heads/fix-login', + head: 'abc123', + isBare: false, + isMainWorktree: false, + comment: '', + linkedIssue: null, + linkedPR: null, + linkedLinearIssue: null, + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 1 + } +} + +const status = (state: 'ready' | 'sleeping'): HostedWorkspaceStatus => ({ + state, + metrics: null, + uptimeMs: null, + usage: { totalMs: 0, centsPerHour: 100, costCents: 0 }, + archive: null, + checkedAt: 1 +}) + +function firstPaint(asleep: boolean) { + const worktree = cloudWorktree(asleep ? 'cloud-asleep' : 'cloud-running', 'fix login') + return defineFixture({ + width: 420, + store: { + repos: [repo], + worktreesByRepo: { [repo.id]: [worktree] }, + // Team sharing on, so the Share row (which needs the team's record) is in the menu. + orcaProfileAuthStatus: { + activeProfileId: 'p', + configured: true, + state: 'connected', + persistence: 'encrypted', + cloud: { cloudProfileId: 'c', userId: 'u', email: 'e', activeOrgId: 'o', linkedAt: 0 }, + organizations: [{ orgId: 'o', name: 'Team', role: 'Owner' }], + capabilities: { flags: { cloudTeamSharing: true }, refreshedAt: 0 } + }, + ephemeralVmRuntimesByWorkspaceId: { + [worktree.id]: { + id: 'vm-1', + workspaceId: worktree.id, + status: asleep ? 'suspended' : 'running', + runtimeEnvironmentId: 'env-cloud', + canSuspend: true + } + }, + // Restored panels on the asleep one: what made the local "Sleep" show beside Wake. + browserTabsByWorktree: asleep + ? { + [worktree.id]: [ + { + id: 'browser-1', + worktreeId: worktree.id, + url: 'http://localhost:3000', + title: 'App', + loading: false, + faviconUrl: null, + canGoBack: false, + canGoForward: false, + loadError: null, + createdAt: 1 + } + ] + } + : {} + }, + setup: () => { + seedCloudWorkspaceSnapshot({ + ids: new Set([worktree.id]), + idsLoaded: true, + status: { + [worktree.id]: { + status: status(asleep ? 'sleeping' : 'ready'), + loading: false, + error: null, + fetchedAt: Date.now() + } + } + }) + Object.assign(window.api.orcaCloudWorkspace, { + listCloudWorkspaceIds: () => slow([worktree.id]), + prepareTransferToLocal: () => slow(null) + }) + Object.assign(window.api.cloudWorkspaces, { + localWorkspaces: () => slow([{ worktreeId: worktree.id, sandboxId: 'sbx_1' }]), + environmentBindings: () => slow({}), + get: () => + slow({ + ok: true, + value: { id: 'sbx_1', status: 'running', visibility: 'private', access: 'owner' } + }) + }) + }, + render: () => ( +
+ +
+ fix login +
+
+
+ ) + }) +} + +export const running = firstPaint(false) +export const asleep = firstPaint(true) diff --git a/src/renderer/src/components/sidebar/workspace-actions/context-menu/WorktreeContextMenuView.tsx b/src/renderer/src/components/sidebar/workspace-actions/context-menu/WorktreeContextMenuView.tsx index 42734c77268..61ca8bf80ce 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/context-menu/WorktreeContextMenuView.tsx +++ b/src/renderer/src/components/sidebar/workspace-actions/context-menu/WorktreeContextMenuView.tsx @@ -15,6 +15,7 @@ import { CloudCopyWorkspaceLinkItem, CloudWorkspaceMenuItems } from '@/components/orca-cloud/CloudWorkspaceMenuItems' +import { prefetchCloudWorkspaceRecord } from '@/components/orca-cloud/use-cloud-workspace-record' import { useIsCloudHostRow, usePrimeCloudRowBindings } from '@/lib/orca-cloud/cloud-host-rows' import { getWorktreeExecutionHostId } from '../../../../../../shared/execution-host' import { WorktreeOpenInAndSshSubMenus } from '../cloud-ssh/WorktreeOpenInAndSshSubMenus' @@ -104,6 +105,17 @@ export default function WorktreeContextMenuView({ model }: { model: WorktreeCont ref={scopeRef} className="relative" {...{ [WORKTREE_CONTEXT_MENU_SCOPE_ATTR]: 'worktree' }} + // The cloud menu's Share and link rows need the team's record: fetch it while the pointer is + // on the row, so it's there when the menu opens (cached; a fresh one isn't fetched again). + onPointerEnter={ + isCloud + ? () => + void prefetchCloudWorkspaceRecord( + worktree.id, + getWorktreeExecutionHostId(worktree, repo ?? undefined) + ) + : undefined + } onContextMenuCapture={(event) => { if (!isEventTargetInsideCurrentTarget(event.currentTarget, event.target)) { return diff --git a/src/renderer/src/components/sidebar/workspace-actions/context-menu/use-worktree-context-menu-model.churn.test.tsx b/src/renderer/src/components/sidebar/workspace-actions/context-menu/use-worktree-context-menu-model.churn.test.tsx new file mode 100644 index 00000000000..1f891b7e431 --- /dev/null +++ b/src/renderer/src/components/sidebar/workspace-actions/context-menu/use-worktree-context-menu-model.churn.test.tsx @@ -0,0 +1,75 @@ +// @vitest-environment happy-dom + +import { act, cleanup, renderHook } from '@testing-library/react' +import { afterEach, describe, expect, it } from 'vitest' +import { useAppStore } from '@/store' +import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' +import { TEST_REPO } from '@/store/repos/repo.test-fixture' +import { makeTab } from '@/store/terminals/terminal-tab.test-fixture' +import { useWorktreeContextMenuModel } from './use-worktree-context-menu-model' + +afterEach(() => { + cleanup() + useAppStore.setState(useAppStore.getInitialState(), true) +}) + +const worktree = makeWorktree({ id: 'repo1::/tmp/wt', repoId: TEST_REPO.id }) +const other = makeWorktree({ + id: 'repo1::/tmp/other', + repoId: TEST_REPO.id, + path: '/tmp/other' +}) + +function renderOpenMenu() { + useAppStore.setState({ + repos: [TEST_REPO], + worktreesByRepo: { [TEST_REPO.id]: [worktree, other] }, + tabsByWorktree: { [worktree.id]: [makeTab({ id: 'tab-1', worktreeId: worktree.id })] }, + ptyIdsByTabId: {} + }) + let renders = 0 + const hook = renderHook(() => { + renders += 1 + return useWorktreeContextMenuModel({ worktree, children: null }) + }) + act(() => hook.result.current.setMenuOpenState(true)) + return { hook, renders: () => renders } +} + +// An open menu used to subscribe to whole activity maps, so every agent status, tab or PTY write +// anywhere re-rendered the whole menu (about 200 components) while the pointer moved over it. +describe('an open workspace menu ignores store writes that change nothing it shows', () => { + it('another workspace’s agent status, tabs and PTYs do not re-render it', () => { + const { renders } = renderOpenMenu() + const before = renders() + for (let i = 0; i < 20; i += 1) { + act(() => { + const state = useAppStore.getState() + state.setAgentStatus( + `pane-${i}`, + { state: 'working', prompt: `prompt ${i}`, agentType: 'codex' }, + 'codex', + { updatedAt: i, stateStartedAt: i }, + { tabId: `other-${i}`, worktreeId: other.id } + ) + useAppStore.setState({ + tabsByWorktree: { + ...state.tabsByWorktree, + [other.id]: [makeTab({ id: `other-${i}`, worktreeId: other.id })] + }, + ptyIdsByTabId: { ...state.ptyIdsByTabId, [`other-${i}`]: [`pty-${i}`] }, + unifiedTabsByWorktree: { ...state.unifiedTabsByWorktree }, + deleteStateByWorktreeId: { ...state.deleteStateByWorktreeId } + }) + }) + } + expect(renders()).toBe(before) + }) + + it('still updates live when this workspace becomes sleepable', () => { + const { hook } = renderOpenMenu() + expect(hook.result.current.sleepableWorktrees).toEqual([]) + act(() => useAppStore.setState({ ptyIdsByTabId: { 'tab-1': ['pty-1'] } })) + expect(hook.result.current.sleepableWorktrees.map((item) => item.id)).toEqual([worktree.id]) + }) +}) diff --git a/src/renderer/src/components/sidebar/workspace-actions/context-menu/use-worktree-context-menu-model.tsx b/src/renderer/src/components/sidebar/workspace-actions/context-menu/use-worktree-context-menu-model.tsx index fc090f95d42..93d7a090de8 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/context-menu/use-worktree-context-menu-model.tsx +++ b/src/renderer/src/components/sidebar/workspace-actions/context-menu/use-worktree-context-menu-model.tsx @@ -1,4 +1,3 @@ -import { selectAwakeBrowserTabsByWorktree } from '@/components/sidebar/workspace-actions/sleep/browser-tab-sleep' import { useIsPairedCloudPrimaryRow } from '@/lib/orca-cloud/cloud-host-rows' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useAppStore } from '@/store/index' @@ -7,20 +6,12 @@ import type { Worktree } from '../../../../../../shared/worktree/types' import { useContextWorkspaceStatuses } from '../../workspace-status/presentation/use-workspace-board-statuses' import { useMenuScopedWorktreeCatalog } from './use-menu-scoped-worktree-catalog' import { useMenuLineageParent } from './use-menu-lineage-parent' -import { - hasSleepableWorkspaceActivity, - useWorkspaceLineageMenuActions -} from './workspace-lineage-menu-actions' +import { useWorkspaceMenuActivity } from './workspace-lineage-menu-actions' +import { getWorkspaceDeleteLineage } from '../deletion/workspace-delete-lineage' import { parseWorkspaceKey } from '../../../../../../shared/workspace-scope' import { getDeleteStateForWorktreeHost } from '../deletion/worktree-delete-state-host-match' import { - EMPTY_AGENT_STATUS_BY_PANE_KEY, - EMPTY_BROWSER_TABS_BY_WORKTREE, - EMPTY_DELETE_STATE_BY_WORKTREE_ID, - EMPTY_STRUCTURED_CHAT_SLEPT_AT, - EMPTY_PTY_IDS_BY_TAB_ID, - EMPTY_TABS_BY_WORKTREE, - EMPTY_UNIFIED_TABS_BY_WORKTREE, + EMPTY_WORKTREES, EMPTY_WORKSPACE_LINEAGE_BY_CHILD_KEY, EMPTY_WORKTREE_LINEAGE_BY_ID, getSharedWorkspaceStatus, @@ -102,31 +93,6 @@ export function useWorktreeContextMenuModel({ ) ) const updateWorktreeLineage = useAppStore((s) => s.updateWorktreeLineage) - const tabsByWorktree = useAppStore((s) => - selectMenuScopedMap(menuOpen, s.tabsByWorktree, EMPTY_TABS_BY_WORKTREE) - ) - const ptyIdsByTabId = useAppStore((s) => - selectMenuScopedMap(menuOpen, s.ptyIdsByTabId, EMPTY_PTY_IDS_BY_TAB_ID) - ) - const browserTabsByWorktree = useAppStore((s) => - selectMenuScopedMap( - menuOpen, - selectAwakeBrowserTabsByWorktree(s), - EMPTY_BROWSER_TABS_BY_WORKTREE - ) - ) - const unifiedTabsByWorktree = useAppStore((s) => - selectMenuScopedMap(menuOpen, s.unifiedTabsByWorktree, EMPTY_UNIFIED_TABS_BY_WORKTREE) - ) - const agentStatusByPaneKey = useAppStore((s) => - selectMenuScopedMap(menuOpen, s.agentStatusByPaneKey, EMPTY_AGENT_STATUS_BY_PANE_KEY) - ) - const structuredChatSleptAtByPaneKey = useAppStore((s) => - selectMenuScopedMap(menuOpen, s.structuredChatSleptAtByPaneKey, EMPTY_STRUCTURED_CHAT_SLEPT_AT) - ) - const deleteStateByWorktreeId = useAppStore((s) => - selectMenuScopedMap(menuOpen, s.deleteStateByWorktreeId, EMPTY_DELETE_STATE_BY_WORKTREE_ID) - ) const scopeRef = useRef(null) const contextMenuOpenedAtRef = useRef(null) const activeContextWorktrees = menuOpen ? contextWorktrees : effectiveSelectedWorktrees @@ -136,54 +102,42 @@ export function useWorktreeContextMenuModel({ const workspaceScope = parseWorkspaceKey(worktree.id) const folderWorkspaceId = workspaceScope?.type === 'folder' ? workspaceScope.folderWorkspaceId : null - const sleepActivity = useMemo( - () => ({ - tabsByWorktree, - ptyIdsByTabId, - browserTabsByWorktree, - unifiedTabsByWorktree, - agentStatusByPaneKey, - structuredChatSleptAtByPaneKey - }), - [ - agentStatusByPaneKey, - browserTabsByWorktree, - structuredChatSleptAtByPaneKey, - ptyIdsByTabId, - tabsByWorktree, - unifiedTabsByWorktree - ] - ) // A paired cloud workspace can be running with nothing open here: its Sleep reaches the sandbox. const pairedCloudSleepable = useIsPairedCloudPrimaryRow(worktree) && !isMultiContext + // Lineage reads only the catalog; per-workspace activity comes from narrow id selectors below. + const lineageTargets = useMemo( + () => + menuOpen && !isMultiContext + ? [ + worktree, + ...getWorkspaceDeleteLineage(worktree, allWorktrees, worktreeLineageById).descendants + ] + : EMPTY_WORKTREES, + [allWorktrees, isMultiContext, menuOpen, worktree, worktreeLineageById] + ) + const activityCandidates = useMemo( + () => [ + ...activeContextWorktrees, + ...lineageTargets.filter((target) => !activeContextWorktrees.includes(target)) + ], + [activeContextWorktrees, lineageTargets] + ) + const { sleepableIds, deletingIds } = useWorkspaceMenuActivity(menuOpen, activityCandidates) const sleepableWorktrees = useMemo( () => activeContextWorktrees.filter( (item) => - hasSleepableWorkspaceActivity(item.id, sleepActivity) || - (pairedCloudSleepable && item.id === worktree.id) + sleepableIds.includes(item.id) || (pairedCloudSleepable && item.id === worktree.id) ), - [activeContextWorktrees, sleepActivity, pairedCloudSleepable, worktree.id] + [activeContextWorktrees, sleepableIds, pairedCloudSleepable, worktree.id] ) - const lineageMenuActions = useWorkspaceLineageMenuActions({ - enabled: menuOpen && !isMultiContext, - parent: worktree, - worktrees: allWorktrees, - lineageById: worktreeLineageById, - activity: sleepActivity - }) - const lineageDescendantCount = lineageMenuActions.descendants.length - const subtreeSleepableWorktrees = lineageMenuActions.sleepableTargets - const deletingContext = useMemo( - () => - activeContextWorktrees.some( - (item) => getDeleteStateForWorktreeHost(item, deleteStateByWorktreeId)?.isDeleting - ), - [activeContextWorktrees, deleteStateByWorktreeId] - ) - const deletingSubtree = lineageMenuActions.targets.some( - (item) => getDeleteStateForWorktreeHost(item, deleteStateByWorktreeId)?.isDeleting + const lineageDescendantCount = Math.max(0, lineageTargets.length - 1) + const subtreeSleepableWorktrees = useMemo( + () => lineageTargets.filter((target) => sleepableIds.includes(target.id)), + [lineageTargets, sleepableIds] ) + const deletingContext = activeContextWorktrees.some((item) => deletingIds.includes(item.id)) + const deletingSubtree = lineageTargets.some((item) => deletingIds.includes(item.id)) const contextDeletePending = isMultiContext ? deletingContext : deletingSubtree const contextWorkspaceStatus = useMemo( () => getSharedWorkspaceStatus(activeContextWorktrees, statusesForWorktree), @@ -343,7 +297,6 @@ export function useWorktreeContextMenuModel({ ...commands, activeContextWorktrees, batchDeleteWorktrees, - browserTabsByWorktree, children, contentClassName, contextDeletePending, @@ -373,7 +326,6 @@ export function useWorktreeContextMenuModel({ parentPicker, parentPickerOpen, projectGroups, - ptyIdsByTabId, removesProject, repo, scopeRef, @@ -385,7 +337,6 @@ export function useWorktreeContextMenuModel({ sleepableWorktrees, subtreeSleepableWorktrees, suppressOpeningPointerEvent, - tabsByWorktree, validParentWorktreeId, worktree, workspaceStatuses diff --git a/src/renderer/src/components/sidebar/workspace-actions/context-menu/workspace-lineage-menu-actions.ts b/src/renderer/src/components/sidebar/workspace-actions/context-menu/workspace-lineage-menu-actions.ts index 645697c35c3..6bbab62bc76 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/context-menu/workspace-lineage-menu-actions.ts +++ b/src/renderer/src/components/sidebar/workspace-actions/context-menu/workspace-lineage-menu-actions.ts @@ -1,4 +1,8 @@ -import { useMemo } from 'react' +import { useShallow } from 'zustand/react/shallow' +import { useAppStore } from '@/store' +import type { AppState } from '@/store/types' +import { selectAwakeBrowserTabsByWorktree } from '@/components/sidebar/workspace-actions/sleep/browser-tab-sleep' +import { getDeleteStateForWorktreeHost } from '../deletion/worktree-delete-state-host-match' import { tabHasLivePty } from '../../../../../../shared/tab-has-live-pty' import type { WorktreeLineage } from '../../../../../../shared/worktree/lineage-types' import type { Worktree } from '../../../../../../shared/worktree/types' @@ -61,52 +65,52 @@ export function getWorkspaceLineageMenuActions(args: { } } -const EMPTY_LINEAGE_MENU_ACTIONS: WorkspaceLineageMenuActions = { - descendants: [], - targets: [], - sleepableTargets: [] +const EMPTY_IDS: readonly string[] = [] + +function selectWorkspaceActivity(state: AppState): WorkspaceActivityMaps { + const browserTabsByWorktree = selectAwakeBrowserTabsByWorktree(state) + return { + tabsByWorktree: state.tabsByWorktree, + ptyIdsByTabId: state.ptyIdsByTabId, + browserTabsByWorktree, + unifiedTabsByWorktree: state.unifiedTabsByWorktree, + agentStatusByPaneKey: state.agentStatusByPaneKey, + structuredChatSleptAtByPaneKey: state.structuredChatSleptAtByPaneKey + } } -export function useWorkspaceLineageMenuActions( - args: Parameters[0] & { enabled: boolean } -): WorkspaceLineageMenuActions { - const { enabled, parent, worktrees, lineageById, activity } = args - const { - tabsByWorktree, - ptyIdsByTabId, - browserTabsByWorktree, - unifiedTabsByWorktree, - agentStatusByPaneKey, - structuredChatSleptAtByPaneKey - } = activity - return useMemo( - () => - enabled - ? getWorkspaceLineageMenuActions({ - parent, - worktrees, - lineageById, - activity: { - tabsByWorktree, - ptyIdsByTabId, - browserTabsByWorktree, - unifiedTabsByWorktree, - agentStatusByPaneKey, - structuredChatSleptAtByPaneKey - } - }) - : EMPTY_LINEAGE_MENU_ACTIONS, - [ - agentStatusByPaneKey, - browserTabsByWorktree, - enabled, - structuredChatSleptAtByPaneKey, - lineageById, - parent, - ptyIdsByTabId, - tabsByWorktree, - unifiedTabsByWorktree, - worktrees - ] +/** + * Which of `worktrees` have something Sleep would close, and which are being deleted, as id lists + * that keep their identity while unchanged. An open menu must not subscribe to the whole activity + * and delete maps: agents, tabs and PTYs anywhere write them many times a second, and each write + * re-rendered the whole menu under the pointer. Closed menus select a shared empty list. + */ +export function useWorkspaceMenuActivity( + enabled: boolean, + worktrees: readonly Worktree[] +): { sleepableIds: readonly string[]; deletingIds: readonly string[] } { + const sleepableIds = useAppStore( + useShallow((state) => { + if (!enabled) { + return EMPTY_IDS + } + const activity = selectWorkspaceActivity(state) + return worktrees + .filter((item) => hasSleepableWorkspaceActivity(item.id, activity)) + .map((item) => item.id) + }) ) + const deletingIds = useAppStore( + useShallow((state) => + enabled + ? worktrees + .filter( + (item) => + getDeleteStateForWorktreeHost(item, state.deleteStateByWorktreeId)?.isDeleting + ) + .map((item) => item.id) + : EMPTY_IDS + ) + ) + return { sleepableIds, deletingIds } } diff --git a/src/renderer/src/components/sidebar/workspace-actions/context-menu/worktree-context-menu-policy.ts b/src/renderer/src/components/sidebar/workspace-actions/context-menu/worktree-context-menu-policy.ts index 17fef0348bc..b0316370e6b 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/context-menu/worktree-context-menu-policy.ts +++ b/src/renderer/src/components/sidebar/workspace-actions/context-menu/worktree-context-menu-policy.ts @@ -25,13 +25,6 @@ const DELETE_POSITION_RESTORE_STABLE_FRAMES = 6 export const PARENT_PICKER_EXIT_ANIMATION_MS = 200 // Closed menus reuse empty identities so teardown map churn cannot wake their subscriptions. -export const EMPTY_TABS_BY_WORKTREE: AppState['tabsByWorktree'] = {} -export const EMPTY_PTY_IDS_BY_TAB_ID: AppState['ptyIdsByTabId'] = {} -export const EMPTY_BROWSER_TABS_BY_WORKTREE: AppState['browserTabsByWorktree'] = {} -export const EMPTY_UNIFIED_TABS_BY_WORKTREE: AppState['unifiedTabsByWorktree'] = {} -export const EMPTY_AGENT_STATUS_BY_PANE_KEY: AppState['agentStatusByPaneKey'] = {} -export const EMPTY_STRUCTURED_CHAT_SLEPT_AT: AppState['structuredChatSleptAtByPaneKey'] = {} -export const EMPTY_DELETE_STATE_BY_WORKTREE_ID: AppState['deleteStateByWorktreeId'] = {} export const EMPTY_WORKTREE_LINEAGE_BY_ID: AppState['worktreeLineageById'] = {} export const EMPTY_WORKSPACE_LINEAGE_BY_CHILD_KEY: AppState['workspaceLineageByChildKey'] = {} export const EMPTY_CROSS_STORE_LINEAGE_BY_STORE_KEY: AppState['crossStoreLineageByStoreKey'] = {} diff --git a/src/renderer/src/components/sidebar/workspace-actions/sleep/WorkspaceVmLifecycleMenuItems.cloud.test.tsx b/src/renderer/src/components/sidebar/workspace-actions/sleep/WorkspaceVmLifecycleMenuItems.cloud.test.tsx new file mode 100644 index 00000000000..53f8d64cfda --- /dev/null +++ b/src/renderer/src/components/sidebar/workspace-actions/sleep/WorkspaceVmLifecycleMenuItems.cloud.test.tsx @@ -0,0 +1,129 @@ +// @vitest-environment happy-dom +// Neil: an asleep cloud workspace's menu showed "Sleep" (the local close-panels item) beside "Wake". +// A cloud row gets one lifecycle item for its state; local VM workspaces are unchanged. +import { cleanup, render, screen } from '@testing-library/react' +import React from 'react' +import { afterEach, describe, expect, it, vi } from 'vitest' + +type MenuState = { + runtime: null | { status: string; canSuspend?: boolean } + waking: boolean + ownedCloud: boolean + archived: boolean +} + +const { state } = vi.hoisted(() => { + const initial: MenuState = { runtime: null, waking: false, ownedCloud: false, archived: false } + return { state: initial } +}) + +vi.mock('@/store', () => ({ + useAppStore: (select: (s: unknown) => unknown) => + select({ + ephemeralVmRuntimesByWorkspaceId: state.runtime ? { w: state.runtime } : {}, + wakingEphemeralVmWorkspaceIds: state.waking ? { w: true } : {} + }) +})) +vi.mock('@/lib/orca-cloud/orca-cloud-workspace-store', () => ({ + useIsCloudWorkspace: () => state.ownedCloud, + useCloudWorkspace: () => state.archived +})) +vi.mock('@/lib/workspace/activation/sidebar-worktree-activation', () => ({ + resumeEphemeralVmWorkspace: vi.fn(), + suspendEphemeralVmWorkspace: vi.fn() +})) +vi.mock('@/components/ui/dropdown-menu', () => ({ + DropdownMenuItem: ({ children, disabled }: { children: React.ReactNode; disabled?: boolean }) => ( +
+ {children} +
+ ) +})) +vi.mock('@/components/ui/tooltip', () => ({ + Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}, + TooltipTrigger: ({ children }: { children: React.ReactNode }) => <>{children}, + TooltipContent: () => null +})) + +import { WorkspaceVmLifecycleMenuItems } from './WorkspaceVmLifecycleMenuItems' + +const PANEL_SLEEP =
Close panels sleep
+ +function items({ hasSleepableActivity = true } = {}): string[] { + render( + + ) + return screen.queryAllByRole('menuitem').map((item) => { + const label = item.textContent ?? '' + return item.getAttribute('aria-disabled') ? `${label} (disabled)` : label + }) +} + +function set(patch: Partial): void { + Object.assign(state, { runtime: null, waking: false, ownedCloud: false, archived: false }, patch) +} + +afterEach(cleanup) + +describe('a cloud workspace has one lifecycle item for its state', () => { + it('running: Sleep, without the local close-panels Sleep', () => { + set({ ownedCloud: true, runtime: { status: 'running' } }) + expect(items()).toEqual(['Sleep']) + }) + + it('asleep with restored panels: Wake only (the bug: Sleep and Wake together)', () => { + set({ ownedCloud: true, runtime: { status: 'suspended' } }) + expect(items()).toEqual(['Wake']) + }) + + it('waking: Waking…, disabled', () => { + set({ ownedCloud: true, runtime: { status: 'suspended' }, waking: true }) + expect(items()).toEqual(['Waking… (disabled)']) + }) + + it('a wake that failed: Try waking again', () => { + set({ ownedCloud: true, runtime: { status: 'resume_failed' } }) + expect(items()).toEqual(['Try waking again']) + }) + + it('transitioning (provisioning): no lifecycle item, not the local Sleep', () => { + set({ ownedCloud: true, runtime: { status: 'provisioning' } }) + expect(items()).toEqual([]) + }) + + it('paired (no VM record here): its Sleep is the one that reaches the sandbox', () => { + set({ runtime: null }) + expect(items()).toEqual(['Close panels sleep']) + }) + + it('archived: nothing', () => { + set({ ownedCloud: true, runtime: { status: 'running' }, archived: true }) + expect(items()).toEqual([]) + }) +}) + +describe('local workspaces are unchanged', () => { + it('no VM: the close-panels Sleep', () => { + set({}) + expect(items()).toEqual(['Close panels sleep']) + }) + + it('a suspended local VM with restored panels keeps both Sleep and Resume VM', () => { + set({ runtime: { status: 'suspended' } }) + expect(items()).toEqual(['Close panels sleep', 'Resume VM']) + }) + + it('a running local VM: Suspend VM in place of Sleep', () => { + set({ runtime: { status: 'running' } }) + expect(items()).toEqual(['Suspend VM']) + }) +}) diff --git a/src/renderer/src/components/sidebar/workspace-actions/sleep/WorkspaceVmLifecycleMenuItems.tsx b/src/renderer/src/components/sidebar/workspace-actions/sleep/WorkspaceVmLifecycleMenuItems.tsx index 5b38a5247f8..5fe47025e5a 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/sleep/WorkspaceVmLifecycleMenuItems.tsx +++ b/src/renderer/src/components/sidebar/workspace-actions/sleep/WorkspaceVmLifecycleMenuItems.tsx @@ -111,7 +111,9 @@ export function WorkspaceVmLifecycleMenuItems({ return null } if (!action) { - return <>{sleepItems} + // This desktop's own cloud workspace mid-transition has no lifecycle item. (A paired one has no + // VM record here; its Sleep is `sleepItems`, which reaches the sandbox.) + return cloud ? null : <>{sleepItems} } const vmItem = ( ) // Sleep and Suspend VM are one action on a running VM. A VM still asleep or waking keeps Sleep - // only while it has restored panels to close; otherwise Sleep would sit there disabled. - return replacesSleep && (action === 'suspend' || !hasSleepableActivity) ? ( + // only while it has restored panels to close; otherwise Sleep would sit there disabled. Not on + // Orca Cloud (Neil): there that "Sleep" read as a second, contradictory item beside Wake; the + // cloud row has exactly one lifecycle item, Sleep or Wake. + return cloud || (replacesSleep && (action === 'suspend' || !hasSleepableActivity)) ? ( vmItem ) : ( <> diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 4c398ff8e82..c1c7b66857f 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -24143,6 +24143,7 @@ "picker": { "title": "Open cloud workspace", "description": "Cloud workspaces that aren’t in your sidebar: shared by teammates, or started on another computer.", + "descriptionOwn": "Your cloud workspaces that aren’t in your sidebar, such as ones started on another computer.", "teammateTitle": "{{name}}’s cloud workspaces", "teammateDescription": "The ones they own or started that you can see.", "runningTitle": "Your running cloud workspaces", @@ -27579,8 +27580,6 @@ "usage": "CPU {{cpu}}% · Memory {{used}} / {{total}} GB", "syncOff": "Off", "syncError": "Couldn’t sync", - "mirroringAndContext": "Mirroring · .context synced", - "mirroring": "Mirroring", "contextSynced": ".context synced", "more": "More actions", "details": "Details", @@ -29202,7 +29201,6 @@ } }, "orcaCloudSync": { - "menuItem": "Mirror to this computer…", "gb": "{{value}} GB", "mb": "{{value}} MB", "kb": "{{value}} KB", @@ -29227,15 +29225,13 @@ "syncedEmpty": "Synced · {{ago}}", "contextLabel": ".context folder", "contextHelper": "Plans and screenshots from this workspace, synced to this computer.", - "mirrorLabel": "Mirror to this computer", - "mirrorHelper": "A read-only copy of this workspace’s files, kept up to date while it runs.", "openFolder": "Open folder", "copied": "Copied", "copyPath": "Copy path", "tryAgain": "Try again", "editedHere_one": "{{count}} file changed on this computer. Edits here don’t sync back. The cloud copy replaces it when it changes.", "editedHere_other": "{{count}} files changed on this computer. Edits here don’t sync back. The cloud copy replaces them when it changes.", - "overLimit": "The mirror is limited to {{size}}. Larger files and anything past the limit aren’t copied.", + "overLimit": "The .context folder is limited to {{size}}. Larger files and anything past the limit aren’t copied.", "tooLarge": "Files over {{size}} aren’t copied.", "removal": "The copy on this computer is removed too." }, diff --git a/src/renderer/src/lib/orca-cloud/cloud-glossary-lint.test.ts b/src/renderer/src/lib/orca-cloud/cloud-glossary-lint.test.ts index acf3f226132..6eb68f5196f 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-glossary-lint.test.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-glossary-lint.test.ts @@ -63,8 +63,8 @@ const RULES: Rule[] = [ { term: 'this Mac', pattern: /Sync to a local directory|\bthis Mac\b/i, - use: 'Mirror to this computer / this computer', - row: 'Mirror to this computer' + use: 'this computer', + row: 'On this computer' }, { term: 'credits', pattern: /\bcredits?\b/i, use: 'sandbox hours', row: 'Time unit' }, { diff --git a/src/renderer/src/lib/orca-cloud/cloud-share-links-flag.ts b/src/renderer/src/lib/orca-cloud/cloud-share-links-flag.ts deleted file mode 100644 index 70abe34e6f5..00000000000 --- a/src/renderer/src/lib/orca-cloud/cloud-share-links-flag.ts +++ /dev/null @@ -1,22 +0,0 @@ -// SHARE-LINKS-HOLD (Neil): cloud workspace share links are held for this release. The code stays; -// every way to produce a link (Copy › Workspace link / chat link, the cloud list's Copy link items, -// ⌘⌥⇧L and its Settings entry) is off unless the account's capabilities turn on `cloudShareLinks`. -// Opening an orca://cloud link someone already has still works. Share with team (visibility) stays. -import { useAppStore } from '@/store' -import type { OrcaProfileAuthStatus } from '../../../../shared/orca-profiles' - -export const CLOUD_SHARE_LINKS_FLAG = 'cloudShareLinks' -export const CLOUD_SHARE_LINK_ACTION_ID = 'cloudWorkspace.copyLink' - -function enabledFor(status: OrcaProfileAuthStatus | null | undefined): boolean { - return status?.capabilities?.flags[CLOUD_SHARE_LINKS_FLAG] === true -} - -/** Outside React (keyboard handlers, the copy itself, Settings' shortcut list). */ -export function cloudShareLinksEnabled(): boolean { - return enabledFor(useAppStore.getState().orcaProfileAuthStatus) -} - -export function useCloudShareLinksEnabled(): boolean { - return useAppStore((state) => enabledFor(state.orcaProfileAuthStatus)) -} diff --git a/src/renderer/src/lib/orca-cloud/cloud-sync-store.ts b/src/renderer/src/lib/orca-cloud/cloud-sync-store.ts index eecdaa6cef3..5bc1f2bc223 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-sync-store.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-sync-store.ts @@ -59,13 +59,9 @@ export function useCloudSync(workspaceId: string): CloudSyncView | null { return useSyncExternalStore(subscribe, () => views.get(workspaceId) ?? null) } -export function isCloudSyncAvailable(): boolean { - return api() !== null -} - export async function setCloudSyncChoice( workspaceId: string, - patch: { context?: boolean; mirror?: boolean } + patch: { context?: boolean } ): Promise { const bridge = api() const current = views.get(workspaceId) @@ -97,40 +93,3 @@ export function seedCloudSyncView(view: CloudSyncView): void { requested.add(view.workspaceId) put(view) } - -/** "Mirror to this computer…" from the workspace menu: the popover opens on the sync section. */ -const focusRequests = new Set() -const focusListeners = new Set<() => void>() -/** Lets the workspace menu finish closing (it hands focus back to its trigger) before the popover opens. */ -const MENU_CLOSE_SETTLE_MS = 150 - -export function requestCloudSyncFocus(workspaceId: string): void { - setTimeout(() => { - focusRequests.add(workspaceId) - for (const listener of focusListeners) { - listener() - } - }, MENU_CLOSE_SETTLE_MS) -} -export function takeCloudSyncFocus(workspaceId: string): boolean { - return focusRequests.delete(workspaceId) -} -/** Calls `listener` when the menu asks for this workspace's sync section (an event, not state). */ -export function onCloudSyncFocusRequest(workspaceId: string, listener: () => void): () => void { - const wrapped = (): void => { - if (focusRequests.has(workspaceId)) { - listener() - } - } - focusListeners.add(wrapped) - return () => focusListeners.delete(wrapped) -} -export function useCloudSyncFocusRequest(workspaceId: string): boolean { - return useSyncExternalStore( - (listener) => { - focusListeners.add(listener) - return () => focusListeners.delete(listener) - }, - () => focusRequests.has(workspaceId) - ) -} diff --git a/src/renderer/src/lib/orca-cloud/cloud-team-sharing-flag.ts b/src/renderer/src/lib/orca-cloud/cloud-team-sharing-flag.ts new file mode 100644 index 00000000000..f0bd234706b --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-team-sharing-flag.ts @@ -0,0 +1,28 @@ +// TEAM-SHARING-HOLD (Neil): sharing cloud workspaces with the team is held for a future release. The +// code stays; the desktop offers none of it unless the account's capabilities turn on +// `cloudTeamSharing` (absent = off, so an older or unaware control plane never brings it back): +// - Share with team / Make private (sidebar, the cloud list, the workspace panel); +// - the private/shared badges and Settings' visibility labels; +// - the "Team" scope of Open cloud workspace…, and the people chip on a workspace; +// - share links (Copy › Workspace link / chat link, the list's Copy link items, ⌘⌥⇧L and its +// Settings entry), since a link only helps someone else open a shared workspace. +// Opening an orca://cloud link still works; one to a workspace you can't open shows the usual +// no-access message. +import { useAppStore } from '@/store' +import type { OrcaProfileAuthStatus } from '../../../../shared/orca-profiles' + +export const CLOUD_TEAM_SHARING_FLAG = 'cloudTeamSharing' +export const CLOUD_SHARE_LINK_ACTION_ID = 'cloudWorkspace.copyLink' + +function enabledFor(status: OrcaProfileAuthStatus | null | undefined): boolean { + return status?.capabilities?.flags[CLOUD_TEAM_SHARING_FLAG] === true +} + +/** Outside React (keyboard handlers, the copy itself, action groups, Settings' shortcut list). */ +export function cloudTeamSharingEnabled(): boolean { + return enabledFor(useAppStore.getState().orcaProfileAuthStatus) +} + +export function useCloudTeamSharingEnabled(): boolean { + return useAppStore((state) => enabledFor(state.orcaProfileAuthStatus)) +} diff --git a/src/shared/cloud-sync/cloud-sync-contract.ts b/src/shared/cloud-sync/cloud-sync-contract.ts index 18b64fb89d2..89b4a47bcfc 100644 --- a/src/shared/cloud-sync/cloud-sync-contract.ts +++ b/src/shared/cloud-sync/cloud-sync-contract.ts @@ -1,5 +1,5 @@ -// Cloud → this computer file sync for Orca Cloud workspaces: `.context` (on by default) and an -// optional read-only mirror of the whole workspace. Main owns the sync; the window shows state. +// Cloud → this computer file sync for Orca Cloud workspaces: the `.context` folder (plans and +// screenshots, on by default). Main owns the sync; the window shows state. export const ORCA_CLOUD_SYNC_CHANNELS = { getState: 'orcaCloudSync:getState', @@ -10,10 +10,10 @@ export const ORCA_CLOUD_SYNC_CHANNELS = { changed: 'orcaCloudSync:changed' } as const -export type CloudSyncChoiceState = { context: boolean; mirror: boolean } +export type CloudSyncChoiceState = { context: boolean } export type CloudSyncPhase = - /** Both rows off: nothing on this computer. */ + /** Sync off: nothing on this computer. */ | 'off' /** First pass in flight, nothing copied yet. */ | 'starting' @@ -57,11 +57,7 @@ export type CloudSyncRemovalPreview = { hasLocalCopy: boolean; editedHere: numbe export type CloudSyncApi = { getState: (workspaceId: string) => Promise - setChoice: (args: { - workspaceId: string - context?: boolean - mirror?: boolean - }) => Promise + setChoice: (args: { workspaceId: string; context?: boolean }) => Promise openFolder: (workspaceId: string) => Promise<{ ok: boolean }> retry: (workspaceId: string) => Promise removalPreview: (workspaceId: string) => Promise