File size: 8,835 Bytes
f778c12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Gateway service command registration shared by `gateway` and legacy `daemon` CLIs.
import { Option, type Command } from "commander";
import { isGatewayServiceEnv } from "../../daemon/constants.js";
import { isGatewayExternallySupervised } from "../../infra/gateway-supervision.js";
import { createLazyImportLoader } from "../../shared/lazy-promise.js";
import { inheritOptionFromParent } from "../command-options.js";
import { resolveGatewayRpcOptionsWithLocalPort } from "../gateway-rpc.js";
import type { DaemonInstallOptions, DaemonLifecycleOptions } from "./types.js";

const daemonInstallModuleLoader = createLazyImportLoader(() => import("./install.runtime.js"));
const daemonLifecycleModuleLoader = createLazyImportLoader(() => import("./lifecycle.runtime.js"));
const updateExecutorModuleLoader = createLazyImportLoader(() => import("./update-executor.js"));
const daemonStatusModuleLoader = createLazyImportLoader(() => import("./status.runtime.js"));

function resolveJsonOption(cmdOpts: { json?: boolean }, command?: Command): boolean {
  const parentJson = inheritOptionFromParent<boolean>(command, "json", "cli");
  return Boolean(cmdOpts.json || parentJson);
}

function resolveInstallOptions(
  cmdOpts: DaemonInstallOptions,
  command?: Command,
): DaemonInstallOptions {
  const parentForce = inheritOptionFromParent<boolean>(command, "force");
  const parentPort = inheritOptionFromParent<string>(command, "port");
  const parentToken = inheritOptionFromParent<string>(command, "token");
  const parentAllowUnconfigured = inheritOptionFromParent<boolean>(command, "allowUnconfigured");
  return {
    ...cmdOpts,
    force: Boolean(cmdOpts.force || parentForce),
    port: cmdOpts.port ?? parentPort,
    token: cmdOpts.token ?? parentToken,
    allowUnconfigured: cmdOpts.allowUnconfigured ?? parentAllowUnconfigured,
    json: resolveJsonOption(cmdOpts, command),
  };
}

function resolveRestartOptions(cmdOpts: DaemonLifecycleOptions, command?: Command) {
  const parentForce = inheritOptionFromParent<boolean>(command, "force");
  const force = Boolean(cmdOpts.force || parentForce);
  const safeFromGateway =
    process.platform === "win32" &&
    isGatewayServiceEnv(process.env) &&
    !isGatewayExternallySupervised() &&
    !force &&
    cmdOpts.wait === undefined &&
    !cmdOpts.preserveDefinition &&
    !cmdOpts.skipDeferral;
  return {
    ...cmdOpts,
    force,
    safe: cmdOpts.safe || safeFromGateway,
    json: resolveJsonOption(cmdOpts, command),
  };
}

function resolveStopOptions(cmdOpts: DaemonLifecycleOptions, command?: Command) {
  const parentForce = inheritOptionFromParent<boolean>(command, "force");
  return {
    ...cmdOpts,
    force: Boolean(cmdOpts.force || parentForce),
    json: resolveJsonOption(cmdOpts, command),
  };
}

/** Attach Gateway service status/install/lifecycle subcommands to a parent command. */
export function addGatewayServiceCommands(parent: Command, opts?: { statusDescription?: string }) {
  parent
    .command("status")
    .description(
      opts?.statusDescription ?? "Show gateway service status + probe connectivity/capability",
    )
    .option("--url <url>", "Gateway WebSocket URL (defaults to config/remote/local)")
    .option("--port <port>", "Local Gateway port")
    .option("--token <token>", "Gateway token (if required)")
    .option("--password <password>", "Gateway password (password auth)")
    .option("--timeout <ms>", "Timeout in ms", "10000")
    .option("--no-probe", "Skip RPC probe")
    .option("--require-rpc", "Exit non-zero when the RPC probe fails", false)
    .option("--deep", "Scan system-level services", false)
    .option("--json", "Output JSON", false)
    .action(async (cmdOpts, command) => {
      const { runDaemonStatus } = await daemonStatusModuleLoader.load();
      await runDaemonStatus({
        rpc: resolveGatewayRpcOptionsWithLocalPort(cmdOpts, command),
        probe: Boolean(cmdOpts.probe),
        requireRpc: Boolean(cmdOpts.requireRpc),
        deep: Boolean(cmdOpts.deep),
        json: resolveJsonOption(cmdOpts, command),
      });
    });

  parent
    .command("install")
    .description("Install and start the Gateway service (launchd/systemd/schtasks)")
    .addOption(new Option("--defer-activation", "Updater service-load handoff").hideHelp())
    .option("--port <port>", "Gateway port")
    .option("--runtime <runtime>", "Daemon runtime (node|bun). Default: node")
    .option("--token <token>", "Gateway token (token auth)")
    .option("--wrapper <path>", "Executable wrapper for generated service ProgramArguments")
    .option("--allow-unconfigured", "Allow the service to start without gateway.mode=local")
    .option("--force", "Reinstall if already installed (may restart a running Gateway)", false)
    .option("--json", "Output JSON", false)
    .addOption(
      new Option("--update-executor <mode>", "Private update executor")
        .choices(["check", "run"])
        .hideHelp(),
    )
    .action(async (cmdOpts, command) => {
      const invoke = async () => {
        const { runDaemonInstall } = await daemonInstallModuleLoader.load();
        await runDaemonInstall(resolveInstallOptions(cmdOpts, command));
      };
      if (cmdOpts.updateExecutor === undefined) {
        await invoke();
      } else {
        const { runGatewayServiceUpdateCommand } = await updateExecutorModuleLoader.load();
        await runGatewayServiceUpdateCommand(cmdOpts.updateExecutor, "install", invoke);
      }
    });

  parent
    .command("uninstall")
    .description("Uninstall the Gateway service (launchd/systemd/schtasks)")
    .option("--json", "Output JSON", false)
    .action(async (cmdOpts, command) => {
      const { runDaemonUninstall } = await daemonLifecycleModuleLoader.load();
      await runDaemonUninstall({ ...cmdOpts, json: resolveJsonOption(cmdOpts, command) });
    });

  parent
    .command("start")
    .description("Start the Gateway service (launchd/systemd/schtasks)")
    .option("--json", "Output JSON", false)
    .action(async (cmdOpts, command) => {
      const { runDaemonStart } = await daemonLifecycleModuleLoader.load();
      await runDaemonStart({ ...cmdOpts, json: resolveJsonOption(cmdOpts, command) });
    });

  parent
    .command("stop")
    .addOption(
      new Option("--update-executor <mode>", "Private update executor")
        .choices(["check", "run"])
        .hideHelp(),
    )
    .description("Stop the Gateway service (launchd/systemd/schtasks)")
    .option("--force", "Allow stop from a non-interactive shell", false)
    .option("--json", "Output JSON", false)
    .option(
      "--disable",
      "Persistently suppress KeepAlive/RunAtLoad so the gateway does not respawn until next start (launchd only)",
      false,
    )
    .action(async (cmdOpts, command) => {
      const invoke = async () => {
        const { runDaemonStop } = await daemonLifecycleModuleLoader.load();
        await runDaemonStop(resolveStopOptions(cmdOpts, command));
      };
      if (cmdOpts.updateExecutor === undefined) {
        await invoke();
      } else {
        const { runGatewayServiceUpdateCommand } = await updateExecutorModuleLoader.load();
        await runGatewayServiceUpdateCommand(cmdOpts.updateExecutor, "stop", invoke);
      }
    });

  parent
    .command("restart")
    .addOption(
      new Option("--update-executor <mode>", "Private update executor")
        .choices(["check", "run"])
        .hideHelp(),
    )
    .description("Restart the Gateway service (launchd/systemd/schtasks)")
    .option("--preserve-definition", "Keep the native service definition", false)
    .option("--force", "Restart immediately without waiting for active gateway work", false)
    .option(
      "--safe",
      "Request an OpenClaw-aware restart after active work drains " +
        "(bounded wait; may force after the timeout expires)",
      false,
    )
    .option(
      "--skip-deferral",
      "Bypass the safe-restart active-work deferral gate; close-stage reply drain still applies; requires --safe",
      false,
    )
    .option(
      "--wait <duration>",
      "Wait duration before restart (ms, 10s, 5m; 0 waits indefinitely). " +
        "For non-safe restarts (plain restart); not compatible with --force or --safe",
    )
    .option("--json", "Output JSON", false)
    .action(async (cmdOpts, command) => {
      const invoke = async () => {
        const { runDaemonRestart } = await daemonLifecycleModuleLoader.load();
        await runDaemonRestart(resolveRestartOptions(cmdOpts, command));
      };
      if (cmdOpts.updateExecutor === undefined) {
        await invoke();
      } else {
        const { runGatewayServiceUpdateCommand } = await updateExecutorModuleLoader.load();
        await runGatewayServiceUpdateCommand(cmdOpts.updateExecutor, "restart", invoke);
      }
    });
}