@goodandready/dsh-cron 0.3.31 → 0.3.33

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 CHANGED
@@ -207,6 +207,8 @@ Every task picks its own runtime; non-LLM runtimes need no model and consume no
207
207
  * **Docker** (`docker`) — run the command in a container image (`dockerImage`).
208
208
  * **Environment variables** — a per-task `env` map (KEY VALUE per line in the UI) applied to external runtimes; secrets do not belong here.
209
209
  * **Workspaces and worktrees** — bind a task to a harness workspace (`workspaceId`, resolved through host `workspaceRegistry`) or path; the agent session created for the run is registered with that workspace's ledger (`attachSession`), so it appears under the project instead of ungrouped. Code-modifying agent tasks can run in an isolated git worktree (`worktree`, `keepWorktree`).
210
+ * **Scope Locks & Conflict Prevention** — declare `writeScopes` (e.g. `src/`, `docs/`) to prevent concurrent agent runs in the same workspace from editing overlapping paths; conflicting tasks queue safely until the lock is released.
211
+ * **Input Change Detection & Hash Gate** — specify `inputHashPaths` (and `skipIfUnchanged`) to compute a deterministic SHA-256 of watched files/directories; if inputs have not changed since the last successful run, execution is skipped (`skipped (inputs unchanged)`), saving 100% of LLM tokens and execution cost.
210
212
 
211
213
  ### 7. Cost Control: Fallback Model & Burn Guard
212
214
  * **Fallback Model** — A task can run on the cheap model by default and still finish on the strong one: set `fallbackModel` (and optionally `fallbackProvider`) and a failed run — `error` or `timeout` — is retried **once** on that model before the ordinary retry backoff applies. History records which model produced the result and whether the fallback was used, usage and cost of both attempts are summed, and the `{model}` template variable renders the model that finished the run. Only agent-mediated tasks (`llm`, `skill`, `workflow`) can use a fallback.
@@ -689,3 +691,11 @@ node scripts/ci-preflight.mjs
689
691
  ## 📄 License
690
692
 
691
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`).
package/README.ru.md CHANGED
@@ -206,6 +206,8 @@ cron({
206
206
  * **Docker** (`docker`) — выполнение команды в контейнере образа (`dockerImage`).
207
207
  * **Переменные окружения** — карта `env` на задачу (в UI — строки KEY VALUE) для внешних рантаймов; секретам здесь не место.
208
208
  * **Workspace и worktree** — привязка задачи к workspace харнесса (`workspaceId`, разрешаемому через службу `workspaceRegistry`) или пути; созданная для прогона сессия агента регистрируется в ведомости этого workspace (`attachSession`), поэтому появляется в группе проекта вместо «неразмещённых». Запуск в изолированном git worktree (`worktree`, `keepWorktree`).
209
+ * **Блокировка областей записи (Scope Locks)** — указание `writeScopes` (например `src/`, `docs/`) для защиты от конфликтов при одновременной работе агентов над одним проектом; пересекающиеся задачи безопасно ждут в очереди освобождения путей.
210
+ * **Контроль изменений входных данных (Input Hash)** — настройка `inputHashPaths` (`skipIfUnchanged`) вычисляет SHA-256 файлов/папок перед запуском; если входные файлы не менялись, запуск пропускается (`skipped (inputs unchanged)`), экономя 100% токенов и бюджета.
209
211
 
210
212
  ### 7. Экономия: fallback-модель и защита бюджета (Burn Guard)
211
213
  * **Fallback-модель** — задача может идти на дешёвой модели по умолчанию и всё же завершиться на сильной: задайте `fallbackModel` (и при необходимости `fallbackProvider`), и сбойный запуск (`error` или `timeout`) один раз повторится на этой модели, прежде чем включится обычный retry с задержкой. В истории видно, какая модель произвела результат и был ли использован fallback; расход и стоимость обеих попыток суммируются; переменная шаблона `{model}` подставляет модель, завершившую запуск. Fallback доступен только агентским типам (`llm`, `skill`, `workflow`).
@@ -643,3 +645,11 @@ MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
643
645
  - **Единый безопасный лимит maxConcurrent**: Схема Config и планировщик TaskScheduler теперь согласованно используют лимит по умолчанию `2` (0 остаётся явным выбором безлимитного режима).
644
646
  - **Изоляция пулов через concurrencyGroup**: Поле `concurrencyGroup` теперь строго контролируется при допуске задач и опустошении очереди (по умолчанию 1 параллельный запуск на именованную группу). Задачи из разных групп исполняются параллельно в пределах общего `maxConcurrent`, а задачи с политикой `queue` стартуют сразу при освобождении слота своей группы.
645
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`).
package/README.zh.md CHANGED
@@ -206,6 +206,8 @@ cron({
206
206
  * **Docker**(`docker`)—— 在镜像容器(`dockerImage`)中执行命令。
207
207
  * **环境变量** —— 按任务的 `env` 映射(界面中每行 KEY VALUE)应用于外部运行时;请勿在此存放密钥。
208
208
  * **工作区与 worktree** —— 将任务绑定到 Harness 工作区(`workspaceId`,通过宿主 `workspaceRegistry` 服务解析)或直接路径;运行创建的智能体会话会登记进该工作区的账本(`attachSession`),因此出现在项目分组下而非「未分组」。对会修改代码的智能体任务,可在隔离的 git worktree 中运行(`worktree`、`keepWorktree`)。
209
+ * **写入范围锁与冲突避免 (Scope Locks)** —— 声明 `writeScopes`(例如 `src/`、`docs/`)防止同一工作区内并发任务互相覆盖代码;重叠任务安全排队等待释放锁。
210
+ * **输入哈希监控与跳过 (Input Hash)** —— 配置 `inputHashPaths`(与 `skipIfUnchanged`)在运行前计算确定性 SHA-256;若输入未变则直接跳过 (`skipped (inputs unchanged)`),节省 100% 的 Token 与调用成本。
209
211
 
210
212
  ### 7. 成本控制:回退模型与支出保护(Burn Guard)
211
213
  * **回退模型** —— 任务可以默认使用便宜模型,失败时改用更强模型完成:设置 `fallbackModel`(可选 `fallbackProvider`),失败(`error` 或 `timeout`)的运行会在该模型上重试一次,之后才进入常规重试退避。历史记录会标明最终产出结果的模型以及是否使用了回退,两次尝试的用量与成本都会累计,模板变量 `{model}` 渲染完成运行的模型。回退仅适用于智能体类型(`llm`、`skill`、`workflow`)。
@@ -637,3 +639,11 @@ MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
637
639
  - **统一安全并发默认值**:配置规范(Config)与调度器(TaskScheduler)全面对齐默认并发上限 `maxConcurrent = 2`(0 仅作为显式无限制选项)。
638
640
  - **并发分组隔离调度**:任务的 `concurrencyGroup` 属性全面接入调度仲裁与队列排队(同名分组默认限流 1 个并发执行),不同分组可并发运行直至 `maxConcurrent`,队列任务随所属分组资源释放立即触发。
639
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}}`) 及环境变量中。
@@ -215,6 +215,20 @@
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.wakeTriggerTypeLabel': 'Event wake trigger',
219
+ 'form.wakeTriggerTypeNone': 'None (Schedule / Cron only)',
220
+ 'form.wakeTriggerTypeFileCount': 'File count threshold (batch run)',
221
+ 'form.wakeTriggerTypeMarkerFile': 'Marker file receipt (flag file)',
222
+ 'form.wakeTriggerTypeProcessExit': 'Process exit watcher (PID / pidFile)',
223
+ 'form.wakeTriggerPathLabel': 'Trigger target path (dir / marker / pidfile)',
224
+ 'form.wakeTriggerPathPlaceholder': 'e.g. incoming/ or build.ready or run.pid',
225
+ 'form.wakeTriggerMinCountLabel': 'Min file count',
226
+ 'form.wakeTriggerConsumeLabel': 'Consume / delete marker after trigger',
227
+ 'form.writeScopesLabel': 'Write scopes (Scope Locks, relative paths per line or comma)',
228
+ 'form.writeScopesPlaceholder': 'e.g. src/, docs/ (prevents concurrent writes on overlapping scopes)',
229
+ 'form.inputHashPathsLabel': 'Input hash paths (inputHashPaths)',
230
+ 'form.inputHashPathsPlaceholder': 'e.g. src/, package.json (skip run if unchanged)',
231
+ 'form.skipIfUnchangedLabel': 'Skip execution if inputs are unchanged (save tokens & budget)',
218
232
  'form.selfHealingLabel': 'Self-healing runbook command (shell)',
219
233
  'form.selfHealingPlaceholder': 'systemctl restart app || true',
220
234
  'form.autoDiagnoseLabel': 'Auto-diagnose failures with AI agent',
@@ -421,6 +435,18 @@
421
435
  'form.preflightTargetLabel': '预检目标参数', 'form.preflightTargetPlaceholder': 'https://example.com/healthz 或 ls /data 或 /:10%',
422
436
  'form.heartbeatIntervalLabel': '心跳打卡时限 (秒, 0 = 禁用)', 'form.gracePeriodLabel': '心跳宽限期 (秒)',
423
437
  'form.priorityLabel': '队列优先级 (1-10,数值越大越先执行)', 'form.concurrencyGroupLabel': '并发分组名称',
438
+ 'form.wakeTriggerTypeLabel': '事件唤醒触发器 (Wake Triggers)',
439
+ 'form.wakeTriggerTypeNone': '无 (仅定时/间隔)',
440
+ 'form.wakeTriggerTypeFileCount': '文件数量阈值 (批量触发)',
441
+ 'form.wakeTriggerTypeMarkerFile': '标记/Flag文件到达',
442
+ 'form.wakeTriggerTypeProcessExit': '进程退出监听 (PID / pidfile)',
443
+ 'form.wakeTriggerPathLabel': '触发目标路径 (目录 / markerPath / pidFile)',
444
+ 'form.wakeTriggerPathPlaceholder': '例如: incoming/ 或 build.ready 或 run.pid',
445
+ 'form.wakeTriggerMinCountLabel': '最小文件阈值 (minCount)',
446
+ 'form.wakeTriggerConsumeLabel': '触发后自动删除标记/PID文件',
447
+ 'form.writeScopesLabel': '文件写入范围锁 (writeScopes, 相对路径)', 'form.writeScopesPlaceholder': '例如: src/, docs/ (阻止与同工作区重叠任务并发执行)',
448
+ 'form.inputHashPathsLabel': '输入文件哈希变动监控 (inputHashPaths)', 'form.inputHashPathsPlaceholder': '例如: src/, package.json (无变动时跳过执行)',
449
+ 'form.skipIfUnchangedLabel': '输入文件无变动时跳过执行 (节省 Token 与预算)',
424
450
  'form.selfHealingLabel': '故障自愈脚本 (Shell)', 'form.selfHealingPlaceholder': 'systemctl restart app || true',
425
451
  'form.autoDiagnoseLabel': '任务失败时启用 AI 智能分析诊断', 'form.agentPresetLabel': '智能体预设 (Agent Preset)',
426
452
  'form.agentPresetPlaceholder': 'standard (留空使用全局默认预设)', 'form.agentPresetHint': '来自 dsh-agent-presets 的智能体预设(如 standard, minimal, cordis, ptc),挂载工作区工具与文件读写能力。',
@@ -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 [formWriteScopes, setFormWriteScopes] = React.useState('');
108
+ const [formInputHashPaths, setFormInputHashPaths] = React.useState('');
109
+ const [formSkipIfUnchanged, setFormSkipIfUnchanged] = React.useState(false);
103
110
  const [formSelfHealingCommand, setFormSelfHealingCommand] = React.useState('');
104
111
  const [formAutoDiagnose, setFormAutoDiagnose] = React.useState(false);
105
112
  const [schedulePreviewRuns, setSchedulePreviewRuns] = React.useState(null);
@@ -333,6 +333,14 @@
333
333
  setFormPreflightTarget(task.preflightTarget || '');
334
334
  setFormPriority(task.priority !== undefined ? task.priority : 5);
335
335
  setFormConcurrencyGroup(task.concurrencyGroup || 'default');
336
+ const _wt = task.wakeTrigger || {};
337
+ setFormWakeTriggerType(_wt.enabled && _wt.type ? _wt.type : 'none');
338
+ setFormWakeTriggerPath(_wt.markerPath || _wt.path || _wt.pidFile || '');
339
+ setFormWakeTriggerMinCount(_wt.minCount || 1);
340
+ setFormWakeTriggerConsume(_wt.consumeMarker !== false);
341
+ setFormWriteScopes(Array.isArray(task.writeScopes) ? task.writeScopes.join('\n') : (task.writeScopes || ''));
342
+ setFormInputHashPaths(Array.isArray(task.inputHashPaths) ? task.inputHashPaths.join('\n') : (task.inputHashPaths || ''));
343
+ setFormSkipIfUnchanged(Boolean(task.skipIfUnchanged));
336
344
  setFormSelfHealingCommand(task.selfHealingCommand || '');
337
345
  setFormAutoDiagnose(Boolean(task.autoDiagnose));
338
346
  setSchedulePreviewRuns(null);
@@ -418,6 +426,18 @@
418
426
  preflightTarget: formPreflightTarget.trim() || undefined,
419
427
  priority: Number(formPriority) || 5,
420
428
  concurrencyGroup: formConcurrencyGroup.trim() || 'default',
429
+ wakeTrigger: formWakeTriggerType && formWakeTriggerType !== 'none' ? {
430
+ enabled: true,
431
+ type: formWakeTriggerType,
432
+ path: formWakeTriggerType === 'file_count' ? formWakeTriggerPath.trim() : undefined,
433
+ minCount: formWakeTriggerType === 'file_count' ? (Number(formWakeTriggerMinCount) || 1) : undefined,
434
+ markerPath: formWakeTriggerType === 'marker_file' ? formWakeTriggerPath.trim() : undefined,
435
+ pidFile: formWakeTriggerType === 'process_exit' ? formWakeTriggerPath.trim() : undefined,
436
+ consumeMarker: Boolean(formWakeTriggerConsume),
437
+ } : null,
438
+ writeScopes: formWriteScopes ? formWriteScopes.split(/[\n,]+/).map((s) => s.trim()).filter(Boolean) : [],
439
+ inputHashPaths: formInputHashPaths ? formInputHashPaths.split(/[\n,]+/).map((s) => s.trim()).filter(Boolean) : [],
440
+ skipIfUnchanged: Boolean(formSkipIfUnchanged),
421
441
  selfHealingCommand: formSelfHealingCommand.trim() || undefined,
422
442
  autoDiagnose: Boolean(formAutoDiagnose),
423
443
  requireApproval: Boolean(formRequireApproval),
@@ -293,6 +293,75 @@
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.wakeTriggerTypeLabel')),
299
+ React.createElement('select', {
300
+ value: formWakeTriggerType,
301
+ onChange: (e) => setFormWakeTriggerType(e.target.value)
302
+ },
303
+ React.createElement('option', { value: 'none' }, T_KEY(t, 'form.wakeTriggerTypeNone')),
304
+ React.createElement('option', { value: 'file_count' }, T_KEY(t, 'form.wakeTriggerTypeFileCount')),
305
+ React.createElement('option', { value: 'marker_file' }, T_KEY(t, 'form.wakeTriggerTypeMarkerFile')),
306
+ React.createElement('option', { value: 'process_exit' }, T_KEY(t, 'form.wakeTriggerTypeProcessExit'))
307
+ )
308
+ ),
309
+ formWakeTriggerType !== 'none' && React.createElement('div', { className: 'dsh-cron-form-group' },
310
+ React.createElement('label', null, T_KEY(t, 'form.wakeTriggerPathLabel')),
311
+ React.createElement('input', {
312
+ type: 'text',
313
+ value: formWakeTriggerPath,
314
+ placeholder: T_KEY(t, 'form.wakeTriggerPathPlaceholder'),
315
+ onChange: (e) => setFormWakeTriggerPath(e.target.value)
316
+ })
317
+ ),
318
+ formWakeTriggerType === 'file_count' && React.createElement('div', { className: 'dsh-cron-form-group' },
319
+ React.createElement('label', null, T_KEY(t, 'form.wakeTriggerMinCountLabel')),
320
+ React.createElement('input', {
321
+ type: 'number',
322
+ min: 1,
323
+ value: formWakeTriggerMinCount,
324
+ onChange: (e) => setFormWakeTriggerMinCount(parseInt(e.target.value, 10) || 1)
325
+ })
326
+ ),
327
+ (formWakeTriggerType === 'marker_file' || formWakeTriggerType === 'process_exit') && React.createElement('div', { className: 'dsh-cron-form-group dsh-cron-form-checkbox' },
328
+ React.createElement('label', null,
329
+ React.createElement('input', {
330
+ type: 'checkbox',
331
+ checked: formWakeTriggerConsume,
332
+ onChange: (e) => setFormWakeTriggerConsume(e.target.checked)
333
+ }),
334
+ React.createElement('span', null, T_KEY(t, 'form.wakeTriggerConsumeLabel'))
335
+ )
336
+ ),
337
+ React.createElement('div', { className: 'dsh-cron-form-group' },
338
+ React.createElement('label', null, T_KEY(t, 'form.writeScopesLabel')),
339
+ React.createElement('input', {
340
+ type: 'text',
341
+ value: formWriteScopes,
342
+ placeholder: T_KEY(t, 'form.writeScopesPlaceholder'),
343
+ onChange: (e) => setFormWriteScopes(e.target.value)
344
+ })
345
+ ),
346
+ React.createElement('div', { className: 'dsh-cron-form-group' },
347
+ React.createElement('label', null, T_KEY(t, 'form.inputHashPathsLabel')),
348
+ React.createElement('input', {
349
+ type: 'text',
350
+ value: formInputHashPaths,
351
+ placeholder: T_KEY(t, 'form.inputHashPathsPlaceholder'),
352
+ onChange: (e) => setFormInputHashPaths(e.target.value)
353
+ })
354
+ ),
355
+ React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: '8px', marginTop: '6px' } },
356
+ React.createElement('input', {
357
+ type: 'checkbox',
358
+ id: 'formSkipIfUnchangedCheckbox',
359
+ checked: formSkipIfUnchanged,
360
+ onChange: (e) => setFormSkipIfUnchanged(e.target.checked)
361
+ }),
362
+ React.createElement('label', { htmlFor: 'formSkipIfUnchangedCheckbox', style: { margin: 0, cursor: 'pointer', fontSize: '13px' } },
363
+ T_KEY(t, 'form.skipIfUnchangedLabel')
364
+ )
296
365
  ),
297
366
  React.createElement('div', { className: 'dsh-cron-form-group' },
298
367
  React.createElement('label', null, T_KEY(t, 'form.selfHealingLabel')),
package/lib/client.js CHANGED
@@ -261,6 +261,20 @@ 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.wakeTriggerTypeLabel': 'Event wake trigger',
265
+ 'form.wakeTriggerTypeNone': 'None (Schedule / Cron only)',
266
+ 'form.wakeTriggerTypeFileCount': 'File count threshold (batch run)',
267
+ 'form.wakeTriggerTypeMarkerFile': 'Marker file receipt (flag file)',
268
+ 'form.wakeTriggerTypeProcessExit': 'Process exit watcher (PID / pidFile)',
269
+ 'form.wakeTriggerPathLabel': 'Trigger target path (dir / marker / pidfile)',
270
+ 'form.wakeTriggerPathPlaceholder': 'e.g. incoming/ or build.ready or run.pid',
271
+ 'form.wakeTriggerMinCountLabel': 'Min file count',
272
+ 'form.wakeTriggerConsumeLabel': 'Consume / delete marker after trigger',
273
+ 'form.writeScopesLabel': 'Write scopes (Scope Locks, relative paths per line or comma)',
274
+ 'form.writeScopesPlaceholder': 'e.g. src/, docs/ (prevents concurrent writes on overlapping scopes)',
275
+ 'form.inputHashPathsLabel': 'Input hash paths (inputHashPaths)',
276
+ 'form.inputHashPathsPlaceholder': 'e.g. src/, package.json (skip run if unchanged)',
277
+ 'form.skipIfUnchangedLabel': 'Skip execution if inputs are unchanged (save tokens & budget)',
264
278
  'form.selfHealingLabel': 'Self-healing runbook command (shell)',
265
279
  'form.selfHealingPlaceholder': 'systemctl restart app || true',
266
280
  'form.autoDiagnoseLabel': 'Auto-diagnose failures with AI agent',
@@ -466,6 +480,18 @@ zh: {
466
480
  'form.preflightTargetLabel': '预检目标参数', 'form.preflightTargetPlaceholder': 'https://example.com/healthz 或 ls /data 或 /:10%',
467
481
  'form.heartbeatIntervalLabel': '心跳打卡时限 (秒, 0 = 禁用)', 'form.gracePeriodLabel': '心跳宽限期 (秒)',
468
482
  'form.priorityLabel': '队列优先级 (1-10,数值越大越先执行)', 'form.concurrencyGroupLabel': '并发分组名称',
483
+ 'form.wakeTriggerTypeLabel': '事件唤醒触发器 (Wake Triggers)',
484
+ 'form.wakeTriggerTypeNone': '无 (仅定时/间隔)',
485
+ 'form.wakeTriggerTypeFileCount': '文件数量阈值 (批量触发)',
486
+ 'form.wakeTriggerTypeMarkerFile': '标记/Flag文件到达',
487
+ 'form.wakeTriggerTypeProcessExit': '进程退出监听 (PID / pidfile)',
488
+ 'form.wakeTriggerPathLabel': '触发目标路径 (目录 / markerPath / pidFile)',
489
+ 'form.wakeTriggerPathPlaceholder': '例如: incoming/ 或 build.ready 或 run.pid',
490
+ 'form.wakeTriggerMinCountLabel': '最小文件阈值 (minCount)',
491
+ 'form.wakeTriggerConsumeLabel': '触发后自动删除标记/PID文件',
492
+ 'form.writeScopesLabel': '文件写入范围锁 (writeScopes, 相对路径)', 'form.writeScopesPlaceholder': '例如: src/, docs/ (阻止与同工作区重叠任务并发执行)',
493
+ 'form.inputHashPathsLabel': '输入文件哈希变动监控 (inputHashPaths)', 'form.inputHashPathsPlaceholder': '例如: src/, package.json (无变动时跳过执行)',
494
+ 'form.skipIfUnchangedLabel': '输入文件无变动时跳过执行 (节省 Token 与预算)',
469
495
  'form.selfHealingLabel': '故障自愈脚本 (Shell)', 'form.selfHealingPlaceholder': 'systemctl restart app || true',
470
496
  'form.autoDiagnoseLabel': '任务失败时启用 AI 智能分析诊断', 'form.agentPresetLabel': '智能体预设 (Agent Preset)',
471
497
  'form.agentPresetPlaceholder': 'standard (留空使用全局默认预设)', 'form.agentPresetHint': '来自 dsh-agent-presets 的智能体预设(如 standard, minimal, cordis, ptc),挂载工作区工具与文件读写能力。',
@@ -1630,6 +1656,13 @@ const [formPreflightType, setFormPreflightType] = React.useState('none');
1630
1656
  const [formPreflightTarget, setFormPreflightTarget] = React.useState('');
1631
1657
  const [formPriority, setFormPriority] = React.useState(5);
1632
1658
  const [formConcurrencyGroup, setFormConcurrencyGroup] = React.useState('default');
1659
+ const [formWakeTriggerType, setFormWakeTriggerType] = React.useState('none');
1660
+ const [formWakeTriggerPath, setFormWakeTriggerPath] = React.useState('');
1661
+ const [formWakeTriggerMinCount, setFormWakeTriggerMinCount] = React.useState(1);
1662
+ const [formWakeTriggerConsume, setFormWakeTriggerConsume] = React.useState(true);
1663
+ const [formWriteScopes, setFormWriteScopes] = React.useState('');
1664
+ const [formInputHashPaths, setFormInputHashPaths] = React.useState('');
1665
+ const [formSkipIfUnchanged, setFormSkipIfUnchanged] = React.useState(false);
1633
1666
  const [formSelfHealingCommand, setFormSelfHealingCommand] = React.useState('');
1634
1667
  const [formAutoDiagnose, setFormAutoDiagnose] = React.useState(false);
1635
1668
  const [schedulePreviewRuns, setSchedulePreviewRuns] = React.useState(null);
@@ -2552,6 +2585,14 @@ setFormPreflightType(task.preflightType || 'none');
2552
2585
  setFormPreflightTarget(task.preflightTarget || '');
2553
2586
  setFormPriority(task.priority !== undefined ? task.priority : 5);
2554
2587
  setFormConcurrencyGroup(task.concurrencyGroup || 'default');
2588
+ const _wt = task.wakeTrigger || {};
2589
+ setFormWakeTriggerType(_wt.enabled && _wt.type ? _wt.type : 'none');
2590
+ setFormWakeTriggerPath(_wt.markerPath || _wt.path || _wt.pidFile || '');
2591
+ setFormWakeTriggerMinCount(_wt.minCount || 1);
2592
+ setFormWakeTriggerConsume(_wt.consumeMarker !== false);
2593
+ setFormWriteScopes(Array.isArray(task.writeScopes) ? task.writeScopes.join('\n') : (task.writeScopes || ''));
2594
+ setFormInputHashPaths(Array.isArray(task.inputHashPaths) ? task.inputHashPaths.join('\n') : (task.inputHashPaths || ''));
2595
+ setFormSkipIfUnchanged(Boolean(task.skipIfUnchanged));
2555
2596
  setFormSelfHealingCommand(task.selfHealingCommand || '');
2556
2597
  setFormAutoDiagnose(Boolean(task.autoDiagnose));
2557
2598
  setSchedulePreviewRuns(null);
@@ -2635,6 +2676,18 @@ preflightType: formPreflightType || 'none',
2635
2676
  preflightTarget: formPreflightTarget.trim() || undefined,
2636
2677
  priority: Number(formPriority) || 5,
2637
2678
  concurrencyGroup: formConcurrencyGroup.trim() || 'default',
2679
+ wakeTrigger: formWakeTriggerType && formWakeTriggerType !== 'none' ? {
2680
+ enabled: true,
2681
+ type: formWakeTriggerType,
2682
+ path: formWakeTriggerType === 'file_count' ? formWakeTriggerPath.trim() : undefined,
2683
+ minCount: formWakeTriggerType === 'file_count' ? (Number(formWakeTriggerMinCount) || 1) : undefined,
2684
+ markerPath: formWakeTriggerType === 'marker_file' ? formWakeTriggerPath.trim() : undefined,
2685
+ pidFile: formWakeTriggerType === 'process_exit' ? formWakeTriggerPath.trim() : undefined,
2686
+ consumeMarker: Boolean(formWakeTriggerConsume),
2687
+ } : null,
2688
+ writeScopes: formWriteScopes ? formWriteScopes.split(/[\n,]+/).map((s) => s.trim()).filter(Boolean) : [],
2689
+ inputHashPaths: formInputHashPaths ? formInputHashPaths.split(/[\n,]+/).map((s) => s.trim()).filter(Boolean) : [],
2690
+ skipIfUnchanged: Boolean(formSkipIfUnchanged),
2638
2691
  selfHealingCommand: formSelfHealingCommand.trim() || undefined,
2639
2692
  autoDiagnose: Boolean(formAutoDiagnose),
2640
2693
  requireApproval: Boolean(formRequireApproval),
@@ -4138,6 +4191,75 @@ onChange: (e) => setFormConcurrencyGroup(e.target.value)
4138
4191
  )
4139
4192
  ),
4140
4193
  _h('div', { className: 'dsh-cron-form-group' },
4194
+ _h('label', null, T_KEY(t, 'form.wakeTriggerTypeLabel')),
4195
+ _h('select', {
4196
+ value: formWakeTriggerType,
4197
+ onChange: (e) => setFormWakeTriggerType(e.target.value)
4198
+ },
4199
+ _h('option', { value: 'none' }, T_KEY(t, 'form.wakeTriggerTypeNone')),
4200
+ _h('option', { value: 'file_count' }, T_KEY(t, 'form.wakeTriggerTypeFileCount')),
4201
+ _h('option', { value: 'marker_file' }, T_KEY(t, 'form.wakeTriggerTypeMarkerFile')),
4202
+ _h('option', { value: 'process_exit' }, T_KEY(t, 'form.wakeTriggerTypeProcessExit'))
4203
+ )
4204
+ ),
4205
+ formWakeTriggerType !== 'none' && _h('div', { className: 'dsh-cron-form-group' },
4206
+ _h('label', null, T_KEY(t, 'form.wakeTriggerPathLabel')),
4207
+ _h('input', {
4208
+ type: 'text',
4209
+ value: formWakeTriggerPath,
4210
+ placeholder: T_KEY(t, 'form.wakeTriggerPathPlaceholder'),
4211
+ onChange: (e) => setFormWakeTriggerPath(e.target.value)
4212
+ })
4213
+ ),
4214
+ formWakeTriggerType === 'file_count' && _h('div', { className: 'dsh-cron-form-group' },
4215
+ _h('label', null, T_KEY(t, 'form.wakeTriggerMinCountLabel')),
4216
+ _h('input', {
4217
+ type: 'number',
4218
+ min: 1,
4219
+ value: formWakeTriggerMinCount,
4220
+ onChange: (e) => setFormWakeTriggerMinCount(parseInt(e.target.value, 10) || 1)
4221
+ })
4222
+ ),
4223
+ (formWakeTriggerType === 'marker_file' || formWakeTriggerType === 'process_exit') && _h('div', { className: 'dsh-cron-form-group dsh-cron-form-checkbox' },
4224
+ _h('label', null,
4225
+ _h('input', {
4226
+ type: 'checkbox',
4227
+ checked: formWakeTriggerConsume,
4228
+ onChange: (e) => setFormWakeTriggerConsume(e.target.checked)
4229
+ }),
4230
+ _h('span', null, T_KEY(t, 'form.wakeTriggerConsumeLabel'))
4231
+ )
4232
+ ),
4233
+ _h('div', { className: 'dsh-cron-form-group' },
4234
+ _h('label', null, T_KEY(t, 'form.writeScopesLabel')),
4235
+ _h('input', {
4236
+ type: 'text',
4237
+ value: formWriteScopes,
4238
+ placeholder: T_KEY(t, 'form.writeScopesPlaceholder'),
4239
+ onChange: (e) => setFormWriteScopes(e.target.value)
4240
+ })
4241
+ ),
4242
+ _h('div', { className: 'dsh-cron-form-group' },
4243
+ _h('label', null, T_KEY(t, 'form.inputHashPathsLabel')),
4244
+ _h('input', {
4245
+ type: 'text',
4246
+ value: formInputHashPaths,
4247
+ placeholder: T_KEY(t, 'form.inputHashPathsPlaceholder'),
4248
+ onChange: (e) => setFormInputHashPaths(e.target.value)
4249
+ })
4250
+ ),
4251
+ _h('div', { style: { display: 'flex', alignItems: 'center', gap: '8px', marginTop: '6px' } },
4252
+ _h('input', {
4253
+ type: 'checkbox',
4254
+ id: 'formSkipIfUnchangedCheckbox',
4255
+ checked: formSkipIfUnchanged,
4256
+ onChange: (e) => setFormSkipIfUnchanged(e.target.checked)
4257
+ }),
4258
+ _h('label', { htmlFor: 'formSkipIfUnchangedCheckbox', style: { margin: 0, cursor: 'pointer', fontSize: '13px' } },
4259
+ T_KEY(t, 'form.skipIfUnchangedLabel')
4260
+ )
4261
+ ),
4262
+ _h('div', { className: 'dsh-cron-form-group' },
4141
4263
  _h('label', null, T_KEY(t, 'form.selfHealingLabel')),
4142
4264
  _h('input', {
4143
4265
  type: 'text',
package/lib/cron-tool.js CHANGED
@@ -326,6 +326,23 @@ export const cronToolParameters = {
326
326
  type: 'string',
327
327
  description: 'Named concurrency group to serialize related tasks',
328
328
  },
329
+ wakeTrigger: {
330
+ type: 'object',
331
+ additionalProperties: true,
332
+ description: 'Event-driven wake trigger (file_count, marker_file, or process_exit)',
333
+ },
334
+ writeScopes: {
335
+ type: 'array',
336
+ description: 'Relative directory/file scopes to lock to prevent conflicting concurrent writes',
337
+ },
338
+ inputHashPaths: {
339
+ type: 'array',
340
+ description: 'Relative directory/file paths to check for changes before running',
341
+ },
342
+ skipIfUnchanged: {
343
+ type: 'boolean',
344
+ description: 'Skip running task if inputHashPaths content has not changed since last successful run',
345
+ },
329
346
  priority: {
330
347
  type: 'number',
331
348
  description: 'Task priority (1 = highest, 10 = lowest, default 5)',
@@ -0,0 +1,106 @@
1
+ // @ts-check
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import crypto from 'node:crypto';
5
+
6
+ /**
7
+ * Normalize an array or string of input paths to watch/hash.
8
+ *
9
+ * @param {string[]|string|null|undefined} paths
10
+ * @returns {string[]}
11
+ */
12
+ export function normalizeInputHashPaths(paths) {
13
+ if (!paths) return [];
14
+ const list = Array.isArray(paths)
15
+ ? paths
16
+ : String(paths).split(/[\n,]+/).map((p) => p.trim());
17
+ return list.filter((p) => typeof p === 'string' && p.length > 0);
18
+ }
19
+
20
+ /**
21
+ * Compute a SHA-256 hash or signature of a file or directory tree.
22
+ * Deterministic and skips noisy or non-tracked artifacts (.git, node_modules).
23
+ *
24
+ * @param {string} targetPath
25
+ * @returns {string}
26
+ */
27
+ export function hashPath(targetPath) {
28
+ if (!fs.existsSync(targetPath)) {
29
+ return 'nonexistent';
30
+ }
31
+
32
+ let stat;
33
+ try {
34
+ stat = fs.statSync(targetPath);
35
+ } catch (_err) {
36
+ return 'error';
37
+ }
38
+
39
+ if (stat.isFile()) {
40
+ try {
41
+ const content = fs.readFileSync(targetPath);
42
+ return crypto.createHash('sha256').update(content).digest('hex').slice(0, 32);
43
+ } catch (_err) {
44
+ return `stat:${stat.size}:${stat.mtimeMs}`;
45
+ }
46
+ }
47
+
48
+ if (stat.isDirectory()) {
49
+ const hash = crypto.createHash('sha256');
50
+ function walk(dir, depth = 0) {
51
+ if (depth > 8) return; // Prevent infinite recursion on deep/circular trees
52
+ let entries = [];
53
+ try {
54
+ entries = fs.readdirSync(dir, { withFileTypes: true });
55
+ } catch (_err) {
56
+ return;
57
+ }
58
+ entries.sort((a, b) => a.name.localeCompare(b.name));
59
+ for (const ent of entries) {
60
+ if (ent.name === '.git' || ent.name === 'node_modules') continue;
61
+ const fullPath = path.join(dir, ent.name);
62
+ if (ent.isFile()) {
63
+ try {
64
+ const st = fs.statSync(fullPath);
65
+ hash.update(`${ent.name}:${st.size}:${st.mtimeMs}:`);
66
+ if (st.size < 2 * 1024 * 1024) {
67
+ const fileBuf = fs.readFileSync(fullPath);
68
+ hash.update(fileBuf);
69
+ }
70
+ } catch (_err) { void _err; }
71
+ } else if (ent.isDirectory()) {
72
+ hash.update(`dir:${ent.name}:`);
73
+ walk(fullPath, depth + 1);
74
+ }
75
+ }
76
+ }
77
+ walk(targetPath);
78
+ return hash.digest('hex').slice(0, 32);
79
+ }
80
+
81
+ return 'other';
82
+ }
83
+
84
+ /**
85
+ * Compute the combined input hash for a task based on its configured inputHashPaths.
86
+ * Returns null if no inputHashPaths are configured or valid.
87
+ *
88
+ * @param {string|null|undefined} cwd
89
+ * @param {string[]|string|null|undefined} inputHashPaths
90
+ * @returns {Promise<string|null>}
91
+ */
92
+ export async function computeTaskInputHash(cwd, inputHashPaths) {
93
+ const normPaths = normalizeInputHashPaths(inputHashPaths);
94
+ if (normPaths.length === 0) return null;
95
+
96
+ const combined = crypto.createHash('sha256');
97
+ const baseDir = cwd || process.cwd();
98
+
99
+ for (const relOrAbs of normPaths) {
100
+ const resolved = path.isAbsolute(relOrAbs) ? relOrAbs : path.resolve(baseDir, relOrAbs);
101
+ const h = hashPath(resolved);
102
+ combined.update(`${relOrAbs}=${h};`);
103
+ }
104
+
105
+ return 'sha256:' + combined.digest('hex').slice(0, 16);
106
+ }
package/lib/locales.json CHANGED
@@ -405,6 +405,20 @@
405
405
  "settings.feishuSecretLabel": "签名密钥(可选)",
406
406
  "settings.feishuSecretPlaceholder": "SEC…",
407
407
  "settings.feishuGlobalNotify": "所有任务的运行结果都推送到飞书",
408
- "settings.feishuHint": "飞书群通知:在目标群里添加「自定义机器人」,把它的 Webhook 地址粘贴到下面;如果机器人开启了「签名校验」,再把签名密钥一并填入。"
408
+ "settings.feishuHint": "飞书群通知:在目标群里添加「自定义机器人」,把它的 Webhook 地址粘贴到下面;如果机器人开启了「签名校验」,再把签名密钥一并填入。",
409
+ "form.writeScopesLabel": "文件写入范围锁 (writeScopes, 每行或逗号分隔一个路径)",
410
+ "form.writeScopesPlaceholder": "例如: src/, docs/ (阻止与同工作区重叠任务并发执行)",
411
+ "form.inputHashPathsLabel": "输入文件哈希变动监控 (inputHashPaths)",
412
+ "form.inputHashPathsPlaceholder": "例如: src/, package.json (无变动时跳过执行)",
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文件"
409
423
  }
410
- }
424
+ }
@@ -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
  }