🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(cli): add `lh update` command to self-upgrade the CLI (#16052)
Arvin Xu248740719211
diff --git a/apps/cli/package.json b/apps/cli/package.jsonindex e6cb019ab76..9b45564d629 100644--- a/apps/cli/package.json+++ b/apps/cli/package.json@@ -37,6 +37,7 @@"@lobechat/tool-runtime": "workspace:*","@trpc/client": "^11.8.1","@types/node": "^24.13.2",+ "@types/semver": "^7.7.1","@types/ws": "^8.18.1","commander": "^13.1.0","dayjs": "^1.11.19",@@ -45,6 +46,7 @@"fast-glob": "^3.3.3","ignore": "^7.0.5","picocolors": "^1.1.1",+ "semver": "^7.7.3","superjson": "^2.2.6","tsdown": "^0.21.4","typescript": "^6.0.3",diff --git a/apps/cli/src/commands/update.test.ts b/apps/cli/src/commands/update.test.tsnew file mode 100644index 00000000000..6e9a4824456--- /dev/null+++ b/apps/cli/src/commands/update.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from 'vitest';++import { buildInstallCommand, isNewerVersion } from './update';++describe('isNewerVersion', () => {+ it('compares core versions', () => {+ expect(isNewerVersion('1.2.3', '1.2.2')).toBe(true);+ expect(isNewerVersion('1.2.2', '1.2.3')).toBe(false);+ expect(isNewerVersion('1.2.3', '1.2.3')).toBe(false);+ expect(isNewerVersion('2.0.0', '1.9.9')).toBe(true);+ });++ it('tolerates a leading v and missing segments', () => {+ expect(isNewerVersion('v1.2.0', '1.2.0')).toBe(false);+ expect(isNewerVersion('1.2', '1.2.0')).toBe(false);+ expect(isNewerVersion('1.3', '1.2.9')).toBe(true);+ });++ it('ranks a stable release above a prerelease of the same core', () => {+ expect(isNewerVersion('1.2.3', '1.2.3-beta.1')).toBe(true);+ expect(isNewerVersion('1.2.3-beta.1', '1.2.3')).toBe(false);+ expect(isNewerVersion('1.2.3-beta.2', '1.2.3-beta.1')).toBe(true);+ expect(isNewerVersion('1.2.3-beta.1', '1.2.3-beta.1')).toBe(false);+ });++ it('orders numeric prerelease identifiers numerically, not lexicographically', () => {+ // The bug a raw string compare gets wrong: beta.10 must outrank beta.9.+ expect(isNewerVersion('1.0.0-beta.10', '1.0.0-beta.9')).toBe(true);+ expect(isNewerVersion('1.0.0-beta.9', '1.0.0-beta.10')).toBe(false);+ expect(isNewerVersion('1.0.0-beta.2', '1.0.0-beta.10')).toBe(false);+ });++ it('returns false for an unparseable latest version', () => {+ expect(isNewerVersion('not-a-version', '1.0.0')).toBe(false);+ });+});++describe('buildInstallCommand', () => {+ it('builds the global install command per package manager', () => {+ expect(buildInstallCommand('npm', '@lobehub/[email protected]')).toEqual({+ args: ['install', '-g', '@lobehub/[email protected]'],+ command: 'npm',+ });+ expect(buildInstallCommand('pnpm', '@lobehub/[email protected]')).toEqual({+ args: ['add', '-g', '@lobehub/[email protected]'],+ command: 'pnpm',+ });+ expect(buildInstallCommand('bun', '@lobehub/[email protected]')).toEqual({+ args: ['add', '-g', '@lobehub/[email protected]'],+ command: 'bun',+ });+ expect(buildInstallCommand('yarn', '@lobehub/[email protected]')).toEqual({+ args: ['global', 'add', '@lobehub/[email protected]'],+ command: 'yarn',+ });+ });+});diff --git a/apps/cli/src/commands/update.ts b/apps/cli/src/commands/update.tsnew file mode 100644index 00000000000..a00efd0c8cf--- /dev/null+++ b/apps/cli/src/commands/update.ts@@ -0,0 +1,179 @@+import { spawn } from 'node:child_process';+import { realpathSync } from 'node:fs';++import type { Command } from 'commander';+import pc from 'picocolors';+import semver from 'semver';++// Pull package metadata from the shared `src/pkg.ts` module (resolved at the+// bundled entry's depth) rather than a local `require('../../package.json')`,+// which would point outside the package once bundled into dist/index.js.+import { cliPackageName, cliVersion } from '../pkg';+import { log } from '../utils/logger';++export type PackageManager = 'npm' | 'pnpm' | 'yarn' | 'bun';++const PACKAGE_MANAGERS: PackageManager[] = ['npm', 'pnpm', 'yarn', 'bun'];++interface UpdateOptions {+ check?: boolean;+ packageManager?: PackageManager;+ tag?: string;+}++/**+ * Detect which package manager installed the CLI so we run the matching global+ * upgrade command. We first trust an explicit `npm_config_user_agent` (set when+ * invoked through a package-manager script) and otherwise infer from the path of+ * the running binary. Falls back to npm.+ */+export function detectPackageManager(): PackageManager {+ const ua = process.env.npm_config_user_agent;+ if (ua) {+ if (ua.startsWith('pnpm')) return 'pnpm';+ if (ua.startsWith('yarn')) return 'yarn';+ if (ua.startsWith('bun')) return 'bun';+ if (ua.startsWith('npm')) return 'npm';+ }++ try {+ const binPath = realpathSync(process.argv[1] ?? '').replaceAll('\\', '/');+ if (binPath.includes('/pnpm/')) return 'pnpm';+ if (binPath.includes('/.bun/') || binPath.includes('/bun/')) return 'bun';+ if (binPath.includes('/yarn/') || binPath.includes('/.yarn/')) return 'yarn';+ } catch {+ // ignore – fall back to npm+ }++ return 'npm';+}++/** Build the global-install command for the detected package manager. */+export function buildInstallCommand(+ pm: PackageManager,+ spec: string,+): { args: string[]; command: string } {+ switch (pm) {+ case 'pnpm': {+ return { args: ['add', '-g', spec], command: 'pnpm' };+ }+ case 'yarn': {+ return { args: ['global', 'add', spec], command: 'yarn' };+ }+ case 'bun': {+ return { args: ['add', '-g', spec], command: 'bun' };+ }+ default: {+ return { args: ['install', '-g', spec], command: 'npm' };+ }+ }+}++/**+ * Whether `latest` is a newer version than `current`. Delegates to `semver` so+ * prerelease identifiers order correctly (e.g. `1.0.0-beta.10` > `1.0.0-beta.9`,+ * which a lexicographic compare gets wrong). Tolerates a leading `v` and missing+ * segments via coercion; an unparseable `latest` is treated as "not newer".+ */+export function isNewerVersion(latest: string, current: string): boolean {+ const latestParsed = semver.coerce(latest, { includePrerelease: true }) ?? semver.parse(latest);+ const currentParsed =+ semver.coerce(current, { includePrerelease: true }) ?? semver.parse(current);+ if (!latestParsed || !currentParsed) return false;+ return semver.gt(latestParsed, currentParsed);+}++async function fetchLatestVersion(name: string, tag: string): Promise<string> {+ const url = `https://registry.npmjs.org/${name}/${encodeURIComponent(tag)}`;+ const res = await fetch(url, { headers: { accept: 'application/json' } });++ if (!res.ok) {+ throw new Error(`npm registry returned status ${res.status} for tag "${tag}"`);+ }++ const data = (await res.json()) as { version?: string };+ if (!data.version) {+ throw new Error('npm registry response is missing the "version" field');+ }++ return data.version;+}++function runInstall(command: string, args: string[]): Promise<void> {+ return new Promise((resolve, reject) => {+ const child = spawn(command, args, {+ shell: process.platform === 'win32',+ stdio: 'inherit',+ });++ child.on('error', reject);+ child.on('close', (code) => {+ if (code === 0) resolve();+ else reject(new Error(`${command} exited with code ${code ?? 'null'}`));+ });+ });+}++export function registerUpdateCommand(program: Command) {+ program+ .command('update')+ .description('Update the LobeHub CLI to the latest published version')+ .option('--check', 'Only check for a newer version without installing')+ .option('--tag <tag>', 'npm dist-tag to update to', 'latest')+ .option(+ '--package-manager <pm>',+ `Force a package manager (${PACKAGE_MANAGERS.join(', ')}) instead of auto-detecting`,+ )+ .action(async (options: UpdateOptions) => {+ if (options.packageManager && !PACKAGE_MANAGERS.includes(options.packageManager)) {+ log.error(+ `Unsupported package manager "${options.packageManager}". Use one of: ${PACKAGE_MANAGERS.join(', ')}.`,+ );+ process.exit(1);+ return;+ }++ const current = cliVersion;+ const tag = options.tag || 'latest';++ log.info(`Current version: ${pc.bold(current)}`);++ let latest: string;+ try {+ latest = await fetchLatestVersion(cliPackageName, tag);+ } catch (error) {+ log.error(`Unable to check for updates: ${(error as Error).message}`);+ process.exit(1);+ return;+ }++ log.info(`Latest version: ${pc.bold(latest)} ${pc.dim(`(${tag})`)}`);++ if (!isNewerVersion(latest, current)) {+ log.info(pc.green('Already on the latest version.'));+ return;+ }++ if (options.check) {+ log.info(+ `Update available: ${current} → ${pc.green(latest)}. Run ${pc.cyan('lh update')} to upgrade.`,+ );+ return;+ }++ const pm = options.packageManager || detectPackageManager();+ const spec = `${cliPackageName}@${latest}`;+ const { args, command } = buildInstallCommand(pm, spec);++ log.info(`Upgrading via ${pc.bold(pm)}: ${pc.dim([command, ...args].join(' '))}`);++ try {+ await runInstall(command, args);+ log.info(pc.green(`Successfully updated to ${latest}. Restart any running sessions.`));+ } catch (error) {+ log.error(`Update failed: ${(error as Error).message}`);+ log.error(`You can upgrade manually: ${[command, ...args].join(' ')}`);+ process.exit(1);+ }+ });+}diff --git a/apps/cli/src/pkg.ts b/apps/cli/src/pkg.tsnew file mode 100644index 00000000000..903e5c54d4d--- /dev/null+++ b/apps/cli/src/pkg.ts@@ -0,0 +1,16 @@+import { createRequire } from 'node:module';++/**+ * Single source of truth for this package's own metadata.+ *+ * Must live directly under `src/` (depth 1), the same depth as the bundled+ * entry `dist/index.js`, so `../package.json` resolves to `@lobehub/cli`'s own+ * package.json both when running from source (`bun src/index.ts`) and from the+ * tsdown bundle (`dist/index.js`). A module one directory deeper would resolve+ * the path outside the package once everything is bundled into a single file.+ */+const require = createRequire(import.meta.url);+const pkg = require('../package.json') as { name: string; version: string };++export const cliPackageName = pkg.name;+export const cliVersion = pkg.version;diff --git a/apps/cli/src/program.ts b/apps/cli/src/program.tsindex 0814b12ce48..026b543912f 100644--- a/apps/cli/src/program.ts+++ b/apps/cli/src/program.ts@@ -1,5 +1,3 @@-import { createRequire } from 'node:module';-import { Command } from 'commander';import { registerAgentCommand } from './commands/agent';@@ -33,11 +31,10 @@ import { registerStatusCommand } from './commands/status';import { registerTaskCommand } from './commands/task';import { registerThreadCommand } from './commands/thread';import { registerTopicCommand } from './commands/topic';+import { registerUpdateCommand } from './commands/update';import { registerUserCommand } from './commands/user';import { registerVerifyCommand } from './commands/verify';--const require = createRequire(import.meta.url);-const { version } = require('../package.json');+import { cliVersion } from './pkg';export function createProgram() {const program = new Command();@@ -45,7 +42,7 @@ export function createProgram() {program.name('lh').description('LobeHub CLI - manage and connect to LobeHub services')- .version(version);+ .version(cliVersion);registerLoginCommand(program);registerLogoutCommand(program);@@ -80,8 +77,9 @@ export function createProgram() {registerConfigCommand(program);registerEvalCommand(program);registerMigrateCommand(program);+ registerUpdateCommand(program);return program;}-export { version as cliVersion };+export { cliPackageName, cliVersion } from './pkg';