opencode-windows-scheduler 1.1.0 → 1.2.1

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 (144) hide show
  1. package/CHANGELOG.md +60 -1
  2. package/README.md +18 -8
  3. package/README.ru.md +13 -3
  4. package/ROADMAP-STRATEGY.md +2 -2
  5. package/ROADMAP.md +51 -18
  6. package/dist/core/analytics.d.ts +10 -0
  7. package/dist/core/analytics.d.ts.map +1 -1
  8. package/dist/core/analytics.js +21 -0
  9. package/dist/core/dry-run.d.ts +18 -1
  10. package/dist/core/dry-run.d.ts.map +1 -1
  11. package/dist/core/dry-run.js +49 -3
  12. package/dist/core/matrix.d.ts.map +1 -1
  13. package/dist/core/matrix.js +10 -0
  14. package/dist/core/one-shot.d.ts +62 -0
  15. package/dist/core/one-shot.d.ts.map +1 -0
  16. package/dist/core/one-shot.js +126 -0
  17. package/dist/core/otel.d.ts +4 -0
  18. package/dist/core/otel.d.ts.map +1 -0
  19. package/dist/core/otel.js +98 -0
  20. package/dist/core/prometheus.d.ts +23 -0
  21. package/dist/core/prometheus.d.ts.map +1 -0
  22. package/dist/core/prometheus.js +146 -0
  23. package/dist/core/ps-wrapper.d.ts +36 -2
  24. package/dist/core/ps-wrapper.d.ts.map +1 -1
  25. package/dist/core/ps-wrapper.js +124 -4
  26. package/dist/core/record-history.d.ts.map +1 -1
  27. package/dist/core/record-history.js +9 -0
  28. package/dist/core/schedule-gate.d.ts +2 -0
  29. package/dist/core/schedule-gate.d.ts.map +1 -0
  30. package/dist/core/schedule-gate.js +182 -0
  31. package/dist/core/schedule-v2.d.ts +88 -0
  32. package/dist/core/schedule-v2.d.ts.map +1 -0
  33. package/dist/core/schedule-v2.js +496 -0
  34. package/dist/core/scheduler/linux.d.ts +12 -3
  35. package/dist/core/scheduler/linux.d.ts.map +1 -1
  36. package/dist/core/scheduler/linux.js +80 -3
  37. package/dist/core/scheduler/mac.d.ts.map +1 -1
  38. package/dist/core/scheduler/mac.js +17 -3
  39. package/dist/core/scheduler/posix.d.ts.map +1 -1
  40. package/dist/core/scheduler/posix.js +3 -0
  41. package/dist/core/scheduler/registry.d.ts +4 -0
  42. package/dist/core/scheduler/registry.d.ts.map +1 -1
  43. package/dist/core/scheduler/types.d.ts +20 -3
  44. package/dist/core/scheduler/types.d.ts.map +1 -1
  45. package/dist/core/scheduler/windows.d.ts.map +1 -1
  46. package/dist/core/scheduler/windows.js +23 -2
  47. package/dist/core/session.d.ts +34 -0
  48. package/dist/core/session.d.ts.map +1 -0
  49. package/dist/core/session.js +105 -0
  50. package/dist/core/structured-log.d.ts +84 -0
  51. package/dist/core/structured-log.d.ts.map +1 -0
  52. package/dist/core/structured-log.js +137 -0
  53. package/dist/core/wrappers/bash.d.ts +24 -0
  54. package/dist/core/wrappers/bash.d.ts.map +1 -1
  55. package/dist/core/wrappers/bash.js +70 -3
  56. package/dist/db/history-repo.d.ts +8 -0
  57. package/dist/db/history-repo.d.ts.map +1 -1
  58. package/dist/db/history-repo.js +76 -6
  59. package/dist/db/metrics-repo.d.ts +3 -0
  60. package/dist/db/metrics-repo.d.ts.map +1 -1
  61. package/dist/db/metrics-repo.js +16 -8
  62. package/dist/db/migrate.d.ts.map +1 -1
  63. package/dist/db/migrate.js +8 -1
  64. package/dist/db/schema.d.ts +1 -1
  65. package/dist/db/schema.d.ts.map +1 -1
  66. package/dist/db/schema.js +19 -0
  67. package/dist/gui-experimental.cjs +1 -0
  68. package/dist/history.d.ts +7 -0
  69. package/dist/history.d.ts.map +1 -1
  70. package/dist/history.js +13 -0
  71. package/dist/index.d.ts +137 -1
  72. package/dist/index.d.ts.map +1 -1
  73. package/dist/index.js +1323 -78
  74. package/dist/integrations.d.ts +64 -0
  75. package/dist/integrations.d.ts.map +1 -0
  76. package/dist/integrations.js +205 -0
  77. package/dist/notifications.d.ts +112 -6
  78. package/dist/notifications.d.ts.map +1 -1
  79. package/dist/notifications.js +396 -34
  80. package/dist/profiles.d.ts +60 -0
  81. package/dist/profiles.d.ts.map +1 -0
  82. package/dist/profiles.js +209 -0
  83. package/dist/rpc.d.ts +592 -4
  84. package/dist/rpc.d.ts.map +1 -1
  85. package/dist/rpc.js +233 -6
  86. package/dist/server.d.ts +2 -0
  87. package/dist/server.d.ts.map +1 -1
  88. package/dist/server.js +473 -58
  89. package/dist/settings.d.ts +95 -0
  90. package/dist/settings.d.ts.map +1 -1
  91. package/dist/settings.js +186 -8
  92. package/dist/shared/jobs-view.d.ts +43 -5
  93. package/dist/shared/jobs-view.d.ts.map +1 -1
  94. package/dist/shared/jobs-view.js +125 -7
  95. package/dist/task-transfer.d.ts +32 -3
  96. package/dist/task-transfer.d.ts.map +1 -1
  97. package/dist/task-transfer.js +101 -3
  98. package/dist/types.d.ts.map +1 -1
  99. package/dist/types.js +3 -11
  100. package/dist/workspaces.d.ts +43 -0
  101. package/dist/workspaces.d.ts.map +1 -1
  102. package/dist/workspaces.js +174 -8
  103. package/docs/ARCHITECTURE.md +32 -12
  104. package/docs/FEATURES.md +186 -10
  105. package/gui-experimental.cjs +4 -2
  106. package/package.json +15 -2
  107. package/scripts/demo-dashboard.mjs +12 -2
  108. package/src/core/analytics.ts +36 -0
  109. package/src/core/dry-run.ts +65 -4
  110. package/src/core/matrix.ts +10 -0
  111. package/src/core/one-shot.ts +173 -0
  112. package/src/core/otel.ts +128 -0
  113. package/src/core/prometheus.ts +215 -0
  114. package/src/core/ps-wrapper.ts +144 -4
  115. package/src/core/record-history.ts +13 -0
  116. package/src/core/schedule-gate.ts +213 -0
  117. package/src/core/schedule-v2.ts +533 -0
  118. package/src/core/scheduler/linux.ts +90 -3
  119. package/src/core/scheduler/mac.ts +35 -4
  120. package/src/core/scheduler/posix.ts +3 -0
  121. package/src/core/scheduler/registry.ts +4 -0
  122. package/src/core/scheduler/types.ts +20 -3
  123. package/src/core/scheduler/windows.ts +24 -2
  124. package/src/core/session.ts +115 -0
  125. package/src/core/structured-log.ts +205 -0
  126. package/src/core/wrappers/bash.ts +98 -2
  127. package/src/db/history-repo.ts +90 -7
  128. package/src/db/metrics-repo.ts +19 -7
  129. package/src/db/migrate.ts +7 -1
  130. package/src/db/schema.ts +25 -0
  131. package/src/gui.tsx +3832 -2868
  132. package/src/history.ts +17 -0
  133. package/src/index.ts +1670 -117
  134. package/src/integrations.ts +253 -0
  135. package/src/notifications.ts +516 -40
  136. package/src/profiles.ts +236 -0
  137. package/src/rpc.ts +244 -6
  138. package/src/server.ts +506 -58
  139. package/src/settings.ts +336 -9
  140. package/src/shared/jobs-view.ts +158 -8
  141. package/src/task-transfer.ts +151 -5
  142. package/src/tui.tsx +290 -14
  143. package/src/types.ts +3 -13
  144. package/src/workspaces.ts +214 -8
@@ -0,0 +1,496 @@
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
+ /** Ограничение на поиск ближайшего запуска. */
16
+ const MAX_SEARCH_DAYS = 5 * 366;
17
+ const MONTH_NAMES = {
18
+ JAN: 1, FEB: 2, MAR: 3, APR: 4, MAY: 5, JUN: 6,
19
+ JUL: 7, AUG: 8, SEP: 9, OCT: 10, NOV: 11, DEC: 12,
20
+ };
21
+ const DOW_NAMES = {
22
+ SUN: 0, MON: 1, TUE: 2, WED: 3, THU: 4, FRI: 5, SAT: 6,
23
+ };
24
+ /** Кэш форматтеров Intl по таймзоне (создание Intl.DateTimeFormat недёшево). */
25
+ const dtfCache = new Map();
26
+ function getDtf(timeZone) {
27
+ const cached = dtfCache.get(timeZone);
28
+ if (cached)
29
+ return cached;
30
+ // hourCycle h23: 00..23, без «24».
31
+ const dtf = new Intl.DateTimeFormat("en-US", {
32
+ timeZone,
33
+ year: "numeric", month: "numeric", day: "numeric",
34
+ hour: "numeric", minute: "numeric", second: "numeric",
35
+ hourCycle: "h23",
36
+ });
37
+ dtfCache.set(timeZone, dtf);
38
+ return dtf;
39
+ }
40
+ export function isValidIanaTimeZone(tz) {
41
+ const t = (tz || "").trim();
42
+ if (!t)
43
+ return false;
44
+ try {
45
+ new Intl.DateTimeFormat("en-US", { timeZone: t });
46
+ return true;
47
+ }
48
+ catch {
49
+ return false;
50
+ }
51
+ }
52
+ /** Системная таймзона (IANA) или "UTC", если её не удалось определить. */
53
+ export function systemTimeZone() {
54
+ try {
55
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
56
+ }
57
+ catch {
58
+ return "UTC";
59
+ }
60
+ }
61
+ /** Части даты в заданной инстанции (или в системной локали, если tz не задан). */
62
+ export function zonedParts(date, timeZone) {
63
+ if (timeZone && timeZone !== Intl.DateTimeFormat().resolvedOptions().timeZone) {
64
+ const parts = getDtf(timeZone).formatToParts(date);
65
+ const bag = {};
66
+ for (const p of parts) {
67
+ if (p.type === "year" || p.type === "month" || p.type === "day"
68
+ || p.type === "hour" || p.type === "minute" || p.type === "second") {
69
+ bag[p.type] = Number(p.value);
70
+ }
71
+ }
72
+ const asUtc = new Date(Date.UTC(bag.year, bag.month - 1, bag.day));
73
+ return {
74
+ year: bag.year, month: bag.month, day: bag.day,
75
+ hour: bag.hour, minute: bag.minute, second: bag.second, ms: date.getUTCMilliseconds(),
76
+ weekday: asUtc.getUTCDay(),
77
+ };
78
+ }
79
+ return {
80
+ year: date.getFullYear(), month: date.getMonth() + 1, day: date.getDate(),
81
+ hour: date.getHours(), minute: date.getMinutes(), second: date.getSeconds(),
82
+ ms: date.getMilliseconds(), weekday: date.getDay(),
83
+ };
84
+ }
85
+ /** Стенные часы → UTC, итеративно учитывая смещение (DST-safe). null — несуществующее время. */
86
+ export function wallToUtc(y, m, d, h, mi, timeZone) {
87
+ const tz = timeZone || Intl.DateTimeFormat().resolvedOptions().timeZone;
88
+ const target = Date.UTC(y, m - 1, d, h, mi);
89
+ const matches = (ms) => {
90
+ const p = zonedParts(new Date(ms), tz);
91
+ return p.year === y && p.month === m && p.day === d && p.hour === h && p.minute === mi;
92
+ };
93
+ let guess = target;
94
+ for (let i = 0; i < 4; i += 1) {
95
+ const p = zonedParts(new Date(guess), tz);
96
+ const actual = Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute);
97
+ const delta = target - actual;
98
+ if (delta === 0)
99
+ break;
100
+ guess += delta;
101
+ }
102
+ // При переходе на зимнее время настенное время существует дважды. Для
103
+ // «следующего запуска» берём ПЕРВОЕ (более раннее) вхождение, а не то, к
104
+ // которому сошлась итерация. Обычно совпадение одно, тогда результат тот же.
105
+ const probes = [0, -30, 30, -60, 60, -90, 90, -120, 120].map((minutes) => guess + minutes * 60000);
106
+ let best = null;
107
+ for (const ms of probes) {
108
+ if (!matches(ms))
109
+ continue;
110
+ if (best === null || ms < best)
111
+ best = ms;
112
+ }
113
+ return best === null ? null : new Date(best);
114
+ }
115
+ function lastDayOfMonth(y, m) {
116
+ return new Date(Date.UTC(y, m, 0)).getUTCDate();
117
+ }
118
+ function nthWeekdayOfMonth(y, m, weekday, n) {
119
+ const firstDow = new Date(Date.UTC(y, m - 1, 1)).getUTCDay();
120
+ const first = 1 + ((weekday - firstDow + 7) % 7);
121
+ const dom = first + 7 * (n - 1);
122
+ return dom <= lastDayOfMonth(y, m) ? dom : null;
123
+ }
124
+ function expandField(token, min, max, names) {
125
+ const result = new Set();
126
+ const items = token.split(",");
127
+ for (const raw of items) {
128
+ let item = raw.trim().toUpperCase();
129
+ if (!item)
130
+ throw new Error(`Пустой элемент в списке «${token}».`);
131
+ if (names && names[item] !== undefined)
132
+ item = String(names[item]);
133
+ // шаг: a-b/n или */n
134
+ const stepMatch = item.match(/^(.*)\/([0-9]+)$/);
135
+ let step = 1;
136
+ if (stepMatch) {
137
+ item = (stepMatch[1] ?? "").trim();
138
+ step = Number(stepMatch[2]);
139
+ if (!Number.isInteger(step) || step < 1) {
140
+ throw new Error(`Недопустимый шаг «/${stepMatch[2]}» в «${raw}».`);
141
+ }
142
+ if (item === "")
143
+ throw new Error(`Некорректный шаг в «${raw}»: перед «/» ничего нет.`);
144
+ }
145
+ if (item === "*" || item === "") {
146
+ for (let v = min; v <= max; v += step)
147
+ result.add(v);
148
+ continue;
149
+ }
150
+ const rangeMatch = item.match(/^([0-9A-Z]+)-([0-9A-Z]+)$/);
151
+ if (rangeMatch) {
152
+ let aToken = rangeMatch[1];
153
+ let bToken = rangeMatch[2];
154
+ if (names && names[aToken] !== undefined)
155
+ aToken = String(names[aToken]);
156
+ if (names && names[bToken] !== undefined)
157
+ bToken = String(names[bToken]);
158
+ const a = Number(aToken);
159
+ const b = Number(bToken);
160
+ if (!Number.isFinite(a) || !Number.isFinite(b)) {
161
+ throw new Error(`Недопустимый диапазон «${item}».`);
162
+ }
163
+ if (a < min || b > max || a > b) {
164
+ throw new Error(`Диапазон «${item}» вне границ ${min}..${max}.`);
165
+ }
166
+ for (let v = a; v <= b; v += step)
167
+ result.add(v);
168
+ continue;
169
+ }
170
+ const num = Number(item);
171
+ if (!Number.isInteger(num) || num < min || num > max) {
172
+ throw new Error(`Значение «${raw}» вне границ ${min}..${max}.`);
173
+ }
174
+ result.add(num);
175
+ }
176
+ return result;
177
+ }
178
+ /** Разворачивает «@every 15m|2h|1d» в обычный cron. */
179
+ export function normalizeCron(expr) {
180
+ const trimmed = expr.trim();
181
+ const match = trimmed.match(/^@every\s+(\d+)([mhd])$/i);
182
+ if (!match)
183
+ return trimmed;
184
+ const n = Number(match[1]);
185
+ const unit = match[2].toLowerCase();
186
+ if (unit === "m" && n >= 1 && n < 60)
187
+ return `*/${n} * * * *`;
188
+ if (unit === "h" && n >= 1 && n <= 23)
189
+ return `0 */${n} * * *`;
190
+ if (unit === "d" && n >= 1 && n <= 31)
191
+ return `0 0 */${n} * *`;
192
+ throw new Error(`Неподдерживаемый интервал «@every ${n}${unit}» (m: 1..59, h: 1..23, d: 1..31).`);
193
+ }
194
+ /** Парсит cron-выражение; бросает Error с понятным сообщением. */
195
+ export function parseCron(expr) {
196
+ const raw = normalizeCron(expr);
197
+ const fields = raw.split(/\s+/);
198
+ if (fields.length !== 5) {
199
+ throw new Error(`Ожидается 5 полей cron, получено ${fields.length}: «${raw}».`);
200
+ }
201
+ const [minF, hourF, domF, monthF, dowF] = fields;
202
+ const minute = expandField(minF, 0, 59);
203
+ const hour = expandField(hourF, 0, 23);
204
+ const month = expandField(monthF, 1, 12, MONTH_NAMES);
205
+ // dom: «*» + опциональный «L» в списке (например «15,L»).
206
+ let dayOfMonth = null;
207
+ let lastDom = false;
208
+ {
209
+ const tokens = domF.trim().toUpperCase().split(",").map((s) => s.trim());
210
+ const kept = [];
211
+ for (const token of tokens) {
212
+ if (token === "L") {
213
+ lastDom = true;
214
+ continue;
215
+ }
216
+ kept.push(token);
217
+ }
218
+ if (domF.trim() !== "*") {
219
+ dayOfMonth = kept.length > 0 ? expandField(kept.join(","), 1, 31) : new Set();
220
+ }
221
+ }
222
+ // dow: «*» + имена + «d#n».
223
+ let dayOfWeek = null;
224
+ const nthWeekday = [];
225
+ {
226
+ const tokens = dowF.trim().toUpperCase().split(",").map((s) => s.trim());
227
+ const kept = [];
228
+ for (const token of tokens) {
229
+ const hash = token.match(/^([0-9A-Z]+)#([1-5])$/);
230
+ if (hash) {
231
+ let dToken = hash[1];
232
+ if (DOW_NAMES[dToken] !== undefined)
233
+ dToken = String(DOW_NAMES[dToken]);
234
+ const weekday = Number(dToken);
235
+ if (!Number.isInteger(weekday) || weekday < 0 || weekday > 7) {
236
+ throw new Error(`День недели «${hash[1]}» вне границ 0..7 в «${dowF}».`);
237
+ }
238
+ nthWeekday.push({ weekday: weekday % 7, n: Number(hash[2]) });
239
+ continue;
240
+ }
241
+ if (token === "L") {
242
+ throw new Error("«L» поддерживается только в поле дня месяца.");
243
+ }
244
+ kept.push(token);
245
+ }
246
+ if (dowF.trim() !== "*") {
247
+ dayOfWeek = kept.length > 0 ? expandField(kept.join(","), 0, 7, DOW_NAMES) : new Set();
248
+ // 0 и 7 — оба воскресенье.
249
+ const mapped = new Set();
250
+ for (const d of dayOfWeek)
251
+ mapped.add(d % 7);
252
+ dayOfWeek = mapped;
253
+ }
254
+ }
255
+ return { raw, minute, hour, dayOfMonth, lastDom, month, dayOfWeek, nthWeekday };
256
+ }
257
+ function domMatches(p, spec) {
258
+ const last = lastDayOfMonth(p.year, p.month);
259
+ if (spec.dayOfMonth && spec.dayOfMonth.has(p.day))
260
+ return true;
261
+ if (spec.lastDom && p.day === last)
262
+ return true;
263
+ return false;
264
+ }
265
+ function dowMatches(p, spec) {
266
+ if (spec.dayOfWeek && spec.dayOfWeek.has(p.weekday))
267
+ return true;
268
+ for (const { weekday, n } of spec.nthWeekday) {
269
+ const dom = nthWeekdayOfMonth(p.year, p.month, weekday, n);
270
+ if (dom === p.day)
271
+ return true;
272
+ }
273
+ return false;
274
+ }
275
+ /** true, если cron срабатывает в указанную минуту (в системной или заданной tz). */
276
+ export function cronMatches(spec, date, timeZone) {
277
+ const p = zonedParts(date, timeZone);
278
+ if (!spec.minute.has(p.minute))
279
+ return false;
280
+ if (!spec.hour.has(p.hour))
281
+ return false;
282
+ if (!spec.month.has(p.month))
283
+ return false;
284
+ const domAny = spec.dayOfMonth === null && !spec.lastDom;
285
+ const dowAny = spec.dayOfWeek === null && spec.nthWeekday.length === 0;
286
+ const dm = domMatches(p, spec);
287
+ const dw = dowMatches(p, spec);
288
+ // Vixie OR-семантика: обе группы ограничены — достаточно совпадения одной.
289
+ if (domAny && dowAny)
290
+ return true;
291
+ if (domAny)
292
+ return dw;
293
+ if (dowAny)
294
+ return dm;
295
+ return dm || dw;
296
+ }
297
+ function iterateDay(p, delta) {
298
+ const d = new Date(Date.UTC(p.year, p.month - 1, p.day + delta));
299
+ return { year: d.getUTCFullYear(), month: d.getUTCMonth() + 1, day: d.getUTCDate() };
300
+ }
301
+ function candidatesOnDay(spec, y, m, d, notBefore, notAfter) {
302
+ const hours = [...spec.hour].sort((a, b) => a - b);
303
+ const minutes = [...spec.minute].sort((a, b) => a - b);
304
+ const result = [];
305
+ for (const hour of hours) {
306
+ for (const minute of minutes) {
307
+ if (notBefore && notAfter) {
308
+ if (hour < notBefore.hour || (hour === notBefore.hour && minute < notBefore.minute))
309
+ continue;
310
+ }
311
+ if (notAfter) {
312
+ if (hour > notAfter.hour || (hour === notAfter.hour && minute > notAfter.minute))
313
+ continue;
314
+ }
315
+ result.push({ hour, minute });
316
+ }
317
+ }
318
+ return result;
319
+ }
320
+ /**
321
+ * Ближайший запуск после `from` (или null, если найти не удалось за 5 лет).
322
+ * `timeZone` — IANA; по умолчанию системная.
323
+ */
324
+ export function nextRun(expr, from, timeZone) {
325
+ const spec = parseCron(expr);
326
+ const base = from.getTime();
327
+ const origin = zonedParts(from, timeZone);
328
+ let cursor = { year: origin.year, month: origin.month, day: origin.day };
329
+ // Не считать время дня на первом дне: только строго после from.
330
+ let firstDay = true;
331
+ for (let i = 0; i < MAX_SEARCH_DAYS; i += 1) {
332
+ if (dayMatches(cursor.year, cursor.month, cursor.day, spec)) {
333
+ const nb = firstDay
334
+ ? { hour: origin.hour, minute: origin.minute + 1 } // строго позже минуты from
335
+ : null;
336
+ const candidates = candidatesOnDay(spec, cursor.year, cursor.month, cursor.day, nb, null);
337
+ for (const cand of candidates) {
338
+ const at = wallToUtc(cursor.year, cursor.month, cursor.day, cand.hour, cand.minute, timeZone);
339
+ if (at && at.getTime() > base)
340
+ return at;
341
+ }
342
+ }
343
+ firstDay = false;
344
+ cursor = iterateDay(cursor, 1);
345
+ }
346
+ return null;
347
+ }
348
+ /** Последний запуск не позже `from` (или null). */
349
+ export function prevRun(expr, from, timeZone) {
350
+ const spec = parseCron(expr);
351
+ const base = from.getTime();
352
+ const origin = zonedParts(from, timeZone);
353
+ let cursor = { year: origin.year, month: origin.month, day: origin.day };
354
+ let firstDay = true;
355
+ for (let i = 0; i < MAX_SEARCH_DAYS; i += 1) {
356
+ if (dayMatches(cursor.year, cursor.month, cursor.day, spec)) {
357
+ const na = firstDay
358
+ ? { hour: origin.hour, minute: origin.minute } // включая текущую минуту
359
+ : null;
360
+ const candidates = candidatesOnDay(spec, cursor.year, cursor.month, cursor.day, null, na);
361
+ for (let i2 = candidates.length - 1; i2 >= 0; i2 -= 1) {
362
+ const cand = candidates[i2];
363
+ const at = wallToUtc(cursor.year, cursor.month, cursor.day, cand.hour, cand.minute, timeZone);
364
+ if (at && at.getTime() <= base)
365
+ return at;
366
+ }
367
+ }
368
+ firstDay = false;
369
+ cursor = iterateDay(cursor, -1);
370
+ }
371
+ return null;
372
+ }
373
+ function dayMatches(y, m, d, spec) {
374
+ if (!spec.month.has(m))
375
+ return false;
376
+ const domAny = spec.dayOfMonth === null && !spec.lastDom;
377
+ const date = new Date(Date.UTC(y, m - 1, d));
378
+ const weekday = date.getUTCDay();
379
+ const p = { year: y, month: m, day: d, weekday };
380
+ if (domAny && spec.dayOfWeek === null && spec.nthWeekday.length === 0)
381
+ return true;
382
+ const dm = domMatches({ year: y, month: m, day: d }, spec);
383
+ const dw = dowMatches(p, spec);
384
+ const dowAny = spec.dayOfWeek === null && spec.nthWeekday.length === 0;
385
+ if (domAny)
386
+ return dw;
387
+ if (dowAny)
388
+ return dm;
389
+ return dm || dw;
390
+ }
391
+ function dayStartUtc(y, m, d, timeZone) {
392
+ const d0 = wallToUtc(y, m, d, 0, 0, timeZone);
393
+ return d0 ?? new Date(Date.UTC(y, m - 1, d, 0, 0));
394
+ }
395
+ // ---------------------------------------------------------------------------
396
+ // Окна запуска (notBefore/notAfter, «дд:мм» 24ч, можно через полночь).
397
+ const DAILY_TIME_RE = /^([01]\d|2[0-3]):[0-5]\d$/;
398
+ export function isValidDailyTime(value) {
399
+ return DAILY_TIME_RE.test((value || "").trim());
400
+ }
401
+ function dailyTimeToMinutes(value) {
402
+ const [h, m] = value.trim().split(":").map(Number);
403
+ return h * 60 + m;
404
+ }
405
+ /** Проверяет пару окна; возвращает текст ошибки или null. */
406
+ export function validateLaunchWindow(notBefore, notAfter) {
407
+ if (notBefore === undefined && notAfter === undefined)
408
+ return null;
409
+ const nb = notBefore?.trim() ?? "";
410
+ const na = notAfter?.trim() ?? "";
411
+ if (!nb && !na)
412
+ return null;
413
+ if (nb && !isValidDailyTime(nb))
414
+ return `notBefore должен быть в формате HH:MM, не "${nb}".`;
415
+ if (na && !isValidDailyTime(na))
416
+ return `notAfter должен быть в формате HH:MM, не "${na}".`;
417
+ if (!nb || !na)
418
+ return "notBefore и notAfter задаются вместе.";
419
+ if (nb === na)
420
+ return "notBefore и notAfter не могут совпадать (пустое окно).";
421
+ return null;
422
+ }
423
+ function wallMinutes(date, timeZone) {
424
+ const p = zonedParts(date, timeZone);
425
+ return { minutes: p.hour * 60 + p.minute, seconds: p.second, ms: p.ms };
426
+ }
427
+ /** Мы внутри окна запуска? */
428
+ export function isInWindow(now, notBefore, notAfter, timeZone) {
429
+ if (validateLaunchWindow(notBefore, notAfter) !== null)
430
+ return true; // невалидное окно не должно блокировать
431
+ if (!notBefore?.trim() && !notAfter?.trim())
432
+ return true;
433
+ const start = dailyTimeToMinutes(notBefore);
434
+ const end = dailyTimeToMinutes(notAfter);
435
+ const { minutes } = wallMinutes(now, timeZone);
436
+ if (start < end)
437
+ return minutes >= start && minutes < end;
438
+ return minutes >= start || minutes < end; // через полночь
439
+ }
440
+ /** Сколько мс ждать до открытия окна (0 — уже открыто / окно не задано). */
441
+ export function windowDelayMs(now, notBefore, notAfter, timeZone) {
442
+ if (validateLaunchWindow(notBefore, notAfter) !== null)
443
+ return 0;
444
+ if (!notBefore?.trim() && !notAfter?.trim())
445
+ return 0;
446
+ if (isInWindow(now, notBefore, notAfter, timeZone))
447
+ return 0;
448
+ const start = dailyTimeToMinutes(notBefore);
449
+ const { minutes, seconds, ms } = wallMinutes(now, timeZone);
450
+ const deltaMin = (start - minutes + 1440) % 1440;
451
+ const deltaSec = deltaMin * 60 - seconds;
452
+ return Math.max(0, deltaSec * 1000 - ms);
453
+ }
454
+ // ---------------------------------------------------------------------------
455
+ // Проверка совместимости с schtasks (родной режим).
456
+ /**
457
+ * true, если выражение умеет оформить Windows Task Scheduler «родными»
458
+ * флагами (MINUTE/HOURLY/DAILY/WEEKLY) и парсится строгим конвертером.
459
+ * Используется для выбора между флагами и минутным опросом.
460
+ */
461
+ export function isNativeSchtasksExpr(expr) {
462
+ try {
463
+ convertCronToSchTasks(normalizeCron(expr));
464
+ return true;
465
+ }
466
+ catch {
467
+ return false;
468
+ }
469
+ }
470
+ /** Конвертер для родного режима; бросает Error для неподдерживаемых. */
471
+ export function convertForSchtasks(expr) {
472
+ return convertCronToSchTasks(normalizeCron(expr));
473
+ }
474
+ /**
475
+ * true, если ОС-триггер не выражает расписание (чужой IANA-таймзона или
476
+ * не конвертируемо в флаги schtasks) — нужен минутный опрос + gate.
477
+ */
478
+ export function needsPollMode(expr, timezone) {
479
+ const tz = (timezone || "").trim();
480
+ if (tz && tz !== systemTimeZone())
481
+ return true;
482
+ return !isNativeSchtasksExpr(expr);
483
+ }
484
+ /**
485
+ * Аргументы schedule-gate для враппера, либо undefined — если врапперу гейт
486
+ * не нужен (нативный cron + системный таймзона + окно не задано).
487
+ * Окно запуска всегда требует gate (перенос реализует враппер).
488
+ */
489
+ export function buildScheduleGate(expr, timezone, notBefore, notAfter) {
490
+ const tz = (timezone || "").trim() || undefined;
491
+ const poll = needsPollMode(expr, tz);
492
+ if (!poll && !(notBefore && notAfter))
493
+ return undefined;
494
+ // cron проверяем только в poll-режиме (см. комментарий у ScheduleGateSpec).
495
+ return { ...(poll ? { cron: expr } : {}), tz, notBefore, notAfter };
496
+ }
@@ -25,8 +25,17 @@ export declare class LinuxScheduler extends PosixSchedulerBase {
25
25
  private writeCrontab;
26
26
  /** Перегенерирует блок плагина из реестра. */
27
27
  private rebuildCrontab;
28
- protected installEntry(_entry: RegistryEntry): Promise<void>;
29
- protected uninstallEntry(_entry: RegistryEntry): Promise<void>;
30
- protected applyPause(_entry: RegistryEntry, _paused: boolean): Promise<void>;
28
+ /** Строка команды one-shot для stdin `at`. */
29
+ private atCommand;
30
+ /**
31
+ * Ставит one-shot в `at` и возвращает id задания.
32
+ * `at -t` принимает локальное время системы в формате YYYYMMDDHHMM.
33
+ */
34
+ private scheduleAt;
35
+ /** Отменяет задание at, если оно ещё существует. */
36
+ private cancelAt;
37
+ protected installEntry(entry: RegistryEntry): Promise<void>;
38
+ protected uninstallEntry(entry: RegistryEntry): Promise<void>;
39
+ protected applyPause(entry: RegistryEntry, paused: boolean): Promise<void>;
31
40
  }
32
41
  //# sourceMappingURL=linux.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"linux.d.ts","sourceRoot":"","sources":["../../../src/core/scheduler/linux.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,kBAAkB,EAAc,MAAM,YAAY,CAAC;AAC5D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAOnD;;;;;;;;;;GAUG;AACH,qBAAa,cAAe,SAAQ,kBAAkB;IACpD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAW;IAC7C,QAAQ,CAAC,KAAK,wBAAwB;;IAMtC,OAAO,CAAC,QAAQ;IAUhB,OAAO,CAAC,WAAW;IAYnB,0EAA0E;YAC5D,WAAW;IAYzB,0DAA0D;IAC1D,OAAO,CAAC,UAAU;IAkBlB,mDAAmD;YACrC,YAAY;IAgB1B,8CAA8C;YAChC,cAAc;cAYZ,YAAY,CAAC,MAAM,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;cAIlD,cAAc,CAAC,MAAM,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;cAIpD,UAAU,CAAC,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;CAGnF"}
1
+ {"version":3,"file":"linux.d.ts","sourceRoot":"","sources":["../../../src/core/scheduler/linux.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,kBAAkB,EAAc,MAAM,YAAY,CAAC;AAC5D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAOnD;;;;;;;;;;GAUG;AACH,qBAAa,cAAe,SAAQ,kBAAkB;IACpD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAW;IAC7C,QAAQ,CAAC,KAAK,wBAAwB;;IAMtC,OAAO,CAAC,QAAQ;IAUhB,OAAO,CAAC,WAAW;IAYnB,0EAA0E;YAC5D,WAAW;IAYzB,0DAA0D;IAC1D,OAAO,CAAC,UAAU;IAkBlB,mDAAmD;YACrC,YAAY;IAgB1B,8CAA8C;YAChC,cAAc;IAY5B,8CAA8C;IAC9C,OAAO,CAAC,SAAS;IAKjB;;;OAGG;YACW,UAAU;IA8CxB,oDAAoD;YACtC,QAAQ;cAUN,YAAY,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;cAUjD,cAAc,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;cAQnD,UAAU,CAAC,KAAK,EAAE,aAAa,EAAE,MAAM,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;CAYjF"}
@@ -1,5 +1,6 @@
1
1
  import { execFile, spawn } from "node:child_process";
2
2
  import { promisify } from "node:util";
3
+ import { buildAtTimestamp } from "../one-shot.js";
3
4
  import { PosixSchedulerBase, shellQuote } from "./posix.js";
4
5
  const execFileAsync = promisify(execFile);
5
6
  const BLOCK_BEGIN = "# >>> opencode-scheduler >>>";
@@ -103,13 +104,89 @@ export class LinuxScheduler extends PosixSchedulerBase {
103
104
  const next = [base, hasTasks ? block : ""].filter(Boolean).join("\n");
104
105
  await this.writeCrontab(next);
105
106
  }
106
- async installEntry(_entry) {
107
+ /** Строка команды one-shot для stdin `at`. */
108
+ atCommand(entry) {
109
+ const log = entry.logFile ? ` >> ${shellQuote(entry.logFile)} 2>&1` : "";
110
+ return `/bin/bash ${shellQuote(entry.command)}${log}`;
111
+ }
112
+ /**
113
+ * Ставит one-shot в `at` и возвращает id задания.
114
+ * `at -t` принимает локальное время системы в формате YYYYMMDDHHMM.
115
+ */
116
+ async scheduleAt(entry) {
117
+ if (!entry.runAt) {
118
+ throw new Error(`Задача "${entry.name}": не задано runAt для one-shot.`);
119
+ }
120
+ const timestamp = buildAtTimestamp(entry.runAt);
121
+ return new Promise((resolve, reject) => {
122
+ const child = spawn("at", ["-t", timestamp], {
123
+ stdio: ["pipe", "pipe", "pipe"],
124
+ });
125
+ let stdout = "";
126
+ let stderr = "";
127
+ child.stdout.on("data", (chunk) => {
128
+ stdout += String(chunk);
129
+ });
130
+ child.stderr.on("data", (chunk) => {
131
+ stderr += String(chunk);
132
+ });
133
+ child.on("error", (err) => {
134
+ reject(new Error(`Не удалось вызвать at (установите пакет at): ${err instanceof Error ? err.message : String(err)}`));
135
+ });
136
+ child.on("close", (code) => {
137
+ if (code !== 0) {
138
+ reject(new Error(`at завершился с кодом ${code}: ${stderr.trim() || stdout.trim()}`));
139
+ return;
140
+ }
141
+ const match = /job\s+(\d+)/i.exec(stdout);
142
+ if (!match) {
143
+ reject(new Error(`at не вернул id задания: ${stdout.trim()}`));
144
+ return;
145
+ }
146
+ resolve(match[1]);
147
+ });
148
+ child.stdin.end(`${this.atCommand(entry)}\n`);
149
+ });
150
+ }
151
+ /** Отменяет задание at, если оно ещё существует. */
152
+ async cancelAt(entry) {
153
+ if (!entry.atJobId)
154
+ return;
155
+ try {
156
+ await execFileAsync("atrm", [entry.atJobId]);
157
+ }
158
+ catch {
159
+ // Задание уже выполнилось или было удалено — это не ошибка.
160
+ }
161
+ delete entry.atJobId;
162
+ }
163
+ async installEntry(entry) {
164
+ if (entry.triggerType === "once") {
165
+ if (!entry.paused) {
166
+ entry.atJobId = await this.scheduleAt(entry);
167
+ }
168
+ return;
169
+ }
107
170
  await this.rebuildCrontab();
108
171
  }
109
- async uninstallEntry(_entry) {
172
+ async uninstallEntry(entry) {
173
+ if (entry.triggerType === "once") {
174
+ await this.cancelAt(entry);
175
+ return;
176
+ }
110
177
  await this.rebuildCrontab();
111
178
  }
112
- async applyPause(_entry, _paused) {
179
+ async applyPause(entry, paused) {
180
+ if (entry.triggerType === "once") {
181
+ if (paused) {
182
+ await this.cancelAt(entry);
183
+ }
184
+ else if (entry.runAt && Date.parse(entry.runAt) > Date.now()) {
185
+ entry.atJobId = await this.scheduleAt(entry);
186
+ }
187
+ await this.registry.upsert(entry);
188
+ return;
189
+ }
113
190
  await this.rebuildCrontab();
114
191
  }
115
192
  }
@@ -1 +1 @@
1
- {"version":3,"file":"mac.d.ts","sourceRoot":"","sources":["../../../src/core/scheduler/mac.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAmBnD,wDAAwD;AACxD,UAAU,eAAe;IACvB,uDAAuD;IACvD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,0DAA0D;IAC1D,QAAQ,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CACjE;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,GAAG,eAAe,CAsDnE;AA2ED;;;;;;GAMG;AACH,qBAAa,YAAa,SAAQ,kBAAkB;IAClD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAY;IAC9C,QAAQ,CAAC,KAAK,wBAAwB;;IAMtC,OAAO,CAAC,KAAK;IAIb,OAAO,CAAC,SAAS;IAIjB,gFAAgF;YAClE,SAAS;cAQP,YAAY,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;cAQjD,cAAc,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;cAMnD,UAAU,CAAC,KAAK,EAAE,aAAa,EAAE,MAAM,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;CAQjF"}
1
+ {"version":3,"file":"mac.d.ts","sourceRoot":"","sources":["../../../src/core/scheduler/mac.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAmBnD,wDAAwD;AACxD,UAAU,eAAe;IACvB,uDAAuD;IACvD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,0DAA0D;IAC1D,QAAQ,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CACjE;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,GAAG,eAAe,CAsDnE;AAyGD;;;;;;GAMG;AACH,qBAAa,YAAa,SAAQ,kBAAkB;IAClD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAY;IAC9C,QAAQ,CAAC,KAAK,wBAAwB;;IAMtC,OAAO,CAAC,KAAK;IAIb,OAAO,CAAC,SAAS;IAIjB,gFAAgF;YAClE,SAAS;cAQP,YAAY,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;cAQjD,cAAc,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;cAMnD,UAAU,CAAC,KAAK,EAAE,aAAa,EAAE,MAAM,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;CAQjF"}
@@ -4,6 +4,7 @@ import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { promisify } from "node:util";
6
6
  import { sanitizeName } from "../../types.js";
7
+ import { buildLaunchdCalendar } from "../one-shot.js";
7
8
  import { PosixSchedulerBase } from "./posix.js";
8
9
  const execFileAsync = promisify(execFile);
9
10
  /** Папка пользовательских LaunchAgents. */
@@ -69,9 +70,16 @@ export function cronToLaunchdSchedule(cron) {
69
70
  }
70
71
  /** Собирает XML plist для задачи. */
71
72
  function buildPlist(label, entry) {
72
- const schedule = entry.triggerType !== "cron"
73
- ? { interval: 315360000 } // file/mcp-event: 10 лет — фактически «никогда».
74
- : cronToLaunchdSchedule(entry.schedule);
73
+ const schedule = entry.triggerType === "once"
74
+ ? (() => {
75
+ if (!entry.runAt) {
76
+ throw new Error(`Задача "${entry.name}": для one-shot не задано runAt.`);
77
+ }
78
+ return { calendar: buildLaunchdCalendar(entry.runAt) };
79
+ })()
80
+ : entry.triggerType !== "cron"
81
+ ? { interval: 315360000 } // file/mcp-event: 10 лет — фактически «никогда».
82
+ : cronToLaunchdSchedule(entry.schedule);
75
83
  const scheduleXml = [];
76
84
  if (schedule.interval !== undefined) {
77
85
  scheduleXml.push(" <key>StartInterval</key>", ` <integer>${schedule.interval}</integer>`);
@@ -87,6 +95,12 @@ function buildPlist(label, entry) {
87
95
  if (schedule.calendar.Weekday !== undefined) {
88
96
  scheduleXml.push(" <key>Weekday</key>", ` <integer>${schedule.calendar.Weekday}</integer>`);
89
97
  }
98
+ if (schedule.calendar.Month !== undefined) {
99
+ scheduleXml.push(" <key>Month</key>", ` <integer>${schedule.calendar.Month}</integer>`);
100
+ }
101
+ if (schedule.calendar.Day !== undefined) {
102
+ scheduleXml.push(" <key>Day</key>", ` <integer>${schedule.calendar.Day}</integer>`);
103
+ }
90
104
  scheduleXml.push(" </dict>");
91
105
  }
92
106
  const workdir = entry.workingDirectory || process.cwd();