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.
- package/CHANGELOG.md +60 -1
- package/README.md +18 -8
- package/README.ru.md +13 -3
- package/ROADMAP-STRATEGY.md +2 -2
- package/ROADMAP.md +51 -18
- package/dist/core/analytics.d.ts +10 -0
- package/dist/core/analytics.d.ts.map +1 -1
- package/dist/core/analytics.js +21 -0
- package/dist/core/dry-run.d.ts +18 -1
- package/dist/core/dry-run.d.ts.map +1 -1
- package/dist/core/dry-run.js +49 -3
- package/dist/core/matrix.d.ts.map +1 -1
- package/dist/core/matrix.js +10 -0
- package/dist/core/one-shot.d.ts +62 -0
- package/dist/core/one-shot.d.ts.map +1 -0
- package/dist/core/one-shot.js +126 -0
- package/dist/core/otel.d.ts +4 -0
- package/dist/core/otel.d.ts.map +1 -0
- package/dist/core/otel.js +98 -0
- package/dist/core/prometheus.d.ts +23 -0
- package/dist/core/prometheus.d.ts.map +1 -0
- package/dist/core/prometheus.js +146 -0
- package/dist/core/ps-wrapper.d.ts +36 -2
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +124 -4
- package/dist/core/record-history.d.ts.map +1 -1
- package/dist/core/record-history.js +9 -0
- package/dist/core/schedule-gate.d.ts +2 -0
- package/dist/core/schedule-gate.d.ts.map +1 -0
- package/dist/core/schedule-gate.js +182 -0
- package/dist/core/schedule-v2.d.ts +88 -0
- package/dist/core/schedule-v2.d.ts.map +1 -0
- package/dist/core/schedule-v2.js +496 -0
- package/dist/core/scheduler/linux.d.ts +12 -3
- package/dist/core/scheduler/linux.d.ts.map +1 -1
- package/dist/core/scheduler/linux.js +80 -3
- package/dist/core/scheduler/mac.d.ts.map +1 -1
- package/dist/core/scheduler/mac.js +17 -3
- package/dist/core/scheduler/posix.d.ts.map +1 -1
- package/dist/core/scheduler/posix.js +3 -0
- package/dist/core/scheduler/registry.d.ts +4 -0
- package/dist/core/scheduler/registry.d.ts.map +1 -1
- package/dist/core/scheduler/types.d.ts +20 -3
- package/dist/core/scheduler/types.d.ts.map +1 -1
- package/dist/core/scheduler/windows.d.ts.map +1 -1
- package/dist/core/scheduler/windows.js +23 -2
- package/dist/core/session.d.ts +34 -0
- package/dist/core/session.d.ts.map +1 -0
- package/dist/core/session.js +105 -0
- package/dist/core/structured-log.d.ts +84 -0
- package/dist/core/structured-log.d.ts.map +1 -0
- package/dist/core/structured-log.js +137 -0
- package/dist/core/wrappers/bash.d.ts +24 -0
- package/dist/core/wrappers/bash.d.ts.map +1 -1
- package/dist/core/wrappers/bash.js +70 -3
- package/dist/db/history-repo.d.ts +8 -0
- package/dist/db/history-repo.d.ts.map +1 -1
- package/dist/db/history-repo.js +76 -6
- package/dist/db/metrics-repo.d.ts +3 -0
- package/dist/db/metrics-repo.d.ts.map +1 -1
- package/dist/db/metrics-repo.js +16 -8
- package/dist/db/migrate.d.ts.map +1 -1
- package/dist/db/migrate.js +8 -1
- package/dist/db/schema.d.ts +1 -1
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +19 -0
- package/dist/gui-experimental.cjs +1 -0
- package/dist/history.d.ts +7 -0
- package/dist/history.d.ts.map +1 -1
- package/dist/history.js +13 -0
- package/dist/index.d.ts +137 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1323 -78
- package/dist/integrations.d.ts +64 -0
- package/dist/integrations.d.ts.map +1 -0
- package/dist/integrations.js +205 -0
- package/dist/notifications.d.ts +112 -6
- package/dist/notifications.d.ts.map +1 -1
- package/dist/notifications.js +396 -34
- package/dist/profiles.d.ts +60 -0
- package/dist/profiles.d.ts.map +1 -0
- package/dist/profiles.js +209 -0
- package/dist/rpc.d.ts +592 -4
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +233 -6
- package/dist/server.d.ts +2 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +473 -58
- package/dist/settings.d.ts +95 -0
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +186 -8
- package/dist/shared/jobs-view.d.ts +43 -5
- package/dist/shared/jobs-view.d.ts.map +1 -1
- package/dist/shared/jobs-view.js +125 -7
- package/dist/task-transfer.d.ts +32 -3
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +101 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +3 -11
- package/dist/workspaces.d.ts +43 -0
- package/dist/workspaces.d.ts.map +1 -1
- package/dist/workspaces.js +174 -8
- package/docs/ARCHITECTURE.md +32 -12
- package/docs/FEATURES.md +186 -10
- package/gui-experimental.cjs +4 -2
- package/package.json +15 -2
- package/scripts/demo-dashboard.mjs +12 -2
- package/src/core/analytics.ts +36 -0
- package/src/core/dry-run.ts +65 -4
- package/src/core/matrix.ts +10 -0
- package/src/core/one-shot.ts +173 -0
- package/src/core/otel.ts +128 -0
- package/src/core/prometheus.ts +215 -0
- package/src/core/ps-wrapper.ts +144 -4
- package/src/core/record-history.ts +13 -0
- package/src/core/schedule-gate.ts +213 -0
- package/src/core/schedule-v2.ts +533 -0
- package/src/core/scheduler/linux.ts +90 -3
- package/src/core/scheduler/mac.ts +35 -4
- package/src/core/scheduler/posix.ts +3 -0
- package/src/core/scheduler/registry.ts +4 -0
- package/src/core/scheduler/types.ts +20 -3
- package/src/core/scheduler/windows.ts +24 -2
- package/src/core/session.ts +115 -0
- package/src/core/structured-log.ts +205 -0
- package/src/core/wrappers/bash.ts +98 -2
- package/src/db/history-repo.ts +90 -7
- package/src/db/metrics-repo.ts +19 -7
- package/src/db/migrate.ts +7 -1
- package/src/db/schema.ts +25 -0
- package/src/gui.tsx +3832 -2868
- package/src/history.ts +17 -0
- package/src/index.ts +1670 -117
- package/src/integrations.ts +253 -0
- package/src/notifications.ts +516 -40
- package/src/profiles.ts +236 -0
- package/src/rpc.ts +244 -6
- package/src/server.ts +506 -58
- package/src/settings.ts +336 -9
- package/src/shared/jobs-view.ts +158 -8
- package/src/task-transfer.ts +151 -5
- package/src/tui.tsx +290 -14
- package/src/types.ts +3 -13
- package/src/workspaces.ts +214 -8
package/src/notifications.ts
CHANGED
|
@@ -1,4 +1,18 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
loadSettings,
|
|
3
|
+
saveSettings,
|
|
4
|
+
type DigestFrequency,
|
|
5
|
+
type DigestSettings,
|
|
6
|
+
type NotificationFilters,
|
|
7
|
+
type NotificationSettings,
|
|
8
|
+
type NotificationTemplates,
|
|
9
|
+
} from "./settings.js";
|
|
10
|
+
import {
|
|
11
|
+
buildAnalytics,
|
|
12
|
+
type AnalyticsRecord,
|
|
13
|
+
type ErrorAnalyticsRow,
|
|
14
|
+
} from "./core/analytics.js";
|
|
15
|
+
import { getHistory } from "./db/history-repo.js";
|
|
2
16
|
|
|
3
17
|
/** Статус завершения задачи, который приходит из record-history. */
|
|
4
18
|
export type NotificationStatus = "success" | "error" | "timeout" | string;
|
|
@@ -11,45 +25,155 @@ export interface NotificationPayload {
|
|
|
11
25
|
error?: string | null;
|
|
12
26
|
}
|
|
13
27
|
|
|
14
|
-
/** Таймаут HTTP
|
|
28
|
+
/** Таймаут HTTP-запроса по умолчанию: уведомление не должно подвешивать задачу. */
|
|
15
29
|
const REQUEST_TIMEOUT_MS = 10_000;
|
|
16
30
|
|
|
31
|
+
/** Максимальная задержка backoff между повторами. */
|
|
32
|
+
const MAX_RETRY_DELAY_MS = 30_000;
|
|
33
|
+
|
|
17
34
|
/** Человекочитаемая длительность: 2300 мс → «2.3s». */
|
|
18
35
|
export function formatDuration(durationMs: number): string {
|
|
19
36
|
const seconds = Math.max(0, Number(durationMs) || 0) / 1000;
|
|
20
37
|
return `${seconds.toFixed(1)}s`;
|
|
21
38
|
}
|
|
22
39
|
|
|
40
|
+
/** Экранирует regexp-спецсимволы. */
|
|
41
|
+
function escapeRegExp(text: string): string {
|
|
42
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
43
|
+
}
|
|
44
|
+
|
|
23
45
|
/**
|
|
24
|
-
*
|
|
46
|
+
* Сопоставление имени задачи с шаблоном: `*` — любая последовательность,
|
|
47
|
+
* регистр не важен. `regen-*` покрывает `regen-api`, `regen-ui`.
|
|
48
|
+
*/
|
|
49
|
+
export function wildcardMatch(pattern: string, value: string): boolean {
|
|
50
|
+
const trimmed = (pattern ?? "").trim();
|
|
51
|
+
if (!trimmed) return false;
|
|
52
|
+
const source = trimmed
|
|
53
|
+
.split("*")
|
|
54
|
+
.map((part) => escapeRegExp(part))
|
|
55
|
+
.join(".*");
|
|
56
|
+
return new RegExp(`^${source}$`, "i").test(value.trim());
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Проверяет, разрешена ли задача фильтрами include/exclude. */
|
|
60
|
+
export function isTaskAllowed(
|
|
61
|
+
taskName: string,
|
|
62
|
+
filters?: NotificationFilters
|
|
63
|
+
): boolean {
|
|
64
|
+
if (!filters) return true;
|
|
65
|
+
const name = (taskName ?? "").trim();
|
|
66
|
+
if (!name) return false;
|
|
67
|
+
const exclude = filters.exclude ?? [];
|
|
68
|
+
if (exclude.some((pattern) => wildcardMatch(pattern, name))) return false;
|
|
69
|
+
const include = filters.include ?? [];
|
|
70
|
+
if (include.length === 0) return true;
|
|
71
|
+
return include.some((pattern) => wildcardMatch(pattern, name));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Подставляет {key} в шаблон; неизвестные плейсхолдеры остаются как есть. */
|
|
75
|
+
export function renderTemplate(
|
|
76
|
+
template: string,
|
|
77
|
+
vars: Record<string, string>
|
|
78
|
+
): string {
|
|
79
|
+
return template.replace(/\{(\w+)\}/g, (match, key: string) =>
|
|
80
|
+
Object.prototype.hasOwnProperty.call(vars, key) ? vars[key] : match
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Формат сообщения по умолчанию:
|
|
25
86
|
* ✅ Задача "Тест" выполнена (2.3s)
|
|
26
87
|
* ❌ Задача "Тест" упала (2.3s): Quality Gate провален
|
|
27
88
|
*/
|
|
28
|
-
export function formatNotificationMessage(
|
|
89
|
+
export function formatNotificationMessage(
|
|
90
|
+
payload: NotificationPayload,
|
|
91
|
+
templates?: NotificationTemplates
|
|
92
|
+
): string {
|
|
29
93
|
const { taskName, status, durationMs, error } = payload;
|
|
30
94
|
const duration = formatDuration(durationMs);
|
|
95
|
+
const isSuccess = status === "success";
|
|
96
|
+
const reason =
|
|
97
|
+
typeof error === "string" && error.trim() ? `: ${error.trim()}` : "";
|
|
31
98
|
|
|
32
|
-
if (
|
|
33
|
-
return
|
|
99
|
+
if (templates && isSuccess && templates.success.trim()) {
|
|
100
|
+
return renderTemplate(templates.success, {
|
|
101
|
+
task: taskName,
|
|
102
|
+
status,
|
|
103
|
+
duration,
|
|
104
|
+
error: "",
|
|
105
|
+
emoji: "✅",
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
if (templates && !isSuccess && templates.error.trim()) {
|
|
109
|
+
return renderTemplate(templates.error, {
|
|
110
|
+
task: taskName,
|
|
111
|
+
status,
|
|
112
|
+
duration,
|
|
113
|
+
error: reason,
|
|
114
|
+
emoji: "❌",
|
|
115
|
+
});
|
|
34
116
|
}
|
|
35
117
|
|
|
36
|
-
|
|
118
|
+
if (isSuccess) {
|
|
119
|
+
return `✅ Задача "${taskName}" выполнена (${duration})`;
|
|
120
|
+
}
|
|
37
121
|
return `❌ Задача "${taskName}" упала (${duration})${reason}`;
|
|
38
122
|
}
|
|
39
123
|
|
|
40
|
-
/**
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
124
|
+
/** Информация о завершении матрицы для уведомления. */
|
|
125
|
+
export interface MatrixNotificationInfo {
|
|
126
|
+
parentName: string;
|
|
127
|
+
status: "success" | "error" | "partial";
|
|
128
|
+
total: number;
|
|
129
|
+
success: number;
|
|
130
|
+
error: number;
|
|
131
|
+
message?: string | null;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Текст уведомления о завершении матрицы. */
|
|
135
|
+
export function formatMatrixMessage(info: MatrixNotificationInfo): string {
|
|
136
|
+
const { parentName, status, total, success, error } = info;
|
|
137
|
+
if (status === "success") {
|
|
138
|
+
return `✅ Матрица "${parentName}" завершилась: ${success} из ${total} клонов успешно.`;
|
|
139
|
+
}
|
|
140
|
+
if (status === "partial") {
|
|
141
|
+
return `⚠️ Матрица "${parentName}" завершилась частично: успешно ${success} из ${total}, ошибок ${error}.`;
|
|
142
|
+
}
|
|
143
|
+
if (total > 0 && error >= total) {
|
|
144
|
+
return `❌ Матрица "${parentName}": все ${total} клонов упали.`;
|
|
145
|
+
}
|
|
146
|
+
return `❌ Матрица "${parentName}" завершилась с ошибками: успешно ${success}, ошибок ${error} из ${total}.`;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Ошибка отправки webhook с признаком, имеет ли смысл повторять запрос. */
|
|
150
|
+
class WebhookError extends Error {
|
|
151
|
+
readonly retryable: boolean;
|
|
152
|
+
constructor(message: string, retryable: boolean) {
|
|
153
|
+
super(message);
|
|
154
|
+
this.retryable = retryable;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export interface WebhookOptions {
|
|
159
|
+
/** Таймаут одной попытки в мс (по умолчанию 10 с). */
|
|
160
|
+
timeoutMs?: number;
|
|
161
|
+
/** Сколько раз повторить после неудачи (по умолчанию 0). */
|
|
162
|
+
retryCount?: number;
|
|
163
|
+
/** Базовая задержка backoff в мс (по умолчанию 1000). */
|
|
164
|
+
retryDelayMs?: number;
|
|
165
|
+
/** Подмена sleep для тестов. */
|
|
166
|
+
sleep?: (ms: number) => Promise<void>;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const defaultSleep = (ms: number) =>
|
|
170
|
+
new Promise<void>((resolve) => setTimeout(resolve, ms));
|
|
171
|
+
|
|
172
|
+
function validateWebhookUrl(url: string): URL {
|
|
48
173
|
const trimmed = (url ?? "").trim();
|
|
49
174
|
if (!trimmed) {
|
|
50
175
|
throw new Error("URL вебхука не задан.");
|
|
51
176
|
}
|
|
52
|
-
|
|
53
177
|
let parsed: URL;
|
|
54
178
|
try {
|
|
55
179
|
parsed = new URL(trimmed);
|
|
@@ -59,9 +183,17 @@ export async function sendWebhook(url: string, message: string): Promise<void> {
|
|
|
59
183
|
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
60
184
|
throw new Error("Вебхук поддерживает только http:// или https://.");
|
|
61
185
|
}
|
|
186
|
+
return parsed;
|
|
187
|
+
}
|
|
62
188
|
|
|
189
|
+
/** Одна попытка POST. Бросает WebhookError с признаком retryable. */
|
|
190
|
+
async function postOnce(
|
|
191
|
+
parsed: URL,
|
|
192
|
+
message: string,
|
|
193
|
+
timeoutMs: number
|
|
194
|
+
): Promise<void> {
|
|
63
195
|
const controller = new AbortController();
|
|
64
|
-
const timer = setTimeout(() => controller.abort(),
|
|
196
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
65
197
|
try {
|
|
66
198
|
const response = await fetch(parsed, {
|
|
67
199
|
method: "POST",
|
|
@@ -72,26 +204,97 @@ export async function sendWebhook(url: string, message: string): Promise<void> {
|
|
|
72
204
|
|
|
73
205
|
if (!response.ok) {
|
|
74
206
|
const body = await response.text().catch(() => "");
|
|
75
|
-
|
|
76
|
-
|
|
207
|
+
const retryable = response.status >= 500 || response.status === 429;
|
|
208
|
+
throw new WebhookError(
|
|
209
|
+
`HTTP ${response.status}${body ? `: ${body.slice(0, 200)}` : ""}`,
|
|
210
|
+
retryable
|
|
77
211
|
);
|
|
78
212
|
}
|
|
79
213
|
} catch (err: any) {
|
|
80
214
|
if (err?.name === "AbortError") {
|
|
81
|
-
throw new
|
|
215
|
+
throw new WebhookError(`Таймаут запроса (${timeoutMs / 1000} с).`, true);
|
|
82
216
|
}
|
|
83
|
-
|
|
217
|
+
if (err instanceof WebhookError) throw err;
|
|
218
|
+
// Сетевые ошибки fetch (DNS, соединение) имеет смысл повторять.
|
|
219
|
+
throw new WebhookError(err instanceof Error ? err.message : String(err), true);
|
|
84
220
|
} finally {
|
|
85
221
|
clearTimeout(timer);
|
|
86
222
|
}
|
|
87
223
|
}
|
|
88
224
|
|
|
225
|
+
/**
|
|
226
|
+
* Отправляет POST на webhook с повторами и экспоненциальным backoff.
|
|
227
|
+
*
|
|
228
|
+
* Тело совместимо одновременно с Discord (`content`) и Slack (`text`).
|
|
229
|
+
* Повторяются только сетевые ошибки, таймауты, 5xx и 429; прочие 4xx — сразу
|
|
230
|
+
* ошибка (повтор не поможет). Бросает исключение только для диагностики —
|
|
231
|
+
* вызывающий код обязан перехватить его, чтобы уведомление не ломало задачу.
|
|
232
|
+
*/
|
|
233
|
+
export async function sendWebhook(
|
|
234
|
+
url: string,
|
|
235
|
+
message: string,
|
|
236
|
+
options: WebhookOptions = {}
|
|
237
|
+
): Promise<void> {
|
|
238
|
+
const parsed = validateWebhookUrl(url);
|
|
239
|
+
const timeoutMs = Math.max(1, Math.floor(options.timeoutMs ?? REQUEST_TIMEOUT_MS));
|
|
240
|
+
const retryCount = Math.max(0, Math.floor(options.retryCount ?? 0));
|
|
241
|
+
const retryDelayMs = Math.max(1, Math.floor(options.retryDelayMs ?? 1_000));
|
|
242
|
+
const sleep = options.sleep ?? defaultSleep;
|
|
243
|
+
|
|
244
|
+
const attempts = retryCount + 1;
|
|
245
|
+
let lastError: unknown;
|
|
246
|
+
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
247
|
+
try {
|
|
248
|
+
await postOnce(parsed, message, timeoutMs);
|
|
249
|
+
return;
|
|
250
|
+
} catch (err) {
|
|
251
|
+
lastError = err;
|
|
252
|
+
const retryable = err instanceof WebhookError ? err.retryable : true;
|
|
253
|
+
if (!retryable || attempt === attempts - 1) break;
|
|
254
|
+
const delay = Math.min(
|
|
255
|
+
MAX_RETRY_DELAY_MS,
|
|
256
|
+
retryDelayMs * 2 ** attempt
|
|
257
|
+
);
|
|
258
|
+
await sleep(delay);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
throw lastError instanceof Error ? lastError : new Error(String(lastError));
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function webhookOptionsFrom(config: NotificationSettings): WebhookOptions {
|
|
265
|
+
const webhook = config.webhook;
|
|
266
|
+
return {
|
|
267
|
+
timeoutMs: webhook?.timeoutMs,
|
|
268
|
+
retryCount: webhook?.retryCount,
|
|
269
|
+
retryDelayMs: webhook?.retryDelayMs,
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Отправляет текст во включённый webhook; ошибки только логируются. */
|
|
274
|
+
async function deliver(config: NotificationSettings, message: string): Promise<boolean> {
|
|
275
|
+
const webhook = config.webhook;
|
|
276
|
+
if (!webhook?.enabled || !webhook.url.trim()) return false;
|
|
277
|
+
try {
|
|
278
|
+
await sendWebhook(webhook.url, message, webhookOptionsFrom(config));
|
|
279
|
+
console.log(`[windows-scheduler] Уведомление отправлено в webhook: ${message}`);
|
|
280
|
+
return true;
|
|
281
|
+
} catch (err: any) {
|
|
282
|
+
console.error(
|
|
283
|
+
`[windows-scheduler] Не удалось отправить webhook-уведомление: ${
|
|
284
|
+
err instanceof Error ? err.message : String(err)
|
|
285
|
+
}`
|
|
286
|
+
);
|
|
287
|
+
return false;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
89
291
|
/**
|
|
90
292
|
* Уведомляет о завершении задачи во все включённые каналы.
|
|
91
293
|
*
|
|
92
294
|
* Правила:
|
|
93
295
|
* - `notifications.enabled === false` — ничего не делает;
|
|
94
296
|
* - `onlyOnError === true` — успешные запуски пропускаются;
|
|
297
|
+
* - фильтры include/exclude отсекают задачи по имени;
|
|
95
298
|
* - ошибки отправки только логируются, наружу не выбрасываются.
|
|
96
299
|
*/
|
|
97
300
|
export async function notifyTaskCompletion(
|
|
@@ -105,34 +308,302 @@ export async function notifyTaskCompletion(
|
|
|
105
308
|
const config = settings.notifications;
|
|
106
309
|
if (!config?.enabled) return;
|
|
107
310
|
if (config.onlyOnError && status === "success") return;
|
|
311
|
+
if (!isTaskAllowed(taskName, config.filters)) return;
|
|
108
312
|
|
|
109
|
-
const message = formatNotificationMessage(
|
|
110
|
-
taskName,
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
313
|
+
const message = formatNotificationMessage(
|
|
314
|
+
{ taskName, status, durationMs, error },
|
|
315
|
+
config.templates
|
|
316
|
+
);
|
|
317
|
+
await deliver(config, message);
|
|
318
|
+
} catch (err: any) {
|
|
319
|
+
// Уведомление не должно ломать запись истории и саму задачу.
|
|
320
|
+
console.error(
|
|
321
|
+
`[windows-scheduler] Ошибка подготовки уведомления: ${
|
|
322
|
+
err instanceof Error ? err.message : String(err)
|
|
323
|
+
}`
|
|
324
|
+
);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Уведомляет о завершении матрицы (Спринт 20).
|
|
330
|
+
*
|
|
331
|
+
* partial — только при `matrix.onPartial`; полный провал — при
|
|
332
|
+
* `matrix.onAllFailed`; успех — только когда `onlyOnError === false`.
|
|
333
|
+
*/
|
|
334
|
+
export async function notifyMatrixCompletion(
|
|
335
|
+
info: MatrixNotificationInfo
|
|
336
|
+
): Promise<void> {
|
|
337
|
+
try {
|
|
338
|
+
const settings = await loadSettings();
|
|
339
|
+
const config = settings.notifications;
|
|
340
|
+
if (!config?.enabled) return;
|
|
341
|
+
const matrix = config.matrix;
|
|
342
|
+
if (!matrix?.enabled) return;
|
|
343
|
+
if (!isTaskAllowed(info.parentName, config.filters)) return;
|
|
344
|
+
|
|
345
|
+
if (info.status === "partial" && !matrix.onPartial) return;
|
|
346
|
+
if (info.status === "error" && !matrix.onAllFailed) return;
|
|
347
|
+
if (info.status === "success" && config.onlyOnError) return;
|
|
348
|
+
|
|
349
|
+
await deliver(config, formatMatrixMessage(info));
|
|
350
|
+
} catch (err: any) {
|
|
351
|
+
console.error(
|
|
352
|
+
`[windows-scheduler] Ошибка уведомления о матрице: ${
|
|
353
|
+
err instanceof Error ? err.message : String(err)
|
|
354
|
+
}`
|
|
355
|
+
);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** Запись о незавершённом запуске (для детектора зависших матриц). */
|
|
360
|
+
export interface RunningTaskRecord {
|
|
361
|
+
id: number;
|
|
362
|
+
taskName: string;
|
|
363
|
+
startedAt: string;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** Найденный зависший клон матрицы. */
|
|
367
|
+
export interface StuckMatrixClone {
|
|
368
|
+
id: number;
|
|
369
|
+
cloneName: string;
|
|
370
|
+
parentName: string;
|
|
371
|
+
startedAt: string;
|
|
372
|
+
minutes: number;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* Ищет клоны матриц, которые выполняются дольше порога.
|
|
377
|
+
* `parentByClone` — соответствие «имя клона → имя родителя» (без регистра).
|
|
378
|
+
*/
|
|
379
|
+
export function findStuckMatrixClones(
|
|
380
|
+
running: RunningTaskRecord[],
|
|
381
|
+
parentByClone: Map<string, string>,
|
|
382
|
+
now: Date,
|
|
383
|
+
thresholdMinutes: number
|
|
384
|
+
): StuckMatrixClone[] {
|
|
385
|
+
if (!Number.isFinite(thresholdMinutes) || thresholdMinutes <= 0) return [];
|
|
386
|
+
const thresholdMs = thresholdMinutes * 60_000;
|
|
387
|
+
const result: StuckMatrixClone[] = [];
|
|
388
|
+
for (const record of running) {
|
|
389
|
+
const parentName = parentByClone.get(record.taskName.toLowerCase());
|
|
390
|
+
if (!parentName) continue;
|
|
391
|
+
const started = new Date(record.startedAt).getTime();
|
|
392
|
+
if (!Number.isFinite(started)) continue;
|
|
393
|
+
const elapsed = now.getTime() - started;
|
|
394
|
+
if (elapsed < thresholdMs) continue;
|
|
395
|
+
result.push({
|
|
396
|
+
id: record.id,
|
|
397
|
+
cloneName: record.taskName,
|
|
398
|
+
parentName,
|
|
399
|
+
startedAt: record.startedAt,
|
|
400
|
+
minutes: Math.floor(elapsed / 60_000),
|
|
114
401
|
});
|
|
402
|
+
}
|
|
403
|
+
return result;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** Текст уведомления о зависшем клоне матрицы. */
|
|
407
|
+
export function formatStuckMatrixMessage(stuck: StuckMatrixClone): string {
|
|
408
|
+
return (
|
|
409
|
+
`⏳ Матрица "${stuck.parentName}": клон "${stuck.cloneName}" выполняется ` +
|
|
410
|
+
`дольше ${stuck.minutes} мин (запущен ${stuck.startedAt}).`
|
|
411
|
+
);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/** Отправляет уведомление о зависшем клоне, если матрицы включены. */
|
|
415
|
+
export async function notifyStuckMatrix(stuck: StuckMatrixClone): Promise<boolean> {
|
|
416
|
+
try {
|
|
417
|
+
const settings = await loadSettings();
|
|
418
|
+
const config = settings.notifications;
|
|
419
|
+
if (!config?.enabled) return false;
|
|
420
|
+
if (!config.matrix?.enabled) return false;
|
|
421
|
+
if (!isTaskAllowed(stuck.parentName, config.filters)) return false;
|
|
422
|
+
return await deliver(config, formatStuckMatrixMessage(stuck));
|
|
423
|
+
} catch (err: any) {
|
|
424
|
+
console.error(
|
|
425
|
+
`[windows-scheduler] Ошибка уведомления о зависшей матрице: ${
|
|
426
|
+
err instanceof Error ? err.message : String(err)
|
|
427
|
+
}`
|
|
428
|
+
);
|
|
429
|
+
return false;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/** Сводка для дайджеста. */
|
|
434
|
+
export interface DigestSummary {
|
|
435
|
+
period: "daily" | "weekly";
|
|
436
|
+
windowDays: number;
|
|
437
|
+
total: number;
|
|
438
|
+
success: number;
|
|
439
|
+
error: number;
|
|
440
|
+
partial: number;
|
|
441
|
+
successRate: number;
|
|
442
|
+
tokens: number;
|
|
443
|
+
costUsd: number;
|
|
444
|
+
topErrors: ErrorAnalyticsRow[];
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** Форматирует деньги: $0.0412. */
|
|
448
|
+
function formatMoney(value: number): string {
|
|
449
|
+
return `$${value.toFixed(4)}`;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** Форматирует локальную дату DD.MM.YYYY. */
|
|
453
|
+
function formatLocalDate(date: Date): string {
|
|
454
|
+
const day = String(date.getDate()).padStart(2, "0");
|
|
455
|
+
const month = String(date.getMonth() + 1).padStart(2, "0");
|
|
456
|
+
return `${day}.${month}.${date.getFullYear()}`;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/** Строит сводку дайджеста из записей истории. */
|
|
460
|
+
export function buildDigestSummary(
|
|
461
|
+
records: AnalyticsRecord[],
|
|
462
|
+
options: { frequency: DigestFrequency; now?: Date }
|
|
463
|
+
): DigestSummary {
|
|
464
|
+
const now = options.now ?? new Date();
|
|
465
|
+
const windowDays = options.frequency === "weekly" ? 7 : 1;
|
|
466
|
+
const report = buildAnalytics(records, {
|
|
467
|
+
days: windowDays,
|
|
468
|
+
now,
|
|
469
|
+
topLimit: 5,
|
|
470
|
+
});
|
|
471
|
+
return {
|
|
472
|
+
period: options.frequency,
|
|
473
|
+
windowDays,
|
|
474
|
+
total: report.totals.total,
|
|
475
|
+
success: report.totals.success,
|
|
476
|
+
error: report.totals.error,
|
|
477
|
+
partial: report.totals.partial,
|
|
478
|
+
successRate: report.totals.successRate,
|
|
479
|
+
tokens: report.totals.tokens,
|
|
480
|
+
costUsd: report.totals.costUsd,
|
|
481
|
+
topErrors: report.errors,
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/** Текст дайджеста. */
|
|
486
|
+
export function formatDigestMessage(
|
|
487
|
+
summary: DigestSummary,
|
|
488
|
+
now: Date = new Date()
|
|
489
|
+
): string {
|
|
490
|
+
const periodLabel = summary.period === "weekly" ? "за неделю" : "за сутки";
|
|
491
|
+
const lines = [
|
|
492
|
+
`📊 Дайджест ${periodLabel} (${formatLocalDate(now)})`,
|
|
493
|
+
`Запусков: ${summary.total} — ✅ ${summary.success}, ❌ ${summary.error}, ⚠️ ${summary.partial} (${summary.successRate}%)`,
|
|
494
|
+
`Стоимость: ${formatMoney(summary.costUsd)} · токенов: ${summary.tokens}`,
|
|
495
|
+
];
|
|
496
|
+
if (summary.topErrors.length > 0) {
|
|
497
|
+
lines.push("Топ ошибок:");
|
|
498
|
+
for (const row of summary.topErrors) {
|
|
499
|
+
lines.push(`• ${row.message} — ${row.count}`);
|
|
500
|
+
}
|
|
501
|
+
} else if (summary.total > 0) {
|
|
502
|
+
lines.push("Ошибок нет 🎉");
|
|
503
|
+
}
|
|
504
|
+
return lines.join("\n");
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* Пора ли отправлять дайджест.
|
|
509
|
+
*
|
|
510
|
+
* daily — раз в сутки после `digest.time`; weekly — по понедельникам после
|
|
511
|
+
* `digest.time`. `lastSentAt` защищает от повторной отправки после перезапуска.
|
|
512
|
+
*/
|
|
513
|
+
export function isDigestDue(digest: DigestSettings, now: Date): boolean {
|
|
514
|
+
if (!digest.enabled) return false;
|
|
515
|
+
const match = /^([01]\d|2[0-3]):([0-5]\d)$/.exec((digest.time ?? "").trim());
|
|
516
|
+
if (!match) return false;
|
|
517
|
+
const hour = Number(match[1]);
|
|
518
|
+
const minute = Number(match[2]);
|
|
519
|
+
|
|
520
|
+
const target = new Date(now.getTime());
|
|
521
|
+
target.setHours(hour, minute, 0, 0);
|
|
522
|
+
if (digest.frequency === "weekly") {
|
|
523
|
+
// Понедельник текущей недели (getDay(): 0 = воскресенье).
|
|
524
|
+
const offset = (target.getDay() + 6) % 7;
|
|
525
|
+
target.setDate(target.getDate() - offset);
|
|
526
|
+
}
|
|
115
527
|
|
|
528
|
+
if (now.getTime() < target.getTime()) return false;
|
|
529
|
+
if (!digest.lastSentAt) return true;
|
|
530
|
+
const last = new Date(digest.lastSentAt).getTime();
|
|
531
|
+
return !Number.isFinite(last) || last < target.getTime();
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* Собирает и отправляет дайджест.
|
|
536
|
+
*
|
|
537
|
+
* `updateLastSentAt` включается только для плановой отправки: ручная кнопка
|
|
538
|
+
* «Отправить сейчас» не должна сдвигать расписание.
|
|
539
|
+
*/
|
|
540
|
+
export async function sendDigestNow(
|
|
541
|
+
options: { now?: Date; updateLastSentAt?: boolean } = {}
|
|
542
|
+
): Promise<{ success: boolean; message: string }> {
|
|
543
|
+
const now = options.now ?? new Date();
|
|
544
|
+
try {
|
|
545
|
+
const settings = await loadSettings();
|
|
546
|
+
const config = settings.notifications;
|
|
547
|
+
if (!config?.enabled) {
|
|
548
|
+
return { success: false, message: "Уведомления выключены." };
|
|
549
|
+
}
|
|
116
550
|
const webhook = config.webhook;
|
|
117
|
-
if (webhook?.enabled
|
|
118
|
-
|
|
119
|
-
await sendWebhook(webhook.url, message);
|
|
120
|
-
console.log(`[windows-scheduler] Уведомление отправлено в webhook: ${message}`);
|
|
121
|
-
} catch (err: any) {
|
|
122
|
-
console.error(
|
|
123
|
-
`[windows-scheduler] Не удалось отправить webhook-уведомление: ${
|
|
124
|
-
err instanceof Error ? err.message : String(err)
|
|
125
|
-
}`
|
|
126
|
-
);
|
|
127
|
-
}
|
|
551
|
+
if (!webhook?.enabled || !webhook.url.trim()) {
|
|
552
|
+
return { success: false, message: "Webhook выключен. Включите канал и укажите URL." };
|
|
128
553
|
}
|
|
554
|
+
const digest = config.digest;
|
|
555
|
+
if (!digest) {
|
|
556
|
+
return { success: false, message: "Настройки дайджеста не найдены." };
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
const records = getHistory(null, 5000) as AnalyticsRecord[];
|
|
560
|
+
const summary = buildDigestSummary(records, {
|
|
561
|
+
frequency: digest.frequency,
|
|
562
|
+
now,
|
|
563
|
+
});
|
|
564
|
+
const text = formatDigestMessage(summary, now);
|
|
565
|
+
await sendWebhook(webhook.url, text, webhookOptionsFrom(config));
|
|
566
|
+
|
|
567
|
+
if (options.updateLastSentAt) {
|
|
568
|
+
await saveSettings({
|
|
569
|
+
notifications: {
|
|
570
|
+
...config,
|
|
571
|
+
digest: { ...digest, lastSentAt: now.toISOString() },
|
|
572
|
+
},
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
return { success: true, message: "Дайджест отправлен." };
|
|
576
|
+
} catch (err: any) {
|
|
577
|
+
return {
|
|
578
|
+
success: false,
|
|
579
|
+
message: err instanceof Error ? err.message : String(err),
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
/** Плановая проверка дайджеста: отправляет, если пора. Возвращает true при отправке. */
|
|
585
|
+
export async function maybeSendDigest(now: Date = new Date()): Promise<boolean> {
|
|
586
|
+
try {
|
|
587
|
+
const settings = await loadSettings();
|
|
588
|
+
const config = settings.notifications;
|
|
589
|
+
if (!config?.enabled) return false;
|
|
590
|
+
const digest = config.digest;
|
|
591
|
+
if (!digest?.enabled) return false;
|
|
592
|
+
if (!isDigestDue(digest, now)) return false;
|
|
593
|
+
const result = await sendDigestNow({ now, updateLastSentAt: true });
|
|
594
|
+
if (result.success) {
|
|
595
|
+
console.log("[windows-scheduler] Дайджест уведомлений отправлен.");
|
|
596
|
+
return true;
|
|
597
|
+
}
|
|
598
|
+
console.error(`[windows-scheduler] Дайджест не отправлен: ${result.message}`);
|
|
599
|
+
return false;
|
|
129
600
|
} catch (err: any) {
|
|
130
|
-
// Уведомление не должно ломать запись истории и саму задачу.
|
|
131
601
|
console.error(
|
|
132
|
-
`[windows-scheduler] Ошибка
|
|
602
|
+
`[windows-scheduler] Ошибка дайджеста: ${
|
|
133
603
|
err instanceof Error ? err.message : String(err)
|
|
134
604
|
}`
|
|
135
605
|
);
|
|
606
|
+
return false;
|
|
136
607
|
}
|
|
137
608
|
}
|
|
138
609
|
|
|
@@ -162,7 +633,12 @@ export async function sendTestNotification(): Promise<{
|
|
|
162
633
|
|
|
163
634
|
await sendWebhook(
|
|
164
635
|
webhook.url,
|
|
165
|
-
"🧪 Тестовое уведомление от OpenCode Scheduler — webhook настроен корректно."
|
|
636
|
+
"🧪 Тестовое уведомление от OpenCode Scheduler — webhook настроен корректно.",
|
|
637
|
+
{
|
|
638
|
+
timeoutMs: webhook.timeoutMs,
|
|
639
|
+
retryCount: webhook.retryCount,
|
|
640
|
+
retryDelayMs: webhook.retryDelayMs,
|
|
641
|
+
}
|
|
166
642
|
);
|
|
167
643
|
return { success: true, message: "Тестовое уведомление отправлено." };
|
|
168
644
|
} catch (err: any) {
|