UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,119 lines • 59.8 kB
import { c as normalizeOptionalLowercaseString, l as normalizeOptionalString, m as readNonBlankString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { D as parseStrictPositiveInteger, E as parseStrictNonNegativeInteger, R as resolveTimerTimeoutMs } from "./number-coercion-D6u-4YD8.mjs";
import { t as expectDefined } from "./expect-DDakjvvQ.mjs";
import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs";
import { r as isErrno } from "./errno-DFcoqIT9.mjs";
import { o as getAsyncWorkSignal } from "./async-work-scope-BXagjUap.mjs";
import { p as sanitizeAgentId } from "./session-key-CqAyZeVk.mjs";
import { n as resolveCronCompletionStatus } from "./completion-status-yI78qGE_.mjs";
import { r as THINKING_LEVELS_HELP } from "./thinking.shared-jmDGV33r.mjs";
import { t as parseDurationMs } from "./parse-duration-D6UJm52I.mjs";
import { r as theme } from "./theme-BOI0xyRZ.mjs";
import { t as exitCliAfterOutput } from "./one-shot-exit-DkbGSQD5.mjs";
import { t as formatDocsLink } from "./links-41lO3DKP.mjs";
import { n as inheritOptionFromParent } from "./command-options-D76J8Wl7.mjs";
import { n as callGatewayFromCli, t as addGatewayClientOptions } from "./gateway-rpc-CxUN2f1a.mjs";
import { t as assertCronActiveHours } from "./active-hours-DyXD6x9W.mjs";
import { t as normalizeHttpWebhookUrl } from "./webhook-url-hdHTU0IF.mjs";
import { t as CRON_JOB_SCRATCH_MAX_BYTES } from "./scratch-contract-COS3OFt4.mjs";
import { r as isValidCronExpression } from "./schedule-DAqfX_yg.mjs";
import { t as readByteStreamWithLimit } from "./read-byte-stream-with-limit-BjmaH2Xs.mjs";
import { n as createCronOutputCommand, r as isCronMachineOutput, t as CRON_GATEWAY_OPTION_NAMES } from "./output-mode-BtF1_08v.mjs";
import { t as parseTimeoutMs } from "./parse-timeout-qqSdJSy9.mjs";
import { t as collectOption } from "./helpers-Cxs4nwgv.mjs";
import { t as applyParentDefaultHelpAction } from "./parent-default-help-BZo1QRJR.mjs";
import { n as setCommandJsonMode } from "./json-mode-DF5JGxtm.mjs";
import { C as parsePositiveCronDurationMs, D as requireCronJobId, E as printCronShow, O as warnIfCronSchedulerDisabled, S as parseCronTimezoneOption, T as printCronList, _ as parseCronStaggerMs, a as assertCronTimeoutSupported, b as parseCronStringOption, c as enrichCronJsonWithStatus, d as handleCronCliError, f as parseAt, g as parseCronNoOutputTimeoutOption, h as parseCronIntegerOption, i as assertCronCliJobSpec, k as CronCliError, l as formatCronLookupMiss, m as parseCronCommandEnv, n as isUnknownCronGetMethodError, o as callCronReadFromCli, p as parseCronCommandArgv, r as listCronJobsFromGateway, s as coerceCronDeliveryPreviews, t as findCronJobByIdOrName, u as getCronChannelOptions, v as parseCronStreamCommandArgv, w as printCronJson, x as parseCronThinkingOption, y as parseCronStringList } from "./list-jobs-B1tD7qNd.mjs";
import { createReadStream } from "node:fs";
import { setTimeout } from "node:timers/promises";
import { Option } from "commander";
//#region src/cli/cron-cli/register.cron-options.ts
function registerCronMutationOptions(e, t) {
	const n = t === "add";
	return e.option("--name <name>", "Job name").option("--display-name <name>", "Human-readable job label").option("--description <text>", "Job description").option("--delete-after-run", "Delete one-shot after successful completion (confirmed/no delivery, intentional silence, or best effort); failed/unknown required delivery retains it disabled", false).option("--keep-after-run", "Keep one-shot job after it succeeds", false).option("--agent <id>", "Agent id for this job").option("--session <target>", "Session target (main|isolated|current|session:<id>)").option("--session-key <key>", "Session key for job routing").option("--wake <mode>", "Wake mode (now|next-heartbeat)", n ? "now" : void 0).option("--at <when>", "One-shot time (ISO, offset-less uses --tz) or duration like 20m").option("--every <duration>", "Interval duration (e.g. 10m, 1h)").option("--pacing-min <duration>", "Minimum delay for a dynamic next check").option("--pacing-max <duration>", "Maximum delay for a dynamic next check").option("--active-hours-start <HH:MM>", "Execution window start (inclusive)").option("--active-hours-end <HH:MM>", "Execution window end (exclusive; 24:00 allowed)").option("--active-hours-timezone <zone>", "Execution window timezone (IANA|user|local)").option("--idle-only", "Yield scheduled execution to foreground work").option("--no-idle-only", "Do not require an idle agent").option("--cron <expr>", "Cron expression (5-field or 6-field with seconds)").option("--on-exit <shell>", "Fire once when the watched command exits").option("--on-exit-cwd <path>", "Working directory for the --on-exit watched command").option("--stream-command <json>", "Stream source argv as a JSON array of strings").option("--stream-cwd <path>", "Working directory for the stream source").option("--stream-mode <mode>", "Stream line selection mode (line|match)").option("--stream-match <regex>", "Regex source required for stream match mode").option("--stream-batch-ms <n>", "Quiet-window batch delay in milliseconds").option("--stream-max-batch-bytes <n>", "Maximum UTF-8 bytes per stream batch").option("--tz <iana>", "Timezone for cron expressions (IANA; cron default: Gateway host local timezone)", n ? "" : void 0).option("--stagger <duration>", "Cron stagger window (e.g. 30s, 5m)").option("--exact", "Disable cron staggering (set stagger to 0)", n ? false : void 0).option("--trigger-script <path|->", "Condition script file, or - for stdin").option("--trigger-once", "Disable after the first successful triggered run", false).option("--system-event <text>", "System event payload (main session)").option("--message <text>", "Agent message payload").option("--skip-if-scratch-empty", "Skip agent turns with present, empty scratch (missing scratch still runs)").option("--no-skip-if-scratch-empty", "Run agent turns even with empty scratch").option("--include-reasoning", "Include reasoning in agent job delivery").option("--no-include-reasoning", "Keep reasoning out of agent job delivery").option("--script <file|->", "Headless script payload file, or - for stdin").option("--script-timeout-seconds <n>", "Script wall-clock timeout seconds").option("--script-tool-budget <n>", "Maximum script tool calls").option("--command <shell>", "Command payload run as sh -lc <shell> on the Gateway").option("--command-argv <json>", "Command payload argv as JSON array of strings").option("--command-cwd <path>", "Working directory for command payloads").option("--command-env <KEY=VALUE>", "Environment override for command payloads (repeatable)", collectOption).option("--command-input <text>", "stdin for command payloads").option("--thinking <level>", `Thinking level for agent jobs (${THINKING_LEVELS_HELP})`).option("--model <model>", "Model override for agent jobs (provider/model or alias)").option("--fallbacks <list>", "Fallback model list for agent jobs").option("--timeout-seconds <n>", "Timeout seconds for agent or command jobs (non-negative integer; 0 disables scheduler timeout)").option("--no-output-timeout-seconds <n>", "No-output timeout seconds for command jobs").option("--output-max-bytes <n>", "Maximum captured stdout/stderr bytes for command jobs").option("--light-context", "Use lightweight bootstrap context for agent jobs", n ? false : void 0).option("--tools <list>", "Tool allow-list (e.g. exec,read or exec read; \"\" disables all tools)").option("--announce", "Fallback-deliver final text to a chat", n ? false : void 0).option("--deliver", "Deprecated (use --announce). Fallback-delivers final text to a chat.").option("--no-deliver", "Disable runner fallback delivery").option("--webhook <url>", "POST the finished payload to a webhook URL").option("--delivery-target <target>", "Dynamic delivery target (owner: positively identified owner DM)").option("--direct-policy <policy>", "Direct-message delivery policy (allow|block)").option("--channel <channel>", `Delivery channel (${getCronChannelOptions()})`, n ? "last" : void 0).option("--to <dest>", "Delivery destination (E.164, Telegram chatId, or Discord channel/user)").option("--thread-id <id>", "Telegram forum topic thread id").option("--account <id>", "Channel account id for delivery (multi-account setups)").option("--best-effort-deliver", n ? "Do not fail the job if delivery fails" : "Do not fail job if delivery fails (also implies --announce when used alone)", n ? false : void 0);
}
async function resolveCronExecutionPolicyOptions(e, t) {
	const n = {};
	if (e.clearIdleOnly && typeof e.idleOnly === "boolean") throw new CronCliError("Use --idle-only/--no-idle-only or --clear-idle-only, not both");
	if (e.clearIdleOnly) n.idleOnly = null;
	else if (typeof e.idleOnly === "boolean") n.idleOnly = e.idleOnly;
	const r = [
		e.activeHoursStart,
		e.activeHoursEnd,
		e.activeHoursTimezone
	].some((e) => e !== void 0);
	if (e.clearActiveHours && r) throw new CronCliError("Use --clear-active-hours or active-hours options, not both");
	if (e.clearActiveHours) n.activeHours = null;
	else if (r) {
		const r = t ? (await t()).activeHours : void 0;
		const i = typeof e.activeHoursStart === "string" ? e.activeHoursStart.trim() : r?.start;
		const a = typeof e.activeHoursEnd === "string" ? e.activeHoursEnd.trim() : r?.end;
		const o = typeof e.activeHoursTimezone === "string" ? e.activeHoursTimezone.trim() : r?.timezone;
		if (i === void 0 || a === void 0) throw new CronCliError("A new active window requires --active-hours-start and --active-hours-end");
		const s = {
			start: i,
			end: a,
			...o !== void 0 ? { timezone: o } : {}
		};
		try {
			assertCronActiveHours(s);
		} catch (e) {
			if (e instanceof Error) throw new CronCliError(e);
			throw e;
		}
		n.activeHours = s;
	}
	return n;
}
function parseCronDeliveryPolicyOptions(e) {
	const t = {};
	if (e.deliveryTarget !== void 0) {
		if (e.clearDeliveryTarget) throw new CronCliError("Use --delivery-target or --clear-delivery-target, not both");
		if (e.deliveryTarget !== "owner") throw new CronCliError("--delivery-target must be owner");
		if (e.to !== void 0 || e.threadId !== void 0 || e.webhook !== void 0) throw new CronCliError("--delivery-target owner cannot be combined with --to, --thread-id, or --webhook");
		t.target = "owner";
	} else if (e.clearDeliveryTarget) t.target = null;
	if (e.directPolicy !== void 0) {
		if (e.clearDirectPolicy) throw new CronCliError("Use --direct-policy or --clear-direct-policy, not both");
		if (e.directPolicy !== "allow" && e.directPolicy !== "block") throw new CronCliError("--direct-policy must be allow or block");
		if (e.webhook !== void 0) throw new CronCliError("--direct-policy requires chat delivery, not --webhook");
		t.directPolicy = e.directPolicy;
	} else if (e.clearDirectPolicy) t.directPolicy = null;
	return t;
}
//#endregion
//#region src/cli/cron-cli/schedule-options.ts
/** Resolve cron creation schedule from either a positional shorthand or explicit flags. */
function resolveCronCreateScheduleFromArgs(e) {
	const t = normalizeOptionalString(e.positionalSchedule);
	const n = normalizeScheduleOptions(e);
	if (t) {
		if (countChosenSchedules(n) > 0) throw new CronCliError("Choose a positional schedule or one of --at, --every, --cron, --on-exit, or --stream-command.");
		n.every = /^every\s+(.+)$/iu.exec(t)?.[1]?.trim() ?? "";
		if (n.every) {
			n.cronExpr = "";
			n.at = "";
		} else {
			const e = t.split(/\s+/u).length;
			n.cronExpr = e === 5 || e === 6 ? t : "";
			n.at = n.cronExpr ? "" : t;
		}
	}
	if (n.onExitCwd && !n.onExitCommand) throw new CronCliError("--on-exit-cwd requires --on-exit.");
	if (countChosenSchedules(n) !== 1) throw new CronCliError("Choose exactly one schedule: --at, --every, --cron, --on-exit, or --stream-command");
	return expectDefined(resolveDirectSchedule(n), "created cron schedule");
}
/** Resolve a cron edit request, allowing at most one direct schedule replacement. */
function resolveCronEditScheduleRequest(e) {
	const t = normalizeScheduleOptions(e);
	const n = countChosenSchedules(t);
	if (hasStreamSchedulePatch(t) && !t.streamCommand) {
		if (t.tz !== void 0 || t.requestedStaggerMs !== void 0) throw new CronCliError("--tz/--stagger/--exact are not valid with stream schedule edits");
		if (n > 0) throw new CronCliError("Choose at most one schedule change");
		return {
			kind: "patch-existing-stream",
			cwd: t.streamCwdSupplied ? t.streamCwd ?? null : void 0,
			mode: t.streamModeSupplied ? t.streamMode : void 0,
			match: t.streamMatchSupplied ? t.streamMatch ?? null : void 0,
			batchMs: t.streamBatchMs,
			maxBatchBytes: t.streamMaxBatchBytes
		};
	}
	if (n > 1) throw new CronCliError("Choose at most one schedule change");
	const r = resolveDirectSchedule(t, { deferStreamMetadataValidation: true });
	if (r) return {
		kind: "direct",
		schedule: r
	};
	if (t.requestedStaggerMs !== void 0 || t.tz !== void 0) return {
		kind: "patch-existing-cron",
		tz: parseCronTimezoneOption(t.tz),
		staggerMs: t.requestedStaggerMs
	};
	return { kind: "none" };
}
/** Apply stream metadata edits without requiring callers to restate the source argv. */
function applyExistingStreamSchedulePatch(e, t) {
	if (e.kind !== "stream") throw new CronCliError("Current job is not a stream schedule; use --stream-command to convert first");
	const n = t.mode ?? e.mode ?? "line";
	const r = t.match === void 0 ? e.match : t.match ?? void 0;
	if (n === "match" && !r) throw new CronCliError("--stream-match is required when --stream-mode=match");
	if (n === "line" && t.match) throw new CronCliError("--stream-match requires --stream-mode=match");
	return {
		...e,
		cwd: t.cwd === void 0 ? e.cwd : t.cwd ?? void 0,
		mode: n,
		match: n === "match" ? r : void 0,
		batchMs: t.batchMs ?? e.batchMs,
		maxBatchBytes: t.maxBatchBytes ?? e.maxBatchBytes
	};
}
/** Validate a newly-created stream schedule after edit metadata has been merged. */
function validateStreamScheduleMetadata(e) {
	const t = e.mode ?? "line";
	if (t === "match" && !e.match) throw new CronCliError("--stream-match is required when --stream-mode=match");
	if (t === "line" && e.match) throw new CronCliError("--stream-match requires --stream-mode=match");
}
/** Apply `--tz`, `--stagger`, or `--exact` metadata changes to an existing cron schedule. */
function applyExistingCronSchedulePatch(e, t) {
	if (e.kind !== "cron") throw new CronCliError("Current job is not a cron schedule; use --cron to convert first");
	return {
		kind: "cron",
		expr: e.expr,
		tz: t.tz ?? e.tz,
		staggerMs: t.staggerMs !== void 0 ? t.staggerMs : e.staggerMs
	};
}
function normalizeScheduleOptions(e) {
	for (const t of [
		e.at,
		e.every,
		e.cron,
		e.onExit
	]) if (typeof t === "string" && !t.trim()) throw new CronCliError("Schedule values must not be blank");
	const t = normalizeOptionalString(e.stagger) ?? "";
	const n = Boolean(e.exact);
	if (t && n) throw new CronCliError("Choose either --stagger or --exact, not both");
	const r = e.streamMode !== void 0;
	const i = normalizeOptionalString(e.streamMode) ?? (r ? void 0 : "line");
	if (i !== "line" && i !== "match") throw new CronCliError("--stream-mode must be line or match");
	const a = i;
	const parsePositiveInteger = (e, t) => {
		const n = (typeof e === "string" || typeof e === "number") && /^\d+$/u.test(String(e).trim()) ? parseStrictPositiveInteger(e) : void 0;
		if (e !== void 0 && n === void 0) throw new CronCliError(`${t} must be a positive integer`);
		return n;
	};
	return {
		at: normalizeOptionalString(e.at) ?? "",
		every: normalizeOptionalString(e.every) ?? "",
		cronExpr: normalizeOptionalString(e.cron) ?? "",
		onExitCommand: readNonBlankString(e.onExit) ?? "",
		onExitCwd: readNonBlankString(e.onExitCwd),
		streamCommand: parseCronStreamCommandArgv(e.streamCommand),
		streamCwd: readNonBlankString(e.streamCwd),
		streamCwdSupplied: e.streamCwd !== void 0,
		streamMode: a,
		streamModeSupplied: r,
		streamMatch: normalizeOptionalString(e.streamMatch),
		streamMatchSupplied: e.streamMatch !== void 0,
		streamBatchMs: parsePositiveInteger(e.streamBatchMs, "--stream-batch-ms"),
		streamMaxBatchBytes: parsePositiveInteger(e.streamMaxBatchBytes, "--stream-max-batch-bytes"),
		tz: normalizeOptionalString(e.tz),
		requestedStaggerMs: parseCronStaggerMs({
			staggerRaw: t,
			useExact: n
		})
	};
}
function hasStreamSchedulePatch(e) {
	return e.streamCwdSupplied || e.streamModeSupplied || e.streamMatchSupplied || e.streamBatchMs !== void 0 || e.streamMaxBatchBytes !== void 0;
}
function countChosenSchedules(e) {
	return [
		e.at,
		e.every,
		e.cronExpr,
		e.onExitCommand,
		e.streamCommand
	].filter(Boolean).length;
}
function resolveDirectSchedule(e, t = {}) {
	if (e.onExitCwd && !e.onExitCommand) throw new CronCliError("--on-exit-cwd requires --on-exit.");
	if (hasStreamSchedulePatch(e) && !e.streamCommand) throw new CronCliError("Stream options require --stream-command.");
	if (e.tz && e.every) throw new CronCliError("--tz is only valid with --cron or offset-less --at");
	if (e.requestedStaggerMs !== void 0 && (e.at || e.every)) throw new CronCliError("--stagger/--exact are only valid for cron schedules");
	if (e.at) {
		const t = parseAt(e.at, e.tz);
		if (!t) throw new CronCliError("Invalid --at. Use an ISO timestamp or a duration like 20m.");
		return {
			kind: "at",
			at: t
		};
	}
	if (e.every) {
		const t = parsePositiveCronDurationMs(e.every);
		if (!t) throw new CronCliError("Invalid --every. Use a duration like 10m, 1h, or 1d.");
		return {
			kind: "every",
			everyMs: t
		};
	}
	if (e.cronExpr) {
		const t = parseCronTimezoneOption(e.tz);
		if (!isValidCronExpression(e.cronExpr, t)) throw new CronCliError(`Invalid cron expression "${e.cronExpr}". Use 5 fields like "0 9 * * *" or 6 fields like "0 0 9 * * *".`);
		return {
			kind: "cron",
			expr: e.cronExpr,
			tz: t,
			staggerMs: e.requestedStaggerMs
		};
	}
	if (e.onExitCommand) {
		if (e.tz || e.requestedStaggerMs !== void 0) throw new CronCliError("--tz/--stagger/--exact are not valid with --on-exit");
		return {
			kind: "on-exit",
			command: e.onExitCommand,
			...e.onExitCwd ? { cwd: e.onExitCwd } : {}
		};
	}
	if (e.streamCommand) {
		if (e.tz || e.requestedStaggerMs !== void 0) throw new CronCliError("--tz/--stagger/--exact are not valid with --stream-command");
		const n = {
			kind: "stream",
			command: e.streamCommand,
			...e.streamCwd ? { cwd: e.streamCwd } : {},
			mode: e.streamMode,
			...e.streamMatch ? { match: e.streamMatch } : {},
			...e.streamBatchMs !== void 0 ? { batchMs: e.streamBatchMs } : {},
			...e.streamMaxBatchBytes !== void 0 ? { maxBatchBytes: e.streamMaxBatchBytes } : {}
		};
		if (!t.deferStreamMetadataValidation) validateStreamScheduleMetadata(n);
		return n;
	}
}
//#endregion
//#region src/cli/cron-cli/thread-id-shared.ts
function parseCronThreadIdOption(e) {
	if (typeof e !== "string") return;
	const t = normalizeOptionalString(e);
	if (!t || !/^\d+$/.test(t)) throw new CronCliError("--thread-id must be a positive integer Telegram topic thread id");
	const n = Number.parseInt(t, 10);
	if (!Number.isSafeInteger(n) || n <= 0) throw new CronCliError("--thread-id must be a safe positive integer Telegram topic thread id");
	return n;
}
function normalizeCronSessionTargetOption(e) {
	const t = normalizeOptionalString(e);
	if (!t) return;
	const n = normalizeLowercaseStringOrEmpty(t);
	if (n === "main" || n === "isolated" || n === "current") return n;
	if (n.startsWith("session:")) {
		const e = normalizeOptionalString(t.slice(8));
		return e ? `session:${e}` : void 0;
	}
}
//#endregion
//#region src/cli/cron-cli/trigger-options.ts
const MAX_CRON_TRIGGER_SCRIPT_BYTES = 65536;
function decodeCronInput(e, t) {
	try {
		return new TextDecoder("utf-8", {
			fatal: true,
			ignoreBOM: true
		}).decode(e);
	} catch (e) {
		throw new CronCliError(`${t} must be valid UTF-8`, { cause: e });
	}
}
async function readCronInput(e, t, n) {
	const r = e === "-" ? t ?? process.stdin : createReadStream(e);
	try {
		return await readByteStreamWithLimit(r, n);
	} catch (e) {
		if (e instanceof Error && isErrno(e) && typeof e.errno === "number" && typeof e.syscall === "string") throw new CronCliError(e);
		throw e;
	}
}
async function readScriptStream(e, t, n) {
	const r = decodeCronInput(await readCronInput(e, t, {
		maxBytes: MAX_CRON_TRIGGER_SCRIPT_BYTES,
		onOverflow: () => new CronCliError(`${n} exceeds ${MAX_CRON_TRIGGER_SCRIPT_BYTES} bytes`)
	}), n).trim();
	if (!r) throw new CronCliError(`${n} must not be empty`);
	return r;
}
/** Reads a trigger script locally before sending the cron RPC. */
async function readCronTriggerScript(e, t) {
	return await readScriptStream(e, t?.stdin, "Trigger script");
}
/** Reads a script payload locally before sending the cron RPC. */
async function readCronPayloadScript(e, t) {
	return await readScriptStream(e, t?.stdin, "Script payload");
}
/** Reads exact scratch content locally; empty content is a meaningful value. */
async function readCronScratchContent(e, t) {
	return decodeCronInput(await readCronInput(e, t?.stdin, {
		maxBytes: CRON_JOB_SCRATCH_MAX_BYTES,
		onOverflow: () => new CronCliError(`Cron scratch exceeds ${CRON_JOB_SCRATCH_MAX_BYTES} bytes`)
	}), "Cron scratch");
}
//#endregion
//#region src/cli/cron-cli/register.cron-add.ts
function registerCronStatusCommand(e) {
	addGatewayClientOptions(createCronOutputCommand(e, "status").description("Show automations scheduler status").action(async (e) => {
		try {
			const t = await callCronReadFromCli("cron.status", e, {});
			printCronJson(t);
		} catch (e) {
			handleCronCliError(e);
		}
	}));
}
function registerCronListCommand(e) {
	addGatewayClientOptions(e.command("list").description("List automations").option("--all", "Include disabled jobs", false).option("--agent <id>", "Filter by agent id").option("--query <text>", "Filter automations by search text").option("--json", "Output JSON", false).action(async (e) => {
		try {
			const t = { includeDisabled: Boolean(e.all) };
			const n = parseCronStringOption(e.agent, "--agent");
			if (n) t.agentId = sanitizeAgentId(n);
			const r = normalizeOptionalString(e.query);
			if (r) t.query = r;
			const i = await listCronJobsFromGateway(e, t);
			if (e.json) {
				printCronJson(enrichCronJsonWithStatus(i));
				return;
			}
			const a = coerceCronDeliveryPreviews(i);
			printCronList(i.jobs, defaultRuntime, { deliveryPreviews: a });
		} catch (e) {
			handleCronCliError(e);
		}
	}));
}
function registerCronAddCommand(e) {
	addGatewayClientOptions(registerCronMutationOptions(createCronOutputCommand(e, "add").description("Add an automation").argument("[scheduleOrName]", "Schedule string, or job name when using --at/--every/--cron").argument("[message]", "Agent message when using a positional schedule"), "add").option("--declaration-key <key>", "Key to avoid duplicate declarations").option("--disabled", "Create job disabled", false).action(async (e, t, n, r) => {
		try {
			const i = await resolveCronExecutionPolicyOptions(n);
			const a = parseCronDeliveryPolicyOptions(n);
			for (const [e, t] of [
				["--command-cwd", n.commandCwd],
				["--on-exit-cwd", n.onExitCwd],
				["--stream-cwd", n.streamCwd]
			]) if (typeof t === "string" && !normalizeOptionalString(t)) throw new CronCliError(`${e} must not be blank`);
			const o = typeof n.at === "string" || typeof n.cron === "string" || typeof n.every === "string" || typeof n.onExit === "string" || typeof n.streamCommand === "string";
			const s = o ? void 0 : e;
			const c = resolveCronCreateScheduleFromArgs({
				...n,
				positionalSchedule: s
			});
			const l = normalizeOptionalString(n.wake) ?? "now";
			if (l !== "now" && l !== "next-heartbeat") throw new CronCliError("--wake must be now or next-heartbeat");
			const u = normalizeOptionalString(n.agent);
			const d = u ? sanitizeAgentId(u) : void 0;
			const f = Boolean(n.announce) || n.deliver === true;
			const p = n.deliver === false;
			const m = typeof n.webhook === "string" ? normalizeHttpWebhookUrl(n.webhook) : null;
			if (typeof n.webhook === "string" && !m) throw new CronCliError("--webhook must be a valid http(s) URL");
			const h = Boolean(m);
			if ([
				f,
				p,
				h
			].filter(Boolean).length > 1) throw new CronCliError("Choose at most one of --announce, --no-deliver, or --webhook");
			const g = await (async () => {
				const e = normalizeOptionalString(n.systemEvent) ?? "";
				const r = normalizeOptionalString(n.message);
				const i = normalizeOptionalString(t);
				const a = readNonBlankString(n.command);
				const o = parseCronCommandArgv(n.commandArgv);
				const s = readNonBlankString(n.script);
				if (typeof n.script === "string" && !s) throw new CronCliError("--script must not be blank");
				const c = parseCronStringList(n.tools);
				if (r && i && r !== i) throw new CronCliError("Pass the automation message either positionally or with --message, not both.");
				const l = r ?? i ?? "";
				if (a && o) throw new CronCliError("Pass command payload either with --command or --command-argv, not both.");
				if ([
					Boolean(e),
					Boolean(l),
					Boolean(a) || Boolean(o),
					Boolean(s)
				].filter(Boolean).length !== 1) throw new CronCliError("Choose exactly one payload: --system-event, --message, --command, or --script");
				if (typeof n.skipIfScratchEmpty === "boolean" && !l) throw new CronCliError("--skip-if-scratch-empty/--no-skip-if-scratch-empty require --message");
				if (typeof n.includeReasoning === "boolean" && !l) throw new CronCliError("--include-reasoning/--no-include-reasoning require --message");
				if (e) {
					if (n.timeoutSeconds !== void 0) assertCronTimeoutSupported("systemEvent");
					return {
						kind: "systemEvent",
						text: e,
						...c ? { toolsAllow: c } : {}
					};
				}
				if (s) {
					if (n.timeoutSeconds !== void 0) assertCronTimeoutSupported("script");
					return {
						kind: "script",
						timeoutSeconds: parseCronIntegerOption(n.scriptTimeoutSeconds, "--script-timeout-seconds"),
						toolBudget: parseCronIntegerOption(n.scriptToolBudget, "--script-tool-budget"),
						toolsAllow: c,
						script: await readCronPayloadScript(s)
					};
				}
				const u = parseCronIntegerOption(n.timeoutSeconds, "--timeout-seconds", "non-negative");
				if (a || o) {
					const e = parseCronNoOutputTimeoutOption(n);
					const t = parseCronIntegerOption(n.outputMaxBytes, "--output-max-bytes");
					return {
						kind: "command",
						argv: o ?? [
							"sh",
							"-lc",
							a ?? ""
						],
						cwd: readNonBlankString(n.commandCwd),
						env: parseCronCommandEnv(n.commandEnv),
						input: typeof n.commandInput === "string" ? n.commandInput : void 0,
						timeoutSeconds: u,
						noOutputTimeoutSeconds: e,
						outputMaxBytes: t,
						...c ? { toolsAllow: c } : {}
					};
				}
				return {
					kind: "agentTurn",
					message: l,
					model: normalizeOptionalString(n.model),
					fallbacks: parseCronStringList(n.fallbacks),
					thinking: parseCronThinkingOption(n.thinking),
					timeoutSeconds: u,
					lightContext: n.lightContext === true ? true : void 0,
					...typeof n.skipIfScratchEmpty === "boolean" ? { skipIfScratchEmpty: n.skipIfScratchEmpty } : {},
					...typeof n.includeReasoning === "boolean" ? { includeReasoning: n.includeReasoning } : {},
					toolsAllow: c
				};
			})();
			const _ = r.getOptionValueSource("session");
			const v = g.kind !== "systemEvent";
			const y = _ === "cli" ? normalizeCronSessionTargetOption(n.session) : v ? "isolated" : "main";
			if (!y) throw new CronCliError("--session must be main, isolated, current, or session:<id>");
			if (n.deleteAfterRun && n.keepAfterRun) throw new CronCliError("Choose --delete-after-run or --keep-after-run, not both");
			await assertCronCliJobSpec({
				sessionTarget: y,
				payload: g
			});
			const b = v && (y !== "main" || g.kind === "agentTurn");
			if ((n.announce || typeof n.deliver === "boolean") && !b) throw new CronCliError("--announce/--no-deliver require an agentTurn job or a non-main command or script job.");
			const x = normalizeOptionalString(n.account);
			const S = parseCronThreadIdOption(n.threadId);
			const C = typeof S === "number";
			const w = a.target !== void 0 || a.directPolicy !== void 0 || r.getOptionValueSource("channel") === "cli" || typeof n.to === "string" || Boolean(x) || C;
			if (w && !b) throw new CronCliError("--channel, --to, --account, and --thread-id require an agentTurn job or a non-main command or script job with delivery.");
			if (h && w) throw new CronCliError("--webhook cannot be combined with chat delivery options.");
			const T = h ? "webhook" : b && (y !== "main" || f || p || w) ? p ? "none" : "announce" : void 0;
			const E = normalizeOptionalString(n.name);
			const D = o ? normalizeOptionalString(e) : void 0;
			if (E && D && E !== D) throw new CronCliError("Pass the automation name either positionally or with --name, not both.");
			const O = E ?? D ?? "";
			if (!O) throw new CronCliError("Cron job name is required. Pass a name or --name <name>.");
			const k = normalizeOptionalString(n.description);
			const A = parseCronStringOption(n.declarationKey, "--declaration-key");
			const j = parseCronStringOption(n.displayName, "--display-name");
			const M = parseCronStringOption(n.pacingMin, "--pacing-min");
			const N = parseCronStringOption(n.pacingMax, "--pacing-max");
			const P = normalizeOptionalString(n.sessionKey);
			const F = readNonBlankString(n.triggerScript);
			if ((n.triggerOnce || n.triggerScript !== void 0) && !F) throw new CronCliError(`--trigger-${n.triggerOnce ? "once requires --trigger-script" : "script must not be blank"}`);
			const I = F && {
				script: await readCronTriggerScript(F),
				...n.triggerOnce ? { once: true } : {}
			};
			if ((g.kind === "agentTurn" || g.kind === "script") && !d) defaultRuntime.error(theme.warn("No --agent specified; the job will run with the configured default agent. Specify --agent to choose a specific agent, or set agents.defaults.systemAgent.agentId."));
			const L = {
				name: O,
				declarationKey: A,
				displayName: j,
				description: k,
				...A && r.getOptionValueSource("disabled") !== "cli" ? {} : { enabled: !n.disabled },
				deleteAfterRun: n.deleteAfterRun ? true : n.keepAfterRun ? false : void 0,
				agentId: d,
				sessionKey: P,
				schedule: c,
				...i,
				...M || N ? { pacing: {
					...M ? { min: M } : {},
					...N ? { max: N } : {}
				} } : {},
				trigger: I,
				sessionTarget: y,
				wakeMode: l,
				payload: g,
				delivery: T ? {
					mode: T,
					...a,
					channel: h || a.target === "owner" && r.getOptionValueSource("channel") !== "cli" ? void 0 : normalizeOptionalString(n.channel),
					to: h ? m : normalizeOptionalString(n.to),
					threadId: h ? void 0 : S,
					accountId: h ? void 0 : x,
					bestEffort: n.bestEffortDeliver ? true : void 0
				} : void 0
			};
			const R = await callGatewayFromCli("cron.add", n, L);
			printCronJson(R);
			await warnIfCronSchedulerDisabled(n);
		} catch (e) {
			handleCronCliError(e);
		}
	}));
}
//#endregion
//#region src/cli/cron-cli/register.cron-edit.ts
const assignIf = (e, t, n, r = n !== void 0) => {
	if (r) e[t] = n;
};
async function readCronJobForEdit(e, t) {
	try {
		return await callGatewayFromCli("cron.get", e, { id: t }, { signal: getAsyncWorkSignal() });
	} catch (n) {
		if (!isUnknownCronGetMethodError(n)) throw n;
		const r = (await listCronJobsFromGateway(e, { includeDisabled: true }, { allowLegacyUnversionedPagination: true })).jobs.find((e) => e.id === t);
		if (!r) throw new CronCliError(`unknown automation id: ${t}`, { cause: n });
		return r;
	}
}
function registerCronEditCommand(e) {
	addGatewayClientOptions(registerCronMutationOptions(createCronOutputCommand(e, "edit").description("Edit an automation (patch fields)").argument("<id>", "Job id"), "edit").option("--clear-display-name", "Restore the stable name in list and detail views", false).option("--enable", "Enable job", false).option("--disable", "Disable job", false).option("--clear-agent", "Unset agent and use default", false).option("--clear-session-key", "Unset session key", false).option("--clear-pacing", "Remove dynamic-cadence bounds", false).option("--clear-active-hours", "Remove the entire execution window", false).option("--clear-idle-only", "Remove the per-job idle-only policy", false).option("--clear-trigger", "Remove the condition trigger", false).option("--clear-thinking", "Remove the per-job thinking override (restore normal cron thinking precedence)", false).option("--clear-fallbacks", "Remove per-job fallback override", false).option("--clear-model", "Remove the per-job model override (restore normal cron model precedence)", false).option("--no-light-context", "Disable lightweight bootstrap context for agent jobs").option("--clear-tools", "Remove tool allow-list (use all tools)", false).option("--clear-channel", "Unset the delivery channel", false).option("--clear-to", "Unset the delivery destination", false).option("--clear-thread-id", "Unset the Telegram forum topic thread id", false).option("--clear-account", "Unset the per-job delivery account override", false).option("--clear-delivery-target", "Remove dynamic owner targeting", false).option("--clear-direct-policy", "Remove the per-job direct-message policy", false).option("--no-best-effort-deliver", "Fail job when delivery fails").option("--failure-alert", "Enable failure alerts for this job").option("--no-failure-alert", "Disable failure alerts for this job").option("--failure-alert-after <n>", "Alert after N consecutive job errors").option("--failure-alert-channel <channel>", `Failure alert channel (${getCronChannelOptions()})`).option("--failure-alert-to <dest>", "Failure alert destination").option("--failure-alert-cooldown <duration>", "Minimum time between alerts (e.g. 1h, 30m)").option("--failure-alert-include-skipped", "Count consecutive skipped runs toward alerts").option("--failure-alert-exclude-skipped", "Exclude skips except local-provider outages").option("--failure-alert-mode <mode>", "Failure alert delivery mode (announce or webhook)").option("--failure-alert-account-id <id>", "Account ID for failure alert channel (multi-account setups)").action(async (e, t) => {
		try {
			const n = requireCronJobId(e);
			if (t.clearTools && t.tools !== void 0) throw new CronCliError("Use --tools or --clear-tools, not both");
			if (typeof t.script === "string" && !readNonBlankString(t.script)) throw new CronCliError("--script must not be blank");
			if (typeof t.command === "string" && !readNonBlankString(t.command)) throw new CronCliError("--command must not be blank");
			if (typeof t.commandCwd === "string" && !normalizeOptionalString(t.commandCwd)) throw new CronCliError("--command-cwd must not be blank");
			const r = readNonBlankString(t.commandCwd);
			let i;
			let a;
			const readExistingCronJob = async () => {
				const e = await (i ??= readCronJobForEdit(t, n));
				if (typeof e.configRevision === "string") a = e.configRevision;
				return e;
			};
			const o = typeof t.session === "string" ? normalizeCronSessionTargetOption(t.session) : void 0;
			if (typeof t.session === "string" && !o) throw new CronCliError("--session must be main, isolated, current, or session:<id>");
			const s = t.systemEvent ? "systemEvent" : typeof t.script === "string" ? "script" : t.command || t.commandArgv ? "command" : t.message ? "agentTurn" : void 0;
			if (o && s) await assertCronCliJobSpec({
				sessionTarget: o,
				payload: { kind: s }
			});
			const c = parseCronThreadIdOption(t.threadId) !== void 0 || typeof t.channel === "string" || typeof t.to === "string" || typeof t.account === "string";
			if (o === "main" && typeof t.systemEvent === "string" && c) throw new CronCliError("--channel, --to, --account, and --thread-id require an agentTurn job or a non-main command or script job with delivery.");
			const l = typeof t.webhook === "string" ? normalizeHttpWebhookUrl(t.webhook) ?? void 0 : void 0;
			if (typeof t.webhook === "string" && !l) throw new CronCliError("--webhook must be a valid http(s) URL");
			const u = Boolean(l);
			if ([
				Boolean(t.announce),
				typeof t.deliver === "boolean",
				u
			].filter(Boolean).length > 1) throw new CronCliError("Choose at most one of --announce, --no-deliver, or --webhook.");
			const d = readNonBlankString(t.triggerScript);
			if (typeof t.triggerScript === "string" && !d) throw new CronCliError("--trigger-script must not be blank");
			if (t.clearTrigger && (d || t.triggerOnce)) throw new CronCliError("Use --clear-trigger or trigger options, not both");
			const f = d ? await readCronTriggerScript(d) : void 0;
			const p = await resolveCronExecutionPolicyOptions(t, readExistingCronJob);
			if (typeof t.name === "string") p.name = t.name;
			const m = parseCronStringOption(t.displayName, "--display-name");
			if (m && t.clearDisplayName) throw new CronCliError("Use --display-name or --clear-display-name, not both");
			if (m || t.clearDisplayName) p.displayName = m ?? null;
			if (typeof t.description === "string") p.description = t.description;
			if (t.enable && t.disable) throw new CronCliError("Choose --enable or --disable, not both");
			if (t.enable || t.disable) p.enabled = Boolean(t.enable);
			if (t.deleteAfterRun && t.keepAfterRun) throw new CronCliError("Choose --delete-after-run or --keep-after-run, not both");
			if (t.deleteAfterRun || t.keepAfterRun) p.deleteAfterRun = Boolean(t.deleteAfterRun);
			if (typeof t.session === "string") p.sessionTarget = o;
			if (typeof t.wake === "string") {
				const e = t.wake.trim();
				if (e !== "now" && e !== "next-heartbeat") throw new CronCliError("--wake must be now or next-heartbeat");
				p.wakeMode = e;
			}
			const h = parseCronStringOption(t.agent, "--agent");
			if (h && t.clearAgent) throw new CronCliError("Use --agent or --clear-agent, not both");
			if (h || t.clearAgent) p.agentId = h ? sanitizeAgentId(h) : null;
			const g = parseCronStringOption(t.sessionKey, "--session-key");
			if (g && t.clearSessionKey) throw new CronCliError("Use --session-key or --clear-session-key, not both");
			if (g || t.clearSessionKey) p.sessionKey = g ?? null;
			const _ = parseCronStringOption(t.pacingMin, "--pacing-min");
			const v = parseCronStringOption(t.pacingMax, "--pacing-max");
			const y = typeof t.pacingMin === "string";
			const b = typeof t.pacingMax === "string";
			if (t.clearPacing && (y || b)) throw new CronCliError("Use --clear-pacing or pacing bounds, not both");
			if (t.clearPacing) p.pacing = null;
			else if (y || b) p.pacing = {
				...(await readExistingCronJob()).pacing,
				..._ ? { min: _ } : {},
				...v ? { max: v } : {}
			};
			if (t.clearTrigger) p.trigger = null;
			else if (f !== void 0) p.trigger = {
				...(await readExistingCronJob()).trigger,
				script: f,
				...t.triggerOnce ? { once: true } : {}
			};
			else if (t.triggerOnce) {
				const e = await readExistingCronJob();
				if (!e.trigger) throw new CronCliError("--trigger-once requires an existing trigger or --trigger-script");
				p.trigger = {
					...e.trigger,
					once: true
				};
			}
			const x = resolveCronEditScheduleRequest(t);
			if (x.kind === "direct") {
				if (x.schedule.kind === "stream") {
					const e = await readExistingCronJob();
					if (e.schedule.kind === "stream") {
						const n = resolveCronEditScheduleRequest({
							streamCwd: t.streamCwd,
							streamMode: t.streamMode,
							streamMatch: t.streamMatch,
							streamBatchMs: t.streamBatchMs,
							streamMaxBatchBytes: t.streamMaxBatchBytes
						});
						p.schedule = {
							...n.kind === "patch-existing-stream" ? applyExistingStreamSchedulePatch(e.schedule, n) : e.schedule,
							command: x.schedule.command
						};
					} else {
						validateStreamScheduleMetadata(x.schedule);
						p.schedule = x.schedule;
					}
				} else if (x.schedule.kind === "cron" && x.schedule.tz === void 0) {
					const e = await readExistingCronJob();
					p.schedule = e.schedule.kind === "cron" && e.schedule.tz !== void 0 ? {
						...x.schedule,
						tz: e.schedule.tz
					} : x.schedule;
				} else p.schedule = x.schedule;
			} else if (x.kind === "patch-existing-cron") {
				const e = await readExistingCronJob();
				p.schedule = applyExistingCronSchedulePatch(e.schedule, x);
			} else if (x.kind === "patch-existing-stream") {
				const e = await readExistingCronJob();
				p.schedule = applyExistingStreamSchedulePatch(e.schedule, x);
			}
			const S = parseCronDeliveryPolicyOptions(t);
			const C = Object.keys(S).length > 0;
			const w = typeof t.systemEvent === "string";
			const T = readNonBlankString(t.script);
			const E = readNonBlankString(t.command);
			const D = parseCronCommandArgv(t.commandArgv);
			if (E && D) throw new CronCliError("Pass command payload either with --command or --command-argv, not both.");
			const O = typeof t.model === "string";
			const k = normalizeOptionalString(t.model);
			if (O && t.clearModel) throw new CronCliError("Use --model or --clear-model, not both");
			const A = typeof t.thinking === "string";
			const j = normalizeOptionalString(t.thinking);
			if (A && t.clearThinking) throw new CronCliError("Use --thinking or --clear-thinking, not both");
			const M = parseCronStringList(t.fallbacks);
			if (typeof t.fallbacks === "string" && t.clearFallbacks) throw new CronCliError("Use --fallbacks or --clear-fallbacks, not both");
			const N = parseCronStringList(t.tools);
			const P = parseCronIntegerOption(t.timeoutSeconds, "--timeout-seconds", "non-negative");
			const F = P !== void 0;
			const I = parseCronNoOutputTimeoutOption(t);
			const L = parseCronIntegerOption(t.outputMaxBytes, "--output-max-bytes");
			const R = parseCronIntegerOption(t.scriptTimeoutSeconds, "--script-timeout-seconds");
			const z = parseCronIntegerOption(t.scriptToolBudget, "--script-tool-budget");
			const B = t.announce || typeof t.deliver === "boolean" || u;
			const V = parseCronThreadIdOption(t.threadId);
			const H = typeof V === "number";
			const U = Boolean(normalizeOptionalString(t.to));
			const W = [
				[
					"channel",
					"channel",
					t.channel,
					t.clearChannel
				],
				[
					"to",
					"to",
					t.to,
					t.clearTo
				],
				[
					"thread-id",
					"threadId",
					V,
					t.clearThreadId
				],
				[
					"account",
					"accountId",
					t.account,
					t.clearAccount
				]
			].map(([e, t, n, r]) => ({
				flag: e,
				key: t,
				value: n,
				clear: r,
				present: t === "threadId" ? typeof n === "number" : typeof n === "string"
			}));
			const G = W.some((e) => e.present || e.clear);
			const ee = typeof t.bestEffortDeliver === "boolean";
			if (u && G) throw new CronCliError("--webhook cannot be combined with chat delivery options.");
			for (const { flag: e, present: t, clear: n } of W) if (t && n) throw new CronCliError(`Use --${e} or --clear-${e}, not both`);
			const K = typeof t.commandInput === "string";
			const te = Boolean(E) || Boolean(D) || Boolean(r) || K || t.commandEnv !== void 0 || I !== void 0 || L !== void 0;
			const ne = typeof t.tools === "string" || Array.isArray(t.tools) || Boolean(t.clearTools);
			const re = typeof t.message === "string" || Boolean(k) || Boolean(t.clearModel) || typeof t.fallbacks === "string" || Boolean(t.clearFallbacks) || Boolean(j) || Boolean(t.clearThinking) || typeof t.lightContext === "boolean" || typeof t.skipIfScratchEmpty === "boolean" || typeof t.includeReasoning === "boolean";
			const q = Boolean(T) || R !== void 0 || z !== void 0;
			if (F && q) assertCronTimeoutSupported("script");
			if (F && w) assertCronTimeoutSupported("systemEvent");
			const J = [
				["systemEvent", w],
				["agentTurn", re],
				["command", te],
				["script", q]
			].filter(([, e]) => e).map(([e]) => e);
			let Y = J[0];
			if (J.length === 0 && (F || ne)) {
				Y = (await readExistingCronJob()).payload.kind;
				if (F) assertCronTimeoutSupported(Y);
			} else if (J.length > 1) throw new CronCliError("Choose at most one payload change");
			for (const [e, n] of [["skipIfScratchEmpty", "skip-if-scratch-empty"], ["includeReasoning", "include-reasoning"]]) if (typeof t[e] === "boolean" && typeof t.message !== "string" && (await readExistingCronJob()).payload.kind !== "agentTurn") throw new CronCliError(`--${n}/--no-${n} require an agentTurn job or --message`);
			let X;
			if (Y === "systemEvent") {
				X = { kind: "systemEvent" };
				assignIf(X, "text", String(t.systemEvent), w);
			} else if (Y === "agentTurn") {
				X = { kind: "agentTurn" };
				assignIf(X, "message", String(t.message), typeof t.message === "string");
				assignIf(X, "model", t.clearModel ? null : k);
				assignIf(X, "fallbacks", M, typeof t.fallbacks === "string");
				assignIf(X, "fallbacks", null, Boolean(t.clearFallbacks));
				if (t.clearThinking) X.thinking = null;
				else assignIf(X, "thinking", parseCronThinkingOption(j), Boolean(j));
				assignIf(X, "timeoutSeconds", P, F);
				assignIf(X, "lightContext", t.lightContext, typeof t.lightContext === "boolean");
				assignIf(X, "skipIfScratchEmpty", t.skipIfScratchEmpty, typeof t.skipIfScratchEmpty === "boolean");
				assignIf(X, "includeReasoning", t.includeReasoning, typeof t.includeReasoning === "boolean");
			} else if (Y === "command") {
				X = { kind: "command" };
				assignIf(X, "argv", D, Boolean(D));
				assignIf(X, "argv", [
					"sh",
					"-lc",
					E
				], Boolean(E));
				assignIf(X, "cwd", r, Boolean(r));
				assignIf(X, "env", parseCronCommandEnv(t.commandEnv), t.commandEnv !== void 0);
				assignIf(X, "input", t.commandInput, K);
				assignIf(X, "timeoutSeconds", P, F);
				assignIf(X, "noOutputTimeoutSeconds", I);
				assignIf(X, "outputMaxBytes", L);
			} else if (Y === "script") {
				X = { kind: "script" };
				if (T) X.script = await readCronPayloadScript(T);
				assignIf(X, "timeoutSeconds", R);
				assignIf(X, "toolBudget", z);
			}
			if (X) {
				if (t.clearTools) X.toolsAllow = ["*"];
				else if (N) X.toolsAllow = N;
				p.payload = X;
			}
			if (B || G || ee || C) {
				const e = { ...S };
				if (B) e.mode = u ? "webhook" : t.announce || t.deliver === true ? "announce" : "none";
				else if (t.bestEffortDeliver === true) e.mode = "announce";
				for (const { key: t, value: n, present: r, clear: i } of W) if (t === "to" && u) e.to = l;
				else if (i || r) e[t] = i ? null : t === "threadId" ? n : normalizeOptionalString(n);
				if (typeof t.bestEffortDeliver === "boolean") e.bestEffort = t.bestEffortDeliver;
				if (C || U || H || u) {
					const t = await readExistingCronJob();
					if (S.target === "owner") {
						e.to = null;
						e.threadId = null;
						if (e.mode === void 0 && t.delivery?.mode === "webhook") e.mode = "announce";
					} else if (t.delivery?.target === "owner" && (U || H || u)) e.target = null;
					const n = e.mode ?? t.delivery?.mode;
					if (S.target === "owner" || S.directPolicy != null) {
						const e = o ?? t.sessionTarget;
						if (w || e === "main" && (Y ?? t.payload.kind) !== "agentTurn") throw new CronCliError("--delivery-target/--direct-policy require an agentTurn job or a non-main job with chat delivery");
						if (n === "webhook") throw new CronCliError("--direct-policy requires chat delivery; use --announce or --no-deliver");
					}
				}
				p.delivery = e;
			}
			const Z = typeof t.failureAlertIncludeSkipped === "boolean";
			const Q = typeof t.failureAlertExcludeSkipped === "boolean";
			if (Z && Q) throw new CronCliError("Use either --failure-alert-include-skipped or --failure-alert-exclude-skipped.");
			const ie = [
				"failureAlertAfter",
				"failureAlertChannel",
				"failureAlertTo",
				"failureAlertCooldown",
				"failureAlertMode",
				"failureAlertAccountId"
			].some((e) => typeof t[e] === "string") || Z || Q;
			const $ = typeof t.failureAlert === "boolean" ? t.failureAlert : void 0;
			if ($ === false && ie) throw new CronCliError("Use --no-failure-alert alone (without failure-alert-* options).");
			if ($ === false) p.failureAlert = false;
			else if ($ === true || ie) {
				const e = {};
				if (typeof t.failureAlertAfter === "string") e.after = parseCronIntegerOption(t.failureAlertAfter, "--failure-alert-after");
				if (typeof t.failureAlertChannel === "string") e.channel = normalizeOptionalLowercaseString(t.failureAlertChannel) ?? null;
				if (typeof t.failureAlertTo === "string") e.to = normalizeOptionalString(t.failureAlertTo) ?? null;
				if (typeof t.failureAlertCooldown === "string") {
					let n;
					try {
						n = parseDurationMs(t.failureAlertCooldown);
					} catch {
						throw new CronCliError("Invalid --failure-alert-cooldown.");
					}
					e.cooldownMs = n;
				}
				if (Z || Q) e.includeSkipped = Z;
				if (typeof t.failureAlertMode === "string") {
					const n = normalizeOptionalLowercaseString(t.failureAlertMode);
					if (n !== "announce" && n !== "webhook") throw new CronCliError("Invalid --failure-alert-mode (must be 'announce' or 'webhook').");
					e.mode = n;
				}
				if (typeof t.failureAlertAccountId === "string") e.accountId = normalizeOptionalString(t.failureAlertAccountId) ?? null;
				p.failureAlert = e;
			}
			const ae = await callGatewayFromCli("cron.update", t, {
				id: n,
				patch: p,
				...a !== void 0 ? { expectedConfigRevision: a } : {}
			});
			defaultRuntime.writeJson(ae);
			await warnIfCronSchedulerDisabled(t);
		} catch (e) {
			handleCronCliError(e);
		}
	}));
}
//#endregion
//#region src/cli/cron-cli/register.cron-scratch.ts
function registerCronScratchCommand(e) {
	addGatewayClientOptions(createCronOutputCommand(e, "scratch").description("Read or replace an automation's private scratch").argument("<id>", "Job id").option("--set <text>", "Replace scratch with exact text").option("--file <path>", "Replace scratch from a file, or - for stdin").option("--unset", "Remove the scratch row", false).option("--expected-revision <n>", "Require the current scratch revision").action(async (e, t) => {
		try {
			const n = requireCronJobId(e);
			const r = [
				t.set !== void 0,
				t.file !== void 0,
				t.unset === true
			].filter(Boolean).length;
			if (r > 1) throw new CronCliError("choose only one of --set, --file, or --unset");
			let i = r === 1 && t.expectedRevision !== void 0 && t.file === void 0 && (t.unset || Buffer.byteLength(String(t.set ?? ""), "utf8") <= 262144) ? parseStrictNonNegativeInteger(t.expectedRevision) : void 0;
			if (i === void 0) {
				const e = await callCronReadFromCli("cron.scratch.get", t, { id: n });
				if (r === 0) {
					if (t.json) printCronJson(e);
					else if (e.scratch) process.stdout.write(e.scratch.content);
					return;
				}
				const a = parseStrictNonNegativeInteger(t.expectedRevision);
				if (t.expectedRevision !== void 0 && a === void 0) throw new CronCliError("--expected-revision must be a non-negative integer");
				i = a ?? e.currentRevision;
			}
			const a = t.unset ? null : t.file !== void 0 ? await readCronScratchContent(String(t.file)) : String(t.set ?? "");
			const o = await callGatewayFromCli("cron.scratch.set", t, {
				id: n,
				content: a,
				expectedRevision: i
			});
			if (!o.ok) throw new CronCliError(`cron scratch changed concurrently (current revision ${o.currentRevision})`);
			printCronJson(o);
		} catch (e) {
			handleCronCliError(e);
		}
	}));
}
//#endregion
//#region src/cli/cron-cli/register.cron-simple.ts
const CRON_RUN_WAIT_TIMEOUT_DEFAULT = "10m";
const CRON_RUN_WAIT_POLL_INTERVAL_DEFAULT = "2s";
function parseCronRunWaitDuration(e) {
	const t = typeof e === "string" || typeof e === "number" || typeof e === "bigint" ? String(e) : "";
	let n;
	try {
		n = parseDurationMs(t, { defaultUnit: "ms" });
	} catch (e) {
		if (e instanceof Error) throw new CronCliError(e);
		throw e;
	}
	return resolveTimerTimeoutMs(n, 0, 0);
}
async function waitForCronRunCompletion(e) {
	const t = performance.now();
	let n = false;
	for (;;) {
		e.signal?.throwIfAborted();
		const r = Math.floor(performance.now() - t);
		if (n && r >= e.timeoutMs) throw new CronCliError(`timed out waiting for cron run ${e.runId}`);
		const i = Math.max(1, e.timeoutMs - r);
		const a = parseTimeoutMs(e.opts.timeout);
		const o = a === void 0 ? i : Math.min(a, i);
		n = true;
		const s = {
			...e.opts,
			timeout: String(o)
		};
		const c = await callGatewayFromCli("cron.runs", s, {
			id: e.jobId,
			runId: e.runId,
			limit: 1
		}, { signal: e.signal });
		e.signal?.throwIfAborted();
		const l = c.entries?.[0];
		if (l?.status === "ok" || l?.status === "error" || l?.status === "skipped") return l;
		const u = Math.floor(performance.now() - t);
		if (u >= e.timeoutMs) throw new CronCliError(`timed out waiting for cron run ${e.runId}`);
		await setTimeout(Math.min(e.pollIntervalMs, e.timeoutMs - u), void 0, { signal: e.signal });
	}
}
function registerCronSimpleCommands(e) {
	for (const [t, n, r] of [
		[
			"rm",
			"Remove an automation",
			"cron.remove"
		],
		[
			"enable",
			"Enable an automation",
			"cron.update"
		],
		[
			"disable",
			"Disable an automation",
			"cron.update"
		],
		[
			"get",
			"Get an automation as JSON",
			"cron.get"
		],
		[
			"bind",
			"Link a key-only automation to its parent conversation (ask the agent in that conversation)",
			"cron.bind"
		]
	]) addGatewayClientOptions(createCronOutputCommand(e, t).description(n).argument("<id>", "Job id").action(async (e, n) => {
		try {
			const i = await (r === "cron.get" ? callCronReadFromCli : callGatewayFromCli)(r, n, {
				id: requireCronJobId(e),
				...r === "cron.update" ? { patch: { enabled: t === "enable" } } : {}
			});
			printCronJson(i);
			if (t === "disable" && 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`);
			if (r === "cron.update") await warnIfCronSchedulerDisabled(n);
		} catch (e) {
			handleCronCliError(e);
		}
	}));
	addGatewayClientOptions(e.command("show").description("Show an automation").argument("<id>", "Job id or exact name").option("--json", "Output JSON", false).action(async (e, t) => {
		try {
			const n = requireCronJobId(e);
			const { job: r, deliveryPreview: i } = await findCronJobByIdOrName(t, n, { includeDeliveryPreview: !t.json });
			if (!r) throw new CronCliError(formatCronLookupMiss(n));
			if (t.json) {
				printCronJson(enrichCronJsonWithStatus(r));
				return;
			}
			printCronShow(r, defaultRuntime, { deliveryPreview: i });
		} catch (e) {
			handleCronCliError(e);
		}
	}));
	addGatewayClientOptions(createCronOutputCommand(e, "runs").description("Show automation run history").argument("[id]", "Job id").option("--id <id>", "Job id (alternative to positional argument)").option("--all", "Show run history across all visible automations", false).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 (e, t) => {
		try {
			const n = normalizeOptionalString(e);
			const r = normalizeOptionalString(t.id);
			if (n && r && n !== r) throw new CronCliError(`Conflicting job ids: positional "${n}" and --id "${r}".`);
			if (t.all && (e !== void 0 || t.id !== void 0)) throw new CronCliError("--all cannot be combined with a job id");
			const i = t.all ? void 0 : requireCronJobId(n ?? r, "Pass it positionally or with --id.");
			const a = parseCronIntegerOption(t.limit ?? "50", "--limit");
			const o = parseCronIntegerOption(t.offset, "--offset", "non-negative");
			if (typeof t.runId === "string" && !t.runId.trim()) throw new CronCliError("--run-id must not be blank");
			const s = await callCronReadFromCli("cron.runs", t, {
				...t.all ? { scope: "all" } : { id: i },
				...typeof t.runId === "string" && t.runId.trim() ? { runId: t.runId } : {},
				...typeof t.status === "string" ? { status: t.status } : {},
				...typeof t.deliveryStatus === "string" ? { deliveryStatus: t.deliveryStatus } : {},
				...typeof t.query === "string" ? { query: t.query } : {},
				...o !== void 0 ? { offset: o } : {},
				...typeof t.sort === "string" ? { sortDir: t.sort } : {},
				limit: a
			});
			printCronJson(s);
		} catch (e) {
			handleCronCliError(e);
		}
	}));
	addGatewayClientOptions(createCronOutputCommand(e, "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 (e, t, n) => {
		const r = t.wait ? getAsyncWorkSignal() : void 0;
		try {
			const i = requireCronJobId(e);
			let a = 0;
			let o = 0;
			if (t.wait) {
				a = parseCronRunWaitDuration(t.waitTimeout);
				o = parseCronRunWaitDuration(t.pollInterval);
				if (o <= 0) throw new CronCliError("invalid --poll-interval");
			}
			if (n.getOptionValueSource("timeout") === "default") t.timeout = "600000";
			const s = await callGatewayFromCli("cron.run", t, {
				id: i,
				mode: t.due ? "due" : "force"
			});
			const c = s;
			if (t.wait && c?.ok && c.enqueued) {
				if (!c.runId) throw new Error("cron run did not return a runId to wait for");
				const e = await waitForCronRunCompletion({
					opts: t,
					jobId: i,
					runId: c.runId,
					timeoutMs: a,
					pollIntervalMs: o,
					signal: r
				});
				r?.throwIfAborted();
				const n = e.completionStatus ?? resolveCronCompletionStatus({
					status: e.status,
					delivered: e.delivered,
					deliveryStatus: e.deliveryStatus
				});
				const l = {
					...e,
					completionStatus: n
				};
				printCronJson({
					...s,
					completed: true,
					status: e.status,
					completionStatus: n,
					run: l
				});
				exitCliAfterOutput(defaultRuntime, n === "succeeded" ? 0 : 1);
			}
			printCronJson(s);
			exitCliAfterOutput(defaultRuntime, c?.ok && (c.ran || c.enqueued) ? 0 : 1);
		} catch (e) {
			if (r?.aborted) return;
			handleCronCliError(e);
		}
	}));
}
//#endregion
//#region src/cli/cron-cli/register.ts
function inheritCronGatewayOptions(e) {
	for (const t of CRON_GATEWAY_OPTION_NAMES) {
		const n = inheritOptionFromParent(e, t);
		const r = e.parent?.getOptionValueSource(t);
		if (n !== void 0 && r && r !== "default") e.setOptionValueWithSource(t, n, r);
	}
}
function registerCronCli(e) {
	const t = e.command("cron").alias("automations").description("Manage automations (via Gateway)").addHelpText("after", () => `\n${theme.muted("Docs:")} ${formatDocsLink("/cli/cron", "docs.openclaw.ai/cli/cron")}\n${theme.muted("Upgrade tip:")} run \`openclaw doctor --fix\` to normalize legacy automation storage.\n`);
	addGatewayClientOptions(t);
	t.hook("preAction", (e, t) => inheritCronGatewayOptions(t));
	registerCronStatusCommand(t);
	registerCronListCommand(t);
	registerCronAddCommand(t);
	registerCronSimpleCommands(t);
	registerCronScratchCommand(t);
	registerCronEditCommand(t);
	setCommandJsonMode(t, "output", ({ argv: e }) => isCronMachineOutput(e));
	applyParentDefaultHelpAction(t);
}
//#endregion
export { registerCronCli };