agent-steward 0.0.1 → 0.0.3
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 +399 -0
- package/CROSS_PLATFORM.md +151 -0
- package/README.md +307 -15
- package/ROADMAP-STRATEGY.md +196 -0
- package/ROADMAP.md +184 -0
- package/dist/core/analytics.d.ts +132 -0
- package/dist/core/analytics.d.ts.map +1 -0
- package/dist/core/analytics.js +290 -0
- package/dist/core/audit.d.ts +96 -0
- package/dist/core/audit.d.ts.map +1 -0
- package/dist/core/audit.js +297 -0
- package/dist/core/cron-to-schtasks.d.ts +12 -0
- package/dist/core/cron-to-schtasks.d.ts.map +1 -0
- package/dist/core/cron-to-schtasks.js +175 -0
- package/dist/core/dry-run.d.ts +102 -0
- package/dist/core/dry-run.d.ts.map +1 -0
- package/dist/core/dry-run.js +447 -0
- package/dist/core/file-watcher.d.ts +31 -0
- package/dist/core/file-watcher.d.ts.map +1 -0
- package/dist/core/file-watcher.js +186 -0
- package/dist/core/git-trigger.d.ts +82 -0
- package/dist/core/git-trigger.d.ts.map +1 -0
- package/dist/core/git-trigger.js +312 -0
- package/dist/core/glob.d.ts +38 -0
- package/dist/core/glob.d.ts.map +1 -0
- package/dist/core/glob.js +233 -0
- package/dist/core/local-ai.d.ts +52 -0
- package/dist/core/local-ai.d.ts.map +1 -0
- package/dist/core/local-ai.js +119 -0
- package/dist/core/lock.d.ts +57 -0
- package/dist/core/lock.d.ts.map +1 -0
- package/dist/core/lock.js +193 -0
- package/dist/core/matrix.d.ts +167 -0
- package/dist/core/matrix.d.ts.map +1 -0
- package/dist/core/matrix.js +724 -0
- 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 +113 -0
- package/dist/core/one-shot.d.ts +90 -0
- package/dist/core/one-shot.d.ts.map +1 -0
- package/dist/core/one-shot.js +182 -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/permissions.d.ts +69 -0
- package/dist/core/permissions.d.ts.map +1 -0
- package/dist/core/permissions.js +143 -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 +73 -0
- package/dist/core/ps-wrapper.d.ts.map +1 -0
- package/dist/core/ps-wrapper.js +1091 -0
- package/dist/core/record-history.d.ts +25 -0
- package/dist/core/record-history.d.ts.map +1 -0
- package/dist/core/record-history.js +471 -0
- 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/savings.d.ts +70 -0
- package/dist/core/savings.d.ts.map +1 -0
- package/dist/core/savings.js +87 -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 +211 -0
- package/dist/core/schedule-v2.d.ts +116 -0
- package/dist/core/schedule-v2.d.ts.map +1 -0
- package/dist/core/schedule-v2.js +586 -0
- package/dist/core/scheduler/at-fallback.d.ts +42 -0
- package/dist/core/scheduler/at-fallback.d.ts.map +1 -0
- package/dist/core/scheduler/at-fallback.js +70 -0
- package/dist/core/scheduler/index.d.ts +32 -0
- package/dist/core/scheduler/index.d.ts.map +1 -0
- package/dist/core/scheduler/index.js +63 -0
- package/dist/core/scheduler/linux.d.ts +46 -0
- package/dist/core/scheduler/linux.d.ts.map +1 -0
- package/dist/core/scheduler/linux.js +261 -0
- package/dist/core/scheduler/logs.d.ts +11 -0
- package/dist/core/scheduler/logs.d.ts.map +1 -0
- package/dist/core/scheduler/logs.js +34 -0
- package/dist/core/scheduler/mac.d.ts +46 -0
- package/dist/core/scheduler/mac.d.ts.map +1 -0
- package/dist/core/scheduler/mac.js +256 -0
- package/dist/core/scheduler/posix.d.ts +40 -0
- package/dist/core/scheduler/posix.d.ts.map +1 -0
- package/dist/core/scheduler/posix.js +100 -0
- package/dist/core/scheduler/registry.d.ts +43 -0
- package/dist/core/scheduler/registry.d.ts.map +1 -0
- package/dist/core/scheduler/registry.js +57 -0
- package/dist/core/scheduler/types.d.ts +86 -0
- package/dist/core/scheduler/types.d.ts.map +1 -0
- package/dist/core/scheduler/types.js +1 -0
- package/dist/core/scheduler/windows.d.ts +112 -0
- package/dist/core/scheduler/windows.d.ts.map +1 -0
- package/dist/core/scheduler/windows.js +749 -0
- package/dist/core/secrets.d.ts +66 -0
- package/dist/core/secrets.d.ts.map +1 -0
- package/dist/core/secrets.js +433 -0
- package/dist/core/self-analysis.d.ts +117 -0
- package/dist/core/self-analysis.d.ts.map +1 -0
- package/dist/core/self-analysis.js +539 -0
- package/dist/core/session.d.ts +42 -0
- package/dist/core/session.d.ts.map +1 -0
- package/dist/core/session.js +134 -0
- package/dist/core/shutdown.d.ts +26 -0
- package/dist/core/shutdown.d.ts.map +1 -0
- package/dist/core/shutdown.js +49 -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 +146 -0
- package/dist/core/summary.d.ts +69 -0
- package/dist/core/summary.d.ts.map +1 -0
- package/dist/core/summary.js +250 -0
- package/dist/core/telegram.d.ts +55 -0
- package/dist/core/telegram.d.ts.map +1 -0
- package/dist/core/telegram.js +344 -0
- package/dist/core/triage-chain.d.ts +40 -0
- package/dist/core/triage-chain.d.ts.map +1 -0
- package/dist/core/triage-chain.js +80 -0
- package/dist/core/triage-compare.d.ts +68 -0
- package/dist/core/triage-compare.d.ts.map +1 -0
- package/dist/core/triage-compare.js +184 -0
- package/dist/core/triage-rules.d.ts +23 -0
- package/dist/core/triage-rules.d.ts.map +1 -0
- package/dist/core/triage-rules.js +196 -0
- package/dist/core/triage-shadow.d.ts +91 -0
- package/dist/core/triage-shadow.d.ts.map +1 -0
- package/dist/core/triage-shadow.js +160 -0
- package/dist/core/triage-worker.d.ts +55 -0
- package/dist/core/triage-worker.d.ts.map +1 -0
- package/dist/core/triage-worker.js +314 -0
- package/dist/core/triage.d.ts +76 -0
- package/dist/core/triage.d.ts.map +1 -0
- package/dist/core/triage.js +271 -0
- package/dist/core/watch-paths.d.ts +6 -0
- package/dist/core/watch-paths.d.ts.map +1 -0
- package/dist/core/watch-paths.js +62 -0
- package/dist/core/wrappers/bash.d.ts +95 -0
- package/dist/core/wrappers/bash.d.ts.map +1 -0
- package/dist/core/wrappers/bash.js +413 -0
- package/dist/db/git-state-repo.d.ts +16 -0
- package/dist/db/git-state-repo.d.ts.map +1 -0
- package/dist/db/git-state-repo.js +38 -0
- package/dist/db/history-repo.d.ts +110 -0
- package/dist/db/history-repo.d.ts.map +1 -0
- package/dist/db/history-repo.js +300 -0
- package/dist/db/index.d.ts +49 -0
- package/dist/db/index.d.ts.map +1 -0
- package/dist/db/index.js +128 -0
- package/dist/db/metrics-repo.d.ts +46 -0
- package/dist/db/metrics-repo.d.ts.map +1 -0
- package/dist/db/metrics-repo.js +103 -0
- package/dist/db/migrate.d.ts +24 -0
- package/dist/db/migrate.d.ts.map +1 -0
- package/dist/db/migrate.js +244 -0
- package/dist/db/recovery.d.ts +11 -0
- package/dist/db/recovery.d.ts.map +1 -0
- package/dist/db/recovery.js +38 -0
- package/dist/db/run-journal.d.ts +60 -0
- package/dist/db/run-journal.d.ts.map +1 -0
- package/dist/db/run-journal.js +143 -0
- package/dist/db/run-resume.d.ts +48 -0
- package/dist/db/run-resume.d.ts.map +1 -0
- package/dist/db/run-resume.js +137 -0
- package/dist/db/runs-repo.d.ts +120 -0
- package/dist/db/runs-repo.d.ts.map +1 -0
- package/dist/db/runs-repo.js +319 -0
- package/dist/db/schema.d.ts +38 -0
- package/dist/db/schema.d.ts.map +1 -0
- package/dist/db/schema.js +325 -0
- package/dist/db/settings-repo.d.ts +8 -0
- package/dist/db/settings-repo.d.ts.map +1 -0
- package/dist/db/settings-repo.js +27 -0
- package/dist/db/tasks-repo.d.ts +26 -0
- package/dist/db/tasks-repo.d.ts.map +1 -0
- package/dist/db/tasks-repo.js +120 -0
- package/dist/db/templates-repo.d.ts +17 -0
- package/dist/db/templates-repo.d.ts.map +1 -0
- package/dist/db/templates-repo.js +57 -0
- package/dist/history.d.ts +60 -0
- package/dist/history.d.ts.map +1 -0
- package/dist/history.js +70 -0
- package/dist/i18n.d.ts +75 -0
- package/dist/i18n.d.ts.map +1 -0
- package/dist/i18n.js +357 -0
- package/dist/index.d.ts +858 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +5209 -0
- package/dist/integrations.d.ts +72 -0
- package/dist/integrations.d.ts.map +1 -0
- package/dist/integrations.js +233 -0
- package/dist/notifications.d.ts +199 -0
- package/dist/notifications.d.ts.map +1 -0
- package/dist/notifications.js +967 -0
- package/dist/profiles.d.ts +64 -0
- package/dist/profiles.d.ts.map +1 -0
- package/dist/profiles.js +305 -0
- package/dist/rpc.d.ts +3915 -0
- package/dist/rpc.d.ts.map +1 -0
- package/dist/rpc.js +1596 -0
- package/dist/schtasks.d.ts +32 -0
- package/dist/schtasks.d.ts.map +1 -0
- package/dist/schtasks.js +45 -0
- package/dist/server.d.ts +128 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +2414 -0
- package/dist/settings.d.ts +389 -0
- package/dist/settings.d.ts.map +1 -0
- package/dist/settings.js +770 -0
- package/dist/shared/jobs-view.d.ts +59 -0
- package/dist/shared/jobs-view.d.ts.map +1 -0
- package/dist/shared/jobs-view.js +146 -0
- package/dist/skill.d.ts +15 -0
- package/dist/skill.d.ts.map +1 -0
- package/dist/skill.js +93 -0
- package/dist/task-transfer.d.ts +252 -0
- package/dist/task-transfer.d.ts.map +1 -0
- package/dist/task-transfer.js +632 -0
- package/dist/templates.d.ts +57 -0
- package/dist/templates.d.ts.map +1 -0
- package/dist/templates.js +16 -0
- package/dist/types.d.ts +112 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +158 -0
- 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 +113 -0
- package/dist/workspaces.d.ts.map +1 -0
- package/dist/workspaces.js +393 -0
- package/docs/ARCHITECTURE.md +559 -0
- package/docs/COMPATIBILITY.md +237 -0
- package/docs/CONCEPT.md +242 -0
- package/docs/CROSS_PLATFORM.ru.md +152 -0
- package/docs/CROSS_PLATFORM.zh.md +148 -0
- package/docs/FAQ.md +52 -0
- package/docs/FAQ.ru.md +53 -0
- package/docs/FAQ.zh.md +43 -0
- package/docs/FEATURES.md +699 -0
- package/docs/FEATURES.zh.md +656 -0
- package/docs/LOCAL-AI.md +300 -0
- package/docs/MIGRATION.md +363 -0
- package/docs/README.ru.md +287 -0
- package/docs/README.zh.md +306 -0
- package/docs/SAVINGS.md +61 -0
- package/docs/SAVINGS.ru.md +60 -0
- package/docs/SAVINGS.zh.md +52 -0
- package/docs/V1-V2-COMPATIBILITY-PLAN.md +366 -0
- package/docs/ZH-LOCALE-PLAN.md +324 -0
- package/docs/dashboard.png +0 -0
- package/docs/spikes/local-model-structured-output.md +81 -0
- package/docs/spikes/ollama-qwen3-4b-smoke.json +28 -0
- package/docs/spikes/ollama-qwen3-4b.json +163 -0
- package/gui-experimental.cjs +9 -0
- package/index.js +2 -0
- package/locales/en.json +781 -0
- package/locales/ru.json +781 -0
- package/locales/zh.json +781 -0
- package/package.json +154 -13
- package/scripts/bench-local.mjs +321 -0
- package/scripts/check-zh-locale.mjs +218 -0
- package/scripts/demo-dashboard.mjs +209 -0
- package/scripts/run-tests.mjs +236 -0
- package/scripts/spike-local-structured.mjs +182 -0
- package/scripts/test-locale.mjs +45 -0
- package/skills/scheduled-job-best-practices/SKILL.md +158 -0
- package/skills/scheduled-job-best-practices/references/recipes.md +163 -0
- package/src/core/analytics.ts +424 -0
- package/src/core/audit.ts +418 -0
- package/src/core/cron-to-schtasks.ts +209 -0
- package/src/core/dry-run.ts +601 -0
- package/src/core/file-watcher.ts +245 -0
- package/src/core/git-trigger.ts +391 -0
- package/src/core/glob.ts +226 -0
- package/src/core/local-ai.ts +173 -0
- package/src/core/lock.ts +219 -0
- package/src/core/matrix.ts +947 -0
- package/src/core/native-notify.ts +157 -0
- package/src/core/one-shot.ts +239 -0
- package/src/core/otel.ts +128 -0
- package/src/core/permissions.ts +200 -0
- package/src/core/prometheus.ts +215 -0
- package/src/core/ps-wrapper.ts +1160 -0
- package/src/core/record-history.ts +615 -0
- package/src/core/retention.ts +141 -0
- package/src/core/savings.ts +150 -0
- package/src/core/schedule-gate.ts +253 -0
- package/src/core/schedule-v2.ts +668 -0
- package/src/core/scheduler/at-fallback.ts +113 -0
- package/src/core/scheduler/index.ts +82 -0
- package/src/core/scheduler/linux.ts +308 -0
- package/src/core/scheduler/logs.ts +37 -0
- package/src/core/scheduler/mac.ts +322 -0
- package/src/core/scheduler/posix.ts +128 -0
- package/src/core/scheduler/registry.ts +101 -0
- package/src/core/scheduler/types.ts +90 -0
- package/src/core/scheduler/windows.ts +881 -0
- package/src/core/secrets.ts +503 -0
- package/src/core/self-analysis.ts +744 -0
- package/src/core/session.ts +150 -0
- package/src/core/shutdown.ts +69 -0
- package/src/core/structured-log.ts +214 -0
- package/src/core/summary.ts +318 -0
- package/src/core/telegram.ts +436 -0
- package/src/core/triage-chain.ts +125 -0
- package/src/core/triage-compare.ts +277 -0
- package/src/core/triage-rules.ts +238 -0
- package/src/core/triage-shadow.ts +240 -0
- package/src/core/triage-worker.ts +344 -0
- package/src/core/triage.ts +366 -0
- package/src/core/watch-paths.ts +70 -0
- package/src/core/wrappers/bash.ts +532 -0
- package/src/db/git-state-repo.ts +62 -0
- package/src/db/history-repo.ts +492 -0
- package/src/db/index.ts +176 -0
- package/src/db/metrics-repo.ts +170 -0
- package/src/db/migrate.ts +328 -0
- package/src/db/recovery.ts +46 -0
- package/src/db/run-journal.ts +212 -0
- package/src/db/run-resume.ts +220 -0
- package/src/db/runs-repo.ts +481 -0
- package/src/db/schema.ts +349 -0
- package/src/db/settings-repo.ts +31 -0
- package/src/db/tasks-repo.ts +162 -0
- package/src/db/templates-repo.ts +77 -0
- package/src/gui.tsx +5222 -0
- package/src/history.ts +128 -0
- package/src/i18n.ts +413 -0
- package/src/index.ts +6642 -0
- package/src/integrations.ts +297 -0
- package/src/notifications.ts +1346 -0
- package/src/profiles.ts +345 -0
- package/src/rpc.ts +1704 -0
- package/src/schtasks.ts +75 -0
- package/src/server.ts +2663 -0
- package/src/settings.ts +1369 -0
- package/src/shared/jobs-view.ts +188 -0
- package/src/skill.ts +113 -0
- package/src/task-transfer.ts +946 -0
- package/src/templates.ts +67 -0
- package/src/tui-v1.tsx +341 -0
- package/src/tui.tsx +329 -0
- package/src/types.ts +226 -0
- package/src/version.ts +27 -0
- package/src/workspaces.ts +487 -0
|
@@ -0,0 +1,967 @@
|
|
|
1
|
+
import { loadSettings, saveSettings, isShadowActive, } from "./settings.js";
|
|
2
|
+
import { buildAnalytics, } from "./core/analytics.js";
|
|
3
|
+
import { getHistory } from "./db/history-repo.js";
|
|
4
|
+
import { getDb, withTransaction } from "./db/index.js";
|
|
5
|
+
import { sendTelegramMessage } from "./core/telegram.js";
|
|
6
|
+
import { sendNativeNotification } from "./core/native-notify.js";
|
|
7
|
+
import { decideTriage } from "./core/triage-chain.js";
|
|
8
|
+
import { recordTriageOutcome } from "./core/triage-shadow.js";
|
|
9
|
+
import { scheduleTriageJob } from "./core/triage-worker.js";
|
|
10
|
+
import { summarizeNotification, summaryProviderFromTriage, } from "./core/summary.js";
|
|
11
|
+
import { t } from "./i18n.js";
|
|
12
|
+
/** Таймаут HTTP-запроса по умолчанию: уведомление не должно подвешивать задачу. */
|
|
13
|
+
const REQUEST_TIMEOUT_MS = 10000;
|
|
14
|
+
/** Максимальная задержка backoff между повторами. */
|
|
15
|
+
const MAX_RETRY_DELAY_MS = 30000;
|
|
16
|
+
/** Человекочитаемая длительность: 2300 мс → «2.3s». */
|
|
17
|
+
export function formatDuration(durationMs) {
|
|
18
|
+
const seconds = Math.max(0, Number(durationMs) || 0) / 1000;
|
|
19
|
+
return `${seconds.toFixed(1)}s`;
|
|
20
|
+
}
|
|
21
|
+
/** Экранирует regexp-спецсимволы. */
|
|
22
|
+
function escapeRegExp(text) {
|
|
23
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Сопоставление имени задачи с шаблоном: `*` — любая последовательность,
|
|
27
|
+
* регистр не важен. `regen-*` покрывает `regen-api`, `regen-ui`.
|
|
28
|
+
*/
|
|
29
|
+
export function wildcardMatch(pattern, value) {
|
|
30
|
+
const trimmed = (pattern ?? "").trim();
|
|
31
|
+
if (!trimmed)
|
|
32
|
+
return false;
|
|
33
|
+
const source = trimmed
|
|
34
|
+
.split("*")
|
|
35
|
+
.map((part) => escapeRegExp(part))
|
|
36
|
+
.join(".*");
|
|
37
|
+
return new RegExp(`^${source}$`, "i").test(value.trim());
|
|
38
|
+
}
|
|
39
|
+
/** Проверяет, разрешена ли задача фильтрами include/exclude. */
|
|
40
|
+
export function isTaskAllowed(taskName, filters) {
|
|
41
|
+
if (!filters)
|
|
42
|
+
return true;
|
|
43
|
+
const name = (taskName ?? "").trim();
|
|
44
|
+
if (!name)
|
|
45
|
+
return false;
|
|
46
|
+
const exclude = filters.exclude ?? [];
|
|
47
|
+
if (exclude.some((pattern) => wildcardMatch(pattern, name)))
|
|
48
|
+
return false;
|
|
49
|
+
const include = filters.include ?? [];
|
|
50
|
+
if (include.length === 0)
|
|
51
|
+
return true;
|
|
52
|
+
return include.some((pattern) => wildcardMatch(pattern, name));
|
|
53
|
+
}
|
|
54
|
+
/** Подставляет {key} в шаблон; неизвестные плейсхолдеры остаются как есть. */
|
|
55
|
+
export function renderTemplate(template, vars) {
|
|
56
|
+
return template.replace(/\{(\w+)\}/g, (match, key) => Object.prototype.hasOwnProperty.call(vars, key) ? vars[key] : match);
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Формат сообщения по умолчанию:
|
|
60
|
+
* ✅ Задача "Тест" выполнена (2.3s)
|
|
61
|
+
* ❌ Задача "Тест" упала (2.3s): Quality Gate провален
|
|
62
|
+
*/
|
|
63
|
+
export function formatNotificationMessage(payload, templates) {
|
|
64
|
+
const { taskName, status, durationMs, error } = payload;
|
|
65
|
+
const duration = formatDuration(durationMs);
|
|
66
|
+
const isSuccess = status === "success";
|
|
67
|
+
const reason = typeof error === "string" && error.trim()
|
|
68
|
+
? t("notify.reason", { error: error.trim() })
|
|
69
|
+
: "";
|
|
70
|
+
const tokens = typeof payload.tokens === "number" && payload.tokens > 0
|
|
71
|
+
? t("notify.usage.tokens", { tokens: String(Math.round(payload.tokens)) })
|
|
72
|
+
: "";
|
|
73
|
+
const cost = typeof payload.costUsd === "number" && payload.costUsd > 0
|
|
74
|
+
? `$${payload.costUsd.toFixed(4)}`
|
|
75
|
+
: "";
|
|
76
|
+
const usage = [tokens, cost].filter(Boolean).join(" · ");
|
|
77
|
+
const usageSuffix = usage ? ` · ${usage}` : "";
|
|
78
|
+
const costVar = usageSuffix;
|
|
79
|
+
const tokensVar = tokens;
|
|
80
|
+
if (templates && isSuccess && templates.success.trim()) {
|
|
81
|
+
return renderTemplate(templates.success, {
|
|
82
|
+
task: taskName,
|
|
83
|
+
status,
|
|
84
|
+
duration,
|
|
85
|
+
error: "",
|
|
86
|
+
emoji: "✅",
|
|
87
|
+
cost: costVar,
|
|
88
|
+
tokens: tokensVar,
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
if (templates && !isSuccess && templates.error.trim()) {
|
|
92
|
+
return renderTemplate(templates.error, {
|
|
93
|
+
task: taskName,
|
|
94
|
+
status,
|
|
95
|
+
duration,
|
|
96
|
+
error: reason,
|
|
97
|
+
emoji: "❌",
|
|
98
|
+
cost: costVar,
|
|
99
|
+
tokens: tokensVar,
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
if (isSuccess) {
|
|
103
|
+
return t("notify.task.success", {
|
|
104
|
+
task: taskName,
|
|
105
|
+
duration,
|
|
106
|
+
cost: usageSuffix,
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
return t("notify.task.error", {
|
|
110
|
+
task: taskName,
|
|
111
|
+
duration,
|
|
112
|
+
error: reason,
|
|
113
|
+
cost: usageSuffix,
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
/** Текст уведомления о завершении матрицы. */
|
|
117
|
+
export function formatMatrixMessage(info) {
|
|
118
|
+
const { parentName, status, total, success, error } = info;
|
|
119
|
+
const params = { parent: parentName, total, success, error };
|
|
120
|
+
if (status === "success") {
|
|
121
|
+
return t("notify.matrix.success", params);
|
|
122
|
+
}
|
|
123
|
+
if (status === "partial") {
|
|
124
|
+
return t("notify.matrix.partial", params);
|
|
125
|
+
}
|
|
126
|
+
if (total > 0 && error >= total) {
|
|
127
|
+
return t("notify.matrix.failedAll", params);
|
|
128
|
+
}
|
|
129
|
+
return t("notify.matrix.failed", params);
|
|
130
|
+
}
|
|
131
|
+
/** Ошибка отправки webhook с признаком, имеет ли смысл повторять запрос. */
|
|
132
|
+
class WebhookError extends Error {
|
|
133
|
+
constructor(message, retryable) {
|
|
134
|
+
super(message);
|
|
135
|
+
this.retryable = retryable;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
139
|
+
function validateWebhookUrl(url) {
|
|
140
|
+
const trimmed = (url ?? "").trim();
|
|
141
|
+
if (!trimmed) {
|
|
142
|
+
throw new Error(t("notify.error.webhookUrlMissing"));
|
|
143
|
+
}
|
|
144
|
+
let parsed;
|
|
145
|
+
try {
|
|
146
|
+
parsed = new URL(trimmed);
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
throw new Error(t("notify.error.webhookUrlInvalid"));
|
|
150
|
+
}
|
|
151
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
152
|
+
throw new Error(t("notify.error.webhookScheme"));
|
|
153
|
+
}
|
|
154
|
+
return parsed;
|
|
155
|
+
}
|
|
156
|
+
/** Одна попытка POST. Бросает WebhookError с признаком retryable. */
|
|
157
|
+
async function postOnce(parsed, message, timeoutMs) {
|
|
158
|
+
const controller = new AbortController();
|
|
159
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
160
|
+
try {
|
|
161
|
+
const response = await fetch(parsed, {
|
|
162
|
+
method: "POST",
|
|
163
|
+
headers: { "Content-Type": "application/json" },
|
|
164
|
+
body: JSON.stringify({ content: message, text: message }),
|
|
165
|
+
signal: controller.signal,
|
|
166
|
+
});
|
|
167
|
+
if (!response.ok) {
|
|
168
|
+
const body = await response.text().catch(() => "");
|
|
169
|
+
const retryable = response.status >= 500 || response.status === 429;
|
|
170
|
+
throw new WebhookError(`HTTP ${response.status}${body ? `: ${body.slice(0, 200)}` : ""}`, retryable);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
catch (err) {
|
|
174
|
+
if (err?.name === "AbortError") {
|
|
175
|
+
throw new WebhookError(t("notify.error.webhookTimeout", { seconds: timeoutMs / 1000 }), true);
|
|
176
|
+
}
|
|
177
|
+
if (err instanceof WebhookError)
|
|
178
|
+
throw err;
|
|
179
|
+
// Сетевые ошибки fetch (DNS, соединение) имеет смысл повторять.
|
|
180
|
+
throw new WebhookError(err instanceof Error ? err.message : String(err), true);
|
|
181
|
+
}
|
|
182
|
+
finally {
|
|
183
|
+
clearTimeout(timer);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Отправляет POST на webhook с повторами и экспоненциальным backoff.
|
|
188
|
+
*
|
|
189
|
+
* Тело совместимо одновременно с Discord (`content`) и Slack (`text`).
|
|
190
|
+
* Повторяются только сетевые ошибки, таймауты, 5xx и 429; прочие 4xx — сразу
|
|
191
|
+
* ошибка (повтор не поможет). Бросает исключение только для диагностики —
|
|
192
|
+
* вызывающий код обязан перехватить его, чтобы уведомление не ломало задачу.
|
|
193
|
+
*/
|
|
194
|
+
export async function sendWebhook(url, message, options = {}) {
|
|
195
|
+
const parsed = validateWebhookUrl(url);
|
|
196
|
+
const timeoutMs = Math.max(1, Math.floor(options.timeoutMs ?? REQUEST_TIMEOUT_MS));
|
|
197
|
+
const retryCount = Math.max(0, Math.floor(options.retryCount ?? 0));
|
|
198
|
+
const retryDelayMs = Math.max(1, Math.floor(options.retryDelayMs ?? 1000));
|
|
199
|
+
const sleep = options.sleep ?? defaultSleep;
|
|
200
|
+
const attempts = retryCount + 1;
|
|
201
|
+
let lastError;
|
|
202
|
+
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
203
|
+
try {
|
|
204
|
+
await postOnce(parsed, message, timeoutMs);
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
catch (err) {
|
|
208
|
+
lastError = err;
|
|
209
|
+
const retryable = err instanceof WebhookError ? err.retryable : true;
|
|
210
|
+
if (!retryable || attempt === attempts - 1)
|
|
211
|
+
break;
|
|
212
|
+
const delay = Math.min(MAX_RETRY_DELAY_MS, retryDelayMs * 2 ** attempt);
|
|
213
|
+
await sleep(delay);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
throw lastError instanceof Error ? lastError : new Error(String(lastError));
|
|
217
|
+
}
|
|
218
|
+
function webhookOptionsFrom(config) {
|
|
219
|
+
const webhook = config.webhook;
|
|
220
|
+
return {
|
|
221
|
+
timeoutMs: webhook?.timeoutMs,
|
|
222
|
+
retryCount: webhook?.retryCount,
|
|
223
|
+
retryDelayMs: webhook?.retryDelayMs,
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Тихие часы: true, если сейчас действует окно `quiet`. Диапазон может
|
|
228
|
+
* переходить через полночь (22:00 → 08:00). Некорректное время — false.
|
|
229
|
+
*/
|
|
230
|
+
export function isQuietHours(now, quiet) {
|
|
231
|
+
if (!quiet?.enabled)
|
|
232
|
+
return false;
|
|
233
|
+
const parse = (value) => {
|
|
234
|
+
const match = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(typeof value === "string" ? value.trim() : "");
|
|
235
|
+
return match ? Number(match[1]) * 60 + Number(match[2]) : null;
|
|
236
|
+
};
|
|
237
|
+
const from = parse(quiet.from);
|
|
238
|
+
const to = parse(quiet.to);
|
|
239
|
+
if (from === null || to === null)
|
|
240
|
+
return false;
|
|
241
|
+
const minutes = now.getHours() * 60 + now.getMinutes();
|
|
242
|
+
if (from === to)
|
|
243
|
+
return true;
|
|
244
|
+
if (from < to)
|
|
245
|
+
return minutes >= from && minutes < to;
|
|
246
|
+
return minutes >= from || minutes < to;
|
|
247
|
+
}
|
|
248
|
+
/** URL дашборда: настройка, иначе фактический порт сервера, иначе null. */
|
|
249
|
+
async function resolveDashboardUrl(config) {
|
|
250
|
+
const custom = (config.dashboardUrl ?? "").trim();
|
|
251
|
+
if (custom)
|
|
252
|
+
return custom;
|
|
253
|
+
try {
|
|
254
|
+
const { getDashboardPort } = await import("./server.js");
|
|
255
|
+
const port = getDashboardPort();
|
|
256
|
+
return port ? `http://localhost:${port}` : null;
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
return null;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
/** Токен и chat_id Telegram: настройки важнее переменных окружения. */
|
|
263
|
+
function telegramCredentials(config) {
|
|
264
|
+
const token = (config.telegram?.botToken ?? "").trim() ||
|
|
265
|
+
(process.env.OPENCODE_SCHEDULER_TELEGRAM_BOT_TOKEN ?? "").trim();
|
|
266
|
+
const chatId = (config.telegram?.chatId ?? "").trim() ||
|
|
267
|
+
(process.env.OPENCODE_SCHEDULER_TELEGRAM_CHAT_ID ?? "").trim();
|
|
268
|
+
return { token, chatId };
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Отправляет сообщение во все включённые каналы и возвращает результат
|
|
272
|
+
* по каждому. Ошибки каналов не прерывают остальные и не содержат секретов.
|
|
273
|
+
*/
|
|
274
|
+
async function deliverDetailed(config, message, only) {
|
|
275
|
+
const results = [];
|
|
276
|
+
const dashboardUrl = await resolveDashboardUrl(config);
|
|
277
|
+
const webhook = config.webhook;
|
|
278
|
+
if ((!only || only === "webhook") &&
|
|
279
|
+
config.enabled &&
|
|
280
|
+
webhook?.enabled &&
|
|
281
|
+
webhook.url.trim()) {
|
|
282
|
+
try {
|
|
283
|
+
await sendWebhook(webhook.url, message, webhookOptionsFrom(config));
|
|
284
|
+
console.log("[agent-steward] Уведомление отправлено в webhook.");
|
|
285
|
+
results.push({ channel: "webhook", ok: true });
|
|
286
|
+
}
|
|
287
|
+
catch (err) {
|
|
288
|
+
const text = err instanceof Error ? err.message : String(err);
|
|
289
|
+
console.error(`[agent-steward] Webhook: ${text}`);
|
|
290
|
+
results.push({ channel: "webhook", ok: false, error: text });
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
const telegram = config.telegram;
|
|
294
|
+
if ((!only || only === "telegram") && config.enabled && telegram?.enabled) {
|
|
295
|
+
const { token, chatId } = telegramCredentials(config);
|
|
296
|
+
if (!token || !chatId) {
|
|
297
|
+
const text = t("notify.error.telegramNoCreds");
|
|
298
|
+
console.error(`[agent-steward] ${text}`);
|
|
299
|
+
results.push({ channel: "telegram", ok: false, error: text });
|
|
300
|
+
}
|
|
301
|
+
else {
|
|
302
|
+
try {
|
|
303
|
+
await sendTelegramMessage(token, chatId, message, {
|
|
304
|
+
apiBase: telegram.apiBase,
|
|
305
|
+
parseMode: telegram.parseMode,
|
|
306
|
+
disableNotification: telegram.disableNotification,
|
|
307
|
+
messageThreadId: telegram.messageThreadId,
|
|
308
|
+
includeDashboardLink: telegram.includeDashboardLink,
|
|
309
|
+
dashboardUrl,
|
|
310
|
+
});
|
|
311
|
+
console.log("[agent-steward] Уведомление отправлено в Telegram.");
|
|
312
|
+
results.push({ channel: "telegram", ok: true });
|
|
313
|
+
}
|
|
314
|
+
catch (err) {
|
|
315
|
+
const text = err instanceof Error ? err.message : String(err);
|
|
316
|
+
console.error(`[agent-steward] Telegram: ${text}`);
|
|
317
|
+
results.push({ channel: "telegram", ok: false, error: text });
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
const native = config.native;
|
|
322
|
+
if ((!only || only === "native") && config.enabled && native?.enabled) {
|
|
323
|
+
const result = await sendNativeNotification({ title: t("notify.native.title"), body: message, sound: native.sound }, {});
|
|
324
|
+
if (result.success) {
|
|
325
|
+
console.log("[agent-steward] Нативное уведомление показано.");
|
|
326
|
+
results.push({ channel: "native", ok: true });
|
|
327
|
+
}
|
|
328
|
+
else {
|
|
329
|
+
const text = result.error ?? t("notify.error.nativeFailed");
|
|
330
|
+
console.error(`[agent-steward] Нативное уведомление: ${text}`);
|
|
331
|
+
results.push({ channel: "native", ok: false, error: text });
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
return results;
|
|
335
|
+
}
|
|
336
|
+
/** Отправляет текст во все включённые каналы; true — хотя бы один успешен. */
|
|
337
|
+
async function deliver(config, message) {
|
|
338
|
+
const results = await deliverDetailed(config, message);
|
|
339
|
+
return results.some((item) => item.ok);
|
|
340
|
+
}
|
|
341
|
+
/** Ключ дедупа: комбинация задачи и статуса. */
|
|
342
|
+
function dedupKey(taskName, status) {
|
|
343
|
+
return (taskName + "|" + status).toLowerCase();
|
|
344
|
+
}
|
|
345
|
+
/** Читает или создаёт запись дедупа. Возвращает { record, isDuplicate }.
|
|
346
|
+
* Если записи нет или окно истекло — создаёт новую с count=1.
|
|
347
|
+
* Если есть и окно ещё активно — увеличивает count и возвращает isDuplicate=true.
|
|
348
|
+
*/
|
|
349
|
+
function dedupReadOrCreate(db, key, taskName, status, dedup) {
|
|
350
|
+
const now = new Date().toISOString();
|
|
351
|
+
const row = db
|
|
352
|
+
.prepare("SELECT * FROM notification_dedup WHERE key = ?")
|
|
353
|
+
.get(key);
|
|
354
|
+
if (!row) {
|
|
355
|
+
db.prepare("INSERT INTO notification_dedup (key, task_name, status, count, first_at, last_at, window_minutes) VALUES (?, ?, ?, 1, ?, ?, ?)").run(key, taskName, status, now, now, dedup.windowMinutes);
|
|
356
|
+
return {
|
|
357
|
+
record: {
|
|
358
|
+
key,
|
|
359
|
+
taskName,
|
|
360
|
+
status,
|
|
361
|
+
count: 1,
|
|
362
|
+
firstAt: now,
|
|
363
|
+
lastAt: now,
|
|
364
|
+
windowMinutes: dedup.windowMinutes,
|
|
365
|
+
},
|
|
366
|
+
isDuplicate: false,
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
const last = new Date(row.last_at).getTime();
|
|
370
|
+
const nowMs = new Date(now).getTime();
|
|
371
|
+
const windowMs = (row.window_minutes ?? dedup.windowMinutes) * 60 * 1000;
|
|
372
|
+
if (nowMs - last > windowMs) {
|
|
373
|
+
// Окно истекло — начинаем заново.
|
|
374
|
+
db.prepare("UPDATE notification_dedup SET count = 1, first_at = ?, last_at = ?, window_minutes = ? WHERE key = ?").run(now, now, dedup.windowMinutes, key);
|
|
375
|
+
return {
|
|
376
|
+
record: {
|
|
377
|
+
key,
|
|
378
|
+
taskName,
|
|
379
|
+
status,
|
|
380
|
+
count: 1,
|
|
381
|
+
firstAt: now,
|
|
382
|
+
lastAt: now,
|
|
383
|
+
windowMinutes: dedup.windowMinutes,
|
|
384
|
+
},
|
|
385
|
+
isDuplicate: false,
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
const count = Math.min(Number(row.count) + 1, dedup.maxCount);
|
|
389
|
+
db.prepare("UPDATE notification_dedup SET count = ?, last_at = ? WHERE key = ?").run(count, now, key);
|
|
390
|
+
return {
|
|
391
|
+
record: {
|
|
392
|
+
key,
|
|
393
|
+
taskName,
|
|
394
|
+
status,
|
|
395
|
+
count,
|
|
396
|
+
firstAt: row.first_at,
|
|
397
|
+
lastAt: now,
|
|
398
|
+
windowMinutes: row.window_minutes ?? dedup.windowMinutes,
|
|
399
|
+
},
|
|
400
|
+
isDuplicate: true,
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
/** Подавлять ли уведомление по дедупу: только если не важный статус. */
|
|
404
|
+
function isDedupSuppressed(status, dedup) {
|
|
405
|
+
const important = dedup.importantStatuses.some((s) => s.toLowerCase() === status.toLowerCase());
|
|
406
|
+
return !important;
|
|
407
|
+
}
|
|
408
|
+
/** Добавляет счётчик повторов к сообщению, если это не первое уведомление. */
|
|
409
|
+
function messageWithDedupCount(message, count) {
|
|
410
|
+
if (count <= 1)
|
|
411
|
+
return message;
|
|
412
|
+
return message + " " + t("notify.dedup.count", { count });
|
|
413
|
+
}
|
|
414
|
+
/** Размерность вектора фиксирована: feature hashing, а не словарь сообщения. */
|
|
415
|
+
const EMBEDDING_DIMENSION = 512;
|
|
416
|
+
/** FNV-1a 32-bit — стабильный хеш токена между процессами и запусками. */
|
|
417
|
+
function fnv1a32(value) {
|
|
418
|
+
let hash = 0x811c9dc5;
|
|
419
|
+
for (let i = 0; i < value.length; i++) {
|
|
420
|
+
hash ^= value.charCodeAt(i);
|
|
421
|
+
hash = Math.imul(hash, 0x01000193);
|
|
422
|
+
}
|
|
423
|
+
return hash >>> 0;
|
|
424
|
+
}
|
|
425
|
+
function embeddingKey(taskName, status) {
|
|
426
|
+
return `emb:${(taskName + "|" + status).toLowerCase()}`;
|
|
427
|
+
}
|
|
428
|
+
/** Простой токенизатор: слова, цифры, нижний регистр. */
|
|
429
|
+
function tokenize(text) {
|
|
430
|
+
return text
|
|
431
|
+
.toLowerCase()
|
|
432
|
+
.replace(/[^a-zа-яё0-9\s]/g, " ")
|
|
433
|
+
.split(/\s+/)
|
|
434
|
+
.filter((t) => t.length > 0);
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* Вектор сообщения: feature hashing в фиксированную размерность.
|
|
438
|
+
*
|
|
439
|
+
* Раньше длина вектора равнялась числу уникальных слов, а индекс — порядку
|
|
440
|
+
* первого появления. Такие векторы нельзя сравнивать позиционно: один и тот
|
|
441
|
+
* же текст с другим порядком слов давал сходство < 1, а векторы разной длины
|
|
442
|
+
* вообще пропускались. Теперь каждый токен детерминированно проецируется
|
|
443
|
+
* в [0, EMBEDDING_DIMENSION), поэтому косинус корректен для любых двух текстов.
|
|
444
|
+
* Вес — 1 + log(tf), L2-нормализация; знак из старшего бита хеша снижает
|
|
445
|
+
* влияние коллизий.
|
|
446
|
+
*/
|
|
447
|
+
function textToVector(text) {
|
|
448
|
+
const tokens = tokenize(text);
|
|
449
|
+
const vec = new Array(EMBEDDING_DIMENSION).fill(0);
|
|
450
|
+
if (tokens.length === 0)
|
|
451
|
+
return vec;
|
|
452
|
+
const counts = new Map();
|
|
453
|
+
for (const tok of tokens)
|
|
454
|
+
counts.set(tok, (counts.get(tok) ?? 0) + 1);
|
|
455
|
+
for (const [tok, count] of counts) {
|
|
456
|
+
const hash = fnv1a32(tok);
|
|
457
|
+
const idx = hash % EMBEDDING_DIMENSION;
|
|
458
|
+
const sign = (hash & 0x80000000) !== 0 ? -1 : 1;
|
|
459
|
+
vec[idx] += sign * (1 + Math.log(count));
|
|
460
|
+
}
|
|
461
|
+
let norm = 0;
|
|
462
|
+
for (const v of vec)
|
|
463
|
+
norm += v * v;
|
|
464
|
+
norm = Math.sqrt(norm);
|
|
465
|
+
if (norm > 0) {
|
|
466
|
+
for (let i = 0; i < vec.length; i++)
|
|
467
|
+
vec[i] /= norm;
|
|
468
|
+
}
|
|
469
|
+
return vec;
|
|
470
|
+
}
|
|
471
|
+
function cosineSimilarity(a, b) {
|
|
472
|
+
// Векторы разных размерностей несравнимы: это разные пространства признаков.
|
|
473
|
+
if (a.length !== b.length || a.length === 0)
|
|
474
|
+
return 0;
|
|
475
|
+
let dot = 0;
|
|
476
|
+
let na = 0;
|
|
477
|
+
let nb = 0;
|
|
478
|
+
for (let i = 0; i < a.length; i++) {
|
|
479
|
+
dot += a[i] * b[i];
|
|
480
|
+
na += a[i] * a[i];
|
|
481
|
+
nb += b[i] * b[i];
|
|
482
|
+
}
|
|
483
|
+
const denom = Math.sqrt(na) * Math.sqrt(nb);
|
|
484
|
+
if (denom === 0)
|
|
485
|
+
return 0;
|
|
486
|
+
return dot / denom;
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* Проверяет, есть ли в БД вектор, достаточно похожий на text.
|
|
490
|
+
* Сравниваются только векторы той же задачи и того же статуса: иначе успех
|
|
491
|
+
* одной задачи «заражал» бы ошибки другой. Берём последние LIMIT векторов окна.
|
|
492
|
+
*/
|
|
493
|
+
function embeddingExists(db, taskName, status, message, threshold, windowMinutes) {
|
|
494
|
+
const since = new Date(Date.now() - windowMinutes * 60000).toISOString();
|
|
495
|
+
const rows = db
|
|
496
|
+
.prepare("SELECT key, embedding_json FROM notification_embeddings " +
|
|
497
|
+
"WHERE task_name = ? AND status = ? AND created_at >= ? " +
|
|
498
|
+
"ORDER BY created_at DESC LIMIT 500")
|
|
499
|
+
.all(taskName, status, since);
|
|
500
|
+
const vec = textToVector(message);
|
|
501
|
+
let bestKey = "";
|
|
502
|
+
let bestSim = 0;
|
|
503
|
+
for (const row of rows) {
|
|
504
|
+
try {
|
|
505
|
+
const emb = JSON.parse(row.embedding_json);
|
|
506
|
+
if (!Array.isArray(emb) || emb.length !== vec.length)
|
|
507
|
+
continue;
|
|
508
|
+
const sim = cosineSimilarity(vec, emb);
|
|
509
|
+
if (sim > bestSim) {
|
|
510
|
+
bestSim = sim;
|
|
511
|
+
bestKey = row.key;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
catch {
|
|
515
|
+
// пропускаем битую запись
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
if (bestSim >= threshold)
|
|
519
|
+
return { found: true, key: bestKey };
|
|
520
|
+
return null;
|
|
521
|
+
}
|
|
522
|
+
/**
|
|
523
|
+
* Сохраняет вектор сообщения в БД.
|
|
524
|
+
* Ключ уникален для каждого сообщения (а не task|status): храним историю,
|
|
525
|
+
* иначе INSERT OR REPLACE оставлял бы только последний вектор и дедуп
|
|
526
|
+
* сравнивал бы новое сообщение само с собой.
|
|
527
|
+
*/
|
|
528
|
+
function storeEmbedding(db, taskName, status, message, vector, windowMinutes) {
|
|
529
|
+
const now = new Date().toISOString();
|
|
530
|
+
const key = embeddingKey(taskName, status) +
|
|
531
|
+
`:${Date.now().toString(36)}:${Math.random().toString(36).slice(2, 8)}`;
|
|
532
|
+
db.prepare("INSERT INTO notification_embeddings (key, task_name, status, message_text, embedding_json, dimension, created_at, window_minutes) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(key, taskName, status, message, JSON.stringify(vector), vector.length, now, windowMinutes);
|
|
533
|
+
}
|
|
534
|
+
/** Очищает старые векторы вне окна и лишние сверх maxVectors. */
|
|
535
|
+
function cleanupEmbeddings(db, windowMinutes, maxVectors) {
|
|
536
|
+
const since = new Date(Date.now() - windowMinutes * 60000).toISOString();
|
|
537
|
+
db.prepare("DELETE FROM notification_embeddings WHERE created_at < ?").run(since);
|
|
538
|
+
if (maxVectors && maxVectors > 0) {
|
|
539
|
+
db.prepare("DELETE FROM notification_embeddings WHERE key NOT IN (" +
|
|
540
|
+
"SELECT key FROM notification_embeddings ORDER BY created_at DESC LIMIT ?)").run(maxVectors);
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
export async function notifyTaskCompletion(taskName, status, durationMs, error, tokens, costUsd, options = {}) {
|
|
544
|
+
try {
|
|
545
|
+
const settings = await loadSettings();
|
|
546
|
+
const config = settings.notifications;
|
|
547
|
+
if (!config?.enabled)
|
|
548
|
+
return;
|
|
549
|
+
if (config.onlyOnError && status === "success")
|
|
550
|
+
return;
|
|
551
|
+
if (!isTaskAllowed(taskName, config.filters))
|
|
552
|
+
return;
|
|
553
|
+
// Тихие часы подавляют успешные запуски, но не ошибки и таймауты.
|
|
554
|
+
if (isQuietHours(new Date(), config.quietHours) &&
|
|
555
|
+
status !== "error" &&
|
|
556
|
+
status !== "timeout") {
|
|
557
|
+
return;
|
|
558
|
+
}
|
|
559
|
+
// Триаж (31.7): в llm/auto уведомление не ждёт локальную модель.
|
|
560
|
+
// Вердикт считается фоновым процессом и пишется в persistent-аудит.
|
|
561
|
+
// В rules правила остаются синхронными, потому что только они подавляют.
|
|
562
|
+
// В shadow-режиме решение фиксируется, но уведомление не подавляется.
|
|
563
|
+
const triageInput = { taskName, status, error, durationMs, tokens, costUsd };
|
|
564
|
+
const triageSettings = config.triage;
|
|
565
|
+
const mode = triageSettings?.mode ?? "off";
|
|
566
|
+
const shadowActive = isShadowActive(triageSettings?.shadow);
|
|
567
|
+
if (triageSettings && (mode === "llm" || mode === "auto") && options.asyncTriage) {
|
|
568
|
+
try {
|
|
569
|
+
const job = (options.scheduleTriage ?? scheduleTriageJob)(triageInput, triageSettings);
|
|
570
|
+
// Injected scheduler может быть асинхронным — не оставляем rejection.
|
|
571
|
+
if (job && typeof job.then === "function") {
|
|
572
|
+
void Promise.resolve(job).catch((err) => {
|
|
573
|
+
console.error(`[agent-steward] Ошибка фонового триажа: ${err instanceof Error ? err.message : String(err)}`);
|
|
574
|
+
});
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
catch (err) {
|
|
578
|
+
console.error(`[agent-steward] Не удалось запустить фоновый триаж: ${err instanceof Error ? err.message : String(err)}`);
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
else if (mode !== "off") {
|
|
582
|
+
const triage = await decideTriage(triageInput, triageSettings);
|
|
583
|
+
const suppressed = !shadowActive && triage.action === "skip";
|
|
584
|
+
recordTriageOutcome(triageInput, triage, { shadowActive, suppressed });
|
|
585
|
+
if (suppressed)
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
// Дедуп (31.2): группирует похожие уведомления в окне времени,
|
|
589
|
+
// считает повторы, но не подавляет важные статусы.
|
|
590
|
+
let dedupCount = 1;
|
|
591
|
+
if (config.dedup?.enabled && config.dedup.suppressDuplicates) {
|
|
592
|
+
const dedup = config.dedup;
|
|
593
|
+
const db = getDb();
|
|
594
|
+
const key = dedupKey(taskName, status);
|
|
595
|
+
// Читать-изменять-записать нужно атомарно: иначе два процесса
|
|
596
|
+
// (задача + дашборд) теряют инкременты счётчика повторов.
|
|
597
|
+
const { record, isDuplicate } = withTransaction(() => dedupReadOrCreate(db, key, taskName, status, dedup));
|
|
598
|
+
dedupCount = record.count;
|
|
599
|
+
if (isDuplicate && isDedupSuppressed(status, dedup)) {
|
|
600
|
+
return;
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
const baseMessage = messageWithDedupCount(formatNotificationMessage({ taskName, status, durationMs, error, tokens, costUsd }, config.templates), dedupCount);
|
|
604
|
+
// Эмбеддинг-дедуп (31.1): семантическое подавление похожих сообщений.
|
|
605
|
+
// Проверяется после rule-based дедупа: если вектор совпадает с существующим
|
|
606
|
+
// на пороге threshold, уведомление подавляется (если не важный статус).
|
|
607
|
+
if (config.embedding?.enabled && config.embedding.suppressDuplicates) {
|
|
608
|
+
const db = getDb();
|
|
609
|
+
const message = baseMessage;
|
|
610
|
+
const hit = embeddingExists(db, taskName, status, message, config.embedding.threshold, config.embedding.windowMinutes ?? 60);
|
|
611
|
+
if (hit &&
|
|
612
|
+
isDedupSuppressed(status, config.dedup ?? {
|
|
613
|
+
enabled: false,
|
|
614
|
+
windowMinutes: 60,
|
|
615
|
+
suppressDuplicates: false,
|
|
616
|
+
importantStatuses: ["error", "timeout"],
|
|
617
|
+
maxCount: 999,
|
|
618
|
+
})) {
|
|
619
|
+
return;
|
|
620
|
+
}
|
|
621
|
+
const vec = textToVector(message);
|
|
622
|
+
storeEmbedding(db, taskName, status, message, vec, config.embedding.windowMinutes ?? 60);
|
|
623
|
+
cleanupEmbeddings(db, config.embedding.windowMinutes ?? 60, config.embedding.maxVectors);
|
|
624
|
+
}
|
|
625
|
+
// Саммари (31.3): в режиме summary используем три строки от модели,
|
|
626
|
+
// при любом отказе остаётся детерминированное усечение или базовое сообщение.
|
|
627
|
+
let finalMessage = baseMessage;
|
|
628
|
+
if (config.summary?.enabled) {
|
|
629
|
+
const summary = await summarizeNotification({
|
|
630
|
+
taskName,
|
|
631
|
+
status,
|
|
632
|
+
error: error ?? undefined,
|
|
633
|
+
durationMs,
|
|
634
|
+
tokens: tokens ?? undefined,
|
|
635
|
+
costUsd: costUsd ?? undefined,
|
|
636
|
+
}, config.summary, summaryProviderFromTriage(config.triage), {});
|
|
637
|
+
if (summary.lines.length) {
|
|
638
|
+
finalMessage = messageWithDedupCount(`${taskName} — ${status}\n${summary.lines.join("\n")}`, dedupCount);
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
await deliver(config, finalMessage);
|
|
642
|
+
}
|
|
643
|
+
catch (err) {
|
|
644
|
+
// Уведомление не должно ломать запись истории и саму задачу.
|
|
645
|
+
console.error(`[agent-steward] Ошибка подготовки уведомления: ${err instanceof Error ? err.message : String(err)}`);
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
/**
|
|
649
|
+
* Уведомляет о завершении матрицы (Спринт 20).
|
|
650
|
+
*
|
|
651
|
+
* partial — только при `matrix.onPartial`; полный провал — при
|
|
652
|
+
* `matrix.onAllFailed`; успех — только когда `onlyOnError === false`.
|
|
653
|
+
*/
|
|
654
|
+
export async function notifyMatrixCompletion(info) {
|
|
655
|
+
try {
|
|
656
|
+
const settings = await loadSettings();
|
|
657
|
+
const config = settings.notifications;
|
|
658
|
+
if (!config?.enabled)
|
|
659
|
+
return;
|
|
660
|
+
const matrix = config.matrix;
|
|
661
|
+
if (!matrix?.enabled)
|
|
662
|
+
return;
|
|
663
|
+
if (!isTaskAllowed(info.parentName, config.filters))
|
|
664
|
+
return;
|
|
665
|
+
if (info.status === "partial" && !matrix.onPartial)
|
|
666
|
+
return;
|
|
667
|
+
if (info.status === "error" && !matrix.onAllFailed)
|
|
668
|
+
return;
|
|
669
|
+
if (info.status === "success" && config.onlyOnError)
|
|
670
|
+
return;
|
|
671
|
+
if (isQuietHours(new Date(), config.quietHours) && info.status !== "error") {
|
|
672
|
+
return;
|
|
673
|
+
}
|
|
674
|
+
await deliver(config, formatMatrixMessage(info));
|
|
675
|
+
}
|
|
676
|
+
catch (err) {
|
|
677
|
+
console.error(`[agent-steward] Ошибка уведомления о матрице: ${err instanceof Error ? err.message : String(err)}`);
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
/**
|
|
681
|
+
* Ищет клоны матриц, которые выполняются дольше порога.
|
|
682
|
+
* `parentByClone` — соответствие «имя клона → имя родителя» (без регистра).
|
|
683
|
+
*/
|
|
684
|
+
export function findStuckMatrixClones(running, parentByClone, now, thresholdMinutes) {
|
|
685
|
+
if (!Number.isFinite(thresholdMinutes) || thresholdMinutes <= 0)
|
|
686
|
+
return [];
|
|
687
|
+
const thresholdMs = thresholdMinutes * 60000;
|
|
688
|
+
const result = [];
|
|
689
|
+
for (const record of running) {
|
|
690
|
+
const parentName = parentByClone.get(record.taskName.toLowerCase());
|
|
691
|
+
if (!parentName)
|
|
692
|
+
continue;
|
|
693
|
+
const started = new Date(record.startedAt).getTime();
|
|
694
|
+
if (!Number.isFinite(started))
|
|
695
|
+
continue;
|
|
696
|
+
const elapsed = now.getTime() - started;
|
|
697
|
+
if (elapsed < thresholdMs)
|
|
698
|
+
continue;
|
|
699
|
+
result.push({
|
|
700
|
+
id: record.id,
|
|
701
|
+
cloneName: record.taskName,
|
|
702
|
+
parentName,
|
|
703
|
+
startedAt: record.startedAt,
|
|
704
|
+
minutes: Math.floor(elapsed / 60000),
|
|
705
|
+
});
|
|
706
|
+
}
|
|
707
|
+
return result;
|
|
708
|
+
}
|
|
709
|
+
/** Текст уведомления о зависшем клоне матрицы. */
|
|
710
|
+
export function formatStuckMatrixMessage(stuck) {
|
|
711
|
+
return t("notify.stuck", {
|
|
712
|
+
parent: stuck.parentName,
|
|
713
|
+
clone: stuck.cloneName,
|
|
714
|
+
minutes: stuck.minutes,
|
|
715
|
+
startedAt: stuck.startedAt,
|
|
716
|
+
});
|
|
717
|
+
}
|
|
718
|
+
/** Отправляет уведомление о зависшем клоне, если матрицы включены. */
|
|
719
|
+
export async function notifyStuckMatrix(stuck) {
|
|
720
|
+
try {
|
|
721
|
+
const settings = await loadSettings();
|
|
722
|
+
const config = settings.notifications;
|
|
723
|
+
if (!config?.enabled)
|
|
724
|
+
return false;
|
|
725
|
+
if (!config.matrix?.enabled)
|
|
726
|
+
return false;
|
|
727
|
+
if (!isTaskAllowed(stuck.parentName, config.filters))
|
|
728
|
+
return false;
|
|
729
|
+
return await deliver(config, formatStuckMatrixMessage(stuck));
|
|
730
|
+
}
|
|
731
|
+
catch (err) {
|
|
732
|
+
console.error(`[agent-steward] Ошибка уведомления о зависшей матрице: ${err instanceof Error ? err.message : String(err)}`);
|
|
733
|
+
return false;
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
/** Форматирует деньги: $0.0412. */
|
|
737
|
+
function formatMoney(value) {
|
|
738
|
+
return `$${value.toFixed(4)}`;
|
|
739
|
+
}
|
|
740
|
+
/** Форматирует локальную дату DD.MM.YYYY. */
|
|
741
|
+
function formatLocalDate(date) {
|
|
742
|
+
const day = String(date.getDate()).padStart(2, "0");
|
|
743
|
+
const month = String(date.getMonth() + 1).padStart(2, "0");
|
|
744
|
+
return `${day}.${month}.${date.getFullYear()}`;
|
|
745
|
+
}
|
|
746
|
+
/** Строит сводку дайджеста из записей истории. */
|
|
747
|
+
export function buildDigestSummary(records, options) {
|
|
748
|
+
const now = options.now ?? new Date();
|
|
749
|
+
const windowDays = options.frequency === "weekly" ? 7 : 1;
|
|
750
|
+
const report = buildAnalytics(records, {
|
|
751
|
+
days: windowDays,
|
|
752
|
+
now,
|
|
753
|
+
topLimit: 5,
|
|
754
|
+
});
|
|
755
|
+
return {
|
|
756
|
+
period: options.frequency,
|
|
757
|
+
windowDays,
|
|
758
|
+
total: report.totals.total,
|
|
759
|
+
success: report.totals.success,
|
|
760
|
+
error: report.totals.error,
|
|
761
|
+
partial: report.totals.partial,
|
|
762
|
+
successRate: report.totals.successRate,
|
|
763
|
+
tokens: report.totals.tokens,
|
|
764
|
+
costUsd: report.totals.costUsd,
|
|
765
|
+
topErrors: report.errors,
|
|
766
|
+
};
|
|
767
|
+
}
|
|
768
|
+
/** Текст дайджеста. */
|
|
769
|
+
export function formatDigestMessage(summary, now = new Date()) {
|
|
770
|
+
const periodLabel = summary.period === "weekly"
|
|
771
|
+
? t("notify.digest.period.weekly")
|
|
772
|
+
: t("notify.digest.period.daily");
|
|
773
|
+
const lines = [
|
|
774
|
+
t("notify.digest.title", { period: periodLabel, date: formatLocalDate(now) }),
|
|
775
|
+
t("notify.digest.runs", {
|
|
776
|
+
total: summary.total,
|
|
777
|
+
success: summary.success,
|
|
778
|
+
error: summary.error,
|
|
779
|
+
partial: summary.partial,
|
|
780
|
+
rate: summary.successRate,
|
|
781
|
+
}),
|
|
782
|
+
t("notify.digest.cost", {
|
|
783
|
+
cost: formatMoney(summary.costUsd),
|
|
784
|
+
tokens: summary.tokens,
|
|
785
|
+
}),
|
|
786
|
+
];
|
|
787
|
+
if (summary.topErrors.length > 0) {
|
|
788
|
+
lines.push(t("notify.digest.topErrors"));
|
|
789
|
+
for (const row of summary.topErrors) {
|
|
790
|
+
lines.push(t("notify.digest.topErrorRow", { message: row.message, count: row.count }));
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
else if (summary.total > 0) {
|
|
794
|
+
lines.push(t("notify.digest.noErrors"));
|
|
795
|
+
}
|
|
796
|
+
return lines.join("\n");
|
|
797
|
+
}
|
|
798
|
+
/**
|
|
799
|
+
* Пора ли отправлять дайджест.
|
|
800
|
+
*
|
|
801
|
+
* daily — раз в сутки после `digest.time`; weekly — по понедельникам после
|
|
802
|
+
* `digest.time`. `lastSentAt` защищает от повторной отправки после перезапуска.
|
|
803
|
+
*/
|
|
804
|
+
export function isDigestDue(digest, now) {
|
|
805
|
+
if (!digest.enabled)
|
|
806
|
+
return false;
|
|
807
|
+
const match = /^([01]\d|2[0-3]):([0-5]\d)$/.exec((digest.time ?? "").trim());
|
|
808
|
+
if (!match)
|
|
809
|
+
return false;
|
|
810
|
+
const hour = Number(match[1]);
|
|
811
|
+
const minute = Number(match[2]);
|
|
812
|
+
const target = new Date(now.getTime());
|
|
813
|
+
target.setHours(hour, minute, 0, 0);
|
|
814
|
+
if (digest.frequency === "weekly") {
|
|
815
|
+
// Понедельник текущей недели (getDay(): 0 = воскресенье).
|
|
816
|
+
const offset = (target.getDay() + 6) % 7;
|
|
817
|
+
target.setDate(target.getDate() - offset);
|
|
818
|
+
}
|
|
819
|
+
if (now.getTime() < target.getTime())
|
|
820
|
+
return false;
|
|
821
|
+
if (!digest.lastSentAt)
|
|
822
|
+
return true;
|
|
823
|
+
const last = new Date(digest.lastSentAt).getTime();
|
|
824
|
+
return !Number.isFinite(last) || last < target.getTime();
|
|
825
|
+
}
|
|
826
|
+
/**
|
|
827
|
+
* Собирает и отправляет дайджест.
|
|
828
|
+
*
|
|
829
|
+
* `updateLastSentAt` включается только для плановой отправки: ручная кнопка
|
|
830
|
+
* «Отправить сейчас» не должна сдвигать расписание.
|
|
831
|
+
*/
|
|
832
|
+
export async function sendDigestNow(options = {}) {
|
|
833
|
+
const now = options.now ?? new Date();
|
|
834
|
+
try {
|
|
835
|
+
const settings = await loadSettings();
|
|
836
|
+
const config = settings.notifications;
|
|
837
|
+
if (!config?.enabled) {
|
|
838
|
+
return { success: false, message: t("notify.error.digestDisabled") };
|
|
839
|
+
}
|
|
840
|
+
const channels = [];
|
|
841
|
+
if (config.webhook?.enabled && config.webhook.url.trim())
|
|
842
|
+
channels.push("webhook");
|
|
843
|
+
if (config.telegram?.enabled)
|
|
844
|
+
channels.push("telegram");
|
|
845
|
+
if (config.native?.enabled)
|
|
846
|
+
channels.push("native");
|
|
847
|
+
if (channels.length === 0) {
|
|
848
|
+
return {
|
|
849
|
+
success: false,
|
|
850
|
+
message: t("notify.error.digestNoChannels"),
|
|
851
|
+
};
|
|
852
|
+
}
|
|
853
|
+
const digest = config.digest;
|
|
854
|
+
if (!digest) {
|
|
855
|
+
return { success: false, message: t("notify.error.digestMissing") };
|
|
856
|
+
}
|
|
857
|
+
const records = getHistory(null, 5000);
|
|
858
|
+
const summary = buildDigestSummary(records, {
|
|
859
|
+
frequency: digest.frequency,
|
|
860
|
+
now,
|
|
861
|
+
});
|
|
862
|
+
const text = formatDigestMessage(summary, now);
|
|
863
|
+
if (!(await deliver(config, text))) {
|
|
864
|
+
return { success: false, message: t("notify.error.digestFailed") };
|
|
865
|
+
}
|
|
866
|
+
if (options.updateLastSentAt) {
|
|
867
|
+
await saveSettings({
|
|
868
|
+
notifications: {
|
|
869
|
+
...config,
|
|
870
|
+
digest: { ...digest, lastSentAt: now.toISOString() },
|
|
871
|
+
},
|
|
872
|
+
});
|
|
873
|
+
}
|
|
874
|
+
return { success: true, message: t("notify.ok.digestSent") };
|
|
875
|
+
}
|
|
876
|
+
catch (err) {
|
|
877
|
+
return {
|
|
878
|
+
success: false,
|
|
879
|
+
message: err instanceof Error ? err.message : String(err),
|
|
880
|
+
};
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
/** Плановая проверка дайджеста: отправляет, если пора. Возвращает true при отправке. */
|
|
884
|
+
export async function maybeSendDigest(now = new Date()) {
|
|
885
|
+
try {
|
|
886
|
+
const settings = await loadSettings();
|
|
887
|
+
const config = settings.notifications;
|
|
888
|
+
if (!config?.enabled)
|
|
889
|
+
return false;
|
|
890
|
+
const digest = config.digest;
|
|
891
|
+
if (!digest?.enabled)
|
|
892
|
+
return false;
|
|
893
|
+
if (!isDigestDue(digest, now))
|
|
894
|
+
return false;
|
|
895
|
+
const result = await sendDigestNow({ now, updateLastSentAt: true });
|
|
896
|
+
if (result.success) {
|
|
897
|
+
console.log("[agent-steward] Дайджест уведомлений отправлен.");
|
|
898
|
+
return true;
|
|
899
|
+
}
|
|
900
|
+
console.error(`[agent-steward] Дайджест не отправлен: ${result.message}`);
|
|
901
|
+
return false;
|
|
902
|
+
}
|
|
903
|
+
catch (err) {
|
|
904
|
+
console.error(`[agent-steward] Ошибка дайджеста: ${err instanceof Error ? err.message : String(err)}`);
|
|
905
|
+
return false;
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
/**
|
|
909
|
+
* Отправляет тестовое сообщение в выбранный канал или во все включённые
|
|
910
|
+
* (кнопка «🧪 Тестовое уведомление»). В отличие от notifyTaskCompletion,
|
|
911
|
+
* результат возвращается пользователю: при тесте важна причина ошибки.
|
|
912
|
+
*/
|
|
913
|
+
export async function sendTestNotification(channel = "all") {
|
|
914
|
+
try {
|
|
915
|
+
const settings = await loadSettings();
|
|
916
|
+
const config = settings.notifications;
|
|
917
|
+
if (!config?.enabled) {
|
|
918
|
+
return {
|
|
919
|
+
success: false,
|
|
920
|
+
message: t("notify.error.testDisabled"),
|
|
921
|
+
};
|
|
922
|
+
}
|
|
923
|
+
const enabled = [];
|
|
924
|
+
if (config.webhook?.enabled && config.webhook.url.trim())
|
|
925
|
+
enabled.push("webhook");
|
|
926
|
+
if (config.telegram?.enabled)
|
|
927
|
+
enabled.push("telegram");
|
|
928
|
+
if (config.native?.enabled)
|
|
929
|
+
enabled.push("native");
|
|
930
|
+
if (enabled.length === 0) {
|
|
931
|
+
return {
|
|
932
|
+
success: false,
|
|
933
|
+
message: t("notify.error.testNoChannels"),
|
|
934
|
+
};
|
|
935
|
+
}
|
|
936
|
+
if (channel !== "all" && !enabled.includes(channel)) {
|
|
937
|
+
return {
|
|
938
|
+
success: false,
|
|
939
|
+
message: t("notify.error.testChannelOff", { channel }),
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
const results = await deliverDetailed(config, t("notify.test.body"), channel === "all" ? undefined : channel);
|
|
943
|
+
const sent = results.filter((item) => item.ok).map((item) => item.channel);
|
|
944
|
+
const failed = results.filter((item) => !item.ok);
|
|
945
|
+
const parts = [];
|
|
946
|
+
if (sent.length > 0) {
|
|
947
|
+
parts.push(t("notify.test.sent", { channels: sent.join(", ") }));
|
|
948
|
+
}
|
|
949
|
+
if (failed.length > 0) {
|
|
950
|
+
parts.push(t("notify.test.errors", {
|
|
951
|
+
errors: failed
|
|
952
|
+
.map((item) => `${item.channel} — ${item.error ?? t("notify.error.testUnknown")}`)
|
|
953
|
+
.join("; "),
|
|
954
|
+
}));
|
|
955
|
+
}
|
|
956
|
+
return {
|
|
957
|
+
success: failed.length === 0 && sent.length > 0,
|
|
958
|
+
message: parts.join(" ") || t("notify.error.testNotSent"),
|
|
959
|
+
};
|
|
960
|
+
}
|
|
961
|
+
catch (err) {
|
|
962
|
+
return {
|
|
963
|
+
success: false,
|
|
964
|
+
message: err instanceof Error ? err.message : String(err),
|
|
965
|
+
};
|
|
966
|
+
}
|
|
967
|
+
}
|