Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

feat: 支持 Linux npm 服务一键更新

Zhehui Bi0da252b06656
diff --git a/apps/docs/content/docs/self-hosting/deploy-vps.mdx b/apps/docs/content/docs/self-hosting/deploy-vps.mdx
index c9d48fc6ae..a4d6c24844 100644
--- a/apps/docs/content/docs/self-hosting/deploy-vps.mdx
+++ b/apps/docs/content/docs/self-hosting/deploy-vps.mdx
@@ -591,11 +591,32 @@ published image with `./update.sh --replace-local-build`. Building needs about 6
on a smaller server, add swap first or use the published image. Engines you install
from **Settings → AI → Providers** live on the data volume and survive either way.
-### Paths A and C (npm with the service above): the same steps by hand
+### Paths A and C (npm with the service above)
-There is no one-command updater for an npm install yet. Do what the script
-does: copy the data first, install one named version, check it, and keep the
-way back. Take the stable version number from
+From a trusted checkout on the Linux server, run this from the administrator shell:
+
+```sh
+sudo ./deploy/update-npm.sh
+```
+
+The script needs systemd with cgroup v2, curl, jq, and the
+[fixed-prefix unit above](#keep-it-running) with the default data directory and
+port. It stages the newer stable package as the service user before downtime,
+then stops the service, copies its data, and starts the new version. It checks
+the local service and verifies that an engine is still ready if one was ready
+before. A failed start or health check restores the previous package and data.
+The script prints the backup location. Keep the backup private because it can
+contain credentials.
+
+If the machine shuts down or the update is interrupted, the next run reports
+the unfinished update and the backup location. To restore the old version and
+the workspace from before the update, run
+`sudo ./deploy/update-npm.sh --rollback`. Data written by the failed version
+is saved alongside the backup. Update between runs to avoid interrupting work.
+
+#### Manual update
+
+For a custom unit, apply the same steps by hand. Take the stable version number from
[`stable.json`](https://raw.githubusercontent.com/milind-soni/OpenMausBot/channels/stable.json)
(`"version"`); until a first version is made stable that file does not exist,
so take the newest one on
@@ -621,8 +642,8 @@ sudo -iu maus sh -c 'mv ~/.openmausbot ~/.openmausbot-failed-update && tar xzf ~
sudo systemctl start openmausbot
```
-A service restart by itself does not update the installed package. For
-foreground `npx` usage, name the release: `npx --yes [email protected] serve --tunnel`.
+A service restart keeps the installed release. For foreground `npx` usage,
+start the version you want with `npx --yes [email protected] serve --tunnel`.
### How far behind a server may fall
diff --git a/deploy/e2e/update-npm.sh b/deploy/e2e/update-npm.sh
new file mode 100644
index 0000000000..17d73a5fb8
--- /dev/null
+++ b/deploy/e2e/update-npm.sh
@@ -0,0 +1,195 @@
+#!/bin/bash
+# Run as root in a disposable Linux systemd VM with Node 24, npm, curl and jq.
+set -euo pipefail
+[[ ${OMB_NPM_UPDATE_TEST_VM:-} == 1 && $EUID == 0 ]] ||
+ { echo "Set OMB_NPM_UPDATE_TEST_VM=1 on a disposable systemd VM."; exit 1; }
+
+updater=$(cd "$(dirname "$0")/.." && pwd)/update-npm.sh
+fixture=/var/lib/omb-npm-update-fixture
+unit_file=/etc/systemd/system/openmausbot.service
+journal=/var/lib/openmausbot-npm-update/pending.json
+account=ombupdate
+home=/home/$account
+npm_bin=$(command -v npm)
+node_path=$(dirname "$(command -v node)")
+for path in "$fixture" "$unit_file" "$home" "${journal%/*}" /usr/sbin/curl /usr/sbin/sleep; do
+ [[ ! -e $path && ! -L $path ]] || { echo "Fixture path already exists: $path"; exit 1; }
+done
+if getent passwd "$account" >/dev/null || systemctl cat openmausbot.service >/dev/null 2>&1; then
+ echo "The fixture needs its own service and account."
+ exit 1
+fi
+install -d -m 0755 "$fixture"
+useradd --create-home --home-dir "$home" "$account"
+as_account() { runuser -u "$account" -- env -C "$home" "HOME=$home" "PATH=$home/.local/bin:$node_path:/usr/bin:/bin" "$@"; }
+as_account mkdir -p "$home/.local/bin" "$home/.openmausbot"
+as_account touch "$home/.openmausbot/before-update"
+
+mkdir "$fixture/dependency" "$fixture/package"
+printf '%s\n' '{"name":"update-fixture-dependency","version":"1.0.0","main":"index.js"}' >"$fixture/dependency/package.json"
+echo 'module.exports = 8799' >"$fixture/dependency/index.js"
+"$npm_bin" pack --quiet --pack-destination "$fixture" "$fixture/dependency"
+cat >"$fixture/package/cli.js" <<'JS'
+#!/usr/bin/env node
+const { fork } = require('node:child_process');
+const { join } = require('node:path');
+const { writeFileSync } = require('node:fs');
+const { createServer } = require('node:http');
+const port = require('update-fixture-dependency');
+const { version } = require('./package.json');
+if (!process.argv.includes('--http-child')) {
+ const child = fork(__filename, ['--http-child'], {
+ env: { ...process.env, OMB_DATA_DIR: join(process.env.HOME, '.openmausbot'), OMB_PORT: String(port) },
+ });
+ child.on('exit', code => process.exit(code ?? 1));
+} else {
+ writeFileSync(join(process.env.OMB_DATA_DIR, version), 'fixture startup\n');
+ createServer((req, res) => {
+ res.setHeader('content-type', 'application/json');
+ res.end(JSON.stringify(req.url === '/api/health/engines'
+ ? { app: 'openmausbot', engines: ['0.1.3', '0.1.4', '0.1.5'].includes(version) ? 0 : 1 }
+ : { app: 'openmausbot', version, pid: process.pid }));
+ }).listen(port, '127.0.0.1');
+}
+JS
+chmod 755 "$fixture/package/cli.js"
+for version in 0.1.1 0.1.2 0.1.3 0.1.4 0.1.5; do
+ jq -n --arg version "$version" --arg dep "file:$fixture/update-fixture-dependency-1.0.0.tgz" \
+ '{name:"openmausbot", $version, bin:{openmausbot:"cli.js"}, dependencies:{"update-fixture-dependency":$dep}}' >"$fixture/package/package.json"
+ "$npm_bin" pack --quiet --pack-destination "$fixture" "$fixture/package"
+done
+as_account "$npm_bin" install --offline --global --prefix "$home/.local" "$fixture/openmausbot-0.1.1.tgz"
+ln -s "$npm_bin" "$fixture/npm"
+cat >"$home/.local/bin/npm" <<'EOF'
+#!/bin/bash
+args=("$@")
+release=${args[-1]#openmausbot@}
+unset 'args[-1]'
+exec /var/lib/omb-npm-update-fixture/npm "${args[@]}" --offline "/var/lib/omb-npm-update-fixture/openmausbot-$release.tgz"
+EOF
+chmod 755 "$home/.local/bin/npm"
+chown "$account:$account" "$home/.local/bin/npm"
+cat >/usr/sbin/curl <<'EOF'
+#!/bin/bash
+if [[ "${!#}" == https://raw.githubusercontent.com/milind-soni/OpenMausBot/channels/stable.json ]]; then
+ cat /var/lib/omb-npm-update-fixture/stable.json
+else
+ exec /usr/bin/curl "$@"
+fi
+EOF
+printf '%s\n' '#!/bin/sh' 'exec /usr/bin/sleep 0.08' >/usr/sbin/sleep
+chmod 755 /usr/sbin/curl /usr/sbin/sleep
+
+cat >"$unit_file" <<EOF
+[Unit]
+Description=OpenMausBot npm update fixture
+
+[Service]
+User=$account
+WorkingDirectory=$home
+Environment=HOME=$home
+Environment=PATH=$home/.local/bin:$node_path:/usr/bin:/bin
+ExecStart=$home/.local/bin/openmausbot serve --tunnel
+Restart=always
+RestartSec=5
+EOF
+systemctl daemon-reload
+systemctl start openmausbot.service
+
+health() { /usr/bin/curl -fsS http://127.0.0.1:8799/api/health 2>/dev/null | jq -er ".$1"; }
+wait_version() {
+ for ((i = 0; i < 150; i++)); do
+ [[ $(health version) == "$1" ]] && return 0
+ /usr/bin/sleep 0.05
+ done
+ journalctl -u openmausbot.service -n 15
+ return 1
+}
+stable() { jq -n --arg version "$1" '{$version}' >"$fixture/stable.json"; }
+expect_failure() {
+ local message=$1 output
+ shift
+ if output=$("$updater" "$@" 2>&1); then
+ printf 'Expected failure, got:\n%s\n' "$output"
+ return 1
+ fi
+ printf '%s\n' "$output"
+ [[ $output == *"$message"* ]]
+}
+
+wait_version 0.1.1
+old_pid=$(health pid)
+printf 'broken manifest\n' >"$fixture/stable.json"
+expect_failure "Can't read the stable release"
+[[ $(health pid) == "$old_pid" ]]
+printf 'Verify stage failure preserves the existing service\n'
+stable 0.1.9
+expect_failure 'npm could not stage'
+[[ $(health pid) == "$old_pid" ]]
+
+stable 0.1.2
+cp "$unit_file" "$fixture/original.service"
+printf 'Environment=OMB_DATA_DIR=/non-default\n' >>"$unit_file"
+systemctl daemon-reload
+expect_failure 'additional environment settings'
+[[ $(health pid) == "$old_pid" ]]
+cp "$fixture/original.service" "$unit_file"
+systemctl daemon-reload
+
+"$updater"
+[[ $(health version) == 0.1.2 && -f $home/.openmausbot/before-update && ! -e $journal ]]
+new_pid=$(health pid)
+"$updater"
+[[ $(health pid) == "$new_pid" ]]
+
+stable 0.1.3
+expect_failure 'OpenMausBot 0.1.2 is running again'
+[[ $(health version) == 0.1.2 && ! -e $home/.openmausbot/0.1.3 && ! -e $journal ]]
+compgen -G "$home/.openmausbot-update.*/failed-data.*/data/0.1.3" >/dev/null
+
+stable 0.1.4
+"$updater" >"$fixture/interrupted.log" 2>&1 &
+updating=$!
+wait_version 0.1.4
+expect_failure 'Another npm service update is running'
+kill -KILL "$updating"
+wait "$updating" 2>/dev/null || :
+/usr/bin/sleep 0.2
+expect_failure 'stopped at applying'
+[[ $(health version) == 0.1.4 ]]
+as_account touch "$home/.openmausbot/after-interruption"
+"$updater" --rollback
+[[ $(health version) == 0.1.2 && ! -e $home/.openmausbot/after-interruption && ! -e $journal ]]
+compgen -G "$home/.openmausbot-update.*/failed-data.*/data/after-interruption" >/dev/null
+
+stable 0.1.5
+"$updater" >"$fixture/interrupted-restore.log" 2>&1 &
+updating=$!
+wait_version 0.1.5
+kill -KILL "$updating"
+wait "$updating" 2>/dev/null || :
+/usr/bin/sleep 0.2
+
+# Recreate a reboot between preserving the failed workspace and moving the replacement into place.
+run_id=$(jq -er .run "$journal")
+workspace=$home/.openmausbot-update.$run_id
+modules=$home/.local/lib/node_modules
+package=$modules/.openmausbot-update.$run_id
+systemctl stop openmausbot.service
+as_account mv -T "$modules/openmausbot" "$package/failed"
+as_account mv -T "$package/previous" "$modules/openmausbot"
+as_account cp -a "$workspace/snapshot" "$workspace/replacement"
+inode=$(stat -c %i "$workspace/replacement")
+jq --arg inode "$inode" '.phase = "restoring" | .restoreInode = $inode' "$journal" >"$journal.fixture"
+mv "$journal.fixture" "$journal"
+failed=$(as_account mktemp -d "$workspace/failed-data.XXXXXXXX")
+as_account mv -T "$home/.openmausbot" "$failed/data"
+as_account mkdir "$home/.openmausbot"
+as_account touch "$home/.openmausbot/new-after-reboot"
+systemctl start openmausbot.service
+wait_version 0.1.2
+"$updater" --rollback
+[[ -f $home/.openmausbot/before-update && ! -e $home/.openmausbot/new-after-reboot && ! -e $journal ]]
+[[ -f $failed/data/0.1.5 ]]
+compgen -G "$workspace/failed-data.*/data/new-after-reboot" >/dev/null
+printf 'Linux npm service update fixture passed.\n'
diff --git a/deploy/update-npm.sh b/deploy/update-npm.sh
new file mode 100755
index 0000000000..b2b7ec130d
--- /dev/null
+++ b/deploy/update-npm.sh
@@ -0,0 +1,293 @@
+#!/bin/bash -p
+# Update the fixed-prefix npm installation used by the documented Linux VPS service.
+set -euo pipefail
+export PATH=/usr/sbin:/usr/bin:/sbin:/bin
+umask 077
+
+unit=openmausbot.service
+state_dir=/var/lib/openmausbot-npm-update
+journal=$state_dir/pending.json
+stable_url=https://raw.githubusercontent.com/milind-soni/OpenMausBot/channels/stable.json
+local_url=http://127.0.0.1:8799
+version_pattern='^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$'
+restore_inode=
+
+die() { printf '%s\n' "$*" >&2; exit 1; }
+property() { systemctl show --property="$1" --value "$unit"; }
+as_service() {
+ runuser -u "$service_user" -- /usr/bin/env -i -C "$service_home" \
+ "HOME=$service_home" "USER=$service_user" "LOGNAME=$service_user" "PATH=$service_path" "$@" 9>&-
+}
+service_test() { as_service /usr/bin/test "$@"; }
+physical_dir() {
+ service_test -d "$1" && [[ $(as_service /usr/bin/readlink -f -- "$1") == "$1" ]]
+}
+package_version() {
+ as_service /usr/bin/jq -er 'select(.name == "openmausbot" and .bin.openmausbot == "cli.js") | .version | strings' "$1/package.json"
+}
+
+read_service() {
+ local account uid home exec_start env entry
+ [[ $(property LoadState) == loaded && $(property NeedDaemonReload) == no &&
+ $(property FragmentPath) == "/etc/systemd/system/$unit" && -z $(property DropInPaths) &&
+ $(property Type) == simple && $(property KillMode) == control-group && $(property Slice) == system.slice ]] ||
+ die "Expected the documented systemd unit at /etc/systemd/system/$unit, with no overrides."
+ for entry in EnvironmentFiles PassEnvironment UnsetEnvironment RootDirectory RootImage \
+ BindPaths BindReadOnlyPaths TemporaryFileSystem ExecStartPre ExecStartPost ExecStop ExecStopPost; do
+ [[ -z $(property "$entry") ]] || die "$unit uses $entry. This installation needs a manual update."
+ done
+ service_user=$(property User)
+ [[ $service_user =~ ^[a-z_][a-z0-9_-]*$ ]] || die "Expected a named, unprivileged service account."
+ account=$(getent passwd "$service_user") || die "Can't find the service account $service_user."
+ IFS=: read -r _ _ uid _ _ home _ <<<"$account"
+ [[ $uid =~ ^[1-9][0-9]*$ && $home =~ ^/[[:alnum:]_./-]+$ && $home != / &&
+ $(property WorkingDirectory) == "$home" ]] || die "Can't verify the service account's home."
+ service_home=$home
+ prefix=$home/.local
+ modules=$prefix/lib/node_modules
+ package_dir=$modules/openmausbot
+ data_dir=$home/.openmausbot
+ cli=$prefix/bin/openmausbot
+ exec_start=$(property ExecStart)
+ case "$exec_start" in
+ "{ path=$cli ; argv[]=$cli serve --tunnel ; ignore_errors=no ; "*|\
+ "{ path=$cli ; argv[]=$cli serve --tailscale ; ignore_errors=no ; "*) ;;
+ *) die "$unit does not start the fixed-prefix npm CLI with --tunnel or --tailscale." ;;
+ esac
+ env=$(property Environment)
+ [[ $env == "HOME=$home PATH="* ]] || die "$unit must set HOME and PATH as in the Linux VPS guide."
+ service_path=${env#"HOME=$home PATH="}
+ [[ $service_path =~ ^(/[[:alnum:]_./-]+)(:/[[:alnum:]_./-]+)*$ ]] ||
+ die "$unit has additional environment settings or an unsupported PATH."
+}
+
+fetch_json() {
+ curl --disable -fsS --max-time 5 --max-filesize 65536 --noproxy '*' "$1"
+}
+healthy() {
+ local health pid group process_data
+ systemctl is-active --quiet "$unit" || return 1
+ health=$(fetch_json "$local_url/api/health") || return 1
+ pid=$(jq -er --arg version "$1" \
+ 'select(.app == "openmausbot" and .version == $version) | .pid | numbers' <<<"$health") || return 1
+ [[ $pid =~ ^[1-9][0-9]*$ ]] || return 1
+ group=$(property ControlGroup) || return 1
+ [[ $group == "/system.slice/$unit" ]] || return 1
+ # serve launches the HTTP process as a child within the unit's cgroup.
+ grep -Fxq "0::$group" "/proc/$pid/cgroup" &&
+ grep -zFxq "OMB_DATA_DIR=$data_dir" "/proc/$pid/environ" &&
+ grep -zFxq 'OMB_PORT=8799' "/proc/$pid/environ" || return 1
+ process_data=$(stat -Lc '%d:%i' "/proc/$pid/root$data_dir") || return 1
+ [[ $process_data == "$(stat -Lc '%d:%i' "$data_dir")" ]]
+}
+engine_count() {
+ local count report
+ if count=$(fetch_json "$local_url/api/health/engines" 2>/dev/null |
+ jq -er 'select(.app == "openmausbot") | .engines | select(type == "number" and . >= 0 and floor == .)'); then
+ printf '%s\n' "$count"
+ return
+ fi
+ # Older releases expose engine readiness through doctor. A zero count can have a nonzero exit status.
+ report=$(as_service /usr/bin/timeout 15 "$cli" doctor --json 2>/dev/null) || :
+ jq -er 'select(.health.app == "openmausbot") | .availableEngineCount | select(type == "number" and . >= 0 and floor == .)' <<<"$report"
+}
+wait_healthy() {
+ local attempt count consecutive=0 deadline=$((SECONDS + 120))
+ for ((attempt = 0; attempt < 30 && SECONDS < deadline; attempt++)); do
+ if healthy "$1" 2>/dev/null; then
+ consecutive=$((consecutive + 1))
+ if ((consecutive >= 3)); then
+ if [[ $engine_before == 0 ]]; then return 0; fi
+ if count=$(engine_count 2>/dev/null) && [[ $count =~ ^[1-9][0-9]*$ ]]; then return 0; fi
+ fi
+ else
+ consecutive=0
+ fi
+ sleep 2
+ done
+ printf 'Version %s or its required engine did not become healthy. See journalctl -u %s.\n' "$1" "$unit" >&2
+ return 1
+}
+stop_service() {
+ local active_state events=/sys/fs/cgroup/system.slice/$unit/cgroup.events
+ systemctl stop "$unit" || return 1
+ active_state=$(property ActiveState) || return 1
+ [[ $active_state == inactive || $active_state == failed ]] && [[ $(property MainPID) == 0 ]] &&
+ { [[ ! -e $events ]] || grep -Fxq 'populated 0' "$events"; }
+}
+
+set_work_paths() {
+ data_work=$service_home/.openmausbot-update.$run_id
+ package_work=$modules/.openmausbot-update.$run_id
+ staged_package=$package_work/install/lib/node_modules/openmausbot
+}
+write_phase() {
+ local next=$1 temporary
+ temporary=$(mktemp "$state_dir/.pending.XXXXXXXX") || return 1
+ jq -n --arg phase "$next" --arg run "$run_id" --arg user "$service_user" --arg home "$service_home" \
+ --arg old "$old_version" --arg target "$target_version" --arg engines "$engine_before" --arg inode "$restore_inode" \
+ '{phase: $phase, run: $run, user: $user, home: $home, old: $old, target: $target, engines: $engines, restoreInode: $inode}' \
+ >"$temporary" && mv -fT -- "$temporary" "$journal" || return 1
+ phase=$next
+ sync -f "$state_dir"
+}
+clear_journal() { rm -- "$journal" && sync -f "$state_dir"; }
+
+restore_previous() {
+ local staging preserved
+ if [[ $phase == applying ]]; then
+ physical_dir "$data_work/snapshot" || return 1
+ stop_service || return 1
+
+ if service_test -d "$package_work/previous"; then
+ if service_test -d "$package_dir"; then
+ as_service /usr/bin/mv -T -- "$package_dir" "$package_work/failed" || return 1
+ fi
+ as_service /usr/bin/mv -T -- "$package_work/previous" "$package_dir" || return 1
+ fi
+ [[ $(package_version "$package_dir") == "$old_version" ]] || return 1
+
+ if ! physical_dir "$data_work/replacement"; then
+ staging=$(as_service /usr/bin/mktemp -d "$data_work/restore.XXXXXXXX") || return 1
+ as_service /usr/bin/cp -a --reflink=auto -- "$data_work/snapshot" "$staging/data" &&
+ as_service /usr/bin/mv -T -- "$staging/data" "$data_work/replacement" || return 1
+ fi
+ restore_inode=$(as_service /usr/bin/stat -c %i -- "$data_work/replacement") || return 1
+ as_service /usr/bin/sync -f "$package_dir" && as_service /usr/bin/sync -f "$data_work" &&
+ write_phase restoring || return 1
+ fi
+ if [[ $phase == restoring ]]; then
+ [[ $(package_version "$package_dir") == "$old_version" ]] || return 1
+ stop_service || return 1
+ if physical_dir "$data_work/replacement"; then
+ [[ $(as_service /usr/bin/stat -c %i -- "$data_work/replacement") == "$restore_inode" ]] || return 1
+ if service_test -e "$data_dir" || service_test -L "$data_dir"; then
+ preserved=$(as_service /usr/bin/mktemp -d "$data_work/failed-data.XXXXXXXX") || return 1
+ as_service /usr/bin/mv -T -- "$data_dir" "$preserved/data" || return 1
+ fi
+ as_service /usr/bin/mv -T -- "$data_work/replacement" "$data_dir" || return 1
+ fi
+ # A reboot between the two renames can leave a freshly created workspace at the live path.
+ [[ $(as_service /usr/bin/stat -c %i -- "$data_dir") == "$restore_inode" ]] &&
+ as_service /usr/bin/sync -f "$data_dir" && write_phase restored || return 1
+ fi
+ [[ $(package_version "$package_dir") == "$old_version" ]] &&
+ systemctl start "$unit" && wait_healthy "$old_version" && clear_journal
+}
+
+failed_update() {
+ printf '%s\n' "$*" >&2
+ if restore_previous; then
+ die "OpenMausBot $old_version is running again. Update files are in $data_work and $package_work."
+ fi
+ die "Recovery is incomplete. See $journal and $data_work, then run this script with --rollback."
+}
+
+read_pending() {
+ phase=$(jq -er '.phase | strings' "$journal")
+ run_id=$(jq -er '.run | strings' "$journal")
+ old_version=$(jq -er '.old | strings' "$journal")
+ target_version=$(jq -er '.target | strings' "$journal")
+ engine_before=$(jq -er '.engines | strings' "$journal")
+ restore_inode=$(jq -er '.restoreInode | strings' "$journal")
+ [[ $phase =~ ^(stopping|applying|restoring|restored)$ && $run_id =~ ^[[:alnum:]]{8}$ &&
+ $old_version =~ $version_pattern && $target_version =~ $version_pattern && $engine_before =~ ^[0-9]+$ ]] ||
+ die "Can't read recovery information in $journal."
+ if [[ $phase == restoring && ! $restore_inode =~ ^[1-9][0-9]*$ ]]; then
+ die "Can't identify the replacement workspace in $journal."
+ fi
+ [[ $(jq -r '.user' "$journal") == "$service_user" && $(jq -r '.home' "$journal") == "$service_home" ]] ||
+ die "$unit no longer matches the account recorded in $journal."
+ set_work_paths
+}
+
+case "${1:-}" in
+ "") mode=update ;;
+ --rollback) mode=rollback ;;
+ -h|--help)
+ printf '%s\n' 'Usage: sudo ./deploy/update-npm.sh [--rollback]' \
+ 'Update the documented Linux npm service to stable, or recover an interrupted update.'
+ exit 0 ;;
+ *) die "Unknown option: $1. See --help." ;;
+esac
+[[ $# -le 1 ]] || die "Expected at most one option. See --help."
+[[ $(uname -s) == Linux && $EUID == 0 ]] || die "Run this updater from a Linux administrator shell."
+for tool in systemctl jq curl getent runuser flock mountpoint; do
+ command -v "$tool" >/dev/null || die "Required command not found: $tool"
+done
+[[ -f /sys/fs/cgroup/cgroup.controllers ]] || die "This updater requires systemd with cgroup v2."
+[[ ! -L $state_dir ]] || die "$state_dir is a symbolic link."
+install -d -m 0700 -- "$state_dir"
+[[ $(stat -c %u -- "$state_dir") == 0 ]] || die "$state_dir must be owned by root."
+exec 9>"$state_dir/lock"
+flock -n 9 || die "Another npm service update is running."
+read_service
+trap 'exit 130' INT
+trap 'exit 143' TERM
+
+if [[ -f $journal ]]; then
+ read_pending
+ [[ $mode == rollback ]] ||
+ die "An update to $target_version stopped at $phase. See $journal and $data_work. Use --rollback to restore $old_version."
+ printf 'Recovering OpenMausBot %s from %s.\n' "$old_version" "$data_work"
+ restore_previous || die "Recovery is incomplete. Check $journal and journalctl -u $unit, then retry --rollback."
+ printf 'OpenMausBot %s is running again.\n' "$old_version"
+ exit 0
+fi
+[[ $mode == update ]] || die "There is no interrupted update to recover."
+
+for dir in "$service_home" "$package_dir" "$data_dir"; do
+ physical_dir "$dir" || die "Expected a real directory at $dir."
+done
+for dir in "$package_dir" "$data_dir"; do
+ if mountpoint -q -- "$dir"; then die "$dir is a mount point. This installation needs a manual update."; fi
+done
+[[ $(as_service /usr/bin/readlink -f -- "$cli") == "$package_dir/cli.js" ]] ||
+ die "The service CLI does not point into the fixed npm prefix."
+old_version=$(package_version "$package_dir") || die "Can't read the installed OpenMausBot package."
+[[ $old_version =~ $version_pattern ]] || die "Unsupported installed version: $old_version"
+target_version=$(curl --disable -fsS --proto '=https' --max-time 15 --max-filesize 65536 "$stable_url" |
+ jq -er '.version | strings') || die "Can't read the stable release. The service was not stopped."
+[[ $target_version =~ $version_pattern ]] || die "The stable channel returned an invalid version."
+if [[ $target_version == "$old_version" ||
+ $(printf '%s\n' "$old_version" "$target_version" | LC_ALL=C sort -V | tail -n 1) != "$target_version" ]]; then
+ printf 'OpenMausBot %s is already at or ahead of stable (%s).\n' "$old_version" "$target_version"
+ exit 0
+fi
+healthy "$old_version" || die "Can't verify that $unit is serving OpenMausBot $old_version on port 8799."
+
+run_slot=$(mktemp -d "$state_dir/run.XXXXXXXX")
+run_id=${run_slot##*.}
+rmdir -- "$run_slot"
+set_work_paths
+as_service /usr/bin/mkdir -m 0700 -- "$data_work" "$package_work"
+printf 'Staging OpenMausBot %s for %s.\n' "$target_version" "$unit"
+as_service npm install --global --prefix "$package_work/install" --no-audit --no-fund "openmausbot@$target_version" ||
+ die "npm could not stage OpenMausBot $target_version. The service was not stopped."
+[[ $(package_version "$staged_package") == "$target_version" ]] ||
+ die "The staged package did not report version $target_version. The service was not stopped."
+physical_dir "$staged_package" || die "npm staged the package at an unexpected path."
+as_service /usr/bin/sync -f "$package_work"
+
+healthy "$old_version" || die "The running service changed while npm was staging the update."
+[[ $(property NeedDaemonReload) == no ]] || die "The service unit changed while npm was staging the update."
+engine_before=$(engine_count) || die "Can't establish engine readiness before the update."
+write_phase stopping || die "Can't record the update. The service was not stopped."
+stop_service || failed_update "Could not stop $unit before taking a backup."
+printf 'Saving the stopped workspace to %s/snapshot.\n' "$data_work"
+if ! physical_dir "$data_dir" ||
+ ! as_service /usr/bin/cp -a --reflink=auto -- "$data_dir" "$data_work/snapshot" ||
+ ! as_service /usr/bin/sync -f "$data_work"; then
+ failed_update "The workspace backup failed."
+fi
+write_phase applying || failed_update "Could not record the backup."
+
+if ! as_service /usr/bin/mv -T -- "$package_dir" "$package_work/previous" ||
+ ! as_service /usr/bin/mv -T -- "$staged_package" "$package_dir" ||
+ ! as_service /usr/bin/sync -f "$package_dir" ||
+ ! systemctl start "$unit" || ! wait_healthy "$target_version"; then
+ failed_update "OpenMausBot $target_version could not be started successfully."
+fi
+clear_journal
+printf 'OpenMausBot %s is running. Backup: %s/snapshot. Previous package: %s/previous.\n' \
+ "$target_version" "$data_work" "$package_work"
diff --git a/docs/deploy-vps.md b/docs/deploy-vps.md
index c46d5a77d6..c2ca2bdfdf 100644
--- a/docs/deploy-vps.md
+++ b/docs/deploy-vps.md
@@ -584,11 +584,32 @@ published image with `./update.sh --replace-local-build`. Building needs about 6
on a smaller server, add swap first or use the published image. Engines you install
from **Settings → Engines** live on the data volume and survive either way.
-### Paths A and C (npm with the service above): the same steps by hand
+### Paths A and C (npm with the service above)
-There is no one-command updater for an npm install yet. Do what the script
-does: copy the data first, install one named version, check it, and keep the
-way back. Take the stable version number from
+From a trusted checkout on the Linux server, run this from the administrator shell:
+
+```sh
+sudo ./deploy/update-npm.sh
+```
+
+The script needs systemd with cgroup v2, curl, jq, and the
+[fixed-prefix unit above](#keep-it-running) with the default data directory and
+port. It stages the newer stable package as the service user before downtime,
+then stops the service, copies its data, and starts the new version. It checks
+the local service and verifies that an engine is still ready if one was ready
+before. A failed start or health check restores the previous package and data.
+The script prints the backup location. Keep the backup private because it can
+contain credentials.
+
+If the machine shuts down or the update is interrupted, the next run reports
+the unfinished update and the backup location. To restore the old version and
+the workspace from before the update, run
+`sudo ./deploy/update-npm.sh --rollback`. Data written by the failed version
+is saved alongside the backup. Update between runs to avoid interrupting work.
+
+#### Manual update
+
+For a custom unit, apply the same steps by hand. Take the stable version number from
[`stable.json`](https://raw.githubusercontent.com/milind-soni/OpenMausBot/channels/stable.json)
(`"version"`), and note the one you run now (`openmausbot --version`). From
the administrator shell, replacing `X.Y.Z`:
@@ -611,8 +632,8 @@ sudo -iu maus sh -c 'mv ~/.openmausbot ~/.openmausbot-failed-update && tar xzf ~
sudo systemctl start openmausbot
```
-A service restart by itself does not update the installed package. For
-foreground `npx` usage, name the release: `npx --yes [email protected] serve --tunnel`.
+A service restart keeps the installed release. For foreground `npx` usage,
+start the version you want with `npx --yes [email protected] serve --tunnel`.
### How far behind a server may fall
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 561ba05b28..0ac9be2bd1 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -1966,9 +1966,9 @@ is newer than the one it reports), and asks before it puts back data from an
update an earlier run left unfinished.
[Every step, the rollback and the exit codes](deploy-vps.md#update).
-For the npm service there is no one-command updater yet:
-[do the same steps by hand](deploy-vps.md#paths-a-and-c-npm-with-the-service-above-the-same-steps-by-hand),
-as the service user while the server is stopped. For a foreground invocation,
+For the [fixed-prefix Linux npm service](deploy-vps.md#paths-a-and-c-npm-with-the-service-above),
+run `sudo ./deploy/update-npm.sh` from a trusted checkout on the server. The
+[manual steps](deploy-vps.md#manual-update) cover custom units. For a foreground invocation,
`npx --yes [email protected] serve --tunnel` selects a particular published
release; replace `X.Y.Z` with that version.