Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(cli): auto-install or update @alook/cli on register

Gener72590d934826
diff --git a/src/cli/commands/register.ts b/src/cli/commands/register.ts
index e6623e066..1cbb9fa5f 100644
--- a/src/cli/commands/register.ts
+++ b/src/cli/commands/register.ts
@@ -4,6 +4,7 @@ import { hostname } from "os";
import { APIClient } from "../lib/client.js";
import { loadCLIConfigForProfile, saveCLIConfigForProfile } from "../lib/config.js";
import { cmdPrefix } from "../lib/env.js";
+import { ensureInstalled } from "../lib/installer.js";
interface MeResponse {
id: string;
@@ -55,6 +56,7 @@ export function registerCommand(): Command {
.requiredOption("--token <token>", "API token (starts with al_)")
.option("--server <url>", "Server URL")
.option("--profile <name>", "Profile name")
+ .option("--no-install", "Skip auto-install/update of @alook/cli")
.action(async (opts, command) => {
const token: string = opts.token;
const profile: string | undefined =
@@ -173,6 +175,9 @@ export function registerCommand(): Command {
console.log(`\nRegistered as ${me.email}`);
console.log(`Workspace: ${ws.name} (${ws.id})`);
console.log(`Runtimes: ${activateResp.runtimes.map((r) => r.provider).join(", ")}`);
+
+ await ensureInstalled({ skip: opts.install === false });
+
console.log();
console.log(
`Run '${cmdPrefix()} daemon start --foreground' to start the daemon.`,
diff --git a/src/cli/commands/version.ts b/src/cli/commands/version.ts
index 07aed820e..e16b3ac94 100644
--- a/src/cli/commands/version.ts
+++ b/src/cli/commands/version.ts
@@ -1,28 +1,11 @@
import { Command } from "commander";
-import { readFileSync } from "fs";
-import { join, dirname } from "path";
-import { fileURLToPath } from "url";
+import { getCurrentVersion } from "../lib/version.js";
export function versionCommand(): Command {
const cmd = new Command("version")
.description("Show CLI version")
.action(() => {
- const __dirname = dirname(fileURLToPath(import.meta.url));
- let version = "unknown";
- try {
- const pkgPath = join(__dirname, "..", "package.json");
- const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
- version = pkg.version;
- } catch {
- try {
- const pkgPath = join(__dirname, "..", "..", "package.json");
- const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
- version = pkg.version;
- } catch {
- // fallback
- }
- }
- console.log(`alook version ${version}`);
+ console.log(`alook version ${getCurrentVersion()}`);
});
return cmd;
diff --git a/src/cli/lib/installer.test.ts b/src/cli/lib/installer.test.ts
new file mode 100644
index 000000000..1161b88ab
--- /dev/null
+++ b/src/cli/lib/installer.test.ts
@@ -0,0 +1,241 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
+import {
+ isNewer,
+ isNpx,
+ detectPackageManager,
+ installArgs,
+ installCmdString,
+ ensureInstalled,
+ type PackageManager,
+} from "./installer.js";
+
+const ENV_KEYS = [
+ "npm_command",
+ "npm_execpath",
+ "npm_config_user_agent",
+ "ALOOK_SERVER_URL",
+];
+const originalEnv: Record<string, string | undefined> = {};
+for (const key of ENV_KEYS) originalEnv[key] = process.env[key];
+
+function resetEnv() {
+ for (const key of ENV_KEYS) {
+ if (originalEnv[key] === undefined) delete process.env[key];
+ else process.env[key] = originalEnv[key];
+ }
+}
+
+beforeEach(() => {
+ for (const key of ENV_KEYS) delete process.env[key];
+});
+
+afterEach(() => {
+ resetEnv();
+});
+
+describe("isNewer", () => {
+ it("compares major.minor.patch", () => {
+ expect(isNewer("0.0.1", "0.0.2")).toBe(true);
+ expect(isNewer("0.0.2", "0.0.1")).toBe(false);
+ expect(isNewer("0.0.1", "0.0.1")).toBe(false);
+ expect(isNewer("0.0.9", "0.1.0")).toBe(true);
+ expect(isNewer("0.1.0", "0.0.9")).toBe(false);
+ expect(isNewer("0.9.9", "1.0.0")).toBe(true);
+ });
+
+ it("strips prerelease suffixes before comparing", () => {
+ expect(isNewer("0.0.1", "0.0.2-beta.1")).toBe(true);
+ expect(isNewer("0.0.2-beta.1", "0.0.2")).toBe(false);
+ });
+});
+
+describe("isNpx", () => {
+ it("returns false when neither env var is set", () => {
+ expect(isNpx()).toBe(false);
+ });
+
+ it("returns true when npm_command is 'exec'", () => {
+ process.env.npm_command = "exec";
+ expect(isNpx()).toBe(true);
+ });
+
+ it("returns true when npm_execpath points at npx-cli", () => {
+ process.env.npm_execpath =
+ "/usr/local/lib/node_modules/npm/bin/npx-cli.js";
+ expect(isNpx()).toBe(true);
+ });
+});
+
+describe("detectPackageManager", () => {
+ it("defaults to npm", () => {
+ expect(detectPackageManager()).toBe("npm");
+ });
+
+ it("detects pnpm from user agent", () => {
+ process.env.npm_config_user_agent = "pnpm/8.0.0 npm/? node/v20";
+ expect(detectPackageManager()).toBe("pnpm");
+ });
+
+ it("detects yarn from user agent", () => {
+ process.env.npm_config_user_agent = "yarn/3.0.0 npm/? node/v20";
+ expect(detectPackageManager()).toBe("yarn");
+ });
+});
+
+describe("installArgs", () => {
+ it("returns npm install args", () => {
+ expect(installArgs("npm")).toEqual([
+ "npm",
+ ["install", "-g", "@alook/cli@latest"],
+ ]);
+ });
+ it("returns pnpm add args", () => {
+ expect(installArgs("pnpm")).toEqual(["pnpm", ["add", "-g", "@alook/cli"]]);
+ });
+ it("returns yarn global add args", () => {
+ expect(installArgs("yarn")).toEqual([
+ "yarn",
+ ["global", "add", "@alook/cli"],
+ ]);
+ });
+});
+
+describe("installCmdString", () => {
+ it("formats the command for display", () => {
+ expect(installCmdString("npm")).toBe("npm install -g @alook/cli@latest");
+ expect(installCmdString("pnpm")).toBe("pnpm add -g @alook/cli");
+ expect(installCmdString("yarn")).toBe("yarn global add @alook/cli");
+ });
+});
+
+describe("ensureInstalled", () => {
+ const logs: string[] = [];
+ const log = (m: string) => {
+ logs.push(m);
+ };
+
+ beforeEach(() => {
+ logs.length = 0;
+ });
+
+ it("skips in dev mode", async () => {
+ const result = await ensureInstalled(
+ {},
+ {
+ isDevFn: () => true,
+ fetchLatest: vi.fn(async () => "0.0.2"),
+ runInstall: vi.fn(() => true),
+ getCurrent: () => "0.0.1",
+ isNpxFn: () => false,
+ log,
+ },
+ );
+ expect(result.skipped).toBe(true);
+ expect(result.action).toBe("none");
+ });
+
+ it("skips when opts.skip is true", async () => {
+ const result = await ensureInstalled(
+ { skip: true },
+ {
+ isDevFn: () => false,
+ fetchLatest: vi.fn(async () => "0.0.2"),
+ runInstall: vi.fn(() => true),
+ getCurrent: () => "0.0.1",
+ isNpxFn: () => false,
+ log,
+ },
+ );
+ expect(result.skipped).toBe(true);
+ });
+
+ it("returns action=none when registry fetch fails", async () => {
+ const run = vi.fn(() => true);
+ const result = await ensureInstalled(
+ {},
+ {
+ isDevFn: () => false,
+ fetchLatest: async () => null,
+ runInstall: run,
+ getCurrent: () => "0.0.1",
+ isNpxFn: () => true,
+ log,
+ },
+ );
+ expect(result.action).toBe("none");
+ expect(result.latest).toBeNull();
+ expect(run).not.toHaveBeenCalled();
+ });
+
+ it("installs when running via npx", async () => {
+ const run = vi.fn((_: PackageManager) => true);
+ const result = await ensureInstalled(
+ {},
+ {
+ isDevFn: () => false,
+ fetchLatest: async () => "0.0.2",
+ runInstall: run,
+ getCurrent: () => "0.0.1",
+ isNpxFn: () => true,
+ log,
+ },
+ );
+ expect(result.action).toBe("installed");
+ expect(run).toHaveBeenCalledOnce();
+ expect(logs.some((l) => l.includes("Installing"))).toBe(true);
+ });
+
+ it("updates when globally installed but outdated", async () => {
+ const run = vi.fn(() => true);
+ const result = await ensureInstalled(
+ {},
+ {
+ isDevFn: () => false,
+ fetchLatest: async () => "0.0.2",
+ runInstall: run,
+ getCurrent: () => "0.0.1",
+ isNpxFn: () => false,
+ log,
+ },
+ );
+ expect(result.action).toBe("updated");
+ expect(run).toHaveBeenCalledOnce();
+ expect(logs.some((l) => l.includes("Updating"))).toBe(true);
+ });
+
+ it("does nothing when globally installed and up to date", async () => {
+ const run = vi.fn(() => true);
+ const result = await ensureInstalled(
+ {},
+ {
+ isDevFn: () => false,
+ fetchLatest: async () => "0.0.2",
+ runInstall: run,
+ getCurrent: () => "0.0.2",
+ isNpxFn: () => false,
+ log,
+ },
+ );
+ expect(result.action).toBe("none");
+ expect(run).not.toHaveBeenCalled();
+ expect(logs.some((l) => l.includes("up to date"))).toBe(true);
+ });
+
+ it("reports failure when the install command exits non-zero", async () => {
+ const run = vi.fn(() => false);
+ const result = await ensureInstalled(
+ {},
+ {
+ isDevFn: () => false,
+ fetchLatest: async () => "0.0.2",
+ runInstall: run,
+ getCurrent: () => "0.0.1",
+ isNpxFn: () => true,
+ log,
+ },
+ );
+ expect(result.action).toBe("failed");
+ expect(logs.some((l) => l.includes("Could not install"))).toBe(true);
+ expect(logs.some((l) => l.includes("Install it manually"))).toBe(true);
+ });
+});
diff --git a/src/cli/lib/installer.ts b/src/cli/lib/installer.ts
new file mode 100644
index 000000000..23f0a6b21
--- /dev/null
+++ b/src/cli/lib/installer.ts
@@ -0,0 +1,154 @@
+import { spawnSync } from "child_process";
+import { isDev } from "./env.js";
+import { getCurrentVersion } from "./version.js";
+
+const PACKAGE = "@alook/cli";
+const REGISTRY_URL = `https://registry.npmjs.org/${PACKAGE}/latest`;
+const FETCH_TIMEOUT_MS = 3000;
+
+export type PackageManager = "npm" | "pnpm" | "yarn";
+
+export interface EnsureInstalledOptions {
+ skip?: boolean;
+}
+
+export interface EnsureInstalledDeps {
+ fetchLatest?: () => Promise<string | null>;
+ runInstall?: (pm: PackageManager) => boolean;
+ getCurrent?: () => string;
+ isNpxFn?: () => boolean;
+ isDevFn?: () => boolean;
+ log?: (msg: string) => void;
+}
+
+export type InstallAction = "none" | "installed" | "updated" | "failed";
+
+export interface EnsureInstalledResult {
+ skipped: boolean;
+ action: InstallAction;
+ current: string;
+ latest: string | null;
+ pm: PackageManager;
+}
+
+export async function fetchLatestVersion(): Promise<string | null> {
+ const ctrl = new AbortController();
+ const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);
+ try {
+ const res = await fetch(REGISTRY_URL, { signal: ctrl.signal });
+ if (!res.ok) return null;
+ const data = (await res.json()) as { version?: string };
+ return typeof data.version === "string" ? data.version : null;
+ } catch {
+ return null;
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+export function isNewer(current: string, latest: string): boolean {
+ const parse = (v: string) =>
+ v
+ .split("-")[0]
+ .split(".")
+ .map((n) => Number.parseInt(n, 10) || 0);
+ const [cMaj = 0, cMin = 0, cPatch = 0] = parse(current);
+ const [lMaj = 0, lMin = 0, lPatch = 0] = parse(latest);
+ if (lMaj !== cMaj) return lMaj > cMaj;
+ if (lMin !== cMin) return lMin > cMin;
+ return lPatch > cPatch;
+}
+
+export function isNpx(): boolean {
+ return (
+ process.env.npm_command === "exec" ||
+ !!process.env.npm_execpath?.includes("npx-cli")
+ );
+}
+
+export function detectPackageManager(): PackageManager {
+ const ua = process.env.npm_config_user_agent || "";
+ if (ua.startsWith("pnpm/")) return "pnpm";
+ if (ua.startsWith("yarn/")) return "yarn";
+ return "npm";
+}
+
+export function installArgs(pm: PackageManager): [string, string[]] {
+ switch (pm) {
+ case "pnpm":
+ return ["pnpm", ["add", "-g", PACKAGE]];
+ case "yarn":
+ return ["yarn", ["global", "add", PACKAGE]];
+ case "npm":
+ return ["npm", ["install", "-g", `${PACKAGE}@latest`]];
+ }
+}
+
+export function installCmdString(pm: PackageManager): string {
+ const [bin, args] = installArgs(pm);
+ return `${bin} ${args.join(" ")}`;
+}
+
+export function runInstall(pm: PackageManager): boolean {
+ const [bin, args] = installArgs(pm);
+ const result = spawnSync(bin, args, { stdio: "inherit" });
+ return result.status === 0;
+}
+
+export async function ensureInstalled(
+ opts: EnsureInstalledOptions = {},
+ deps: EnsureInstalledDeps = {},
+): Promise<EnsureInstalledResult> {
+ const fetchLatest = deps.fetchLatest ?? fetchLatestVersion;
+ const runInst = deps.runInstall ?? runInstall;
+ const getCurrent = deps.getCurrent ?? getCurrentVersion;
+ const isNpxFn = deps.isNpxFn ?? isNpx;
+ const isDevFn = deps.isDevFn ?? isDev;
+ const log = deps.log ?? ((m) => console.log(m));
+
+ const current = getCurrent();
+ const pm = detectPackageManager();
+
+ if (isDevFn() || opts.skip) {
+ return { skipped: true, action: "none", current, latest: null, pm };
+ }
+
+ const latest = await fetchLatest();
+ if (!latest) {
+ return { skipped: false, action: "none", current, latest: null, pm };
+ }
+
+ const runningViaNpx = isNpxFn();
+ const needsInstall = runningViaNpx;
+ const needsUpdate = !runningViaNpx && isNewer(current, latest);
+
+ if (!needsInstall && !needsUpdate) {
+ log(`\n✓ ${PACKAGE} is up to date (${current})`);
+ return { skipped: false, action: "none", current, latest, pm };
+ }
+
+ const cmdStr = installCmdString(pm);
+ if (needsInstall) {
+ log(`\nInstalling ${PACKAGE} globally (${cmdStr})...`);
+ } else {
+ log(`\nUpdating ${PACKAGE} ${current} → ${latest} (${cmdStr})...`);
+ }
+
+ const ok = runInst(pm);
+ if (!ok) {
+ log(
+ `\nCould not ${needsInstall ? "install" : "update"} ${PACKAGE} automatically.`,
+ );
+ log(`Install it manually: ${cmdStr}`);
+ return { skipped: false, action: "failed", current, latest, pm };
+ }
+
+ log(`✓ ${needsInstall ? "Installed" : "Updated"} ${PACKAGE} ${latest}`);
+ return {
+ skipped: false,
+ action: needsInstall ? "installed" : "updated",
+ current,
+ latest,
+ pm,
+ };
+}
diff --git a/src/cli/lib/version.test.ts b/src/cli/lib/version.test.ts
new file mode 100644
index 000000000..5edd9f279
--- /dev/null
+++ b/src/cli/lib/version.test.ts
@@ -0,0 +1,16 @@
+import { describe, it, expect } from "vitest";
+import { readFileSync } from "fs";
+import { join, dirname } from "path";
+import { fileURLToPath } from "url";
+import { getCurrentVersion } from "./version.js";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+
+describe("getCurrentVersion", () => {
+ it("returns the version declared in the CLI's package.json", () => {
+ const pkg = JSON.parse(
+ readFileSync(join(__dirname, "..", "package.json"), "utf-8"),
+ );
+ expect(getCurrentVersion()).toBe(pkg.version);
+ });
+});
diff --git a/src/cli/lib/version.ts b/src/cli/lib/version.ts
new file mode 100644
index 000000000..5596c4087
--- /dev/null
+++ b/src/cli/lib/version.ts
@@ -0,0 +1,20 @@
+import { readFileSync } from "fs";
+import { join, dirname } from "path";
+import { fileURLToPath } from "url";
+
+export function getCurrentVersion(): string {
+ const __dirname = dirname(fileURLToPath(import.meta.url));
+ const candidates = [
+ join(__dirname, "..", "package.json"),
+ join(__dirname, "..", "..", "package.json"),
+ ];
+ for (const candidate of candidates) {
+ try {
+ const pkg = JSON.parse(readFileSync(candidate, "utf-8"));
+ if (typeof pkg.version === "string") return pkg.version;
+ } catch {
+ // try next candidate
+ }
+ }
+ return "unknown";
+}