mirror of
https://github.com/openclaw/openclaw.git
synced 2026-07-16 23:41:35 +00:00
* fix(core): make indexed access explicit in auto-reply, infra, and config Part 1/3 of the src NUIA phase-3b burn-down (#104600): iteration and destructuring over index reads, boundary guards on parsed input, and named invariants. Config path walkers bind the path head once; SQLite migration key handling is hoisted without query-shape changes. * fix(core): make indexed access explicit in cli, gateway, commands, security, shared Part 2/3: argv/token selection restructured, gateway event/attachment invariants named, security parsers stay fail-closed (invariant violations throw), edit-distance matrices access checked entries. * fix(core): make indexed access explicit across remaining src surfaces Part 3/3: channels, plugins, process, cron, plugin-sdk, media, logging, tui, hooks, daemon, and small directories. Latent bug fixed: a tailnet resolver could leak undefined through a string|null contract and now fails with a descriptive local error. * fix(core): keep optional boundaries optional after per-commit review Review findings: expectDefined misused where absence is a legitimate state. CLI --profile/route-args missing next tokens take their existing miss paths; help normalization compares --help against the last positional again; first-time plugin install spreads absent cfg.plugins; denylist scan iterates manifest dependency entries instead of throwing on omitted sections; tailnet resolver returns a guaranteed string at the source instead of a caller-side undefined throw. * refactor(core): closed-key provider labels and honest optional passthroughs PROVIDER_LABELS becomes a satisfies-typed closed record (static reads provably defined; dynamic lookups go through providerUsageLabel with honest string|undefined). Status-scan overview passes its optional params through unchanged instead of asserting them. * fix(channels): make getChatChannelMeta honestly optional The original signature claimed ChatChannelMeta while leaking undefined on bundled channel id metadata drift; three of four callers already handled absence. The return type now says so, and the one assuming caller falls back to the raw channel label. * fix(core): index-safety for post-rebase main drift Covers the sqlite-sessions flip and auth-source-plan code that landed mid-phase, plus the channel-validation test consuming the now honestly optional getChatChannelMeta. * refactor(channels): split chat-meta accessors along the SDK contract getChatChannelMeta keeps its shipped plugin-SDK signature (defined for bundled ids, fail-loud on impossible misses); new findChatChannelMeta carries the drift-tolerant optional contract for core auto-enable and formatting paths. * fix(qa-channel): own channel metadata instead of a guaranteed-undefined catalog lookup qa-channel spread getChatChannelMeta over an id that is never in the bundled catalog, shipping an empty setup meta by accident; the fail-loud SDK accessor exposed it. The channel now declares its metadata once. * fix(gateway): heartbeat projection lookahead is optional at the transcript tail expectDefined wrapped messages[i + 1] whose absence on the final message is the normal case; the adjacent ternary already handled it. Restores the plain optional read with an explicit guard in the pair condition. * fix(plugin-sdk): channel plugin factory tolerates non-bundled channel ids again createChannelPluginBase spreads bundled catalog meta for ANY channel id, where absence is the normal case for external plugins; the resolver is honestly optional again while the exported bundled-id accessor keeps the fail-loud contract. * fix(core): spreads of optional config sections stay optional Fresh-setup and first-install paths (crestodian setup inference, hook installs, agent config base, target agent models) legitimately lack the section being rebuilt; spreading undefined is the shipped {} semantics. Removes the remaining gratuitous assertion wraps found by tree audit.
237 lines
7.4 KiB
TypeScript
237 lines
7.4 KiB
TypeScript
// Manages compile-cache respawn behavior for the CLI entrypoint.
|
|
import { spawn, type ChildProcess } from "node:child_process";
|
|
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
import { enableCompileCache, getCompileCacheDir } from "node:module";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import process from "node:process";
|
|
import { expectDefined } from "@openclaw/normalization-core";
|
|
import { isTerminalInteractiveRespawnArgv } from "./cli/respawn-policy.js";
|
|
import { attachChildProcessBridge } from "./process/child-process-bridge.js";
|
|
import {
|
|
runRespawnChildWithSignalBridge,
|
|
type RespawnChildRuntime,
|
|
} from "./process/respawn-child-runner.js";
|
|
|
|
// Node 24.0-24.14 can deadlock during ESM module loading when compile cache is
|
|
// enabled on Windows npm-global installs. Keep the skip scoped to that platform.
|
|
const MIN_COMPILE_CACHE_NODE_24_MINOR = 15;
|
|
const COMPILE_CACHE_DISABLED_RESPAWNED_ENV = "OPENCLAW_COMPILE_CACHE_DISABLED_RESPAWNED";
|
|
|
|
export function resolveEntryInstallRoot(entryFile: string): string {
|
|
const entryDir = path.dirname(entryFile);
|
|
const entryParent = path.basename(entryDir);
|
|
return entryParent === "dist" || entryParent === "src" ? path.dirname(entryDir) : entryDir;
|
|
}
|
|
|
|
export function isSourceCheckoutInstallRoot(installRoot: string): boolean {
|
|
return (
|
|
existsSync(path.join(installRoot, ".git")) ||
|
|
existsSync(path.join(installRoot, "src", "entry.ts"))
|
|
);
|
|
}
|
|
|
|
function isNodeCompileCacheDisabled(env: NodeJS.ProcessEnv | undefined): boolean {
|
|
return env?.NODE_DISABLE_COMPILE_CACHE !== undefined;
|
|
}
|
|
|
|
function isNodeCompileCacheRequested(env: NodeJS.ProcessEnv | undefined): boolean {
|
|
return env?.NODE_COMPILE_CACHE !== undefined && !isNodeCompileCacheDisabled(env);
|
|
}
|
|
|
|
export function isNodeVersionAffectedByCompileCacheDeadlock(
|
|
nodeVersion: string | undefined,
|
|
): boolean {
|
|
if (!nodeVersion) {
|
|
return false;
|
|
}
|
|
const match = nodeVersion.match(/^(\d+)\.(\d+)/);
|
|
if (!match) {
|
|
return false;
|
|
}
|
|
const major = Number.parseInt(expectDefined(match[1], "compile-cache major version capture"), 10);
|
|
const minor = Number.parseInt(expectDefined(match[2], "compile-cache minor version capture"), 10);
|
|
if (major !== 24) {
|
|
return false;
|
|
}
|
|
return minor < MIN_COMPILE_CACHE_NODE_24_MINOR;
|
|
}
|
|
|
|
export function shouldEnableOpenClawCompileCache(params: {
|
|
env?: NodeJS.ProcessEnv;
|
|
installRoot: string;
|
|
nodeVersion?: string;
|
|
platform?: NodeJS.Platform;
|
|
}): boolean {
|
|
if (isNodeCompileCacheDisabled(params.env)) {
|
|
return false;
|
|
}
|
|
if (
|
|
(params.platform ?? process.platform) === "win32" &&
|
|
isNodeVersionAffectedByCompileCacheDeadlock(params.nodeVersion ?? process.versions.node)
|
|
) {
|
|
return false;
|
|
}
|
|
return !isSourceCheckoutInstallRoot(params.installRoot);
|
|
}
|
|
|
|
function sanitizeCompileCachePathSegment(value: string): string {
|
|
const normalized = value.replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^_+|_+$/g, "");
|
|
return normalized.length > 0 ? normalized : "unknown";
|
|
}
|
|
|
|
function readPackageVersion(packageJsonPath: string): string {
|
|
try {
|
|
const parsed = JSON.parse(readFileSync(packageJsonPath, "utf8")) as unknown;
|
|
if (
|
|
parsed &&
|
|
typeof parsed === "object" &&
|
|
"version" in parsed &&
|
|
typeof parsed.version === "string" &&
|
|
parsed.version.trim().length > 0
|
|
) {
|
|
return parsed.version;
|
|
}
|
|
} catch {
|
|
// Fall through to an install-metadata-only cache key.
|
|
}
|
|
return "unknown";
|
|
}
|
|
|
|
export function resolveOpenClawCompileCacheDirectory(params: {
|
|
env?: NodeJS.ProcessEnv;
|
|
installRoot: string;
|
|
}): string {
|
|
const env = params.env ?? process.env;
|
|
const packageJsonPath = path.join(params.installRoot, "package.json");
|
|
const version = sanitizeCompileCachePathSegment(readPackageVersion(packageJsonPath));
|
|
let installMarker = "no-package-json";
|
|
try {
|
|
const stat = statSync(packageJsonPath);
|
|
installMarker = `${Math.trunc(stat.mtimeMs)}-${stat.size}`;
|
|
} catch {
|
|
// Package archives should always have package.json, but keep startup best-effort.
|
|
}
|
|
const baseDirectory =
|
|
env.NODE_COMPILE_CACHE && !isNodeCompileCacheDisabled(env)
|
|
? env.NODE_COMPILE_CACHE
|
|
: path.join(os.tmpdir(), "node-compile-cache");
|
|
return path.join(
|
|
baseDirectory,
|
|
"openclaw",
|
|
version,
|
|
sanitizeCompileCachePathSegment(installMarker),
|
|
);
|
|
}
|
|
|
|
type OpenClawCompileCacheRespawnPlan = {
|
|
command: string;
|
|
args: string[];
|
|
env: NodeJS.ProcessEnv;
|
|
detachForProcessTree: boolean;
|
|
};
|
|
|
|
type OpenClawCompileCacheRespawnRuntime = RespawnChildRuntime & {
|
|
writeError: (message: string) => void;
|
|
};
|
|
|
|
export function buildOpenClawCompileCacheRespawnPlan(params: {
|
|
currentFile: string;
|
|
env?: NodeJS.ProcessEnv;
|
|
execArgv?: string[];
|
|
execPath?: string;
|
|
installRoot: string;
|
|
argv?: string[];
|
|
compileCacheDir?: string;
|
|
nodeVersion?: string;
|
|
platform?: NodeJS.Platform;
|
|
}): OpenClawCompileCacheRespawnPlan | undefined {
|
|
const env = params.env ?? process.env;
|
|
const needsDisabledCompileCacheRespawn =
|
|
isSourceCheckoutInstallRoot(params.installRoot) ||
|
|
((params.platform ?? process.platform) === "win32" &&
|
|
isNodeVersionAffectedByCompileCacheDeadlock(params.nodeVersion ?? process.versions.node));
|
|
if (!needsDisabledCompileCacheRespawn) {
|
|
return undefined;
|
|
}
|
|
if (env[COMPILE_CACHE_DISABLED_RESPAWNED_ENV] === "1") {
|
|
return undefined;
|
|
}
|
|
if (!params.compileCacheDir && !isNodeCompileCacheRequested(env)) {
|
|
return undefined;
|
|
}
|
|
const nextEnv: NodeJS.ProcessEnv = {
|
|
...env,
|
|
NODE_DISABLE_COMPILE_CACHE: "1",
|
|
[COMPILE_CACHE_DISABLED_RESPAWNED_ENV]: "1",
|
|
};
|
|
delete nextEnv.NODE_COMPILE_CACHE;
|
|
return {
|
|
command: params.execPath ?? process.execPath,
|
|
args: [
|
|
...(params.execArgv ?? process.execArgv),
|
|
params.currentFile,
|
|
...(params.argv ?? process.argv).slice(2),
|
|
],
|
|
env: nextEnv,
|
|
detachForProcessTree:
|
|
(params.platform ?? process.platform) !== "win32" &&
|
|
!isTerminalInteractiveRespawnArgv(params.argv ?? process.argv),
|
|
};
|
|
}
|
|
|
|
export function respawnWithoutOpenClawCompileCacheIfNeeded(params: {
|
|
currentFile: string;
|
|
installRoot: string;
|
|
}): boolean {
|
|
const plan = buildOpenClawCompileCacheRespawnPlan({
|
|
currentFile: params.currentFile,
|
|
installRoot: params.installRoot,
|
|
compileCacheDir: getCompileCacheDir?.(),
|
|
});
|
|
if (!plan) {
|
|
return false;
|
|
}
|
|
runOpenClawCompileCacheRespawnPlan(plan);
|
|
return true;
|
|
}
|
|
|
|
export function runOpenClawCompileCacheRespawnPlan(
|
|
plan: OpenClawCompileCacheRespawnPlan,
|
|
runtime: OpenClawCompileCacheRespawnRuntime = {
|
|
spawn,
|
|
attachChildProcessBridge,
|
|
exit: process.exit.bind(process) as (code?: number) => never,
|
|
writeError: (message: string) => process.stderr.write(message),
|
|
},
|
|
): ChildProcess {
|
|
return runRespawnChildWithSignalBridge({
|
|
command: plan.command,
|
|
args: plan.args,
|
|
env: plan.env,
|
|
detachForProcessTree: plan.detachForProcessTree,
|
|
runtime,
|
|
onError: (error) => {
|
|
runtime.writeError(
|
|
`[openclaw] Failed to respawn CLI without compile cache: ${
|
|
error instanceof Error ? (error.stack ?? error.message) : String(error)
|
|
}\n`,
|
|
);
|
|
},
|
|
});
|
|
}
|
|
|
|
export function enableOpenClawCompileCache(params: {
|
|
env?: NodeJS.ProcessEnv;
|
|
installRoot: string;
|
|
}): void {
|
|
if (!shouldEnableOpenClawCompileCache(params)) {
|
|
return;
|
|
}
|
|
try {
|
|
enableCompileCache(resolveOpenClawCompileCacheDirectory(params));
|
|
} catch {
|
|
// Best-effort only; never block startup.
|
|
}
|
|
}
|