opencode-windows-scheduler 1.0.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +58 -7
- package/README.md +14 -4
- package/README.ru.md +14 -4
- package/ROADMAP.md +30 -20
- package/dist/core/analytics.d.ts +129 -0
- package/dist/core/analytics.d.ts.map +1 -0
- package/dist/core/analytics.js +286 -0
- package/dist/core/dry-run.d.ts +13 -0
- package/dist/core/dry-run.d.ts.map +1 -1
- package/dist/core/dry-run.js +30 -0
- package/dist/core/matrix.d.ts.map +1 -1
- package/dist/core/matrix.js +10 -0
- package/dist/core/ps-wrapper.d.ts +32 -2
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +101 -3
- package/dist/core/retention.d.ts +29 -0
- package/dist/core/retention.d.ts.map +1 -0
- package/dist/core/retention.js +98 -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/types.d.ts +15 -0
- 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 +13 -1
- package/dist/core/wrappers/bash.d.ts +15 -0
- package/dist/core/wrappers/bash.d.ts.map +1 -1
- package/dist/core/wrappers/bash.js +44 -1
- package/dist/db/history-repo.d.ts +41 -0
- package/dist/db/history-repo.d.ts.map +1 -1
- package/dist/db/history-repo.js +78 -0
- package/dist/db/schema.d.ts +1 -1
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +11 -0
- package/dist/index.d.ts +117 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1094 -56
- 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 +645 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +251 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +200 -7
- package/dist/settings.d.ts +80 -0
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +159 -8
- package/dist/task-transfer.d.ts +13 -0
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +26 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +3 -11
- package/dist/version.d.ts +8 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +27 -0
- 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 +45 -13
- package/docs/FEATURES.md +103 -12
- package/gui-experimental.cjs +4 -2
- package/package.json +8 -2
- package/src/core/analytics.ts +414 -0
- package/src/core/dry-run.ts +42 -0
- package/src/core/matrix.ts +10 -0
- package/src/core/ps-wrapper.ts +117 -3
- package/src/core/retention.ts +141 -0
- package/src/core/schedule-gate.ts +213 -0
- package/src/core/schedule-v2.ts +533 -0
- package/src/core/scheduler/types.ts +15 -0
- package/src/core/scheduler/windows.ts +13 -1
- package/src/core/wrappers/bash.ts +60 -0
- package/src/db/history-repo.ts +116 -0
- package/src/db/schema.ts +14 -0
- package/src/gui.tsx +3613 -2725
- package/src/index.ts +1325 -55
- package/src/notifications.ts +516 -40
- package/src/profiles.ts +236 -0
- package/src/rpc.ts +267 -2
- package/src/server.ts +226 -7
- package/src/settings.ts +285 -9
- package/src/task-transfer.ts +44 -0
- package/src/types.ts +3 -13
- package/src/version.ts +27 -0
- package/src/workspaces.ts +214 -8
- package/dist/gui-experimental.cjs +0 -1
package/dist/notifications.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { type DigestFrequency, type DigestSettings, type NotificationFilters, type NotificationTemplates } from "./settings.js";
|
|
2
|
+
import { type AnalyticsRecord, type ErrorAnalyticsRow } from "./core/analytics.js";
|
|
1
3
|
/** Статус завершения задачи, который приходит из record-history. */
|
|
2
4
|
export type NotificationStatus = "success" | "error" | "timeout" | string;
|
|
3
5
|
/** Содержимое уведомления. */
|
|
@@ -10,28 +12,132 @@ export interface NotificationPayload {
|
|
|
10
12
|
/** Человекочитаемая длительность: 2300 мс → «2.3s». */
|
|
11
13
|
export declare function formatDuration(durationMs: number): string;
|
|
12
14
|
/**
|
|
13
|
-
*
|
|
15
|
+
* Сопоставление имени задачи с шаблоном: `*` — любая последовательность,
|
|
16
|
+
* регистр не важен. `regen-*` покрывает `regen-api`, `regen-ui`.
|
|
17
|
+
*/
|
|
18
|
+
export declare function wildcardMatch(pattern: string, value: string): boolean;
|
|
19
|
+
/** Проверяет, разрешена ли задача фильтрами include/exclude. */
|
|
20
|
+
export declare function isTaskAllowed(taskName: string, filters?: NotificationFilters): boolean;
|
|
21
|
+
/** Подставляет {key} в шаблон; неизвестные плейсхолдеры остаются как есть. */
|
|
22
|
+
export declare function renderTemplate(template: string, vars: Record<string, string>): string;
|
|
23
|
+
/**
|
|
24
|
+
* Формат сообщения по умолчанию:
|
|
14
25
|
* ✅ Задача "Тест" выполнена (2.3s)
|
|
15
26
|
* ❌ Задача "Тест" упала (2.3s): Quality Gate провален
|
|
16
27
|
*/
|
|
17
|
-
export declare function formatNotificationMessage(payload: NotificationPayload): string;
|
|
28
|
+
export declare function formatNotificationMessage(payload: NotificationPayload, templates?: NotificationTemplates): string;
|
|
29
|
+
/** Информация о завершении матрицы для уведомления. */
|
|
30
|
+
export interface MatrixNotificationInfo {
|
|
31
|
+
parentName: string;
|
|
32
|
+
status: "success" | "error" | "partial";
|
|
33
|
+
total: number;
|
|
34
|
+
success: number;
|
|
35
|
+
error: number;
|
|
36
|
+
message?: string | null;
|
|
37
|
+
}
|
|
38
|
+
/** Текст уведомления о завершении матрицы. */
|
|
39
|
+
export declare function formatMatrixMessage(info: MatrixNotificationInfo): string;
|
|
40
|
+
export interface WebhookOptions {
|
|
41
|
+
/** Таймаут одной попытки в мс (по умолчанию 10 с). */
|
|
42
|
+
timeoutMs?: number;
|
|
43
|
+
/** Сколько раз повторить после неудачи (по умолчанию 0). */
|
|
44
|
+
retryCount?: number;
|
|
45
|
+
/** Базовая задержка backoff в мс (по умолчанию 1000). */
|
|
46
|
+
retryDelayMs?: number;
|
|
47
|
+
/** Подмена sleep для тестов. */
|
|
48
|
+
sleep?: (ms: number) => Promise<void>;
|
|
49
|
+
}
|
|
18
50
|
/**
|
|
19
|
-
* Отправляет POST на webhook.
|
|
51
|
+
* Отправляет POST на webhook с повторами и экспоненциальным backoff.
|
|
20
52
|
*
|
|
21
53
|
* Тело совместимо одновременно с Discord (`content`) и Slack (`text`).
|
|
22
|
-
*
|
|
23
|
-
*
|
|
54
|
+
* Повторяются только сетевые ошибки, таймауты, 5xx и 429; прочие 4xx — сразу
|
|
55
|
+
* ошибка (повтор не поможет). Бросает исключение только для диагностики —
|
|
56
|
+
* вызывающий код обязан перехватить его, чтобы уведомление не ломало задачу.
|
|
24
57
|
*/
|
|
25
|
-
export declare function sendWebhook(url: string, message: string): Promise<void>;
|
|
58
|
+
export declare function sendWebhook(url: string, message: string, options?: WebhookOptions): Promise<void>;
|
|
26
59
|
/**
|
|
27
60
|
* Уведомляет о завершении задачи во все включённые каналы.
|
|
28
61
|
*
|
|
29
62
|
* Правила:
|
|
30
63
|
* - `notifications.enabled === false` — ничего не делает;
|
|
31
64
|
* - `onlyOnError === true` — успешные запуски пропускаются;
|
|
65
|
+
* - фильтры include/exclude отсекают задачи по имени;
|
|
32
66
|
* - ошибки отправки только логируются, наружу не выбрасываются.
|
|
33
67
|
*/
|
|
34
68
|
export declare function notifyTaskCompletion(taskName: string, status: NotificationStatus, durationMs: number, error?: string | null): Promise<void>;
|
|
69
|
+
/**
|
|
70
|
+
* Уведомляет о завершении матрицы (Спринт 20).
|
|
71
|
+
*
|
|
72
|
+
* partial — только при `matrix.onPartial`; полный провал — при
|
|
73
|
+
* `matrix.onAllFailed`; успех — только когда `onlyOnError === false`.
|
|
74
|
+
*/
|
|
75
|
+
export declare function notifyMatrixCompletion(info: MatrixNotificationInfo): Promise<void>;
|
|
76
|
+
/** Запись о незавершённом запуске (для детектора зависших матриц). */
|
|
77
|
+
export interface RunningTaskRecord {
|
|
78
|
+
id: number;
|
|
79
|
+
taskName: string;
|
|
80
|
+
startedAt: string;
|
|
81
|
+
}
|
|
82
|
+
/** Найденный зависший клон матрицы. */
|
|
83
|
+
export interface StuckMatrixClone {
|
|
84
|
+
id: number;
|
|
85
|
+
cloneName: string;
|
|
86
|
+
parentName: string;
|
|
87
|
+
startedAt: string;
|
|
88
|
+
minutes: number;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Ищет клоны матриц, которые выполняются дольше порога.
|
|
92
|
+
* `parentByClone` — соответствие «имя клона → имя родителя» (без регистра).
|
|
93
|
+
*/
|
|
94
|
+
export declare function findStuckMatrixClones(running: RunningTaskRecord[], parentByClone: Map<string, string>, now: Date, thresholdMinutes: number): StuckMatrixClone[];
|
|
95
|
+
/** Текст уведомления о зависшем клоне матрицы. */
|
|
96
|
+
export declare function formatStuckMatrixMessage(stuck: StuckMatrixClone): string;
|
|
97
|
+
/** Отправляет уведомление о зависшем клоне, если матрицы включены. */
|
|
98
|
+
export declare function notifyStuckMatrix(stuck: StuckMatrixClone): Promise<boolean>;
|
|
99
|
+
/** Сводка для дайджеста. */
|
|
100
|
+
export interface DigestSummary {
|
|
101
|
+
period: "daily" | "weekly";
|
|
102
|
+
windowDays: number;
|
|
103
|
+
total: number;
|
|
104
|
+
success: number;
|
|
105
|
+
error: number;
|
|
106
|
+
partial: number;
|
|
107
|
+
successRate: number;
|
|
108
|
+
tokens: number;
|
|
109
|
+
costUsd: number;
|
|
110
|
+
topErrors: ErrorAnalyticsRow[];
|
|
111
|
+
}
|
|
112
|
+
/** Строит сводку дайджеста из записей истории. */
|
|
113
|
+
export declare function buildDigestSummary(records: AnalyticsRecord[], options: {
|
|
114
|
+
frequency: DigestFrequency;
|
|
115
|
+
now?: Date;
|
|
116
|
+
}): DigestSummary;
|
|
117
|
+
/** Текст дайджеста. */
|
|
118
|
+
export declare function formatDigestMessage(summary: DigestSummary, now?: Date): string;
|
|
119
|
+
/**
|
|
120
|
+
* Пора ли отправлять дайджест.
|
|
121
|
+
*
|
|
122
|
+
* daily — раз в сутки после `digest.time`; weekly — по понедельникам после
|
|
123
|
+
* `digest.time`. `lastSentAt` защищает от повторной отправки после перезапуска.
|
|
124
|
+
*/
|
|
125
|
+
export declare function isDigestDue(digest: DigestSettings, now: Date): boolean;
|
|
126
|
+
/**
|
|
127
|
+
* Собирает и отправляет дайджест.
|
|
128
|
+
*
|
|
129
|
+
* `updateLastSentAt` включается только для плановой отправки: ручная кнопка
|
|
130
|
+
* «Отправить сейчас» не должна сдвигать расписание.
|
|
131
|
+
*/
|
|
132
|
+
export declare function sendDigestNow(options?: {
|
|
133
|
+
now?: Date;
|
|
134
|
+
updateLastSentAt?: boolean;
|
|
135
|
+
}): Promise<{
|
|
136
|
+
success: boolean;
|
|
137
|
+
message: string;
|
|
138
|
+
}>;
|
|
139
|
+
/** Плановая проверка дайджеста: отправляет, если пора. Возвращает true при отправке. */
|
|
140
|
+
export declare function maybeSendDigest(now?: Date): Promise<boolean>;
|
|
35
141
|
/**
|
|
36
142
|
* Отправляет тестовое сообщение в webhook (кнопка «🧪 Тестовое уведомление»).
|
|
37
143
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"notifications.d.ts","sourceRoot":"","sources":["../src/notifications.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"notifications.d.ts","sourceRoot":"","sources":["../src/notifications.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,eAAe,EACpB,KAAK,cAAc,EACnB,KAAK,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AAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,CAwChD;AAED,wFAAwF;AACxF,wBAAsB,eAAe,CAAC,GAAG,GAAE,IAAiB,GAAG,OAAO,CAAC,OAAO,CAAC,CAuB9E;AAED;;;;;GAKG;AACH,wBAAsB,oBAAoB,IAAI,OAAO,CAAC;IACpD,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC,CA+BD"}
|
package/dist/notifications.js
CHANGED
|
@@ -1,33 +1,108 @@
|
|
|
1
|
-
import { loadSettings } from "./settings.js";
|
|
2
|
-
|
|
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
|
-
|
|
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
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
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(),
|
|
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
|
-
|
|
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
|
|
141
|
+
throw new WebhookError(`Таймаут запроса (${timeoutMs / 1000} с).`, true);
|
|
62
142
|
}
|
|
63
|
-
|
|
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
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
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
|
|
93
|
-
|
|
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
|
-
|
|
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) {
|