opencode-windows-scheduler 1.1.0 → 1.2.0

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.
Files changed (84) hide show
  1. package/CHANGELOG.md +45 -1
  2. package/README.md +13 -3
  3. package/README.ru.md +13 -3
  4. package/ROADMAP.md +20 -13
  5. package/dist/core/analytics.d.ts +10 -0
  6. package/dist/core/analytics.d.ts.map +1 -1
  7. package/dist/core/analytics.js +21 -0
  8. package/dist/core/dry-run.d.ts +13 -0
  9. package/dist/core/dry-run.d.ts.map +1 -1
  10. package/dist/core/dry-run.js +30 -0
  11. package/dist/core/matrix.d.ts.map +1 -1
  12. package/dist/core/matrix.js +10 -0
  13. package/dist/core/ps-wrapper.d.ts +32 -2
  14. package/dist/core/ps-wrapper.d.ts.map +1 -1
  15. package/dist/core/ps-wrapper.js +101 -3
  16. package/dist/core/schedule-gate.d.ts +2 -0
  17. package/dist/core/schedule-gate.d.ts.map +1 -0
  18. package/dist/core/schedule-gate.js +182 -0
  19. package/dist/core/schedule-v2.d.ts +88 -0
  20. package/dist/core/schedule-v2.d.ts.map +1 -0
  21. package/dist/core/schedule-v2.js +496 -0
  22. package/dist/core/scheduler/types.d.ts +15 -0
  23. package/dist/core/scheduler/types.d.ts.map +1 -1
  24. package/dist/core/scheduler/windows.d.ts.map +1 -1
  25. package/dist/core/scheduler/windows.js +13 -1
  26. package/dist/core/wrappers/bash.d.ts +15 -0
  27. package/dist/core/wrappers/bash.d.ts.map +1 -1
  28. package/dist/core/wrappers/bash.js +44 -1
  29. package/dist/db/history-repo.d.ts +8 -0
  30. package/dist/db/history-repo.d.ts.map +1 -1
  31. package/dist/db/history-repo.js +13 -0
  32. package/dist/db/schema.d.ts +1 -1
  33. package/dist/db/schema.d.ts.map +1 -1
  34. package/dist/db/schema.js +11 -0
  35. package/dist/index.d.ts +117 -0
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +1010 -54
  38. package/dist/notifications.d.ts +112 -6
  39. package/dist/notifications.d.ts.map +1 -1
  40. package/dist/notifications.js +396 -34
  41. package/dist/profiles.d.ts +60 -0
  42. package/dist/profiles.d.ts.map +1 -0
  43. package/dist/profiles.js +209 -0
  44. package/dist/rpc.d.ts +511 -0
  45. package/dist/rpc.d.ts.map +1 -1
  46. package/dist/rpc.js +190 -2
  47. package/dist/server.d.ts.map +1 -1
  48. package/dist/server.js +5 -2
  49. package/dist/settings.d.ts +57 -0
  50. package/dist/settings.d.ts.map +1 -1
  51. package/dist/settings.js +118 -8
  52. package/dist/task-transfer.d.ts +13 -0
  53. package/dist/task-transfer.d.ts.map +1 -1
  54. package/dist/task-transfer.js +26 -0
  55. package/dist/types.d.ts.map +1 -1
  56. package/dist/types.js +3 -11
  57. package/dist/workspaces.d.ts +43 -0
  58. package/dist/workspaces.d.ts.map +1 -1
  59. package/dist/workspaces.js +174 -8
  60. package/docs/ARCHITECTURE.md +32 -12
  61. package/docs/FEATURES.md +86 -7
  62. package/gui-experimental.cjs +4 -2
  63. package/package.json +6 -2
  64. package/src/core/analytics.ts +36 -0
  65. package/src/core/dry-run.ts +42 -0
  66. package/src/core/matrix.ts +10 -0
  67. package/src/core/ps-wrapper.ts +117 -3
  68. package/src/core/schedule-gate.ts +213 -0
  69. package/src/core/schedule-v2.ts +533 -0
  70. package/src/core/scheduler/types.ts +15 -0
  71. package/src/core/scheduler/windows.ts +13 -1
  72. package/src/core/wrappers/bash.ts +60 -0
  73. package/src/db/history-repo.ts +23 -0
  74. package/src/db/schema.ts +14 -0
  75. package/src/gui.tsx +767 -22
  76. package/src/index.ts +1226 -52
  77. package/src/notifications.ts +516 -40
  78. package/src/profiles.ts +236 -0
  79. package/src/rpc.ts +201 -2
  80. package/src/server.ts +5 -2
  81. package/src/settings.ts +214 -9
  82. package/src/task-transfer.ts +44 -0
  83. package/src/types.ts +3 -13
  84. package/src/workspaces.ts +214 -8
@@ -0,0 +1,533 @@
1
+ /**
2
+ * Расширенный cron и окна запуска (Спринт 19).
3
+ *
4
+ * Два режима регистрации в ОС:
5
+ * - «родной» (флаги schtasks / строки crontab / plist launchd) — только для
6
+ * простых выражений и системной таймзоны;
7
+ * - «опрос раз в минуту» (MINUTE /mo 1 + node-gate в обёртке) — для всего
8
+ * остального (timezone != system, списки, L, #, комбинации). Обёртка
9
+ * вызывает dist/core/schedule-gate.js, который сам решает, пора ли запускать.
10
+ *
11
+ * Здесь живёт только чистая математика: парсинг, совпадение, ближайший запуск.
12
+ * Никакого I/O и обращения к ОС.
13
+ */
14
+ import { convertCronToSchTasks } from "./cron-to-schtasks.js";
15
+ import type { CronConversion } from "../types.js";
16
+
17
+ /** Ограничение на поиск ближайшего запуска. */
18
+ const MAX_SEARCH_DAYS = 5 * 366;
19
+
20
+ const MONTH_NAMES: Record<string, number> = {
21
+ JAN: 1, FEB: 2, MAR: 3, APR: 4, MAY: 5, JUN: 6,
22
+ JUL: 7, AUG: 8, SEP: 9, OCT: 10, NOV: 11, DEC: 12,
23
+ };
24
+ const DOW_NAMES: Record<string, number> = {
25
+ SUN: 0, MON: 1, TUE: 2, WED: 3, THU: 4, FRI: 5, SAT: 6,
26
+ };
27
+
28
+ export interface ZonedParts {
29
+ year: number; month: number; day: number;
30
+ hour: number; minute: number; second: number; ms: number;
31
+ weekday: number; // 0=Вс..6=Сб
32
+ }
33
+
34
+ /** Кэш форматтеров Intl по таймзоне (создание Intl.DateTimeFormat недёшево). */
35
+ const dtfCache = new Map<string, Intl.DateTimeFormat>();
36
+
37
+ function getDtf(timeZone: string): Intl.DateTimeFormat {
38
+ const cached = dtfCache.get(timeZone);
39
+ if (cached) return cached;
40
+ // hourCycle h23: 00..23, без «24».
41
+ const dtf = new Intl.DateTimeFormat("en-US", {
42
+ timeZone,
43
+ year: "numeric", month: "numeric", day: "numeric",
44
+ hour: "numeric", minute: "numeric", second: "numeric",
45
+ hourCycle: "h23",
46
+ });
47
+ dtfCache.set(timeZone, dtf);
48
+ return dtf;
49
+ }
50
+
51
+ export function isValidIanaTimeZone(tz: string): boolean {
52
+ const t = (tz || "").trim();
53
+ if (!t) return false;
54
+ try {
55
+ new Intl.DateTimeFormat("en-US", { timeZone: t });
56
+ return true;
57
+ } catch {
58
+ return false;
59
+ }
60
+ }
61
+
62
+ /** Системная таймзона (IANA) или "UTC", если её не удалось определить. */
63
+ export function systemTimeZone(): string {
64
+ try {
65
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
66
+ } catch {
67
+ return "UTC";
68
+ }
69
+ }
70
+
71
+ /** Части даты в заданной инстанции (или в системной локали, если tz не задан). */
72
+ export function zonedParts(date: Date, timeZone?: string): ZonedParts {
73
+ if (timeZone && timeZone !== Intl.DateTimeFormat().resolvedOptions().timeZone) {
74
+ const parts = getDtf(timeZone).formatToParts(date);
75
+ const bag: Record<string, number> = {};
76
+ for (const p of parts) {
77
+ if (p.type === "year" || p.type === "month" || p.type === "day"
78
+ || p.type === "hour" || p.type === "minute" || p.type === "second") {
79
+ bag[p.type] = Number(p.value);
80
+ }
81
+ }
82
+ const asUtc = new Date(Date.UTC(bag.year, bag.month - 1, bag.day));
83
+ return {
84
+ year: bag.year, month: bag.month, day: bag.day,
85
+ hour: bag.hour, minute: bag.minute, second: bag.second, ms: date.getUTCMilliseconds(),
86
+ weekday: asUtc.getUTCDay(),
87
+ };
88
+ }
89
+ return {
90
+ year: date.getFullYear(), month: date.getMonth() + 1, day: date.getDate(),
91
+ hour: date.getHours(), minute: date.getMinutes(), second: date.getSeconds(),
92
+ ms: date.getMilliseconds(), weekday: date.getDay(),
93
+ };
94
+ }
95
+
96
+ /** Стенные часы → UTC, итеративно учитывая смещение (DST-safe). null — несуществующее время. */
97
+ export function wallToUtc(y: number, m: number, d: number, h: number, mi: number, timeZone?: string): Date | null {
98
+ const tz = timeZone || Intl.DateTimeFormat().resolvedOptions().timeZone;
99
+ const target = Date.UTC(y, m - 1, d, h, mi);
100
+ const matches = (ms: number): boolean => {
101
+ const p = zonedParts(new Date(ms), tz);
102
+ return p.year === y && p.month === m && p.day === d && p.hour === h && p.minute === mi;
103
+ };
104
+ let guess = target;
105
+ for (let i = 0; i < 4; i += 1) {
106
+ const p = zonedParts(new Date(guess), tz);
107
+ const actual = Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute);
108
+ const delta = target - actual;
109
+ if (delta === 0) break;
110
+ guess += delta;
111
+ }
112
+ // При переходе на зимнее время настенное время существует дважды. Для
113
+ // «следующего запуска» берём ПЕРВОЕ (более раннее) вхождение, а не то, к
114
+ // которому сошлась итерация. Обычно совпадение одно, тогда результат тот же.
115
+ const probes = [0, -30, 30, -60, 60, -90, 90, -120, 120].map(
116
+ (minutes) => guess + minutes * 60_000
117
+ );
118
+ let best: number | null = null;
119
+ for (const ms of probes) {
120
+ if (!matches(ms)) continue;
121
+ if (best === null || ms < best) best = ms;
122
+ }
123
+ return best === null ? null : new Date(best);
124
+ }
125
+
126
+ function lastDayOfMonth(y: number, m: number): number {
127
+ return new Date(Date.UTC(y, m, 0)).getUTCDate();
128
+ }
129
+
130
+ function nthWeekdayOfMonth(y: number, m: number, weekday: number, n: number): number | null {
131
+ const firstDow = new Date(Date.UTC(y, m - 1, 1)).getUTCDay();
132
+ const first = 1 + ((weekday - firstDow + 7) % 7);
133
+ const dom = first + 7 * (n - 1);
134
+ return dom <= lastDayOfMonth(y, m) ? dom : null;
135
+ }
136
+
137
+ function expandField(token: string, min: number, max: number, names?: Record<string, number>): Set<number> {
138
+ const result = new Set<number>();
139
+ const items = token.split(",");
140
+ for (const raw of items) {
141
+ let item = raw.trim().toUpperCase();
142
+ if (!item) throw new Error(`Пустой элемент в списке «${token}».`);
143
+ if (names && names[item] !== undefined) item = String(names[item]);
144
+ // шаг: a-b/n или */n
145
+ const stepMatch = item.match(/^(.*)\/([0-9]+)$/);
146
+ let step = 1;
147
+ if (stepMatch) {
148
+ item = (stepMatch[1] ?? "").trim();
149
+ step = Number(stepMatch[2]);
150
+ if (!Number.isInteger(step) || step < 1) {
151
+ throw new Error(`Недопустимый шаг «/${stepMatch[2]}» в «${raw}».`);
152
+ }
153
+ if (item === "") throw new Error(`Некорректный шаг в «${raw}»: перед «/» ничего нет.`);
154
+ }
155
+ if (item === "*" || item === "") {
156
+ for (let v = min; v <= max; v += step) result.add(v);
157
+ continue;
158
+ }
159
+ const rangeMatch = item.match(/^([0-9A-Z]+)-([0-9A-Z]+)$/);
160
+ if (rangeMatch) {
161
+ let aToken = rangeMatch[1];
162
+ let bToken = rangeMatch[2];
163
+ if (names && names[aToken] !== undefined) aToken = String(names[aToken]);
164
+ if (names && names[bToken] !== undefined) bToken = String(names[bToken]);
165
+ const a = Number(aToken);
166
+ const b = Number(bToken);
167
+ if (!Number.isFinite(a) || !Number.isFinite(b)) {
168
+ throw new Error(`Недопустимый диапазон «${item}».`);
169
+ }
170
+ if (a < min || b > max || a > b) {
171
+ throw new Error(`Диапазон «${item}» вне границ ${min}..${max}.`);
172
+ }
173
+ for (let v = a; v <= b; v += step) result.add(v);
174
+ continue;
175
+ }
176
+ const num = Number(item);
177
+ if (!Number.isInteger(num) || num < min || num > max) {
178
+ throw new Error(`Значение «${raw}» вне границ ${min}..${max}.`);
179
+ }
180
+ result.add(num);
181
+ }
182
+ return result;
183
+ }
184
+
185
+ export interface ParsedCron {
186
+ /** Исходное выражение (после расширения @every). */
187
+ raw: string;
188
+ minute: Set<number>;
189
+ hour: Set<number>;
190
+ /** Дни месяца или null, если поле = «*» и не содержит L. */
191
+ dayOfMonth: Set<number> | null;
192
+ /** true — поле содержит «L» (последний день месяца). */
193
+ lastDom: boolean;
194
+ month: Set<number>;
195
+ /** День недели 0(Вс)..6(Сб) или null, если поле = «*» и не содержит «#». */
196
+ dayOfWeek: Set<number> | null;
197
+ /** Пары {weekday, n} для «#». */
198
+ nthWeekday: Array<{ weekday: number; n: number }>;
199
+ }
200
+
201
+ /** Разворачивает «@every 15m|2h|1d» в обычный cron. */
202
+ export function normalizeCron(expr: string): string {
203
+ const trimmed = expr.trim();
204
+ const match = trimmed.match(/^@every\s+(\d+)([mhd])$/i);
205
+ if (!match) return trimmed;
206
+ const n = Number(match[1]);
207
+ const unit = match[2].toLowerCase();
208
+ if (unit === "m" && n >= 1 && n < 60) return `*/${n} * * * *`;
209
+ if (unit === "h" && n >= 1 && n <= 23) return `0 */${n} * * *`;
210
+ if (unit === "d" && n >= 1 && n <= 31) return `0 0 */${n} * *`;
211
+ throw new Error(`Неподдерживаемый интервал «@every ${n}${unit}» (m: 1..59, h: 1..23, d: 1..31).`);
212
+ }
213
+
214
+ /** Парсит cron-выражение; бросает Error с понятным сообщением. */
215
+ export function parseCron(expr: string): ParsedCron {
216
+ const raw = normalizeCron(expr);
217
+ const fields = raw.split(/\s+/);
218
+ if (fields.length !== 5) {
219
+ throw new Error(`Ожидается 5 полей cron, получено ${fields.length}: «${raw}».`);
220
+ }
221
+ const [minF, hourF, domF, monthF, dowF] = fields;
222
+
223
+ const minute = expandField(minF, 0, 59);
224
+ const hour = expandField(hourF, 0, 23);
225
+ const month = expandField(monthF, 1, 12, MONTH_NAMES);
226
+
227
+ // dom: «*» + опциональный «L» в списке (например «15,L»).
228
+ let dayOfMonth: Set<number> | null = null;
229
+ let lastDom = false;
230
+ {
231
+ const tokens = domF.trim().toUpperCase().split(",").map((s) => s.trim());
232
+ const kept: string[] = [];
233
+ for (const token of tokens) {
234
+ if (token === "L") { lastDom = true; continue; }
235
+ kept.push(token);
236
+ }
237
+ if (domF.trim() !== "*") {
238
+ dayOfMonth = kept.length > 0 ? expandField(kept.join(","), 1, 31) : new Set();
239
+ }
240
+ }
241
+
242
+ // dow: «*» + имена + «d#n».
243
+ let dayOfWeek: Set<number> | null = null;
244
+ const nthWeekday: Array<{ weekday: number; n: number }> = [];
245
+ {
246
+ const tokens = dowF.trim().toUpperCase().split(",").map((s) => s.trim());
247
+ const kept: string[] = [];
248
+ for (const token of tokens) {
249
+ const hash = token.match(/^([0-9A-Z]+)#([1-5])$/);
250
+ if (hash) {
251
+ let dToken = hash[1];
252
+ if (DOW_NAMES[dToken] !== undefined) dToken = String(DOW_NAMES[dToken]);
253
+ const weekday = Number(dToken);
254
+ if (!Number.isInteger(weekday) || weekday < 0 || weekday > 7) {
255
+ throw new Error(`День недели «${hash[1]}» вне границ 0..7 в «${dowF}».`);
256
+ }
257
+ nthWeekday.push({ weekday: weekday % 7, n: Number(hash[2]) });
258
+ continue;
259
+ }
260
+ if (token === "L") {
261
+ throw new Error("«L» поддерживается только в поле дня месяца.");
262
+ }
263
+ kept.push(token);
264
+ }
265
+ if (dowF.trim() !== "*") {
266
+ dayOfWeek = kept.length > 0 ? expandField(kept.join(","), 0, 7, DOW_NAMES) : new Set();
267
+ // 0 и 7 — оба воскресенье.
268
+ const mapped = new Set<number>();
269
+ for (const d of dayOfWeek) mapped.add(d % 7);
270
+ dayOfWeek = mapped;
271
+ }
272
+ }
273
+
274
+ return { raw, minute, hour, dayOfMonth, lastDom, month, dayOfWeek, nthWeekday };
275
+ }
276
+
277
+ function domMatches(p: { year: number; month: number; day: number }, spec: ParsedCron): boolean {
278
+ const last = lastDayOfMonth(p.year, p.month);
279
+ if (spec.dayOfMonth && spec.dayOfMonth.has(p.day)) return true;
280
+ if (spec.lastDom && p.day === last) return true;
281
+ return false;
282
+ }
283
+
284
+ function dowMatches(p: { year: number; month: number; day: number; weekday: number }, spec: ParsedCron): boolean {
285
+ if (spec.dayOfWeek && spec.dayOfWeek.has(p.weekday)) return true;
286
+ for (const { weekday, n } of spec.nthWeekday) {
287
+ const dom = nthWeekdayOfMonth(p.year, p.month, weekday, n);
288
+ if (dom === p.day) return true;
289
+ }
290
+ return false;
291
+ }
292
+
293
+ /** true, если cron срабатывает в указанную минуту (в системной или заданной tz). */
294
+ export function cronMatches(spec: ParsedCron, date: Date, timeZone?: string): boolean {
295
+ const p = zonedParts(date, timeZone);
296
+ if (!spec.minute.has(p.minute)) return false;
297
+ if (!spec.hour.has(p.hour)) return false;
298
+ if (!spec.month.has(p.month)) return false;
299
+ const domAny = spec.dayOfMonth === null && !spec.lastDom;
300
+ const dowAny = spec.dayOfWeek === null && spec.nthWeekday.length === 0;
301
+ const dm = domMatches(p, spec);
302
+ const dw = dowMatches(p, spec);
303
+ // Vixie OR-семантика: обе группы ограничены — достаточно совпадения одной.
304
+ if (domAny && dowAny) return true;
305
+ if (domAny) return dw;
306
+ if (dowAny) return dm;
307
+ return dm || dw;
308
+ }
309
+
310
+ function iterateDay(p: { year: number; month: number; day: number }, delta: 1 | -1): { year: number; month: number; day: number } {
311
+ const d = new Date(Date.UTC(p.year, p.month - 1, p.day + delta));
312
+ return { year: d.getUTCFullYear(), month: d.getUTCMonth() + 1, day: d.getUTCDate() };
313
+ }
314
+
315
+ function candidatesOnDay(
316
+ spec: ParsedCron,
317
+ y: number,
318
+ m: number,
319
+ d: number,
320
+ notBefore: { hour: number; minute: number } | null,
321
+ notAfter: { hour: number; minute: number } | null,
322
+ ): Array<{ hour: number; minute: number }> {
323
+ const hours = [...spec.hour].sort((a, b) => a - b);
324
+ const minutes = [...spec.minute].sort((a, b) => a - b);
325
+ const result: Array<{ hour: number; minute: number }> = [];
326
+ for (const hour of hours) {
327
+ for (const minute of minutes) {
328
+ if (notBefore && notAfter) {
329
+ if (hour < notBefore.hour || (hour === notBefore.hour && minute < notBefore.minute)) continue;
330
+ }
331
+ if (notAfter) {
332
+ if (hour > notAfter.hour || (hour === notAfter.hour && minute > notAfter.minute)) continue;
333
+ }
334
+ result.push({ hour, minute });
335
+ }
336
+ }
337
+ return result;
338
+ }
339
+
340
+ /**
341
+ * Ближайший запуск после `from` (или null, если найти не удалось за 5 лет).
342
+ * `timeZone` — IANA; по умолчанию системная.
343
+ */
344
+ export function nextRun(expr: string, from: Date, timeZone?: string): Date | null {
345
+ const spec = parseCron(expr);
346
+ const base = from.getTime();
347
+ const origin = zonedParts(from, timeZone);
348
+ let cursor = { year: origin.year, month: origin.month, day: origin.day };
349
+ // Не считать время дня на первом дне: только строго после from.
350
+ let firstDay = true;
351
+ for (let i = 0; i < MAX_SEARCH_DAYS; i += 1) {
352
+ if (dayMatches(cursor.year, cursor.month, cursor.day, spec)) {
353
+ const nb = firstDay
354
+ ? { hour: origin.hour, minute: origin.minute + 1 } // строго позже минуты from
355
+ : null;
356
+ const candidates = candidatesOnDay(spec, cursor.year, cursor.month, cursor.day, nb, null);
357
+ for (const cand of candidates) {
358
+ const at = wallToUtc(cursor.year, cursor.month, cursor.day, cand.hour, cand.minute, timeZone);
359
+ if (at && at.getTime() > base) return at;
360
+ }
361
+ }
362
+ firstDay = false;
363
+ cursor = iterateDay(cursor, 1);
364
+ }
365
+ return null;
366
+ }
367
+
368
+ /** Последний запуск не позже `from` (или null). */
369
+ export function prevRun(expr: string, from: Date, timeZone?: string): Date | null {
370
+ const spec = parseCron(expr);
371
+ const base = from.getTime();
372
+ const origin = zonedParts(from, timeZone);
373
+ let cursor = { year: origin.year, month: origin.month, day: origin.day };
374
+ let firstDay = true;
375
+ for (let i = 0; i < MAX_SEARCH_DAYS; i += 1) {
376
+ if (dayMatches(cursor.year, cursor.month, cursor.day, spec)) {
377
+ const na = firstDay
378
+ ? { hour: origin.hour, minute: origin.minute } // включая текущую минуту
379
+ : null;
380
+ const candidates = candidatesOnDay(spec, cursor.year, cursor.month, cursor.day, null, na);
381
+ for (let i2 = candidates.length - 1; i2 >= 0; i2 -= 1) {
382
+ const cand = candidates[i2];
383
+ const at = wallToUtc(cursor.year, cursor.month, cursor.day, cand.hour, cand.minute, timeZone);
384
+ if (at && at.getTime() <= base) return at;
385
+ }
386
+ }
387
+ firstDay = false;
388
+ cursor = iterateDay(cursor, -1);
389
+ }
390
+ return null;
391
+ }
392
+
393
+ function dayMatches(y: number, m: number, d: number, spec: ParsedCron): boolean {
394
+ if (!spec.month.has(m)) return false;
395
+ const domAny = spec.dayOfMonth === null && !spec.lastDom;
396
+ const date = new Date(Date.UTC(y, m - 1, d));
397
+ const weekday = date.getUTCDay();
398
+ const p = { year: y, month: m, day: d, weekday };
399
+ if (domAny && spec.dayOfWeek === null && spec.nthWeekday.length === 0) return true;
400
+ const dm = domMatches({ year: y, month: m, day: d }, spec);
401
+ const dw = dowMatches(p, spec);
402
+ const dowAny = spec.dayOfWeek === null && spec.nthWeekday.length === 0;
403
+ if (domAny) return dw;
404
+ if (dowAny) return dm;
405
+ return dm || dw;
406
+ }
407
+
408
+ function dayStartUtc(y: number, m: number, d: number, timeZone?: string): Date {
409
+ const d0 = wallToUtc(y, m, d, 0, 0, timeZone);
410
+ return d0 ?? new Date(Date.UTC(y, m - 1, d, 0, 0));
411
+ }
412
+
413
+
414
+ // ---------------------------------------------------------------------------
415
+ // Окна запуска (notBefore/notAfter, «дд:мм» 24ч, можно через полночь).
416
+
417
+ const DAILY_TIME_RE = /^([01]\d|2[0-3]):[0-5]\d$/;
418
+
419
+ export function isValidDailyTime(value: string): boolean {
420
+ return DAILY_TIME_RE.test((value || "").trim());
421
+ }
422
+
423
+ function dailyTimeToMinutes(value: string): number {
424
+ const [h, m] = value.trim().split(":").map(Number);
425
+ return h * 60 + m;
426
+ }
427
+
428
+ /** Проверяет пару окна; возвращает текст ошибки или null. */
429
+ export function validateLaunchWindow(notBefore?: string | null, notAfter?: string | null): string | null {
430
+ if (notBefore === undefined && notAfter === undefined) return null;
431
+ const nb = notBefore?.trim() ?? "";
432
+ const na = notAfter?.trim() ?? "";
433
+ if (!nb && !na) return null;
434
+ if (nb && !isValidDailyTime(nb)) return `notBefore должен быть в формате HH:MM, не "${nb}".`;
435
+ if (na && !isValidDailyTime(na)) return `notAfter должен быть в формате HH:MM, не "${na}".`;
436
+ if (!nb || !na) return "notBefore и notAfter задаются вместе.";
437
+ if (nb === na) return "notBefore и notAfter не могут совпадать (пустое окно).";
438
+ return null;
439
+ }
440
+
441
+ function wallMinutes(date: Date, timeZone?: string): { minutes: number; seconds: number; ms: number } {
442
+ const p = zonedParts(date, timeZone);
443
+ return { minutes: p.hour * 60 + p.minute, seconds: p.second, ms: p.ms };
444
+ }
445
+
446
+ /** Мы внутри окна запуска? */
447
+ export function isInWindow(now: Date, notBefore?: string | null, notAfter?: string | null, timeZone?: string): boolean {
448
+ if (validateLaunchWindow(notBefore, notAfter) !== null) return true; // невалидное окно не должно блокировать
449
+ if (!notBefore?.trim() && !notAfter?.trim()) return true;
450
+ const start = dailyTimeToMinutes(notBefore as string);
451
+ const end = dailyTimeToMinutes(notAfter as string);
452
+ const { minutes } = wallMinutes(now, timeZone);
453
+ if (start < end) return minutes >= start && minutes < end;
454
+ return minutes >= start || minutes < end; // через полночь
455
+ }
456
+
457
+ /** Сколько мс ждать до открытия окна (0 — уже открыто / окно не задано). */
458
+ export function windowDelayMs(now: Date, notBefore?: string | null, notAfter?: string | null, timeZone?: string): number {
459
+ if (validateLaunchWindow(notBefore, notAfter) !== null) return 0;
460
+ if (!notBefore?.trim() && !notAfter?.trim()) return 0;
461
+ if (isInWindow(now, notBefore, notAfter, timeZone)) return 0;
462
+ const start = dailyTimeToMinutes(notBefore as string);
463
+ const { minutes, seconds, ms } = wallMinutes(now, timeZone);
464
+ const deltaMin = (start - minutes + 1440) % 1440;
465
+ const deltaSec = deltaMin * 60 - seconds;
466
+ return Math.max(0, deltaSec * 1000 - ms);
467
+ }
468
+
469
+ // ---------------------------------------------------------------------------
470
+ // Проверка совместимости с schtasks (родной режим).
471
+
472
+ /**
473
+ * true, если выражение умеет оформить Windows Task Scheduler «родными»
474
+ * флагами (MINUTE/HOURLY/DAILY/WEEKLY) и парсится строгим конвертером.
475
+ * Используется для выбора между флагами и минутным опросом.
476
+ */
477
+ export function isNativeSchtasksExpr(expr: string): boolean {
478
+ try {
479
+ convertCronToSchTasks(normalizeCron(expr));
480
+ return true;
481
+ } catch {
482
+ return false;
483
+ }
484
+ }
485
+
486
+ /** Конвертер для родного режима; бросает Error для неподдерживаемых. */
487
+ export function convertForSchtasks(expr: string): CronConversion {
488
+ return convertCronToSchTasks(normalizeCron(expr));
489
+ }
490
+
491
+ // ---------------------------------------------------------------------------
492
+ // Политика планирования одной задачи (общий код для Windows-бека и index.ts).
493
+
494
+ /** Аргументы schedule-gate, которые запекаются во враппер (cron/tz/окно/пернос). */
495
+ export interface ScheduleGateSpec {
496
+ /**
497
+ * Cron-выражение для повторной проверки внутри обёртки. Задаётся только в
498
+ * poll-режиме: при родном триггере ОС уже сработала точно по cron, и повторная
499
+ * проверка ломала бы ручной запуск и catch-up.
500
+ */
501
+ cron?: string;
502
+ tz?: string;
503
+ notBefore?: string;
504
+ notAfter?: string;
505
+ }
506
+
507
+ /**
508
+ * true, если ОС-триггер не выражает расписание (чужой IANA-таймзона или
509
+ * не конвертируемо в флаги schtasks) — нужен минутный опрос + gate.
510
+ */
511
+ export function needsPollMode(expr: string, timezone?: string | null): boolean {
512
+ const tz = (timezone || "").trim();
513
+ if (tz && tz !== systemTimeZone()) return true;
514
+ return !isNativeSchtasksExpr(expr);
515
+ }
516
+
517
+ /**
518
+ * Аргументы schedule-gate для враппера, либо undefined — если врапперу гейт
519
+ * не нужен (нативный cron + системный таймзона + окно не задано).
520
+ * Окно запуска всегда требует gate (перенос реализует враппер).
521
+ */
522
+ export function buildScheduleGate(
523
+ expr: string,
524
+ timezone?: string | null,
525
+ notBefore?: string,
526
+ notAfter?: string
527
+ ): ScheduleGateSpec | undefined {
528
+ const tz = (timezone || "").trim() || undefined;
529
+ const poll = needsPollMode(expr, tz);
530
+ if (!poll && !(notBefore && notAfter)) return undefined;
531
+ // cron проверяем только в poll-режиме (см. комментарий у ScheduleGateSpec).
532
+ return { ...(poll ? { cron: expr } : {}), tz, notBefore, notAfter };
533
+ }
@@ -30,6 +30,21 @@ export interface CreateTaskOptions {
30
30
  model?: string;
31
31
  /** Приоритет задачи 0..10 (хранится в реестре для диагностики). */
32
32
  priority?: number;
33
+ /** IANA-таймзона задачи (например, "Europe/Moscow"). undefined — системная. */
34
+ timezone?: string;
35
+ /** Окно запуска «не раньше» (HH:MM, 24ч). Парно с notAfter. */
36
+ notBefore?: string;
37
+ /** Окно запуска «не позже» (HH:MM, 24ч). Парно с notBefore. */
38
+ notAfter?: string;
39
+ /** Аргументы schedule-gate для обёртки (расширенный cron / окно). */
40
+ scheduleGate?: {
41
+ cron?: string;
42
+ tz?: string;
43
+ notBefore?: string;
44
+ notAfter?: string;
45
+ /** Путь к defer-файлу для переноса из окна (lock-файл + .defer). */
46
+ deferFile?: string;
47
+ };
33
48
  }
34
49
 
35
50
  /** Результат немедленного запуска. */
@@ -4,6 +4,7 @@ import iconv from "iconv-lite";
4
4
  import type { ScheduledTaskInfo } from "../../types.js";
5
5
  import { TASK_FOLDER, TASK_FOLDER_NAME } from "../../types.js";
6
6
  import { buildScheduleFlags, convertCronToSchTasks } from "../cron-to-schtasks.js";
7
+ import { needsPollMode } from "../schedule-v2.js";
7
8
  import type {
8
9
  CreateTaskOptions,
9
10
  RunTaskResult,
@@ -136,12 +137,23 @@ export class WindowsScheduler implements SchedulerBackend {
136
137
  const { name, command, schedule, triggerType } = options;
137
138
 
138
139
  let scheduleFlags: string[];
140
+
139
141
  if (triggerType && triggerType !== "cron") {
140
142
  // Файловый или MCP-триггер: однократный запуск в далёком будущем.
141
143
  // Активация — только вручную (runTask / файловый watcher / emit_event).
142
144
  scheduleFlags = ["/sc", "ONCE", "/sd", "31.12.2099", "/st", "00:00"];
143
145
  } else {
144
- scheduleFlags = buildScheduleFlags(convertCronToSchTasks(schedule));
146
+ // Выражения, которые Windows не выражает нативно (список через запятую, L, #,
147
+ // именованные месяцы и т.д.), падают в минутный опрос + gate во враппере.
148
+ const tz = options.timezone?.trim() || null;
149
+ const poll = needsPollMode(schedule, tz);
150
+ if (poll) {
151
+ scheduleFlags = ["/sc", "MINUTE", "/mo", "1"];
152
+ } else {
153
+ // parseCron/валидация УЖЕ выполнена вызывающим кодом перед этим местом.
154
+ const native = convertCronToSchTasks(schedule);
155
+ scheduleFlags = buildScheduleFlags(native);
156
+ }
145
157
  }
146
158
 
147
159
  const fullName = taskFullName(name);