opencode-windows-scheduler 1.2.3 → 1.3.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 +39 -2
- package/README.md +14 -3
- package/ROADMAP-STRATEGY.md +61 -159
- package/ROADMAP.md +63 -96
- package/dist/core/native-notify.d.ts +36 -0
- package/dist/core/native-notify.d.ts.map +1 -0
- package/dist/core/native-notify.js +110 -0
- package/dist/core/record-history.js +4 -4
- package/dist/core/telegram.d.ts +45 -0
- package/dist/core/telegram.d.ts.map +1 -0
- package/dist/core/telegram.js +160 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -3
- package/dist/notifications.d.ts +26 -6
- package/dist/notifications.d.ts.map +1 -1
- package/dist/notifications.js +191 -34
- package/dist/settings.d.ts +47 -2
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +97 -2
- package/docs/ARCHITECTURE.md +4 -2
- package/docs/FEATURES.md +28 -11
- package/docs/README.ru.md +11 -2
- package/gui-experimental.cjs +4 -4
- package/package.json +3 -2
- package/src/core/native-notify.ts +154 -0
- package/src/core/record-history.ts +6 -4
- package/src/core/telegram.ts +219 -0
- package/src/gui.tsx +220 -6
- package/src/index.ts +7 -3
- package/src/notifications.ts +232 -40
- package/src/settings.ts +162 -4
package/src/notifications.ts
CHANGED
|
@@ -13,6 +13,8 @@ import {
|
|
|
13
13
|
type ErrorAnalyticsRow,
|
|
14
14
|
} from "./core/analytics.js";
|
|
15
15
|
import { getHistory } from "./db/history-repo.js";
|
|
16
|
+
import { sendTelegramMessage } from "./core/telegram.js";
|
|
17
|
+
import { sendNativeNotification } from "./core/native-notify.js";
|
|
16
18
|
|
|
17
19
|
/** Статус завершения задачи, который приходит из record-history. */
|
|
18
20
|
export type NotificationStatus = "success" | "error" | "timeout" | string;
|
|
@@ -23,6 +25,10 @@ export interface NotificationPayload {
|
|
|
23
25
|
status: NotificationStatus;
|
|
24
26
|
durationMs: number;
|
|
25
27
|
error?: string | null;
|
|
28
|
+
/** Потраченные токены, если известны. */
|
|
29
|
+
tokens?: number | null;
|
|
30
|
+
/** Стоимость запуска в USD, если известна. */
|
|
31
|
+
costUsd?: number | null;
|
|
26
32
|
}
|
|
27
33
|
|
|
28
34
|
/** Таймаут HTTP-запроса по умолчанию: уведомление не должно подвешивать задачу. */
|
|
@@ -95,6 +101,18 @@ export function formatNotificationMessage(
|
|
|
95
101
|
const isSuccess = status === "success";
|
|
96
102
|
const reason =
|
|
97
103
|
typeof error === "string" && error.trim() ? `: ${error.trim()}` : "";
|
|
104
|
+
const tokens =
|
|
105
|
+
typeof payload.tokens === "number" && payload.tokens > 0
|
|
106
|
+
? String(Math.round(payload.tokens))
|
|
107
|
+
: "";
|
|
108
|
+
const cost =
|
|
109
|
+
typeof payload.costUsd === "number" && payload.costUsd > 0
|
|
110
|
+
? `$${payload.costUsd.toFixed(4)}`
|
|
111
|
+
: "";
|
|
112
|
+
const usage = [tokens ? `${tokens} tok` : "", cost].filter(Boolean).join(" · ");
|
|
113
|
+
const usageSuffix = usage ? ` · ${usage}` : "";
|
|
114
|
+
const costVar = usageSuffix;
|
|
115
|
+
const tokensVar = tokens;
|
|
98
116
|
|
|
99
117
|
if (templates && isSuccess && templates.success.trim()) {
|
|
100
118
|
return renderTemplate(templates.success, {
|
|
@@ -103,6 +121,8 @@ export function formatNotificationMessage(
|
|
|
103
121
|
duration,
|
|
104
122
|
error: "",
|
|
105
123
|
emoji: "✅",
|
|
124
|
+
cost: costVar,
|
|
125
|
+
tokens: tokensVar,
|
|
106
126
|
});
|
|
107
127
|
}
|
|
108
128
|
if (templates && !isSuccess && templates.error.trim()) {
|
|
@@ -112,13 +132,15 @@ export function formatNotificationMessage(
|
|
|
112
132
|
duration,
|
|
113
133
|
error: reason,
|
|
114
134
|
emoji: "❌",
|
|
135
|
+
cost: costVar,
|
|
136
|
+
tokens: tokensVar,
|
|
115
137
|
});
|
|
116
138
|
}
|
|
117
139
|
|
|
118
140
|
if (isSuccess) {
|
|
119
|
-
return `✅ Задача "${taskName}" выполнена (${duration})`;
|
|
141
|
+
return `✅ Задача "${taskName}" выполнена (${duration})${usageSuffix}`;
|
|
120
142
|
}
|
|
121
|
-
return `❌ Задача "${taskName}" упала (${duration})${reason}`;
|
|
143
|
+
return `❌ Задача "${taskName}" упала (${duration})${reason}${usageSuffix}`;
|
|
122
144
|
}
|
|
123
145
|
|
|
124
146
|
/** Информация о завершении матрицы для уведомления. */
|
|
@@ -270,22 +292,149 @@ function webhookOptionsFrom(config: NotificationSettings): WebhookOptions {
|
|
|
270
292
|
};
|
|
271
293
|
}
|
|
272
294
|
|
|
273
|
-
/**
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
295
|
+
/** Канал доставки уведомлений. */
|
|
296
|
+
export type NotificationChannel = "webhook" | "telegram" | "native";
|
|
297
|
+
|
|
298
|
+
/** Результат отправки в один канал. */
|
|
299
|
+
export interface ChannelDeliveryResult {
|
|
300
|
+
channel: NotificationChannel;
|
|
301
|
+
ok: boolean;
|
|
302
|
+
error?: string;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Тихие часы: true, если сейчас действует окно `quiet`. Диапазон может
|
|
307
|
+
* переходить через полночь (22:00 → 08:00). Некорректное время — false.
|
|
308
|
+
*/
|
|
309
|
+
export function isQuietHours(
|
|
310
|
+
now: Date,
|
|
311
|
+
quiet?: { enabled?: boolean; from?: string; to?: string } | null
|
|
312
|
+
): boolean {
|
|
313
|
+
if (!quiet?.enabled) return false;
|
|
314
|
+
const parse = (value: unknown): number | null => {
|
|
315
|
+
const match = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(
|
|
316
|
+
typeof value === "string" ? value.trim() : ""
|
|
317
|
+
);
|
|
318
|
+
return match ? Number(match[1]) * 60 + Number(match[2]) : null;
|
|
319
|
+
};
|
|
320
|
+
const from = parse(quiet.from);
|
|
321
|
+
const to = parse(quiet.to);
|
|
322
|
+
if (from === null || to === null) return false;
|
|
323
|
+
const minutes = now.getHours() * 60 + now.getMinutes();
|
|
324
|
+
if (from === to) return true;
|
|
325
|
+
if (from < to) return minutes >= from && minutes < to;
|
|
326
|
+
return minutes >= from || minutes < to;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** URL дашборда: настройка, иначе фактический порт сервера, иначе null. */
|
|
330
|
+
async function resolveDashboardUrl(
|
|
331
|
+
config: NotificationSettings
|
|
332
|
+
): Promise<string | null> {
|
|
333
|
+
const custom = (config.dashboardUrl ?? "").trim();
|
|
334
|
+
if (custom) return custom;
|
|
277
335
|
try {
|
|
278
|
-
await
|
|
279
|
-
|
|
280
|
-
return
|
|
281
|
-
} catch
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
336
|
+
const { getDashboardPort } = await import("./server.js");
|
|
337
|
+
const port = getDashboardPort();
|
|
338
|
+
return port ? `http://localhost:${port}` : null;
|
|
339
|
+
} catch {
|
|
340
|
+
return null;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** Токен и chat_id Telegram: настройки важнее переменных окружения. */
|
|
345
|
+
function telegramCredentials(config: NotificationSettings): {
|
|
346
|
+
token: string;
|
|
347
|
+
chatId: string;
|
|
348
|
+
} {
|
|
349
|
+
const token =
|
|
350
|
+
(config.telegram?.botToken ?? "").trim() ||
|
|
351
|
+
(process.env.OPENCODE_SCHEDULER_TELEGRAM_BOT_TOKEN ?? "").trim();
|
|
352
|
+
const chatId =
|
|
353
|
+
(config.telegram?.chatId ?? "").trim() ||
|
|
354
|
+
(process.env.OPENCODE_SCHEDULER_TELEGRAM_CHAT_ID ?? "").trim();
|
|
355
|
+
return { token, chatId };
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* Отправляет сообщение во все включённые каналы и возвращает результат
|
|
360
|
+
* по каждому. Ошибки каналов не прерывают остальные и не содержат секретов.
|
|
361
|
+
*/
|
|
362
|
+
async function deliverDetailed(
|
|
363
|
+
config: NotificationSettings,
|
|
364
|
+
message: string,
|
|
365
|
+
only?: NotificationChannel
|
|
366
|
+
): Promise<ChannelDeliveryResult[]> {
|
|
367
|
+
const results: ChannelDeliveryResult[] = [];
|
|
368
|
+
const dashboardUrl = await resolveDashboardUrl(config);
|
|
369
|
+
|
|
370
|
+
const webhook = config.webhook;
|
|
371
|
+
if (
|
|
372
|
+
(!only || only === "webhook") &&
|
|
373
|
+
config.enabled &&
|
|
374
|
+
webhook?.enabled &&
|
|
375
|
+
webhook.url.trim()
|
|
376
|
+
) {
|
|
377
|
+
try {
|
|
378
|
+
await sendWebhook(webhook.url, message, webhookOptionsFrom(config));
|
|
379
|
+
console.log("[windows-scheduler] Уведомление отправлено в webhook.");
|
|
380
|
+
results.push({ channel: "webhook", ok: true });
|
|
381
|
+
} catch (err: any) {
|
|
382
|
+
const text = err instanceof Error ? err.message : String(err);
|
|
383
|
+
console.error(`[windows-scheduler] Webhook: ${text}`);
|
|
384
|
+
results.push({ channel: "webhook", ok: false, error: text });
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
const telegram = config.telegram;
|
|
389
|
+
if ((!only || only === "telegram") && config.enabled && telegram?.enabled) {
|
|
390
|
+
const { token, chatId } = telegramCredentials(config);
|
|
391
|
+
if (!token || !chatId) {
|
|
392
|
+
const text = "Telegram включён, но не заданы botToken/chatId.";
|
|
393
|
+
console.error(`[windows-scheduler] ${text}`);
|
|
394
|
+
results.push({ channel: "telegram", ok: false, error: text });
|
|
395
|
+
} else {
|
|
396
|
+
try {
|
|
397
|
+
await sendTelegramMessage(token, chatId, message, {
|
|
398
|
+
apiBase: telegram.apiBase,
|
|
399
|
+
parseMode: telegram.parseMode,
|
|
400
|
+
disableNotification: telegram.disableNotification,
|
|
401
|
+
messageThreadId: telegram.messageThreadId,
|
|
402
|
+
includeDashboardLink: telegram.includeDashboardLink,
|
|
403
|
+
dashboardUrl,
|
|
404
|
+
});
|
|
405
|
+
console.log("[windows-scheduler] Уведомление отправлено в Telegram.");
|
|
406
|
+
results.push({ channel: "telegram", ok: true });
|
|
407
|
+
} catch (err: any) {
|
|
408
|
+
const text = err instanceof Error ? err.message : String(err);
|
|
409
|
+
console.error(`[windows-scheduler] Telegram: ${text}`);
|
|
410
|
+
results.push({ channel: "telegram", ok: false, error: text });
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
const native = config.native;
|
|
416
|
+
if ((!only || only === "native") && config.enabled && native?.enabled) {
|
|
417
|
+
const result = await sendNativeNotification(
|
|
418
|
+
{ title: "OpenCode Scheduler", body: message, sound: native.sound },
|
|
419
|
+
{}
|
|
286
420
|
);
|
|
287
|
-
|
|
421
|
+
if (result.success) {
|
|
422
|
+
console.log("[windows-scheduler] Нативное уведомление показано.");
|
|
423
|
+
results.push({ channel: "native", ok: true });
|
|
424
|
+
} else {
|
|
425
|
+
const text = result.error ?? "не удалось показать уведомление";
|
|
426
|
+
console.error(`[windows-scheduler] Нативное уведомление: ${text}`);
|
|
427
|
+
results.push({ channel: "native", ok: false, error: text });
|
|
428
|
+
}
|
|
288
429
|
}
|
|
430
|
+
|
|
431
|
+
return results;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/** Отправляет текст во все включённые каналы; true — хотя бы один успешен. */
|
|
435
|
+
async function deliver(config: NotificationSettings, message: string): Promise<boolean> {
|
|
436
|
+
const results = await deliverDetailed(config, message);
|
|
437
|
+
return results.some((item) => item.ok);
|
|
289
438
|
}
|
|
290
439
|
|
|
291
440
|
/**
|
|
@@ -301,7 +450,9 @@ export async function notifyTaskCompletion(
|
|
|
301
450
|
taskName: string,
|
|
302
451
|
status: NotificationStatus,
|
|
303
452
|
durationMs: number,
|
|
304
|
-
error?: string | null
|
|
453
|
+
error?: string | null,
|
|
454
|
+
tokens?: number | null,
|
|
455
|
+
costUsd?: number | null
|
|
305
456
|
): Promise<void> {
|
|
306
457
|
try {
|
|
307
458
|
const settings = await loadSettings();
|
|
@@ -309,9 +460,17 @@ export async function notifyTaskCompletion(
|
|
|
309
460
|
if (!config?.enabled) return;
|
|
310
461
|
if (config.onlyOnError && status === "success") return;
|
|
311
462
|
if (!isTaskAllowed(taskName, config.filters)) return;
|
|
463
|
+
// Тихие часы подавляют успешные запуски, но не ошибки и таймауты.
|
|
464
|
+
if (
|
|
465
|
+
isQuietHours(new Date(), config.quietHours) &&
|
|
466
|
+
status !== "error" &&
|
|
467
|
+
status !== "timeout"
|
|
468
|
+
) {
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
312
471
|
|
|
313
472
|
const message = formatNotificationMessage(
|
|
314
|
-
{ taskName, status, durationMs, error },
|
|
473
|
+
{ taskName, status, durationMs, error, tokens, costUsd },
|
|
315
474
|
config.templates
|
|
316
475
|
);
|
|
317
476
|
await deliver(config, message);
|
|
@@ -345,6 +504,9 @@ export async function notifyMatrixCompletion(
|
|
|
345
504
|
if (info.status === "partial" && !matrix.onPartial) return;
|
|
346
505
|
if (info.status === "error" && !matrix.onAllFailed) return;
|
|
347
506
|
if (info.status === "success" && config.onlyOnError) return;
|
|
507
|
+
if (isQuietHours(new Date(), config.quietHours) && info.status !== "error") {
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
348
510
|
|
|
349
511
|
await deliver(config, formatMatrixMessage(info));
|
|
350
512
|
} catch (err: any) {
|
|
@@ -547,9 +709,15 @@ export async function sendDigestNow(
|
|
|
547
709
|
if (!config?.enabled) {
|
|
548
710
|
return { success: false, message: "Уведомления выключены." };
|
|
549
711
|
}
|
|
550
|
-
const
|
|
551
|
-
if (
|
|
552
|
-
|
|
712
|
+
const channels: NotificationChannel[] = [];
|
|
713
|
+
if (config.webhook?.enabled && config.webhook.url.trim()) channels.push("webhook");
|
|
714
|
+
if (config.telegram?.enabled) channels.push("telegram");
|
|
715
|
+
if (config.native?.enabled) channels.push("native");
|
|
716
|
+
if (channels.length === 0) {
|
|
717
|
+
return {
|
|
718
|
+
success: false,
|
|
719
|
+
message: "Все каналы выключены. Включите webhook, Telegram или нативные уведомления.",
|
|
720
|
+
};
|
|
553
721
|
}
|
|
554
722
|
const digest = config.digest;
|
|
555
723
|
if (!digest) {
|
|
@@ -562,7 +730,9 @@ export async function sendDigestNow(
|
|
|
562
730
|
now,
|
|
563
731
|
});
|
|
564
732
|
const text = formatDigestMessage(summary, now);
|
|
565
|
-
await
|
|
733
|
+
if (!(await deliver(config, text))) {
|
|
734
|
+
return { success: false, message: "Не удалось отправить дайджест ни в один канал." };
|
|
735
|
+
}
|
|
566
736
|
|
|
567
737
|
if (options.updateLastSentAt) {
|
|
568
738
|
await saveSettings({
|
|
@@ -608,39 +778,61 @@ export async function maybeSendDigest(now: Date = new Date()): Promise<boolean>
|
|
|
608
778
|
}
|
|
609
779
|
|
|
610
780
|
/**
|
|
611
|
-
* Отправляет тестовое сообщение в
|
|
612
|
-
*
|
|
613
|
-
*
|
|
614
|
-
* при тесте важно увидеть причину ошибки.
|
|
781
|
+
* Отправляет тестовое сообщение в выбранный канал или во все включённые
|
|
782
|
+
* (кнопка «🧪 Тестовое уведомление»). В отличие от notifyTaskCompletion,
|
|
783
|
+
* результат возвращается пользователю: при тесте важна причина ошибки.
|
|
615
784
|
*/
|
|
616
|
-
export async function sendTestNotification(
|
|
785
|
+
export async function sendTestNotification(
|
|
786
|
+
channel: "all" | NotificationChannel = "all"
|
|
787
|
+
): Promise<{
|
|
617
788
|
success: boolean;
|
|
618
789
|
message: string;
|
|
619
790
|
}> {
|
|
620
791
|
try {
|
|
621
792
|
const settings = await loadSettings();
|
|
622
|
-
const
|
|
793
|
+
const config = settings.notifications;
|
|
794
|
+
if (!config?.enabled) {
|
|
795
|
+
return {
|
|
796
|
+
success: false,
|
|
797
|
+
message: "Уведомления выключены. Включите главный переключатель.",
|
|
798
|
+
};
|
|
799
|
+
}
|
|
623
800
|
|
|
624
|
-
|
|
801
|
+
const enabled: NotificationChannel[] = [];
|
|
802
|
+
if (config.webhook?.enabled && config.webhook.url.trim()) enabled.push("webhook");
|
|
803
|
+
if (config.telegram?.enabled) enabled.push("telegram");
|
|
804
|
+
if (config.native?.enabled) enabled.push("native");
|
|
805
|
+
if (enabled.length === 0) {
|
|
625
806
|
return {
|
|
626
807
|
success: false,
|
|
627
|
-
message:
|
|
808
|
+
message:
|
|
809
|
+
"Все каналы выключены. Включите webhook, Telegram или нативные уведомления.",
|
|
628
810
|
};
|
|
629
811
|
}
|
|
630
|
-
if (!
|
|
631
|
-
return { success: false, message:
|
|
812
|
+
if (channel !== "all" && !enabled.includes(channel)) {
|
|
813
|
+
return { success: false, message: `Канал ${channel} выключен.` };
|
|
632
814
|
}
|
|
633
815
|
|
|
634
|
-
await
|
|
635
|
-
|
|
636
|
-
"🧪 Тестовое уведомление от OpenCode Scheduler —
|
|
637
|
-
|
|
638
|
-
timeoutMs: webhook.timeoutMs,
|
|
639
|
-
retryCount: webhook.retryCount,
|
|
640
|
-
retryDelayMs: webhook.retryDelayMs,
|
|
641
|
-
}
|
|
816
|
+
const results = await deliverDetailed(
|
|
817
|
+
config,
|
|
818
|
+
"🧪 Тестовое уведомление от OpenCode Scheduler — канал настроен корректно.",
|
|
819
|
+
channel === "all" ? undefined : channel
|
|
642
820
|
);
|
|
643
|
-
|
|
821
|
+
const sent = results.filter((item) => item.ok).map((item) => item.channel);
|
|
822
|
+
const failed = results.filter((item) => !item.ok);
|
|
823
|
+
const parts: string[] = [];
|
|
824
|
+
if (sent.length > 0) parts.push(`Отправлено: ${sent.join(", ")}.`);
|
|
825
|
+
if (failed.length > 0) {
|
|
826
|
+
parts.push(
|
|
827
|
+
`Ошибки: ${failed
|
|
828
|
+
.map((item) => `${item.channel} — ${item.error ?? "неизвестная ошибка"}`)
|
|
829
|
+
.join("; ")}.`
|
|
830
|
+
);
|
|
831
|
+
}
|
|
832
|
+
return {
|
|
833
|
+
success: failed.length === 0 && sent.length > 0,
|
|
834
|
+
message: parts.join(" ") || "Тестовое уведомление не отправлено.",
|
|
835
|
+
};
|
|
644
836
|
} catch (err: any) {
|
|
645
837
|
return {
|
|
646
838
|
success: false,
|
package/src/settings.ts
CHANGED
|
@@ -60,11 +60,52 @@ export interface DigestSettings {
|
|
|
60
60
|
lastSentAt: string | null;
|
|
61
61
|
}
|
|
62
62
|
|
|
63
|
+
/** parse_mode для Telegram Bot API. Пустая строка — plain text. */
|
|
64
|
+
export type TelegramParseMode = "" | "HTML" | "Markdown" | "MarkdownV2";
|
|
65
|
+
|
|
66
|
+
/** Telegram-канал уведомлений (Спринт 25). */
|
|
67
|
+
export interface TelegramNotificationSettings {
|
|
68
|
+
/** Включён ли Telegram-канал. */
|
|
69
|
+
enabled: boolean;
|
|
70
|
+
/** Токен бота из @BotFather. Хранится только локально. */
|
|
71
|
+
botToken: string;
|
|
72
|
+
/** ID чата или канала-получателя. */
|
|
73
|
+
chatId: string;
|
|
74
|
+
/** Разметка сообщения; пусто — plain text. */
|
|
75
|
+
parseMode: TelegramParseMode;
|
|
76
|
+
/** Отправлять без звука. */
|
|
77
|
+
disableNotification: boolean;
|
|
78
|
+
/** ID темы в супергруппе (forum topic), null — обычное сообщение. */
|
|
79
|
+
messageThreadId: number | null;
|
|
80
|
+
/** Добавлять ссылку на локальный дашборд. */
|
|
81
|
+
includeDashboardLink: boolean;
|
|
82
|
+
/** База API; по умолчанию https://api.telegram.org. */
|
|
83
|
+
apiBase: string;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Нативные уведомления ОС (Спринт 25). */
|
|
87
|
+
export interface NativeNotificationSettings {
|
|
88
|
+
/** Windows Toast, macOS Notification Center, Linux notify-send. */
|
|
89
|
+
enabled: boolean;
|
|
90
|
+
/** Со звуком (где поддерживается). */
|
|
91
|
+
sound: boolean;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Тихие часы (Спринт 25): success/partial подавляются, ошибки проходят. */
|
|
95
|
+
export interface QuietHoursSettings {
|
|
96
|
+
/** Включён ли режим тихих часов. */
|
|
97
|
+
enabled: boolean;
|
|
98
|
+
/** Начало в HH:MM (локальное время). */
|
|
99
|
+
from: string;
|
|
100
|
+
/** Конец в HH:MM; диапазон может переходить через полночь. */
|
|
101
|
+
to: string;
|
|
102
|
+
}
|
|
103
|
+
|
|
63
104
|
/**
|
|
64
105
|
* Уведомления о завершении задач.
|
|
65
106
|
*
|
|
66
|
-
*
|
|
67
|
-
*
|
|
107
|
+
* Каналы: webhook (Discord/Slack/generic), Telegram Bot API и нативные
|
|
108
|
+
* уведомления ОС. Все каналы опциональны и не зависят друг от друга.
|
|
68
109
|
*/
|
|
69
110
|
export interface NotificationSettings {
|
|
70
111
|
/** Главный выключатель уведомлений. */
|
|
@@ -73,6 +114,14 @@ export interface NotificationSettings {
|
|
|
73
114
|
onlyOnError: boolean;
|
|
74
115
|
/** Webhook-канал. */
|
|
75
116
|
webhook?: WebhookNotificationSettings;
|
|
117
|
+
/** Telegram-канал. */
|
|
118
|
+
telegram?: TelegramNotificationSettings;
|
|
119
|
+
/** Нативные уведомления ОС. */
|
|
120
|
+
native?: NativeNotificationSettings;
|
|
121
|
+
/** Тихие часы. */
|
|
122
|
+
quietHours?: QuietHoursSettings;
|
|
123
|
+
/** Переопределение ссылки на дашборд; пусто — порт берётся у сервера. */
|
|
124
|
+
dashboardUrl?: string;
|
|
76
125
|
/** Шаблоны сообщений. */
|
|
77
126
|
templates?: NotificationTemplates;
|
|
78
127
|
/** Фильтры по задачам. */
|
|
@@ -241,10 +290,30 @@ export function defaultNotifications(): NotificationSettings {
|
|
|
241
290
|
retryDelayMs: DEFAULT_WEBHOOK_RETRY_DELAY_MS,
|
|
242
291
|
},
|
|
243
292
|
templates: {
|
|
244
|
-
success: '✅ Задача "{task}" выполнена ({duration})',
|
|
245
|
-
error: '❌ Задача "{task}" упала ({duration}){error}',
|
|
293
|
+
success: '✅ Задача "{task}" выполнена ({duration}){cost}',
|
|
294
|
+
error: '❌ Задача "{task}" упала ({duration}){error}{cost}',
|
|
246
295
|
},
|
|
247
296
|
filters: { include: [], exclude: [] },
|
|
297
|
+
telegram: {
|
|
298
|
+
enabled: false,
|
|
299
|
+
botToken: "",
|
|
300
|
+
chatId: "",
|
|
301
|
+
parseMode: "HTML",
|
|
302
|
+
disableNotification: false,
|
|
303
|
+
messageThreadId: null,
|
|
304
|
+
includeDashboardLink: true,
|
|
305
|
+
apiBase: "https://api.telegram.org",
|
|
306
|
+
},
|
|
307
|
+
native: {
|
|
308
|
+
enabled: false,
|
|
309
|
+
sound: true,
|
|
310
|
+
},
|
|
311
|
+
quietHours: {
|
|
312
|
+
enabled: false,
|
|
313
|
+
from: "22:00",
|
|
314
|
+
to: "08:00",
|
|
315
|
+
},
|
|
316
|
+
dashboardUrl: "",
|
|
248
317
|
matrix: {
|
|
249
318
|
enabled: true,
|
|
250
319
|
onPartial: true,
|
|
@@ -311,6 +380,30 @@ function asRecord(value: unknown): Record<string, unknown> | undefined {
|
|
|
311
380
|
: undefined;
|
|
312
381
|
}
|
|
313
382
|
|
|
383
|
+
/** Приводит parse_mode Telegram к допустимому значению. */
|
|
384
|
+
function normalizeTelegramParseMode(
|
|
385
|
+
value: unknown,
|
|
386
|
+
fallback: TelegramParseMode
|
|
387
|
+
): TelegramParseMode {
|
|
388
|
+
return value === "" || value === "HTML" || value === "Markdown" || value === "MarkdownV2"
|
|
389
|
+
? value
|
|
390
|
+
: fallback;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/** Проверяет http(s)-базу API; иначе возвращает fallback. */
|
|
394
|
+
function normalizeHttpBase(value: unknown, fallback: string): string {
|
|
395
|
+
if (typeof value !== "string") return fallback;
|
|
396
|
+
const trimmed = value.trim().replace(/\/+$/, "");
|
|
397
|
+
if (!trimmed) return fallback;
|
|
398
|
+
try {
|
|
399
|
+
const parsed = new URL(trimmed);
|
|
400
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return fallback;
|
|
401
|
+
return trimmed;
|
|
402
|
+
} catch {
|
|
403
|
+
return fallback;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
314
407
|
/** Приводит настройки уведомлений к безопасному виду. */
|
|
315
408
|
function normalizeNotifications(
|
|
316
409
|
value: unknown,
|
|
@@ -321,6 +414,9 @@ function normalizeNotifications(
|
|
|
321
414
|
const fallbackFilters = fallback.filters ?? { include: [], exclude: [] };
|
|
322
415
|
const fallbackMatrix = fallback.matrix ?? defaultNotifications().matrix!;
|
|
323
416
|
const fallbackDigest = fallback.digest ?? defaultNotifications().digest!;
|
|
417
|
+
const fallbackTelegram = fallback.telegram ?? defaultNotifications().telegram!;
|
|
418
|
+
const fallbackNative = fallback.native ?? defaultNotifications().native!;
|
|
419
|
+
const fallbackQuiet = fallback.quietHours ?? defaultNotifications().quietHours!;
|
|
324
420
|
|
|
325
421
|
const raw = asRecord(value);
|
|
326
422
|
if (!raw) {
|
|
@@ -334,6 +430,10 @@ function normalizeNotifications(
|
|
|
334
430
|
},
|
|
335
431
|
matrix: { ...fallbackMatrix },
|
|
336
432
|
digest: { ...fallbackDigest },
|
|
433
|
+
telegram: { ...fallbackTelegram },
|
|
434
|
+
native: { ...fallbackNative },
|
|
435
|
+
quietHours: { ...fallbackQuiet },
|
|
436
|
+
dashboardUrl: fallback.dashboardUrl ?? "",
|
|
337
437
|
};
|
|
338
438
|
}
|
|
339
439
|
|
|
@@ -342,6 +442,9 @@ function normalizeNotifications(
|
|
|
342
442
|
const rawFilters = asRecord(raw.filters);
|
|
343
443
|
const rawMatrix = asRecord(raw.matrix);
|
|
344
444
|
const rawDigest = asRecord(raw.digest);
|
|
445
|
+
const rawTelegram = asRecord(raw.telegram);
|
|
446
|
+
const rawNative = asRecord(raw.native);
|
|
447
|
+
const rawQuiet = asRecord(raw.quietHours);
|
|
345
448
|
|
|
346
449
|
const frequency: DigestFrequency =
|
|
347
450
|
rawDigest?.frequency === "weekly" || rawDigest?.frequency === "daily"
|
|
@@ -399,6 +502,61 @@ function normalizeNotifications(
|
|
|
399
502
|
include: normalizeNameList(rawFilters?.include, fallbackFilters.include),
|
|
400
503
|
exclude: normalizeNameList(rawFilters?.exclude, fallbackFilters.exclude),
|
|
401
504
|
},
|
|
505
|
+
telegram: {
|
|
506
|
+
enabled:
|
|
507
|
+
typeof rawTelegram?.enabled === "boolean"
|
|
508
|
+
? rawTelegram.enabled
|
|
509
|
+
: fallbackTelegram.enabled,
|
|
510
|
+
botToken:
|
|
511
|
+
typeof rawTelegram?.botToken === "string"
|
|
512
|
+
? rawTelegram.botToken.trim().slice(0, 512)
|
|
513
|
+
: fallbackTelegram.botToken,
|
|
514
|
+
chatId:
|
|
515
|
+
typeof rawTelegram?.chatId === "string"
|
|
516
|
+
? rawTelegram.chatId.trim().slice(0, 128)
|
|
517
|
+
: fallbackTelegram.chatId,
|
|
518
|
+
parseMode: normalizeTelegramParseMode(
|
|
519
|
+
rawTelegram?.parseMode,
|
|
520
|
+
fallbackTelegram.parseMode
|
|
521
|
+
),
|
|
522
|
+
disableNotification:
|
|
523
|
+
typeof rawTelegram?.disableNotification === "boolean"
|
|
524
|
+
? rawTelegram.disableNotification
|
|
525
|
+
: fallbackTelegram.disableNotification,
|
|
526
|
+
messageThreadId:
|
|
527
|
+
rawTelegram?.messageThreadId === null
|
|
528
|
+
? null
|
|
529
|
+
: Number.isFinite(Number(rawTelegram?.messageThreadId))
|
|
530
|
+
? Math.max(0, Math.floor(Number(rawTelegram?.messageThreadId)))
|
|
531
|
+
: fallbackTelegram.messageThreadId,
|
|
532
|
+
includeDashboardLink:
|
|
533
|
+
typeof rawTelegram?.includeDashboardLink === "boolean"
|
|
534
|
+
? rawTelegram.includeDashboardLink
|
|
535
|
+
: fallbackTelegram.includeDashboardLink,
|
|
536
|
+
apiBase: normalizeHttpBase(rawTelegram?.apiBase, fallbackTelegram.apiBase),
|
|
537
|
+
},
|
|
538
|
+
native: {
|
|
539
|
+
enabled:
|
|
540
|
+
typeof rawNative?.enabled === "boolean"
|
|
541
|
+
? rawNative.enabled
|
|
542
|
+
: fallbackNative.enabled,
|
|
543
|
+
sound:
|
|
544
|
+
typeof rawNative?.sound === "boolean"
|
|
545
|
+
? rawNative.sound
|
|
546
|
+
: fallbackNative.sound,
|
|
547
|
+
},
|
|
548
|
+
quietHours: {
|
|
549
|
+
enabled:
|
|
550
|
+
typeof rawQuiet?.enabled === "boolean"
|
|
551
|
+
? rawQuiet.enabled
|
|
552
|
+
: fallbackQuiet.enabled,
|
|
553
|
+
from: normalizeDailyTime(rawQuiet?.from, fallbackQuiet.from),
|
|
554
|
+
to: normalizeDailyTime(rawQuiet?.to, fallbackQuiet.to),
|
|
555
|
+
},
|
|
556
|
+
dashboardUrl:
|
|
557
|
+
typeof raw.dashboardUrl === "string"
|
|
558
|
+
? raw.dashboardUrl.trim().slice(0, 500)
|
|
559
|
+
: (fallback.dashboardUrl ?? ""),
|
|
402
560
|
matrix: {
|
|
403
561
|
enabled:
|
|
404
562
|
typeof rawMatrix?.enabled === "boolean"
|