Skip to content

Commit c93390e

Browse files
committed
fix(cloud-workers): build complete source runtime artifacts
Allow the canonical package builder to include explicitly selected source runtime plugins with exact target-installed dependencies and regenerated inventory. Preserve concise enrollment prerequisite errors without changing trust or normal core publication. Fixes #130702. Complete source-built cloud worker packages now retain required runtime plugins; deployment artifacts must be rebuilt from the landed source.
1 parent c47974c commit c93390e

8 files changed

Lines changed: 505 additions & 45 deletions

‎docs/gateway/cloud-workers.md‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -184,11 +184,32 @@ openclaw config set cloudWorkers.profiles.aws.settings.setup \
184184
"${existing_setup}; sudo npm install -g openclaw@${gateway_version}; openclaw plugins install npm:@openclaw/codex@${gateway_version} --pin --force"
185185
```
186186

187-
`--force` allows setup replay to converge when the plugin is already installed. After upgrading the Gateway, update both appended package versions to match it while preserving the rest of the setup. Unreleased source builds require exact locally packed packages instead of registry versions.
187+
`--force` allows setup replay to converge when the plugin is already installed. After upgrading the Gateway, update both appended package versions to match it while preserving the rest of the setup. This recipe requires both exact versions to exist in the registry. For unreleased source builds, use a complete custom node package as described below; a standalone local plugin tarball does not carry official npm provenance.
188+
189+
### Build a complete custom node package
190+
191+
For a trusted source build, produce the node distribution from the same source revision as the Gateway. The canonical package builder can explicitly include source-owned plugins that the ordinary core package excludes:
192+
193+
```bash
194+
source_sha="$(git rev-parse HEAD)"
195+
node scripts/package-openclaw-for-docker.mjs \
196+
--bundle-plugin codex \
197+
--pnpm-pack \
198+
--allow-unreleased-changelog \
199+
--output-dir .artifacts/cloud-node \
200+
--output-name "openclaw-cloud-${source_sha}.tgz"
201+
shasum -a 256 ".artifacts/cloud-node/openclaw-cloud-${source_sha}.tgz"
202+
```
203+
204+
Run this in a clean, trusted checkout with dependencies installed. The builder compiles the runtime, includes the selected plugin's built entrypoints and import closure, and regenerates the installation inventory. It temporarily adds the plugin's exact runtime dependency pins to the distribution manifest, rejecting conflicting or unpinned dependencies, then restores the source manifest and inventory. Repeat `--bundle-plugin <id>` for additional source plugins. Without that option, the ordinary core package and external plugin publication contracts are unchanged.
205+
206+
Publish the resulting archive through your existing immutable artifact delivery path and make `settings.setup` verify its SHA-256 before installing it globally with normal npm lifecycle scripts enabled. Record both source SHA and archive digest: different unreleased builds can share a version. Do not copy a plugin into an installed release or substitute a standalone `npm-pack:` plugin archive for this distribution.
207+
208+
Native dependencies are declared at the distribution root and installed for the target operating system and CPU; the archive does not copy the build host's plugin `node_modules`. Target installation still needs registry access and is not an offline dependency bundle. Verify each target architecture you deploy. Use `--skip-build` only when reusing a complete build from that same source revision with all selected plugin outputs present.
188209

189210
### Bundle installation
190211

191-
The setup bootstrap first reuses an installed `openclaw` binary when its version exactly matches the Gateway, then tries the exact `openclaw@<version>` registry package. For an unreleased source build, install a locally packed candidate with the same version in `settings.setup`; the provider will select it before touching the registry. After the node connects and publishes its session-host inventory, the Gateway pushes one content-addressed worker bundle through the paired channel. The node verifies and publishes those exact bytes without installing the normal OpenClaw package dependency tree. A stale Gateway build retires the environment and reprovisions against the current bundle rather than downgrading the execution-context protocol.
212+
The setup bootstrap first reuses an installed `openclaw` binary when its version exactly matches the Gateway, then tries the exact `openclaw@<version>` registry package. For an unreleased source build, install the matching [complete custom node package](/gateway/cloud-workers#build-a-complete-custom-node-package) in `settings.setup`; the provider will select it before touching the registry. After the node connects and publishes its session-host inventory, the Gateway pushes one content-addressed worker bundle through the paired channel. The node verifies and publishes those exact bytes without installing the normal OpenClaw package dependency tree. A stale Gateway build retires the environment and reprovisions against the current bundle rather than downgrading the execution-context protocol.
192213

193214
Codex remote execution additionally requires `settings.setup` or the cloud image to install the exact official npm `@openclaw/codex` plugin matching the Gateway version, including its pinned platform-native `@openai/codex` dependency. An exact-version bundled plugin is also accepted. Enrollment preserves the plugin's official npm or bundled provenance in the node's isolated per-lease state; it does not install plugins from npm or accept an untrusted local plugin path. A missing, mismatched, or untrusted plugin fails before the node starts.
194215

‎extensions/crabbox/src/crabbox-worker-node-enrollment.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,10 @@ export function createCrabboxNodeEnrollmentSetup(params: {
4242
if (executionMode !== "remote-exec") {
4343
return [];
4444
}
45+
// Uncaught node -e errors dump source and append a stack to the diagnosis,
46+
// pushing the actionable message out of the bounded provider error tail.
4547
const inspectPlugin = [
48+
"try{",
4649
'const fs=require("node:fs"),path=require("node:path"),module=require("node:module");',
4750
'const inspection=JSON.parse(fs.readFileSync(0,"utf8")),plugin=inspection.plugin;',
4851
`const version=${JSON.stringify(enrollment.openclawVersion)};`,
@@ -69,6 +72,7 @@ export function createCrabboxNodeEnrollmentSetup(params: {
6972
'if(!existing.isSymbolicLink()||fs.realpathSync(projected)!==root){throw new Error("Codex node plugin path is occupied")}',
7073
'}catch(error){if(error.code!=="ENOENT"){throw error}fs.symlinkSync(root,projected)}',
7174
"}",
75+
"}catch(error){console.error(String(error));process.exitCode=1}",
7276
].join("");
7377
return [
7478
`"$@" plugins inspect codex --json | node -e ${shellQuote(inspectPlugin)} "$state_dir"`,

‎extensions/crabbox/src/crabbox-worker-provider.test.ts‎

Lines changed: 62 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { spawnSync } from "node:child_process";
12
import fs from "node:fs";
23
import path from "node:path";
34
import { fileURLToPath } from "node:url";
@@ -1063,39 +1064,68 @@ describe("Crabbox worker provider", () => {
10631064
});
10641065
});
10651066

1066-
it("preserves the node enrollment diagnosis after the Crabbox banner and setup noise", async () => {
1067-
const diagnosis =
1068-
"Error: Codex remote-exec requires the exact official @openclaw/[email protected] plugin to be installed by cloudWorkers profile setup";
1069-
const stderr = [
1070-
`workspace owner acquired wait=218ms recovered=false run context: run=${"a".repeat(32)} lease=${LEASE_ID} slug=openclaw-${"b".repeat(32)} provider=machine0 [email protected]:2222 workspace=/workspace/openclaw`,
1071-
"x".repeat(2_000),
1072-
diagnosis,
1073-
" at prepareCodex ([eval]:20:11)",
1074-
" at runScriptInThisContext (node:internal/vm:209:10)",
1075-
" at node:internal/process/execution:446:12",
1076-
" at [eval]-wrapper:6:24",
1077-
" at runScriptInContext (node:internal/process/execution:444:60)",
1078-
" at evalFunction (node:internal/process/execution:279:30)",
1079-
"Node.js v24.15.0",
1080-
].join("\n");
1081-
const provider = providerWithRunner(async (argv) => {
1082-
if (argv[1] === "status") {
1083-
return commandResult({ stdout: inspectJson() });
1084-
}
1085-
return argv[1] === "run"
1086-
? commandResult({ code: 1, stderr, stdout: "setup progress ".repeat(200) })
1087-
: commandResult();
1088-
});
1067+
it.skipIf(process.platform === "win32")(
1068+
"preserves the actual node enrollment diagnosis after setup noise",
1069+
async () => {
1070+
const diagnosis =
1071+
"Error: Codex remote-exec requires the exact official @openclaw/[email protected] plugin to be installed by cloudWorkers profile setup";
1072+
const home = tempDirs.make("crabbox-enrollment-");
1073+
const bin = path.join(home, "bin");
1074+
fs.mkdirSync(bin);
1075+
fs.symlinkSync(process.execPath, path.join(bin, "node"));
1076+
fs.writeFileSync(
1077+
path.join(bin, "openclaw"),
1078+
[
1079+
"#!/bin/sh",
1080+
'case "$*" in',
1081+
' --version) echo "OpenClaw 2026.8.1" ;;',
1082+
' "plugins inspect codex --json") echo \'{"ok":false}\'; exit 1 ;;',
1083+
' *) echo "unexpected command: $*" >&2; exit 99 ;;',
1084+
"esac",
1085+
].join("\n"),
1086+
{ mode: 0o700 },
1087+
);
1088+
const calls: string[][] = [];
1089+
const provider = providerWithRunner(async (argv, options) => {
1090+
calls.push(argv);
1091+
if (argv[1] === "status") {
1092+
return commandResult({ stdout: inspectJson() });
1093+
}
1094+
if (argv[1] !== "run") {
1095+
return commandResult();
1096+
}
1097+
const result = spawnSync("/bin/bash", [], {
1098+
input: options.input,
1099+
encoding: "utf8",
1100+
timeout: 10_000,
1101+
env: {
1102+
HOME: home,
1103+
PATH: `${bin}:/usr/bin:/bin`,
1104+
CRABBOX_WORKER_SETUP_CODE: "fixture-setup",
1105+
},
1106+
});
1107+
expect(result.status).toBe(1);
1108+
return commandResult({
1109+
code: result.status,
1110+
stdout: "setup progress ".repeat(200),
1111+
stderr: `workspace owner acquired\n${result.stderr}\nworkspace owner released\nremote command exited 1`,
1112+
});
1113+
});
10891114

1090-
await expect(
1091-
provider.provision({ ...PROFILE, provider: "machine0" }, OPERATION_ID, {
1092-
executionMode: "remote-exec",
1093-
}),
1094-
).rejects.toMatchObject({
1095-
code: "invalid_profile",
1096-
message: expect.stringContaining(diagnosis),
1097-
});
1098-
});
1115+
await expect(
1116+
provider.provision({ ...PROFILE, provider: "machine0" }, OPERATION_ID, {
1117+
executionMode: "remote-exec",
1118+
}),
1119+
).rejects.toMatchObject({
1120+
code: "invalid_profile",
1121+
message: expect.stringContaining(diagnosis),
1122+
});
1123+
expect(calls.at(-1)?.[1]).toBe("stop");
1124+
expect(
1125+
fs.existsSync(path.join(home, ".openclaw", "cloud-workers", LEASE_ID, "node.pid")),
1126+
).toBe(false);
1127+
},
1128+
);
10991129

11001130
it("preserves the allocated lease and both failures when setup cleanup times out", async () => {
11011131
let releaseCommitted = false;
Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
// Composes explicitly selected source plugins into a custom core distribution.
2+
import fs from "node:fs/promises";
3+
import path from "node:path";
4+
import { isDeepStrictEqual } from "node:util";
5+
import { satisfies, valid } from "semver";
6+
import { validateBundledPackageDependencyAlignment } from "../package-source-dependencies.mjs";
7+
import {
8+
collectBundledPluginBuildEntries,
9+
collectRootPackageExcludedExtensionDirs,
10+
DOCKER_SELECTED_PLUGIN_BUILD_IDS_ENV,
11+
NON_PACKAGED_BUNDLED_PLUGIN_DIRS,
12+
} from "./bundled-plugin-build-entries.mjs";
13+
import { assertRealOutputRoot } from "./output-root-guard.mjs";
14+
import {
15+
PACKAGE_DIST_INVENTORY_RELATIVE_PATH,
16+
PACKAGE_INSTALL_GUARD_RELATIVE_PATH,
17+
} from "./package-dist-inventory-contract.mts";
18+
19+
type PackageJson = {
20+
name: string;
21+
version: string;
22+
files: string[];
23+
dependencies?: Record<string, string>;
24+
optionalDependencies?: Record<string, string>;
25+
peerDependencies?: Record<string, string>;
26+
peerDependenciesMeta?: Record<string, { optional?: boolean }>;
27+
};
28+
29+
export function resolvePackageBundledPlugins(sourceDir: string, pluginIds: string[]) {
30+
const ids = [...new Set(pluginIds)].toSorted();
31+
if (ids.length === 0) {
32+
return [];
33+
}
34+
const entries = collectBundledPluginBuildEntries({
35+
cwd: sourceDir,
36+
env: { [DOCKER_SELECTED_PLUGIN_BUILD_IDS_ENV]: ids.join(",") },
37+
});
38+
const excluded = collectRootPackageExcludedExtensionDirs({ cwd: sourceDir });
39+
return ids.map((id) => {
40+
const entry = entries.find((candidate) => candidate.id === id);
41+
if (!entry?.hasPackageJson || !excluded.has(id) || NON_PACKAGED_BUNDLED_PLUGIN_DIRS.has(id)) {
42+
throw new Error(
43+
`--bundle-plugin requires a source plugin excluded from the core package: ${id}`,
44+
);
45+
}
46+
return entry;
47+
});
48+
}
49+
50+
/** Called under the canonical packer's source lifecycle lock, before bundling workspace deps. */
51+
export async function preparePackageBundledPlugins(sourceDir: string, pluginIds: string[]) {
52+
const selected = resolvePackageBundledPlugins(sourceDir, pluginIds);
53+
if (selected.length === 0) {
54+
return async () => {};
55+
}
56+
assertRealOutputRoot(path.join(sourceDir, "dist"));
57+
const packagePath = path.join(sourceDir, "package.json");
58+
const original = await fs.readFile(packagePath, "utf8");
59+
const packageJson = JSON.parse(original) as PackageJson;
60+
for (const { id, sourceEntries } of selected) {
61+
const sourcePackage = JSON.parse(
62+
await fs.readFile(path.join(sourceDir, "extensions", id, "package.json"), "utf8"),
63+
) as PackageJson;
64+
const pluginRoot = path.join(sourceDir, "dist", "extensions", id);
65+
const builtPackage = JSON.parse(
66+
await fs.readFile(path.join(pluginRoot, "package.json"), "utf8"),
67+
) as PackageJson;
68+
const manifest = JSON.parse(
69+
await fs.readFile(path.join(pluginRoot, "openclaw.plugin.json"), "utf8"),
70+
) as { id: string };
71+
if (
72+
manifest.id !== id ||
73+
(["name", "version", "dependencies", "optionalDependencies"] as const).some(
74+
(key) => !isDeepStrictEqual(builtPackage[key], sourcePackage[key]),
75+
)
76+
) {
77+
throw new Error(
78+
`Built plugin ${id} does not match source metadata; rebuild before packaging`,
79+
);
80+
}
81+
for (const entry of sourceEntries) {
82+
await fs.access(path.join(pluginRoot, entry.replace(/\.[^.]+$/u, ".js")));
83+
}
84+
for (const section of ["dependencies", "optionalDependencies"] as const) {
85+
const dependencies = sourcePackage[section] ?? {};
86+
for (const [name, spec] of Object.entries(dependencies)) {
87+
if (valid(spec) !== spec) {
88+
throw new Error(
89+
`Selected plugin ${id} requires an exact dependency pin: ${name}@${spec}`,
90+
);
91+
}
92+
}
93+
for (const existing of [packageJson.dependencies, packageJson.optionalDependencies]) {
94+
validateBundledPackageDependencyAlignment({
95+
bundledDependencies: dependencies,
96+
bundledPackageLabel: `selected plugin ${id}`,
97+
rootDependencies: { ...dependencies, ...existing },
98+
});
99+
}
100+
packageJson[section] = { ...packageJson[section], ...dependencies };
101+
}
102+
}
103+
// A required dependency must not remain optional when another selected owner needs it.
104+
for (const name of Object.keys(packageJson.dependencies ?? {})) {
105+
delete packageJson.optionalDependencies?.[name];
106+
}
107+
for (const { id, packageJson: metadata } of selected) {
108+
const plugin = metadata as PackageJson;
109+
for (const [name, range] of Object.entries(plugin.peerDependencies ?? {})) {
110+
const version =
111+
name === packageJson.name
112+
? packageJson.version
113+
: (packageJson.dependencies?.[name] ?? packageJson.optionalDependencies?.[name]);
114+
if (
115+
(!version && !plugin.peerDependenciesMeta?.[name]?.optional) ||
116+
(version && !satisfies(version, range))
117+
) {
118+
throw new Error(`Selected plugin ${id} requires peer ${name}@${range} in the distribution`);
119+
}
120+
}
121+
}
122+
const exclusions = new Set(selected.map(({ id }) => `!dist/extensions/${id}/**`));
123+
packageJson.files = packageJson.files.filter((entry) => !exclusions.has(entry));
124+
const snapshots = await Promise.all(
125+
["package.json", PACKAGE_DIST_INVENTORY_RELATIVE_PATH, PACKAGE_INSTALL_GUARD_RELATIVE_PATH].map(
126+
async (relativePath) => {
127+
const target = path.join(sourceDir, relativePath);
128+
const bytes = await fs.readFile(target).catch((error: unknown) => {
129+
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) {
130+
throw error;
131+
}
132+
return null;
133+
});
134+
return { target, bytes };
135+
},
136+
),
137+
);
138+
const cleanup = async (preparationFailure?: { cause: unknown }) => {
139+
const results = await Promise.allSettled(
140+
snapshots.map(({ target, bytes }) =>
141+
bytes === null ? fs.rm(target, { force: true }) : fs.writeFile(target, bytes),
142+
),
143+
);
144+
const failures = results.filter((result) => result.status === "rejected");
145+
if (failures.length) {
146+
throw new AggregateError(
147+
[
148+
...(preparationFailure ? [preparationFailure.cause] : []),
149+
...failures.map((result) => result.reason),
150+
],
151+
"Selected plugin package cleanup failed",
152+
preparationFailure,
153+
);
154+
}
155+
};
156+
try {
157+
await fs.writeFile(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`);
158+
// Inventory must see the custom manifest before pack, or postinstall would prune the plugin.
159+
const { writePackageDistInventoryForPublish } = await import("./package-dist-inventory.ts");
160+
await writePackageDistInventoryForPublish(sourceDir);
161+
return cleanup;
162+
} catch (error) {
163+
await cleanup({ cause: error });
164+
throw error;
165+
}
166+
}

0 commit comments

Comments
 (0)