forked from openclaw/openclaw
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenclaw.mjs
More file actions
executable file
·401 lines (370 loc) · 11.5 KB
/
openclaw.mjs
File metadata and controls
executable file
·401 lines (370 loc) · 11.5 KB
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
#!/usr/bin/env node
import { spawn } from "node:child_process";
import { existsSync, readFileSync, statSync } from "node:fs";
import { access } from "node:fs/promises";
import module from "node:module";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
const MIN_NODE_MAJOR = 22;
const MIN_NODE_MINOR = 12;
const MIN_NODE_VERSION = `${MIN_NODE_MAJOR}.${MIN_NODE_MINOR}`;
const parseNodeVersion = (rawVersion) => {
const [majorRaw = "0", minorRaw = "0"] = rawVersion.split(".");
return {
major: Number(majorRaw),
minor: Number(minorRaw),
};
};
const isSupportedNodeVersion = (version) =>
version.major > MIN_NODE_MAJOR ||
(version.major === MIN_NODE_MAJOR && version.minor >= MIN_NODE_MINOR);
const ensureSupportedNodeVersion = () => {
if (isSupportedNodeVersion(parseNodeVersion(process.versions.node))) {
return;
}
process.stderr.write(
`openclaw: Node.js v${MIN_NODE_VERSION}+ is required (current: v${process.versions.node}).\n` +
"If you use nvm, run:\n" +
` nvm install ${MIN_NODE_MAJOR}\n` +
` nvm use ${MIN_NODE_MAJOR}\n` +
` nvm alias default ${MIN_NODE_MAJOR}\n`,
);
process.exit(1);
};
ensureSupportedNodeVersion();
const isSourceCheckoutLauncher = () =>
existsSync(new URL("./.git", import.meta.url)) ||
existsSync(new URL("./src/entry.ts", import.meta.url));
const isNodeCompileCacheDisabled = () => process.env.NODE_DISABLE_COMPILE_CACHE !== undefined;
const isNodeCompileCacheRequested = () =>
Boolean(process.env.NODE_COMPILE_CACHE) && !isNodeCompileCacheDisabled();
const sanitizeCompileCachePathSegment = (value) => {
const normalized = value.replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^_+|_+$/g, "");
return normalized.length > 0 ? normalized : "unknown";
};
const readPackageVersion = () => {
try {
const parsed = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8"));
if (typeof parsed?.version === "string" && parsed.version.trim().length > 0) {
return parsed.version;
}
} catch {
// Fall through to an install-metadata-only cache key.
}
return "unknown";
};
const resolvePackagedCompileCacheDirectory = () => {
const packageJsonUrl = new URL("./package.json", import.meta.url);
const version = sanitizeCompileCachePathSegment(readPackageVersion());
let installMarker = "no-package-json";
try {
const stat = statSync(packageJsonUrl);
installMarker = `${Math.trunc(stat.mtimeMs)}-${stat.size}`;
} catch {
// Package archives should always have package.json, but keep startup best-effort.
}
const baseDirectory = isNodeCompileCacheRequested()
? process.env.NODE_COMPILE_CACHE
: path.join(os.tmpdir(), "node-compile-cache");
return path.join(
baseDirectory,
"openclaw",
version,
sanitizeCompileCachePathSegment(installMarker),
);
};
const respawnSignals =
process.platform === "win32"
? ["SIGTERM", "SIGINT", "SIGBREAK"]
: ["SIGTERM", "SIGINT", "SIGHUP", "SIGQUIT"];
const respawnSignalExitGraceMs = 1_000;
const respawnSignalForceKillGraceMs = 1_000;
const runRespawnedChild = (command, args, env) => {
const child = spawn(command, args, {
stdio: "inherit",
env,
});
const listeners = new Map();
// This intentionally overlaps with src/entry.compile-cache.ts; keep the
// respawn supervision behavior in sync until the launcher can share TS code.
// Give the child a moment to honor forwarded signals, then exit the wrapper so
// a child that ignores SIGTERM cannot keep the launcher alive indefinitely.
let signalExitTimer = null;
let signalForceKillTimer = null;
const detach = () => {
for (const [signal, listener] of listeners) {
process.off(signal, listener);
}
listeners.clear();
if (signalExitTimer) {
clearTimeout(signalExitTimer);
signalExitTimer = null;
}
if (signalForceKillTimer) {
clearTimeout(signalForceKillTimer);
signalForceKillTimer = null;
}
};
const forceKillChild = () => {
try {
child.kill(process.platform === "win32" ? "SIGTERM" : "SIGKILL");
} catch {
// Best-effort shutdown fallback.
}
};
const requestChildTermination = () => {
try {
child.kill("SIGTERM");
} catch {
// Best-effort shutdown fallback.
}
signalForceKillTimer = setTimeout(() => {
forceKillChild();
process.exit(1);
}, respawnSignalForceKillGraceMs);
signalForceKillTimer.unref?.();
};
const scheduleParentExit = () => {
if (signalExitTimer) {
return;
}
signalExitTimer = setTimeout(() => {
requestChildTermination();
}, respawnSignalExitGraceMs);
signalExitTimer.unref?.();
};
for (const signal of respawnSignals) {
const listener = () => {
try {
child.kill(signal);
} catch {
// Best-effort signal forwarding.
}
scheduleParentExit();
};
try {
process.on(signal, listener);
listeners.set(signal, listener);
} catch {
// Unsupported signal on this platform.
}
}
child.once("exit", (code, signal) => {
detach();
if (signal) {
process.exit(1);
}
process.exit(code ?? 1);
});
child.once("error", (error) => {
detach();
process.stderr.write(
`[openclaw] Failed to respawn launcher: ${
error instanceof Error ? (error.stack ?? error.message) : String(error)
}\n`,
);
process.exit(1);
});
return true;
};
const respawnWithoutCompileCacheIfNeeded = () => {
if (!isSourceCheckoutLauncher()) {
return false;
}
if (process.env.OPENCLAW_SOURCE_COMPILE_CACHE_RESPAWNED === "1") {
return false;
}
if (!module.getCompileCacheDir?.() && !isNodeCompileCacheRequested()) {
return false;
}
const env = {
...process.env,
NODE_DISABLE_COMPILE_CACHE: "1",
OPENCLAW_SOURCE_COMPILE_CACHE_RESPAWNED: "1",
};
delete env.NODE_COMPILE_CACHE;
return runRespawnedChild(
process.execPath,
[...process.execArgv, fileURLToPath(import.meta.url), ...process.argv.slice(2)],
env,
);
};
const respawnWithPackagedCompileCacheIfNeeded = () => {
if (isSourceCheckoutLauncher() || isNodeCompileCacheDisabled()) {
return false;
}
if (process.env.OPENCLAW_PACKAGED_COMPILE_CACHE_RESPAWNED === "1") {
return false;
}
const currentDirectory = module.getCompileCacheDir?.();
if (!currentDirectory) {
return false;
}
const desiredDirectory = resolvePackagedCompileCacheDirectory();
if (path.resolve(currentDirectory) === path.resolve(desiredDirectory)) {
return false;
}
const env = {
...process.env,
NODE_COMPILE_CACHE: desiredDirectory,
OPENCLAW_PACKAGED_COMPILE_CACHE_RESPAWNED: "1",
};
return runRespawnedChild(
process.execPath,
[...process.execArgv, fileURLToPath(import.meta.url), ...process.argv.slice(2)],
env,
);
};
const waitingForCompileCacheRespawn =
respawnWithoutCompileCacheIfNeeded() || respawnWithPackagedCompileCacheIfNeeded();
// https://nodejs.org/api/module.html#module-compile-cache
if (
!waitingForCompileCacheRespawn &&
module.enableCompileCache &&
!isNodeCompileCacheDisabled() &&
!isSourceCheckoutLauncher()
) {
try {
module.enableCompileCache(resolvePackagedCompileCacheDirectory());
} catch {
// Ignore errors
}
}
const isModuleNotFoundError = (err) =>
err && typeof err === "object" && "code" in err && err.code === "ERR_MODULE_NOT_FOUND";
const isDirectModuleNotFoundError = (err, specifier) => {
if (!isModuleNotFoundError(err)) {
return false;
}
const expectedUrl = new URL(specifier, import.meta.url);
if ("url" in err && err.url === expectedUrl.href) {
return true;
}
const message = "message" in err && typeof err.message === "string" ? err.message : "";
const expectedPath = fileURLToPath(expectedUrl);
return (
message.includes(`Cannot find module '${expectedPath}'`) ||
message.includes(`Cannot find module "${expectedPath}"`)
);
};
const installProcessWarningFilter = async () => {
// Keep bootstrap warnings consistent with the TypeScript runtime.
for (const specifier of ["./dist/warning-filter.js", "./dist/warning-filter.mjs"]) {
try {
const mod = await import(specifier);
if (typeof mod.installProcessWarningFilter === "function") {
mod.installProcessWarningFilter();
return;
}
} catch (err) {
if (isDirectModuleNotFoundError(err, specifier)) {
continue;
}
throw err;
}
}
};
const tryImport = async (specifier) => {
try {
await import(specifier);
return true;
} catch (err) {
// Only swallow direct entry misses; rethrow transitive resolution failures.
if (isDirectModuleNotFoundError(err, specifier)) {
return false;
}
throw err;
}
};
const exists = async (specifier) => {
try {
await access(new URL(specifier, import.meta.url));
return true;
} catch {
return false;
}
};
const buildMissingEntryErrorMessage = async () => {
const lines = ["openclaw: missing dist/entry.(m)js (build output)."];
if (!(await exists("./src/entry.ts"))) {
return lines.join("\n");
}
lines.push("This install looks like an unbuilt source tree or GitHub source archive.");
lines.push(
"Build locally with `pnpm install && pnpm build`, or install a built package instead.",
);
lines.push(
"For pinned GitHub installs, use `npm install -g github:openclaw/openclaw#<ref>` instead of a raw `/archive/<ref>.tar.gz` URL.",
);
lines.push("For releases, use `npm install -g openclaw@latest`.");
return lines.join("\n");
};
const isBareRootHelpInvocation = (argv) =>
argv.length === 3 && (argv[2] === "--help" || argv[2] === "-h");
const isBrowserHelpInvocation = (argv) =>
argv.length === 4 && argv[2] === "browser" && (argv[3] === "--help" || argv[3] === "-h");
const isHelpFastPathDisabled = () =>
process.env.OPENCLAW_DISABLE_CLI_STARTUP_HELP_FAST_PATH === "1";
const loadPrecomputedHelpText = (key) => {
try {
const raw = readFileSync(new URL("./dist/cli-startup-metadata.json", import.meta.url), "utf8");
const parsed = JSON.parse(raw);
const value = parsed?.[key];
return typeof value === "string" && value.length > 0 ? value : null;
} catch {
return null;
}
};
const tryOutputBareRootHelp = async () => {
if (!isBareRootHelpInvocation(process.argv)) {
return false;
}
const precomputed = loadPrecomputedHelpText("rootHelpText");
if (precomputed) {
process.stdout.write(precomputed);
return true;
}
for (const specifier of ["./dist/cli/program/root-help.js", "./dist/cli/program/root-help.mjs"]) {
try {
const mod = await import(specifier);
if (typeof mod.outputRootHelp === "function") {
mod.outputRootHelp();
return true;
}
} catch (err) {
if (isDirectModuleNotFoundError(err, specifier)) {
continue;
}
throw err;
}
}
return false;
};
const tryOutputBrowserHelp = () => {
if (!isBrowserHelpInvocation(process.argv)) {
return false;
}
const precomputed = loadPrecomputedHelpText("browserHelpText");
if (!precomputed) {
return false;
}
process.stdout.write(precomputed);
return true;
};
if (!waitingForCompileCacheRespawn) {
if (!isHelpFastPathDisabled() && (await tryOutputBareRootHelp())) {
// OK
} else if (!isHelpFastPathDisabled() && tryOutputBrowserHelp()) {
// OK
} else {
await installProcessWarningFilter();
if (await tryImport("./dist/entry.js")) {
// OK
} else if (await tryImport("./dist/entry.mjs")) {
// OK
} else {
throw new Error(await buildMissingEntryErrorMessage());
}
}
}