@goodandready/dsh-cron 0.3.35 → 0.3.36
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 +12 -0
- package/README.ru.md +12 -0
- package/README.zh.md +12 -0
- package/lib/cron-as-code.js +224 -0
- package/lib/scheduler/scheduler.js +12 -0
- package/lib/store/task-schema.js +2 -0
- package/lib/store/task-transfer.js +2 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -711,3 +711,15 @@ Context is automatically injected into prompts (`{{trigger.type}}`, `{{trigger.f
|
|
|
711
711
|
- **Dedicated Digest Tasks (`type: "digest"`)**: Schedule consolidated summary reports (e.g., daily at 09:00 AM) that aggregate runs, errors, token usage, and cost across all tasks.
|
|
712
712
|
- **REST API**: Inspect digests on-demand via `GET /dsh-cron/digest` or trigger delivery via `POST /dsh-cron/digest/send`.
|
|
713
713
|
- **Channel Routing**: Automatically delivers formatted summaries to Telegram, Feishu, or webhook channels.
|
|
714
|
+
|
|
715
|
+
### Cron-as-Code (`.dsh/cron.yaml`)
|
|
716
|
+
Declare recurring tasks directly in your repository. `dsh-cron` automatically detects and synchronizes `.dsh/cron.yaml`, `.dsh/cron.yml`, or `.dsh/cron.json`:
|
|
717
|
+
```yaml
|
|
718
|
+
tasks:
|
|
719
|
+
- id: nightly-audit
|
|
720
|
+
title: Nightly Security Audit
|
|
721
|
+
schedule: "0 2 * * *"
|
|
722
|
+
command: npm audit
|
|
723
|
+
timeBoxMinutes: 15
|
|
724
|
+
```
|
|
725
|
+
Git-managed tasks are isolated with zero interference to manual GUI tasks.
|
package/README.ru.md
CHANGED
|
@@ -665,3 +665,15 @@ MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
|
|
|
665
665
|
- **Тип задачи `type: "digest"`**: Настройка периодических отчетов (например, каждое утро в 09:00), агрегирующих количество запусков, сбои, токены и затраты в USD.
|
|
666
666
|
- **REST API**: Эндпоинты `GET /dsh-cron/digest` для просмотра статистики и `POST /dsh-cron/digest/send` для отправки в каналы.
|
|
667
667
|
- **Интеграция с каналами**: Доставка форматированного отчета в Telegram, Feishu или вебхуки.
|
|
668
|
+
|
|
669
|
+
### Cron-as-Code (`.dsh/cron.yaml`)
|
|
670
|
+
Декларируйте расписания задач прямо в репозитории проекта. `dsh-cron` автоматически обнаруживает и синхронизирует конфигурацию из `.dsh/cron.yaml`, `.dsh/cron.yml` или `.dsh/cron.json`:
|
|
671
|
+
```yaml
|
|
672
|
+
tasks:
|
|
673
|
+
- id: nightly-audit
|
|
674
|
+
title: Ночной аудит безопасности
|
|
675
|
+
schedule: "0 2 * * *"
|
|
676
|
+
command: npm audit
|
|
677
|
+
timeBoxMinutes: 15
|
|
678
|
+
```
|
|
679
|
+
Задачи из репозитория изолированы и не перезаписывают ручные задачи, созданные в UI.
|
package/README.zh.md
CHANGED
|
@@ -658,3 +658,15 @@ MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
|
|
|
658
658
|
|
|
659
659
|
- **简报专用任务类型 (`type: "digest"`)**: 可定时调度汇总报告(如每日早晨 09:00),聚合所有任务的运行状态、失败诊断、Token 消耗与估算成本。
|
|
660
660
|
- **REST API**: 支持 `GET /dsh-cron/digest` 查询统计报告,以及 `POST /dsh-cron/digest/send` 主动推送到各通知渠道。
|
|
661
|
+
|
|
662
|
+
### 代码化 Cron(`.dsh/cron.yaml`)
|
|
663
|
+
直接在项目仓库中声明定时任务。`dsh-cron` 自动发现并同步 `.dsh/cron.yaml`、`.dsh/cron.yml` 或 `.dsh/cron.json`:
|
|
664
|
+
```yaml
|
|
665
|
+
tasks:
|
|
666
|
+
- id: nightly-audit
|
|
667
|
+
title: 每夜安全检查
|
|
668
|
+
schedule: "0 2 * * *"
|
|
669
|
+
command: npm audit
|
|
670
|
+
timeBoxMinutes: 15
|
|
671
|
+
```
|
|
672
|
+
Git 管理的任务具有隔离标识,绝不影响或覆盖 UI 手动创建的任务。
|
|
@@ -0,0 +1,224 @@
|
|
|
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
|
+
/**
|
|
7
|
+
* Lightweight, robust parser for .dsh/cron.yaml, .dsh/cron.yml, and .dsh/cron.json files (#416).
|
|
8
|
+
* Handles JSON and standard task list YAML without external dependencies.
|
|
9
|
+
*/
|
|
10
|
+
export function parseCronAsCode(rawContent) {
|
|
11
|
+
if (!rawContent || typeof rawContent !== 'string') return { tasks: [] };
|
|
12
|
+
const trimmed = rawContent.trim();
|
|
13
|
+
if (!trimmed) return { tasks: [] };
|
|
14
|
+
|
|
15
|
+
// 1. Try standard JSON first
|
|
16
|
+
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
|
|
17
|
+
try {
|
|
18
|
+
const parsed = JSON.parse(trimmed);
|
|
19
|
+
if (Array.isArray(parsed)) return { tasks: parsed };
|
|
20
|
+
if (parsed && Array.isArray(parsed.tasks)) return parsed;
|
|
21
|
+
return { tasks: [] };
|
|
22
|
+
} catch (_err) {
|
|
23
|
+
void _err;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// 2. Simple, resilient YAML parser for task documents
|
|
28
|
+
const lines = trimmed.split(/\r?\n/);
|
|
29
|
+
const tasks = [];
|
|
30
|
+
let currentTask = null;
|
|
31
|
+
let inTasksSection = false;
|
|
32
|
+
|
|
33
|
+
for (const rawLine of lines) {
|
|
34
|
+
const line = rawLine.replace(/#.*$/, '').trimEnd();
|
|
35
|
+
if (!line.trim()) continue;
|
|
36
|
+
|
|
37
|
+
if (line.match(/^tasks\s*:/i)) {
|
|
38
|
+
inTasksSection = true;
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const itemMatch = line.match(/^(\s*)-\s+(.*)$/);
|
|
43
|
+
if (itemMatch) {
|
|
44
|
+
if (currentTask) tasks.push(currentTask);
|
|
45
|
+
currentTask = {};
|
|
46
|
+
const rest = itemMatch[2].trim();
|
|
47
|
+
if (rest) {
|
|
48
|
+
const kv = parseYamlKeyValue(rest);
|
|
49
|
+
if (kv) currentTask[kv.key] = kv.value;
|
|
50
|
+
}
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
if (currentTask) {
|
|
55
|
+
const kv = parseYamlKeyValue(line.trim());
|
|
56
|
+
if (kv) {
|
|
57
|
+
currentTask[kv.key] = kv.value;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
if (currentTask) tasks.push(currentTask);
|
|
63
|
+
return { tasks };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function parseYamlKeyValue(line) {
|
|
67
|
+
const match = line.match(/^([a-zA-Z0-9_-]+)\s*:\s*(.*)$/);
|
|
68
|
+
if (!match) return null;
|
|
69
|
+
const key = match[1].trim();
|
|
70
|
+
let valStr = match[2].trim();
|
|
71
|
+
|
|
72
|
+
// Strip wrapping quotes
|
|
73
|
+
if ((valStr.startsWith('"') && valStr.endsWith('"')) || (valStr.startsWith("'") && valStr.endsWith("'"))) {
|
|
74
|
+
valStr = valStr.slice(1, -1);
|
|
75
|
+
return { key, value: valStr };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
if (valStr.toLowerCase() === 'true') return { key, value: true };
|
|
79
|
+
if (valStr.toLowerCase() === 'false') return { key, value: false };
|
|
80
|
+
if (/^-?\d+$/.test(valStr)) return { key, value: parseInt(valStr, 10) };
|
|
81
|
+
if (/^-?\d+\.\d+$/.test(valStr)) return { key, value: parseFloat(valStr) };
|
|
82
|
+
|
|
83
|
+
return { key, value: valStr };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Reconciles tasks declared in a workspace with the store (#416).
|
|
88
|
+
*/
|
|
89
|
+
export function reconcileWorkspaceCronTasks(store, workspaceId, declaredTasks = []) {
|
|
90
|
+
if (!store || !workspaceId) return { created: 0, updated: 0, deleted: 0 };
|
|
91
|
+
|
|
92
|
+
const currentTasks = store.list ? store.list() : (store.tasks ? Object.values(store.tasks) : []);
|
|
93
|
+
const existingManaged = new Map();
|
|
94
|
+
|
|
95
|
+
for (const t of currentTasks) {
|
|
96
|
+
if (t && t.workspaceId === workspaceId && t.managedBy === 'cron_as_code') {
|
|
97
|
+
existingManaged.set(t.id, t);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
let created = 0;
|
|
102
|
+
let updated = 0;
|
|
103
|
+
let deleted = 0;
|
|
104
|
+
const seenIds = new Set();
|
|
105
|
+
|
|
106
|
+
for (const decl of declaredTasks) {
|
|
107
|
+
if (!decl || typeof decl !== 'object') continue;
|
|
108
|
+
const rawId = decl.id || decl.name || Math.random().toString(36).slice(2, 9);
|
|
109
|
+
const taskId = `cac_${workspaceId}_${rawId}`.replace(/[^a-zA-Z0-9_-]/g, '_');
|
|
110
|
+
seenIds.add(taskId);
|
|
111
|
+
|
|
112
|
+
const taskRecord = {
|
|
113
|
+
...decl,
|
|
114
|
+
id: taskId,
|
|
115
|
+
title: decl.title || decl.name || rawId,
|
|
116
|
+
schedule: decl.schedule || '0 0 * * *',
|
|
117
|
+
status: decl.status || 'active',
|
|
118
|
+
workspaceId,
|
|
119
|
+
managedBy: 'cron_as_code',
|
|
120
|
+
origin: '.dsh/cron.yaml',
|
|
121
|
+
type: decl.type || 'script',
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
if (existingManaged.has(taskId)) {
|
|
125
|
+
const existing = existingManaged.get(taskId);
|
|
126
|
+
store.set({ ...existing, ...taskRecord });
|
|
127
|
+
updated++;
|
|
128
|
+
} else {
|
|
129
|
+
store.set(taskRecord);
|
|
130
|
+
created++;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Delete tasks removed from declaration
|
|
135
|
+
for (const [id, oldTask] of existingManaged.entries()) {
|
|
136
|
+
if (!seenIds.has(id)) {
|
|
137
|
+
if (typeof store.delete === 'function') {
|
|
138
|
+
store.delete(id);
|
|
139
|
+
} else {
|
|
140
|
+
oldTask.status = 'completed';
|
|
141
|
+
store.set(oldTask);
|
|
142
|
+
}
|
|
143
|
+
deleted++;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
return { created, updated, deleted };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* CronAsCodeManager observes workspace directories and auto-synchronizes .dsh/cron.yaml files (#416).
|
|
152
|
+
*/
|
|
153
|
+
export class CronAsCodeManager {
|
|
154
|
+
constructor(scheduler) {
|
|
155
|
+
this.scheduler = scheduler;
|
|
156
|
+
this.watchers = new Map(); // workspaceId -> { watcher, filePath }
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
findConfigFile(workspaceDir) {
|
|
160
|
+
if (!workspaceDir || typeof workspaceDir !== 'string') return null;
|
|
161
|
+
const candidates = [
|
|
162
|
+
path.join(workspaceDir, '.dsh', 'cron.yaml'),
|
|
163
|
+
path.join(workspaceDir, '.dsh', 'cron.yml'),
|
|
164
|
+
path.join(workspaceDir, '.dsh', 'cron.json'),
|
|
165
|
+
];
|
|
166
|
+
for (const c of candidates) {
|
|
167
|
+
if (fs.existsSync(c)) return c;
|
|
168
|
+
}
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
syncWorkspace(workspaceId, workspaceDir) {
|
|
173
|
+
if (!workspaceId || !workspaceDir || !this.scheduler) return null;
|
|
174
|
+
const filePath = this.findConfigFile(workspaceDir);
|
|
175
|
+
|
|
176
|
+
if (!filePath) {
|
|
177
|
+
this.unwatchWorkspace(workspaceId);
|
|
178
|
+
return null;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
try {
|
|
182
|
+
const content = fs.readFileSync(filePath, 'utf8');
|
|
183
|
+
const { tasks } = parseCronAsCode(content);
|
|
184
|
+
const res = reconcileWorkspaceCronTasks(this.scheduler.store, workspaceId, tasks);
|
|
185
|
+
logger.info(`[dsh-cron] Cron-as-Code synchronized "${filePath}" for workspace ${workspaceId}: +${res.created} ~${res.updated} -${res.deleted}`);
|
|
186
|
+
|
|
187
|
+
// Arm watcher if not already watching this file
|
|
188
|
+
const current = this.watchers.get(workspaceId);
|
|
189
|
+
if (!current || current.filePath !== filePath) {
|
|
190
|
+
this.unwatchWorkspace(workspaceId);
|
|
191
|
+
try {
|
|
192
|
+
const watcher = fs.watch(filePath, (event) => {
|
|
193
|
+
if (event === 'change') {
|
|
194
|
+
this.syncWorkspace(workspaceId, workspaceDir);
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
this.watchers.set(workspaceId, { watcher, filePath });
|
|
198
|
+
} catch (_err) {
|
|
199
|
+
void _err;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
return res;
|
|
204
|
+
} catch (err) {
|
|
205
|
+
logger.error(`[dsh-cron] Failed to read Cron-as-Code file "${filePath}": ${err.message}`);
|
|
206
|
+
return null;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
unwatchWorkspace(workspaceId) {
|
|
211
|
+
const entry = this.watchers.get(workspaceId);
|
|
212
|
+
if (entry && entry.watcher) {
|
|
213
|
+
bestEffort('cron-as-code-unwatch', () => entry.watcher.close());
|
|
214
|
+
this.watchers.delete(workspaceId);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
stopAll() {
|
|
219
|
+
for (const entry of this.watchers.values()) {
|
|
220
|
+
bestEffort('cron-as-code-stop', () => entry.watcher.close());
|
|
221
|
+
}
|
|
222
|
+
this.watchers.clear();
|
|
223
|
+
}
|
|
224
|
+
}
|
|
@@ -5,6 +5,7 @@ import { FileSystemWatcherManager } from '../watcher.js';
|
|
|
5
5
|
import { parseNaturalSchedule } from '../nl-schedule.js';
|
|
6
6
|
import { ScopeLockManager } from '../scope-locks.js';
|
|
7
7
|
import { WakeTriggerManager } from '../wake-triggers.js';
|
|
8
|
+
import { CronAsCodeManager } from '../cron-as-code.js';
|
|
8
9
|
|
|
9
10
|
const MAX_TIMEOUT_MS = 2147483647; // 2^31 - 1 ms (~24.85 days)
|
|
10
11
|
import {
|
|
@@ -342,6 +343,7 @@ export class TaskScheduler {
|
|
|
342
343
|
this.watcherManager = new FileSystemWatcherManager(this);
|
|
343
344
|
this.scopeLocks = new ScopeLockManager();
|
|
344
345
|
this.wakeTriggerManager = new WakeTriggerManager(this);
|
|
346
|
+
this.cronAsCodeManager = new CronAsCodeManager(this);
|
|
345
347
|
this.logger = opts.logger || null;
|
|
346
348
|
this.isStopped = false;
|
|
347
349
|
this.generation = 0;
|
|
@@ -380,6 +382,13 @@ export class TaskScheduler {
|
|
|
380
382
|
this.deferredTimers.set(taskId, timer);
|
|
381
383
|
}
|
|
382
384
|
|
|
385
|
+
syncWorkspaceCronAsCode(workspaceId, workspaceDir) {
|
|
386
|
+
if (this.cronAsCodeManager) {
|
|
387
|
+
return this.cronAsCodeManager.syncWorkspace(workspaceId, workspaceDir);
|
|
388
|
+
}
|
|
389
|
+
return null;
|
|
390
|
+
}
|
|
391
|
+
|
|
383
392
|
clearDeferredTimer(taskId) {
|
|
384
393
|
const t = this.deferredTimers.get(taskId);
|
|
385
394
|
if (t) {
|
|
@@ -511,6 +520,9 @@ export class TaskScheduler {
|
|
|
511
520
|
if (this.wakeTriggerManager) {
|
|
512
521
|
this.wakeTriggerManager.stopAll();
|
|
513
522
|
}
|
|
523
|
+
if (this.cronAsCodeManager) {
|
|
524
|
+
this.cronAsCodeManager.stopAll();
|
|
525
|
+
}
|
|
514
526
|
|
|
515
527
|
// Clear concurrency queue (#217)
|
|
516
528
|
this.queue = [];
|
package/lib/store/task-schema.js
CHANGED
|
@@ -102,6 +102,8 @@ export const TaskSchema = z.object({
|
|
|
102
102
|
wakeTrigger: z.any(),
|
|
103
103
|
workWindow: z.any(),
|
|
104
104
|
timeBoxMinutes: z.number().min(0).default(0),
|
|
105
|
+
managedBy: z.string().default(''),
|
|
106
|
+
origin: z.string().default(''),
|
|
105
107
|
maxMemoryMb: z.number().min(0).default(0),
|
|
106
108
|
executionTimeoutMs: z.number().min(0).default(900000),
|
|
107
109
|
maxLogBytesPerRun: z.number().min(0).default(5 * 1024 * 1024),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@goodandready/dsh-cron",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.36",
|
|
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",
|