@xiangyixie/dsh-superagent 0.18.4 → 0.19.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/lib/index.js +177 -15
- package/lib/schedule.js +92 -1
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -35,7 +35,15 @@ import { createMemory, isInside, MEMORY_KINDS, normalizeScope } from './memory.j
|
|
|
35
35
|
import { createUserMemory, USER_MEMORY_CATEGORIES } from './user-memory.js'
|
|
36
36
|
import { createNotifyPolicy, createOutbox } from './notify.js'
|
|
37
37
|
import { createRuntimeControl } from './runtime-control.js'
|
|
38
|
-
import {
|
|
38
|
+
import {
|
|
39
|
+
createScheduler,
|
|
40
|
+
formatSchedule,
|
|
41
|
+
formatScheduleList,
|
|
42
|
+
normalizeScheduleInput,
|
|
43
|
+
rruleForInterval,
|
|
44
|
+
rruleFromCron,
|
|
45
|
+
rruleWithStart,
|
|
46
|
+
} from './schedule.js'
|
|
39
47
|
import { createLongGoalManager, formatStatus as formatLongGoal } from './long-goal.js'
|
|
40
48
|
import { ACTIVE_STATUSES, createStore, resolveStateRoot, TERMINAL_STATUSES } from './store.js'
|
|
41
49
|
import { createTemplateStore, expandTemplate, formatTemplateDetail, formatTemplateList, TemplateError } from './templates.js'
|
|
@@ -596,8 +604,7 @@ function acceptanceFromToolArgs(entry) {
|
|
|
596
604
|
* `budget` is read only for `superagent_start`; on a schedule, `budget` is the
|
|
597
605
|
* plan's own spending ceiling and is not a goal-mode field.
|
|
598
606
|
*/
|
|
599
|
-
function goalModeFromToolArgs(args, { budget = true } = {}) {
|
|
600
|
-
if (args.goal_mode !== true) {
|
|
607
|
+
function goalModeFromToolArgs(args, { budget = true } = {}) { if (args.goal_mode !== true) {
|
|
601
608
|
if (args.acceptance !== undefined) {
|
|
602
609
|
throw new Error('acceptance is only read in goal mode; pass goal_mode: true to enable it (goal mode is off by default)')
|
|
603
610
|
}
|
|
@@ -615,6 +622,95 @@ function goalModeFromToolArgs(args, { budget = true } = {}) {
|
|
|
615
622
|
}
|
|
616
623
|
}
|
|
617
624
|
|
|
625
|
+
/** The Host Schedule tool a root Agent can call itself, when the host exposes it. */
|
|
626
|
+
const HOST_SCHEDULE_TOOL = 'schedule_create'
|
|
627
|
+
|
|
628
|
+
/**
|
|
629
|
+
* Resolve whether this caller may create a Host scheduled task.
|
|
630
|
+
*
|
|
631
|
+
* The host tool refuses delegated subagents, so they stay on the local timer
|
|
632
|
+
* instead of asking for a handoff that would fail. A missing tools service or
|
|
633
|
+
* a preset without `dsh-tool-schedule` reads as unavailable, never as "try it".
|
|
634
|
+
*
|
|
635
|
+
* @param {object} agent - calling Agent.
|
|
636
|
+
* @returns {string | null} tool name, or null when the plugin must keep the timer.
|
|
637
|
+
*/
|
|
638
|
+
function hostScheduleToolFor(agent) {
|
|
639
|
+
const header = agent?.session?.header
|
|
640
|
+
if ((header?.delegationDepth ?? 0) > 0) return null
|
|
641
|
+
try {
|
|
642
|
+
const tools = agent?.ctx?.tools
|
|
643
|
+
if (typeof tools?.get !== 'function') return null
|
|
644
|
+
return tools.get(HOST_SCHEDULE_TOOL, agent.ctx) ? HOST_SCHEDULE_TOOL : null
|
|
645
|
+
} catch {
|
|
646
|
+
return null
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/** `superagent_start` arguments one host-delivered message should repeat. */
|
|
651
|
+
function startArgsForDraft(draft, args = {}) {
|
|
652
|
+
return {
|
|
653
|
+
goal: draft.goal,
|
|
654
|
+
mode: draft.mode,
|
|
655
|
+
session_id: draft.ownerSessionId,
|
|
656
|
+
...(args.goal_mode === undefined ? {} : { goal_mode: args.goal_mode }),
|
|
657
|
+
...(args.acceptance === undefined ? {} : { acceptance: args.acceptance }),
|
|
658
|
+
...(args.max_rounds === undefined ? {} : { max_rounds: args.max_rounds }),
|
|
659
|
+
...(args.max_wall_clock_minutes === undefined ? {} : { max_wall_clock_minutes: args.max_wall_clock_minutes }),
|
|
660
|
+
...(args.no_progress_rounds === undefined ? {} : { no_progress_rounds: args.no_progress_rounds }),
|
|
661
|
+
...(args.budget === undefined ? {} : { budget: args.budget }),
|
|
662
|
+
...(args.human_priority === undefined ? {} : { human_priority: args.human_priority }),
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
/** `superagent_start` arguments a stored plugin-local plan should repeat. */
|
|
667
|
+
function startArgsForPlan(plan) {
|
|
668
|
+
return {
|
|
669
|
+
goal: plan.goal,
|
|
670
|
+
mode: plan.mode,
|
|
671
|
+
session_id: plan.ownerSessionId,
|
|
672
|
+
...(plan.goalMode ? { goal_mode: true } : {}),
|
|
673
|
+
...(plan.concurrency?.humanPriority === false ? { human_priority: false } : {}),
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
/** The exact `schedule_create` payload for one stored plan, or null when cron cannot be mapped. */
|
|
678
|
+
function schedulePayloadFor(plan) {
|
|
679
|
+
const rule = plan.schedule.cron ? rruleFromCron(plan.schedule.cron) : rruleForInterval(plan.schedule.everyMinutes)
|
|
680
|
+
if (!rule) return null
|
|
681
|
+
return {
|
|
682
|
+
title: plan.name,
|
|
683
|
+
prompt: `[scheduled task ${plan.name}] Start the scheduled run now by calling superagent_start with these arguments:\n`
|
|
684
|
+
+ `${JSON.stringify(startArgsForPlan(plan), null, 2)}\n`
|
|
685
|
+
+ 'This message is the recurring trigger; do not create or edit the schedule.',
|
|
686
|
+
rrule: rruleWithStart(rule, plan.schedule.timeZone),
|
|
687
|
+
target: 'this_session',
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/**
|
|
692
|
+
* Tell the model to create the plan through the host instead of returning a
|
|
693
|
+
* plugin timer. The tool result carries the exact arguments so the follow-up
|
|
694
|
+
* call needs no translation.
|
|
695
|
+
*/
|
|
696
|
+
function scheduleHandoffText({ draft, rrule, toolName, args }) {
|
|
697
|
+
const payload = {
|
|
698
|
+
title: draft.name,
|
|
699
|
+
prompt: `[scheduled task ${draft.name}] Start the scheduled run now by calling superagent_start with these arguments:\n`
|
|
700
|
+
+ `${JSON.stringify(startArgsForDraft(draft, args), null, 2)}\n`
|
|
701
|
+
+ 'This message is the recurring trigger; do not create or edit the schedule.',
|
|
702
|
+
rrule: rruleWithStart(rrule, draft.schedule.timeZone),
|
|
703
|
+
target: 'this_session',
|
|
704
|
+
}
|
|
705
|
+
return `handoff: this host exposes ${toolName}, so this plan belongs to the Host Scheduler, not to the plugin.\n\n`
|
|
706
|
+
+ 'Call it now with exactly these arguments:\n'
|
|
707
|
+
+ `${JSON.stringify(payload, null, 2)}\n\n`
|
|
708
|
+
+ 'Do not tell the user the schedule exists until that call succeeds. It will then appear in the host\'s '
|
|
709
|
+
+ 'scheduled tasks and deliver the prompt above to this session at each occurrence.\n'
|
|
710
|
+
+ 'No timer is armed in this plugin for a host-backed plan. If the call fails, report its error verbatim; '
|
|
711
|
+
+ 'do not fall back to a local timer silently.'
|
|
712
|
+
}
|
|
713
|
+
|
|
618
714
|
function usageLine(usage, status) {
|
|
619
715
|
if (!usage || !usage.modelCalls) {
|
|
620
716
|
if (ACTIVE_STATUSES.has(status)) {
|
|
@@ -2486,7 +2582,9 @@ export function apply(ctx, config) {
|
|
|
2486
2582
|
return [
|
|
2487
2583
|
'已展开,下一步起可用(参数见各自 schema):',
|
|
2488
2584
|
'- superagent_goal: 长期目标按阶段推进,多里程碑或必须按序时用;action=create/status/list/answer/retry_phase/resume/pause/cancel',
|
|
2489
|
-
'- superagent_schedule: 定时或按间隔自动起 run;action=create/list/pause/resume/delete/run-now'
|
|
2585
|
+
'- superagent_schedule: 定时或按间隔自动起 run;action=create/list/migrate/pause/resume/delete/run-now。'
|
|
2586
|
+
+ '宿主会话能调 schedule_create 时,create 只返回要转交的参数,必须自己调 schedule_create 建到宿主定时任务里;'
|
|
2587
|
+
+ '插件本地定时只作兜底',
|
|
2490
2588
|
'- superagent_inject: 给正在跑的 worker 立刻发指令;不着急就用 superagent_followup',
|
|
2491
2589
|
'- superagent_memory: 跨 run 笔记;action=list/search/set/forget,layer="user" 读写用户级事实',
|
|
2492
2590
|
'- superagent_template: 工作流模板;action=list/show/expand/save/delete,expand 出 goal 再 start',
|
|
@@ -3005,15 +3103,16 @@ export function apply(ctx, config) {
|
|
|
3005
3103
|
registerTool(defineTool({
|
|
3006
3104
|
name: 'superagent_schedule',
|
|
3007
3105
|
description:
|
|
3008
|
-
'Create and manage scheduled runs that start on
|
|
3009
|
-
+ 'superagent_start. Actions: create, list, pause, resume, delete, run-now.
|
|
3010
|
-
+ '
|
|
3011
|
-
+ '
|
|
3106
|
+
'Create and manage scheduled runs that start on cron or a fixed interval without anyone calling '
|
|
3107
|
+
+ 'superagent_start. Actions: create, list, migrate, pause, resume, delete, run-now. When this session has '
|
|
3108
|
+
+ 'schedule_create, create returns a handoff payload: call schedule_create with it so the plan lands in the '
|
|
3109
|
+
+ 'host\'s scheduled tasks. The plugin timer is only a fallback for subagents, presets without '
|
|
3110
|
+
+ 'dsh-tool-schedule, and cron with no lossless RRULE mapping. Cron is 5 fields; seconds and macros are refused.',
|
|
3012
3111
|
properties: {
|
|
3013
3112
|
action: {
|
|
3014
3113
|
type: 'string',
|
|
3015
|
-
enum: ['create', 'list', 'pause', 'resume', 'delete', 'run-now'],
|
|
3016
|
-
description: 'create, list, pause/resume, delete, or start one run now
|
|
3114
|
+
enum: ['create', 'list', 'migrate', 'pause', 'resume', 'delete', 'run-now'],
|
|
3115
|
+
description: 'create, list, migrate local plans to the Host Scheduler, pause/resume, delete, or start one run now.',
|
|
3017
3116
|
},
|
|
3018
3117
|
id: { type: 'string', description: 'Schedule id (sch-...); required for pause, resume, delete, run-now.' },
|
|
3019
3118
|
name: { type: 'string', description: 'create: short name used in list and notifications.' },
|
|
@@ -3134,6 +3233,40 @@ export function apply(ctx, config) {
|
|
|
3134
3233
|
}
|
|
3135
3234
|
: null
|
|
3136
3235
|
const recovery = scheduleOwnerRecovery()
|
|
3236
|
+
// Validate the timing before choosing an owner for the timer: a bad
|
|
3237
|
+
// cron must fail the same way whether the host or the plugin runs it.
|
|
3238
|
+
let draft
|
|
3239
|
+
try {
|
|
3240
|
+
draft = normalizeScheduleInput({
|
|
3241
|
+
name: args.name,
|
|
3242
|
+
goal,
|
|
3243
|
+
mode: args.mode,
|
|
3244
|
+
cron: args.cron,
|
|
3245
|
+
everyMinutes: args.every_minutes,
|
|
3246
|
+
timeZone: args.timezone,
|
|
3247
|
+
missPolicy: args.miss_policy,
|
|
3248
|
+
goalMode: goalModeFromToolArgs(args, { budget: false }),
|
|
3249
|
+
budget,
|
|
3250
|
+
humanPriority: args.human_priority,
|
|
3251
|
+
ownerSessionId: String(args.session_id ?? check.agent.id).trim(),
|
|
3252
|
+
ownerRecovery: recovery,
|
|
3253
|
+
cwd: check.agent.session?.cwd ?? workbenchRoot,
|
|
3254
|
+
}, { now: () => Date.now() })
|
|
3255
|
+
} catch (error) {
|
|
3256
|
+
return describeError(error)
|
|
3257
|
+
}
|
|
3258
|
+
const hostTool = hostScheduleToolFor(check.agent)
|
|
3259
|
+
const hostRule = hostTool
|
|
3260
|
+
? (draft.schedule.cron ? rruleFromCron(draft.schedule.cron) : rruleForInterval(draft.schedule.everyMinutes))
|
|
3261
|
+
: null
|
|
3262
|
+
if (hostTool && hostRule) {
|
|
3263
|
+
return scheduleHandoffText({ draft, rrule: hostRule, toolName: hostTool, args })
|
|
3264
|
+
}
|
|
3265
|
+
const fallbackReason = hostTool
|
|
3266
|
+
? `cron "${draft.schedule.cron}" has no lossless RRULE equivalent in ${hostTool}, so the plan stays local`
|
|
3267
|
+
: (check.agent.session?.header?.delegationDepth ?? 0) > 0
|
|
3268
|
+
? `a delegated subagent cannot call ${HOST_SCHEDULE_TOOL}, so the plan stays local`
|
|
3269
|
+
: `this session cannot call ${HOST_SCHEDULE_TOOL} (the host preset does not mount dsh-tool-schedule), so the plan stays local`
|
|
3137
3270
|
const plan = await scheduler.create({
|
|
3138
3271
|
name: args.name,
|
|
3139
3272
|
goal,
|
|
@@ -3148,6 +3281,7 @@ export function apply(ctx, config) {
|
|
|
3148
3281
|
ownerSessionId: String(args.session_id ?? check.agent.id).trim(),
|
|
3149
3282
|
ownerRecovery: recovery,
|
|
3150
3283
|
cwd: check.agent.session?.cwd ?? workbenchRoot,
|
|
3284
|
+
fallbackReason,
|
|
3151
3285
|
})
|
|
3152
3286
|
const warning = recovery === 'none'
|
|
3153
3287
|
? '\n\nwarning: this host has no Host Session API, so it cannot reopen the owning session after a '
|
|
@@ -3156,10 +3290,9 @@ export function apply(ctx, config) {
|
|
|
3156
3290
|
: ''
|
|
3157
3291
|
const hostNotice = hostScheduleVisible
|
|
3158
3292
|
? ''
|
|
3159
|
-
: '\n\nnote:
|
|
3160
|
-
+
|
|
3161
|
-
|
|
3162
|
-
return `created schedule ${plan.id}. The timer is armed from now on; no further tool call is needed.\n\n`
|
|
3293
|
+
: '\n\nnote: the plugin context itself has no ctx.schedule; the local timer is the only engine here. '
|
|
3294
|
+
+ `It checks every ${cfg.schedulerTickSeconds}s while the app is running.`
|
|
3295
|
+
return `created schedule ${plan.id}. The plugin-local timer is armed from now on; no further tool call is needed.\n\n`
|
|
3163
3296
|
+ formatSchedule(plan) + warning + hostNotice
|
|
3164
3297
|
}
|
|
3165
3298
|
if (action === 'list') {
|
|
@@ -3170,6 +3303,35 @@ export function apply(ctx, config) {
|
|
|
3170
3303
|
+ `${snapshot.waiting} waiting (${snapshot.manualWaiting} manual)`
|
|
3171
3304
|
return `${formatScheduleList(plans)}\n${quota}`
|
|
3172
3305
|
}
|
|
3306
|
+
if (action === 'migrate') {
|
|
3307
|
+
const plans = await scheduler.list()
|
|
3308
|
+
if (plans.length === 0) {
|
|
3309
|
+
return 'no plugin-local plans to migrate; every new plan on this host is created through schedule_create already'
|
|
3310
|
+
}
|
|
3311
|
+
const migrated = []
|
|
3312
|
+
const skipped = []
|
|
3313
|
+
for (const plan of plans) {
|
|
3314
|
+
const payload = schedulePayloadFor(plan)
|
|
3315
|
+
if (!payload) {
|
|
3316
|
+
skipped.push(`${plan.id} ("${plan.name}"): cron "${plan.schedule.cron}" has no lossless RRULE equivalent`)
|
|
3317
|
+
continue
|
|
3318
|
+
}
|
|
3319
|
+
if (plan.enabled) await scheduler.pause(plan.id, 'migrating to a Host scheduled task')
|
|
3320
|
+
migrated.push({ pluginId: plan.id, arguments: payload })
|
|
3321
|
+
}
|
|
3322
|
+
const lines = [
|
|
3323
|
+
`migration: ${migrated.length} plan(s) are paused and ready to move to the Host Scheduler.`,
|
|
3324
|
+
'For each one, call schedule_create with the arguments below, then call superagent_schedule '
|
|
3325
|
+
+ 'action="delete" with the pluginId once the host task exists. A paused local plan cannot double-fire '
|
|
3326
|
+
+ 'while the host task is being created; action="resume" undoes the pause if the migration is abandoned.',
|
|
3327
|
+
JSON.stringify(migrated, null, 2),
|
|
3328
|
+
]
|
|
3329
|
+
if (skipped.length > 0) {
|
|
3330
|
+
lines.push('these plans stay local because their cron cannot be mapped without changing the schedule:')
|
|
3331
|
+
lines.push(...skipped.map(line => `- ${line}`))
|
|
3332
|
+
}
|
|
3333
|
+
return lines.join('\n')
|
|
3334
|
+
}
|
|
3173
3335
|
if (action === 'pause') {
|
|
3174
3336
|
const plan = await scheduler.pause(String(args.id ?? ''), 'paused by superagent_schedule')
|
|
3175
3337
|
return `paused ${plan.id} ("${plan.name}"). It will not start again until action="resume".`
|
|
@@ -3187,7 +3349,7 @@ export function apply(ctx, config) {
|
|
|
3187
3349
|
return `started ${run.id} now for schedule ${plan.id} ("${plan.name}"); its next planned window is `
|
|
3188
3350
|
+ `${plan.nextRunAt}. Poll the run with superagent_status.`
|
|
3189
3351
|
}
|
|
3190
|
-
return describeError(`unknown action "${args.action}"; use create, list, pause, resume, delete, or run-now`)
|
|
3352
|
+
return describeError(`unknown action "${args.action}"; use create, list, migrate, pause, resume, delete, or run-now`)
|
|
3191
3353
|
} catch (error) {
|
|
3192
3354
|
if (error instanceof TemplateError) return templateProblem(error)
|
|
3193
3355
|
return describeError(error)
|
package/lib/schedule.js
CHANGED
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
import { randomUUID } from 'node:crypto'
|
|
22
22
|
import fsp from 'node:fs/promises'
|
|
23
23
|
import path from 'node:path'
|
|
24
|
-
import { nextCronTime, parseCron, validateTimeZone } from './cron.js'
|
|
24
|
+
import { nextCronTime, parseCron, validateTimeZone, zonedParts } from './cron.js'
|
|
25
25
|
import { normalizeGoalSpec } from './goal.js'
|
|
26
26
|
import { ACTIVE_STATUSES, TERMINAL_STATUSES } from './store.js'
|
|
27
27
|
|
|
@@ -146,6 +146,7 @@ export function normalizeScheduleInput(input = {}, { now }) {
|
|
|
146
146
|
ownerRecovery,
|
|
147
147
|
requiresLiveSession: ownerRecovery === 'none',
|
|
148
148
|
cwd: input.cwd ? path.resolve(String(input.cwd)) : null,
|
|
149
|
+
fallbackReason: input.fallbackReason ? String(input.fallbackReason) : null,
|
|
149
150
|
createdAt,
|
|
150
151
|
updatedAt: createdAt,
|
|
151
152
|
nextRunAt: null,
|
|
@@ -983,6 +984,9 @@ export function formatScheduleList(plans) {
|
|
|
983
984
|
lines.push(
|
|
984
985
|
`- ${plan.id} ${plan.name} — ${state}`,
|
|
985
986
|
` when: ${when}; miss policy ${plan.schedule.missPolicy}; next ${plan.nextRunAt ?? 'not computed'}`,
|
|
987
|
+
` engine: plugin-local timer (fallback: ${plan.fallbackReason ?? 'plan predates host-schedule handoff'}) — `
|
|
988
|
+
+ "runs only while this host process is alive and is not listed in the host's scheduled tasks; "
|
|
989
|
+
+ 'migrate with action="migrate"',
|
|
986
990
|
` last: ${plan.lastStatus ?? 'never'}; failures in a row ${plan.consecutiveFailures}; `
|
|
987
991
|
+ `runs ${plan.totalRuns} (${plan.catchUpRuns ?? 0} catch-up); missed ${plan.missedRuns}; `
|
|
988
992
|
+ `skipped ${plan.skippedRuns ?? 0}`,
|
|
@@ -1011,6 +1015,7 @@ export function formatSchedule(plan) {
|
|
|
1011
1015
|
`schedule ${plan.id} — ${plan.name}`,
|
|
1012
1016
|
`goal: ${oneLine(plan.goal, 300)}${plan.goal.length > 300 ? '…' : ''}`,
|
|
1013
1017
|
`when: ${when}; miss policy ${plan.schedule.missPolicy}`,
|
|
1018
|
+
`engine: plugin-local timer (fallback: ${plan.fallbackReason ?? 'plan predates host-schedule handoff'})`,
|
|
1014
1019
|
`next: ${plan.nextRunAt ?? 'not computed'}; last: ${plan.lastStatus ?? 'never'}`,
|
|
1015
1020
|
`owner: session ${plan.ownerSessionId}; mode ${plan.mode}${plan.goalMode ? '; goal mode on' : ''}`
|
|
1016
1021
|
+ `${plan.ownerRecovery ? `; restart recovery ${plan.ownerRecovery}` : ''}`
|
|
@@ -1029,3 +1034,89 @@ export function formatSchedule(plan) {
|
|
|
1029
1034
|
}
|
|
1030
1035
|
return lines.join('\n')
|
|
1031
1036
|
}
|
|
1037
|
+
|
|
1038
|
+
/**
|
|
1039
|
+
* Map a 5-field cron expression to the RRULE subset the Host Schedule tool
|
|
1040
|
+
* accepts, or null when the conversion would not be lossless.
|
|
1041
|
+
*
|
|
1042
|
+
* The host tool refuses BY parts on MINUTELY and HOURLY and keeps day-of-month
|
|
1043
|
+
* and month work behind MONTHLY/YEARLY, so only the plain shapes below are
|
|
1044
|
+
* converted. Everything else stays on the plugin-local timer on purpose.
|
|
1045
|
+
*
|
|
1046
|
+
* @param {string} expression - normalized 5-field cron.
|
|
1047
|
+
* @returns {string | null} RRULE body, or null when there is no exact mapping.
|
|
1048
|
+
*/
|
|
1049
|
+
export function rruleFromCron(expression) {
|
|
1050
|
+
const fields = String(expression ?? '').trim().split(/\s+/)
|
|
1051
|
+
if (fields.length !== 5) return null
|
|
1052
|
+
const [minute, hour, dom, month, dow] = fields
|
|
1053
|
+
if (dom !== '*' || month !== '*') return null
|
|
1054
|
+
if (minute === '*' && hour === '*' && dow === '*') return 'FREQ=MINUTELY;INTERVAL=1'
|
|
1055
|
+
const step = /^\*\/(\d{1,2})$/.exec(minute)
|
|
1056
|
+
if (step && hour === '*' && dow === '*') {
|
|
1057
|
+
const every = Number(step[1])
|
|
1058
|
+
return every >= 1 && every <= 59 ? `FREQ=MINUTELY;INTERVAL=${every}` : null
|
|
1059
|
+
}
|
|
1060
|
+
const minuteValue = /^\d{1,2}$/.test(minute) ? Number(minute) : null
|
|
1061
|
+
if (minuteValue === null || minuteValue > 59) return null
|
|
1062
|
+
if (dow === '*') {
|
|
1063
|
+
const hourValue = /^\d{1,2}$/.test(hour) ? Number(hour) : null
|
|
1064
|
+
if (hourValue === null || hourValue > 23) return null
|
|
1065
|
+
return `FREQ=DAILY;BYHOUR=${hourValue};BYMINUTE=${minuteValue}`
|
|
1066
|
+
}
|
|
1067
|
+
const hourValue = /^\d{1,2}$/.test(hour) ? Number(hour) : null
|
|
1068
|
+
if (hourValue === null || hourValue > 23) return null
|
|
1069
|
+
const byDay = weekdaysToByDay(dow)
|
|
1070
|
+
if (!byDay) return null
|
|
1071
|
+
return `FREQ=WEEKLY;BYDAY=${byDay};BYHOUR=${hourValue};BYMINUTE=${minuteValue}`
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
const WEEKDAY_NAMES = { SUN: 0, MON: 1, TUE: 2, WED: 3, THU: 4, FRI: 5, SAT: 6 }
|
|
1075
|
+
const WEEKDAY_CODES = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA']
|
|
1076
|
+
|
|
1077
|
+
function weekdayNumber(token) {
|
|
1078
|
+
const text = String(token).trim().toUpperCase()
|
|
1079
|
+
if (Object.hasOwn(WEEKDAY_NAMES, text)) return WEEKDAY_NAMES[text]
|
|
1080
|
+
if (!/^\d$/.test(text)) return null
|
|
1081
|
+
return Number(text) === 7 ? 0 : Number(text)
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
function weekdaysToByDay(field) {
|
|
1085
|
+
const days = []
|
|
1086
|
+
for (const token of String(field).split(',')) {
|
|
1087
|
+
const range = token.split('-')
|
|
1088
|
+
if (range.length === 2) {
|
|
1089
|
+
const from = weekdayNumber(range[0])
|
|
1090
|
+
const to = weekdayNumber(range[1])
|
|
1091
|
+
if (from === null || to === null || from > to) return null
|
|
1092
|
+
for (let day = from; day <= to; day++) days.push(WEEKDAY_CODES[day])
|
|
1093
|
+
continue
|
|
1094
|
+
}
|
|
1095
|
+
if (range.length !== 1) return null
|
|
1096
|
+
const one = weekdayNumber(token)
|
|
1097
|
+
if (one === null) return null
|
|
1098
|
+
days.push(WEEKDAY_CODES[one])
|
|
1099
|
+
}
|
|
1100
|
+
const unique = [...new Set(days)]
|
|
1101
|
+
return unique.length > 0 ? unique.join(',') : null
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
/** RRULE body for a fixed interval plan. */
|
|
1105
|
+
export function rruleForInterval(everyMinutes) {
|
|
1106
|
+
return `FREQ=MINUTELY;INTERVAL=${Number(everyMinutes)}`
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
/**
|
|
1110
|
+
* Prefix an RRULE body with the DTSTART line the Host Schedule tool requires.
|
|
1111
|
+
*
|
|
1112
|
+
* @param {string} rule - RRULE body such as `FREQ=DAILY;BYHOUR=9;BYMINUTE=0`.
|
|
1113
|
+
* @param {string} timeZone - IANA zone the rule is written in.
|
|
1114
|
+
* @param {number} [nowMs] - current epoch milliseconds.
|
|
1115
|
+
* @returns {string} two-line rrule document.
|
|
1116
|
+
*/
|
|
1117
|
+
export function rruleWithStart(rule, timeZone, nowMs = Date.now()) {
|
|
1118
|
+
const at = zonedParts(nowMs, timeZone)
|
|
1119
|
+
const pad = value => String(value).padStart(2, '0')
|
|
1120
|
+
const stamp = `${at.year}${pad(at.month)}${pad(at.day)}T${pad(at.hour)}${pad(at.minute)}${pad(at.second)}`
|
|
1121
|
+
return `DTSTART;TZID=${timeZone}:${stamp}\nRRULE:${rule}`
|
|
1122
|
+
}
|