File size: 7,782 Bytes
fc93158 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 | import { spawnSync } from "node:child_process";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { resolveStateDir } from "../../config/paths.js";
import { resolveOpenClawPackageRoot } from "../../infra/openclaw-root.js";
import { readPackageName, readPackageVersion } from "../../infra/package-json.js";
import { normalizePackageTagInput } from "../../infra/package-tag.js";
import { trimLogTail } from "../../infra/restart-sentinel.js";
import { parseSemver } from "../../infra/runtime-guard.js";
import { fetchNpmTagVersion } from "../../infra/update-check.js";
import {
detectGlobalInstallManagerByPresence,
detectGlobalInstallManagerForRoot,
type CommandRunner,
type GlobalInstallManager,
} from "../../infra/update-global.js";
import type { UpdateStepProgress, UpdateStepResult } from "../../infra/update-runner.js";
import { runCommandWithTimeout } from "../../process/exec.js";
import { defaultRuntime } from "../../runtime.js";
import { theme } from "../../terminal/theme.js";
import { pathExists } from "../../utils.js";
export type UpdateCommandOptions = {
json?: boolean;
restart?: boolean;
dryRun?: boolean;
channel?: string;
tag?: string;
timeout?: string;
yes?: boolean;
};
export type UpdateStatusOptions = {
json?: boolean;
timeout?: string;
};
export type UpdateWizardOptions = {
timeout?: string;
};
const INVALID_TIMEOUT_ERROR = "--timeout must be a positive integer (seconds)";
export function parseTimeoutMsOrExit(timeout?: string): number | undefined | null {
const timeoutMs = timeout ? Number.parseInt(timeout, 10) * 1000 : undefined;
if (timeoutMs !== undefined && (Number.isNaN(timeoutMs) || timeoutMs <= 0)) {
defaultRuntime.error(INVALID_TIMEOUT_ERROR);
defaultRuntime.exit(1);
return null;
}
return timeoutMs;
}
const OPENCLAW_REPO_URL = "https://github.com/openclaw/openclaw.git";
const MAX_LOG_CHARS = 8000;
export const DEFAULT_PACKAGE_NAME = "openskynet";
const CORE_PACKAGE_NAMES = new Set([DEFAULT_PACKAGE_NAME, "openclaw"]);
export function normalizeTag(value?: string | null): string | null {
return normalizePackageTagInput(value, ["openclaw", "openskynet", DEFAULT_PACKAGE_NAME]);
}
export function normalizeVersionTag(tag: string): string | null {
const trimmed = tag.trim();
if (!trimmed) {
return null;
}
const cleaned = trimmed.startsWith("v") ? trimmed.slice(1) : trimmed;
return parseSemver(cleaned) ? cleaned : null;
}
export { readPackageName, readPackageVersion };
export async function resolveTargetVersion(
tag: string,
timeoutMs?: number,
): Promise<string | null> {
const direct = normalizeVersionTag(tag);
if (direct) {
return direct;
}
const res = await fetchNpmTagVersion({ tag, timeoutMs });
return res.version ?? null;
}
export async function isGitCheckout(root: string): Promise<boolean> {
try {
await fs.stat(path.join(root, ".git"));
return true;
} catch {
return false;
}
}
export async function isCorePackage(root: string): Promise<boolean> {
const name = await readPackageName(root);
return Boolean(name && CORE_PACKAGE_NAMES.has(name));
}
export async function isEmptyDir(targetPath: string): Promise<boolean> {
try {
const entries = await fs.readdir(targetPath);
return entries.length === 0;
} catch {
return false;
}
}
export function resolveGitInstallDir(): string {
const override = process.env.OPENCLAW_GIT_DIR?.trim();
if (override) {
return path.resolve(override);
}
return resolveDefaultGitDir();
}
function resolveDefaultGitDir(): string {
return resolveStateDir(process.env, os.homedir);
}
export function resolveNodeRunner(): string {
const base = path.basename(process.execPath).toLowerCase();
if (base === "node" || base === "node.exe") {
return process.execPath;
}
return "node";
}
export async function resolveUpdateRoot(): Promise<string> {
return (
(await resolveOpenClawPackageRoot({
moduleUrl: import.meta.url,
argv1: process.argv[1],
cwd: process.cwd(),
})) ?? process.cwd()
);
}
export async function runUpdateStep(params: {
name: string;
argv: string[];
cwd?: string;
timeoutMs: number;
progress?: UpdateStepProgress;
env?: NodeJS.ProcessEnv;
}): Promise<UpdateStepResult> {
const command = params.argv.join(" ");
params.progress?.onStepStart?.({
name: params.name,
command,
index: 0,
total: 0,
});
const started = Date.now();
const res = await runCommandWithTimeout(params.argv, {
cwd: params.cwd,
env: params.env,
timeoutMs: params.timeoutMs,
});
const durationMs = Date.now() - started;
const stderrTail = trimLogTail(res.stderr, MAX_LOG_CHARS);
params.progress?.onStepComplete?.({
name: params.name,
command,
index: 0,
total: 0,
durationMs,
exitCode: res.code,
stderrTail,
});
return {
name: params.name,
command,
cwd: params.cwd ?? process.cwd(),
durationMs,
exitCode: res.code,
stdoutTail: trimLogTail(res.stdout, MAX_LOG_CHARS),
stderrTail,
};
}
export async function ensureGitCheckout(params: {
dir: string;
timeoutMs: number;
progress?: UpdateStepProgress;
}): Promise<UpdateStepResult | null> {
const dirExists = await pathExists(params.dir);
if (!dirExists) {
return await runUpdateStep({
name: "git clone",
argv: ["git", "clone", OPENCLAW_REPO_URL, params.dir],
timeoutMs: params.timeoutMs,
progress: params.progress,
});
}
if (!(await isGitCheckout(params.dir))) {
const empty = await isEmptyDir(params.dir);
if (!empty) {
throw new Error(
`OPENCLAW_GIT_DIR points at a non-git directory: ${params.dir}. Set OPENCLAW_GIT_DIR to an empty folder or an openclaw checkout.`,
);
}
return await runUpdateStep({
name: "git clone",
argv: ["git", "clone", OPENCLAW_REPO_URL, params.dir],
cwd: params.dir,
timeoutMs: params.timeoutMs,
progress: params.progress,
});
}
if (!(await isCorePackage(params.dir))) {
throw new Error(`OPENCLAW_GIT_DIR does not look like a core checkout: ${params.dir}.`);
}
return null;
}
export async function resolveGlobalManager(params: {
root: string;
installKind: "git" | "package" | "unknown";
timeoutMs: number;
}): Promise<GlobalInstallManager> {
const runCommand = createGlobalCommandRunner();
if (params.installKind === "package") {
const detected = await detectGlobalInstallManagerForRoot(
runCommand,
params.root,
params.timeoutMs,
);
if (detected) {
return detected;
}
}
const byPresence = await detectGlobalInstallManagerByPresence(runCommand, params.timeoutMs);
return byPresence ?? "npm";
}
export async function tryWriteCompletionCache(root: string, jsonMode: boolean): Promise<void> {
const binPath = path.join(root, "openclaw.mjs");
if (!(await pathExists(binPath))) {
return;
}
const result = spawnSync(resolveNodeRunner(), [binPath, "completion", "--write-state"], {
cwd: root,
env: process.env,
encoding: "utf-8",
});
if (result.error) {
if (!jsonMode) {
defaultRuntime.log(theme.warn(`Completion cache update failed: ${String(result.error)}`));
}
return;
}
if (result.status !== 0 && !jsonMode) {
const stderr = (result.stderr ?? "").toString().trim();
const detail = stderr ? ` (${stderr})` : "";
defaultRuntime.log(theme.warn(`Completion cache update failed${detail}.`));
}
}
export function createGlobalCommandRunner(): CommandRunner {
return async (argv, options) => {
const res = await runCommandWithTimeout(argv, options);
return { stdout: res.stdout, stderr: res.stderr, code: res.code };
};
}
|