@soffits/dsh-cron-jobs 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/controller.js CHANGED
@@ -2,6 +2,8 @@ import { JobRunner, agentModel, agentSettings, isGated, jobKind } from './job.js
2
2
  import { CronTimer, ScheduleError, ScheduleTimer, describeSchedule, parseSchedule, scheduleFromInput } from './schedule.js'
3
3
  import { JobStore } from './store.js'
4
4
  import { deliveryTarget, resolveDelivery } from './deliver.js'
5
+ import { DEFAULT_COALESCE_SECONDS, DEFAULT_MAX_RUNS_PER_HOUR, Deduper, EventBatcher, EventInputError, checkPatterns, normalizeEvent, subscribed } from './events.js'
6
+ import { WatcherInputError, WatcherSupervisor, checkWatcher } from './watchers.js'
5
7
 
6
8
  /** How often the watchdog looks for lost timers. */
7
9
  export const WATCHDOG_MS = 60_000
@@ -71,8 +73,12 @@ export class CronJobs {
71
73
  * @param {() => Date} [options.now]
72
74
  * @param {number} [options.watchdogMs] - How often the watchdog looks for lost timers; 0 turns it off.
73
75
  * @param {number} [options.overdueMs] - How far past its due time a tick must be before the watchdog runs it.
76
+ * @param {{ coalesceSeconds?: number, maxRunsPerHour?: number }} [options.events] - Event batching (events.js).
77
+ * @param {{ set: typeof setTimeout, clear: typeof clearTimeout }} [options.timers] - Event batch timers; replaceable for tests.
78
+ * @param {object[]} [options.watchers] - Watchers from the plugin config.
79
+ * @param {object} [options.watcherOptions] - Passed to {@link WatcherSupervisor} (stateRoot, limits, spawn).
74
80
  */
75
- constructor({ jobs, logger, run, wake, reuse, settle, send, answer, checks, defaults = {}, signal, record, history, CronClass = CronTimer, TimerClass = ScheduleTimer, now = () => new Date(), watchdogMs = WATCHDOG_MS, overdueMs = OVERDUE_MS }) {
81
+ constructor({ jobs, logger, run, wake, reuse, settle, send, answer, checks, defaults = {}, signal, record, history, CronClass = CronTimer, TimerClass = ScheduleTimer, now = () => new Date(), watchdogMs = WATCHDOG_MS, overdueMs = OVERDUE_MS, events = {}, timers, watchers = [], watcherOptions = {} }) {
76
82
  this.logger = logger
77
83
  this.defaults = defaults
78
84
  this.history = history
@@ -84,6 +90,25 @@ export class CronJobs {
84
90
  this.overdueMs = overdueMs
85
91
  this.record = record ?? (async () => {})
86
92
  this.deps = { run, wake, reuse, settle, send, answer, checks, defaults, logger, signal, record, history, now }
93
+ this.eventSettings = {
94
+ coalesceMs: (events.coalesceSeconds ?? DEFAULT_COALESCE_SECONDS) * 1000,
95
+ maxRunsPerHour: events.maxRunsPerHour ?? DEFAULT_MAX_RUNS_PER_HOUR,
96
+ ...(timers ? { timers } : {}),
97
+ }
98
+ this.deduper = new Deduper({ now: () => this.now().getTime() })
99
+ this.configWatchers = []
100
+ for (const def of watchers) {
101
+ if (def.enabled === false) continue
102
+ try {
103
+ const clean = checkWatcher(def)
104
+ if (this.configWatchers.some(other => other.id === clean.id)) throw new WatcherInputError(`duplicate watcher id ${clean.id}`)
105
+ this.configWatchers.push({ ...clean, source: 'config' })
106
+ } catch (error) {
107
+ logger.error('[watcher %s] not started: %s', def?.id, error instanceof Error ? error.message : String(error))
108
+ }
109
+ }
110
+ this.watcherOptions = watcherOptions
111
+ this.supervisor = undefined
87
112
  /** @type {Map<string, { job: object, runner: JobRunner, spec?: object, record?: object, timer?: any, error?: string }>} */
88
113
  this.entries = new Map()
89
114
  this.inflight = new Set()
@@ -111,9 +136,67 @@ export class CronJobs {
111
136
  ...(entry.record ? { keepSession: sessionId => this.keepSession(entry, sessionId) } : {}),
112
137
  })
113
138
  this.entries.set(entry.job.id, entry)
139
+ this.subscribe(entry)
114
140
  return entry
115
141
  }
116
142
 
143
+ /** (Re)create the event batcher of a job with `on`; waiting events are dropped. */
144
+ subscribe(entry) {
145
+ entry.batcher?.discard()
146
+ entry.batcher?.stop()
147
+ entry.batcher = undefined
148
+ if (!(entry.job.on?.length > 0)) return
149
+ entry.batcher = new EventBatcher({
150
+ ...this.eventSettings,
151
+ now: () => this.now().getTime(),
152
+ busy: () => entry.runner.running,
153
+ start: batch => this.runEvents(entry, batch),
154
+ })
155
+ }
156
+
157
+ /** Start an event run; the batcher only calls this when the job is idle. */
158
+ runEvents(entry, batch) {
159
+ if (this.stopped || !this.listening(entry)) return
160
+ this.runTracked(entry, entry.runner.tick({ trigger: 'event', events: batch }), { scheduled: true })
161
+ }
162
+
163
+ /**
164
+ * Whether a job takes events now: it subscribes, is not paused, ended or
165
+ * disabled, and its definition is valid.
166
+ */
167
+ listening(entry) {
168
+ if (entry.batcher === undefined || entry.error !== undefined) return false
169
+ if (entry.record) return entry.record.status === 'active'
170
+ return entry.job.enabled !== false && !this.pausedEntry(entry)
171
+ }
172
+
173
+ /**
174
+ * Take one event: drop a duplicate, hand it to every job listening on its
175
+ * channel, and call `release` once all those runs have started.
176
+ * @param {object} input - `{ channel, data?, text?, key?, source?, at? }`.
177
+ * @param {() => void} [release]
178
+ * @returns {{ matched: string[], duplicate?: true }} Ids of the jobs it went to.
179
+ * @throws {EventInputError} for a malformed event.
180
+ */
181
+ emit(input, release = () => {}) {
182
+ const event = normalizeEvent(input, this.now)
183
+ if (this.stopped) throw Object.assign(new Error('the scheduler is stopping'), { code: 'unavailable' })
184
+ if (this.deduper.seenBefore(event)) {
185
+ release()
186
+ this.record({ time: this.now().toISOString(), job: null, event: 'event', channel: event.channel, duplicate: true })
187
+ return { matched: [], duplicate: true }
188
+ }
189
+ const targets = [...this.entries.values()].filter(entry => this.listening(entry) && subscribed(entry.job.on, event.channel))
190
+ let left = targets.length
191
+ const done = () => { if (--left === 0) release() }
192
+ if (left === 0) release()
193
+ for (const entry of targets) entry.batcher.add(event, done)
194
+ const matched = targets.map(entry => entry.job.id)
195
+ this.record({ time: this.now().toISOString(), job: null, event: 'event', channel: event.channel, ...(event.source ? { source: event.source } : {}), matched })
196
+ if (matched.length > 0) this.logger.info('event %s for %s', event.channel, matched.join(', '))
197
+ return { matched }
198
+ }
199
+
117
200
  /** Arm the timers of jobs that should run; paused jobs start held. */
118
201
  start() {
119
202
  for (const entry of this.entries.values()) {
@@ -130,9 +213,87 @@ export class CronJobs {
130
213
  this.watchdog = setInterval(() => this.checkOverdue(), this.watchdogMs)
131
214
  this.watchdog.unref?.()
132
215
  }
216
+ this.startWatchers()
133
217
  return this
134
218
  }
135
219
 
220
+ /** Start the config and stored watchers. */
221
+ startWatchers() {
222
+ if (this.supervisor !== undefined || this.stopped) return
223
+ this.supervisor = new WatcherSupervisor({
224
+ ...this.watcherOptions,
225
+ emit: event => this.emit(event),
226
+ logger: this.logger,
227
+ record: this.record,
228
+ notify: (text, def) => this.notifyDefault(text, `watcher ${def.id}`),
229
+ onDone: id => this.watcherDone(id),
230
+ })
231
+ this.supervisor.set(this.watcherDefinitions())
232
+ }
233
+
234
+ /** Every watcher that should run: config ones first, then stored ones whose id is free. */
235
+ watcherDefinitions() {
236
+ const defs = [...this.configWatchers]
237
+ for (const [, stored] of this.history?.watchers?.entries() ?? []) {
238
+ if (defs.some(def => def.id === stored.id)) continue
239
+ defs.push({ id: stored.id, channel: stored.channel, command: stored.command, ...(stored.cwd ? { cwd: stored.cwd } : {}), ...(stored.once ? { once: true } : {}), source: 'tool' })
240
+ }
241
+ return defs
242
+ }
243
+
244
+ /** Send a note to the plugin's default delivery target, if there is one. */
245
+ async notifyDefault(text, from) {
246
+ const target = resolveDelivery({}, this.defaults.deliver)
247
+ if (target === undefined || this.deps.send === undefined) {
248
+ this.logger.warn('%s: %s (no delivery target)', from, text)
249
+ return
250
+ }
251
+ const sent = await this.deps.send(target, { text, files: [] }, { job: from }, {})
252
+ if (sent.status !== 'sent') this.logger.warn('%s: note not delivered: %s', from, sent.error)
253
+ }
254
+
255
+ /** A once watcher finished: forget its stored definition. */
256
+ async watcherDone(id) {
257
+ const table = this.history?.watchers
258
+ if (table?.get(id) === undefined) return
259
+ await table.delete(id)
260
+ this.supervisor?.set(this.watcherDefinitions())
261
+ }
262
+
263
+ /**
264
+ * Create a stored watcher and start it.
265
+ * @param {{ id: string, channel: string, command: string, cwd?: string, once?: boolean, createdBy?: string }} input
266
+ */
267
+ async createWatcher(input) {
268
+ const table = this.history?.watchers
269
+ if (table === undefined) throw new JobInputError('invalid_state', 'watcher storage is not available')
270
+ const def = checkWatcher(input)
271
+ if (this.configWatchers.some(other => other.id === def.id) || table.get(def.id) !== undefined) throw new WatcherInputError(`a watcher with id ${def.id} already exists`)
272
+ await table.put(def.id, { ...def, createdAt: this.now().toISOString(), ...(input.createdBy ? { createdBy: input.createdBy } : {}) })
273
+ this.supervisor?.set(this.watcherDefinitions())
274
+ return this.watcherView(def.id)
275
+ }
276
+
277
+ /** Stop and delete a stored watcher. */
278
+ async removeWatcher(id) {
279
+ const table = this.history?.watchers
280
+ if (this.configWatchers.some(other => other.id === id)) throw new JobInputError('read_only', `watcher ${JSON.stringify(id)} is defined in the plugin config; change it there`)
281
+ if (table?.get(id) === undefined) throw new JobInputError('not_found', `no watcher with id ${JSON.stringify(id)}`)
282
+ await table.delete(id)
283
+ this.supervisor?.set(this.watcherDefinitions())
284
+ return { id, deleted: true }
285
+ }
286
+
287
+ /** Watchers with their status. */
288
+ listWatchers() {
289
+ const running = new Map((this.supervisor?.list() ?? []).map(view => [view.id, view]))
290
+ return this.watcherDefinitions().map(def => running.get(def.id) ?? { id: def.id, channel: def.channel, command: def.command, cwd: def.cwd ?? null, once: def.once === true, source: def.source, state: 'stopped' })
291
+ }
292
+
293
+ watcherView(id) {
294
+ return this.listWatchers().find(view => view.id === id)
295
+ }
296
+
136
297
  /**
137
298
  * Find jobs whose next run is well in the past although nothing paused
138
299
  * them: their timer was lost. Each such tick is written to the run log as
@@ -169,7 +330,17 @@ export class CronJobs {
169
330
  this.logger.error('[%s] not scheduled: %s', job.name, entry.error)
170
331
  return
171
332
  }
333
+ if (job.onError) {
334
+ entry.error = job.onError
335
+ this.logger.error('[%s] not scheduled: %s', job.name, entry.error)
336
+ return
337
+ }
172
338
  if (record ? record.status === 'ended' : job.enabled === false) return
339
+ // Runs only on events: no timer.
340
+ if (entry.spec === undefined && !job.specError && job.on?.length > 0) {
341
+ this.logger.info('[%s] listening on %s%s', job.name, job.on.join(', '), this.pausedEntry(entry) ? ' (paused)' : '')
342
+ return
343
+ }
173
344
  const paused = this.pausedEntry(entry)
174
345
  let timer
175
346
  try {
@@ -201,22 +372,39 @@ export class CronJobs {
201
372
 
202
373
  fire(entry) {
203
374
  if (this.pausedEntry(entry)) return
204
- const tick = entry.runner.tick()
205
- this.track(entry.record ? tick.finally(() => this.saveNext(entry)) : tick, entry.job.name)
375
+ this.runTracked(entry, entry.runner.tick(), { scheduled: true })
376
+ }
377
+
378
+ /**
379
+ * Track a run; afterwards save a stored job's next run (for runs not
380
+ * started by hand) and let a waiting event batch run.
381
+ */
382
+ runTracked(entry, tick, { scheduled = false } = {}) {
383
+ const after = tick.finally(async () => {
384
+ if (scheduled && entry.record) await this.saveNext(entry)
385
+ }).finally(() => entry.batcher?.idle())
386
+ return this.track(after, entry.job.name)
206
387
  }
207
388
 
208
- /** After a scheduled run of a stored job: save its next run, or end it. */
389
+ /**
390
+ * After a scheduled or event run of a stored job: save its next run, or
391
+ * end it (a once job, or a schedule with no more runs and no events to
392
+ * wait for).
393
+ */
209
394
  async saveNext(entry) {
210
395
  if (this.entries.get(entry.job.id) !== entry || this.store === undefined) return
211
396
  const current = this.store.get(entry.job.id)
212
397
  if (current === undefined) return
213
398
  const next = entry.timer?.nextRun() ?? null
214
- const status = current.status === 'active' && next === null ? 'ended' : current.status
399
+ const listens = current.on?.length > 0
400
+ const ends = current.status === 'active' && (current.once === true || (next === null && !listens))
401
+ const status = ends ? 'ended' : current.status
215
402
  await this.saveRecord(entry, { ...current, status, scheduledAt: next?.toISOString() })
216
403
  if (status === 'ended') {
217
404
  entry.timer?.stop()
218
405
  entry.timer = undefined
219
- this.logger.info('[%s] ended: no more runs', entry.job.name)
406
+ entry.batcher?.discard()
407
+ this.logger.info('[%s] ended: %s', entry.job.name, current.once ? 'it runs once' : 'no more runs')
220
408
  }
221
409
  }
222
410
 
@@ -250,9 +438,13 @@ export class CronJobs {
250
438
  if (this.stopped) return Promise.allSettled([...this.inflight])
251
439
  this.stopped = true
252
440
  clearInterval(this.watchdog)
253
- for (const entry of this.entries.values()) entry.timer?.stop()
441
+ for (const entry of this.entries.values()) {
442
+ entry.timer?.stop()
443
+ entry.batcher?.stop()
444
+ }
445
+ const watchers = this.supervisor?.stop()
254
446
  const stopping = this.record({ time: this.now().toISOString(), job: null, event: 'scheduler-stop' })
255
- await Promise.allSettled([...this.inflight, stopping])
447
+ await Promise.allSettled([...this.inflight, stopping, watchers])
256
448
  }
257
449
 
258
450
  isPaused(id) {
@@ -292,7 +484,7 @@ export class CronJobs {
292
484
  if (entry === undefined) return { ok: false, code: 'not-found' }
293
485
  if (this.stopped) return { ok: false, code: 'stopped' }
294
486
  if (entry.runner.running) return { ok: false, code: 'busy' }
295
- this.track(entry.runner.tick({ trigger: 'manual' }), entry.job.name)
487
+ this.runTracked(entry, entry.runner.tick({ trigger: 'manual' }))
296
488
  return { ok: true, startedAt: entry.runner.current.startedAt }
297
489
  }
298
490
 
@@ -305,13 +497,14 @@ export class CronJobs {
305
497
  async setPaused(id, paused) {
306
498
  const entry = this.entries.get(id)
307
499
  if (entry === undefined) return { ok: false, code: 'not-found' }
500
+ if (paused) entry.batcher?.discard()
308
501
  if (entry.record) {
309
502
  if (entry.record.status === 'ended') return { ok: false, code: 'ended' }
310
503
  let status = paused ? 'paused' : 'active'
311
504
  if (paused) entry.timer?.pause?.()
312
505
  else entry.timer?.resume?.()
313
506
  const next = entry.timer?.nextRun() ?? null
314
- if (!paused && entry.timer && next === null) status = 'ended'
507
+ if (!paused && entry.timer && next === null && !(entry.record.on?.length > 0)) status = 'ended'
315
508
  await this.saveRecord(entry, {
316
509
  ...entry.record, status, updatedAt: this.now().toISOString(),
317
510
  scheduledAt: entry.timer ? next?.toISOString() : entry.record.scheduledAt,
@@ -351,21 +544,24 @@ export class CronJobs {
351
544
  async create(input) {
352
545
  const store = this.requireStore()
353
546
  const now = this.now()
354
- const spec = scheduleFromInput(input.schedule)
547
+ const on = input.on === undefined ? [] : patterns(input.on)
548
+ const spec = hasSchedule(input.schedule) || on.length === 0 ? scheduleFromInput(input.schedule ?? {}) : undefined
355
549
  const draft = {
356
550
  id: '',
357
551
  title: title(input.title),
358
552
  ...text('prompt', input.prompt),
359
553
  ...text('command', input.command),
360
554
  ...text('answerCheck', input.answerCheck),
361
- schedule: spec,
555
+ ...(spec ? { schedule: spec } : {}),
556
+ ...(on.length > 0 ? { on } : {}),
557
+ ...(input.once === true ? { once: true } : {}),
362
558
  ...(input.cwd ? { cwd: input.cwd } : {}),
363
559
  ...(input.preset ? { preset: input.preset } : {}),
364
560
  target: input.target ?? { kind: 'new' },
365
561
  ...(deliveryTarget(input.deliver) !== undefined ? { deliver: deliveryTarget(input.deliver) } : {}),
366
562
  ...(input.model !== undefined ? { model: storedModel(input.model) } : {}),
367
563
  status: 'active',
368
- scheduledAt: firstRun(spec, now),
564
+ ...(spec ? { scheduledAt: firstRun(spec, now) } : {}),
369
565
  createdAt: now.toISOString(),
370
566
  updatedAt: now.toISOString(),
371
567
  ...(input.createdBy ? { createdBy: input.createdBy } : {}),
@@ -404,16 +600,33 @@ export class CronJobs {
404
600
  if (patch.target !== undefined) next.target = patch.target
405
601
  if (patch.deliver !== undefined) next.deliver = deliveryTarget(patch.deliver)
406
602
  if (patch.model !== undefined) next.model = patch.model === null ? undefined : storedModel(patch.model)
603
+ if (patch.on !== undefined) {
604
+ const on = patterns(patch.on)
605
+ if (on.length > 0) next.on = on
606
+ else delete next.on
607
+ }
608
+ if (patch.once !== undefined) {
609
+ if (patch.once) next.once = true
610
+ else delete next.once
611
+ }
407
612
  if (patch.schedule !== undefined) {
408
- next.schedule = changedSchedule(current.schedule, patch.schedule)
409
- next.scheduledAt = firstRun(next.schedule, now)
410
- if (next.status === 'ended') next.status = 'active'
613
+ const schedule = changedSchedule(current.schedule, patch.schedule)
614
+ if (schedule === null) {
615
+ delete next.schedule
616
+ delete next.scheduledAt
617
+ } else {
618
+ next.schedule = schedule
619
+ next.scheduledAt = firstRun(next.schedule, now)
620
+ }
411
621
  }
622
+ // A new schedule or new subscriptions bring an ended job back.
623
+ if (next.status === 'ended' && (patch.schedule !== undefined || (patch.on !== undefined && next.on))) next.status = 'active'
412
624
  requireWork(next)
413
625
  await this.saveRecord(entry, next)
414
626
  entry.job = fromStored(entry.record)
415
627
  entry.spec = entry.job.spec
416
628
  entry.runner.job = entry.job
629
+ this.subscribe(entry)
417
630
  if (!this.stopped) this.arm(entry)
418
631
  this.logger.info('[%s] updated stored job %s', entry.job.name, id)
419
632
  return this.view(entry)
@@ -424,6 +637,8 @@ export class CronJobs {
424
637
  const entry = this.storedEntry(id)
425
638
  entry.timer?.stop()
426
639
  entry.timer = undefined
640
+ entry.batcher?.discard()
641
+ entry.batcher?.stop()
427
642
  await this.store.delete(id)
428
643
  this.entries.delete(id)
429
644
  await this.history?.forget(id)
@@ -451,7 +666,7 @@ export class CronJobs {
451
666
  else if (job.enabled === false) state = 'disabled'
452
667
  else if (error !== undefined) state = 'invalid'
453
668
  else if (paused) state = 'paused'
454
- else if (spec?.kind !== 'cron' && timer && this.nextRun(entry) === null) state = 'ended'
669
+ else if (spec?.kind !== 'cron' && timer && this.nextRun(entry) === null && !(job.on?.length > 0)) state = 'ended'
455
670
  else state = 'active'
456
671
  const next = state === 'active' ? this.nextRun(entry) : null
457
672
  const gated = isGated(job)
@@ -465,6 +680,9 @@ export class CronJobs {
465
680
  paused,
466
681
  pausedAt: record ? (paused ? record.updatedAt : null) : this.history?.state(job.id).pausedAt ?? null,
467
682
  schedule: spec ? { ...spec, text: describeSchedule(spec) } : null,
683
+ on: job.on?.length > 0 ? job.on : null,
684
+ once: job.once === true,
685
+ pendingEvents: entry.batcher?.size > 0 ? { count: entry.batcher.size, dueAt: new Date(entry.batcher.dueAt).toISOString() } : null,
468
686
  cron: spec?.kind === 'cron' ? spec.expression : null,
469
687
  timeZone: scheduleZone(spec) ?? null,
470
688
  command: job.command || null,
@@ -502,10 +720,19 @@ export class CronJobs {
502
720
  /** A config job as the runner and timers see it. */
503
721
  function fromConfig(job) {
504
722
  const given = ['cron', 'rrule', 'at'].filter(key => typeof job[key] === 'string' && job[key].trim() !== '')
723
+ let on
724
+ let onError
725
+ try {
726
+ on = checkPatterns(job.on ?? [])
727
+ } catch (error) {
728
+ onError = error.message
729
+ }
505
730
  let spec
506
731
  let specError
507
- if (given.length !== 1) {
508
- specError = 'set exactly one of cron, rrule or at'
732
+ if (given.length === 0 && on?.length > 0) {
733
+ // Runs only on events.
734
+ } else if (given.length !== 1) {
735
+ specError = on?.length > 0 ? 'set at most one of cron, rrule or at' : 'set exactly one of cron, rrule or at, or on'
509
736
  } else if (given[0] === 'cron') {
510
737
  spec = { kind: 'cron', expression: job.cron, ...(job.timeZone ? { timeZone: job.timeZone } : {}) }
511
738
  } else {
@@ -523,6 +750,8 @@ function fromConfig(job) {
523
750
  ...(spec?.kind !== 'cron' && spec ? { timeZone: scheduleZone(spec) } : {}),
524
751
  spec,
525
752
  specError,
753
+ on: on ?? [],
754
+ ...(onError ? { onError } : {}),
526
755
  ...(sessionId ? { target: { kind: 'session', sessionId } } : {}),
527
756
  }
528
757
  }
@@ -541,6 +770,8 @@ function fromStored(record) {
541
770
  target: record.target,
542
771
  ...(record.deliver !== undefined ? { deliver: record.deliver } : {}),
543
772
  spec: record.schedule,
773
+ on: record.on ?? [],
774
+ ...(record.once ? { once: true } : {}),
544
775
  }
545
776
  }
546
777
 
@@ -565,13 +796,27 @@ function firstRun(spec, now) {
565
796
  return first.toISOString()
566
797
  }
567
798
 
799
+ /** The edited schedule, or null when an empty cron, rrule or at removes it. */
568
800
  function changedSchedule(current, input) {
569
801
  const { cron, rrule, at, timeZone } = input
570
802
  if ([cron, rrule, at].some(value => value !== undefined && value !== '')) return scheduleFromInput(input)
571
- if (timeZone !== undefined && current.kind === 'cron') return scheduleFromInput({ cron: current.expression, timeZone })
803
+ if ([cron, rrule, at].some(value => value === '')) return null
804
+ if (timeZone !== undefined && current?.kind === 'cron') return scheduleFromInput({ cron: current.expression, timeZone })
572
805
  throw new ScheduleError('invalid_rule', 'give cron, rrule or at for the new schedule (timeZone alone changes only a cron schedule)')
573
806
  }
574
807
 
808
+ function hasSchedule(input) {
809
+ return input !== undefined && ['cron', 'rrule', 'at'].some(key => typeof input[key] === 'string' && input[key].trim() !== '')
810
+ }
811
+
812
+ function patterns(list) {
813
+ try {
814
+ return checkPatterns(list)
815
+ } catch (error) {
816
+ throw new JobInputError('invalid_job', error.message)
817
+ }
818
+ }
819
+
575
820
  function title(value) {
576
821
  const trimmed = typeof value === 'string' ? value.trim() : ''
577
822
  if (trimmed === '') throw new JobInputError('invalid_job', 'title must not be empty')
@@ -592,6 +837,7 @@ function storedModel(value) {
592
837
 
593
838
  function requireWork(record) {
594
839
  if (!record.prompt && !record.command) throw new JobInputError('invalid_job', 'a job needs a prompt, a command, or both')
840
+ if (record.schedule === undefined && !(record.on?.length > 0)) throw new JobInputError('invalid_job', 'a job needs a schedule, on (event channels), or both')
595
841
  if ((record.target.kind === 'session') && !record.target.sessionId) throw new JobInputError('invalid_job', 'a session target needs a session id')
596
842
  }
597
843