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,290 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Аналитика по истории запусков (Спринт 18).
|
|
3
|
+
*
|
|
4
|
+
* Чистые функции без БД и HTTP: дашборд и RPC отдают JSON, экспорт — CSV.
|
|
5
|
+
* Так агрегаты легко тестировать без запуска сервера.
|
|
6
|
+
*/
|
|
7
|
+
import { computeSavings, } from "./savings.js";
|
|
8
|
+
/** Оценка стоимости, если запись истории не содержит costUsd. */
|
|
9
|
+
export const ESTIMATED_COST_PER_1K_TOKENS_USD = 0.003;
|
|
10
|
+
function toNumber(value) {
|
|
11
|
+
const n = Number(value);
|
|
12
|
+
return Number.isFinite(n) && n > 0 ? n : 0;
|
|
13
|
+
}
|
|
14
|
+
/** Стоимость записи: явная цена, иначе оценка по токенам. */
|
|
15
|
+
export function recordCost(record) {
|
|
16
|
+
const cost = toNumber(record.costUsd);
|
|
17
|
+
if (cost > 0)
|
|
18
|
+
return cost;
|
|
19
|
+
const tokens = toNumber(record.tokens);
|
|
20
|
+
return tokens > 0 ? (tokens / 1000) * ESTIMATED_COST_PER_1K_TOKENS_USD : 0;
|
|
21
|
+
}
|
|
22
|
+
/** Дата записи в UTC-формате YYYY-MM-DD. */
|
|
23
|
+
export function recordDate(record) {
|
|
24
|
+
const time = new Date(record.startedAt).getTime();
|
|
25
|
+
if (!Number.isFinite(time))
|
|
26
|
+
return "";
|
|
27
|
+
return new Date(time).toISOString().slice(0, 10);
|
|
28
|
+
}
|
|
29
|
+
function utcDayKey(date) {
|
|
30
|
+
return date.toISOString().slice(0, 10);
|
|
31
|
+
}
|
|
32
|
+
function percent(part, total) {
|
|
33
|
+
if (total <= 0)
|
|
34
|
+
return 0;
|
|
35
|
+
return Math.round((part / total) * 1000) / 10;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Строит отчёт по истории: итоги, дневные бакеты, разбивка по задачам,
|
|
39
|
+
* матрицам и моделям.
|
|
40
|
+
*/
|
|
41
|
+
export function buildAnalytics(records, options = {}) {
|
|
42
|
+
const windowDays = Math.max(1, Math.floor(options.days ?? 14));
|
|
43
|
+
const topLimit = Math.max(1, Math.floor(options.topLimit ?? 10));
|
|
44
|
+
const now = options.now ?? new Date();
|
|
45
|
+
const dayKeys = [];
|
|
46
|
+
const dayBuckets = new Map();
|
|
47
|
+
for (let i = windowDays - 1; i >= 0; i -= 1) {
|
|
48
|
+
const key = utcDayKey(new Date(now.getTime() - i * 24 * 60 * 60 * 1000));
|
|
49
|
+
dayKeys.push(key);
|
|
50
|
+
dayBuckets.set(key, {
|
|
51
|
+
date: key,
|
|
52
|
+
total: 0,
|
|
53
|
+
success: 0,
|
|
54
|
+
error: 0,
|
|
55
|
+
partial: 0,
|
|
56
|
+
tokens: 0,
|
|
57
|
+
costUsd: 0,
|
|
58
|
+
avgDurationMs: 0,
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
const byTask = new Map();
|
|
62
|
+
const byModel = new Map();
|
|
63
|
+
const byError = new Map();
|
|
64
|
+
const cloneParent = new Map();
|
|
65
|
+
for (const task of options.tasks ?? []) {
|
|
66
|
+
const parentId = task.matrixParentId?.trim();
|
|
67
|
+
if (parentId)
|
|
68
|
+
cloneParent.set(task.name.toLowerCase(), parentId);
|
|
69
|
+
}
|
|
70
|
+
let totalsTotal = 0;
|
|
71
|
+
let totalsSuccess = 0;
|
|
72
|
+
let totalsError = 0;
|
|
73
|
+
let totalsPartial = 0;
|
|
74
|
+
let totalsTokens = 0;
|
|
75
|
+
let totalsCost = 0;
|
|
76
|
+
let durationsSum = 0;
|
|
77
|
+
let durationsCount = 0;
|
|
78
|
+
let recordsInWindow = 0;
|
|
79
|
+
const windowRecords = [];
|
|
80
|
+
for (const record of records) {
|
|
81
|
+
const date = recordDate(record);
|
|
82
|
+
if (!date)
|
|
83
|
+
continue;
|
|
84
|
+
const bucket = dayBuckets.get(date);
|
|
85
|
+
// Итоги считаются только по окну — это «аналитика за период».
|
|
86
|
+
if (!bucket)
|
|
87
|
+
continue;
|
|
88
|
+
recordsInWindow += 1;
|
|
89
|
+
const tokens = toNumber(record.tokens);
|
|
90
|
+
const cost = recordCost(record);
|
|
91
|
+
const status = String(record.status ?? "");
|
|
92
|
+
// Незавершённые запуски не участвуют в аналитике: их ещё нельзя оценить.
|
|
93
|
+
if (status === "running")
|
|
94
|
+
continue;
|
|
95
|
+
windowRecords.push(record);
|
|
96
|
+
const duration = toNumber(record.durationMs);
|
|
97
|
+
bucket.total += 1;
|
|
98
|
+
bucket.tokens += tokens;
|
|
99
|
+
bucket.costUsd += cost;
|
|
100
|
+
if (status === "success")
|
|
101
|
+
bucket.success += 1;
|
|
102
|
+
else if (status === "partial")
|
|
103
|
+
bucket.partial += 1;
|
|
104
|
+
else
|
|
105
|
+
bucket.error += 1;
|
|
106
|
+
if (duration > 0) {
|
|
107
|
+
bucket.avgDurationMs =
|
|
108
|
+
(bucket.avgDurationMs * (bucket.total - 1) + duration) / bucket.total;
|
|
109
|
+
}
|
|
110
|
+
totalsTotal += 1;
|
|
111
|
+
totalsTokens += tokens;
|
|
112
|
+
totalsCost += cost;
|
|
113
|
+
if (status === "success")
|
|
114
|
+
totalsSuccess += 1;
|
|
115
|
+
else if (status === "partial")
|
|
116
|
+
totalsPartial += 1;
|
|
117
|
+
else
|
|
118
|
+
totalsError += 1;
|
|
119
|
+
if (duration > 0) {
|
|
120
|
+
durationsSum += duration;
|
|
121
|
+
durationsCount += 1;
|
|
122
|
+
}
|
|
123
|
+
const taskKey = record.taskName.toLowerCase();
|
|
124
|
+
const existing = byTask.get(taskKey) ?? {
|
|
125
|
+
taskName: record.taskName,
|
|
126
|
+
total: 0,
|
|
127
|
+
success: 0,
|
|
128
|
+
error: 0,
|
|
129
|
+
successRate: 0,
|
|
130
|
+
avgDurationMs: 0,
|
|
131
|
+
tokens: 0,
|
|
132
|
+
costUsd: 0,
|
|
133
|
+
isMatrixClone: cloneParent.has(taskKey),
|
|
134
|
+
matrixParentId: cloneParent.get(taskKey) ?? null,
|
|
135
|
+
};
|
|
136
|
+
existing.total += 1;
|
|
137
|
+
if (status === "success")
|
|
138
|
+
existing.success += 1;
|
|
139
|
+
else
|
|
140
|
+
existing.error += 1;
|
|
141
|
+
existing.tokens += tokens;
|
|
142
|
+
existing.costUsd += cost;
|
|
143
|
+
if (duration > 0) {
|
|
144
|
+
existing.avgDurationMs =
|
|
145
|
+
(existing.avgDurationMs * (existing.total - 1) + duration) / existing.total;
|
|
146
|
+
}
|
|
147
|
+
byTask.set(taskKey, existing);
|
|
148
|
+
const model = record.model?.trim() || "(default)";
|
|
149
|
+
const modelRow = byModel.get(model) ?? { model, total: 0, costUsd: 0 };
|
|
150
|
+
modelRow.total += 1;
|
|
151
|
+
modelRow.costUsd += cost;
|
|
152
|
+
byModel.set(model, modelRow);
|
|
153
|
+
// Топ ошибок: группируем по тексту, чтобы дайджест показывал частые причины.
|
|
154
|
+
if (status !== "success" && status !== "partial") {
|
|
155
|
+
const message = typeof record.error === "string" && record.error.trim()
|
|
156
|
+
? record.error.trim().slice(0, 160)
|
|
157
|
+
: "(без текста)";
|
|
158
|
+
const errorRow = byError.get(message) ?? {
|
|
159
|
+
message,
|
|
160
|
+
count: 0,
|
|
161
|
+
lastAt: record.startedAt,
|
|
162
|
+
};
|
|
163
|
+
errorRow.count += 1;
|
|
164
|
+
if (new Date(record.startedAt).getTime() >
|
|
165
|
+
new Date(errorRow.lastAt).getTime()) {
|
|
166
|
+
errorRow.lastAt = record.startedAt;
|
|
167
|
+
}
|
|
168
|
+
byError.set(message, errorRow);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
const tasks = [...byTask.values()]
|
|
172
|
+
.map((row) => ({
|
|
173
|
+
...row,
|
|
174
|
+
successRate: percent(row.success, row.total),
|
|
175
|
+
avgDurationMs: Math.round(row.avgDurationMs),
|
|
176
|
+
costUsd: Math.round(row.costUsd * 1e6) / 1e6,
|
|
177
|
+
}))
|
|
178
|
+
.sort((a, b) => b.total - a.total || a.taskName.localeCompare(b.taskName));
|
|
179
|
+
const matrices = new Map();
|
|
180
|
+
for (const row of tasks) {
|
|
181
|
+
if (!row.matrixParentId)
|
|
182
|
+
continue;
|
|
183
|
+
const key = row.matrixParentId.toLowerCase();
|
|
184
|
+
const matrix = matrices.get(key) ?? {
|
|
185
|
+
parentId: row.matrixParentId,
|
|
186
|
+
clones: 0,
|
|
187
|
+
total: 0,
|
|
188
|
+
success: 0,
|
|
189
|
+
error: 0,
|
|
190
|
+
successRate: 0,
|
|
191
|
+
tokens: 0,
|
|
192
|
+
costUsd: 0,
|
|
193
|
+
};
|
|
194
|
+
matrix.clones += 1;
|
|
195
|
+
matrix.total += row.total;
|
|
196
|
+
matrix.success += row.success;
|
|
197
|
+
matrix.error += row.error;
|
|
198
|
+
matrix.tokens += row.tokens;
|
|
199
|
+
matrix.costUsd += row.costUsd;
|
|
200
|
+
matrices.set(key, matrix);
|
|
201
|
+
}
|
|
202
|
+
const daily = dayKeys.map((key) => {
|
|
203
|
+
const bucket = dayBuckets.get(key);
|
|
204
|
+
return {
|
|
205
|
+
...bucket,
|
|
206
|
+
avgDurationMs: Math.round(bucket.avgDurationMs),
|
|
207
|
+
costUsd: Math.round(bucket.costUsd * 1e6) / 1e6,
|
|
208
|
+
};
|
|
209
|
+
});
|
|
210
|
+
return {
|
|
211
|
+
generatedAt: new Date().toISOString(),
|
|
212
|
+
windowDays,
|
|
213
|
+
totals: {
|
|
214
|
+
total: totalsTotal,
|
|
215
|
+
success: totalsSuccess,
|
|
216
|
+
error: totalsError,
|
|
217
|
+
partial: totalsPartial,
|
|
218
|
+
successRate: percent(totalsSuccess, totalsTotal),
|
|
219
|
+
avgDurationMs: durationsCount > 0 ? Math.round(durationsSum / durationsCount) : 0,
|
|
220
|
+
tokens: totalsTokens,
|
|
221
|
+
costUsd: Math.round(totalsCost * 1e6) / 1e6,
|
|
222
|
+
},
|
|
223
|
+
daily,
|
|
224
|
+
tasks,
|
|
225
|
+
topByCost: [...tasks].sort((a, b) => b.costUsd - a.costUsd).slice(0, topLimit),
|
|
226
|
+
matrices: [...matrices.values()]
|
|
227
|
+
.map((row) => ({
|
|
228
|
+
...row,
|
|
229
|
+
successRate: percent(row.success, row.total),
|
|
230
|
+
costUsd: Math.round(row.costUsd * 1e6) / 1e6,
|
|
231
|
+
}))
|
|
232
|
+
.sort((a, b) => b.costUsd - a.costUsd),
|
|
233
|
+
byModel: [...byModel.values()]
|
|
234
|
+
.map((row) => ({ ...row, costUsd: Math.round(row.costUsd * 1e6) / 1e6 }))
|
|
235
|
+
.sort((a, b) => b.costUsd - a.costUsd),
|
|
236
|
+
errors: [...byError.values()]
|
|
237
|
+
.sort((a, b) => b.count - a.count || a.message.localeCompare(b.message))
|
|
238
|
+
.slice(0, topLimit),
|
|
239
|
+
savings: computeSavings(windowRecords, { topLimit }),
|
|
240
|
+
sources: {
|
|
241
|
+
historyRecords: records.length,
|
|
242
|
+
recordsInWindow,
|
|
243
|
+
topLimit,
|
|
244
|
+
},
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
/** Экранирование значения для CSV (RFC 4180). */
|
|
248
|
+
export function csvCell(value) {
|
|
249
|
+
if (value === null || value === undefined)
|
|
250
|
+
return "";
|
|
251
|
+
const text = String(value);
|
|
252
|
+
if (/[",\r\n;]/.test(text))
|
|
253
|
+
return `"${text.replace(/"/g, '""')}"`;
|
|
254
|
+
return text;
|
|
255
|
+
}
|
|
256
|
+
/** Заголовок CSV-экспорта истории. */
|
|
257
|
+
export const HISTORY_CSV_HEADER = [
|
|
258
|
+
"startedAt",
|
|
259
|
+
"finishedAt",
|
|
260
|
+
"taskName",
|
|
261
|
+
"status",
|
|
262
|
+
"durationMs",
|
|
263
|
+
"tokens",
|
|
264
|
+
"costUsd",
|
|
265
|
+
"model",
|
|
266
|
+
"workspaceId",
|
|
267
|
+
"error",
|
|
268
|
+
];
|
|
269
|
+
/** История в CSV: точки с запятой как разделитель — дружелюбно к Excel (RU). */
|
|
270
|
+
export function historyToCsv(records) {
|
|
271
|
+
const rows = [HISTORY_CSV_HEADER.join(";")];
|
|
272
|
+
for (const record of records) {
|
|
273
|
+
rows.push([
|
|
274
|
+
record.startedAt,
|
|
275
|
+
record.finishedAt ?? "",
|
|
276
|
+
record.taskName,
|
|
277
|
+
record.status,
|
|
278
|
+
record.durationMs ?? "",
|
|
279
|
+
record.tokens ?? "",
|
|
280
|
+
record.costUsd ?? "",
|
|
281
|
+
record.model ?? "",
|
|
282
|
+
record.workspaceId ?? "",
|
|
283
|
+
record.error ?? "",
|
|
284
|
+
]
|
|
285
|
+
.map(csvCell)
|
|
286
|
+
.join(";"));
|
|
287
|
+
}
|
|
288
|
+
// BOM, чтобы Excel корректно открыл UTF-8 с кириллицей.
|
|
289
|
+
return `\uFEFF${rows.join("\r\n")}`;
|
|
290
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { type PermissionPolicy } from "./permissions.js";
|
|
2
|
+
/**
|
|
3
|
+
* Журнал аудита мутаций (Спринт 26).
|
|
4
|
+
*
|
|
5
|
+
* Фиксирует кто, когда и через какой интерфейс создал / изменил / запустил /
|
|
6
|
+
* удалил задачу или настройки. Записи лежат в SQLite рядом с историей, поэтому
|
|
7
|
+
* аудит не зависит от файловых логов и переживает перезапуск. Любая ошибка
|
|
8
|
+
* записи проглатывается: аудит не должен ломать основную операцию.
|
|
9
|
+
*/
|
|
10
|
+
export type AuditActor = "mcp" | "gui" | "http" | "system" | string;
|
|
11
|
+
export interface AuditEntryInput {
|
|
12
|
+
action: string;
|
|
13
|
+
targetType?: string | null;
|
|
14
|
+
target?: string | null;
|
|
15
|
+
actor: AuditActor;
|
|
16
|
+
/** Конкретный инструмент / RPC-метод / HTTP-маршрут. */
|
|
17
|
+
source?: string | null;
|
|
18
|
+
details?: unknown;
|
|
19
|
+
remote?: string | null;
|
|
20
|
+
/** Время события (ISO). По умолчанию — сейчас. */
|
|
21
|
+
ts?: string;
|
|
22
|
+
}
|
|
23
|
+
export interface AuditRecord {
|
|
24
|
+
id: number;
|
|
25
|
+
ts: string;
|
|
26
|
+
action: string;
|
|
27
|
+
targetType: string | null;
|
|
28
|
+
target: string | null;
|
|
29
|
+
actor: string;
|
|
30
|
+
source: string | null;
|
|
31
|
+
details: unknown;
|
|
32
|
+
remote: string | null;
|
|
33
|
+
}
|
|
34
|
+
export interface ReadAuditFilter {
|
|
35
|
+
action?: string;
|
|
36
|
+
target?: string;
|
|
37
|
+
actor?: string;
|
|
38
|
+
since?: string;
|
|
39
|
+
until?: string;
|
|
40
|
+
limit?: number;
|
|
41
|
+
}
|
|
42
|
+
export interface ReadAuditResult {
|
|
43
|
+
records: AuditRecord[];
|
|
44
|
+
total: number;
|
|
45
|
+
}
|
|
46
|
+
export declare const DEFAULT_AUDIT_RETENTION_DAYS = 90;
|
|
47
|
+
export declare const DEFAULT_AUDIT_MAX_RECORDS = 10000;
|
|
48
|
+
/** Рекурсивно вычищает секреты из произвольной структуры details. */
|
|
49
|
+
export declare function redactAuditDetails(value: unknown, depth?: number): unknown;
|
|
50
|
+
/**
|
|
51
|
+
* Записывает событие аудита. Никогда не бросает исключение.
|
|
52
|
+
* Возвращает id записи или null при ошибке.
|
|
53
|
+
*/
|
|
54
|
+
export declare function recordAudit(entry: AuditEntryInput): number | null;
|
|
55
|
+
export interface ToolBlockedInput {
|
|
56
|
+
/** Имя задачи, для которой действует запрет. */
|
|
57
|
+
task: string;
|
|
58
|
+
/** Заблокированный инструмент (например, shell или write). */
|
|
59
|
+
tool: string;
|
|
60
|
+
actor?: AuditActor;
|
|
61
|
+
source?: string | null;
|
|
62
|
+
/** Дополнительные детали события; можно переопределить/дополнить. */
|
|
63
|
+
details?: Record<string, unknown>;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Записывает событие tool.blocked для задачи и инструмента.
|
|
67
|
+
*
|
|
68
|
+
* Детали события — обычный объект, поэтому вызывающая сторона может добавить
|
|
69
|
+
* причину, список разрешённых инструментов и любые другие поля.
|
|
70
|
+
* Возвращает id записи или null, если журнал недоступен.
|
|
71
|
+
*/
|
|
72
|
+
export declare function recordToolBlocked(input: ToolBlockedInput): number | null;
|
|
73
|
+
/**
|
|
74
|
+
* Фиксирует запреты задачи из её политики allowedTools/deniedTools.
|
|
75
|
+
*
|
|
76
|
+
* Явно запрещённые инструменты попадают в аудит по одному событию на
|
|
77
|
+
* инструмент. Для режима «только разрешённые» пишется одно событие с
|
|
78
|
+
* инструментом `*`, потому что список заблокированных в этом режиме
|
|
79
|
+
* неограничен. Возвращает число записанных событий.
|
|
80
|
+
*/
|
|
81
|
+
export declare function recordTaskToolBlocks(task: string, allowedTools: readonly string[] | null | undefined, deniedTools: readonly string[] | null | undefined, actor?: AuditActor, source?: string, policy?: PermissionPolicy, legacyShell?: boolean): number;
|
|
82
|
+
/** Читает журнал аудита (новые сверху). */
|
|
83
|
+
export declare function readAuditLog(filter?: ReadAuditFilter): ReadAuditResult;
|
|
84
|
+
/**
|
|
85
|
+
* Удаляет старые записи и лишние сверх maxRecords.
|
|
86
|
+
* Возвращает количество удалённых строк.
|
|
87
|
+
*/
|
|
88
|
+
export declare function cleanupAuditLog(options?: {
|
|
89
|
+
retentionDays?: number;
|
|
90
|
+
maxRecords?: number;
|
|
91
|
+
}): number;
|
|
92
|
+
/** Удаляет все записи (тесты / обслуживание). */
|
|
93
|
+
export declare function clearAuditLog(): void;
|
|
94
|
+
/** Сбрасывает троттлинг очистки (для тестов). */
|
|
95
|
+
export declare function resetAuditCleanupThrottle(): void;
|
|
96
|
+
//# sourceMappingURL=audit.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"audit.d.ts","sourceRoot":"","sources":["../../src/core/audit.ts"],"names":[],"mappings":"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"}
|
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
import { getDb } from "../db/index.js";
|
|
2
|
+
import { redactSecretsInText } from "./secrets.js";
|
|
3
|
+
import { resolvePermissions, } from "./permissions.js";
|
|
4
|
+
export const DEFAULT_AUDIT_RETENTION_DAYS = 90;
|
|
5
|
+
export const DEFAULT_AUDIT_MAX_RECORDS = 10000;
|
|
6
|
+
const SENSITIVE_KEY_RE = /(TOKEN|SECRET|PASS|PASSWORD|PASSWD|API_?KEY|CREDENTIAL|AUTH)/i;
|
|
7
|
+
const PURE_SECRET_REF_RE = /^\$\{secret:[A-Za-z0-9_.-]{1,64}\}$/;
|
|
8
|
+
function looksLikeSecretRef(value) {
|
|
9
|
+
return PURE_SECRET_REF_RE.test(value.trim());
|
|
10
|
+
}
|
|
11
|
+
/** Рекурсивно вычищает секреты из произвольной структуры details. */
|
|
12
|
+
export function redactAuditDetails(value, depth = 0) {
|
|
13
|
+
if (depth > 8)
|
|
14
|
+
return "[truncated]";
|
|
15
|
+
if (typeof value === "string")
|
|
16
|
+
return redactSecretsInText(value);
|
|
17
|
+
if (value == null || typeof value !== "object")
|
|
18
|
+
return value;
|
|
19
|
+
if (Array.isArray(value)) {
|
|
20
|
+
return value.slice(0, 200).map((item) => redactAuditDetails(item, depth + 1));
|
|
21
|
+
}
|
|
22
|
+
const result = {};
|
|
23
|
+
for (const [key, item] of Object.entries(value)) {
|
|
24
|
+
if (typeof item === "string" &&
|
|
25
|
+
SENSITIVE_KEY_RE.test(key) &&
|
|
26
|
+
!looksLikeSecretRef(item)) {
|
|
27
|
+
result[key] = "***";
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
result[key] = redactAuditDetails(item, depth + 1);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return result;
|
|
34
|
+
}
|
|
35
|
+
function safeJson(value) {
|
|
36
|
+
if (value === undefined || value === null)
|
|
37
|
+
return null;
|
|
38
|
+
try {
|
|
39
|
+
return JSON.stringify(redactAuditDetails(value));
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
let lastCleanupAt = 0;
|
|
46
|
+
/**
|
|
47
|
+
* Записывает событие аудита. Никогда не бросает исключение.
|
|
48
|
+
* Возвращает id записи или null при ошибке.
|
|
49
|
+
*/
|
|
50
|
+
export function recordAudit(entry) {
|
|
51
|
+
try {
|
|
52
|
+
const ts = entry.ts ?? new Date().toISOString();
|
|
53
|
+
const result = getDb()
|
|
54
|
+
.prepare(`INSERT INTO audit_log
|
|
55
|
+
(ts, action, target_type, target, actor, source, details_json, remote)
|
|
56
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
57
|
+
.run(ts, String(entry.action || "unknown").slice(0, 128), entry.targetType == null ? null : String(entry.targetType).slice(0, 64), entry.target == null ? null : String(entry.target).slice(0, 256), String(entry.actor || "system").slice(0, 32), entry.source == null ? null : String(entry.source).slice(0, 128), safeJson(entry.details), entry.remote == null ? null : String(entry.remote).slice(0, 128));
|
|
58
|
+
maybeCleanup();
|
|
59
|
+
return Number(result.lastInsertRowid) || null;
|
|
60
|
+
}
|
|
61
|
+
catch (err) {
|
|
62
|
+
try {
|
|
63
|
+
console.warn(`[audit] не удалось записать событие: ${err instanceof Error ? err.message : String(err)}`);
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
// console недоступен — молча игнорируем.
|
|
67
|
+
}
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Ленивая ротация: не чаще раза в час, лимиты по умолчанию. Точные лимиты из
|
|
73
|
+
* settings применяются в cleanupHistory / manage_settings.
|
|
74
|
+
*/
|
|
75
|
+
function maybeCleanup() {
|
|
76
|
+
const now = Date.now();
|
|
77
|
+
if (now - lastCleanupAt < 60 * 60 * 1000)
|
|
78
|
+
return;
|
|
79
|
+
lastCleanupAt = now;
|
|
80
|
+
try {
|
|
81
|
+
cleanupAuditLog({
|
|
82
|
+
retentionDays: DEFAULT_AUDIT_RETENTION_DAYS,
|
|
83
|
+
maxRecords: DEFAULT_AUDIT_MAX_RECORDS,
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
// очистка не критична
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function rowToRecord(row) {
|
|
91
|
+
let details = null;
|
|
92
|
+
if (row.details_json) {
|
|
93
|
+
try {
|
|
94
|
+
details = JSON.parse(String(row.details_json));
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
details = String(row.details_json);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return {
|
|
101
|
+
id: Number(row.id),
|
|
102
|
+
ts: String(row.ts),
|
|
103
|
+
action: String(row.action),
|
|
104
|
+
targetType: row.target_type == null ? null : String(row.target_type),
|
|
105
|
+
target: row.target == null ? null : String(row.target),
|
|
106
|
+
actor: String(row.actor ?? "system"),
|
|
107
|
+
source: row.source == null ? null : String(row.source),
|
|
108
|
+
details,
|
|
109
|
+
remote: row.remote == null ? null : String(row.remote),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Записывает событие tool.blocked для задачи и инструмента.
|
|
114
|
+
*
|
|
115
|
+
* Детали события — обычный объект, поэтому вызывающая сторона может добавить
|
|
116
|
+
* причину, список разрешённых инструментов и любые другие поля.
|
|
117
|
+
* Возвращает id записи или null, если журнал недоступен.
|
|
118
|
+
*/
|
|
119
|
+
export function recordToolBlocked(input) {
|
|
120
|
+
return recordAudit({
|
|
121
|
+
action: "tool.blocked",
|
|
122
|
+
targetType: "task",
|
|
123
|
+
target: input.task,
|
|
124
|
+
actor: input.actor ?? "system",
|
|
125
|
+
source: input.source ?? "policy",
|
|
126
|
+
details: { tool: input.tool, ...(input.details ?? {}) },
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Фиксирует запреты задачи из её политики allowedTools/deniedTools.
|
|
131
|
+
*
|
|
132
|
+
* Явно запрещённые инструменты попадают в аудит по одному событию на
|
|
133
|
+
* инструмент. Для режима «только разрешённые» пишется одно событие с
|
|
134
|
+
* инструментом `*`, потому что список заблокированных в этом режиме
|
|
135
|
+
* неограничен. Возвращает число записанных событий.
|
|
136
|
+
*/
|
|
137
|
+
export function recordTaskToolBlocks(task, allowedTools, deniedTools, actor = "system", source = "policy", policy, legacyShell) {
|
|
138
|
+
const normalizedDenied = Array.from(new Set((deniedTools ?? [])
|
|
139
|
+
.map((tool) => String(tool).trim())
|
|
140
|
+
.filter(Boolean)));
|
|
141
|
+
const normalizedAllowed = Array.from(new Set((allowedTools ?? [])
|
|
142
|
+
.map((tool) => String(tool).trim())
|
|
143
|
+
.filter(Boolean)));
|
|
144
|
+
const details = {
|
|
145
|
+
reason: "deniedTools",
|
|
146
|
+
allowedTools: normalizedAllowed.length > 0 ? normalizedAllowed : null,
|
|
147
|
+
deniedTools: normalizedDenied.length > 0 ? normalizedDenied : null,
|
|
148
|
+
};
|
|
149
|
+
let written = 0;
|
|
150
|
+
for (const tool of normalizedDenied) {
|
|
151
|
+
if (recordToolBlocked({ task, tool, actor, source, details }) != null) {
|
|
152
|
+
written++;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
if (normalizedDenied.length === 0 && normalizedAllowed.length > 0) {
|
|
156
|
+
if (recordToolBlocked({
|
|
157
|
+
task,
|
|
158
|
+
tool: "*",
|
|
159
|
+
actor,
|
|
160
|
+
source,
|
|
161
|
+
details: {
|
|
162
|
+
reason: "allowedTools",
|
|
163
|
+
allowedTools: normalizedAllowed,
|
|
164
|
+
deniedTools: null,
|
|
165
|
+
},
|
|
166
|
+
}) != null) {
|
|
167
|
+
written++;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
// Спринт 32 / релиз 1.6: фиксируем инструменты, запрещённые политикой по
|
|
171
|
+
// умолчанию (hybrid: shell/question; secure: ещё edit/webfetch/websearch/
|
|
172
|
+
// subagent). Это политика на момент сохранения задачи, а не попытки вызова:
|
|
173
|
+
// detached-обёртка не имеет доступа к SQLite.
|
|
174
|
+
if (policy) {
|
|
175
|
+
const effective = resolvePermissions({
|
|
176
|
+
policy,
|
|
177
|
+
legacyShell,
|
|
178
|
+
allowedTools: normalizedAllowed,
|
|
179
|
+
deniedTools: normalizedDenied,
|
|
180
|
+
});
|
|
181
|
+
for (const denied of effective.deniedByPolicy) {
|
|
182
|
+
if (recordToolBlocked({
|
|
183
|
+
task,
|
|
184
|
+
tool: denied.action,
|
|
185
|
+
actor,
|
|
186
|
+
source,
|
|
187
|
+
details: {
|
|
188
|
+
reason: "default-policy",
|
|
189
|
+
policy: effective.policy,
|
|
190
|
+
legacyShell: effective.legacyShell,
|
|
191
|
+
hint: denied.hint,
|
|
192
|
+
allowedTools: normalizedAllowed.length > 0 ? normalizedAllowed : null,
|
|
193
|
+
deniedTools: normalizedDenied.length > 0 ? normalizedDenied : null,
|
|
194
|
+
},
|
|
195
|
+
}) != null) {
|
|
196
|
+
written++;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return written;
|
|
201
|
+
}
|
|
202
|
+
/** Читает журнал аудита (новые сверху). */
|
|
203
|
+
export function readAuditLog(filter = {}) {
|
|
204
|
+
const limit = Math.max(1, Math.min(5000, Math.floor(filter.limit ?? 200) || 200));
|
|
205
|
+
const where = [];
|
|
206
|
+
const params = [];
|
|
207
|
+
if (filter.action?.trim()) {
|
|
208
|
+
where.push("action = ?");
|
|
209
|
+
params.push(filter.action.trim());
|
|
210
|
+
}
|
|
211
|
+
if (filter.target?.trim()) {
|
|
212
|
+
where.push("target = ?");
|
|
213
|
+
params.push(filter.target.trim());
|
|
214
|
+
}
|
|
215
|
+
if (filter.actor?.trim()) {
|
|
216
|
+
where.push("actor = ?");
|
|
217
|
+
params.push(filter.actor.trim());
|
|
218
|
+
}
|
|
219
|
+
if (filter.since?.trim()) {
|
|
220
|
+
where.push("ts >= ?");
|
|
221
|
+
params.push(filter.since.trim());
|
|
222
|
+
}
|
|
223
|
+
if (filter.until?.trim()) {
|
|
224
|
+
where.push("ts <= ?");
|
|
225
|
+
params.push(filter.until.trim());
|
|
226
|
+
}
|
|
227
|
+
const clause = where.length ? `WHERE ${where.join(" AND ")}` : "";
|
|
228
|
+
try {
|
|
229
|
+
const db = getDb();
|
|
230
|
+
const totalRow = db
|
|
231
|
+
.prepare(`SELECT COUNT(*) AS count FROM audit_log ${clause}`)
|
|
232
|
+
.get(...params);
|
|
233
|
+
const rows = db
|
|
234
|
+
.prepare(`SELECT * FROM audit_log ${clause} ORDER BY ts DESC, id DESC LIMIT ?`)
|
|
235
|
+
.all(...params, limit);
|
|
236
|
+
return { records: rows.map(rowToRecord), total: Number(totalRow?.count) || 0 };
|
|
237
|
+
}
|
|
238
|
+
catch (err) {
|
|
239
|
+
try {
|
|
240
|
+
console.warn(`[audit] не удалось прочитать журнал: ${err instanceof Error ? err.message : String(err)}`);
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
// ignore
|
|
244
|
+
}
|
|
245
|
+
return { records: [], total: 0 };
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Удаляет старые записи и лишние сверх maxRecords.
|
|
250
|
+
* Возвращает количество удалённых строк.
|
|
251
|
+
*/
|
|
252
|
+
export function cleanupAuditLog(options = {}) {
|
|
253
|
+
const retentionDays = Math.max(0, Math.floor(options.retentionDays ?? DEFAULT_AUDIT_RETENTION_DAYS) || 0);
|
|
254
|
+
const maxRecords = Math.max(100, Math.floor(options.maxRecords ?? DEFAULT_AUDIT_MAX_RECORDS) || DEFAULT_AUDIT_MAX_RECORDS);
|
|
255
|
+
let deleted = 0;
|
|
256
|
+
try {
|
|
257
|
+
const db = getDb();
|
|
258
|
+
if (retentionDays > 0) {
|
|
259
|
+
const cutoff = new Date(Date.now() - retentionDays * 24 * 60 * 60 * 1000).toISOString();
|
|
260
|
+
const result = db.prepare("DELETE FROM audit_log WHERE ts < ?").run(cutoff);
|
|
261
|
+
deleted += Number(result.changes) || 0;
|
|
262
|
+
}
|
|
263
|
+
const countRow = db.prepare("SELECT COUNT(*) AS count FROM audit_log").get();
|
|
264
|
+
const count = Number(countRow?.count) || 0;
|
|
265
|
+
if (count > maxRecords) {
|
|
266
|
+
const excess = count - maxRecords;
|
|
267
|
+
const result = db
|
|
268
|
+
.prepare(`DELETE FROM audit_log WHERE id IN (
|
|
269
|
+
SELECT id FROM audit_log ORDER BY ts ASC, id ASC LIMIT ?
|
|
270
|
+
)`)
|
|
271
|
+
.run(excess);
|
|
272
|
+
deleted += Number(result.changes) || 0;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
catch (err) {
|
|
276
|
+
try {
|
|
277
|
+
console.warn(`[audit] не удалось очистить журнал: ${err instanceof Error ? err.message : String(err)}`);
|
|
278
|
+
}
|
|
279
|
+
catch {
|
|
280
|
+
// ignore
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
return deleted;
|
|
284
|
+
}
|
|
285
|
+
/** Удаляет все записи (тесты / обслуживание). */
|
|
286
|
+
export function clearAuditLog() {
|
|
287
|
+
try {
|
|
288
|
+
getDb().exec("DELETE FROM audit_log");
|
|
289
|
+
}
|
|
290
|
+
catch {
|
|
291
|
+
// ignore
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
/** Сбрасывает троттлинг очистки (для тестов). */
|
|
295
|
+
export function resetAuditCleanupThrottle() {
|
|
296
|
+
lastCleanupAt = 0;
|
|
297
|
+
}
|