File size: 11,895 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
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
// Cron simple command registration: remove, toggle, show, runs, and run-now.
import {
  resolvePositiveTimerTimeoutMs,
  resolveTimerTimeoutMs,
} from "@openclaw/normalization-core/number-coercion";
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
import { Option, type Command } from "commander";
import { resolveCronCompletionStatus } from "../../cron/completion-status.js";
import type { CronRunLogEntry } from "../../cron/run-log-types.js";
import { defaultRuntime } from "../../runtime.js";
import { sleep } from "../../utils/sleep.js";
import type { GatewayRpcOpts } from "../gateway-rpc.js";
import { addGatewayClientOptions, callGatewayFromCli } from "../gateway-rpc.js";
import { exitCliAfterOutput } from "../one-shot-exit.js";
import { parseDurationMs } from "../parse-duration.js";
import { parseTimeoutMs } from "../parse-timeout.js";
import { CronCliError } from "./cron-cli-error.js";
import { findCronJobByIdOrName } from "./list-jobs.js";
import { createCronOutputCommand } from "./output-mode.js";
import {
  enrichCronJsonWithStatus,
  formatCronLookupMiss,
  handleCronCliError,
  parseCronIntegerOption,
  printCronJson,
  printCronShow,
  requireCronJobId,
  warnIfCronSchedulerDisabled,
} from "./shared.js";

const CRON_RUN_WAIT_TIMEOUT_DEFAULT = "10m";
const CRON_RUN_WAIT_POLL_INTERVAL_DEFAULT = "2s";

type CronRunCommandResult = {
  ok?: boolean;
  ran?: boolean;
  enqueued?: boolean;
  runId?: string;
};

function parseCronRunWaitDuration(raw: unknown): number {
  const input =
    typeof raw === "string" || typeof raw === "number" || typeof raw === "bigint"
      ? String(raw)
      : "";
  let durationMs: number;
  try {
    durationMs = parseDurationMs(input, { defaultUnit: "ms" });
  } catch (error) {
    if (error instanceof Error) {
      throw new CronCliError(error);
    }
    throw error;
  }
  return resolveTimerTimeoutMs(durationMs, 0, 0);
}

function parseCronRunPollInterval(raw: unknown): number {
  const durationMs = parseCronRunWaitDuration(raw);
  if (durationMs <= 0) {
    throw new CronCliError("invalid --poll-interval");
  }
  return resolvePositiveTimerTimeoutMs(durationMs, 2_000);
}

async function waitForCronRunCompletion(params: {
  opts: GatewayRpcOpts;
  jobId: string;
  runId: string;
  timeoutMs: number;
  pollIntervalMs: number;
}): Promise<CronRunLogEntry> {
  // Poll the task ledger rather than cron.run because completion state is written asynchronously.
  const startedAt = performance.now();
  let hasPolled = false;
  for (;;) {
    const elapsedBeforePollMs = Math.floor(performance.now() - startedAt);
    if (hasPolled && elapsedBeforePollMs >= params.timeoutMs) {
      throw new CronCliError(`timed out waiting for cron run ${params.runId}`);
    }
    const remainingMs = Math.max(1, params.timeoutMs - elapsedBeforePollMs);
    const configuredTimeoutMs = parseTimeoutMs(params.opts.timeout);
    const pollTimeoutMs =
      configuredTimeoutMs === undefined ? remainingMs : Math.min(configuredTimeoutMs, remainingMs);
    hasPolled = true;
    // History reads share the wait deadline, but enqueue keeps its own RPC
    // timeout and a zero-duration wait still gets one immediate ledger poll.
    const pollOpts = { ...params.opts, timeout: String(pollTimeoutMs) };
    const page = (await callGatewayFromCli("cron.runs", pollOpts, {
      id: params.jobId,
      runId: params.runId,
      limit: 1,
    })) as { entries?: CronRunLogEntry[] };
    const entry = page.entries?.[0];
    if (entry?.status === "ok" || entry?.status === "error" || entry?.status === "skipped") {
      return entry;
    }
    const elapsedMs = Math.floor(performance.now() - startedAt);
    if (elapsedMs >= params.timeoutMs) {
      throw new CronCliError(`timed out waiting for cron run ${params.runId}`);
    }
    await sleep(Math.min(params.pollIntervalMs, params.timeoutMs - elapsedMs));
  }
}

function registerCronToggleCommand(params: {
  cron: Command;
  name: "enable" | "disable";
  description: string;
  enabled: boolean;
}) {
  addGatewayClientOptions(
    createCronOutputCommand(params.cron, params.name)
      .description(params.description)
      .argument("<id>", "Job id")
      .action(async (id, opts) => {
        try {
          const res = await callGatewayFromCli("cron.update", opts, {
            id: requireCronJobId(id),
            patch: { enabled: params.enabled },
          });
          printCronJson(res);
          if (!params.enabled && process.stderr.isTTY) {
            process.stderr.write(
              `Note: 'openclaw cron list' hides disabled jobs by default. Use 'openclaw cron list --all' to see this job, or 'openclaw cron enable <id>' to re-enable it.\n`,
            );
          }
          await warnIfCronSchedulerDisabled(opts);
        } catch (err) {
          handleCronCliError(err);
        }
      }),
  );
}

export function registerCronSimpleCommands(cron: Command) {
  addGatewayClientOptions(
    createCronOutputCommand(cron, "rm")
      .description("Remove an automation")
      .argument("<id>", "Job id")
      .action(async (id, opts) => {
        try {
          const res = await callGatewayFromCli("cron.remove", opts, { id: requireCronJobId(id) });
          printCronJson(res);
        } catch (err) {
          handleCronCliError(err);
        }
      }),
  );

  registerCronToggleCommand({
    cron,
    name: "enable",
    description: "Enable an automation",
    enabled: true,
  });
  registerCronToggleCommand({
    cron,
    name: "disable",
    description: "Disable an automation",
    enabled: false,
  });

  addGatewayClientOptions(
    createCronOutputCommand(cron, "get")
      .description("Get an automation as JSON")
      .argument("<id>", "Job id")
      .action(async (id, opts) => {
        try {
          const res = await callGatewayFromCli("cron.get", opts, { id: requireCronJobId(id) });
          printCronJson(res);
        } catch (err) {
          handleCronCliError(err);
        }
      }),
  );

  addGatewayClientOptions(
    cron
      .command("show")
      .description("Show an automation")
      .argument("<id>", "Job id or exact name")
      .option("--json", "Output JSON", false)
      .action(async (idArg, opts) => {
        try {
          const id = requireCronJobId(idArg);
          const { job, deliveryPreview } = await findCronJobByIdOrName(opts, id, {
            includeDeliveryPreview: !opts.json,
          });
          if (!job) {
            throw new CronCliError(formatCronLookupMiss(id));
          }
          if (opts.json) {
            printCronJson(enrichCronJsonWithStatus(job));
            return;
          }
          printCronShow(job, defaultRuntime, { deliveryPreview });
        } catch (err) {
          handleCronCliError(err);
        }
      }),
  );

  addGatewayClientOptions(
    createCronOutputCommand(cron, "runs")
      .description("Show automation run history")
      .argument("[id]", "Job id")
      .option("--id <id>", "Job id (alternative to positional argument)")
      .option("--run-id <runId>", "Filter by cron run id")
      .addOption(
        new Option("--status <status>", "Filter by run status").choices([
          "all",
          "ok",
          "error",
          "skipped",
        ]),
      )
      .addOption(
        new Option("--delivery-status <status>", "Filter by delivery status").choices([
          "delivered",
          "not-delivered",
          "unknown",
          "not-requested",
        ]),
      )
      .option("--query <text>", "Filter by run summary or error text")
      .option("--offset <n>", "Entries to skip before returning results")
      .addOption(new Option("--sort <direction>", "Sort by run time").choices(["asc", "desc"]))
      .option("--limit <n>", "Max entries (default 50)", "50")
      .action(async (idArg, opts) => {
        try {
          const argId = normalizeOptionalString(idArg);
          const flagId = normalizeOptionalString(opts.id);
          if (argId && flagId && argId !== flagId) {
            throw new CronCliError(
              `Conflicting job ids: positional "${argId}" and --id "${flagId}".`,
            );
          }
          const id = requireCronJobId(argId ?? flagId, "Pass it positionally or with --id.");
          const limit = parseCronIntegerOption(opts.limit ?? "50", "--limit");
          const offset = parseCronIntegerOption(opts.offset, "--offset", "non-negative");
          if (typeof opts.runId === "string" && !opts.runId.trim()) {
            throw new CronCliError("--run-id must not be blank");
          }
          const res = await callGatewayFromCli("cron.runs", opts, {
            id,
            ...(typeof opts.runId === "string" && opts.runId.trim() ? { runId: opts.runId } : {}),
            ...(typeof opts.status === "string" ? { status: opts.status } : {}),
            ...(typeof opts.deliveryStatus === "string"
              ? { deliveryStatus: opts.deliveryStatus }
              : {}),
            ...(typeof opts.query === "string" ? { query: opts.query } : {}),
            ...(offset !== undefined ? { offset } : {}),
            ...(typeof opts.sort === "string" ? { sortDir: opts.sort } : {}),
            limit,
          });
          printCronJson(res);
        } catch (err) {
          handleCronCliError(err);
        }
      }),
  );

  addGatewayClientOptions(
    createCronOutputCommand(cron, "run")
      .description("Run an automation now (debug)")
      .argument("<id>", "Job id")
      .option("--due", "Run only when due (default behavior in older versions)", false)
      .option("--wait", "Wait for the queued run to finish", false)
      .option(
        "--wait-timeout <duration>",
        "Maximum time to wait for --wait",
        CRON_RUN_WAIT_TIMEOUT_DEFAULT,
      )
      .option(
        "--poll-interval <duration>",
        "Polling interval for --wait",
        CRON_RUN_WAIT_POLL_INTERVAL_DEFAULT,
      )
      .action(async (idArg, opts, command) => {
        try {
          const id = requireCronJobId(idArg);
          let waitTimeoutMs = 0;
          let pollIntervalMs = 0;
          if (opts.wait) {
            waitTimeoutMs = parseCronRunWaitDuration(opts.waitTimeout);
            pollIntervalMs = parseCronRunPollInterval(opts.pollInterval);
          }
          if (command.getOptionValueSource("timeout") === "default") {
            opts.timeout = "600000";
          }
          const res = await callGatewayFromCli("cron.run", opts, {
            id,
            mode: opts.due ? "due" : "force",
          });
          const result = res as CronRunCommandResult | undefined;
          if (opts.wait && result?.ok && result.enqueued) {
            if (!result.runId) {
              throw new Error("cron run did not return a runId to wait for");
            }
            const run = await waitForCronRunCompletion({
              opts,
              jobId: id,
              runId: result.runId,
              timeoutMs: waitTimeoutMs,
              pollIntervalMs,
            });
            const completionStatus =
              run.completionStatus ??
              resolveCronCompletionStatus({
                status: run.status,
                delivered: run.delivered,
                deliveryStatus: run.deliveryStatus,
              });
            const completedRun = { ...run, completionStatus };
            printCronJson({
              ...res,
              completed: true,
              status: run.status,
              completionStatus,
              run: completedRun,
            });
            exitCliAfterOutput(defaultRuntime, completionStatus === "succeeded" ? 0 : 1);
          }
          printCronJson(res);
          exitCliAfterOutput(defaultRuntime, result?.ok && (result.ran || result.enqueued) ? 0 : 1);
        } catch (err) {
          handleCronCliError(err);
        }
      }),
  );
}