UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

10 lines • 21.8 kB
import{l as normalizeOptionalString,m as readNonBlankString,o as normalizeLowercaseStringOrEmpty}from"./string-coerce-CpTFcSwY.mjs";import{A as resolveExpiresAtMsFromDurationMs,D as parseStrictPositiveInteger,E as parseStrictNonNegativeInteger,V as timestampMsToIsoString,m as asSafeIntegerInRange,t as MAX_DATE_TIMESTAMP_MS}from"./number-coercion-B3CfI447.mjs";import{a as asOptionalRecord}from"./record-coerce-BTbqdJ3-.mjs";import{r as defaultRuntime,t as ExitError}from"./runtime-DIcLIHcp.mjs";import{o as getAsyncWorkSignal}from"./async-work-scope-DBcxYU4O.mjs";import{c as visibleWidth,s as truncateToVisibleWidth}from"./ansi-54CEWBZf.mjs";import{n as sanitizeTerminalText}from"./safe-text-B_QTgn0s.mjs";import{t as isAbortError}from"./abort-signal-BKkRe6pu.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{n as formatTimestamp}from"./timestamps-gtUruwBs.mjs";import{l as normalizeThinkLevel,r as THINKING_LEVELS_HELP}from"./thinking.shared-B2DqfPmC.mjs";import{t as parseDurationMs}from"./parse-duration-BueP0M46.mjs";import{r as listChannelPlugins}from"./registry-CpNh6QcT.mjs";import{i as readCronJobNotFoundError}from"./gateway-error-details-CMG6VuUF.mjs";import"./plugins-DxOycUNJ.mjs";import{n as isRich,r as theme,t as colorize}from"./theme-DS2CtI9X.mjs";import{t as danger}from"./globals-l9I53ZKA.mjs";import{t as GatewayClientRequestError}from"./request-error-DCrb--_5.mjs";import{n as formatDurationHuman}from"./format-duration-CDAHVcL7.mjs";import{t as ExpectedCliError}from"./expected-cli-error-oDVmXYil.mjs";import{r as isJsonOutputModeActive}from"./json-output-mode-SfJd0w4b.mjs";import{d as rethrowExpectedCliError,i as formatCliOperatorError}from"./failure-output-Gn9zHEk3.mjs";import{t as exitCliAfterOutput}from"./one-shot-exit-LLy48Ehj.mjs";import{n as callGatewayFromCli}from"./gateway-rpc-17pTfL8i.mjs";import{r as isOffsetlessIsoDateTime}from"./iso-time-BhVR3DDS.mjs";import{t as parseAbsoluteTimeMs}from"./parse-Cijfw9N8.mjs";import{n as resolveCronStaggerMs}from"./stagger-D1kYvF8-.mjs";import{t as parseOffsetlessIsoDateTimeInTimeZone}from"./parse-offsetless-zoned-datetime-CBjdLrzW.mjs";import{a as resolveTimezone}from"./format-datetime-Zj0XS4tu.mjs";import{t as buildCronCommandShellArgv}from"./command-shell-5btBWeTb.mjs";import{t as formatExactDuration}from"./format-duration-exact-Dmb7bay7.mjs";import{randomUUID}from"node:crypto"; //!src/cli/cron-cli/cron-cli-error.ts var CronCliError=class extends Error{constructor(e,t){super(typeof e===`string`?e:e.message,t);this.originalError=typeof e===`string`?void 0:e;this.matches=t?.matches}}; //!src/cli/cron-cli/shared.ts async function assertCronCliJobSpec(e){const{assertSupportedJobSpec:t}=await import(`./jobs-validation-CkPOx73y.mjs`);try{t(e)}catch(e){throw new CronCliError(e instanceof Error?e.message:String(e))}}function parseCronStringOption(e,t){const n=normalizeOptionalString(e);if(typeof e===`string`&&!n)throw new CronCliError(`${t} must not be blank`);return n}function parseCronThinkingOption(e){const t=normalizeOptionalString(e);if(t&&!normalizeThinkLevel(t))throw new CronCliError(`Invalid --thinking. Use one of: ${THINKING_LEVELS_HELP}.`);return t}function parseCronIntegerOption(e,t,n=`positive`){const r=n===`non-negative`?parseStrictNonNegativeInteger(e):parseStrictPositiveInteger(e);if(e!==void 0&&r===void 0)throw new CronCliError(`Invalid ${t} (must be a ${n} integer).`);return r}function assertCronTimeoutSupported(e){if(e===`script`)throw new CronCliError(`Use --script-timeout-seconds for script jobs, not --timeout-seconds.`);if(e!==`agentTurn`&&e!==`command`)throw new CronCliError(`--timeout-seconds is not supported for ${e} jobs.`)}function parseCronNoOutputTimeoutOption(e){return parseCronIntegerOption(e.noOutputTimeoutSeconds??(typeof e.outputTimeoutSeconds===`string`||typeof e.outputTimeoutSeconds===`number`?e.outputTimeoutSeconds:void 0),`--no-output-timeout-seconds`)}function parseCronArgv(e,t){if(typeof e!==`string`)return;let n;try{n=JSON.parse(e)}catch{throw new CronCliError(`${t} must be a JSON array of strings`)}if(!Array.isArray(n)||n.length===0||n.some(e=>typeof e!==`string`||e.length===0))throw new CronCliError(`${t} must be a non-empty JSON array of non-empty strings`);return n}function parseCronCommandArgv(e){return parseCronArgv(e,`--command-argv`)}function parseCronStreamCommandArgv(e){return parseCronArgv(e,`--stream-command`)}function parseCronCommandEnv(e){const t=Array.isArray(e)?e:typeof e===`string`?[e]:[];if(t.length===0)return;const n=Object.create(null);for(const e of t){if(typeof e!==`string`)throw new CronCliError(`--command-env must be KEY=VALUE`);const t=e.indexOf(`=`);const r=t>0?e.slice(0,t).trim():``;if(!r)throw new CronCliError(`--command-env must be KEY=VALUE`);n[r]=e.slice(t+1)}return n}const getCronChannelOptions=()=>{const e=listChannelPlugins().map(e=>e.id).filter(Boolean);return e.length>0?[`last`,...e].join(`|`):`last|<channel-plugin-id>`};function toLocalIsoTime(e){return typeof e===`number`&&Number.isFinite(e)?formatTimestamp(new Date(e),{style:`long`}):void 0}function enrichCronRunEntriesForDisplay(e){if(!e||typeof e!==`object`)return e;const t=e;const n=t.entries;if(!Array.isArray(n))return e;const r=n.map(e=>{if(!e||typeof e!==`object`)return e;const t=e;if(t.action!==`finished`)return t;const n={};const r=typeof t.errorReason===`string`?t.errorReason.trim():``;if(r)n.cause=r;for(const[e,r]of[[`ts`,`tsIso`],[`runAtMs`,`runAtIso`],[`nextRunAtMs`,`nextRunAtIso`]]){const i=toLocalIsoTime(t[e]);if(i)n[r]=i}return Object.keys(n).length>0?Object.assign({},t,n):t});return{...t,entries:r}}function printCronJson(e){defaultRuntime.writeJson(enrichCronRunEntriesForDisplay(e))}function enrichCronJsonWithStatus(e){if(!e||typeof e!==`object`)return e;const t=e;if(`state`in t&&`enabled`in t)return{...t,status:computeStatus(t)};if(`jobs`in t&&Array.isArray(t.jobs))return{...t,jobs:t.jobs.map(e=>Object.assign({},e,{status:computeStatus(e)}))};return e}function computeStatus(e){const t=asOptionalRecord(e.state)??{};if(t.runningAtMs)return`running`;if(!e.enabled)return`disabled`;return typeof t.lastRunStatus===`string`?t.lastRunStatus:typeof t.lastStatus===`string`?t.lastStatus:`idle`}function decorateStatusWithFailures(e,t){const n=t??0;if(e!==`error`||n<=1)return e;return n>99?`${e} (99+x)`:`${e} (${n}x)`}function formatCronStatusForDisplay(e){const t=e.state??{};const n=computeStatus(e);const r=e.enabled&&e.schedule?.kind===`stream`&&t.streamStatus===`disabled`;const i=n===`ok`&&t.lastDeliveryStatus===`not-delivered`;const a=n===`ok`&&t.lastDeliveryStatus===`unknown`;const o=i&&!r&&t.deliverySuppressionReason!==void 0;const s=n===`error`?theme.error:n===`running`||a||i&&!o?theme.warn:n===`ok`?theme.success:theme.muted;let c=decorateStatusWithFailures(n,t.consecutiveErrors);if(r&&n!==`running`)c=`disabled`;else if(n===`disabled`&&t.autoDisabled)c=t.autoDisabled.reason===`schedule-errors`?`disabled (schedule)`:`disabled (${t.autoDisabled.consecutiveErrors}x)`;else if(i)c=o?`ok (suppressed)`:`ok (not delivered)`;else if(a)c=`delivery unknown`;return{label:c,color:s}}function handleCronCliError(e){if(e instanceof ExitError)throw e;if(getAsyncWorkSignal()?.aborted&&isAbortError(e))return;rethrowExpectedCliError(e);const t=readCronJobNotFoundError(e);const n=e instanceof CronCliError?e.originalError??e:e;const r=e instanceof CronCliError?e.matches:void 0;if(isJsonOutputModeActive(process.argv)){if(!t&&!(e instanceof CronCliError)&&!(e instanceof GatewayClientRequestError))throw e;const i=t?formatCronLookupMiss(t.jobId):formatCliOperatorError(n);throw new ExpectedCliError({message:i,humanOutput:danger(i),machineOutput:i,matches:r})}const i=t?formatCronLookupMiss(t.jobId):formatErrorMessage(n);defaultRuntime.error(danger(r?`${i}\n${formatCronJobMatches(r)}`:i));exitCliAfterOutput(defaultRuntime,1)}function createCronAmbiguousNameError(e){return new CronCliError(`Multiple automations match this name. Retry this command with a matching job ID instead of the name.`,{matches:e.map(e=>({id:e.id,name:e.name,schedule:e.schedule?.kind===`on-exit`||e.schedule?.kind===`stream`?e.schedule.kind:formatSchedule(e.schedule,e.trigger!==void 0),enabled:e.enabled,status:computeStatus(e)}))})}function formatCronJobMatches(e){return[`Matching automations:`,...e.map(e=>` ${sanitizeTerminalText(e.id)} ${sanitizeTerminalText(e.name)}\n ${sanitizeTerminalText(e.schedule)}; enabled: ${e.enabled?`yes`:`no`}; status: ${sanitizeTerminalText(e.status)}`)].join(` `)}const formatCronLookupMiss=e=>`Automation not found: ${sanitizeTerminalText(e)}. Run \`${formatCliCommand(`openclaw cron list`)}\` to see recent automation ids.`;function requireCronJobId(e,t=`Pass it positionally.`){const n=normalizeOptionalString(e);if(!n)throw new CronCliError(`Missing job id. ${t}`);return n}async function warnIfCronSchedulerDisabled(e){try{const t=await callGatewayFromCli(`cron.status`,e,{});if(t?.enabled!==false)return;const n=typeof t?.sqlitePath===`string`?t.sqlitePath:typeof t?.storePath===`string`?t.storePath:``;defaultRuntime.error([`warning: the automations scheduler is disabled in the Gateway; jobs are saved but will not run automatically.`,"To enable automatic runs, set `cron.enabled: true` (or remove `cron.enabled: false`), remove `OPENCLAW_SKIP_CRON=1` from the Gateway's launch environment, and restart the Gateway.",n?`store: ${n}`:``].filter(Boolean).join(` `))}catch{}}async function buildCronCommandShellArgvForGateway(e,t){const n=`The Gateway did not report its platform, so --command cannot pick its shell. Pass the exact argv with --command-argv instead.`;let r;try{r=await callGatewayFromCli(`system.info`,t,{})}catch(e){if(e instanceof GatewayClientRequestError&&e.message===`unknown method: system.info`)throw new CronCliError(n,{cause:e});throw e}const i=readNonBlankString(r.platform);if(!i)throw new CronCliError(n);return buildCronCommandShellArgv(e,i)}function parsePositiveCronDurationMs(e){try{const t=parseDurationMs(e);return t>0&&t<=864e13?t:null}catch{return null}}function parseCronStaggerMs(e){if(e.useExact)return 0;if(!e.staggerRaw)return;const t=parsePositiveCronDurationMs(e.staggerRaw);if(!t)throw new CronCliError(`Invalid --stagger; use e.g. 30s, 1m, 5m`);return t}function parseCronStringList(e){if(e===void 0)return;return(Array.isArray(e)?e.map(e=>String(e)).join(` `):typeof e===`string`?e:``).split(/[,\s]+/u).filter(Boolean)}const INVALID_CRON_TIMEZONE_MESSAGE=`Invalid --tz. Use an IANA timezone such as America/New_York.`;function parseCronTimezoneOption(e){const t=normalizeOptionalString(e);if(t&&!resolveTimezone(t))throw new CronCliError(INVALID_CRON_TIMEZONE_MESSAGE);return t}function parseAt(e,t){const n=e.trim();if(!n)return null;if(t&&isOffsetlessIsoDateTime(n)){const e=parseOffsetlessIsoDateTimeInTimeZone(n,t);if(!e.ok){if(e.reason===`invalid-timezone`)throw new CronCliError(INVALID_CRON_TIMEZONE_MESSAGE);return null}return e.iso}parseCronTimezoneOption(t);const r=parseAbsoluteTimeMs(n);if(r!==null)return timestampMsToIsoString(r)??null;const i=parsePositiveCronDurationMs(n.startsWith(`+`)?n.slice(1):n);if(i!==null){const e=resolveExpiresAtMsFromDurationMs(i);return timestampMsToIsoString(e)??null}return null}const CRON_COLUMNS=[[`id`,`ID`,36],[`declaration`,`Declaration`,24],[`name`,`Name`,24],[`schedule`,`Schedule`,32],[`next`,`Next`,10],[`last`,`Last`,10],[`status`,`Status`,19],[`target`,`Target`,9],[`delivery`,`Delivery`,64],[`agent`,`Agent ID`,10],[`owner`,`Owner`,24],[`model`,`Model`,20]];const TRUNCATED_SUFFIX=`...`;const stringifyCell=(e,t=`-`)=>{if(typeof e===`string`)return e;if(typeof e===`number`||typeof e===`boolean`)return String(e);return t};const formatCell=(e,t)=>{const n=sanitizeTerminalText(stringifyCell(e));const r=visibleWidth(n)<=t?n:`${truncateToVisibleWidth(n,t-3)}${TRUNCATED_SUFFIX}`;const i=t-visibleWidth(r);return i>0?`${r}${` `.repeat(i)}`:r};const formatSpan=e=>e<6e4?`<1m`:formatDurationHuman(e);const formatRelative=(e,t)=>{if(!e)return`-`;const n=e-t;const r=formatSpan(Math.abs(n));return n>=0?`in ${r}`:`${r} ago`};const formatSchedule=(e,t=false,n=`summary`)=>{const r=t?`+trigger`:``;if(e?.kind===`at`){const t=timestampMsToIsoString(parseAbsoluteTimeMs(e.at));return`at ${(t&&n===`summary`?`${t.slice(0,-8)}Z`:t)?.replace(`T`,` `)??`-`}${r}`}if(e?.kind===`every`)return`every ${formatExactDuration(e.everyMs)}${r}`;if(e?.kind===`on-exit`){const t=e.cwd?` @ ${e.cwd}`:``;return`on-exit ${e.command}${t}`}if(e?.kind===`stream`){const t=e.cwd?` @ ${e.cwd}`:``;return`stream ${e.command.join(` `)}${t}${r}`}if(e?.kind===`event`)return`event ${e.source}`;if(e?.kind!==`cron`)return`-`;const i=e.tz?`cron ${e.expr} @ ${e.tz}${r}`:`cron ${e.expr}${r}`;const a=resolveCronStaggerMs(e);if(a<=0)return`${i} (exact)`;return`${i} (stagger ${formatExactDuration(a)})`};function coerceCronDeliveryPreviews(e){const t=e&&typeof e===`object`?e.deliveryPreviews:void 0;if(!t||typeof t!==`object`)return/* @__PURE__ */ new Map;return new Map(Object.entries(t).flatMap(([e,t])=>{if(!t||typeof t!==`object`)return[];const n=t;if(typeof n.label!==`string`||typeof n.detail!==`string`)return[];return[[e,{label:n.label,detail:n.detail}]]}))}function formatCronPolicies(e){const t=e.activeHours;const n=e.payload?.kind===`agentTurn`?e.payload.skipIfScratchEmpty:void 0;const r=e.payload?.kind===`agentTurn`?e.payload.includeReasoning:void 0;return sanitizeTerminalText([t?`active hours=${t.start}-${t.end} @ ${t.timezone??`user`}`:void 0,e.idleOnly!==void 0?`idle only=${e.idleOnly}`:void 0,e.delivery?.target?`delivery target=${e.delivery.target}`:void 0,e.delivery?.directPolicy?`direct policy=${e.delivery.directPolicy}`:void 0,n!==void 0?`skip if scratch empty=${n}`:void 0,r!==void 0?`include reasoning=${r}`:void 0].filter(e=>e!==void 0).join(`; `))}function printCronList(e,t=defaultRuntime,n){if(e.length===0){t.log(`No automations.`);return}const r=isRich();const i=CRON_COLUMNS.map(([,e,t])=>formatCell(e,t)).join(` `);const a=[r?theme.heading(i):i];const o=Date.now();for(const t of e){const e=t.state??{};const i=formatCronStatusForDisplay(t);const s=n?.deliveryPreviews?.get(t.id);const c=t.effectiveAgentId??t.agentId;const l=t.payload?.kind===`agentTurn`?t.payload.model:void 0;const u={id:[t.id,theme.accent],declaration:[t.declarationKey,theme.muted],name:[t.displayName??t.name,theme.info],schedule:[formatSchedule(t.schedule,t.trigger!==void 0),theme.info],next:[t.enabled?formatRelative(e.nextRunAtMs,o):`-`,theme.muted],last:[formatRelative(e.lastRunAtMs,o),theme.muted],status:[i.label,i.color],target:[t.sessionTarget,t.sessionTarget===`main`?theme.accent:theme.accentBright],delivery:[s?`${s.label} (${s.detail})`:`-`,s?theme.info:theme.muted],agent:[c??`unresolved`,c?theme.info:theme.muted],owner:[t.owner?.sessionKey??t.owner?.agentId,t.owner?theme.info:theme.muted],model:[l,l?theme.info:theme.muted]};const d=CRON_COLUMNS.map(([e,,t])=>{const[n,i]=u[e];return colorize(r,i,formatCell(n,t))}).join(` `);a.push(d.trimEnd());const f=formatCronPolicies(t);if(f)a.push(` policies: ${f}`)}t.log(a.join(` `))}function printCronShow(e,t=defaultRuntime,n){const r=n?.deliveryPreview??{label:`-`,detail:`unavailable`};const i=e.state??{};const a=e.payload?.kind===`agentTurn`?e.payload.model:void 0;const showValue=e=>sanitizeTerminalText(stringifyCell(e));t.log(`id: ${showValue(e.id)}`);t.log(`declaration: ${showValue(e.declarationKey)}`);t.log(`name: ${showValue(e.name)}`);t.log(`display name: ${showValue(e.displayName)}`);t.log(`owner agent: ${showValue(e.owner?.agentId)}`);t.log(`owner session: ${showValue(e.owner?.sessionKey)}`);t.log(`enabled: ${e.enabled?`yes`:`no`}`);const o=formatSchedule(e.schedule,e.trigger!==void 0,`detail`);t.log(`schedule: ${showValue(o)}`);t.log(`policies: ${formatCronPolicies(e)||`-`}`);if(e.schedule?.kind===`stream`){t.log(`stream status: ${showValue(i.streamStatus)}`);t.log(`stream error: ${showValue(i.streamError)}`)}t.log(`trigger: ${e.trigger?`once=${e.trigger.once===true?`yes`:`no`}; evals=${i.triggerEvalCount??0}; last eval=${formatRelative(i.lastTriggerEvalAtMs,Date.now())}; last fire=${formatRelative(i.lastTriggerFireAtMs,Date.now())}`:`-`}`);t.log(`session: ${showValue(e.sessionTarget)}`);t.log(`agent: ${showValue(e.agentId)}`);t.log(`model: ${showValue(a)}`);t.log(`delivery: ${showValue(r.label)} (${showValue(r.detail)})`);t.log(`next: ${formatRelative(i.nextRunAtMs,Date.now())}`);t.log(`last: ${formatRelative(i.lastRunAtMs,Date.now())}`);t.log(`status: ${showValue(formatCronStatusForDisplay(e).label)}`);t.log(`last error: ${showValue(i.lastError)}`);t.log(`last delivery: ${showValue(i.lastDeliveryStatus)}`);t.log(`last delivery suppression: ${showValue(i.deliverySuppressionReason)}`);t.log(`last delivery error: ${showValue(i.lastDeliveryError)}`);t.log(`diagnostic: ${showValue(i.lastDiagnosticSummary)}`)} //!src/cli/cron-cli/list-jobs.ts const CRON_LIST_PAGE_SIZE=200;const CRON_LIST_MAX_PAGES=50;const CRON_LIST_MAX_SNAPSHOT_RESTARTS=3;function isUnknownCronGetMethodError(e){return e instanceof Error&&e.name===`GatewayClientRequestError`&&e.gatewayCode===`INVALID_REQUEST`&&e.message.includes(`unknown method: cron.get`)}async function listCronJobsFromGateway(e,t,n={}){const r=getAsyncWorkSignal();let i=n.allowLegacyUnversionedPagination===true;for(let n=0;n<=CRON_LIST_MAX_SNAPSHOT_RESTARTS;n+=1){let n=0;let a;let o;let s;let c;let l=false;const u=[];const d={};for(let f=0;f<CRON_LIST_MAX_PAGES;f+=1){r?.throwIfAborted();const f=await callGatewayFromCli(`cron.list`,e,{...t,limit:CRON_LIST_PAGE_SIZE,offset:n},{signal:r});const p=f!==null&&typeof f===`object`&&(f.snapshotRevision!==void 0||f.total!==void 0||f.offset!==void 0||f.limit!==void 0);if(!f||typeof f!==`object`||!Array.isArray(f.jobs)||f.jobs.length>CRON_LIST_PAGE_SIZE||f.snapshotRevision!==void 0&&(typeof f.snapshotRevision!==`string`||f.snapshotRevision.length===0)||f.total!==void 0&&asSafeIntegerInRange(f.total,{min:0})===void 0||f.offset!==void 0&&asSafeIntegerInRange(f.offset,{min:0})===void 0||f.limit!==void 0&&(asSafeIntegerInRange(f.limit,{min:1,max:CRON_LIST_PAGE_SIZE})===void 0||f.jobs.length>f.limit)||f.hasMore!==void 0&&typeof f.hasMore!==`boolean`||p&&(f.snapshotRevision===void 0||f.total===void 0||f.offset===void 0||f.limit===void 0||f.hasMore===void 0||f.nextOffset===void 0))throw new Error(`cron.list returned an invalid inventory page`);const m=p?`canonical`:`legacy`;if(s!==void 0&&s!==m){l=true;break}if(a!==void 0&&f.snapshotRevision!==a||o!==void 0&&f.total!==o){l=true;break}if(f.offset!==void 0&&f.offset!==n)throw new Error(`cron.list returned an invalid inventory page`);if(!p&&!i){const t=f.jobs[0];if(t&&(typeof t.id!==`string`||t.id.length===0))throw new Error(`cron.list returned an invalid inventory page`);const n=t?.id??randomUUID();try{await callGatewayFromCli(`cron.get`,e,{id:n},{signal:r})}catch(e){if(isUnknownCronGetMethodError(e))i=true;else if(!isMissingCronGetError(e,n))throw e}if(!i)throw new Error(`cron.list returned an invalid inventory page`)}s??=m;c??=f;a??=f.snapshotRevision;o??=f.total;u.push(...f.jobs);if(f.deliveryPreviews)Object.assign(d,f.deliveryPreviews);if(!f.hasMore){if(o!==void 0&&u.length!==o||f.nextOffset!==void 0&&f.nextOffset!==null)throw new Error(`cron.list returned an inconsistent terminal inventory page`);return{...c,jobs:u,...Object.keys(d).length>0?{deliveryPreviews:d}:{},...c.hasMore!==void 0?{hasMore:false,nextOffset:null}:{}}}if(typeof f.nextOffset!==`number`||!Number.isSafeInteger(f.nextOffset)||f.nextOffset<=n||o!==void 0&&f.nextOffset!==n+f.jobs.length)throw new Error(`cron.list pagination did not advance while looking up automation`);n=f.nextOffset}if(!l)throw new Error(`cron.list pagination exceeded maximum pages while looking up automation`)}throw new Error(`cron.list inventory changed repeatedly while reading automations`)}function isMissingCronGetError(e,t){return isUnknownCronGetMethodError(e)||e instanceof Error&&e.name===`GatewayClientRequestError`&&e.gatewayCode===`INVALID_REQUEST`&&(e.message.includes(`automation not found: ${t}`)||e.message.includes(`cron job not found: ${t}`))}async function findCronJobByIdOrName(e,t,n={}){const r=getAsyncWorkSignal();let i=false;try{r?.throwIfAborted();const i=await callGatewayFromCli(`cron.get`,e,{id:t},{signal:r});if(i?.id===t){if(!n.includeDeliveryPreview)return{job:i};return{job:i,deliveryPreview:(await listCronJobsFromGateway(e,{includeDisabled:true,query:t})).deliveryPreviews?.[i.id]}}}catch(e){if(!isMissingCronGetError(e,t))throw e;i=isUnknownCronGetMethodError(e)}const a=await listCronJobsFromGateway(e,{includeDisabled:true},{allowLegacyUnversionedPagination:i});const o=normalizeLowercaseStringOrEmpty(t);let s=a.jobs.find(e=>normalizeLowercaseStringOrEmpty(e.id)===o);if(!s){const e=a.jobs.filter(e=>normalizeLowercaseStringOrEmpty(e.name)===o);if(e.length>1)throw createCronAmbiguousNameError(e);s=e[0]}return{job:s,deliveryPreview:s?a.deliveryPreviews?.[s.id]:void 0}}export{parsePositiveCronDurationMs as C,requireCronJobId as D,printCronShow as E,warnIfCronSchedulerDisabled as O,parseCronTimezoneOption as S,printCronList as T,parseCronStaggerMs as _,assertCronTimeoutSupported as a,parseCronStringOption as b,enrichCronJsonWithStatus as c,handleCronCliError as d,parseAt as f,parseCronNoOutputTimeoutOption as g,parseCronIntegerOption as h,assertCronCliJobSpec as i,CronCliError as k,formatCronLookupMiss as l,parseCronCommandEnv as m,isUnknownCronGetMethodError as n,buildCronCommandShellArgvForGateway as o,parseCronCommandArgv as p,listCronJobsFromGateway as r,coerceCronDeliveryPreviews as s,findCronJobByIdOrName as t,getCronChannelOptions as u,parseCronStreamCommandArgv as v,printCronJson as w,parseCronThinkingOption as x,parseCronStringList as y};