Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
Agents controller: an installable CLI (install.sh, service, doctor, update, env file, keychain) (#671)
Louis Amaudruzb509d83aace7
diff --git a/.github/workflows/agent-controller-release.yml b/.github/workflows/agent-controller-release.ymlnew file mode 100644index 000000000..7e2b68a53--- /dev/null+++ b/.github/workflows/agent-controller-release.yml@@ -0,0 +1,103 @@+name: switch-agent-controller release++# Builds the installable agents controller (console/packages/agent-controller)+# and publishes it as a GitHub release: the npm package+# `switch-agent-controller-<version>.tgz`, installed with+# `npm install --global <its URL>`, and the `install.sh` that finds and installs+# the newest one. `switch-agent-controller update` and `install.sh` read these+# releases, so nothing needs an npm registry or token.+#+# Trigger by pushing a tag like `switch-agent-controller-v0.2.0`; the package+# is built with the tag's version. `workflow_dispatch` builds and tests it+# without releasing, for verification. See RELEASING.md.++on:+ push:+ tags:+ - 'switch-agent-controller-v*'+ workflow_dispatch:++jobs:+ release:+ name: Build, test and release+ runs-on: ubuntu-latest+ permissions:+ contents: write+ defaults:+ run:+ working-directory: console+ steps:+ - name: Checkout+ uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4++ - name: Set up pnpm+ uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4+ with:+ version: 11.5.3++ - name: Set up Node+ uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4+ with:+ node-version-file: console/.nvmrc+ cache: pnpm+ cache-dependency-path: console/pnpm-lock.yaml++ - name: Resolve version+ id: version+ env:+ REF: ${{ github.ref }}+ run: |+ case "$REF" in+ refs/tags/switch-agent-controller-v*)+ version="${REF#refs/tags/switch-agent-controller-v}"+ if ! printf '%s' "$version" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$'; then+ echo "::error::The tag's version must be x.y.z, not '$version'."+ exit 1+ fi+ # Stamped on the runner, not committed: the CLI reports the version it was built with.+ (cd packages/agent-controller && npm pkg set version="$version")+ echo "release=true" >> "$GITHUB_OUTPUT"+ ;;+ *)+ version="$(node -p "require('./packages/agent-controller/package.json').version")"+ echo "release=false" >> "$GITHUB_OUTPUT"+ ;;+ esac+ echo "version=$version" >> "$GITHUB_OUTPUT"++ - name: Install dependencies+ run: pnpm install --frozen-lockfile++ - name: Build the workspace packages+ run: pnpm -r --filter './packages/**' run build++ - name: Test the controller+ run: pnpm --filter @switch-console/agent-controller run test++ - name: Package+ run: pnpm --filter @switch-console/agent-controller run package++ - name: Smoke-test the package+ env:+ VERSION: ${{ steps.version.outputs.version }}+ run: |+ prefix="$(mktemp -d)"+ npm install --global --prefix "$prefix" "packages/agent-controller/dist-package/switch-agent-controller-$VERSION.tgz"+ test "$("$prefix/bin/switch-agent-controller" --version)" = "$VERSION"+ "$prefix/bin/switch-agent-controller" --help > /dev/null++ - name: Release+ if: steps.version.outputs.release == 'true'+ env:+ GH_TOKEN: ${{ github.token }}+ VERSION: ${{ steps.version.outputs.version }}+ TAG: ${{ github.ref_name }}+ run: |+ gh release create "$TAG" \+ "packages/agent-controller/dist-package/switch-agent-controller-$VERSION.tgz" \+ packages/agent-controller/install.sh \+ --title "switch-agent-controller $VERSION" \+ --notes "The Switch agents controller $VERSION, for running managed agents on your own Linux or macOS machines.++ Install (Node 22.13 or later): \`npm install --global https://github.com/$GITHUB_REPOSITORY/releases/download/$TAG/switch-agent-controller-$VERSION.tgz\`, or run \`install.sh\`. Then enroll with a code from the Machines page and run \`switch-agent-controller install-service\`. An installed controller updates with \`switch-agent-controller update\`." \+ --latest=falsediff --git a/CHANGELOG.md b/CHANGELOG.mdindex a083c9497..1623ac8f2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3038,6 +3038,37 @@ per-release notes on their GitHub Releases (`switch-console-v*` tags).---+## agent-controller++The headless agents controller, `switch-agent-controller`+(`console/packages/agent-controller/`), released on `switch-agent-controller-v*`+tags; see RELEASING.md.++### [Unreleased]++#### Added+- **Installable on its own.** Each release publishes one npm package (the CLI and+ the shared-host bundle, no dependencies) and an `install.sh`, which checks Node,+ installs the newest release, and can enroll the machine and install the service+ in one go.+- **`install-service` / `uninstall-service`:** runs the controller as a systemd user+ unit on Linux or a launchd agent on macOS, restarted only after an error that may+ pass.+- **`doctor`:** checks Node, enrollment, the credential, the server (including a+ proxy that does not route `/v1` to switch-core), each provider CLI and its+ sign-in, the service, and updates.+- **`update`:** installs the newest release and restarts the service. `run` logs+ when a newer one exists.+- **`run --env-file` and `install-service --env-file`:** environment for the agents,+ such as provider API keys or Vertex AI and Bedrock settings. Sessions now inherit+ the Vertex and Bedrock variables Claude Code reads (`ANTHROPIC_VERTEX_PROJECT_ID`,+ `CLOUD_ML_REGION`, `ANTHROPIC_BEDROCK_BASE_URL`, …).+- **`enroll --secret-store`:** keeps the controller credential in the macOS keychain+ (the default on a Mac) or the desktop keyring, as well as in owner-only files (the+ default elsewhere).++---+## agent-runtimeThe Switch protocol client and MCP runtimediff --git a/RELEASING.md b/RELEASING.mdindex 834d70b2b..7e19f361c 100644--- a/RELEASING.md+++ b/RELEASING.md@@ -169,6 +169,35 @@ The canary app only reads GitHub's 10 most recent releases, and core and stablereleases count toward them. If 10 of those are published after the newest canary,canary installs find no update until the next canary is tagged.+## switch-agent-controller release (separate)++The headless agents controller (`console/packages/agent-controller`), which runs+managed agents on a customer's own Linux or macOS machine, releases on its own tag,+`switch-agent-controller-v<version>`, via+`.github/workflows/agent-controller-release.yml`:++```bash+git tag switch-agent-controller-v0.2.0 <commit on main>+git push origin switch-agent-controller-v0.2.0+```++- **The tag sets the version.** It must be `x.y.z`; the workflow stamps it into the+ package on the runner, so `package.json` is not bumped. The controller reports it+ to Switch and compares it with newer releases.+- **What it publishes:** a GitHub Release holding+ `switch-agent-controller-<version>.tgz` (one npm package with the CLI and the+ shared-host bundle, no dependencies) and `install.sh`. It is never marked Latest,+ so Switch Console's stable updater never sees it.+- **How installs find it:** `install.sh` and `switch-agent-controller update` list the+ repository's releases and take the highest non-draft, non-prerelease controller tag+ that carries its package. No npm registry or token is involved.+- **Canary visibility:** each controller release counts toward the 10 most recent+ releases the Console canary updater reads (see Canary builds above).+- **Not gated:** the workflow needs no approval. It tests the controller, packs it,+ installs the package and runs it once before releasing.++`workflow_dispatch` runs everything except the release, for verification.+## Where artifacts are publishedThe images, the chart, and the standalone compose artifact all go to **GitHubdiff --git a/console/.gitignore b/console/.gitignoreindex 234ec9fc2..14f423b9d 100644--- a/console/.gitignore+++ b/console/.gitignore@@ -6,6 +6,7 @@ out/# The connection-model benchmark's own bundle of its host entrypoint.packages/*/dist-bench/+packages/*/dist-package/# App-specific outputsapps/*/out/diff --git a/console/packages/agent-controller/README.md b/console/packages/agent-controller/README.mdindex a88afe577..431c98b0c 100644--- a/console/packages/agent-controller/README.md+++ b/console/packages/agent-controller/README.md@@ -30,27 +30,52 @@ relay accepts.- macOS or Linux. The shared host needs POSIX process control.- Node 22.13 or later. The store uses the built-in `node:sqlite`.-- The workspace packages built, so the shared-host bundle exists:- `pnpm install && pnpm -r --filter './packages/**' run build` from `console/`.- Each provider CLI the agents use, installed on `PATH` and signed in as the userthe controller runs as (`claude`, `codex`, `opencode`, `agent`/`cursor-agent`,- `antigravity-acp`).-- A Switch server with `AGENT_MANAGEMENT_ENABLED=true`.+ `antigravity-acp`), or its API key in the `--env-file` the controller runs with.+- A Switch server with `AGENT_MANAGEMENT_ENABLED=true`. Behind a proxy or ingress,+ `/v1` must reach switch-core (the Helm chart routes it).++## Install++Each `switch-agent-controller-v*` release on GitHub carries one npm package, the CLI+and the shared-host bundle it runs agents with, with no dependencies. The gateway's+Machines page shows the one command that installs it, enrolls the machine and starts+it as a service:++```bash+curl -fsSL https://raw.githubusercontent.com/sandbox-quantum/switch/main/console/packages/agent-controller/install.sh \+ | sh -s -- --server https://switch.example.com --code <code>+```++Without `--server` and `--code`, `install.sh` only installs. It installs with+`npm install --global`, so npm's global prefix must be writable by the user+(`npm config set prefix ~/.local` otherwise). The package can also be installed+directly: `npm install --global <the release's .tgz URL>`.++From a checkout, build the workspace packages+(`pnpm install && pnpm -r --filter './packages/**' run build` from `console/`) and+run `node packages/agent-controller/dist/cli.mjs`; `pnpm --filter+@switch-console/agent-controller run package` builds the release package into+`dist-package/`.## Enroll and runCreate a one-time enrollment code in Switch. It is valid for 10 minutes. Then:```bash-node packages/agent-controller/dist/cli.mjs enroll \+switch-agent-controller enroll \--server https://switch.example.com \--code <code> \- [--name build-box] [--description "The build box in the office"] [--data-dir <dir>]--node packages/agent-controller/dist/cli.mjs run [--data-dir <dir>]-node packages/agent-controller/dist/cli.mjs status [--data-dir <dir>]-node packages/agent-controller/dist/cli.mjs set-info [--name <name>] \- [--description <text>] [--data-dir <dir>]+ [--name build-box] [--description "The build box in the office"] [--data-dir <dir>] \+ [--secret-store keychain|secret-service|file]++switch-agent-controller install-service [--data-dir <dir>] [--env-file <path>]+switch-agent-controller run [--data-dir <dir>] [--env-file <path>]+switch-agent-controller status [--data-dir <dir>]+switch-agent-controller set-info [--name <name>] [--description <text>] [--data-dir <dir>]+switch-agent-controller doctor [--data-dir <dir>]+switch-agent-controller update [--check]```- `--server` is the agent bridge URL, and it must be `https`. Plain `http` is@@ -107,7 +132,71 @@ revision or an explicit restart. The other agents are not affected. An agent hosrunning as a separate process by an earlier version of the controller is stoppedbefore this one starts its own.-To run it as a service, have your init system run `run` and restart it on exit code+### As a service++`install-service` runs the controller as a service of the user who runs it: a+systemd user unit on Linux (`~/.config/systemd/user/switch-agent-controller.service`,+log with `journalctl --user -u switch-agent-controller`) or a launchd agent on macOS+(`~/Library/LaunchAgents/com.switch.agent-controller.plist`, logging to+`controller.log` in the data directory). It starts at once and at each login. On+Linux it also starts at boot and survives logout only with lingering on+(`sudo loginctl enable-linger <user>`), which it says when it is off. The service+keeps the `PATH` of the shell that installed it, so the provider CLIs found then are+found by the service. A data directory other than the default gets a service name+with a hash of its path, so two controllers on one account each get their own.+`uninstall-service` stops and removes it and keeps the enrollment.++On Linux without a systemd user manager (some containers and minimal VMs),+`install-service` refuses. Run `run` under your own supervisor instead, with the+restart rules below.++### Environment for the agents++`--env-file <path>` (on `run` and `install-service`) reads `NAME=value` lines,+as systemd's `EnvironmentFile=` does for the common cases (comments, blank lines,+`export `, single or double quotes), into the environment the agents inherit:++```bash+# Claude Code on Vertex AI, signed in with `gcloud auth application-default login`+CLAUDE_CODE_USE_VERTEX=1+ANTHROPIC_VERTEX_PROJECT_ID=my-project+CLOUD_ML_REGION=us-east5+```++Sessions inherit only the provider variables Switch knows (API keys, base URLs,+model overrides, and the Vertex AI, Bedrock and Google Cloud settings), plus the+basics a CLI needs. The file is read once at start; restart the service after+changing it.++### The controller credential++`enroll --secret-store` says where the controller credential is kept, and the data+directory remembers it:++- `keychain`, the default on macOS: the login keychain, through `security`. The+ launchd agent runs in the user's session and can read it.+- `secret-service`: the desktop keyring on Linux (GNOME Keyring, KWallet), through+ `secret-tool`. Choose it only where the keyring is unlocked whenever the controller+ starts, which a service started at boot usually is not.+- `file`, the default on Linux: a file only the user can read, in the data directory.++### Updates++`update` installs the newest release with npm and restarts the service if it runs;+`update --check` only says whether there is one. `run` logs a warning when a newer+release exists, and `doctor` shows it.++### Checking a machine++`doctor` checks what a machine needs to run agents and says what to do where it+falls short: Node, the platform, enrollment, the credential, the server (exchanging+the credential, so a proxy that does not send `/v1` to switch-core shows up),+the shared-host bundle, each provider CLI on `PATH` and its sign-in, the service,+and updates. It exits 1 when a check fails.++### Running under your own supervisor++To run it under another supervisor, have it run `run` and restart it on exit code`1` only. Do not restart it on `2`, because it would fail the same way until itsconfiguration is fixed, nor on `3`, because a revoked controller must be enrolledagain, nor on `4`, because two instances would take the stream from each other in@@ -283,8 +372,7 @@ session hosts it launches with `process.execPath` run as Node too.agent host is not connected, is dropped with a warning in the log. Switch keeps nocopy to send again.- Only enrollment by one-time code, or adoption of an identity a parent process- enrolled (see "Run by a parent process"). There is no EC2 machine secret, and- the controller itself has no OS keychain backend.+ enrolled (see "Run by a parent process"). There is no EC2 machine secret.- No session limit is enforced. `sessions_max` is reported as `0`.- OOM kills are not detected. `oom_kills` is always `0`.- `restarts_10m` counts the relaunches reconciling made, not the restarts after a@@ -308,7 +396,7 @@ It holds:| Path | What ||---|---|| `controller.db` | SQLite: identity, cached assignment, per-agent applied revision and local failures, restart times, each agent's stream cursor, the relay's port, status seq. Everything except the identity can be rebuilt from the server. |-| `secrets/controller-credential` | The controller credential (see below). Absent when the credential is handed over with `--credential-stdin`. |+| `secrets/controller-credential` | The controller credential, with the `file` secret store (see below). Absent with a keychain store, or when the credential is handed over with `--credential-stdin`. || `agents/<id>/credentials.json` | Each agent's relay endpoint, relay token and hub, in the layout the shared host reads. No Switch credential. || `agent hosts/<id>/` | Each agent's agent host state root: `watch.json`, `config.json`, `health.json` (what `status` reads), its journal, and `supervisor/failure.json` once it has failed for good. |@@ -323,9 +411,9 @@ Sessions an agent host starts keep their state where the shared host puts it## The file secret store-Run on its own, v1 keeps the controller credential in a plaintext file. The file has mode 0600 and-sits in a 0700 directory. No OS keychain backend exists yet, and the controller logs-a warning saying so every time it starts. Anyone who can read this user's files, or+With the `file` secret store (the default on Linux), the controller credential is a+plaintext file. The file has mode 0600 and sits in a 0700 directory, and the+controller logs a warning saying so every time it starts. Anyone who can read this user's files, ora backup of them, can act as this controller until it is revoked. If the file isever readable by other users, the controller refuses to use it. In that case, revokethe controller in Switch and enroll it again.diff --git a/console/packages/agent-controller/install.sh b/console/packages/agent-controller/install.shnew file mode 100755index 000000000..7fdd98c38--- /dev/null+++ b/console/packages/agent-controller/install.sh@@ -0,0 +1,116 @@+#!/bin/sh+# Installs the Switch agents controller (switch-agent-controller) with npm,+# from the newest controller release on GitHub, and optionally enrolls this+# machine and installs the controller as a service of this user.+#+# curl -fsSL <url of this file> | sh+# curl -fsSL <url of this file> | sh -s -- --server <Switch API URL> --code <code> [--name <name>] [--description <text>]+#+# Options:+# --server <url> --code <code> Enroll with a one-time code from the Machines page.+# --name <name> The machine's name in Switch (default: the host name).+# --description <text> What the machine is for, shown on the Machines page.+# --no-service Enroll, but do not install the service.+# --version <x.y.z> Install this release rather than the newest.+#+# SWITCH_CONTROLLER_RELEASES_REPOSITORY (owner/name) installs from a fork's releases.+set -eu++REPO="${SWITCH_CONTROLLER_RELEASES_REPOSITORY:-sandbox-quantum/switch}"+TAG_PREFIX="switch-agent-controller-v"++fail() {+ echo "switch-agent-controller install: $*" >&2+ exit 1+}++SERVER=""+CODE=""+NAME=""+DESCRIPTION=""+SERVICE=1+VERSION=""+while [ $# -gt 0 ]; do+ case "$1" in+ --server) [ $# -ge 2 ] || fail "--server needs a URL."; SERVER="$2"; shift 2 ;;+ --code) [ $# -ge 2 ] || fail "--code needs a code."; CODE="$2"; shift 2 ;;+ --name) [ $# -ge 2 ] || fail "--name needs a name."; NAME="$2"; shift 2 ;;+ --description) [ $# -ge 2 ] || fail "--description needs a text."; DESCRIPTION="$2"; shift 2 ;;+ --no-service) SERVICE=0; shift ;;+ --version) [ $# -ge 2 ] || fail "--version needs x.y.z."; VERSION="$2"; shift 2 ;;+ *) fail "Unknown option '$1'." ;;+ esac+done+if [ -n "$SERVER" ] && [ -z "$CODE" ]; then fail "--server needs --code too."; fi+if [ -z "$SERVER" ] && [ -n "$CODE" ]; then fail "--code needs --server too."; fi++case "$(uname -s)" in+ Linux | Darwin) ;;+ *) fail "The controller runs on Linux and macOS only." ;;+esac+command -v curl >/dev/null 2>&1 || fail "curl is needed."+command -v node >/dev/null 2>&1 || fail "Node 22.13 or later is needed (https://nodejs.org)."+command -v npm >/dev/null 2>&1 || fail "npm is needed; it comes with Node."+node -e 'const [a, b] = process.versions.node.split(".").map(Number); process.exit(a > 22 || (a === 22 && b >= 13) ? 0 : 1)' ||+ fail "Node $(node --version) is too old; the controller needs 22.13 or later."++if [ -n "$VERSION" ]; then+ case "$VERSION" in+ *[!0-9.]* | "") fail "--version must be x.y.z." ;;+ esac+ URL="https://github.com/$REPO/releases/download/$TAG_PREFIX$VERSION/switch-agent-controller-$VERSION.tgz"+else+ # The repository also releases Switch and Switch Console: take the highest+ # controller release that carries its package, leaving out drafts and prereleases.+ URL="$(curl -fsSL -H 'Accept: application/vnd.github+json' "https://api.github.com/repos/$REPO/releases?per_page=100" |+ TAG_PREFIX="$TAG_PREFIX" node -e '+ let input = "";+ process.stdin.on("data", (chunk) => (input += chunk));+ process.stdin.on("end", () => {+ const prefix = process.env.TAG_PREFIX;+ const parse = (v) => (/^\d+\.\d+\.\d+$/.test(v) ? v.split(".").map(Number) : null);+ let best = null;+ for (const release of JSON.parse(input)) {+ if (release.draft || release.prerelease || !release.tag_name.startsWith(prefix)) continue;+ const version = release.tag_name.slice(prefix.length);+ const parts = parse(version);+ const asset = release.assets.find((a) => a.name === `switch-agent-controller-${version}.tgz`);+ if (!parts || !asset) continue;+ const order = (x, y) => x[0] - y[0] || x[1] - y[1] || x[2] - y[2];+ if (!best || order(parts, best.parts) > 0) best = { parts, url: asset.browser_download_url };+ }+ if (best) process.stdout.write(best.url);+ });+ ')" || fail "Could not list the releases of $REPO."+ [ -n "$URL" ] || fail "$REPO has no switch-agent-controller release yet."+fi++PREFIX="$(npm config get prefix)"+if [ ! -w "$PREFIX" ] && [ ! -w "$PREFIX/lib/node_modules" ]; then+ fail "npm installs global packages into $PREFIX, which this user cannot write. Point npm at a folder of yours, then run this again:+ npm config set prefix \"\$HOME/.local\" (and make sure \$HOME/.local/bin is on your PATH)"+fi++echo "Installing $URL"+npm install --global "$URL"+BIN="$PREFIX/bin/switch-agent-controller"+[ -x "$BIN" ] || fail "npm did not install $BIN."++if [ -z "$SERVER" ]; then+ echo+ echo "Installed $("$BIN" --version). Next, with a code from the Machines page in Switch:"+ echo " switch-agent-controller enroll --server <Switch API URL> --code <code>"+ echo " switch-agent-controller install-service"+ echo "Check this machine with: switch-agent-controller doctor"+ exit 0+fi++set -- enroll --server "$SERVER" --code "$CODE"+if [ -n "$NAME" ]; then set -- "$@" --name "$NAME"; fi+if [ -n "$DESCRIPTION" ]; then set -- "$@" --description "$DESCRIPTION"; fi+"$BIN" "$@"+if [ "$SERVICE" = 1 ]; then+ "$BIN" install-service+fi+echo+"$BIN" doctordiff --git a/console/packages/agent-controller/package.json b/console/packages/agent-controller/package.jsonindex 28147897a..46484dfe9 100644--- a/console/packages/agent-controller/package.json+++ b/console/packages/agent-controller/package.json@@ -21,7 +21,8 @@"lint": "sh -c 'root=$(cd ../.. && pwd); cd \"$root/apps/switch-console-desktop\" && pnpm exec oxlint --config .oxlintrc.json \"$root/packages/agent-controller\"'","format": "oxfmt","format:check": "oxfmt --check",- "typecheck": "tsgo --noEmit -p tsconfig.json"+ "typecheck": "tsgo --noEmit -p tsconfig.json",+ "package": "node scripts/package.mjs"},"dependencies": {"@switch-console/agent-providers": "workspace:*",@@ -34,6 +35,7 @@"@types/node": "^24.13.3","@types/ws": "^8.18.2","@typescript/native-preview": "7.0.0-dev.20260609.1",+ "esbuild": "0.25.12","tsdown": "^0.22.2","vitest": "^5.0.1"},diff --git a/console/packages/agent-controller/scripts/package.mjs b/console/packages/agent-controller/scripts/package.mjsnew file mode 100644index 000000000..2c6079e22--- /dev/null+++ b/console/packages/agent-controller/scripts/package.mjs@@ -0,0 +1,91 @@+import { execFileSync } from 'node:child_process';+import { copyFile, mkdir, readFile, rm, writeFile } from 'node:fs/promises';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { build } from 'esbuild';++/**+ * Builds the installable controller: one npm package holding the CLI and the+ * shared-host bundle it runs agents with, each bundled whole so the package+ * has no dependencies to install, then packs it into+ * `dist-package/switch-agent-controller-<version>.tgz` for+ * `npm install --global <file or URL>`.+ *+ * The version is this package's: a release sets it from the tag before+ * running this, and the CLI reports what it was built with.+ */+const root = join(dirname(fileURLToPath(import.meta.url)), '..');+const out = join(root, 'dist-package');+const stage = join(out, 'package');+const manifest = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'));+const { version } = manifest;+if (!/^\d+\.\d+\.\d+$/.test(version))+ throw new Error(`The package version must be x.y.z to be released, not '${version}'.`);++/** Kept out, as in Switch Console's own bundle: the controller must stay headless. */+const FORBIDDEN = ['electron', 'better-sqlite3', 'drizzle-orm'];+const headless = {+ name: 'headless',+ setup(pluginBuild) {+ pluginBuild.onResolve({ filter: /.*/ }, (args) => {+ const hit = FORBIDDEN.find((name) => args.path === name || args.path.startsWith(`${name}/`));+ return hit+ ? {+ errors: [+ { text: `The controller must not depend on '${hit}' (from ${args.importer}).` },+ ],+ }+ : null;+ });+ },+};+const common = {+ bundle: true,+ platform: 'node',+ format: 'esm',+ target: 'node22',+ logLevel: 'warning',+ plugins: [headless],+ // Bundled CommonJS dependencies still call require.+ banner: {+ js: "import { createRequire as createPackagedRequire } from 'node:module'; const require = createPackagedRequire(import.meta.url);",+ },+};++await rm(out, { recursive: true, force: true });+await mkdir(stage, { recursive: true });+await build({+ ...common,+ entryPoints: [join(root, 'src', 'cli.ts')],+ outfile: join(stage, 'cli.mjs'),+ tsconfig: join(root, 'tsconfig.json'),+});+await build({+ ...common,+ entryPoints: [join(root, '..', 'agent-providers', 'src', 'host', 'shared-daemon.ts')],+ // The name the CLI looks for beside itself (PACKAGED_SHARED_HOST_BUNDLE).+ outfile: join(stage, 'shared-host.mjs'),+ tsconfig: join(root, '..', 'agent-providers', 'tsconfig.json'),+});+await writeFile(+ join(stage, 'package.json'),+ `${JSON.stringify(+ {+ name: 'switch-agent-controller',+ version,+ description: manifest.description,+ license: manifest.license,+ type: 'module',+ bin: { 'switch-agent-controller': './cli.mjs' },+ files: ['cli.mjs', 'shared-host.mjs', 'README.md', 'LICENSE'],+ engines: manifest.engines,+ os: ['darwin', 'linux'],+ },+ null,+ 2+ )}\n`+);+await copyFile(join(root, 'README.md'), join(stage, 'README.md'));+await copyFile(join(root, '..', '..', '..', 'LICENSE'), join(stage, 'LICENSE'));+execFileSync('npm', ['pack', '--pack-destination', out], { cwd: stage, stdio: 'inherit' });+process.stdout.write(`${join(out, `switch-agent-controller-${version}.tgz`)}\n`);diff --git a/console/packages/agent-controller/src/doctor.test.ts b/console/packages/agent-controller/src/doctor.test.tsnew file mode 100644index 000000000..9378dee21--- /dev/null+++ b/console/packages/agent-controller/src/doctor.test.ts@@ -0,0 +1,97 @@+import { describe, expect, it } from 'vitest';+import { ControllerApiError } from './api';+import { type DoctorInputs, formatChecks, runDoctor } from './doctor';+import { MemorySecretStore } from './secrets';++function inputs(overrides: Partial<DoctorInputs> = {}): DoctorInputs {+ return {+ version: '0.2.0',+ nodeVersion: 'v22.13.0',+ platform: 'linux',+ dataDir: '/data',+ identity: {+ controllerId: 'controller-1',+ server: 'https://switch.example.invalid',+ name: 'build-box',+ enrolledAt: '2026-10-01T00:00:00Z',+ },+ revokedAt: null,+ secrets: new MemorySecretStore({ 'controller-credential': 'swcc_x' }, 'test'),+ bundle: () => '/opt/shared-host.mjs',+ exchange: async () => ({}),+ locate: async (provider) =>+ provider === 'claude' ? { path: '/usr/bin/claude', version: '2.1.0' } : null,+ probe: async () => ({ status: 'authenticated', message: 'Signed in.', models: [] }),+ service: async () => 'running',+ latest: async () => ({ version: '0.2.0', packageUrl: 'https://example.invalid/p.tgz' }),+ ...overrides,+ };+}++const status = (checks: Awaited<ReturnType<typeof runDoctor>>, name: string) =>+ checks.find((check) => check.name === name)?.status;++describe('doctor', () => {+ it('passes a machine that is ready', async () => {+ const checks = await runDoctor(inputs());+ expect(checks.filter((check) => check.status !== 'ok')).toEqual([]);+ expect(formatChecks(checks)).toContain('ok claude');+ });++ it('fails an old Node, and a machine with no signed-in provider', async () => {+ const checks = await runDoctor(+ inputs({+ nodeVersion: 'v22.12.0',+ probe: async () => ({+ status: 'unauthenticated',+ message: 'Run claude auth login',+ models: [],+ }),+ })+ );+ expect(status(checks, 'Node')).toBe('fail');+ expect(status(checks, 'claude')).toBe('warn');+ expect(status(checks, 'Providers')).toBe('fail');+ });++ it('points at the proxy when the server answers, but not as the Switch API', async () => {+ const checks = await runDoctor(+ inputs({+ exchange: async () => {+ throw new ControllerApiError(200, 'invalid_response', 'not the protocol', false, null);+ },+ })+ );+ expect(checks.find((check) => check.name === 'Server')?.detail).toMatch(+ /send \/v1 to switch-core/+ );+ });++ it('stops at enrollment when there is none, and says how to enroll', async () => {+ const checks = await runDoctor(inputs({ identity: null }));+ expect(status(checks, 'Enrollment')).toBe('fail');+ expect(checks.find((check) => check.name === 'Server')).toBeUndefined();+ });++ it('warns about a newer release, a stopped service, and a failed update check', async () => {+ expect(+ status(+ await runDoctor(+ inputs({ latest: async () => ({ version: '0.3.0', packageUrl: 'https://x.invalid' }) })+ ),+ 'Version'+ )+ ).toBe('warn');+ expect(status(await runDoctor(inputs({ service: async () => 'stopped' })), 'Service')).toBe(+ 'warn'+ );+ const offline = await runDoctor(+ inputs({+ latest: async () => {+ throw new Error('offline');+ },+ })+ );+ expect(offline.find((check) => check.name === 'Version')?.detail).toMatch(/offline/);+ });+});diff --git a/console/packages/agent-controller/src/doctor.ts b/console/packages/agent-controller/src/doctor.tsnew file mode 100644index 000000000..36d11a2ea--- /dev/null+++ b/console/packages/agent-controller/src/doctor.ts@@ -0,0 +1,217 @@+import type { ProviderReadiness } from '@switch-console/agent-providers';+import { ControllerApiError } from './api';+import { errorMessage } from './log';+import { PROVIDERS, type Provider } from './schemas';+import { CONTROLLER_CREDENTIAL, type SecretStore } from './secrets';+import type { ServiceState } from './service';+import type { LocatedProvider } from './status';+import type { Identity } from './store';+import { type ControllerRelease, isNewer } from './update';++export type CheckStatus = 'ok' | 'warn' | 'fail';+export type Check = { name: string; status: CheckStatus; detail: string };++/** The oldest Node the controller runs on: it needs the built-in `node:sqlite`. */+export const MIN_NODE: readonly [number, number] = [22, 13];++/** Everything `doctor` looks at, so it can be checked without the machine it describes. */+export type DoctorInputs = {+ version: string;+ nodeVersion: string;+ platform: NodeJS.Platform;+ dataDir: string;+ identity: Identity | null;+ revokedAt: string | null;+ secrets: SecretStore;+ /** The shared-host bundle's path; throws when there is none. */+ bundle: () => string;+ /** Exchanges the credential for a token: proof the server is reached and accepts it. */+ exchange: (server: string, controllerId: string, credential: string) => Promise<unknown>;+ locate: (provider: Provider) => Promise<LocatedProvider | null>;+ probe: (bundle: string, provider: Provider, binary: string) => Promise<ProviderReadiness>;+ service: () => Promise<ServiceState>;+ latest: () => Promise<ControllerRelease | null>;+};++function nodeCheck(nodeVersion: string): Check {+ const [major = 0, minor = 0] = nodeVersion.replace(/^v/, '').split('.').map(Number);+ const ok = major > MIN_NODE[0] || (major === MIN_NODE[0] && minor >= MIN_NODE[1]);+ return {+ name: 'Node',+ status: ok ? 'ok' : 'fail',+ detail: ok+ ? nodeVersion+ : `${nodeVersion}; the controller needs ${MIN_NODE.join('.')} or later.`,+ };+}++async function serverChecks(inputs: DoctorInputs): Promise<Check[]> {+ if (!inputs.identity)+ return [+ {+ name: 'Enrollment',+ status: 'fail',+ detail: `${inputs.dataDir} is not enrolled. Run: switch-agent-controller enroll --server <url> --code <code>, with a code from the Machines page.`,+ },+ ];+ const { identity } = inputs;+ const checks: Check[] = [+ {+ name: 'Enrollment',+ status: inputs.revokedAt ? 'fail' : 'ok',+ detail: inputs.revokedAt+ ? `Controller ${identity.controllerId} was revoked at ${inputs.revokedAt}; enroll this machine again.`+ : `Controller ${identity.controllerId} ("${identity.name}") on ${identity.server}`,+ },+ ];+ if (inputs.revokedAt) return checks;+ let credential: string | null;+ try {+ credential = await inputs.secrets.get(CONTROLLER_CREDENTIAL);+ } catch (error) {+ checks.push({+ name: 'Credential',+ status: 'fail',+ detail: `Cannot read it from ${inputs.secrets.description}: ${errorMessage(error)}`,+ });+ return checks;+ }+ if (!credential) {+ checks.push({+ name: 'Credential',+ status: 'fail',+ detail: `Not in ${inputs.secrets.description}; enroll this machine again.`,+ });+ return checks;+ }+ checks.push({ name: 'Credential', status: 'ok', detail: `In ${inputs.secrets.description}` });+ try {+ await inputs.exchange(identity.server, identity.controllerId, credential);+ checks.push({+ name: 'Server',+ status: 'ok',+ detail: `${identity.server} accepts this controller`,+ });+ } catch (error) {+ const detail =+ error instanceof ControllerApiError+ ? error.code === 'invalid_response' || error.code === 'unexpected_response'+ ? `${identity.server} answered, but not as the Switch API (${error.message}). If Switch runs behind a proxy or ingress, it must send /v1 to switch-core.`+ : `${error.code}: ${error.message}`+ : `${identity.server} cannot be reached: ${errorMessage(error)}`;+ checks.push({ name: 'Server', status: 'fail', detail });+ }+ return checks;+}++async function providerChecks(inputs: DoctorInputs, bundle: string | null): Promise<Check[]> {+ const checks: Check[] = [];+ let ready = 0;+ for (const provider of PROVIDERS) {+ const located = await inputs.locate(provider);+ if (!located) continue;+ const version = located.version ? ` ${located.version}` : '';+ if (!bundle) {+ checks.push({+ name: provider,+ status: 'warn',+ detail: `Installed${version}; sign-in not checked without the shared-host bundle.`,+ });+ continue;+ }+ try {+ const readiness = await inputs.probe(bundle, provider, located.path);+ if (readiness.status === 'authenticated') ready++;+ checks.push({+ name: provider,+ status: readiness.status === 'authenticated' ? 'ok' : 'warn',+ detail: `Installed${version}, ${readiness.status}${readiness.message ? `: ${readiness.message}` : ''}`,+ });+ } catch (error) {+ checks.push({+ name: provider,+ status: 'warn',+ detail: `Installed${version}; its sign-in could not be checked: ${errorMessage(error)}`,+ });+ }+ }+ if (ready === 0)+ checks.push({+ name: 'Providers',+ status: 'fail',+ detail:+ 'No provider CLI is installed and signed in on PATH for this user, so no agent can run here. Install one (claude, codex, opencode, cursor or antigravity) and sign in, or set its API key in the --env-file the service runs with.',+ });+ return checks;+}++/** Checks this machine can run the agents Switch places on it, and says what to do where it cannot. */+export async function runDoctor(inputs: DoctorInputs): Promise<Check[]> {+ const checks: Check[] = [nodeCheck(inputs.nodeVersion)];+ const supported = inputs.platform === 'darwin' || inputs.platform === 'linux';+ checks.push({+ name: 'Platform',+ status: supported ? 'ok' : 'fail',+ detail: supported+ ? inputs.platform+ : `${inputs.platform} is not supported; use Linux or macOS.`,+ });+ checks.push(...(await serverChecks(inputs)));+ let bundle: string | null = null;+ try {+ bundle = inputs.bundle();+ checks.push({ name: 'Shared host', status: 'ok', detail: bundle });+ } catch (error) {+ checks.push({ name: 'Shared host', status: 'fail', detail: errorMessage(error) });+ }+ checks.push(...(await providerChecks(inputs, bundle)));+ const service = await inputs.service().catch((error: unknown) => errorMessage(error));+ checks.push(+ service === 'running'+ ? { name: 'Service', status: 'ok', detail: 'Installed and running' }+ : service === 'stopped'+ ? { name: 'Service', status: 'warn', detail: 'Installed, but not running' }+ : service === 'not-installed'+ ? {+ name: 'Service',+ status: 'warn',+ detail:+ 'Not installed; run: switch-agent-controller install-service (or keep `run` going yourself)',+ }+ : { name: 'Service', status: 'warn', detail: `Cannot tell: ${service}` }+ );+ try {+ const latest = await inputs.latest();+ checks.push(+ !latest+ ? {+ name: 'Version',+ status: 'ok',+ detail: `${inputs.version}; no release is published yet`,+ }+ : isNewer(latest.version, inputs.version)+ ? {+ name: 'Version',+ status: 'warn',+ detail: `${inputs.version}; ${latest.version} is available: switch-agent-controller update`,+ }+ : { name: 'Version', status: 'ok', detail: `${inputs.version}, the latest` }+ );+ } catch (error) {+ checks.push({+ name: 'Version',+ status: 'warn',+ detail: `${inputs.version}; could not check for a newer one: ${errorMessage(error)}`,+ });+ }+ return checks;+}++const MARK: Record<CheckStatus, string> = { ok: 'ok ', warn: 'warn', fail: 'FAIL' };++export function formatChecks(checks: Check[]): string {+ const width = Math.max(...checks.map((check) => check.name.length));+ return checks+ .map((check) => `${MARK[check.status]} ${check.name.padEnd(width)} ${check.detail}`)+ .join('\n');+}diff --git a/console/packages/agent-controller/src/env-file.test.ts b/console/packages/agent-controller/src/env-file.test.tsnew file mode 100644index 000000000..78230e9d5--- /dev/null+++ b/console/packages/agent-controller/src/env-file.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from 'vitest';+import { parseEnvFile } from './env-file';+import { ConfigurationError } from './errors';++describe('parseEnvFile', () => {+ it('reads NAME=value lines, skipping comments and blanks, with export and quotes', () => {+ expect(+ parseEnvFile(+ [+ '# Vertex AI',+ 'CLAUDE_CODE_USE_VERTEX=1',+ '',+ 'export ANTHROPIC_VERTEX_PROJECT_ID=my-project',+ 'CLOUD_ML_REGION="us-east5"',+ "NOTE='kept as is $HOME'",+ 'QUOTED="say \\"hi\\""',+ 'EMPTY=',+ ].join('\n'),+ 'agents.env'+ )+ ).toEqual({+ CLAUDE_CODE_USE_VERTEX: '1',+ ANTHROPIC_VERTEX_PROJECT_ID: 'my-project',+ CLOUD_ML_REGION: 'us-east5',+ NOTE: 'kept as is $HOME',+ QUOTED: 'say "hi"',+ EMPTY: '',+ });+ });++ it('refuses what it would have to guess at, naming the line', () => {+ expect(() => parseEnvFile('A=1\nnot a line', 'agents.env')).toThrow(+ /agents\.env, line 2: expected NAME=value/+ );+ expect(() => parseEnvFile('A=two words', 'agents.env')).toThrow(/quote a value/);+ expect(() => parseEnvFile('A="open', 'agents.env')).toThrow(/closing " is missing/);+ expect(() => parseEnvFile('1A=x', 'agents.env')).toThrow(ConfigurationError);+ });+});diff --git a/console/packages/agent-controller/src/env-file.ts b/console/packages/agent-controller/src/env-file.tsnew file mode 100644index 000000000..fd94a5ead--- /dev/null+++ b/console/packages/agent-controller/src/env-file.ts@@ -0,0 +1,56 @@+import { readFile } from 'node:fs/promises';+import { ConfigurationError } from './errors';++const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;++/**+ * Parses an environment file the way systemd's `EnvironmentFile=` reads the+ * common cases, so one file serves both `run --env-file` and the service:+ * `NAME=value` per line, blank lines and `#` comments skipped, an optional+ * `export ` prefix, and a value in single or double quotes taken literally+ * (double quotes also unescape `\"` and `\\`). Anything else is refused with+ * its line number rather than guessed at.+ */+export function parseEnvFile(text: string, source: string): Record<string, string> {+ const values: Record<string, string> = {};+ const lines = text.split(/\r?\n/);+ for (const [index, raw] of lines.entries()) {+ const line = raw.trim();+ if (line === '' || line.startsWith('#')) continue;+ const body = line.startsWith('export ') ? line.slice('export '.length).trimStart() : line;+ const equals = body.indexOf('=');+ const name = equals === -1 ? '' : body.slice(0, equals).trim();+ if (!NAME.test(name))+ throw new ConfigurationError(+ `${source}, line ${index + 1}: expected NAME=value, where NAME is letters, digits and underscores.`+ );+ values[name] = unquote(body.slice(equals + 1).trim(), `${source}, line ${index + 1}`);+ }+ return values;+}++function unquote(value: string, where: string): string {+ const quote = value[0];+ if (quote !== '"' && quote !== "'") {+ if (/["'\s]/.test(value))+ throw new ConfigurationError(`${where}: quote a value that holds spaces or quotes.`);+ return value;+ }+ if (value.length < 2 || value.at(-1) !== quote)+ throw new ConfigurationError(`${where}: the value's closing ${quote} is missing.`);+ const inner = value.slice(1, -1);+ return quote === '"' ? inner.replace(/\\(["\\])/g, '$1') : inner;+}++/** Reads `path` as an environment file; see {@link parseEnvFile}. */+export async function readEnvFile(path: string): Promise<Record<string, string>> {+ let text: string;+ try {+ text = await readFile(path, 'utf8');+ } catch (error) {+ throw new ConfigurationError(+ `The environment file ${path} cannot be read: ${(error as Error).message}`+ );+ }+ return parseEnvFile(text, path);+}diff --git a/console/packages/agent-controller/src/handover.test.ts b/console/packages/agent-controller/src/handover.test.tsindex 9f1ed9be8..dce25cf45 100644--- a/console/packages/agent-controller/src/handover.test.ts+++ b/console/packages/agent-controller/src/handover.test.ts@@ -174,7 +174,7 @@ describe('resolveSharedHostBundle', () => {};expect(() => resolveSharedHostBundle(undefined, {}, unresolvable)).toThrow(ConfigurationError);expect(() => resolveSharedHostBundle(undefined, {}, unresolvable)).toThrow(- /none could be found in the workspace: Cannot find package/+ /none is installed beside the CLI or built in the workspace: Cannot find package/);});diff --git a/console/packages/agent-controller/src/handover.ts b/console/packages/agent-controller/src/handover.tsindex 1446226fe..747666eed 100644--- a/console/packages/agent-controller/src/handover.ts+++ b/console/packages/agent-controller/src/handover.ts@@ -1,4 +1,4 @@-import { accessSync, constants, statSync } from 'node:fs';+import { accessSync, constants, existsSync, statSync } from 'node:fs';import { resolve } from 'node:path';import { fileURLToPath } from 'node:url';import { normalizeServerUrl } from './api';@@ -108,23 +108,23 @@ export function adoptIdentity(/*** The agent-providers shared-host bundle the controller runs its agents with:- * `--shared-host-bundle`, then `SWITCH_CONTROLLER_SHARED_HOST_BUNDLE`, then the- * one built in the workspace. A packaged parent names its own copy, since a- * bundled controller has no workspace to resolve it from.+ * `--shared-host-bundle`, then `SWITCH_CONTROLLER_SHARED_HOST_BUNDLE`, then+ * `defaultBundle` ({@link defaultSharedHostBundle}: the one installed beside+ * the CLI, or the one built in the workspace).*/export function resolveSharedHostBundle(flag: string | undefined,env: NodeJS.ProcessEnv,- workspaceDefault: () => string+ defaultBundle: () => string): string {const named = flag ?? env[SHARED_HOST_BUNDLE_ENV];if (named) return readableBundle(resolve(named), `The shared host bundle ${resolve(named)}`);let path: string;try {- path = workspaceDefault();+ path = defaultBundle();} catch (error) {throw new ConfigurationError(- `No shared host bundle was named, and none could be found in the workspace: ${errorMessage(error)} Name one with --shared-host-bundle.`+ `No shared host bundle was named, and none is installed beside the CLI or built in the workspace: ${errorMessage(error)} Name one with --shared-host-bundle.`);}return readableBundle(@@ -153,6 +153,19 @@ function readableBundle(path: string, what: string, hint = ''): string {return path;}+/** The file name of the shared-host bundle in a packaged install, beside the CLI. */+export const PACKAGED_SHARED_HOST_BUNDLE = 'shared-host.mjs';++/**+ * The shared-host bundle installed beside the CLI, as the packaged controller+ * ships it; in a workspace checkout, where there is none, the one built there.+ */+export function defaultSharedHostBundle(): string {+ const beside = fileURLToPath(new URL(`./${PACKAGED_SHARED_HOST_BUNDLE}`, import.meta.url));+ if (existsSync(beside)) return beside;+ return workspaceSharedHostBundle();+}+/** The bundle as built in the workspace, resolved through the package's exports. */export function workspaceSharedHostBundle(): string {return fileURLToPath(import.meta.resolve('@switch-console/agent-providers/shared-host-daemon'));diff --git a/console/packages/agent-controller/src/main.ts b/console/packages/agent-controller/src/main.tsindex c2fbe0db2..0deeb1693 100644--- a/console/packages/agent-controller/src/main.ts+++ b/console/packages/agent-controller/src/main.ts@@ -1,4 +1,7 @@+import { spawn } from 'node:child_process';+import { realpathSync } from 'node:fs';import { hostname } from 'node:os';+import { resolve } from 'node:path';import { parseArgs } from 'node:util';import packageJson from '../package.json' with { type: 'json' };import {@@ -6,11 +9,14 @@ import {ControllerApiError,ControllerClient,enroll,+ exchangeToken,normalizeServerUrl,nodeWebSocket,} from './api';import { DEFAULT_TIMING, runController } from './controller';import { DetachedRuntime } from './detached-runtime';+import { formatChecks, runDoctor } from './doctor';+import { readEnvFile } from './env-file';import { ConfigurationError, UsageError } from './errors';import {EXIT_CONFIGURATION,@@ -24,8 +30,8 @@ import {adoptIdentity,CREDENTIAL_STDIN_TIMEOUT_MS,readCredential,+ defaultSharedHostBundle,resolveSharedHostBundle,- workspaceSharedHostBundle,} from './handover';import { createLogger, errorMessage } from './log';import { dataLayout, ensureDataDir, resolveDataDir, serverWorkspacesDir } from './paths';@@ -35,12 +41,29 @@ import {emptyObservation,InProcessRuntime,observeOnDisk,+ probeProvider,} from './runtime';import { AgentRuntimes } from './runtimes';import type { ControllerInfoChange } from './schemas';-import { CONTROLLER_CREDENTIAL, FileSecretStore, MemorySecretStore } from './secrets';+import {+ CONTROLLER_CREDENTIAL,+ defaultSecretStoreKind,+ isSecretStoreKind,+ MemorySecretStore,+ runCommand as runSecretCommand,+ SECRET_STORE_KINDS,+ secretStoreFor,+} from './secrets';+import {+ installService,+ LAUNCHD_FINAL_EXIT_CODES,+ restartService,+ serviceState,+ uninstallService,+} from './service';import { contractPlatform, mapAgentProcess, PathProviderLocator } from './status';import { ControllerStore } from './store';+import { isNewer, latestRelease, releasesRepository } from './update';export const VERSION: string = packageJson.version;@@ -71,6 +94,28 @@ Commands:clears the description. The same limits as at enrollment.status [--data-dir <dir>] [--shared-host-bundle <path>]Show this controller's identity and its agents, from local state only.+ install-service [--data-dir <dir>] [--env-file <path>] [--shared-host-bundle <path>]+ Run this controller as a service of this user: a systemd user unit on+ Linux, a launchd agent on macOS. It starts now and again at each login+ (at boot too, on Linux with lingering on), and restarts after an error+ that may pass. It keeps the PATH of the shell that installed it.+ uninstall-service [--data-dir <dir>]+ Stop the service and remove it. The enrollment and data are kept.+ doctor [--data-dir <dir>] [--shared-host-bundle <path>]+ Check this machine can run agents: Node, enrollment, the credential, the+ server, the provider CLIs and their sign-in, the service, and updates.+ update [--check] [--data-dir <dir>]+ Install the newest release with npm, and restart the service if it runs.+ --check only says whether there is one.++run --env-file and install-service --env-file read NAME=value lines (as for+systemd's EnvironmentFile) into the agents' environment: provider API keys, or+Vertex AI and Bedrock settings such as CLAUDE_CODE_USE_VERTEX,+ANTHROPIC_VERTEX_PROJECT_ID and CLOUD_ML_REGION.+enroll --secret-store keychain|secret-service|file says where the controller+credential is kept: the macOS keychain by default on a Mac, owner-only files+by default elsewhere. secret-service (the desktop keyring) needs an unlocked+keyring whenever the controller starts.The data directory defaults to SWITCH_CONTROLLER_DATA_DIR, then the OS default.The shared host bundle defaults to SWITCH_CONTROLLER_SHARED_HOST_BUNDLE, then@@ -81,18 +126,26 @@ Exit codes: 0 stopped, 1 error that may pass, 2 configuration error,`;function bundlePath(flag: string | undefined): string {- return resolveSharedHostBundle(flag, process.env, workspaceSharedHostBundle);+ return resolveSharedHostBundle(flag, process.env, defaultSharedHostBundle);}async function openState(dataDirFlag: string | undefined) {const dataDir = resolveDataDir(dataDirFlag);await ensureDataDir(dataDir);const layout = dataLayout(dataDir);+ const store = ControllerStore.open(layout.database);+ const recorded = store.secretStoreKind() ?? 'file';+ if (!isSecretStoreKind(recorded)) {+ store.close();+ throw new ConfigurationError(+ `${dataDir} keeps its credential in '${recorded}', which this version does not know. Update switch-agent-controller.`+ );+ }return {dataDir,layout,- store: ControllerStore.open(layout.database),- secrets: new FileSecretStore(layout.secrets),+ store,+ secrets: secretStoreFor(recorded, { dir: layout.secrets, dataDir }, runSecretCommand),};}@@ -105,17 +158,22 @@ async function enrollCommand(args: string[]): Promise<number> {name: { type: 'string' },description: { type: 'string' },'data-dir': { type: 'string' },+ 'secret-store': { type: 'string' },},strict: true,});if (!values.server) throw new UsageError('enroll needs --server <agent-bridge-url>.');+ const secretStore = values['secret-store'] ?? defaultSecretStoreKind(process.platform);+ if (!isSecretStoreKind(secretStore))+ throw new UsageError(`--secret-store must be one of ${SECRET_STORE_KINDS.join(', ')}.`);if (!values.code) throw new UsageError('enroll needs --code <code>.');const server = normalizeServerUrl(values.server);const name = values.name ?? hostname();const description = values.description?.trim() || undefined;if (description !== undefined && description.length > MAX_DESCRIPTION)throw new UsageError(`--description must be at most ${MAX_DESCRIPTION} characters.`);- const { dataDir, store, secrets } = await openState(values['data-dir']);+ const { dataDir, layout, store } = await openState(values['data-dir']);+ const secrets = secretStoreFor(secretStore, { dir: layout.secrets, dataDir }, runSecretCommand);try {const existing = store.identity();if (existing && !store.revokedAt())@@ -133,6 +191,7 @@ async function enrollCommand(args: string[]): Promise<number> {},});await secrets.set(CONTROLLER_CREDENTIAL, enrolled.credential);+ store.saveSecretStoreKind(secretStore);store.saveIdentity({controllerId: enrolled.controller_id,server,@@ -140,9 +199,10 @@ async function enrollCommand(args: string[]): Promise<number> {enrolledAt: new Date().toISOString(),});process.stdout.write(- `Enrolled as controller ${enrolled.controller_id} ("${name}") on ${server}.\nData: ${dataDir}\nStart it with: switch-agent-controller run${values['data-dir'] ? ` --data-dir ${dataDir}` : ''}\n`+ `Enrolled as controller ${enrolled.controller_id} ("${name}") on ${server}.\nData: ${dataDir}\nRun it as a service: switch-agent-controller install-service${values['data-dir'] ? ` --data-dir ${dataDir}` : ''}\nor in this terminal: switch-agent-controller run${values['data-dir'] ? ` --data-dir ${dataDir}` : ''}\n`);- process.stderr.write(`Warning: ${secrets.startupWarning()}\n`);+ const warning = secrets.startupWarning();+ if (warning) process.stderr.write(`Warning: ${warning}\n`);return EXIT_OK;} finally {store.close();@@ -235,10 +295,15 @@ async function runCommand(args: string[]): Promise<number> {server: { type: 'string' },name: { type: 'string' },'credential-stdin': { type: 'boolean' },+ 'env-file': { type: 'string' },+ launchd: { type: 'boolean' },},strict: true,});assertSupportedPlatform(process.platform);+ // Before anything reads the environment: the agents inherit it.+ const fromFile = values['env-file'] ? await readEnvFile(resolve(values['env-file'])) : {};+ Object.assign(process.env, fromFile);const controllerId = values['controller-id'];if ((controllerId === undefined) !== (values.server === undefined))throw new UsageError('--controller-id and --server adopt an identity together; pass both.');@@ -263,6 +328,13 @@ async function runCommand(args: string[]): Promise<number> {stop.abort();};for (const signal of SIGNALS) process.once(signal, onSignal);+ if (Object.keys(fromFile).length)+ log.info("Read the agents' environment from a file", {+ file: values['env-file'],+ names: Object.keys(fromFile),+ });+ // A controller a parent runs is updated with the parent.+ if (credential === null) void announceUpdate(log);try {if (controllerId !== undefined && values.server !== undefined) {const previousServer = store.identity()?.server;@@ -393,18 +465,179 @@ async function statusCommand(args: string[]): Promise<number> {}}+/** Logs that a newer release exists; a check that fails says so at debug and changes nothing. */+async function announceUpdate(log: ReturnType<typeof createLogger>): Promise<void> {+ try {+ const latest = await latestRelease(fetch, releasesRepository(process.env));+ if (latest && isNewer(latest.version, VERSION))+ log.warn(+ `switch-agent-controller ${latest.version} is available (this is ${VERSION}). Install it with: switch-agent-controller update`+ );+ } catch (error) {+ log.debug('Could not check for a newer release', { error: errorMessage(error) });+ }+}++/** The CLI file this process runs, through any npm bin link, as a service names it. */+function cliPath(): string {+ const entry = process.argv[1];+ if (!entry) throw new ConfigurationError('Cannot tell which file this CLI runs from.');+ return realpathSync(entry);+}++async function installServiceCommand(args: string[]): Promise<number> {+ const { values } = parseArgs({+ args,+ options: {+ 'data-dir': { type: 'string' },+ 'env-file': { type: 'string' },+ 'shared-host-bundle': { type: 'string' },+ },+ strict: true,+ });+ assertSupportedPlatform(process.platform);+ const envFile = values['env-file'] ? resolve(values['env-file']) : null;+ // Read now, so a broken file fails here rather than in the service.+ if (envFile) await readEnvFile(envFile);+ const sharedHostBundle = values['shared-host-bundle']+ ? bundlePath(values['shared-host-bundle'])+ : null;+ const { dataDir, store } = await openState(values['data-dir']);+ try {+ if (!store.identity())+ throw new ConfigurationError(+ `${dataDir} is not enrolled. Enroll first: switch-agent-controller enroll --server <url> --code <code>`+ );+ } finally {+ store.close();+ }+ const report = await installService(+ {+ node: process.execPath,+ cli: cliPath(),+ dataDir,+ envFile,+ sharedHostBundle,+ path: process.env.PATH ?? '/usr/local/bin:/usr/bin:/bin',+ },+ runSecretCommand+ );+ process.stdout.write([`Installed and started: ${report.file}`, ...report.notes, ''].join('\n'));+ return EXIT_OK;+}++async function uninstallServiceCommand(args: string[]): Promise<number> {+ const { values } = parseArgs({+ args,+ options: { 'data-dir': { type: 'string' } },+ strict: true,+ });+ const removed = await uninstallService(resolveDataDir(values['data-dir']), runSecretCommand);+ process.stdout.write(+ removed ? 'Stopped and removed the service.\n' : 'No service was installed.\n'+ );+ return EXIT_OK;+}++async function doctorCommand(args: string[]): Promise<number> {+ const { values } = parseArgs({+ args,+ options: { 'data-dir': { type: 'string' }, 'shared-host-bundle': { type: 'string' } },+ strict: true,+ });+ const { dataDir, store, secrets } = await openState(values['data-dir']);+ const locator = new PathProviderLocator(process.env.PATH);+ try {+ const checks = await runDoctor({+ version: VERSION,+ nodeVersion: process.version,+ platform: process.platform,+ dataDir,+ identity: store.identity(),+ revokedAt: store.revokedAt(),+ secrets,+ bundle: () => bundlePath(values['shared-host-bundle']),+ exchange: (server, controllerId, credential) =>+ exchangeToken(fetch, server, controllerId, credential),+ locate: (provider) => locator.locate(provider),+ probe: (bundle, provider, binary) => probeProvider(bundle, provider, binary, dataDir),+ service: () => serviceState(dataDir, runSecretCommand),+ latest: () => latestRelease(fetch, releasesRepository(process.env)),+ });+ process.stdout.write(`${formatChecks(checks)}\n`);+ return checks.some((check) => check.status === 'fail') ? 1 : EXIT_OK;+ } finally {+ store.close();+ }+}++async function updateCommand(args: string[]): Promise<number> {+ const { values } = parseArgs({+ args,+ options: { check: { type: 'boolean' }, 'data-dir': { type: 'string' } },+ strict: true,+ });+ const latest = await latestRelease(fetch, releasesRepository(process.env));+ if (!latest) {+ process.stdout.write('No switch-agent-controller release is published yet.\n');+ return 1;+ }+ if (!isNewer(latest.version, VERSION)) {+ process.stdout.write(`This is the latest release, ${VERSION}.\n`);+ return EXIT_OK;+ }+ if (values.check) {+ process.stdout.write(+ `${latest.version} is available (this is ${VERSION}). Install it with: switch-agent-controller update\n`+ );+ return EXIT_OK;+ }+ process.stdout.write(`Installing ${latest.version} from ${latest.packageUrl}\n`);+ const code = await new Promise<number | null>((done, fail) => {+ const child = spawn('npm', ['install', '--global', latest.packageUrl], { stdio: 'inherit' });+ child.once('error', fail);+ child.once('exit', done);+ });+ if (code !== 0)+ throw new Error(+ `npm install exited with ${code}. If npm needs root to install globally, point it at a folder of yours (npm config set prefix ~/.local) and install again.`+ );+ const dataDir = resolveDataDir(values['data-dir']);+ if ((await serviceState(dataDir, runSecretCommand)) === 'running') {+ await restartService(dataDir, runSecretCommand);+ process.stdout.write(`Installed ${latest.version} and restarted the service.\n`);+ } else process.stdout.write(`Installed ${latest.version}.\n`);+ return EXIT_OK;+}+export async function main(argv: string[]): Promise<number> {const [command, ...rest] = argv;try {switch (command) {case 'enroll':return await enrollCommand(rest);- case 'run':- return await runCommand(rest);+ case 'run': {+ const code = await runCommand(rest).catch((error: unknown) => {+ reportFailure(error);+ return exitCodeFor(error);+ });+ // launchd cannot spare exit codes from a restart; the reason is logged above.+ return rest.includes('--launchd') && LAUNCHD_FINAL_EXIT_CODES.includes(code)+ ? EXIT_OK+ : code;+ }case 'set-info':return await setInfoCommand(rest);case 'status':return await statusCommand(rest);+ case 'install-service':+ return await installServiceCommand(rest);+ case 'uninstall-service':+ return await uninstallServiceCommand(rest);+ case 'doctor':+ return await doctorCommand(rest);+ case 'update':+ return await updateCommand(rest);case undefined:case '-h':case '--help':@@ -418,12 +651,16 @@ export async function main(argv: string[]): Promise<number> {throw new UsageError(`Unknown command '${command}'.`);}} catch (error) {- // The last line is the reason: a parent that supervises this process shows it.- if (error instanceof UsageError || isParseArgsError(error))- process.stderr.write(`${USAGE}\nswitch-agent-controller: ${errorMessage(error)}\n`);- else if (error instanceof ControllerApiError)- process.stderr.write(`switch-agent-controller: ${error.code}: ${error.message}\n`);- else process.stderr.write(`switch-agent-controller: ${errorMessage(error)}\n`);+ reportFailure(error);return exitCodeFor(error);}}++/** The last line is the reason: a parent that supervises this process shows it. */+function reportFailure(error: unknown): void {+ if (error instanceof UsageError || isParseArgsError(error))+ process.stderr.write(`${USAGE}\nswitch-agent-controller: ${errorMessage(error)}\n`);+ else if (error instanceof ControllerApiError)+ process.stderr.write(`switch-agent-controller: ${error.code}: ${error.message}\n`);+ else process.stderr.write(`switch-agent-controller: ${errorMessage(error)}\n`);+}diff --git a/console/packages/agent-controller/src/runtime.ts b/console/packages/agent-controller/src/runtime.tsindex f903cfb96..cfeadc33a 100644--- a/console/packages/agent-controller/src/runtime.ts+++ b/console/packages/agent-controller/src/runtime.ts@@ -115,6 +115,22 @@ export interface AgentRuntime extends AgentRunner {/** How long an agent host asked to stop is given; each session host is allowed 20 s of it. */export const STOP_TIMEOUT_MS = 30_000;const PROBE_TIMEOUT_MS = 90_000;++/** Asks a provider's CLI, through the shared-host bundle's `--probe`, whether it is signed in. */+export async function probeProvider(+ bundlePath: string,+ provider: Provider,+ binaryPath: string,+ cwd: string+): Promise<ProviderReadiness> {+ const { stdout } = await execute(+ process.execPath,+ [bundlePath, '--probe', provider, cwd, binaryPath],+ { timeout: PROBE_TIMEOUT_MS, maxBuffer: 4 * 1024 * 1024, env: process.env }+ );+ const line = stdout.trim().split('\n').at(-1) ?? '';+ return providerReadinessSchema.parse(JSON.parse(line));+}/** Failures an agent host is started again after, within `CRASH_WINDOW_MS`. */const MAX_CRASHES = 3;const CRASH_WINDOW_MS = 10 * 60 * 1000;@@ -535,14 +551,8 @@ export class InProcessRuntime implements AgentRuntime {}}- async probe(provider: Provider, binaryPath: string, cwd: string): Promise<ProviderReadiness> {- const { stdout } = await execute(- process.execPath,- [this.deps.bundlePath, '--probe', provider, cwd, binaryPath],- { timeout: PROBE_TIMEOUT_MS, maxBuffer: 4 * 1024 * 1024, env: process.env }- );- const line = stdout.trim().split('\n').at(-1) ?? '';- return providerReadinessSchema.parse(JSON.parse(line));+ probe(provider: Provider, binaryPath: string, cwd: string): Promise<ProviderReadiness> {+ return probeProvider(this.deps.bundlePath, provider, binaryPath, cwd);}private async writeFlags(root: string, flags: WatchFlags): Promise<void> {diff --git a/console/packages/agent-controller/src/secrets.test.ts b/console/packages/agent-controller/src/secrets.test.tsindex 98c3fd8f0..d15b4c6c8 100644--- a/console/packages/agent-controller/src/secrets.test.ts+++ b/console/packages/agent-controller/src/secrets.test.ts@@ -2,7 +2,16 @@ import { chmodSync, mkdtempSync, rmSync, statSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { afterEach, beforeEach, describe, expect, it } from 'vitest';-import { CONTROLLER_CREDENTIAL, FileSecretStore, MemorySecretStore } from './secrets';+import {+ CommandFailure,+ type CommandRunner,+ CONTROLLER_CREDENTIAL,+ defaultSecretStoreKind,+ FileSecretStore,+ KeychainSecretStore,+ MemorySecretStore,+ SecretServiceStore,+} from './secrets';let dir: string;@@ -66,3 +75,60 @@ describe('MemorySecretStore', () => {await expect(new MemorySecretStore({}, 'test').set('../x', 'y')).rejects.toThrow(/Invalid/);});});++describe('OS keychain stores', () => {+ type Call = { file: string; args: string[]; input: string | null };+ function runner(answer: (call: Call) => { stdout: string } | CommandFailure) {+ const calls: Call[] = [];+ const run: CommandRunner = async (file, args, input) => {+ const call = { file, args, input };+ calls.push(call);+ const result = answer(call);+ if (result instanceof CommandFailure) throw result;+ return result;+ };+ return { calls, run };+ }++ it('keeps the macOS keychain value off the command line, and reads a missing one as none', async () => {+ const { calls, run } = runner((call) =>+ call.args[0] === 'find-generic-password'+ ? new CommandFailure(call.file, call.args, 44, 'not found', 'exit 44')+ : { stdout: '' }+ );+ const store = new KeychainSecretStore('/data', run);+ await store.set(CONTROLLER_CREDENTIAL, 'swcc_secret-value');+ expect(calls[0].args).toEqual(['-i']);+ expect(calls[0].input).toContain('-w "swcc_secret-value"');+ expect(calls[0].input).toContain(`-a "${CONTROLLER_CREDENTIAL}@/data"`);+ expect(calls.flatMap((call) => call.args).join(' ')).not.toContain('swcc_secret-value');+ expect(await store.get(CONTROLLER_CREDENTIAL)).toBeNull();+ });++ it('fails loud on a keychain error that is not "not found"', async () => {+ const { run } = runner(+ (call) => new CommandFailure(call.file, call.args, 51, 'user interaction is not allowed', 'x')+ );+ await expect(new KeychainSecretStore('/data', run).get(CONTROLLER_CREDENTIAL)).rejects.toThrow(+ /user interaction is not allowed/+ );+ });++ it('gives secret-tool the value on stdin, and reads a silent exit 1 as none', async () => {+ const { calls, run } = runner((call) =>+ call.args[0] === 'lookup'+ ? new CommandFailure(call.file, call.args, 1, '', 'exit 1')+ : { stdout: '' }+ );+ const store = new SecretServiceStore('/data', run);+ await store.set(CONTROLLER_CREDENTIAL, 'swcc_secret-value');+ expect(calls[0].input).toBe('swcc_secret-value');+ expect(calls[0].args).not.toContain('swcc_secret-value');+ expect(await store.get(CONTROLLER_CREDENTIAL)).toBeNull();+ });++ it('defaults to the keychain on a Mac only', () => {+ expect(defaultSecretStoreKind('darwin')).toBe('keychain');+ expect(defaultSecretStoreKind('linux')).toBe('file');+ });+});diff --git a/console/packages/agent-controller/src/secrets.ts b/console/packages/agent-controller/src/secrets.tsindex b887f9ea2..6f3e8dca7 100644--- a/console/packages/agent-controller/src/secrets.ts+++ b/console/packages/agent-controller/src/secrets.ts@@ -1,3 +1,4 @@+import { execFile } from 'node:child_process';import { randomUUID } from 'node:crypto';import { chmod, mkdir, open, readFile, rename, stat, unlink } from 'node:fs/promises';import { join } from 'node:path';@@ -120,3 +121,189 @@ export class MemorySecretStore implements SecretStore {this.values.delete(name);}}++/** Where `enroll` keeps the controller credential; recorded in the store so `run` reads it there. */+export const SECRET_STORE_KINDS = ['file', 'keychain', 'secret-service'] as const;+export type SecretStoreKind = (typeof SECRET_STORE_KINDS)[number];++export function isSecretStoreKind(value: string): value is SecretStoreKind {+ return (SECRET_STORE_KINDS as readonly string[]).includes(value);+}++/**+ * Runs a command with `input` on stdin; rejects with a {@link CommandFailure}+ * when it exits non-zero.+ */+export type CommandRunner = (+ file: string,+ args: string[],+ input: string | null+) => Promise<{ stdout: string }>;++export const runCommand: CommandRunner = (file, args, input) =>+ new Promise((resolve, reject) => {+ const child = execFile(file, args, { timeout: 15_000 }, (error, stdout, stderr) => {+ if (error) {+ reject(new CommandFailure(file, args, error.code, stderr.trim(), error.message));+ return;+ }+ resolve({ stdout });+ });+ child.stdin?.end(input ?? '');+ });++/** A command that exited non-zero, or could not be run (`code` is then a string such as `ENOENT`). */+export class CommandFailure extends Error {+ constructor(+ file: string,+ args: string[],+ readonly code: number | string | null | undefined,+ readonly stderr: string,+ detail: string+ ) {+ super(`${file} ${args[0] ?? ''} failed: ${stderr || detail}`);+ this.name = 'CommandFailure';+ }+}++const SERVICE = 'switch-agent-controller';++/** One keychain entry per secret and data directory, so two controllers on one account do not share. */+function account(dataDir: string, name: string): string {+ if (!NAME.test(name)) throw new Error(`Invalid secret name '${name}'.`);+ return `${name}@${dataDir}`;+}++/**+ * The macOS login keychain, through `security`. The value is written through+ * `security -i` on stdin, never on the command line, where other processes+ * could read it.+ */+export class KeychainSecretStore implements SecretStore {+ readonly description = 'the macOS login keychain';++ constructor(+ private readonly dataDir: string,+ private readonly run: CommandRunner+ ) {}++ startupWarning(): null {+ return null;+ }++ async get(name: string): Promise<string | null> {+ try {+ const { stdout } = await this.run(+ 'security',+ ['find-generic-password', '-s', SERVICE, '-a', account(this.dataDir, name), '-w'],+ null+ );+ return stdout.trim();+ } catch (error) {+ // 44: errSecItemNotFound.+ if (error instanceof CommandFailure && error.code === 44) return null;+ throw error;+ }+ }++ async set(name: string, value: string): Promise<void> {+ if (/["\\\n]/.test(value)) throw new Error('This secret cannot be stored in the keychain.');+ const command = `add-generic-password -U -s ${SERVICE} -a "${account(this.dataDir, name)}" -w "${value}"\n`;+ await this.run('security', ['-i'], command);+ }++ async delete(name: string): Promise<void> {+ try {+ await this.run(+ 'security',+ ['delete-generic-password', '-s', SERVICE, '-a', account(this.dataDir, name)],+ null+ );+ } catch (error) {+ if (!(error instanceof CommandFailure && error.code === 44)) throw error;+ }+ }+}++/**+ * The desktop keyring on Linux (GNOME Keyring, KWallet) through libsecret's+ * `secret-tool`, which reads the value from stdin. It needs a session bus and+ * an unlocked keyring, which a service started at boot usually lacks; that is+ * why it is chosen only when asked for.+ */+export class SecretServiceStore implements SecretStore {+ readonly description = 'the desktop keyring (Secret Service)';++ constructor(+ private readonly dataDir: string,+ private readonly run: CommandRunner+ ) {}++ startupWarning(): null {+ return null;+ }++ async get(name: string): Promise<string | null> {+ const attributes = ['service', SERVICE, 'account', account(this.dataDir, name)];+ try {+ const { stdout } = await this.run('secret-tool', ['lookup', ...attributes], null);+ return stdout.trim() || null;+ } catch (error) {+ // `lookup` exits 1, saying nothing, when there is no such secret.+ if (error instanceof CommandFailure && error.code === 1 && error.stderr === '') return null;+ throw error;+ }+ }++ async set(name: string, value: string): Promise<void> {+ await this.run(+ 'secret-tool',+ [+ 'store',+ '--label',+ 'Switch agents controller',+ 'service',+ SERVICE,+ 'account',+ account(this.dataDir, name),+ ],+ value+ );+ }++ async delete(name: string): Promise<void> {+ await this.run(+ 'secret-tool',+ ['clear', 'service', SERVICE, 'account', account(this.dataDir, name)],+ null+ );+ }+}++/**+ * The store a data directory's credential lives in. `dir` is the file+ * backend's directory; `dataDir` keys keychain entries.+ */+export function secretStoreFor(+ kind: SecretStoreKind,+ paths: { dir: string; dataDir: string },+ run: CommandRunner+): SecretStore {+ switch (kind) {+ case 'file':+ return new FileSecretStore(paths.dir);+ case 'keychain':+ return new KeychainSecretStore(paths.dataDir, run);+ case 'secret-service':+ return new SecretServiceStore(paths.dataDir, run);+ }+}++/**+ * What `enroll` uses when not told: the macOS keychain on a Mac, where the+ * service runs in the user's session and can read it; files elsewhere, since+ * a Linux service usually starts with no keyring to unlock.+ */+export function defaultSecretStoreKind(platform: NodeJS.Platform): SecretStoreKind {+ return platform === 'darwin' ? 'keychain' : 'file';+}diff --git a/console/packages/agent-controller/src/service.test.ts b/console/packages/agent-controller/src/service.test.tsnew file mode 100644index 000000000..8cc78c528--- /dev/null+++ b/console/packages/agent-controller/src/service.test.ts@@ -0,0 +1,56 @@+import { homedir } from 'node:os';+import { describe, expect, it } from 'vitest';+import { defaultDataDir } from './paths';+import { launchdPlist, serviceIdentity, systemdUnit, type ServiceSpec } from './service';++const SPEC: ServiceSpec = {+ node: '/usr/bin/node',+ cli: '/home/me/.local/lib/node_modules/switch-agent-controller/cli.mjs',+ dataDir: '/srv/controller data',+ envFile: '/home/me/agents.env',+ sharedHostBundle: null,+ path: '/home/me/.local/bin:/usr/bin:/bin',+};++describe('systemdUnit', () => {+ it('runs the controller on its data directory, restarting on exit code 1 only', () => {+ const unit = systemdUnit(SPEC);+ expect(unit).toContain(+ 'ExecStart="/usr/bin/node" "/home/me/.local/lib/node_modules/switch-agent-controller/cli.mjs" "run" "--data-dir" "/srv/controller data" "--env-file" "/home/me/agents.env"'+ );+ expect(unit).toContain('Environment="PATH=/home/me/.local/bin:/usr/bin:/bin"');+ expect(unit).toContain('Restart=on-failure');+ expect(unit).toContain('RestartPreventExitStatus=2 3 4');+ expect(unit).not.toContain('--launchd');+ });+});++describe('launchdPlist', () => {+ it('runs with --launchd, restarts only an unsuccessful exit, and logs to a file', () => {+ const plist = launchdPlist(+ { ...SPEC, dataDir: '/Users/me/A & B' },+ 'com.switch.agent-controller',+ '/Users/me/A & B/controller.log'+ );+ expect(plist).toContain('<string>/Users/me/A & B</string>');+ expect(plist).toContain('<string>--launchd</string>');+ expect(plist).toMatch(/<key>SuccessfulExit<\/key>\s*<false\/>/);+ expect(plist).toContain(+ '<key>StandardErrorPath</key>\n <string>/Users/me/A & B/controller.log</string>'+ );+ });+});++describe('serviceIdentity', () => {+ it('names the default data directory plainly, and any other with a hash of its path', () => {+ const home = defaultDataDir({ platform: process.platform, env: process.env, home: homedir() });+ expect(serviceIdentity(home)).toEqual({+ unit: 'switch-agent-controller',+ label: 'com.switch.agent-controller',+ });+ const other = serviceIdentity('/srv/controller');+ expect(other.unit).toMatch(/^switch-agent-controller-[0-9a-f]{8}$/);+ expect(other.label).toMatch(/^com\.switch\.agent-controller\.[0-9a-f]{8}$/);+ expect(serviceIdentity('/srv/other').unit).not.toBe(other.unit);+ });+});diff --git a/console/packages/agent-controller/src/service.ts b/console/packages/agent-controller/src/service.tsnew file mode 100644index 000000000..e64cb1af9--- /dev/null+++ b/console/packages/agent-controller/src/service.ts@@ -0,0 +1,280 @@+import { createHash } from 'node:crypto';+import { access, mkdir, rm, writeFile } from 'node:fs/promises';+import { homedir, userInfo } from 'node:os';+import { dirname, isAbsolute, join } from 'node:path';+import { ConfigurationError } from './errors';+import { defaultDataDir } from './paths';+import { CommandFailure, type CommandRunner } from './secrets';++/**+ * What the installed service runs: `node <cli> run` on one data directory,+ * with the PATH it was installed from, so the provider CLIs found then are+ * found by the service too.+ */+export type ServiceSpec = {+ node: string;+ cli: string;+ dataDir: string;+ envFile: string | null;+ sharedHostBundle: string | null;+ path: string;+};++/** How the service is known to its init system; see {@link serviceIdentity}. */+export type ServiceIdentity = {+ /** The systemd unit name, without `.service`. */+ unit: string;+ /** The launchd label. */+ label: string;+};++/**+ * One service per data directory: the default one gets the plain name, any+ * other a name carrying a hash of its path, so two controllers on one account+ * each get their own.+ */+export function serviceIdentity(dataDir: string): ServiceIdentity {+ const isDefault =+ dataDir === defaultDataDir({ platform: process.platform, env: process.env, home: homedir() });+ const suffix = isDefault+ ? ''+ : `-${createHash('sha256').update(dataDir).digest('hex').slice(0, 8)}`;+ return {+ unit: `switch-agent-controller${suffix}`,+ label: `com.switch.agent-controller${suffix.replace('-', '.')}`,+ };+}++function runArguments(spec: ServiceSpec, launchd: boolean): string[] {+ return [+ spec.node,+ spec.cli,+ 'run',+ '--data-dir',+ spec.dataDir,+ ...(spec.envFile ? ['--env-file', spec.envFile] : []),+ ...(spec.sharedHostBundle ? ['--shared-host-bundle', spec.sharedHostBundle] : []),+ ...(launchd ? ['--launchd'] : []),+ ];+}++/**+ * The systemd user unit: restarted on exit code 1 only, since 2 (configuration),+ * 3 (revoked) and 4 (taken over) would fail the same way again.+ */+export function systemdUnit(spec: ServiceSpec): string {+ const quote = (value: string) => `"${value.replace(/(["\\])/g, '\\$1')}"`;+ return [+ '[Unit]',+ 'Description=Switch agents controller',+ 'After=network-online.target',+ 'Wants=network-online.target',+ '',+ '[Service]',+ `ExecStart=${runArguments(spec, false).map(quote).join(' ')}`,+ `Environment=${quote(`PATH=${spec.path}`)}`,+ 'Restart=on-failure',+ 'RestartSec=5',+ 'RestartPreventExitStatus=2 3 4',+ '',+ '[Install]',+ 'WantedBy=default.target',+ '',+ ].join('\n');+}++function xml(value: string): string {+ return value+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}++/**+ * The launchd agent. launchd cannot spare particular exit codes from a+ * restart, so the controller runs with `--launchd`, which ends with 0 on the+ * codes that must not restart (having logged why), and `KeepAlive` restarts+ * only an unsuccessful exit.+ */+export function launchdPlist(spec: ServiceSpec, label: string, logFile: string): string {+ const strings = (values: string[]) =>+ values.map((value) => ` <string>${xml(value)}</string>`).join('\n');+ return `<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>Label</key>+ <string>${xml(label)}</string>+ <key>ProgramArguments</key>+ <array>+${strings(runArguments(spec, true))}+ </array>+ <key>EnvironmentVariables</key>+ <dict>+ <key>PATH</key>+ <string>${xml(spec.path)}</string>+ </dict>+ <key>RunAtLoad</key>+ <true/>+ <key>KeepAlive</key>+ <dict>+ <key>SuccessfulExit</key>+ <false/>+ </dict>+ <key>ThrottleInterval</key>+ <integer>5</integer>+ <key>StandardOutPath</key>+ <string>${xml(logFile)}</string>+ <key>StandardErrorPath</key>+ <string>${xml(logFile)}</string>+</dict>+</plist>+`;+}++/** The exit codes `--launchd` turns into 0, so launchd does not restart into the same failure. */+export const LAUNCHD_FINAL_EXIT_CODES: readonly number[] = [2, 3, 4];++/** Where the service's files are, for this user. */+export type ServicePaths = {+ /** The systemd unit file, or the launchd plist. */+ file: string;+ /** Where launchd writes the controller's log; systemd keeps it in the journal. */+ logFile: string | null;+};++function systemdUserDir(env: NodeJS.ProcessEnv, home: string): string {+ const config = env.XDG_CONFIG_HOME;+ return join(config && isAbsolute(config) ? config : join(home, '.config'), 'systemd', 'user');+}++export function servicePaths(identity: ServiceIdentity, dataDir: string): ServicePaths {+ if (process.platform === 'darwin')+ return {+ file: join(homedir(), 'Library', 'LaunchAgents', `${identity.label}.plist`),+ logFile: join(dataDir, 'controller.log'),+ };+ if (process.platform === 'linux')+ return {+ file: join(systemdUserDir(process.env, homedir()), `${identity.unit}.service`),+ logFile: null,+ };+ throw new ConfigurationError(+ 'install-service supports Linux (systemd) and macOS (launchd). Run `switch-agent-controller run` under your own supervisor elsewhere.'+ );+}++/** What installing said, for the person who ran it. */+export type InstallReport = { file: string; notes: string[] };++/** Writes the service for this user, and starts it now and at each login (or boot, with lingering). */+export async function installService(+ spec: ServiceSpec,+ run: CommandRunner+): Promise<InstallReport> {+ const identity = serviceIdentity(spec.dataDir);+ const paths = servicePaths(identity, spec.dataDir);+ await mkdir(dirname(paths.file), { recursive: true });+ const notes: string[] = [];+ if (process.platform === 'darwin') {+ if (!paths.logFile) throw new Error('A launchd agent needs a log file.');+ await writeFile(paths.file, launchdPlist(spec, identity.label, paths.logFile), { mode: 0o644 });+ const domain = `gui/${userInfo().uid}`;+ // Replacing one already loaded: launchd refuses to bootstrap a label it has.+ await run('launchctl', ['bootout', `${domain}/${identity.label}`], null).catch(() => {});+ await run('launchctl', ['bootstrap', domain, paths.file], null);+ notes.push(`It runs while you are logged in, and logs to ${paths.logFile}.`);+ return { file: paths.file, notes };+ }+ await assertSystemdUser(run);+ await writeFile(paths.file, systemdUnit(spec), { mode: 0o644 });+ await run('systemctl', ['--user', 'daemon-reload'], null);+ await run('systemctl', ['--user', 'enable', identity.unit], null);+ await run('systemctl', ['--user', 'restart', identity.unit], null);+ notes.push(`Its log: journalctl --user -u ${identity.unit} -f`);+ if (!(await lingering(run)))+ notes.push(+ `It stops when you log out and starts at your next login. To keep it running and start it at boot, run: sudo loginctl enable-linger ${userInfo().username}`+ );+ return { file: paths.file, notes };+}++/** Stops the service and removes its file; a service that is not installed is not an error. */+export async function uninstallService(dataDir: string, run: CommandRunner): Promise<boolean> {+ const identity = serviceIdentity(dataDir);+ const paths = servicePaths(identity, dataDir);+ const state = await serviceState(dataDir, run);+ if (process.platform === 'darwin')+ await run('launchctl', ['bootout', `gui/${userInfo().uid}/${identity.label}`], null).catch(+ () => {}+ );+ else await run('systemctl', ['--user', 'disable', '--now', identity.unit], null).catch(() => {});+ await rm(paths.file, { force: true });+ if (process.platform === 'linux')+ await run('systemctl', ['--user', 'daemon-reload'], null).catch(() => {});+ return state !== 'not-installed';+}++/** Restarts the installed service, as after an update replaced the files it runs. */+export async function restartService(dataDir: string, run: CommandRunner): Promise<void> {+ const identity = serviceIdentity(dataDir);+ if (process.platform === 'darwin')+ await run('launchctl', ['kickstart', '-k', `gui/${userInfo().uid}/${identity.label}`], null);+ else await run('systemctl', ['--user', 'restart', identity.unit], null);+}++export type ServiceState = 'running' | 'stopped' | 'not-installed';++/** Whether the service for this data directory is installed, and running. */+export async function serviceState(dataDir: string, run: CommandRunner): Promise<ServiceState> {+ const identity = serviceIdentity(dataDir);+ const paths = servicePaths(identity, dataDir);+ try {+ await access(paths.file);+ } catch {+ return 'not-installed';+ }+ if (process.platform === 'darwin') {+ try {+ const { stdout } = await run(+ 'launchctl',+ ['print', `gui/${userInfo().uid}/${identity.label}`],+ null+ );+ return /state = running/.test(stdout) ? 'running' : 'stopped';+ } catch {+ return 'stopped';+ }+ }+ try {+ const { stdout } = await run('systemctl', ['--user', 'is-active', identity.unit], null);+ return stdout.trim() === 'active' ? 'running' : 'stopped';+ } catch (error) {+ if (error instanceof CommandFailure) return 'stopped';+ throw error;+ }+}++async function assertSystemdUser(run: CommandRunner): Promise<void> {+ try {+ await run('systemctl', ['--user', 'show-environment'], null);+ } catch (error) {+ throw new ConfigurationError(+ `This user has no systemd user manager to install the service with (${(error as Error).message}). Run \`switch-agent-controller run\` under your own supervisor, restarting it on exit code 1 only.`+ );+ }+}++async function lingering(run: CommandRunner): Promise<boolean> {+ try {+ const { stdout } = await run(+ 'loginctl',+ ['show-user', userInfo().username, '-p', 'Linger'],+ null+ );+ return /Linger=yes/.test(stdout);+ } catch {+ return false;+ }+}diff --git a/console/packages/agent-controller/src/store.ts b/console/packages/agent-controller/src/store.tsindex 1359fc3fb..c2bb2f69b 100644--- a/console/packages/agent-controller/src/store.ts+++ b/console/packages/agent-controller/src/store.ts@@ -135,6 +135,18 @@ export class ControllerStore {});}+ /**+ * Where `enroll` put the controller credential. Null for a data directory+ * enrolled before the choice was recorded, which kept it in files.+ */+ secretStoreKind(): string | null {+ return this.meta('secret_store');+ }++ saveSecretStoreKind(kind: string): void {+ this.setMeta('secret_store', kind);+ }+/** Records the name the server now has for this controller. */saveName(name: string): void {if (!this.meta('controller_id'))diff --git a/console/packages/agent-controller/src/update.test.ts b/console/packages/agent-controller/src/update.test.tsnew file mode 100644index 000000000..b408b22cf--- /dev/null+++ b/console/packages/agent-controller/src/update.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from 'vitest';+import { isNewer, latestRelease, releasesRepository } from './update';++function release(tag: string, extra: Partial<{ draft: boolean; prerelease: boolean }> = {}) {+ const version = tag.replace('switch-agent-controller-v', '');+ return {+ tag_name: tag,+ draft: false,+ prerelease: false,+ ...extra,+ assets: [+ {+ name: `switch-agent-controller-${version}.tgz`,+ browser_download_url: `https://example.invalid/${tag}/switch-agent-controller-${version}.tgz`,+ },+ ],+ };+}++const answering = (body: unknown, status = 200) =>+ (async () => new Response(JSON.stringify(body), { status })) as unknown as typeof fetch;++describe('isNewer', () => {+ it('compares x.y.z numerically, and never ranks a version it cannot read', () => {+ expect(isNewer('0.10.0', '0.9.9')).toBe(true);+ expect(isNewer('1.0.0', '1.0.0')).toBe(false);+ expect(isNewer('0.9.0', '0.10.0')).toBe(false);+ expect(isNewer('1.0.0-rc.1', '0.1.0')).toBe(false);+ });+});++describe('latestRelease', () => {+ it('picks the highest controller release, leaving out other products, drafts and prereleases', async () => {+ const latest = await latestRelease(+ answering([+ release('switch-agent-controller-v0.2.0'),+ release('switch-agent-controller-v0.10.0'),+ release('switch-agent-controller-v0.11.0', { prerelease: true }),+ release('switch-agent-controller-v0.12.0', { draft: true }),+ { ...release('switch-v9.9.9'), tag_name: 'switch-v9.9.9' },+ { ...release('switch-agent-controller-v0.13.0'), assets: [] },+ ]),+ 'owner/repo'+ );+ expect(latest).toEqual({+ version: '0.10.0',+ packageUrl:+ 'https://example.invalid/switch-agent-controller-v0.10.0/switch-agent-controller-0.10.0.tgz',+ });+ });++ it('is null with no controller release, and fails loud when GitHub refuses', async () => {+ expect(await latestRelease(answering([]), 'owner/repo')).toBeNull();+ await expect(latestRelease(answering({}, 403), 'owner/repo')).rejects.toThrow(/403/);+ });+});++describe('releasesRepository', () => {+ it('defaults to the Switch repository and takes a fork named owner/name', () => {+ expect(releasesRepository({})).toBe('sandbox-quantum/switch');+ expect(+ releasesRepository({ SWITCH_CONTROLLER_RELEASES_REPOSITORY: 'someone/switch-fork' })+ ).toBe('someone/switch-fork');+ expect(() =>+ releasesRepository({ SWITCH_CONTROLLER_RELEASES_REPOSITORY: 'https://evil.invalid/x' })+ ).toThrow(/owner\/name/);+ });+});diff --git a/console/packages/agent-controller/src/update.ts b/console/packages/agent-controller/src/update.tsnew file mode 100644index 000000000..f4368d68f--- /dev/null+++ b/console/packages/agent-controller/src/update.ts@@ -0,0 +1,77 @@+import { z } from 'zod';++/** The repository whose releases carry the packaged controller; a fork names its own. */+export const RELEASES_REPOSITORY_ENV = 'SWITCH_CONTROLLER_RELEASES_REPOSITORY';+const DEFAULT_RELEASES_REPOSITORY = 'sandbox-quantum/switch';++/** Release tags are `switch-agent-controller-v<version>`. */+export const RELEASE_TAG_PREFIX = 'switch-agent-controller-v';++export function releasesRepository(env: NodeJS.ProcessEnv): string {+ const named = env[RELEASES_REPOSITORY_ENV]?.trim();+ if (!named) return DEFAULT_RELEASES_REPOSITORY;+ if (!/^[\w.-]+\/[\w.-]+$/.test(named))+ throw new Error(`${RELEASES_REPOSITORY_ENV} must be owner/name, not '${named}'.`);+ return named;+}++/** The file a release carries for `npm install -g`. */+export function packageAssetName(version: string): string {+ return `switch-agent-controller-${version}.tgz`;+}++const releaseSchema = z.object({+ tag_name: z.string(),+ draft: z.boolean(),+ prerelease: z.boolean(),+ assets: z.array(z.object({ name: z.string(), browser_download_url: z.string() })),+});++export type ControllerRelease = { version: string; packageUrl: string };++type Version = [number, number, number];++function parseVersion(value: string): Version | null {+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(value);+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;+}++/** Whether `candidate` is a later release than `current`; versions not plain x.y.z never are. */+export function isNewer(candidate: string, current: string): boolean {+ const a = parseVersion(candidate);+ const b = parseVersion(current);+ if (!a || !b) return false;+ for (let index = 0; index < 3; index++) if (a[index] !== b[index]) return a[index] > b[index];+ return false;+}++/**+ * The newest published controller release: the highest version among the+ * repository's releases tagged for the controller, leaving out drafts,+ * prereleases and a release without its package. The repository also+ * releases Switch and Switch Console, so "the latest release" is not it.+ */+export async function latestRelease(+ fetchImpl: typeof fetch,+ repository: string+): Promise<ControllerRelease | null> {+ const response = await fetchImpl(+ `https://api.github.com/repos/${repository}/releases?per_page=100`,+ { headers: { accept: 'application/vnd.github+json' }, signal: AbortSignal.timeout(15_000) }+ );+ if (!response.ok)+ throw new Error(`GitHub answered ${response.status} when listing ${repository}'s releases.`);+ const releases = z.array(releaseSchema).parse(await response.json());+ let best: ControllerRelease | null = null;+ for (const release of releases) {+ if (release.draft || release.prerelease || !release.tag_name.startsWith(RELEASE_TAG_PREFIX))+ continue;+ const version = release.tag_name.slice(RELEASE_TAG_PREFIX.length);+ if (!parseVersion(version)) continue;+ const asset = release.assets.find((candidate) => candidate.name === packageAssetName(version));+ if (!asset) continue;+ if (!best || isNewer(version, best.version))+ best = { version, packageUrl: asset.browser_download_url };+ }+ return best;+}diff --git a/console/packages/agent-providers/src/host/agent-env.ts b/console/packages/agent-providers/src/host/agent-env.tsindex 75b318314..ff55b41bc 100644--- a/console/packages/agent-providers/src/host/agent-env.ts+++ b/console/packages/agent-providers/src/host/agent-env.ts@@ -3,12 +3,16 @@ export const AGENT_ENV_VARS = ['ANTHROPIC_API_KEY','ANTHROPIC_AUTH_TOKEN','ANTHROPIC_BASE_URL',+ 'ANTHROPIC_BEDROCK_BASE_URL','ANTHROPIC_DEFAULT_HAIKU_MODEL','ANTHROPIC_DEFAULT_OPUS_MODEL','ANTHROPIC_DEFAULT_SONNET_MODEL','ANTHROPIC_MODEL','ANTHROPIC_SMALL_FAST_MODEL',+ 'ANTHROPIC_VERTEX_BASE_URL',+ 'ANTHROPIC_VERTEX_PROJECT_ID','AWS_ACCESS_KEY_ID',+ 'AWS_BEARER_TOKEN_BEDROCK','AWS_DEFAULT_REGION','AWS_PROFILE','AWS_REGION',@@ -20,10 +24,14 @@ export const AGENT_ENV_VARS = ['BAILIAN_CODING_PLAN_API_KEY','CLAUDE_CODE_DISABLE_BACKGROUND_TASKS','CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS',+ 'CLAUDE_CODE_SKIP_BEDROCK_AUTH',+ 'CLAUDE_CODE_SKIP_VERTEX_AUTH','CLAUDE_CODE_SUBAGENT_MODEL','CLAUDE_CODE_USE_BEDROCK','CLAUDE_CODE_USE_VERTEX','CLAUDE_CONFIG_DIR',+ 'CLOUDSDK_CONFIG',+ 'CLOUD_ML_REGION','CODEX_HOME','CURSOR_API_KEY','DASHSCOPE_API_KEY',@@ -36,8 +44,8 @@ export const AGENT_ENV_VARS = ['GOOGLE_GEMINI_BASE_URL','GOOGLE_GENAI_API_VERSION','GOOGLE_VERTEX_BASE_URL',- 'HTTP_PROXY','HTTPS_PROXY',+ 'HTTP_PROXY','KIMI_API_KEY','MISTRAL_API_KEY','MOONSHOT_API_KEY',diff --git a/console/pnpm-lock.yaml b/console/pnpm-lock.yamlindex 67e5f6428..b32ddad0d 100644--- a/console/pnpm-lock.yaml+++ b/console/pnpm-lock.yaml@@ -324,6 +324,9 @@ importers:'@typescript/native-preview':specifier: 7.0.0-dev.20260609.1version: 7.0.0-dev.20260609.1+ esbuild:+ specifier: 0.25.12+ version: 0.25.12tsdown:specifier: ^0.22.2diff --git a/docs/design/agent-controllers-v1.md b/docs/design/agent-controllers-v1.mdindex 3ca8e85d8..5a3ce37f5 100644--- a/docs/design/agent-controllers-v1.md+++ b/docs/design/agent-controllers-v1.md@@ -297,21 +297,26 @@ exactly the answer a missing one does.## Headless agents controller (`console/packages/agent-controller`)-- CLI `switch-agent-controller`:- - `enroll --server <agent-bridge-url> --code <code> [--name] [--description] [--data-dir]`- - `run [--data-dir]`+- CLI `switch-agent-controller`, released as its own npm package on+ `switch-agent-controller-v*` GitHub releases, with an `install.sh` (see RELEASING.md):+ - `enroll --server <agent-bridge-url> --code <code> [--name] [--description] [--data-dir] [--secret-store]`+ - `run [--data-dir] [--env-file]`- `set-info [--name] [--description] [--data-dir]`: renames the machine and/or changes itsdescription on the server, with the controller's own credential, and records the new namelocally.- `status [--data-dir]`+ - `install-service` / `uninstall-service`: a systemd user unit or a launchd agent+ - `doctor`: what the machine lacks to run agents+ - `update [--check]`: the newest release, from GitHub- **Data dir:** `SWITCH_CONTROLLER_DATA_DIR`, otherwise the OS default.- macOS: `~/Library/Application Support/Switch/agent-controller`- Linux: `$XDG_STATE_HOME/switch/agent-controller`, or `~/.local/state/switch/agent-controller`- Mode 0700.- **Store:** `node:sqlite`, one file. It holds identity, the assignment cache, per-agent applied revision andruntime state, and the status seq. It is a cache that can be rebuilt from the server.-- **Secrets:** behind a `SecretStore` interface. v1 ships a file backend (0600) that **logs a- warning at startup**, saying no OS keychain backend is in use.+- **Secrets:** behind a `SecretStore` interface: the macOS keychain (the default on a Mac), the+ desktop keyring through `secret-tool` (on request), or a file backend (0600, the default on+ Linux) that **logs a warning at startup**. The data directory records which one `enroll` used.- **Run loop:**1. Exchange the token, refreshing it before expiry. On `controller_revoked`: stop all agents, wipe the credential, and exit non-zero.2. Open the nudge stream, reconnecting with jittered backoff capped at 8 s anddiff --git a/gateway/src/data/management.ts b/gateway/src/data/management.tsindex f162ff7c4..5cfc46181 100644--- a/gateway/src/data/management.ts+++ b/gateway/src/data/management.ts@@ -286,20 +286,39 @@ export function shellQuote(value: string): string {return `'${value.replace(/'/g, `'\\''`)}'`;}+/** The enroll options for a machine's name and description, when given (blank is left out: the name then defaults to the host name). */+function machineWords(machine: { name: string; description: string }): string[] {+ const words: string[] = [];+ const name = machine.name.trim();+ const description = machine.description.trim();+ if (name) words.push("--name", name);+ if (description) words.push("--description", description);+ return words;+}+/**- * The command a user runs on the machine to enroll it with a fresh code, with- * the machine's name and description when given (blank is left out: the name- * then defaults to the host name).+ * The controller's installer, as published on the default branch: it finds the+ * newest `switch-agent-controller` release and installs it with npm.*/+export const CONTROLLER_INSTALL_SCRIPT_URL =+ "https://raw.githubusercontent.com/sandbox-quantum/switch/main/console/packages/agent-controller/install.sh";++/** The one command that installs the controller, enrolls the machine with a fresh code and starts it as a service. */+export function installCommand(+ server: string,+ code: string,+ machine: { name: string; description: string },+): string {+ const options = ["--server", server, "--code", code, ...machineWords(machine)];+ return `curl -fsSL ${CONTROLLER_INSTALL_SCRIPT_URL} | sh -s -- ${options.map(shellQuote).join(" ")}`;+}++/** The command a user runs on a machine where the controller is installed already, to enroll it with a fresh code. */export function enrollCommand(server: string,code: string,machine: { name: string; description: string },): string {- const words = ["switch-agent-controller", "enroll", "--server", server, "--code", code];- const name = machine.name.trim();- const description = machine.description.trim();- if (name) words.push("--name", name);- if (description) words.push("--description", description);+ const words = ["switch-agent-controller", "enroll", "--server", server, "--code", code, ...machineWords(machine)];return words.map(shellQuote).join(" ");}diff --git a/gateway/src/pages/machines/AddMachineDialog.test.tsx b/gateway/src/pages/machines/AddMachineDialog.test.tsxindex 5987efeff..7110d0c8e 100644--- a/gateway/src/pages/machines/AddMachineDialog.test.tsx+++ b/gateway/src/pages/machines/AddMachineDialog.test.tsx@@ -33,6 +33,11 @@ describe("AddMachineDialog", () => {"switch-agent-controller enroll --server https://switch-api.example.test --code swce_example",),).toBeTruthy();+ expect(+ screen.getByText(+ /^curl -fsSL https:\/\/raw\.githubusercontent\.com\/.+\/install\.sh \| sh -s -- --server https:\/\/switch-api\.example\.test --code swce_example$/,+ ),+ ).toBeTruthy();expect(screen.queryByText(new RegExp(window.location.origin))).toBeNull();});@@ -54,7 +59,7 @@ describe("AddMachineDialog", () => {it("shows no command for a name or description that is too long", async () => {issue("https://switch-api.example.test");render(<AddMachineDialog open onClose={() => {}} />);- await screen.findByText(/--code swce_example/);+ expect(await screen.findAllByText(/--code swce_example/)).toHaveLength(2);fireEvent.change(screen.getByLabelText("Description (optional)"), {target: { value: "x".repeat(501) },});diff --git a/gateway/src/pages/machines/AddMachineDialog.tsx b/gateway/src/pages/machines/AddMachineDialog.tsxindex 7246ffd50..b02ca2929 100644--- a/gateway/src/pages/machines/AddMachineDialog.tsx+++ b/gateway/src/pages/machines/AddMachineDialog.tsx@@ -21,6 +21,7 @@ import {createEnrollmentCode,type EnrollmentCode,enrollCommand,+ installCommand,MAX_MACHINE_DESCRIPTION,MAX_MACHINE_NAME,} from "../../data/management";@@ -53,10 +54,11 @@ function CopyBlock({ text, label }: { text: string; label: string }) {}/**- * Issues a one-time enrollment code and shows the command that enrolls a- * machine's agents controller with it. The code is shown once: closing the- * dialog discards it, and a new open issues a new one. The optional name and- * description go into the command, so the machine enrolls with them.+ * Issues a one-time enrollment code and shows the commands that install a+ * machine's agents controller and enroll it with that code. The code is shown+ * once: closing the dialog discards it, and a new open issues a new one. The+ * optional name and description go into the commands, so the machine enrolls+ * with them.*/export default function AddMachineDialog({open,@@ -103,7 +105,9 @@ export default function AddMachineDialog({<DialogContentText sx={{ mb: 2 }}>Run the agents controller on the machine that should run your agents (a laptop, yourown VM or a server). Enroll it once with the code below; it then runs whatever agents- you place on it here.+ you place on it here. It needs Linux or macOS with Node 22.13 or later, and the CLI of+ each provider your agents use (such as <code>claude</code> or <code>codex</code>),+ signed in as the user the controller runs as.</DialogContentText>{error && <Alert severity="error">Could not issue an enrollment code: {error}</Alert>}{!error && !enrollment && <CircularProgress size={24} />}@@ -130,22 +134,38 @@ export default function AddMachineDialog({/></Stack><Box>- <Typography variant="subtitle2" gutterBottom>- Enrollment command- </Typography>{enrollment.server_url && (nameError || descriptionError) ? (- <Alert severity="warning">Shorten the name or description to see the command.</Alert>+ <Alert severity="warning">Shorten the name or description to see the commands.</Alert>) : enrollment.server_url ? (- <>- <CopyBlock- text={enrollCommand(enrollment.server_url, enrollment.code, { name, description })}- label="Copy command"- />- <Typography variant="caption" color="text.secondary">- <code>--server</code> is this Switch's API address. If the machine reaches- Switch at a different address, change it to that one.- </Typography>- </>+ <Stack spacing={2}>+ <Box>+ <Typography variant="subtitle2" gutterBottom>+ Install, enroll and start+ </Typography>+ <CopyBlock+ text={installCommand(enrollment.server_url, enrollment.code, { name, description })}+ label="Copy install command"+ />+ <Typography variant="caption" color="text.secondary">+ Installs the newest controller with npm, enrolls this machine, and runs the+ controller as a service of your user. <code>--server</code> is this Switch's+ API address. If the machine reaches Switch at a different address, change it+ to that one.+ </Typography>+ </Box>+ <Box>+ <Typography variant="subtitle2" gutterBottom>+ Already installed+ </Typography>+ <CopyBlock+ text={enrollCommand(enrollment.server_url, enrollment.code, { name, description })}+ label="Copy enroll command"+ />+ <Typography variant="caption" color="text.secondary">+ Then start it with <code>switch-agent-controller install-service</code>.+ </Typography>+ </Box>+ </Stack>) : (<Alert severity="warning">This server does not say where its Switch API is, so no enrollment command@@ -163,9 +183,9 @@ export default function AddMachineDialog({<CopyBlock text={enrollment.code} label="Copy code" /></Box><Alert severity="info">- Single use, valid until {formatDate(enrollment.expires_at)}. After enrolling, start- it with <code>switch-agent-controller run</code>; the machine appears in the list- once it reports.+ Single use, valid until {formatDate(enrollment.expires_at)}. The machine appears in+ the list once its controller reports. If it does not, run{" "}+ <code>switch-agent-controller doctor</code> on it to see what is missing.</Alert></Stack>)}