@goodandready/dsh-cron 0.3.33 → 0.3.34
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/README.md +6 -0
- package/README.ru.md +6 -0
- package/README.zh.md +6 -0
- package/lib/client-src/10-locales.js +13 -1
- package/lib/client-src/50-cron-screen-state.js +3 -0
- package/lib/client-src/53-cron-screen-modal-actions.js +11 -1
- package/lib/client-src/62-modal-task-form-tail.js +29 -1
- package/lib/client.js +53 -0
- package/lib/cron-tool.js +9 -0
- package/lib/locales.json +7 -1
- package/lib/scheduler/scheduler-execution.js +42 -1
- package/lib/scheduler/scheduler.js +23 -0
- package/lib/store/task-schema.js +2 -0
- package/lib/store/task-transfer.js +2 -0
- package/lib/task-create.js +3 -0
- package/lib/task-patch.js +7 -0
- package/lib/work-windows.js +167 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -699,3 +699,9 @@ Wake agent tasks reactively based on local events:
|
|
|
699
699
|
- **Marker / Flag File**: trigger when a flag file (e.g., `build.ready`) appears, with automatic consumption.
|
|
700
700
|
- **Process Exit**: monitor a PID or `.pid` file and trigger post-processing as soon as the background job completes.
|
|
701
701
|
Context is automatically injected into prompts (`{{trigger.type}}`, `{{trigger.fileCount}}`) and process environment variables (`DSH_CRON_WAKE_TYPE`, `DSH_CRON_WAKE_PATH`).
|
|
702
|
+
|
|
703
|
+
### Time-Boxing & Work Windows (v0.3.34)
|
|
704
|
+
|
|
705
|
+
- **Time-Boxing (`timeBoxMinutes`)**: Set a maximum wall-clock execution limit per run. When exceeded, the agent turn aborts gracefully.
|
|
706
|
+
- **Work Windows (`workWindow`)**: Restrict resource-intensive tasks to run only within specific hours (e.g., `22:00-07:00`) or days.
|
|
707
|
+
- **Outside Policy**: Choose to either `skip` runs outside the window or `defer` execution until the window opens.
|
package/README.ru.md
CHANGED
|
@@ -653,3 +653,9 @@ MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
|
|
|
653
653
|
- **Файл-флаг / маркер (`marker_file`)**: запуск при появлении файла готовности (например, `ready.flag`) с автоматическим удалением (`consumeMarker`).
|
|
654
654
|
- **Завершение процесса (`process_exit`)**: отслеживание PID или файла `.pid` и запуск постобработки сразу после завершения фонового процесса.
|
|
655
655
|
Контекст передается в переменные промпта (`{{trigger.type}}`, `{{trigger.fileCount}}`) и окружения (`DSH_CRON_WAKE_TYPE`).
|
|
656
|
+
|
|
657
|
+
### Ограничение времени и окна допустимой работы (v0.3.34)
|
|
658
|
+
|
|
659
|
+
- **Time-Boxing (`timeBoxMinutes`)**: Лимит общего времени выполнения задачи в минутах с мягким прерыванием по таймауту.
|
|
660
|
+
- **Окна работы (`workWindow`)**: Запуск тяжелых задач только в разрешенные часы (например, `22:00-07:00`) или дни недели.
|
|
661
|
+
- **Политика вне окна (`outsidePolicy`)**: `skip` (пропуск с записью статуса) или `defer` (откладывание до открытия окна).
|
package/README.zh.md
CHANGED
|
@@ -647,3 +647,9 @@ MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
|
|
|
647
647
|
- **标记/Flag文件到达 (`marker_file`)**: 标志文件出现时触发并自动删除标记文件。
|
|
648
648
|
- **进程退出监听 (`process_exit`)**: 监听 PID 或 `.pid` 文件,后台任务退出后立即唤醒任务进行后续处理。
|
|
649
649
|
上下文自动注入到提示词变量 (`{{trigger.type}}`, `{{trigger.fileCount}}`) 及环境变量中。
|
|
650
|
+
|
|
651
|
+
### 时间预算与运行窗口 (v0.3.34)
|
|
652
|
+
|
|
653
|
+
- **Time-Boxing (`timeBoxMinutes`)**: 设置单次执行的最长分钟上限,超时时通过 AbortSignal 优雅中止。
|
|
654
|
+
- **时间窗口 (`workWindow`)**: 限制高负载任务仅在指定时段(如 `22:00-07:00`)或特定星期内运行。
|
|
655
|
+
- **窗口外策略 (`outsidePolicy`)**: 支持 `skip`(跳过本次运行)或 `defer`(推迟到窗口开启时自动执行)。
|
|
@@ -215,7 +215,13 @@
|
|
|
215
215
|
'form.gracePeriodLabel': 'Heartbeat grace period (seconds)',
|
|
216
216
|
'form.priorityLabel': 'Queue priority (1-10, higher runs first)',
|
|
217
217
|
'form.concurrencyGroupLabel': 'Concurrency group',
|
|
218
|
-
|
|
218
|
+
'form.workWindowHoursLabel': 'Allowed work hours (e.g. 22:00-07:00)',
|
|
219
|
+
'form.workWindowHoursPlaceholder': 'e.g. 22:00-07:00 or 09:00-18:00',
|
|
220
|
+
'form.workWindowPolicyLabel': 'Outside window policy',
|
|
221
|
+
'form.workWindowPolicySkip': 'Skip execution (record skipped)',
|
|
222
|
+
'form.workWindowPolicyDefer': 'Defer until window opens',
|
|
223
|
+
'form.timeBoxMinutesLabel': 'Timebox deadline (minutes, 0 = unlimited)',
|
|
224
|
+
'form.wakeTriggerTypeLabel': 'Event wake trigger',
|
|
219
225
|
'form.wakeTriggerTypeNone': 'None (Schedule / Cron only)',
|
|
220
226
|
'form.wakeTriggerTypeFileCount': 'File count threshold (batch run)',
|
|
221
227
|
'form.wakeTriggerTypeMarkerFile': 'Marker file receipt (flag file)',
|
|
@@ -435,6 +441,12 @@
|
|
|
435
441
|
'form.preflightTargetLabel': '预检目标参数', 'form.preflightTargetPlaceholder': 'https://example.com/healthz 或 ls /data 或 /:10%',
|
|
436
442
|
'form.heartbeatIntervalLabel': '心跳打卡时限 (秒, 0 = 禁用)', 'form.gracePeriodLabel': '心跳宽限期 (秒)',
|
|
437
443
|
'form.priorityLabel': '队列优先级 (1-10,数值越大越先执行)', 'form.concurrencyGroupLabel': '并发分组名称',
|
|
444
|
+
'form.workWindowHoursLabel': '运行时间窗口 (workWindow, 如 22:00-07:00)',
|
|
445
|
+
'form.workWindowHoursPlaceholder': '例如: 22:00-07:00 或 09:00-18:00',
|
|
446
|
+
'form.workWindowPolicyLabel': '窗口外执行策略',
|
|
447
|
+
'form.workWindowPolicySkip': '跳过本次执行 (record skipped)',
|
|
448
|
+
'form.workWindowPolicyDefer': '延迟至窗口开启时执行 (defer)',
|
|
449
|
+
'form.timeBoxMinutesLabel': 'Timebox 运行上限 (分钟, 0 = 不限制)',
|
|
438
450
|
'form.wakeTriggerTypeLabel': '事件唤醒触发器 (Wake Triggers)',
|
|
439
451
|
'form.wakeTriggerTypeNone': '无 (仅定时/间隔)',
|
|
440
452
|
'form.wakeTriggerTypeFileCount': '文件数量阈值 (批量触发)',
|
|
@@ -104,6 +104,9 @@
|
|
|
104
104
|
const [formWakeTriggerPath, setFormWakeTriggerPath] = React.useState('');
|
|
105
105
|
const [formWakeTriggerMinCount, setFormWakeTriggerMinCount] = React.useState(1);
|
|
106
106
|
const [formWakeTriggerConsume, setFormWakeTriggerConsume] = React.useState(true);
|
|
107
|
+
const [formWorkWindowHours, setFormWorkWindowHours] = React.useState('');
|
|
108
|
+
const [formWorkWindowPolicy, setFormWorkWindowPolicy] = React.useState('skip');
|
|
109
|
+
const [formTimeBoxMinutes, setFormTimeBoxMinutes] = React.useState(0);
|
|
107
110
|
const [formWriteScopes, setFormWriteScopes] = React.useState('');
|
|
108
111
|
const [formInputHashPaths, setFormInputHashPaths] = React.useState('');
|
|
109
112
|
const [formSkipIfUnchanged, setFormSkipIfUnchanged] = React.useState(false);
|
|
@@ -333,6 +333,10 @@
|
|
|
333
333
|
setFormPreflightTarget(task.preflightTarget || '');
|
|
334
334
|
setFormPriority(task.priority !== undefined ? task.priority : 5);
|
|
335
335
|
setFormConcurrencyGroup(task.concurrencyGroup || 'default');
|
|
336
|
+
const _ww = task.workWindow || {};
|
|
337
|
+
setFormWorkWindowHours(_ww.hours || '');
|
|
338
|
+
setFormWorkWindowPolicy(_ww.outsidePolicy || 'skip');
|
|
339
|
+
setFormTimeBoxMinutes(Number(task.timeBoxMinutes) || 0);
|
|
336
340
|
const _wt = task.wakeTrigger || {};
|
|
337
341
|
setFormWakeTriggerType(_wt.enabled && _wt.type ? _wt.type : 'none');
|
|
338
342
|
setFormWakeTriggerPath(_wt.markerPath || _wt.path || _wt.pidFile || '');
|
|
@@ -426,7 +430,13 @@
|
|
|
426
430
|
preflightTarget: formPreflightTarget.trim() || undefined,
|
|
427
431
|
priority: Number(formPriority) || 5,
|
|
428
432
|
concurrencyGroup: formConcurrencyGroup.trim() || 'default',
|
|
429
|
-
|
|
433
|
+
workWindow: formWorkWindowHours.trim() ? {
|
|
434
|
+
enabled: true,
|
|
435
|
+
hours: formWorkWindowHours.trim(),
|
|
436
|
+
outsidePolicy: formWorkWindowPolicy,
|
|
437
|
+
} : null,
|
|
438
|
+
timeBoxMinutes: Number(formTimeBoxMinutes) > 0 ? Number(formTimeBoxMinutes) : undefined,
|
|
439
|
+
wakeTrigger: formWakeTriggerType && formWakeTriggerType !== 'none' ? {
|
|
430
440
|
enabled: true,
|
|
431
441
|
type: formWakeTriggerType,
|
|
432
442
|
path: formWakeTriggerType === 'file_count' ? formWakeTriggerPath.trim() : undefined,
|
|
@@ -294,7 +294,35 @@
|
|
|
294
294
|
})
|
|
295
295
|
)
|
|
296
296
|
),
|
|
297
|
-
|
|
297
|
+
React.createElement('div', { className: 'dsh-cron-form-group' },
|
|
298
|
+
React.createElement('label', null, T_KEY(t, 'form.workWindowHoursLabel')),
|
|
299
|
+
React.createElement('input', {
|
|
300
|
+
type: 'text',
|
|
301
|
+
value: formWorkWindowHours,
|
|
302
|
+
placeholder: T_KEY(t, 'form.workWindowHoursPlaceholder'),
|
|
303
|
+
onChange: (e) => setFormWorkWindowHours(e.target.value)
|
|
304
|
+
})
|
|
305
|
+
),
|
|
306
|
+
formWorkWindowHours.trim() && React.createElement('div', { className: 'dsh-cron-form-group' },
|
|
307
|
+
React.createElement('label', null, T_KEY(t, 'form.workWindowPolicyLabel')),
|
|
308
|
+
React.createElement('select', {
|
|
309
|
+
value: formWorkWindowPolicy,
|
|
310
|
+
onChange: (e) => setFormWorkWindowPolicy(e.target.value)
|
|
311
|
+
},
|
|
312
|
+
React.createElement('option', { value: 'skip' }, T_KEY(t, 'form.workWindowPolicySkip')),
|
|
313
|
+
React.createElement('option', { value: 'defer' }, T_KEY(t, 'form.workWindowPolicyDefer'))
|
|
314
|
+
)
|
|
315
|
+
),
|
|
316
|
+
React.createElement('div', { className: 'dsh-cron-form-group' },
|
|
317
|
+
React.createElement('label', null, T_KEY(t, 'form.timeBoxMinutesLabel')),
|
|
318
|
+
React.createElement('input', {
|
|
319
|
+
type: 'number',
|
|
320
|
+
min: 0,
|
|
321
|
+
value: formTimeBoxMinutes,
|
|
322
|
+
onChange: (e) => setFormTimeBoxMinutes(parseInt(e.target.value, 10) || 0)
|
|
323
|
+
})
|
|
324
|
+
),
|
|
325
|
+
React.createElement('div', { className: 'dsh-cron-form-group' },
|
|
298
326
|
React.createElement('label', null, T_KEY(t, 'form.wakeTriggerTypeLabel')),
|
|
299
327
|
React.createElement('select', {
|
|
300
328
|
value: formWakeTriggerType,
|
package/lib/client.js
CHANGED
|
@@ -261,6 +261,12 @@ en: {
|
|
|
261
261
|
'form.gracePeriodLabel': 'Heartbeat grace period (seconds)',
|
|
262
262
|
'form.priorityLabel': 'Queue priority (1-10, higher runs first)',
|
|
263
263
|
'form.concurrencyGroupLabel': 'Concurrency group',
|
|
264
|
+
'form.workWindowHoursLabel': 'Allowed work hours (e.g. 22:00-07:00)',
|
|
265
|
+
'form.workWindowHoursPlaceholder': 'e.g. 22:00-07:00 or 09:00-18:00',
|
|
266
|
+
'form.workWindowPolicyLabel': 'Outside window policy',
|
|
267
|
+
'form.workWindowPolicySkip': 'Skip execution (record skipped)',
|
|
268
|
+
'form.workWindowPolicyDefer': 'Defer until window opens',
|
|
269
|
+
'form.timeBoxMinutesLabel': 'Timebox deadline (minutes, 0 = unlimited)',
|
|
264
270
|
'form.wakeTriggerTypeLabel': 'Event wake trigger',
|
|
265
271
|
'form.wakeTriggerTypeNone': 'None (Schedule / Cron only)',
|
|
266
272
|
'form.wakeTriggerTypeFileCount': 'File count threshold (batch run)',
|
|
@@ -480,6 +486,12 @@ zh: {
|
|
|
480
486
|
'form.preflightTargetLabel': '预检目标参数', 'form.preflightTargetPlaceholder': 'https://example.com/healthz 或 ls /data 或 /:10%',
|
|
481
487
|
'form.heartbeatIntervalLabel': '心跳打卡时限 (秒, 0 = 禁用)', 'form.gracePeriodLabel': '心跳宽限期 (秒)',
|
|
482
488
|
'form.priorityLabel': '队列优先级 (1-10,数值越大越先执行)', 'form.concurrencyGroupLabel': '并发分组名称',
|
|
489
|
+
'form.workWindowHoursLabel': '运行时间窗口 (workWindow, 如 22:00-07:00)',
|
|
490
|
+
'form.workWindowHoursPlaceholder': '例如: 22:00-07:00 或 09:00-18:00',
|
|
491
|
+
'form.workWindowPolicyLabel': '窗口外执行策略',
|
|
492
|
+
'form.workWindowPolicySkip': '跳过本次执行 (record skipped)',
|
|
493
|
+
'form.workWindowPolicyDefer': '延迟至窗口开启时执行 (defer)',
|
|
494
|
+
'form.timeBoxMinutesLabel': 'Timebox 运行上限 (分钟, 0 = 不限制)',
|
|
483
495
|
'form.wakeTriggerTypeLabel': '事件唤醒触发器 (Wake Triggers)',
|
|
484
496
|
'form.wakeTriggerTypeNone': '无 (仅定时/间隔)',
|
|
485
497
|
'form.wakeTriggerTypeFileCount': '文件数量阈值 (批量触发)',
|
|
@@ -1660,6 +1672,9 @@ const [formWakeTriggerType, setFormWakeTriggerType] = React.useState('none');
|
|
|
1660
1672
|
const [formWakeTriggerPath, setFormWakeTriggerPath] = React.useState('');
|
|
1661
1673
|
const [formWakeTriggerMinCount, setFormWakeTriggerMinCount] = React.useState(1);
|
|
1662
1674
|
const [formWakeTriggerConsume, setFormWakeTriggerConsume] = React.useState(true);
|
|
1675
|
+
const [formWorkWindowHours, setFormWorkWindowHours] = React.useState('');
|
|
1676
|
+
const [formWorkWindowPolicy, setFormWorkWindowPolicy] = React.useState('skip');
|
|
1677
|
+
const [formTimeBoxMinutes, setFormTimeBoxMinutes] = React.useState(0);
|
|
1663
1678
|
const [formWriteScopes, setFormWriteScopes] = React.useState('');
|
|
1664
1679
|
const [formInputHashPaths, setFormInputHashPaths] = React.useState('');
|
|
1665
1680
|
const [formSkipIfUnchanged, setFormSkipIfUnchanged] = React.useState(false);
|
|
@@ -2585,6 +2600,10 @@ setFormPreflightType(task.preflightType || 'none');
|
|
|
2585
2600
|
setFormPreflightTarget(task.preflightTarget || '');
|
|
2586
2601
|
setFormPriority(task.priority !== undefined ? task.priority : 5);
|
|
2587
2602
|
setFormConcurrencyGroup(task.concurrencyGroup || 'default');
|
|
2603
|
+
const _ww = task.workWindow || {};
|
|
2604
|
+
setFormWorkWindowHours(_ww.hours || '');
|
|
2605
|
+
setFormWorkWindowPolicy(_ww.outsidePolicy || 'skip');
|
|
2606
|
+
setFormTimeBoxMinutes(Number(task.timeBoxMinutes) || 0);
|
|
2588
2607
|
const _wt = task.wakeTrigger || {};
|
|
2589
2608
|
setFormWakeTriggerType(_wt.enabled && _wt.type ? _wt.type : 'none');
|
|
2590
2609
|
setFormWakeTriggerPath(_wt.markerPath || _wt.path || _wt.pidFile || '');
|
|
@@ -2676,6 +2695,12 @@ preflightType: formPreflightType || 'none',
|
|
|
2676
2695
|
preflightTarget: formPreflightTarget.trim() || undefined,
|
|
2677
2696
|
priority: Number(formPriority) || 5,
|
|
2678
2697
|
concurrencyGroup: formConcurrencyGroup.trim() || 'default',
|
|
2698
|
+
workWindow: formWorkWindowHours.trim() ? {
|
|
2699
|
+
enabled: true,
|
|
2700
|
+
hours: formWorkWindowHours.trim(),
|
|
2701
|
+
outsidePolicy: formWorkWindowPolicy,
|
|
2702
|
+
} : null,
|
|
2703
|
+
timeBoxMinutes: Number(formTimeBoxMinutes) > 0 ? Number(formTimeBoxMinutes) : undefined,
|
|
2679
2704
|
wakeTrigger: formWakeTriggerType && formWakeTriggerType !== 'none' ? {
|
|
2680
2705
|
enabled: true,
|
|
2681
2706
|
type: formWakeTriggerType,
|
|
@@ -4191,6 +4216,34 @@ onChange: (e) => setFormConcurrencyGroup(e.target.value)
|
|
|
4191
4216
|
)
|
|
4192
4217
|
),
|
|
4193
4218
|
_h('div', { className: 'dsh-cron-form-group' },
|
|
4219
|
+
_h('label', null, T_KEY(t, 'form.workWindowHoursLabel')),
|
|
4220
|
+
_h('input', {
|
|
4221
|
+
type: 'text',
|
|
4222
|
+
value: formWorkWindowHours,
|
|
4223
|
+
placeholder: T_KEY(t, 'form.workWindowHoursPlaceholder'),
|
|
4224
|
+
onChange: (e) => setFormWorkWindowHours(e.target.value)
|
|
4225
|
+
})
|
|
4226
|
+
),
|
|
4227
|
+
formWorkWindowHours.trim() && _h('div', { className: 'dsh-cron-form-group' },
|
|
4228
|
+
_h('label', null, T_KEY(t, 'form.workWindowPolicyLabel')),
|
|
4229
|
+
_h('select', {
|
|
4230
|
+
value: formWorkWindowPolicy,
|
|
4231
|
+
onChange: (e) => setFormWorkWindowPolicy(e.target.value)
|
|
4232
|
+
},
|
|
4233
|
+
_h('option', { value: 'skip' }, T_KEY(t, 'form.workWindowPolicySkip')),
|
|
4234
|
+
_h('option', { value: 'defer' }, T_KEY(t, 'form.workWindowPolicyDefer'))
|
|
4235
|
+
)
|
|
4236
|
+
),
|
|
4237
|
+
_h('div', { className: 'dsh-cron-form-group' },
|
|
4238
|
+
_h('label', null, T_KEY(t, 'form.timeBoxMinutesLabel')),
|
|
4239
|
+
_h('input', {
|
|
4240
|
+
type: 'number',
|
|
4241
|
+
min: 0,
|
|
4242
|
+
value: formTimeBoxMinutes,
|
|
4243
|
+
onChange: (e) => setFormTimeBoxMinutes(parseInt(e.target.value, 10) || 0)
|
|
4244
|
+
})
|
|
4245
|
+
),
|
|
4246
|
+
_h('div', { className: 'dsh-cron-form-group' },
|
|
4194
4247
|
_h('label', null, T_KEY(t, 'form.wakeTriggerTypeLabel')),
|
|
4195
4248
|
_h('select', {
|
|
4196
4249
|
value: formWakeTriggerType,
|
package/lib/cron-tool.js
CHANGED
|
@@ -326,6 +326,15 @@ export const cronToolParameters = {
|
|
|
326
326
|
type: 'string',
|
|
327
327
|
description: 'Named concurrency group to serialize related tasks',
|
|
328
328
|
},
|
|
329
|
+
workWindow: {
|
|
330
|
+
type: 'object',
|
|
331
|
+
additionalProperties: true,
|
|
332
|
+
description: 'Restricted hours or off-peak work window for execution',
|
|
333
|
+
},
|
|
334
|
+
timeBoxMinutes: {
|
|
335
|
+
type: 'number',
|
|
336
|
+
description: 'Maximum wall-clock execution time in minutes before graceful abort',
|
|
337
|
+
},
|
|
329
338
|
wakeTrigger: {
|
|
330
339
|
type: 'object',
|
|
331
340
|
additionalProperties: true,
|
package/lib/locales.json
CHANGED
|
@@ -419,6 +419,12 @@
|
|
|
419
419
|
"form.wakeTriggerPathLabel": "触发目标路径 (目录 / markerPath / pidFile)",
|
|
420
420
|
"form.wakeTriggerPathPlaceholder": "例如: incoming/ 或 build.ready 或 run.pid",
|
|
421
421
|
"form.wakeTriggerMinCountLabel": "最小文件阈值 (minCount)",
|
|
422
|
-
"form.wakeTriggerConsumeLabel": "触发后自动删除标记/PID文件"
|
|
422
|
+
"form.wakeTriggerConsumeLabel": "触发后自动删除标记/PID文件",
|
|
423
|
+
"form.workWindowHoursLabel": "运行时间窗口 (workWindow, 如 22:00-07:00)",
|
|
424
|
+
"form.workWindowHoursPlaceholder": "例如: 22:00-07:00 或 09:00-18:00",
|
|
425
|
+
"form.workWindowPolicyLabel": "窗口外执行策略",
|
|
426
|
+
"form.workWindowPolicySkip": "跳过本次执行 (record skipped)",
|
|
427
|
+
"form.workWindowPolicyDefer": "延迟至窗口开启时执行 (defer)",
|
|
428
|
+
"form.timeBoxMinutesLabel": "Timebox 运行上限 (分钟, 0 = 不限制)"
|
|
423
429
|
}
|
|
424
430
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isInsideWorkWindow, getNextWindowStart } from '../work-windows.js';
|
|
1
2
|
import { recordPromptRunOutcome } from '../prompt-evolver.js';
|
|
2
3
|
import { evaluateAdaptiveRun, calculateNextAdaptiveState } from '../adaptive.js';
|
|
3
4
|
import { globalBudgetManager } from '../global-budgets.js';
|
|
@@ -162,7 +163,27 @@ export async function executeTask(scheduler, taskId, options = {}) {
|
|
|
162
163
|
preflightBlocked: true,
|
|
163
164
|
};
|
|
164
165
|
}
|
|
165
|
-
|
|
166
|
+
// Work Window & Off-Peak enforcement (#412)
|
|
167
|
+
if (task.workWindow && task.workWindow.enabled && !options.dryRun && !options.ignoreWorkWindow) {
|
|
168
|
+
const windowCheck = isInsideWorkWindow(task.workWindow, new Date(), task.timezone);
|
|
169
|
+
if (!windowCheck.inside) {
|
|
170
|
+
const policy = task.workWindow.outsidePolicy || 'skip';
|
|
171
|
+
if (policy === 'skip') {
|
|
172
|
+
logger.info(`[dsh-cron] task "${task.title}" (${taskId}) skipped: outside work window (${windowCheck.reason})`);
|
|
173
|
+
scheduler.recordSkipped(taskId, `Outside work window: ${windowCheck.reason}`);
|
|
174
|
+
if (typeof scheduler.drainQueue === 'function') scheduler.drainQueue();
|
|
175
|
+
return { ok: false, status: 'skipped', reason: 'outside_work_window' };
|
|
176
|
+
} else if (policy === 'defer') {
|
|
177
|
+
const nextStart = getNextWindowStart(task.workWindow, new Date(), task.timezone);
|
|
178
|
+
const delayMs = Math.max(1000, nextStart - Date.now());
|
|
179
|
+
logger.info(`[dsh-cron] task "${task.title}" (${taskId}) deferred until work window opens in ${Math.round(delayMs / 1000)}s`);
|
|
180
|
+
scheduler.armDeferredTimer(taskId, delayMs, options);
|
|
181
|
+
return { ok: false, status: 'deferred', nextStart };
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const preflight = await executePreflight(task);
|
|
166
187
|
if (!preflight.ok) {
|
|
167
188
|
return {
|
|
168
189
|
ok: false,
|
|
@@ -274,6 +295,26 @@ export async function executeTask(scheduler, taskId, options = {}) {
|
|
|
274
295
|
}
|
|
275
296
|
|
|
276
297
|
const preflightStart = Date.now();
|
|
298
|
+
// Work Window & Off-Peak enforcement (#412)
|
|
299
|
+
if (task.workWindow && task.workWindow.enabled && !options.dryRun && !options.ignoreWorkWindow) {
|
|
300
|
+
const windowCheck = isInsideWorkWindow(task.workWindow, new Date(), task.timezone);
|
|
301
|
+
if (!windowCheck.inside) {
|
|
302
|
+
const policy = task.workWindow.outsidePolicy || 'skip';
|
|
303
|
+
if (policy === 'skip') {
|
|
304
|
+
logger.info(`[dsh-cron] task "${task.title}" (${taskId}) skipped: outside work window (${windowCheck.reason})`);
|
|
305
|
+
scheduler.recordSkipped(taskId, `Outside work window: ${windowCheck.reason}`);
|
|
306
|
+
if (typeof scheduler.drainQueue === 'function') scheduler.drainQueue();
|
|
307
|
+
return { ok: false, status: 'skipped', reason: 'outside_work_window' };
|
|
308
|
+
} else if (policy === 'defer') {
|
|
309
|
+
const nextStart = getNextWindowStart(task.workWindow, new Date(), task.timezone);
|
|
310
|
+
const delayMs = Math.max(1000, nextStart - Date.now());
|
|
311
|
+
logger.info(`[dsh-cron] task "${task.title}" (${taskId}) deferred until work window opens in ${Math.round(delayMs / 1000)}s`);
|
|
312
|
+
scheduler.armDeferredTimer(taskId, delayMs, options);
|
|
313
|
+
return { ok: false, status: 'deferred', nextStart };
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
277
318
|
const preflight = await executePreflight(task);
|
|
278
319
|
const preflightDurationMs = Date.now() - preflightStart;
|
|
279
320
|
if (!preflight.ok) {
|
|
@@ -333,6 +333,7 @@ export class TaskScheduler {
|
|
|
333
333
|
this.timers = new Map();
|
|
334
334
|
this.retryTimers = new Map();
|
|
335
335
|
this.adaptiveTimers = new Map();
|
|
336
|
+
this.deferredTimers = new Map();
|
|
336
337
|
this.running = new Map();
|
|
337
338
|
this.runCounters = {};
|
|
338
339
|
this.queue = [];
|
|
@@ -367,6 +368,26 @@ export class TaskScheduler {
|
|
|
367
368
|
}
|
|
368
369
|
}
|
|
369
370
|
|
|
371
|
+
armDeferredTimer(taskId, delayMs, options = {}) {
|
|
372
|
+
this.clearDeferredTimer(taskId);
|
|
373
|
+
const timer = setTimeout(() => {
|
|
374
|
+
this.deferredTimers.delete(taskId);
|
|
375
|
+
if (!this.isStopped) {
|
|
376
|
+
this.runTask(taskId, options).catch((_err) => { void _err; });
|
|
377
|
+
}
|
|
378
|
+
}, delayMs);
|
|
379
|
+
if (timer.unref) timer.unref();
|
|
380
|
+
this.deferredTimers.set(taskId, timer);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
clearDeferredTimer(taskId) {
|
|
384
|
+
const t = this.deferredTimers.get(taskId);
|
|
385
|
+
if (t) {
|
|
386
|
+
clearTimeout(t);
|
|
387
|
+
this.deferredTimers.delete(taskId);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
370
391
|
clearAdaptiveTimer(taskId) {
|
|
371
392
|
const t = this.adaptiveTimers.get(taskId);
|
|
372
393
|
if (t) {
|
|
@@ -377,6 +398,7 @@ export class TaskScheduler {
|
|
|
377
398
|
|
|
378
399
|
armAdaptiveTimer(taskId, delayMs) {
|
|
379
400
|
this.clearAdaptiveTimer(taskId);
|
|
401
|
+
this.clearDeferredTimer(taskId);
|
|
380
402
|
if (this.wakeTriggerManager) {
|
|
381
403
|
this.wakeTriggerManager.unregisterTask(taskId);
|
|
382
404
|
}
|
|
@@ -525,6 +547,7 @@ export class TaskScheduler {
|
|
|
525
547
|
|
|
526
548
|
clearScheduled(taskId) {
|
|
527
549
|
this.clearAdaptiveTimer(taskId);
|
|
550
|
+
this.clearDeferredTimer(taskId);
|
|
528
551
|
if (this.wakeTriggerManager) {
|
|
529
552
|
this.wakeTriggerManager.unregisterTask(taskId);
|
|
530
553
|
}
|
package/lib/store/task-schema.js
CHANGED
|
@@ -100,6 +100,8 @@ export const TaskSchema = z.object({
|
|
|
100
100
|
skipIfUnchanged: z.boolean().default(false),
|
|
101
101
|
lastInputHash: z.string().default(''),
|
|
102
102
|
wakeTrigger: z.any(),
|
|
103
|
+
workWindow: z.any(),
|
|
104
|
+
timeBoxMinutes: z.number().min(0).default(0),
|
|
103
105
|
maxMemoryMb: z.number().min(0).default(0),
|
|
104
106
|
executionTimeoutMs: z.number().min(0).default(900000),
|
|
105
107
|
maxLogBytesPerRun: z.number().min(0).default(5 * 1024 * 1024),
|
package/lib/task-create.js
CHANGED
|
@@ -11,6 +11,7 @@ import { CHANNEL_IDS } from './channels.js';
|
|
|
11
11
|
import { redactTaskSecrets } from './http-utils.js';
|
|
12
12
|
import { normalizeScopes } from './scope-locks.js';
|
|
13
13
|
import { normalizeWakeTrigger } from './wake-triggers.js';
|
|
14
|
+
import { normalizeWorkWindow } from './work-windows.js';
|
|
14
15
|
import { normalizeInputHashPaths } from './input-hash.js';
|
|
15
16
|
import { sanitizeDependsOn, sanitizeJoinPolicy, validateDAG } from './dag.js';
|
|
16
17
|
|
|
@@ -66,6 +67,8 @@ export function executeCreateTask(store, scheduler, args) {
|
|
|
66
67
|
elseTask: args.elseTask ? String(args.elseTask).trim() : undefined,
|
|
67
68
|
autoHeal: args.autoHeal !== undefined ? Boolean(args.autoHeal) : undefined,
|
|
68
69
|
wakeTrigger: args.wakeTrigger !== undefined ? normalizeWakeTrigger(args.wakeTrigger) : undefined,
|
|
70
|
+
workWindow: args.workWindow !== undefined ? normalizeWorkWindow(args.workWindow) : undefined,
|
|
71
|
+
timeBoxMinutes: args.timeBoxMinutes !== undefined ? Math.max(0, Number(args.timeBoxMinutes) || 0) : undefined,
|
|
69
72
|
writeScopes: args.writeScopes !== undefined ? normalizeScopes(args.writeScopes) : undefined,
|
|
70
73
|
inputHashPaths: args.inputHashPaths !== undefined ? normalizeInputHashPaths(args.inputHashPaths) : undefined,
|
|
71
74
|
skipIfUnchanged: args.skipIfUnchanged !== undefined ? Boolean(args.skipIfUnchanged) : undefined,
|
package/lib/task-patch.js
CHANGED
|
@@ -22,6 +22,7 @@ import { pickPatchableFields, restoreTaskSecrets } from './http-utils.js';
|
|
|
22
22
|
import { unknownChannelIds } from './channels.js';
|
|
23
23
|
import { normalizeScopes } from './scope-locks.js';
|
|
24
24
|
import { normalizeWakeTrigger } from './wake-triggers.js';
|
|
25
|
+
import { normalizeWorkWindow } from './work-windows.js';
|
|
25
26
|
import { normalizeInputHashPaths } from './input-hash.js';
|
|
26
27
|
import { isConfigOwned, configOwnedMessage } from './config-jobs.js';
|
|
27
28
|
|
|
@@ -135,6 +136,12 @@ export function buildTaskPatch(current, body) {
|
|
|
135
136
|
if (patch.autoHeal !== undefined) {
|
|
136
137
|
patch.autoHeal = Boolean(patch.autoHeal);
|
|
137
138
|
}
|
|
139
|
+
if (patch.workWindow !== undefined) {
|
|
140
|
+
patch.workWindow = normalizeWorkWindow(patch.workWindow);
|
|
141
|
+
}
|
|
142
|
+
if (patch.timeBoxMinutes !== undefined) {
|
|
143
|
+
patch.timeBoxMinutes = Math.max(0, Number(patch.timeBoxMinutes) || 0);
|
|
144
|
+
}
|
|
138
145
|
if (patch.wakeTrigger !== undefined) {
|
|
139
146
|
patch.wakeTrigger = normalizeWakeTrigger(patch.wakeTrigger);
|
|
140
147
|
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { logger } from './logger.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Parses an hours range string like "22:00-06:00", "09:00-18:00", "22-6".
|
|
5
|
+
* Returns { startMinute, endMinute, spansMidnight } or null if invalid.
|
|
6
|
+
*/
|
|
7
|
+
export function parseHoursRange(rangeStr) {
|
|
8
|
+
if (!rangeStr || typeof rangeStr !== 'string') return null;
|
|
9
|
+
const match = rangeStr.trim().match(/^(\d{1,2})(?::(\d{2}))?\s*-\s*(\d{1,2})(?::(\d{2}))?$/);
|
|
10
|
+
if (!match) return null;
|
|
11
|
+
|
|
12
|
+
const startH = parseInt(match[1], 10);
|
|
13
|
+
const startM = match[2] ? parseInt(match[2], 10) : 0;
|
|
14
|
+
const endH = parseInt(match[3], 10);
|
|
15
|
+
const endM = match[4] ? parseInt(match[4], 10) : 0;
|
|
16
|
+
|
|
17
|
+
if (startH < 0 || startH > 23 || startM < 0 || startM > 59) return null;
|
|
18
|
+
if (endH < 0 || endH > 23 || endM < 0 || endM > 59) return null;
|
|
19
|
+
|
|
20
|
+
const startMinute = startH * 60 + startM;
|
|
21
|
+
const endMinute = endH * 60 + endM;
|
|
22
|
+
const spansMidnight = startMinute > endMinute;
|
|
23
|
+
|
|
24
|
+
return { startMinute, endMinute, spansMidnight };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Normalizes workWindow configuration.
|
|
29
|
+
*/
|
|
30
|
+
export function normalizeWorkWindow(cfg) {
|
|
31
|
+
if (!cfg || typeof cfg !== 'object') return null;
|
|
32
|
+
const enabled = cfg.enabled !== false;
|
|
33
|
+
const hours = typeof cfg.hours === 'string' ? cfg.hours.trim() : '';
|
|
34
|
+
const parsedHours = parseHoursRange(hours);
|
|
35
|
+
|
|
36
|
+
let daysOfWeek = [];
|
|
37
|
+
if (Array.isArray(cfg.daysOfWeek)) {
|
|
38
|
+
daysOfWeek = cfg.daysOfWeek
|
|
39
|
+
.map((d) => parseInt(d, 10))
|
|
40
|
+
.filter((d) => Number.isInteger(d) && d >= 0 && d <= 6);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const outsidePolicy = ['defer', 'skip'].includes(String(cfg.outsidePolicy || '').toLowerCase())
|
|
44
|
+
? String(cfg.outsidePolicy).toLowerCase()
|
|
45
|
+
: 'skip';
|
|
46
|
+
|
|
47
|
+
const timeBoxMinutes = Number(cfg.timeBoxMinutes) > 0 ? Number(cfg.timeBoxMinutes) : null;
|
|
48
|
+
const offPeakOnly = Boolean(cfg.offPeakOnly);
|
|
49
|
+
|
|
50
|
+
// If offPeakOnly is set and hours are not specified, default to 22:00-07:00
|
|
51
|
+
const effectiveHours = offPeakOnly && !hours ? '22:00-07:00' : hours;
|
|
52
|
+
|
|
53
|
+
return {
|
|
54
|
+
enabled,
|
|
55
|
+
hours: effectiveHours,
|
|
56
|
+
daysOfWeek,
|
|
57
|
+
outsidePolicy,
|
|
58
|
+
timeBoxMinutes,
|
|
59
|
+
offPeakOnly,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Extracts current hour, minute, and day of week for a Date in a specific timezone.
|
|
65
|
+
*/
|
|
66
|
+
export function getTimeInTimezone(date, timezone) {
|
|
67
|
+
try {
|
|
68
|
+
const d = date instanceof Date ? date : new Date(date);
|
|
69
|
+
const formatter = new Intl.DateTimeFormat('en-US', {
|
|
70
|
+
timeZone: timezone || 'UTC',
|
|
71
|
+
hour12: false,
|
|
72
|
+
weekday: 'narrow',
|
|
73
|
+
hour: 'numeric',
|
|
74
|
+
minute: 'numeric',
|
|
75
|
+
});
|
|
76
|
+
const parts = formatter.formatToParts(d);
|
|
77
|
+
let hour = 0;
|
|
78
|
+
let minute = 0;
|
|
79
|
+
for (const part of parts) {
|
|
80
|
+
if (part.type === 'hour') hour = parseInt(part.value, 10) % 24;
|
|
81
|
+
if (part.type === 'minute') minute = parseInt(part.value, 10);
|
|
82
|
+
}
|
|
83
|
+
// Calculate 0-6 day of week in timezone
|
|
84
|
+
const dayFormatter = new Intl.DateTimeFormat('en-US', {
|
|
85
|
+
timeZone: timezone || 'UTC',
|
|
86
|
+
weekday: 'numeric', // 1..7 (Sunday is 1 or 7 depending on locale, let's use short)
|
|
87
|
+
});
|
|
88
|
+
const shortDay = new Intl.DateTimeFormat('en-US', {
|
|
89
|
+
timeZone: timezone || 'UTC',
|
|
90
|
+
weekday: 'short',
|
|
91
|
+
}).format(d);
|
|
92
|
+
const dayMap = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };
|
|
93
|
+
const dayOfWeek = dayMap[shortDay] !== undefined ? dayMap[shortDay] : d.getDay();
|
|
94
|
+
|
|
95
|
+
return { hour, minute, currentMinute: hour * 60 + minute, dayOfWeek };
|
|
96
|
+
} catch (_err) {
|
|
97
|
+
void _err;
|
|
98
|
+
const d = date instanceof Date ? date : new Date(date);
|
|
99
|
+
return {
|
|
100
|
+
hour: d.getUTCHours(),
|
|
101
|
+
minute: d.getUTCMinutes(),
|
|
102
|
+
currentMinute: d.getUTCHours() * 60 + d.getUTCMinutes(),
|
|
103
|
+
dayOfWeek: d.getUTCDay(),
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Checks if current time is inside the work window.
|
|
110
|
+
*/
|
|
111
|
+
export function isInsideWorkWindow(workWindow, date = new Date(), timezone = 'UTC') {
|
|
112
|
+
const norm = normalizeWorkWindow(workWindow);
|
|
113
|
+
if (!norm || !norm.enabled) return { inside: true };
|
|
114
|
+
|
|
115
|
+
const { currentMinute, dayOfWeek } = getTimeInTimezone(date, timezone);
|
|
116
|
+
|
|
117
|
+
// 1. Day of week check
|
|
118
|
+
if (norm.daysOfWeek && norm.daysOfWeek.length > 0) {
|
|
119
|
+
if (!norm.daysOfWeek.includes(dayOfWeek)) {
|
|
120
|
+
return {
|
|
121
|
+
inside: false,
|
|
122
|
+
reason: `Day of week (${dayOfWeek}) not in allowed days [${norm.daysOfWeek.join(',')}]`,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// 2. Hours check
|
|
128
|
+
if (norm.hours) {
|
|
129
|
+
const parsed = parseHoursRange(norm.hours);
|
|
130
|
+
if (parsed) {
|
|
131
|
+
const { startMinute, endMinute, spansMidnight } = parsed;
|
|
132
|
+
let inRange = false;
|
|
133
|
+
if (spansMidnight) {
|
|
134
|
+
inRange = currentMinute >= startMinute || currentMinute < endMinute;
|
|
135
|
+
} else {
|
|
136
|
+
inRange = currentMinute >= startMinute && currentMinute < endMinute;
|
|
137
|
+
}
|
|
138
|
+
if (!inRange) {
|
|
139
|
+
return {
|
|
140
|
+
inside: false,
|
|
141
|
+
reason: `Current time (${Math.floor(currentMinute / 60)}:${String(currentMinute % 60).padStart(2, '0')}) is outside allowed window ${norm.hours}`,
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
return { inside: true };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Calculates the next timestamp (ms) when the window opens.
|
|
152
|
+
*/
|
|
153
|
+
export function getNextWindowStart(workWindow, date = new Date(), timezone = 'UTC') {
|
|
154
|
+
const norm = normalizeWorkWindow(workWindow);
|
|
155
|
+
if (!norm || !norm.enabled) return Date.now();
|
|
156
|
+
|
|
157
|
+
const now = date instanceof Date ? date.getTime() : new Date(date).getTime();
|
|
158
|
+
// Step forward minute by minute (up to 7 days = 10080 minutes) to find when window opens
|
|
159
|
+
for (let m = 1; m <= 10080; m++) {
|
|
160
|
+
const candidate = new Date(now + m * 60 * 1000);
|
|
161
|
+
const check = isInsideWorkWindow(norm, candidate, timezone);
|
|
162
|
+
if (check.inside) {
|
|
163
|
+
return candidate.getTime();
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return now + 3600000; // Fallback 1 hour
|
|
167
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@goodandready/dsh-cron",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.34",
|
|
4
4
|
"description": "Background automation runner for DSH: isolated agent runs, script/HTTP/SSH/Docker runtimes, cost guard, notifications, heartbeats.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|