agent-steward 0.0.0-stage → 0.0.2
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 +376 -0
- package/CROSS_PLATFORM.md +149 -0
- package/LICENSE +21 -0
- package/README.md +314 -2
- package/ROADMAP-STRATEGY.md +147 -0
- package/ROADMAP.md +1069 -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 +20 -0
- package/dist/core/cron-to-schtasks.d.ts.map +1 -0
- package/dist/core/cron-to-schtasks.js +250 -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 +195 -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 +68 -0
- package/dist/core/one-shot.d.ts.map +1 -0
- package/dist/core/one-shot.js +139 -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 +1071 -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/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 +44 -0
- package/dist/core/scheduler/linux.d.ts.map +1 -0
- package/dist/core/scheduler/linux.js +225 -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 +40 -0
- package/dist/core/scheduler/mac.d.ts.map +1 -0
- package/dist/core/scheduler/mac.js +207 -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 +89 -0
- package/dist/core/scheduler/registry.d.ts +41 -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 +99 -0
- package/dist/core/scheduler/windows.d.ts.map +1 -0
- package/dist/core/scheduler/windows.js +596 -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/self-analysis.test.d.ts +2 -0
- package/dist/core/self-analysis.test.d.ts.map +1 -0
- package/dist/core/self-analysis.test.js +219 -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 +47 -0
- package/dist/db/index.d.ts.map +1 -0
- package/dist/db/index.js +120 -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/schema.d.ts +24 -0
- package/dist/db/schema.d.ts.map +1 -0
- package/dist/db/schema.js +170 -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/gui-experimental.cjs +1 -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 +5179 -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 +60 -0
- package/dist/profiles.d.ts.map +1 -0
- package/dist/profiles.js +227 -0
- package/dist/rpc.d.ts +3806 -0
- package/dist/rpc.d.ts.map +1 -0
- package/dist/rpc.js +1507 -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 +2413 -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 +628 -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 +96 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +130 -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 +457 -0
- package/docs/COMPATIBILITY.md +233 -0
- package/docs/CONCEPT.md +230 -0
- package/docs/CROSS_PLATFORM.ru.md +150 -0
- package/docs/CROSS_PLATFORM.zh.md +146 -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 +698 -0
- package/docs/FEATURES.zh.md +655 -0
- package/docs/LOCAL-AI.md +300 -0
- package/docs/MIGRATION.md +355 -0
- package/docs/README.ru.md +268 -0
- package/docs/README.zh.md +305 -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 +1 -0
- package/locales/en.json +780 -0
- package/locales/ru.json +780 -0
- package/locales/zh.json +780 -0
- package/package.json +149 -4
- 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 +288 -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 +189 -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 +1140 -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/index.ts +82 -0
- package/src/core/scheduler/linux.ts +257 -0
- package/src/core/scheduler/logs.ts +37 -0
- package/src/core/scheduler/mac.ts +270 -0
- package/src/core/scheduler/posix.ts +114 -0
- package/src/core/scheduler/registry.ts +99 -0
- package/src/core/scheduler/types.ts +90 -0
- package/src/core/scheduler/windows.ts +711 -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 +166 -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/schema.ts +188 -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 +6605 -0
- package/src/integrations.ts +297 -0
- package/src/notifications.ts +1346 -0
- package/src/profiles.ts +254 -0
- package/src/rpc.ts +1609 -0
- package/src/schtasks.ts +75 -0
- package/src/server.ts +2662 -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 +944 -0
- package/src/templates.ts +67 -0
- package/src/tui-v1.tsx +341 -0
- package/src/tui.tsx +329 -0
- package/src/types.ts +191 -0
- package/src/version.ts +27 -0
- package/src/workspaces.ts +487 -0
package/dist/settings.js
ADDED
|
@@ -0,0 +1,770 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { PLUGIN_DIR } from "./types.js";
|
|
5
|
+
import { DEFAULT_LOCALE, normalizeLocale, normalizeLocaleMode, SUPPORTED_LOCALES, messageIn, t } from "./i18n.js";
|
|
6
|
+
import { DEFAULT_PERMISSION_POLICY, normalizePolicy, } from "./core/permissions.js";
|
|
7
|
+
/** Дни shadow-периода по умолчанию. */
|
|
8
|
+
export const DEFAULT_SHADOW_DAYS = 14;
|
|
9
|
+
export const SETTINGS_FILE = path.join(PLUGIN_DIR, "settings.json");
|
|
10
|
+
export const DEFAULT_MAX_CONCURRENT = 1;
|
|
11
|
+
export const DEFAULT_WINTER_MODE = false;
|
|
12
|
+
export const DEFAULT_RETENTION_DAYS = 30;
|
|
13
|
+
export const DEFAULT_MAX_RECORDS = 5000;
|
|
14
|
+
/** Уведомления (Спринт 20): таймаут webhook, повторы и порог «зависшей» матрицы. */
|
|
15
|
+
export const DEFAULT_WEBHOOK_TIMEOUT_MS = 10000;
|
|
16
|
+
export const DEFAULT_WEBHOOK_RETRY_COUNT = 2;
|
|
17
|
+
export const DEFAULT_WEBHOOK_RETRY_DELAY_MS = 1000;
|
|
18
|
+
export const DEFAULT_STUCK_AFTER_MINUTES = 60;
|
|
19
|
+
/** Входящие хуки (Спринт 22): тело до 256 KiB, timestamp ±5 минут. */
|
|
20
|
+
export const DEFAULT_HOOK_MAX_BODY_BYTES = 256 * 1024;
|
|
21
|
+
export const DEFAULT_HOOK_TIMESTAMP_TOLERANCE_SECONDS = 300;
|
|
22
|
+
const MAX_HOOK_BODY_BYTES = 5 * 1024 * 1024;
|
|
23
|
+
const MAX_HOOK_CREDENTIAL_LENGTH = 512;
|
|
24
|
+
/** Аудит (Спринт 26): включён, 90 дней и не больше 10 000 записей. */
|
|
25
|
+
export const DEFAULT_AUDIT_RETENTION_DAYS = 90;
|
|
26
|
+
export const DEFAULT_AUDIT_MAX_RECORDS = 10000;
|
|
27
|
+
/** Значения аудита по умолчанию. */
|
|
28
|
+
export function defaultAuditSettings() {
|
|
29
|
+
return {
|
|
30
|
+
enabled: true,
|
|
31
|
+
retentionDays: DEFAULT_AUDIT_RETENTION_DAYS,
|
|
32
|
+
maxRecords: DEFAULT_AUDIT_MAX_RECORDS,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/** Политика прав по умолчанию: гибрид (без shell/question). */
|
|
36
|
+
export function defaultPermissionsSettings() {
|
|
37
|
+
return { defaultPolicy: DEFAULT_PERMISSION_POLICY };
|
|
38
|
+
}
|
|
39
|
+
/** Приводит настройки прав к безопасному виду. */
|
|
40
|
+
function normalizePermissionsSettings(value, fallback) {
|
|
41
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
42
|
+
return { ...fallback };
|
|
43
|
+
}
|
|
44
|
+
const raw = value;
|
|
45
|
+
return {
|
|
46
|
+
defaultPolicy: normalizePolicy(raw.defaultPolicy, fallback.defaultPolicy),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/** Приводит настройки аудита к безопасному виду. */
|
|
50
|
+
function normalizeAuditSettings(value, fallback) {
|
|
51
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
52
|
+
return { ...fallback };
|
|
53
|
+
}
|
|
54
|
+
const raw = value;
|
|
55
|
+
return {
|
|
56
|
+
enabled: typeof raw.enabled === "boolean" ? raw.enabled : fallback.enabled,
|
|
57
|
+
retentionDays: normalizeRetentionLimit(raw.retentionDays, fallback.retentionDays),
|
|
58
|
+
maxRecords: normalizeRetentionLimit(raw.maxRecords, fallback.maxRecords),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
/** Значения интеграций по умолчанию: хуки выключены, подпись обязательна. */
|
|
62
|
+
export function defaultIntegrations() {
|
|
63
|
+
return {
|
|
64
|
+
hooks: {
|
|
65
|
+
enabled: false,
|
|
66
|
+
token: "",
|
|
67
|
+
secret: "",
|
|
68
|
+
requireSignature: true,
|
|
69
|
+
maxBodyBytes: DEFAULT_HOOK_MAX_BODY_BYTES,
|
|
70
|
+
timestampToleranceSeconds: DEFAULT_HOOK_TIMESTAMP_TOLERANCE_SECONDS,
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
/** Генерирует криптостойкие учётные данные для входящего хука. */
|
|
75
|
+
export function generateHookCredentials() {
|
|
76
|
+
return {
|
|
77
|
+
token: crypto.randomBytes(24).toString("hex"),
|
|
78
|
+
secret: crypto.randomBytes(32).toString("hex"),
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
/** Ретеншн по умолчанию: 30 дней и не больше 5000 записей. */
|
|
82
|
+
export function defaultHistorySettings() {
|
|
83
|
+
return {
|
|
84
|
+
retentionDays: DEFAULT_RETENTION_DAYS,
|
|
85
|
+
maxRecords: DEFAULT_MAX_RECORDS,
|
|
86
|
+
lastCleanupAt: null,
|
|
87
|
+
lastCleanupDeleted: 0,
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
/** Приводит счётчик ретеншна к безопасному целому (>= 0). */
|
|
91
|
+
function normalizeRetentionLimit(value, fallback) {
|
|
92
|
+
const n = Number(value);
|
|
93
|
+
if (!Number.isFinite(n))
|
|
94
|
+
return fallback;
|
|
95
|
+
const int = Math.floor(n);
|
|
96
|
+
return int >= 0 ? int : fallback;
|
|
97
|
+
}
|
|
98
|
+
/** Приводит настройки ретеншна к безопасному виду. */
|
|
99
|
+
function normalizeHistorySettings(value, fallback) {
|
|
100
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
101
|
+
return { ...fallback };
|
|
102
|
+
}
|
|
103
|
+
const raw = value;
|
|
104
|
+
const lastCleanupAt = typeof raw.lastCleanupAt === "string" && raw.lastCleanupAt.trim()
|
|
105
|
+
? raw.lastCleanupAt.trim()
|
|
106
|
+
: null;
|
|
107
|
+
return {
|
|
108
|
+
retentionDays: normalizeRetentionLimit(raw.retentionDays, fallback.retentionDays),
|
|
109
|
+
maxRecords: normalizeRetentionLimit(raw.maxRecords, fallback.maxRecords),
|
|
110
|
+
lastCleanupAt,
|
|
111
|
+
lastCleanupDeleted: normalizeRetentionLimit(raw.lastCleanupDeleted, fallback.lastCleanupDeleted),
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
/** Значения уведомлений по умолчанию: всё выключено, только ошибки. */
|
|
115
|
+
export function defaultNotifications() {
|
|
116
|
+
return {
|
|
117
|
+
enabled: false,
|
|
118
|
+
onlyOnError: true,
|
|
119
|
+
webhook: {
|
|
120
|
+
enabled: false,
|
|
121
|
+
url: "",
|
|
122
|
+
timeoutMs: DEFAULT_WEBHOOK_TIMEOUT_MS,
|
|
123
|
+
retryCount: DEFAULT_WEBHOOK_RETRY_COUNT,
|
|
124
|
+
retryDelayMs: DEFAULT_WEBHOOK_RETRY_DELAY_MS,
|
|
125
|
+
},
|
|
126
|
+
templates: {
|
|
127
|
+
success: t("notify.task.success"),
|
|
128
|
+
error: t("notify.task.error"),
|
|
129
|
+
},
|
|
130
|
+
filters: { include: [], exclude: [] },
|
|
131
|
+
telegram: {
|
|
132
|
+
enabled: false,
|
|
133
|
+
botToken: "",
|
|
134
|
+
chatId: "",
|
|
135
|
+
parseMode: "HTML",
|
|
136
|
+
disableNotification: false,
|
|
137
|
+
messageThreadId: null,
|
|
138
|
+
includeDashboardLink: true,
|
|
139
|
+
apiBase: "https://api.telegram.org",
|
|
140
|
+
},
|
|
141
|
+
native: {
|
|
142
|
+
enabled: false,
|
|
143
|
+
sound: true,
|
|
144
|
+
},
|
|
145
|
+
quietHours: {
|
|
146
|
+
enabled: false,
|
|
147
|
+
from: "22:00",
|
|
148
|
+
to: "08:00",
|
|
149
|
+
},
|
|
150
|
+
dashboardUrl: "",
|
|
151
|
+
matrix: {
|
|
152
|
+
enabled: true,
|
|
153
|
+
onPartial: true,
|
|
154
|
+
onAllFailed: true,
|
|
155
|
+
stuckAfterMinutes: DEFAULT_STUCK_AFTER_MINUTES,
|
|
156
|
+
},
|
|
157
|
+
digest: {
|
|
158
|
+
enabled: false,
|
|
159
|
+
frequency: "daily",
|
|
160
|
+
time: "09:00",
|
|
161
|
+
lastSentAt: null,
|
|
162
|
+
},
|
|
163
|
+
triage: {
|
|
164
|
+
mode: "off",
|
|
165
|
+
baseUrl: "http://127.0.0.1:11434",
|
|
166
|
+
model: "qwen3:4b",
|
|
167
|
+
timeoutMs: 60000,
|
|
168
|
+
fallback: "rules",
|
|
169
|
+
confidenceThreshold: 0.6,
|
|
170
|
+
shadow: {
|
|
171
|
+
enabled: true,
|
|
172
|
+
days: DEFAULT_SHADOW_DAYS,
|
|
173
|
+
startedAt: null,
|
|
174
|
+
},
|
|
175
|
+
},
|
|
176
|
+
dedup: {
|
|
177
|
+
enabled: false,
|
|
178
|
+
windowMinutes: 60,
|
|
179
|
+
suppressDuplicates: false,
|
|
180
|
+
importantStatuses: ["error", "timeout"],
|
|
181
|
+
maxCount: 999,
|
|
182
|
+
},
|
|
183
|
+
embedding: {
|
|
184
|
+
enabled: false,
|
|
185
|
+
suppressDuplicates: false,
|
|
186
|
+
windowMinutes: 60,
|
|
187
|
+
threshold: 0.85,
|
|
188
|
+
maxVectors: 10000,
|
|
189
|
+
},
|
|
190
|
+
summary: {
|
|
191
|
+
enabled: false,
|
|
192
|
+
maxLines: 3,
|
|
193
|
+
maxCharsPerLine: 120,
|
|
194
|
+
timeoutMs: 8000,
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
/** Приводит значение лимита к безопасному целому (>= 0). */
|
|
199
|
+
function normalizeMaxConcurrent(value, fallback) {
|
|
200
|
+
const n = Number(value);
|
|
201
|
+
if (!Number.isFinite(n))
|
|
202
|
+
return fallback;
|
|
203
|
+
const int = Math.floor(n);
|
|
204
|
+
return int >= 0 ? int : fallback;
|
|
205
|
+
}
|
|
206
|
+
/** Приводит значение зимнего режима к boolean. */
|
|
207
|
+
function normalizeWinterMode(value, fallback) {
|
|
208
|
+
if (typeof value === "boolean")
|
|
209
|
+
return value;
|
|
210
|
+
if (value === "true")
|
|
211
|
+
return true;
|
|
212
|
+
if (value === "false")
|
|
213
|
+
return false;
|
|
214
|
+
return fallback;
|
|
215
|
+
}
|
|
216
|
+
/** Приводит значение к конечному целому в диапазоне [min, max]. */
|
|
217
|
+
function normalizeIntInRange(value, fallback, min, max) {
|
|
218
|
+
const n = Number(value);
|
|
219
|
+
if (!Number.isFinite(n))
|
|
220
|
+
return fallback;
|
|
221
|
+
return Math.min(max, Math.max(min, Math.floor(n)));
|
|
222
|
+
}
|
|
223
|
+
/** Приводит число с плавающей точкой к безопасному диапазону. */
|
|
224
|
+
function normalizeFloatInRange(value, fallback, min, max) {
|
|
225
|
+
const n = Number(value);
|
|
226
|
+
if (!Number.isFinite(n))
|
|
227
|
+
return fallback;
|
|
228
|
+
return Math.min(max, Math.max(min, n));
|
|
229
|
+
}
|
|
230
|
+
/** Приводит время HH:MM к безопасному виду. */
|
|
231
|
+
function normalizeDailyTime(value, fallback) {
|
|
232
|
+
if (typeof value === "string" && /^([01]\d|2[0-3]):[0-5]\d$/.test(value.trim())) {
|
|
233
|
+
return value.trim();
|
|
234
|
+
}
|
|
235
|
+
return fallback;
|
|
236
|
+
}
|
|
237
|
+
/** Список имён задач: массив строк, обрезанных и без пустых значений. */
|
|
238
|
+
function normalizeNameList(value, fallback) {
|
|
239
|
+
if (!Array.isArray(value))
|
|
240
|
+
return [...fallback];
|
|
241
|
+
return value
|
|
242
|
+
.filter((item) => typeof item === "string")
|
|
243
|
+
.map((item) => item.trim())
|
|
244
|
+
.filter((item) => item.length > 0);
|
|
245
|
+
}
|
|
246
|
+
function asRecord(value) {
|
|
247
|
+
return value && typeof value === "object" && !Array.isArray(value)
|
|
248
|
+
? value
|
|
249
|
+
: undefined;
|
|
250
|
+
}
|
|
251
|
+
/** Приводит parse_mode Telegram к допустимому значению. */
|
|
252
|
+
function normalizeTelegramParseMode(value, fallback) {
|
|
253
|
+
return value === "" || value === "HTML" || value === "Markdown" || value === "MarkdownV2"
|
|
254
|
+
? value
|
|
255
|
+
: fallback;
|
|
256
|
+
}
|
|
257
|
+
/** Проверяет http(s)-базу API; иначе возвращает fallback. */
|
|
258
|
+
function normalizeHttpBase(value, fallback) {
|
|
259
|
+
if (typeof value !== "string")
|
|
260
|
+
return fallback;
|
|
261
|
+
const trimmed = value.trim().replace(/\/+$/, "");
|
|
262
|
+
if (!trimmed)
|
|
263
|
+
return fallback;
|
|
264
|
+
try {
|
|
265
|
+
const parsed = new URL(trimmed);
|
|
266
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
|
|
267
|
+
return fallback;
|
|
268
|
+
return trimmed;
|
|
269
|
+
}
|
|
270
|
+
catch {
|
|
271
|
+
return fallback;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Встроенный шаблон (ru или en) заменяется текущим переводом; пользовательский
|
|
276
|
+
* текст остаётся как есть. Иначе сохранённые при первой установке дефолты
|
|
277
|
+
* навсегда застывали бы на языке установки.
|
|
278
|
+
*/
|
|
279
|
+
function localizedTemplate(value, key, fallback) {
|
|
280
|
+
const raw = typeof value === "string" && value.trim() ? value : fallback;
|
|
281
|
+
const builtin = SUPPORTED_LOCALES.some((locale) => messageIn(locale, key) === raw);
|
|
282
|
+
return builtin ? t(key) : raw;
|
|
283
|
+
}
|
|
284
|
+
/** Приводит режим триажа к допустимому значению. */
|
|
285
|
+
function normalizeTriageMode(value, fallback) {
|
|
286
|
+
return value === "off" || value === "rules" || value === "llm" || value === "auto"
|
|
287
|
+
? value
|
|
288
|
+
: fallback;
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Приводит fallback триажа к допустимому значению.
|
|
292
|
+
*
|
|
293
|
+
* Старое имя `skip` означает «пропустить правила и отправить уведомление»,
|
|
294
|
+
* поэтому нормализуется в однозначное `notify`.
|
|
295
|
+
*/
|
|
296
|
+
function normalizeTriageFallback(value, fallback) {
|
|
297
|
+
if (value === "rules" || value === "notify")
|
|
298
|
+
return value;
|
|
299
|
+
if (value === "skip")
|
|
300
|
+
return "notify";
|
|
301
|
+
return fallback === "skip" ? "notify" : fallback;
|
|
302
|
+
}
|
|
303
|
+
/** Приводит порог уверенности к диапазону 0..1. */
|
|
304
|
+
function normalizeConfidence(value, fallback) {
|
|
305
|
+
const n = Number(value);
|
|
306
|
+
if (!Number.isFinite(n))
|
|
307
|
+
return fallback;
|
|
308
|
+
return Math.min(1, Math.max(0, n));
|
|
309
|
+
}
|
|
310
|
+
const TRIAGE_RULE_FIELDS = ["status", "task", "error", "cost"];
|
|
311
|
+
const TRIAGE_RULE_OPERATORS = [
|
|
312
|
+
"equals",
|
|
313
|
+
"contains",
|
|
314
|
+
"regex",
|
|
315
|
+
"gt",
|
|
316
|
+
"lt",
|
|
317
|
+
"gte",
|
|
318
|
+
"lte",
|
|
319
|
+
];
|
|
320
|
+
const TRIAGE_RULE_CATEGORIES = [
|
|
321
|
+
"quality",
|
|
322
|
+
"timeout",
|
|
323
|
+
"permission",
|
|
324
|
+
"network",
|
|
325
|
+
"unknown",
|
|
326
|
+
];
|
|
327
|
+
const TRIAGE_RULE_SEVERITIES = ["low", "medium", "high"];
|
|
328
|
+
/** Допустимые операторы для поля: текст сравнивается строками, cost — числами. */
|
|
329
|
+
function ruleOperatorAllowed(field, operator) {
|
|
330
|
+
return field === "cost"
|
|
331
|
+
? operator !== "contains" && operator !== "regex"
|
|
332
|
+
: operator === "equals" || operator === "contains" || operator === "regex";
|
|
333
|
+
}
|
|
334
|
+
/** Нормализует одно правило; невалидное возвращает null (правило отбрасывается). */
|
|
335
|
+
function normalizeTriageRule(value) {
|
|
336
|
+
const raw = asRecord(value);
|
|
337
|
+
if (!raw)
|
|
338
|
+
return null;
|
|
339
|
+
const field = TRIAGE_RULE_FIELDS.includes(raw.field)
|
|
340
|
+
? raw.field
|
|
341
|
+
: null;
|
|
342
|
+
const operator = TRIAGE_RULE_OPERATORS.includes(raw.operator)
|
|
343
|
+
? raw.operator
|
|
344
|
+
: null;
|
|
345
|
+
if (!field || !operator || !ruleOperatorAllowed(field, operator))
|
|
346
|
+
return null;
|
|
347
|
+
let ruleValue;
|
|
348
|
+
if (field === "cost") {
|
|
349
|
+
const n = Number(raw.value);
|
|
350
|
+
if (!Number.isFinite(n) || n < 0)
|
|
351
|
+
return null;
|
|
352
|
+
ruleValue = n;
|
|
353
|
+
}
|
|
354
|
+
else {
|
|
355
|
+
if (typeof raw.value !== "string" || !raw.value.trim())
|
|
356
|
+
return null;
|
|
357
|
+
ruleValue = raw.value.trim().slice(0, 500);
|
|
358
|
+
}
|
|
359
|
+
if (operator === "regex") {
|
|
360
|
+
try {
|
|
361
|
+
new RegExp(String(ruleValue), "iu");
|
|
362
|
+
}
|
|
363
|
+
catch {
|
|
364
|
+
return null;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
const rule = { field, operator, value: ruleValue };
|
|
368
|
+
if (typeof raw.id === "string" && raw.id.trim())
|
|
369
|
+
rule.id = raw.id.trim().slice(0, 64);
|
|
370
|
+
if (TRIAGE_RULE_CATEGORIES.includes(raw.category)) {
|
|
371
|
+
rule.category = raw.category;
|
|
372
|
+
}
|
|
373
|
+
if (TRIAGE_RULE_SEVERITIES.includes(raw.severity)) {
|
|
374
|
+
rule.severity = raw.severity;
|
|
375
|
+
}
|
|
376
|
+
if (raw.confidence !== undefined)
|
|
377
|
+
rule.confidence = normalizeConfidence(raw.confidence, 0.8);
|
|
378
|
+
if (raw.action === "notify" || raw.action === "skip")
|
|
379
|
+
rule.action = raw.action;
|
|
380
|
+
if (typeof raw.reason === "string" && raw.reason.trim()) {
|
|
381
|
+
rule.reason = raw.reason.trim().slice(0, 300);
|
|
382
|
+
}
|
|
383
|
+
const priority = Number(raw.priority);
|
|
384
|
+
rule.priority = Number.isFinite(priority)
|
|
385
|
+
? Math.min(10000, Math.max(-10000, Math.trunc(priority)))
|
|
386
|
+
: 0;
|
|
387
|
+
return rule;
|
|
388
|
+
}
|
|
389
|
+
/** Нормализует массив правил; undefined сохраняет встроенный набор. */
|
|
390
|
+
function normalizeTriageRules(value, fallback) {
|
|
391
|
+
if (value === undefined)
|
|
392
|
+
return fallback?.map((rule) => ({ ...rule }));
|
|
393
|
+
if (!Array.isArray(value))
|
|
394
|
+
return fallback?.map((rule) => ({ ...rule }));
|
|
395
|
+
return value
|
|
396
|
+
.slice(0, 200)
|
|
397
|
+
.map(normalizeTriageRule)
|
|
398
|
+
.filter((rule) => rule !== null);
|
|
399
|
+
}
|
|
400
|
+
/** Нормализует настройки shadow-режима триажа. */
|
|
401
|
+
function normalizeTriageShadow(value, fallback) {
|
|
402
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
403
|
+
return { ...fallback };
|
|
404
|
+
}
|
|
405
|
+
const raw = value;
|
|
406
|
+
return {
|
|
407
|
+
enabled: typeof raw.enabled === "boolean" ? raw.enabled : fallback.enabled,
|
|
408
|
+
days: normalizeIntInRange(raw.days, fallback.days, 1, 365),
|
|
409
|
+
startedAt: typeof raw.startedAt === "string" && raw.startedAt.trim()
|
|
410
|
+
? raw.startedAt.trim()
|
|
411
|
+
: null,
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
function normalizeDedupSettings(value, fallback) {
|
|
415
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
416
|
+
return { ...fallback };
|
|
417
|
+
}
|
|
418
|
+
const raw = value;
|
|
419
|
+
return {
|
|
420
|
+
enabled: typeof raw.enabled === "boolean" ? raw.enabled : fallback.enabled,
|
|
421
|
+
windowMinutes: normalizeIntInRange(raw.windowMinutes, fallback.windowMinutes, 1, 10080),
|
|
422
|
+
suppressDuplicates: typeof raw.suppressDuplicates === "boolean"
|
|
423
|
+
? raw.suppressDuplicates
|
|
424
|
+
: fallback.suppressDuplicates,
|
|
425
|
+
importantStatuses: Array.isArray(raw.importantStatuses) &&
|
|
426
|
+
raw.importantStatuses.every((s) => typeof s === "string")
|
|
427
|
+
? raw.importantStatuses.map((s) => String(s)).slice(0, 32)
|
|
428
|
+
: fallback.importantStatuses,
|
|
429
|
+
maxCount: normalizeIntInRange(raw.maxCount, fallback.maxCount, 1, 10000),
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
/** Нормализация настроек семантического дедупа (Спринт 31.1). */
|
|
433
|
+
function normalizeEmbeddingSettings(value, fallback) {
|
|
434
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
435
|
+
return { ...fallback };
|
|
436
|
+
}
|
|
437
|
+
const raw = value;
|
|
438
|
+
return {
|
|
439
|
+
enabled: typeof raw.enabled === "boolean" ? raw.enabled : fallback.enabled,
|
|
440
|
+
suppressDuplicates: typeof raw.suppressDuplicates === "boolean"
|
|
441
|
+
? raw.suppressDuplicates
|
|
442
|
+
: fallback.suppressDuplicates,
|
|
443
|
+
windowMinutes: normalizeIntInRange(raw.windowMinutes, fallback.windowMinutes, 1, 10080),
|
|
444
|
+
threshold: normalizeFloatInRange(raw.threshold, fallback.threshold, 0, 1),
|
|
445
|
+
maxVectors: normalizeIntInRange(raw.maxVectors, fallback.maxVectors, 100, 100000),
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
/** Нормализует настройки саммари уведомлений (Спринт 31.3). */
|
|
449
|
+
function normalizeSummarySettings(value, fallback) {
|
|
450
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
451
|
+
return { ...fallback };
|
|
452
|
+
}
|
|
453
|
+
const raw = value;
|
|
454
|
+
return {
|
|
455
|
+
enabled: typeof raw.enabled === "boolean" ? raw.enabled : fallback.enabled,
|
|
456
|
+
maxLines: normalizeIntInRange(raw.maxLines, fallback.maxLines, 1, 3),
|
|
457
|
+
maxCharsPerLine: normalizeIntInRange(raw.maxCharsPerLine, fallback.maxCharsPerLine, 20, 500),
|
|
458
|
+
timeoutMs: normalizeIntInRange(raw.timeoutMs, fallback.timeoutMs, 1000, 120000),
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
/** Текущий shadow-период ещё активен? (ничего не меняет, только читает). */
|
|
462
|
+
export function isShadowActive(shadow) {
|
|
463
|
+
if (!shadow || !shadow.enabled || !shadow.startedAt)
|
|
464
|
+
return false;
|
|
465
|
+
const started = new Date(shadow.startedAt).getTime();
|
|
466
|
+
if (!Number.isFinite(started))
|
|
467
|
+
return false;
|
|
468
|
+
const now = Date.now();
|
|
469
|
+
const days = Number.isFinite(shadow.days) && shadow.days > 0 ? shadow.days : DEFAULT_SHADOW_DAYS;
|
|
470
|
+
return now - started < days * 24 * 60 * 60 * 1000;
|
|
471
|
+
}
|
|
472
|
+
/** Начать shadow-период, если ещё не Started. Возвращает нормализованные настройки shadow. */
|
|
473
|
+
export function startShadow(shadow) {
|
|
474
|
+
const nowIso = new Date().toISOString();
|
|
475
|
+
if (!shadow) {
|
|
476
|
+
return { enabled: true, days: DEFAULT_SHADOW_DAYS, startedAt: nowIso };
|
|
477
|
+
}
|
|
478
|
+
if (!shadow.startedAt) {
|
|
479
|
+
return { ...shadow, startedAt: nowIso };
|
|
480
|
+
}
|
|
481
|
+
return { ...shadow };
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* Настройки shadow после сохранения: включённый режим без даты старта
|
|
485
|
+
* получает текущий момент, выключенный — сбрасывает дату.
|
|
486
|
+
*/
|
|
487
|
+
export function settleShadowOnSave(shadow) {
|
|
488
|
+
if (!shadow)
|
|
489
|
+
return startShadow(undefined);
|
|
490
|
+
if (!shadow.enabled)
|
|
491
|
+
return { ...shadow, startedAt: null };
|
|
492
|
+
return startShadow(shadow);
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* Приводит настройки триажа к безопасному виду.
|
|
496
|
+
*
|
|
497
|
+
* Экспортируется, чтобы RPC-сравнение «до/после» валидировало пользовательский
|
|
498
|
+
* ввод той же схемой, что и сохранённые настройки.
|
|
499
|
+
*/
|
|
500
|
+
export function normalizeTriageSettings(value, fallback) {
|
|
501
|
+
const fallbackShadow = fallback.shadow ?? defaultNotifications().triage.shadow;
|
|
502
|
+
const raw = asRecord(value);
|
|
503
|
+
const rules = normalizeTriageRules(raw?.rules, fallback.rules);
|
|
504
|
+
return {
|
|
505
|
+
mode: normalizeTriageMode(raw?.mode, fallback.mode),
|
|
506
|
+
baseUrl: normalizeHttpBase(raw?.baseUrl, fallback.baseUrl),
|
|
507
|
+
model: typeof raw?.model === "string" && raw.model.trim()
|
|
508
|
+
? raw.model.trim().slice(0, 200)
|
|
509
|
+
: fallback.model,
|
|
510
|
+
timeoutMs: normalizeIntInRange(raw?.timeoutMs, fallback.timeoutMs, 1000, 120000),
|
|
511
|
+
fallback: normalizeTriageFallback(raw?.fallback, fallback.fallback),
|
|
512
|
+
confidenceThreshold: normalizeConfidence(raw?.confidenceThreshold, fallback.confidenceThreshold),
|
|
513
|
+
...(rules !== undefined ? { rules } : {}),
|
|
514
|
+
shadow: normalizeTriageShadow(raw?.shadow, fallbackShadow),
|
|
515
|
+
};
|
|
516
|
+
}
|
|
517
|
+
/** Приводит настройки уведомлений к безопасному виду. */
|
|
518
|
+
function normalizeNotifications(value, fallback) {
|
|
519
|
+
const fallbackWebhook = fallback.webhook ?? defaultNotifications().webhook;
|
|
520
|
+
const fallbackTemplates = fallback.templates ?? defaultNotifications().templates;
|
|
521
|
+
const fallbackFilters = fallback.filters ?? { include: [], exclude: [] };
|
|
522
|
+
const fallbackMatrix = fallback.matrix ?? defaultNotifications().matrix;
|
|
523
|
+
const fallbackDigest = fallback.digest ?? defaultNotifications().digest;
|
|
524
|
+
const fallbackTelegram = fallback.telegram ?? defaultNotifications().telegram;
|
|
525
|
+
const fallbackNative = fallback.native ?? defaultNotifications().native;
|
|
526
|
+
const fallbackQuiet = fallback.quietHours ?? defaultNotifications().quietHours;
|
|
527
|
+
const fallbackTriage = fallback.triage ?? defaultNotifications().triage;
|
|
528
|
+
const fallbackShadow = fallbackTriage.shadow ?? defaultNotifications().triage.shadow;
|
|
529
|
+
const raw = asRecord(value);
|
|
530
|
+
if (!raw) {
|
|
531
|
+
return {
|
|
532
|
+
...fallback,
|
|
533
|
+
webhook: { ...fallbackWebhook },
|
|
534
|
+
templates: { ...fallbackTemplates },
|
|
535
|
+
filters: {
|
|
536
|
+
include: [...fallbackFilters.include],
|
|
537
|
+
exclude: [...fallbackFilters.exclude],
|
|
538
|
+
},
|
|
539
|
+
matrix: { ...fallbackMatrix },
|
|
540
|
+
digest: { ...fallbackDigest },
|
|
541
|
+
telegram: { ...fallbackTelegram },
|
|
542
|
+
native: { ...fallbackNative },
|
|
543
|
+
quietHours: { ...fallbackQuiet },
|
|
544
|
+
triage: {
|
|
545
|
+
...fallbackTriage,
|
|
546
|
+
rules: fallbackTriage.rules?.map((rule) => ({ ...rule })),
|
|
547
|
+
shadow: { ...fallbackShadow },
|
|
548
|
+
},
|
|
549
|
+
dashboardUrl: fallback.dashboardUrl ?? "",
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
const rawWebhook = asRecord(raw.webhook);
|
|
553
|
+
const rawTemplates = asRecord(raw.templates);
|
|
554
|
+
const rawFilters = asRecord(raw.filters);
|
|
555
|
+
const rawMatrix = asRecord(raw.matrix);
|
|
556
|
+
const rawDigest = asRecord(raw.digest);
|
|
557
|
+
const rawTelegram = asRecord(raw.telegram);
|
|
558
|
+
const rawNative = asRecord(raw.native);
|
|
559
|
+
const rawQuiet = asRecord(raw.quietHours);
|
|
560
|
+
const rawTriage = asRecord(raw.triage);
|
|
561
|
+
const frequency = rawDigest?.frequency === "weekly" || rawDigest?.frequency === "daily"
|
|
562
|
+
? rawDigest.frequency
|
|
563
|
+
: fallbackDigest.frequency;
|
|
564
|
+
const lastSentAt = typeof rawDigest?.lastSentAt === "string" && rawDigest.lastSentAt.trim()
|
|
565
|
+
? rawDigest.lastSentAt.trim()
|
|
566
|
+
: null;
|
|
567
|
+
return {
|
|
568
|
+
enabled: typeof raw.enabled === "boolean" ? raw.enabled : fallback.enabled,
|
|
569
|
+
onlyOnError: typeof raw.onlyOnError === "boolean" ? raw.onlyOnError : fallback.onlyOnError,
|
|
570
|
+
webhook: {
|
|
571
|
+
enabled: typeof rawWebhook?.enabled === "boolean"
|
|
572
|
+
? rawWebhook.enabled
|
|
573
|
+
: fallbackWebhook.enabled,
|
|
574
|
+
url: typeof rawWebhook?.url === "string"
|
|
575
|
+
? rawWebhook.url.trim()
|
|
576
|
+
: fallbackWebhook.url,
|
|
577
|
+
timeoutMs: normalizeIntInRange(rawWebhook?.timeoutMs, fallbackWebhook.timeoutMs, 1000, 120000),
|
|
578
|
+
retryCount: normalizeIntInRange(rawWebhook?.retryCount, fallbackWebhook.retryCount, 0, 5),
|
|
579
|
+
retryDelayMs: normalizeIntInRange(rawWebhook?.retryDelayMs, fallbackWebhook.retryDelayMs, 100, 60000),
|
|
580
|
+
},
|
|
581
|
+
templates: {
|
|
582
|
+
success: localizedTemplate(rawTemplates?.success, "notify.task.success", fallbackTemplates.success),
|
|
583
|
+
error: localizedTemplate(rawTemplates?.error, "notify.task.error", fallbackTemplates.error),
|
|
584
|
+
},
|
|
585
|
+
filters: {
|
|
586
|
+
include: normalizeNameList(rawFilters?.include, fallbackFilters.include),
|
|
587
|
+
exclude: normalizeNameList(rawFilters?.exclude, fallbackFilters.exclude),
|
|
588
|
+
},
|
|
589
|
+
telegram: {
|
|
590
|
+
enabled: typeof rawTelegram?.enabled === "boolean"
|
|
591
|
+
? rawTelegram.enabled
|
|
592
|
+
: fallbackTelegram.enabled,
|
|
593
|
+
botToken: typeof rawTelegram?.botToken === "string"
|
|
594
|
+
? rawTelegram.botToken.trim().slice(0, 512)
|
|
595
|
+
: fallbackTelegram.botToken,
|
|
596
|
+
chatId: typeof rawTelegram?.chatId === "string"
|
|
597
|
+
? rawTelegram.chatId.trim().slice(0, 128)
|
|
598
|
+
: fallbackTelegram.chatId,
|
|
599
|
+
parseMode: normalizeTelegramParseMode(rawTelegram?.parseMode, fallbackTelegram.parseMode),
|
|
600
|
+
disableNotification: typeof rawTelegram?.disableNotification === "boolean"
|
|
601
|
+
? rawTelegram.disableNotification
|
|
602
|
+
: fallbackTelegram.disableNotification,
|
|
603
|
+
messageThreadId: rawTelegram?.messageThreadId === null
|
|
604
|
+
? null
|
|
605
|
+
: Number.isFinite(Number(rawTelegram?.messageThreadId))
|
|
606
|
+
? Math.max(0, Math.floor(Number(rawTelegram?.messageThreadId)))
|
|
607
|
+
: fallbackTelegram.messageThreadId,
|
|
608
|
+
includeDashboardLink: typeof rawTelegram?.includeDashboardLink === "boolean"
|
|
609
|
+
? rawTelegram.includeDashboardLink
|
|
610
|
+
: fallbackTelegram.includeDashboardLink,
|
|
611
|
+
apiBase: normalizeHttpBase(rawTelegram?.apiBase, fallbackTelegram.apiBase),
|
|
612
|
+
},
|
|
613
|
+
native: {
|
|
614
|
+
enabled: typeof rawNative?.enabled === "boolean"
|
|
615
|
+
? rawNative.enabled
|
|
616
|
+
: fallbackNative.enabled,
|
|
617
|
+
sound: typeof rawNative?.sound === "boolean"
|
|
618
|
+
? rawNative.sound
|
|
619
|
+
: fallbackNative.sound,
|
|
620
|
+
},
|
|
621
|
+
quietHours: {
|
|
622
|
+
enabled: typeof rawQuiet?.enabled === "boolean"
|
|
623
|
+
? rawQuiet.enabled
|
|
624
|
+
: fallbackQuiet.enabled,
|
|
625
|
+
from: normalizeDailyTime(rawQuiet?.from, fallbackQuiet.from),
|
|
626
|
+
to: normalizeDailyTime(rawQuiet?.to, fallbackQuiet.to),
|
|
627
|
+
},
|
|
628
|
+
dashboardUrl: typeof raw.dashboardUrl === "string"
|
|
629
|
+
? raw.dashboardUrl.trim().slice(0, 500)
|
|
630
|
+
: (fallback.dashboardUrl ?? ""),
|
|
631
|
+
matrix: {
|
|
632
|
+
enabled: typeof rawMatrix?.enabled === "boolean"
|
|
633
|
+
? rawMatrix.enabled
|
|
634
|
+
: fallbackMatrix.enabled,
|
|
635
|
+
onPartial: typeof rawMatrix?.onPartial === "boolean"
|
|
636
|
+
? rawMatrix.onPartial
|
|
637
|
+
: fallbackMatrix.onPartial,
|
|
638
|
+
onAllFailed: typeof rawMatrix?.onAllFailed === "boolean"
|
|
639
|
+
? rawMatrix.onAllFailed
|
|
640
|
+
: fallbackMatrix.onAllFailed,
|
|
641
|
+
stuckAfterMinutes: normalizeIntInRange(rawMatrix?.stuckAfterMinutes, fallbackMatrix.stuckAfterMinutes, 0, 10080),
|
|
642
|
+
},
|
|
643
|
+
digest: {
|
|
644
|
+
enabled: typeof rawDigest?.enabled === "boolean"
|
|
645
|
+
? rawDigest.enabled
|
|
646
|
+
: fallbackDigest.enabled,
|
|
647
|
+
frequency,
|
|
648
|
+
time: normalizeDailyTime(rawDigest?.time, fallbackDigest.time),
|
|
649
|
+
lastSentAt,
|
|
650
|
+
},
|
|
651
|
+
triage: normalizeTriageSettings(rawTriage, fallbackTriage),
|
|
652
|
+
dedup: normalizeDedupSettings(raw.dedup, fallback.dedup ?? defaultNotifications().dedup),
|
|
653
|
+
embedding: normalizeEmbeddingSettings(raw.embedding, fallback.embedding ?? defaultNotifications().embedding),
|
|
654
|
+
summary: normalizeSummarySettings(raw.summary, fallback.summary ?? defaultNotifications().summary),
|
|
655
|
+
};
|
|
656
|
+
}
|
|
657
|
+
/** Приводит настройки интеграций к безопасному виду. */
|
|
658
|
+
function normalizeIntegrations(value, fallback) {
|
|
659
|
+
const fallbackHooks = fallback.hooks ?? defaultIntegrations().hooks;
|
|
660
|
+
const raw = asRecord(value);
|
|
661
|
+
const rawHooks = asRecord(raw?.hooks);
|
|
662
|
+
const readCredential = (input, previous) => {
|
|
663
|
+
if (typeof input !== "string")
|
|
664
|
+
return previous;
|
|
665
|
+
return input.trim().slice(0, MAX_HOOK_CREDENTIAL_LENGTH);
|
|
666
|
+
};
|
|
667
|
+
return {
|
|
668
|
+
hooks: {
|
|
669
|
+
enabled: typeof rawHooks?.enabled === "boolean"
|
|
670
|
+
? rawHooks.enabled
|
|
671
|
+
: fallbackHooks.enabled,
|
|
672
|
+
token: readCredential(rawHooks?.token, fallbackHooks.token),
|
|
673
|
+
secret: readCredential(rawHooks?.secret, fallbackHooks.secret),
|
|
674
|
+
requireSignature: typeof rawHooks?.requireSignature === "boolean"
|
|
675
|
+
? rawHooks.requireSignature
|
|
676
|
+
: fallbackHooks.requireSignature,
|
|
677
|
+
maxBodyBytes: normalizeIntInRange(rawHooks?.maxBodyBytes, fallbackHooks.maxBodyBytes, 1024, MAX_HOOK_BODY_BYTES),
|
|
678
|
+
timestampToleranceSeconds: normalizeIntInRange(rawHooks?.timestampToleranceSeconds, fallbackHooks.timestampToleranceSeconds, 0, 86400),
|
|
679
|
+
},
|
|
680
|
+
};
|
|
681
|
+
}
|
|
682
|
+
/** Читает настройки. Битый/отсутствующий файл — значения по умолчанию. */
|
|
683
|
+
export async function loadSettings() {
|
|
684
|
+
const fallbackNotifications = defaultNotifications();
|
|
685
|
+
const fallbackHistory = defaultHistorySettings();
|
|
686
|
+
const fallbackIntegrations = defaultIntegrations();
|
|
687
|
+
const fallbackAudit = defaultAuditSettings();
|
|
688
|
+
const fallbackPermissions = defaultPermissionsSettings();
|
|
689
|
+
try {
|
|
690
|
+
const raw = await fs.readFile(SETTINGS_FILE, "utf8");
|
|
691
|
+
const parsed = JSON.parse(raw);
|
|
692
|
+
return {
|
|
693
|
+
maxConcurrent: normalizeMaxConcurrent(parsed?.maxConcurrent, DEFAULT_MAX_CONCURRENT),
|
|
694
|
+
locale: normalizeLocaleMode(parsed?.locale, DEFAULT_LOCALE),
|
|
695
|
+
uiLocale: normalizeLocale(parsed?.uiLocale, DEFAULT_LOCALE),
|
|
696
|
+
winterMode: normalizeWinterMode(parsed?.winterMode, DEFAULT_WINTER_MODE),
|
|
697
|
+
notifications: normalizeNotifications(parsed?.notifications, fallbackNotifications),
|
|
698
|
+
history: normalizeHistorySettings(parsed?.history, fallbackHistory),
|
|
699
|
+
integrations: normalizeIntegrations(parsed?.integrations, fallbackIntegrations),
|
|
700
|
+
audit: normalizeAuditSettings(parsed?.audit, fallbackAudit),
|
|
701
|
+
permissions: normalizePermissionsSettings(parsed?.permissions, fallbackPermissions),
|
|
702
|
+
};
|
|
703
|
+
}
|
|
704
|
+
catch {
|
|
705
|
+
return {
|
|
706
|
+
maxConcurrent: DEFAULT_MAX_CONCURRENT,
|
|
707
|
+
locale: DEFAULT_LOCALE,
|
|
708
|
+
uiLocale: DEFAULT_LOCALE,
|
|
709
|
+
winterMode: DEFAULT_WINTER_MODE,
|
|
710
|
+
notifications: fallbackNotifications,
|
|
711
|
+
history: fallbackHistory,
|
|
712
|
+
integrations: fallbackIntegrations,
|
|
713
|
+
audit: fallbackAudit,
|
|
714
|
+
permissions: fallbackPermissions,
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
/** Сохраняет настройки (частичное обновление поверх текущих). */
|
|
719
|
+
export async function saveSettings(patch) {
|
|
720
|
+
const current = await loadSettings();
|
|
721
|
+
const next = {
|
|
722
|
+
maxConcurrent: patch.maxConcurrent !== undefined
|
|
723
|
+
? normalizeMaxConcurrent(patch.maxConcurrent, current.maxConcurrent)
|
|
724
|
+
: current.maxConcurrent,
|
|
725
|
+
locale: patch.locale !== undefined
|
|
726
|
+
? normalizeLocaleMode(patch.locale, current.locale)
|
|
727
|
+
: current.locale,
|
|
728
|
+
uiLocale: patch.uiLocale !== undefined
|
|
729
|
+
? normalizeLocale(patch.uiLocale, current.uiLocale)
|
|
730
|
+
: current.uiLocale,
|
|
731
|
+
winterMode: patch.winterMode !== undefined
|
|
732
|
+
? normalizeWinterMode(patch.winterMode, current.winterMode)
|
|
733
|
+
: current.winterMode,
|
|
734
|
+
notifications: patch.notifications !== undefined
|
|
735
|
+
? normalizeNotifications(patch.notifications, current.notifications)
|
|
736
|
+
: current.notifications,
|
|
737
|
+
history: patch.history !== undefined
|
|
738
|
+
? normalizeHistorySettings(patch.history, current.history)
|
|
739
|
+
: current.history,
|
|
740
|
+
integrations: patch.integrations !== undefined
|
|
741
|
+
? normalizeIntegrations(patch.integrations, current.integrations)
|
|
742
|
+
: current.integrations,
|
|
743
|
+
audit: patch.audit !== undefined
|
|
744
|
+
? normalizeAuditSettings(patch.audit, current.audit)
|
|
745
|
+
: current.audit,
|
|
746
|
+
permissions: patch.permissions !== undefined
|
|
747
|
+
? normalizePermissionsSettings(patch.permissions, current.permissions)
|
|
748
|
+
: current.permissions,
|
|
749
|
+
};
|
|
750
|
+
// Удобство: при включении хуков без явных учётных данных генерируем их,
|
|
751
|
+
// чтобы функция сразу работала, а секреты не приходилось придумывать вручную.
|
|
752
|
+
if (next.integrations.hooks.enabled) {
|
|
753
|
+
if (!next.integrations.hooks.token || !next.integrations.hooks.secret) {
|
|
754
|
+
const generated = generateHookCredentials();
|
|
755
|
+
if (!next.integrations.hooks.token)
|
|
756
|
+
next.integrations.hooks.token = generated.token;
|
|
757
|
+
if (!next.integrations.hooks.secret)
|
|
758
|
+
next.integrations.hooks.secret = generated.secret;
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
// Удобство: включённый shadow-режим без даты старта стартует при первом сохранении.
|
|
762
|
+
// Иначе shadow не логировал бы решения, а триаж реально подавлял бы уведомления.
|
|
763
|
+
const triage = next.notifications.triage;
|
|
764
|
+
if (triage) {
|
|
765
|
+
triage.shadow = settleShadowOnSave(triage.shadow);
|
|
766
|
+
}
|
|
767
|
+
await fs.mkdir(PLUGIN_DIR, { recursive: true });
|
|
768
|
+
await fs.writeFile(SETTINGS_FILE, JSON.stringify(next, null, 2), "utf8");
|
|
769
|
+
return next;
|
|
770
|
+
}
|