File size: 6,835 Bytes
fb4d8fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env node
import process from "node:process";
import type { GatewayLockHandle } from "../infra/gateway-lock.js";

declare const __OPENCLAW_VERSION__: string | undefined;

const BUNDLED_VERSION =
  (typeof __OPENCLAW_VERSION__ === "string" && __OPENCLAW_VERSION__) ||
  process.env.OPENCLAW_BUNDLED_VERSION ||
  "0.0.0";

function argValue(args: string[], flag: string): string | undefined {
  const idx = args.indexOf(flag);
  if (idx < 0) {
    return undefined;
  }
  const value = args[idx + 1];
  return value && !value.startsWith("-") ? value : undefined;
}

function hasFlag(args: string[], flag: string): boolean {
  return args.includes(flag);
}

const args = process.argv.slice(2);

type GatewayWsLogStyle = "auto" | "full" | "compact";

async function main() {
  if (hasFlag(args, "--version") || hasFlag(args, "-v")) {
    // Match `openclaw --version` behavior for Swift env/version checks.
    // Keep output a single line.
    console.log(BUNDLED_VERSION);
    process.exit(0);
  }

  // Bun runtime ships a global `Long` that protobufjs detects, but it does not
  // implement the long.js API that Baileys/WAProto expects (fromBits, ...).
  // Ensure we use long.js so the embedded gateway doesn't crash at startup.
  if (typeof process.versions.bun === "string") {
    const mod = await import("long");
    const Long = (mod as unknown as { default?: unknown }).default ?? mod;
    (globalThis as unknown as { Long?: unknown }).Long = Long;
  }

  const [
    { loadConfig },
    { startGatewayServer },
    { setGatewayWsLogStyle },
    { setVerbose },
    { acquireGatewayLock, GatewayLockError },
    { consumeGatewaySigusr1RestartAuthorization, isGatewaySigusr1RestartExternallyAllowed },
    { defaultRuntime },
    { enableConsoleCapture, setConsoleTimestampPrefix },
  ] = await Promise.all([
    import("../config/config.js"),
    import("../gateway/server.js"),
    import("../gateway/ws-logging.js"),
    import("../globals.js"),
    import("../infra/gateway-lock.js"),
    import("../infra/restart.js"),
    import("../runtime.js"),
    import("../logging.js"),
  ] as const);

  enableConsoleCapture();
  setConsoleTimestampPrefix(true);
  setVerbose(hasFlag(args, "--verbose"));

  const wsLogRaw = hasFlag(args, "--compact") ? "compact" : argValue(args, "--ws-log");
  const wsLogStyle: GatewayWsLogStyle =
    wsLogRaw === "compact" ? "compact" : wsLogRaw === "full" ? "full" : "auto";
  setGatewayWsLogStyle(wsLogStyle);

  const cfg = loadConfig();
  const portRaw =
    argValue(args, "--port") ??
    process.env.OPENCLAW_GATEWAY_PORT ??
    process.env.CLAWDBOT_GATEWAY_PORT ??
    (typeof cfg.gateway?.port === "number" ? String(cfg.gateway.port) : "") ??
    "18789";
  const port = Number.parseInt(portRaw, 10);
  if (Number.isNaN(port) || port <= 0) {
    defaultRuntime.error(`Invalid --port (${portRaw})`);
    process.exit(1);
  }

  const bindRaw =
    argValue(args, "--bind") ??
    process.env.OPENCLAW_GATEWAY_BIND ??
    process.env.CLAWDBOT_GATEWAY_BIND ??
    cfg.gateway?.bind ??
    "loopback";
  const bind =
    bindRaw === "loopback" ||
    bindRaw === "lan" ||
    bindRaw === "auto" ||
    bindRaw === "custom" ||
    bindRaw === "tailnet"
      ? bindRaw
      : null;
  if (!bind) {
    defaultRuntime.error('Invalid --bind (use "loopback", "lan", "tailnet", "auto", or "custom")');
    process.exit(1);
  }

  const token = argValue(args, "--token");
  if (token) {
    process.env.OPENCLAW_GATEWAY_TOKEN = token;
  }

  let server: Awaited<ReturnType<typeof startGatewayServer>> | null = null;
  let lock: GatewayLockHandle | null = null;
  let shuttingDown = false;
  let forceExitTimer: ReturnType<typeof setTimeout> | null = null;
  let restartResolver: (() => void) | null = null;

  const cleanupSignals = () => {
    process.removeListener("SIGTERM", onSigterm);
    process.removeListener("SIGINT", onSigint);
    process.removeListener("SIGUSR1", onSigusr1);
  };

  const request = (action: "stop" | "restart", signal: string) => {
    if (shuttingDown) {
      defaultRuntime.log(`gateway: received ${signal} during shutdown; ignoring`);
      return;
    }
    shuttingDown = true;
    const isRestart = action === "restart";
    defaultRuntime.log(
      `gateway: received ${signal}; ${isRestart ? "restarting" : "shutting down"}`,
    );

    forceExitTimer = setTimeout(() => {
      defaultRuntime.error("gateway: shutdown timed out; exiting without full cleanup");
      cleanupSignals();
      process.exit(0);
    }, 5000);

    void (async () => {
      try {
        await server?.close({
          reason: isRestart ? "gateway restarting" : "gateway stopping",
          restartExpectedMs: isRestart ? 1500 : null,
        });
      } catch (err) {
        defaultRuntime.error(`gateway: shutdown error: ${String(err)}`);
      } finally {
        if (forceExitTimer) {
          clearTimeout(forceExitTimer);
        }
        server = null;
        if (isRestart) {
          shuttingDown = false;
          restartResolver?.();
        } else {
          cleanupSignals();
          process.exit(0);
        }
      }
    })();
  };

  const onSigterm = () => {
    defaultRuntime.log("gateway: signal SIGTERM received");
    request("stop", "SIGTERM");
  };
  const onSigint = () => {
    defaultRuntime.log("gateway: signal SIGINT received");
    request("stop", "SIGINT");
  };
  const onSigusr1 = () => {
    defaultRuntime.log("gateway: signal SIGUSR1 received");
    const authorized = consumeGatewaySigusr1RestartAuthorization();
    if (!authorized && !isGatewaySigusr1RestartExternallyAllowed()) {
      defaultRuntime.log(
        "gateway: SIGUSR1 restart ignored (not authorized; enable commands.restart or use gateway tool).",
      );
      return;
    }
    request("restart", "SIGUSR1");
  };

  process.on("SIGTERM", onSigterm);
  process.on("SIGINT", onSigint);
  process.on("SIGUSR1", onSigusr1);

  try {
    try {
      lock = await acquireGatewayLock();
    } catch (err) {
      if (err instanceof GatewayLockError) {
        defaultRuntime.error(`Gateway start blocked: ${err.message}`);
        process.exit(1);
      }
      throw err;
    }
    // eslint-disable-next-line no-constant-condition
    while (true) {
      try {
        server = await startGatewayServer(port, { bind });
      } catch (err) {
        cleanupSignals();
        defaultRuntime.error(`Gateway failed to start: ${String(err)}`);
        process.exit(1);
      }
      await new Promise<void>((resolve) => {
        restartResolver = resolve;
      });
    }
  } finally {
    await (lock as GatewayLockHandle | null)?.release();
    cleanupSignals();
  }
}

void main().catch((err) => {
  console.error(
    "[openclaw] Gateway daemon failed:",
    err instanceof Error ? (err.stack ?? err.message) : err,
  );
  process.exit(1);
});