@crewx/cron 0.1.10-rc.19 → 0.1.10-rc.190
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/dist/cli.d.ts +3 -1
- package/dist/cli.js +6 -409
- package/dist/src/builtins.d.ts +14 -0
- package/dist/src/builtins.js +1 -0
- package/dist/src/engine.d.ts +39 -12
- package/dist/src/engine.js +5 -819
- package/dist/src/runtime.d.ts +128 -0
- package/dist/src/runtime.js +1 -0
- package/dist/src/types.d.ts +95 -1
- package/dist/src/types.js +1 -3
- package/package.json +3 -3
- package/dist/cli.d.ts.map +0 -1
- package/dist/cli.js.map +0 -1
- package/dist/src/engine.d.ts.map +0 -1
- package/dist/src/engine.js.map +0 -1
- package/dist/src/types.d.ts.map +0 -1
- package/dist/src/types.js.map +0 -1
- package/dist/tsconfig.tsbuildinfo +0 -1
package/dist/src/engine.js
CHANGED
|
@@ -1,819 +1,5 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
-
}
|
|
8
|
-
Object.defineProperty(o, k2, desc);
|
|
9
|
-
}) : (function(o, m, k, k2) {
|
|
10
|
-
if (k2 === undefined) k2 = k;
|
|
11
|
-
o[k2] = m[k];
|
|
12
|
-
}));
|
|
13
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
-
}) : function(o, v) {
|
|
16
|
-
o["default"] = v;
|
|
17
|
-
});
|
|
18
|
-
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
-
var ownKeys = function(o) {
|
|
20
|
-
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
-
var ar = [];
|
|
22
|
-
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
-
return ar;
|
|
24
|
-
};
|
|
25
|
-
return ownKeys(o);
|
|
26
|
-
};
|
|
27
|
-
return function (mod) {
|
|
28
|
-
if (mod && mod.__esModule) return mod;
|
|
29
|
-
var result = {};
|
|
30
|
-
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
-
__setModuleDefault(result, mod);
|
|
32
|
-
return result;
|
|
33
|
-
};
|
|
34
|
-
})();
|
|
35
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.DATA_PATHS = void 0;
|
|
37
|
-
exports.getLocalTimestamp = getLocalTimestamp;
|
|
38
|
-
exports.logUsage = logUsage;
|
|
39
|
-
exports.getProjectRoot = getProjectRoot;
|
|
40
|
-
exports.normalizeMode = normalizeMode;
|
|
41
|
-
exports.loadSchedules = loadSchedules;
|
|
42
|
-
exports.saveSchedules = saveSchedules;
|
|
43
|
-
exports.acquireLock = acquireLock;
|
|
44
|
-
exports.releaseLock = releaseLock;
|
|
45
|
-
exports.shouldRunNow = shouldRunNow;
|
|
46
|
-
exports.describeCron = describeCron;
|
|
47
|
-
exports.calculateNextRun = calculateNextRun;
|
|
48
|
-
exports.isDaemonRunning = isDaemonRunning;
|
|
49
|
-
exports.startDaemon = startDaemon;
|
|
50
|
-
exports.stopDaemon = stopDaemon;
|
|
51
|
-
exports.ensureDaemonRunning = ensureDaemonRunning;
|
|
52
|
-
exports.getDaemonStatus = getDaemonStatus;
|
|
53
|
-
exports.executeSchedule = executeSchedule;
|
|
54
|
-
exports.daemonTick = daemonTick;
|
|
55
|
-
exports.runDaemonForeground = runDaemonForeground;
|
|
56
|
-
exports.addSchedule = addSchedule;
|
|
57
|
-
exports.removeSchedule = removeSchedule;
|
|
58
|
-
exports.enableSchedule = enableSchedule;
|
|
59
|
-
exports.disableSchedule = disableSchedule;
|
|
60
|
-
exports.updateSchedule = updateSchedule;
|
|
61
|
-
const child_process_1 = require("child_process");
|
|
62
|
-
const path = __importStar(require("path"));
|
|
63
|
-
const fs = __importStar(require("fs"));
|
|
64
|
-
const sdk_1 = require("@crewx/sdk");
|
|
65
|
-
const DATA_DIR = path.join(process.cwd(), '.crewx');
|
|
66
|
-
const SCHEDULES_FILE = path.join(DATA_DIR, '.cron-data.json');
|
|
67
|
-
const LOG_FILE = path.join(DATA_DIR, '.cron-daemon.log');
|
|
68
|
-
const LOCK_FILE = path.join(DATA_DIR, '.cron-data.json.lock');
|
|
69
|
-
const USAGE_LOG_FILE = path.join(DATA_DIR, 'cron-usage.log');
|
|
70
|
-
const PID_FILE = path.join(DATA_DIR, '.cron-daemon.pid');
|
|
71
|
-
function resolveDataDir(dir) {
|
|
72
|
-
return dir ? path.join(dir, '.crewx') : DATA_DIR;
|
|
73
|
-
}
|
|
74
|
-
function resolveSchedulesFile(dir) {
|
|
75
|
-
return path.join(resolveDataDir(dir), '.cron-data.json');
|
|
76
|
-
}
|
|
77
|
-
function resolvePidFile(dir) {
|
|
78
|
-
return path.join(resolveDataDir(dir), '.cron-daemon.pid');
|
|
79
|
-
}
|
|
80
|
-
const DAEMON_INTERVAL_MS = 60 * 1000;
|
|
81
|
-
const runningSchedules = new Set();
|
|
82
|
-
function getLocalTimestamp() {
|
|
83
|
-
const now = new Date();
|
|
84
|
-
const y = now.getFullYear();
|
|
85
|
-
const m = String(now.getMonth() + 1).padStart(2, '0');
|
|
86
|
-
const d = String(now.getDate()).padStart(2, '0');
|
|
87
|
-
const h = String(now.getHours()).padStart(2, '0');
|
|
88
|
-
const min = String(now.getMinutes()).padStart(2, '0');
|
|
89
|
-
const s = String(now.getSeconds()).padStart(2, '0');
|
|
90
|
-
return `${y}-${m}-${d} ${h}:${min}:${s}`;
|
|
91
|
-
}
|
|
92
|
-
function logUsage(...args) {
|
|
93
|
-
ensureDataDir();
|
|
94
|
-
const timestamp = getLocalTimestamp();
|
|
95
|
-
const message = args.join(' ');
|
|
96
|
-
const logLine = `${timestamp} | [cron] ${message}\n`;
|
|
97
|
-
fs.appendFileSync(USAGE_LOG_FILE, logLine);
|
|
98
|
-
}
|
|
99
|
-
function ensureDataDir(dir) {
|
|
100
|
-
const dataDir = resolveDataDir(dir);
|
|
101
|
-
if (!fs.existsSync(dataDir)) {
|
|
102
|
-
fs.mkdirSync(dataDir, { recursive: true });
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
function safeReadJsonFile(filePath) {
|
|
106
|
-
try {
|
|
107
|
-
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
108
|
-
}
|
|
109
|
-
catch {
|
|
110
|
-
return null;
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
function getProjectRoot() {
|
|
114
|
-
try {
|
|
115
|
-
return (0, child_process_1.execSync)('git rev-parse --show-toplevel', { encoding: 'utf8' }).trim();
|
|
116
|
-
}
|
|
117
|
-
catch {
|
|
118
|
-
return process.cwd();
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
function getBuiltinMemoryCliPath() {
|
|
122
|
-
return path.join(getProjectRoot(), 'packages', 'built-in', 'memory', 'dist', 'cli.js');
|
|
123
|
-
}
|
|
124
|
-
function maybeRewriteLegacyMemoryCommand(command) {
|
|
125
|
-
if (!command.includes('/skills/memory-v2/memory-v2.js')) {
|
|
126
|
-
return command;
|
|
127
|
-
}
|
|
128
|
-
const builtinMemoryCli = getBuiltinMemoryCliPath();
|
|
129
|
-
return `node ${builtinMemoryCli} summarize-dirty`;
|
|
130
|
-
}
|
|
131
|
-
function migrateLegacyMemoryDebounceSchedule() {
|
|
132
|
-
ensureDataDir();
|
|
133
|
-
const legacyFile = path.join(getProjectRoot(), 'skills', 'cron', '.cron-data.json');
|
|
134
|
-
if (!fs.existsSync(legacyFile)) {
|
|
135
|
-
return;
|
|
136
|
-
}
|
|
137
|
-
const legacySchedules = safeReadJsonFile(legacyFile);
|
|
138
|
-
if (!Array.isArray(legacySchedules)) {
|
|
139
|
-
return;
|
|
140
|
-
}
|
|
141
|
-
const legacySchedule = legacySchedules.find(s => s.name === 'memory-debounce');
|
|
142
|
-
if (!legacySchedule) {
|
|
143
|
-
return;
|
|
144
|
-
}
|
|
145
|
-
const targetSchedules = fs.existsSync(SCHEDULES_FILE) ? safeReadJsonFile(SCHEDULES_FILE) ?? [] : [];
|
|
146
|
-
if (targetSchedules.some(s => s.name === 'memory-debounce')) {
|
|
147
|
-
return;
|
|
148
|
-
}
|
|
149
|
-
const migratedSchedule = {
|
|
150
|
-
...legacySchedule,
|
|
151
|
-
command: maybeRewriteLegacyMemoryCommand(legacySchedule.command),
|
|
152
|
-
updated_at: new Date().toISOString(),
|
|
153
|
-
next_run: calculateNextRun(legacySchedule.cron, legacySchedule.timezone),
|
|
154
|
-
};
|
|
155
|
-
saveSchedules([...targetSchedules, migratedSchedule]);
|
|
156
|
-
}
|
|
157
|
-
function normalizeMode(mode) {
|
|
158
|
-
if (mode === 'query')
|
|
159
|
-
return 'query';
|
|
160
|
-
if (mode === 'command')
|
|
161
|
-
return 'command';
|
|
162
|
-
return 'execute';
|
|
163
|
-
}
|
|
164
|
-
function loadSchedules(dir) {
|
|
165
|
-
ensureDataDir(dir);
|
|
166
|
-
if (!dir) {
|
|
167
|
-
migrateLegacyMemoryDebounceSchedule();
|
|
168
|
-
}
|
|
169
|
-
const schedulesFile = resolveSchedulesFile(dir);
|
|
170
|
-
if (!fs.existsSync(schedulesFile)) {
|
|
171
|
-
return [];
|
|
172
|
-
}
|
|
173
|
-
try {
|
|
174
|
-
const data = fs.readFileSync(schedulesFile, 'utf8');
|
|
175
|
-
return JSON.parse(data);
|
|
176
|
-
}
|
|
177
|
-
catch (e) {
|
|
178
|
-
const err = e;
|
|
179
|
-
console.error('Failed to load schedules:', err.message);
|
|
180
|
-
return [];
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
function saveSchedules(schedules, dir) {
|
|
184
|
-
ensureDataDir(dir);
|
|
185
|
-
const schedulesFile = resolveSchedulesFile(dir);
|
|
186
|
-
const tempFile = `${schedulesFile}.tmp`;
|
|
187
|
-
fs.writeFileSync(tempFile, JSON.stringify(schedules, null, 2));
|
|
188
|
-
fs.renameSync(tempFile, schedulesFile);
|
|
189
|
-
}
|
|
190
|
-
async function acquireLock(timeout = 5000) {
|
|
191
|
-
ensureDataDir();
|
|
192
|
-
const startTime = Date.now();
|
|
193
|
-
while (Date.now() - startTime < timeout) {
|
|
194
|
-
try {
|
|
195
|
-
fs.writeFileSync(LOCK_FILE, String(process.pid), { flag: 'wx' });
|
|
196
|
-
return true;
|
|
197
|
-
}
|
|
198
|
-
catch (e) {
|
|
199
|
-
const err = e;
|
|
200
|
-
if (err.code === 'EEXIST') {
|
|
201
|
-
try {
|
|
202
|
-
const stat = fs.statSync(LOCK_FILE);
|
|
203
|
-
if (Date.now() - stat.mtimeMs > 30000) {
|
|
204
|
-
fs.unlinkSync(LOCK_FILE);
|
|
205
|
-
continue;
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
catch {
|
|
209
|
-
continue;
|
|
210
|
-
}
|
|
211
|
-
await new Promise(resolve => setTimeout(resolve, 100));
|
|
212
|
-
}
|
|
213
|
-
else {
|
|
214
|
-
throw e;
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
return false;
|
|
219
|
-
}
|
|
220
|
-
function releaseLock() {
|
|
221
|
-
try {
|
|
222
|
-
fs.unlinkSync(LOCK_FILE);
|
|
223
|
-
}
|
|
224
|
-
catch {
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
const DAY_NAMES = {
|
|
228
|
-
SUN: 0, MON: 1, TUE: 2, WED: 3, THU: 4, FRI: 5, SAT: 6,
|
|
229
|
-
};
|
|
230
|
-
const MONTH_NAMES = {
|
|
231
|
-
JAN: 1, FEB: 2, MAR: 3, APR: 4, MAY: 5, JUN: 6,
|
|
232
|
-
JUL: 7, AUG: 8, SEP: 9, OCT: 10, NOV: 11, DEC: 12,
|
|
233
|
-
};
|
|
234
|
-
function resolveValue(token, fieldIdx) {
|
|
235
|
-
const upper = token.toUpperCase();
|
|
236
|
-
if (fieldIdx === 4) {
|
|
237
|
-
const day = DAY_NAMES[upper];
|
|
238
|
-
if (day !== undefined)
|
|
239
|
-
return day;
|
|
240
|
-
const num = parseInt(token, 10);
|
|
241
|
-
return num === 7 ? 0 : num;
|
|
242
|
-
}
|
|
243
|
-
if (fieldIdx === 3) {
|
|
244
|
-
const month = MONTH_NAMES[upper];
|
|
245
|
-
if (month !== undefined)
|
|
246
|
-
return month;
|
|
247
|
-
}
|
|
248
|
-
return parseInt(token, 10);
|
|
249
|
-
}
|
|
250
|
-
function matchSegment(segment, value, fieldIdx) {
|
|
251
|
-
if (segment === '*')
|
|
252
|
-
return true;
|
|
253
|
-
if (segment.includes('/')) {
|
|
254
|
-
const slashPos = segment.indexOf('/');
|
|
255
|
-
const rangePart = segment.slice(0, slashPos);
|
|
256
|
-
const step = parseInt(segment.slice(slashPos + 1), 10);
|
|
257
|
-
if (isNaN(step) || step <= 0)
|
|
258
|
-
return false;
|
|
259
|
-
if (rangePart === '*') {
|
|
260
|
-
return value % step === 0;
|
|
261
|
-
}
|
|
262
|
-
if (rangePart.includes('-')) {
|
|
263
|
-
const dashPos = rangePart.indexOf('-');
|
|
264
|
-
const start = resolveValue(rangePart.slice(0, dashPos), fieldIdx);
|
|
265
|
-
const end = resolveValue(rangePart.slice(dashPos + 1), fieldIdx);
|
|
266
|
-
return value >= start && value <= end && (value - start) % step === 0;
|
|
267
|
-
}
|
|
268
|
-
const base = resolveValue(rangePart, fieldIdx);
|
|
269
|
-
return value >= base && (value - base) % step === 0;
|
|
270
|
-
}
|
|
271
|
-
if (segment.includes('-')) {
|
|
272
|
-
const dashPos = segment.indexOf('-');
|
|
273
|
-
const start = resolveValue(segment.slice(0, dashPos), fieldIdx);
|
|
274
|
-
const end = resolveValue(segment.slice(dashPos + 1), fieldIdx);
|
|
275
|
-
if (start <= end) {
|
|
276
|
-
return value >= start && value <= end;
|
|
277
|
-
}
|
|
278
|
-
return value >= start || value <= end;
|
|
279
|
-
}
|
|
280
|
-
return resolveValue(segment, fieldIdx) === value;
|
|
281
|
-
}
|
|
282
|
-
function matchField(field, value, fieldIdx) {
|
|
283
|
-
return field.split(',').some(seg => matchSegment(seg.trim(), value, fieldIdx));
|
|
284
|
-
}
|
|
285
|
-
function isValidTimezone(tz) {
|
|
286
|
-
try {
|
|
287
|
-
Intl.DateTimeFormat('en-US', { timeZone: tz });
|
|
288
|
-
return true;
|
|
289
|
-
}
|
|
290
|
-
catch {
|
|
291
|
-
return false;
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
function shouldRunNow(cronExpr, now, timezone) {
|
|
295
|
-
let checkDate = now;
|
|
296
|
-
if (timezone) {
|
|
297
|
-
if (!isValidTimezone(timezone)) {
|
|
298
|
-
console.error(`Invalid timezone: ${timezone}, skipping execution`);
|
|
299
|
-
return false;
|
|
300
|
-
}
|
|
301
|
-
else {
|
|
302
|
-
const formatter = new Intl.DateTimeFormat('en-US', {
|
|
303
|
-
timeZone: timezone,
|
|
304
|
-
year: 'numeric',
|
|
305
|
-
month: '2-digit',
|
|
306
|
-
day: '2-digit',
|
|
307
|
-
hour: '2-digit',
|
|
308
|
-
minute: '2-digit',
|
|
309
|
-
hour12: false,
|
|
310
|
-
});
|
|
311
|
-
const parts = formatter.formatToParts(now);
|
|
312
|
-
const getPart = (type) => parseInt(parts.find(p => p.type === type)?.value ?? '0', 10);
|
|
313
|
-
const year = getPart('year');
|
|
314
|
-
const month = getPart('month');
|
|
315
|
-
const day = getPart('day');
|
|
316
|
-
checkDate = {
|
|
317
|
-
getMinutes: () => getPart('minute'),
|
|
318
|
-
getHours: () => getPart('hour'),
|
|
319
|
-
getDate: () => getPart('day'),
|
|
320
|
-
getMonth: () => getPart('month') - 1,
|
|
321
|
-
getDay: () => new Date(year, month - 1, day).getDay(),
|
|
322
|
-
};
|
|
323
|
-
}
|
|
324
|
-
}
|
|
325
|
-
const fields = cronExpr.trim().split(/\s+/);
|
|
326
|
-
if (fields.length !== 5) {
|
|
327
|
-
console.error(`Invalid cron expression: ${cronExpr}`);
|
|
328
|
-
return false;
|
|
329
|
-
}
|
|
330
|
-
const [minute, hour, dayOfMonth, month, dayOfWeek] = fields;
|
|
331
|
-
const m = checkDate.getMinutes();
|
|
332
|
-
const h = checkDate.getHours();
|
|
333
|
-
const dom = checkDate.getDate();
|
|
334
|
-
const mon = checkDate.getMonth() + 1;
|
|
335
|
-
const dow = checkDate.getDay();
|
|
336
|
-
return (matchField(minute, m, 0) &&
|
|
337
|
-
matchField(hour, h, 1) &&
|
|
338
|
-
matchField(dayOfMonth, dom, 2) &&
|
|
339
|
-
matchField(month, mon, 3) &&
|
|
340
|
-
matchField(dayOfWeek, dow, 4));
|
|
341
|
-
}
|
|
342
|
-
function describeCron(cronExpr) {
|
|
343
|
-
const fields = cronExpr.trim().split(/\s+/);
|
|
344
|
-
if (fields.length !== 5)
|
|
345
|
-
return cronExpr;
|
|
346
|
-
const [minute, hour, dayOfMonth, month, dayOfWeek] = fields;
|
|
347
|
-
if (minute === '0' && hour !== '*' && dayOfMonth === '*' && month === '*' && dayOfWeek === '*') {
|
|
348
|
-
return `Daily at ${hour}:00`;
|
|
349
|
-
}
|
|
350
|
-
if (minute !== '*' && hour !== '*' && dayOfMonth === '*' && month === '*' && dayOfWeek === '*') {
|
|
351
|
-
return `Daily at ${hour}:${minute.padStart(2, '0')}`;
|
|
352
|
-
}
|
|
353
|
-
if (cronExpr === '* * * * *') {
|
|
354
|
-
return 'Every minute';
|
|
355
|
-
}
|
|
356
|
-
if (minute === '*/5' && hour === '*' && dayOfMonth === '*' && month === '*' && dayOfWeek === '*') {
|
|
357
|
-
return 'Every 5 minutes';
|
|
358
|
-
}
|
|
359
|
-
return cronExpr;
|
|
360
|
-
}
|
|
361
|
-
function getDateParts(d, timezone) {
|
|
362
|
-
if (timezone && isValidTimezone(timezone)) {
|
|
363
|
-
const formatter = new Intl.DateTimeFormat('en-US', {
|
|
364
|
-
timeZone: timezone,
|
|
365
|
-
year: 'numeric', month: '2-digit', day: '2-digit',
|
|
366
|
-
hour: '2-digit', minute: '2-digit', hour12: false,
|
|
367
|
-
weekday: 'short',
|
|
368
|
-
});
|
|
369
|
-
const parts = formatter.formatToParts(d);
|
|
370
|
-
const getPart = (type) => parseInt(parts.find(p => p.type === type)?.value ?? '0', 10);
|
|
371
|
-
const weekdayStr = parts.find(p => p.type === 'weekday')?.value ?? '';
|
|
372
|
-
const weekdayMap = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };
|
|
373
|
-
return {
|
|
374
|
-
minute: getPart('minute'),
|
|
375
|
-
hour: getPart('hour'),
|
|
376
|
-
day: getPart('day'),
|
|
377
|
-
month: getPart('month'),
|
|
378
|
-
weekday: weekdayMap[weekdayStr] ?? d.getDay(),
|
|
379
|
-
};
|
|
380
|
-
}
|
|
381
|
-
return {
|
|
382
|
-
minute: d.getMinutes(),
|
|
383
|
-
hour: d.getHours(),
|
|
384
|
-
day: d.getDate(),
|
|
385
|
-
month: d.getMonth() + 1,
|
|
386
|
-
weekday: d.getDay(),
|
|
387
|
-
};
|
|
388
|
-
}
|
|
389
|
-
function getTimezoneOffsetMinutes(date, timezone) {
|
|
390
|
-
const utcStr = date.toLocaleString('en-US', { timeZone: 'UTC' });
|
|
391
|
-
const tzStr = date.toLocaleString('en-US', { timeZone: timezone });
|
|
392
|
-
return (new Date(tzStr).getTime() - new Date(utcStr).getTime()) / 60000;
|
|
393
|
-
}
|
|
394
|
-
function calculateNextRun(cronExpr, timezone) {
|
|
395
|
-
const fields = cronExpr.trim().split(/\s+/);
|
|
396
|
-
if (fields.length !== 5)
|
|
397
|
-
return null;
|
|
398
|
-
const [minuteField, hourField, dayField, monthField, weekdayField] = fields;
|
|
399
|
-
const matchingHours = [];
|
|
400
|
-
for (let h = 0; h < 24; h++) {
|
|
401
|
-
if (matchField(hourField, h, 1))
|
|
402
|
-
matchingHours.push(h);
|
|
403
|
-
}
|
|
404
|
-
const matchingMinutes = [];
|
|
405
|
-
for (let m = 0; m < 60; m++) {
|
|
406
|
-
if (matchField(minuteField, m, 0))
|
|
407
|
-
matchingMinutes.push(m);
|
|
408
|
-
}
|
|
409
|
-
if (matchingHours.length === 0 || matchingMinutes.length === 0)
|
|
410
|
-
return null;
|
|
411
|
-
const now = new Date();
|
|
412
|
-
const useTz = timezone && isValidTimezone(timezone);
|
|
413
|
-
const startParts = getDateParts(now, timezone);
|
|
414
|
-
for (let dayOffset = 0; dayOffset <= 366; dayOffset++) {
|
|
415
|
-
const refDate = new Date(now.getTime() + dayOffset * 86400000);
|
|
416
|
-
const dp = getDateParts(refDate, timezone);
|
|
417
|
-
if (!matchField(monthField, dp.month, 3))
|
|
418
|
-
continue;
|
|
419
|
-
if (!matchField(dayField, dp.day, 2))
|
|
420
|
-
continue;
|
|
421
|
-
if (!matchField(weekdayField, dp.weekday, 4))
|
|
422
|
-
continue;
|
|
423
|
-
for (const h of matchingHours) {
|
|
424
|
-
for (const m of matchingMinutes) {
|
|
425
|
-
if (dayOffset === 0 && (h < startParts.hour || (h === startParts.hour && m <= startParts.minute))) {
|
|
426
|
-
continue;
|
|
427
|
-
}
|
|
428
|
-
let candidate;
|
|
429
|
-
if (useTz) {
|
|
430
|
-
const offsetMin = getTimezoneOffsetMinutes(refDate, timezone);
|
|
431
|
-
candidate = new Date(refDate);
|
|
432
|
-
candidate.setUTCHours(h - Math.floor(offsetMin / 60), m - (offsetMin % 60), 0, 0);
|
|
433
|
-
}
|
|
434
|
-
else {
|
|
435
|
-
candidate = new Date(refDate);
|
|
436
|
-
candidate.setHours(h, m, 0, 0);
|
|
437
|
-
}
|
|
438
|
-
if (candidate.getTime() <= now.getTime())
|
|
439
|
-
continue;
|
|
440
|
-
const cp = getDateParts(candidate, timezone);
|
|
441
|
-
if (cp.hour === h && cp.minute === m &&
|
|
442
|
-
matchField(dayField, cp.day, 2) &&
|
|
443
|
-
matchField(monthField, cp.month, 3) &&
|
|
444
|
-
matchField(weekdayField, cp.weekday, 4)) {
|
|
445
|
-
return candidate.toISOString();
|
|
446
|
-
}
|
|
447
|
-
}
|
|
448
|
-
}
|
|
449
|
-
}
|
|
450
|
-
return null;
|
|
451
|
-
}
|
|
452
|
-
function readDaemonPid(dir) {
|
|
453
|
-
try {
|
|
454
|
-
const raw = fs.readFileSync(resolvePidFile(dir), 'utf8').trim();
|
|
455
|
-
const pid = Number.parseInt(raw, 10);
|
|
456
|
-
return Number.isInteger(pid) && pid > 0 ? pid : null;
|
|
457
|
-
}
|
|
458
|
-
catch {
|
|
459
|
-
return null;
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
function writeDaemonPid(pid, dir) {
|
|
463
|
-
ensureDataDir(dir);
|
|
464
|
-
fs.writeFileSync(resolvePidFile(dir), `${pid}\n`);
|
|
465
|
-
}
|
|
466
|
-
function removeDaemonPidFile(dir) {
|
|
467
|
-
try {
|
|
468
|
-
fs.unlinkSync(resolvePidFile(dir));
|
|
469
|
-
}
|
|
470
|
-
catch {
|
|
471
|
-
}
|
|
472
|
-
}
|
|
473
|
-
function isPidAlive(pid) {
|
|
474
|
-
try {
|
|
475
|
-
process.kill(pid, 0);
|
|
476
|
-
return true;
|
|
477
|
-
}
|
|
478
|
-
catch (e) {
|
|
479
|
-
const err = e;
|
|
480
|
-
if (err.code === 'EPERM')
|
|
481
|
-
return true;
|
|
482
|
-
return false;
|
|
483
|
-
}
|
|
484
|
-
}
|
|
485
|
-
function getDaemonCliPath() {
|
|
486
|
-
const distCli = path.join(__dirname, '..', 'cli.js');
|
|
487
|
-
if (fs.existsSync(distCli)) {
|
|
488
|
-
return distCli;
|
|
489
|
-
}
|
|
490
|
-
throw new Error(`Cron CLI entrypoint not found: ${distCli}`);
|
|
491
|
-
}
|
|
492
|
-
function isDaemonRunning(dir) {
|
|
493
|
-
const pid = readDaemonPid(dir);
|
|
494
|
-
if (!pid) {
|
|
495
|
-
return false;
|
|
496
|
-
}
|
|
497
|
-
const alive = isPidAlive(pid);
|
|
498
|
-
if (!alive) {
|
|
499
|
-
removeDaemonPidFile(dir);
|
|
500
|
-
}
|
|
501
|
-
return alive;
|
|
502
|
-
}
|
|
503
|
-
function startDaemon(dir) {
|
|
504
|
-
if (isDaemonRunning(dir)) {
|
|
505
|
-
const pid = readDaemonPid(dir);
|
|
506
|
-
if (pid)
|
|
507
|
-
return pid;
|
|
508
|
-
throw new Error('Daemon is already running');
|
|
509
|
-
}
|
|
510
|
-
ensureDataDir(dir);
|
|
511
|
-
const cliPath = getDaemonCliPath();
|
|
512
|
-
const child = (0, child_process_1.spawn)('node', [cliPath, 'daemon', '--foreground'], {
|
|
513
|
-
cwd: dir || undefined,
|
|
514
|
-
detached: true,
|
|
515
|
-
stdio: 'ignore',
|
|
516
|
-
windowsHide: true,
|
|
517
|
-
});
|
|
518
|
-
if (!child.pid) {
|
|
519
|
-
throw new Error('Failed to start daemon: no PID returned');
|
|
520
|
-
}
|
|
521
|
-
child.unref();
|
|
522
|
-
writeDaemonPid(child.pid, dir);
|
|
523
|
-
return child.pid;
|
|
524
|
-
}
|
|
525
|
-
function stopDaemon(dir) {
|
|
526
|
-
const pid = readDaemonPid(dir);
|
|
527
|
-
if (!pid) {
|
|
528
|
-
removeDaemonPidFile(dir);
|
|
529
|
-
return false;
|
|
530
|
-
}
|
|
531
|
-
if (!isPidAlive(pid)) {
|
|
532
|
-
removeDaemonPidFile(dir);
|
|
533
|
-
return false;
|
|
534
|
-
}
|
|
535
|
-
process.kill(pid, 'SIGTERM');
|
|
536
|
-
return true;
|
|
537
|
-
}
|
|
538
|
-
function ensureDaemonRunning(dir) {
|
|
539
|
-
if (isDaemonRunning(dir))
|
|
540
|
-
return;
|
|
541
|
-
console.log('⚡ cron 데몬이 꺼져 있어서 자동 시작합니다...');
|
|
542
|
-
try {
|
|
543
|
-
startDaemon(dir);
|
|
544
|
-
}
|
|
545
|
-
catch (e) {
|
|
546
|
-
const err = e;
|
|
547
|
-
console.error('Failed to auto-start daemon:', err.message);
|
|
548
|
-
process.exit(1);
|
|
549
|
-
}
|
|
550
|
-
}
|
|
551
|
-
function getDaemonStatus(dir) {
|
|
552
|
-
const schedules = loadSchedules(dir);
|
|
553
|
-
const enabled = schedules.filter(s => s.enabled).length;
|
|
554
|
-
const pid = readDaemonPid(dir);
|
|
555
|
-
const running = pid !== null && isDaemonRunning(dir);
|
|
556
|
-
let started_at = null;
|
|
557
|
-
const pidFile = resolvePidFile(dir);
|
|
558
|
-
if (running && fs.existsSync(pidFile)) {
|
|
559
|
-
try {
|
|
560
|
-
started_at = fs.statSync(pidFile).mtime.toISOString();
|
|
561
|
-
}
|
|
562
|
-
catch {
|
|
563
|
-
started_at = null;
|
|
564
|
-
}
|
|
565
|
-
}
|
|
566
|
-
return {
|
|
567
|
-
running,
|
|
568
|
-
pid: running ? pid : null,
|
|
569
|
-
started_at,
|
|
570
|
-
schedules: {
|
|
571
|
-
total: schedules.length,
|
|
572
|
-
enabled,
|
|
573
|
-
},
|
|
574
|
-
};
|
|
575
|
-
}
|
|
576
|
-
async function executeSchedule(schedule, dir) {
|
|
577
|
-
if (!schedule.allow_concurrent && runningSchedules.has(schedule.id)) {
|
|
578
|
-
console.log(`[${getLocalTimestamp()}] Schedule ${schedule.id} already running, skipping`);
|
|
579
|
-
return { success: false, error: 'Already running' };
|
|
580
|
-
}
|
|
581
|
-
runningSchedules.add(schedule.id);
|
|
582
|
-
const workingDir = schedule.working_directory || getProjectRoot();
|
|
583
|
-
const mode = schedule.mode;
|
|
584
|
-
const modeFlag = mode === 'execute' ? 'x' : 'q';
|
|
585
|
-
console.log(`[${getLocalTimestamp()}] Executing schedule ${schedule.id}: ${schedule.name ?? schedule.cron}`);
|
|
586
|
-
console.log(`[${getLocalTimestamp()}] Command: ${schedule.command}`);
|
|
587
|
-
return new Promise((resolve) => {
|
|
588
|
-
const env = { ...process.env, ...schedule.env };
|
|
589
|
-
delete env['CLAUDECODE'];
|
|
590
|
-
const child = mode === 'command'
|
|
591
|
-
? (0, child_process_1.spawn)('sh', ['-c', schedule.command], {
|
|
592
|
-
cwd: workingDir,
|
|
593
|
-
stdio: 'inherit',
|
|
594
|
-
windowsHide: true,
|
|
595
|
-
env,
|
|
596
|
-
})
|
|
597
|
-
: (0, child_process_1.spawn)('crewx', [modeFlag, schedule.command], {
|
|
598
|
-
cwd: workingDir,
|
|
599
|
-
stdio: 'inherit',
|
|
600
|
-
windowsHide: true,
|
|
601
|
-
env,
|
|
602
|
-
});
|
|
603
|
-
const timeout = setTimeout(() => {
|
|
604
|
-
console.log(`[${getLocalTimestamp()}] Schedule ${schedule.id} timeout, killing process`);
|
|
605
|
-
try {
|
|
606
|
-
child.kill('SIGTERM');
|
|
607
|
-
}
|
|
608
|
-
catch (e) {
|
|
609
|
-
const err = e;
|
|
610
|
-
console.error(`Failed to kill process: ${err.message}`);
|
|
611
|
-
}
|
|
612
|
-
runningSchedules.delete(schedule.id);
|
|
613
|
-
resolve({ success: false, error: 'Timeout' });
|
|
614
|
-
}, schedule.timeout_ms || 600000);
|
|
615
|
-
child.on('close', (code) => {
|
|
616
|
-
clearTimeout(timeout);
|
|
617
|
-
runningSchedules.delete(schedule.id);
|
|
618
|
-
const schedules = loadSchedules(dir);
|
|
619
|
-
const idx = schedules.findIndex(s => s.id === schedule.id);
|
|
620
|
-
if (idx !== -1) {
|
|
621
|
-
const s = schedules[idx];
|
|
622
|
-
s.last_run = new Date().toISOString();
|
|
623
|
-
s.run_count = (s.run_count || 0) + 1;
|
|
624
|
-
s.next_run = calculateNextRun(schedule.cron, schedule.timezone);
|
|
625
|
-
saveSchedules(schedules, dir);
|
|
626
|
-
}
|
|
627
|
-
if (code === 0) {
|
|
628
|
-
console.log(`[${getLocalTimestamp()}] Schedule ${schedule.id} completed successfully`);
|
|
629
|
-
resolve({ success: true });
|
|
630
|
-
}
|
|
631
|
-
else {
|
|
632
|
-
console.log(`[${getLocalTimestamp()}] Schedule ${schedule.id} failed with code ${code}`);
|
|
633
|
-
resolve({ success: false, error: `Exit code: ${code}` });
|
|
634
|
-
}
|
|
635
|
-
});
|
|
636
|
-
child.on('error', (err) => {
|
|
637
|
-
clearTimeout(timeout);
|
|
638
|
-
runningSchedules.delete(schedule.id);
|
|
639
|
-
console.error(`[${getLocalTimestamp()}] Schedule ${schedule.id} error: ${err.message}`);
|
|
640
|
-
resolve({ success: false, error: err.message });
|
|
641
|
-
});
|
|
642
|
-
});
|
|
643
|
-
}
|
|
644
|
-
function getLocalMinuteKey(now, timezone) {
|
|
645
|
-
if (!timezone || !isValidTimezone(timezone)) {
|
|
646
|
-
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
|
|
647
|
-
}
|
|
648
|
-
const fmt = new Intl.DateTimeFormat('en-CA', {
|
|
649
|
-
timeZone: timezone,
|
|
650
|
-
year: 'numeric', month: '2-digit', day: '2-digit',
|
|
651
|
-
hour: '2-digit', minute: '2-digit', hour12: false,
|
|
652
|
-
});
|
|
653
|
-
return fmt.format(now);
|
|
654
|
-
}
|
|
655
|
-
async function daemonTick(dir) {
|
|
656
|
-
const now = new Date();
|
|
657
|
-
const schedules = loadSchedules(dir);
|
|
658
|
-
const enabledSchedules = schedules.filter(s => s.enabled);
|
|
659
|
-
if (enabledSchedules.length === 0) {
|
|
660
|
-
return;
|
|
661
|
-
}
|
|
662
|
-
for (const schedule of enabledSchedules) {
|
|
663
|
-
if (shouldRunNow(schedule.cron, now, schedule.timezone)) {
|
|
664
|
-
const minuteKey = getLocalMinuteKey(now, schedule.timezone);
|
|
665
|
-
if (schedule.last_run) {
|
|
666
|
-
const lastRunMinuteKey = getLocalMinuteKey(new Date(schedule.last_run), schedule.timezone);
|
|
667
|
-
if (lastRunMinuteKey === minuteKey) {
|
|
668
|
-
continue;
|
|
669
|
-
}
|
|
670
|
-
}
|
|
671
|
-
await executeSchedule(schedule, dir);
|
|
672
|
-
}
|
|
673
|
-
}
|
|
674
|
-
}
|
|
675
|
-
function runDaemonForeground(dir) {
|
|
676
|
-
writeDaemonPid(process.pid, dir);
|
|
677
|
-
let cleanedUp = false;
|
|
678
|
-
const cleanup = () => {
|
|
679
|
-
if (cleanedUp)
|
|
680
|
-
return;
|
|
681
|
-
cleanedUp = true;
|
|
682
|
-
const pid = readDaemonPid(dir);
|
|
683
|
-
if (pid === process.pid) {
|
|
684
|
-
removeDaemonPidFile(dir);
|
|
685
|
-
}
|
|
686
|
-
};
|
|
687
|
-
process.on('SIGTERM', () => {
|
|
688
|
-
cleanup();
|
|
689
|
-
process.exit(0);
|
|
690
|
-
});
|
|
691
|
-
process.on('SIGINT', () => {
|
|
692
|
-
cleanup();
|
|
693
|
-
process.exit(0);
|
|
694
|
-
});
|
|
695
|
-
process.on('exit', cleanup);
|
|
696
|
-
console.log(`[${getLocalTimestamp()}] Cron daemon starting in foreground mode`);
|
|
697
|
-
console.log(`[${getLocalTimestamp()}] Check interval: 1 minute`);
|
|
698
|
-
console.log(`[${getLocalTimestamp()}] Press Ctrl+C to stop\n`);
|
|
699
|
-
const schedules = loadSchedules(dir);
|
|
700
|
-
const enabled = schedules.filter(s => s.enabled).length;
|
|
701
|
-
console.log(`[${getLocalTimestamp()}] Active schedules: ${enabled}/${schedules.length}\n`);
|
|
702
|
-
void daemonTick(dir);
|
|
703
|
-
setInterval(() => {
|
|
704
|
-
void daemonTick(dir);
|
|
705
|
-
}, DAEMON_INTERVAL_MS);
|
|
706
|
-
}
|
|
707
|
-
function addSchedule(cron, command, options, dataDir) {
|
|
708
|
-
if (options.timezone && !isValidTimezone(options.timezone)) {
|
|
709
|
-
throw new Error(`Invalid timezone: ${options.timezone}`);
|
|
710
|
-
}
|
|
711
|
-
const schedule = {
|
|
712
|
-
id: (0, sdk_1.generateId)('cron'),
|
|
713
|
-
cron,
|
|
714
|
-
command,
|
|
715
|
-
mode: normalizeMode(options.mode ?? 'execute'),
|
|
716
|
-
enabled: true,
|
|
717
|
-
name: options.name ?? null,
|
|
718
|
-
working_directory: options.dir ?? null,
|
|
719
|
-
timezone: options.timezone ?? null,
|
|
720
|
-
timeout_ms: parseInt(options.timeout ?? '600000', 10),
|
|
721
|
-
allow_concurrent: options.allowConcurrent ?? false,
|
|
722
|
-
created_at: new Date().toISOString(),
|
|
723
|
-
updated_at: new Date().toISOString(),
|
|
724
|
-
run_count: 0,
|
|
725
|
-
};
|
|
726
|
-
schedule.next_run = calculateNextRun(cron, schedule.timezone);
|
|
727
|
-
const schedules = loadSchedules(dataDir);
|
|
728
|
-
schedules.push(schedule);
|
|
729
|
-
saveSchedules(schedules, dataDir);
|
|
730
|
-
return schedule;
|
|
731
|
-
}
|
|
732
|
-
function removeSchedule(id, dir) {
|
|
733
|
-
const schedules = loadSchedules(dir);
|
|
734
|
-
const idx = schedules.findIndex(s => s.id === id);
|
|
735
|
-
if (idx === -1) {
|
|
736
|
-
throw new Error(`Schedule not found: ${id}`);
|
|
737
|
-
}
|
|
738
|
-
const removed = schedules.splice(idx, 1)[0];
|
|
739
|
-
saveSchedules(schedules, dir);
|
|
740
|
-
return removed;
|
|
741
|
-
}
|
|
742
|
-
function enableSchedule(id, dir) {
|
|
743
|
-
const schedules = loadSchedules(dir);
|
|
744
|
-
const schedule = schedules.find(s => s.id === id);
|
|
745
|
-
if (!schedule) {
|
|
746
|
-
throw new Error(`Schedule not found: ${id}`);
|
|
747
|
-
}
|
|
748
|
-
schedule.enabled = true;
|
|
749
|
-
schedule.updated_at = new Date().toISOString();
|
|
750
|
-
schedule.next_run = calculateNextRun(schedule.cron, schedule.timezone);
|
|
751
|
-
saveSchedules(schedules, dir);
|
|
752
|
-
return schedule;
|
|
753
|
-
}
|
|
754
|
-
function disableSchedule(id, dir) {
|
|
755
|
-
const schedules = loadSchedules(dir);
|
|
756
|
-
const schedule = schedules.find(s => s.id === id);
|
|
757
|
-
if (!schedule) {
|
|
758
|
-
throw new Error(`Schedule not found: ${id}`);
|
|
759
|
-
}
|
|
760
|
-
schedule.enabled = false;
|
|
761
|
-
schedule.updated_at = new Date().toISOString();
|
|
762
|
-
saveSchedules(schedules, dir);
|
|
763
|
-
return schedule;
|
|
764
|
-
}
|
|
765
|
-
function updateSchedule(id, options, dir) {
|
|
766
|
-
const schedules = loadSchedules(dir);
|
|
767
|
-
const schedule = schedules.find(s => s.id === id);
|
|
768
|
-
if (!schedule) {
|
|
769
|
-
throw new Error(`Schedule not found: ${id}`);
|
|
770
|
-
}
|
|
771
|
-
if (options.timezone !== undefined && options.timezone !== null && !isValidTimezone(options.timezone)) {
|
|
772
|
-
throw new Error(`Invalid timezone: ${options.timezone}`);
|
|
773
|
-
}
|
|
774
|
-
const changes = [];
|
|
775
|
-
if (options.cron !== undefined) {
|
|
776
|
-
schedule.cron = options.cron;
|
|
777
|
-
changes.push(`cron: ${options.cron}`);
|
|
778
|
-
}
|
|
779
|
-
if (options.command !== undefined) {
|
|
780
|
-
schedule.command = options.command;
|
|
781
|
-
changes.push(`command: ${options.command}`);
|
|
782
|
-
}
|
|
783
|
-
if (options.name !== undefined) {
|
|
784
|
-
schedule.name = options.name;
|
|
785
|
-
changes.push(`name: ${options.name}`);
|
|
786
|
-
}
|
|
787
|
-
if (options.mode !== undefined) {
|
|
788
|
-
schedule.mode = normalizeMode(options.mode);
|
|
789
|
-
changes.push(`mode: ${schedule.mode}`);
|
|
790
|
-
}
|
|
791
|
-
if (options.timezone !== undefined) {
|
|
792
|
-
schedule.timezone = options.timezone;
|
|
793
|
-
changes.push(`timezone: ${options.timezone}`);
|
|
794
|
-
}
|
|
795
|
-
if (options.working_directory !== undefined) {
|
|
796
|
-
schedule.working_directory = options.working_directory;
|
|
797
|
-
changes.push(`working_directory: ${options.working_directory}`);
|
|
798
|
-
}
|
|
799
|
-
if (options.timeout_ms !== undefined) {
|
|
800
|
-
schedule.timeout_ms = options.timeout_ms;
|
|
801
|
-
changes.push(`timeout: ${options.timeout_ms}ms`);
|
|
802
|
-
}
|
|
803
|
-
if (options.allow_concurrent !== undefined) {
|
|
804
|
-
schedule.allow_concurrent = options.allow_concurrent;
|
|
805
|
-
changes.push(`allow_concurrent: ${options.allow_concurrent}`);
|
|
806
|
-
}
|
|
807
|
-
schedule.updated_at = new Date().toISOString();
|
|
808
|
-
schedule.next_run = calculateNextRun(schedule.cron, schedule.timezone);
|
|
809
|
-
saveSchedules(schedules, dir);
|
|
810
|
-
return { schedule, changes };
|
|
811
|
-
}
|
|
812
|
-
exports.DATA_PATHS = {
|
|
813
|
-
DATA_DIR,
|
|
814
|
-
SCHEDULES_FILE,
|
|
815
|
-
LOG_FILE,
|
|
816
|
-
USAGE_LOG_FILE,
|
|
817
|
-
PID_FILE,
|
|
818
|
-
};
|
|
819
|
-
//# sourceMappingURL=engine.js.map
|
|
1
|
+
"use strict";var Ue=exports&&exports.__createBinding||(Object.create?(function(e,n,t,r){if(r===void 0)r=t;var o=Object.getOwnPropertyDescriptor(n,t);if(!o||("get"in o?!n.__esModule:o.writable||o.configurable)){o={enumerable:true,get:function(){return n[t]}}}Object.defineProperty(e,r,o)}):(function(e,n,t,r){if(r===void 0)r=t;e[r]=n[t]}));var Me=exports&&exports.__setModuleDefault||(Object.create?(function(e,n){Object.defineProperty(e,"default",{enumerable:true,value:n})}):function(e,n){e["default"]=n});var de=exports&&exports.__importStar||(function(){var e=function(n){e=Object.getOwnPropertyNames||function(t){var r=[];for(var o in t)if(Object.prototype.hasOwnProperty.call(t,o))r[r.length]=o;return r};return e(n)};return function(n){if(n&&n.__esModule)return n;var t={};if(n!=null){for(var r=e(n),o=0;o<r.length;o++)if(r[o]!=="default")Ue(t,n,r[o])}Me(t,n);return t}})();Object.defineProperty(exports,"__esModule",{value:true});exports.DATA_PATHS=exports.CRON_RUNTIME_PROCESS_LEASE_FILENAME=exports.createCronRuntime=exports.getProjectRoot=exports.BUILTIN_SCHEDULES=exports.CronStoreError=void 0;exports.getLocalTimestamp=g;exports.logUsage=Ve;exports.acquireWorkspaceLock=G;exports.releaseWorkspaceLock=B;exports.migrateLegacyMemoryDebounceSchedule=nn;exports.normalizeMode=oe;exports.createScheduleStore=D;exports.loadSchedules=rn;exports.saveSchedules=on;exports.getRemovedBuiltins=ve;exports.seedBuiltinSchedules=an;exports.acquireLock=un;exports.releaseLock=ln;exports.releaseRunLock=Ee;exports.shouldRunNow=ke;exports.describeCron=_n;exports.calculateNextRun=j;exports.isDaemonRunning=ue;exports.startDaemon=In;exports.stopDaemon=On;exports.startDaemonSafe=Le;exports.ensureDaemonRunning=Tn;exports.getDaemonStatus=Cn;exports.executeSchedule=Pe;exports.getLocalMinuteKey=Re;exports.buildOccurrenceKey=Ne;exports.daemonTick=le;exports.runDaemonForeground=$n;exports.addSchedule=Ln;exports.removeSchedule=Pn;exports.enableSchedule=Rn;exports.disableSchedule=Nn;exports.updateSchedule=bn;const b=require("child_process");const q=require("crypto");const d=de(require("path"));const u=de(require("fs"));const L=require("./types");Object.defineProperty(exports,"CronStoreError",{enumerable:true,get:function(){return L.CronStoreError}});const k=require("@crewx/sdk");const A=require("./builtins");Object.defineProperty(exports,"BUILTIN_SCHEDULES",{enumerable:true,get:function(){return A.BUILTIN_SCHEDULES}});Object.defineProperty(exports,"getProjectRoot",{enumerable:true,get:function(){return A.getProjectRoot}});const p=d.resolve(process.cwd());const F=d.join(p,".crewx");const je=d.join(F,".cron-data.json");const xe=d.join(F,".cron-daemon.log");const ze=d.join(F,".cron-data.json.lock");const Be=d.join(F,"cron-usage.log");const He=d.join(F,".cron-daemon.pid");const Ke=d.join(F,".cron-builtins.json");function P(e){return d.join(d.resolve(e??p),".crewx")}function ne(e){return d.join(P(e),".cron-data.json")}function fe(e){return d.join(P(e),".cron-data.json.lock")}function We(e){return d.join(P(e),"cron-usage.log")}function z(e){return d.join(P(e),".cron-daemon.pid")}function me(e){return d.join(P(e),".cron-builtins.json")}function qe(e,n,t){const r=(0,k.reserveUpdateAdmission)(e,n,t);if(!r){console.error(`[${g()}] Failed to record update-admission reservation for task ${e}`)}return r}function Ge(e){(0,k.releaseUpdateAdmissionReservation)(e)}function Se(e,n){return d.join(P(n),`.cron-run-${e}.lock`)}const Je=60*1e3;const ge=5e3;const Xe=25;const Ze=3e4;const ye=5e3;function g(){const e=new Date;const n=e.getFullYear();const t=String(e.getMonth()+1).padStart(2,"0");const r=String(e.getDate()).padStart(2,"0");const o=String(e.getHours()).padStart(2,"0");const c=String(e.getMinutes()).padStart(2,"0");const i=String(e.getSeconds()).padStart(2,"0");return`${n}-${t}-${r} ${o}:${c}:${i}`}function Ve(e,...n){const t=s=>s!==void 0&&(s==="."||s===".."||d.isAbsolute(s)||s.includes(d.sep)||s.includes("/")||s.includes("\\")||s.endsWith(".crewx")||(()=>{try{return u.statSync(s).isDirectory()}catch{return false}})());let r;let o;if(n.length>0&&(e===void 0||t(e))){r=e;o=n}else if(n.length===0&&t(e)){r=e;o=[]}else if(n.length===1&&t(n[0])){r=n[0];o=e===void 0?[]:[e]}else{r=void 0;o=e===void 0?n:[e,...n]}U(r);const c=g();const i=o.join(" ");const a=`${c} | [cron] ${i}
|
|
2
|
+
`;u.appendFileSync(We(r),a)}function U(e){const n=P(e);if(!u.existsSync(n)){u.mkdirSync(n,{recursive:true})}}function te(e){try{return JSON.parse(u.readFileSync(e,"utf8"))}catch{return null}}const Ye=new Int32Array(new SharedArrayBuffer(4));function Qe(){Atomics.wait(Ye,0,0,Xe)}function he(e){try{const n=JSON.parse(u.readFileSync(e,"utf8"));if(typeof n.token!=="string"||typeof n.pid!=="number"||typeof n.created_at!=="number"){return null}return n}catch{return null}}function G(e,n=ge){const t=d.resolve(e);U(t);const r=fe(t);const o=(0,q.randomUUID)();const c=Date.now()+Math.max(0,n);const i={workspacePath:t,lockPath:r,token:o};while(true){const a={token:o,pid:process.pid,created_at:Date.now()};try{u.writeFileSync(r,JSON.stringify(a),{flag:"wx",mode:384});return i}catch(s){const f=s;if(f.code!=="EEXIST")throw s;const w=he(r);if(w&&Date.now()-w.created_at>Ze){B({...i,token:w.token});continue}if(Date.now()>=c){throw new L.CronStoreError("CRON_STORE_LOCK_TIMEOUT",`Timed out waiting for cron store lock: ${r}`,r)}Qe()}}}function B(e){const n=he(e.lockPath);if(!n||n.token!==e.token)return false;try{u.unlinkSync(e.lockPath);return true}catch(t){const r=t;if(r.code==="ENOENT")return false;throw t}}const re=(0,A.findBuiltinById)("memory-debounce");function en(e){if(!e.includes("/skills/memory-v2/memory-v2.js")){return e}return re.buildCommand()}function nn(e=(0,A.getProjectRoot)()){const n=d.resolve(e);const t=d.join(n,"skills","cron",".cron-data.json");if(!u.existsSync(t)){return}const r=te(t);if(!Array.isArray(r)){return}const o=r.find(s=>s.name===re.name);if(!o){return}const c=D(n);const i=c.list();if(i.some(s=>s.name===re.name)){return}const a={...o,command:en(o.command),updated_at:new Date().toISOString(),next_run:j(o.cron,o.timezone)};c.create(a)}function we(e){if(e.includes("--overdrive")){console.warn("warning: --overdrive in cron command is ignored and may silently override --model")}}function oe(e){if(e==="query")return"query";if(e==="command")return"command";return"execute"}function O(e){return{...e,...e.env?{env:{...e.env}}:{}}}function Z(e){let n;try{n=u.readFileSync(e,"utf8")}catch(r){const o=r;if(o.code==="ENOENT")return[];throw r}let t;try{t=JSON.parse(n)}catch(r){throw new L.CronStoreError("CRON_STORE_CORRUPT",`Cron schedule store is not valid JSON: ${e}`,e)}if(!Array.isArray(t)){throw new L.CronStoreError("CRON_STORE_CORRUPT",`Cron schedule store must contain a top-level array: ${e}`,e)}return t}function tn(e){if(process.platform==="win32")return;try{const n=u.openSync(e,"r");try{u.fsyncSync(n)}finally{u.closeSync(n)}}catch{}}function pe(e,n){const t=d.dirname(e);const r=d.join(t,`.${d.basename(e)}.${process.pid}.${(0,q.randomUUID)()}.tmp`);const o=JSON.stringify(n,null,2);let c;try{c=u.openSync(r,"wx",384);u.writeFileSync(c,o);u.fsyncSync(c);u.closeSync(c);c=void 0;u.renameSync(r,e);tn(t)}finally{if(c!==void 0){try{u.closeSync(c)}catch{}}try{u.unlinkSync(r)}catch{}}}function J(e,n){const t=e.find(r=>r.id===n);if(!t){throw new L.CronStoreError("CRON_SCHEDULE_NOT_FOUND",`Schedule not found: ${n}`)}return t}function M(e,n){const t=G(e);try{const r=ne(e);const o=Z(r);const c=n(o);pe(r,o);return c}finally{B(t)}}function D(e=p){const n=d.resolve(e);const t=P(n);const r=ne(n);const o=fe(n);return{workspacePath:n,dataDir:t,schedulesFile:r,lockFile:o,list(){return Z(r).map(O)},get(c){const i=Z(r).find(a=>a.id===c);return i?O(i):void 0},create(c){return M(n,i=>{if(i.some(a=>a.id===c.id)){throw new L.CronStoreError("CRON_SCHEDULE_EXISTS",`Schedule already exists: ${c.id}`)}i.push(O(c));return O(c)})},update(c,i){return M(n,a=>{const s=J(a,c);if(i.cron!==void 0)s.cron=i.cron;if(i.command!==void 0)s.command=i.command;if(i.mode!==void 0)s.mode=i.mode;if(i.enabled!==void 0)s.enabled=i.enabled;if(i.name!==void 0)s.name=i.name;if(i.working_directory!==void 0)s.working_directory=i.working_directory;if(i.timezone!==void 0)s.timezone=i.timezone;if(i.timeout_ms!==void 0)s.timeout_ms=i.timeout_ms;if(i.allow_concurrent!==void 0)s.allow_concurrent=i.allow_concurrent;if(i.env!==void 0){if(i.env===null)delete s.env;else s.env={...i.env}}if(i.model!==void 0){if(i.model===null)delete s.model;else s.model=i.model}if(i.provider!==void 0){if(i.provider===null)delete s.provider;else s.provider=i.provider}s.updated_at=new Date().toISOString();s.next_run=j(s.cron,s.timezone);return O(s)})},remove(c){return M(n,i=>{const a=i.findIndex(f=>f.id===c);if(a===-1){throw new L.CronStoreError("CRON_SCHEDULE_NOT_FOUND",`Schedule not found: ${c}`)}const[s]=i.splice(a,1);return O(s)})},toggle(c,i){return M(n,a=>{const s=J(a,c);s.enabled=i??!s.enabled;s.updated_at=new Date().toISOString();if(s.enabled){s.next_run=j(s.cron,s.timezone)}return O(s)})},claimOccurrence(c,i){return M(n,a=>{const s=J(a,typeof c==="string"?c:c.id);if(s.last_occurrence_key===i.occurrenceKey){return{claimed:false,schedule:O(s)}}const f=i.startedAt??new Date().toISOString();s.last_started_at=f;s.last_occurrence_key=i.occurrenceKey;s.updated_at=f;return{claimed:true,schedule:O(s)}})},recordStarted(c,i){return M(n,a=>{const s=J(a,typeof c==="string"?c:c.id);const f=typeof i==="string"?{startedAt:i}:i;const w=f?.startedAt??new Date().toISOString();s.last_started_at=w;if(f?.occurrenceKey!==void 0){s.last_occurrence_key=f.occurrenceKey}s.updated_at=w;return O(s)})},recordFinished(c,i){return M(n,a=>{const s=J(a,typeof c==="string"?c:c.id);const f=i?.finishedAt??new Date().toISOString();s.last_run=f;s.run_count=(s.run_count||0)+1;s.next_run=i?.nextRun!==void 0?i.nextRun:j(s.cron,s.timezone);if(i?.outcome!==void 0)s.last_outcome=i.outcome;else if(i?.success!==void 0)s.last_outcome=i.success?"success":"failure";s.updated_at=f;return O(s)})}}}function rn(e){return D(e??p).list()}function on(e,n){const t=d.resolve(n??p);const r=G(t);try{const o=ne(t);Z(o);pe(o,e.map(O))}finally{B(r)}}function _e(e){const n=te(me(e));return{removed_builtins:Array.isArray(n?.removed_builtins)?n.removed_builtins:[]}}function cn(e,n){U(n);const t=me(n);const r=`${t}.tmp`;u.writeFileSync(r,JSON.stringify(e,null,2));u.renameSync(r,t)}function ve(e){return _e(e).removed_builtins}function sn(e,n){const t=_e(n);if(!t.removed_builtins.includes(e)){t.removed_builtins.push(e);cn(t,n)}}function an(e){const n=D(e??p);const t=n.list();const r=new Set(t.map(i=>i.name));const o=new Set(ve(e));const c=[];for(const i of A.BUILTIN_SCHEDULES){if(r.has(i.name))continue;if(o.has(i.builtin_id))continue;const a=new Date().toISOString();const s={id:(0,k.generateId)("cron"),cron:i.cron,command:i.buildCommand(),mode:i.mode,enabled:true,name:i.name,working_directory:null,timezone:null,timeout_ms:6e5,allow_concurrent:false,created_at:a,updated_at:a,run_count:0,next_run:j(i.cron,null)};n.create(s);r.add(i.name);c.push(i.builtin_id)}return c}const ie=new Map;async function un(e=ge,n){const t=d.resolve(n??p);try{ie.set(t,G(t,e));return true}catch(r){if(r instanceof L.CronStoreError&&r.code==="CRON_STORE_LOCK_TIMEOUT")return false;throw r}}function ln(e){const n=d.resolve(e??p);const t=ie.get(n);if(!t)return;ie.delete(n);B(t)}function X(e){return te(e)}function dn(e,n){const t=d.dirname(e);const r=d.join(t,`.${d.basename(e)}.${process.pid}.${(0,q.randomUUID)()}.tmp`);let o;try{o=u.openSync(r,"wx",384);u.writeFileSync(o,JSON.stringify(n));u.fsyncSync(o);u.closeSync(o);o=void 0;u.renameSync(r,e)}finally{if(o!==void 0){try{u.closeSync(o)}catch{}}try{u.unlinkSync(r)}catch{}}}function ce(e,n,t){const r=G(e);try{return t(Se(n,e))}finally{B(r)}}function fn(e){try{return Math.max(0,Date.now()-u.statSync(e).mtimeMs)}catch{return null}}function mn(e,n){if(e.startTime!==null&&n.startTime!==null){return e.startTime===n.startTime}if(e.commandLine!==null&&n.commandLine!==null){return e.commandLine===n.commandLine}return null}function Sn(e,n,t){if(e.phase!=="child"){const a=fn(n);if(a===null)return false;const s=e.hostPid??e.pid;const f=ae(s);return f===false||a>t+ye}const r=e.childPid??e.pid;const o=ae(r);if(o===false)return true;if(o!==true)return false;if(!e.childIdentity)return false;const c=Oe(r);if(!c)return false;const i=mn(e.childIdentity,c);if(i===false)return true;return false}function gn(e,n,t,r){const o=d.resolve(r??p);U(o);const c=Se(e,o);const i=(0,q.randomUUID)();const a=(0,q.randomUUID)();const s={leaseId:i,ownerToken:a,phase:"admitting",hostPid:process.pid,pid:process.pid,taskId:n,startedAt:new Date().toISOString()};return ce(o,e,()=>{for(let w=0;w<2;w++){try{u.writeFileSync(c,JSON.stringify(s),{flag:"wx",mode:384});return{acquired:true,lease:{scheduleId:e,workspacePath:o,lockFile:c,leaseId:i,ownerToken:a,taskId:n}}}catch(R){const T=R;if(T.code!=="EEXIST")throw T;const S=X(c);if(!S){return{acquired:false,runningTaskId:"unknown",reason:"execution_lease"}}if(Sn(S,c,t)){const _=X(c);if(_?.leaseId!==void 0&&_.leaseId!==S.leaseId){continue}try{u.unlinkSync(c)}catch{}continue}return{acquired:false,runningTaskId:S.taskId,reason:"execution_lease"}}}const f=X(c);return{acquired:false,runningTaskId:f?.taskId??"unknown",reason:"execution_lease"}})}function yn(e,n,t){return ce(e.workspacePath,e.scheduleId,r=>{const o=X(r);if(!o||o.leaseId!==e.leaseId||o.ownerToken!==e.ownerToken){return false}dn(r,{...o,phase:"child",pid:n,childPid:n,childIdentity:t});return true})}function Ee(e,n,t){const r=d.resolve(t??p);U(r);return ce(r,e,o=>{const c=X(o);if(!c||c.leaseId!==n)return false;try{u.unlinkSync(o);return true}catch(i){const a=i;if(a.code==="ENOENT")return false;throw i}})}const hn={SUN:0,MON:1,TUE:2,WED:3,THU:4,FRI:5,SAT:6};const wn={JAN:1,FEB:2,MAR:3,APR:4,MAY:5,JUN:6,JUL:7,AUG:8,SEP:9,OCT:10,NOV:11,DEC:12};function H(e,n){const t=e.toUpperCase();if(n===4){const r=hn[t];if(r!==void 0)return r;const o=parseInt(e,10);return o===7?0:o}if(n===3){const r=wn[t];if(r!==void 0)return r}return parseInt(e,10)}function pn(e,n,t){if(e==="*")return true;if(e.includes("/")){const r=e.indexOf("/");const o=e.slice(0,r);const c=parseInt(e.slice(r+1),10);if(isNaN(c)||c<=0)return false;if(o==="*"){return n%c===0}if(o.includes("-")){const a=o.indexOf("-");const s=H(o.slice(0,a),t);const f=H(o.slice(a+1),t);return n>=s&&n<=f&&(n-s)%c===0}const i=H(o,t);return n>=i&&(n-i)%c===0}if(e.includes("-")){const r=e.indexOf("-");const o=H(e.slice(0,r),t);const c=H(e.slice(r+1),t);if(o<=c){return n>=o&&n<=c}return n>=o||n<=c}return H(e,t)===n}function I(e,n,t){return e.split(",").some(r=>pn(r.trim(),n,t))}function K(e){try{Intl.DateTimeFormat("en-US",{timeZone:e});return true}catch{return false}}function ke(e,n,t){let r=n;if(t){if(!K(t)){console.error(`Invalid timezone: ${t}, skipping execution`);return false}else{const C=new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:false});const y=C.formatToParts(n);const v=E=>parseInt(y.find(N=>N.type===E)?.value??"0",10);const l=v("year");const m=v("month");const h=v("day");r={getMinutes:()=>v("minute"),getHours:()=>v("hour"),getDate:()=>v("day"),getMonth:()=>v("month")-1,getDay:()=>new Date(l,m-1,h).getDay()}}}const o=e.trim().split(/\s+/);if(o.length!==5){console.error(`Invalid cron expression: ${e}`);return false}const[c,i,a,s,f]=o;const w=r.getMinutes();const R=r.getHours();const T=r.getDate();const S=r.getMonth()+1;const _=r.getDay();return I(c,w,0)&&I(i,R,1)&&I(a,T,2)&&I(s,S,3)&&I(f,_,4)}function _n(e){const n=e.trim().split(/\s+/);if(n.length!==5)return e;const[t,r,o,c,i]=n;if(t==="0"&&r!=="*"&&o==="*"&&c==="*"&&i==="*"){return`Daily at ${r}:00`}if(t!=="*"&&r!=="*"&&o==="*"&&c==="*"&&i==="*"){return`Daily at ${r}:${t.padStart(2,"0")}`}if(e==="* * * * *"){return"Every minute"}if(t==="*/5"&&r==="*"&&o==="*"&&c==="*"&&i==="*"){return"Every 5 minutes"}return e}function se(e,n){if(n&&K(n)){const t=new Intl.DateTimeFormat("en-US",{timeZone:n,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:false,weekday:"short"});const r=t.formatToParts(e);const o=a=>parseInt(r.find(s=>s.type===a)?.value??"0",10);const c=r.find(a=>a.type==="weekday")?.value??"";const i={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6};return{minute:o("minute"),hour:o("hour"),day:o("day"),month:o("month"),weekday:i[c]??e.getDay()}}return{minute:e.getMinutes(),hour:e.getHours(),day:e.getDate(),month:e.getMonth()+1,weekday:e.getDay()}}function vn(e,n){const t=e.toLocaleString("en-US",{timeZone:"UTC"});const r=e.toLocaleString("en-US",{timeZone:n});return(new Date(r).getTime()-new Date(t).getTime())/6e4}function j(e,n){const t=e.trim().split(/\s+/);if(t.length!==5)return null;const[r,o,c,i,a]=t;const s=[];for(let S=0;S<24;S++){if(I(o,S,1))s.push(S)}const f=[];for(let S=0;S<60;S++){if(I(r,S,0))f.push(S)}if(s.length===0||f.length===0)return null;const w=new Date;const R=n&&K(n);const T=se(w,n);for(let S=0;S<=366;S++){const _=new Date(w.getTime()+S*864e5);const C=se(_,n);if(!I(i,C.month,3))continue;if(!I(c,C.day,2))continue;if(!I(a,C.weekday,4))continue;for(const y of s){for(const v of f){if(S===0&&(y<T.hour||y===T.hour&&v<=T.minute)){continue}let l;if(R){const h=vn(_,n);l=new Date(_);l.setUTCHours(y-Math.floor(h/60),v-h%60,0,0)}else{l=new Date(_);l.setHours(y,v,0,0)}if(l.getTime()<=w.getTime())continue;const m=se(l,n);if(m.hour===y&&m.minute===v&&I(c,m.day,2)&&I(i,m.month,3)&&I(a,m.weekday,4)){return l.toISOString()}}}}return null}function x(e){try{const n=u.readFileSync(z(e),"utf8").trim();if(!/^\d+$/.test(n))return null;const t=Number(n);return Number.isSafeInteger(t)&&t>0?t:null}catch{return null}}function De(e,n){U(n);u.writeFileSync(z(n),`${e}
|
|
3
|
+
`)}function V(e){try{u.unlinkSync(z(e))}catch{}}function ae(e){try{process.kill(e,0);return true}catch(n){const t=n;return t.code==="ESRCH"?false:"unknown"}}function Ie(e){try{const n=process.platform==="win32"?(0,b.execFileSync)("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}):(0,b.execFileSync)("ps",["-ww","-p",String(e),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return n.trim()||null}catch{return null}}function En(e){try{const n=process.platform==="win32"?(0,b.execFileSync)("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CreationDate.ToUniversalTime().ToString("o")`],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}):(0,b.execFileSync)("ps",["-p",String(e),"-o","lstart="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return n.trim()||null}catch{return null}}function Oe(e){const n={commandLine:Ie(e),startTime:En(e)};return n.commandLine!==null||n.startTime!==null?n:null}const W={isAlive:ae,getCommandLine:Ie};function Te(e){const n=e.replace(/\\/g,"/");return process.platform==="win32"?n.toLowerCase():n}function kn(){try{const e=Te(Ce()).split("/").filter(Boolean);const n=e.slice(-3).join("/");return n||null}catch{return null}}function Dn(e){if(!e?.trim())return"unknown";const n=kn();if(!n)return"unknown";const t=Te(e);return t.includes("daemon --foreground")&&t.includes(n)?"running":"stale"}function Ce(){const e=[d.join(__dirname,"..","cli.js"),d.join(__dirname,"..","dist","cli.js")];const n=e.find(t=>u.existsSync(t));if(n){return n}throw new Error(`Cron CLI entrypoint not found: ${e[0]}`)}function Y(e,n=W){const t=x(e);if(!t){V(e);return"stale"}let r;try{r=n.isAlive(t)}catch{r="unknown"}if(!r){V(e);return"stale"}let o;try{o=n.getCommandLine(t)}catch{return"unknown"}const c=Dn(o);if(c==="stale"){V(e)}return c}function ue(e,n=W){return Y(e,n)==="running"}function $e(e,n=b.spawn){if((0,k.isDurablyQuiescing)()){throw new Error("Cannot start cron daemon: a desktop update is draining active work")}U(e);const t=Ce();const r={...process.env};if(process.versions.electron){r.ELECTRON_RUN_AS_NODE="1"}const o=n(process.execPath,[t,"daemon","--foreground"],{cwd:e||void 0,detached:true,stdio:"ignore",windowsHide:true,env:r});if(!o.pid){throw new Error("Failed to start daemon: no PID returned")}o.unref();De(o.pid,e);return o.pid}function In(e,n=W){const t=Y(e,n);if(t==="running"){const r=x(e);if(r)return r;throw new Error("Daemon is already running")}if(t==="unknown"){const r=x(e);throw new Error(`Unable to determine cron daemon liveness (pid=${r??"unknown"}, pidFile=${z(e)}); refusing to start`)}return $e(e,n.spawnImpl)}function On(e,n=W){if(Y(e,n)!=="running")return false;const t=x(e);if(!t)return false;process.kill(t,"SIGTERM");return true}function Le(e,n=W){const t=Y(e,n);if(t==="running"){return{started:false}}if(t==="unknown"){return{started:false,error:`Unable to determine cron daemon liveness (pid=${x(e)??"unknown"}, pidFile=${z(e)}); refusing to start`}}try{const r=$e(e,n.spawnImpl);return{started:true,pid:r}}catch(r){const o=r;return{started:false,error:o.message}}}function Tn(e,n=W){if(ue(e,n))return;console.log("\u26A1 Cron daemon is not running; starting it automatically...");const t=Le(e,n);if(!t.started){console.error("Failed to auto-start daemon:",t.error);process.exit(1)}}function Cn(e){const n=D(e??p).list();const t=n.filter(a=>a.enabled).length;const r=ue(e);const o=r?x(e):null;let c=null;const i=z(e);if(r&&u.existsSync(i)){try{c=u.statSync(i).mtime.toISOString()}catch{c=null}}return{running:r,pid:r?o:null,started_at:c,schedules:{total:n.length,enabled:t}}}async function Pe(e,n){const t=n?.dir;const r=d.resolve(t??p);const o=n?.trigger??"cron";const c=e.timeout_ms||6e5;const i=(0,k.generateId)("tsk");let a;if(!e.allow_concurrent){const l=gn(e.id,i,c,t);if(!l.acquired){console.log(`[${g()}] Schedule ${e.id} already running (task ${l.runningTaskId}), skipping`);return{status:"conflict",runningTaskId:l.runningTaskId,reason:l.reason}}a=l.lease}const s=()=>{if(a){Ee(e.id,a.leaseId,t);a=void 0}Ge(i)};if(!qe(i,e.id,c)){console.log(`[${g()}] Schedule ${e.id} blocked: could not durably record the update-admission reservation`);s();return{status:"blocked",reason:"ADMISSION_UNKNOWN"}}if((0,k.isDurablyQuiescing)()){console.log(`[${g()}] Schedule ${e.id} blocked: a desktop update is draining active work`);s();return{status:"blocked",reason:"UPDATE_QUIESCING"}}try{const l=D(r);const m=new Date().toISOString();if(n?.occurrenceKey!==void 0){const h=l.claimOccurrence(e.id,{occurrenceKey:n.occurrenceKey,startedAt:m});if(!h.claimed){s();console.log(`[${g()}] Schedule ${e.id} occurrence ${n.occurrenceKey} already claimed, skipping`);return{status:"conflict",runningTaskId:"",reason:"occurrence_claim"}}}else{if(l.get(e.id)){l.recordStarted(e.id,{startedAt:m})}}}catch(l){s();throw l}const f=e.working_directory||n?.dir||(0,A.getProjectRoot)();const w=e.mode;const R=w==="execute"?"x":"q";const T=n?.overrides?.model??e.model;const S=n?.overrides?.provider??e.provider;console.log(`[${g()}] Executing schedule ${e.id}: ${e.name??e.cron} (task ${i})`);console.log(`[${g()}] Command: ${e.command}`);const _=(0,k.withoutCrewxRootContext)({...process.env,...e.env,CREWX_TRACE_ID:i});delete _["CLAUDECODE"];if(!e.env||!("CREWX_CONFIG"in e.env)){delete _["CREWX_CONFIG"]}_["CREWX_WORKSPACE"]=f;const C=[R,e.command];if(T){C.push("--model",T)}if(w!=="command"&&S){C.push("--provider",S)}C.push("--metadata",JSON.stringify({trigger:o,schedule_id:e.id}));let y;try{if(w==="command"){y=(0,b.spawn)("sh",["-c",e.command],{cwd:f,stdio:"ignore",windowsHide:true,detached:true,env:_})}else{const l=(0,k.resolveCrewxExecutable)({env:_,cwd:f});if(!l.ok){const N=new Error((0,k.formatCrewxExecutableFailure)(l));Object.assign(N,{code:"CLI_UNRESOLVABLE"});throw N}const m=(0,k.createCrewxChildInvocation)(l,{baseEnv:_});const h=(0,k.resolveWindowsSpawnProgram)({command:m.command,env:m.env,cwd:f,packageName:"crewx",allowShellFallback:true});const E=(0,k.materializeWindowsSpawnProgram)(h,[...m.args,...C]);y=(0,b.spawn)(E.command,E.argv,{cwd:f,stdio:"ignore",windowsHide:E.windowsHide,detached:true,env:m.env,shell:E.shell??false})}await new Promise((l,m)=>{y.once("spawn",()=>l());y.once("error",h=>m(h))})}catch(l){const m=l;console.error(`[${g()}] Schedule ${e.id} failed to spawn: ${m.message}`);s();throw m}if(a&&y.pid){const l=yn(a,y.pid,Oe(y.pid));if(!l){const m=new Error("Cron execution lease was replaced before child ownership was established");console.error(`[${g()}] Schedule ${e.id} failed to hand off its execution lease: ${m.message}`);try{y.kill("SIGTERM")}catch{}s();throw m}}y.unref();const v=new Promise(l=>{let m=false;let h=false;let E;const N=setTimeout(()=>{m=true;console.log(`[${g()}] Schedule ${e.id} timeout, killing process`);try{y.kill("SIGTERM")}catch($){const Q=$;console.error(`Failed to kill process: ${Q.message}`)}E=setTimeout(()=>{try{y.kill("SIGKILL")}catch{}},ye);if(typeof E==="object"&&E!==null&&"unref"in E){E.unref()}if(!h){h=true;l({success:false,error:"Timeout"})}},c);y.on("close",$=>{clearTimeout(N);if(E)clearTimeout(E);s();const Q=new Date().toISOString();const Ae=m?"timeout":$===0?"success":"failure";try{D(r).recordFinished(e.id,{finishedAt:Q,outcome:Ae})}catch(ee){const Fe=ee;if(!(ee instanceof L.CronStoreError&&ee.code==="CRON_SCHEDULE_NOT_FOUND")){console.error(`[${g()}] Failed to record schedule ${e.id} completion: ${Fe.message}`)}}if(m){console.log(`[${g()}] Schedule ${e.id} terminated after timeout`);if(!h){h=true;l({success:false,error:"Timeout"})}}else if($===0){console.log(`[${g()}] Schedule ${e.id} completed successfully`);if(!h){h=true;l({success:true})}}else{console.log(`[${g()}] Schedule ${e.id} failed with code ${$}`);if(!h){h=true;l({success:false,error:`Exit code: ${$}`})}}});y.on("error",$=>{clearTimeout(N);console.error(`[${g()}] Schedule ${e.id} error: ${$.message}`);if(!h){h=true;l({success:false,error:$.message})}})});return{status:"running",taskId:i,done:v}}function Re(e,n){if(!n||!K(n)){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")} ${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`}const t=new Intl.DateTimeFormat("en-CA",{timeZone:n,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:false});return t.format(e)}function Ne(e,n){return`${e.trim()}|${n}`}async function le(e){if((0,k.isDurablyQuiescing)()){console.log(`[${g()}] Daemon tick skipped: a desktop update is draining active work`);return}const n=new Date;const t=D(e??p).list();const r=t.filter(o=>o.enabled);if(r.length===0){return}for(const o of r){if(ke(o.cron,n,o.timezone)){const c=Re(n,o.timezone);const i=Ne(o.cron,c);try{await Pe(o,{dir:e,occurrenceKey:i})}catch(a){const s=a;console.error(`[${g()}] Schedule ${o.id} failed to spawn: ${s.message}`)}}}}var be=require("./runtime");Object.defineProperty(exports,"createCronRuntime",{enumerable:true,get:function(){return be.createCronRuntime}});Object.defineProperty(exports,"CRON_RUNTIME_PROCESS_LEASE_FILENAME",{enumerable:true,get:function(){return be.CRON_RUNTIME_PROCESS_LEASE_FILENAME}});function $n(e){De(process.pid,e);let n=false;const t=()=>{if(n)return;n=true;const c=x(e);if(c===process.pid){V(e)}};process.on("SIGTERM",()=>{t();process.exit(0)});process.on("SIGINT",()=>{t();process.exit(0)});process.on("exit",t);console.log(`[${g()}] Cron daemon starting in foreground mode`);console.log(`[${g()}] Check interval: 1 minute`);console.log(`[${g()}] Press Ctrl+C to stop
|
|
4
|
+
`);const r=D(e??p).list();const o=r.filter(c=>c.enabled).length;console.log(`[${g()}] Active schedules: ${o}/${r.length}
|
|
5
|
+
`);void le(e);setInterval(()=>{void le(e)},Je)}function Ln(e,n,t,r){if(t.timezone&&!K(t.timezone)){throw new Error(`Invalid timezone: ${t.timezone}`)}we(n);const o={id:(0,k.generateId)("cron"),cron:e,command:n,mode:oe(t.mode??"execute"),enabled:true,name:t.name??null,working_directory:t.dir??null,timezone:t.timezone??null,timeout_ms:parseInt(t.timeout??"600000",10),allow_concurrent:t.allowConcurrent??false,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),run_count:0};if(t.model){o.model=t.model}if(t.provider){o.provider=t.provider}o.next_run=j(e,o.timezone);return D(r??p).create(o)}function Pn(e,n){const t=D(n??p).remove(e);const r=(0,A.findBuiltinByName)(t.name);if(r){sn(r.builtin_id,n)}return t}function Rn(e,n){return D(n??p).toggle(e,true)}function Nn(e,n){return D(n??p).toggle(e,false)}function bn(e,n,t){if(n.timezone!==void 0&&n.timezone!==null&&!K(n.timezone)){throw new Error(`Invalid timezone: ${n.timezone}`)}const r=D(t??p);const o=r.get(e);if(!o){throw new Error(`Schedule not found: ${e}`)}const c=[];const i={};if(n.cron!==void 0){i.cron=n.cron;c.push(`cron: ${n.cron}`)}if(n.command!==void 0){we(n.command);i.command=n.command;c.push(`command: ${n.command}`)}if(n.name!==void 0){i.name=n.name;c.push(`name: ${n.name}`)}if(n.mode!==void 0){i.mode=oe(n.mode);c.push(`mode: ${i.mode}`)}if(n.timezone!==void 0){i.timezone=n.timezone;c.push(`timezone: ${n.timezone}`)}if(n.working_directory!==void 0){i.working_directory=n.working_directory;c.push(`working_directory: ${n.working_directory}`)}if(n.timeout_ms!==void 0){i.timeout_ms=n.timeout_ms;c.push(`timeout: ${n.timeout_ms}ms`)}if(n.allow_concurrent!==void 0){i.allow_concurrent=n.allow_concurrent;c.push(`allow_concurrent: ${n.allow_concurrent}`)}if(n.model!==void 0){if(n.model===null){i.model=null;c.push("model: (cleared, reverts to agent default)")}else{i.model=n.model;c.push(`model: ${n.model}`)}}if(n.provider!==void 0){if(n.provider===null){i.provider=null;c.push("provider: (cleared, reverts to agent default)")}else{i.provider=n.provider;c.push(`provider: ${n.provider}`)}}return{schedule:r.update(o.id,i),changes:c}}exports.DATA_PATHS={DATA_DIR:F,SCHEDULES_FILE:je,LOG_FILE:xe,LOCK_FILE:ze,USAGE_LOG_FILE:Be,PID_FILE:He,BUILTINS_META_FILE:Ke};
|