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
@@ -1,33 +1,108 @@
1
- import { loadSettings } from "./settings.js";
2
- /** Таймаут HTTP-запроса: уведомление не должно подвешивать обёртку задачи. */
1
+ import { loadSettings, saveSettings, } from "./settings.js";
2
+ import { buildAnalytics, } from "./core/analytics.js";
3
+ import { getHistory } from "./db/history-repo.js";
4
+ /** Таймаут HTTP-запроса по умолчанию: уведомление не должно подвешивать задачу. */
3
5
  const REQUEST_TIMEOUT_MS = 10000;
6
+ /** Максимальная задержка backoff между повторами. */
7
+ const MAX_RETRY_DELAY_MS = 30000;
4
8
  /** Человекочитаемая длительность: 2300 мс → «2.3s». */
5
9
  export function formatDuration(durationMs) {
6
10
  const seconds = Math.max(0, Number(durationMs) || 0) / 1000;
7
11
  return `${seconds.toFixed(1)}s`;
8
12
  }
13
+ /** Экранирует regexp-спецсимволы. */
14
+ function escapeRegExp(text) {
15
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
16
+ }
17
+ /**
18
+ * Сопоставление имени задачи с шаблоном: `*` — любая последовательность,
19
+ * регистр не важен. `regen-*` покрывает `regen-api`, `regen-ui`.
20
+ */
21
+ export function wildcardMatch(pattern, value) {
22
+ const trimmed = (pattern ?? "").trim();
23
+ if (!trimmed)
24
+ return false;
25
+ const source = trimmed
26
+ .split("*")
27
+ .map((part) => escapeRegExp(part))
28
+ .join(".*");
29
+ return new RegExp(`^${source}$`, "i").test(value.trim());
30
+ }
31
+ /** Проверяет, разрешена ли задача фильтрами include/exclude. */
32
+ export function isTaskAllowed(taskName, filters) {
33
+ if (!filters)
34
+ return true;
35
+ const name = (taskName ?? "").trim();
36
+ if (!name)
37
+ return false;
38
+ const exclude = filters.exclude ?? [];
39
+ if (exclude.some((pattern) => wildcardMatch(pattern, name)))
40
+ return false;
41
+ const include = filters.include ?? [];
42
+ if (include.length === 0)
43
+ return true;
44
+ return include.some((pattern) => wildcardMatch(pattern, name));
45
+ }
46
+ /** Подставляет {key} в шаблон; неизвестные плейсхолдеры остаются как есть. */
47
+ export function renderTemplate(template, vars) {
48
+ return template.replace(/\{(\w+)\}/g, (match, key) => Object.prototype.hasOwnProperty.call(vars, key) ? vars[key] : match);
49
+ }
9
50
  /**
10
- * Формат сообщения:
51
+ * Формат сообщения по умолчанию:
11
52
  * ✅ Задача "Тест" выполнена (2.3s)
12
53
  * ❌ Задача "Тест" упала (2.3s): Quality Gate провален
13
54
  */
14
- export function formatNotificationMessage(payload) {
55
+ export function formatNotificationMessage(payload, templates) {
15
56
  const { taskName, status, durationMs, error } = payload;
16
57
  const duration = formatDuration(durationMs);
17
- if (status === "success") {
58
+ const isSuccess = status === "success";
59
+ const reason = typeof error === "string" && error.trim() ? `: ${error.trim()}` : "";
60
+ if (templates && isSuccess && templates.success.trim()) {
61
+ return renderTemplate(templates.success, {
62
+ task: taskName,
63
+ status,
64
+ duration,
65
+ error: "",
66
+ emoji: "✅",
67
+ });
68
+ }
69
+ if (templates && !isSuccess && templates.error.trim()) {
70
+ return renderTemplate(templates.error, {
71
+ task: taskName,
72
+ status,
73
+ duration,
74
+ error: reason,
75
+ emoji: "❌",
76
+ });
77
+ }
78
+ if (isSuccess) {
18
79
  return `✅ Задача "${taskName}" выполнена (${duration})`;
19
80
  }
20
- const reason = typeof error === "string" && error.trim() ? `: ${error.trim()}` : "";
21
81
  return `❌ Задача "${taskName}" упала (${duration})${reason}`;
22
82
  }
23
- /**
24
- * Отправляет POST на webhook.
25
- *
26
- * Тело совместимо одновременно с Discord (`content`) и Slack (`text`).
27
- * Бросает исключение только для диагностики — вызывающий код обязан
28
- * перехватить его, чтобы уведомление не ломало задачу.
29
- */
30
- export async function sendWebhook(url, message) {
83
+ /** Текст уведомления о завершении матрицы. */
84
+ export function formatMatrixMessage(info) {
85
+ const { parentName, status, total, success, error } = info;
86
+ if (status === "success") {
87
+ return `✅ Матрица "${parentName}" завершилась: ${success} из ${total} клонов успешно.`;
88
+ }
89
+ if (status === "partial") {
90
+ return `⚠️ Матрица "${parentName}" завершилась частично: успешно ${success} из ${total}, ошибок ${error}.`;
91
+ }
92
+ if (total > 0 && error >= total) {
93
+ return `❌ Матрица "${parentName}": все ${total} клонов упали.`;
94
+ }
95
+ return `❌ Матрица "${parentName}" завершилась с ошибками: успешно ${success}, ошибок ${error} из ${total}.`;
96
+ }
97
+ /** Ошибка отправки webhook с признаком, имеет ли смысл повторять запрос. */
98
+ class WebhookError extends Error {
99
+ constructor(message, retryable) {
100
+ super(message);
101
+ this.retryable = retryable;
102
+ }
103
+ }
104
+ const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
105
+ function validateWebhookUrl(url) {
31
106
  const trimmed = (url ?? "").trim();
32
107
  if (!trimmed) {
33
108
  throw new Error("URL вебхука не задан.");
@@ -42,8 +117,12 @@ export async function sendWebhook(url, message) {
42
117
  if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
43
118
  throw new Error("Вебхук поддерживает только http:// или https://.");
44
119
  }
120
+ return parsed;
121
+ }
122
+ /** Одна попытка POST. Бросает WebhookError с признаком retryable. */
123
+ async function postOnce(parsed, message, timeoutMs) {
45
124
  const controller = new AbortController();
46
- const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
125
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
47
126
  try {
48
127
  const response = await fetch(parsed, {
49
128
  method: "POST",
@@ -53,25 +132,85 @@ export async function sendWebhook(url, message) {
53
132
  });
54
133
  if (!response.ok) {
55
134
  const body = await response.text().catch(() => "");
56
- throw new Error(`HTTP ${response.status}${body ? `: ${body.slice(0, 200)}` : ""}`);
135
+ const retryable = response.status >= 500 || response.status === 429;
136
+ throw new WebhookError(`HTTP ${response.status}${body ? `: ${body.slice(0, 200)}` : ""}`, retryable);
57
137
  }
58
138
  }
59
139
  catch (err) {
60
140
  if (err?.name === "AbortError") {
61
- throw new Error(`Таймаут запроса (${REQUEST_TIMEOUT_MS / 1000} с).`);
141
+ throw new WebhookError(`Таймаут запроса (${timeoutMs / 1000} с).`, true);
62
142
  }
63
- throw err instanceof Error ? err : new Error(String(err));
143
+ if (err instanceof WebhookError)
144
+ throw err;
145
+ // Сетевые ошибки fetch (DNS, соединение) имеет смысл повторять.
146
+ throw new WebhookError(err instanceof Error ? err.message : String(err), true);
64
147
  }
65
148
  finally {
66
149
  clearTimeout(timer);
67
150
  }
68
151
  }
152
+ /**
153
+ * Отправляет POST на webhook с повторами и экспоненциальным backoff.
154
+ *
155
+ * Тело совместимо одновременно с Discord (`content`) и Slack (`text`).
156
+ * Повторяются только сетевые ошибки, таймауты, 5xx и 429; прочие 4xx — сразу
157
+ * ошибка (повтор не поможет). Бросает исключение только для диагностики —
158
+ * вызывающий код обязан перехватить его, чтобы уведомление не ломало задачу.
159
+ */
160
+ export async function sendWebhook(url, message, options = {}) {
161
+ const parsed = validateWebhookUrl(url);
162
+ const timeoutMs = Math.max(1, Math.floor(options.timeoutMs ?? REQUEST_TIMEOUT_MS));
163
+ const retryCount = Math.max(0, Math.floor(options.retryCount ?? 0));
164
+ const retryDelayMs = Math.max(1, Math.floor(options.retryDelayMs ?? 1000));
165
+ const sleep = options.sleep ?? defaultSleep;
166
+ const attempts = retryCount + 1;
167
+ let lastError;
168
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
169
+ try {
170
+ await postOnce(parsed, message, timeoutMs);
171
+ return;
172
+ }
173
+ catch (err) {
174
+ lastError = err;
175
+ const retryable = err instanceof WebhookError ? err.retryable : true;
176
+ if (!retryable || attempt === attempts - 1)
177
+ break;
178
+ const delay = Math.min(MAX_RETRY_DELAY_MS, retryDelayMs * 2 ** attempt);
179
+ await sleep(delay);
180
+ }
181
+ }
182
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
183
+ }
184
+ function webhookOptionsFrom(config) {
185
+ const webhook = config.webhook;
186
+ return {
187
+ timeoutMs: webhook?.timeoutMs,
188
+ retryCount: webhook?.retryCount,
189
+ retryDelayMs: webhook?.retryDelayMs,
190
+ };
191
+ }
192
+ /** Отправляет текст во включённый webhook; ошибки только логируются. */
193
+ async function deliver(config, message) {
194
+ const webhook = config.webhook;
195
+ if (!webhook?.enabled || !webhook.url.trim())
196
+ return false;
197
+ try {
198
+ await sendWebhook(webhook.url, message, webhookOptionsFrom(config));
199
+ console.log(`[windows-scheduler] Уведомление отправлено в webhook: ${message}`);
200
+ return true;
201
+ }
202
+ catch (err) {
203
+ console.error(`[windows-scheduler] Не удалось отправить webhook-уведомление: ${err instanceof Error ? err.message : String(err)}`);
204
+ return false;
205
+ }
206
+ }
69
207
  /**
70
208
  * Уведомляет о завершении задачи во все включённые каналы.
71
209
  *
72
210
  * Правила:
73
211
  * - `notifications.enabled === false` — ничего не делает;
74
212
  * - `onlyOnError === true` — успешные запуски пропускаются;
213
+ * - фильтры include/exclude отсекают задачи по имени;
75
214
  * - ошибки отправки только логируются, наружу не выбрасываются.
76
215
  */
77
216
  export async function notifyTaskCompletion(taskName, status, durationMs, error) {
@@ -82,26 +221,245 @@ export async function notifyTaskCompletion(taskName, status, durationMs, error)
82
221
  return;
83
222
  if (config.onlyOnError && status === "success")
84
223
  return;
85
- const message = formatNotificationMessage({
86
- taskName,
87
- status,
88
- durationMs,
89
- error,
224
+ if (!isTaskAllowed(taskName, config.filters))
225
+ return;
226
+ const message = formatNotificationMessage({ taskName, status, durationMs, error }, config.templates);
227
+ await deliver(config, message);
228
+ }
229
+ catch (err) {
230
+ // Уведомление не должно ломать запись истории и саму задачу.
231
+ console.error(`[windows-scheduler] Ошибка подготовки уведомления: ${err instanceof Error ? err.message : String(err)}`);
232
+ }
233
+ }
234
+ /**
235
+ * Уведомляет о завершении матрицы (Спринт 20).
236
+ *
237
+ * partial — только при `matrix.onPartial`; полный провал — при
238
+ * `matrix.onAllFailed`; успех — только когда `onlyOnError === false`.
239
+ */
240
+ export async function notifyMatrixCompletion(info) {
241
+ try {
242
+ const settings = await loadSettings();
243
+ const config = settings.notifications;
244
+ if (!config?.enabled)
245
+ return;
246
+ const matrix = config.matrix;
247
+ if (!matrix?.enabled)
248
+ return;
249
+ if (!isTaskAllowed(info.parentName, config.filters))
250
+ return;
251
+ if (info.status === "partial" && !matrix.onPartial)
252
+ return;
253
+ if (info.status === "error" && !matrix.onAllFailed)
254
+ return;
255
+ if (info.status === "success" && config.onlyOnError)
256
+ return;
257
+ await deliver(config, formatMatrixMessage(info));
258
+ }
259
+ catch (err) {
260
+ console.error(`[windows-scheduler] Ошибка уведомления о матрице: ${err instanceof Error ? err.message : String(err)}`);
261
+ }
262
+ }
263
+ /**
264
+ * Ищет клоны матриц, которые выполняются дольше порога.
265
+ * `parentByClone` — соответствие «имя клона → имя родителя» (без регистра).
266
+ */
267
+ export function findStuckMatrixClones(running, parentByClone, now, thresholdMinutes) {
268
+ if (!Number.isFinite(thresholdMinutes) || thresholdMinutes <= 0)
269
+ return [];
270
+ const thresholdMs = thresholdMinutes * 60000;
271
+ const result = [];
272
+ for (const record of running) {
273
+ const parentName = parentByClone.get(record.taskName.toLowerCase());
274
+ if (!parentName)
275
+ continue;
276
+ const started = new Date(record.startedAt).getTime();
277
+ if (!Number.isFinite(started))
278
+ continue;
279
+ const elapsed = now.getTime() - started;
280
+ if (elapsed < thresholdMs)
281
+ continue;
282
+ result.push({
283
+ id: record.id,
284
+ cloneName: record.taskName,
285
+ parentName,
286
+ startedAt: record.startedAt,
287
+ minutes: Math.floor(elapsed / 60000),
90
288
  });
289
+ }
290
+ return result;
291
+ }
292
+ /** Текст уведомления о зависшем клоне матрицы. */
293
+ export function formatStuckMatrixMessage(stuck) {
294
+ return (`⏳ Матрица "${stuck.parentName}": клон "${stuck.cloneName}" выполняется ` +
295
+ `дольше ${stuck.minutes} мин (запущен ${stuck.startedAt}).`);
296
+ }
297
+ /** Отправляет уведомление о зависшем клоне, если матрицы включены. */
298
+ export async function notifyStuckMatrix(stuck) {
299
+ try {
300
+ const settings = await loadSettings();
301
+ const config = settings.notifications;
302
+ if (!config?.enabled)
303
+ return false;
304
+ if (!config.matrix?.enabled)
305
+ return false;
306
+ if (!isTaskAllowed(stuck.parentName, config.filters))
307
+ return false;
308
+ return await deliver(config, formatStuckMatrixMessage(stuck));
309
+ }
310
+ catch (err) {
311
+ console.error(`[windows-scheduler] Ошибка уведомления о зависшей матрице: ${err instanceof Error ? err.message : String(err)}`);
312
+ return false;
313
+ }
314
+ }
315
+ /** Форматирует деньги: $0.0412. */
316
+ function formatMoney(value) {
317
+ return `$${value.toFixed(4)}`;
318
+ }
319
+ /** Форматирует локальную дату DD.MM.YYYY. */
320
+ function formatLocalDate(date) {
321
+ const day = String(date.getDate()).padStart(2, "0");
322
+ const month = String(date.getMonth() + 1).padStart(2, "0");
323
+ return `${day}.${month}.${date.getFullYear()}`;
324
+ }
325
+ /** Строит сводку дайджеста из записей истории. */
326
+ export function buildDigestSummary(records, options) {
327
+ const now = options.now ?? new Date();
328
+ const windowDays = options.frequency === "weekly" ? 7 : 1;
329
+ const report = buildAnalytics(records, {
330
+ days: windowDays,
331
+ now,
332
+ topLimit: 5,
333
+ });
334
+ return {
335
+ period: options.frequency,
336
+ windowDays,
337
+ total: report.totals.total,
338
+ success: report.totals.success,
339
+ error: report.totals.error,
340
+ partial: report.totals.partial,
341
+ successRate: report.totals.successRate,
342
+ tokens: report.totals.tokens,
343
+ costUsd: report.totals.costUsd,
344
+ topErrors: report.errors,
345
+ };
346
+ }
347
+ /** Текст дайджеста. */
348
+ export function formatDigestMessage(summary, now = new Date()) {
349
+ const periodLabel = summary.period === "weekly" ? "за неделю" : "за сутки";
350
+ const lines = [
351
+ `📊 Дайджест ${periodLabel} (${formatLocalDate(now)})`,
352
+ `Запусков: ${summary.total} — ✅ ${summary.success}, ❌ ${summary.error}, ⚠️ ${summary.partial} (${summary.successRate}%)`,
353
+ `Стоимость: ${formatMoney(summary.costUsd)} · токенов: ${summary.tokens}`,
354
+ ];
355
+ if (summary.topErrors.length > 0) {
356
+ lines.push("Топ ошибок:");
357
+ for (const row of summary.topErrors) {
358
+ lines.push(`• ${row.message} — ${row.count}`);
359
+ }
360
+ }
361
+ else if (summary.total > 0) {
362
+ lines.push("Ошибок нет 🎉");
363
+ }
364
+ return lines.join("\n");
365
+ }
366
+ /**
367
+ * Пора ли отправлять дайджест.
368
+ *
369
+ * daily — раз в сутки после `digest.time`; weekly — по понедельникам после
370
+ * `digest.time`. `lastSentAt` защищает от повторной отправки после перезапуска.
371
+ */
372
+ export function isDigestDue(digest, now) {
373
+ if (!digest.enabled)
374
+ return false;
375
+ const match = /^([01]\d|2[0-3]):([0-5]\d)$/.exec((digest.time ?? "").trim());
376
+ if (!match)
377
+ return false;
378
+ const hour = Number(match[1]);
379
+ const minute = Number(match[2]);
380
+ const target = new Date(now.getTime());
381
+ target.setHours(hour, minute, 0, 0);
382
+ if (digest.frequency === "weekly") {
383
+ // Понедельник текущей недели (getDay(): 0 = воскресенье).
384
+ const offset = (target.getDay() + 6) % 7;
385
+ target.setDate(target.getDate() - offset);
386
+ }
387
+ if (now.getTime() < target.getTime())
388
+ return false;
389
+ if (!digest.lastSentAt)
390
+ return true;
391
+ const last = new Date(digest.lastSentAt).getTime();
392
+ return !Number.isFinite(last) || last < target.getTime();
393
+ }
394
+ /**
395
+ * Собирает и отправляет дайджест.
396
+ *
397
+ * `updateLastSentAt` включается только для плановой отправки: ручная кнопка
398
+ * «Отправить сейчас» не должна сдвигать расписание.
399
+ */
400
+ export async function sendDigestNow(options = {}) {
401
+ const now = options.now ?? new Date();
402
+ try {
403
+ const settings = await loadSettings();
404
+ const config = settings.notifications;
405
+ if (!config?.enabled) {
406
+ return { success: false, message: "Уведомления выключены." };
407
+ }
91
408
  const webhook = config.webhook;
92
- if (webhook?.enabled && webhook.url.trim()) {
93
- try {
94
- await sendWebhook(webhook.url, message);
95
- console.log(`[windows-scheduler] Уведомление отправлено в webhook: ${message}`);
96
- }
97
- catch (err) {
98
- console.error(`[windows-scheduler] Не удалось отправить webhook-уведомление: ${err instanceof Error ? err.message : String(err)}`);
99
- }
409
+ if (!webhook?.enabled || !webhook.url.trim()) {
410
+ return { success: false, message: "Webhook выключен. Включите канал и укажите URL." };
100
411
  }
412
+ const digest = config.digest;
413
+ if (!digest) {
414
+ return { success: false, message: "Настройки дайджеста не найдены." };
415
+ }
416
+ const records = getHistory(null, 5000);
417
+ const summary = buildDigestSummary(records, {
418
+ frequency: digest.frequency,
419
+ now,
420
+ });
421
+ const text = formatDigestMessage(summary, now);
422
+ await sendWebhook(webhook.url, text, webhookOptionsFrom(config));
423
+ if (options.updateLastSentAt) {
424
+ await saveSettings({
425
+ notifications: {
426
+ ...config,
427
+ digest: { ...digest, lastSentAt: now.toISOString() },
428
+ },
429
+ });
430
+ }
431
+ return { success: true, message: "Дайджест отправлен." };
101
432
  }
102
433
  catch (err) {
103
- // Уведомление не должно ломать запись истории и саму задачу.
104
- console.error(`[windows-scheduler] Ошибка подготовки уведомления: ${err instanceof Error ? err.message : String(err)}`);
434
+ return {
435
+ success: false,
436
+ message: err instanceof Error ? err.message : String(err),
437
+ };
438
+ }
439
+ }
440
+ /** Плановая проверка дайджеста: отправляет, если пора. Возвращает true при отправке. */
441
+ export async function maybeSendDigest(now = new Date()) {
442
+ try {
443
+ const settings = await loadSettings();
444
+ const config = settings.notifications;
445
+ if (!config?.enabled)
446
+ return false;
447
+ const digest = config.digest;
448
+ if (!digest?.enabled)
449
+ return false;
450
+ if (!isDigestDue(digest, now))
451
+ return false;
452
+ const result = await sendDigestNow({ now, updateLastSentAt: true });
453
+ if (result.success) {
454
+ console.log("[windows-scheduler] Дайджест уведомлений отправлен.");
455
+ return true;
456
+ }
457
+ console.error(`[windows-scheduler] Дайджест не отправлен: ${result.message}`);
458
+ return false;
459
+ }
460
+ catch (err) {
461
+ console.error(`[windows-scheduler] Ошибка дайджеста: ${err instanceof Error ? err.message : String(err)}`);
462
+ return false;
105
463
  }
106
464
  }
107
465
  /**
@@ -123,7 +481,11 @@ export async function sendTestNotification() {
123
481
  if (!webhook.url.trim()) {
124
482
  return { success: false, message: "Не задан URL вебхука." };
125
483
  }
126
- await sendWebhook(webhook.url, "🧪 Тестовое уведомление от OpenCode Scheduler — webhook настроен корректно.");
484
+ await sendWebhook(webhook.url, "🧪 Тестовое уведомление от OpenCode Scheduler — webhook настроен корректно.", {
485
+ timeoutMs: webhook.timeoutMs,
486
+ retryCount: webhook.retryCount,
487
+ retryDelayMs: webhook.retryDelayMs,
488
+ });
127
489
  return { success: true, message: "Тестовое уведомление отправлено." };
128
490
  }
129
491
  catch (err) {
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Профили (Спринт 21): каждый профиль — отдельная директория со своей БД,
3
+ * настройками, логами, обёртками и портом дашборда. Профиль `default`
4
+ * использует базовую директорию плагина (как раньше — без миграции), остальные
5
+ * живут в `<base>/profiles/<name>`.
6
+ */
7
+ export declare const DEFAULT_PROFILE = "default";
8
+ /** Метаданные профиля: имя и порт дашборда. */
9
+ export interface ProfileMeta {
10
+ name: string;
11
+ port: number;
12
+ }
13
+ /** Описание профиля для RPC/GUI. */
14
+ export interface ProfileInfo {
15
+ name: string;
16
+ dir: string;
17
+ port: number | null;
18
+ isDefault: boolean;
19
+ active: boolean;
20
+ }
21
+ /**
22
+ * Базовая директория плагина (до профилей).
23
+ *
24
+ * Windows: %APPDATA%\opencode\windows-scheduler.
25
+ * macOS/Linux: $XDG_CONFIG_HOME/opencode/windows-scheduler или
26
+ * ~/.config/opencode/windows-scheduler.
27
+ * OPENCODE_SCHEDULER_HOME переопределяет всё (тесты, кастомные установки).
28
+ */
29
+ export declare function getBasePluginDir(): string;
30
+ /** Нормализует имя профиля: нижний регистр, только [a-z0-9_-]. */
31
+ export declare function sanitizeProfileName(value: string | null | undefined): string;
32
+ /** Валидация имени профиля (без «исправления»): пусто/кривые символы — ошибка. */
33
+ export declare function validateProfileName(value: string): string | null;
34
+ /**
35
+ * Имя текущего профиля: OPENCODE_SCHEDULER_PROFILE > файл-маркер > default.
36
+ */
37
+ export declare function getProfileName(): string;
38
+ /** Директория профиля: default — базовая, остальные — <base>/profiles/<name>. */
39
+ export declare function getProfileDir(name?: string): string;
40
+ /** Читает profile.json профиля (или null, если файла нет/он битый). */
41
+ export declare function readProfileMeta(name: string): ProfileMeta | null;
42
+ /** Порт дашборда профиля: env > profile.json > null (дефолтная логика сервера). */
43
+ export declare function getProfilePort(name?: string): number | null;
44
+ /** Список существующих профилей (default всегда первый). */
45
+ export declare function listProfiles(): ProfileInfo[];
46
+ /**
47
+ * Создаёт профиль: директорию + profile.json. Для default просто гарантирует
48
+ * базовую директорию. Возвращает метаданные профиля.
49
+ */
50
+ export declare function createProfile(name: string, port?: number): ProfileMeta;
51
+ /** Удаляет профиль (кроме default). Возвращает true, если директория удалена. */
52
+ export declare function deleteProfile(name: string): boolean;
53
+ /**
54
+ * Переключает активный профиль через файл-маркер. Изменение подхватится при
55
+ * следующем запуске OpenCode (директории вычисляются при загрузке модуля).
56
+ */
57
+ export declare function setActiveProfile(name: string): void;
58
+ /** true, если профиль переключается переменной окружения (маркер не поможет). */
59
+ export declare function isProfilePinnedByEnv(): boolean;
60
+ //# sourceMappingURL=profiles.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"profiles.d.ts","sourceRoot":"","sources":["../src/profiles.ts"],"names":[],"mappings":"AAIA;;;;;GAKG;AAEH,eAAO,MAAM,eAAe,YAAY,CAAC;AAKzC,+CAA+C;AAC/C,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;CACd;AAED,oCAAoC;AACpC,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,SAAS,EAAE,OAAO,CAAC;IACnB,MAAM,EAAE,OAAO,CAAC;CACjB;AAED;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,IAAI,MAAM,CAWzC;AAED,kEAAkE;AAClE,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,CAQ5E;AAED,kFAAkF;AAClF,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAOhE;AAYD;;GAEG;AACH,wBAAgB,cAAc,IAAI,MAAM,CAIvC;AAED,iFAAiF;AACjF,wBAAgB,aAAa,CAAC,IAAI,GAAE,MAAyB,GAAG,MAAM,CAKrE;AAOD,uEAAuE;AACvE,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,GAAG,IAAI,CAahE;AAED,mFAAmF;AACnF,wBAAgB,cAAc,CAAC,IAAI,GAAE,MAAyB,GAAG,MAAM,GAAG,IAAI,CAQ7E;AAED,4DAA4D;AAC5D,wBAAgB,YAAY,IAAI,WAAW,EAAE,CA6B5C;AAcD;;;GAGG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,WAAW,CAkBtE;AAED,iFAAiF;AACjF,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAenD;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAQnD;AAED,iFAAiF;AACjF,wBAAgB,oBAAoB,IAAI,OAAO,CAE9C"}