Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(lume): add explicit updater flow

Francesco Bonacci3982eb44bc4d
diff --git a/.github/workflows/cd-swift-lume.yml b/.github/workflows/cd-swift-lume.yml
index 66001fa348..26e9282a05 100644
--- a/.github/workflows/cd-swift-lume.yml
+++ b/.github/workflows/cd-swift-lume.yml
@@ -33,6 +33,10 @@ on:
required: true
PROVISIONING_PROFILE_BASE64:
required: true
+ RELEASE_APP_ID:
+ required: false
+ RELEASE_APP_PRIVATE_KEY:
+ required: false
permissions:
contents: write
@@ -46,6 +50,8 @@ env:
APP_SPECIFIC_PASSWORD: ${{ secrets.APP_SPECIFIC_PASSWORD }}
DEVELOPER_NAME: ${{ secrets.DEVELOPER_NAME }}
PROVISIONING_PROFILE_BASE64: ${{ secrets.PROVISIONING_PROFILE_BASE64 }}
+ RELEASE_APP_ID: ${{ secrets.RELEASE_APP_ID }}
+ RELEASE_APP_PRIVATE_KEY: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
jobs:
notarize:
@@ -312,3 +318,39 @@ jobs:
```
generate_release_notes: false
make_latest: true
+
+ - name: Generate GitHub App token (for bake-version push)
+ id: app-token
+ if: startsWith(github.ref, 'refs/tags/lume-v')
+ uses: actions/create-github-app-token@v1
+ with:
+ app-id: ${{ secrets.RELEASE_APP_ID }}
+ private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
+ owner: ${{ github.repository_owner }}
+ repositories: ${{ github.event.repository.name }}
+
+ - name: Bake version into install script (commit + push)
+ if: startsWith(github.ref, 'refs/tags/lume-v')
+ env:
+ VERSION: ${{ steps.set_version.outputs.version }}
+ GH_TOKEN: ${{ steps.app-token.outputs.token }}
+ run: |
+ git config --unset-all "http.https://github.com/.extraheader" || true
+ git remote set-url origin "https://x-access-token:${GH_TOKEN}@github.com/${{ github.repository }}.git"
+ git fetch origin main
+ git checkout -B bake-lume-version origin/main
+
+ sed -i '' \
+ "s/^LUME_BAKED_VERSION=.*/LUME_BAKED_VERSION=\"${VERSION}\"/" \
+ libs/lume/scripts/install.sh
+
+ if git diff --quiet -- libs/lume/scripts/install.sh; then
+ echo "LUME_BAKED_VERSION already ${VERSION}; nothing to commit."
+ exit 0
+ fi
+
+ git config user.name "trycua-release[bot]"
+ git config user.email "trycua-release[bot]@users.noreply.github.com"
+ git add libs/lume/scripts/install.sh
+ git commit -m "chore(lume): bake version ${VERSION} into install script [skip ci]"
+ git push origin bake-lume-version:main
diff --git a/docs/content/docs/how-to-guides/lume/install-lume.mdx b/docs/content/docs/how-to-guides/lume/install-lume.mdx
index fae163db00..be13e8717e 100644
--- a/docs/content/docs/how-to-guides/lume/install-lume.mdx
+++ b/docs/content/docs/how-to-guides/lume/install-lume.mdx
@@ -34,6 +34,23 @@ Install with a single command:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/trycua/cua/main/libs/lume/scripts/install.sh)"
```
+## Update Lume
+
+Check whether a newer release is available:
+
+```bash
+lume check-update
+```
+
+Apply an available update:
+
+```bash
+lume update --apply
+```
+
+The installer no longer creates scheduled auto-updaters. Older `lume-update` cron jobs and
+LaunchAgents are removed the next time the installer runs.
+
### Manual Start (No Background Service)
By default, Lume is installed as a background service that starts automatically on login. If you prefer to start the Lume API service manually when needed, you can use the `--no-background-service` option:
diff --git a/docs/content/docs/reference/lume/cli.mdx b/docs/content/docs/reference/lume/cli.mdx
index a98b2ed82a..1ee844388c 100644
--- a/docs/content/docs/reference/lume/cli.mdx
+++ b/docs/content/docs/reference/lume/cli.mdx
@@ -22,6 +22,22 @@ lume run ubuntu-noble-vanilla:latest
registry](https://github.com/orgs/trycua/packages).
</Callout>
+### Update Lume
+
+```bash
+# Check whether a newer release is available
+lume check-update
+
+# Apply an available update
+lume update --apply
+```
+
+`lume check-update --json` returns the current version, latest version, update availability,
+release notes URL, and install command. `lume update` only applies an update when `--apply` is
+provided.
+
+The MCP server also exposes a read-only `check_for_update` tool with the same update-state payload.
+
### Create a Custom VM
```bash
diff --git a/libs/lume/scripts/install.sh b/libs/lume/scripts/install.sh
index d97a476a5c..fad801757b 100755
--- a/libs/lume/scripts/install.sh
+++ b/libs/lume/scripts/install.sh
@@ -36,12 +36,21 @@ LATEST_RELEASE_URL="https://api.github.com/repos/$GITHUB_REPO/releases/latest"
# Option to skip background service setup (default: install it)
INSTALL_BACKGROUND_SERVICE=true
-# Option to skip auto-updater setup (default: install it)
-INSTALL_AUTO_UPDATER=true
-
-# Option to run updater at login (default: false, uses cron instead)
+# Deprecated auto-updater flags are still accepted for compatibility, but
+# scheduled self-updates are no longer installed. Updates are explicit:
+# `lume check-update` and `lume update --apply`.
+INSTALL_AUTO_UPDATER=false
UPDATE_ON_LOGIN=false
+# Release selection:
+# LUME_VERSION=0.3.10 pins a specific `lume-v0.3.10` release.
+# LUME_BAKED_VERSION is updated by release automation so the default
+# installer path does not need a GitHub API call.
+LUME_VERSION="${LUME_VERSION:-}"
+# ~~~ BAKED_VERSION: auto-updated by CD workflow after each release — do not edit ~~~
+LUME_BAKED_VERSION="0.3.10"
+# ~~~ END_BAKED_VERSION ~~~
+
# Default port for lume serve (default: 7777)
LUME_PORT=7777
@@ -60,9 +69,11 @@ while [ "$#" -gt 0 ]; do
INSTALL_BACKGROUND_SERVICE=false
;;
--no-auto-updater)
+ echo "${YELLOW}Warning: --no-auto-updater is deprecated; scheduled auto-updates are no longer installed.${NORMAL}"
INSTALL_AUTO_UPDATER=false
;;
--update-on-login)
+ echo "${YELLOW}Warning: --update-on-login is deprecated; use 'lume update --apply' for explicit updates.${NORMAL}"
UPDATE_ON_LOGIN=true
;;
--help)
@@ -73,8 +84,8 @@ while [ "$#" -gt 0 ]; do
echo " --install-dir DIR Install to the specified directory (default: $DEFAULT_INSTALL_DIR)"
echo " --port PORT Specify the port for lume serve (default: 7777)"
echo " --no-background-service Do not setup the Lume background service (LaunchAgent)"
- echo " --no-auto-updater Do not setup automatic updates"
- echo " --update-on-login Check for updates at login (adds second Login Item)"
+ echo " --no-auto-updater Deprecated no-op; scheduled auto-updates are no longer installed"
+ echo " --update-on-login Deprecated no-op; use 'lume update --apply'"
echo " --help Display this help message"
echo ""
echo "Examples:"
@@ -164,6 +175,21 @@ create_temp_dir() {
# Get the latest lume release tag
get_latest_lume_tag() {
+ if [ -n "$LUME_VERSION" ]; then
+ local pinned="${LUME_VERSION#lume-v}"
+ pinned="${pinned#v}"
+ echo "Using Lume release from LUME_VERSION: ${BOLD}lume-v$pinned${NORMAL}" >&2
+ echo "lume-v$pinned"
+ return 0
+ fi
+
+ if [ -n "$LUME_BAKED_VERSION" ]; then
+ local baked="${LUME_BAKED_VERSION#v}"
+ echo "Using baked Lume release: ${BOLD}lume-v$baked${NORMAL}" >&2
+ echo "lume-v$baked"
+ return 0
+ fi
+
echo "Finding latest Lume release..." >&2
local page=1
@@ -346,196 +372,19 @@ WRAPPER_EOF
fi
}
-# Install the auto-updater script
-install_updater_script() {
- UPDATER_SCRIPT="$INSTALL_DIR/lume-update"
-
- echo "Installing auto-updater script to $UPDATER_SCRIPT..."
-
- cat <<'UPDATER_EOF' > "$UPDATER_SCRIPT"
-#!/bin/bash
-# Lume Auto-Updater
-# This script checks for updates and installs them if available
-
-set -e
-
-LOG_FILE="/tmp/lume_updater.log"
-GITHUB_REPO="trycua/cua"
-
-log() {
- echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
-}
-
-log "Starting Lume update check..."
-
-# Find lume binary location
-LUME_BIN=$(command -v lume 2>/dev/null || echo "$HOME/.local/bin/lume")
-INSTALL_DIR=$(dirname "$LUME_BIN")
-APP_INSTALL_DIR="$HOME/.local/share/lume"
-
-if [ ! -x "$LUME_BIN" ]; then
- log "ERROR: lume binary not found at $LUME_BIN"
- exit 1
-fi
-
-# Get current version
-CURRENT_VERSION=$("$LUME_BIN" --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1 || echo "0.0.0")
-log "Current version: $CURRENT_VERSION"
-
-# Get latest release tag from GitHub
-get_latest_tag() {
- local page=1
- local per_page=100
- local max_pages=5
-
- while [ $page -le $max_pages ]; do
- local response=$(curl -s "https://api.github.com/repos/$GITHUB_REPO/releases?per_page=$per_page&page=$page")
-
- if [ -z "$response" ]; then
- return 1
- fi
-
- local tag=$(echo "$response" | grep -oE '"tag_name":\s*"lume-[^"]*"' | head -n 1 | cut -d '"' -f 4)
-
- if [ -n "$tag" ]; then
- echo "$tag"
- return 0
- fi
-
- page=$((page + 1))
- done
-
- return 1
-}
-
-LATEST_TAG=$(get_latest_tag)
-if [ -z "$LATEST_TAG" ]; then
- log "ERROR: Could not fetch latest release tag"
- exit 1
-fi
-
-# Extract version from tag (lume-vX.Y.Z -> X.Y.Z)
-LATEST_VERSION=$(echo "$LATEST_TAG" | sed 's/lume-v//' | sed 's/lume-//')
-log "Latest version: $LATEST_VERSION"
-
-# Compare versions (simple string comparison works for semver)
-version_gt() {
- [ "$(printf '%s\n' "$1" "$2" | sort -V | tail -n1)" = "$1" ] && [ "$1" != "$2" ]
-}
-
-apply_update() {
- log "Downloading and applying update..."
-
- TEMP_DIR=$(mktemp -d)
- trap 'rm -rf "$TEMP_DIR"' EXIT
-
- DOWNLOAD_URL="https://github.com/$GITHUB_REPO/releases/download/$LATEST_TAG/lume.tar.gz"
-
- if curl -sL "$DOWNLOAD_URL" -o "$TEMP_DIR/lume.tar.gz"; then
- if tar -tzf "$TEMP_DIR/lume.tar.gz" > /dev/null 2>&1; then
- tar -xzf "$TEMP_DIR/lume.tar.gz" -C "$TEMP_DIR"
-
- # Stop the daemon before updating
- launchctl unload "$HOME/Library/LaunchAgents/com.trycua.lume_daemon.plist" 2>/dev/null || true
-
- if [ -d "$TEMP_DIR/lume.app" ]; then
- # New .app bundle format
- mkdir -p "$APP_INSTALL_DIR"
- rm -rf "$APP_INSTALL_DIR/lume.app"
- mv "$TEMP_DIR/lume.app" "$APP_INSTALL_DIR/"
-
- # Ensure wrapper script exists
- mkdir -p "$INSTALL_DIR"
- cat > "$INSTALL_DIR/lume" <<INNER_WRAPPER_EOF
-#!/bin/sh
-exec "$APP_INSTALL_DIR/lume.app/Contents/MacOS/lume" "\$@"
-INNER_WRAPPER_EOF
- chmod +x "$INSTALL_DIR/lume"
-
- # Clean up old standalone files
- rm -rf "$INSTALL_DIR/lume_lume.bundle"
-
- log "Successfully updated lume to version $LATEST_VERSION (.app bundle)"
- else
- # Legacy standalone binary format
- mv "$TEMP_DIR/lume" "$INSTALL_DIR/"
- chmod +x "$INSTALL_DIR/lume"
-
- if [ -d "$TEMP_DIR/lume_lume.bundle" ]; then
- rm -rf "$INSTALL_DIR/lume_lume.bundle"
- mv "$TEMP_DIR/lume_lume.bundle" "$INSTALL_DIR/"
- log "Resource bundle installed"
- fi
-
- log "Successfully updated lume to version $LATEST_VERSION"
- fi
-
- # Restart the daemon
- launchctl load "$HOME/Library/LaunchAgents/com.trycua.lume_daemon.plist" 2>/dev/null || true
-
- # Show macOS notification
- osascript -e "display notification \"Updated to version $LATEST_VERSION\" with title \"Lume Updated\"" 2>/dev/null || true
- else
- log "ERROR: Downloaded file is not a valid archive"
- exit 1
- fi
- else
- log "ERROR: Failed to download update"
- exit 1
- fi
-}
-
-if version_gt "$LATEST_VERSION" "$CURRENT_VERSION"; then
- log "New version available: $LATEST_VERSION (current: $CURRENT_VERSION)"
-
- case "${1:-}" in
- --apply|--silent)
- # Silent mode: update immediately without dialog (used by login LaunchAgent)
- apply_update
- ;;
- *)
- # Interactive mode: show dialog asking user if they want to update (used by cron)
- RESPONSE=$(osascript -e "display dialog \"Lume $LATEST_VERSION is available (current: $CURRENT_VERSION).\" buttons {\"Later\", \"Update Now\"} default button \"Update Now\" with title \"Lume Update\"" 2>/dev/null || echo "")
-
- if echo "$RESPONSE" | grep -q "Update Now"; then
- log "User chose to update"
- apply_update
- else
- log "User chose to skip update"
- fi
- ;;
- esac
-else
- log "Already up to date (version $CURRENT_VERSION)"
-fi
-
-log "Update check complete"
-UPDATER_EOF
-
- chmod +x "$UPDATER_SCRIPT"
- echo "Auto-updater script installed."
-}
-
-# Remove legacy auto-updater LaunchAgent if it exists (now integrated into daemon)
-cleanup_legacy_updater() {
+# Remove scheduled auto-updater artifacts from older installers.
+cleanup_deprecated_auto_updater() {
UPDATER_SERVICE_NAME="com.trycua.lume_updater"
UPDATER_PLIST_PATH="$HOME/Library/LaunchAgents/$UPDATER_SERVICE_NAME.plist"
+ UPDATER_SCRIPT="$INSTALL_DIR/lume-update"
- if [ -f "$UPDATER_PLIST_PATH" ]; then
- echo "Removing legacy auto-updater LaunchAgent (now integrated into daemon)..."
- launchctl unload "$UPDATER_PLIST_PATH" 2>/dev/null || true
- rm "$UPDATER_PLIST_PATH"
+ if crontab -l 2>/dev/null | grep -q "lume-update"; then
+ echo "Removing deprecated auto-updater cron job..."
+ crontab -l 2>/dev/null | grep -v "lume-update" | crontab - 2>/dev/null || true
fi
-}
-
-# Remove auto-updater if it exists
-remove_auto_updater() {
- UPDATER_SERVICE_NAME="com.trycua.lume_updater"
- UPDATER_PLIST_PATH="$HOME/Library/LaunchAgents/$UPDATER_SERVICE_NAME.plist"
- UPDATER_SCRIPT="$INSTALL_DIR/lume-update"
if [ -f "$UPDATER_PLIST_PATH" ]; then
- echo "Removing existing auto-updater LaunchAgent..."
+ echo "Removing deprecated auto-updater LaunchAgent..."
launchctl unload "$UPDATER_PLIST_PATH" 2>/dev/null || true
rm "$UPDATER_PLIST_PATH"
fi
@@ -543,8 +392,6 @@ remove_auto_updater() {
if [ -f "$UPDATER_SCRIPT" ]; then
rm "$UPDATER_SCRIPT"
fi
-
- echo "Auto-updater removed."
}
# Main installation flow
@@ -655,69 +502,12 @@ EOF
fi
fi
- # Install updater script and setup update checks
- if [ "$INSTALL_AUTO_UPDATER" = true ]; then
- install_updater_script
- UPDATER_SCRIPT="$INSTALL_DIR/lume-update"
- UPDATER_SERVICE_NAME="com.trycua.lume_updater"
- UPDATER_PLIST_PATH="$HOME/Library/LaunchAgents/$UPDATER_SERVICE_NAME.plist"
-
- if [ "$UPDATE_ON_LOGIN" = true ]; then
- # Remove cron job if switching to login-based updates
- crontab -l 2>/dev/null | grep -v "lume-update" | crontab - 2>/dev/null || true
-
- # Unload existing updater service if present
- if [ -f "$UPDATER_PLIST_PATH" ]; then
- launchctl unload "$UPDATER_PLIST_PATH" 2>/dev/null || true
- fi
-
- # Create LaunchAgent that runs updater at login (not persistent, silent mode)
- cat <<EOF > "$UPDATER_PLIST_PATH"
-<?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>$UPDATER_SERVICE_NAME</string>
- <key>ProgramArguments</key>
- <array>
- <string>$UPDATER_SCRIPT</string>
- <string>--silent</string>
- </array>
- <key>RunAtLoad</key>
- <true/>
- <key>StandardOutPath</key>
- <string>/tmp/lume_updater.log</string>
- <key>StandardErrorPath</key>
- <string>/tmp/lume_updater.error.log</string>
-</dict>
-</plist>
-EOF
- chmod 644 "$UPDATER_PLIST_PATH"
- launchctl load "$UPDATER_PLIST_PATH"
- echo "${GREEN}Auto-updater installed. Checks at login.${NORMAL}"
- else
- # Clean up any LaunchAgent updater (we use cron by default)
- cleanup_legacy_updater
-
- # Setup cron job for daily update check (doesn't show in Login Items)
- CRON_ENTRY="0 10 * * 1 $UPDATER_SCRIPT >/tmp/lume_updater.log 2>&1"
- EXISTING_CRON=$(crontab -l 2>/dev/null || echo "")
- NEW_CRON=$(echo "$EXISTING_CRON" | grep -v "lume-update" || echo "")
- echo "${NEW_CRON}${NEW_CRON:+
-}${CRON_ENTRY}" | crontab -
- echo "${GREEN}Auto-updater installed. Checks weekly on Mondays at 10am via cron.${NORMAL}"
- fi
-
- # Run updater once after installation
- if [ -x "$UPDATER_SCRIPT" ]; then
- "$UPDATER_SCRIPT" &
- fi
- else
- # Remove updater cron job and LaunchAgent if auto-updater is disabled
- crontab -l 2>/dev/null | grep -v "lume-update" | crontab - 2>/dev/null || true
- cleanup_legacy_updater
- fi
+ cleanup_deprecated_auto_updater
+ echo ""
+ echo "Updates are explicit. To check later, run:"
+ echo " ${BOLD}lume check-update${NORMAL}"
+ echo "To update, run:"
+ echo " ${BOLD}lume update --apply${NORMAL}"
}
# Run the installation
diff --git a/libs/lume/src/Commands/CheckUpdate.swift b/libs/lume/src/Commands/CheckUpdate.swift
new file mode 100644
index 0000000000..692e87afda
--- /dev/null
+++ b/libs/lume/src/Commands/CheckUpdate.swift
@@ -0,0 +1,131 @@
+import ArgumentParser
+import Foundation
+
+struct CheckUpdate: AsyncParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "check-update",
+ abstract: "Check whether a newer Lume release is available",
+ discussion: """
+ Read-only update check. Uses GitHub Releases, caches the result briefly,
+ and never installs anything.
+ """
+ )
+
+ @Flag(help: "Emit the structured update-state payload as JSON")
+ var json: Bool = false
+
+ @Flag(help: "Bypass the local update-check cache")
+ var noCache: Bool = false
+
+ func run() async throws {
+ guard LumeVersionCheck.updateChecksEnabled() else {
+ if json {
+ try printJSON(LumeVersionCheck.disabledState())
+ } else {
+ print("Update checks disabled by LUME_UPDATE_CHECK.")
+ }
+ return
+ }
+
+ let state = await LumeVersionCheck.checkUpdateState(noCache: noCache)
+
+ if json {
+ try printJSON(state)
+ } else if let error = state.error {
+ print("Update check failed: \(error)")
+ } else if state.updateAvailable, let latest = state.latestVersion {
+ print("Update available: Lume \(latest) (you have \(state.currentVersion)).")
+ print("Update with: lume update --apply")
+ } else {
+ print("Up to date (Lume \(state.currentVersion)).")
+ }
+ }
+}
+
+struct Update: AsyncParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "update",
+ abstract: "Check for a Lume update and optionally apply it",
+ discussion: """
+ Without --apply, this command only checks for a newer release and prints
+ the command to install it. With --apply, it delegates installation to
+ the canonical Lume installer pinned to the discovered version.
+ """
+ )
+
+ @Flag(help: "Apply the update by re-running the official installer")
+ var apply: Bool = false
+
+ @Flag(help: "Emit the structured update-state payload as JSON")
+ var json: Bool = false
+
+ func run() async throws {
+ if json && apply {
+ throw ValidationError("--json cannot be combined with --apply because installer output is interactive.")
+ }
+
+ guard LumeVersionCheck.updateChecksEnabled() else {
+ if json {
+ try printJSON(LumeVersionCheck.disabledState())
+ } else {
+ print("Update checks disabled by LUME_UPDATE_CHECK.")
+ }
+ return
+ }
+
+ let state = await LumeVersionCheck.checkUpdateState(noCache: false)
+
+ if json {
+ try printJSON(state)
+ }
+
+ if let error = state.error {
+ if !json {
+ print("Update check failed: \(error)")
+ }
+ throw ExitCode.failure
+ }
+
+ guard state.updateAvailable, let latest = state.latestVersion else {
+ if !json {
+ print("Up to date (Lume \(state.currentVersion)).")
+ }
+ return
+ }
+
+ if !apply {
+ if !json {
+ print("Update available: Lume \(latest) (you have \(state.currentVersion)).")
+ print("Run `lume update --apply` to install.")
+ }
+ return
+ }
+
+ if !json {
+ print("Installing Lume \(latest)...")
+ }
+
+ let status = try LumeVersionCheck.runInstallScript(version: latest)
+ guard status == 0 else {
+ if !json {
+ print("Installer failed with exit status \(status).")
+ print("You can retry manually: \(LumeVersionCheck.manualInstallCommand())")
+ }
+ throw ExitCode(status)
+ }
+
+ if !json {
+ print("Lume \(latest) installed.")
+ }
+ }
+}
+
+private func printJSON<T: Encodable>(_ value: T) throws {
+ let encoder = JSONEncoder()
+ encoder.keyEncodingStrategy = .convertToSnakeCase
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
+ let data = try encoder.encode(value)
+ if let string = String(data: data, encoding: .utf8) {
+ print(string)
+ }
+}
diff --git a/libs/lume/src/Server/MCPServer.swift b/libs/lume/src/Server/MCPServer.swift
index 492a64653b..5864e0b14b 100644
--- a/libs/lume/src/Server/MCPServer.swift
+++ b/libs/lume/src/Server/MCPServer.swift
@@ -316,6 +316,14 @@ final class LumeMCPServer {
private var toolDefinitions: [Tool] {
[
+ Tool(
+ name: "check_for_update",
+ description: "Check whether a newer Lume release is available on GitHub. Read-only; never installs. Mirrors `lume check-update --json`.",
+ inputSchema: .object([
+ "type": .string("object"),
+ "properties": .object([:])
+ ])
+ ),
Tool(
name: "lume_list_vms",
description: "List all virtual machines with their status, IP addresses, and resource allocation",
@@ -519,6 +527,8 @@ final class LumeMCPServer {
return try await handleExec(params.arguments)
case "lume_create_vm":
return try await handleCreateVM(params.arguments)
+ case "check_for_update":
+ return try await handleCheckForUpdate(params.arguments)
default:
return CallTool.Result(
content: [.text("Unknown tool: \(params.name)")],
@@ -535,6 +545,26 @@ final class LumeMCPServer {
// MARK: - Tool Implementations
+ private func handleCheckForUpdate(_ args: [String: Value]?) async throws -> CallTool.Result {
+ let state = await LumeVersionCheck.checkUpdateState(noCache: false)
+ let encoder = JSONEncoder()
+ encoder.keyEncodingStrategy = .convertToSnakeCase
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
+ let json = try encoder.encode(state)
+
+ let summary: String
+ if let error = state.error {
+ summary = "Update check failed: \(error)"
+ } else if state.updateAvailable, let latest = state.latestVersion {
+ summary = "Update available: Lume \(latest) (you have \(state.currentVersion))."
+ } else {
+ summary = "Up to date (Lume \(state.currentVersion))."
+ }
+
+ let payload = String(data: json, encoding: .utf8) ?? "{}"
+ return CallTool.Result(content: [.text("\(summary)\n\n\(payload)")])
+ }
+
private func handleListVMs(_ args: [String: Value]?) async throws -> CallTool.Result {
let storage = args?["storage"]?.stringValue
let vms = try controller.list(storage: storage)
diff --git a/libs/lume/src/Update/VersionCheck.swift b/libs/lume/src/Update/VersionCheck.swift
new file mode 100644
index 0000000000..e93e1c82a4
--- /dev/null
+++ b/libs/lume/src/Update/VersionCheck.swift
@@ -0,0 +1,303 @@
+import Foundation
+
+enum LumeVersionCheck {
+ static let releaseTagPrefix = "lume-v"
+ static let releasesURL = URL(string: "https://api.github.com/repos/trycua/cua/releases?per_page=40")!
+ static let defaultInstallScriptURL =
+ "https://raw.githubusercontent.com/trycua/cua/main/libs/lume/scripts/install.sh"
+
+ private static let cacheRefreshSeconds: TimeInterval = 20 * 60 * 60
+ private static let updateCheckEnv = "LUME_UPDATE_CHECK"
+ private static let installScriptURLEnv = "LUME_INSTALL_SCRIPT_URL"
+
+ struct State: Codable {
+ let currentVersion: String
+ let latestVersion: String?
+ let updateAvailable: Bool
+ let source: String
+ let checkedAt: String
+ let cacheHit: Bool
+ let installCommand: String?
+ let releaseNotesURL: String?
+ let error: String?
+
+ enum CodingKeys: String, CodingKey {
+ case currentVersion
+ case latestVersion
+ case updateAvailable
+ case source
+ case checkedAt
+ case cacheHit
+ case installCommand
+ case releaseNotesURL
+ case error
+ }
+
+ func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encode(currentVersion, forKey: .currentVersion)
+ try encodeOptional(latestVersion, into: &container, forKey: .latestVersion)
+ try container.encode(updateAvailable, forKey: .updateAvailable)
+ try container.encode(source, forKey: .source)
+ try container.encode(checkedAt, forKey: .checkedAt)
+ try container.encode(cacheHit, forKey: .cacheHit)
+ try encodeOptional(installCommand, into: &container, forKey: .installCommand)
+ try encodeOptional(releaseNotesURL, into: &container, forKey: .releaseNotesURL)
+ try encodeOptional(error, into: &container, forKey: .error)
+ }
+
+ private func encodeOptional(
+ _ value: String?,
+ into container: inout KeyedEncodingContainer<CodingKeys>,
+ forKey key: CodingKeys
+ ) throws {
+ if let value {
+ try container.encode(value, forKey: key)
+ } else {
+ try container.encodeNil(forKey: key)
+ }
+ }
+ }
+
+ struct Cache: Codable {
+ var lastCheckedUnix: TimeInterval?
+ var latestVersion: String?
+ }
+
+ static func checkUpdateState(noCache: Bool = false) async -> State {
+ guard updateChecksEnabled() else {
+ return disabledState()
+ }
+
+ let current = Lume.Version.current
+ let now = Date()
+ let checkedAt = ISO8601DateFormatter().string(from: now)
+ let cached = (try? readCache()) ?? Cache(lastCheckedUnix: nil, latestVersion: nil)
+ let cacheFresh =
+ cached.lastCheckedUnix
+ .map { now.timeIntervalSince1970 - $0 < cacheRefreshSeconds } ?? false
+ let useCache = !noCache && cacheFresh && cached.latestVersion != nil
+
+ let latest: String?
+ let cacheHit: Bool
+ let fetchError: String?
+
+ if useCache {
+ latest = cached.latestVersion
+ cacheHit = true
+ fetchError = nil
+ } else {
+ do {
+ let fetched = try await fetchLatestVersion()
+ latest = fetched
+ cacheHit = false
+ fetchError = nil
+ try? writeCache(Cache(lastCheckedUnix: now.timeIntervalSince1970, latestVersion: fetched))
+ } catch {
+ if let cachedLatest = cached.latestVersion {
+ latest = cachedLatest
+ cacheHit = true
+ fetchError = nil
+ } else {
+ latest = nil
+ cacheHit = false
+ fetchError = error.localizedDescription
+ }
+ }
+ }
+
+ let updateAvailable = latest.map { isNewer($0, than: current) } ?? false
+ let releaseNotesURL =
+ updateAvailable
+ ? "https://github.com/trycua/cua/releases/tag/\(releaseTagPrefix)\(latest ?? "")"
+ : nil
+
+ return State(
+ currentVersion: current,
+ latestVersion: latest,
+ updateAvailable: updateAvailable,
+ source: "github_releases",
+ checkedAt: checkedAt,
+ cacheHit: cacheHit,
+ installCommand: updateAvailable ? manualInstallCommand(version: latest) : nil,
+ releaseNotesURL: releaseNotesURL,
+ error: fetchError
+ )
+ }
+
+ static func updateChecksEnabled() -> Bool {
+ guard let value = ProcessInfo.processInfo.environment[updateCheckEnv]?.lowercased() else {
+ return true
+ }
+ return !["0", "false", "no", "off"].contains(value)
+ }
+
+ static func disabledState() -> State {
+ State(
+ currentVersion: Lume.Version.current,
+ latestVersion: nil,
+ updateAvailable: false,
+ source: "github_releases",
+ checkedAt: ISO8601DateFormatter().string(from: Date()),
+ cacheHit: false,
+ installCommand: nil,
+ releaseNotesURL: nil,
+ error: "Update checks disabled by LUME_UPDATE_CHECK"
+ )
+ }
+
+ static func manualInstallCommand() -> String {
+ "curl -fsSL \(installScriptURL()) | bash"
+ }
+
+ static func manualInstallCommand(version: String?) -> String {
+ guard let version else {
+ return manualInstallCommand()
+ }
+ return "curl -fsSL \(installScriptURL()) | LUME_VERSION=\(version) bash"
+ }
+
+ static func installScriptURL() -> String {
+ ProcessInfo.processInfo.environment[installScriptURLEnv] ?? defaultInstallScriptURL
+ }
+
+ static func runInstallScript(version: String) throws -> Int32 {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/bin/bash")
+ process.arguments = ["-c", manualInstallCommand()]
+
+ var environment = ProcessInfo.processInfo.environment
+ environment["LUME_VERSION"] = version
+ process.environment = environment
+
+ try process.run()
+ process.waitUntilExit()
+ return process.terminationStatus
+ }
+
+ static func isNewer(_ lhs: String, than rhs: String) -> Bool {
+ compare(lhs, rhs) == .orderedDescending
+ }
+
+ static func compare(_ lhs: String, _ rhs: String) -> ComparisonResult {
+ let left = parseVersion(lhs)
+ let right = parseVersion(rhs)
+ for index in 0..<max(left.count, right.count) {
+ let l = index < left.count ? left[index] : 0
+ let r = index < right.count ? right[index] : 0
+ if l < r { return .orderedAscending }
+ if l > r { return .orderedDescending }
+ }
+ return .orderedSame
+ }
+
+ private static func fetchLatestVersion() async throws -> String {
+ var versions: [String] = []
+
+ for page in 1...5 {
+ var components = URLComponents(url: releasesURL, resolvingAgainstBaseURL: false)!
+ components.queryItems = [
+ URLQueryItem(name: "per_page", value: "100"),
+ URLQueryItem(name: "page", value: String(page)),
+ ]
+
+ guard let url = components.url else {
+ throw VersionCheckError.invalidResponse
+ }
+
+ var request = URLRequest(url: url)
+ request.timeoutInterval = 4
+ request.setValue("application/vnd.github+json", forHTTPHeaderField: "Accept")
+ request.setValue("lume/\(Lume.Version.current)", forHTTPHeaderField: "User-Agent")
+
+ let (data, response) = try await URLSession.shared.data(for: request)
+ if let http = response as? HTTPURLResponse, !(200..<300).contains(http.statusCode) {
+ throw VersionCheckError.httpStatus(http.statusCode)
+ }
+
+ guard let releases = try JSONSerialization.jsonObject(with: data) as? [[String: Any]] else {
+ throw VersionCheckError.invalidResponse
+ }
+
+ versions.append(
+ contentsOf: releases
+ .compactMap { $0["tag_name"] as? String }
+ .filter { $0.hasPrefix(releaseTagPrefix) }
+ .map { String($0.dropFirst(releaseTagPrefix.count)) }
+ .filter { isPlainSemver($0) }
+ )
+
+ if releases.count < 100 {
+ break
+ }
+ }
+
+ let sortedVersions = versions.sorted { compare($0, $1) == .orderedDescending }
+
+ guard let latest = sortedVersions.first else {
+ throw VersionCheckError.noLumeRelease
+ }
+ return latest
+ }
+
+ private static func parseVersion(_ version: String) -> [Int] {
+ version
+ .split(separator: "-", maxSplits: 1, omittingEmptySubsequences: true)
+ .first?
+ .split(separator: ".")
+ .map { Int($0) ?? 0 } ?? []
+ }
+
+ private static func isPlainSemver(_ version: String) -> Bool {
+ let parts = version.split(separator: ".")
+ guard parts.count == 3 else { return false }
+ return parts.allSatisfy { Int($0) != nil }
+ }
+
+ private static func cacheFileURL() -> URL {
+ let env = ProcessInfo.processInfo.environment
+ let cacheRoot =
+ env["XDG_CACHE_HOME"]
+ ?? "\(FileManager.default.homeDirectoryForCurrentUser.path)/.cache"
+ return URL(fileURLWithPath: cacheRoot).appendingPathComponent("lume/version_check.json")
+ }
+
+ private static func readCache() throws -> Cache {
+ let url = cacheFileURL()
+ let data = try Data(contentsOf: url)
+ return try JSONDecoder().decode(Cache.self, from: data)
+ }
+
+ private static func writeCache(_ cache: Cache) throws {
+ let url = cacheFileURL()
+ try FileManager.default.createDirectory(
+ at: url.deletingLastPathComponent(),
+ withIntermediateDirectories: true
+ )
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
+ let data = try encoder.encode(cache)
+ try data.write(to: url, options: .atomic)
+ }
+}
+
+enum VersionCheckError: Error, CustomStringConvertible, LocalizedError {
+ case httpStatus(Int)
+ case invalidResponse
+ case noLumeRelease
+
+ var description: String {
+ switch self {
+ case .httpStatus(let status):
+ return "GitHub releases request failed with HTTP \(status)"
+ case .invalidResponse:
+ return "GitHub releases response was not valid JSON"
+ case .noLumeRelease:
+ return "No lume-v* release was found"
+ }
+ }
+
+ var errorDescription: String? {
+ description
+ }
+}
diff --git a/libs/lume/src/Utils/CommandDocExtractor.swift b/libs/lume/src/Utils/CommandDocExtractor.swift
index f0e52a56ec..1a70de41cc 100644
--- a/libs/lume/src/Utils/CommandDocExtractor.swift
+++ b/libs/lume/src/Utils/CommandDocExtractor.swift
@@ -87,6 +87,8 @@ enum CommandDocExtractor {
pruneDoc,
configDoc,
logsDoc,
+ checkUpdateDoc,
+ updateDoc,
setupDoc,
]
}
@@ -521,6 +523,38 @@ enum CommandDocExtractor {
)
}
+ // MARK: - Update
+
+ private static var checkUpdateDoc: CommandDoc {
+ CommandDoc(
+ name: "check-update",
+ abstract: "Check whether a newer Lume release is available",
+ discussion: "Read-only update check. Uses GitHub Releases, caches the result briefly, and never installs anything.",
+ arguments: [],
+ options: [],
+ flags: [
+ FlagDoc(name: "json", shortName: nil, help: "Emit the structured update-state payload as JSON", defaultValue: false),
+ FlagDoc(name: "no-cache", shortName: nil, help: "Bypass the local update-check cache", defaultValue: false),
+ ],
+ subcommands: []
+ )
+ }
+
+ private static var updateDoc: CommandDoc {
+ CommandDoc(
+ name: "update",
+ abstract: "Check for a Lume update and optionally apply it",
+ discussion: "Without --apply, this command only checks for a newer release and prints the command to install it. With --apply, it delegates installation to the canonical Lume installer pinned to the discovered version.",
+ arguments: [],
+ options: [],
+ flags: [
+ FlagDoc(name: "apply", shortName: nil, help: "Apply the update by re-running the official installer", defaultValue: false),
+ FlagDoc(name: "json", shortName: nil, help: "Emit the structured update-state payload as JSON", defaultValue: false),
+ ],
+ subcommands: []
+ )
+ }
+
// MARK: - Setup
private static var setupDoc: CommandDoc {
diff --git a/libs/lume/src/Utils/CommandRegistry.swift b/libs/lume/src/Utils/CommandRegistry.swift
index cd4ee0d885..4752567640 100644
--- a/libs/lume/src/Utils/CommandRegistry.swift
+++ b/libs/lume/src/Utils/CommandRegistry.swift
@@ -21,6 +21,8 @@ enum CommandRegistry {
Prune.self,
Config.self,
Logs.self,
+ CheckUpdate.self,
+ Update.self,
Setup.self,
DumpDocs.self,
]
diff --git a/libs/lume/tests/VersionCheckTests.swift b/libs/lume/tests/VersionCheckTests.swift
new file mode 100644
index 0000000000..8bcb03d4c2
--- /dev/null
+++ b/libs/lume/tests/VersionCheckTests.swift
@@ -0,0 +1,22 @@
+import XCTest
+@testable import lume
+
+final class VersionCheckTests: XCTestCase {
+ func testSemanticVersionComparison() {
+ XCTAssertTrue(LumeVersionCheck.isNewer("0.3.11", than: "0.3.10"))
+ XCTAssertTrue(LumeVersionCheck.isNewer("0.4.0", than: "0.3.99"))
+ XCTAssertFalse(LumeVersionCheck.isNewer("0.3.10", than: "0.3.10"))
+ XCTAssertFalse(LumeVersionCheck.isNewer("0.3.9", than: "0.3.10"))
+ }
+
+ func testInstallScriptURLOverride() {
+ setenv("LUME_INSTALL_SCRIPT_URL", "file:///tmp/lume-install.sh", 1)
+ defer { unsetenv("LUME_INSTALL_SCRIPT_URL") }
+
+ XCTAssertEqual(LumeVersionCheck.installScriptURL(), "file:///tmp/lume-install.sh")
+ XCTAssertEqual(
+ LumeVersionCheck.manualInstallCommand(version: "0.3.10"),
+ "curl -fsSL file:///tmp/lume-install.sh | LUME_VERSION=0.3.10 bash"
+ )
+ }
+}
diff --git a/scripts/docs-generators/config.json b/scripts/docs-generators/config.json
index 2a009ccd31..66cd332f79 100644
--- a/scripts/docs-generators/config.json
+++ b/scripts/docs-generators/config.json
@@ -35,7 +35,7 @@
"name": "Lume VM Manager",
"language": "swift",
"sourcePath": "libs/lume/src",
- "docsOutputPath": "docs/content/docs/lume/reference",
+ "docsOutputPath": "docs/content/docs/reference/lume",
"generatorScript": "scripts/docs-generators/lume.ts",
"watchPaths": [
"libs/lume/src/Commands/**/*.swift",
@@ -49,7 +49,7 @@
"outputs": [
{
"type": "cli",
- "outputFile": "cli-reference.mdx",
+ "outputFile": "cli.mdx",
"extractCommand": ".build/release/lume dump-docs --type cli"
},
{
diff --git a/scripts/docs-generators/generate-changelog.ts b/scripts/docs-generators/generate-changelog.ts
index 14b32c6cc6..cfebbb5b76 100644
--- a/scripts/docs-generators/generate-changelog.ts
+++ b/scripts/docs-generators/generate-changelog.ts
@@ -68,7 +68,7 @@ const SDK_CONFIGS: SDKConfig[] = [
name: 'lume',
displayName: 'Lume',
tagPrefix: 'lume-v',
- outputPath: 'lume/reference/changelog.mdx',
+ outputPath: 'reference/lume/changelog.mdx',
},
{
name: 'cuabot',
diff --git a/scripts/docs-generators/generate-versioned-docs.ts b/scripts/docs-generators/generate-versioned-docs.ts
index 53cd2cf52e..60fc1d0374 100644
--- a/scripts/docs-generators/generate-versioned-docs.ts
+++ b/scripts/docs-generators/generate-versioned-docs.ts
@@ -86,10 +86,10 @@ const SDK_CONFIGS: SDKConfig[] = [
tagPrefix: 'lume-v',
packageDir: 'libs/lume',
packageName: 'lume',
- outputDir: 'lume/reference',
+ outputDir: 'reference/lume',
extractionType: 'swift-dump-docs',
minVersion: '0.2',
- docsBasePath: 'lume/reference',
+ docsBasePath: 'reference/lume',
},
{
name: 'cuabot',
@@ -163,7 +163,7 @@ async function main() {
await generateVersionDocs(config, latestVersion, majorMinor);
const files =
config.extractionType === 'swift-dump-docs'
- ? 'cli-reference.mdx + http-api.mdx'
+ ? 'cli.mdx + http-api.mdx'
: 'api.mdx';
console.log(` ✅ Generated v${majorMinor}/${files}`);
} catch (error) {
@@ -399,7 +399,7 @@ async function generateSwiftVersionDocs(
}
// Write outputs
- fs.writeFileSync(path.join(outputDir, 'cli-reference.mdx'), cliMdx);
+ fs.writeFileSync(path.join(outputDir, 'cli.mdx'), cliMdx);
fs.writeFileSync(path.join(outputDir, 'http-api.mdx'), apiMdx);
// Create meta.json
@@ -409,7 +409,7 @@ async function generateSwiftVersionDocs(
{
title: `v${majorMinor}`,
description: `${config.displayName} v${majorMinor} Reference`,
- pages: ['cli-reference', 'http-api'],
+ pages: ['cli', 'http-api'],
},
null,
2
@@ -525,7 +525,7 @@ function generateVersionedLumeMDX(
// Insert old-version callout instead
result.push('<Callout type="warn">');
result.push(
- ` This is documentation for **v${majorMinor}**. [View latest version](/lume/reference/cli-reference).`
+ ` This is documentation for **v${majorMinor}**. [View latest version](/reference/lume/cli).`
);
result.push('</Callout>');
result.push('');
diff --git a/scripts/docs-generators/lume.ts b/scripts/docs-generators/lume.ts
index ddddf5b0f5..109baa5888 100644
--- a/scripts/docs-generators/lume.ts
+++ b/scripts/docs-generators/lume.ts
@@ -116,7 +116,7 @@ export interface APIStatusCodeDoc {
const ROOT_DIR = path.resolve(__dirname, '../..');
const LUME_DIR = path.join(ROOT_DIR, 'libs', 'lume');
-const DOCS_OUTPUT_DIR = path.join(ROOT_DIR, 'docs', 'content', 'docs', 'lume', 'reference');
+const DOCS_OUTPUT_DIR = path.join(ROOT_DIR, 'docs', 'content', 'docs', 'reference', 'lume');
const TAG_PREFIX = 'lume-v';
// ============================================================================
@@ -157,7 +157,7 @@ export function discoverVersions(currentVersion: string): VersionInfo[] {
// Add current version (latest)
versions.push({
version: currentMajorMinor,
- href: '/lume/reference/cli-reference',
+ href: '/reference/lume/cli',
isCurrent: true,
});
@@ -170,7 +170,7 @@ export function discoverVersions(currentVersion: string): VersionInfo[] {
if (version === currentMajorMinor) continue;
versions.push({
version,
- href: `/lume/reference/${entry.name}/cli-reference`,
+ href: `/reference/lume/${entry.name}/cli`,
isCurrent: false,
});
}
@@ -239,7 +239,7 @@ async function main() {
const cliMdx = generateCLIReferenceMDX(cliDocs);
const apiMdx = generateHTTPAPIMDX(apiDocs);
- const cliPath = path.join(DOCS_OUTPUT_DIR, 'cli-reference.mdx');
+ const cliPath = path.join(DOCS_OUTPUT_DIR, 'cli.mdx');
const apiPath = path.join(DOCS_OUTPUT_DIR, 'http-api.mdx');
if (checkOnly) {
@@ -251,13 +251,13 @@ async function main() {
if (fs.existsSync(cliPath)) {
const existingCli = fs.readFileSync(cliPath, 'utf-8');
if (existingCli !== cliMdx) {
- console.error('❌ cli-reference.mdx is out of sync with source code');
+ console.error('❌ cli.mdx is out of sync with source code');
hasDrift = true;
} else {
- console.log('✅ cli-reference.mdx is up to date');
+ console.log('✅ cli.mdx is up to date');
}
} else {
- console.error('❌ cli-reference.mdx does not exist');
+ console.error('❌ cli.mdx does not exist');
hasDrift = true;
}
@@ -351,7 +351,7 @@ export function generateCLIReferenceMDX(docs: CLIDocumentation): string {
const vmManagement = ['create', 'run', 'stop', 'delete', 'clone'];
const vmInfo = ['ls', 'get', 'set'];
const imageManagement = ['images', 'pull', 'push', 'ipsw', 'prune'];
- const configuration = ['config', 'serve', 'logs', 'setup'];
+ const configuration = ['config', 'serve', 'logs', 'setup', 'check-update', 'update'];
lines.push('## VM Management');
lines.push('');