@goodandready/dsh-cron 0.3.32 → 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 +14 -0
- package/README.ru.md +14 -0
- package/README.zh.md +14 -0
- package/lib/client-src/10-locales.js +30 -0
- package/lib/client-src/50-cron-screen-state.js +7 -0
- package/lib/client-src/53-cron-screen-modal-actions.js +24 -0
- package/lib/client-src/62-modal-task-form-tail.js +68 -0
- package/lib/client.js +129 -0
- package/lib/cron-tool.js +14 -0
- package/lib/locales.json +17 -2
- package/lib/prompt-interpolation.js +15 -0
- package/lib/scheduler/scheduler-execution.js +42 -1
- package/lib/scheduler/scheduler.js +40 -0
- package/lib/store/task-schema.js +3 -0
- package/lib/store/task-transfer.js +3 -0
- package/lib/task-create.js +5 -0
- package/lib/task-patch.js +11 -0
- package/lib/wake-triggers.js +362 -0
- package/lib/work-windows.js +167 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -691,3 +691,17 @@ node scripts/ci-preflight.mjs
|
|
|
691
691
|
## 📄 License
|
|
692
692
|
|
|
693
693
|
MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
|
|
694
|
+
|
|
695
|
+
### Event-Driven Wake Triggers (v0.3.33)
|
|
696
|
+
|
|
697
|
+
Wake agent tasks reactively based on local events:
|
|
698
|
+
- **File Count Threshold**: trigger when `>= N` matching files appear in a directory (batch processing).
|
|
699
|
+
- **Marker / Flag File**: trigger when a flag file (e.g., `build.ready`) appears, with automatic consumption.
|
|
700
|
+
- **Process Exit**: monitor a PID or `.pid` file and trigger post-processing as soon as the background job completes.
|
|
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
|
@@ -645,3 +645,17 @@ MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
|
|
|
645
645
|
- **Единый безопасный лимит maxConcurrent**: Схема Config и планировщик TaskScheduler теперь согласованно используют лимит по умолчанию `2` (0 остаётся явным выбором безлимитного режима).
|
|
646
646
|
- **Изоляция пулов через concurrencyGroup**: Поле `concurrencyGroup` теперь строго контролируется при допуске задач и опустошении очереди (по умолчанию 1 параллельный запуск на именованную группу). Задачи из разных групп исполняются параллельно в пределах общего `maxConcurrent`, а задачи с политикой `queue` стартуют сразу при освобождении слота своей группы.
|
|
647
647
|
|
|
648
|
+
|
|
649
|
+
### Событийные триггеры пробуждения (v0.3.33)
|
|
650
|
+
|
|
651
|
+
Реактивный запуск задач агента по системным событиям:
|
|
652
|
+
- **Порог количества файлов (`file_count`)**: запуск при накоплении `>= N` файлов в целевой директории.
|
|
653
|
+
- **Файл-флаг / маркер (`marker_file`)**: запуск при появлении файла готовности (например, `ready.flag`) с автоматическим удалением (`consumeMarker`).
|
|
654
|
+
- **Завершение процесса (`process_exit`)**: отслеживание PID или файла `.pid` и запуск постобработки сразу после завершения фонового процесса.
|
|
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
|
@@ -639,3 +639,17 @@ MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
|
|
|
639
639
|
- **统一安全并发默认值**:配置规范(Config)与调度器(TaskScheduler)全面对齐默认并发上限 `maxConcurrent = 2`(0 仅作为显式无限制选项)。
|
|
640
640
|
- **并发分组隔离调度**:任务的 `concurrencyGroup` 属性全面接入调度仲裁与队列排队(同名分组默认限流 1 个并发执行),不同分组可并发运行直至 `maxConcurrent`,队列任务随所属分组资源释放立即触发。
|
|
641
641
|
|
|
642
|
+
|
|
643
|
+
### 事件驱动唤醒触发器 (v0.3.33)
|
|
644
|
+
|
|
645
|
+
基于本地系统事件响应式唤醒智能体任务:
|
|
646
|
+
- **文件数量阈值 (`file_count`)**: 目标目录下积累 `>= N` 个匹配文件时自动触发批量处理。
|
|
647
|
+
- **标记/Flag文件到达 (`marker_file`)**: 标志文件出现时触发并自动删除标记文件。
|
|
648
|
+
- **进程退出监听 (`process_exit`)**: 监听 PID 或 `.pid` 文件,后台任务退出后立即唤醒任务进行后续处理。
|
|
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,6 +215,21 @@
|
|
|
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
|
+
'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',
|
|
225
|
+
'form.wakeTriggerTypeNone': 'None (Schedule / Cron only)',
|
|
226
|
+
'form.wakeTriggerTypeFileCount': 'File count threshold (batch run)',
|
|
227
|
+
'form.wakeTriggerTypeMarkerFile': 'Marker file receipt (flag file)',
|
|
228
|
+
'form.wakeTriggerTypeProcessExit': 'Process exit watcher (PID / pidFile)',
|
|
229
|
+
'form.wakeTriggerPathLabel': 'Trigger target path (dir / marker / pidfile)',
|
|
230
|
+
'form.wakeTriggerPathPlaceholder': 'e.g. incoming/ or build.ready or run.pid',
|
|
231
|
+
'form.wakeTriggerMinCountLabel': 'Min file count',
|
|
232
|
+
'form.wakeTriggerConsumeLabel': 'Consume / delete marker after trigger',
|
|
218
233
|
'form.writeScopesLabel': 'Write scopes (Scope Locks, relative paths per line or comma)',
|
|
219
234
|
'form.writeScopesPlaceholder': 'e.g. src/, docs/ (prevents concurrent writes on overlapping scopes)',
|
|
220
235
|
'form.inputHashPathsLabel': 'Input hash paths (inputHashPaths)',
|
|
@@ -426,6 +441,21 @@
|
|
|
426
441
|
'form.preflightTargetLabel': '预检目标参数', 'form.preflightTargetPlaceholder': 'https://example.com/healthz 或 ls /data 或 /:10%',
|
|
427
442
|
'form.heartbeatIntervalLabel': '心跳打卡时限 (秒, 0 = 禁用)', 'form.gracePeriodLabel': '心跳宽限期 (秒)',
|
|
428
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 = 不限制)',
|
|
450
|
+
'form.wakeTriggerTypeLabel': '事件唤醒触发器 (Wake Triggers)',
|
|
451
|
+
'form.wakeTriggerTypeNone': '无 (仅定时/间隔)',
|
|
452
|
+
'form.wakeTriggerTypeFileCount': '文件数量阈值 (批量触发)',
|
|
453
|
+
'form.wakeTriggerTypeMarkerFile': '标记/Flag文件到达',
|
|
454
|
+
'form.wakeTriggerTypeProcessExit': '进程退出监听 (PID / pidfile)',
|
|
455
|
+
'form.wakeTriggerPathLabel': '触发目标路径 (目录 / markerPath / pidFile)',
|
|
456
|
+
'form.wakeTriggerPathPlaceholder': '例如: incoming/ 或 build.ready 或 run.pid',
|
|
457
|
+
'form.wakeTriggerMinCountLabel': '最小文件阈值 (minCount)',
|
|
458
|
+
'form.wakeTriggerConsumeLabel': '触发后自动删除标记/PID文件',
|
|
429
459
|
'form.writeScopesLabel': '文件写入范围锁 (writeScopes, 相对路径)', 'form.writeScopesPlaceholder': '例如: src/, docs/ (阻止与同工作区重叠任务并发执行)',
|
|
430
460
|
'form.inputHashPathsLabel': '输入文件哈希变动监控 (inputHashPaths)', 'form.inputHashPathsPlaceholder': '例如: src/, package.json (无变动时跳过执行)',
|
|
431
461
|
'form.skipIfUnchangedLabel': '输入文件无变动时跳过执行 (节省 Token 与预算)',
|
|
@@ -100,6 +100,13 @@
|
|
|
100
100
|
const [formPreflightTarget, setFormPreflightTarget] = React.useState('');
|
|
101
101
|
const [formPriority, setFormPriority] = React.useState(5);
|
|
102
102
|
const [formConcurrencyGroup, setFormConcurrencyGroup] = React.useState('default');
|
|
103
|
+
const [formWakeTriggerType, setFormWakeTriggerType] = React.useState('none');
|
|
104
|
+
const [formWakeTriggerPath, setFormWakeTriggerPath] = React.useState('');
|
|
105
|
+
const [formWakeTriggerMinCount, setFormWakeTriggerMinCount] = React.useState(1);
|
|
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);
|
|
103
110
|
const [formWriteScopes, setFormWriteScopes] = React.useState('');
|
|
104
111
|
const [formInputHashPaths, setFormInputHashPaths] = React.useState('');
|
|
105
112
|
const [formSkipIfUnchanged, setFormSkipIfUnchanged] = React.useState(false);
|
|
@@ -333,6 +333,15 @@
|
|
|
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);
|
|
340
|
+
const _wt = task.wakeTrigger || {};
|
|
341
|
+
setFormWakeTriggerType(_wt.enabled && _wt.type ? _wt.type : 'none');
|
|
342
|
+
setFormWakeTriggerPath(_wt.markerPath || _wt.path || _wt.pidFile || '');
|
|
343
|
+
setFormWakeTriggerMinCount(_wt.minCount || 1);
|
|
344
|
+
setFormWakeTriggerConsume(_wt.consumeMarker !== false);
|
|
336
345
|
setFormWriteScopes(Array.isArray(task.writeScopes) ? task.writeScopes.join('\n') : (task.writeScopes || ''));
|
|
337
346
|
setFormInputHashPaths(Array.isArray(task.inputHashPaths) ? task.inputHashPaths.join('\n') : (task.inputHashPaths || ''));
|
|
338
347
|
setFormSkipIfUnchanged(Boolean(task.skipIfUnchanged));
|
|
@@ -421,6 +430,21 @@
|
|
|
421
430
|
preflightTarget: formPreflightTarget.trim() || undefined,
|
|
422
431
|
priority: Number(formPriority) || 5,
|
|
423
432
|
concurrencyGroup: formConcurrencyGroup.trim() || 'default',
|
|
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' ? {
|
|
440
|
+
enabled: true,
|
|
441
|
+
type: formWakeTriggerType,
|
|
442
|
+
path: formWakeTriggerType === 'file_count' ? formWakeTriggerPath.trim() : undefined,
|
|
443
|
+
minCount: formWakeTriggerType === 'file_count' ? (Number(formWakeTriggerMinCount) || 1) : undefined,
|
|
444
|
+
markerPath: formWakeTriggerType === 'marker_file' ? formWakeTriggerPath.trim() : undefined,
|
|
445
|
+
pidFile: formWakeTriggerType === 'process_exit' ? formWakeTriggerPath.trim() : undefined,
|
|
446
|
+
consumeMarker: Boolean(formWakeTriggerConsume),
|
|
447
|
+
} : null,
|
|
424
448
|
writeScopes: formWriteScopes ? formWriteScopes.split(/[\n,]+/).map((s) => s.trim()).filter(Boolean) : [],
|
|
425
449
|
inputHashPaths: formInputHashPaths ? formInputHashPaths.split(/[\n,]+/).map((s) => s.trim()).filter(Boolean) : [],
|
|
426
450
|
skipIfUnchanged: Boolean(formSkipIfUnchanged),
|
|
@@ -293,6 +293,74 @@
|
|
|
293
293
|
onChange: (e) => setFormConcurrencyGroup(e.target.value)
|
|
294
294
|
})
|
|
295
295
|
)
|
|
296
|
+
),
|
|
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' },
|
|
326
|
+
React.createElement('label', null, T_KEY(t, 'form.wakeTriggerTypeLabel')),
|
|
327
|
+
React.createElement('select', {
|
|
328
|
+
value: formWakeTriggerType,
|
|
329
|
+
onChange: (e) => setFormWakeTriggerType(e.target.value)
|
|
330
|
+
},
|
|
331
|
+
React.createElement('option', { value: 'none' }, T_KEY(t, 'form.wakeTriggerTypeNone')),
|
|
332
|
+
React.createElement('option', { value: 'file_count' }, T_KEY(t, 'form.wakeTriggerTypeFileCount')),
|
|
333
|
+
React.createElement('option', { value: 'marker_file' }, T_KEY(t, 'form.wakeTriggerTypeMarkerFile')),
|
|
334
|
+
React.createElement('option', { value: 'process_exit' }, T_KEY(t, 'form.wakeTriggerTypeProcessExit'))
|
|
335
|
+
)
|
|
336
|
+
),
|
|
337
|
+
formWakeTriggerType !== 'none' && React.createElement('div', { className: 'dsh-cron-form-group' },
|
|
338
|
+
React.createElement('label', null, T_KEY(t, 'form.wakeTriggerPathLabel')),
|
|
339
|
+
React.createElement('input', {
|
|
340
|
+
type: 'text',
|
|
341
|
+
value: formWakeTriggerPath,
|
|
342
|
+
placeholder: T_KEY(t, 'form.wakeTriggerPathPlaceholder'),
|
|
343
|
+
onChange: (e) => setFormWakeTriggerPath(e.target.value)
|
|
344
|
+
})
|
|
345
|
+
),
|
|
346
|
+
formWakeTriggerType === 'file_count' && React.createElement('div', { className: 'dsh-cron-form-group' },
|
|
347
|
+
React.createElement('label', null, T_KEY(t, 'form.wakeTriggerMinCountLabel')),
|
|
348
|
+
React.createElement('input', {
|
|
349
|
+
type: 'number',
|
|
350
|
+
min: 1,
|
|
351
|
+
value: formWakeTriggerMinCount,
|
|
352
|
+
onChange: (e) => setFormWakeTriggerMinCount(parseInt(e.target.value, 10) || 1)
|
|
353
|
+
})
|
|
354
|
+
),
|
|
355
|
+
(formWakeTriggerType === 'marker_file' || formWakeTriggerType === 'process_exit') && React.createElement('div', { className: 'dsh-cron-form-group dsh-cron-form-checkbox' },
|
|
356
|
+
React.createElement('label', null,
|
|
357
|
+
React.createElement('input', {
|
|
358
|
+
type: 'checkbox',
|
|
359
|
+
checked: formWakeTriggerConsume,
|
|
360
|
+
onChange: (e) => setFormWakeTriggerConsume(e.target.checked)
|
|
361
|
+
}),
|
|
362
|
+
React.createElement('span', null, T_KEY(t, 'form.wakeTriggerConsumeLabel'))
|
|
363
|
+
)
|
|
296
364
|
),
|
|
297
365
|
React.createElement('div', { className: 'dsh-cron-form-group' },
|
|
298
366
|
React.createElement('label', null, T_KEY(t, 'form.writeScopesLabel')),
|
package/lib/client.js
CHANGED
|
@@ -261,6 +261,21 @@ 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)',
|
|
270
|
+
'form.wakeTriggerTypeLabel': 'Event wake trigger',
|
|
271
|
+
'form.wakeTriggerTypeNone': 'None (Schedule / Cron only)',
|
|
272
|
+
'form.wakeTriggerTypeFileCount': 'File count threshold (batch run)',
|
|
273
|
+
'form.wakeTriggerTypeMarkerFile': 'Marker file receipt (flag file)',
|
|
274
|
+
'form.wakeTriggerTypeProcessExit': 'Process exit watcher (PID / pidFile)',
|
|
275
|
+
'form.wakeTriggerPathLabel': 'Trigger target path (dir / marker / pidfile)',
|
|
276
|
+
'form.wakeTriggerPathPlaceholder': 'e.g. incoming/ or build.ready or run.pid',
|
|
277
|
+
'form.wakeTriggerMinCountLabel': 'Min file count',
|
|
278
|
+
'form.wakeTriggerConsumeLabel': 'Consume / delete marker after trigger',
|
|
264
279
|
'form.writeScopesLabel': 'Write scopes (Scope Locks, relative paths per line or comma)',
|
|
265
280
|
'form.writeScopesPlaceholder': 'e.g. src/, docs/ (prevents concurrent writes on overlapping scopes)',
|
|
266
281
|
'form.inputHashPathsLabel': 'Input hash paths (inputHashPaths)',
|
|
@@ -471,6 +486,21 @@ zh: {
|
|
|
471
486
|
'form.preflightTargetLabel': '预检目标参数', 'form.preflightTargetPlaceholder': 'https://example.com/healthz 或 ls /data 或 /:10%',
|
|
472
487
|
'form.heartbeatIntervalLabel': '心跳打卡时限 (秒, 0 = 禁用)', 'form.gracePeriodLabel': '心跳宽限期 (秒)',
|
|
473
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 = 不限制)',
|
|
495
|
+
'form.wakeTriggerTypeLabel': '事件唤醒触发器 (Wake Triggers)',
|
|
496
|
+
'form.wakeTriggerTypeNone': '无 (仅定时/间隔)',
|
|
497
|
+
'form.wakeTriggerTypeFileCount': '文件数量阈值 (批量触发)',
|
|
498
|
+
'form.wakeTriggerTypeMarkerFile': '标记/Flag文件到达',
|
|
499
|
+
'form.wakeTriggerTypeProcessExit': '进程退出监听 (PID / pidfile)',
|
|
500
|
+
'form.wakeTriggerPathLabel': '触发目标路径 (目录 / markerPath / pidFile)',
|
|
501
|
+
'form.wakeTriggerPathPlaceholder': '例如: incoming/ 或 build.ready 或 run.pid',
|
|
502
|
+
'form.wakeTriggerMinCountLabel': '最小文件阈值 (minCount)',
|
|
503
|
+
'form.wakeTriggerConsumeLabel': '触发后自动删除标记/PID文件',
|
|
474
504
|
'form.writeScopesLabel': '文件写入范围锁 (writeScopes, 相对路径)', 'form.writeScopesPlaceholder': '例如: src/, docs/ (阻止与同工作区重叠任务并发执行)',
|
|
475
505
|
'form.inputHashPathsLabel': '输入文件哈希变动监控 (inputHashPaths)', 'form.inputHashPathsPlaceholder': '例如: src/, package.json (无变动时跳过执行)',
|
|
476
506
|
'form.skipIfUnchangedLabel': '输入文件无变动时跳过执行 (节省 Token 与预算)',
|
|
@@ -1638,6 +1668,13 @@ const [formPreflightType, setFormPreflightType] = React.useState('none');
|
|
|
1638
1668
|
const [formPreflightTarget, setFormPreflightTarget] = React.useState('');
|
|
1639
1669
|
const [formPriority, setFormPriority] = React.useState(5);
|
|
1640
1670
|
const [formConcurrencyGroup, setFormConcurrencyGroup] = React.useState('default');
|
|
1671
|
+
const [formWakeTriggerType, setFormWakeTriggerType] = React.useState('none');
|
|
1672
|
+
const [formWakeTriggerPath, setFormWakeTriggerPath] = React.useState('');
|
|
1673
|
+
const [formWakeTriggerMinCount, setFormWakeTriggerMinCount] = React.useState(1);
|
|
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);
|
|
1641
1678
|
const [formWriteScopes, setFormWriteScopes] = React.useState('');
|
|
1642
1679
|
const [formInputHashPaths, setFormInputHashPaths] = React.useState('');
|
|
1643
1680
|
const [formSkipIfUnchanged, setFormSkipIfUnchanged] = React.useState(false);
|
|
@@ -2563,6 +2600,15 @@ setFormPreflightType(task.preflightType || 'none');
|
|
|
2563
2600
|
setFormPreflightTarget(task.preflightTarget || '');
|
|
2564
2601
|
setFormPriority(task.priority !== undefined ? task.priority : 5);
|
|
2565
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);
|
|
2607
|
+
const _wt = task.wakeTrigger || {};
|
|
2608
|
+
setFormWakeTriggerType(_wt.enabled && _wt.type ? _wt.type : 'none');
|
|
2609
|
+
setFormWakeTriggerPath(_wt.markerPath || _wt.path || _wt.pidFile || '');
|
|
2610
|
+
setFormWakeTriggerMinCount(_wt.minCount || 1);
|
|
2611
|
+
setFormWakeTriggerConsume(_wt.consumeMarker !== false);
|
|
2566
2612
|
setFormWriteScopes(Array.isArray(task.writeScopes) ? task.writeScopes.join('\n') : (task.writeScopes || ''));
|
|
2567
2613
|
setFormInputHashPaths(Array.isArray(task.inputHashPaths) ? task.inputHashPaths.join('\n') : (task.inputHashPaths || ''));
|
|
2568
2614
|
setFormSkipIfUnchanged(Boolean(task.skipIfUnchanged));
|
|
@@ -2649,6 +2695,21 @@ preflightType: formPreflightType || 'none',
|
|
|
2649
2695
|
preflightTarget: formPreflightTarget.trim() || undefined,
|
|
2650
2696
|
priority: Number(formPriority) || 5,
|
|
2651
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,
|
|
2704
|
+
wakeTrigger: formWakeTriggerType && formWakeTriggerType !== 'none' ? {
|
|
2705
|
+
enabled: true,
|
|
2706
|
+
type: formWakeTriggerType,
|
|
2707
|
+
path: formWakeTriggerType === 'file_count' ? formWakeTriggerPath.trim() : undefined,
|
|
2708
|
+
minCount: formWakeTriggerType === 'file_count' ? (Number(formWakeTriggerMinCount) || 1) : undefined,
|
|
2709
|
+
markerPath: formWakeTriggerType === 'marker_file' ? formWakeTriggerPath.trim() : undefined,
|
|
2710
|
+
pidFile: formWakeTriggerType === 'process_exit' ? formWakeTriggerPath.trim() : undefined,
|
|
2711
|
+
consumeMarker: Boolean(formWakeTriggerConsume),
|
|
2712
|
+
} : null,
|
|
2652
2713
|
writeScopes: formWriteScopes ? formWriteScopes.split(/[\n,]+/).map((s) => s.trim()).filter(Boolean) : [],
|
|
2653
2714
|
inputHashPaths: formInputHashPaths ? formInputHashPaths.split(/[\n,]+/).map((s) => s.trim()).filter(Boolean) : [],
|
|
2654
2715
|
skipIfUnchanged: Boolean(formSkipIfUnchanged),
|
|
@@ -4155,6 +4216,74 @@ onChange: (e) => setFormConcurrencyGroup(e.target.value)
|
|
|
4155
4216
|
)
|
|
4156
4217
|
),
|
|
4157
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' },
|
|
4247
|
+
_h('label', null, T_KEY(t, 'form.wakeTriggerTypeLabel')),
|
|
4248
|
+
_h('select', {
|
|
4249
|
+
value: formWakeTriggerType,
|
|
4250
|
+
onChange: (e) => setFormWakeTriggerType(e.target.value)
|
|
4251
|
+
},
|
|
4252
|
+
_h('option', { value: 'none' }, T_KEY(t, 'form.wakeTriggerTypeNone')),
|
|
4253
|
+
_h('option', { value: 'file_count' }, T_KEY(t, 'form.wakeTriggerTypeFileCount')),
|
|
4254
|
+
_h('option', { value: 'marker_file' }, T_KEY(t, 'form.wakeTriggerTypeMarkerFile')),
|
|
4255
|
+
_h('option', { value: 'process_exit' }, T_KEY(t, 'form.wakeTriggerTypeProcessExit'))
|
|
4256
|
+
)
|
|
4257
|
+
),
|
|
4258
|
+
formWakeTriggerType !== 'none' && _h('div', { className: 'dsh-cron-form-group' },
|
|
4259
|
+
_h('label', null, T_KEY(t, 'form.wakeTriggerPathLabel')),
|
|
4260
|
+
_h('input', {
|
|
4261
|
+
type: 'text',
|
|
4262
|
+
value: formWakeTriggerPath,
|
|
4263
|
+
placeholder: T_KEY(t, 'form.wakeTriggerPathPlaceholder'),
|
|
4264
|
+
onChange: (e) => setFormWakeTriggerPath(e.target.value)
|
|
4265
|
+
})
|
|
4266
|
+
),
|
|
4267
|
+
formWakeTriggerType === 'file_count' && _h('div', { className: 'dsh-cron-form-group' },
|
|
4268
|
+
_h('label', null, T_KEY(t, 'form.wakeTriggerMinCountLabel')),
|
|
4269
|
+
_h('input', {
|
|
4270
|
+
type: 'number',
|
|
4271
|
+
min: 1,
|
|
4272
|
+
value: formWakeTriggerMinCount,
|
|
4273
|
+
onChange: (e) => setFormWakeTriggerMinCount(parseInt(e.target.value, 10) || 1)
|
|
4274
|
+
})
|
|
4275
|
+
),
|
|
4276
|
+
(formWakeTriggerType === 'marker_file' || formWakeTriggerType === 'process_exit') && _h('div', { className: 'dsh-cron-form-group dsh-cron-form-checkbox' },
|
|
4277
|
+
_h('label', null,
|
|
4278
|
+
_h('input', {
|
|
4279
|
+
type: 'checkbox',
|
|
4280
|
+
checked: formWakeTriggerConsume,
|
|
4281
|
+
onChange: (e) => setFormWakeTriggerConsume(e.target.checked)
|
|
4282
|
+
}),
|
|
4283
|
+
_h('span', null, T_KEY(t, 'form.wakeTriggerConsumeLabel'))
|
|
4284
|
+
)
|
|
4285
|
+
),
|
|
4286
|
+
_h('div', { className: 'dsh-cron-form-group' },
|
|
4158
4287
|
_h('label', null, T_KEY(t, 'form.writeScopesLabel')),
|
|
4159
4288
|
_h('input', {
|
|
4160
4289
|
type: 'text',
|
package/lib/cron-tool.js
CHANGED
|
@@ -326,6 +326,20 @@ 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
|
+
},
|
|
338
|
+
wakeTrigger: {
|
|
339
|
+
type: 'object',
|
|
340
|
+
additionalProperties: true,
|
|
341
|
+
description: 'Event-driven wake trigger (file_count, marker_file, or process_exit)',
|
|
342
|
+
},
|
|
329
343
|
writeScopes: {
|
|
330
344
|
type: 'array',
|
|
331
345
|
description: 'Relative directory/file scopes to lock to prevent conflicting concurrent writes',
|
package/lib/locales.json
CHANGED
|
@@ -410,6 +410,21 @@
|
|
|
410
410
|
"form.writeScopesPlaceholder": "例如: src/, docs/ (阻止与同工作区重叠任务并发执行)",
|
|
411
411
|
"form.inputHashPathsLabel": "输入文件哈希变动监控 (inputHashPaths)",
|
|
412
412
|
"form.inputHashPathsPlaceholder": "例如: src/, package.json (无变动时跳过执行)",
|
|
413
|
-
"form.skipIfUnchangedLabel": "输入文件无变动时跳过执行 (节省 Token 与预算)"
|
|
413
|
+
"form.skipIfUnchangedLabel": "输入文件无变动时跳过执行 (节省 Token 与预算)",
|
|
414
|
+
"form.wakeTriggerTypeLabel": "事件唤醒触发器 (Wake Triggers)",
|
|
415
|
+
"form.wakeTriggerTypeNone": "无 (仅定时/间隔)",
|
|
416
|
+
"form.wakeTriggerTypeFileCount": "文件数量阈值 (批量触发)",
|
|
417
|
+
"form.wakeTriggerTypeMarkerFile": "标记/Flag文件到达",
|
|
418
|
+
"form.wakeTriggerTypeProcessExit": "进程退出监听 (PID / pidfile)",
|
|
419
|
+
"form.wakeTriggerPathLabel": "触发目标路径 (目录 / markerPath / pidFile)",
|
|
420
|
+
"form.wakeTriggerPathPlaceholder": "例如: incoming/ 或 build.ready 或 run.pid",
|
|
421
|
+
"form.wakeTriggerMinCountLabel": "最小文件阈值 (minCount)",
|
|
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 = 不限制)"
|
|
414
429
|
}
|
|
415
|
-
}
|
|
430
|
+
}
|
|
@@ -125,6 +125,12 @@ export function buildPromptContext(task = {}, options = {}) {
|
|
|
125
125
|
}
|
|
126
126
|
}
|
|
127
127
|
|
|
128
|
+
if (options.wakeTrigger && typeof options.wakeTrigger === 'object') {
|
|
129
|
+
ctx['trigger.type'] = options.wakeTrigger.type || '';
|
|
130
|
+
ctx['trigger.markerPath'] = options.wakeTrigger.markerPath || '';
|
|
131
|
+
ctx['trigger.fileCount'] = String(options.wakeTrigger.fileCount ?? '');
|
|
132
|
+
ctx['trigger.pid'] = String(options.wakeTrigger.pid ?? '');
|
|
133
|
+
}
|
|
128
134
|
return ctx;
|
|
129
135
|
}
|
|
130
136
|
|
|
@@ -215,5 +221,14 @@ export function resolveTaskForExecution(task, options = {}) {
|
|
|
215
221
|
resolved.env = env;
|
|
216
222
|
}
|
|
217
223
|
|
|
224
|
+
if (options.wakeTrigger && typeof options.wakeTrigger === 'object') {
|
|
225
|
+
const env = { ...(resolved.env || {}) };
|
|
226
|
+
env.DSH_CRON_WAKE_TYPE = String(options.wakeTrigger.type || '');
|
|
227
|
+
if (options.wakeTrigger.markerPath) env.DSH_CRON_WAKE_MARKER = String(options.wakeTrigger.markerPath);
|
|
228
|
+
if (options.wakeTrigger.path) env.DSH_CRON_WAKE_PATH = String(options.wakeTrigger.path);
|
|
229
|
+
if (options.wakeTrigger.fileCount !== undefined) env.DSH_CRON_WAKE_FILE_COUNT = String(options.wakeTrigger.fileCount);
|
|
230
|
+
if (options.wakeTrigger.pid !== undefined) env.DSH_CRON_WAKE_PID = String(options.wakeTrigger.pid);
|
|
231
|
+
resolved.env = env;
|
|
232
|
+
}
|
|
218
233
|
return resolved;
|
|
219
234
|
}
|
|
@@ -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) {
|
|
@@ -4,6 +4,7 @@ import { Cron } from 'croner';
|
|
|
4
4
|
import { FileSystemWatcherManager } from '../watcher.js';
|
|
5
5
|
import { parseNaturalSchedule } from '../nl-schedule.js';
|
|
6
6
|
import { ScopeLockManager } from '../scope-locks.js';
|
|
7
|
+
import { WakeTriggerManager } from '../wake-triggers.js';
|
|
7
8
|
|
|
8
9
|
const MAX_TIMEOUT_MS = 2147483647; // 2^31 - 1 ms (~24.85 days)
|
|
9
10
|
import {
|
|
@@ -332,6 +333,7 @@ export class TaskScheduler {
|
|
|
332
333
|
this.timers = new Map();
|
|
333
334
|
this.retryTimers = new Map();
|
|
334
335
|
this.adaptiveTimers = new Map();
|
|
336
|
+
this.deferredTimers = new Map();
|
|
335
337
|
this.running = new Map();
|
|
336
338
|
this.runCounters = {};
|
|
337
339
|
this.queue = [];
|
|
@@ -339,6 +341,7 @@ export class TaskScheduler {
|
|
|
339
341
|
this.heartbeatTimer = null;
|
|
340
342
|
this.watcherManager = new FileSystemWatcherManager(this);
|
|
341
343
|
this.scopeLocks = new ScopeLockManager();
|
|
344
|
+
this.wakeTriggerManager = new WakeTriggerManager(this);
|
|
342
345
|
this.logger = opts.logger || null;
|
|
343
346
|
this.isStopped = false;
|
|
344
347
|
this.generation = 0;
|
|
@@ -365,6 +368,26 @@ export class TaskScheduler {
|
|
|
365
368
|
}
|
|
366
369
|
}
|
|
367
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
|
+
|
|
368
391
|
clearAdaptiveTimer(taskId) {
|
|
369
392
|
const t = this.adaptiveTimers.get(taskId);
|
|
370
393
|
if (t) {
|
|
@@ -375,6 +398,10 @@ export class TaskScheduler {
|
|
|
375
398
|
|
|
376
399
|
armAdaptiveTimer(taskId, delayMs) {
|
|
377
400
|
this.clearAdaptiveTimer(taskId);
|
|
401
|
+
this.clearDeferredTimer(taskId);
|
|
402
|
+
if (this.wakeTriggerManager) {
|
|
403
|
+
this.wakeTriggerManager.unregisterTask(taskId);
|
|
404
|
+
}
|
|
378
405
|
if (this.jobs.has(taskId)) {
|
|
379
406
|
this.jobs.get(taskId).stop();
|
|
380
407
|
this.jobs.delete(taskId);
|
|
@@ -469,6 +496,9 @@ export class TaskScheduler {
|
|
|
469
496
|
if (this.watcherManager) {
|
|
470
497
|
this.watcherManager.syncAll(tasks);
|
|
471
498
|
}
|
|
499
|
+
if (this.wakeTriggerManager) {
|
|
500
|
+
this.wakeTriggerManager.syncTasks(tasks);
|
|
501
|
+
}
|
|
472
502
|
}
|
|
473
503
|
|
|
474
504
|
stopAll() {
|
|
@@ -478,6 +508,9 @@ export class TaskScheduler {
|
|
|
478
508
|
if (this.watcherManager) {
|
|
479
509
|
this.watcherManager.stopAll();
|
|
480
510
|
}
|
|
511
|
+
if (this.wakeTriggerManager) {
|
|
512
|
+
this.wakeTriggerManager.stopAll();
|
|
513
|
+
}
|
|
481
514
|
|
|
482
515
|
// Clear concurrency queue (#217)
|
|
483
516
|
this.queue = [];
|
|
@@ -514,6 +547,10 @@ export class TaskScheduler {
|
|
|
514
547
|
|
|
515
548
|
clearScheduled(taskId) {
|
|
516
549
|
this.clearAdaptiveTimer(taskId);
|
|
550
|
+
this.clearDeferredTimer(taskId);
|
|
551
|
+
if (this.wakeTriggerManager) {
|
|
552
|
+
this.wakeTriggerManager.unregisterTask(taskId);
|
|
553
|
+
}
|
|
517
554
|
if (this.watcherManager) {
|
|
518
555
|
this.watcherManager.unwatchTask(taskId);
|
|
519
556
|
}
|
|
@@ -584,6 +621,9 @@ export class TaskScheduler {
|
|
|
584
621
|
if (this.watcherManager) {
|
|
585
622
|
this.watcherManager.watchTask(task);
|
|
586
623
|
}
|
|
624
|
+
if (this.wakeTriggerManager) {
|
|
625
|
+
this.wakeTriggerManager.registerTask(task);
|
|
626
|
+
}
|
|
587
627
|
|
|
588
628
|
try {
|
|
589
629
|
const parsed = parseScheduleExpression(task.schedule);
|
package/lib/store/task-schema.js
CHANGED
|
@@ -99,6 +99,9 @@ export const TaskSchema = z.object({
|
|
|
99
99
|
inputHashPaths: z.any(),
|
|
100
100
|
skipIfUnchanged: z.boolean().default(false),
|
|
101
101
|
lastInputHash: z.string().default(''),
|
|
102
|
+
wakeTrigger: z.any(),
|
|
103
|
+
workWindow: z.any(),
|
|
104
|
+
timeBoxMinutes: z.number().min(0).default(0),
|
|
102
105
|
maxMemoryMb: z.number().min(0).default(0),
|
|
103
106
|
executionTimeoutMs: z.number().min(0).default(900000),
|
|
104
107
|
maxLogBytesPerRun: z.number().min(0).default(5 * 1024 * 1024),
|
|
@@ -108,6 +108,9 @@ export const PATCHABLE_TASK_FIELDS = [
|
|
|
108
108
|
'inputHashPaths',
|
|
109
109
|
'skipIfUnchanged',
|
|
110
110
|
'lastInputHash',
|
|
111
|
+
'wakeTrigger',
|
|
112
|
+
'workWindow',
|
|
113
|
+
'timeBoxMinutes',
|
|
111
114
|
];
|
|
112
115
|
|
|
113
116
|
/** Fields a duplicate inherits; anything else is runtime state, not config. */
|
package/lib/task-create.js
CHANGED
|
@@ -10,6 +10,8 @@ import { parseScheduleExpression } from './scheduler.js';
|
|
|
10
10
|
import { CHANNEL_IDS } from './channels.js';
|
|
11
11
|
import { redactTaskSecrets } from './http-utils.js';
|
|
12
12
|
import { normalizeScopes } from './scope-locks.js';
|
|
13
|
+
import { normalizeWakeTrigger } from './wake-triggers.js';
|
|
14
|
+
import { normalizeWorkWindow } from './work-windows.js';
|
|
13
15
|
import { normalizeInputHashPaths } from './input-hash.js';
|
|
14
16
|
import { sanitizeDependsOn, sanitizeJoinPolicy, validateDAG } from './dag.js';
|
|
15
17
|
|
|
@@ -64,6 +66,9 @@ export function executeCreateTask(store, scheduler, args) {
|
|
|
64
66
|
swarm: args.swarm !== undefined ? sanitizeSwarmConfig(args.swarm) : undefined,
|
|
65
67
|
elseTask: args.elseTask ? String(args.elseTask).trim() : undefined,
|
|
66
68
|
autoHeal: args.autoHeal !== undefined ? Boolean(args.autoHeal) : undefined,
|
|
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,
|
|
67
72
|
writeScopes: args.writeScopes !== undefined ? normalizeScopes(args.writeScopes) : undefined,
|
|
68
73
|
inputHashPaths: args.inputHashPaths !== undefined ? normalizeInputHashPaths(args.inputHashPaths) : undefined,
|
|
69
74
|
skipIfUnchanged: args.skipIfUnchanged !== undefined ? Boolean(args.skipIfUnchanged) : undefined,
|
package/lib/task-patch.js
CHANGED
|
@@ -21,6 +21,8 @@ import { PATCHABLE_TASK_FIELDS, validateTaskType } from './task-transfer.js';
|
|
|
21
21
|
import { pickPatchableFields, restoreTaskSecrets } from './http-utils.js';
|
|
22
22
|
import { unknownChannelIds } from './channels.js';
|
|
23
23
|
import { normalizeScopes } from './scope-locks.js';
|
|
24
|
+
import { normalizeWakeTrigger } from './wake-triggers.js';
|
|
25
|
+
import { normalizeWorkWindow } from './work-windows.js';
|
|
24
26
|
import { normalizeInputHashPaths } from './input-hash.js';
|
|
25
27
|
import { isConfigOwned, configOwnedMessage } from './config-jobs.js';
|
|
26
28
|
|
|
@@ -134,6 +136,15 @@ export function buildTaskPatch(current, body) {
|
|
|
134
136
|
if (patch.autoHeal !== undefined) {
|
|
135
137
|
patch.autoHeal = Boolean(patch.autoHeal);
|
|
136
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
|
+
}
|
|
145
|
+
if (patch.wakeTrigger !== undefined) {
|
|
146
|
+
patch.wakeTrigger = normalizeWakeTrigger(patch.wakeTrigger);
|
|
147
|
+
}
|
|
137
148
|
if (patch.writeScopes !== undefined) {
|
|
138
149
|
patch.writeScopes = normalizeScopes(patch.writeScopes);
|
|
139
150
|
}
|
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { logger } from './logger.js';
|
|
4
|
+
import { bestEffort } from './best-effort.js';
|
|
5
|
+
|
|
6
|
+
const DISALLOWED_ROOTS = [
|
|
7
|
+
'/',
|
|
8
|
+
'/proc',
|
|
9
|
+
'/sys',
|
|
10
|
+
'/dev',
|
|
11
|
+
'/etc',
|
|
12
|
+
'/boot',
|
|
13
|
+
'/run',
|
|
14
|
+
'/var/run',
|
|
15
|
+
'c:\\',
|
|
16
|
+
'c:\\windows',
|
|
17
|
+
'c:\\windows\\system32',
|
|
18
|
+
'c:\\program files',
|
|
19
|
+
'c:\\program files (x86)',
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Validates that a path does not target sensitive system locations or escape root.
|
|
24
|
+
*/
|
|
25
|
+
export function isSafeWakePath(targetPath) {
|
|
26
|
+
if (!targetPath || typeof targetPath !== 'string') {
|
|
27
|
+
return { safe: false, error: 'Path must be a non-empty string' };
|
|
28
|
+
}
|
|
29
|
+
const trimmed = targetPath.trim();
|
|
30
|
+
if (trimmed.includes('\0')) {
|
|
31
|
+
return { safe: false, error: 'Path must not contain null bytes' };
|
|
32
|
+
}
|
|
33
|
+
const resolved = path.resolve(trimmed);
|
|
34
|
+
const lower = resolved.toLowerCase();
|
|
35
|
+
|
|
36
|
+
for (const root of DISALLOWED_ROOTS) {
|
|
37
|
+
if (lower === root || lower === root.replace(/\\/g, '/')) {
|
|
38
|
+
return { safe: false, error: `Path "${resolved}" targets a disallowed system root directory` };
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (resolved === path.parse(resolved).root) {
|
|
43
|
+
return { safe: false, error: `Path "${resolved}" is a filesystem root` };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
return { safe: true, resolved };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Normalizes wake trigger configuration. Returns null if invalid or disabled.
|
|
51
|
+
*/
|
|
52
|
+
export function normalizeWakeTrigger(cfg) {
|
|
53
|
+
if (!cfg || typeof cfg !== 'object') return null;
|
|
54
|
+
const enabled = cfg.enabled !== false;
|
|
55
|
+
const type = String(cfg.type || '').trim().toLowerCase();
|
|
56
|
+
|
|
57
|
+
if (!['file_count', 'marker_file', 'process_exit'].includes(type)) {
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const normalized = {
|
|
62
|
+
enabled,
|
|
63
|
+
type,
|
|
64
|
+
pollIntervalMs: Math.max(20, Number(cfg.pollIntervalMs) || 3000),
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
if (type === 'file_count') {
|
|
68
|
+
normalized.path = String(cfg.path || '').trim();
|
|
69
|
+
normalized.minCount = Math.max(1, parseInt(cfg.minCount, 10) || 1);
|
|
70
|
+
normalized.pattern = String(cfg.pattern || '*').trim() || '*';
|
|
71
|
+
} else if (type === 'marker_file') {
|
|
72
|
+
normalized.markerPath = String(cfg.markerPath || cfg.path || '').trim();
|
|
73
|
+
normalized.consumeMarker = cfg.consumeMarker !== false;
|
|
74
|
+
} else if (type === 'process_exit') {
|
|
75
|
+
if (cfg.pid !== undefined && cfg.pid !== null && cfg.pid !== '') {
|
|
76
|
+
const pidNum = parseInt(cfg.pid, 10);
|
|
77
|
+
if (Number.isInteger(pidNum) && pidNum > 1) {
|
|
78
|
+
normalized.pid = pidNum;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
normalized.pidFile = String(cfg.pidFile || '').trim();
|
|
82
|
+
normalized.consumeMarker = Boolean(cfg.consumeMarker);
|
|
83
|
+
if (!normalized.pid && !normalized.pidFile) {
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return normalized;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Checks if an OS process is currently running.
|
|
93
|
+
*/
|
|
94
|
+
export function isProcessAlive(pid) {
|
|
95
|
+
if (!Number.isInteger(pid) || pid <= 1) return false;
|
|
96
|
+
try {
|
|
97
|
+
process.kill(pid, 0);
|
|
98
|
+
return true;
|
|
99
|
+
} catch (err) {
|
|
100
|
+
return err.code === 'EPERM';
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Matches a filename against a glob pattern (wildcards * and ?, comma-separated).
|
|
106
|
+
*/
|
|
107
|
+
export function matchPattern(filename, pattern) {
|
|
108
|
+
if (!pattern || pattern.trim() === '' || pattern === '*') return true;
|
|
109
|
+
const parts = pattern.split(',').map((p) => p.trim()).filter(Boolean);
|
|
110
|
+
if (!parts.length) return true;
|
|
111
|
+
|
|
112
|
+
return parts.some((p) => {
|
|
113
|
+
const regexStr = '^' + p.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.') + '$';
|
|
114
|
+
try {
|
|
115
|
+
return new RegExp(regexStr, 'i').test(filename);
|
|
116
|
+
} catch (_err) {
|
|
117
|
+
void _err;
|
|
118
|
+
return false;
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Counts non-directory files in a directory matching pattern.
|
|
125
|
+
*/
|
|
126
|
+
export function countMatchingFiles(dir, pattern = '*') {
|
|
127
|
+
try {
|
|
128
|
+
const entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
129
|
+
const matched = [];
|
|
130
|
+
for (const entry of entries) {
|
|
131
|
+
if (entry.isFile() || entry.isSymbolicLink()) {
|
|
132
|
+
if (matchPattern(entry.name, pattern)) {
|
|
133
|
+
matched.push(entry.name);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return { count: matched.length, files: matched };
|
|
138
|
+
} catch (_err) {
|
|
139
|
+
void _err;
|
|
140
|
+
return { count: 0, files: [] };
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* WakeTriggerManager manages background observation and event-driven waking of tasks (#410).
|
|
146
|
+
*/
|
|
147
|
+
export class WakeTriggerManager {
|
|
148
|
+
constructor(scheduler) {
|
|
149
|
+
this.scheduler = scheduler;
|
|
150
|
+
this.watchers = new Map(); // taskId -> { timer, config, state }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
syncTasks(tasks) {
|
|
154
|
+
if (!Array.isArray(tasks)) return;
|
|
155
|
+
const activeTaskIds = new Set();
|
|
156
|
+
for (const task of tasks) {
|
|
157
|
+
if (task && task.id && task.status === 'active' && task.wakeTrigger) {
|
|
158
|
+
const norm = normalizeWakeTrigger(task.wakeTrigger);
|
|
159
|
+
if (norm && norm.enabled) {
|
|
160
|
+
activeTaskIds.add(task.id);
|
|
161
|
+
this.registerTask(task);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// Stop watchers for tasks that are no longer active or have no wake trigger
|
|
167
|
+
for (const taskId of this.watchers.keys()) {
|
|
168
|
+
if (!activeTaskIds.has(taskId)) {
|
|
169
|
+
this.unregisterTask(taskId);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
registerTask(task) {
|
|
175
|
+
if (!task || !task.id) return;
|
|
176
|
+
const norm = normalizeWakeTrigger(task.wakeTrigger);
|
|
177
|
+
|
|
178
|
+
if (!norm || !norm.enabled || task.status !== 'active') {
|
|
179
|
+
this.unregisterTask(task.id);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const current = this.watchers.get(task.id);
|
|
184
|
+
const configSig = JSON.stringify(norm);
|
|
185
|
+
|
|
186
|
+
if (current && current.sig === configSig) {
|
|
187
|
+
return; // Already registered with same config
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
this.unregisterTask(task.id);
|
|
191
|
+
|
|
192
|
+
const state = {
|
|
193
|
+
triggered: false,
|
|
194
|
+
lastCount: 0,
|
|
195
|
+
processSeenAlive: false,
|
|
196
|
+
monitoredPid: norm.pid || null,
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
const runCheck = async () => {
|
|
200
|
+
if (!this.scheduler || this.scheduler.isStopped) return;
|
|
201
|
+
try {
|
|
202
|
+
if (norm.type === 'file_count') {
|
|
203
|
+
await this._checkFileCount(task, norm, state);
|
|
204
|
+
} else if (norm.type === 'marker_file') {
|
|
205
|
+
await this._checkMarkerFile(task, norm, state);
|
|
206
|
+
} else if (norm.type === 'process_exit') {
|
|
207
|
+
await this._checkProcessExit(task, norm, state);
|
|
208
|
+
}
|
|
209
|
+
} catch (err) {
|
|
210
|
+
logger.error(`[dsh-cron] Wake trigger check failed for task "${task.title}" (${task.id}): ${err.message}`);
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
const timer = setInterval(runCheck, norm.pollIntervalMs);
|
|
215
|
+
if (timer.unref) timer.unref();
|
|
216
|
+
|
|
217
|
+
this.watchers.set(task.id, {
|
|
218
|
+
timer,
|
|
219
|
+
sig: configSig,
|
|
220
|
+
config: norm,
|
|
221
|
+
state,
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
// Run first check promptly
|
|
225
|
+
setImmediate(runCheck);
|
|
226
|
+
logger.info(`[dsh-cron] Wake trigger (${norm.type}) registered for task "${task.title}" (${task.id})`);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
unregisterTask(taskId) {
|
|
230
|
+
const entry = this.watchers.get(taskId);
|
|
231
|
+
if (entry) {
|
|
232
|
+
if (entry.timer) clearInterval(entry.timer);
|
|
233
|
+
this.watchers.delete(taskId);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
stopAll() {
|
|
238
|
+
for (const entry of this.watchers.values()) {
|
|
239
|
+
if (entry.timer) clearInterval(entry.timer);
|
|
240
|
+
}
|
|
241
|
+
this.watchers.clear();
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async _checkFileCount(task, cfg, state) {
|
|
245
|
+
const check = isSafeWakePath(cfg.path);
|
|
246
|
+
if (!check.safe) return;
|
|
247
|
+
if (!fs.existsSync(check.resolved)) return;
|
|
248
|
+
|
|
249
|
+
const { count, files } = countMatchingFiles(check.resolved, cfg.pattern);
|
|
250
|
+
|
|
251
|
+
if (count >= cfg.minCount) {
|
|
252
|
+
// Trigger if not triggered yet, or if new files arrived since last trigger
|
|
253
|
+
if (!state.triggered || count > state.lastCount) {
|
|
254
|
+
state.triggered = true;
|
|
255
|
+
state.lastCount = count;
|
|
256
|
+
logger.info(`[dsh-cron] Wake trigger file_count (${count} >= ${cfg.minCount}) fired for task "${task.title}" (${task.id})`);
|
|
257
|
+
await this._triggerTask(task, {
|
|
258
|
+
type: 'file_count',
|
|
259
|
+
path: check.resolved,
|
|
260
|
+
fileCount: count,
|
|
261
|
+
minCount: cfg.minCount,
|
|
262
|
+
pattern: cfg.pattern,
|
|
263
|
+
matchedFiles: files,
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
} else {
|
|
267
|
+
// Reset trigger state when file count drops below threshold
|
|
268
|
+
state.triggered = false;
|
|
269
|
+
state.lastCount = count;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
async _checkMarkerFile(task, cfg, state) {
|
|
274
|
+
const check = isSafeWakePath(cfg.markerPath);
|
|
275
|
+
if (!check.safe) return;
|
|
276
|
+
if (!fs.existsSync(check.resolved)) {
|
|
277
|
+
state.triggered = false;
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
if (state.triggered) return; // Wait for marker to disappear / re-appear
|
|
282
|
+
|
|
283
|
+
state.triggered = true;
|
|
284
|
+
|
|
285
|
+
if (cfg.consumeMarker) {
|
|
286
|
+
try {
|
|
287
|
+
fs.unlinkSync(check.resolved);
|
|
288
|
+
} catch (_err) {
|
|
289
|
+
void _err;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
logger.info(`[dsh-cron] Wake trigger marker_file (${check.resolved}) fired for task "${task.title}" (${task.id})`);
|
|
294
|
+
await this._triggerTask(task, {
|
|
295
|
+
type: 'marker_file',
|
|
296
|
+
markerPath: check.resolved,
|
|
297
|
+
consumed: Boolean(cfg.consumeMarker),
|
|
298
|
+
triggeredAt: Date.now(),
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
async _checkProcessExit(task, cfg, state) {
|
|
303
|
+
// If tracking via pidFile, attempt to read PID
|
|
304
|
+
if (cfg.pidFile) {
|
|
305
|
+
const check = isSafeWakePath(cfg.pidFile);
|
|
306
|
+
if (check.safe && fs.existsSync(check.resolved)) {
|
|
307
|
+
try {
|
|
308
|
+
const content = fs.readFileSync(check.resolved, 'utf8').trim();
|
|
309
|
+
const parsed = parseInt(content, 10);
|
|
310
|
+
if (Number.isInteger(parsed) && parsed > 1) {
|
|
311
|
+
state.monitoredPid = parsed;
|
|
312
|
+
}
|
|
313
|
+
} catch (_err) {
|
|
314
|
+
void _err;
|
|
315
|
+
}
|
|
316
|
+
} else {
|
|
317
|
+
// pidFile does not exist yet or was removed
|
|
318
|
+
if (!state.monitoredPid) return;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
if (!state.monitoredPid) return;
|
|
323
|
+
|
|
324
|
+
const alive = isProcessAlive(state.monitoredPid);
|
|
325
|
+
|
|
326
|
+
if (alive) {
|
|
327
|
+
state.processSeenAlive = true;
|
|
328
|
+
} else if (state.processSeenAlive && !alive) {
|
|
329
|
+
// Process was alive and has now exited!
|
|
330
|
+
const exitedPid = state.monitoredPid;
|
|
331
|
+
state.processSeenAlive = false;
|
|
332
|
+
state.monitoredPid = null;
|
|
333
|
+
|
|
334
|
+
if (cfg.consumeMarker && cfg.pidFile) {
|
|
335
|
+
const check = isSafeWakePath(cfg.pidFile);
|
|
336
|
+
if (check.safe && fs.existsSync(check.resolved)) {
|
|
337
|
+
bestEffort('unlink-pid-file', () => fs.unlinkSync(check.resolved));
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
logger.info(`[dsh-cron] Wake trigger process_exit (PID ${exitedPid}) fired for task "${task.title}" (${task.id})`);
|
|
342
|
+
await this._triggerTask(task, {
|
|
343
|
+
type: 'process_exit',
|
|
344
|
+
pid: exitedPid,
|
|
345
|
+
pidFile: cfg.pidFile || '',
|
|
346
|
+
exitTime: Date.now(),
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
async _triggerTask(task, wakeContext) {
|
|
352
|
+
if (!this.scheduler || this.scheduler.isStopped) return;
|
|
353
|
+
try {
|
|
354
|
+
await this.scheduler.runTask(task.id, {
|
|
355
|
+
wakeTrigger: wakeContext,
|
|
356
|
+
trigger: `wakeTrigger:${wakeContext.type}`,
|
|
357
|
+
});
|
|
358
|
+
} catch (err) {
|
|
359
|
+
logger.error(`[dsh-cron] Wake trigger execution failed for task ${task.id}: ${err.message}`);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
}
|
|
@@ -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",
|