乐于分享
好东西不私藏

OpenClaw v2026.5.12源码系列01-GatewayServer是如何启动起来的

OpenClaw v2026.5.12源码系列01-GatewayServer是如何启动起来的

1.前言

本文将对OpenClaw v2026.5.12如何启动GatewayServer做出源码分析。

2.如何启动GatewayServer

1.从位于根源码根目录的package.json,找到openclaw命令背后的执行文件openclaw.mjs

   -- package.json   ...   "bin": {	  "openclaw""openclaw.mjs"   },   ...

2.openclaw.mjs import了 /dist/entry.js.  /dist/entry.js是编译后的js文件,编译前的是src/entry.ts文件。

    -- openclaw.mjs    ...    if (await tryImport("./dist/entry.js")) {         // OK    }     ...

3.entry.ts文件在runMainOrRootHelp函数中调用了src/cli/run-main.ts的runCli函数

   -- src/entry.ts   async function runMainOrRootHelp(argv: string[]): Promise<void> {   	  ...   	  try {   	    const { runCli } = await gatewayEntryStartupTrace.measure(   	      "run-main-import",   	      () => import("./cli/run-main.js"),   	    );   	    await runCli(argv);   	  } catch (error) {   	  ...   	  }    }

4.run-main.ts中的runCli函数调用了tryRunGatewayRunFastPath函数。tryRunGatewayRunFastPath函数中调用了src/cli/gateway-cli/run.ts文件的addGatewayRunCommand函数。

   -- src/cli/run-main.ts   export async function runCli(argvstring[] = process.argv) {	  ...	  if (!bootstrapProxyBeforeFastPath &&          (await tryRunGatewayRunFastPath(normalizedArgv, startupTrace))		  ) {		      return;	  }	   if (!isHelpOrVersionInvocation) {	      await bootstrapCliProxyCaptureAndDispatcher(startupTrace, {	        ensureDispatcher: shouldUseCliEnvProxy,	      });	   }	    if (	      bootstrapProxyBeforeFastPath &&	      (await tryRunGatewayRunFastPath(normalizedArgv, startupTrace))	    ) {	      return;	    }	    ...   }   async function tryRunGatewayRunFastPath(		  argvstring[],		  startupTraceReturnType<typeof createGatewayCliMainStartupTrace>,   ): Promise<boolean> {		   ...		   const [			   ...			    { addGatewayRunCommand },			    ...		  ] = await startupTrace.measure("gateway-run-imports"() =>			    Promise.all([...			      import("./gateway-cli/run.js"),			    ...			    ]),		  );		  ...		  const gateway = addGatewayRunCommand(		    program.command("gateway").description("Run, inspect, and query the WebSocket Gateway"),		  );		  addGatewayRunCommand(		    gateway.command("run").description("Run the WebSocket Gateway (foreground)"),		  );	 	...   }

5.run.ts的addGatewayRunCommand函数调用了runGatewayCommand函数。runGatewayCommand函数调用了src/gateway/server.ts的startGatewayServer函数

   --src/cli/gateway-cli/run.ts   export function addGatewayRunCommand(cmd: Command): Command {	  return cmd	  ...	  .action(async (opts, command) => {	     await runGatewayCommand(resolveGatewayRunOptions(opts, command));	  });   }   async function runGatewayCommand(opts: GatewayRunOpts) {...const { startGatewayServer } = await startupTrace.measure("cli.server-import"() =>withProgress(			  { label"Loading gateway modules…"indeterminatetrue },			  async () => import("../../gateway/server.js"),),);...const startLoop = async () =>await runGatewayLoop({			  runtime: defaultRuntime,			  lockPort: port,			  healthHost,			  startasync ({ startupStartedAt } = {}) => {const startupConfigSnapshotReadForThisStart = startupConfigSnapshotReadForNextStart;				startupConfigSnapshotReadForNextStart = undefined;return await startGatewayServer(port, {				  bind,				  auth: authOverride,				  tailscale: tailscaleOverride,				  startupStartedAt,				  ...(startupConfigSnapshotReadForThisStart? { startupConfigSnapshotRead: startupConfigSnapshotReadForThisStart }: {}),});			  },});...   }

6.server.ts的startGatewayServer函数调用了src/gateway/server.impl.ts的startGatewayServer函数。

--src/gateway/server.tsexport async function startGatewayServer(	  ...args: Parameters<typeof import("./server.impl.js").startGatewayServer>): ReturnType<typeof import("./server.impl.js").startGatewayServer> {	  const mod = await loadServerImpl();	  return await mod.startGatewayServer(...args);}

7.server.impl.ts的startGatewayServer函数src/gateway/server-runtime-state.ts的createGatewayRuntimeState函数。

   --src/gateway/server.impl.ts   ...   const {    ...   } = await startupTrace.measure("runtime.state"() =>    createGatewayRuntimeState({     ...    }),  );  ...

8.server-runtime-state.ts的createGatewayRuntimeState函数调用src/gateway//server-http.ts的createGatewayHttpServer函数创建GatewayHttpServer,调用http-listen.ts的listenGatewayHttpServer函数进行监听。

   --src/gateway/server-runtime-state.ts   export async function createGatewayRuntimeState(params: {	 ...	 const httpServer = createGatewayHttpServer({...	 });	 ...	 await listenGatewayHttpServer({				  httpServer: server,				  bindHost: host,				  port: params.port,	 });	 ...   }

3.启动GatewayServer的调用链总结

    package.json    → openclaw.mjs      → src/entry.ts        → src/cli/run-main.ts  //runCli() tryRunGatewayRunFastPath()          → src/cli/gateway-cli/run.ts   //addGatewayRunCommand()  runGatewayCommand()             → src/gateway/server.ts   //startGatewayServer()                  → src/gateway/server.impl.ts  //startGatewayServer()                      →  src/gateway/server-runtime-state.ts  //createGatewayRuntimeState()                            →  src/gateway//server-http.ts  //createGatewayHttpServer()                                  →  src/gateway/server/http-listen.ts  //listenGatewayHttpServer()